查看: 73|回复: 0

LangChain 智能体Agent

[复制链接]

1

主题

0

回帖

0

积分

热心网友

金币
0
阅读权限
220
精华
0
威望
0
贡献
0
在线时间
0 小时
注册时间
2008-3-5
发表于 2026-3-16 08:44:00 | 显示全部楼层 |阅读模式

Agent智能体

Agent(智能体)是一个通过动态协调大语言模型(LLM)和**工具(Tools)来完成复杂任务的智能系统。

它让LLM充当“决策大脑”,根据用户输入自主选择和执行工具(如搜索、计算、数据库查询等),最终生成精准的响应

核心能力

作为一个智能体,需要具备以下核心能力:

image

1)大模型(LLM):作为大脑,提供推理、规划和知识理解能力。
2)记忆(Memory):具备短期记忆(上下文)和长期记忆(向量存储),支持快速知识检索
3)工具(Tool):调用外部工具(如API、数据库)的执行单元
4)规划(Planning):任务分解、反思与自省框架实现复杂任务处理
5)行动(Action):实际执行决策的能力
6)协作:通过与其他智能体交互合作,完成更复杂的任务目标

Agent创建

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)

调用工具

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=[get_wether],
    system_prompt="你是一个聊天助手,可以回答用户问题"
)

res = agent.invoke(
    {
        "messages": [
            {"role": "user", "content": "明天苏州天气如何?"},
        ]
    }
)


for msg in res["messages"]:
    print(type(msg).__name__, msg.content)

输出:

HumanMessage 明天苏州天气如何?
AIMessage 
ToolMessage 晴天
AIMessage 明天苏州的天气是晴天,适合外出活动!记得做好防晒哦~

流式输出

通过create_agent方法可以创建Agent对象,其也是Runnable接口的子类实现,也拥有:

  • invoke,执行,一次得到完整结果
  • stream,执行,流式输出得到结果
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=[get_wether, get_temp],
    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"工具调用: { [tc['name'] for tc in latest_message.tool_calls] }")
    except AttributeError as e:
        pass


来源:https://www.cnblogs.com/1873cy/p/19698084
回复

使用道具 举报

您需要登录后才可以回帖 登录 | 立即注册

本版积分规则

相关侵权、举报、投诉及建议等,请发 E-mail:qiongdian@foxmail.com

Powered by Discuz! X5.0 © 2001-2026 Discuz! Team.

在本版发帖返回顶部