UNPKG

@mastra/core

Version:
302 lines (301 loc) • 9.94 kB
import { prepareJsonSchemaForOpenAIStrictMode } from "@mastra/schema-compat"; // src/llm/model/free-form-object.ts /** * Whether a JSON schema has an object with free-form keys (e.g. `z.record()`), which OpenAI * strict mode cannot express: it requires every object to list fixed keys with * `additionalProperties: false`. */ function hasFreeFormObject(schema) { if (!schema || typeof schema !== "object" || Array.isArray(schema)) return false; const node = schema; const additional = node.additionalProperties; if (additional === true || additional && typeof additional === "object") return true; if (node.patternProperties || node.propertyNames) return true; const subschemas = []; for (const key of [ "properties", "$defs", "definitions" ]) { const map = node[key]; if (map && typeof map === "object" && !Array.isArray(map)) subschemas.push(...Object.values(map)); } for (const key of [ "anyOf", "oneOf", "allOf" ]) { const list = node[key]; if (Array.isArray(list)) subschemas.push(...list); } const items = node.items; if (Array.isArray(items)) subschemas.push(...items); else if (items) subschemas.push(items); if (Array.isArray(node.prefixItems)) subschemas.push(...node.prefixItems); return subschemas.some(hasFreeFormObject); } // src/llm/model/aisdk/generate-to-stream.ts /** * Converts a doGenerate result to a ReadableStream format. * This is shared between V2 and V3 model wrappers since the content/result structure is compatible. */ function createStreamFromGenerateResult(result) { return new ReadableStream({ start(controller) { controller.enqueue({ type: "stream-start", warnings: result.warnings }); controller.enqueue({ type: "response-metadata", id: result.response?.id, modelId: result.response?.modelId, timestamp: result.response?.timestamp }); const toolCallMeta = {}; for (const message of result.content) if (message.type === "tool-call") { const toolCall = message; toolCallMeta[toolCall.toolCallId] = { providerExecuted: toolCall.providerExecuted }; controller.enqueue({ type: "tool-input-start", id: toolCall.toolCallId, toolName: toolCall.toolName, providerExecuted: toolCall.providerExecuted, dynamic: toolCall.dynamic, providerMetadata: toolCall.providerMetadata }); controller.enqueue({ type: "tool-input-delta", id: toolCall.toolCallId, delta: toolCall.input, providerMetadata: toolCall.providerMetadata }); controller.enqueue({ type: "tool-input-end", id: toolCall.toolCallId, providerMetadata: toolCall.providerMetadata }); controller.enqueue(toolCall); } else if (message.type === "tool-result") { const toolResult = message; const meta = toolCallMeta[toolResult.toolCallId]; if (meta?.providerExecuted) controller.enqueue({ ...toolResult, providerExecuted: meta.providerExecuted }); else controller.enqueue(message); } else if (message.type === "text") { const text = message; const id = `msg_${globalThis.crypto.randomUUID()}`; controller.enqueue({ type: "text-start", id, providerMetadata: text.providerMetadata }); controller.enqueue({ type: "text-delta", id, delta: text.text, providerMetadata: text.providerMetadata }); controller.enqueue({ type: "text-end", id, providerMetadata: text.providerMetadata }); } else if (message.type === "reasoning") { const id = `reasoning_${globalThis.crypto.randomUUID()}`; const reasoning = message; controller.enqueue({ type: "reasoning-start", id, providerMetadata: reasoning.providerMetadata }); controller.enqueue({ type: "reasoning-delta", id, delta: reasoning.text, providerMetadata: reasoning.providerMetadata }); controller.enqueue({ type: "reasoning-end", id, providerMetadata: reasoning.providerMetadata }); } else if (message.type === "file") { const file = message; controller.enqueue({ type: "file", mediaType: file.mediaType, data: file.data, providerMetadata: file.providerMetadata }); } else if (message.type === "source") { const source = message; if (source.sourceType === "url") controller.enqueue({ type: "source", id: source.id, sourceType: "url", url: source.url, title: source.title, providerMetadata: source.providerMetadata }); else controller.enqueue({ type: "source", id: source.id, sourceType: "document", mediaType: source.mediaType, filename: source.filename, title: source.title, providerMetadata: source.providerMetadata }); } else if (message.type === "reasoning-file" || message.type === "custom") controller.enqueue(message); else controller.enqueue({ type: "raw", rawValue: message }); controller.enqueue({ type: "finish", finishReason: result.finishReason, usage: result.usage, providerMetadata: result.providerMetadata }); controller.close(); } }); } // src/llm/model/aisdk/v5/model.ts const isAzureOpenAIModel = (provider) => provider === "azure.chat" || provider === "azure.responses"; /** * Prepares function tool schemas for strict mode when an AI SDK 5 `@ai-sdk/azure` request is strict. * * The v2 Chat and Responses models copy the single `openai.strictJsonSchema` flag into every * function tool's `strict`, so opting into strict structured output also makes every tool strict. * Azure rejects a strict tool schema that leaves keys out of `required` or uses keywords such as * `uniqueItems` (#28593). Native `openai.*` models are left alone: OpenAI accepts constraints that * preparing would move into descriptions. */ function prepareAzureStrictToolSchemas(options) { if (!options.tools?.length || options.providerOptions?.openai?.strictJsonSchema !== true) return options; return { ...options, tools: options.tools.map((tool) => { if (tool.type !== "function" || hasFreeFormObject(tool.inputSchema)) return tool; try { return { ...tool, inputSchema: prepareJsonSchemaForOpenAIStrictMode(tool.inputSchema) }; } catch { return tool; } }) }; } /** * Strips per-tool `strict` from function tools (V2 providers don't support it) * and, when any tool had `strict: true`, injects `strictJsonSchema: true` into * the OpenAI provider options so the V2 OpenAI provider enables strict mode * globally for all tools. */ function applyStrictForV2(options, provider) { if (!options.tools?.length) return options; let hasStrictTool = false; const sanitizedTools = options.tools.map((tool) => { if (tool.type !== "function" || !("strict" in tool)) return tool; if (tool.strict === true) hasStrictTool = true; const { strict: _strict, ...rest } = tool; return rest; }); let result = { ...options, tools: sanitizedTools }; if (hasStrictTool) { const existingOpenai = options.providerOptions?.openai ?? {}; if (existingOpenai.strictJsonSchema == null) result = { ...result, providerOptions: { ...options.providerOptions, openai: { ...existingOpenai, strictJsonSchema: true } } }; } return isAzureOpenAIModel(provider) ? prepareAzureStrictToolSchemas(result) : result; } /** * Wrapper class for AI SDK V5 (LanguageModelV2) that converts doGenerate to return * a stream format for consistency with Mastra's streaming architecture. */ var AISDKV5LanguageModel = class { /** * The language model must specify which language model interface version it implements. */ specificationVersion = "v2"; /** * Name of the provider for logging purposes. */ provider; /** * Provider-specific model ID for logging purposes. */ modelId; /** Full `provider/model` ID this model was resolved from, when known. */ id; gatewayId; /** * Supported URL patterns by media type for the provider. * * The keys are media type patterns or full media types (e.g. `*\/*` for everything, `audio/*`, `video/*`, or `application/pdf`). * and the values are arrays of regular expressions that match the URL paths. * The matching should be against lower-case URLs. * Matched URLs are supported natively by the model and are not downloaded. * @returns A map of supported URL patterns by media type (as a promise or a plain object). */ supportedUrls; /** * Whether the wrapped provider model sends native structured output (for example * `@ai-sdk/openai-compatible` models created with `supportsStructuredOutputs: true`). */ supportsStructuredOutputs; #model; constructor(config) { this.#model = config; this.provider = this.#model.provider; this.modelId = this.#model.modelId; this.gatewayId = config.gatewayId; this.supportedUrls = this.#model.supportedUrls; const supportsStructuredOutputs = config.supportsStructuredOutputs; if (typeof supportsStructuredOutputs === "boolean") this.supportsStructuredOutputs = supportsStructuredOutputs; } async doGenerate(options) { const result = await this.#model.doGenerate(applyStrictForV2(options, this.provider)); return { ...result, request: result.request, response: result.response, stream: createStreamFromGenerateResult(result) }; } async doStream(options) { return await this.#model.doStream(applyStrictForV2(options, this.provider)); } /** * Custom serialization for tracing/observability spans. * `#model` is already a true JS private field and not enumerable, so * the wrapped provider SDK client can't leak. This method makes the * safe shape explicit and avoids walking `supportedUrls` (a * PromiseLike / regex map that isn't useful in spans). */ serializeForSpan() { return { specificationVersion: this.specificationVersion, modelId: this.modelId, provider: this.provider, gatewayId: this.gatewayId }; } }; export { hasFreeFormObject as i, prepareAzureStrictToolSchemas as n, createStreamFromGenerateResult as r, AISDKV5LanguageModel as t }; //# sourceMappingURL=model-DS-b2R-R.js.map