NutritionAI가 어떻게 에이전트에게 강력한 식품 영양 정보 기능을 제공할 수 있는지 가장 잘 이해하기 위해, Passio NutritionAI를 통해 해당 정보를 찾을 수 있는 에이전트를 만들어 보겠습니다.

tool 정의하기

먼저 Passio NutritionAI tool을 생성해야 합니다.

Passio Nutrition AI

LangChain에는 Passio NutritionAI를 쉽게 사용하여 식품 영양 정보를 찾을 수 있는 내장 tool이 있습니다. 이를 사용하려면 API key가 필요하며, 무료 tier를 제공합니다. API key를 생성한 후, 다음과 같이 export해야 합니다:
export NUTRITIONAI_SUBSCRIPTION_KEY="..."
… 또는 dotenv 패키지와 같은 다른 방법을 통해 Python 환경에 제공할 수 있습니다. constructor 호출을 통해 명시적으로 key를 제어할 수도 있습니다.
from dotenv import load_dotenv
from langchain_core.utils import get_from_env

load_dotenv()

nutritionai_subscription_key = get_from_env(
    "nutritionai_subscription_key", "NUTRITIONAI_SUBSCRIPTION_KEY"
)
from langchain_community.tools.passio_nutrition_ai import NutritionAI
from langchain_community.utilities.passio_nutrition_ai import NutritionAIAPI
nutritionai_search = NutritionAI(api_wrapper=NutritionAIAPI())
nutritionai_search.invoke("chicken tikka masala")
nutritionai_search.invoke("Schnuck Markets sliced pepper jack cheese")

Tools

이제 tool이 준비되었으므로, 이후에 사용할 tool 목록을 생성할 수 있습니다.
tools = [nutritionai_search]

agent 생성하기

tool을 정의했으므로 이제 agent를 생성할 수 있습니다. OpenAI Functions agent를 사용할 것입니다 - 이 유형의 agent에 대한 자세한 정보와 다른 옵션은 이 가이드를 참조하세요. 먼저, agent를 안내할 LLM을 선택합니다.
from langchain_openai import ChatOpenAI

llm = ChatOpenAI(model="gpt-3.5-turbo", temperature=0)
다음으로, agent를 안내하는 데 사용할 prompt를 선택합니다.
from langchain_classic import hub

# Get the prompt to use - you can modify this!
prompt = hub.pull("hwchase17/openai-functions-agent")
prompt.messages
[SystemMessagePromptTemplate(prompt=PromptTemplate(input_variables=[], template='You are a helpful assistant')),
 MessagesPlaceholder(variable_name='chat_history', optional=True),
 HumanMessagePromptTemplate(prompt=PromptTemplate(input_variables=['input'], template='{input}')),
 MessagesPlaceholder(variable_name='agent_scratchpad')]
이제 LLM, prompt, tool을 사용하여 agent를 초기화할 수 있습니다. agent는 입력을 받아 어떤 작업을 수행할지 결정하는 역할을 합니다. 중요한 점은 Agent가 이러한 작업을 실행하지 않는다는 것입니다 - 이는 AgentExecutor(다음 단계)가 수행합니다. 이러한 구성 요소에 대해 생각하는 방법에 대한 자세한 내용은 개념 가이드를 참조하세요.
from langchain.agents import create_openai_functions_agent

agent = create_openai_functions_agent(llm, tools, prompt)
마지막으로, agent(두뇌)와 tool을 AgentExecutor(agent를 반복적으로 호출하고 tool을 실행함) 내부에 결합합니다. 이러한 구성 요소에 대해 생각하는 방법에 대한 자세한 내용은 개념 가이드를 참조하세요.
from langchain.agents import AgentExecutor

agent_executor = AgentExecutor(agent=agent, tools=tools, verbose=True)

agent 실행하기

이제 몇 가지 쿼리로 agent를 실행할 수 있습니다! 현재로서는 이들이 모두 stateless 쿼리라는 점에 유의하세요 (이전 상호작용을 기억하지 않습니다).
agent_executor.invoke({"input": "hi!"})
> Entering new AgentExecutor chain...
Hello! How can I assist you today?

> Finished chain.
{'input': 'hi!', 'output': 'Hello! How can I assist you today?'}
agent_executor.invoke({"input": "how many calories are in a slice pepperoni pizza?"})
이러한 메시지를 자동으로 추적하려면 RunnableWithMessageHistory로 래핑할 수 있습니다.
agent_executor.invoke(
    {"input": "I had bacon and eggs for breakfast.  How many calories is that?"}
)
agent_executor.invoke(
    {
        "input": "I had sliced pepper jack cheese for a snack.  How much protein did I have?"
    }
)
agent_executor.invoke(
    {
        "input": "I had sliced colby cheese for a snack. Give me calories for this Schnuck Markets product."
    }
)
agent_executor.invoke(
    {
        "input": "I had chicken tikka masala for dinner.  how much calories, protein, and fat did I have with default quantity?"
    }
)

결론

여기까지입니다! 이 빠른 시작에서는 식품 영양 정보를 답변에 통합할 수 있는 간단한 agent를 만드는 방법을 다루었습니다. Agent는 복잡한 주제이며, 배울 것이 많습니다!
Connect these docs programmatically to Claude, VSCode, and more via MCP for real-time answers.
I