File: bedrock.py

package info (click to toggle)
anthropic-sdk-python 0.75.0-1
  • links: PTS, VCS
  • area: main
  • in suites: sid
  • size: 4,252 kB
  • sloc: python: 29,737; sh: 177; makefile: 5
file content (46 lines) | stat: -rw-r--r-- 1,309 bytes parent folder | download
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
#!/usr/bin/env -S poetry run python

# Note: you must have installed `anthropic` with the `bedrock` extra
# e.g. `pip install -U anthropic[bedrock]`

from anthropic import AnthropicBedrock

# Note: this assumes you have AWS credentials configured.
#
# https://boto3.amazonaws.com/v1/documentation/api/latest/guide/credentials.html
client = AnthropicBedrock()

print("------ standard response ------")
message = client.messages.create(
    max_tokens=1024,
    messages=[
        {
            "role": "user",
            "content": "Hello!",
        }
    ],
    model="anthropic.claude-sonnet-4-5-20250929-v1:0",
)
print(message.model_dump_json(indent=2))

print("------ streamed response ------")

with client.messages.stream(
    max_tokens=1024,
    messages=[
        {
            "role": "user",
            "content": "Say hello there!",
        }
    ],
    model="anthropic.claude-sonnet-4-5-20250929-v1:0",
) as stream:
    for text in stream.text_stream:
        print(text, end="", flush=True)
    print()

    # you can still get the accumulated final message outside of
    # the context manager, as long as the entire stream was consumed
    # inside of the context manager
    accumulated = stream.get_final_message()
    print("accumulated message: ", accumulated.model_dump_json(indent=2))