Skip to content

LangChain Agent

TIP

Agent(代理)让 LLM 自主决定调用哪些工具来完成用户的任务。

定义工具

python
from langchain.tools import tool

@tool
def calculate(expression: str) -> str:
    """计算数学表达式"""
    try:
        result = eval(expression)
        return f"结果: {result}"
    except Exception as e:
        return f"计算错误: {e}"

@tool
def get_weather(city: str) -> str:
    """查询城市天气"""
    return f"{city} 天气: 晴天, 25°C"

创建 Agent

python
from langchain.agents import create_tool_calling_agent, AgentExecutor

tools = [calculate, get_weather]
agent = create_tool_calling_agent(llm, tools, prompt)

agent_executor = AgentExecutor(
    agent=agent,
    tools=tools,
    verbose=True
)

agent_executor.invoke({"input": "计算 15 * 37"})