How to get text from Claude API response in python
Quick answer
Use the official
anthropic Python SDK to call the Claude model and access the response text via message.content[0].text. Initialize the client with your API key from os.environ, then call client.messages.create() with your prompt and model name.PREREQUISITES
Python 3.8+Anthropic API keypip install anthropic>=0.20
Setup
Install the official Anthropic Python SDK and set your API key as an environment variable.
- Run
pip install anthropic>=0.20to install the SDK. - Set your API key in your shell:
export ANTHROPIC_API_KEY='your_api_key_here'.
pip install anthropic>=0.20 Step by step
Use this complete Python example to send a prompt to Claude and extract the text from the response.
import os
import anthropic
client = anthropic.Anthropic(api_key=os.environ["ANTHROPIC_API_KEY"])
message = client.messages.create(
model="claude-3-5-haiku-20241022",
max_tokens=500,
system="You are a helpful assistant.",
messages=[{"role": "user", "content": "Hello, how are you?"}]
)
text = message.content[0].text
print(text) output
Hello! I'm doing well, thank you. How can I assist you today?
Common variations
You can change the model parameter to other Claude versions like claude-3-5-haiku-20240229. For asynchronous calls, use Python's asyncio with the SDK's async client methods. Streaming responses are not currently supported in the official SDK.
import asyncio
import os
import anthropic
async def main():
client = anthropic.Anthropic(api_key=os.environ["ANTHROPIC_API_KEY"])
message = await client.messages.acreate(
model="claude-3-5-haiku-20240229",
max_tokens=300,
system="You are a helpful assistant.",
messages=[{"role": "user", "content": "Tell me a joke."}]
)
print(message.content[0].text)
asyncio.run(main()) output
Why did the scarecrow win an award? Because he was outstanding in his field!
Troubleshooting
If you get an authentication error, verify your ANTHROPIC_API_KEY environment variable is set correctly. If the response is empty, check your max_tokens parameter and ensure your prompt is valid. For network issues, confirm your internet connection and retry.
Key Takeaways
- Use
message.content[0].textto extract the text from the Claude API response. - Always initialize the Anthropic client with your API key from
os.environ. - The
systemparameter sets the assistant's behavior, whilemessagescontains user input. - You can use async methods with the Anthropic SDK for non-blocking calls.
- Check environment variables and token limits if you encounter errors or empty responses.