Skip to content

Commit ef7bb0c

Browse files
Dwij1704dot-agi
andauthored
Enhance the wrap_llm_call function to set prompt and completion attri… (#958)
Enhance the wrap_llm_call function to set prompt and completion attributes based on input arguments and results. Include token usage attributes from callbacks for improved telemetry tracking. Co-authored-by: Pratyush Shukla <ps4534@nyu.edu>
1 parent 6382a87 commit ef7bb0c

1 file changed

Lines changed: 25 additions & 1 deletion

File tree

agentops/instrumentation/crewai/instrumentation.py

Lines changed: 25 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -12,7 +12,7 @@
1212
from opentelemetry.instrumentation.instrumentor import BaseInstrumentor
1313
from opentelemetry.sdk.resources import SERVICE_NAME, TELEMETRY_SDK_NAME, DEPLOYMENT_ENVIRONMENT
1414
from agentops.instrumentation.crewai.version import __version__
15-
from agentops.semconv import SpanAttributes, AgentOpsSpanKindValues, Meters, ToolAttributes
15+
from agentops.semconv import SpanAttributes, AgentOpsSpanKindValues, Meters, ToolAttributes, MessageAttributes
1616
from .crewai_span_attributes import CrewAISpanAttributes, set_span_attribute
1717

1818
# Initialize logger
@@ -367,6 +367,30 @@ def wrap_llm_call(tracer, duration_histogram, token_histogram, environment, appl
367367

368368
result = wrapped(*args, **kwargs)
369369

370+
# Set prompt attributes from args
371+
if args and isinstance(args[0], list):
372+
for i, message in enumerate(args[0]):
373+
if isinstance(message, dict):
374+
if 'role' in message:
375+
span.set_attribute(MessageAttributes.PROMPT_ROLE.format(i=i), message['role'])
376+
if 'content' in message:
377+
span.set_attribute(MessageAttributes.PROMPT_CONTENT.format(i=i), message['content'])
378+
379+
# Set completion attributes from result
380+
if result:
381+
span.set_attribute(MessageAttributes.COMPLETION_CONTENT.format(i=0), str(result))
382+
span.set_attribute(MessageAttributes.COMPLETION_ROLE.format(i=0), "assistant")
383+
384+
# Set token usage attributes from callbacks
385+
if 'callbacks' in kwargs and kwargs['callbacks'] and hasattr(kwargs['callbacks'][0], 'token_cost_process'):
386+
token_process = kwargs['callbacks'][0].token_cost_process
387+
if hasattr(token_process, 'completion_tokens'):
388+
span.set_attribute(SpanAttributes.LLM_USAGE_COMPLETION_TOKENS, token_process.completion_tokens)
389+
if hasattr(token_process, 'prompt_tokens'):
390+
span.set_attribute(SpanAttributes.LLM_USAGE_PROMPT_TOKENS, token_process.prompt_tokens)
391+
if hasattr(token_process, 'total_tokens'):
392+
span.set_attribute(SpanAttributes.LLM_USAGE_TOTAL_TOKENS, token_process.total_tokens)
393+
370394
if duration_histogram:
371395
duration = time.time() - start_time
372396
duration_histogram.record(

0 commit comments

Comments
 (0)