How to define a tool for Claude API
Quick answer
To define a tool for the Claude API, use the
anthropic Python SDK by creating a client with your API key and calling client.messages.create with the system parameter to set tool behavior and messages for user input. This lets you customize Claude's responses as a tool within your application.PREREQUISITES
Python 3.8+Anthropic API keypip install anthropic>=0.20
Setup
Install the Anthropic Python SDK and set your API key as an environment variable to authenticate requests.
pip install anthropic>=0.20 Step by step
Define a tool by specifying the system prompt to instruct Claude on its role and use client.messages.create to send user messages. The example below shows a simple tool that answers questions about weather.
import os
import anthropic
client = anthropic.Anthropic(api_key=os.environ["ANTHROPIC_API_KEY"])
system_prompt = "You are a helpful weather information tool. Answer user queries about weather concisely."
user_message = "What's the weather like in New York today?"
response = client.messages.create(
model="claude-3-5-haiku-20241022",
max_tokens=200,
system=system_prompt,
messages=[{"role": "user", "content": user_message}]
)
print(response.content[0].text) output
The weather in New York today is mostly sunny with a high of 68°F (20°C) and a low of 54°F (12°C).
Common variations
- Use different Claude models like
claude-3-5-haiku-20241022for shorter responses. - Adjust
max_tokensto control response length. - Implement async calls with
asyncioandclient.messages.acreatefor concurrency.
import asyncio
import os
import anthropic
async def async_tool_call():
client = anthropic.Anthropic(api_key=os.environ["ANTHROPIC_API_KEY"])
system_prompt = "You are a concise assistant tool."
user_message = "Summarize the benefits of AI tools."
response = await client.messages.acreate(
model="claude-3-5-haiku-20241022",
max_tokens=100,
system=system_prompt,
messages=[{"role": "user", "content": user_message}]
)
print(response.content[0].text)
asyncio.run(async_tool_call()) output
AI tools improve efficiency, automate tasks, and enhance decision-making by providing fast, accurate insights.
Troubleshooting
- If you get authentication errors, verify your
ANTHROPIC_API_KEYenvironment variable is set correctly. - For rate limit errors, reduce request frequency or check your quota on the Anthropic dashboard.
- If responses are incomplete, increase
max_tokensor check for network issues.
Key Takeaways
- Use the
systemparameter to define the tool's behavior in Claude API calls. - Always authenticate with your API key from environment variables using the Anthropic SDK.
- Adjust
max_tokensand model choice to tailor response length and style. - Async calls with
client.messages.acreateenable efficient concurrent tool usage. - Check environment variables and quotas to troubleshoot common API errors.