searchusermenu
  • 发布文章
  • 消息中心
点赞
收藏
评论
分享
原创

AI Agent 简介及 ReAct 框架工程实践

2025-10-09 10:05:47
1
0

1、引言:从 LLM 到 Agent 的范式转变

大模型(LLM)已经具备强大的理解与生成能力,但在复杂任务执行、工具调用、上下文记忆与决策规划等方面仍有限,即缺乏自主规划(Planning)使用工具(Tool Use)长期记忆(Memory)的能力。这导致 LLM 无法解决需要多步推理、与实时数据交互或调用外部系统的复杂任务。

AI Agent 范式正是为解决这些局限而生。一个 Agent 是一个将 LLM 作为“大脑”,并赋予其自主性工具集的软件实体。它能够将一个复杂的最终目标拆解为一系列中间步骤,并根据环境的反馈(Observation)迭代地调整其行动,最终达成目标。LLM 是大脑,Agent 是会思考和行动的智能体。Agent 能够:

  • 拥有目标与计划;

  • 自动选择与调用工具;

  • 进行多步推理与决策;

  • 处理动态环境与反馈

 

2、AI Agent 基础概念与核心组件

2.1 AI Agent 的定义与核心组件

AI Agent 是一种基于 LLM 的自治实体,能够模拟人类代理行为,通过多步交互完成目标任务。其核心组件包括:

  • 感知模块:捕获用户输入或环境信号(如查询或传感器数据)。

  • 规划模块:利用 LLM 生成行动计划,例如分解任务为子步骤。

  • 行动模块:调用外部工具(如 API、数据库)执行具体操作。

  • 记忆模块:维护上下文历史,支持短期(会话级)和长期(知识库)记忆。

  • 反思模块:评估行动结果,调整后续策略。

这些组件形成一个闭环反馈系统,确保 Agent 的适应性和鲁棒性。

2.2 与传统 AI 系统的区别

传统的 AI 系统(如聊天机器人、推荐系统、图像识别系统等)通常具有以下特征:

特征 描述
被动响应 只能根据输入触发响应,无法主动行动。
单任务模型 只能完成一个明确的任务(如分类、问答、翻译)。
数据驱动但无上下文意识 模型仅依赖输入数据,而缺乏对环境、历史状态的记忆。
黑盒执行 输入 → 模型推理 → 输出,中间没有决策过程或推理链可解释。
可扩展性差 想让系统具备新能力,通常需要重新训练模型或重新部署。
固定流程 系统的逻辑基本是固定的业务流程,不具备动态规划或自我决策能力。

而 AI Agent(智能体) 是能够 感知环境、思考决策、执行行动、反思改进 的智能系统。

特征 描述
主动性 (Proactive) Agent 可以主动决策与行动,而不是仅等待输入。
多步骤推理 (Reasoning) 具备思考能力,能将复杂任务分解为可执行步骤。
工具使用 (Tool Use) 可调用外部 API、数据库、搜索引擎等工具完成任务。
记忆能力 (Memory) 能保存上下文、历史任务、用户偏好。
反思与改进 (Reflection) 可评估自己行动的结果,优化下一步策略。
多智能体协作 (Collaboration) 多个 Agent 可协同完成任务,如一个计划 Agent + 执行 Agent。

2.3 典型应用场景

场景类别 说明 Agent 主要能力
智能客服 Agent 可自动理解用户意图、追问上下文、调用系统接口执行任务 - 自然语言理解- 工单系统调用- 记忆用户上下文- 自我纠错与追问
智能助理 Agent(AI Copilot) 企业内部知识问答 + 工具调用 + 任务执行,如“帮我生成周报并发邮件” - 任务分解(ReAct)- 工具使用(API 调用)- 多轮记忆(Memory)
运维/DevOps Agent 主动监控集群、自动诊断告警、执行修复脚本 - 环境感知- 指令生成与执行(如 kubectl 命令)- 异常反思与自愈
数据分析 Agent 根据自然语言自动生成 SQL 查询、可视化报表、洞察分析 - NL2SQL + 执行- 数据洞察(Chain-of-Thought)- 图表生成与解释
教育辅导 Agent 自适应出题、讲解错题、生成学习计划 - 学情建模(Memory)- 内容生成(LLM)- 交互式教学(ReAct)
法律/金融顾问 Agent 解读合同、风险分析、生成建议报告 - 文档解析- 知识检索(RAG)- 推理与解释
多 Agent 协作系统 一个 Planner Agent 拆解任务,多个 Worker Agent 执行 - 任务分工- 通信协议(Message Passing)- 状态管理

3、ReAct 框架介绍

3.1 ReAct 框架的起源与原理

ReAct 框架源于 2022 年 Yao 等人的论文《ReAct: Synergizing Reasoning and Acting in Language Models》,旨在解决 LLM 在工具使用中的幻觉(hallucination)问题。通过交替“推理”(Thought)和“行动”(Action),ReAct 引导模型生成结构化输出:Thought(分析问题)→ Action(工具调用)→ Observation(结果反馈)→ 循环迭代,直至任务完成。

这种机制模拟人类认知过程,提高了 Agent 的可解释性和准确率

3.2. ReAct 的工作流 (Thought → Action → Observation)

ReAct (Reasoning and Acting) 框架通过在 LLM 的输出中交替生成思维链 (Thought)行动指令 (Action),使 Agent 能够执行动态、复杂的任务:

  1. Thought (思考):LLM 分析当前目标、评估现有信息,并规划下一步要采取的行动。

  2. Action (行动):LLM 根据 Thought,输出一个格式化的工具调用指令,包含工具名称和所需的输入参数

  3. Observation (观察):环境(Agent 运行时)执行 Action,并将工具的实际输出结果返回给 LLM。

  4. 迭代:LLM 将 Observation 纳入下一次 Thought 的输入中,直到它得出最终答案,此时 Action 变为 Final Answer。

 

 

3.3 ReAct 的 Prompt 工程

ReAct 框架的成功高度依赖于一个结构化的 Prompt,它必须清晰地定义 Agent 的角色可用工具强制输出格式

一个典型的 ReAct Prompt 结构会包含:

  1. 角色指令:定义 Agent 的身份和目标。

  2. 工具描述:详细描述每个工具的用途名称参数 Schema

  3. 输出格式:强制要求 Agent 严格遵循 Thought、Action、Observation 的交替模式。

ReAct 的提示模板通常为:

 Question: [用户查询]
 Thought: [推理步骤]
 Action: [工具名][参数]
 Observation: [工具输出]
 Thought: ...
 Final Answer: [最终结果]

 

4、LangChain Agent 关键组件介绍

  • LLM(语言模型):代理的“大脑”,负责思考、推理、生成计划,作用是接收用户输入 → 理解问题 → 输出“下一步要做什么”(如调用哪个工具或直接回答)

  • Prompt Template(提示模板):定义模型思考的框架、用于指导模型如何推理、调用工具、格式化输出。作用是 让大模型的输出结构化(例如 “Thought → Action → Observation → Final Answer”)。

  • Tool(工具):工具是 Agent 的“手脚”,用于执行模型本身无法直接完成的任务。

  • Memory(记忆):保存对话历史、上下文或长期状态,类似于人类的记忆,使 Agent 拥有持续对话能力

  • Agent Executor(代理执行器):整个代理系统的核心控制器

    • 负责:

      1. 调用 LLM 生成计划;

      2. 根据计划调用合适的工具;

      3. 收集工具结果反馈;

      4. 迭代执行,直到生成最终答案

 

5、ReAct 框架的工程实践

LangChain 是构建 Agent 应用最流行的框架之一,它抽象了 ReAct 循环、工具管理和 LLM 交互,使得 Agent 的搭建变得高效简洁。

5.1 安装依赖与配置

 pip install langchain langchain-community serpapi

5.2 配置 SerpAPI Key

 在 https://serpapi.com/ 注册后,获取一个 API key。

5.3 定义 Agent 工具(Tools)

 tools = load_tools(["serpapi", "llm-math"], llm=llm)

5.4 代码示例

5.4.1 阿里百炼模型封装

