11import os
2+ import asyncio
23import ldclient
34from ldclient import Context
45from ldclient .config import Config
5- from ldai .client import LDAIClient , AIConfig , ModelConfig , ProviderConfig , LDMessage
6- from ldai . tracker import TokenUsage
6+ from ldai .client import LDAIClient
7+ from ldai_langchain import LangChainProvider
78from langchain .chat_models import init_chat_model
89
910# Set sdk_key to your LaunchDarkly SDK key.
@@ -21,43 +22,7 @@ def map_provider_to_langchain(provider_name):
2122 lower_provider = provider_name .lower ()
2223 return provider_mapping .get (lower_provider , lower_provider )
2324
24- def track_langchain_metrics (tracker , func ):
25- """
26- Track LangChain-specific operations.
27-
28- This function will track the duration of the operation, the token
29- usage, and the success or error status.
30-
31- If the provided function throws, then this method will also throw.
32-
33- In the case the provided function throws, this function will record the
34- duration and an error.
35-
36- A failed operation will not have any token usage data.
37-
38- :param tracker: The LaunchDarkly tracker instance.
39- :param func: Function to track.
40- :return: Result of the tracked function.
41- """
42- try :
43- result = tracker .track_duration_of (func )
44- tracker .track_success ()
45- if hasattr (result , "usage_metadata" ) and result .usage_metadata :
46- # Extract token usage from LangChain response
47- usage_data = result .usage_metadata
48- token_usage = TokenUsage (
49- input = usage_data .get ("input_tokens" , 0 ),
50- output = usage_data .get ("output_tokens" , 0 ),
51- total = usage_data .get ("total_tokens" , 0 ) # LangChain also has values for input_token_details { cache_creation, cache_read }
52- )
53- tracker .track_tokens (token_usage )
54- except Exception :
55- tracker .track_error ()
56- raise
57-
58- return result
59-
60- def main ():
25+ async def async_main ():
6126 if not sdk_key :
6227 print ("*** Please set the LAUNCHDARKLY_SDK_KEY env first" )
6328 exit ()
@@ -92,12 +57,13 @@ def main():
9257 # provider=ProviderConfig(name='openai'),
9358 # messages=[LDMessage(role='system', content='You are a helpful assistant.')],
9459 # )
95- # config_value, tracker = aiclient.config (ai_config_key, context, default, {'myUserVariable': "Testing Variable"})
96- config_value , tracker = aiclient .config (
60+ # config_value = aiclient.completion_config (ai_config_key, context, default, {'myUserVariable': "Testing Variable"})
61+ config_value = aiclient .completion_config (
9762 ai_config_key ,
9863 context ,
9964 variables = {'myUserVariable' : "Testing Variable" }
10065 )
66+ tracker = config_value .tracker
10167
10268 if not config_value .enabled :
10369 print ("AI Config is disabled" )
@@ -120,8 +86,11 @@ def main():
12086 print ("User Input:\n " , USER_INPUT )
12187 messages .append ({'role' : 'user' , 'content' : USER_INPUT })
12288
123- # Track the LangChain completion with LaunchDarkly metrics
124- completion = track_langchain_metrics (tracker , lambda : llm .invoke (messages ))
89+ # Track the LangChain completion with LaunchDarkly metrics using the LD LangChain provider's extractor
90+ completion = await tracker .track_metrics_of (
91+ lambda : llm .ainvoke (messages ),
92+ LangChainProvider .get_ai_metrics_from_response ,
93+ )
12594 ai_response = completion .content
12695
12796 # Add the AI response to the conversation history.
@@ -139,5 +108,9 @@ def main():
139108 ldclient .get ().close ()
140109
141110
111+ def main ():
112+ asyncio .run (async_main ())
113+
114+
142115if __name__ == "__main__" :
143116 main ()
0 commit comments