Skip to content
Merged
Show file tree
Hide file tree
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
Expand Up @@ -13,6 +13,7 @@
Tuple,
Type,
TypeVar,
Union,
cast,
)

Expand All @@ -31,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:
Expand Down Expand Up @@ -199,11 +201,16 @@ 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):
if image: # Only yield if string is not empty
yield f"{ImageAttributes.IMAGE_URL}", image
elif isinstance(image, Mapping):
image_dict = dict(image)
if url := image_dict.pop("url"):
yield f"{ImageAttributes.IMAGE_URL}", url


def _get_attributes_from_completion_create_param(
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -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,
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -1256,6 +1256,79 @@ 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,
},
)
)
Comment on lines +1297 to +1306

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Any reason not to use vcrpy instead of a manual mock?


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))

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"

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"

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])
Expand Down Expand Up @@ -1873,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
Expand Down