-
Notifications
You must be signed in to change notification settings - Fork 6
Add span normalizer for tool input.value and output.value #77
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
Open
andrei-rusu
wants to merge
4
commits into
main
Choose a base branch
from
dev/andreiru/custom_span_processor
base: main
Could not load branches
Branch not found: {{ refName }}
Loading
Could not load tags
Nothing to show
Loading
Are you sure you want to change the base?
Some commits from the old base branch may be removed from the timeline,
and old review comments may become outdated.
Open
Changes from 1 commit
Commits
Show all changes
4 commits
Select commit
Hold shift + click to select a range
95ec5c9
add span normalizer for tool input.value and output.value
andrei-rusu aba83d1
change order to be extra cautious
andrei-rusu 789d213
make status "success" or "error"
andrei-rusu b442124
fix the output normalization only for tool spans
andrei-rusu 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
84 changes: 84 additions & 0 deletions
84
src/uipath_llamaindex/_cli/_tracing/_attribute_normalizer.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,84 @@ | ||
| """OpenTelemetry SpanProcessor for normalizing LlamaIndex tool call attributes. | ||
|
|
||
| LlamaIndex wraps tool arguments in {"kwargs": {...}} which differs from other | ||
| frameworks like LangChain that use flat {"arg": value} format. This processor | ||
| normalizes the format at the span level before exporters or dev terminal read it. | ||
| """ | ||
|
|
||
| import json | ||
| import logging | ||
| from typing import Any, Optional | ||
|
|
||
| from opentelemetry.context import Context | ||
| from opentelemetry.sdk.trace import ReadableSpan, Span, SpanProcessor | ||
|
|
||
| logger = logging.getLogger(__name__) | ||
|
|
||
|
|
||
| class AttributeNormalizingSpanProcessor(SpanProcessor): | ||
| """Normalizes LlamaIndex tool call attributes to match other frameworks. | ||
|
|
||
| Unwraps {"kwargs": {...}} to flat {...} format for consistency with LangChain. | ||
| """ | ||
|
|
||
| def on_start(self, span: Span, parent_context: Optional[Context] = None) -> None: | ||
| """Called when span starts - no action needed.""" | ||
| pass | ||
|
|
||
| def on_end(self, span: ReadableSpan) -> None: | ||
| """Normalize tool call attributes before span is consumed by exporters/terminal.""" | ||
| if not span._attributes: | ||
| return | ||
|
|
||
| try: | ||
| # Get the mutable internal attributes dict | ||
| attrs: dict = span._attributes # type: ignore[attr-defined] | ||
|
|
||
| # Normalize tool call attributes | ||
| for key in ("input.value", "output.value"): | ||
| if key in attrs: | ||
| original = attrs[key] | ||
| normalized = self._normalize_attribute(key, original) | ||
|
|
||
| if normalized != original: | ||
| attrs[key] = normalized | ||
| if logger.isEnabledFor(logging.DEBUG): | ||
| logger.debug( | ||
| f"Normalized {key} in span '{span.name}': " | ||
| f"{original[:50]}... → {normalized[:50]}..." | ||
| ) | ||
|
|
||
| except Exception as e: | ||
| # Don't crash span processing if normalization fails | ||
| logger.debug( | ||
| f"Failed to normalize span '{getattr(span, 'name', 'unknown')}': {e}" | ||
| ) | ||
|
|
||
| def _normalize_attribute(self, key: str, value: Any) -> str: | ||
| """Unwrap LlamaIndex's kwargs wrapper if present.""" | ||
| if isinstance(value, str): | ||
| try: | ||
| value = json.loads(value) | ||
| except Exception: | ||
| pass | ||
| if isinstance(value, dict): | ||
| if key == "input.value": | ||
| if "kwargs" in value: | ||
| value = json.dumps(value["kwargs"]) | ||
| elif key == "output.value": | ||
| value = json.dumps( | ||
| { | ||
| "content": value.get("raw_output"), | ||
| "status": not value.get("is_error", False), | ||
| "tool_call_id": value.get("tool_call_id"), | ||
| } | ||
| ) | ||
| return str(value) | ||
|
|
||
| def shutdown(self) -> None: | ||
| """Called on processor shutdown - no cleanup needed.""" | ||
| pass | ||
|
|
||
| def force_flush(self, timeout_millis: int = 30000) -> bool: | ||
| """Force flush - always succeeds (nothing to flush).""" | ||
| return True |
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
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.
Uh oh!
There was an error while loading. Please reload this page.
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.
I think would be a better design to pass the trace provider to the runtime factory. this would imply changes in the core library also