|
| 1 | +"""Keep Gemini's ordered, unindexed parts distinct in streamed traces.""" |
| 2 | + |
| 3 | +import asyncio |
| 4 | +import json |
| 5 | + |
| 6 | +import httpx |
| 7 | +import pytest |
| 8 | +from fi_instrumentation import safe_json_dumps |
| 9 | +from fi_instrumentation.fi_types import ( |
| 10 | + MessageAttributes, |
| 11 | + SpanAttributes, |
| 12 | + ToolCallAttributes, |
| 13 | +) |
| 14 | +from google import genai |
| 15 | +from google.genai import _api_client, types |
| 16 | +from opentelemetry.sdk.trace import TracerProvider |
| 17 | +from opentelemetry.sdk.trace.export import SimpleSpanProcessor |
| 18 | +from opentelemetry.sdk.trace.export.in_memory_span_exporter import InMemorySpanExporter |
| 19 | +from opentelemetry.trace import StatusCode |
| 20 | +from traceai_google_genai import GoogleGenAIInstrumentor |
| 21 | +from traceai_google_genai._stream import _Stream |
| 22 | +from traceai_google_genai._with_span import _WithSpan |
| 23 | + |
| 24 | + |
| 25 | +def _response(parts, index=0, **kwargs): |
| 26 | + return types.GenerateContentResponse( |
| 27 | + candidates=[ |
| 28 | + types.Candidate( |
| 29 | + index=index, content=types.Content(role="model", parts=parts) |
| 30 | + ) |
| 31 | + ], |
| 32 | + **kwargs, |
| 33 | + ) |
| 34 | + |
| 35 | + |
| 36 | +def _call(name, **args): |
| 37 | + return types.Part(function_call=types.FunctionCall(name=name, args=args)) |
| 38 | + |
| 39 | + |
| 40 | +def _messages(span): |
| 41 | + return json.loads(span.attributes[SpanAttributes.OUTPUT_VALUE])["candidates"] |
| 42 | + |
| 43 | + |
| 44 | +def _assert_calls(span, calls): |
| 45 | + prefix = f"{SpanAttributes.GEN_AI_OUTPUT_MESSAGES}.0.{MessageAttributes.MESSAGE_TOOL_CALLS}" |
| 46 | + names = { |
| 47 | + key: value |
| 48 | + for key, value in span.attributes.items() |
| 49 | + if key.startswith(prefix) |
| 50 | + and key.endswith(ToolCallAttributes.TOOL_CALL_FUNCTION_NAME) |
| 51 | + } |
| 52 | + assert names == { |
| 53 | + f"{prefix}.{i}.{ToolCallAttributes.TOOL_CALL_FUNCTION_NAME}": call.name |
| 54 | + for i, call in enumerate(calls) |
| 55 | + } |
| 56 | + for i, call in enumerate(calls): |
| 57 | + assert ( |
| 58 | + json.loads( |
| 59 | + span.attributes[ |
| 60 | + f"{prefix}.{i}.{ToolCallAttributes.TOOL_CALL_FUNCTION_ARGUMENTS_JSON}" |
| 61 | + ] |
| 62 | + ) |
| 63 | + == call.args |
| 64 | + ) |
| 65 | + |
| 66 | + |
| 67 | +@pytest.fixture |
| 68 | +def tracing(): |
| 69 | + provider = TracerProvider() |
| 70 | + exporter = InMemorySpanExporter() |
| 71 | + provider.add_span_processor(SimpleSpanProcessor(exporter)) |
| 72 | + yield provider, exporter |
| 73 | + provider.shutdown() |
| 74 | + |
| 75 | + |
| 76 | +def _consume(chunks, asynchronous, with_span): |
| 77 | + if not asynchronous: |
| 78 | + return list(_Stream(iter(chunks), with_span)) |
| 79 | + |
| 80 | + async def consume(): |
| 81 | + async def source(): |
| 82 | + for chunk in chunks: |
| 83 | + yield chunk |
| 84 | + |
| 85 | + return [chunk async for chunk in _Stream(source(), with_span)] |
| 86 | + |
| 87 | + return asyncio.run(consume()) |
| 88 | + |
| 89 | + |
| 90 | +@pytest.mark.parametrize("asynchronous", [False, True], ids=["sync", "async"]) |
| 91 | +@pytest.mark.parametrize( |
| 92 | + "groups", |
| 93 | + [ |
| 94 | + [[_call("weather", city="Paris"), _call("time", zone="UTC")]], |
| 95 | + [[_call("weather", city="Paris")], [_call("weather", city="London")]], |
| 96 | + [ |
| 97 | + [types.Part(text="Checking "), _call("weather", city="Paris")], |
| 98 | + [_call("time", zone="UTC"), types.Part(text="now.")], |
| 99 | + ], |
| 100 | + pytest.param( |
| 101 | + [ |
| 102 | + [ |
| 103 | + { |
| 104 | + "function_call": {"name": "weather", "args": {"city": "Paris"}}, |
| 105 | + "thought_signature": b"first-signature", |
| 106 | + }, |
| 107 | + { |
| 108 | + "function_call": {"name": "time", "args": {"zone": "UTC"}}, |
| 109 | + "thought_signature": b"second-signature", |
| 110 | + }, |
| 111 | + ] |
| 112 | + ], |
| 113 | + marks=pytest.mark.skipif( |
| 114 | + "thought_signature" not in types.Part.model_fields, |
| 115 | + reason="This SDK predates thought signatures", |
| 116 | + ), |
| 117 | + ), |
| 118 | + [ |
| 119 | + [ |
| 120 | + types.Part( |
| 121 | + file_data=types.FileData( |
| 122 | + file_uri="gs://example/first", mime_type="image/png" |
| 123 | + ) |
| 124 | + ) |
| 125 | + ], |
| 126 | + [ |
| 127 | + types.Part( |
| 128 | + file_data=types.FileData( |
| 129 | + file_uri="gs://example/second", mime_type="image/png" |
| 130 | + ) |
| 131 | + ) |
| 132 | + ], |
| 133 | + ], |
| 134 | + [[types.Part(text="Hello ")], [types.Part(text="world")]], |
| 135 | + [[_call("weather", city="Paris")]], |
| 136 | + ], |
| 137 | + ids=[ |
| 138 | + "parallel", |
| 139 | + "repeated-name", |
| 140 | + "text-and-tools", |
| 141 | + "signatures", |
| 142 | + "media", |
| 143 | + "text", |
| 144 | + "single-part", |
| 145 | + ], |
| 146 | +) |
| 147 | +def test_stream_preserves_parts(tracing, asynchronous, groups): |
| 148 | + provider, exporter = tracing |
| 149 | + groups = [[types.Part.model_validate(part) for part in parts] for parts in groups] |
| 150 | + chunks = [_response(parts) for parts in groups] |
| 151 | + chunks.append( |
| 152 | + types.GenerateContentResponse( |
| 153 | + candidates=[ |
| 154 | + types.Candidate(index=0, finish_reason=types.FinishReason.STOP) |
| 155 | + ], |
| 156 | + usage_metadata=types.GenerateContentResponseUsageMetadata( |
| 157 | + prompt_token_count=3, candidates_token_count=4, total_token_count=7 |
| 158 | + ), |
| 159 | + model_version="gemini-test", |
| 160 | + ) |
| 161 | + ) |
| 162 | + snapshots = [chunk.model_dump(exclude_unset=True) for chunk in chunks] |
| 163 | + span = provider.get_tracer(__name__).start_span("stream") |
| 164 | + received = _consume(chunks, asynchronous, _WithSpan(span)) |
| 165 | + |
| 166 | + assert len(received) == len(chunks) |
| 167 | + assert all(actual is expected for actual, expected in zip(received, chunks)) |
| 168 | + assert [chunk.model_dump(exclude_unset=True) for chunk in chunks] == snapshots |
| 169 | + finished = exporter.get_finished_spans() |
| 170 | + assert len(finished) == 1 |
| 171 | + result = finished[0] |
| 172 | + expected_parts = [part for group in groups for part in group] |
| 173 | + # Preserve the existing trace serialization, including bytes signatures. |
| 174 | + expected = json.loads( |
| 175 | + safe_json_dumps( |
| 176 | + [part.model_dump(exclude_unset=True) for part in expected_parts] |
| 177 | + ) |
| 178 | + ) |
| 179 | + actual = _messages(result)[0] |
| 180 | + assert actual["content"]["parts"] == expected |
| 181 | + assert actual["finish_reason"] == "STOP" |
| 182 | + assert result.status.status_code == StatusCode.OK |
| 183 | + assert result.attributes[SpanAttributes.GEN_AI_USAGE_INPUT_TOKENS] == 3 |
| 184 | + assert result.attributes[SpanAttributes.GEN_AI_USAGE_OUTPUT_TOKENS] == 4 |
| 185 | + assert result.attributes[SpanAttributes.GEN_AI_USAGE_TOTAL_TOKENS] == 7 |
| 186 | + _assert_calls(result, [p.function_call for p in expected_parts if p.function_call]) |
| 187 | + texts = [p.text for p in expected_parts if p.text] |
| 188 | + if texts: |
| 189 | + assert result.attributes[ |
| 190 | + f"{SpanAttributes.GEN_AI_OUTPUT_MESSAGES}.0.{MessageAttributes.MESSAGE_CONTENT}" |
| 191 | + ] == "".join(texts) |
| 192 | + |
| 193 | + |
| 194 | +@pytest.mark.parametrize("asynchronous", [False, True], ids=["sync", "async"]) |
| 195 | +def test_empty_stream_finishes_without_output(tracing, asynchronous): |
| 196 | + provider, exporter = tracing |
| 197 | + assert ( |
| 198 | + _consume( |
| 199 | + [], |
| 200 | + asynchronous, |
| 201 | + _WithSpan(provider.get_tracer(__name__).start_span("stream")), |
| 202 | + ) |
| 203 | + == [] |
| 204 | + ) |
| 205 | + spans = exporter.get_finished_spans() |
| 206 | + assert len(spans) == 1 |
| 207 | + assert SpanAttributes.OUTPUT_VALUE not in spans[0].attributes |
| 208 | + assert spans[0].status.status_code == StatusCode.OK |
| 209 | + |
| 210 | + |
| 211 | +@pytest.mark.parametrize("asynchronous", [False, True], ids=["sync", "async"]) |
| 212 | +def test_stream_keeps_candidate_indexes_separate(tracing, asynchronous): |
| 213 | + provider, exporter = tracing |
| 214 | + chunks = [ |
| 215 | + types.GenerateContentResponse( |
| 216 | + candidates=[ |
| 217 | + _response([_call("first", x=1)], index=1).candidates[0], |
| 218 | + _response([_call("zeroth", x=0)], index=0).candidates[0], |
| 219 | + ] |
| 220 | + ), |
| 221 | + _response([_call("second", x=2)], index=1), |
| 222 | + ] |
| 223 | + _consume( |
| 224 | + chunks, |
| 225 | + asynchronous, |
| 226 | + _WithSpan(provider.get_tracer(__name__).start_span("stream")), |
| 227 | + ) |
| 228 | + messages = _messages(exporter.get_finished_spans()[0]) |
| 229 | + assert [ |
| 230 | + [part["function_call"]["name"] for part in candidate["content"]["parts"]] |
| 231 | + for candidate in messages |
| 232 | + ] == [["zeroth"], ["first", "second"]] |
| 233 | + |
| 234 | + |
| 235 | +@pytest.mark.parametrize("asynchronous", [False, True], ids=["sync", "async"]) |
| 236 | +def test_real_sdk_stream_exports_all_tool_calls(tracing, asynchronous, monkeypatch): |
| 237 | + provider, exporter = tracing |
| 238 | + chunks = [ |
| 239 | + _response([_call("weather", city="Paris"), _call("time", zone="UTC")]), |
| 240 | + _response([types.Part(text="Done.")]), |
| 241 | + ] |
| 242 | + requests = [] |
| 243 | + |
| 244 | + def respond(request): |
| 245 | + requests.append(request) |
| 246 | + assert ":streamGenerateContent" in request.url.path |
| 247 | + assert request.url.params["alt"] == "sse" |
| 248 | + data = "".join( |
| 249 | + f"data: {chunk.model_dump_json(exclude_unset=True, by_alias=True)}\n\n" |
| 250 | + for chunk in chunks |
| 251 | + ) |
| 252 | + return httpx.Response( |
| 253 | + 200, text=data, headers={"content-type": "text/event-stream"} |
| 254 | + ) |
| 255 | + |
| 256 | + transport = httpx.MockTransport(respond) |
| 257 | + sync_http = httpx.Client(transport=transport) |
| 258 | + async_http = httpx.AsyncClient(transport=transport) |
| 259 | + # Inject at the HTTP boundary so SDK versions before HttpOptions.client_args |
| 260 | + # also exercise real request building, SSE parsing and response conversion. |
| 261 | + monkeypatch.setattr(_api_client, "SyncHttpxClient", lambda **kwargs: sync_http) |
| 262 | + monkeypatch.setattr(_api_client, "AsyncHttpxClient", lambda **kwargs: async_http) |
| 263 | + client = genai.Client(api_key="offline-test-key") |
| 264 | + instrumentor = GoogleGenAIInstrumentor() |
| 265 | + instrumentor.instrument(tracer_provider=provider) |
| 266 | + try: |
| 267 | + if asynchronous: |
| 268 | + |
| 269 | + async def consume(): |
| 270 | + try: |
| 271 | + stream = await client.aio.models.generate_content_stream( |
| 272 | + model="gemini-test", contents="Run both tools." |
| 273 | + ) |
| 274 | + return [chunk async for chunk in stream] |
| 275 | + finally: |
| 276 | + await async_http.aclose() |
| 277 | + |
| 278 | + received = asyncio.run(consume()) |
| 279 | + else: |
| 280 | + received = list( |
| 281 | + client.models.generate_content_stream( |
| 282 | + model="gemini-test", contents="Run both tools." |
| 283 | + ) |
| 284 | + ) |
| 285 | + assert len(requests) == 1 |
| 286 | + assert received[0].function_calls == [ |
| 287 | + part.function_call for part in chunks[0].candidates[0].content.parts |
| 288 | + ] |
| 289 | + assert received[1].text == "Done." |
| 290 | + spans = exporter.get_finished_spans() |
| 291 | + assert len(spans) == 1 |
| 292 | + _assert_calls(spans[0], received[0].function_calls) |
| 293 | + assert len(_messages(spans[0])[0]["content"]["parts"]) == 3 |
| 294 | + finally: |
| 295 | + instrumentor.uninstrument() |
| 296 | + sync_http.close() |
| 297 | + if not async_http.is_closed: |
| 298 | + asyncio.run(async_http.aclose()) |
0 commit comments