-
Notifications
You must be signed in to change notification settings - Fork 0
feat: preserve safe provider termination metadata #114
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
5 commits
Select commit
Hold shift + click to select a range
86439f9
feat(cli): preserve safe provider termination diagnostics
byapparov 9225faa
fix(cli): suppress request ID payloads in termination metadata
byapparov 648d3ef
fix(sdk): generate termination types from runtime schemas
byapparov f1fad01
fix(cli): align termination schemas and availability metadata
byapparov f0cea12
test(cli): guard termination metadata against provider data leaks
byapparov 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,123 @@ | ||
| import type { LanguageModelV2Middleware } from "@ai-sdk/provider" | ||
| import z from "zod" | ||
|
|
||
| export namespace ProviderTermination { | ||
| const VALUE_LIMIT = 128 | ||
| const DIAGNOSTIC_LIMIT = 2048 | ||
| function Field(limit: number) { | ||
| return z.object({ | ||
| status: z.enum(["available", "unavailable", "redacted"]), | ||
| value: z.string().max(limit).optional(), | ||
| truncated: z.boolean(), | ||
| }) | ||
| } | ||
| type Field = z.infer<ReturnType<typeof Field>> | ||
|
|
||
| export const Info = z | ||
| .object({ | ||
| providerID: z.string(), | ||
| modelID: z.string(), | ||
| normalizedReason: z.string(), | ||
| rawReason: Field(VALUE_LIMIT), | ||
| requestID: Field(VALUE_LIMIT), | ||
| diagnostic: Field(DIAGNOSTIC_LIMIT), | ||
| }) | ||
| .meta({ ref: "ProviderTermination" }) | ||
| export type Info = z.infer<typeof Info> | ||
|
|
||
| const reasons = new Set([ | ||
| "FINISH_REASON_UNSPECIFIED", | ||
| "STOP", | ||
| "MAX_TOKENS", | ||
| "SAFETY", | ||
| "RECITATION", | ||
| "LANGUAGE", | ||
| "OTHER", | ||
| "BLOCKLIST", | ||
| "PROHIBITED_CONTENT", | ||
| "SPII", | ||
| "MALFORMED_FUNCTION_CALL", | ||
| "IMAGE_SAFETY", | ||
| "UNEXPECTED_TOOL_CALL", | ||
| "NO_IMAGE", | ||
| "IMAGE_PROHIBITED_CONTENT", | ||
| "IMAGE_OTHER", | ||
| "IMAGE_RECITATION", | ||
| ]) | ||
|
|
||
| function field(value: unknown, allowed: (value: string) => boolean, limit = VALUE_LIMIT): Field { | ||
| if (typeof value !== "string" || !value) return { status: "unavailable", truncated: false } | ||
| if (value.length > limit || !allowed(value)) return { status: "redacted", truncated: value.length > limit } | ||
| return { status: "available", value, truncated: false } | ||
| } | ||
|
|
||
| function record(value: unknown): Record<string, unknown> | undefined { | ||
| if (typeof value !== "object" || value === null || Array.isArray(value)) return | ||
| return value as Record<string, unknown> | ||
| } | ||
|
|
||
| export function middleware(input: { providerID: string; modelID: string; npm: string }): LanguageModelV2Middleware { | ||
| const google = input.npm === "@ai-sdk/google" || input.npm === "@ai-sdk/google-vertex" | ||
| return { | ||
| async transformParams({ type, params }) { | ||
| return type === "stream" && google ? { ...params, includeRawChunks: true } : params | ||
| }, | ||
| async wrapStream({ doStream }) { | ||
| const result = await doStream() | ||
| let rawReason = field(undefined, () => false) | ||
| let diagnostic = field(undefined, () => false) | ||
| const headers = result.response?.headers | ||
|
byapparov marked this conversation as resolved.
|
||
| // A provider/proxy can echo arbitrary credentials into an ID header. | ||
| // Format allowlists cannot distinguish an opaque ID from an opaque key. | ||
| const requestID = field(headers?.["x-request-id"] || headers?.["x-goog-request-id"], () => false) | ||
| return { | ||
| ...result, | ||
| stream: result.stream.pipeThrough( | ||
| new TransformStream({ | ||
| transform(chunk, controller) { | ||
| if (chunk.type === "raw") { | ||
| if (google) { | ||
| const candidates = record(chunk.rawValue)?.candidates | ||
| const candidate = Array.isArray(candidates) ? record(candidates[0]) : undefined | ||
| if (candidate?.finishReason != null) { | ||
| rawReason = field(candidate.finishReason, (value) => reasons.has(value)) | ||
| // Provider messages can contain prompts or tool arguments. Retain only | ||
| // presence/size information; do not collect their free-form contents. | ||
| diagnostic = field(candidate.finishMessage, () => false, DIAGNOSTIC_LIMIT) | ||
| } | ||
| } | ||
| // Raw payloads must never escape this boundary to stream consumers. | ||
| return | ||
| } | ||
| if (chunk.type !== "finish") { | ||
| controller.enqueue(chunk) | ||
| return | ||
| } | ||
| const termination: Info = { | ||
| providerID: input.providerID, | ||
| modelID: input.modelID, | ||
| normalizedReason: chunk.finishReason, | ||
| rawReason, | ||
| requestID, | ||
| diagnostic, | ||
| } | ||
| controller.enqueue({ | ||
| ...chunk, | ||
| providerMetadata: { | ||
| ...chunk.providerMetadata, | ||
| aictrl: { ...chunk.providerMetadata?.aictrl, termination }, | ||
| }, | ||
| }) | ||
| }, | ||
| }), | ||
| ), | ||
| } | ||
| }, | ||
| } | ||
| } | ||
|
|
||
| export function from(metadata: unknown): Info | undefined { | ||
| const result = Info.safeParse(record(record(metadata)?.aictrl)?.termination) | ||
| return result.success ? result.data : undefined | ||
| } | ||
| } | ||
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,37 @@ | ||
| import { expect, test } from "bun:test" | ||
| import path from "path" | ||
|
|
||
| test("generate publishes the termination schema used by SDK codegen", async () => { | ||
| const proc = Bun.spawn( | ||
| ["bun", "run", "--conditions=browser", path.resolve(import.meta.dir, "../../src/index.ts"), "generate"], | ||
| { | ||
| stdout: "pipe", | ||
| stderr: "pipe", | ||
| }, | ||
| ) | ||
| const [stdout, stderr, exit] = await Promise.all([ | ||
| new Response(proc.stdout).text(), | ||
| new Response(proc.stderr).text(), | ||
| proc.exited, | ||
| ]) | ||
| expect(exit, stderr).toBe(0) | ||
| const spec = JSON.parse(stdout) | ||
| const part = spec.components.schemas.StepFinishPart | ||
| const diagnostic = spec.components.schemas.ProviderTermination | ||
| expect(spec.openapi).toBe("3.1.1") | ||
| expect(part.properties.termination).toEqual({ $ref: "#/components/schemas/ProviderTermination" }) | ||
| expect(part.$schema).toBe("https://json-schema.org/draft/2020-12/schema") | ||
| expect(diagnostic.$schema).toBe("https://json-schema.org/draft/2020-12/schema") | ||
| expect(part.id).toBeUndefined() | ||
| expect(diagnostic.id).toBeUndefined() | ||
| expect(part.$id).toBeUndefined() | ||
| expect(diagnostic.$id).toBeUndefined() | ||
| expect(part.properties.type.const).toBe("step-finish") | ||
| expect(stdout).not.toMatch(/"ref"\s*:/) | ||
| expect(stdout).not.toMatch(/"nullable"\s*:/) | ||
| expect(part.required).not.toContain("termination") | ||
| expect(diagnostic.required).toContain("normalizedReason") | ||
| expect(diagnostic.properties.rawReason.properties.value.maxLength).toBe(128) | ||
| expect(diagnostic.properties.diagnostic.properties.value.maxLength).toBe(2048) | ||
| expect(diagnostic.properties.requestID.properties.status.enum).toEqual(["available", "unavailable", "redacted"]) | ||
| }) |
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.