0Pricing
AI Engineering Academy · 课时

为您的 Agent 定义工具

使用 @tool 装饰器创建自定义工具,编写清晰的描述供 LLM 决定何时调用各工具,并使用 Pydantic 添加输入验证。

为您的 Agent 定义工具 是 CoddyKit 上的免费 AI Engineering Academy 课时。 这是第 2 节课,共 4 节。 你可以在下方免费阅读本课时的完整内容 — 然后在浏览器中使用内置代码编辑器和全天候 AI 导师进行实践。 这是 AI Engineering Academy 学习路径的一部分,你的进度在网页和 CoddyKit 应用中同步。 AI Engineering Academy 课程共包含 4 节课。

本课时的部分内容尚未翻译,以英文显示。

Tools Give Agents Superpowers

An agent without tools can only reason about what it already knows — it cannot search the web, query a database, or send an email. Tools are Python functions that extend the agent's capabilities by letting it take real-world actions and retrieve fresh information. Defining tools clearly is one of the most important steps in building a reliable agent.

The @tool Decorator in LangChain

LangChain's @tool decorator transforms any Python function into a tool the agent can call. The function's docstring becomes the tool description that the LLM uses to decide when to call it. A clear, specific description dramatically improves the agent's tool selection accuracy.

from langchain_core.tools import tool

@tool
def get_weather(city: str) -> str:
    '''Get the current weather conditions for a given city.
    Use this tool when the user asks about weather in a specific location.
    Input should be just the city name, e.g. 'London' or 'New York'.
    '''
    # Real implementation would call a weather API
    return f'The weather in {city} is 18 degrees Celsius and partly cloudy.'

print(get_weather.name)         # 'get_weather'
print(get_weather.description)  # The docstring above

Type Annotations and Schema Generation

LangChain automatically generates a JSON Schema for each tool from its Python type annotations. The agent receives this schema in the system prompt so it knows what arguments are required, their types, and any constraints. Always annotate your tool functions with precise types.

from langchain_core.tools import tool

@tool
def calculate_compound_interest(
    principal: float,
    annual_rate: float,
    years: int
) -> float:
    '''Calculate compound interest earned over a number of years.
    Args:
        principal: Initial investment amount in dollars.
        annual_rate: Annual interest rate as a decimal (e.g. 0.05 for 5%).
        years: Number of years to compound.
    Returns:
        Final amount after compounding.
    '''
    return principal * (1 + annual_rate) ** years

# Inspect the auto-generated schema
print(calculate_compound_interest.args_schema.schema())

Input Validation with Pydantic

For tools with complex inputs, define a Pydantic model as the args_schema. This gives you automatic validation, type coercion, and descriptive field-level documentation that the LLM sees when deciding how to call the tool.

from langchain_core.tools import tool
from pydantic import BaseModel, Field

class SearchInput(BaseModel):
    query: str = Field(description='The search query to look up.')
    num_results: int = Field(default=5, ge=1, le=20, description='Number of results to return (1-20).')

@tool(args_schema=SearchInput)
def web_search(query: str, num_results: int = 5) -> str:
    '''Search the web for current information on any topic.
    Use this for facts that may have changed after the model training cutoff.
    '''
    return f'Searching for "{query}", returning {num_results} results...'

Writing Effective Tool Descriptions

The tool description is the most important part of your tool definition — the LLM reads it to decide when and how to call the tool. A good description answers: What does this tool do? When should it be used? What should the input look like? What will the output be?

  • Bad: 'Search tool.'
  • Good: 'Search the web for current news, facts, or data. Use when the user asks about recent events or facts not in training data. Input: a concise search query.'

Tool Return Types

Tools can return strings, dictionaries, or structured Pydantic objects. However, the agent ultimately needs the result as text to include in the conversation. If you return a dict, LangChain serializes it to a string. For complex nested data, format it as a readable summary rather than raw JSON to help the model reason about it.

from langchain_core.tools import tool
import json

@tool
def get_stock_price(ticker: str) -> str:
    '''Look up the current stock price for a given ticker symbol.
    Input should be the stock ticker symbol in uppercase, e.g. AAPL or MSFT.
    '''
    # Stub — real implementation calls a financial API
    data = {'ticker': ticker, 'price': 182.50, 'currency': 'USD', 'change': '+1.2%'}
    return f'{ticker}: ${data["price"]} ({data["change"]})'

Handling Tool Errors Gracefully

Tools fail. APIs go down, network timeouts happen, and users provide invalid inputs. Instead of letting exceptions crash your agent loop, wrap tool logic in try/except and return a descriptive error string. The agent can then reason about the failure and decide whether to retry or use a different approach.

from langchain_core.tools import tool
import requests

