@mastra/core
Version:
126 lines • 6.85 kB
TypeScript
import type { ModelMessage, ToolResultPart } from '../../../_types/@internal_ai-sdk-v5@0.0.98/dist/index.js';
import type { IMastraLogger } from '../../../logger/index.js';
import type { MastraDBMessage } from '../state/types.js';
import type { ResponseItemIdProvider } from './response-item-metadata.js';
/**
* Tool result with input field (Anthropic requirement)
*/
export type ToolResultWithInput = ToolResultPart & {
input: Record<string, unknown>;
};
/**
* Removes provider-executed tool parts that a *different* provider produced.
*
* A provider-executed tool result is the provider's own payload, in the provider's
* own shape, and each provider validates it against its own schema on the way back
* in. Those shapes disagree — OpenAI's `web_search` result is an object, Anthropic's
* is an array — and the tool names collide, so replaying one provider's stored result
* to another throws during prompt conversion, before the request is even built. That
* bricks the thread permanently rather than degrading one turn.
*
* These parts are deliberately exempt from `sanitizeOrphanedToolPairs` (their results
* may legitimately be deferred), so they need dropping here instead. Only parts whose
* origin message is stamped with a provider that differs from the target are removed;
* unstamped history is left untouched, so nothing changes for threads that predate
* provider stamping.
*
* Only the provider-executed parts are removed. Text and reasoning from the same foreign
* turn stay, because they are provider-agnostic content rather than a provider's own
* validated payload. The trade-off is that a later turn may still reference a search whose
* results are no longer in context — an incomplete answer instead of an unusable thread.
*
* Matching is by exact provider string, not by vendor family, because provider ids are not
* a uniform namespace: `ModelRouterLanguageModel` falls back to the configured provider id,
* so values like `crof` sit alongside `anthropic.messages`. A same-vendor switch such as
* `openai.responses` to `openai.chat` therefore also drops — the safe direction, since the
* alternative is guessing that two providers share a payload shape.
*
* @param messages - Converted model messages about to be sent
* @param dbMessages - Stored messages, read for the `provider` each assistant turn was generated by
* @param targetProvider - Provider the prompt is being built for; when unknown, nothing is dropped
* @param logger - Optional logger, warned once per dropped tool call
* @returns The same array when nothing is dropped, otherwise a new array
*
* @see https://github.com/mastra-ai/mastra/issues/23082
*/
export declare function dropCrossProviderExecutedParts<T extends ModelMessage>(messages: T[], dbMessages: MastraDBMessage[], targetProvider: string | undefined, logger?: IMastraLogger): T[];
/**
* Ensures model messages are compatible with Anthropic API requirements.
*
* Anthropic API requires tool-result parts to include an 'input' field
* that matches the original tool call arguments.
*
* @param messages - Array of model messages to transform
* @param dbMessages - MastraDB messages to look up tool call args from
* @returns Messages with tool-result parts enriched with input field
*
* @see https://github.com/mastra-ai/mastra/issues/11376 - Anthropic models fail with empty object tool input
*/
export declare function ensureAnthropicCompatibleMessages(messages: ModelMessage[], dbMessages: MastraDBMessage[]): ModelMessage[];
/**
* Removes orphan tool_use / tool_result blocks. Anthropic requires every tool_result
* to be in the message immediately after its matching tool_use, and every tool_use
* to have a matching tool_result in the next message. Recall windows can slice
* through a parallel tool-call group and leave behind half a pair.
*/
export declare function sanitizeOrphanedToolPairs(messages: ModelMessage[]): ModelMessage[];
/**
* Keeps result-less tool calls in the prompt by pairing each one with a placeholder result.
*
* Used when the caller opted to keep suspended tool calls visible to the agent
* (`filterIncompleteToolCalls: false`). Providers reject a tool_use with no matching
* tool_result, so dropping the call is not the only option — synthesizing the missing
* half keeps the pending call in context while satisfying the pairing requirement.
*
* Provider-executed calls are left alone: they may be legitimately deferred to the next
* request, and giving them a result would resolve a call the provider intends to resume.
*
* @see https://github.com/mastra-ai/mastra/issues/20610
*/
export declare function pairOrphanedToolCalls(messages: ModelMessage[]): ModelMessage[];
/**
* Checks if a message part has an OpenAI reasoning itemId.
*
* OpenAI Responses reasoning items are tracked via `providerMetadata.openai.itemId`.
* Each reasoning item has a unique itemId that must be preserved for proper deduplication.
*
* @param part - A message part to check
* @returns true if the part has an OpenAI itemId
*
* @see https://github.com/mastra-ai/mastra/issues/9005 - OpenAI reasoning items filtering
*/
export declare function hasOpenAIReasoningItemId(part: unknown): boolean;
/**
* Checks if a message part has an OpenAI-compatible Responses itemId.
*
* Provider-neutral Responses item IDs are tracked via provider metadata or
* provider options fields such as `openai.itemId` or `azure.itemId`.
*/
export declare function hasResponseProviderItemId(part: unknown): boolean;
/**
* Extracts an OpenAI itemId from a message part if present.
*
* This only inspects `providerMetadata.openai.itemId`; use
* `getResponseProviderItemIdFromPart` for provider-aware Azure/OpenAI lookups.
*
* @param part - A message part to extract from
* @returns The itemId string or undefined if not present
*/
export declare function getOpenAIReasoningItemId(part: unknown): string | undefined;
export declare function getResponseProviderItemIdFromPart(part: unknown): {
provider: ResponseItemIdProvider;
itemId: string;
} | undefined;
/**
* Finds the tool call args for a given toolCallId by searching through messages.
* This is used to reconstruct the input field when converting tool-result parts to StaticToolResult.
*
* Searches through messages in reverse order (most recent first) for better performance.
* Checks both content.parts (v2 format) and toolInvocations (legacy AIV4 format).
*
* @param messages - Array of MastraDB messages to search through
* @param toolCallId - The ID of the tool call to find args for
* @returns The args object from the matching tool call, or an empty object if not found
*/
export declare function findToolCallArgs(messages: MastraDBMessage[], toolCallId: string): Record<string, unknown>;
//# sourceMappingURL=provider-compat.d.ts.map