Repository navigation
[2033] Link prompt used via sdk with the traces #437
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
Show all changes
3 commits
Select commit
Hold shift + click to select a range
d3b9eab
feat: Implement prompt tracing functionality with context management …
sarathms-kv d8251d2
feat: Enhance prompt context management for threading with OpenTeleme…
sarathms-kv d3dd1e7
feat: Enhance threading support for prompt propagation in use_prompt …
sarathms-kv 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
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
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -0,0 +1,65 @@ | ||
| import logging | ||
| from contextlib import contextmanager | ||
| from typing import Any, Dict, Iterator, Mapping, Optional | ||
|
|
||
| from opentelemetry import context as context_api | ||
|
|
||
| from netra.config import Config | ||
|
|
||
| logger = logging.getLogger(__name__) | ||
|
|
||
| ATTR_PROMPT_ID = f"{Config.LIBRARY_NAME}.prompt.id" | ||
| ATTR_PROMPT_NAME = f"{Config.LIBRARY_NAME}.prompt.name" | ||
| ATTR_PROMPT_VERSION = f"{Config.LIBRARY_NAME}.prompt.version" | ||
| ATTR_PROMPT_LABEL = f"{Config.LIBRARY_NAME}.prompt.label" | ||
|
|
||
| # Prompt identity tagged onto every span started inside `use_prompt`. Stored in the | ||
| # OTel context (not a bare ContextVar) so the threading instrumentation carries it | ||
| # into ThreadPoolExecutor workers. | ||
| _ACTIVE_PROMPT_KEY = "netra.active_prompt" | ||
|
|
||
|
|
||
| def get_active_prompt_attributes() -> Dict[str, Any]: | ||
| """ | ||
| Build span attributes for the prompt set by `use_prompt`. | ||
|
|
||
| Returns: | ||
| Span attributes, or an empty dict when no prompt is active or it carries no identity | ||
| """ | ||
| prompt = context_api.get_value(_ACTIVE_PROMPT_KEY) | ||
| if not isinstance(prompt, Mapping): | ||
| return {} | ||
|
|
||
| prompt_id = prompt.get("promptId") | ||
| version = prompt.get("versionNumber") | ||
| if not prompt_id or version is None: | ||
| logger.debug("Active prompt has no promptId/versionNumber; spans will not be linked: %s", list(prompt)) | ||
| return {} | ||
|
|
||
| attributes: Dict[str, Any] = {ATTR_PROMPT_ID: prompt_id, ATTR_PROMPT_VERSION: version} | ||
| if prompt.get("promptName"): | ||
| attributes[ATTR_PROMPT_NAME] = prompt["promptName"] | ||
| if prompt.get("label"): | ||
| attributes[ATTR_PROMPT_LABEL] = prompt["label"] | ||
| return attributes | ||
|
|
||
|
|
||
| @contextmanager | ||
| def use_prompt(prompt: Optional[Mapping[str, Any]]) -> Iterator[None]: | ||
| """ | ||
| Link every span started inside the block to a prompt version. | ||
|
|
||
| The prompt lives in the OTel context, so it reaches worker threads only when | ||
| the threading instrumentation propagates that context (e.g. `ThreadPoolExecutor`). | ||
|
|
||
| Args: | ||
| prompt: The value returned by `Netra.prompts.get_prompt`. A missing or | ||
| empty value is accepted and links nothing. | ||
| """ | ||
| if not isinstance(prompt, Mapping): | ||
| logger.debug("use_prompt called without a prompt mapping (%s); nothing linked", type(prompt).__name__) | ||
| token = context_api.attach(context_api.set_value(_ACTIVE_PROMPT_KEY, prompt)) | ||
| try: | ||
| yield | ||
| finally: | ||
| context_api.detach(token) | ||
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,102 @@ | ||
| import pytest | ||
| from opentelemetry.sdk.trace import TracerProvider | ||
| from opentelemetry.sdk.trace.export import SimpleSpanProcessor | ||
| from opentelemetry.sdk.trace.export.in_memory_span_exporter import InMemorySpanExporter | ||
|
|
||
| from netra.processors.session_span_processor import SessionSpanProcessor | ||
| from netra.prompts.context import ( | ||
| ATTR_PROMPT_ID, | ||
| ATTR_PROMPT_LABEL, | ||
| ATTR_PROMPT_NAME, | ||
| ATTR_PROMPT_VERSION, | ||
| get_active_prompt_attributes, | ||
| use_prompt, | ||
| ) | ||
|
|
||
| PROMPT = { | ||
| "messages": [{"role": "user", "content": "hi"}], | ||
| "promptId": "p1", | ||
| "promptName": "welcome", | ||
| "versionNumber": 3, | ||
| "label": "production", | ||
| } | ||
|
|
||
|
|
||
| class TestUsePrompt: | ||
| def test_no_active_prompt_yields_no_attributes(self) -> None: | ||
| assert get_active_prompt_attributes() == {} | ||
|
|
||
| def test_active_prompt_yields_identity_attributes(self) -> None: | ||
| with use_prompt(PROMPT): | ||
| assert get_active_prompt_attributes() == { | ||
| ATTR_PROMPT_ID: "p1", | ||
| ATTR_PROMPT_NAME: "welcome", | ||
| ATTR_PROMPT_VERSION: 3, | ||
| ATTR_PROMPT_LABEL: "production", | ||
| } | ||
| assert get_active_prompt_attributes() == {} | ||
|
|
||
| @pytest.mark.parametrize("prompt", [None, {}, {"promptId": "p1"}, {"versionNumber": 1}, "not-a-mapping"]) | ||
| def test_untrackable_prompt_links_nothing(self, prompt: object) -> None: | ||
| with use_prompt(prompt): # type: ignore[arg-type] | ||
| assert get_active_prompt_attributes() == {} | ||
|
|
||
| def test_version_zero_is_kept(self) -> None: | ||
| with use_prompt({"promptId": "p1", "versionNumber": 0}): | ||
| assert get_active_prompt_attributes()[ATTR_PROMPT_VERSION] == 0 | ||
|
|
||
| def test_nested_blocks_restore_outer_prompt(self) -> None: | ||
| inner = {**PROMPT, "promptId": "p2"} | ||
| with use_prompt(PROMPT): | ||
| with use_prompt(inner): | ||
| assert get_active_prompt_attributes()[ATTR_PROMPT_ID] == "p2" | ||
| assert get_active_prompt_attributes()[ATTR_PROMPT_ID] == "p1" | ||
|
|
||
| def test_prompt_reset_when_block_raises(self) -> None: | ||
| with pytest.raises(RuntimeError): | ||
| with use_prompt(PROMPT): | ||
| raise RuntimeError("boom") | ||
| assert get_active_prompt_attributes() == {} | ||
|
|
||
|
|
||
| class TestSpanTagging: | ||
| def test_spans_inside_block_are_tagged_and_outside_are_not(self) -> None: | ||
| exporter = InMemorySpanExporter() | ||
| provider = TracerProvider() | ||
| provider.add_span_processor(SessionSpanProcessor()) | ||
| provider.add_span_processor(SimpleSpanProcessor(exporter)) | ||
| tracer = provider.get_tracer("test") | ||
|
|
||
| with use_prompt(PROMPT): | ||
| with tracer.start_as_current_span("inside"): | ||
| pass | ||
| with tracer.start_as_current_span("outside"): | ||
| pass | ||
|
|
||
| spans = {s.name: s.attributes for s in exporter.get_finished_spans()} | ||
| assert spans["inside"][ATTR_PROMPT_ID] == "p1" | ||
| assert spans["inside"][ATTR_PROMPT_VERSION] == 3 | ||
| assert ATTR_PROMPT_ID not in spans["outside"] | ||
|
|
||
|
|
||
| def test_prompt_propagates_into_threadpool_with_threading_instrumentation() -> None: | ||
| from concurrent.futures import ThreadPoolExecutor | ||
|
|
||
| from opentelemetry.instrumentation.threading import ThreadingInstrumentor | ||
|
|
||
| ThreadingInstrumentor().instrument() | ||
| try: | ||
| with use_prompt(PROMPT), ThreadPoolExecutor(1) as pool: | ||
| attrs = pool.submit(get_active_prompt_attributes).result() | ||
| assert attrs[ATTR_PROMPT_ID] == "p1" | ||
|
|
||
| import threading | ||
|
|
||
| out: dict = {} | ||
| with use_prompt(PROMPT): | ||
| t = threading.Thread(target=lambda: out.update(get_active_prompt_attributes())) | ||
| t.start() | ||
| t.join() | ||
| assert out[ATTR_PROMPT_ID] == "p1" | ||
| finally: | ||
| ThreadingInstrumentor().uninstrument() |
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.