构建真实世界的 Agent:工具上下文与结构化输出
构建真实世界的 Agent:工具上下文与结构化输出
前面的 Agent 示例比较简单。实际项目里你需要系统提示词、运行时上下文传递、结构化输出。这篇把这些东西组装到一起。
完整的 Agent 配置
```python from dataclasses import dataclass from langchain.agents import create_agent from langchain.agents.structured_output import ToolStrategy from langchain.tools import ToolRuntime, tool from langgraph.checkpoint.memory import InMemorySaver
SYSTEM_PROMPT = """你是一个天气预报专家。 可用工具:get_weather_for_location 和 get_user_location。 如果用户问天气但没说地点,先用 get_user_location 获取位置。"""
@dataclass class Context: user_id: str
@tool def get_weather_for_location(city: str) -> str: """获取指定城市的天气。""" return f"It's always sunny in {city}!"
@tool def get_user_location(runtime: ToolRuntime[Context]) -> str: """根据用户ID获取位置。""" return "Florida" if runtime.context.user_id == "1" else "SF" ```
ToolRuntime[Context] 是关键设计。工具函数通过 runtime 参数拿到调用上下文,比如当前用户是谁。这个信息不是大模型传的,是你在 invoke 时注入的。
结构化输出
```python @dataclass class ResponseFormat: punny_response: str weather_conditions: str | None = None
agent = create_agent( model="openai:gpt-4o-mini", system_prompt=SYSTEM_PROMPT, tools=[get_user_location, get_weather_for_location], context_schema=Context, response_format=ToolStrategy(ResponseFormat), checkpointer=InMemorySaver() ) ```
ToolStrategy(ResponseFormat) 让模型最后一步把结果填进你定义的 dataclass。拿结果时用 response['structured_response']。
调用
```python config = {"configurable": {"thread_id": "1"}} response = agent.invoke( {"messages": [{"role": "user", "content": "外面天气怎么样?"}]}, config=config, context=Context(user_id="1") ) print(response["structured_response"]) ```
执行流程:用户提问,模型发现需要位置,调用 get_user_location 通过 runtime 拿到 user_id,得到 Florida,再调用 get_weather,最后填充 ResponseFormat 返回。
小结
真实 Agent 五要素:模型、系统提示词、工具带运行时上下文、结构化输出、记忆管理。context_schema 解决了「工具需要知道当前用户是谁」这类问题,response_format 保证输出格式可控。