How to classify text with Claude API
Quick answer
Use the
anthropic Python SDK to classify text with Claude by sending a prompt that instructs the model to categorize the input. Create a client with your API key, call client.messages.create with model="claude-3-5-sonnet-20241022", and parse the response content for classification results.PREREQUISITES
Python 3.8+Anthropic API keypip install anthropic>=0.20
Setup
Install the anthropic SDK and set your API key as an environment variable.
- Install the SDK:
pip install anthropic - Set environment variable:
export ANTHROPIC_API_KEY='your_api_key'(Linux/macOS) orset ANTHROPIC_API_KEY=your_api_key(Windows)
pip install anthropic output
Collecting anthropic Downloading anthropic-0.20.0-py3-none-any.whl (20 kB) Installing collected packages: anthropic Successfully installed anthropic-0.20.0
Step by step
This example shows how to classify text by prompting Claude to assign a category label. The prompt instructs Claude to respond with a single category based on the input text.
import os
import anthropic
client = anthropic.Anthropic(api_key=os.environ["ANTHROPIC_API_KEY"])
text_to_classify = "I love sunny days and going to the beach."
prompt = f"Classify the following text into one of these categories: Weather, Sports, Food, Travel, or Other.\nText: {text_to_classify}\nCategory:"
response = client.messages.create(
model="claude-3-5-sonnet-20241022",
max_tokens=10,
system="You are a helpful text classification assistant.",
messages=[{"role": "user", "content": prompt}]
)
category = response.content[0].text.strip()
print(f"Text: {text_to_classify}")
print(f"Predicted category: {category}") output
Text: I love sunny days and going to the beach. Predicted category: Weather
Common variations
- Use different Claude models like
claude-sonnet-4-5for potentially improved accuracy. - Adjust
max_tokensto control response length. - Use async calls with
asyncioandclient.messages.acreatefor concurrency. - Format prompt to request JSON output for structured classification.
import asyncio
import os
import anthropic
async def classify_text_async(text):
client = anthropic.Anthropic(api_key=os.environ["ANTHROPIC_API_KEY"])
prompt = f"Classify the text into categories: Weather, Sports, Food, Travel, Other.\nText: {text}\nCategory:"
response = await client.messages.acreate(
model="claude-3-5-sonnet-20241022",
max_tokens=10,
system="You are a helpful text classification assistant.",
messages=[{"role": "user", "content": prompt}]
)
return response.content[0].text.strip()
async def main():
category = await classify_text_async("The pizza was delicious and cheesy.")
print(f"Predicted category: {category}")
asyncio.run(main()) output
Predicted category: Food
Troubleshooting
- If you get authentication errors, verify your
ANTHROPIC_API_KEYenvironment variable is set correctly. - If the classification is off, refine your prompt to be more explicit or provide examples.
- For rate limits, consider retrying with exponential backoff.
- Ensure you use the
system=parameter instead of a system role message.
Key Takeaways
- Use the
anthropicSDK withclient.messages.createto classify text via prompt engineering. - Set the
system=parameter to guide Claude's behavior effectively. - Async calls enable concurrent classification for higher throughput.
- Refine prompts and categories for better classification accuracy.
- Always secure your API key via environment variables to avoid leaks.