Define a tool
This exercise introduces the basic shape of a custom tool through a small example that answers a question about a user. It demonstrates how to connect an agent-facing purpose to behavior that returns a result for the agent to use.
from random import randint
from pydantic import Field
from xah import Tool
class AgeTool(Tool):
"""Use this tool to provide a randomly generated age for a named user."""
# (1)!
# (2)!
user: str = Field(
...,
description="The name of the user whose age you want to know.", # (3)!
)
async def run(self):
# (4)!
age = randint(1, 100)
return f"{self.user} is {age} years old."
- The tool docstring is exposed to the agent, so use it to explain when and why it should call the tool.
- Tools are Pydantic AI models and support Python type annotations and Pydantic
Fields. - Field descriptions are also exposed to the agent and provide guidance for each argument.
- The harness calls
run()when the model selects the tool; its return value is provided back to the model.
This file defines the tool used by the following toolset and harness exercises; it is not a standalone agent to launch.