1+ import os
2+ import openai
3+
4+ from openinference .instrumentation .openai import OpenAIInstrumentor
5+
6+ from quotientai import QuotientAI
7+
8+ # Initialize with lazy_init=True to avoid errors if API key is not available at build time
9+ quotient = QuotientAI (lazy_init = True )
10+
11+ # Apply decorator at module level - it will be a no-op until client is configured
12+ @quotient .trace ()
13+ def test_openai ():
14+ client = openai .OpenAI ()
15+ response = client .chat .completions .create (
16+ model = "gpt-3.5-turbo" ,
17+ messages = [{"role" : "user" , "content" : "Write a haiku." }],
18+ max_tokens = 20 ,
19+ stream = True ,
20+ stream_options = {"include_usage" : True },
21+ )
22+
23+ for chunk in response :
24+ if chunk .choices and (content := chunk .choices [0 ].delta .content ):
25+ print (content , end = "" )
26+
27+
28+ def setup_quotient ():
29+ """Configure QuotientAI at runtime when API key is available."""
30+ # Get API key from environment
31+ quotient_api_key = os .environ .get ("QUOTIENT_API_KEY" )
32+
33+ if not quotient_api_key :
34+ print ("Warning: QUOTIENT_API_KEY not found. Tracing will be disabled." )
35+ return False
36+
37+ # Configure the client with the API key
38+ quotient .configure (quotient_api_key )
39+
40+ # Initialize the tracer with instruments
41+ quotient .tracer .init (
42+ app_name = "quotient-trace-openai-lazyinit" ,
43+ environment = "dev" ,
44+ instruments = [OpenAIInstrumentor ()],
45+ )
46+
47+ print ("QuotientAI tracing configured successfully." )
48+ return True
49+
50+
51+ if __name__ == "__main__" :
52+ tracing_enabled = setup_quotient ()
53+ print (
54+ "Running OpenAI test with" ,
55+ "tracing enabled" if tracing_enabled else "tracing disabled" ,
56+ )
57+ print ("=" * 50 )
58+
59+ test_openai ()
0 commit comments