dashscope_llm.py

 
import os
 from dotenv import load_dotenv
 from langchain_openai import ChatOpenAI
 from typing import Optional, Dict
 
 
 def init_dashscope_llm(
        model_name: str = "qwen-plus",
        temperature: float = 0.0,
        additional_kwargs: Optional[Dict] = None
 ) -> ChatOpenAI:
    """
    初始化阿里百炼 ChatOpenAI 模型实例
 
    Args:
        model_name: 阿里百炼模型名,如 "qwen-plus"、"qwen-turbo"、"qwen-max"
        temperature: 生成温度(0.0~1.0,0.0 更严谨,1.0 更多样)
        additional_kwargs: 额外模型参数(如 max_tokens、top_p 等)
 
    Returns:
        初始化完成的 ChatOpenAI 实例
 
    Raises:
        ValueError: 未配置 DASHSCOPE_API_KEY 时抛出
    """
    # 1. 加载环境变量(从 .env 文件或系统环境变量中读取)
    load_dotenv() # 若项目中已全局加载,可注释此句(避免重复加载)
    dashscope_api_key = os.getenv("DASHSCOPE_API_KEY")
 
    # 2. 验证 API Key 是否存在
    if not dashscope_api_key:
        raise ValueError(
            "阿里百炼 API Key 未配置!请在 .env 文件中添加 DASHSCOPE_API_KEY=你的密钥,"
            "或在系统环境变量中设置该值"
        )
 
    # 3. 处理额外参数(默认空字典,避免 None 报错)
    additional_kwargs = additional_kwargs or {}
 
    # 4. 初始化并返回模型实例
    return ChatOpenAI(
        api_key=dashscope_api_key,
        base_url="https://dashscope.aliyuncs.com/compatible-mode/v1", # 阿里百炼固定兼容接口
        model_name=model_name,
        temperature=temperature,
        **additional_kwargs # 传递额外参数(如 max_tokens=2048)
    )
 
 
 # 可选:提供默认模型实例(方便快速引用,避免每次调用函数)
 default_llm = init_dashscope_llm()

 

 
5.4.2 搭建 ReAct Agent 实例
 
 import os
 os.environ["OPENAI_API_KEY"] = 'Your OpenAI API Key'
 os.environ["SERPAPI_API_KEY"] = 'Your SERPAPI_API_KEY '
 import logging
 logging.basicConfig(level=logging.DEBUG)
 # 加载所需的库
 from langchain_community.agent_toolkits.load_tools import load_tools
 from langchain.agents import initialize_agent
 from langchain.agents import AgentType
 from dashscope_llm import default_llm
 llm = default_llm
 # 设置工具
 tools = load_tools(["serpapi", "llm-math"], llm=llm)
 # 初始化Agent
 agent = initialize_agent(tools, llm, agent=AgentType.ZERO_SHOT_REACT_DESCRIPTION, verbose=False)
 agent.invoke("如果寒武纪股票最新的股价上涨 15%,它的新价格会是多少?")

