LangChain 代理簡介

使用 LangChain 開發 LLM 應用

Jonathan Bennion

AI Engineer & LangChain Contributor

什麼是代理?

 

代理:使用 LLM 執行_動作_

工具:代理呼叫的_函式_

 

  • 本節ReAct 代理

代理根據使用者輸入決定要用哪個工具。

使用 LangChain 開發 LLM 應用

ReAct 代理

  • Reason + Act

 

What is the weather like in Kingston, Jamaica?

Thought: I should call Weather() to find the
weather in Kingston, Jamaica.


Act: Weather("Kingston, Jamaica")
Observe: The weather is mostly sunny with temperatures of 82°F.

思考、行動、觀察的循環。

使用 LangChain 開發 LLM 應用

LangGraph

LangGraph 標誌。

 

  • LangChain 的分支,專注設計代理系統
  • 統一、與工具無關的語法
  • pip install langgraph==0.2.74
使用 LangChain 開發 LLM 應用

ReAct 代理

from langgraph.prebuilt import create_react_agent
from langchain_community.agent_toolkits.load_tools import load_tools

llm = ChatOpenAI(model="gpt-4o-mini", api_key=openai_api_key) tools = load_tools(["llm-math"], llm=llm)
agent = create_react_agent(llm, tools)
messages = agent.invoke({"messages": [("human", "What is the square root of 101?")]})
print(messages)
使用 LangChain 開發 LLM 應用

ReAct 代理

{'messages': [
    HumanMessage(content='What is the square root of 101?', ...),
    AIMessage(content='', ..., tool_calls=[{'name': 'Calculator', 'args': {'__arg1': 'sqrt(101)'}, ...),
    ToolMessage(content='Answer: 10.04987562112089', ...),
    AIMessage(content='The square root of 101 is approximately 10.05.', ...)
]}
print(messages['messages'][-1].content)
The square root of 101 is approximately 10.05.
使用 LangChain 開發 LLM 應用

一起來練習吧!

使用 LangChain 開發 LLM 應用

Preparing Video For Download...