LangChain Agent 入门:让大模型学会使用工具

Published by rcdfrd on 2026-02-10

LangChain Agent 入门:让大模型学会使用工具

大模型能聊天,但不能查天气、不能算数、不能操作数据库。Agent 就是给大模型装上手脚,让它根据需要调用外部工具。

最简 Agent

LangChain 1.0 用 `create_agent` 一行搞定:

```python from langchain.agents import create_agent

agent = create_agent(model="openai:gpt-4o-mini") response = agent.invoke({"messages": [{"role": "user", "content": "天气怎么样"}]}) ```

不带工具的 Agent 本质上就是个有状态的聊天模型。返回的 response 里有完整的消息历史。

给 Agent 加工具

工具就是普通 Python 函数,关键在于 docstring 要写清楚,大模型靠这个判断什么时候该用这个工具:

```python def get_weather(city: str) -> str: """Get the weather information for a given city.""" return f"It's always sunny in {city}!"

agent = create_agent( model="openai:gpt-4o-mini", tools=[get_weather], )

response = agent.invoke( {"messages": [{"role": "user", "content": "sf 天气怎么样"}]} ) ```

执行过程是这样的:用户提问 → 模型决定调用 get_weather → 框架执行函数 → 结果返回给模型 → 模型生成最终回复。消息历史里能看到完整的调用链。

流式输出

Agent 支持两种流式模式:

```python

values 模式:每步输出完整状态

for event in agent.stream( {"messages": [{"role": "user", "content": "天气如何"}]}, stream_mode="values" ): event["messages"][-1].pretty_print()

messages 模式:token 级别的流

for chunk in agent.stream( {"messages": [{"role": "user", "content": "天气如何"}]}, stream_mode="messages" ): print(chunk[0].content, end="") ```

`values` 模式适合调试,能看到每一步的完整状态变化。`messages` 模式适合前端展示,拿到 token 就往页面上写。

小结

Agent 三件事:选模型、定义工具函数、create_agent 组装。大模型负责决策,工具负责执行,框架负责协调。这个模式理解了,后面的记忆管理、Human-in-the-Loop 都是在这个基础上加东西。