5.4.3 日志输出

  agent = initialize_agent(tools, llm, agent=AgentType.ZERO_SHOT_REACT_DESCRIPTION, verbose=True)
 DEBUG:openai._base_client:Request options: {'method': 'post', 'url': '/chat/completions', 'headers': {'X-Stainless-Raw-Response': 'true'}, 'files': None, 'idempotency_key': 'stainless-python-retry-7c4c6806-f4f3-4aa6-a2b4-6371c8ad6889', 'json_data': {'messages': [{'content': 'Answer the following questions as best you can. You have access to the following tools:\n\nSearch(query: str, **kwargs: Any) -> str - A search engine. Useful for when you need to answer questions about current events. Input should be a search query.\nCalculator(*args: Any, callbacks: Union[list[langchain_core.callbacks.base.BaseCallbackHandler], langchain_core.callbacks.base.BaseCallbackManager, NoneType] = None, tags: Optional[list[str]] = None, metadata: Optional[dict[str, Any]] = None, **kwargs: Any) -> Any - Useful for when you need to answer questions about math.\n\nUse the following format:\n\nQuestion: the input question you must answer\nThought: you should always think about what to do\nAction: the action to take, should be one of [Search, Calculator]\nAction Input: the input to the action\nObservation: the result of the action\n... (this Thought/Action/Action Input/Observation can repeat N times)\nThought: I now know the final answer\nFinal Answer: the final answer to the original input question\n\nBegin!\n\nQuestion: 如果寒武纪股票最新的股价上涨 15%,它的新价格会是多少?\nThought:', 'role': 'user'}], 'model': 'qwen-plus', 'stop': ['\nObservation:', '\n\tObservation:'], 'stream': False, 'temperature': 0.0}}
 
 
 > Entering new AgentExecutor chain...
 
 INFO:httpx:HTTP Request: POST https://dashscope.aliyuncs.com/compatible-mode/v1/chat/completions "HTTP/1.1 200 OK"
 
 DEBUG:openai._base_client:HTTP Response: POST https://dashscope.aliyuncs.com/compatible-mode/v1/chat/completions "200 OK" Headers({'vary': 'Origin,Access-Control-Request-Method,Access-Control-Request-Headers, Accept-Encoding', 'x-request-id': '0035fd50-2891-463e-a985-801a764c77cb', 'x-dashscope-call-gateway': 'true', 'content-type': 'application/json', 'req-cost-time': '2338', 'req-arrive-time': '1759928381012', 'resp-start-time': '1759928383350', 'x-envoy-upstream-service-time': '2337', 'set-cookie': 'acw_tc=0035fd50-2891-463e-a985-801a764c77cb6baf5c54ebff7f2c690c44c0520fc308;path=/;HttpOnly;Max-Age=1800', 'content-encoding': 'gzip', 'date': 'Wed, 08 Oct 2025 12:59:42 GMT', 'server': 'istio-envoy', 'transfer-encoding': 'chunked'})
 DEBUG:openai._base_client:request_id: 0035fd50-2891-463e-a985-801a764c77cb
 Thought: 我需要知道寒武纪股票的当前价格,然后将其乘以1.15(即增加15%)来计算新价格。首先,我必须查找寒武纪股票的最新股价。
 Action: Search
 Action Input: 寒武纪股票最新价格DEBUG:urllib3.connectionpool:Starting new HTTPS connection (1): serpapi.com:443
 DEBUG:urllib3.connectionpool:https://serpapi.com:443 "GET /search?engine=google&google_domain=google.com&gl=us&hl=en&api_key=1eee5c79f6b3789533d5f787c8281241e8bdd05906959bdd6f17de334b5e7264&q=%E5%AF%92%E6%AD%A6%E7%BA%AA%E8%82%A1%E7%A5%A8%E6%9C%80%E6%96%B0%E4%BB%B7%E6%A0%BC&output=json&source=python HTTP/1.1" 200 None
 DEBUG:openai._base_client:Request options: {'method': 'post', 'url': '/chat/completions', 'headers': {'X-Stainless-Raw-Response': 'true'}, 'files': None, 'idempotency_key': 'stainless-python-retry-be0fcf24-47e3-4357-9baa-65c27346fab7', 'json_data': {'messages': [{'content': "Answer the following questions as best you can. You have access to the following tools:\n\nSearch(query: str, **kwargs: Any) -> str - A search engine. Useful for when you need to answer questions about current events. Input should be a search query.\nCalculator(*args: Any, callbacks: Union[list[langchain_core.callbacks.base.BaseCallbackHandler], langchain_core.callbacks.base.BaseCallbackManager, NoneType] = None, tags: Optional[list[str]] = None, metadata: Optional[dict[str, Any]] = None, **kwargs: Any) -> Any - Useful for when you need to answer questions about math.\n\nUse the following format:\n\nQuestion: the input question you must answer\nThought: you should always think about what to do\nAction: the action to take, should be one of [Search, Calculator]\nAction Input: the input to the action\nObservation: the result of the action\n... (this Thought/Action/Action Input/Observation can repeat N times)\nThought: I now know the final answer\nFinal Answer: the final answer to the original input question\n\nBegin!\n\nQuestion: 如果寒武纪股票最新的股价上涨 15%,它的新价格会是多少?\nThought:Thought: 我需要知道寒武纪股票的当前价格,然后将其乘以1.15(即增加15%)来计算新价格。首先,我必须查找寒武纪股票的最新股价。\nAction: Search\nAction Input: 寒武纪股票最新价格\nObservation: ['手机东方财富网是东方财富网的手机门户网站,为亿万用户打造一个手机联通世界的超级平台,提供7*24小时全面及时的财经中文资讯,内容覆盖国内外突发事件、股市资讯、全球新闻', '截至2025年10月07日,寒武纪(688256)的交易价格报1,325.00,前一交易日收于1,323.50,日内波动范围介于1,318.23至1,399.00之间,52周波动范围介于302.32至1,595.88之间。', '寒武纪-U (688256) · 最高价. 1399.00 · 最低价. 1318.23 · 成交量. 865.40万手 · 今开. 1388.00 · 昨收. 1323.50 · 成交额. 117.00亿 · 换手率. 2.07% · 市盈率(静). 亏损.', '雪球为您提供寒武纪-U(SH688256)股票股价,实时行情,热门讨论,最新资讯,最新公告,公司资料,财务数据,财务指标分析等与寒武纪-U(SH688256)股票相关的信息与服务.', '寒武纪定增结果出炉!9月30日晚间,国产AI芯片巨头寒武纪披露了定增结果。此次定增发行价格为1195.02元/股,实际发行数量为333.49万股,募集资金总额达39.85亿元。......', '... 寒武纪、摩尔线程已适配 2025-09-30 22:52 1195.02元!寒武纪刷新A股定增价格最高纪录! 2025-09-30 22:44 【公告精选】寒武纪定增发行价出炉,*ST正平停牌 ...', '寒武纪(688256)的实时行情,及时准确的提供寒武纪(688256)的flash分时走势、K线图、均价线系统、MACD、KDJ、交易量等全面技术分析,帮你做出及时判断, ...', '提供寒武纪-U(688256)的行情走势、资金流向、行业概念板块排行、成份股排行、大盘分析、证券聚焦、市场总貌、股吧互动等与寒武纪-U(688256)有关的信息和服务。', '430.00% · 前收市價 1,323.50 · 開市 1,388.00 · 買入價 1,325.00 x -- · 賣出價 1,325.30 x -- · 今日波幅 1,318.23 - 1,399.00 · 52 週波幅 302.32 - 1,595.88 · 成交量 ...', '寒武纪(688256.SH) ; SSH高装(全). 931867CNY01. 2023-12-11 ; 沪港深500信息HKD. H30498. 2023-12-11 ; 上证180优选(全)HKD. H40093. 2023-12-11 ; 沪港深500非周期(全).']\nThought:", 'role': 'user'}], 'model': 'qwen-plus', 'stop': ['\nObservation:', '\n\tObservation:'], 'stream': False, 'temperature': 0.0}}
 
 
 Observation: ['手机东方财富网是东方财富网的手机门户网站,为亿万用户打造一个手机联通世界的超级平台,提供7*24小时全面及时的财经中文资讯,内容覆盖国内外突发事件、股市资讯、全球新闻', '截至2025年10月07日,寒武纪(688256)的交易价格报1,325.00,前一交易日收于1,323.50,日内波动范围介于1,318.23至1,399.00之间,52周波动范围介于302.32至1,595.88之间。', '寒武纪-U (688256) · 最高价. 1399.00 · 最低价. 1318.23 · 成交量. 865.40万手 · 今开. 1388.00 · 昨收. 1323.50 · 成交额. 117.00亿 · 换手率. 2.07% · 市盈率(静). 亏损.', '雪球为您提供寒武纪-U(SH688256)股票股价,实时行情,热门讨论,最新资讯,最新公告,公司资料,财务数据,财务指标分析等与寒武纪-U(SH688256)股票相关的信息与服务.', '寒武纪定增结果出炉!9月30日晚间,国产AI芯片巨头寒武纪披露了定增结果。此次定增发行价格为1195.02元/股,实际发行数量为333.49万股,募集资金总额达39.85亿元。......', '... 寒武纪、摩尔线程已适配 2025-09-30 22:52 1195.02元!寒武纪刷新A股定增价格最高纪录! 2025-09-30 22:44 【公告精选】寒武纪定增发行价出炉,*ST正平停牌 ...', '寒武纪(688256)的实时行情,及时准确的提供寒武纪(688256)的flash分时走势、K线图、均价线系统、MACD、KDJ、交易量等全面技术分析,帮你做出及时判断, ...', '提供寒武纪-U(688256)的行情走势、资金流向、行业概念板块排行、成份股排行、大盘分析、证券聚焦、市场总貌、股吧互动等与寒武纪-U(688256)有关的信息和服务。', '430.00% · 前收市價 1,323.50 · 開市 1,388.00 · 買入價 1,325.00 x -- · 賣出價 1,325.30 x -- · 今日波幅 1,318.23 - 1,399.00 · 52 週波幅 302.32 - 1,595.88 · 成交量 ...', '寒武纪(688256.SH) ; SSH高装(全). 931867CNY01. 2023-12-11 ; 沪港深500信息HKD. H30498. 2023-12-11 ; 上证180优选(全)HKD. H40093. 2023-12-11 ; 沪港深500非周期(全).']
 Thought:Thought: 从搜索结果中可以看到,寒武纪股票(688256)的最新价格为 **1,325.00元**(多个来源显示“交易价格报1,325.00”或“买入价1,325.00”)。现在我需要计算该价格基础上上涨15%后的新价格。
 DEBUG:httpcore.http11:receive_response_headers.complete return_value=(b'HTTP/1.1', 200, b'OK', [(b'vary', b'Origin,Access-Control-Request-Method,Access-Control-Request-Headers, Accept-Encoding'), (b'x-request-id', b'd7325f58-65c5-48ec-9c7d-d25a77afa2f4'), (b'x-dashscope-call-gateway', b'true'), (b'content-type', b'application/json'), (b'req-cost-time', b'2561'), (b'req-arrive-time', b'1759928385183'), (b'resp-start-time', b'1759928387744'), (b'x-envoy-upstream-service-time', b'2559'), (b'content-encoding', b'gzip'), (b'date', b'Wed, 08 Oct 2025 12:59:47 GMT'), (b'server', b'istio-envoy'), (b'transfer-encoding', b'chunked')])
 INFO:httpx:HTTP Request: POST https://dashscope.aliyuncs.com/compatible-mode/v1/chat/completions "HTTP/1.1 200 OK"
 
 DEBUG:openai._base_client:HTTP Response: POST https://dashscope.aliyuncs.com/compatible-mode/v1/chat/completions "200 OK" Headers({'vary': 'Origin,Access-Control-Request-Method,Access-Control-Request-Headers, Accept-Encoding', 'x-request-id': 'd7325f58-65c5-48ec-9c7d-d25a77afa2f4', 'x-dashscope-call-gateway': 'true', 'content-type': 'application/json', 'req-cost-time': '2561', 'req-arrive-time': '1759928385183', 'resp-start-time': '1759928387744', 'x-envoy-upstream-service-time': '2559', 'content-encoding': 'gzip', 'date': 'Wed, 08 Oct 2025 12:59:47 GMT', 'server': 'istio-envoy', 'transfer-encoding': 'chunked'})
 DEBUG:openai._base_client:request_id: d7325f58-65c5-48ec-9c7d-d25a77afa2f4
 DEBUG:openai._base_client:Request options: {'method': 'post', 'url': '/chat/completions', 'headers': {'X-Stainless-Raw-Response': 'true'}, 'files': None, 'idempotency_key': 'stainless-python-retry-8813eddc-96c0-4bee-8ab7-1c5978df0b30', 'json_data': {'messages': [{'content': 'Translate a math problem into a expression that can be executed using Python\'s numexpr library. Use the output of running this code to answer the question.\n\nQuestion: ${Question with math problem.}\n```text\n${single line mathematical expression that solves the problem}\n```\n...numexpr.evaluate(text)...\n```output\n${Output of running the code}\n```\nAnswer: ${Answer}\n\nBegin.\n\nQuestion: What is 37593 * 67?\n```text\n37593 * 67\n```\n...numexpr.evaluate("37593 * 67")...\n```output\n2518731\n```\nAnswer: 2518731\n\nQuestion: 37593^(1/5)\n```text\n37593**(1/5)\n```\n...numexpr.evaluate("37593**(1/5)")...\n```output\n8.222831614237718\n```\nAnswer: 8.222831614237718\n\nQuestion: 1325 * 1.15\n', 'role': 'user'}], 'model': 'qwen-plus', 'stop': ['```output'], 'stream': False, 'temperature': 0.0}}
 
 
 Action: Calculator
 Action Input: 1325 * 1.15
 DEBUG:httpcore.http11:receive_response_headers.complete return_value=(b'HTTP/1.1', 200, b'OK', [(b'vary', b'Origin,Access-Control-Request-Method,Access-Control-Request-Headers, Accept-Encoding'), (b'x-request-id', b'cfb22cc8-47b1-4417-83c7-26d26a57c267'), (b'x-dashscope-call-gateway', b'true'), (b'content-type', b'application/json'), (b'req-cost-time', b'627'), (b'req-arrive-time', b'1759928387794'), (b'resp-start-time', b'1759928388421'), (b'x-envoy-upstream-service-time', b'626'), (b'content-encoding', b'gzip'), (b'date', b'Wed, 08 Oct 2025 12:59:47 GMT'), (b'server', b'istio-envoy'), (b'transfer-encoding', b'chunked')])
 INFO:httpx:HTTP Request: POST https://dashscope.aliyuncs.com/compatible-mode/v1/chat/completions "HTTP/1.1 200 OK"
 DEBUG:httpcore.http11:receive_response_body.started request=<Request [b'POST']>
 DEBUG:httpcore.http11:receive_response_body.complete
 DEBUG:httpcore.http11:response_closed.started
 DEBUG:httpcore.http11:response_closed.complete
 DEBUG:openai._base_client:HTTP Response: POST https://dashscope.aliyuncs.com/compatible-mode/v1/chat/completions "200 OK" Headers({'vary': 'Origin,Access-Control-Request-Method,Access-Control-Request-Headers, Accept-Encoding', 'x-request-id': 'cfb22cc8-47b1-4417-83c7-26d26a57c267', 'x-dashscope-call-gateway': 'true', 'content-type': 'application/json', 'req-cost-time': '627', 'req-arrive-time': '1759928387794', 'resp-start-time': '1759928388421', 'x-envoy-upstream-service-time': '626', 'content-encoding': 'gzip', 'date': 'Wed, 08 Oct 2025 12:59:47 GMT', 'server': 'istio-envoy', 'transfer-encoding': 'chunked'})
 DEBUG:openai._base_client:request_id: cfb22cc8-47b1-4417-83c7-26d26a57c267
 DEBUG:openai._base_client:Request options: {'method': 'post', 'url': '/chat/completions', 'headers': {'X-Stainless-Raw-Response': 'true'}, 'files': None, 'idempotency_key': 'stainless-python-retry-05736117-6a98-4beb-97d9-62022155ef06', 'json_data': {'messages': [{'content': "Answer the following questions as best you can. You have access to the following tools:\n\nSearch(query: str, **kwargs: Any) -> str - A search engine. Useful for when you need to answer questions about current events. Input should be a search query.\nCalculator(*args: Any, callbacks: Union[list[langchain_core.callbacks.base.BaseCallbackHandler], langchain_core.callbacks.base.BaseCallbackManager, NoneType] = None, tags: Optional[list[str]] = None, metadata: Optional[dict[str, Any]] = None, **kwargs: Any) -> Any - Useful for when you need to answer questions about math.\n\nUse the following format:\n\nQuestion: the input question you must answer\nThought: you should always think about what to do\nAction: the action to take, should be one of [Search, Calculator]\nAction Input: the input to the action\nObservation: the result of the action\n... (this Thought/Action/Action Input/Observation can repeat N times)\nThought: I now know the final answer\nFinal Answer: the final answer to the original input question\n\nBegin!\n\nQuestion: 如果寒武纪股票最新的股价上涨 15%,它的新价格会是多少?\nThought:Thought: 我需要知道寒武纪股票的当前价格,然后将其乘以1.15(即增加15%)来计算新价格。首先,我必须查找寒武纪股票的最新股价。\nAction: Search\nAction Input: 寒武纪股票最新价格\nObservation: ['手机东方财富网是东方财富网的手机门户网站,为亿万用户打造一个手机联通世界的超级平台,提供7*24小时全面及时的财经中文资讯,内容覆盖国内外突发事件、股市资讯、全球新闻', '截至2025年10月07日,寒武纪(688256)的交易价格报1,325.00,前一交易日收于1,323.50,日内波动范围介于1,318.23至1,399.00之间,52周波动范围介于302.32至1,595.88之间。', '寒武纪-U (688256) · 最高价. 1399.00 · 最低价. 1318.23 · 成交量. 865.40万手 · 今开. 1388.00 · 昨收. 1323.50 · 成交额. 117.00亿 · 换手率. 2.07% · 市盈率(静). 亏损.', '雪球为您提供寒武纪-U(SH688256)股票股价,实时行情,热门讨论,最新资讯,最新公告,公司资料,财务数据,财务指标分析等与寒武纪-U(SH688256)股票相关的信息与服务.', '寒武纪定增结果出炉!9月30日晚间,国产AI芯片巨头寒武纪披露了定增结果。此次定增发行价格为1195.02元/股,实际发行数量为333.49万股,募集资金总额达39.85亿元。......', '... 寒武纪、摩尔线程已适配 2025-09-30 22:52 1195.02元!寒武纪刷新A股定增价格最高纪录! 2025-09-30 22:44 【公告精选】寒武纪定增发行价出炉,*ST正平停牌 ...', '寒武纪(688256)的实时行情,及时准确的提供寒武纪(688256)的flash分时走势、K线图、均价线系统、MACD、KDJ、交易量等全面技术分析,帮你做出及时判断, ...', '提供寒武纪-U(688256)的行情走势、资金流向、行业概念板块排行、成份股排行、大盘分析、证券聚焦、市场总貌、股吧互动等与寒武纪-U(688256)有关的信息和服务。', '430.00% · 前收市價 1,323.50 · 開市 1,388.00 · 買入價 1,325.00 x -- · 賣出價 1,325.30 x -- · 今日波幅 1,318.23 - 1,399.00 · 52 週波幅 302.32 - 1,595.88 · 成交量 ...', '寒武纪(688256.SH) ; SSH高装(全). 931867CNY01. 2023-12-11 ; 沪港深500信息HKD. H30498. 2023-12-11 ; 上证180优选(全)HKD. H40093. 2023-12-11 ; 沪港深500非周期(全).']\nThought:Thought: 从搜索结果中可以看到,寒武纪股票(688256)的最新价格为 **1,325.00元**(多个来源显示“交易价格报1,325.00”或“买入价1,325.00”)。现在我需要计算该价格基础上上涨15%后的新价格。\n\nAction: Calculator\nAction Input: 1325 * 1.15\nObservation: Answer: 1523.7499999999998\nThought:", 'role': 'user'}], 'model': 'qwen-plus', 'stop': ['\nObservation:', '\n\tObservation:'], 'stream': False, 'temperature': 0.0}}
 
 Observation: Answer: 1523.7499999999998
 Thought:Thought: 计算结果显示,寒武纪股票在当前价格1,325.00元上涨15%后的新价格约为1,523.75元。
 DEBUG:httpcore.http11:receive_response_headers.complete return_value=(b'HTTP/1.1', 200, b'OK', [(b'vary', b'Origin,Access-Control-Request-Method,Access-Control-Request-Headers, Accept-Encoding'), (b'x-request-id', b'ed8e8993-3fdd-4920-aa7d-9c6a8101b078'), (b'x-dashscope-call-gateway', b'true'), (b'content-type', b'application/json'), (b'req-cost-time', b'2228'), (b'req-arrive-time', b'1759928388486'), (b'resp-start-time', b'1759928390714'), (b'x-envoy-upstream-service-time', b'2226'), (b'content-encoding', b'gzip'), (b'date', b'Wed, 08 Oct 2025 12:59:50 GMT'), (b'server', b'istio-envoy'), (b'transfer-encoding', b'chunked')])
 INFO:httpx:HTTP Request: POST https://dashscope.aliyuncs.com/compatible-mode/v1/chat/completions "HTTP/1.1 200 OK"
 
 DEBUG:openai._base_client:HTTP Response: POST https://dashscope.aliyuncs.com/compatible-mode/v1/chat/completions "200 OK" Headers({'vary': 'Origin,Access-Control-Request-Method,Access-Control-Request-Headers, Accept-Encoding', 'x-request-id': 'ed8e8993-3fdd-4920-aa7d-9c6a8101b078', 'x-dashscope-call-gateway': 'true', 'content-type': 'application/json', 'req-cost-time': '2228', 'req-arrive-time': '1759928388486', 'resp-start-time': '1759928390714', 'x-envoy-upstream-service-time': '2226', 'content-encoding': 'gzip', 'date': 'Wed, 08 Oct 2025 12:59:50 GMT', 'server': 'istio-envoy', 'transfer-encoding': 'chunked'})
 DEBUG:openai._base_client:request_id: ed8e8993-3fdd-4920-aa7d-9c6a8101b078
 
 Final Answer: 如果寒武纪股票最新股价上涨15%,它的新价格将是约1,523.75元。
 
 > Finished chain.
 
 Process finished with exit code 0
 

 

