-
Notifications
You must be signed in to change notification settings - Fork 25
feat(platform): add W3C trace context headers to LLM Gateway requests #1612
New issue
Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.
By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.
Already on GitHub? Sign in to your account
Merged
Merged
Changes from all commits
Commits
File filter
Filter by extension
Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
There are no files selected for viewing
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
42 changes: 42 additions & 0 deletions
42
packages/uipath-platform/src/uipath/platform/chat/llm_trace_context.py
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -0,0 +1,42 @@ | ||
| """W3C-style trace context headers for LLM Gateway requests.""" | ||
|
|
||
| from opentelemetry import trace | ||
| from uipath.core.feature_flags import FeatureFlags | ||
|
|
||
| from ..common._config import UiPathConfig | ||
|
|
||
|
|
||
| def build_trace_context_headers( | ||
| extra_baggage: list[str] | None = None, | ||
| ) -> dict[str, str]: | ||
| """Build W3C-style trace context headers from the current OpenTelemetry span. | ||
|
|
||
| Args: | ||
| extra_baggage: Additional baggage entries (e.g. ``["source=agents"]``) | ||
| that callers can inject alongside the platform-level entries. | ||
|
|
||
| Returns an empty dict when the ``EnableTraceContextHeaders`` feature flag | ||
| is not enabled, or when no active span is present. | ||
| """ | ||
| if not FeatureFlags.is_flag_enabled("EnableTraceContextHeaders"): | ||
| return {} | ||
|
|
||
| headers: dict[str, str] = {} | ||
| span = trace.get_current_span() | ||
| ctx = span.get_span_context() | ||
| if ctx and ctx.trace_id and ctx.span_id: | ||
| trace_id = format(ctx.trace_id, "032x") | ||
| span_id = format(ctx.span_id, "016x") | ||
| headers["x-uipath-traceparent-id"] = f"00-{trace_id}-{span_id}" | ||
|
|
||
| baggage_parts: list[str] = list(extra_baggage) if extra_baggage else [] | ||
| if folder_key := UiPathConfig.folder_key: | ||
| baggage_parts.append(f"folderKey={folder_key}") | ||
| if agent_id := UiPathConfig.process_uuid: | ||
| baggage_parts.append(f"agentId={agent_id}") | ||
| if process_key := UiPathConfig.process_key: | ||
| baggage_parts.append(f"processKey={process_key}") | ||
| if baggage_parts: | ||
| headers["x-uipath-tracebaggage"] = ",".join(baggage_parts) | ||
|
|
||
| return headers | ||
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
161 changes: 161 additions & 0 deletions
161
packages/uipath-platform/tests/services/test_llm_trace_context.py
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -0,0 +1,161 @@ | ||
| """Tests for build_trace_context_headers.""" | ||
|
|
||
| import os | ||
| from unittest.mock import patch | ||
|
|
||
| from opentelemetry import trace | ||
| from opentelemetry.sdk.trace import TracerProvider | ||
| from opentelemetry.trace import NonRecordingSpan, SpanContext, TraceFlags | ||
| from uipath.core.feature_flags import FeatureFlags | ||
|
|
||
| from uipath.platform.chat.llm_trace_context import build_trace_context_headers | ||
|
|
||
| FEATURE_FLAG = "EnableTraceContextHeaders" | ||
|
|
||
|
|
||
| class TestFeatureFlagDisabled: | ||
| """When the feature flag is off, no headers are returned.""" | ||
|
|
||
| def setup_method(self) -> None: | ||
| FeatureFlags.reset_flags() | ||
|
|
||
| def test_returns_empty_dict_by_default(self) -> None: | ||
| assert build_trace_context_headers() == {} | ||
|
|
||
| def test_returns_empty_dict_when_explicitly_disabled(self) -> None: | ||
| FeatureFlags.configure_flags({FEATURE_FLAG: False}) | ||
| assert build_trace_context_headers() == {} | ||
|
|
||
|
|
||
| class TestTraceparentHeader: | ||
| """When enabled, x-uipath-traceparent-id is populated from the active span.""" | ||
|
|
||
| def setup_method(self) -> None: | ||
| FeatureFlags.reset_flags() | ||
| FeatureFlags.configure_flags({FEATURE_FLAG: True}) | ||
|
|
||
| def test_traceparent_from_active_span(self) -> None: | ||
| provider = TracerProvider() | ||
| tracer = provider.get_tracer("test") | ||
| with tracer.start_as_current_span("test-span") as span: | ||
| ctx = span.get_span_context() | ||
| expected_trace_id = format(ctx.trace_id, "032x") | ||
| expected_span_id = format(ctx.span_id, "016x") | ||
|
|
||
| headers = build_trace_context_headers() | ||
|
|
||
| assert "x-uipath-traceparent-id" in headers | ||
| value = headers["x-uipath-traceparent-id"] | ||
| assert value == f"00-{expected_trace_id}-{expected_span_id}" | ||
| # Verify format: version (2) + dash + trace_id (32) + dash + span_id (16) | ||
| parts = value.split("-") | ||
| assert len(parts) == 3 | ||
| assert parts[0] == "00" | ||
| assert len(parts[1]) == 32 | ||
| assert len(parts[2]) == 16 | ||
|
|
||
| def test_no_traceparent_without_active_span(self) -> None: | ||
| # INVALID_SPAN has trace_id=0 and span_id=0 | ||
| from opentelemetry.context import attach, detach | ||
|
|
||
| ctx = SpanContext( | ||
| trace_id=0, | ||
| span_id=0, | ||
| is_remote=False, | ||
| trace_flags=TraceFlags(0), | ||
| ) | ||
| non_recording = NonRecordingSpan(ctx) | ||
| token = attach(trace.set_span_in_context(non_recording)) | ||
| try: | ||
| headers = build_trace_context_headers() | ||
| finally: | ||
| detach(token) | ||
|
|
||
| assert "x-uipath-traceparent-id" not in headers | ||
|
|
||
|
|
||
| class TestBaggageHeader: | ||
| """When enabled, x-uipath-tracebaggage is populated from UiPathConfig.""" | ||
|
|
||
| def setup_method(self) -> None: | ||
| FeatureFlags.reset_flags() | ||
| FeatureFlags.configure_flags({FEATURE_FLAG: True}) | ||
|
|
||
| def test_all_env_vars_present(self) -> None: | ||
| env = { | ||
| "UIPATH_FOLDER_KEY": "folder-abc", | ||
| "UIPATH_PROCESS_UUID": "agent-123", | ||
| "UIPATH_PROCESS_KEY": "process-789", | ||
| } | ||
| with patch.dict(os.environ, env, clear=True): | ||
| headers = build_trace_context_headers() | ||
|
|
||
| baggage = headers["x-uipath-tracebaggage"] | ||
| assert "folderKey=folder-abc" in baggage | ||
| assert "agentId=agent-123" in baggage | ||
| assert "processKey=process-789" in baggage | ||
|
|
||
| def test_partial_env_vars(self) -> None: | ||
| env = {"UIPATH_FOLDER_KEY": "folder-only"} | ||
| with patch.dict(os.environ, env, clear=True): | ||
| headers = build_trace_context_headers() | ||
|
|
||
| baggage = headers["x-uipath-tracebaggage"] | ||
| assert "folderKey=folder-only" in baggage | ||
|
|
||
| def test_no_baggage_without_env_vars(self) -> None: | ||
| with patch.dict(os.environ, {}, clear=True): | ||
| headers = build_trace_context_headers() | ||
|
|
||
| assert "x-uipath-tracebaggage" not in headers | ||
|
|
||
| def test_baggage_comma_separated(self) -> None: | ||
| env = { | ||
| "UIPATH_FOLDER_KEY": "f1", | ||
| "UIPATH_PROCESS_UUID": "a1", | ||
| } | ||
| with patch.dict(os.environ, env, clear=True): | ||
| headers = build_trace_context_headers() | ||
|
|
||
| baggage = headers["x-uipath-tracebaggage"] | ||
| parts = baggage.split(",") | ||
| assert len(parts) == 2 # folderKey + agentId | ||
|
|
||
| def test_extra_baggage_included(self) -> None: | ||
| env = {"UIPATH_FOLDER_KEY": "f1"} | ||
| with patch.dict(os.environ, env, clear=True): | ||
| headers = build_trace_context_headers(extra_baggage=["source=agents"]) | ||
|
|
||
| baggage = headers["x-uipath-tracebaggage"] | ||
| assert "source=agents" in baggage | ||
| assert "folderKey=f1" in baggage | ||
|
|
||
| def test_extra_baggage_only(self) -> None: | ||
| with patch.dict(os.environ, {}, clear=True): | ||
| headers = build_trace_context_headers( | ||
| extra_baggage=["source=agents", "custom=value"] | ||
| ) | ||
|
|
||
| baggage = headers["x-uipath-tracebaggage"] | ||
| assert baggage == "source=agents,custom=value" | ||
|
|
||
|
|
||
| class TestBothHeaders: | ||
| """When enabled with an active span and env vars, both headers are present.""" | ||
|
|
||
| def setup_method(self) -> None: | ||
| FeatureFlags.reset_flags() | ||
| FeatureFlags.configure_flags({FEATURE_FLAG: True}) | ||
|
|
||
| def test_both_headers_present(self) -> None: | ||
| provider = TracerProvider() | ||
| tracer = provider.get_tracer("test") | ||
| env = {"UIPATH_FOLDER_KEY": "folder-abc"} | ||
| with ( | ||
| tracer.start_as_current_span("test-span"), | ||
| patch.dict(os.environ, env, clear=True), | ||
| ): | ||
| headers = build_trace_context_headers() | ||
|
|
||
| assert "x-uipath-traceparent-id" in headers | ||
| assert "x-uipath-tracebaggage" in headers |
Some generated files are not rendered by default. Learn more about how customized files appear on GitHub.
Oops, something went wrong.
Some generated files are not rendered by default. Learn more about how customized files appear on GitHub.
Oops, something went wrong.
Oops, something went wrong.
Add this suggestion to a batch that can be applied as a single commit.
This suggestion is invalid because no changes were made to the code.
Suggestions cannot be applied while the pull request is closed.
Suggestions cannot be applied while viewing a subset of changes.
Only one suggestion per line can be applied in a batch.
Add this suggestion to a batch that can be applied as a single commit.
Applying suggestions on deleted lines is not supported.
You must change the existing code in this line in order to create a valid suggestion.
Outdated suggestions cannot be applied.
This suggestion has been applied or marked resolved.
Suggestions cannot be applied from pending reviews.
Suggestions cannot be applied on multi-line comments.
Suggestions cannot be applied while the pull request is queued to merge.
Suggestion cannot be applied right now. Please check back later.
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
you should use:
similar to https://github.com/UiPath/uipath-python/pull/1547/changes