You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何在LangChain Agent工具内部获取并利用工具执行结果?

解决LangChain工具输出的访问与保存问题

首先纠正你工具代码里的错误:原代码中return print('tool 1 ran')逻辑有问题,因为print()函数执行后返回的是None,你需要直接返回工具运行的结果字符串,修正后的基础工具代码如下:

@tool
def action_one(topic: str) -> str:
    """do this for the topic"""
    result = 'tool 1 ran'
    return result

针对保存工具输出的需求,提供两种实现方案:

方案一:在工具内部直接处理保存

如果希望工具运行时自动将结果写入文件或数据库,直接在工具函数内部添加保存逻辑即可:

@tool
def action_one(topic: str) -> str:
    """do this for the topic"""
    result = 'tool 1 ran'
    
    # 写入本地文件(追加模式)
    with open('tool_output_log.txt', 'a', encoding='utf-8') as f:
        f.write(f"[{topic}] 工具输出:{result}\n")
    
    # 示例:保存到SQLite数据库(需先导入sqlite3库)
    # import sqlite3
    # conn = sqlite3.connect('tool_results.db')
    # cursor = conn.cursor()
    # cursor.execute("CREATE TABLE IF NOT EXISTS tool_records (topic TEXT, output TEXT, create_time TIMESTAMP DEFAULT CURRENT_TIMESTAMP)")
    # cursor.execute("INSERT INTO tool_records (topic, output) VALUES (?, ?)", (topic, result))
    # conn.commit()
    # conn.close()
    
    return result

方案二:在Agent调用工具后捕获输出并保存

如果需要在工具外部统一处理结果,可以在Agent运行流程中捕获工具的返回值,或者通过回调函数监听工具运行事件:

方式1:直接获取Agent运行结果

from langchain.agents import AgentExecutor, create_react_agent
from langchain_core.prompts import PromptTemplate
from langchain_openai import ChatOpenAI

# 修正后的工具
@tool
def action_one(topic: str) -> str:
    """do this for the topic"""
    return 'tool 1 ran'

# 初始化Agent
llm = ChatOpenAI(model="gpt-3.5-turbo")
tools = [action_one]
prompt = PromptTemplate.from_template(
    """Answer the following questions as best you can. You have access to the following tools:

{tools}

Use the following format:

Question: the input question you must answer
Thought: you should always think about what to do
Action: the action to take, should be one of [{tool_names}]
Action Input: the input to the action
Observation: the result of the action
... (this cycle can repeat N times)
Thought: I now know the final answer
Final Answer: the final answer to the original input question

Begin!

Question: {input}
Thought:"""
)
agent = create_react_agent(llm, tools, prompt)
agent_executor = AgentExecutor(agent=agent, tools=tools, verbose=True)

# 运行Agent并提取结果
response = agent_executor.invoke({"input": "测试主题"})
# 提取工具输出并保存
with open('agent_output_log.txt', 'a', encoding='utf-8') as f:
    f.write(f"输入主题:测试主题,工具输出:{response['output']}\n")

方式2:用回调函数监听工具运行

如果需要精准捕获每一次工具的调用结果,可自定义回调类:

from langchain_core.callbacks.base import BaseCallbackHandler

class ToolOutputRecorder(BaseCallbackHandler):
    def on_tool_end(self, output, **kwargs):
        # 工具运行结束时自动触发此方法
        with open('tool_callback_log.txt', 'a', encoding='utf-8') as f:
            f.write(f"工具输出:{output}\n")

# 运行Agent时传入回调
response = agent_executor.invoke(
    {"input": "测试主题"},
    callbacks=[ToolOutputRecorder()]
)

内容的提问来源于stack exchange,提问作者DataGuy

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.06.13 21:32:38