2. 使用LangChain创建基础Agent

任务目标

使用LangChain框架搭建一个基础Agent,集成LLM与自定义工具,实现对话式交互。Agent能够根据用户问题自动选择调用工具或直接回答,形成完整的“思考-行动-观察”循环。

环境依赖

需要安装以下Python包(建议Python 3.9+):

pip install langchain langchain-

同时需要配置 (或使用其他兼容的LLM,如通过langchain-接入的模型)。本案例使用的-mini模型,通过环境变量_传入密钥。

核心实现

本案例实现一个具备“加法计算”和“获取当前时间”两个工具的Agent。Agent通过ReAct推理循环决定调用哪个工具,并将工具结果整合后回复用户。完整代码如下:

import os
from datetime import datetime
from langchain.agents import create_react_agent, AgentExecutor
from langchain.agents.output_parsers import ReActSingleInputOutputParser
from langchain.tools import Tool
from langchain_ import ChatOpenAI
from langchain.prompts import PromptTemplate

# 1. 定义工具函数
def add_numbers(a: float, b: float) -> float:
    """计算两个数字的和"""
    return a + b

def get_current_time() -> str:
    """返回当前系统时间"""
    return datetime.now().strftime("%Y-%m-%d %H:%M:%S")

# 2. 包装为LangChain工具
tools = [
    Tool(
        name="add_numbers",
        func=lambda x: str(add_numbers(*map(float, x.split(",")))),
        description="计算两个数字的和。输入格式:两个数字用逗号分隔,例如 '3,5'"
    ),
    Tool(
        name="get_current_time",
        func=lambda _: get_current_time(),
        description="获取当前日期和时间,无需输入参数"
    )
]

# 3. 初始化LLM
llm = ChatOpenAI(
    model="-mini",
    temperature=0,
    =os.getenv("_")
)

# 4. 创建ReAct提示模板
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 Thought/Action/Action Input/Observation 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_scratchpad}"""
)

# 5. 构建Agent
agent = create_react_agent(
    llm=llm,
    tools=tools,
    prompt=prompt
)

# 6. 创建执行器
agent_executor = AgentExecutor(
    agent=agent,
    tools=tools,
    verbose=True,
    handle_parsing_errors=True,
    max_iterations=3
)

# 7. 对话式交互入口
def chat():
    print("Agent已启动。输入'退出'结束对话。")
    while True:
        user_input = input("\n你: ")
        if user_input.lower() in ["退出", "exit", "quit"]:
            break
        try:
            response = agent_executor.invoke({"input": user_input})
            print(f"Agent: {response['output']}")
        except Exception as e:
            print(f"发生错误: {e}")

if __name__ == "__main__":
    chat()

运行方式

export _="your--here"
python agent_demo.py

验证方法

启动程序后,依次输入以下三类问题,观察Agent行为:

  1. 工具调用类:输入“计算 123 和 456 的和”,Agent应调用add_numbers工具并返回结果579。
  2. 时间查询类:输入“现在几点了”,Agent应调用get_current_time工具并返回当前时间。
  3. 纯对话类:输入“你好,介绍一下你自己”,Agent应直接回答,不调用任何工具。

通过条件:上述三类问题均能得到正确响应;在verbose模式下,能看到Agent的Thought/Action/Observation推理过程;工具调用结果与直接计算/系统时间一致。

预期输出示例

对于输入“计算 123 和 456 的和”,预期最终输出为:

Agent: 123 和 456 的和是 579。

对于输入“现在几点了”,预期输出格式为:

Agent: 当前时间是 2025-01-15 14:30:22。

常见问题

  • 错误:确保_已正确设置且账户有可用额度。
  • 工具输入格式错误:若Agent调用工具时报错,检查add_numbers的输入是否为“数字,数字”格式,可在func中添加异常处理。
  • 推理循环不终止:若Agent陷入重复调用,可降低max_iterations值或检查提示模板格式是否严格匹配。