-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathbedrock_basic.py
More file actions
69 lines (54 loc) · 2.11 KB
/
Copy pathbedrock_basic.py
File metadata and controls
69 lines (54 loc) · 2.11 KB
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
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
"""Enforce a Bedrock InvokeModel call with @protect.
``boto3`` does NOT route through httpx — it uses its own urllib3
session — so ``nullrun.init()`` cannot auto-track Bedrock calls the
way it does OpenAI / Anthropic / Mistral. We call ``track_llm``
manually with the token counts Bedrock returns in its response.
``@protect`` still gates the call (budget / kill / pause); ``@guarded``
still translates a ``NullRunError`` into a friendly exit.
Run:
pip install "nullrun[bedrock]" boto3
export NULLRUN_API_KEY=nr_live_...
export AWS_ACCESS_KEY_ID=...
export AWS_SECRET_ACCESS_KEY=...
export AWS_DEFAULT_REGION=us-east-1
python examples/bedrock_basic.py
"""
from __future__ import annotations
from _env import load_env
load_env() # populate os.environ from examples/.env (no-op if absent)
import os
import boto3
from nullrun import guarded, init_or_die, protect, shutdown, track_llm
init_or_die(api_key=os.environ["NULLRUN_API_KEY"])
client = boto3.client("bedrock-runtime", region_name=os.environ.get("AWS_DEFAULT_REGION", "us-east-1"))
@guarded
@protect
def answer(prompt: str) -> str:
response = client.invoke_model(
modelId="anthropic.claude-3-5-sonnet-20240620-v1:0",
contentType="application/json",
accept="application/json",
body=(
b'{"anthropic_version":"bedrock-2023-05-31",'
b'"max_tokens":256,'
b'"messages":[{"role":"user","content":"' + prompt.encode("utf-8") + b'"}]}'
),
)
# Parse the Anthropic-on-Bedrock response shape.
import json
payload = json.loads(response["body"].read())
usage = payload.get("usage") or {}
in_tok = int(usage.get("input_tokens") or 0)
out_tok = int(usage.get("output_tokens") or 0)
track_llm(input_tokens=in_tok, output_tokens=out_tok, model="claude-3-5-sonnet-bedrock")
parts = [
block.get("text", "")
for block in payload.get("content", [])
if block.get("type") == "text"
]
return "".join(parts)
if __name__ == "__main__":
try:
print(answer("In one sentence, what does NullRun do?"))
finally:
shutdown()