How to beginner · 3 min read

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 key
  • pip 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) or set ANTHROPIC_API_KEY=your_api_key (Windows)
bash
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.

python
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-5 for potentially improved accuracy.
  • Adjust max_tokens to control response length.
  • Use async calls with asyncio and client.messages.acreate for concurrency.
  • Format prompt to request JSON output for structured classification.
python
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_KEY environment 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 anthropic SDK with client.messages.create to 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.
Verified 2026-04 · claude-3-5-sonnet-20241022, claude-sonnet-4-5
Verify ↗