Anthropic API¶
So far this tutorial has used OpenAI's API. Anthropic's Claude models are another popular choice for text analysis tasks. The good news is that everything you have learned so far — prompting, structured output, async programming, and batch processing — carries over. Only the SDK details differ.
This chapter covers the essentials: making a basic query and getting structured output. We will reuse the sentiment analysis example from the basics chapter so you can compare the two APIs directly.
Setup¶
Install the dependencies and configure your API key. You can create an API key in the Claude Console.
On Google Colab, store your key in Colab Secrets first: click the key icon in the left sidebar, add a secret named ANTHROPIC_API_KEY, and enable notebook access. Running locally, put the key in a .env file or in the ANTHROPIC_API_KEY environment variable (see handling API keys).
%pip install -q anthropic pydantic python-dotenv
import os
from dotenv import load_dotenv
load_dotenv() # loads a .env file from the working directory, if there is one
if "ANTHROPIC_API_KEY" not in os.environ:
try:
# On Google Colab, read the key from Colab Secrets
from google.colab import userdata
os.environ["ANTHROPIC_API_KEY"] = userdata.get("ANTHROPIC_API_KEY")
except ImportError:
raise RuntimeError("Set ANTHROPIC_API_KEY in your environment or in a .env file")
Basic query¶
Let's run the same sentiment analysis example with Claude. Compared with OpenAI's Responses API, there are three differences to notice:
- The API is called the Messages API, and the input is a list of messages instead of a single string.
- The system prompt goes into the top-level
systemparameter (OpenAI calls itinstructions). - The
max_tokensparameter is required. It caps the length of the response.
from anthropic import Anthropic
text_message = "The service here is very good!"
system_prompt = "You are an expert on sentiment analysis. Your job is to evaluate the sentiment of the given text message."
user_instruction = f"Given the following text message: '{text_message}', please evaluate its sentiment by giving a score in the range of -1 to 1, where -1 means negative and 1 means positive. Also explain why."
client = Anthropic()
response = client.messages.create(
model="claude-haiku-4-5",
max_tokens=1024,
system=system_prompt,
messages=[{"role": "user", "content": user_instruction}],
)
print(response.content[0].text)
# Sentiment Analysis **Sentiment Score: 0.95 (Highly Positive)** ## Explanation This message expresses a **strongly positive sentiment** for the following reasons: 1. **Positive Adjective**: The word "good" is a clear positive descriptor that directly praises the service. 2. **Intensifier**: The adverb "very" amplifies the positive sentiment, indicating the service is not just good, but notably good. 3. **Direct Compliment**: The statement is a straightforward compliment about the service quality with no qualifying language or sarcasm. 4. **Exclamation Mark**: The exclamation point at the end conveys enthusiasm and genuine satisfaction rather than indifference. The score of 0.95 (rather than a perfect 1.0) reflects that it's a genuine positive statement, though it's conversational rather than extremely emphatic. A perfect 1.0 might be reserved for more intense expressions like "The service here is absolutely amazing!"
We use claude-haiku-4-5 in this chapter.
It is the fastest and cheapest current Claude model ($1 per 1M input tokens, $5 per 1M output tokens) and works well for large-scale text processing.
See the models overview for the full lineup and pricing.
Structured output¶
Just like OpenAI, Anthropic supports structured output with a Pydantic model.
We can reuse the exact same Sentiment model from the structured output chapter.
The method is client.messages.parse, the model goes into the output_format parameter, and the parsed result comes back in response.parsed_output.
from pydantic import BaseModel, Field
class Sentiment(BaseModel):
score: float = Field(
ge=-1,
le=1,
description="Sentiment score in the range of -1 to 1, where -1 means negative and 1 means positive.",
)
explanation: str = Field(description="Explanation of the sentiment score.")
response = client.messages.parse(
model="claude-haiku-4-5",
max_tokens=1024,
system=system_prompt,
messages=[{"role": "user", "content": user_instruction}],
output_format=Sentiment,
)
parsed_output = response.parsed_output
# Print the result as a dictionary
print(parsed_output.model_dump())
# You can get the score and explanation directly
print(f"Score: {parsed_output.score}")
print(f"Explanation: {parsed_output.explanation}")
{'score': 0.85, 'explanation': "The message contains a clear positive sentiment. The phrase 'very good' is an explicit compliment about the service, with the intensifier 'very' strengthening the positive evaluation. The exclamation mark at the end further emphasizes enthusiasm and satisfaction. There are no negative elements or hedging language that would reduce the positive sentiment."}
Score: 0.85
Explanation: The message contains a clear positive sentiment. The phrase 'very good' is an explicit compliment about the service, with the intensifier 'very' strengthening the positive evaluation. The exclamation mark at the end further emphasizes enthusiasm and satisfaction. There are no negative elements or hedging language that would reduce the positive sentiment.
Scaling up¶
The techniques from the rest of this tutorial transfer directly:
- Async and threading: the
anthropicpackage provides anAsyncAnthropicclient that mirrorsAsyncOpenAI, so the patterns from the async programming chapter work the same way. Watch your rate limits. - Batch processing: Anthropic's Message Batches API works like OpenAI's batch API — you submit a file of requests, results come back within 24 hours, and you get a 50% discount.