| 1 |
#!/usr/bin/env -S uv run python |
| 2 |
|
| 3 |
# Note: you must have installed `anthropic` with the `bedrock` extra |
| 4 |
# e.g. `pip install -U anthropic[bedrock]` |
| 5 |
|
| 6 |
from anthropic import AnthropicBedrock |
| 7 |
|
| 8 |
# Note: this assumes you have AWS credentials configured. |
| 9 |
# |
| 10 |
# https://boto3.amazonaws.com/v1/documentation/api/latest/guide/credentials.html |
| 11 |
client = AnthropicBedrock() |
| 12 |
|
| 13 |
print("------ standard response ------") |
| 14 |
message = client.messages.create( |
| 15 |
max_tokens=1024, |
| 16 |
messages=[ |
| 17 |
{ |
| 18 |
"role": "user", |
| 19 |
"content": "Hello!", |
| 20 |
} |
| 21 |
], |
| 22 |
model="global.anthropic.claude-sonnet-5", |
| 23 |
) |
| 24 |
print(message.model_dump_json(indent=2)) |
| 25 |
|
| 26 |
print("------ streamed response ------") |
| 27 |
|
| 28 |
with client.messages.stream( |
| 29 |
max_tokens=1024, |
| 30 |
messages=[ |
| 31 |
{ |
| 32 |
"role": "user", |
| 33 |
"content": "Say hello there!", |
| 34 |
} |
| 35 |
], |
| 36 |
model="global.anthropic.claude-sonnet-5", |
| 37 |
) as stream: |
| 38 |
for text in stream.text_stream: |
| 39 |
print(text, end="", flush=True) |
| 40 |
print() |
| 41 |
|
| 42 |
# you can still get the accumulated final message outside of |
| 43 |
# the context manager, as long as the entire stream was consumed |
| 44 |
# inside of the context manager |
| 45 |
accumulated = stream.get_final_message() |
| 46 |
print("accumulated message: ", accumulated.model_dump_json(indent=2)) |