Skip to content

Commit 2ed060d

Browse files
authored
fix(ai): send thinking back exactly as the endpoint streamed it (#68182)
1 parent 1c80a8e commit 2ed060d

16 files changed

Lines changed: 284 additions & 17 deletions

‎packages/ai/README.md‎

Lines changed: 11 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -18,7 +18,10 @@ console.log(await ai.text(input)) // just the answer's text
1818
const response = await ai.generate(input) // { message, usage?, finish }
1919
console.log(Message.text(response.message), response.usage?.totalTokens, response.finish.reason)
2020
// also Message.reasoning(response.message), Message.toolCalls(response.message)
21-
const generated = await ai.image.generate({ model: provider.model("gpt-image-2", { api: "openai-images" }), prompt: "A lighthouse" })
21+
const generated = await ai.image.generate({
22+
model: provider.model("gpt-image-2", { api: "openai-images" }),
23+
prompt: "A lighthouse",
24+
})
2225
await ai.write(generated.images[0], "./lighthouse.png") // also ai.file(path), ai.bytes(asset), ai.base64(asset), ai.materialize(asset)
2326
for await (const event of ai.stream(ai.request(input))) {
2427
// StreamEvent
@@ -222,6 +225,7 @@ try {
222225
| `quota-exceeded` | Out of credits or plan limits; waiting rarely helps | `status`, `code`, `retryAfterMs` |
223226
| `context-overflow` | The request is longer than the model's context window | `status`, `code` |
224227
| `payload-too-large` | The request body is over the provider's size limit | `status`, `code` |
228+
| `invalid-reasoning` | The provider rejected reasoning state sent back to it, such as a thinking signature | `status`, `code` |
225229
| `invalid-request` | The provider rejected the request as sent, such as an unknown model or a bad parameter | `status`, `code`, `parameter` |
226230
| `auth` | Missing, invalid or unauthorized credentials | `status`, `code` |
227231
| `content-filter` | Blocked by the provider's content policy | `status`, `code` |
@@ -235,6 +239,8 @@ try {
235239
transport's message, and `error.reason` keeps the full detail the kind is read from, such as the raw response body and
236240
headers.
237241

242+
Today `invalid-reasoning` covers one message, Anthropic's ``Invalid `signature` in `thinking` block``.
243+
238244
### Raw provider events
239245

240246
Set `includeRaw: true` on a request to also receive every provider frame as `{ type: "raw", data }`, in order and
@@ -1441,7 +1447,10 @@ const program = Effect.gen(function* () {
14411447
response.language // the provider's own value, lowercased ("en", "eng", "english", "en_us")
14421448

14431449
// Text deltas as the model transcribes, then one finish carrying the whole transcript.
1444-
yield* Transcription.stream({ model: provider.model("gpt-4o-mini-transcribe", { api: "openai-transcription" }), audio }).pipe(
1450+
yield* Transcription.stream({
1451+
model: provider.model("gpt-4o-mini-transcribe", { api: "openai-transcription" }),
1452+
audio,
1453+
}).pipe(
14451454
Stream.tap((event) => (event.type === "text-delta" ? Console.log(event.delta) : Effect.void)),
14461455
Stream.runDrain,
14471456
)

‎packages/ai/src/protocols/anthropic-messages.ts‎

Lines changed: 21 additions & 9 deletions
Original file line numberDiff line numberDiff line change
@@ -523,7 +523,8 @@ interface ParserState {
523523
readonly compactions: Readonly<Record<number, string | null>>
524524
readonly providerMetadataKey: string
525525
readonly tools: ToolStream.State<number>
526-
readonly reasoningSignatures: Readonly<Record<number, string>>
526+
// `streamed` once a `signature_delta` arrived: the first replaces the `content_block_start` signature, later ones append.
527+
readonly reasoningSignatures: Readonly<Record<number, { readonly signature: string; readonly streamed: boolean }>>
527528
readonly usage?: Usage
528529
readonly pendingFinish?: FinishDetails & { readonly providerMetadata?: ProviderMetadata }
529530
readonly lifecycle: Lifecycle.State
@@ -730,8 +731,11 @@ const lowerToolResultContent = Effect.fnUntraced(function* (part: ToolResultPart
730731
return yield* Effect.forEach(content, (item) => lowerToolResultContentItem(item, request))
731732
})
732733

733-
const requireThinkingSignature = (request: LLMRequest) => {
734+
const requireThinkingSignature = (request: LLMRequest, signature: string | undefined) => {
734735
if (request.model.compatibility?.requireSignature !== undefined) return request.model.compatibility.requireSignature
736+
// This route streamed the block with an empty signature, so it takes one back. Anthropic only leaves the
737+
// signature empty on a block cut off mid-stream, which callers must not replay.
738+
if (signature === "") return false
735739
const provider = request.model.provider.toLowerCase()
736740
const model = request.model.id.toLowerCase()
737741
const baseURL = (ProviderShared.baseURL(request.model) ?? "").toLowerCase()
@@ -911,7 +915,7 @@ const lowerMessages = Effect.fnUntraced(function* (request: LLMRequest, breakpoi
911915
continue
912916
}
913917
if (!signature || signature.trim().length === 0) {
914-
if (part.text.trim().length > 0 && !requireThinkingSignature(request)) {
918+
if (part.text.trim().length > 0 && !requireThinkingSignature(request, signature)) {
915919
content.push({ type: "thinking", thinking: part.text, signature: "" })
916920
}
917921
continue
@@ -1258,7 +1262,7 @@ const onContentBlockStart = (
12581262
reasoningSignatures:
12591263
event.index === undefined || block.signature === undefined
12601264
? state.reasoningSignatures
1261-
: { ...state.reasoningSignatures, [event.index]: block.signature },
1265+
: { ...state.reasoningSignatures, [event.index]: { signature: block.signature, streamed: false } },
12621266
},
12631267
events,
12641268
]
@@ -1325,13 +1329,21 @@ const onContentBlockDelta = Effect.fnUntraced(function* (
13251329
] satisfies StepResult
13261330
}
13271331

1328-
if (delta.type === "signature_delta" && delta.signature) {
1332+
if (delta.type === "signature_delta" && delta.signature !== undefined) {
13291333
const index = event.index ?? 0
13301334
if (!state.lifecycle.reasoning.has(`reasoning-${index}`)) return [state, NO_EVENTS] satisfies StepResult
13311335
return [
13321336
{
13331337
...state,
1334-
reasoningSignatures: { ...state.reasoningSignatures, [index]: delta.signature },
1338+
reasoningSignatures: {
1339+
...state.reasoningSignatures,
1340+
[index]: {
1341+
signature: state.reasoningSignatures[index]?.streamed
1342+
? state.reasoningSignatures[index].signature + delta.signature
1343+
: delta.signature,
1344+
streamed: true,
1345+
},
1346+
},
13351347
},
13361348
NO_EVENTS,
13371349
] satisfies StepResult
@@ -1374,7 +1386,7 @@ const onContentBlockStop = Effect.fnUntraced(function* (state: ParserState, even
13741386
const result = yield* ToolStream.finish(ADAPTER, state.tools, event.index)
13751387
const events: StreamEvent[] = []
13761388
const resultEvents = result.events ?? []
1377-
const signature = state.reasoningSignatures[event.index]
1389+
const signature = state.reasoningSignatures[event.index]?.signature
13781390
const lifecycle = resultEvents.length
13791391
? Lifecycle.start(state.lifecycle)
13801392
: Lifecycle.reasoningEnd(
@@ -1435,12 +1447,12 @@ const onMessageStop = Effect.fnUntraced(function* (state: ParserState) {
14351447
const lifecycle = result.events.length ? Lifecycle.start(state.lifecycle) : state.lifecycle
14361448
events.push(...result.events)
14371449
const closed = Object.entries(state.reasoningSignatures).reduce(
1438-
(current, [index, signature]) =>
1450+
(current, [index, reasoning]) =>
14391451
Lifecycle.reasoningEnd(
14401452
current,
14411453
events,
14421454
`reasoning-${index}`,
1443-
providerMetadata(state.providerMetadataKey, { signature }),
1455+
providerMetadata(state.providerMetadataKey, { signature: reasoning.signature }),
14441456
),
14451457
lifecycle,
14461458
)

‎packages/ai/src/provider-error.ts‎

Lines changed: 4 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -150,6 +150,8 @@ const QUOTA_TEXT =
150150
// under `invalid_request_error`. The Vercel AI Gateway drops OpenAI's `moderation_blocked` code.
151151
const CONTENT_POLICY_TEXT =
152152
/violating our usage policy|blocked by content filtering policy|content[-_\s]?policy|rejected (?:as a result of our|by the) safety system|detected potentially unsafe or sensitive content|rejected in accordance with our terms of use/i
153+
// Anthropic: "messages.1.content.0: Invalid `signature` in `thinking` block".
154+
const THINKING_SIGNATURE_TEXT = /invalid \W?signature\W? in \W?thinking\W? block/i
153155
const SERVER_ERROR_TEXT =
154156
/\b(?:try again|(?:please |you can )?retry (?:the |this |your )?request|try (?:the |this |your )?request again|(?:currently |temporarily )?at capacity|overloaded|temporarily unavailable|service[-_\s]?unavailable|(?:server|internal)[-_\s]?error|server (?:is )?busy|provider returned (?:an )?error|resource[-_\s]?exhausted|upstream (?:connect|connection|request)|request buffer limit while retrying upstream)\b/i
155157

@@ -235,6 +237,8 @@ export function classifyProviderFailure(input: ProviderFailure): AIError["reason
235237
return new InvalidRequestError({ ...details, classification: "context-overflow" })
236238
if (input.status === 413 || isPayloadTooLarge(text))
237239
return new InvalidRequestError({ ...details, classification: "payload-too-large" })
240+
if (clientScoped && input.status !== 429 && THINKING_SIGNATURE_TEXT.test(input.message))
241+
return new InvalidRequestError({ ...details, classification: "invalid-reasoning" })
238242
if (codes.some((code) => CONTENT_POLICY_CODES.has(code)) || (clientScoped && CONTENT_POLICY_TEXT.test(input.message)))
239243
return new ContentPolicyError(details)
240244
if (

‎packages/ai/src/schema/errors.ts‎

Lines changed: 8 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -5,7 +5,11 @@ import { ProviderID, RouteID } from "./ids.js"
55
import type { TextResponse } from "./events.js"
66
import { awsErrorType, providerCodes } from "../utils/provider-codes.js"
77

8-
export const ProviderFailureClassification = Schema.Literals(["context-overflow", "payload-too-large"])
8+
export const ProviderFailureClassification = Schema.Literals([
9+
"context-overflow",
10+
"payload-too-large",
11+
"invalid-reasoning",
12+
])
913
export type ProviderFailureClassification = typeof ProviderFailureClassification.Type
1014

1115
export class HttpContext extends Schema.Class<HttpContext>("AI.HttpContext")({
@@ -172,6 +176,7 @@ interface RetryAfter {
172176
* - `rate-limit`: throttled; send again later. `quota-exceeded`: out of credits or plan limits; waiting rarely helps.
173177
* - `context-overflow`: the request is longer than the model's context window. `payload-too-large`: the request
174178
* body is over the provider's size limit.
179+
* - `invalid-reasoning`: the provider rejected reasoning state sent back to it, such as a thinking signature.
175180
* - `invalid-request`: the provider rejected the request as sent, such as an unknown model or a bad parameter.
176181
* - `auth`: missing, invalid or unauthorized credentials. `content-filter`: blocked by the provider's content policy.
177182
* - `provider`: the provider failed: a server error, an overload, malformed output or an unrecognized error.
@@ -183,6 +188,7 @@ export type AIErrorDetails =
183188
| ({ readonly kind: "quota-exceeded" } & ProviderReport & RetryAfter)
184189
| ({ readonly kind: "context-overflow" } & ProviderReport)
185190
| ({ readonly kind: "payload-too-large" } & ProviderReport)
191+
| ({ readonly kind: "invalid-reasoning" } & ProviderReport)
186192
| ({ readonly kind: "invalid-request"; readonly parameter?: string } & ProviderReport)
187193
| ({ readonly kind: "auth" } & ProviderReport)
188194
| ({ readonly kind: "content-filter" } & ProviderReport)
@@ -262,6 +268,7 @@ export class AIError extends Schema.TaggedError<AIError>()("AI.Error", {
262268
case "InvalidRequest":
263269
if (reason.classification === "context-overflow") return { kind: "context-overflow", ...report }
264270
if (reason.classification === "payload-too-large") return { kind: "payload-too-large", ...report }
271+
if (reason.classification === "invalid-reasoning") return { kind: "invalid-reasoning", ...report }
265272
return { kind: "invalid-request", ...report, parameter: reason.parameter }
266273
case "Authentication":
267274
return { kind: "auth", ...report }

‎packages/ai/test/error-details.types.ts‎

Lines changed: 2 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -14,6 +14,7 @@ export type Checks = [
1414
| "quota-exceeded"
1515
| "context-overflow"
1616
| "payload-too-large"
17+
| "invalid-reasoning"
1718
| "invalid-request"
1819
| "auth"
1920
| "content-filter"
@@ -38,6 +39,7 @@ export const narrowing = (details: AIErrorDetails) => {
3839
return [details.status, details.code, details.retryAfterMs]
3940
case "context-overflow":
4041
case "payload-too-large":
42+
case "invalid-reasoning":
4143
case "auth":
4244
case "content-filter":
4345
// @ts-expect-error a rejection that is not a throttle carries no `retryAfterMs`

‎packages/ai/test/provider-error.test.ts‎

Lines changed: 4 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -831,6 +831,7 @@ describe("AIError details", () => {
831831
const everyReason = [
832832
new InvalidRequestError({ message, classification: "context-overflow" }),
833833
new InvalidRequestError({ message, classification: "payload-too-large" }),
834+
new InvalidRequestError({ message, classification: "invalid-reasoning" }),
834835
new InvalidRequestError({ message }),
835836
new UnsupportedOperationError({ message, operation: "compact" }),
836837
new AuthenticationError({ message }),
@@ -849,6 +850,7 @@ describe("AIError details", () => {
849850
expect(everyReason.map((error) => error.details.kind)).toEqual([
850851
"context-overflow",
851852
"payload-too-large",
853+
"invalid-reasoning",
852854
"invalid-request",
853855
"unsupported",
854856
"auth",
@@ -864,12 +866,13 @@ describe("AIError details", () => {
864866
])
865867
})
866868

867-
test("context-overflow and payload-too-large are exactly the classified invalid requests", () => {
869+
test("context-overflow, payload-too-large and invalid-reasoning are exactly the classified invalid requests", () => {
868870
const classified = (error: AIError, classification: string) =>
869871
error.reason._tag === "InvalidRequest" && error.reason.classification === classification
870872
for (const error of everyReason) {
871873
expect(error.details.kind === "context-overflow").toBe(classified(error, "context-overflow"))
872874
expect(error.details.kind === "payload-too-large").toBe(classified(error, "payload-too-large"))
875+
expect(error.details.kind === "invalid-reasoning").toBe(classified(error, "invalid-reasoning"))
873876
}
874877
})
875878

‎packages/ai/test/provider/anthropic-messages.test.ts‎

Lines changed: 63 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -1130,6 +1130,69 @@ describe("Anthropic Messages route", () => {
11301130
}),
11311131
)
11321132

1133+
it.effect("sends thinking back with the empty signature the endpoint streamed", () =>
1134+
Effect.gen(function* () {
1135+
const glm = LanguageModel.make({
1136+
id: "glm-4.6",
1137+
provider: "custom-gateway",
1138+
api: AnthropicMessages.api.with({
1139+
baseURL: "https://gateway.test/v1/",
1140+
auth: Auth.header("x-api-key", "test"),
1141+
metadataKey: "custom-gateway",
1142+
}),
1143+
})
1144+
const streamed = (start: Record<string, string>, signatureDeltas: string[]) =>
1145+
sseEvents(
1146+
{ type: "message_start", message: { usage: { input_tokens: 5 } } },
1147+
{ type: "content_block_start", index: 0, content_block: { type: "thinking", thinking: "", ...start } },
1148+
{ type: "content_block_delta", index: 0, delta: { type: "thinking_delta", thinking: "Reasoning." } },
1149+
...signatureDeltas.map((signature) => ({
1150+
type: "content_block_delta",
1151+
index: 0,
1152+
delta: { type: "signature_delta", signature },
1153+
})),
1154+
{ type: "content_block_stop", index: 0 },
1155+
{ type: "message_delta", delta: { stop_reason: "end_turn" }, usage: { output_tokens: 2 } },
1156+
{ type: "message_stop" },
1157+
)
1158+
const replay = (body: string, signature: string) =>
1159+
Effect.gen(function* () {
1160+
const response = yield* generateResponse(ai.request({ model: glm, prompt: "Think." })).pipe(
1161+
Effect.provide(fixedResponse(body)),
1162+
)
1163+
expect(response.message.content).toEqual([
1164+
{ type: "reasoning", text: "Reasoning.", providerMetadata: { "custom-gateway": { signature } } },
1165+
])
1166+
return yield* compileRequest(ai.request({ model: glm, messages: [response.message], cache: "none" }))
1167+
})
1168+
1169+
for (const [body, signature] of [
1170+
[streamed({ signature: "" }, []), ""],
1171+
[streamed({}, [""]), ""],
1172+
// A trailing empty delta must not wipe the real signature before it.
1173+
[streamed({ signature: "" }, ["sig_1", ""]), "sig_1"],
1174+
] as const) {
1175+
expect((yield* replay(body, signature)).body.messages).toEqual([
1176+
{ role: "assistant", content: [{ type: "thinking", thinking: "Reasoning.", signature }] },
1177+
])
1178+
}
1179+
expect((yield* compileUnsignedReasoning(glm)).body.messages).toEqual([])
1180+
1181+
const required = yield* compileRequest(
1182+
ai.request({
1183+
model: LanguageModel.make({ ...glm, compatibility: { requireSignature: true } }),
1184+
messages: [
1185+
Message.assistant([
1186+
{ type: "reasoning", text: "Reasoning.", providerMetadata: { "custom-gateway": { signature: "" } } },
1187+
]),
1188+
],
1189+
cache: "none",
1190+
}),
1191+
)
1192+
expect(required.body.messages).toEqual([])
1193+
}),
1194+
)
1195+
11331196
it.effect("round-trips redacted thinking as redacted_thinking blocks", () =>
11341197
Effect.gen(function* () {
11351198
const prepared = yield* compileRequest(

‎packages/core/perf/snapshot.ts‎

Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -326,6 +326,7 @@ export async function session(snapshots: "on" | "off", ttft: number) {
326326
retry: () => Effect.succeed({ retry: false as const }),
327327
recoverContinuation: false,
328328
recoverOverflow: Effect.succeed(false),
329+
recoverSignature: Effect.succeed(false),
329330
})
330331
}
331332
}).pipe(

‎packages/core/src/session/context.ts‎

Lines changed: 4 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -40,6 +40,7 @@ import { SessionModelRequest } from "./model-request.js"
4040
import { SessionRunnerModel } from "./runner/model.js"
4141
import { SessionSchema } from "./schema.js"
4242
import { SessionStore } from "./store.js"
43+
import { ThinkingSignature } from "./thinking-signature.js"
4344

4445
export interface Selection {
4546
readonly session: SessionSchema.Info
@@ -114,11 +115,12 @@ const layer = Layer.effect(
114115
const api = yield* CodeModeApi.Service
115116
const agentRunner = yield* CodeModeAgents.Service
116117
const websearch = yield* WebSearch.Service
118+
const signatures = yield* ThinkingSignature.Service
117119

118120
const resolveModel = (
119121
session: SessionSchema.Info,
120122
request: { readonly kind: SessionRequestKind; readonly agent: Agent.ID },
121-
) => models.resolve(session, model.available, request)
123+
) => models.resolve(session, model.available, request).pipe(Effect.map(signatures.apply))
122124

123125
const selectTitle = Effect.fn("SessionContext.selectTitle")(function* (session: SessionSchema.Info) {
124126
const agent = yield* agents.get(Agent.ID.make("title"))
@@ -302,6 +304,7 @@ export const node = makeLocationNode({
302304
SessionModelRequest.node,
303305
SessionStore.node,
304306
SkillInstructions.node,
307+
ThinkingSignature.node,
305308
Tool.node,
306309
WebSearch.node,
307310
],

0 commit comments

Comments
 (0)