通过 LangChain 的 AgentExecutor 和 verbose=True 选项,我们可以清晰地看到 LLM 如何遵循 ReAct Prompt 的指令,自主地思考(Thought)、选择工具(Action)并利用工具反馈(Observation)来完成多步骤任务。

 

6 总结与展望

AI Agent 是 LLM 应用的必然趋势,而 ReAct 框架作为其核心推理逻辑,为 Agent 的自主行动和复杂规划提供了强大的支撑。

借助 LangChain 这类成熟的 Python 库,开发者可以快速地将复杂的 ReAct 逻辑部署到生产环境,通过定义清晰的工具和任务,实现高度自动化、智能化的应用。随着 Agent 生态的不断发展,我们期待 ReAct 及其变体将在各个行业中发挥更大的潜力

0条评论
0 / 1000
程****平
5文章数
0粉丝数
程****平
5 文章 | 0 粉丝
原创

AI Agent 简介及 ReAct 框架工程实践

2025-10-09 10:05:47
1
0

1、引言:从 LLM 到 Agent 的范式转变

大模型(LLM)已经具备强大的理解与生成能力,但在复杂任务执行、工具调用、上下文记忆与决策规划等方面仍有限,即缺乏自主规划(Planning)使用工具(Tool Use)长期记忆(Memory)的能力。这导致 LLM 无法解决需要多步推理、与实时数据交互或调用外部系统的复杂任务。

