From 5e656854abc24611504a028af2ea0182eb323d34 Mon Sep 17 00:00:00 2001 From: Roger Hu Date: Thu, 18 Sep 2025 09:13:49 -0700 Subject: [PATCH 1/5] fix image url extractor --- .../openai/_request_attributes_extractor.py | 17 +++- .../openai/test_instrumentor.py | 77 +++++++++++++++++++ 2 files changed, 90 insertions(+), 4 deletions(-) diff --git a/python/instrumentation/openinference-instrumentation-openai/src/openinference/instrumentation/openai/_request_attributes_extractor.py b/python/instrumentation/openinference-instrumentation-openai/src/openinference/instrumentation/openai/_request_attributes_extractor.py index 74b051484f..e6c6887c67 100644 --- a/python/instrumentation/openinference-instrumentation-openai/src/openinference/instrumentation/openai/_request_attributes_extractor.py +++ b/python/instrumentation/openinference-instrumentation-openai/src/openinference/instrumentation/openai/_request_attributes_extractor.py @@ -13,6 +13,7 @@ Tuple, Type, TypeVar, + Union, cast, ) @@ -194,11 +195,19 @@ def _get_attributes_from_message_content( def _get_attributes_from_image( self, - image: Mapping[str, Any], + image: Union[Mapping[str, Any], str], ) -> Iterator[Tuple[str, AttributeValue]]: - image = dict(image) - if url := image.pop("url"): - yield f"{ImageAttributes.IMAGE_URL}", url + # Handle both dict and string formats for image_url + if isinstance(image, str): + # Simplified format: image_url is directly a URL string + if image: # Only yield if string is not empty + yield f"{ImageAttributes.IMAGE_URL}", image + elif isinstance(image, Mapping): + # Standard format: image_url is a dict with "url" key + image_dict = dict(image) + if url := image_dict.pop("url"): + yield f"{ImageAttributes.IMAGE_URL}", url + # For any other type, silently return empty (graceful handling) def _get_attributes_from_completion_create_param( diff --git a/python/instrumentation/openinference-instrumentation-openai/tests/openinference/instrumentation/openai/test_instrumentor.py b/python/instrumentation/openinference-instrumentation-openai/tests/openinference/instrumentation/openai/test_instrumentor.py index d3070b44c2..5adeb1ad77 100644 --- a/python/instrumentation/openinference-instrumentation-openai/tests/openinference/instrumentation/openai/test_instrumentor.py +++ b/python/instrumentation/openinference-instrumentation-openai/tests/openinference/instrumentation/openai/test_instrumentor.py @@ -1145,6 +1145,83 @@ def test_chat_completions_with_config_hiding_hiding_inputs( in_memory_span_exporter.clear() +@pytest.mark.parametrize("image_url_format", ["string", "dict"]) +def test_chat_completions_with_image_url_formats_issue_2188( + respx_mock: MockRouter, + in_memory_span_exporter: InMemorySpanExporter, + completion_usage: Dict[str, Any], + model_name: str, + image_url_format: str, +) -> None: + """ + This test ensures that both string and dict formats for image_url are handled correctly: + - String format: "image_url": "https://example.com/image.png" + - Dict format: "image_url": {"url": "https://example.com/image.png"} + """ + image_url_content: Union[str, Dict[str, str]] + if image_url_format == "string": + image_url_content = "https://example.com/test-image.png" + else: + image_url_content = {"url": "https://example.com/test-image.png"} + + input_messages = [ + {"role": "system", "content": "You are a helpful assistant."}, + { + "role": "user", + "content": [ + {"type": "text", "text": "What's in this image?"}, + {"type": "image_url", "image_url": image_url_content}, + ], + }, + ] + + output_messages = [{"role": "assistant", "content": "I can see an image."}] + invocation_parameters = { + "model": model_name, + "temperature": 0.7, + "n": 1, + } + + url = "https://api.openai.com/v1/chat/completions" + respx_mock.post(url).mock( + return_value=Response( + status_code=200, + json={ + "choices": [{"index": 0, "message": output_messages[0], "finish_reason": "stop"}], + "model": model_name, + "usage": completion_usage, + }, + ) + ) + + # This should not raise a ValueError regardless of image_url format + openai = import_module("openai") + client = openai.OpenAI(api_key="sk-test") + client.chat.completions.create(messages=input_messages, **invocation_parameters) + + spans = in_memory_span_exporter.get_finished_spans() + assert len(spans) == 2 # httpx instrumentor + openai instrumentor + span = spans[1] + + assert span.status.is_ok + attributes = dict(cast(Mapping[str, AttributeValue], span.attributes)) + + # Verify that image attributes are correctly extracted for both formats + image_url_key = "llm.input_messages.1.message.contents.1.message_content.image.image.url" + image_url_attr = attributes.get(image_url_key) + assert image_url_attr == "https://example.com/test-image.png" + + # Verify message content type is correctly set to "image" + content_type_key = "llm.input_messages.1.message.contents.1.message_content.type" + content_type_attr = attributes.get(content_type_key) + assert content_type_attr == "image" + + # Clean up for other tests + assert attributes.pop(OPENINFERENCE_SPAN_KIND, None) == OpenInferenceSpanKindValues.LLM.value + assert attributes.pop(LLM_PROVIDER, None) == LLM_PROVIDER_OPENAI + assert attributes.pop(LLM_SYSTEM, None) == LLM_SYSTEM_OPENAI + + @pytest.mark.parametrize("hide_outputs", [False, True]) @pytest.mark.parametrize("hide_output_messages", [False, True]) @pytest.mark.parametrize("hide_output_text", [False, True]) From 18c4f6f90324a0d2b83643f17ae74b0def0e1bc9 Mon Sep 17 00:00:00 2001 From: Roger Hu Date: Thu, 18 Sep 2025 09:20:50 -0700 Subject: [PATCH 2/5] chore --- .../instrumentation/openai/_request_attributes_extractor.py | 3 --- 1 file changed, 3 deletions(-) diff --git a/python/instrumentation/openinference-instrumentation-openai/src/openinference/instrumentation/openai/_request_attributes_extractor.py b/python/instrumentation/openinference-instrumentation-openai/src/openinference/instrumentation/openai/_request_attributes_extractor.py index e6c6887c67..1381a24dac 100644 --- a/python/instrumentation/openinference-instrumentation-openai/src/openinference/instrumentation/openai/_request_attributes_extractor.py +++ b/python/instrumentation/openinference-instrumentation-openai/src/openinference/instrumentation/openai/_request_attributes_extractor.py @@ -199,15 +199,12 @@ def _get_attributes_from_image( ) -> Iterator[Tuple[str, AttributeValue]]: # Handle both dict and string formats for image_url if isinstance(image, str): - # Simplified format: image_url is directly a URL string if image: # Only yield if string is not empty yield f"{ImageAttributes.IMAGE_URL}", image elif isinstance(image, Mapping): - # Standard format: image_url is a dict with "url" key image_dict = dict(image) if url := image_dict.pop("url"): yield f"{ImageAttributes.IMAGE_URL}", url - # For any other type, silently return empty (graceful handling) def _get_attributes_from_completion_create_param( From 5931a179d60dea938c4c166244817bda06317d08 Mon Sep 17 00:00:00 2001 From: Roger Hu Date: Tue, 7 Oct 2025 10:06:34 -0700 Subject: [PATCH 3/5] clean up comments --- .../openinference/instrumentation/openai/test_instrumentor.py | 4 ---- 1 file changed, 4 deletions(-) diff --git a/python/instrumentation/openinference-instrumentation-openai/tests/openinference/instrumentation/openai/test_instrumentor.py b/python/instrumentation/openinference-instrumentation-openai/tests/openinference/instrumentation/openai/test_instrumentor.py index 5adeb1ad77..502d37f6da 100644 --- a/python/instrumentation/openinference-instrumentation-openai/tests/openinference/instrumentation/openai/test_instrumentor.py +++ b/python/instrumentation/openinference-instrumentation-openai/tests/openinference/instrumentation/openai/test_instrumentor.py @@ -1194,7 +1194,6 @@ def test_chat_completions_with_image_url_formats_issue_2188( ) ) - # This should not raise a ValueError regardless of image_url format openai = import_module("openai") client = openai.OpenAI(api_key="sk-test") client.chat.completions.create(messages=input_messages, **invocation_parameters) @@ -1206,17 +1205,14 @@ def test_chat_completions_with_image_url_formats_issue_2188( assert span.status.is_ok attributes = dict(cast(Mapping[str, AttributeValue], span.attributes)) - # Verify that image attributes are correctly extracted for both formats image_url_key = "llm.input_messages.1.message.contents.1.message_content.image.image.url" image_url_attr = attributes.get(image_url_key) assert image_url_attr == "https://example.com/test-image.png" - # Verify message content type is correctly set to "image" content_type_key = "llm.input_messages.1.message.contents.1.message_content.type" content_type_attr = attributes.get(content_type_key) assert content_type_attr == "image" - # Clean up for other tests assert attributes.pop(OPENINFERENCE_SPAN_KIND, None) == OpenInferenceSpanKindValues.LLM.value assert attributes.pop(LLM_PROVIDER, None) == LLM_PROVIDER_OPENAI assert attributes.pop(LLM_SYSTEM, None) == LLM_SYSTEM_OPENAI From 4bd06a8487af8439c51820e5869cd50c6cc711d0 Mon Sep 17 00:00:00 2001 From: Roger Hu Date: Tue, 7 Oct 2025 10:17:28 -0700 Subject: [PATCH 4/5] fix typing --- .../instrumentation/openai/_attributes/_responses_api.py | 8 ++++++-- 1 file changed, 6 insertions(+), 2 deletions(-) diff --git a/python/instrumentation/openinference-instrumentation-openai/src/openinference/instrumentation/openai/_attributes/_responses_api.py b/python/instrumentation/openinference-instrumentation-openai/src/openinference/instrumentation/openai/_attributes/_responses_api.py index 3ff92921fa..deda191745 100644 --- a/python/instrumentation/openinference-instrumentation-openai/src/openinference/instrumentation/openai/_attributes/_responses_api.py +++ b/python/instrumentation/openinference-instrumentation-openai/src/openinference/instrumentation/openai/_attributes/_responses_api.py @@ -482,7 +482,9 @@ def _get_attributes_from_response_input_param_function_call_output( if (call_id := obj.get("call_id")) is not None: yield f"{prefix}{MessageAttributes.MESSAGE_TOOL_CALL_ID}", call_id if (output := obj.get("output")) is not None: - yield f"{prefix}{MessageAttributes.MESSAGE_CONTENT}", output + # Convert complex output types to string for AttributeValue compatibility + output_str = output if isinstance(output, str) else safe_json_dumps(output) + yield f"{prefix}{MessageAttributes.MESSAGE_CONTENT}", output_str @classmethod @stop_on_exception @@ -495,7 +497,9 @@ def _get_attributes_from_response_custom_tool_call_output_param( if (call_id := obj.get("call_id")) is not None: yield f"{prefix}{MessageAttributes.MESSAGE_TOOL_CALL_ID}", call_id if (output := obj.get("output")) is not None: - yield f"{prefix}{MessageAttributes.MESSAGE_CONTENT}", output + # Convert complex output types to string for AttributeValue compatibility + output_str = output if isinstance(output, str) else safe_json_dumps(output) + yield f"{prefix}{MessageAttributes.MESSAGE_CONTENT}", output_str @classmethod @stop_on_exception From 0004b566ac38fe80fc4cc0dc9ed72fdf66fc09e2 Mon Sep 17 00:00:00 2001 From: Roger Hu Date: Tue, 7 Oct 2025 10:27:18 -0700 Subject: [PATCH 5/5] mypy --- .../instrumentation/openai/_request_attributes_extractor.py | 3 ++- .../instrumentation/openai/_response_attributes_extractor.py | 5 ++++- .../instrumentation/openai/test_instrumentor.py | 3 ++- 3 files changed, 8 insertions(+), 3 deletions(-) diff --git a/python/instrumentation/openinference-instrumentation-openai/src/openinference/instrumentation/openai/_request_attributes_extractor.py b/python/instrumentation/openinference-instrumentation-openai/src/openinference/instrumentation/openai/_request_attributes_extractor.py index ac50145dc5..991e84a3d2 100644 --- a/python/instrumentation/openinference-instrumentation-openai/src/openinference/instrumentation/openai/_request_attributes_extractor.py +++ b/python/instrumentation/openinference-instrumentation-openai/src/openinference/instrumentation/openai/_request_attributes_extractor.py @@ -32,7 +32,8 @@ ToolCallAttributes, ) -# TODO: Update to use SpanAttributes.EMBEDDING_INVOCATION_PARAMETERS after https://github.com/Arize-ai/openinference/pull/2162 is merged +# TODO: Update to use SpanAttributes.EMBEDDING_INVOCATION_PARAMETERS after +# https://github.com/Arize-ai/openinference/pull/2162 is merged _EMBEDDING_INVOCATION_PARAMETERS = "embedding.invocation_parameters" if TYPE_CHECKING: diff --git a/python/instrumentation/openinference-instrumentation-openai/src/openinference/instrumentation/openai/_response_attributes_extractor.py b/python/instrumentation/openinference-instrumentation-openai/src/openinference/instrumentation/openai/_response_attributes_extractor.py index b497458214..027a5eac71 100644 --- a/python/instrumentation/openinference-instrumentation-openai/src/openinference/instrumentation/openai/_response_attributes_extractor.py +++ b/python/instrumentation/openinference-instrumentation-openai/src/openinference/instrumentation/openai/_response_attributes_extractor.py @@ -120,7 +120,10 @@ def _get_attributes_from_completion( if (index := getattr(choice, "index", None)) is None: continue if text := getattr(choice, "text", None): - yield f"{SpanAttributes.LLM_CHOICES}.{index}.{ChoiceAttributes.COMPLETION_TEXT}", text + yield ( + f"{SpanAttributes.LLM_CHOICES}.{index}.{ChoiceAttributes.COMPLETION_TEXT}", + text, + ) def _get_attributes_from_create_embedding_response( self, diff --git a/python/instrumentation/openinference-instrumentation-openai/tests/openinference/instrumentation/openai/test_instrumentor.py b/python/instrumentation/openinference-instrumentation-openai/tests/openinference/instrumentation/openai/test_instrumentor.py index 06453e5f85..af5ae84778 100644 --- a/python/instrumentation/openinference-instrumentation-openai/tests/openinference/instrumentation/openai/test_instrumentor.py +++ b/python/instrumentation/openinference-instrumentation-openai/tests/openinference/instrumentation/openai/test_instrumentor.py @@ -1946,7 +1946,8 @@ def tool_call_function_arguments(prefix: str, i: int, j: int) -> str: TOOL_CALL_FUNCTION_ARGUMENTS_JSON = ToolCallAttributes.TOOL_CALL_FUNCTION_ARGUMENTS_JSON EMBEDDING_EMBEDDINGS = SpanAttributes.EMBEDDING_EMBEDDINGS EMBEDDING_MODEL_NAME = SpanAttributes.EMBEDDING_MODEL_NAME -# TODO: Update to use SpanAttributes.EMBEDDING_INVOCATION_PARAMETERS after https://github.com/Arize-ai/openinference/pull/2162 is merged +# TODO: Update to use SpanAttributes.EMBEDDING_INVOCATION_PARAMETERS after +# https://github.com/Arize-ai/openinference/pull/2162 is merged EMBEDDING_INVOCATION_PARAMETERS = "embedding.invocation_parameters" EMBEDDING_VECTOR = EmbeddingAttributes.EMBEDDING_VECTOR EMBEDDING_TEXT = EmbeddingAttributes.EMBEDDING_TEXT