Lesson
Defining Tools in the API Payload
To give Claude access to a tool, you must describe it in the API payload using a very specific JSON schema format. Claude reads this description to understand what the tool does and what arguments it requires.
The tools Array
In your API request, you add a tools array alongside your messages.
Here is how you would define a get_weather tool:
const tools = [
{
name: "get_weather",
description: "Get the current weather for a specific city.",
input_schema: {
type: "object",
properties: {
city: {
type: "string",
description: "The name of the city, e.g., 'London' or 'Tokyo'"
}
},
required: ["city"]
}
}
];
Anatomy of a Tool Definition
name: The exact name of the function in your code. It must contain only letters, numbers, hyphens, and underscores.description: This is arguably the most important part. Claude reads this description to decide whether it should use the tool. If the description is vague, Claude might ignore it or use it at the wrong time. Be extremely specific.input_schema: This defines the arguments your function needs. It uses standard JSON Schema format.properties: The specific arguments (likecity). You must provide a type (string, number, boolean) and a description for each one.required: An array of argument names that Claude must provide when calling the tool.
Sending the Request
Once you have defined the tool, you just attach the array to your API call.
const response = await anthropic.messages.create({
model: 'claude-3-haiku-20240307',
max_tokens: 500,
tools: tools, // Attach the tools array here
messages: [
{ role: 'user', content: 'What is the weather in Paris today?' }
]
});
Because you provided the tool and asked about the weather, Claude will read the description of get_weather, realize it's a perfect match for the user's intent, and generate a tool_use request instead of a standard text reply.
We will look at how to handle that tool_use request in the next lesson.