Skip to content
Closed
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
8 changes: 8 additions & 0 deletions python/frameworks/google-adk/CHANGELOG.md
Original file line number Diff line number Diff line change
@@ -1,5 +1,13 @@
# Changelog

## Unreleased

- Preserve the async-generator protocol for Runner and BaseAgent streams,
including direct iteration, `asend()`, `athrow()` and `aclose()`. Finish spans
and close the underlying stream on early exit, errors and cancellation.
- Keep stream tracing context active only while executing the stream, so
consumer work and interleaved runs retain their own span and session context.

## [0.1.5] - 2026-05-15

- Fix `instrument()` crash on `google-adk >= 1.32`. Patch targets and
Expand Down
28 changes: 27 additions & 1 deletion python/frameworks/google-adk/README.md
Original file line number Diff line number Diff line change
Expand Up @@ -4,6 +4,32 @@

Python auto-instrumentation library for Google ADK.

## Stream lifecycle

Instrumented `Runner.run_async()` and `BaseAgent.run_async()` streams preserve
the async-generator protocol. You can use `async for`, direct `__anext__()` calls,
`asend()`, `athrow()` and `aclose()`. The stream's tracing context is active while
the agent executes; your event-processing code retains its own context.

If you stop reading before exhaustion, close the stream so the agent can release
resources and its spans can finish. For example:

```python
events = runner.run_async(
user_id=user_id, session_id=session_id, new_message=message
)
try:
async for event in events:
if should_stop(event):
break
finally:
await events.aclose()
```

Normal exhaustion sets the span status to OK. Unhandled exceptions are recorded
as errors. Explicit close and cancellation end spans without marking an
incomplete stream as successful.


## Quickstart

Expand Down Expand Up @@ -105,4 +131,4 @@ Run the python file to send the traces to Future AGI Platform.