@tool
def fetch_url(url: str) -> str:
    '''Fetch the text content of a web page given its URL.
    Use for accessing specific documents or web pages the user references.
    '''
    try:
        resp = requests.get(url, timeout=10)
        resp.raise_for_status()
        return resp.text[:2000]  # Return first 2000 chars
    except requests.Timeout:
        return 'Error: Request timed out after 10 seconds.'
    except requests.HTTPError as e:
        return f'Error: HTTP {e.response.status_code}'
    except Exception as e:
        return f'Error fetching URL: {str(e)}'

Asynchronous Tools

When your agent runs many tool calls or your tools make I/O-bound network requests, define async tool functions to avoid blocking the event loop. LangChain's agent executor supports async tools natively — just use async def in your tool function.

from langchain_core.tools import tool
import httpx

@tool
async def async_fetch(url: str) -> str:
    '''Asynchronously fetch content from a URL.
    Preferred over fetch_url when making multiple concurrent requests.
    '''
    async with httpx.AsyncClient(timeout=10) as client:
        try:
            resp = await client.get(url)
            resp.raise_for_status()
            return resp.text[:2000]
        except Exception as e:
            return f'Error: {str(e)}'

Organizing Tools into a Toolkit

When you have many related tools, group them into a toolkit — a class that returns a list of tools. LangChain toolkits follow a common pattern: they accept configuration like API keys in the constructor and expose a get_tools() method. This makes tool management clean and reusable across different agents.

from langchain_core.tools import BaseTool
from typing import List

class WeatherToolkit:
    def __init__(self, api_key: str):
        self.api_key = api_key

    def get_tools(self) -> List[BaseTool]:
        return [
            get_weather,          # defined earlier with @tool
            get_weather_forecast,  # another tool
            get_weather_alert      # another tool
        ]

# Usage
toolkit = WeatherToolkit(api_key='your_weather_api_key')
tools = toolkit.get_tools()
print(f'Loaded {len(tools)} weather tools')

Limiting Tool Access by User Role

Not every user should have access to every tool. A read-only user should not trigger a send_email or delete_record tool. Implement role-based tool access by selecting which tools to pass to the agent based on the authenticated user's permissions.

def get_tools_for_user(user_role: str) -> list:
    read_tools = [web_search, get_weather, calculate_compound_interest]
    write_tools = [send_email, create_calendar_event, update_record]

    if user_role == 'admin':
        return read_tools + write_tools
    elif user_role == 'member':
        return read_tools
    else:
        return [web_search]  # Guest: only public search

Tool Documentation Best Practices

Well-documented tools dramatically reduce agent errors. Follow these best practices: use a clear verb-first name (search_web, not websearch), describe the expected input format explicitly, mention when NOT to use the tool to avoid false positives, and describe what the output looks like so the model can parse it correctly.

Quick Check

Test your understanding of defining tools for LangChain agents.

Lesson Recap

In this lesson you learned: the @tool decorator turns Python functions into agent-callable tools using their docstrings as descriptions, Pydantic schemas add validated typed inputs, and tools should handle errors gracefully by returning descriptive error strings. Next up we assemble a full ReAct agent with LangChain and trace its reasoning steps.

常见问题解答

「为您的 Agent 定义工具」课时是免费的吗?

是的 — 「为您的 Agent 定义工具」的完整文本可在网页上免费阅读。要进行交互式练习(内置代码编辑器和全天候 AI 导师)并解锁 AI Engineering Academy 课程的其余内容,请升级到 CoddyKit PRO。 AI Engineering Academy 课程共包含 4 节课。

「为您的 Agent 定义工具」这节课中我会学到什么?

使用 @tool 装饰器创建自定义工具,编写清晰的描述供 LLM 决定何时调用各工具,并使用 Pydantic 添加输入验证。 你通过在浏览器中直接运行的动手代码来练习 AI Engineering Academy,全天候 AI 导师会在你学习这节课的过程中回答你的问题。

学习 AI Engineering Academy 需要有经验吗?

无需任何先前经验。CoddyKit 上的 AI Engineering Academy 课程适合初学者到高级学习者,你可以从这里开始或从头开始,按照自己的节奏学习。 这是第 2 节课,共 4 节。

「为您的 Agent 定义工具」课时需要多长时间?

大多数 CoddyKit 课程大约需要 5–10 分钟。每节课都很精短且互动,所以你能稳步进步,并在网页和应用中从离开的地方继续。

我能在这节 AI Engineering Academy 课中编写并运行代码吗?

能。每节 AI Engineering Academy 课都包含内置代码编辑器,你可以在浏览器中直接编写并运行真实代码,并获得即时 AI 反馈 — 无需本地设置。

此课程中的所有课时

  1. ReAct 框架:思考、行动、观察
  2. 为您的 Agent 定义工具
  3. 使用 LangChain 构建 ReAct Agent
  4. 处理智能体故障与循环
← 返回 AI Engineering Academy