AI Agent 范式正是为解决这些局限而生。一个 Agent 是一个将 LLM 作为“大脑”,并赋予其自主性工具集的软件实体。它能够将一个复杂的最终目标拆解为一系列中间步骤,并根据环境的反馈(Observation)迭代地调整其行动,最终达成目标。LLM 是大脑,Agent 是会思考和行动的智能体。Agent 能够:

  • 拥有目标与计划;

  • 自动选择与调用工具;

  • 进行多步推理与决策;

  • 处理动态环境与反馈

 

2、AI Agent 基础概念与核心组件

2.1 AI Agent 的定义与核心组件

AI Agent 是一种基于 LLM 的自治实体,能够模拟人类代理行为,通过多步交互完成目标任务。其核心组件包括:

  • 感知模块:捕获用户输入或环境信号(如查询或传感器数据)。

  • 规划模块:利用 LLM 生成行动计划,例如分解任务为子步骤。

  • 行动模块:调用外部工具(如 API、数据库)执行具体操作。

  • 记忆模块:维护上下文历史,支持短期(会话级)和长期(知识库)记忆。

  • 反思模块:评估行动结果,调整后续策略。

这些组件形成一个闭环反馈系统,确保 Agent 的适应性和鲁棒性。

2.2 与传统 AI 系统的区别

传统的 AI 系统(如聊天机器人、推荐系统、图像识别系统等)通常具有以下特征:

特征 描述
被动响应 只能根据输入触发响应,无法主动行动。
单任务模型 只能完成一个明确的任务(如分类、问答、翻译)。
数据驱动但无上下文意识 模型仅依赖输入数据,而缺乏对环境、历史状态的记忆。
黑盒执行 输入 → 模型推理 → 输出,中间没有决策过程或推理链可解释。
可扩展性差 想让系统具备新能力,通常需要重新训练模型或重新部署。
固定流程 系统的逻辑基本是固定的业务流程,不具备动态规划或自我决策能力。

而 AI Agent(智能体) 是能够 感知环境、思考决策、执行行动、反思改进 的智能系统。

特征 描述
主动性 (Proactive) Agent 可以主动决策与行动,而不是仅等待输入。
多步骤推理 (Reasoning) 具备思考能力,能将复杂任务分解为可执行步骤。
工具使用 (Tool Use) 可调用外部 API、数据库、搜索引擎等工具完成任务。
记忆能力 (Memory) 能保存上下文、历史任务、用户偏好。
反思与改进 (Reflection) 可评估自己行动的结果,优化下一步策略。
多智能体协作 (Collaboration) 多个 Agent 可协同完成任务,如一个计划 Agent + 执行 Agent。

2.3 典型应用场景

场景类别 说明 Agent 主要能力
智能客服 Agent 可自动理解用户意图、追问上下文、调用系统接口执行任务 - 自然语言理解- 工单系统调用- 记忆用户上下文- 自我纠错与追问
智能助理 Agent(AI Copilot) 企业内部知识问答 + 工具调用 + 任务执行,如“帮我生成周报并发邮件” - 任务分解(ReAct)- 工具使用(API 调用)- 多轮记忆(Memory)
运维/DevOps Agent 主动监控集群、自动诊断告警、执行修复脚本 - 环境感知- 指令生成与执行(如 kubectl 命令)- 异常反思与自愈
数据分析 Agent 根据自然语言自动生成 SQL 查询、可视化报表、洞察分析 - NL2SQL + 执行- 数据洞察(Chain-of-Thought)- 图表生成与解释
教育辅导 Agent 自适应出题、讲解错题、生成学习计划 - 学情建模(Memory)- 内容生成(LLM)- 交互式教学(ReAct)
法律/金融顾问 Agent 解读合同、风险分析、生成建议报告 - 文档解析- 知识检索(RAG)- 推理与解释
多 Agent 协作系统 一个 Planner Agent 拆解任务,多个 Worker Agent 执行 - 任务分工- 通信协议(Message Passing)- 状态管理

3、ReAct 框架介绍

3.1 ReAct 框架的起源与原理

ReAct 框架源于 2022 年 Yao 等人的论文《ReAct: Synergizing Reasoning and Acting in Language Models》,旨在解决 LLM 在工具使用中的幻觉(hallucination)问题。通过交替“推理”(Thought)和“行动”(Action),ReAct 引导模型生成结构化输出:Thought(分析问题)→ Action(工具调用)→ Observation(结果反馈)→ 循环迭代,直至任务完成。

这种机制模拟人类认知过程,提高了 Agent 的可解释性和准确率

3.2. ReAct 的工作流 (Thought → Action → Observation)

ReAct (Reasoning and Acting) 框架通过在 LLM 的输出中交替生成思维链 (Thought)行动指令 (Action),使 Agent 能够执行动态、复杂的任务:

  1. Thought (思考):LLM 分析当前目标、评估现有信息,并规划下一步要采取的行动。

  2. Action (行动):LLM 根据 Thought,输出一个格式化的工具调用指令,包含工具名称和所需的输入参数

  3. Observation (观察):环境(Agent 运行时)执行 Action,并将工具的实际输出结果返回给 LLM。

  4. 迭代:LLM 将 Observation 纳入下一次 Thought 的输入中,直到它得出最终答案,此时 Action 变为 Final Answer。

 

 

3.3 ReAct 的 Prompt 工程

ReAct 框架的成功高度依赖于一个结构化的 Prompt,它必须清晰地定义 Agent 的角色可用工具强制输出格式

一个典型的 ReAct Prompt 结构会包含:

  1. 角色指令:定义 Agent 的身份和目标。

  2. 工具描述:详细描述每个工具的用途名称参数 Schema

  3. 输出格式:强制要求 Agent 严格遵循 Thought、Action、Observation 的交替模式。

ReAct 的提示模板通常为:

 Question: [用户查询]
 Thought: [推理步骤]
 Action: [工具名][参数]
 Observation: [工具输出]
 Thought: ...
 Final Answer: [最终结果]

 

4、LangChain Agent 关键组件介绍

  • LLM(语言模型):代理的“大脑”,负责思考、推理、生成计划,作用是接收用户输入 → 理解问题 → 输出“下一步要做什么”(如调用哪个工具或直接回答)

  • Prompt Template(提示模板):定义模型思考的框架、用于指导模型如何推理、调用工具、格式化输出。作用是 让大模型的输出结构化(例如 “Thought → Action → Observation → Final Answer”)。

  • Tool(工具):工具是 Agent 的“手脚”,用于执行模型本身无法直接完成的任务。

  • Memory(记忆):保存对话历史、上下文或长期状态,类似于人类的记忆,使 Agent 拥有持续对话能力

  • Agent Executor(代理执行器):整个代理系统的核心控制器

    • 负责:

      1. 调用 LLM 生成计划;

      2. 根据计划调用合适的工具;

      3. 收集工具结果反馈;

      4. 迭代执行,直到生成最终答案

 

5、ReAct 框架的工程实践

LangChain 是构建 Agent 应用最流行的框架之一,它抽象了 ReAct 循环、工具管理和 LLM 交互,使得 Agent 的搭建变得高效简洁。

5.1 安装依赖与配置

 pip install langchain langchain-community serpapi

5.2 配置 SerpAPI Key

 在 https://serpapi.com/ 注册后,获取一个 API key。

5.3 定义 Agent 工具(Tools)

 tools = load_tools(["serpapi", "llm-math"], llm=llm)

5.4 代码示例

5.4.1 阿里百炼模型封装

