-
Notifications
You must be signed in to change notification settings - Fork 7
fix(mastra): record time_to_first_token for streaming model spans #2214
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
Cedric / ViaDézo1er (viadezo1er)
wants to merge
1
commit into
main
Choose a base branch
from
cedric/token-usage-ttft
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 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
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -0,0 +1,12 @@ | ||
| --- | ||
| "braintrust": patch | ||
| --- | ||
|
|
||
| fix(mastra): Record `time_to_first_token` for streaming Mastra model spans | ||
|
|
||
| The Mastra observability exporter now derives `time_to_first_token` (in | ||
| seconds) from a streaming model span's `completionStartTime` attribute and its | ||
| start time, matching the metric Braintrust surfaces for other streaming LLM | ||
| calls. | ||
|
|
||
| Ports the TTFT portion of mastra-ai/mastra#11029. |
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,101 @@ | ||
| import { | ||
| afterEach, | ||
| beforeAll, | ||
| beforeEach, | ||
| describe, | ||
| expect, | ||
| test, | ||
| } from "vitest"; | ||
| import { configureNode } from "../node/config"; | ||
| import { _exportsForTestingOnly, initLogger } from "../logger"; | ||
| import { BraintrustObservabilityExporter } from "./mastra"; | ||
|
|
||
| try { | ||
| configureNode(); | ||
| } catch { | ||
| // Best-effort initialization for test environments. | ||
| } | ||
|
|
||
| type MastraExportedSpan = Parameters< | ||
| BraintrustObservabilityExporter["exportTracingEvent"] | ||
| >[0]["exportedSpan"]; | ||
|
|
||
| describe("BraintrustObservabilityExporter model metrics", () => { | ||
| let backgroundLogger: ReturnType< | ||
| typeof _exportsForTestingOnly.useTestBackgroundLogger | ||
| >; | ||
|
|
||
| beforeAll(async () => { | ||
| await _exportsForTestingOnly.simulateLoginForTests(); | ||
| }); | ||
|
|
||
| beforeEach(() => { | ||
| backgroundLogger = _exportsForTestingOnly.useTestBackgroundLogger(); | ||
| initLogger({ projectId: "test-project-id", projectName: "mastra.test.ts" }); | ||
| }); | ||
|
|
||
| afterEach(() => { | ||
| _exportsForTestingOnly.clearTestBackgroundLogger(); | ||
| }); | ||
|
|
||
| // Run a model span's full lifecycle through the exporter and return the logged | ||
| // row. Both events are required: onEnd is a no-op without a prior onStart. | ||
| async function logModelSpan( | ||
| attributes: Record<string, unknown>, | ||
| ): Promise<any> { | ||
| const span: MastraExportedSpan = { | ||
| id: "span-1", | ||
| traceId: "trace-1", | ||
| name: "llm: 'mock-model'", | ||
| type: "model_generation", | ||
| startTime: 1_000_000_000, | ||
| attributes, | ||
| }; | ||
| const exporter = new BraintrustObservabilityExporter(); | ||
| await exporter.exportTracingEvent({ | ||
| type: "span_started", | ||
| exportedSpan: span, | ||
| }); | ||
| await exporter.exportTracingEvent({ | ||
| type: "span_ended", | ||
| exportedSpan: { ...span, endTime: 1_000_000_005 }, | ||
| }); | ||
| await backgroundLogger.flush(); | ||
| const events = (await backgroundLogger.drain()) as any[]; | ||
| return events.find((event) => event.span_attributes?.name === span.name); | ||
| } | ||
|
|
||
| test("maps token usage and derives time_to_first_token in seconds", async () => { | ||
| // Span starts at t=1_000_000_000ms; first token at +750ms → 0.75s TTFT. | ||
| const row = await logModelSpan({ | ||
| usage: { | ||
| inputTokens: 100, | ||
| outputTokens: 50, | ||
| inputDetails: { cacheRead: 40, cacheWrite: 10 }, | ||
| outputDetails: { reasoning: 20 }, | ||
| }, | ||
| completionStartTime: new Date(1_000_000_750), | ||
| }); | ||
|
|
||
| expect(row?.metrics).toMatchObject({ | ||
| prompt_tokens: 100, | ||
| completion_tokens: 50, | ||
| tokens: 150, | ||
| prompt_cached_tokens: 40, | ||
| prompt_cache_creation_tokens: 10, | ||
| completion_reasoning_tokens: 20, | ||
| }); | ||
| expect(row?.metrics?.time_to_first_token).toBeCloseTo(0.75, 5); | ||
| // completionStartTime feeds the TTFT metric, but the raw value stays in | ||
| // metadata for backward compatibility (earlier releases surfaced it there). | ||
| expect(row?.metadata?.completionStartTime).toBeDefined(); | ||
| }); | ||
|
|
||
| test("omits time_to_first_token for non-streaming spans", async () => { | ||
| const row = await logModelSpan({ | ||
| usage: { inputTokens: 10, outputTokens: 5 }, | ||
| }); | ||
| expect(row?.metrics?.tokens).toBe(15); | ||
| expect(row?.metrics?.time_to_first_token).toBeUndefined(); | ||
| }); | ||
| }); |
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.
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 know this is slightly unrelated but it would be sick if we could log the actual metrics here instead of the keys. We fumbled this earlier but would be a nice lil related cleanup.