11import os
22import json
33import boto3
4- from typing import Dict , Iterator
4+ from typing import Dict , Iterator , Optional
55
66from opentelemetry import trace
77from langtrace_python_sdk import langtrace
88from 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
1423def 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" )
5771def 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