LangChain 智能体Agent
<h1 id="agent智能体">Agent智能体</h1><p>Agent(智能体)是一个通过动态协调<strong>大语言模型(LLM)</strong>和**工具(Tools)来完成复杂任务的智能系统。</p>
<p>它让LLM充当“决策大脑”,根据用户输入自主选择和执行工具(如搜索、计算、数据库查询等),最终生成精准的响应</p>
<h2 id="核心能力">核心能力</h2>
<p>作为一个智能体,需要具备以下核心能力:<br>
<img src="https://img2024.cnblogs.com/blog/2734270/202603/2734270-20260310160517951-356841777.png" alt="image" loading="lazy"></p>
<p>1)大模型(LLM):作为大脑,提供推理、规划和知识理解能力。<br>
2)记忆(Memory):具备短期记忆(上下文)和长期记忆(向量存储),支持快速知识检索<br>
3)工具(Tool):调用外部工具(如API、数据库)的执行单元<br>
4)规划(Planning):任务分解、反思与自省框架实现复杂任务处理<br>
5)行动(Action):实际执行决策的能力<br>
6)协作:通过与其他智能体交互合作,完成更复杂的任务目标</p>
<h2 id="agent创建">Agent创建</h2>
<pre><code>from langchain.agents import create_agent
from langchain_community.chat_models import ChatTongyi
agent = create_agent(
model=ChatTongyi(model="qwen3-max"),
tools=[],
system_prompt="你是一个聊天助手,可以回答用户问题"
)
res = agent.invoke(
{
"messages": [
{"role": "user", "content": "明天苏州天气如何?"},
]
}
)
print(res)
</code></pre>
<h3 id="调用工具">调用工具</h3>
<pre><code>from langchain.agents import create_agent
from langchain_community.chat_models import ChatTongyi
from langchain_core.tools import tool
@tool(description="获取天气")
def get_wether():
return "晴天"
agent = create_agent(
model=ChatTongyi(model="qwen3-max"),
tools=,
system_prompt="你是一个聊天助手,可以回答用户问题"
)
res = agent.invoke(
{
"messages": [
{"role": "user", "content": "明天苏州天气如何?"},
]
}
)
for msg in res["messages"]:
print(type(msg).__name__, msg.content)
</code></pre>
<p>输出:</p>
<pre><code>HumanMessage 明天苏州天气如何?
AIMessage
ToolMessage 晴天
AIMessage 明天苏州的天气是晴天,适合外出活动!记得做好防晒哦~
</code></pre>
<h3 id="流式输出">流式输出</h3>
<p>通过<code>create_agent</code>方法可以创建Agent对象,其也是Runnable接口的子类实现,也拥有:</p>
<ul>
<li>invoke,执行,一次得到完整结果</li>
<li>stream,执行,流式输出得到结果</li>
</ul>
<pre><code>from langchain.agents import create_agent
from langchain_community.chat_models import ChatTongyi
from langchain_core.tools import tool
@tool(description="获取天气")
def get_wether():
return "晴天"
@tool(description="获取温度")
def get_temp():
return "26度"
agent = create_agent(
model=ChatTongyi(model="qwen3-max"),
tools=,
system_prompt="你是一个聊天助手,可以回答用户问题"
)
for chunk in agent.stream(
{
"messages": [
{"role": "user", "content": "明天苏州天气气温如何?"},
]
},
stream_mode="values"
):
latest_message = chunk["messages"][-1]
if latest_message.content:
print(type(latest_message).__name__, latest_message.content)
try:
if latest_message.tool_calls:
print(f"工具调用: { for tc in latest_message.tool_calls] }")
except AttributeError as e:
pass
</code></pre><br><br>
来源:https://www.cnblogs.com/1873cy/p/19698084
頁:
[1]