Skip to content

Feature: Instrument OpenAI's new Responses API #2782 #2787

New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Open
wants to merge 3 commits into
base: main
Choose a base branch
from
Open
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
Original file line number Diff line number Diff line change
@@ -28,6 +28,7 @@
runs_retrieve_wrapper,
runs_create_and_stream_wrapper,
messages_list_wrapper,
responses_retrieve_wrapper,
)

from opentelemetry.instrumentation.openai.utils import is_metrics_enabled
@@ -243,6 +244,11 @@ def _instrument(self, **kwargs):
"Messages.list",
messages_list_wrapper(tracer),
)
wrap_function_wrapper(
"openai.resources.responses",
"Responses.retrieve",
responses_retrieve_wrapper(tracer),
)
except (AttributeError, ModuleNotFoundError):
pass

Original file line number Diff line number Diff line change
@@ -15,13 +15,46 @@

from openai._legacy_response import LegacyAPIResponse
from openai.types.beta.threads.run import Run
from openai.types.responses import Response

logger = logging.getLogger(__name__)

assistants = {}
runs = {}


@_with_tracer_wrapper
def responses_retrieve_wrapper(tracer, wrapped, instance, args, kwargs):
@dont_throw
def process_response(response):
if isinstance(response, LegacyAPIResponse):
parsed_response = response.parse()
else:
parsed_response = response
assert isinstance(parsed_response, Response)

response_id = parsed_response.id
response_text = parsed_response.content

span = tracer.start_span(
"openai.response.retrieve",
kind=SpanKind.CLIENT,
attributes={SpanAttributes.LLM_REQUEST_TYPE: LLMRequestTypeValues.CHAT.value},
)

_set_span_attribute(span, "gen_ai.response.id", response_id)
_set_span_attribute(span, "gen_ai.response.content", response_text)
span.end()

if context_api.get_value(_SUPPRESS_INSTRUMENTATION_KEY):
return wrapped(*args, **kwargs)

response = wrapped(*args, **kwargs)
process_response(response)

return response


@_with_tracer_wrapper
def assistants_create_wrapper(tracer, wrapped, instance, args, kwargs):
if context_api.get_value(_SUPPRESS_INSTRUMENTATION_KEY):
@@ -46,11 +79,13 @@ def runs_create_wrapper(tracer, wrapped, instance, args, kwargs):
instructions = kwargs.get("instructions")

response = wrapped(*args, **kwargs)
response_dict = model_as_dict(response)

runs[thread_id] = {
"start_time": time.time_ns(),
"assistant_id": kwargs.get("assistant_id"),
"instructions": instructions,
"run_id": response_dict.get("id"),
}

return response
@@ -66,13 +101,15 @@ def process_response(response):
parsed_response = response
assert type(parsed_response) is Run

if parsed_response.id in runs:
if parsed_response.thread_id in runs:
thread_id = parsed_response.thread_id
runs[thread_id]["end_time"] = time.time_ns()
if parsed_response.usage:
runs[thread_id]["usage"] = parsed_response.usage

if context_api.get_value(_SUPPRESS_INSTRUMENTATION_KEY):
return wrapped(*args, **kwargs)

thread_id = kwargs.get("thread_id")
response = wrapped(*args, **kwargs)
process_response(response)

@@ -102,7 +139,7 @@ def messages_list_wrapper(tracer, wrapped, instance, args, kwargs):
start_time=run.get("start_time"),
)

i = 0
prompt_index = 0
if assistants.get(run["assistant_id"]) is not None or Config.enrich_assistant:
if Config.enrich_assistant:
assistant = model_as_dict(
@@ -112,6 +149,11 @@ def messages_list_wrapper(tracer, wrapped, instance, args, kwargs):
else:
assistant = assistants[run["assistant_id"]]

_set_span_attribute(
span,
SpanAttributes.LLM_SYSTEM,
"openai",
)
_set_span_attribute(
span,
SpanAttributes.LLM_REQUEST_MODEL,
@@ -122,25 +164,47 @@ def messages_list_wrapper(tracer, wrapped, instance, args, kwargs):
SpanAttributes.LLM_RESPONSE_MODEL,
assistant["model"],
)
_set_span_attribute(span, f"{SpanAttributes.LLM_PROMPTS}.{i}.role", "system")
_set_span_attribute(span, f"{SpanAttributes.LLM_PROMPTS}.{prompt_index}.role", "system")
_set_span_attribute(
span,
f"{SpanAttributes.LLM_PROMPTS}.{i}.content",
f"{SpanAttributes.LLM_PROMPTS}.{prompt_index}.content",
assistant["instructions"],
)
i += 1
_set_span_attribute(span, f"{SpanAttributes.LLM_PROMPTS}.{i}.role", "system")
prompt_index += 1
_set_span_attribute(span, f"{SpanAttributes.LLM_PROMPTS}.{prompt_index}.role", "system")
_set_span_attribute(
span, f"{SpanAttributes.LLM_PROMPTS}.{i}.content", run["instructions"]
span, f"{SpanAttributes.LLM_PROMPTS}.{prompt_index}.content", run["instructions"]
)
prompt_index += 1

for i, msg in enumerate(messages):
prefix = f"{SpanAttributes.LLM_COMPLETIONS}.{i}"
completion_index = 0
for msg in messages:
prefix = f"{SpanAttributes.LLM_COMPLETIONS}.{completion_index}"
content = msg.get("content")

_set_span_attribute(span, f"{prefix}.role", msg.get("role"))
message_content = content[0].get("text").get("value")
message_role = msg.get("role")
if message_role in ["user", "system"]:
_set_span_attribute(span, f"{SpanAttributes.LLM_PROMPTS}.{prompt_index}.role", message_role)
_set_span_attribute(span, f"{SpanAttributes.LLM_PROMPTS}.{prompt_index}.content", message_content)
prompt_index += 1
else:
_set_span_attribute(span, f"{prefix}.role", msg.get("role"))
_set_span_attribute(span, f"{prefix}.content", message_content)
_set_span_attribute(span, f"gen_ai.response.{completion_index}.id", msg.get("id"))
completion_index += 1

if run.get("usage"):
usage_dict = model_as_dict(run.get("usage"))
_set_span_attribute(
span, f"{prefix}.content", content[0].get("text").get("value")
span,
SpanAttributes.LLM_USAGE_COMPLETION_TOKENS,
usage_dict.get("completion_tokens"),
)
_set_span_attribute(
span,
SpanAttributes.LLM_USAGE_PROMPT_TOKENS,
usage_dict.get("prompt_tokens"),
)

span.end(run.get("end_time"))
@@ -175,6 +239,11 @@ def runs_create_and_stream_wrapper(tracer, wrapped, instance, args, kwargs):
_set_span_attribute(
span, SpanAttributes.LLM_REQUEST_MODEL, assistants[assistant_id]["model"]
)
_set_span_attribute(
span,
SpanAttributes.LLM_SYSTEM,
"openai",
)
_set_span_attribute(
span,
SpanAttributes.LLM_RESPONSE_MODEL,
@@ -195,7 +264,7 @@ def runs_create_and_stream_wrapper(tracer, wrapped, instance, args, kwargs):
)

kwargs["event_handler"] = EventHandleWrapper(
original_handler=kwargs["event_handler"], span=span
original_handler=kwargs["event_handler"], span=span,
)

response = wrapped(*args, **kwargs)