Skip to content

fix(py): OpenTelemetry span error status and flushable lifecycle helpers - #7133

Closed
huangjeff5 wants to merge 4 commits into
fix/py-otel-tool-call-arguments-jsonfrom
fix/py-otel-bugbash-followups
Closed

huangjeff5 wants to merge 4 commits into
fix/py-otel-tool-call-arguments-jsonfrom
fix/py-otel-bugbash-followups

Conversation

@huangjeff5

Copy link
Copy Markdown
Contributor

Follow-up telemetry fixes stacked on #7098.

Main Changes

  • Mark chat span ERROR on failed turn: When a model call ends in a failure turn, the span status is set to ERROR and records the failure exception.
  • Made GenAiInstrumentation flushable: Exposed lifecycle flush/shutdown helpers to guarantee telemetry drains before process exit.
  • JSON-quoted string tool call arguments: Quotes string tool args in gen_ai.tool.call.arguments ("ORD-555"), matching JS telemetry specs.

_encode_json_value returned str values unchanged, so a tool taking
order_id: str wrote ORD-555 raw into gen_ai.tool.call.arguments and
json.loads failed downstream. Encode strings like every other value,
matching JS JSON.stringify. (BR-01)
The operation.details event path called bare json.dumps on mapped
messages. part_json dumps in python mode, so a datetime in a tool
response raised TypeError after the model had already replied, and
generate returned finish_reason=failed. Route span and event content
through one non-raising encoder; datetime/UUID/Decimal now encode via
pydantic_core.to_jsonable_python (ISO 8601 for datetime). (BR-02)
…tion flushable

set_custom_metadata_attributes, set_span_state, SpanState,
flush_instrumentations, and dispose_instrumentations lived only in
genkit._core, so apps stamping tenant_id or draining spans on serverless
shutdown needed private imports. Export them from genkit.telemetry.

GenAiInstrumentation now implements FlushableInstrumentation: flush()
force-flushes the global OTel tracer, meter, and logger providers,
skipping proxies and logging (not raising) on flush failure. (BR-03)
A model can return ModelResponse(finish_reason=failed, error=...) instead
of raising. _run_model_span ignored response.error and
_resolve_finish_reasons hardcoded failed=False, so the chat span stayed
UNSET with finish_reasons=['stop']. Now the span gets StatusCode.ERROR,
error.type (the Genkit status, or _OTHER), finish_reasons=['error'], and
the duration metric carries error.type. (BR-04)

@gemini-code-assist gemini-code-assist Bot left a comment

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.

Code Review

This pull request introduces support for force-flushing OpenTelemetry providers (tracer, meter, and logger) to prevent telemetry loss in serverless environments, improves error reporting for models returning failures, and enhances JSON serialization safety. Additionally, several telemetry lifecycle and metadata helpers are now exposed publicly. The review feedback suggests improving backwards compatibility with older opentelemetry-api versions by gracefully handling potential import and execution failures of get_logger_provider.


from opentelemetry import metrics as metrics_api, trace as trace_api
from opentelemetry._logs import get_logger as get_otel_logger
from opentelemetry._logs import get_logger as get_otel_logger, get_logger_provider

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.

medium

Importing get_logger_provider directly from opentelemetry._logs might raise an ImportError on older versions of opentelemetry-api where the logs API is not fully present or structured differently. To ensure backwards compatibility and prevent the entire module from failing to import, consider catching ImportError and falling back gracefully.

Suggested change
from opentelemetry._logs import get_logger as get_otel_logger, get_logger_provider
from opentelemetry._logs import get_logger as get_otel_logger
try:
from opentelemetry._logs import get_logger_provider
except ImportError:
get_logger_provider = None

``meter``, or ``otel_logger`` aren't reachable from here; flush
those on the provider you built.
"""
providers = (trace_api.get_tracer_provider(), metrics_api.get_meter_provider(), get_logger_provider())

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.

medium

If get_logger_provider is None (due to older opentelemetry-api versions), calling it directly will raise a TypeError. We should safely build the list of providers by checking if get_logger_provider is available.

Suggested change
providers = (trace_api.get_tracer_provider(), metrics_api.get_meter_provider(), get_logger_provider())
providers = [trace_api.get_tracer_provider(), metrics_api.get_meter_provider()]
if get_logger_provider is not None:
providers.append(get_logger_provider())

@huangjeff5

Copy link
Copy Markdown
Contributor Author

Closing: migrated to standalone repository genkit-ai/genkit-python (PR #55): genkit-ai/genkit-python#55

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

1 participant