dashscope_llm.py

 
import os
 from dotenv import load_dotenv
 from langchain_openai import ChatOpenAI
 from typing import Optional, Dict
 
 
 def init_dashscope_llm(
        model_name: str = "qwen-plus",
        temperature: float = 0.0,
        additional_kwargs: Optional[Dict] = None
 ) -> ChatOpenAI:
    """
    初始化阿里百炼 ChatOpenAI 模型实例
 
    Args:
        model_name: 阿里百炼模型名,如 "qwen-plus"、"qwen-turbo"、"qwen-max"
        temperature: 生成温度(0.0~1.0,0.0 更严谨,1.0 更多样)
        additional_kwargs: 额外模型参数(如 max_tokens、top_p 等)
 
    Returns:
        初始化完成的 ChatOpenAI 实例
 
    Raises:
        ValueError: 未配置 DASHSCOPE_API_KEY 时抛出
    """
    # 1. 加载环境变量(从 .env 文件或系统环境变量中读取)
    load_dotenv() # 若项目中已全局加载,可注释此句(避免重复加载)
    dashscope_api_key = os.getenv("DASHSCOPE_API_KEY")
 
    # 2. 验证 API Key 是否存在
    if not dashscope_api_key:
        raise ValueError(
            "阿里百炼 API Key 未配置!请在 .env 文件中添加 DASHSCOPE_API_KEY=你的密钥,"
            "或在系统环境变量中设置该值"
        )
 
    # 3. 处理额外参数(默认空字典,避免 None 报错)
    additional_kwargs = additional_kwargs or {}
 
    # 4. 初始化并返回模型实例
    return ChatOpenAI(
        api_key=dashscope_api_key,
        base_url="https://dashscope.aliyuncs.com/compatible-mode/v1", # 阿里百炼固定兼容接口
        model_name=model_name,
        temperature=temperature,
        **additional_kwargs # 传递额外参数(如 max_tokens=2048)
    )
 
 
 # 可选:提供默认模型实例(方便快速引用,避免每次调用函数)
 default_llm = init_dashscope_llm()

 

 
5.4.2 搭建 ReAct Agent 实例
 
 import os
 os.environ["OPENAI_API_KEY"] = 'Your OpenAI API Key'
 os.environ["SERPAPI_API_KEY"] = 'Your SERPAPI_API_KEY '
 import logging
 logging.basicConfig(level=logging.DEBUG)
 # 加载所需的库
 from langchain_community.agent_toolkits.load_tools import load_tools
 from langchain.agents import initialize_agent
 from langchain.agents import AgentType
 from dashscope_llm import default_llm
 llm = default_llm
 # 设置工具
 tools = load_tools(["serpapi", "llm-math"], llm=llm)
 # 初始化Agent
 agent = initialize_agent(tools, llm, agent=AgentType.ZERO_SHOT_REACT_DESCRIPTION, verbose=False)
 agent.invoke("如果寒武纪股票最新的股价上涨 15%,它的新价格会是多少?")

