How to translate text with Claude API
Quick answer
Use the
anthropic Python SDK to call client.messages.create with the claude-3-5-sonnet-20241022 model, passing a translation prompt in the messages parameter and the system parameter to set context. The API returns the translated text in response.content[0].text.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 your API key in your shell:
export ANTHROPIC_API_KEY='your_api_key_here'
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 translate English text to Spanish using the Claude API. The system parameter sets the assistant's role, and the messages array contains the user prompt.
import os
import anthropic
client = anthropic.Anthropic(api_key=os.environ["ANTHROPIC_API_KEY"])
response = client.messages.create(
model="claude-3-5-sonnet-20241022",
max_tokens=500,
system="You are a helpful assistant that translates English text to Spanish.",
messages=[{"role": "user", "content": "Translate this to Spanish: 'Hello, how are you today?'"}]
)
translated_text = response.content[0].text
print("Translated text:", translated_text) output
Translated text: Hola, ¿cómo estás hoy?
Common variations
You can translate to other languages by changing the system prompt or user message. For asynchronous calls, use asyncio with client.messages.acreate. To use a different Claude model, update the model parameter accordingly.
import asyncio
import os
import anthropic
async def translate_async(text: str, target_language: str):
client = anthropic.Anthropic(api_key=os.environ["ANTHROPIC_API_KEY"])
system_prompt = f"You are a helpful assistant that translates English text to {target_language}."
user_message = {"role": "user", "content": f"Translate this to {target_language}: '{text}'"}
response = await client.messages.acreate(
model="claude-3-5-sonnet-20241022",
max_tokens=500,
system=system_prompt,
messages=[user_message]
)
return response.content[0].text
async def main():
result = await translate_async("Good morning, have a nice day!", "French")
print("Translated text:", result)
asyncio.run(main()) output
Translated text: Bonjour, passez une bonne journée !
Troubleshooting
- If you get an authentication error, verify your
ANTHROPIC_API_KEYenvironment variable is set correctly. - If the response is incomplete, increase
max_tokens. - For unexpected output, ensure your
systemprompt clearly instructs the model to translate.
Key Takeaways
- Use the
anthropicSDK withclient.messages.createfor Claude translation tasks. - Set the
systemparameter to specify translation instructions clearly. - Async calls are supported via
client.messages.acreatefor non-blocking translation. - Adjust
max_tokensto control response length and avoid truncation. - Always keep your API key secure and set via environment variables.