```shell
python your_file.py
```
```
146 changes: 84 additions & 62 deletions python/frameworks/google-adk/traceai_google_adk/_wrappers.py
Original file line number Diff line number Diff line change
Expand Up @@ -3,14 +3,16 @@
import json
import logging
from abc import ABC
from contextlib import ExitStack
from contextlib import ExitStack, contextmanager
from functools import partial
from typing import (
Any,
AsyncGenerator,
Callable,
Iterable,
Iterator,
Mapping,
Optional,
OrderedDict,
TypedDict,
TypeVar,
Expand Down Expand Up @@ -76,6 +78,78 @@ class _RunnerRunAsyncKwargs(TypedDict):
run_config: NotRequired[RunConfig]


async def _trace_async_generator(
generator: AsyncGenerator[Event, Any],
tracer: trace_api.Tracer,
name: str,
attributes: Mapping[str, AttributeValue],
*,
user_id: Optional[str] = None,
session_id: Optional[str] = None,
) -> AsyncGenerator[Event, Any]:
"""Trace generator execution without leaving its context in the consumer."""
span = tracer.start_span(name=name, attributes=attributes)
with ExitStack() as stack:
stack.enter_context(trace_api.use_span(span, end_on_exit=False))
if user_id is not None:
stack.enter_context(using_user(user_id))
if session_id is not None:
stack.enter_context(using_session(session_id))
generator_context = context_api.get_current()

@contextmanager
def resume_context() -> Iterator[None]:
nonlocal generator_context
token = context_api.attach(generator_context)
try:
yield
finally:
# An agent may itself hold a child span across yielded events.
generator_context = context_api.get_current()
context_api.detach(token)

advance = generator.__anext__
try:
try:
while True:
with resume_context():
event = await advance()
if event.is_final_response():
try:
span.set_attribute(
SpanAttributes.OUTPUT_VALUE,
event.model_dump_json(exclude_none=True),
)
span.set_attribute(
SpanAttributes.OUTPUT_MIME_TYPE,
FiMimeTypeValues.JSON.value,
)
except Exception:
logger.exception(
f"Failed to get attribute: {SpanAttributes.OUTPUT_VALUE}."
)
try:
value = yield event
except GeneratorExit:
return
except BaseException as exc: # noqa: BLE001
# Forward injected exceptions, including cancellation, unchanged.
advance = partial(generator.athrow, exc)
else:
advance = partial(generator.asend, value)
finally:
with resume_context():
await generator.aclose()
except StopAsyncIteration:
span.set_status(StatusCode.OK)
except Exception as exc:
span.record_exception(exc)
span.set_status(StatusCode.ERROR)
raise
finally:
span.end()


class _RunnerRunAsync(_WithTracer):
def __call__(
self,
Expand Down Expand Up @@ -109,40 +183,14 @@ def __call__(
if (session_id := kwargs.get("session_id")) is not None:
attributes[SpanAttributes.GEN_AI_CONVERSATION_ID] = session_id

class _AsyncGenerator(wrapt.ObjectProxy): # type: ignore[misc]
__wrapped__: AsyncGenerator[Event, None]

async def __aiter__(self) -> Any:
with ExitStack() as stack:
span = stack.enter_context(
tracer.start_as_current_span(
name=name,
attributes=attributes,
)
)
if user_id is not None:
stack.enter_context(using_user(user_id))
if session_id is not None:
stack.enter_context(using_session(session_id))
async for event in self.__wrapped__:
if event.is_final_response():
try:
span.set_attribute(
SpanAttributes.OUTPUT_VALUE,
event.model_dump_json(exclude_none=True),
)
span.set_attribute(
SpanAttributes.OUTPUT_MIME_TYPE,
FiMimeTypeValues.JSON.value,
)
except Exception:
logger.exception(
f"Failed to get attribute: {SpanAttributes.OUTPUT_VALUE}."
)
yield event
span.set_status(StatusCode.OK)

return _AsyncGenerator(generator)
return _trace_async_generator(
generator,
tracer,
name,
attributes,
user_id=user_id,
session_id=session_id,
)


class _BaseAgentRunAsync(_WithTracer):
Expand All @@ -163,33 +211,7 @@ def __call__(
attributes[SpanAttributes.GEN_AI_SPAN_KIND] = FiSpanKindValues.AGENT.value
attributes[SpanAttributes.GEN_AI_AGENT_NAME] = instance.name

class _AsyncGenerator(wrapt.ObjectProxy): # type: ignore[misc]
__wrapped__: AsyncGenerator[Event, None]

async def __aiter__(self) -> Any:
with tracer.start_as_current_span(
name=name,
attributes=attributes,
) as span:
async for event in self.__wrapped__:
if event.is_final_response():
try:
span.set_attribute(
SpanAttributes.OUTPUT_VALUE,
event.model_dump_json(exclude_none=True),
)
span.set_attribute(
SpanAttributes.OUTPUT_MIME_TYPE,
FiMimeTypeValues.JSON.value,
)
except Exception:
logger.exception(
f"Failed to get attribute: {SpanAttributes.OUTPUT_VALUE}."
)
yield event
span.set_status(StatusCode.OK)

return _AsyncGenerator(generator)
return _trace_async_generator(generator, tracer, name, attributes)


class _TraceCallLlm(_WithTracer):
Expand Down
22 changes: 11 additions & 11 deletions python/tests/test_framework_google_adk.py
Original file line number Diff line number Diff line change
Expand Up @@ -50,16 +50,16 @@ def test_instrumentation_dependencies(self):
deps = self.instrumentor.instrumentation_dependencies()
assert ("google-adk >= 1.2.1",) == deps

def test_instrument_basic(self):
def test_instrument_basic(self, monkeypatch):
"""Test basic instrumentation setup without complex patches."""
# Mock tracer setup
mock_tracer = Mock()
self.instrumentor._tracer = mock_tracer
monkeypatch.setattr(self.instrumentor, "_tracer", mock_tracer, raising=False)

# Mock the helper methods to avoid complex patching
self.instrumentor._patch_trace_call_llm = Mock()
self.instrumentor._patch_trace_tool_call = Mock()
self.instrumentor._disable_existing_tracers = Mock()
monkeypatch.setattr(self.instrumentor, "_patch_trace_call_llm", Mock())
monkeypatch.setattr(self.instrumentor, "_patch_trace_tool_call", Mock())
monkeypatch.setattr(self.instrumentor, "_disable_existing_tracers", Mock())

# Test that the helper methods would be called
self.instrumentor._patch_trace_call_llm()
Expand All @@ -71,13 +71,13 @@ def test_instrument_basic(self):
self.instrumentor._patch_trace_tool_call.assert_called_once()
self.instrumentor._disable_existing_tracers.assert_called_once()

def test_uninstrument(self):
def test_uninstrument(self, monkeypatch):
"""Test uninstrumentation."""
# Mock the cleanup methods
self.instrumentor._unpatch_trace_call_llm = Mock()
self.instrumentor._unpatch_trace_tool_call = Mock()
self.instrumentor._restore_existing_tracers = Mock()
self.instrumentor._originals = []
monkeypatch.setattr(self.instrumentor, "_unpatch_trace_call_llm", Mock())
monkeypatch.setattr(self.instrumentor, "_unpatch_trace_tool_call", Mock())
monkeypatch.setattr(self.instrumentor, "_restore_existing_tracers", Mock())
monkeypatch.setattr(self.instrumentor, "_originals", [], raising=False)

self.instrumentor._uninstrument()

Expand Down Expand Up @@ -461,4 +461,4 @@ def test_utility_functions_exception_handling(self):


if __name__ == "__main__":
pytest.main([__file__])
pytest.main([__file__])
Loading