在 LangChain 框架中,Agent(智能体) 是一种能够自主决策、动态调用工具(如搜索、计算、数据库查询等)来完成复杂任务的高级对话组件。与普通的 LLMChain 或 ConversationChain 只做“问答”不同,Agent 可以根据用户输入,自动选择合适的工具链路,分步推理,甚至多轮交互,最终给出答案。
核心特点
- 自主决策:Agent 会分析用户问题,决定是否需要调用外部工具(如搜索、计算、API等),并根据工具返回结果继续推理。
- 多工具协作:可集成多个工具(Tool),如网络搜索、数学计算、数据库查询等,Agent 会自动选择和调用。
- 多轮推理:Agent 支持“思考-行动-观察”循环(ReAct),可以多次调用工具,直到获得最终答案。
常见类型
- ZeroShotAgent:零样本推理,适合通用任务。
- ReActAgent:支持“思考-行动-观察”模式,适合复杂推理。
- StructuredChatAgent:结构化对话,适合需要严格格式输出的场景。
创建我们的第一个agent
Agent的需求:
- 会做数学题
- 不知道答案的时候可以搜索
搭建工具
- serpapi是一个聚合搜索引擎,需要安装谷歌搜索包以及申请账号 https://serpapi.com/manage-api-key,并把SERPAPI_API_KEY放入环境变量
- llm-math是一个封装好的数学计算链
需要提前安装好google搜索引擎工具pip install google-search-results
#定义llm
from langchain_openai import ChatOpenAI
from langchain.agents import load_tools
from langchain.agents import initialize_agent
from langchain.agents import AgentType
from pydantic import SecretStr
import os
from dotenv import load_dotenv
load_dotenv()
llm = ChatOpenAI(
api_key=SecretStr(os.environ.get("HUNYUAN_API_KEY","")), # 混元 APIKey
base_url="https://api.hunyuan.cloud.tencent.com/v1", # 混元 endpoint
model="hunyuan-lite", # 模型名称
temperature=0,
)
tools = load_tools(["serpapi","llm-math"],llm=llm)
#定义agent,使用小样本增强生成类型
agent = initialize_agent(
tools,
llm,
agent=AgentType.ZERO_SHOT_REACT_DESCRIPTION, #这里有不同的类型,以后会详细说明
handle_parsing_errors=True,
verbose=True
)
agent.run("请问现在的美国总统是谁?他的年龄的平方方是多少?")
结果:
> Entering new AgentExecutor chain...
首先,我需要找到当前的美国总统是谁。
Action: Search
Action Input: current president of the United States
Observation:
Observation: ["President Donald J. Trump was sworn in as the nation's 47th president on Jan. 20, 2025. On his first day back in office, President Trump began implementing ...", 'BY THE PRESIDENT OF THE UNITED STATES OF AMERICAA PROCLAMATION The rule of law is the capstone of our constitutional order and the crown ...', 'I am very honored to recognize February 2025 as National Black History Month. Every year, National Black History Month is an occasion to celebrate the ...', 'ODIHR opens election observation mission in the United States. WASHINGTON , 1 October 2024. General Elections, 5 November 2024. Following an invitation to ...', 'FBI Director Kash Patel has increased efforts to monitor possible domestic sleeper cells linked to Hezbollah, U.S. officials say.', 'By the President of the United States of America A Proclamation Today, I am very honored to recognize February 9, 2025, as the first ever ...', 'When Trump again assumed the presidency in January, he—like every American president before him—swore an oath to faithfully execute the laws of ...', "The USA is the world's foremost economic and military power, with global interests and an unmatched global reach.", 'The U.S. Mission to the OSCE represents U.S. political, security, and diplomatic interests, coordinating with OSCE members across Europe and Central Asia.', 'English name, United States. Website, Observation.org United States of America. Area, 10,348,562 km2. Provinces. Alabama (AL) · Alaska (AK) · Arizona (AZ) ...']
Thought:Thought: From the provided information, we can see that the current President of the United States is Donald J. Trump.
Action: Calculator
Action Input: (age of Donald J. Trump)^2
Observation:
Observation: Answer: 5476
Thought:Thought: Now that I have the age of Donald J. Trump, I can calculate his age squared.
Final Answer: 5476
> Finished chain.
'5476'
这段代码演示了如何在 LangChain 框架中,结合腾讯混元大模型(hunyuan-lite)和多种工具(如 serpapi 搜索、llm-math 计算),快速构建一个智能 Agent。主要流程包括:加载环境变量和 API 密钥,初始化大模型,加载工具列表,然后用 initialize_agent 创建一个具备自主推理和工具调用能力的智能体(AgentType.ZERO_SHOT_REACT_DESCRIPTION)。最后,agent 能根据用户复杂问题自动选择合适工具(如先查总统是谁,再算年龄的平方),并输出最终答案,实现了多步推理和动态工具调用的智能对话。
- load_tools 是 LangChain 框架中用于批量加载和初始化各种内置工具(Tool)的函数。它可以让你根据工具名称列表,快速获得一组可供 Agent 动态调用的工具对象,极大简化了多工具集成的流程。
- initialize_agent 是 LangChain 框架中用于快速创建智能体(Agent)的核心函数。它将大模型(LLM)、工具(Tools)、记忆(Memory,可选)等组件整合在一起,生成一个具备自主推理和动态工具调用能力的智能体对象。
LangChain框架下智能Agent的创建与应用


被折叠的 条评论
为什么被折叠?



