Loading...
Loading...
Working with Claude's Messages API — system prompts, extended thinking, and tool use
import anthropic, os
client = anthropic.Anthropic(api_key=os.getenv('ANTHROPIC_API_KEY'))
response = client.messages.create(
model='claude-3-5-sonnet-20241022',
max_tokens=1000,
system='You are a helpful coding tutor.',
messages=[
{'role': 'user', 'content': 'Explain what an API is.'}
]
)
print(response.content[0].text)In the Anthropic API, the system prompt is a separate parameter, not part of messages. This prevents accidental override.
with client.messages.stream(
model='claude-3-5-sonnet-20241022',
max_tokens=1000,
messages=[{'role': 'user', 'content': 'Tell me a story.'}]
) as stream:
for text in stream.text_stream:
print(text, end='')Write a Claude document analyzer:
import anthropic, os
client = anthropic.Anthropic(api_key=os.getenv('ANTHROPIC_API_KEY'))
def analyze(text, analysis_type='summary'):
prompts = {
'summary': 'Provide a 3-bullet summary.',
'sentiment': 'Analyze the sentiment.',
'entities': 'Extract named entities.',
}
response = client.messages.create(
model='claude-3-5-sonnet-20241022',
max_tokens=1000,
system='You are a precise document analyst.',
messages=[{'role': 'user', 'content': f'{prompts[analysis_type]}
{text}'}]
)
return response.content[0].text