Introduction to Claude Tool Use and Pydantic
Claude, an AI model developed by Anthropic, offers a tool use feature that allows for more controlled and structured outputs. Pydantic, a data validation library for Python, provides a way to define data schemas and ensure type consistency. When used together, these tools enable developers to specify exact output structures for Claude's responses.
Setting Up the Environment
To implement Claude tool use with Pydantic, you'll need the following libraries:
from pydantic import BaseModel, Field
from typing import List
from anthropic import Anthropic
import os
Ensure you have the anthropic
and pydantic
libraries installed in your Python environment.
Defining the Pydantic Model
Create a Pydantic model to define the structure of Claude's output:
class TextAnalysis(BaseModel):
sentiment: str = Field(description="Overall sentiment of the text (positive, negative, or neutral)")
main_topics: List[str] = Field(description="List of main topics in the text")
word_count: int = Field(description="Total word count of the text")
This model specifies the exact fields and types expected in the AI's response.
Implementing Claude Tool Use
Here's a function that demonstrates Claude tool use with Pydantic:
def analyze_text_with_claude(api_key: str, text: str) -> TextAnalysis:
client = Anthropic(api_key=api_key)
text_analysis_schema = TextAnalysis.model_json_schema()
tools = [
{
"name": "build_text_analysis_result",
"description": "build the text analysis object",
"input_schema": text_analysis_schema
}
]
message = client.messages.create(
model="claude-3-haiku-20240307",
max_tokens=1200,
temperature=0.2,
system="You are analyzing the sentiment of a text.",
messages=[
{
"role": "user",
"content": f"{text}"
}
],
tools=tools,
tool_choice={"type": "tool", "name": "build_text_analysis_result"}
)
function_call = message.content[0].input
return TextAnalysis(**function_call)
This function performs the following steps:
- Creates an Anthropic client.
- Generates a JSON schema from the Pydantic model.
- Defines a tool that uses this schema.
- Sends a request to Claude with the tool definition.
- Parses Claude's response into a Pydantic object.
Usage Example
Here's how to use the analyze_text_with_claude
function:
api_key = os.environ.get("ANTHROPIC_API_KEY")
sample_text = "Claude tool use can be quite useful if used correctly."
analysis = analyze_text_with_claude(api_key, sample_text)
print(f"Sentiment: {analysis.sentiment}")
print(f"Main topics: {', '.join(analysis.main_topics)}")
print(f"Word count: {analysis.word_count}")
This code snippet demonstrates how to call the function and access the structured data returned by Claude.
Benefits of Using Claude Tool Use with Pydantic
- Structured Output: Ensures Claude's responses adhere to a predefined structure.
- Type Safety: Pydantic provides automatic type checking and validation.
- Consistency: Guarantees uniform response formats across multiple API calls.
- Ease of Integration: Structured responses can be easily integrated into existing Python codebases.
Conclusion
Implementing Claude tool use with Pydantic offers a powerful method for obtaining structured AI responses. This approach is particularly useful for applications requiring consistent, typed data from AI models. With Claude's advanced capabilities and Pydantic's data validation, developers can create more reliable and maintainable AI-powered applications.