LangChain 代理简介

使用 LangChain 开发 LLM 应用

Jonathan Bennion

AI Engineer & LangChain Contributor

什么是代理?

 

代理(Agents):使用 LLM 执行_动作_

工具(Tools):代理调用的_函数_

 

  • 本节ReAct 代理

一个代理根据用户输入决定使用哪种工具。

使用 LangChain 开发 LLM 应用

ReAct 代理

  • Reason + Act

 

金斯敦(牙买加)天气如何?

思考:我应该调用 Weather() 获取牙买加金斯敦的天气。
行动:Weather("Kingston, Jamaica")
观测:多晴,气温 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 应用

Vamos praticar!

使用 LangChain 开发 LLM 应用

Preparing Video For Download...