Skip to content

Commit f3d43b0

Browse files
committed
add token counts for when they are present
1 parent 0fe6825 commit f3d43b0

File tree

2 files changed

+17
-4
lines changed
  • src/langtrace_python_sdk/instrumentation

2 files changed

+17
-4
lines changed

src/langtrace_python_sdk/instrumentation/langchain_community/patch.py

Lines changed: 9 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -71,8 +71,15 @@ def traced_method(wrapped, instance, args, kwargs):
7171
result = wrapped(*args, **kwargs)
7272
if trace_output:
7373
span.set_attribute("langchain.outputs", to_json_string(result))
74-
span.set_attribute(SpanAttributes.LLM_USAGE_COMPLETION_TOKENS, instance.get_num_tokens(result))
75-
span.set_attribute(SpanAttributes.LLM_USAGE_PROMPT_TOKENS, instance.get_num_tokens(args[0]))
74+
75+
prompt_tokens = instance.get_num_tokens(args[0])
76+
completion_tokens = instance.get_num_tokens(result)
77+
if hasattr(result, 'usage'):
78+
prompt_tokens = result.usage.prompt_tokens
79+
completion_tokens = result.usage.completion_tokens
80+
81+
span.set_attribute(SpanAttributes.LLM_USAGE_COMPLETION_TOKENS, prompt_tokens)
82+
span.set_attribute(SpanAttributes.LLM_USAGE_PROMPT_TOKENS, completion_tokens)
7683

7784

7885
span.set_status(StatusCode.OK)

src/langtrace_python_sdk/instrumentation/langchain_core/patch.py

Lines changed: 8 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -82,9 +82,15 @@ def traced_method(wrapped, instance, args, kwargs):
8282

8383
if trace_output:
8484
span.set_attribute("langchain.outputs", to_json_string(result))
85-
if result.generations[0][0].text:
85+
if hasattr(result, 'usage'):
86+
prompt_tokens = result.usage.prompt_tokens
87+
completion_tokens = result.usage.completion_tokens
88+
span.set_attribute(SpanAttributes.LLM_USAGE_PROMPT_TOKENS, prompt_tokens)
89+
span.set_attribute(SpanAttributes.LLM_USAGE_COMPLETION_TOKENS, completion_tokens)
90+
91+
elif result.generations[0][0].text:
8692
span.set_attribute(SpanAttributes.LLM_USAGE_COMPLETION_TOKENS, instance.get_num_tokens(result.generations[0][0].text))
87-
if isinstance(args[0][0], str):
93+
elif isinstance(args[0][0], str):
8894
span.set_attribute(SpanAttributes.LLM_USAGE_PROMPT_TOKENS, instance.get_num_tokens(args[0][0]))
8995

9096
else:

0 commit comments

Comments
 (0)