-
Notifications
You must be signed in to change notification settings - Fork 112
Feat/tracing #165
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
SailingSF
wants to merge
2
commits into
main
Choose a base branch
from
feat/tracing
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.
+164
−2
Open
Feat/tracing #165
Changes from all commits
Commits
Show all changes
2 commits
Select commit
Hold shift + click to select a range
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
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -0,0 +1,51 @@ | ||
| """Per-turn trace identity for outbound LLM telemetry. | ||
|
|
||
| `ChatSession.turn_stream` sets the active `TraceContext` for the | ||
| duration of a turn. The OpenAI provider reads it when talking to | ||
| MindsHub and attaches langfuse-style headers so every LLM call (and | ||
| any nested tool/scratchpad LLM call made within the same asyncio | ||
| task) is attributed to the same session + turn server-side. | ||
|
|
||
| A `ContextVar` is used so that nested calls — `_stream_and_handle_tools`, | ||
| `generate_object` (structured output), the cerebellum's diff call, | ||
| and the scratchpad's `coding_provider` calls — all inherit the same | ||
| trace automatically without threading kwargs through every layer. | ||
|
|
||
| Scope: only consumed by the OpenAI provider when its base URL points | ||
| at MindsHub. Other providers (direct Anthropic, raw OpenAI, Azure, | ||
| Gemini) ignore the context entirely. | ||
| """ | ||
|
|
||
| from __future__ import annotations | ||
|
|
||
| from contextvars import ContextVar, Token | ||
| from dataclasses import dataclass | ||
|
|
||
|
|
||
| @dataclass(frozen=True) | ||
| class TraceContext: | ||
| """Identifiers attached to outbound LLM calls during a turn.""" | ||
|
|
||
| session_id: str | None = None | ||
| turn_id: int | None = None | ||
| harness: str | None = None | ||
|
|
||
|
|
||
| _trace_ctx: ContextVar[TraceContext | None] = ContextVar( | ||
| "anton_trace_ctx", default=None | ||
| ) | ||
|
|
||
|
|
||
| def get_trace_context() -> TraceContext | None: | ||
| """Return the active trace context, or None if no turn is in flight.""" | ||
| return _trace_ctx.get() | ||
|
|
||
|
|
||
| def set_trace_context(ctx: TraceContext | None) -> Token: | ||
| """Install a trace context for the current task; pair with `reset_trace_context`.""" | ||
| return _trace_ctx.set(ctx) | ||
|
|
||
|
|
||
| def reset_trace_context(token: Token) -> None: | ||
| """Restore the previous trace context. Pass the token returned by `set_trace_context`.""" | ||
| _trace_ctx.reset(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 |
|---|---|---|
|
|
@@ -24,6 +24,11 @@ | |
| StreamToolResult, | ||
| TokenLimitExceeded, | ||
| ) | ||
| from anton.core.llm.tracing import ( | ||
| TraceContext, | ||
| reset_trace_context, | ||
| set_trace_context, | ||
| ) | ||
| from anton.core.backends.manager import ScratchpadManager | ||
| from anton.core.tools.registry import ToolRegistry | ||
| from anton.core.tools.tool_defs import ( | ||
|
|
@@ -81,6 +86,11 @@ class ChatSessionConfig: | |
| initial_history: list[dict] | None = None | ||
| history_store: HistoryStore | None = None | ||
| session_id: str | None = None | ||
| # Identifier for the host harness driving this session (e.g. "cowork", | ||
| # "cli"). Surfaced on telemetry / langfuse traces so the harness that | ||
| # produced a given trace is filterable in the dashboard. None means the | ||
| # host didn't identify itself. | ||
| harness: str | None = None | ||
| proactive_dashboards: bool = False | ||
| tools: list[ToolDef] = field(default_factory=list) | ||
|
|
||
|
|
@@ -117,6 +127,11 @@ def __init__(self, config: ChatSessionConfig) -> None: | |
| ) | ||
| self._history_store = config.history_store | ||
| self._session_id = config.session_id | ||
| self._harness = config.harness | ||
| # Set per-turn by `turn_stream` so any LLM call made during that | ||
| # turn can read the current turn identifier (used by telemetry / | ||
| # langfuse propagation in the provider layer). | ||
| self._current_turn_id: int | None = None | ||
| self._cancel_event = asyncio.Event() | ||
| self._escape_watcher: EscapeWatcher | None = None | ||
| self._active_datasource: str | None = None | ||
|
|
@@ -1077,9 +1092,20 @@ async def turn(self, user_input: str | list[dict]) -> str: | |
| return reply | ||
|
|
||
| async def turn_stream( | ||
| self, user_input: str | list[dict] | ||
| self, | ||
| user_input: str | list[dict], | ||
| *, | ||
| turn_id: int | None = None, | ||
| ) -> AsyncIterator[StreamEvent]: | ||
| """Streaming version of turn(). Yields events as they arrive.""" | ||
| """Streaming version of turn(). Yields events as they arrive. | ||
|
|
||
| `turn_id` lets the host (cowork, CLI, …) tag the turn with its | ||
| own identifier so downstream telemetry can correlate the LLM | ||
| calls + tool spans made during this turn. Stored on | ||
| `self._current_turn_id` so the provider layer can read it | ||
| without threading the arg through every internal call. | ||
| """ | ||
| self._current_turn_id = turn_id | ||
|
Member
There was a problem hiding this comment. Choose a reason for hiding this commentThe reason will be displayed to describe this comment to others. Learn more. is this used somwhere? if not we can remove it |
||
| self._append_history({"role": "user", "content": user_input}) | ||
|
|
||
| # Log user input to episodic memory | ||
|
|
@@ -1099,6 +1125,21 @@ async def turn_stream( | |
| user_message=user_msg_str, | ||
| ) | ||
|
|
||
| # Per-turn trace identity. The OpenAI provider reads this when | ||
| # talking to MindsHub and attaches langfuse-style headers so the | ||
| # router can attribute every LLM call (and any spans nested | ||
| # inside this turn via tools / scratchpad) to the right session. | ||
| # ContextVar propagation also covers `asyncio.create_task` spawns | ||
| # — the cerebellum flush + identity extraction tasks scheduled | ||
| # below inherit a copy of this context. | ||
| _trace_token = set_trace_context( | ||
| TraceContext( | ||
| session_id=self._session_id, | ||
| turn_id=turn_id if turn_id is not None else self._turn_count + 1, | ||
| harness=self._harness, | ||
| ) | ||
| ) | ||
|
|
||
| try: | ||
| while True: | ||
| try: | ||
|
|
@@ -1174,6 +1215,7 @@ async def turn_stream( | |
| self._active_explainability.finalize( | ||
| "".join(assistant_text_parts)[:2000] | ||
| ) | ||
| reset_trace_context(_trace_token) | ||
|
|
||
| # Log assistant response to episodic memory | ||
| if self._episodic is not None and assistant_text_parts: | ||
|
|
||
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.
Do we need this set twice, its already in Langfuse-tags?