Skip to content

实战:Tool Calling

学习如何定义和使用工具来扩展 Agent 的能力。

工具允许模型与外部系统交互。在 LangChain 中,工具就是带有元数据的 Python 函数。

使用 @tool 装饰器

python
from langchain.tools import tool

@tool
def search(query: str) -> str:
    """Search for information."""
    return f"Results for: {query}"

将工具传入 Agent

python
from langchain.agents import create_agent

agent = create_agent(
    model="openai:gpt-4o",
    tools=[search],
    system_prompt="You are a helpful assistant",
)

工具运行时上下文

工具可以访问运行时上下文:

python
from langchain.tools import tool, ToolRuntime

@tool
def fetch_user_email_preferences(runtime: ToolRuntime) -> str:
    """Fetch the user's email preferences from the store."""
    user_id = runtime.context.user_id
    return f"Preferences for user {user_id}"

工具最佳实践

工具应该有良好的文档:它们的名称、描述和参数名称会成为模型提示词的一部分。LangChain 的 @tool 装饰器会自动添加元数据。

下一步

本站为非官方中文学习站点,不代表 LangChain 官方。部分内容参考官方文档并重新整理为中文学习笔记。