5.4.3 日志输出

  agent = initialize_agent(tools, llm, agent=AgentType.ZERO_SHOT_REACT_DESCRIPTION, verbose=True)
 DEBUG:openai._base_client:Request options: {'method': 'post', 'url': '/chat/completions', 'headers': {'X-Stainless-Raw-Response': 'true'}, 'files': None, 'idempotency_key': 'stainless-python-retry-7c4c6806-f4f3-4aa6-a2b4-6371c8ad6889', 'json_data': {'messages': [{'content': 'Answer the following questions as best you can. You have access to the following tools:\n\nSearch(query: str, **kwargs: Any) -> str - A search engine. Useful for when you need to answer questions about current events. Input should be a search query.\nCalculator(*args: Any, callbacks: Union[list[langchain_core.callbacks.base.BaseCallbackHandler], langchain_core.callbacks.base.BaseCallbackManager, NoneType] = None, tags: Optional[list[str]] = None, metadata: Optional[dict[str, Any]] = None, **kwargs: Any) -> Any - Useful for when you need to answer questions about math.\n\nUse the following format:\n\nQuestion: the input question you must answer\nThought: you should always think about what to do\nAction: the action to take, should be one of [Search, Calculator]\nAction Input: the input to the action\nObservation: the result of the action\n... (this Thought/Action/Action Input/Observation can repeat N times)\nThought: I now know the final answer\nFinal Answer: the final answer to the original input question\n\nBegin!\n\nQuestion: 如果寒武纪股票最新的股价上涨 15%,它的新价格会是多少?\nThought:', 'role': 'user'}], 'model': 'qwen-plus', 'stop': ['\nObservation:', '\n\tObservation:'], 'stream': False, 'temperature': 0.0}}
 
 
 > Entering new AgentExecutor chain...
 
 INFO:httpx:HTTP Request: POST https://dashscope.aliyuncs.com/compatible-mode/v1/chat/completions "HTTP/1.1 200 OK"
 
 DEBUG:openai._base_client:HTTP Response: POST https://dashscope.aliyuncs.com/compatible-mode/v1/chat/completions "200 OK" Headers({'vary': 'Origin,Access-Control-Request-Method,Access-Control-Request-Headers, Accept-Encoding', 'x-request-id': '0035fd50-2891-463e-a985-801a764c77cb', 'x-dashscope-call-gateway': 'true', 'content-type': 'application/json', 'req-cost-time': '2338', 'req-arrive-time': '1759928381012', 'resp-start-time': '1759928383350', 'x-envoy-upstream-service-time': '2337', 'set-cookie': 'acw_tc=0035fd50-2891-463e-a985-801a764c77cb6baf5c54ebff7f2c690c44c0520fc308;path=/;HttpOnly;Max-Age=1800', 'content-encoding': 'gzip', 'date': 'Wed, 08 Oct 2025 12:59:42 GMT', 'server': 'istio-envoy', 'transfer-encoding': 'chunked'})
 DEBUG:openai._base_client:request_id: 0035fd50-2891-463e-a985-801a764c77cb
 Thought: 我需要知道寒武纪股票的当前价格,然后将其乘以1.15(即增加15%)来计算新价格。首先,我必须查找寒武纪股票的最新股价。
 Action: Search
 Action Input: 寒武纪股票最新价格DEBUG:urllib3.connectionpool:Starting new HTTPS connection (1): serpapi.com:443
 DEBUG:urllib3.connectionpool:https://serpapi.com:443 "GET /search?engine=google&google_domain=google.com&gl=us&hl=en&api_key=1eee5c79f6b3789533d5f787c8281241e8bdd05906959bdd6f17de334b5e7264&q=%E5%AF%92%E6%AD%A6%E7%BA%AA%E8%82%A1%E7%A5%A8%E6%9C%80%E6%96%B0%E4%BB%B7%E6%A0%BC&output=json&source=python HTTP/1.1" 200 None
 DEBUG:openai._base_client:Request options: {'method': 'post', 'url': '/chat/completions', 'headers': {'X-Stainless-Raw-Response': 'true'}, 'files': None, 'idempotency_key': 'stainless-python-retry-be0fcf24-47e3-4357-9baa-65c27346fab7', 'json_data': {'messages': [{'content': "Answer the following questions as best you can. You have access to the following tools:\n\nSearch(query: str, **kwargs: Any) -> str - A search engine. Useful for when you need to answer questions about current events. Input should be a search query.\nCalculator(*args: Any, callbacks: Union[list[langchain_core.callbacks.base.BaseCallbackHandler], langchain_core.callbacks.base.BaseCallbackManager, NoneType] = None, tags: Optional[list[str]] = None, metadata: Optional[dict[str, Any]] = None, **kwargs: Any) -> Any - Useful for when you need to answer questions about math.\n\nUse the following format:\n\nQuestion: the input question you must answer\nThought: you should always think about what to do\nAction: the action to take, should be one of [Search, Calculator]\nAction Input: the input to the action\nObservation: the result of the action\n... (this Thought/Action/Action Input/Observation can repeat N times)\nThought: I now know the final answer\nFinal Answer: the final answer to the original input question\n\nBegin!\n\nQuestion: 如果寒武纪股票最新的股价上涨 15%,它的新价格会是多少?\nThought:Thought: 我需要知道寒武纪股票的当前价格,然后将其乘以1.15(即增加15%)来计算新价格。首先,我必须查找寒武纪股票的最新股价。\nAction: Search\nAction Input: 寒武纪股票最新价格\nObservation: ['手机东方财富网是东方财富网的手机门户网站,为亿万用户打造一个手机联通世界的超级平台,提供7*24小时全面及时的财经中文资讯,内容覆盖国内外突发事件、股市资讯、全球新闻', '截至2025年10月07日,寒武纪(688256)的交易价格报1,325.00,前一交易日收于1,323.50,日内波动范围介于1,318.23至1,399.00之间,52周波动范围介于302.32至1,595.88之间。', '寒武纪-U (688256) · 最高价. 1399.00 · 最低价. 1318.23 · 成交量. 865.40万手 · 今开. 1388.00 · 昨收. 1323.50 · 成交额. 117.00亿 · 换手率. 2.07% · 市盈率(静). 亏损.', '雪球为您提供寒武纪-U(SH688256)股票股价,实时行情,热门讨论,最新资讯,最新公告,公司资料,财务数据,财务指标分析等与寒武纪-U(SH688256)股票相关的信息与服务.', '寒武纪定增结果出炉!9月30日晚间,国产AI芯片巨头寒武纪披露了定增结果。此次定增发行价格为1195.02元/股,实际发行数量为333.49万股,募集资金总额达39.85亿元。......', '... 寒武纪、摩尔线程已适配 2025-09-30 22:52 1195.02元!寒武纪刷新A股定增价格最高纪录! 2025-09-30 22:44 【公告精选】寒武纪定增发行价出炉,*ST正平停牌 ...', '寒武纪(688256)的实时行情,及时准确的提供寒武纪(688256)的flash分时走势、K线图、均价线系统、MACD、KDJ、交易量等全面技术分析,帮你做出及时判断, ...', '提供寒武纪-U(688256)的行情走势、资金流向、行业概念板块排行、成份股排行、大盘分析、证券聚焦、市场总貌、股吧互动等与寒武纪-U(688256)有关的信息和服务。', '430.00% · 前收市價 1,323.50 · 開市 1,388.00 · 買入價 1,325.00 x -- · 賣出價 1,325.30 x -- · 今日波幅 1,318.23 - 1,399.00 · 52 週波幅 302.32 - 1,595.88 · 成交量 ...', '寒武纪(688256.SH) ; SSH高装(全). 931867CNY01. 2023-12-11 ; 沪港深500信息HKD. H30498. 2023-12-11 ; 上证180优选(全)HKD. H40093. 2023-12-11 ; 沪港深500非周期(全).']\nThought:", 'role': 'user'}], 'model': 'qwen-plus', 'stop': ['\nObservation:', '\n\tObservation:'], 'stream': False, 'temperature': 0.0}}
 
 
 Observation: ['手机东方财富网是东方财富网的手机门户网站,为亿万用户打造一个手机联通世界的超级平台,提供7*24小时全面及时的财经中文资讯,内容覆盖国内外突发事件、股市资讯、全球新闻', '截至2025年10月07日,寒武纪(688256)的交易价格报1,325.00,前一交易日收于1,323.50,日内波动范围介于1,318.23至1,399.00之间,52周波动范围介于302.32至1,595.88之间。', '寒武纪-U (688256) · 最高价. 1399.00 · 最低价. 1318.23 · 成交量. 865.40万手 · 今开. 1388.00 · 昨收. 1323.50 · 成交额. 117.00亿 · 换手率. 2.07% · 市盈率(静). 亏损.', '雪球为您提供寒武纪-U(SH688256)股票股价,实时行情,热门讨论,最新资讯,最新公告,公司资料,财务数据,财务指标分析等与寒武纪-U(SH688256)股票相关的信息与服务.', '寒武纪定增结果出炉!9月30日晚间,国产AI芯片巨头寒武纪披露了定增结果。此次定增发行价格为1195.02元/股,实际发行数量为333.49万股,募集资金总额达39.85亿元。......', '... 寒武纪、摩尔线程已适配 2025-09-30 22:52 1195.02元!寒武纪刷新A股定增价格最高纪录! 2025-09-30 22:44 【公告精选】寒武纪定增发行价出炉,*ST正平停牌 ...', '寒武纪(688256)的实时行情,及时准确的提供寒武纪(688256)的flash分时走势、K线图、均价线系统、MACD、KDJ、交易量等全面技术分析,帮你做出及时判断, ...', '提供寒武纪-U(688256)的行情走势、资金流向、行业概念板块排行、成份股排行、大盘分析、证券聚焦、市场总貌、股吧互动等与寒武纪-U(688256)有关的信息和服务。', '430.00% · 前收市價 1,323.50 · 開市 1,388.00 · 買入價 1,325.00 x -- · 賣出價 1,325.30 x -- · 今日波幅 1,318.23 - 1,399.00 · 52 週波幅 302.32 - 1,595.88 · 成交量 ...', '寒武纪(688256.SH) ; SSH高装(全). 931867CNY01. 2023-12-11 ; 沪港深500信息HKD. H30498. 2023-12-11 ; 上证180优选(全)HKD. H40093. 2023-12-11 ; 沪港深500非周期(全).']
 Thought:Thought: 从搜索结果中可以看到,寒武纪股票(688256)的最新价格为 **1,325.00元**(多个来源显示“交易价格报1,325.00”或“买入价1,325.00”)。现在我需要计算该价格基础上上涨15%后的新价格。
 DEBUG:httpcore.http11:receive_response_headers.complete return_value=(b'HTTP/1.1', 200, b'OK', [(b'vary', b'Origin,Access-Control-Request-Method,Access-Control-Request-Headers, Accept-Encoding'), (b'x-request-id', b'd7325f58-65c5-48ec-9c7d-d25a77afa2f4'), (b'x-dashscope-call-gateway', b'true'), (b'content-type', b'application/json'), (b'req-cost-time', b'2561'), (b'req-arrive-time', b'1759928385183'), (b'resp-start-time', b'1759928387744'), (b'x-envoy-upstream-service-time', b'2559'), (b'content-encoding', b'gzip'), (b'date', b'Wed, 08 Oct 2025 12:59:47 GMT'), (b'server', b'istio-envoy'), (b'transfer-encoding', b'chunked')])
 INFO:httpx:HTTP Request: POST https://dashscope.aliyuncs.com/compatible-mode/v1/chat/completions "HTTP/1.1 200 OK"
 
 DEBUG:openai._base_client:HTTP Response: POST https://dashscope.aliyuncs.com/compatible-mode/v1/chat/completions "200 OK" Headers({'vary': 'Origin,Access-Control-Request-Method,Access-Control-Request-Headers, Accept-Encoding', 'x-request-id': 'd7325f58-65c5-48ec-9c7d-d25a77afa2f4', 'x-dashscope-call-gateway': 'true', 'content-type': 'application/json', 'req-cost-time': '2561', 'req-arrive-time': '1759928385183', 'resp-start-time': '1759928387744', 'x-envoy-upstream-service-time': '2559', 'content-encoding': 'gzip', 'date': 'Wed, 08 Oct 2025 12:59:47 GMT', 'server': 'istio-envoy', 'transfer-encoding': 'chunked'})
 DEBUG:openai._base_client:request_id: d7325f58-65c5-48ec-9c7d-d25a77afa2f4
 DEBUG:openai._base_client:Request options: {'method': 'post', 'url': '/chat/completions', 'headers': {'X-Stainless-Raw-Response': 'true'}, 'files': None, 'idempotency_key': 'stainless-python-retry-8813eddc-96c0-4bee-8ab7-1c5978df0b30', 'json_data': {'messages': [{'content': 'Translate a math problem into a expression that can be executed using Python\'s numexpr library. Use the output of running this code to answer the question.\n\nQuestion: ${Question with math problem.}\n```text\n${single line mathematical expression that solves the problem}\n```\n...numexpr.evaluate(text)...\n```output\n${Output of running the code}\n```\nAnswer: ${Answer}\n\nBegin.\n\nQuestion: What is 37593 * 67?\n```text\n37593 * 67\n```\n...numexpr.evaluate("37593 * 67")...\n```output\n2518731\n```\nAnswer: 2518731\n\nQuestion: 37593^(1/5)\n```text\n37593**(1/5)\n```\n...numexpr.evaluate("37593**(1/5)")...\n```output\n8.222831614237718\n```\nAnswer: 8.222831614237718\n\nQuestion: 1325 * 1.15\n', 'role': 'user'}], 'model': 'qwen-plus', 'stop': ['```output'], 'stream': False, 'temperature': 0.0}}
 
 
 Action: Calculator
 Action Input: 1325 * 1.15
 DEBUG:httpcore.http11:receive_response_headers.complete return_value=(b'HTTP/1.1', 200, b'OK', [(b'vary', b'Origin,Access-Control-Request-Method,Access-Control-Request-Headers, Accept-Encoding'), (b'x-request-id', b'cfb22cc8-47b1-4417-83c7-26d26a57c267'), (b'x-dashscope-call-gateway', b'true'), (b'content-type', b'application/json'), (b'req-cost-time', b'627'), (b'req-arrive-time', b'1759928387794'), (b'resp-start-time', b'1759928388421'), (b'x-envoy-upstream-service-time', b'626'), (b'content-encoding', b'gzip'), (b'date', b'Wed, 08 Oct 2025 12:59:47 GMT'), (b'server', b'istio-envoy'), (b'transfer-encoding', b'chunked')])
 INFO:httpx:HTTP Request: POST https://dashscope.aliyuncs.com/compatible-mode/v1/chat/completions "HTTP/1.1 200 OK"
 DEBUG:httpcore.http11:receive_response_body.started request=<Request [b'POST']>
 DEBUG:httpcore.http11:receive_response_body.complete
 DEBUG:httpcore.http11:response_closed.started
 DEBUG:httpcore.http11:response_closed.complete
 DEBUG:openai._base_client:HTTP Response: POST https://dashscope.aliyuncs.com/compatible-mode/v1/chat/completions "200 OK" Headers({'vary': 'Origin,Access-Control-Request-Method,Access-Control-Request-Headers, Accept-Encoding', 'x-request-id': 'cfb22cc8-47b1-4417-83c7-26d26a57c267', 'x-dashscope-call-gateway': 'true', 'content-type': 'application/json', 'req-cost-time': '627', 'req-arrive-time': '1759928387794', 'resp-start-time': '1759928388421', 'x-envoy-upstream-service-time': '626', 'content-encoding': 'gzip', 'date': 'Wed, 08 Oct 2025 12:59:47 GMT', 'server': 'istio-envoy', 'transfer-encoding': 'chunked'})
 DEBUG:openai._base_client:request_id: cfb22cc8-47b1-4417-83c7-26d26a57c267
 DEBUG:openai._base_client:Request options: {'method': 'post', 'url': '/chat/completions', 'headers': {'X-Stainless-Raw-Response': 'true'}, 'files': None, 'idempotency_key': 'stainless-python-retry-05736117-6a98-4beb-97d9-62022155ef06', 'json_data': {'messages': [{'content': "Answer the following questions as best you can. You have access to the following tools:\n\nSearch(query: str, **kwargs: Any) -> str - A search engine. Useful for when you need to answer questions about current events. Input should be a search query.\nCalculator(*args: Any, callbacks: Union[list[langchain_core.callbacks.base.BaseCallbackHandler], langchain_core.callbacks.base.BaseCallbackManager, NoneType] = None, tags: Optional[list[str]] = None, metadata: Optional[dict[str, Any]] = None, **kwargs: Any) -> Any - Useful for when you need to answer questions about math.\n\nUse the following format:\n\nQuestion: the input question you must answer\nThought: you should always think about what to do\nAction: the action to take, should be one of [Search, Calculator]\nAction Input: the input to the action\nObservation: the result of the action\n... (this Thought/Action/Action Input/Observation can repeat N times)\nThought: I now know the final answer\nFinal Answer: the final answer to the original input question\n\nBegin!\n\nQuestion: 如果寒武纪股票最新的股价上涨 15%,它的新价格会是多少?\nThought:Thought: 我需要知道寒武纪股票的当前价格,然后将其乘以1.15(即增加15%)来计算新价格。首先,我必须查找寒武纪股票的最新股价。\nAction: Search\nAction Input: 寒武纪股票最新价格\nObservation: ['手机东方财富网是东方财富网的手机门户网站,为亿万用户打造一个手机联通世界的超级平台,提供7*24小时全面及时的财经中文资讯,内容覆盖国内外突发事件、股市资讯、全球新闻', '截至2025年10月07日,寒武纪(688256)的交易价格报1,325.00,前一交易日收于1,323.50,日内波动范围介于1,318.23至1,399.00之间,52周波动范围介于302.32至1,595.88之间。', '寒武纪-U (688256) · 最高价. 1399.00 · 最低价. 1318.23 · 成交量. 865.40万手 · 今开. 1388.00 · 昨收. 1323.50 · 成交额. 117.00亿 · 换手率. 2.07% · 市盈率(静). 亏损.', '雪球为您提供寒武纪-U(SH688256)股票股价,实时行情,热门讨论,最新资讯,最新公告,公司资料,财务数据,财务指标分析等与寒武纪-U(SH688256)股票相关的信息与服务.', '寒武纪定增结果出炉!9月30日晚间,国产AI芯片巨头寒武纪披露了定增结果。此次定增发行价格为1195.02元/股,实际发行数量为333.49万股,募集资金总额达39.85亿元。......', '... 寒武纪、摩尔线程已适配 2025-09-30 22:52 1195.02元!寒武纪刷新A股定增价格最高纪录! 2025-09-30 22:44 【公告精选】寒武纪定增发行价出炉,*ST正平停牌 ...', '寒武纪(688256)的实时行情,及时准确的提供寒武纪(688256)的flash分时走势、K线图、均价线系统、MACD、KDJ、交易量等全面技术分析,帮你做出及时判断, ...', '提供寒武纪-U(688256)的行情走势、资金流向、行业概念板块排行、成份股排行、大盘分析、证券聚焦、市场总貌、股吧互动等与寒武纪-U(688256)有关的信息和服务。', '430.00% · 前收市價 1,323.50 · 開市 1,388.00 · 買入價 1,325.00 x -- · 賣出價 1,325.30 x -- · 今日波幅 1,318.23 - 1,399.00 · 52 週波幅 302.32 - 1,595.88 · 成交量 ...', '寒武纪(688256.SH) ; SSH高装(全). 931867CNY01. 2023-12-11 ; 沪港深500信息HKD. H30498. 2023-12-11 ; 上证180优选(全)HKD. H40093. 2023-12-11 ; 沪港深500非周期(全).']\nThought:Thought: 从搜索结果中可以看到,寒武纪股票(688256)的最新价格为 **1,325.00元**(多个来源显示“交易价格报1,325.00”或“买入价1,325.00”)。现在我需要计算该价格基础上上涨15%后的新价格。\n\nAction: Calculator\nAction Input: 1325 * 1.15\nObservation: Answer: 1523.7499999999998\nThought:", 'role': 'user'}], 'model': 'qwen-plus', 'stop': ['\nObservation:', '\n\tObservation:'], 'stream': False, 'temperature': 0.0}}
 
 Observation: Answer: 1523.7499999999998
 Thought:Thought: 计算结果显示,寒武纪股票在当前价格1,325.00元上涨15%后的新价格约为1,523.75元。
 DEBUG:httpcore.http11:receive_response_headers.complete return_value=(b'HTTP/1.1', 200, b'OK', [(b'vary', b'Origin,Access-Control-Request-Method,Access-Control-Request-Headers, Accept-Encoding'), (b'x-request-id', b'ed8e8993-3fdd-4920-aa7d-9c6a8101b078'), (b'x-dashscope-call-gateway', b'true'), (b'content-type', b'application/json'), (b'req-cost-time', b'2228'), (b'req-arrive-time', b'1759928388486'), (b'resp-start-time', b'1759928390714'), (b'x-envoy-upstream-service-time', b'2226'), (b'content-encoding', b'gzip'), (b'date', b'Wed, 08 Oct 2025 12:59:50 GMT'), (b'server', b'istio-envoy'), (b'transfer-encoding', b'chunked')])
 INFO:httpx:HTTP Request: POST https://dashscope.aliyuncs.com/compatible-mode/v1/chat/completions "HTTP/1.1 200 OK"
 
 DEBUG:openai._base_client:HTTP Response: POST https://dashscope.aliyuncs.com/compatible-mode/v1/chat/completions "200 OK" Headers({'vary': 'Origin,Access-Control-Request-Method,Access-Control-Request-Headers, Accept-Encoding', 'x-request-id': 'ed8e8993-3fdd-4920-aa7d-9c6a8101b078', 'x-dashscope-call-gateway': 'true', 'content-type': 'application/json', 'req-cost-time': '2228', 'req-arrive-time': '1759928388486', 'resp-start-time': '1759928390714', 'x-envoy-upstream-service-time': '2226', 'content-encoding': 'gzip', 'date': 'Wed, 08 Oct 2025 12:59:50 GMT', 'server': 'istio-envoy', 'transfer-encoding': 'chunked'})
 DEBUG:openai._base_client:request_id: ed8e8993-3fdd-4920-aa7d-9c6a8101b078
 
 Final Answer: 如果寒武纪股票最新股价上涨15%,它的新价格将是约1,523.75元。
 
 > Finished chain.
 
 Process finished with exit code 0
 

 

通过 LangChain 的 AgentExecutor 和 verbose=True 选项,我们可以清晰地看到 LLM 如何遵循 ReAct Prompt 的指令,自主地思考(Thought)、选择工具(Action)并利用工具反馈(Observation)来完成多步骤任务。

 

6 总结与展望

AI Agent 是 LLM 应用的必然趋势,而 ReAct 框架作为其核心推理逻辑,为 Agent 的自主行动和复杂规划提供了强大的支撑。

借助 LangChain 这类成熟的 Python 库,开发者可以快速地将复杂的 ReAct 逻辑部署到生产环境,通过定义清晰的工具和任务,实现高度自动化、智能化的应用。随着 Agent 生态的不断发展,我们期待 ReAct 及其变体将在各个行业中发挥更大的潜力

文章来自个人专栏
文章 | 订阅
0条评论
0 / 1000
请输入你的评论
0
0