UNPKG

@mastra/core

Version:
410 lines • 22.1 kB
import type { LanguageModelV2Prompt } from '../_types/@ai-sdk_provider@2.0.5/dist/index.js'; import type { MastraDBMessage, MessageList } from '../agent/message-list/index.js'; import type { Processor, ProcessAPIErrorArgs, ProcessAPIErrorResult, ProcessLLMRequestArgs, ProcessLLMRequestResult } from './index.js'; /** * A single compatibility rule that resolves a known provider history * incompatibility. Rules can resolve issues either: * * - **Reactively** via {@link CompatRule.fix}: when an API call fails with an * error matching one of {@link CompatRule.errorPatterns}, the fix mutates * the persisted message list and the request is retried. Suitable for * incompatibilities that, once fixed, stay fixed across future turns * (e.g. tool-call ID format). * * - **Preemptively** via {@link CompatRule.applyToPrompt}: runs in * `processLLMRequest` after `MessageList → LanguageModelV2Prompt` conversion * and before the prompt is sent to the provider. Mutations affect only the * outbound prompt; nothing is persisted to the message list. Suitable for * incompatibilities that would otherwise re-trigger on every turn (e.g. * fields the model adds to its own response that the same provider rejects * on subsequent input). * * A rule may implement either hook, both, or — rarely — neither (e.g. a * placeholder for future error-pattern matching). */ export interface CompatRule { /** Human-readable identifier for logging/debugging. */ name: string; /** Regexes matched against the error message and response body. */ errorPatterns?: RegExp[]; /** Mutate persisted messages to resolve the incompatibility. Return `true` if changes were made. */ fix?: (messages: MastraDBMessage[]) => boolean; /** * Rewrite the outbound LLM request preemptively. Receives the resolved model * so rules can scope themselves to specific providers, and — when the caller * has it — the message list the prompt was built from, for provenance the * converted prompt no longer carries. Return a new prompt to forward, or * `undefined` to leave the prompt unchanged. */ applyToPrompt?: (args: { prompt: LanguageModelV2Prompt; model: unknown; /** Provider id of the API the prompt is sent to (see `ProcessLLMRequestArgs.apiProviderId`). */ apiProviderId?: string; messageList?: MessageList; }) => LanguageModelV2Prompt | undefined; } /** * Anthropic enforces `^[a-zA-Z0-9_-]+$` on tool_use.id values. * Tool-call IDs from other providers (e.g. containing `.`, `:`) will be * rejected. This rule rewrites offending characters to `_` in the outbound * prompt, so the rejection never happens and persisted history keeps its * original IDs. */ export declare const anthropicToolIdFormat: CompatRule; export declare function isMaybeCerebras(model: string | { provider?: string; modelId?: string; } | ((...args: any[]) => any) | { model: any; enabled?: boolean; }[] | unknown): boolean; export declare function isMaybeAnthropic(model: string | { provider?: string; modelId?: string; } | ((...args: any[]) => any) | { model: any; enabled?: boolean; }[] | unknown): boolean; /** * Provider-executed tools are provider-owned continuation state. A foreign * provider cannot resolve their IDs, so remove the call and paired result from * the outbound prompt while leaving persisted history untouched. */ export declare const stripForeignProviderExecutedTools: CompatRule; /** * Detects Anthropic models that removed assistant-message prefill support. * Claude 4.6 and later reject assistant-prefill requests, while earlier * models retain support. Unknown Anthropic model versions are matched * conservatively so a new model cannot silently bypass compatibility guards. */ export declare function isMaybeAnthropicWithoutAssistantPrefill(model: unknown): boolean; /** * Detects Google models that reject a request ending on a model turn. * * Gemini 3 and later return 400 "Requests ending with a model turn are not * supported"; Gemini 2.x accepted the same prompt, including under native * structured output. Unknown Google model versions are matched conservatively * so a new model cannot silently bypass compatibility guards. * * @see https://github.com/mastra-ai/mastra/issues/23320 */ export declare function isMaybeGoogleWithoutTrailingModelTurn(model: unknown): boolean; export declare function isMaybeAzure(model: string | { provider?: string; modelId?: string; } | ((...args: any[]) => any) | { model: any; enabled?: boolean; }[] | unknown): boolean; /** * Detects providers that reject a conversation whose first non-system turn is * the assistant's: Amazon Bedrock ("A conversation must start with a user * message") and Google/Vertex Gemini. OpenAI, Anthropic, Groq, Mistral, * DeepSeek and Cerebras accept that shape, so they are left alone. * * @see https://github.com/mastra-ai/mastra/issues/5465 * @see https://github.com/mastra-ai/mastra/issues/8053 */ export declare function isMaybeRequiringUserFirstTurn(model: unknown): boolean; /** * Inserts a minimal user turn ahead of a leading assistant turn for providers * that require conversations to start with the user (see * {@link isMaybeRequiringUserFirstTurn}). History windows commonly start on an * assistant turn — agents that greet first, or `lastMessages` cutting into a * thread — and those providers reject the whole request otherwise. */ export declare const ensureUserFirstTurn: { name: string; applyToPrompt({ prompt, model, }: { prompt: LanguageModelV2Prompt; model: unknown; }): LanguageModelV2Prompt | undefined; }; /** * Cerebras's API rejects assistant messages carrying a `reasoning_content` * field with HTTP 400 (`property '...reasoning_content' is unsupported`). * * Starting in `@ai-sdk/openai-compatible@1.0.32` (https://github.com/vercel/ai/pull/12049), * which `@ai-sdk/cerebras` depends on, reasoning parts on assistant messages * are unconditionally serialized as `reasoning_content` on outbound requests. * That breaks multi-turn tool calls with reasoning enabled (e.g. * `cerebras/zai-glm-4.7`) on the second-or-later assistant turn. * * This rule preemptively strips `reasoning` parts from assistant messages * in the outbound prompt when the resolved model is Cerebras. The strip * runs in `processLLMRequest` so it affects only what is sent to Cerebras — * the persisted message list (memory, UI, observability) keeps the full * reasoning trace, and other providers (e.g. Z.ai's coding-plan endpoint, * which *requires* `reasoning_content` echoed back for its preserved-thinking * feature) are unaffected because the rule is provider-scoped. * * It can't be reactive (`processAPIError`) because the model emits a fresh * reasoning part on every turn — a reactive rule would cause one * failed-and-retried request per turn. * * Once https://github.com/vercel/ai/pull/11278 lands a per-provider * `sendReasoning` opt-out, this rule can be replaced with `sendReasoning: false` * on the cerebras provider config. */ export declare const cerebrasStripReasoningContent: CompatRule; /** * Legacy records could contain Anthropic signed thinking metadata with an * empty reasoning text. Anthropic signs the exact thinking text, so replaying * that mismatched pair is rejected with the "thinking blocks cannot be * modified" 400. * * Reactive, because an empty text with a signature is not by itself a sign of * corruption: Claude 5.x returns exactly that for every thinking block when * `display` is left at its default (`omitted`). Stripping those up front would * change the prompt prefix on every step and break prompt caching, so the * blocks are only dropped, from earlier assistant messages, once Anthropic has * actually rejected the history. * * @see https://github.com/mastra-ai/mastra/issues/28309 */ export declare const anthropicStripEmptySignedReasoningContent: CompatRule; /** * Anthropic accepts its own thinking/reasoning history, but rejects reasoning * parts emitted by other providers. Strip only foreign reasoning parts at the * Anthropic provider boundary so persisted history remains intact and native * Anthropic thinking can still round-trip. */ export declare const anthropicStripForeignReasoningContent: CompatRule; /** * Replays of signed `thinking`/`redacted_thinking` blocks to a provider other * than the one that signed them are rejected — Anthropic returns * `Invalid \`signature\` in \`thinking\` block`. * * Several providers are served through `@ai-sdk/anthropic` and therefore write * their reasoning metadata under the same `anthropic` key — Kimi For Coding * talks to `api.kimi.com` over the Anthropic wire format — so a signature's * `anthropic` key alone cannot tell which provider signed it. The durable * provenance is the `provider` each assistant turn was stamped with by * `buildResponseModelMetadata`, which only the persisted message list carries. * * Reasoning parts whose signature came from a turn stamped with a provider * different from the current target are dropped from the outbound prompt, so * the rejection never happens. Unstamped history is left untouched — turns * persisted before their provider had a distinct identity stay ambiguous and * are forwarded as-is. Turns emptied of all content by the drop are removed * from the prompt (Anthropic rejects empty assistant content). */ export declare const anthropicStripForeignSignedReasoning: CompatRule; /** * Azure OpenAI's content moderation can classify `<system-reminder>` wrappers * in user messages as prompt injection. Rename the wrapper at the provider * boundary while leaving persisted history and other providers unchanged. */ export declare const azureSystemReminderTransform: CompatRule; /** * OpenAI's Responses API replays a persisted assistant message by reference * (`item_reference`) when the message carries an `itemId` (`msg_…`). If that * message has no accompanying `reasoning` item, the request is rejected with a * non-retryable 400: * * ``` * Item 'msg_…' of type 'message' was provided without its required 'reasoning' item: 'rs_…' * ``` * * Because the offending message is already persisted, that 400 repeats on every * subsequent turn, and the thread stops working. This rule is a recovery * seatbelt for histories that are *already* corrupted: dropping the `itemId` * makes the message replay by value instead of by reference, which OpenAI * accepts. The content the user sees is unchanged. * * The repair is in-memory for the current turn: a message sourced from storage * is not re-drained, so a later turn on the same thread spends one rejected * request before recovering again. Same property as `anthropicToolIdFormat`. * * Reactive by design — it fires only after OpenAI has actually rejected the * request, so a legitimately reasoning-free message (e.g. * `reasoning.effort: 'none'`, or a non-reasoning model) is untouched on any * thread that has not already hit this 400. Once it has, see the collateral * note below. * * Deliberately narrow: * - Matches only the `of type 'message'` phrasing. The sibling `function_call` * (`fc_…`) variant is a different failure, addressed by PR #19408. Matching * narrowly is not the same as repairing narrowly, though: once a message is * established as an orphan, every item reference it carries is unsatisfiable * for the same reason, so the repair covers all of them. A message whose * `msg_…` id was dropped while its `fc_…` id stayed would simply fail on the * next item in the list, spending the one available retry to arrive at the * same error. * - Strips only the item-reference keys (`itemId` and its result-side partner * `resultItemId`); all other fields in the namespace survive. * - Reads and strips through the shared Responses helpers, so the `azure` * namespace is covered on the same footing as `openai` — the repo treats * them as one Responses family, and Azure raises this same 400. * - Skips a message whose reasoning lives on the immediately preceding * assistant row, when that row has reasoning and no text of its own. Stored * history can split one turn across adjacent assistant rows (adjacent rows * are merged when streamed, but not when loaded from storage), and in that * case the reasoning item *is* present in the prompt — stripping the id * there would fix nothing and would discard a valid reference. A preceding * row that already paired its own reasoning with its own text is not cover * and does not suppress the repair. * * Not covered by that guard, deliberately: the `assistant[reasoning, tool-call] * → tool[result] → assistant[text]` shape, where the preceding entry is a tool * message. If OpenAI rejected the text item there, its reference is genuinely * unsatisfiable and stripping is the right repair. * * The rule repairs every orphan-shaped message in the history rather than only * the id named in the error, because `fix` does not receive the error and the * error names only the first item OpenAI tripped over. Healing that one id * would trade a permanent failure for N sequential ones, and there is a single * retry available, not N. * * The cost of that breadth: in a thread that mixes a reasoning model with a * non-reasoning Responses model, the non-reasoning turns are also orphan-shaped * (an `itemId`, no reasoning) but are perfectly valid, and they lose their item * references too. Ordinary text and tool parts still replay correctly — by * value instead of by reference — so for them the effect is a lost item * reference, not a failure. * * One part type pays more than a reference. A hosted `tool_search` call cannot * be replayed by value at all, so `isUnreplayableHostedToolSearchPart` * (`output-converter.ts`) drops it from the prompt once its ids are gone. On a * genuinely orphaned message that is the right outcome — the ids pointed into * the rejected response. On a swept-along valid message it costs the model that * search result, and it would have to search again. That is accepted: the * asymmetry is still deliberate, because under-stripping ends the turn outright * while over-stripping costs a reference, or at worst one hosted search. * * Known limitation: the guard reasons about message *shape*, because the * required `rs_…` id named in the error is not available to `fix`. A turn whose * reasoning row belongs to a different turn could in principle be skipped * when it should have been repaired. That case degrades to today's behavior — the turn * fails as it already does — so the guard can cost a recovery, never cause a * new failure. * * This is a seatbelt, not the cure: the path that produces these orphans is * fixed separately in the processor-retry rollback (#22291). */ export declare const openaiOrphanItemId: CompatRule; /** * Removes steps that hold nothing but reasoning when more assistant content * follows them. The step's other parts were lost (older `@mastra/memory` * releases stripped an `updateWorkingMemory` call and kept its thinking), so * `@ai-sdk/anthropic` merges the leftover signed thinking into the next * assistant step — a shape Anthropic rejects on every later turn. * * Reactive (matches Anthropic's "cannot be modified" 400); a recovery seatbelt * for history saved before the strip was fixed. * * @see https://github.com/mastra-ai/mastra/issues/22798 */ export declare const anthropicOrphanedThinkingStep: CompatRule; /** * Merges the leading system messages of a Chat Completions request into one. * * Whether a server accepts several system messages depends on the host's chat template, not the * model or provider: the same Qwen3.5 weights are accepted by some hosts and rejected with * `System message must be at the beginning` by others. One leading system message is valid * everywhere. * * Applies when the API provider id ends in `.chat` (`openai.chat`, `groq.chat`, `<name>.chat` * from `createOpenAICompatible`, ...). Native APIs with a dedicated system field (`anthropic`, * `google.generative-ai`, `bedrock`) and Responses APIs never do. Prompts are left unchanged when * any merged message other than the last carries `providerOptions` (e.g. a cache breakpoint), * since merging would drop it. * * @see https://github.com/mastra-ai/mastra/issues/25435 */ export declare const chatCompletionsSingleSystemMessage: CompatRule; /** * Sends an assistant tool call that has no input (`undefined` or `null`) as `{}`. * * A call whose arguments could not be parsed is stored as an `output-error` tool part with no * `args`. Replayed as-is, providers reject every later request on the thread (Anthropic: * `tool_use.input: Field required`; OpenAI-compatible: `function.arguments must be defined`). * The error result stays paired with the call; only the call's input is filled in. An empty string * is a real stored input, not a missing one, and is left as it is. * * Applies to every provider, runs in `processLLMRequest` so the stored message keeps its shape. */ export declare const toolCallEmptyInput: CompatRule; /** * All built-in compat rules. Extend by passing additional rules to the * `ProviderHistoryCompat` constructor. */ export declare const DEFAULT_COMPAT_RULES: CompatRule[]; /** * Handles provider-specific history incompatibilities by applying a registry * of {@link CompatRule}s. Rules can rewrite the outbound prompt preemptively * via `processLLMRequest`, or react to non-retryable API rejections via * `processAPIError`. * * Built-in rules: * - **anthropic-tool-id-format** — rewrites tool-call IDs that contain * characters outside `[a-zA-Z0-9_-]` (e.g. `.` or `:` from other * providers). Preemptive; runs in `processLLMRequest` so the persisted * message list keeps its original IDs. Both the call and its paired result * are rewritten together, and a sanitized ID that would collide with an ID * already in the prompt gets a `_2`/`_3`… suffix. The reactive fallback * (matching a 400 response body and retrying with sanitized IDs) covers * providers the preemptive check doesn't recognize, such as Vertex-hosted * Claude. * - **cerebras-strip-reasoning-content** — strips `reasoning` parts from * assistant messages in the outbound prompt when the resolved model is * Cerebras, to avoid the `@ai-sdk/openai-compatible@>=1.0.32` regression * that serializes them as `reasoning_content` (a field Cerebras's API * rejects). Preemptive; runs in `processLLMRequest` so the persisted * message list keeps the reasoning trace. * - **anthropic-strip-empty-signed-reasoning-content** — strips legacy * Anthropic signed reasoning blocks whose text was lost before replay. * Reactive (matches the "thinking blocks cannot be modified" 400), because * Claude 5.x returns empty-text signed blocks as normal output and they must * be replayed untouched to keep the prompt cache. * - **anthropic-strip-foreign-reasoning-content** — strips non-Anthropic * `reasoning` parts from assistant messages in the outbound prompt when the * resolved model is Anthropic. Anthropic-native reasoning parts are kept. * - **anthropic-strip-foreign-signed-reasoning** — drops signed thinking * blocks from the outbound prompt when their origin turn was stamped with a * provider different from the current target (preemptive). Turns emptied of * all content by the drop are removed from the prompt. Unstamped history is * left untouched. * - **openai-orphan-item-id** — drops the Responses `itemId` (`openai` and * `azure` namespaces alike) from every item-bearing part of an assistant * message that carries one but has no `reasoning` part, so it replays by * value instead of as an unsatisfiable `item_reference`. Reactive (matches * the specific `of type 'message' … without its required 'reasoning' item` * 400); a recovery seatbelt for already-corrupted history. * - **anthropic-orphaned-thinking-step** — drops steps left with only signed * reasoning when more assistant content follows them, so Anthropic doesn't * see that thinking merged into the next step. Reactive (matches the * "thinking blocks ... cannot be modified" 400); a recovery seatbelt for * already-corrupted history. * - **chat-completions-single-system-message** — merges the leading system * messages into one for Chat Completions providers (API provider id ending * in `.chat`), whose hosted chat templates often reject a second system * message. Skipped when an earlier one carries its own `providerOptions`. * Preemptive. * - **tool-call-empty-input** — sends an assistant tool call whose input is * `undefined` or `null` as `{}`, keeping its paired result, so a stored * call with unparseable arguments can't make every later request fail. * Preemptive; the stored message keeps its shape. * - **ensure-user-first-turn** — inserts a `.` user turn ahead of a leading * assistant turn for Amazon Bedrock and Google/Vertex, which reject * assistant-first conversations. Preemptive; the turn is never persisted. * * To add custom rules, pass them to the constructor: * ```ts * new ProviderHistoryCompat({ * additionalRules: [myCustomRule], * }) * ``` */ export declare class ProviderHistoryCompat implements Processor<'provider-history-compat'> { readonly id: 'provider-history-compat'; readonly name = "Provider History Compat"; private rules; constructor(opts?: { additionalRules?: CompatRule[]; }); processLLMRequest({ prompt, model, apiProviderId, messageList }: ProcessLLMRequestArgs): ProcessLLMRequestResult; processAPIError({ error, messageList, retryCount, }: ProcessAPIErrorArgs): Promise<ProcessAPIErrorResult | void>; } //# sourceMappingURL=provider-history-compat.d.ts.map