-
Notifications
You must be signed in to change notification settings - Fork 24
fix(chat): Improve agent loop tracing #303
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
dcramer
merged 7 commits into
getsentry:main
from
obostjancic:ognjenbostjancic/tet-2304-improve-juniors-instrumentation
May 21, 2026
Merged
Changes from all commits
Commits
Show all changes
7 commits
Select commit
Hold shift + click to select a range
844e90e
feat(chat): Add per-LLM-call gen_ai.chat spans to pi-agent loop
obostjancic faeadbb
fix(tracing): Emit structured tool result for slackChannelListMessage…
obostjancic c1a85b8
fix(tracing): Address span lifecycle and advisor coverage gaps
obostjancic 1568b42
docs(tracing): Update spec and telemetry map for gen_ai.chat improvem…
obostjancic c7b6278
ref(tracing): Import GEN_AI_PROVIDER_NAME from pi/client instead of l…
obostjancic 4cc8534
test(tracing): Update slackChannelListMessages integration tests for …
obostjancic c9b028e
docs(tracing): Fix stale comment about extractGenAiUsageAttributes ca…
obostjancic 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
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -0,0 +1,128 @@ | ||
| import type { StreamFn } from "@mariozechner/pi-agent-core"; | ||
| import { | ||
| type Api, | ||
| type AssistantMessage, | ||
| type Context, | ||
| type Model, | ||
| streamSimple, | ||
| } from "@mariozechner/pi-ai"; | ||
| import * as Sentry from "@/chat/sentry"; | ||
| import { | ||
| extractGenAiUsageAttributes, | ||
| getLogContextAttributes, | ||
| serializeGenAiAttribute, | ||
| } from "@/chat/logging"; | ||
| import { GEN_AI_PROVIDER_NAME } from "@/chat/pi/client"; | ||
|
|
||
| // Compose only the OTel GenAI attributes that are knowable at span start | ||
| // (request-shape + system instructions). End-of-call attributes such as | ||
| // usage and finish reasons are set after the stream resolves. | ||
| function buildChatStartAttributes( | ||
| model: Model<Api>, | ||
| context: Context, | ||
| ): Record<string, string> { | ||
| const attributes: Record<string, string> = { | ||
| "gen_ai.operation.name": "chat", | ||
| "gen_ai.provider.name": GEN_AI_PROVIDER_NAME, | ||
| "gen_ai.request.model": model.id, | ||
| }; | ||
|
|
||
| const inputMessages = serializeGenAiAttribute(context.messages); | ||
| if (inputMessages) { | ||
| attributes["gen_ai.input.messages"] = inputMessages; | ||
| } | ||
|
|
||
| if (context.systemPrompt) { | ||
| const systemInstructions = serializeGenAiAttribute([ | ||
| { type: "text", content: context.systemPrompt }, | ||
| ]); | ||
| if (systemInstructions) { | ||
| attributes["gen_ai.system_instructions"] = systemInstructions; | ||
| } | ||
| } | ||
|
|
||
| return attributes; | ||
| } | ||
|
|
||
| // Composes post-stream attributes for the chat span. | ||
| // Known gap: `gen_ai.response.finish_reasons` emits pi-ai's raw StopReason | ||
| // values (e.g. "toolUse", "aborted") instead of the OTel canonical set | ||
| // ("tool_use", "max_tokens"). Tracked separately, out of scope here. | ||
| function buildChatEndAttributes( | ||
| message: AssistantMessage, | ||
| ): Record<string, string | string[] | number> { | ||
| const attributes: Record<string, string | string[] | number> = {}; | ||
|
|
||
| const outputMessages = serializeGenAiAttribute([message]); | ||
| if (outputMessages) { | ||
| attributes["gen_ai.output.messages"] = outputMessages; | ||
| } | ||
|
|
||
| Object.assign(attributes, extractGenAiUsageAttributes(message)); | ||
|
|
||
| if (message.stopReason) { | ||
| attributes["gen_ai.response.finish_reasons"] = [message.stopReason]; | ||
| } | ||
|
|
||
| if (message.model) { | ||
| attributes["gen_ai.response.model"] = message.model; | ||
| } | ||
|
|
||
| return attributes; | ||
| } | ||
|
|
||
| /** | ||
| * Wraps pi-ai's `streamSimple` so each LLM call inside a pi-agent-core agent | ||
| * loop produces its own `gen_ai.chat` Sentry span. The returned function is | ||
| * passed to `new Agent({ streamFn: ... })` and runs once per loop iteration. | ||
| * | ||
| * The base argument exists so tests can inject a stub stream function. | ||
| */ | ||
| export function createTracedStreamFn(base: StreamFn = streamSimple): StreamFn { | ||
| return async (model, context, options) => { | ||
| const span = Sentry.startInactiveSpan({ | ||
| name: `chat ${model.id}`, | ||
| op: "gen_ai.chat", | ||
| attributes: { | ||
| ...getLogContextAttributes(), | ||
| ...buildChatStartAttributes(model, context), | ||
| }, | ||
| }); | ||
|
|
||
| try { | ||
| const stream = await Sentry.withActiveSpan(span, () => | ||
| Promise.resolve(base(model, context, options)), | ||
| ); | ||
|
|
||
| stream | ||
| .result() | ||
| .then( | ||
| (finalMessage) => { | ||
| try { | ||
| for (const [key, value] of Object.entries( | ||
| buildChatEndAttributes(finalMessage), | ||
| )) { | ||
| span.setAttribute(key, value); | ||
| } | ||
| } finally { | ||
| span.end(); | ||
| } | ||
| }, | ||
| () => { | ||
| span.setStatus({ code: 2, message: "LLM stream failed" }); | ||
| span.end(); | ||
| }, | ||
| ) | ||
| .catch(() => { | ||
| // setAttribute is best-effort; suppress unexpected attribute-write | ||
| // errors so they don't surface as unhandled promise rejections. | ||
| }); | ||
|
|
||
| return stream; | ||
| } catch (error) { | ||
| span.setStatus({ code: 2, message: "LLM call failed" }); | ||
| span.end(); | ||
| throw error; | ||
| } | ||
|
cursor[bot] marked this conversation as resolved.
|
||
| }; | ||
| } | ||
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
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.
Uh oh!
There was an error while loading. Please reload this page.