Skip to content

Commit cda6d3c

Browse files
refactor(bedrock): move SDK initialization to function level with proper error handling
Co-Authored-By: [email protected] <[email protected]>
1 parent 8ff104d commit cda6d3c

File tree

2 files changed

+30
-17
lines changed

2 files changed

+30
-17
lines changed

src/examples/awsbedrock_examples/__init__.py

Lines changed: 3 additions & 5 deletions
Original file line numberDiff line numberDiff line change
@@ -1,14 +1,12 @@
11
from examples.awsbedrock_examples.converse import use_converse, use_converse_stream
2-
from langtrace_python_sdk import langtrace, with_langtrace_root_span
3-
4-
langtrace.init()
2+
from langtrace_python_sdk import with_langtrace_root_span
53

64
class AWSBedrockRunner:
75
@with_langtrace_root_span("AWS_Bedrock")
86
def run(self):
97
# Standard completion
108
print("\nRunning standard completion example...")
11-
response = use_converse()
9+
response = use_converse("Tell me a short joke")
1210
if response:
1311
content = response.get('output', {}).get('message', {}).get('content', [])
1412
if content:
@@ -17,7 +15,7 @@ def run(self):
1715
# Streaming completion
1816
print("\nRunning streaming completion example...")
1917
try:
20-
for chunk in use_converse_stream():
18+
for chunk in use_converse_stream("Tell me about yourself"):
2119
content = chunk.get('output', {}).get('message', {}).get('content', [])
2220
if content:
2321
print(f"Chunk: {content[0].get('text', '')}", end='', flush=True)

src/examples/awsbedrock_examples/converse.py

Lines changed: 27 additions & 12 deletions
Original file line numberDiff line numberDiff line change
@@ -1,18 +1,31 @@
11
import os
22
import json
33
import boto3
4-
from typing import Dict, Iterator
4+
from typing import Dict, Iterator, Optional
55

66
from opentelemetry import trace
77
from langtrace_python_sdk import langtrace
88
from langtrace_python_sdk.instrumentation.aws_bedrock import AWSBedrockInstrumentation
99

10-
# Initialize instrumentation
11-
AWSBedrockInstrumentation().instrument()
12-
langtrace.init(api_key=os.environ["LANGTRACE_API_KEY"])
10+
def initialize_sdk() -> None:
11+
"""Initialize the SDK if API key is available."""
12+
try:
13+
api_key = os.environ.get("LANGTRACE_API_KEY")
14+
if not api_key:
15+
print("Warning: LANGTRACE_API_KEY not found in environment")
16+
return
17+
langtrace.init(api_key=api_key)
18+
# Initialize instrumentation
19+
AWSBedrockInstrumentation().instrument()
20+
except Exception as e:
21+
print(f"Warning: Failed to initialize SDK: {e}")
1322

1423
def get_bedrock_client():
1524
"""Create an instrumented AWS Bedrock client."""
25+
# Check for required AWS credentials
26+
if not os.environ.get("AWS_ACCESS_KEY_ID") or not os.environ.get("AWS_SECRET_ACCESS_KEY"):
27+
raise ValueError("AWS credentials not found in environment")
28+
1629
return boto3.client(
1730
"bedrock-runtime",
1831
region_name="us-east-1",
@@ -21,12 +34,13 @@ def get_bedrock_client():
2134
)
2235

2336
@trace.get_tracer(__name__).start_as_current_span("bedrock_converse")
24-
def use_converse(input_text: str) -> Dict:
37+
def use_converse(input_text: str) -> Optional[Dict]:
2538
"""Example of standard completion request with vendor attributes."""
26-
client = get_bedrock_client()
27-
model_id = "anthropic.claude-3-haiku-20240307-v1:0"
28-
39+
initialize_sdk()
2940
try:
41+
client = get_bedrock_client()
42+
model_id = "anthropic.claude-3-haiku-20240307-v1:0"
43+
3044
response = client.invoke_model(
3145
modelId=model_id,
3246
body=json.dumps({
@@ -51,15 +65,16 @@ def use_converse(input_text: str) -> Dict:
5165
return json.loads(content)
5266
except Exception as e:
5367
print(f"ERROR: Can't invoke '{model_id}'. Reason: {e}")
54-
raise
68+
return None
5569

5670
@trace.get_tracer(__name__).start_as_current_span("bedrock_converse_stream")
5771
def use_converse_stream(input_text: str) -> Iterator[Dict]:
5872
"""Example of streaming completion with vendor attributes."""
59-
client = get_bedrock_client()
60-
model_id = "anthropic.claude-3-haiku-20240307-v1:0"
61-
73+
initialize_sdk()
6274
try:
75+
client = get_bedrock_client()
76+
model_id = "anthropic.claude-3-haiku-20240307-v1:0"
77+
6378
response = client.invoke_model_with_response_stream(
6479
modelId=model_id,
6580
body=json.dumps({

0 commit comments

Comments
 (0)