'use strict'; var chunkDURT53SS_cjs = require('./chunk-DURT53SS.cjs'); var chunkDBTKQ3U2_cjs = require('./chunk-DBTKQ3U2.cjs'); var chunkZMNN3DOV_cjs = require('./chunk-ZMNN3DOV.cjs'); var chunkOCS2GTEN_cjs = require('./chunk-OCS2GTEN.cjs'); var chunkCWEKD6V4_cjs = require('./chunk-CWEKD6V4.cjs'); var chunkPJIAL3WK_cjs = require('./chunk-PJIAL3WK.cjs'); var crypto = require('crypto'); var v4 = require('zod/v4'); // src/stream/types.ts var ChunkFrom = /* @__PURE__ */ ((ChunkFrom2) => { ChunkFrom2["AGENT"] = "AGENT"; ChunkFrom2["USER"] = "USER"; ChunkFrom2["SYSTEM"] = "SYSTEM"; ChunkFrom2["WORKFLOW"] = "WORKFLOW"; ChunkFrom2["NETWORK"] = "NETWORK"; return ChunkFrom2; })(ChunkFrom || {}); var MASTRA_MODEL_STREAM_TRANSPORT = /* @__PURE__ */ Symbol.for("@mastra/core.modelStreamTransport"); function attachModelStreamTransport(target, transport) { if (!transport) return; Object.defineProperty(target, MASTRA_MODEL_STREAM_TRANSPORT, { configurable: true, value: transport }); } function readModelStreamTransport(target) { return target?.[MASTRA_MODEL_STREAM_TRANSPORT]; } // src/llm/model/aisdk/v6/model.ts function remapToolsToV3(options) { if (!options.tools?.length) { return options; } const remappedTools = options.tools.map((tool) => { if (tool.type === "provider-defined") { return { ...tool, type: "provider" }; } return tool; }); return { ...options, tools: remappedTools }; } var AISDKV6LanguageModel = class { /** * The language model must specify which language model interface version it implements. */ specificationVersion = "v3"; /** * Name of the provider for logging purposes. */ provider; /** * Provider-specific model ID for logging purposes. */ modelId; /** * 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; #model; constructor(config) { this.#model = config; this.provider = this.#model.provider; this.modelId = this.#model.modelId; this.supportedUrls = this.#model.supportedUrls; } async doGenerate(options) { const result = await this.#model.doGenerate(remapToolsToV3(options)); return { ...result, request: result.request, response: result.response, stream: chunkCWEKD6V4_cjs.createStreamFromGenerateResult(result) }; } async doStream(options) { return await this.#model.doStream(remapToolsToV3(options)); } /** * 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 }; } }; // src/llm/model/router.ts function isLanguageModelV3(model) { return model.specificationVersion === "v3"; } var OPENAI_WS_ALLOWLIST = /* @__PURE__ */ new Set(["openai"]); var OPENAI_API_HOST = "api.openai.com"; function createGatewayModelCache() { return { modelInstances: /* @__PURE__ */ new Map(), webSocketFetches: /* @__PURE__ */ new Map(), gatewayStreamTransports: /* @__PURE__ */ new Map() }; } function getOpenAITransport(providerOptions, providerId) { const transportOptions = providerId === "azure-openai" ? providerOptions?.azure : providerOptions?.openai; return { transport: transportOptions?.transport ?? "fetch", websocket: transportOptions?.websocket }; } function isOpenAIBaseUrl(baseURL) { if (!baseURL) return true; try { const hostname = new URL(baseURL).hostname; return hostname === OPENAI_API_HOST; } catch { return false; } } function stableHeaderKey(headers) { if (!headers) return ""; const entries = Object.entries(headers); if (entries.length === 0) return ""; return JSON.stringify(entries.sort(([a], [b]) => a.localeCompare(b))); } function mergeHeaders(baseHeaders, authHeaders) { if (!baseHeaders && !authHeaders) return void 0; return { ...baseHeaders, ...authHeaders }; } function getStaticProvidersByGateway(name) { return Object.fromEntries(Object.entries(chunkDURT53SS_cjs.PROVIDER_REGISTRY).filter(([_provider, config]) => config.gateway === name)); } var defaultGateways = [ new chunkZMNN3DOV_cjs.NetlifyGateway(), new chunkDURT53SS_cjs.MastraGateway(), new chunkDBTKQ3U2_cjs.ModelsDevGateway(getStaticProvidersByGateway(`models.dev`)) ]; var ModelRouterLanguageModel = class _ModelRouterLanguageModel { specificationVersion = "v2"; defaultObjectGenerationMode = "json"; supportsStructuredOutputs = true; supportsImageUrls = true; /** * Supported URL patterns by media type for the provider. * This is a lazy promise that resolves the underlying model's supportedUrls. * Models like Mistral define which URL patterns they support (e.g., application/pdf for https URLs). * * @see https://github.com/mastra-ai/mastra/issues/12152 */ supportedUrls; modelId; provider; gatewayId; config; gateway; _supportedUrlsPromise = null; instanceGatewayCache = createGatewayModelCache(); #lastStreamTransport; constructor(config, customGateways) { let normalizedConfig; if (typeof config === "string") { normalizedConfig = { id: config }; } else if ("providerId" in config && "modelId" in config) { normalizedConfig = { id: `${config.providerId}/${config.modelId}`, url: config.url, apiKey: config.apiKey, headers: config.headers }; } else { normalizedConfig = { id: config.id, url: config.url, apiKey: config.apiKey, headers: config.headers }; } const parsedConfig = { ...normalizedConfig, routerId: normalizedConfig.id }; const allGateways = customGateways?.length ? [ ...customGateways, ...defaultGateways.filter((dg) => !customGateways.some((cg) => chunkDURT53SS_cjs.getGatewayId(cg) === chunkDURT53SS_cjs.getGatewayId(dg))) ] : defaultGateways; this.gateway = chunkDURT53SS_cjs.findGatewayForModel(normalizedConfig.id, allGateways); this.gatewayId = chunkDURT53SS_cjs.getGatewayId(this.gateway); const gatewayPrefix = this.gatewayId === "models.dev" ? void 0 : this.gatewayId; const parsed = chunkDBTKQ3U2_cjs.parseModelRouterId(normalizedConfig.id, gatewayPrefix); this.provider = parsed.providerId || "openai-compatible"; if (parsed.providerId && parsed.modelId !== normalizedConfig.id) { parsedConfig.id = parsed.modelId; } this.modelId = parsedConfig.id; this.config = parsedConfig; const self = this; this.supportedUrls = { then(onfulfilled, onrejected) { return self._resolveSupportedUrls().then(onfulfilled, onrejected); } }; } /** * Lazily resolves the underlying model's supportedUrls. * This is cached to avoid multiple model resolutions. * @internal */ async _resolveSupportedUrls() { if (this._supportedUrlsPromise) { return this._supportedUrlsPromise; } this._supportedUrlsPromise = this._fetchSupportedUrls(); return this._supportedUrlsPromise; } /** * Fetches supportedUrls from the underlying model. * @internal */ async _fetchSupportedUrls() { let apiKey; try { const parsed = chunkDBTKQ3U2_cjs.parseModelRouterId( this.config.routerId, this.gatewayId === "models.dev" ? void 0 : this.gatewayId ); const auth = await this.resolveAuth(parsed.providerId, parsed.modelId); apiKey = auth.apiKey ?? ""; const gatewayPrefix = this.gatewayId === "models.dev" ? void 0 : this.gatewayId; const model = await this.resolveLanguageModel({ apiKey, auth, headers: mergeHeaders(this.config.headers, auth.headers), ...chunkDBTKQ3U2_cjs.parseModelRouterId(this.config.routerId, gatewayPrefix) }); const modelSupportedUrls = model.supportedUrls; if (!modelSupportedUrls) { return {}; } if (typeof modelSupportedUrls.then === "function") { const resolved = await modelSupportedUrls; return resolved ?? {}; } return modelSupportedUrls ?? {}; } catch { return {}; } } /** @internal */ _getStreamTransport() { return this.#lastStreamTransport; } /** * Custom serialization for tracing/observability spans. * Excludes `config` (holds apiKey, headers, url) and `gateway` * (may hold proxy credentials or cached tokens) so they cannot leak * into telemetry backends. */ serializeForSpan() { return { specificationVersion: this.specificationVersion, modelId: this.modelId, provider: this.provider, gatewayId: this.gatewayId }; } getGatewayCache() { let cache = _ModelRouterLanguageModel.gatewayCaches.get(this.gateway); if (!cache) { cache = createGatewayModelCache(); _ModelRouterLanguageModel.gatewayCaches.set(this.gateway, cache); } return cache; } shouldUseInstanceGatewayCache(auth) { return this.config.apiKey !== void 0 || auth.source === "explicit" || auth.source === "gateway"; } setStreamTransportHandle({ resolvedTransport, transport, responsesWebSocket }) { if (resolvedTransport !== "websocket") { this.#lastStreamTransport = void 0; return; } if (!transport) { this.#lastStreamTransport = void 0; return; } this.#lastStreamTransport = { type: transport.type, close: transport.close, closeOnFinish: responsesWebSocket?.closeOnFinish ?? true }; } async resolveAuth(providerId, modelId) { if (this.config.url) { return { apiKey: this.config.apiKey ?? "", headers: this.config.headers, source: "explicit" }; } const explicitHeaders = this.config.headers; const explicitApiKey = this.config.apiKey; const request = { gatewayId: this.gatewayId, providerId, modelId, routerId: this.config.routerId }; if (explicitApiKey) { return { apiKey: explicitApiKey, headers: explicitHeaders, source: "explicit" }; } const rawGatewayAuth = await this.gateway.resolveAuth?.(request); const gatewayAuth = rawGatewayAuth?.bearerToken ? { ...rawGatewayAuth, headers: { ...rawGatewayAuth.headers, Authorization: `Bearer ${rawGatewayAuth.bearerToken}` } } : rawGatewayAuth; if (gatewayAuth?.apiKey || gatewayAuth?.headers || gatewayAuth?.bearerToken) { return { ...gatewayAuth, headers: { ...explicitHeaders, ...gatewayAuth.headers }, source: gatewayAuth.source ?? "gateway" }; } return { apiKey: await this.gateway.getApiKey(request.routerId), headers: explicitHeaders, source: "legacy" }; } setStreamTransportFromCache({ cache, resolvedTransport, key, responsesWebSocket }) { const wsFetch = cache.webSocketFetches.get(key); const gatewayTransport = cache.gatewayStreamTransports.get(key); const transport = wsFetch ? { type: "openai-websocket", close: () => wsFetch.close() } : gatewayTransport; this.setStreamTransportHandle({ resolvedTransport, transport, responsesWebSocket }); } async doGenerate(options) { let auth; try { const parsed = chunkDBTKQ3U2_cjs.parseModelRouterId( this.config.routerId, this.gatewayId === "models.dev" ? void 0 : this.gatewayId ); auth = await this.resolveAuth(parsed.providerId, parsed.modelId); } catch (error) { return { stream: new ReadableStream({ start(controller) { controller.enqueue({ type: "error", error }); controller.close(); } }) }; } const gatewayPrefix = this.gatewayId === "models.dev" ? void 0 : this.gatewayId; const model = await this.resolveLanguageModel({ apiKey: auth.apiKey ?? "", auth, headers: mergeHeaders(this.config.headers, auth.headers), ...chunkDBTKQ3U2_cjs.parseModelRouterId(this.config.routerId, gatewayPrefix) }); if (isLanguageModelV3(model)) { const aiSDKV6Model = new AISDKV6LanguageModel(model); return aiSDKV6Model.doGenerate(options); } const aiSDKV5Model = new chunkCWEKD6V4_cjs.AISDKV5LanguageModel(model); return aiSDKV5Model.doGenerate(options); } async doStream(options) { let auth; try { const parsed = chunkDBTKQ3U2_cjs.parseModelRouterId( this.config.routerId, this.gatewayId === "models.dev" ? void 0 : this.gatewayId ); auth = await this.resolveAuth(parsed.providerId, parsed.modelId); } catch (error) { return { stream: new ReadableStream({ start(controller) { controller.enqueue({ type: "error", error }); controller.close(); } }) }; } const gatewayPrefix = this.gatewayId === "models.dev" ? void 0 : this.gatewayId; const parsedModelId = chunkDBTKQ3U2_cjs.parseModelRouterId(this.config.routerId, gatewayPrefix); const { transport, websocket } = getOpenAITransport( options.providerOptions, parsedModelId.providerId ); const requestedTransport = transport === "auto" ? "websocket" : transport; const allowWebSocket = requestedTransport === "websocket" && !this.config.url && (this.gatewayId === "models.dev" && OPENAI_WS_ALLOWLIST.has(this.provider) || this.gatewayId === "azure-openai"); const resolvedTransport = allowWebSocket ? "websocket" : "fetch"; const model = await this.resolveLanguageModel({ apiKey: auth.apiKey ?? "", auth, headers: mergeHeaders(this.config.headers, auth.headers), transport: resolvedTransport, responsesWebSocket: websocket, ...parsedModelId }); const streamTransport = this.#lastStreamTransport; if (isLanguageModelV3(model)) { const aiSDKV6Model = new AISDKV6LanguageModel(model); const streamResult2 = await aiSDKV6Model.doStream(options); attachModelStreamTransport(streamResult2, streamTransport); return streamResult2; } const aiSDKV5Model = new chunkCWEKD6V4_cjs.AISDKV5LanguageModel(model); const streamResult = await aiSDKV5Model.doStream(options); attachModelStreamTransport(streamResult, streamTransport); return streamResult; } async resolveLanguageModel({ modelId, providerId, apiKey, auth, headers, transport, responsesWebSocket }) { const resolvedTransport = transport ?? "fetch"; const websocketKey = resolvedTransport === "websocket" ? `${responsesWebSocket?.url ?? ""}:${stableHeaderKey(responsesWebSocket?.headers)}` : ""; const useInstanceCache = this.shouldUseInstanceGatewayCache(auth); const cache = useInstanceCache ? this.instanceGatewayCache : this.getGatewayCache(); const authScopeKey = useInstanceCache ? `${auth.source ?? ""}` : ""; const key = crypto.createHash("sha256").update( JSON.stringify([ this.gatewayId, modelId, providerId, this.config.url || "", stableHeaderKey(headers), resolvedTransport, websocketKey, authScopeKey ]) ).digest("hex"); if (cache.modelInstances.has(key)) { this.setStreamTransportFromCache({ cache, resolvedTransport, key, responsesWebSocket }); return cache.modelInstances.get(key); } if (this.config.url) { const modelInstance2 = chunkOCS2GTEN_cjs.createOpenAICompatible({ name: providerId, apiKey, baseURL: this.config.url, headers, supportsStructuredOutputs: true }).chatModel(modelId); cache.modelInstances.set(key, modelInstance2); this.setStreamTransportHandle({ resolvedTransport, responsesWebSocket }); return modelInstance2; } if (resolvedTransport === "websocket" && providerId === "openai" && this.gatewayId === "models.dev") { const baseURL = await this.gateway.buildUrl(this.config.routerId, process.env); if (isOpenAIBaseUrl(baseURL)) { const { modelInstance: modelInstance2, wsFetch } = this.resolveOpenAIWebSocketModel({ modelId, apiKey, baseURL, headers, responsesWebSocket }); cache.modelInstances.set(key, modelInstance2); cache.webSocketFetches.set(key, wsFetch); this.setStreamTransportFromCache({ cache, resolvedTransport, key, responsesWebSocket }); return modelInstance2; } } const modelInstance = await this.gateway.resolveLanguageModel({ modelId, providerId, apiKey, headers, transport: resolvedTransport, responsesWebSocket }); const gatewayTransport = readGatewayStreamTransport(modelInstance); cache.modelInstances.set(key, modelInstance); if (gatewayTransport) { cache.gatewayStreamTransports.set(key, gatewayTransport); } this.setStreamTransportHandle({ resolvedTransport, transport: gatewayTransport, responsesWebSocket }); return modelInstance; } resolveOpenAIWebSocketModel({ modelId, apiKey, baseURL, headers, responsesWebSocket }) { const wsFetch = chunkDURT53SS_cjs.createOpenAIWebSocketFetch({ url: responsesWebSocket?.url, headers: responsesWebSocket?.headers }); const modelInstance = chunkOCS2GTEN_cjs.createOpenAI({ apiKey, baseURL, headers, fetch: wsFetch }).responses(modelId); return { modelInstance, wsFetch }; } static _clearCachesForTests() { _ModelRouterLanguageModel.gatewayCaches = /* @__PURE__ */ new WeakMap(); } static gatewayCaches = /* @__PURE__ */ new WeakMap(); }; function readGatewayStreamTransport(model) { return model[chunkOCS2GTEN_cjs.MASTRA_GATEWAY_STREAM_TRANSPORT]; } // src/llm/model/aisdk/v4/model.ts var AISDKV4LegacyLanguageModel = class { specificationVersion = "v1"; provider; modelId; defaultObjectGenerationMode; supportsImageUrls; supportsStructuredOutputs; #model; constructor(config) { this.#model = config; this.provider = config.provider; this.modelId = config.modelId; this.defaultObjectGenerationMode = config.defaultObjectGenerationMode; this.supportsImageUrls = config.supportsImageUrls; this.supportsStructuredOutputs = config.supportsStructuredOutputs; } supportsUrl(url) { return this.#model.supportsUrl?.(url) ?? false; } doGenerate(options) { return this.#model.doGenerate(options); } doStream(options) { return this.#model.doStream(options); } /** * 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. */ serializeForSpan() { return { specificationVersion: this.specificationVersion, modelId: this.modelId, provider: this.provider }; } }; // src/llm/model/resolve-model.ts function isOpenAICompatibleObjectConfig(modelConfig) { if (typeof modelConfig === "object" && "specificationVersion" in modelConfig) return false; if (typeof modelConfig === "object" && !("model" in modelConfig)) { if ("id" in modelConfig) return true; if ("providerId" in modelConfig && "modelId" in modelConfig) return true; } return false; } async function resolveModelConfig(modelConfig, requestContext = new chunkPJIAL3WK_cjs.RequestContext(), mastra) { if (typeof modelConfig === "function") { modelConfig = await modelConfig({ requestContext, mastra }); } if (modelConfig instanceof ModelRouterLanguageModel || modelConfig instanceof AISDKV4LegacyLanguageModel || modelConfig instanceof chunkCWEKD6V4_cjs.AISDKV5LanguageModel || modelConfig instanceof AISDKV6LanguageModel) { return modelConfig; } if (typeof modelConfig === "object" && "specificationVersion" in modelConfig) { if (modelConfig.specificationVersion === "v2") { return new chunkCWEKD6V4_cjs.AISDKV5LanguageModel(modelConfig); } if (modelConfig.specificationVersion === "v3") { return new AISDKV6LanguageModel(modelConfig); } if (modelConfig.specificationVersion === "v1") { return new AISDKV4LegacyLanguageModel(modelConfig); } if (typeof modelConfig.doStream === "function" && typeof modelConfig.doGenerate === "function") { return new chunkCWEKD6V4_cjs.AISDKV5LanguageModel(modelConfig); } return modelConfig; } const gatewayRecord = mastra?.listGateways(); const customGateways = gatewayRecord ? Object.values(gatewayRecord) : void 0; if (typeof modelConfig === "string" || isOpenAICompatibleObjectConfig(modelConfig)) { return new ModelRouterLanguageModel(modelConfig, customGateways); } throw new Error("Invalid model configuration provided"); } // src/llm/model/model-auth-resolver.ts function mergeAuthHeaders(auth) { if (!auth?.bearerToken) return auth; return { ...auth, headers: { ...auth.headers, Authorization: `Bearer ${auth.bearerToken}` } }; } function hasExplicitAuth(explicit) { return Boolean( explicit?.apiKey || explicit?.bearerToken || explicit?.headers && Object.keys(explicit.headers).length > 0 ); } async function resolveModelAuth({ gateway, request, explicit }) { if (hasExplicitAuth(explicit)) { return mergeAuthHeaders({ ...explicit, source: "explicit" }) ?? { source: "explicit" }; } const gatewayAuth = mergeAuthHeaders(await gateway.resolveAuth?.(request)); if (gatewayAuth?.apiKey || gatewayAuth?.headers || gatewayAuth?.bearerToken) { return { ...gatewayAuth, source: gatewayAuth.source ?? "gateway" }; } return { apiKey: await gateway.getApiKey(request.routerId), source: "legacy" }; } var VERSION = "2.0.72" ; var googleErrorDataSchema = chunkOCS2GTEN_cjs.lazySchema( () => chunkOCS2GTEN_cjs.zodSchema( v4.z.object({ error: v4.z.object({ code: v4.z.number().nullable(), message: v4.z.string(), status: v4.z.string() }) }) ) ); var googleFailedResponseHandler = chunkOCS2GTEN_cjs.createJsonErrorResponseHandler({ errorSchema: googleErrorDataSchema, errorToMessage: (data) => data.error.message }); var googleEmbeddingContentPartSchema = v4.z.union([ v4.z.object({ text: v4.z.string() }), v4.z.object({ inlineData: v4.z.object({ mimeType: v4.z.string(), data: v4.z.string() }) }) ]); var googleGenerativeAIEmbeddingProviderOptions = chunkOCS2GTEN_cjs.lazySchema( () => chunkOCS2GTEN_cjs.zodSchema( v4.z.object({ /** * Optional. Optional reduced dimension for the output embedding. * If set, excessive values in the output embedding are truncated from the end. */ outputDimensionality: v4.z.number().optional(), /** * Optional. Specifies the task type for generating embeddings. * Supported task types: * - SEMANTIC_SIMILARITY: Optimized for text similarity. * - CLASSIFICATION: Optimized for text classification. * - CLUSTERING: Optimized for clustering texts based on similarity. * - RETRIEVAL_DOCUMENT: Optimized for document retrieval. * - RETRIEVAL_QUERY: Optimized for query-based retrieval. * - QUESTION_ANSWERING: Optimized for answering questions. * - FACT_VERIFICATION: Optimized for verifying factual information. * - CODE_RETRIEVAL_QUERY: Optimized for retrieving code blocks based on natural language queries. */ taskType: v4.z.enum([ "SEMANTIC_SIMILARITY", "CLASSIFICATION", "CLUSTERING", "RETRIEVAL_DOCUMENT", "RETRIEVAL_QUERY", "QUESTION_ANSWERING", "FACT_VERIFICATION", "CODE_RETRIEVAL_QUERY" ]).optional(), /** * Optional. Per-value multimodal content parts for embedding non-text * content (images, video, PDF, audio). Each entry corresponds to the * embedding value at the same index and its parts are merged with the * text value in the request. Use `null` for entries that are text-only. * * The array length must match the number of values being embedded. In * the case of a single embedding, the array length must be 1. */ content: v4.z.array(v4.z.array(googleEmbeddingContentPartSchema).min(1).nullable()).optional() }) ) ); var GoogleGenerativeAIEmbeddingModel = class { constructor(modelId, config) { this.specificationVersion = "v2"; this.maxEmbeddingsPerCall = 2048; this.supportsParallelCalls = true; this.modelId = modelId; this.config = config; } get provider() { return this.config.provider; } async doEmbed({ values, headers, abortSignal, providerOptions }) { const googleOptions = await chunkOCS2GTEN_cjs.parseProviderOptions({ provider: "google", providerOptions, schema: googleGenerativeAIEmbeddingProviderOptions }); if (values.length > this.maxEmbeddingsPerCall) { throw new chunkOCS2GTEN_cjs.TooManyEmbeddingValuesForCallError({ provider: this.provider, modelId: this.modelId, maxEmbeddingsPerCall: this.maxEmbeddingsPerCall, values }); } const mergedHeaders = chunkOCS2GTEN_cjs.combineHeaders( await chunkOCS2GTEN_cjs.resolve(this.config.headers), headers ); const multimodalContent = googleOptions == null ? void 0 : googleOptions.content; if (multimodalContent != null && multimodalContent.length !== values.length) { throw new Error( `The number of multimodal content entries (${multimodalContent.length}) must match the number of values (${values.length}).` ); } if (values.length === 1) { const valueParts = multimodalContent == null ? void 0 : multimodalContent[0]; const textPart = values[0] ? [{ text: values[0] }] : []; const parts = valueParts != null ? [...textPart, ...valueParts] : [{ text: values[0] }]; const { responseHeaders: responseHeaders2, value: response2, rawValue: rawValue2 } = await chunkOCS2GTEN_cjs.postJsonToApi({ url: `${this.config.baseURL}/models/${this.modelId}:embedContent`, headers: mergedHeaders, body: { model: `models/${this.modelId}`, content: { parts }, outputDimensionality: googleOptions == null ? void 0 : googleOptions.outputDimensionality, taskType: googleOptions == null ? void 0 : googleOptions.taskType }, failedResponseHandler: googleFailedResponseHandler, successfulResponseHandler: chunkOCS2GTEN_cjs.createJsonResponseHandler( googleGenerativeAISingleEmbeddingResponseSchema ), abortSignal, fetch: this.config.fetch }); return { embeddings: [response2.embedding.values], usage: void 0, response: { headers: responseHeaders2, body: rawValue2 } }; } const { responseHeaders, value: response, rawValue } = await chunkOCS2GTEN_cjs.postJsonToApi({ url: `${this.config.baseURL}/models/${this.modelId}:batchEmbedContents`, headers: mergedHeaders, body: { requests: values.map((value, index) => { const valueParts = multimodalContent == null ? void 0 : multimodalContent[index]; const textPart = value ? [{ text: value }] : []; return { model: `models/${this.modelId}`, content: { role: "user", parts: valueParts != null ? [...textPart, ...valueParts] : [{ text: value }] }, outputDimensionality: googleOptions == null ? void 0 : googleOptions.outputDimensionality, taskType: googleOptions == null ? void 0 : googleOptions.taskType }; }) }, failedResponseHandler: googleFailedResponseHandler, successfulResponseHandler: chunkOCS2GTEN_cjs.createJsonResponseHandler( googleGenerativeAITextEmbeddingResponseSchema ), abortSignal, fetch: this.config.fetch }); return { embeddings: response.embeddings.map((item) => item.values), usage: void 0, response: { headers: responseHeaders, body: rawValue } }; } }; var googleGenerativeAITextEmbeddingResponseSchema = chunkOCS2GTEN_cjs.lazySchema( () => chunkOCS2GTEN_cjs.zodSchema( v4.z.object({ embeddings: v4.z.array(v4.z.object({ values: v4.z.array(v4.z.number()) })) }) ) ); var googleGenerativeAISingleEmbeddingResponseSchema = chunkOCS2GTEN_cjs.lazySchema( () => chunkOCS2GTEN_cjs.zodSchema( v4.z.object({ embedding: v4.z.object({ values: v4.z.array(v4.z.number()) }) }) ) ); function convertJSONSchemaToOpenAPISchema(jsonSchema, isRoot = true) { if (jsonSchema == null) { return void 0; } if (isEmptyObjectSchema(jsonSchema)) { if (isRoot) { return void 0; } if (typeof jsonSchema === "object" && jsonSchema.description) { return { type: "object", description: jsonSchema.description }; } return { type: "object" }; } if (typeof jsonSchema === "boolean") { return { type: "boolean", properties: {} }; } const { type, description, required, properties, items, allOf, anyOf, oneOf, format, const: constValue, minLength, enum: enumValues } = jsonSchema; const result = {}; if (description) result.description = description; if (required) result.required = required; if (format) result.format = format; if (constValue !== void 0) { result.enum = [constValue]; } if (type) { if (Array.isArray(type)) { const hasNull = type.includes("null"); const nonNullTypes = type.filter((t) => t !== "null"); if (nonNullTypes.length === 0) { result.type = "null"; } else { result.anyOf = nonNullTypes.map((t) => ({ type: t })); if (hasNull) { result.nullable = true; } } } else { result.type = type; } } if (enumValues !== void 0) { result.enum = enumValues; } if (properties != null) { result.properties = Object.entries(properties).reduce( (acc, [key, value]) => { acc[key] = convertJSONSchemaToOpenAPISchema(value, false); return acc; }, {} ); } if (items) { result.items = Array.isArray(items) ? items.map((item) => convertJSONSchemaToOpenAPISchema(item, false)) : convertJSONSchemaToOpenAPISchema(items, false); } if (allOf) { result.allOf = allOf.map( (item) => convertJSONSchemaToOpenAPISchema(item, false) ); } if (anyOf) { if (anyOf.some( (schema) => typeof schema === "object" && (schema == null ? void 0 : schema.type) === "null" )) { const nonNullSchemas = anyOf.filter( (schema) => !(typeof schema === "object" && (schema == null ? void 0 : schema.type) === "null") ); if (nonNullSchemas.length === 1) { const converted = convertJSONSchemaToOpenAPISchema( nonNullSchemas[0], false ); if (typeof converted === "object") { result.nullable = true; Object.assign(result, converted); } } else { result.anyOf = nonNullSchemas.map( (item) => convertJSONSchemaToOpenAPISchema(item, false) ); result.nullable = true; } } else { result.anyOf = anyOf.map( (item) => convertJSONSchemaToOpenAPISchema(item, false) ); } } if (oneOf) { result.oneOf = oneOf.map( (item) => convertJSONSchemaToOpenAPISchema(item, false) ); } if (minLength !== void 0) { result.minLength = minLength; } return result; } function isEmptyObjectSchema(jsonSchema) { return jsonSchema != null && typeof jsonSchema === "object" && jsonSchema.type === "object" && (jsonSchema.properties == null || Object.keys(jsonSchema.properties).length === 0) && !jsonSchema.additionalProperties; } function convertToGoogleGenerativeAIMessages(prompt, options) { var _a, _b; const systemInstructionParts = []; const contents = []; let systemMessagesAllowed = true; const isGemmaModel = (_a = options == null ? void 0 : options.isGemmaModel) != null ? _a : false; const supportsFunctionResponseParts = (_b = options == null ? void 0 : options.supportsFunctionResponseParts) != null ? _b : true; for (const { role, content } of prompt) { switch (role) { case "system": { if (!systemMessagesAllowed) { throw new chunkOCS2GTEN_cjs.UnsupportedFunctionalityError({ functionality: "system messages are only supported at the beginning of the conversation" }); } systemInstructionParts.push({ text: content }); break; } case "user": { systemMessagesAllowed = false; const parts = []; for (const part of content) { switch (part.type) { case "text": { parts.push({ text: part.text }); break; } case "file": { const mediaType = part.mediaType === "image/*" ? "image/jpeg" : part.mediaType; parts.push( part.data instanceof URL ? { fileData: { mimeType: mediaType, fileUri: part.data.toString() } } : { inlineData: { mimeType: mediaType, data: chunkOCS2GTEN_cjs.convertToBase64(part.data) } } ); break; } } } contents.push({ role: "user", parts }); break; } case "assistant": { systemMessagesAllowed = false; contents.push({ role: "model", parts: content.map((part) => { var _a2, _b2, _c; const thoughtSignature = ((_b2 = (_a2 = part.providerOptions) == null ? void 0 : _a2.google) == null ? void 0 : _b2.thoughtSignature) != null ? String((_c = part.providerOptions.google) == null ? void 0 : _c.thoughtSignature) : void 0; switch (part.type) { case "text": { return part.text.length === 0 ? void 0 : { text: part.text, thoughtSignature }; } case "reasoning": { return part.text.length === 0 ? void 0 : { text: part.text, thought: true, thoughtSignature }; } case "file": { if (part.mediaType !== "image/png") { throw new chunkOCS2GTEN_cjs.UnsupportedFunctionalityError({ functionality: "Only PNG images are supported in assistant messages" }); } if (part.data instanceof URL) { throw new chunkOCS2GTEN_cjs.UnsupportedFunctionalityError({ functionality: "File data URLs in assistant messages are not supported" }); } return { inlineData: { mimeType: part.mediaType, data: chunkOCS2GTEN_cjs.convertToBase64(part.data) } }; } case "tool-call": { return { functionCall: { name: part.toolName, args: part.input }, thoughtSignature }; } } }).filter((part) => part !== void 0) }); break; } case "tool": { systemMessagesAllowed = false; const parts = []; for (const part of content) { const output = part.output; if (output.type === "content") { if (supportsFunctionResponseParts) { appendToolResultParts({ parts, part, output }); } else { appendLegacyToolResultParts({ parts, part, output }); } } else { parts.push({ functionResponse: { name: part.toolName, response: { name: part.toolName, content: output.value } } }); } } contents.push({ role: "user", parts }); break; } } } if (isGemmaModel && systemInstructionParts.length > 0 && contents.length > 0 && contents[0].role === "user") { const systemText = systemInstructionParts.map((part) => part.text).join("\n\n"); contents[0].parts.unshift({ text: systemText + "\n\n" }); } return { systemInstruction: systemInstructionParts.length > 0 && !isGemmaModel ? { parts: systemInstructionParts } : void 0, contents }; } function appendToolResultParts({ parts, part, output }) { const responseTextParts = []; const functionResponseParts = []; for (const contentPart of output.value) { switch (contentPart.type) { case "text": responseTextParts.push(contentPart.text); break; case "media": functionResponseParts.push({ inlineData: { mimeType: contentPart.mediaType, data: contentPart.data } }); break; } } const responseText = responseTextParts.length > 0 ? responseTextParts.join("\n") : "Tool executed successfully."; parts.push({ functionResponse: { name: part.toolName, response: { name: part.toolName, content: responseText }, ...functionResponseParts.length > 0 ? { parts: functionResponseParts } : {} } }); } function appendLegacyToolResultParts({ parts, part, output }) { for (const contentPart of output.value) { switch (contentPart.type) { case "text": parts.push({ functionResponse: { name: part.toolName, response: { name: part.toolName, content: contentPart.text } } }); break; case "media": parts.push( { inlineData: { mimeType: contentPart.mediaType, data: contentPart.data } }, { text: "Tool executed successfully and returned this image as a response" } ); break; default: parts.push({ text: JSON.stringify(contentPart) }); break; } } } function getModelPath(modelId) { return modelId.includes("/") ? modelId : `models/${modelId}`; } var googleGenerativeAIProviderOptions = chunkOCS2GTEN_cjs.lazySchema( () => chunkOCS2GTEN_cjs.zodSchema( v4.z.object({ responseModalities: v4.z.array(v4.z.enum(["TEXT", "IMAGE"])).optional(), thinkingConfig: v4.z.object({ thinkingBudget: v4.z.number().optional(), includeThoughts: v4.z.boolean().optional(), // https://ai.google.dev/gemini-api/docs/gemini-3?thinking=high#thinking_level thinkingLevel: v4.z.enum(["minimal", "low", "medium", "high"]).optional() }).optional(), /** * Optional. * The name of the cached content used as context to serve the prediction. * Format: cachedContents/{cachedContent} */ cachedContent: v4.z.string().optional(), /** * Optional. Enable structured output. Default is true. * * This is useful when the JSON Schema contains elements that are * not supported by the OpenAPI schema version that * Google Generative AI uses. You can use this to disable * structured outputs if you need to. */ structuredOutputs: v4.z.boolean().optional(), /** * Optional. A list of unique safety settings for blocking unsafe content. */ safetySettings: v4.z.array( v4.z.object({ category: v4.z.enum([ "HARM_CATEGORY_UNSPECIFIED", "HARM_CATEGORY_HATE_SPEECH", "HARM_CATEGORY_DANGEROUS_CONTENT", "HARM_CATEGORY_HARASSMENT", "HARM_CATEGORY_SEXUALLY_EXPLICIT", "HARM_CATEGORY_CIVIC_INTEGRITY" ]), threshold: v4.z.enum([ "HARM_BLOCK_THRESHOLD_UNSPECIFIED", "BLOCK_LOW_AND_ABOVE", "BLOCK_MEDIUM_AND_ABOVE", "BLOCK_ONLY_HIGH", "BLOCK_NONE", "OFF" ]) }) ).optional(), threshold: v4.z.enum([ "HARM_BLOCK_THRESHOLD_UNSPECIFIED", "BLOCK_LOW_AND_ABOVE", "BLOCK_MEDIUM_AND_ABOVE", "BLOCK_ONLY_HIGH", "BLOCK_NONE", "OFF" ]).optional(), /** * Optional. Enables timestamp understanding for audio-only files. * * https://cloud.google.com/vertex-ai/generative-ai/docs/multimodal/audio-understanding */ audioTimestamp: v4.z.boolean().optional(), /** * Optional. Defines labels used in billing reports. Available on Vertex AI only. * * https://cloud.google.com/vertex-ai/generative-ai/docs/multimodal/add-labels-to-api-calls */ labels: v4.z.record(v4.z.string(), v4.z.string()).optional(), /** * Optional. If specified, the media resolution specified will be used. * * https://ai.google.dev/api/generate-content#MediaResolution */ mediaResolution: v4.z.enum([ "MEDIA_RESOLUTION_UNSPECIFIED", "MEDIA_RESOLUTION_LOW", "MEDIA_RESOLUTION_MEDIUM", "MEDIA_RESOLUTION_HIGH" ]).optional(), /** * Optional. Configures the image generation aspect ratio for Gemini models. * * https://ai.google.dev/gemini-api/docs/image-generation#aspect_ratios */ imageConfig: v4.z.object({ aspectRatio: v4.z.enum([ "1:1", "2:3", "3:2", "3:4", "4:3", "4:5", "5:4", "9:16", "16:9", "21:9", "1:8", "8:1", "1:4", "4:1" ]).optional(), imageSize: v4.z.enum(["1K", "2K", "4K", "512"]).optional() }).optional(), /** * Optional. Configuration for grounding retrieval. * Used to provide location context for Google Maps and Google Search grounding. * * https://cloud.google.com/vertex-ai/generative-ai/docs/grounding/grounding-with-google-maps */ retrievalConfig: v4.z.object({ latLng: v4.z.object({ latitude: v4.z.number(), longitude: v4.z.number() }).optional() }).optional(), /** * Optional. The service tier to use for the request. */ serviceTier: v4.z.enum(["standard", "flex", "priority"]).optional() }) ) ); var VertexServiceTierMap = { standard: "SERVICE_TIER_STANDARD", flex: "SERVICE_TIER_FLEX", priority: "SERVICE_TIER_PRIORITY" }; function prepareTools({ tools, toolChoice, modelId }) { var _a; tools = (tools == null ? void 0 : tools.length) ? tools : void 0; const toolWarnings = []; const isLatest = [ "gemini-flash-latest", "gemini-flash-lite-latest", "gemini-pro-latest" ].some((id) => id === modelId); const isGemini2orNewer = modelId.includes("gemini-2") || modelId.includes("gemini-3") || modelId.includes("nano-banana") || isLatest; const supportsFileSearch = modelId.includes("gemini-2.5") || modelId.includes("gemini-3"); if (tools == null) { return { tools: void 0, toolConfig: void 0, toolWarnings }; } const hasFunctionTools = tools.some((tool) => tool.type === "function"); const hasProviderDefinedTools = tools.some( (tool) => tool.type === "provider-defined" ); if (hasFunctionTools && hasProviderDefinedTools) { const functionTools = tools.filter((tool) => tool.type === "function"); toolWarnings.push({ type: "unsupported-tool", tool: tools.find((tool) => tool.type === "function"), details: `Cannot mix function tools with provider-defined tools in the same request. Falling back to provider-defined tools only. The following function tools will be ignored: ${functionTools.map((t) => t.name).join(", ")}. Please use either function tools or provider-defined tools, but not both.` }); } if (hasProviderDefinedTools) { const googleTools2 = []; const providerDefinedTools = tools.filter( (tool) => tool.type === "provider-defined" ); providerDefinedTools.forEach((tool) => { switch (tool.id) { case "google.google_search": if (isGemini2orNewer) { googleTools2.push({ googleSearch: { ...tool.args } }); } else { toolWarnings.push({ type: "unsupported-tool", tool, details: "Google Search requires Gemini 2.0 or newer." }); } break; case "google.enterprise_web_search": if (isGemini2orNewer) { googleTools2.push({ enterpriseWebSearch: {} }); } else { toolWarnings.push({ type: "unsupported-tool", tool, details: "Enterprise Web Search requires Gemini 2.0 or newer." }); } break; case "google.url_context": if (isGemini2orNewer) { googleTools2.push({ urlContext: {} }); } else { toolWarnings.push({ type: "unsupported-tool", tool, details: "The URL context tool is not supported with other Gemini models than Gemini 2." }); } break; case "google.code_execution": if (isGemini2orNewer) { googleTools2.push({ codeExecution: {} }); } else { toolWarnings.push({ type: "unsupported-tool", tool, details: "The code execution tools is not supported with other Gemini models than Gemini 2." }); } break; case "google.file_search": if (supportsFileSearch) { googleTools2.push({ fileSearch: { ...tool.args } }); } else { toolWarnings.push({ type: "unsupported-tool", tool, details: "The file search tool is only supported with Gemini 2.5 models." }); } break; case "google.vertex_rag_store": if (isGemini2orNewer) { googleTools2.push({ retrieval: { vertex_rag_store: { rag_resources: { rag_corpus: tool.args.ragCorpus }, similarity_top_k: tool.args.topK } } }); } else { toolWarnings.push({ type: "unsupported-tool", tool, details: "The RAG store tool is not supported with other Gemini models than Gemini 2." }); } break; case "google.google_maps": if (isGemini2orNewer) { googleTools2.push({ googleMaps: {} }); } else { toolWarnings.push({ type: "unsupported-tool", tool, details: "The Google Maps grounding tool is not supported with Gemini models other than Gemini 2 or newer." }); } break; default: toolWarnings.push({ type: "unsupported-tool", tool }); break; } }); return { tools: googleTools2.length > 0 ? googleTools2 : void 0, toolConfig: void 0, toolWarnings }; } const functionDeclarations = []; let hasStrictTools = false; for (const tool of tools) { switch (tool.type) { case "function": functionDeclarations.push({ name: tool.name, description: (_a = tool.description) != null ? _a : "", parameters: convertJSONSchemaToOpenAPISchema(tool.inputSchema) }); if (tool.strict === true) { hasStrictTools = true; } break; default: toolWarnings.push({ type: "unsupported-tool", tool }); break; } } if (toolChoice == null) { return { tools: [{ functionDeclarations }], toolConfig: hasStrictTools ? { functionCallingConfig: { mode: "VALIDATED" } } : void 0, toolWarnings }; } const type = toolChoice.type; switch (type) { case "auto": return { tools: [{ functionDeclarations }], toolConfig: { functionCallingConfig: { mode: hasStrictTools ? "VALIDATED" : "AUTO" } }, toolWarnings }; case "none": return { tools: [{ functionDeclarations }], toolConfig: { functionCallingConfig: { mode: "NONE" } }, toolWarnings }; case "required": return { tools: [{ functionDeclarations }], toolConfig: { functionCallingConfig: { mode: hasStrictTools ? "VALIDATED" : "ANY" } }, toolWarnings }; case "tool": return { tools: [{ functionDeclarations }], toolConfig: { functionCallingConfig: { mode: hasStrictTools ? "VALIDATED" : "ANY", allowedFunctionNames: [toolChoice.toolName] } }, toolWarnings }; default: { const _exhaustiveCheck = type; throw new chunkOCS2GTEN_cjs.UnsupportedFunctionalityError({ functionality: `tool choice type: ${_exhaustiveCheck}` }); } } } function mapGoogleGenerativeAIFinishReason({ finishReason, hasToolCalls }) { switch (finishReason) { case "STOP": return hasToolCalls ? "tool-calls" : "stop"; case "MAX_TOKENS": return "length"; case "IMAGE_SAFETY": case "RECITATION": case "SAFETY": case "BLOCKLIST": case "PROHIBITED_CONTENT": case "SPII": return "content-filter"; case "FINISH_REASON_UNSPECIFIED": case "OTHER": return "other"; case "MALFORMED_FUNCTION_CALL": return "error"; default: return "unknown"; } } var GoogleGenerativeAILanguageModel = class { constructor(modelId, config) { this.specificationVersion = "v2"; var _a; this.modelId = modelId; this.config = config; this.generateId = (_a = config.generateId) != null ? _a : chunkOCS2GTEN_cjs.generateId; } get provider() { return this.config.provider; } get supportedUrls() { var _a, _b, _c; return (_c = (_b = (_a = this.config).supportedUrls) == null ? void 0 : _b.call(_a)) != null ? _c : {}; } async getArgs({ prompt, maxOutputTokens, temperature, topP, topK, frequencyPenalty, presencePenalty, stopSequences, responseFormat, seed, tools, toolChoice, providerOptions }) { var _a; const warnings = []; const googleOptions = await chunkOCS2GTEN_cjs.parseProviderOptions({ provider: "google", providerOptions, schema: googleGenerativeAIProviderOptions }); const isVertexProvider = this.config.provider.startsWith("google.vertex."); if ((tools == null ? void 0 : tools.some( (tool) => tool.type === "provider-defined" && tool.id === "google.vertex_rag_store" )) && !isVertexProvider) { warnings.push({ type: "other", message: `The 'vertex_rag_store' tool is only supported with the Google Vertex provider and might not be supported or could behave unexpectedly with the current Google provider (${this.config.provider}).` }); } let sanitizedServiceTier = googleOptions == null ? void 0 : googleOptions.serviceTier; if ((googleOptions == null ? void 0 : googleOptions.serviceTier) && isVertexProvider) { sanitizedServiceTier = VertexServiceTierMap[googleOptions.serviceTier]; } const isGemmaModel = this.modelId.toLowerCase().startsWith("gemma-"); const supportsFunctionResponseParts = this.modelId.startsWith("gemini-3"); const { contents, systemInstruction } = convertToGoogleGenerativeAIMessages( prompt, { isGemmaModel, supportsFunctionResponseParts } ); const { tools: googleTools2, toolConfig: googleToolConfig, toolWarnings } = prepareTools({ tools, toolChoice, modelId: this.modelId }); return { args: { generationConfig: { // standardized settings: maxOutputTokens, temperature, topK, topP, frequencyPenalty, presencePenalty, stopSequences, seed, // response format: responseMimeType: (responseFormat == null ? void 0 : responseFormat.type) === "json" ? "application/json" : void 0, responseSchema: (responseFormat == null ? void 0 : responseFormat.type) === "json" && responseFormat.schema != null && // Google GenAI does not support all OpenAPI Schema features, // so this is needed as an escape hatch: // TODO convert into provider option ((_a = googleOptions == null ? void 0 : googleOptions.structuredOutputs) != null ? _a : true) ? convertJSONSchemaToOpenAPISchema(responseFormat.schema) : void 0, ...(googleOptions == null ? void 0 : googleOptions.audioTimestamp) && { audioTimestamp: googleOptions.audioTimestamp }, // provider options: responseModalities: googleOptions == null ? void 0 : googleOptions.responseModalities, thinkingConfig: googleOptions == null ? void 0 : googleOptions.thinkingConfig, ...(googleOptions == null ? void 0 : googleOptions.imageConfig) && { imageConfig: googleOptions.imageConfig }, ...(googleOptions == null ? void 0 : googleOptions.mediaResolution) && { mediaResolution: googleOptions.mediaResolution } }, contents, systemInstruction: isGemmaModel ? void 0 : systemInstruction, safetySettings: googleOptions == null ? void 0 : googleOptions.safetySettings, tools: googleTools2, toolConfig: (googleOptions == null ? void 0 : googleOptions.retrievalConfig) ? { ...googleToolConfig, retrievalConfig: googleOptions.retrievalConfig } : googleToolConfig, cachedContent: googleOptions == null ? void 0 : googleOptions.cachedContent, labels: googleOptions == null ? void 0 : googleOptions.labels, serviceTier: sanitizedServiceTier }, warnings: [...warnings, ...toolWarnings] }; } async doGenerate(options) { var _a, _b, _c, _d, _e, _f, _g, _h, _i, _j, _k, _l, _m, _n; const { args, warnings } = await this.getArgs(options); const body = JSON.stringify(args); const mergedHeaders = chunkOCS2GTEN_cjs.combineHeaders( await chunkOCS2GTEN_cjs.resolve(this.config.headers), options.headers ); const { responseHeaders, value: response, rawValue: rawResponse } = await chunkOCS2GTEN_cjs.postJsonToApi({ url: `${this.config.baseURL}/${getModelPath( this.modelId )}:generateContent`, headers: mergedHeaders, body: args, failedResponseHandler: googleFailedResponseHandler, successfulResponseHandler: chunkOCS2GTEN_cjs.createJsonResponseHandler(responseSchema), abortSignal: options.abortSignal, fetch: this.config.fetch }); const candidate = response.candidates[0]; const content = []; const parts = (_b = (_a = candidate.content) == null ? void 0 : _a.parts) != null ? _b : []; const usageMetadata = response.usageMetadata; let lastCodeExecutionToolCallId; for (const part of parts) { if ("executableCode" in part && ((_c = part.executableCode) == null ? void 0 : _c.code)) { const toolCallId = this.config.generateId(); lastCodeExecutionToolCallId = toolCallId; content.push({ type: "tool-call", toolCallId, toolName: "code_execution", input: JSON.stringify(part.executableCode), providerExecuted: true }); } else if ("codeExecutionResult" in part && part.codeExecutionResult) { content.push({ type: "tool-result", // Assumes a result directly follows its corresponding call part. toolCallId: lastCodeExecutionToolCallId, toolName: "code_execution", result: { outcome: part.codeExecutionResult.outcome, output: part.codeExecutionResult.output }, providerExecuted: true }); lastCodeExecutionToolCallId = void 0; } else if ("text" in part && part.text != null) { const thoughtSignatureMetadata = part.thoughtSignature ? { google: { thoughtSignature: part.thoughtSignature } } : void 0; if (part.text.length === 0) { if (thoughtSignatureMetadata != null && content.length > 0) { const lastContent = content[content.length - 1]; if (lastContent.type !== "file") { lastContent.providerMetadata = thoughtSignatureMetadata; } } } else { content.push({ type: part.thought === true ? "reasoning" : "text", text: part.text, providerMetadata: thoughtSignatureMetadata }); } } else if ("functionCall" in part) { content.push({ type: "tool-call", toolCallId: this.config.generateId(), toolName: part.functionCall.name, input: JSON.stringify(part.functionCall.args), providerMetadata: part.thoughtSignature ? { google: { thoughtSignature: part.thoughtSignature } } : void 0 }); } else if ("inlineData" in part) { content.push({ type: "file", data: part.inlineData.data, mediaType: part.inlineData.mimeType }); } } const sources = (_d = extractSources({ groundingMetadata: candidate.groundingMetadata, generateId: this.config.generateId })) != null ? _d : []; for (const source of sources) { content.push(source); } return { content, finishReason: mapGoogleGenerativeAIFinishReason({ finishReason: candidate.finishReason, hasToolCalls: content.some((part) => part.type === "tool-call") }), usage: { inputTokens: (_e = usageMetadata == null ? void 0 : usageMetadata.promptTokenCount) != null ? _e : void 0, outputTokens: (_f = usageMetadata == null ? void 0 : usageMetadata.candidatesTokenCount) != null ? _f : void 0, totalTokens: (_g = usageMetadata == null ? void 0 : usageMetadata.totalTokenCount) != null ? _g : void 0, reasoningTokens: (_h = usageMetadata == null ? void 0 : usageMetadata.thoughtsTokenCount) != null ? _h : void 0, cachedInputTokens: (_i = usageMetadata == null ? void 0 : usageMetadata.cachedContentTokenCount) != null ? _i : void 0 }, warnings, providerMetadata: { google: { promptFeedback: (_j = response.promptFeedback) != null ? _j : null, groundingMetadata: (_k = candidate.groundingMetadata) != null ? _k : null, urlContextMetadata: (_l = candidate.urlContextMetadata) != null ? _l : null, safetyRatings: (_m = candidate.safetyRatings) != null ? _m : null, serviceTier: (_n = response.serviceTier) != null ? _n : null } }, request: { body }, response: { // TODO timestamp, model id, id headers: responseHeaders, body: rawResponse } }; } async doStream(options) { const { args, warnings } = await this.getArgs(options); const body = JSON.stringify(args); const headers = chunkOCS2GTEN_cjs.combineHeaders( await chunkOCS2GTEN_cjs.resolve(this.config.headers), options.headers ); const { responseHeaders, value: response } = await chunkOCS2GTEN_cjs.postJsonToApi({ url: `${this.config.baseURL}/${getModelPath( this.modelId )}:streamGenerateContent?alt=sse`, headers, body: args, failedResponseHandler: googleFailedResponseHandler, successfulResponseHandler: chunkOCS2GTEN_cjs.createEventSourceResponseHandler(chunkSchema), abortSignal: options.abortSignal, fetch: this.config.fetch }); let finishReason = "unknown"; const usage = { inputTokens: void 0, outputTokens: void 0, totalTokens: void 0 }; let providerMetadata = void 0; let lastGroundingMetadata = null; let lastUrlContextMetadata = null; let serviceTier = null; const generateId3 = this.config.generateId; let hasToolCalls = false; let currentTextBlockId = null; let currentReasoningBlockId = null; let blockCounter = 0; const emittedSourceUrls = /* @__PURE__ */ new Set(); let lastCodeExecutionToolCallId; return { stream: response.pipeThrough( new TransformStream({ start(controller) { controller.enqueue({ type: "stream-start", warnings }); }, transform(chunk, controller) { var _a, _b, _c, _d, _e, _f, _g, _h, _i, _j; if (options.includeRawChunks) { controller.enqueue({ type: "raw", rawValue: chunk.rawValue }); } if (!chunk.success) { controller.enqueue({ type: "error", error: chunk.error }); return; } const value = chunk.value; const usageMetadata = value.usageMetadata; if (usageMetadata != null) { usage.inputTokens = (_a = usageMetadata.promptTokenCount) != null ? _a : void 0; usage.outputTokens = (_b = usageMetadata.candidatesTokenCount) != null ? _b : void 0; usage.totalTokens = (_c = usageMetadata.totalTokenCount) != null ? _c : void 0; usage.reasoningTokens = (_d = usageMetadata.thoughtsTokenCount) != null ? _d : void 0; usage.cachedInputTokens = (_e = usageMetadata.cachedContentTokenCount) != null ? _e : void 0; } if (value.serviceTier != null) { serviceTier = value.serviceTier; } const candidate = (_f = value.candidates) == null ? void 0 : _f[0]; if (candidate == null) { return; } const content = candidate.content; if (candidate.groundingMetadata != null) { lastGroundingMetadata = candidate.groundingMetadata; } if (candidate.urlContextMetadata != null) { lastUrlContextMetadata = candidate.urlContextMetadata; } const sources = extractSources({ groundingMetadata: candidate.groundingMetadata, generateId: generateId3 }); if (sources != null) { for (const source of sources) { if (source.sourceType === "url" && !emittedSourceUrls.has(source.url)) { emittedSourceUrls.add(source.url); controller.enqueue(source); } } } if (content != null) { const parts = (_g = content.parts) != null ? _g : []; for (const part of parts) { if ("executableCode" in part && ((_h = part.executableCode) == null ? void 0 : _h.code)) { const toolCallId = generateId3(); lastCodeExecutionToolCallId = toolCallId; controller.enqueue({ type: "tool-call", toolCallId, toolName: "code_execution", input: JSON.stringify(part.executableCode), providerExecuted: true }); hasToolCalls = true; } else if ("codeExecutionResult" in part && part.codeExecutionResult) { const toolCallId = lastCodeExecutionToolCallId; if (toolCallId) { controller.enqueue({ type: "tool-result", toolCallId, toolName: "code_execution", result: { outcome: part.codeExecutionResult.outcome, output: part.codeExecutionResult.output }, providerExecuted: true }); lastCodeExecutionToolCallId = void 0; } } else if ("text" in part && part.text != null) { const thoughtSignatureMetadata = part.thoughtSignature ? { google: { thoughtSignature: part.thoughtSignature } } : void 0; if (part.text.length === 0) { if (thoughtSignatureMetadata != null && currentTextBlockId !== null) { controller.enqueue({ type: "text-delta", id: currentTextBlockId, delta: "", providerMetadata: thoughtSignatureMetadata }); } } else if (part.thought === true) { if (currentTextBlockId !== null) { controller.enqueue({ type: "text-end", id: currentTextBlockId }); currentTextBlockId = null; } if (currentReasoningBlockId === null) { currentReasoningBlockId = String(blockCounter++); controller.enqueue({ type: "reasoning-start", id: currentReasoningBlockId, providerMetadata: thoughtSignatureMetadata }); } controller.enqueue({ type: "reasoning-delta", id: currentReasoningBlockId, delta: part.text, providerMetadata: thoughtSignatureMetadata }); } else { if (currentReasoningBlockId !== null) { controller.enqueue({ type: "reasoning-end", id: currentReasoningBlockId }); currentReasoningBlockId = null; } if (currentTextBlockId === null) { currentTextBlockId = String(blockCounter++); controller.enqueue({ type: "text-start", id: currentTextBlockId, providerMetadata: thoughtSignatureMetadata }); } controller.enqueue({ type: "text-delta", id: currentTextBlockId, delta: part.text, providerMetadata: thoughtSignatureMetadata }); } } else if ("inlineData" in part) { controller.enqueue({ type: "file", mediaType: part.inlineData.mimeType, data: part.inlineData.data }); } } const toolCallDeltas = getToolCallsFromParts({ parts: content.parts, generateId: generateId3 }); if (toolCallDeltas != null) { for (const toolCall of toolCallDeltas) { controller.enqueue({ type: "tool-input-start", id: toolCall.toolCallId, toolName: toolCall.toolName, providerMetadata: toolCall.providerMetadata }); controller.enqueue({ type: "tool-input-delta", id: toolCall.toolCallId, delta: toolCall.args, providerMetadata: toolCall.providerMetadata }); controller.enqueue({ type: "tool-input-end", id: toolCall.toolCallId, providerMetadata: toolCall.providerMetadata }); controller.enqueue({ type: "tool-call", toolCallId: toolCall.toolCallId, toolName: toolCall.toolName, input: toolCall.args, providerMetadata: toolCall.providerMetadata }); hasToolCalls = true; } } } if (candidate.finishReason != null) { finishReason = mapGoogleGenerativeAIFinishReason({ finishReason: candidate.finishReason, hasToolCalls }); providerMetadata = { google: { promptFeedback: (_i = value.promptFeedback) != null ? _i : null, groundingMetadata: lastGroundingMetadata, urlContextMetadata: lastUrlContextMetadata, safetyRatings: (_j = candidate.safetyRatings) != null ? _j : null, serviceTier } }; if (usageMetadata != null) { providerMetadata.google.usageMetadata = usageMetadata; } } }, flush(controller) { if (currentTextBlockId !== null) { controller.enqueue({ type: "text-end", id: currentTextBlockId }); } if (currentReasoningBlockId !== null) { controller.enqueue({ type: "reasoning-end", id: currentReasoningBlockId }); } controller.enqueue({ type: "finish", finishReason, usage, providerMetadata }); } }) ), response: { headers: responseHeaders }, request: { body } }; } }; function getToolCallsFromParts({ parts, generateId: generateId3 }) { const functionCallParts = parts == null ? void 0 : parts.filter( (part) => "functionCall" in part ); return functionCallParts == null || functionCallParts.length === 0 ? void 0 : functionCallParts.map((part) => ({ type: "tool-call", toolCallId: generateId3(), toolName: part.functionCall.name, args: JSON.stringify(part.functionCall.args), providerMetadata: part.thoughtSignature ? { google: { thoughtSignature: part.thoughtSignature } } : void 0 })); } function extractSources({ groundingMetadata, generateId: generateId3 }) { var _a, _b, _c, _d, _e, _f; if (!(groundingMetadata == null ? void 0 : groundingMetadata.groundingChunks)) { return void 0; } const sources = []; for (const chunk of groundingMetadata.groundingChunks) { if (chunk.web != null) { sources.push({ type: "source", sourceType: "url", id: generateId3(), url: chunk.web.uri, title: (_a = chunk.web.title) != null ? _a : void 0 }); } else if (chunk.image != null) { sources.push({ type: "source", sourceType: "url", id: generateId3(), // Google requires attribution to the source URI, not the actual image URI. // TODO: add another type in v7 to allow both the image and source URL to be included separately url: chunk.image.sourceUri, title: (_b = chunk.image.title) != null ? _b : void 0 }); } else if (chunk.retrievedContext != null) { const uri = chunk.retrievedContext.uri; const fileSearchStore = chunk.retrievedContext.fileSearchStore; if (uri && (uri.startsWith("http://") || uri.startsWith("https://"))) { sources.push({ type: "source", sourceType: "url", id: generateId3(), url: uri, title: (_c = chunk.retrievedContext.title) != null ? _c : void 0 }); } else if (uri) { const title = (_d = chunk.retrievedContext.title) != null ? _d : "Unknown Document"; let mediaType = "application/octet-stream"; let filename = void 0; if (uri.endsWith(".pdf")) { mediaType = "application/pdf"; filename = uri.split("/").pop(); } else if (uri.endsWith(".txt")) { mediaType = "text/plain"; filename = uri.split("/").pop(); } else if (uri.endsWith(".docx")) { mediaType = "application/vnd.openxmlformats-officedocument.wordprocessingml.document"; filename = uri.split("/").pop(); } else if (uri.endsWith(".doc")) { mediaType = "application/msword"; filename = uri.split("/").pop(); } else if (uri.match(/\.(md|markdown)$/)) { mediaType = "text/markdown"; filename = uri.split("/").pop(); } else { filename = uri.split("/").pop(); } sources.push({ type: "source", sourceType: "document", id: generateId3(), mediaType, title, filename }); } else if (fileSearchStore) { const title = (_e = chunk.retrievedContext.title) != null ? _e : "Unknown Document"; sources.push({ type: "source", sourceType: "document", id: generateId3(), mediaType: "application/octet-stream", title, filename: fileSearchStore.split("/").pop() }); } } else if (chunk.maps != null) { if (chunk.maps.uri) { sources.push({ type: "source", sourceType: "url", id: generateId3(), url: chunk.maps.uri, title: (_f = chunk.maps.title) != null ? _f : void 0 }); } } } return sources.length > 0 ? sources : void 0; } var getGroundingMetadataSchema = () => v4.z.object({ webSearchQueries: v4.z.array(v4.z.string()).nullish(), imageSearchQueries: v4.z.array(v4.z.string()).nullish(), retrievalQueries: v4.z.array(v4.z.string()).nullish(), searchEntryPoint: v4.z.object({ renderedContent: v4.z.string() }).nullish(), groundingChunks: v4.z.array( v4.z.object({ web: v4.z.object({ uri: v4.z.string(), title: v4.z.string().nullish() }).nullish(), image: v4.z.object({ sourceUri: v4.z.string(), imageUri: v4.z.string(), title: v4.z.string().nullish(), domain: v4.z.string().nullish() }).nullish(), retrievedContext: v4.z.object({ uri: v4.z.string().nullish(), title: v4.z.string().nullish(), text: v4.z.string().nullish(), fileSearchStore: v4.z.string().nullish() }).nullish(), maps: v4.z.object({ uri: v4.z.string().nullish(), title: v4.z.string().nullish(), text: v4.z.string().nullish(), placeId: v4.z.string().nullish() }).nullish() }) ).nullish(), groundingSupports: v4.z.array( v4.z.object({ segment: v4.z.object({ startIndex: v4.z.number().nullish(), endIndex: v4.z.number().nullish(), text: v4.z.string().nullish() }).nullish(), segment_text: v4.z.string().nullish(), groundingChunkIndices: v4.z.array(v4.z.number()).nullish(), supportChunkIndices: v4.z.array(v4.z.number()).nullish(), confidenceScores: v4.z.array(v4.z.number()).nullish(), confidenceScore: v4.z.array(v4.z.number()).nullish() }) ).nullish(), retrievalMetadata: v4.z.union([ v4.z.object({ webDynamicRetrievalScore: v4.z.number() }), v4.z.object({}) ]).nullish() }); var getContentSchema = () => v4.z.object({ parts: v4.z.array( v4.z.union([ // note: order matters since text can be fully empty v4.z.object({ functionCall: v4.z.object({ name: v4.z.string(), args: v4.z.unknown() }), thoughtSignature: v4.z.string().nullish() }), v4.z.object({ inlineData: v4.z.object({ mimeType: v4.z.string(), data: v4.z.string() }) }), v4.z.object({ executableCode: v4.z.object({ language: v4.z.string(), code: v4.z.string() }).nullish(), codeExecutionResult: v4.z.object({ outcome: v4.z.string(), output: v4.z.string() }).nullish(), text: v4.z.string().nullish(), thought: v4.z.boolean().nullish(), thoughtSignature: v4.z.string().nullish() }) ]) ).nullish() }); var getSafetyRatingSchema = () => v4.z.object({ category: v4.z.string().nullish(), probability: v4.z.string().nullish(), probabilityScore: v4.z.number().nullish(), severity: v4.z.string().nullish(), severityScore: v4.z.number().nullish(), blocked: v4.z.boolean().nullish() }); var tokenDetailsSchema = v4.z.array( v4.z.object({ modality: v4.z.string(), tokenCount: v4.z.number() }) ).nullish(); var usageSchema = v4.z.object({ cachedContentTokenCount: v4.z.number().nullish(), thoughtsTokenCount: v4.z.number().nullish(), promptTokenCount: v4.z.number().nullish(), candidatesTokenCount: v4.z.number().nullish(), totalTokenCount: v4.z.number().nullish(), // https://cloud.google.com/vertex-ai/generative-ai/docs/reference/rest/v1/GenerateContentResponse#TrafficType trafficType: v4.z.string().nullish(), // https://ai.google.dev/api/generate-content#Modality promptTokensDetails: tokenDetailsSchema, candidatesTokensDetails: tokenDetailsSchema }); var getUrlContextMetadataSchema = () => v4.z.object({ urlMetadata: v4.z.array( v4.z.object({ retrievedUrl: v4.z.string(), urlRetrievalStatus: v4.z.string() }) ) }); var responseSchema = chunkOCS2GTEN_cjs.lazySchema( () => chunkOCS2GTEN_cjs.zodSchema( v4.z.object({ candidates: v4.z.array( v4.z.object({ content: getContentSchema().nullish().or(v4.z.object({}).strict()), finishReason: v4.z.string().nullish(), safetyRatings: v4.z.array(getSafetyRatingSchema()).nullish(), groundingMetadata: getGroundingMetadataSchema().nullish(), urlContextMetadata: getUrlContextMetadataSchema().nullish() }) ), usageMetadata: usageSchema.nullish(), promptFeedback: v4.z.object({ blockReason: v4.z.string().nullish(), safetyRatings: v4.z.array(getSafetyRatingSchema()).nullish() }).nullish(), serviceTier: v4.z.string().nullish() }) ) ); var chunkSchema = chunkOCS2GTEN_cjs.lazySchema( () => chunkOCS2GTEN_cjs.zodSchema( v4.z.object({ candidates: v4.z.array( v4.z.object({ content: getContentSchema().nullish(), finishReason: v4.z.string().nullish(), safetyRatings: v4.z.array(getSafetyRatingSchema()).nullish(), groundingMetadata: getGroundingMetadataSchema().nullish(), urlContextMetadata: getUrlContextMetadataSchema().nullish() }) ).nullish(), usageMetadata: usageSchema.nullish(), promptFeedback: v4.z.object({ blockReason: v4.z.string().nullish(), safetyRatings: v4.z.array(getSafetyRatingSchema()).nullish() }).nullish(), serviceTier: v4.z.string().nullish() }) ) ); var codeExecution = chunkOCS2GTEN_cjs.createProviderDefinedToolFactoryWithOutputSchema({ id: "google.code_execution", name: "code_execution", inputSchema: v4.z.object({ language: v4.z.string().describe("The programming language of the code."), code: v4.z.string().describe("The code to be executed.") }), outputSchema: v4.z.object({ outcome: v4.z.string().describe('The outcome of the execution (e.g., "OUTCOME_OK").'), output: v4.z.string().describe("The output from the code execution.") }) }); var enterpriseWebSearch = chunkOCS2GTEN_cjs.createProviderDefinedToolFactory({ id: "google.enterprise_web_search", name: "enterprise_web_search", inputSchema: chunkOCS2GTEN_cjs.lazySchema(() => chunkOCS2GTEN_cjs.zodSchema(v4.z.object({}))) }); var fileSearchArgsBaseSchema = v4.z.object({ /** The names of the file_search_stores to retrieve from. * Example: `fileSearchStores/my-file-search-store-123` */ fileSearchStoreNames: v4.z.array(v4.z.string()).describe( "The names of the file_search_stores to retrieve from. Example: `fileSearchStores/my-file-search-store-123`" ), /** The number of file search retrieval chunks to retrieve. */ topK: v4.z.number().int().positive().describe("The number of file search retrieval chunks to retrieve.").optional(), /** Metadata filter to apply to the file search retrieval documents. * See https://google.aip.dev/160 for the syntax of the filter expression. */ metadataFilter: v4.z.string().describe( "Metadata filter to apply to the file search retrieval documents. See https://google.aip.dev/160 for the syntax of the filter expression." ).optional() }).passthrough(); var fileSearchArgsSchema = chunkOCS2GTEN_cjs.lazySchema( () => chunkOCS2GTEN_cjs.zodSchema(fileSearchArgsBaseSchema) ); var fileSearch = chunkOCS2GTEN_cjs.createProviderDefinedToolFactory({ id: "google.file_search", name: "file_search", inputSchema: fileSearchArgsSchema }); var googleMaps = chunkOCS2GTEN_cjs.createProviderDefinedToolFactory({ id: "google.google_maps", name: "google_maps", inputSchema: chunkOCS2GTEN_cjs.lazySchema(() => chunkOCS2GTEN_cjs.zodSchema(v4.z.object({}))) }); var googleSearchToolArgsBaseSchema = v4.z.object({ searchTypes: v4.z.object({ webSearch: v4.z.object({}).optional(), imageSearch: v4.z.object({}).optional() }).optional(), timeRangeFilter: v4.z.object({ startTime: v4.z.string(), endTime: v4.z.string() }).optional() }).passthrough(); var googleSearchToolArgsSchema = chunkOCS2GTEN_cjs.lazySchema( () => chunkOCS2GTEN_cjs.zodSchema(googleSearchToolArgsBaseSchema) ); var googleSearch = chunkOCS2GTEN_cjs.createProviderDefinedToolFactory({ id: "google.google_search", name: "google_search", inputSchema: googleSearchToolArgsSchema }); var urlContext = chunkOCS2GTEN_cjs.createProviderDefinedToolFactory({ id: "google.url_context", name: "url_context", inputSchema: chunkOCS2GTEN_cjs.lazySchema(() => chunkOCS2GTEN_cjs.zodSchema(v4.z.object({}))) }); var vertexRagStore = chunkOCS2GTEN_cjs.createProviderDefinedToolFactory({ id: "google.vertex_rag_store", name: "vertex_rag_store", inputSchema: v4.z.object({ ragCorpus: v4.z.string(), topK: v4.z.number().optional() }) }); var googleTools = { /** * Creates a Google search tool that gives Google direct access to real-time web content. * Must have name "google_search". */ googleSearch, /** * Creates an Enterprise Web Search tool for grounding responses using a compliance-focused web index. * Designed for highly-regulated industries (finance, healthcare, public sector). * Does not log customer data and supports VPC service controls. * Must have name "enterprise_web_search". * * @note Only available on Vertex AI. Requires Gemini 2.0 or newer. * * @see https://cloud.google.com/vertex-ai/generative-ai/docs/grounding/web-grounding-enterprise */ enterpriseWebSearch, /** * Creates a Google Maps grounding tool that gives the model access to Google Maps data. * Must have name "google_maps". * * @see https://ai.google.dev/gemini-api/docs/maps-grounding * @see https://cloud.google.com/vertex-ai/generative-ai/docs/grounding/grounding-with-google-maps */ googleMaps, /** * Creates a URL context tool that gives Google direct access to real-time web content. * Must have name "url_context". */ urlContext, /** * Enables Retrieval Augmented Generation (RAG) via the Gemini File Search tool. * Must have name "file_search". * * @param fileSearchStoreNames - Fully-qualified File Search store resource names. * @param metadataFilter - Optional filter expression to restrict the files that can be retrieved. * @param topK - Optional result limit for the number of chunks returned from File Search. * * @see https://ai.google.dev/gemini-api/docs/file-search */ fileSearch, /** * A tool that enables the model to generate and run Python code. * Must have name "code_execution". * * @note Ensure the selected model supports Code Execution. * Multi-tool usage with the code execution tool is typically compatible with Gemini >=2 models. * * @see https://ai.google.dev/gemini-api/docs/code-execution (Google AI) * @see https://cloud.google.com/vertex-ai/generative-ai/docs/model-reference/code-execution-api (Vertex AI) */ codeExecution, /** * Creates a Vertex RAG Store tool that enables the model to perform RAG searches against a Vertex RAG Store. * Must have name "vertex_rag_store". */ vertexRagStore }; var GoogleGenerativeAIImageModel = class { constructor(modelId, settings, config) { this.modelId = modelId; this.settings = settings; this.config = config; this.specificationVersion = "v2"; } get maxImagesPerCall() { var _a; return (_a = this.settings.maxImagesPerCall) != null ? _a : 4; } get provider() { return this.config.provider; } async doGenerate(options) { var _a, _b, _c; const { prompt, n = 1, size = "1024x1024", aspectRatio = "1:1", seed, providerOptions, headers, abortSignal } = options; const warnings = []; if (size != null) { warnings.push({ type: "unsupported-setting", setting: "size", details: "This model does not support the `size` option. Use `aspectRatio` instead." }); } if (seed != null) { warnings.push({ type: "unsupported-setting", setting: "seed", details: "This model does not support the `seed` option through this provider." }); } const googleOptions = await chunkOCS2GTEN_cjs.parseProviderOptions({ provider: "google", providerOptions, schema: googleImageProviderOptionsSchema }); const currentDate = (_c = (_b = (_a = this.config._internal) == null ? void 0 : _a.currentDate) == null ? void 0 : _b.call(_a)) != null ? _c : /* @__PURE__ */ new Date(); const parameters = { sampleCount: n }; if (aspectRatio != null) { parameters.aspectRatio = aspectRatio; } if (googleOptions) { Object.assign(parameters, googleOptions); } const body = { instances: [{ prompt }], parameters }; const { responseHeaders, value: response } = await chunkOCS2GTEN_cjs.postJsonToApi({ url: `${this.config.baseURL}/models/${this.modelId}:predict`, headers: chunkOCS2GTEN_cjs.combineHeaders(await chunkOCS2GTEN_cjs.resolve(this.config.headers), headers), body, failedResponseHandler: googleFailedResponseHandler, successfulResponseHandler: chunkOCS2GTEN_cjs.createJsonResponseHandler( googleImageResponseSchema ), abortSignal, fetch: this.config.fetch }); return { images: response.predictions.map( (p) => p.bytesBase64Encoded ), warnings: warnings != null ? warnings : [], providerMetadata: { google: { images: response.predictions.map((prediction) => ({ // Add any prediction-specific metadata here })) } }, response: { timestamp: currentDate, modelId: this.modelId, headers: responseHeaders } }; } }; var googleImageResponseSchema = chunkOCS2GTEN_cjs.lazySchema( () => chunkOCS2GTEN_cjs.zodSchema( v4.z.object({ predictions: v4.z.array(v4.z.object({ bytesBase64Encoded: v4.z.string() })).default([]) }) ) ); var googleImageProviderOptionsSchema = chunkOCS2GTEN_cjs.lazySchema( () => chunkOCS2GTEN_cjs.zodSchema( v4.z.object({ personGeneration: v4.z.enum(["dont_allow", "allow_adult", "allow_all"]).nullish(), aspectRatio: v4.z.enum(["1:1", "3:4", "4:3", "9:16", "16:9"]).nullish() }) ) ); function createGoogleGenerativeAI(options = {}) { var _a, _b; const baseURL = (_a = chunkOCS2GTEN_cjs.withoutTrailingSlash(options.baseURL)) != null ? _a : "https://generativelanguage.googleapis.com/v1beta"; const providerName = (_b = options.name) != null ? _b : "google.generative-ai"; const getHeaders = () => chunkOCS2GTEN_cjs.withUserAgentSuffix( { "x-goog-api-key": chunkOCS2GTEN_cjs.loadApiKey({ apiKey: options.apiKey, environmentVariableName: "GOOGLE_GENERATIVE_AI_API_KEY", description: "Google Generative AI" }), ...options.headers }, `ai-sdk/google/${VERSION}` ); const createChatModel = (modelId) => { var _a2; return new GoogleGenerativeAILanguageModel(modelId, { provider: providerName, baseURL, headers: getHeaders, generateId: (_a2 = options.generateId) != null ? _a2 : chunkOCS2GTEN_cjs.generateId, supportedUrls: () => ({ "*": [ // Google Generative Language "files" endpoint // e.g. https://generativelanguage.googleapis.com/v1beta/files/... new RegExp(`^${baseURL}/files/.*$`), // YouTube URLs (public or unlisted videos) new RegExp( `^https://(?:www\\.)?youtube\\.com/watch\\?v=[\\w-]+(?:&[\\w=&.-]*)?$` ), new RegExp(`^https://youtu\\.be/[\\w-]+(?:\\?[\\w=&.-]*)?$`) ] }), fetch: options.fetch }); }; const createEmbeddingModel = (modelId) => new GoogleGenerativeAIEmbeddingModel(modelId, { provider: providerName, baseURL, headers: getHeaders, fetch: options.fetch }); const createImageModel = (modelId, settings = {}) => new GoogleGenerativeAIImageModel(modelId, settings, { provider: providerName, baseURL, headers: getHeaders, fetch: options.fetch }); const provider = function(modelId) { if (new.target) { throw new Error( "The Google Generative AI model function cannot be called with the new keyword." ); } return createChatModel(modelId); }; provider.languageModel = createChatModel; provider.chat = createChatModel; provider.generativeAI = createChatModel; provider.embedding = createEmbeddingModel; provider.textEmbedding = createEmbeddingModel; provider.textEmbeddingModel = createEmbeddingModel; provider.image = createImageModel; provider.imageModel = createImageModel; provider.tools = googleTools; return provider; } createGoogleGenerativeAI(); var openaiErrorDataSchema = v4.z.object({ error: v4.z.object({ message: v4.z.string(), // The additional information below is handled loosely to support // OpenAI-compatible providers that have slightly different error // responses: type: v4.z.string().nullish(), param: v4.z.any().nullish(), code: v4.z.union([v4.z.string(), v4.z.number()]).nullish() }) }); var openaiFailedResponseHandler = chunkOCS2GTEN_cjs.createJsonErrorResponseHandler({ errorSchema: openaiErrorDataSchema, errorToMessage: (data) => data.error.message }); function getOpenAILanguageModelCapabilities(modelId) { const supportsFlexProcessing = modelId.startsWith("o3") || modelId.startsWith("o4-mini") || modelId.startsWith("gpt-5") && !modelId.startsWith("gpt-5-chat"); const supportsPriorityProcessing = modelId.startsWith("gpt-4") || modelId.startsWith("gpt-5") && !modelId.startsWith("gpt-5-nano") && !modelId.startsWith("gpt-5-chat") && !modelId.startsWith("gpt-5.4-nano") || modelId.startsWith("o3") || modelId.startsWith("o4-mini"); const isReasoningModel = !(modelId.startsWith("gpt-3") || modelId.startsWith("gpt-4") || modelId.startsWith("chatgpt-4o") || modelId.startsWith("gpt-5-chat")); const supportsNonReasoningParameters = modelId.startsWith("gpt-5.1") || modelId.startsWith("gpt-5.2") || modelId.startsWith("gpt-5.3") || modelId.startsWith("gpt-5.4"); const systemMessageMode = isReasoningModel ? "developer" : "system"; return { supportsFlexProcessing, supportsPriorityProcessing, isReasoningModel, systemMessageMode, supportsNonReasoningParameters }; } function convertToOpenAIChatMessages({ prompt, systemMessageMode = "system" }) { const messages = []; const warnings = []; for (const { role, content } of prompt) { switch (role) { case "system": { switch (systemMessageMode) { case "system": { messages.push({ role: "system", content }); break; } case "developer": { messages.push({ role: "developer", content }); break; } case "remove": { warnings.push({ type: "other", message: "system messages are removed for this model" }); break; } default: { const _exhaustiveCheck = systemMessageMode; throw new Error( `Unsupported system message mode: ${_exhaustiveCheck}` ); } } break; } case "user": { if (content.length === 1 && content[0].type === "text") { messages.push({ role: "user", content: content[0].text }); break; } messages.push({ role: "user", content: content.map((part, index) => { var _a, _b, _c; switch (part.type) { case "text": { return { type: "text", text: part.text }; } case "file": { if (part.mediaType.startsWith("image/")) { const mediaType = part.mediaType === "image/*" ? "image/jpeg" : part.mediaType; return { type: "image_url", image_url: { url: part.data instanceof URL ? part.data.toString() : `data:${mediaType};base64,${chunkOCS2GTEN_cjs.convertToBase64(part.data)}`, // OpenAI specific extension: image detail detail: (_b = (_a = part.providerOptions) == null ? void 0 : _a.openai) == null ? void 0 : _b.imageDetail } }; } else if (part.mediaType.startsWith("audio/")) { if (part.data instanceof URL) { throw new chunkOCS2GTEN_cjs.UnsupportedFunctionalityError({ functionality: "audio file parts with URLs" }); } switch (part.mediaType) { case "audio/wav": { return { type: "input_audio", input_audio: { data: chunkOCS2GTEN_cjs.convertToBase64(part.data), format: "wav" } }; } case "audio/mp3": case "audio/mpeg": { return { type: "input_audio", input_audio: { data: chunkOCS2GTEN_cjs.convertToBase64(part.data), format: "mp3" } }; } default: { throw new chunkOCS2GTEN_cjs.UnsupportedFunctionalityError({ functionality: `audio content parts with media type ${part.mediaType}` }); } } } else if (part.mediaType === "application/pdf") { if (part.data instanceof URL) { throw new chunkOCS2GTEN_cjs.UnsupportedFunctionalityError({ functionality: "PDF file parts with URLs" }); } return { type: "file", file: typeof part.data === "string" && part.data.startsWith("file-") ? { file_id: part.data } : { filename: (_c = part.filename) != null ? _c : `part-${index}.pdf`, file_data: `data:application/pdf;base64,${chunkOCS2GTEN_cjs.convertToBase64(part.data)}` } }; } else { throw new chunkOCS2GTEN_cjs.UnsupportedFunctionalityError({ functionality: `file part media type ${part.mediaType}` }); } } } }) }); break; } case "assistant": { let text = ""; const toolCalls = []; for (const part of content) { switch (part.type) { case "text": { text += part.text; break; } case "tool-call": { toolCalls.push({ id: part.toolCallId, type: "function", function: { name: part.toolName, arguments: JSON.stringify(part.input) } }); break; } } } messages.push({ role: "assistant", content: text, tool_calls: toolCalls.length > 0 ? toolCalls : void 0 }); break; } case "tool": { for (const toolResponse of content) { const output = toolResponse.output; let contentValue; switch (output.type) { case "text": case "error-text": contentValue = output.value; break; case "content": case "json": case "error-json": contentValue = JSON.stringify(output.value); break; } messages.push({ role: "tool", tool_call_id: toolResponse.toolCallId, content: contentValue }); } break; } default: { const _exhaustiveCheck = role; throw new Error(`Unsupported role: ${_exhaustiveCheck}`); } } } return { messages, warnings }; } function getResponseMetadata({ id, model, created }) { return { id: id != null ? id : void 0, modelId: model != null ? model : void 0, timestamp: created ? new Date(created * 1e3) : void 0 }; } function mapOpenAIFinishReason(finishReason) { switch (finishReason) { case "stop": return "stop"; case "length": return "length"; case "content_filter": return "content-filter"; case "function_call": case "tool_calls": return "tool-calls"; default: return "unknown"; } } var openaiChatResponseSchema = chunkOCS2GTEN_cjs.lazyValidator( () => chunkOCS2GTEN_cjs.zodSchema( v4.z.object({ id: v4.z.string().nullish(), created: v4.z.number().nullish(), model: v4.z.string().nullish(), choices: v4.z.array( v4.z.object({ message: v4.z.object({ role: v4.z.literal("assistant").nullish(), content: v4.z.string().nullish(), tool_calls: v4.z.array( v4.z.object({ id: v4.z.string().nullish(), type: v4.z.literal("function"), function: v4.z.object({ name: v4.z.string(), arguments: v4.z.string() }) }) ).nullish(), annotations: v4.z.array( v4.z.object({ type: v4.z.literal("url_citation"), url_citation: v4.z.object({ start_index: v4.z.number(), end_index: v4.z.number(), url: v4.z.string(), title: v4.z.string() }) }) ).nullish() }), index: v4.z.number(), logprobs: v4.z.object({ content: v4.z.array( v4.z.object({ token: v4.z.string(), logprob: v4.z.number(), top_logprobs: v4.z.array( v4.z.object({ token: v4.z.string(), logprob: v4.z.number() }) ) }) ).nullish() }).nullish(), finish_reason: v4.z.string().nullish() }) ), usage: v4.z.object({ prompt_tokens: v4.z.number().nullish(), completion_tokens: v4.z.number().nullish(), total_tokens: v4.z.number().nullish(), prompt_tokens_details: v4.z.object({ cached_tokens: v4.z.number().nullish() }).nullish(), completion_tokens_details: v4.z.object({ reasoning_tokens: v4.z.number().nullish(), accepted_prediction_tokens: v4.z.number().nullish(), rejected_prediction_tokens: v4.z.number().nullish() }).nullish() }).nullish() }) ) ); var openaiChatChunkSchema = chunkOCS2GTEN_cjs.lazyValidator( () => chunkOCS2GTEN_cjs.zodSchema( v4.z.union([ v4.z.object({ id: v4.z.string().nullish(), created: v4.z.number().nullish(), model: v4.z.string().nullish(), choices: v4.z.array( v4.z.object({ delta: v4.z.object({ role: v4.z.enum(["assistant"]).nullish(), content: v4.z.string().nullish(), tool_calls: v4.z.array( v4.z.object({ index: v4.z.number(), id: v4.z.string().nullish(), type: v4.z.literal("function").nullish(), function: v4.z.object({ name: v4.z.string().nullish(), arguments: v4.z.string().nullish() }) }) ).nullish(), annotations: v4.z.array( v4.z.object({ type: v4.z.literal("url_citation"), url_citation: v4.z.object({ start_index: v4.z.number(), end_index: v4.z.number(), url: v4.z.string(), title: v4.z.string() }) }) ).nullish() }).nullish(), logprobs: v4.z.object({ content: v4.z.array( v4.z.object({ token: v4.z.string(), logprob: v4.z.number(), top_logprobs: v4.z.array( v4.z.object({ token: v4.z.string(), logprob: v4.z.number() }) ) }) ).nullish() }).nullish(), finish_reason: v4.z.string().nullish(), index: v4.z.number() }) ), usage: v4.z.object({ prompt_tokens: v4.z.number().nullish(), completion_tokens: v4.z.number().nullish(), total_tokens: v4.z.number().nullish(), prompt_tokens_details: v4.z.object({ cached_tokens: v4.z.number().nullish() }).nullish(), completion_tokens_details: v4.z.object({ reasoning_tokens: v4.z.number().nullish(), accepted_prediction_tokens: v4.z.number().nullish(), rejected_prediction_tokens: v4.z.number().nullish() }).nullish() }).nullish() }), openaiErrorDataSchema ]) ) ); var openaiChatLanguageModelOptions = chunkOCS2GTEN_cjs.lazyValidator( () => chunkOCS2GTEN_cjs.zodSchema( v4.z.object({ /** * Modify the likelihood of specified tokens appearing in the completion. * * Accepts a JSON object that maps tokens (specified by their token ID in * the GPT tokenizer) to an associated bias value from -100 to 100. */ logitBias: v4.z.record(v4.z.coerce.number(), v4.z.number()).optional(), /** * Return the log probabilities of the tokens. * * Setting to true will return the log probabilities of the tokens that * were generated. * * Setting to a number will return the log probabilities of the top n * tokens that were generated. */ logprobs: v4.z.union([v4.z.boolean(), v4.z.number()]).optional(), /** * Whether to enable parallel function calling during tool use. Default to true. */ parallelToolCalls: v4.z.boolean().optional(), /** * A unique identifier representing your end-user, which can help OpenAI to * monitor and detect abuse. */ user: v4.z.string().optional(), /** * Reasoning effort for reasoning models. Defaults to `medium`. */ reasoningEffort: v4.z.enum(["none", "minimal", "low", "medium", "high", "xhigh"]).optional(), /** * Maximum number of completion tokens to generate. Useful for reasoning models. */ maxCompletionTokens: v4.z.number().optional(), /** * Whether to enable persistence in responses API. */ store: v4.z.boolean().optional(), /** * Metadata to associate with the request. */ metadata: v4.z.record(v4.z.string().max(64), v4.z.string().max(512)).optional(), /** * Parameters for prediction mode. */ prediction: v4.z.record(v4.z.string(), v4.z.any()).optional(), /** * Whether to use structured outputs. * * @default true */ structuredOutputs: v4.z.boolean().optional(), /** * Service tier for the request. * - 'auto': Default service tier. The request will be processed with the service tier configured in the * Project settings. Unless otherwise configured, the Project will use 'default'. * - 'flex': 50% cheaper processing at the cost of increased latency. Only available for o3 and o4-mini models. * - 'priority': Higher-speed processing with predictably low latency at premium cost. Available for Enterprise customers. * - 'default': The request will be processed with the standard pricing and performance for the selected model. * * @default 'auto' */ serviceTier: v4.z.enum(["auto", "flex", "priority", "default"]).optional(), /** * Whether to use strict JSON schema validation. * * @default false */ strictJsonSchema: v4.z.boolean().optional(), /** * Controls the verbosity of the model's responses. * Lower values will result in more concise responses, while higher values will result in more verbose responses. */ textVerbosity: v4.z.enum(["low", "medium", "high"]).optional(), /** * A cache key for prompt caching. Allows manual control over prompt caching behavior. * Useful for improving cache hit rates and working around automatic caching issues. */ promptCacheKey: v4.z.string().optional(), /** * The retention policy for the prompt cache. * - 'in_memory': Default. Standard prompt caching behavior. * - '24h': Extended prompt caching that keeps cached prefixes active for up to 24 hours. * Currently only available for 5.1 series models. * * @default 'in_memory' */ promptCacheRetention: v4.z.enum(["in_memory", "24h"]).optional(), /** * A stable identifier used to help detect users of your application * that may be violating OpenAI's usage policies. The IDs should be a * string that uniquely identifies each user. We recommend hashing their * username or email address, in order to avoid sending us any identifying * information. */ safetyIdentifier: v4.z.string().optional() }) ) ); function prepareChatTools({ tools, toolChoice, structuredOutputs, strictJsonSchema }) { tools = (tools == null ? void 0 : tools.length) ? tools : void 0; const toolWarnings = []; if (tools == null) { return { tools: void 0, toolChoice: void 0, toolWarnings }; } const openaiTools2 = []; for (const tool of tools) { switch (tool.type) { case "function": openaiTools2.push({ type: "function", function: { name: tool.name, description: tool.description, parameters: tool.inputSchema, strict: structuredOutputs ? strictJsonSchema : void 0 } }); break; default: toolWarnings.push({ type: "unsupported-tool", tool }); break; } } if (toolChoice == null) { return { tools: openaiTools2, toolChoice: void 0, toolWarnings }; } const type = toolChoice.type; switch (type) { case "auto": case "none": case "required": return { tools: openaiTools2, toolChoice: type, toolWarnings }; case "tool": return { tools: openaiTools2, toolChoice: { type: "function", function: { name: toolChoice.toolName } }, toolWarnings }; default: { const _exhaustiveCheck = type; throw new chunkOCS2GTEN_cjs.UnsupportedFunctionalityError({ functionality: `tool choice type: ${_exhaustiveCheck}` }); } } } var OpenAIChatLanguageModel = class { constructor(modelId, config) { this.specificationVersion = "v2"; this.supportedUrls = { "image/*": [/^https?:\/\/.*$/] }; this.modelId = modelId; this.config = config; } get provider() { return this.config.provider; } async getArgs({ prompt, maxOutputTokens, temperature, topP, topK, frequencyPenalty, presencePenalty, stopSequences, responseFormat, seed, tools, toolChoice, providerOptions }) { var _a, _b, _c, _d; const warnings = []; const openaiOptions = (_a = await chunkOCS2GTEN_cjs.parseProviderOptions({ provider: "openai", providerOptions, schema: openaiChatLanguageModelOptions })) != null ? _a : {}; const structuredOutputs = (_b = openaiOptions.structuredOutputs) != null ? _b : true; const modelCapabilities = getOpenAILanguageModelCapabilities(this.modelId); if (topK != null) { warnings.push({ type: "unsupported-setting", setting: "topK" }); } if ((responseFormat == null ? void 0 : responseFormat.type) === "json" && responseFormat.schema != null && !structuredOutputs) { warnings.push({ type: "unsupported-setting", setting: "responseFormat", details: "JSON response format schema is only supported with structuredOutputs" }); } const { messages, warnings: messageWarnings } = convertToOpenAIChatMessages( { prompt, systemMessageMode: modelCapabilities.systemMessageMode } ); warnings.push(...messageWarnings); const strictJsonSchema = (_c = openaiOptions.strictJsonSchema) != null ? _c : false; const baseArgs = { // model id: model: this.modelId, // model specific settings: logit_bias: openaiOptions.logitBias, logprobs: openaiOptions.logprobs === true || typeof openaiOptions.logprobs === "number" ? true : void 0, top_logprobs: typeof openaiOptions.logprobs === "number" ? openaiOptions.logprobs : typeof openaiOptions.logprobs === "boolean" ? openaiOptions.logprobs ? 0 : void 0 : void 0, user: openaiOptions.user, parallel_tool_calls: openaiOptions.parallelToolCalls, // standardized settings: max_tokens: maxOutputTokens, temperature, top_p: topP, frequency_penalty: frequencyPenalty, presence_penalty: presencePenalty, response_format: (responseFormat == null ? void 0 : responseFormat.type) === "json" ? structuredOutputs && responseFormat.schema != null ? { type: "json_schema", json_schema: { schema: responseFormat.schema, strict: strictJsonSchema, name: (_d = responseFormat.name) != null ? _d : "response", description: responseFormat.description } } : { type: "json_object" } : void 0, stop: stopSequences, seed, verbosity: openaiOptions.textVerbosity, // openai specific settings: // TODO AI SDK 6: remove, we auto-map maxOutputTokens now max_completion_tokens: openaiOptions.maxCompletionTokens, store: openaiOptions.store, metadata: openaiOptions.metadata, prediction: openaiOptions.prediction, reasoning_effort: openaiOptions.reasoningEffort, service_tier: openaiOptions.serviceTier, prompt_cache_key: openaiOptions.promptCacheKey, prompt_cache_retention: openaiOptions.promptCacheRetention, safety_identifier: openaiOptions.safetyIdentifier, // messages: messages }; if (modelCapabilities.isReasoningModel) { if (openaiOptions.reasoningEffort !== "none" || !modelCapabilities.supportsNonReasoningParameters) { if (baseArgs.temperature != null) { baseArgs.temperature = void 0; warnings.push({ type: "unsupported-setting", setting: "temperature", details: "temperature is not supported for reasoning models" }); } if (baseArgs.top_p != null) { baseArgs.top_p = void 0; warnings.push({ type: "unsupported-setting", setting: "topP", details: "topP is not supported for reasoning models" }); } if (baseArgs.logprobs != null) { baseArgs.logprobs = void 0; warnings.push({ type: "other", message: "logprobs is not supported for reasoning models" }); } } if (baseArgs.frequency_penalty != null) { baseArgs.frequency_penalty = void 0; warnings.push({ type: "unsupported-setting", setting: "frequencyPenalty", details: "frequencyPenalty is not supported for reasoning models" }); } if (baseArgs.presence_penalty != null) { baseArgs.presence_penalty = void 0; warnings.push({ type: "unsupported-setting", setting: "presencePenalty", details: "presencePenalty is not supported for reasoning models" }); } if (baseArgs.logit_bias != null) { baseArgs.logit_bias = void 0; warnings.push({ type: "other", message: "logitBias is not supported for reasoning models" }); } if (baseArgs.top_logprobs != null) { baseArgs.top_logprobs = void 0; warnings.push({ type: "other", message: "topLogprobs is not supported for reasoning models" }); } if (baseArgs.max_tokens != null) { if (baseArgs.max_completion_tokens == null) { baseArgs.max_completion_tokens = baseArgs.max_tokens; } baseArgs.max_tokens = void 0; } } else if (this.modelId.startsWith("gpt-4o-search-preview") || this.modelId.startsWith("gpt-4o-mini-search-preview")) { if (baseArgs.temperature != null) { baseArgs.temperature = void 0; warnings.push({ type: "unsupported-setting", setting: "temperature", details: "temperature is not supported for the search preview models and has been removed." }); } } if (openaiOptions.serviceTier === "flex" && !modelCapabilities.supportsFlexProcessing) { warnings.push({ type: "unsupported-setting", setting: "serviceTier", details: "flex processing is only available for o3, o4-mini, and gpt-5 models" }); baseArgs.service_tier = void 0; } if (openaiOptions.serviceTier === "priority" && !modelCapabilities.supportsPriorityProcessing) { warnings.push({ type: "unsupported-setting", setting: "serviceTier", details: "priority processing is only available for supported models (gpt-4, gpt-5, gpt-5-mini, o3, o4-mini) and requires Enterprise access. gpt-5-nano is not supported" }); baseArgs.service_tier = void 0; } const { tools: openaiTools2, toolChoice: openaiToolChoice, toolWarnings } = prepareChatTools({ tools, toolChoice, structuredOutputs, strictJsonSchema }); return { args: { ...baseArgs, tools: openaiTools2, tool_choice: openaiToolChoice }, warnings: [...warnings, ...toolWarnings] }; } async doGenerate(options) { var _a, _b, _c, _d, _e, _f, _g, _h, _i, _j, _k, _l, _m, _n; const { args: body, warnings } = await this.getArgs(options); const { responseHeaders, value: response, rawValue: rawResponse } = await chunkOCS2GTEN_cjs.postJsonToApi({ url: this.config.url({ path: "/chat/completions", modelId: this.modelId }), headers: chunkOCS2GTEN_cjs.combineHeaders(this.config.headers(), options.headers), body, failedResponseHandler: openaiFailedResponseHandler, successfulResponseHandler: chunkOCS2GTEN_cjs.createJsonResponseHandler( openaiChatResponseSchema ), abortSignal: options.abortSignal, fetch: this.config.fetch }); const choice = response.choices[0]; const content = []; const text = choice.message.content; if (text != null && text.length > 0) { content.push({ type: "text", text }); } for (const toolCall of (_a = choice.message.tool_calls) != null ? _a : []) { content.push({ type: "tool-call", toolCallId: (_b = toolCall.id) != null ? _b : chunkOCS2GTEN_cjs.generateId(), toolName: toolCall.function.name, input: toolCall.function.arguments }); } for (const annotation of (_c = choice.message.annotations) != null ? _c : []) { content.push({ type: "source", sourceType: "url", id: chunkOCS2GTEN_cjs.generateId(), url: annotation.url_citation.url, title: annotation.url_citation.title }); } const completionTokenDetails = (_d = response.usage) == null ? void 0 : _d.completion_tokens_details; const promptTokenDetails = (_e = response.usage) == null ? void 0 : _e.prompt_tokens_details; const providerMetadata = { openai: {} }; if ((completionTokenDetails == null ? void 0 : completionTokenDetails.accepted_prediction_tokens) != null) { providerMetadata.openai.acceptedPredictionTokens = completionTokenDetails == null ? void 0 : completionTokenDetails.accepted_prediction_tokens; } if ((completionTokenDetails == null ? void 0 : completionTokenDetails.rejected_prediction_tokens) != null) { providerMetadata.openai.rejectedPredictionTokens = completionTokenDetails == null ? void 0 : completionTokenDetails.rejected_prediction_tokens; } if (((_f = choice.logprobs) == null ? void 0 : _f.content) != null) { providerMetadata.openai.logprobs = choice.logprobs.content; } return { content, finishReason: mapOpenAIFinishReason(choice.finish_reason), usage: { inputTokens: (_h = (_g = response.usage) == null ? void 0 : _g.prompt_tokens) != null ? _h : void 0, outputTokens: (_j = (_i = response.usage) == null ? void 0 : _i.completion_tokens) != null ? _j : void 0, totalTokens: (_l = (_k = response.usage) == null ? void 0 : _k.total_tokens) != null ? _l : void 0, reasoningTokens: (_m = completionTokenDetails == null ? void 0 : completionTokenDetails.reasoning_tokens) != null ? _m : void 0, cachedInputTokens: (_n = promptTokenDetails == null ? void 0 : promptTokenDetails.cached_tokens) != null ? _n : void 0 }, request: { body }, response: { ...getResponseMetadata(response), headers: responseHeaders, body: rawResponse }, warnings, providerMetadata }; } async doStream(options) { const { args, warnings } = await this.getArgs(options); const body = { ...args, stream: true, stream_options: { include_usage: true } }; const { responseHeaders, value: response } = await chunkOCS2GTEN_cjs.postJsonToApi({ url: this.config.url({ path: "/chat/completions", modelId: this.modelId }), headers: chunkOCS2GTEN_cjs.combineHeaders(this.config.headers(), options.headers), body, failedResponseHandler: openaiFailedResponseHandler, successfulResponseHandler: chunkOCS2GTEN_cjs.createEventSourceResponseHandler( openaiChatChunkSchema ), abortSignal: options.abortSignal, fetch: this.config.fetch }); const toolCalls = []; let finishReason = "unknown"; const usage = { inputTokens: void 0, outputTokens: void 0, totalTokens: void 0 }; let metadataExtracted = false; let isActiveText = false; const providerMetadata = { openai: {} }; return { stream: response.pipeThrough( new TransformStream({ start(controller) { controller.enqueue({ type: "stream-start", warnings }); }, transform(chunk, controller) { var _a, _b, _c, _d, _e, _f, _g, _h, _i, _j, _k, _l, _m, _n, _o, _p, _q, _r, _s, _t, _u, _v, _w, _x; if (options.includeRawChunks) { controller.enqueue({ type: "raw", rawValue: chunk.rawValue }); } if (!chunk.success) { finishReason = "error"; controller.enqueue({ type: "error", error: chunk.error }); return; } const value = chunk.value; if ("error" in value) { finishReason = "error"; controller.enqueue({ type: "error", error: value.error }); return; } if (!metadataExtracted) { const metadata = getResponseMetadata(value); if (Object.values(metadata).some(Boolean)) { metadataExtracted = true; controller.enqueue({ type: "response-metadata", ...getResponseMetadata(value) }); } } if (value.usage != null) { usage.inputTokens = (_a = value.usage.prompt_tokens) != null ? _a : void 0; usage.outputTokens = (_b = value.usage.completion_tokens) != null ? _b : void 0; usage.totalTokens = (_c = value.usage.total_tokens) != null ? _c : void 0; usage.reasoningTokens = (_e = (_d = value.usage.completion_tokens_details) == null ? void 0 : _d.reasoning_tokens) != null ? _e : void 0; usage.cachedInputTokens = (_g = (_f = value.usage.prompt_tokens_details) == null ? void 0 : _f.cached_tokens) != null ? _g : void 0; if (((_h = value.usage.completion_tokens_details) == null ? void 0 : _h.accepted_prediction_tokens) != null) { providerMetadata.openai.acceptedPredictionTokens = (_i = value.usage.completion_tokens_details) == null ? void 0 : _i.accepted_prediction_tokens; } if (((_j = value.usage.completion_tokens_details) == null ? void 0 : _j.rejected_prediction_tokens) != null) { providerMetadata.openai.rejectedPredictionTokens = (_k = value.usage.completion_tokens_details) == null ? void 0 : _k.rejected_prediction_tokens; } } const choice = value.choices[0]; if ((choice == null ? void 0 : choice.finish_reason) != null) { finishReason = mapOpenAIFinishReason(choice.finish_reason); } if (((_l = choice == null ? void 0 : choice.logprobs) == null ? void 0 : _l.content) != null) { providerMetadata.openai.logprobs = choice.logprobs.content; } if ((choice == null ? void 0 : choice.delta) == null) { return; } const delta = choice.delta; if (delta.content != null) { if (!isActiveText) { controller.enqueue({ type: "text-start", id: "0" }); isActiveText = true; } controller.enqueue({ type: "text-delta", id: "0", delta: delta.content }); } if (delta.tool_calls != null) { for (const toolCallDelta of delta.tool_calls) { const index = toolCallDelta.index; if (toolCalls[index] == null) { if (toolCallDelta.type != null && toolCallDelta.type !== "function") { throw new chunkOCS2GTEN_cjs.InvalidResponseDataError({ data: toolCallDelta, message: `Expected 'function' type.` }); } if (toolCallDelta.id == null) { throw new chunkOCS2GTEN_cjs.InvalidResponseDataError({ data: toolCallDelta, message: `Expected 'id' to be a string.` }); } if (((_m = toolCallDelta.function) == null ? void 0 : _m.name) == null) { throw new chunkOCS2GTEN_cjs.InvalidResponseDataError({ data: toolCallDelta, message: `Expected 'function.name' to be a string.` }); } controller.enqueue({ type: "tool-input-start", id: toolCallDelta.id, toolName: toolCallDelta.function.name }); toolCalls[index] = { id: toolCallDelta.id, type: "function", function: { name: toolCallDelta.function.name, arguments: (_n = toolCallDelta.function.arguments) != null ? _n : "" }, hasFinished: false }; const toolCall2 = toolCalls[index]; if (((_o = toolCall2.function) == null ? void 0 : _o.name) != null && ((_p = toolCall2.function) == null ? void 0 : _p.arguments) != null) { if (toolCall2.function.arguments.length > 0) { controller.enqueue({ type: "tool-input-delta", id: toolCall2.id, delta: toolCall2.function.arguments }); } if (chunkOCS2GTEN_cjs.isParsableJson(toolCall2.function.arguments)) { controller.enqueue({ type: "tool-input-end", id: toolCall2.id }); controller.enqueue({ type: "tool-call", toolCallId: (_q = toolCall2.id) != null ? _q : chunkOCS2GTEN_cjs.generateId(), toolName: toolCall2.function.name, input: toolCall2.function.arguments }); toolCall2.hasFinished = true; } } continue; } const toolCall = toolCalls[index]; if (toolCall.hasFinished) { continue; } if (((_r = toolCallDelta.function) == null ? void 0 : _r.arguments) != null) { toolCall.function.arguments += (_t = (_s = toolCallDelta.function) == null ? void 0 : _s.arguments) != null ? _t : ""; } controller.enqueue({ type: "tool-input-delta", id: toolCall.id, delta: (_u = toolCallDelta.function.arguments) != null ? _u : "" }); if (((_v = toolCall.function) == null ? void 0 : _v.name) != null && ((_w = toolCall.function) == null ? void 0 : _w.arguments) != null && chunkOCS2GTEN_cjs.isParsableJson(toolCall.function.arguments)) { controller.enqueue({ type: "tool-input-end", id: toolCall.id }); controller.enqueue({ type: "tool-call", toolCallId: (_x = toolCall.id) != null ? _x : chunkOCS2GTEN_cjs.generateId(), toolName: toolCall.function.name, input: toolCall.function.arguments }); toolCall.hasFinished = true; } } } if (delta.annotations != null) { for (const annotation of delta.annotations) { controller.enqueue({ type: "source", sourceType: "url", id: chunkOCS2GTEN_cjs.generateId(), url: annotation.url_citation.url, title: annotation.url_citation.title }); } } }, flush(controller) { if (isActiveText) { controller.enqueue({ type: "text-end", id: "0" }); } controller.enqueue({ type: "finish", finishReason, usage, ...providerMetadata != null ? { providerMetadata } : {} }); } }) ), request: { body }, response: { headers: responseHeaders } }; } }; function convertToOpenAICompletionPrompt({ prompt, user = "user", assistant = "assistant" }) { let text = ""; if (prompt[0].role === "system") { text += `${prompt[0].content} `; prompt = prompt.slice(1); } for (const { role, content } of prompt) { switch (role) { case "system": { throw new chunkOCS2GTEN_cjs.InvalidPromptError({ message: "Unexpected system message in prompt: ${content}", prompt }); } case "user": { const userMessage = content.map((part) => { switch (part.type) { case "text": { return part.text; } } }).filter(Boolean).join(""); text += `${user}: ${userMessage} `; break; } case "assistant": { const assistantMessage = content.map((part) => { switch (part.type) { case "text": { return part.text; } case "tool-call": { throw new chunkOCS2GTEN_cjs.UnsupportedFunctionalityError({ functionality: "tool-call messages" }); } } }).join(""); text += `${assistant}: ${assistantMessage} `; break; } case "tool": { throw new chunkOCS2GTEN_cjs.UnsupportedFunctionalityError({ functionality: "tool messages" }); } default: { const _exhaustiveCheck = role; throw new Error(`Unsupported role: ${_exhaustiveCheck}`); } } } text += `${assistant}: `; return { prompt: text, stopSequences: [` ${user}:`] }; } function getResponseMetadata2({ id, model, created }) { return { id: id != null ? id : void 0, modelId: model != null ? model : void 0, timestamp: created != null ? new Date(created * 1e3) : void 0 }; } function mapOpenAIFinishReason2(finishReason) { switch (finishReason) { case "stop": return "stop"; case "length": return "length"; case "content_filter": return "content-filter"; case "function_call": case "tool_calls": return "tool-calls"; default: return "unknown"; } } var openaiCompletionResponseSchema = chunkOCS2GTEN_cjs.lazyValidator( () => chunkOCS2GTEN_cjs.zodSchema( v4.z.object({ id: v4.z.string().nullish(), created: v4.z.number().nullish(), model: v4.z.string().nullish(), choices: v4.z.array( v4.z.object({ text: v4.z.string(), finish_reason: v4.z.string(), logprobs: v4.z.object({ tokens: v4.z.array(v4.z.string()), token_logprobs: v4.z.array(v4.z.number()), top_logprobs: v4.z.array(v4.z.record(v4.z.string(), v4.z.number())).nullish() }).nullish() }) ), usage: v4.z.object({ prompt_tokens: v4.z.number(), completion_tokens: v4.z.number(), total_tokens: v4.z.number() }).nullish() }) ) ); var openaiCompletionChunkSchema = chunkOCS2GTEN_cjs.lazyValidator( () => chunkOCS2GTEN_cjs.zodSchema( v4.z.union([ v4.z.object({ id: v4.z.string().nullish(), created: v4.z.number().nullish(), model: v4.z.string().nullish(), choices: v4.z.array( v4.z.object({ text: v4.z.string(), finish_reason: v4.z.string().nullish(), index: v4.z.number(), logprobs: v4.z.object({ tokens: v4.z.array(v4.z.string()), token_logprobs: v4.z.array(v4.z.number()), top_logprobs: v4.z.array(v4.z.record(v4.z.string(), v4.z.number())).nullish() }).nullish() }) ), usage: v4.z.object({ prompt_tokens: v4.z.number(), completion_tokens: v4.z.number(), total_tokens: v4.z.number() }).nullish() }), openaiErrorDataSchema ]) ) ); var openaiCompletionProviderOptions = chunkOCS2GTEN_cjs.lazyValidator( () => chunkOCS2GTEN_cjs.zodSchema( v4.z.object({ /** Echo back the prompt in addition to the completion. */ echo: v4.z.boolean().optional(), /** Modify the likelihood of specified tokens appearing in the completion. Accepts a JSON object that maps tokens (specified by their token ID in the GPT tokenizer) to an associated bias value from -100 to 100. You can use this tokenizer tool to convert text to token IDs. Mathematically, the bias is added to the logits generated by the model prior to sampling. The exact effect will vary per model, but values between -1 and 1 should decrease or increase likelihood of selection; values like -100 or 100 should result in a ban or exclusive selection of the relevant token. As an example, you can pass {"50256": -100} to prevent the <|endoftext|> token from being generated. */ logitBias: v4.z.record(v4.z.string(), v4.z.number()).optional(), /** The suffix that comes after a completion of inserted text. */ suffix: v4.z.string().optional(), /** A unique identifier representing your end-user, which can help OpenAI to monitor and detect abuse. Learn more. */ user: v4.z.string().optional(), /** Return the log probabilities of the tokens. Including logprobs will increase the response size and can slow down response times. However, it can be useful to better understand how the model is behaving. Setting to true will return the log probabilities of the tokens that were generated. Setting to a number will return the log probabilities of the top n tokens that were generated. */ logprobs: v4.z.union([v4.z.boolean(), v4.z.number()]).optional() }) ) ); var OpenAICompletionLanguageModel = class { constructor(modelId, config) { this.specificationVersion = "v2"; this.supportedUrls = { // No URLs are supported for completion models. }; this.modelId = modelId; this.config = config; } get providerOptionsName() { return this.config.provider.split(".")[0].trim(); } get provider() { return this.config.provider; } async getArgs({ prompt, maxOutputTokens, temperature, topP, topK, frequencyPenalty, presencePenalty, stopSequences: userStopSequences, responseFormat, tools, toolChoice, seed, providerOptions }) { const warnings = []; const openaiOptions = { ...await chunkOCS2GTEN_cjs.parseProviderOptions({ provider: "openai", providerOptions, schema: openaiCompletionProviderOptions }), ...await chunkOCS2GTEN_cjs.parseProviderOptions({ provider: this.providerOptionsName, providerOptions, schema: openaiCompletionProviderOptions }) }; if (topK != null) { warnings.push({ type: "unsupported-setting", setting: "topK" }); } if (tools == null ? void 0 : tools.length) { warnings.push({ type: "unsupported-setting", setting: "tools" }); } if (toolChoice != null) { warnings.push({ type: "unsupported-setting", setting: "toolChoice" }); } if (responseFormat != null && responseFormat.type !== "text") { warnings.push({ type: "unsupported-setting", setting: "responseFormat", details: "JSON response format is not supported." }); } const { prompt: completionPrompt, stopSequences } = convertToOpenAICompletionPrompt({ prompt }); const stop = [...stopSequences != null ? stopSequences : [], ...userStopSequences != null ? userStopSequences : []]; return { args: { // model id: model: this.modelId, // model specific settings: echo: openaiOptions.echo, logit_bias: openaiOptions.logitBias, logprobs: (openaiOptions == null ? void 0 : openaiOptions.logprobs) === true ? 0 : (openaiOptions == null ? void 0 : openaiOptions.logprobs) === false ? void 0 : openaiOptions == null ? void 0 : openaiOptions.logprobs, suffix: openaiOptions.suffix, user: openaiOptions.user, // standardized settings: max_tokens: maxOutputTokens, temperature, top_p: topP, frequency_penalty: frequencyPenalty, presence_penalty: presencePenalty, seed, // prompt: prompt: completionPrompt, // stop sequences: stop: stop.length > 0 ? stop : void 0 }, warnings }; } async doGenerate(options) { var _a, _b, _c; const { args, warnings } = await this.getArgs(options); const { responseHeaders, value: response, rawValue: rawResponse } = await chunkOCS2GTEN_cjs.postJsonToApi({ url: this.config.url({ path: "/completions", modelId: this.modelId }), headers: chunkOCS2GTEN_cjs.combineHeaders(this.config.headers(), options.headers), body: args, failedResponseHandler: openaiFailedResponseHandler, successfulResponseHandler: chunkOCS2GTEN_cjs.createJsonResponseHandler( openaiCompletionResponseSchema ), abortSignal: options.abortSignal, fetch: this.config.fetch }); const choice = response.choices[0]; const providerMetadata = { openai: {} }; if (choice.logprobs != null) { providerMetadata.openai.logprobs = choice.logprobs; } return { content: [{ type: "text", text: choice.text }], usage: { inputTokens: (_a = response.usage) == null ? void 0 : _a.prompt_tokens, outputTokens: (_b = response.usage) == null ? void 0 : _b.completion_tokens, totalTokens: (_c = response.usage) == null ? void 0 : _c.total_tokens }, finishReason: mapOpenAIFinishReason2(choice.finish_reason), request: { body: args }, response: { ...getResponseMetadata2(response), headers: responseHeaders, body: rawResponse }, providerMetadata, warnings }; } async doStream(options) { const { args, warnings } = await this.getArgs(options); const body = { ...args, stream: true, stream_options: { include_usage: true } }; const { responseHeaders, value: response } = await chunkOCS2GTEN_cjs.postJsonToApi({ url: this.config.url({ path: "/completions", modelId: this.modelId }), headers: chunkOCS2GTEN_cjs.combineHeaders(this.config.headers(), options.headers), body, failedResponseHandler: openaiFailedResponseHandler, successfulResponseHandler: chunkOCS2GTEN_cjs.createEventSourceResponseHandler( openaiCompletionChunkSchema ), abortSignal: options.abortSignal, fetch: this.config.fetch }); let finishReason = "unknown"; const providerMetadata = { openai: {} }; const usage = { inputTokens: void 0, outputTokens: void 0, totalTokens: void 0 }; let isFirstChunk = true; return { stream: response.pipeThrough( new TransformStream({ start(controller) { controller.enqueue({ type: "stream-start", warnings }); }, transform(chunk, controller) { if (options.includeRawChunks) { controller.enqueue({ type: "raw", rawValue: chunk.rawValue }); } if (!chunk.success) { finishReason = "error"; controller.enqueue({ type: "error", error: chunk.error }); return; } const value = chunk.value; if ("error" in value) { finishReason = "error"; controller.enqueue({ type: "error", error: value.error }); return; } if (isFirstChunk) { isFirstChunk = false; controller.enqueue({ type: "response-metadata", ...getResponseMetadata2(value) }); controller.enqueue({ type: "text-start", id: "0" }); } if (value.usage != null) { usage.inputTokens = value.usage.prompt_tokens; usage.outputTokens = value.usage.completion_tokens; usage.totalTokens = value.usage.total_tokens; } const choice = value.choices[0]; if ((choice == null ? void 0 : choice.finish_reason) != null) { finishReason = mapOpenAIFinishReason2(choice.finish_reason); } if ((choice == null ? void 0 : choice.logprobs) != null) { providerMetadata.openai.logprobs = choice.logprobs; } if ((choice == null ? void 0 : choice.text) != null && choice.text.length > 0) { controller.enqueue({ type: "text-delta", id: "0", delta: choice.text }); } }, flush(controller) { if (!isFirstChunk) { controller.enqueue({ type: "text-end", id: "0" }); } controller.enqueue({ type: "finish", finishReason, providerMetadata, usage }); } }) ), request: { body }, response: { headers: responseHeaders } }; } }; var openaiEmbeddingProviderOptions = chunkOCS2GTEN_cjs.lazyValidator( () => chunkOCS2GTEN_cjs.zodSchema( v4.z.object({ /** The number of dimensions the resulting output embeddings should have. Only supported in text-embedding-3 and later models. */ dimensions: v4.z.number().optional(), /** A unique identifier representing your end-user, which can help OpenAI to monitor and detect abuse. Learn more. */ user: v4.z.string().optional() }) ) ); var openaiTextEmbeddingResponseSchema = chunkOCS2GTEN_cjs.lazyValidator( () => chunkOCS2GTEN_cjs.zodSchema( v4.z.object({ data: v4.z.array(v4.z.object({ embedding: v4.z.array(v4.z.number()) })), usage: v4.z.object({ prompt_tokens: v4.z.number() }).nullish() }) ) ); var OpenAIEmbeddingModel = class { constructor(modelId, config) { this.specificationVersion = "v2"; this.maxEmbeddingsPerCall = 2048; this.supportsParallelCalls = true; this.modelId = modelId; this.config = config; } get provider() { return this.config.provider; } async doEmbed({ values, headers, abortSignal, providerOptions }) { var _a; if (values.length > this.maxEmbeddingsPerCall) { throw new chunkOCS2GTEN_cjs.TooManyEmbeddingValuesForCallError({ provider: this.provider, modelId: this.modelId, maxEmbeddingsPerCall: this.maxEmbeddingsPerCall, values }); } const openaiOptions = (_a = await chunkOCS2GTEN_cjs.parseProviderOptions({ provider: "openai", providerOptions, schema: openaiEmbeddingProviderOptions })) != null ? _a : {}; const { responseHeaders, value: response, rawValue } = await chunkOCS2GTEN_cjs.postJsonToApi({ url: this.config.url({ path: "/embeddings", modelId: this.modelId }), headers: chunkOCS2GTEN_cjs.combineHeaders(this.config.headers(), headers), body: { model: this.modelId, input: values, encoding_format: "float", dimensions: openaiOptions.dimensions, user: openaiOptions.user }, failedResponseHandler: openaiFailedResponseHandler, successfulResponseHandler: chunkOCS2GTEN_cjs.createJsonResponseHandler( openaiTextEmbeddingResponseSchema ), abortSignal, fetch: this.config.fetch }); return { embeddings: response.data.map((item) => item.embedding), usage: response.usage ? { tokens: response.usage.prompt_tokens } : void 0, response: { headers: responseHeaders, body: rawValue } }; } }; var openaiImageResponseSchema = chunkOCS2GTEN_cjs.lazyValidator( () => chunkOCS2GTEN_cjs.zodSchema( v4.z.object({ created: v4.z.number().nullish(), data: v4.z.array( v4.z.object({ b64_json: v4.z.string(), revised_prompt: v4.z.string().nullish() }) ), background: v4.z.string().nullish(), output_format: v4.z.string().nullish(), size: v4.z.string().nullish(), quality: v4.z.string().nullish(), usage: v4.z.object({ input_tokens: v4.z.number().nullish(), output_tokens: v4.z.number().nullish(), total_tokens: v4.z.number().nullish(), input_tokens_details: v4.z.object({ image_tokens: v4.z.number().nullish(), text_tokens: v4.z.number().nullish() }).nullish() }).nullish() }) ) ); var modelMaxImagesPerCall = { "dall-e-3": 1, "dall-e-2": 10, "gpt-image-1": 10, "gpt-image-1-mini": 10, "gpt-image-1.5": 10, "gpt-image-2": 10 }; var hasDefaultResponseFormat = /* @__PURE__ */ new Set([ "gpt-image-1", "gpt-image-1-mini", "gpt-image-1.5", "gpt-image-2" ]); var baseImageModelOptionsObject = v4.z.object({ /** * Quality of the generated image(s). * * Valid values: `standard`, `hd`, `low`, `medium`, `high`, `auto`. */ quality: v4.z.enum(["standard", "hd", "low", "medium", "high", "auto"]).optional(), /** * Background behavior for the generated image(s). * * If `transparent`, the output format must support transparency * (i.e. `png` or `webp`). */ background: v4.z.enum(["transparent", "opaque", "auto"]).optional(), /** * Format in which the generated image(s) are returned. */ outputFormat: v4.z.enum(["png", "jpeg", "webp"]).optional(), /** * Compression level (0-100) for the generated image(s). Applies to the * `jpeg` and `webp` output formats. */ outputCompression: v4.z.number().int().min(0).max(100).optional(), /** * A unique identifier representing your end-user, which can help OpenAI * to monitor and detect abuse. */ user: v4.z.string().optional() }); chunkOCS2GTEN_cjs.lazyValidator( () => chunkOCS2GTEN_cjs.zodSchema(baseImageModelOptionsObject) ); var openaiImageModelGenerationOptions = chunkOCS2GTEN_cjs.lazyValidator( () => chunkOCS2GTEN_cjs.zodSchema( baseImageModelOptionsObject.extend({ /** * Style of the generated image. `vivid` produces hyper-real and * dramatic images; `natural` produces more subdued, less hyper-real * looking images. */ style: v4.z.enum(["vivid", "natural"]).optional(), /** * Content moderation level for the generated image(s). `low` applies * less restrictive filtering. */ moderation: v4.z.enum(["auto", "low"]).optional() }) ) ); var OpenAIImageModel = class { constructor(modelId, config) { this.modelId = modelId; this.config = config; this.specificationVersion = "v2"; } get maxImagesPerCall() { var _a; return (_a = modelMaxImagesPerCall[this.modelId]) != null ? _a : 1; } get provider() { return this.config.provider; } async doGenerate({ prompt, n, size, aspectRatio, seed, providerOptions, headers, abortSignal }) { var _a, _b, _c, _d; const warnings = []; if (aspectRatio != null) { warnings.push({ type: "unsupported-setting", setting: "aspectRatio", details: "This model does not support aspect ratio. Use `size` instead." }); } if (seed != null) { warnings.push({ type: "unsupported-setting", setting: "seed" }); } const currentDate = (_c = (_b = (_a = this.config._internal) == null ? void 0 : _a.currentDate) == null ? void 0 : _b.call(_a)) != null ? _c : /* @__PURE__ */ new Date(); const openaiOptions = (_d = await chunkOCS2GTEN_cjs.parseProviderOptions({ provider: "openai", providerOptions, schema: openaiImageModelGenerationOptions })) != null ? _d : {}; const { value: response, responseHeaders } = await chunkOCS2GTEN_cjs.postJsonToApi({ url: this.config.url({ path: "/images/generations", modelId: this.modelId }), headers: chunkOCS2GTEN_cjs.combineHeaders(this.config.headers(), headers), body: { model: this.modelId, prompt, n, size, quality: openaiOptions.quality, style: openaiOptions.style, background: openaiOptions.background, moderation: openaiOptions.moderation, output_format: openaiOptions.outputFormat, output_compression: openaiOptions.outputCompression, user: openaiOptions.user, ...!hasDefaultResponseFormat.has(this.modelId) ? { response_format: "b64_json" } : {} }, failedResponseHandler: openaiFailedResponseHandler, successfulResponseHandler: chunkOCS2GTEN_cjs.createJsonResponseHandler( openaiImageResponseSchema ), abortSignal, fetch: this.config.fetch }); return { images: response.data.map((item) => item.b64_json), warnings, response: { timestamp: currentDate, modelId: this.modelId, headers: responseHeaders }, providerMetadata: { openai: { images: response.data.map((item, index) => ({ ...item.revised_prompt ? { revisedPrompt: item.revised_prompt } : {}, ...response.created != null ? { created: response.created } : {}, ...response.size != null ? { size: response.size } : {}, ...response.quality != null ? { quality: response.quality } : {}, ...response.background != null ? { background: response.background } : {}, ...response.output_format != null ? { outputFormat: response.output_format } : {}, ...distributeTokenDetails( response.usage, index, response.data.length ) })) } } }; } }; function distributeTokenDetails(usage, index, total) { if (usage == null) { return {}; } const result = {}; const details = usage.input_tokens_details; if ((details == null ? void 0 : details.image_tokens) != null) { const base = Math.floor(details.image_tokens / total); const remainder = details.image_tokens - base * (total - 1); result.imageTokens = index === total - 1 ? remainder : base; } if ((details == null ? void 0 : details.text_tokens) != null) { const base = Math.floor(details.text_tokens / total); const remainder = details.text_tokens - base * (total - 1); result.textTokens = index === total - 1 ? remainder : base; } if (usage.input_tokens != null) { const base = Math.floor(usage.input_tokens / total); const remainder = usage.input_tokens - base * (total - 1); result.inputTokens = index === total - 1 ? remainder : base; } if (usage.output_tokens != null) { const base = Math.floor(usage.output_tokens / total); const remainder = usage.output_tokens - base * (total - 1); result.outputTokens = index === total - 1 ? remainder : base; } return result; } var codeInterpreterInputSchema = chunkOCS2GTEN_cjs.lazySchema( () => chunkOCS2GTEN_cjs.zodSchema( v4.z.object({ code: v4.z.string().nullish(), containerId: v4.z.string() }) ) ); var codeInterpreterOutputSchema = chunkOCS2GTEN_cjs.lazySchema( () => chunkOCS2GTEN_cjs.zodSchema( v4.z.object({ outputs: v4.z.array( v4.z.discriminatedUnion("type", [ v4.z.object({ type: v4.z.literal("logs"), logs: v4.z.string() }), v4.z.object({ type: v4.z.literal("image"), url: v4.z.string() }) ]) ).nullish() }) ) ); var codeInterpreterArgsSchema = chunkOCS2GTEN_cjs.lazySchema( () => chunkOCS2GTEN_cjs.zodSchema( v4.z.object({ container: v4.z.union([ v4.z.string(), v4.z.object({ fileIds: v4.z.array(v4.z.string()).optional() }) ]).optional() }) ) ); var codeInterpreterToolFactory = chunkOCS2GTEN_cjs.createProviderDefinedToolFactoryWithOutputSchema({ id: "openai.code_interpreter", name: "code_interpreter", inputSchema: codeInterpreterInputSchema, outputSchema: codeInterpreterOutputSchema }); var codeInterpreter = (args = {}) => { return codeInterpreterToolFactory(args); }; var comparisonFilterSchema = v4.z.object({ key: v4.z.string(), type: v4.z.enum(["eq", "ne", "gt", "gte", "lt", "lte", "in", "nin"]), value: v4.z.union([v4.z.string(), v4.z.number(), v4.z.boolean(), v4.z.array(v4.z.string())]) }); var compoundFilterSchema = v4.z.object({ type: v4.z.enum(["and", "or"]), filters: v4.z.array( v4.z.union([comparisonFilterSchema, v4.z.lazy(() => compoundFilterSchema)]) ) }); var fileSearchArgsSchema2 = chunkOCS2GTEN_cjs.lazySchema( () => chunkOCS2GTEN_cjs.zodSchema( v4.z.object({ vectorStoreIds: v4.z.array(v4.z.string()), maxNumResults: v4.z.number().optional(), ranking: v4.z.object({ ranker: v4.z.string().optional(), scoreThreshold: v4.z.number().optional() }).optional(), filters: v4.z.union([comparisonFilterSchema, compoundFilterSchema]).optional() }) ) ); var fileSearchOutputSchema = chunkOCS2GTEN_cjs.lazySchema( () => chunkOCS2GTEN_cjs.zodSchema( v4.z.object({ queries: v4.z.array(v4.z.string()), results: v4.z.array( v4.z.object({ attributes: v4.z.record(v4.z.string(), v4.z.unknown()), fileId: v4.z.string(), filename: v4.z.string(), score: v4.z.number(), text: v4.z.string() }) ).nullable() }) ) ); var fileSearch2 = chunkOCS2GTEN_cjs.createProviderDefinedToolFactoryWithOutputSchema({ id: "openai.file_search", name: "file_search", inputSchema: v4.z.object({}), outputSchema: fileSearchOutputSchema }); var imageGenerationArgsSchema = chunkOCS2GTEN_cjs.lazySchema( () => chunkOCS2GTEN_cjs.zodSchema( v4.z.object({ background: v4.z.enum(["auto", "opaque", "transparent"]).optional(), inputFidelity: v4.z.enum(["low", "high"]).optional(), inputImageMask: v4.z.object({ fileId: v4.z.string().optional(), imageUrl: v4.z.string().optional() }).optional(), model: v4.z.string().optional(), moderation: v4.z.enum(["auto"]).optional(), outputCompression: v4.z.number().int().min(0).max(100).optional(), outputFormat: v4.z.enum(["png", "jpeg", "webp"]).optional(), partialImages: v4.z.number().int().min(0).max(3).optional(), quality: v4.z.enum(["auto", "low", "medium", "high"]).optional(), size: v4.z.enum(["1024x1024", "1024x1536", "1536x1024", "auto"]).optional() }).strict() ) ); var imageGenerationInputSchema = chunkOCS2GTEN_cjs.lazySchema(() => chunkOCS2GTEN_cjs.zodSchema(v4.z.object({}))); var imageGenerationOutputSchema = chunkOCS2GTEN_cjs.lazySchema( () => chunkOCS2GTEN_cjs.zodSchema(v4.z.object({ result: v4.z.string() })) ); var imageGenerationToolFactory = chunkOCS2GTEN_cjs.createProviderDefinedToolFactoryWithOutputSchema({ id: "openai.image_generation", name: "image_generation", inputSchema: imageGenerationInputSchema, outputSchema: imageGenerationOutputSchema }); var imageGeneration = (args = {}) => { return imageGenerationToolFactory(args); }; var localShellInputSchema = chunkOCS2GTEN_cjs.lazySchema( () => chunkOCS2GTEN_cjs.zodSchema( v4.z.object({ action: v4.z.object({ type: v4.z.literal("exec"), command: v4.z.array(v4.z.string()), timeoutMs: v4.z.number().optional(), user: v4.z.string().optional(), workingDirectory: v4.z.string().optional(), env: v4.z.record(v4.z.string(), v4.z.string()).optional() }) }) ) ); var localShellOutputSchema = chunkOCS2GTEN_cjs.lazySchema( () => chunkOCS2GTEN_cjs.zodSchema(v4.z.object({ output: v4.z.string() })) ); var localShell = chunkOCS2GTEN_cjs.createProviderDefinedToolFactoryWithOutputSchema({ id: "openai.local_shell", name: "local_shell", inputSchema: localShellInputSchema, outputSchema: localShellOutputSchema }); var webSearchArgsSchema = chunkOCS2GTEN_cjs.lazySchema( () => chunkOCS2GTEN_cjs.zodSchema( v4.z.object({ externalWebAccess: v4.z.boolean().optional(), filters: v4.z.object({ allowedDomains: v4.z.array(v4.z.string()).optional() }).optional(), searchContextSize: v4.z.enum(["low", "medium", "high"]).optional(), userLocation: v4.z.object({ type: v4.z.literal("approximate"), country: v4.z.string().optional(), city: v4.z.string().optional(), region: v4.z.string().optional(), timezone: v4.z.string().optional() }).optional() }) ) ); var webSearchInputSchema = chunkOCS2GTEN_cjs.lazySchema(() => chunkOCS2GTEN_cjs.zodSchema(v4.z.object({}))); var webSearchOutputSchema = chunkOCS2GTEN_cjs.lazySchema( () => chunkOCS2GTEN_cjs.zodSchema( v4.z.object({ action: v4.z.discriminatedUnion("type", [ v4.z.object({ type: v4.z.literal("search"), query: v4.z.string().optional() }), v4.z.object({ type: v4.z.literal("openPage"), url: v4.z.string().nullish() }), v4.z.object({ type: v4.z.literal("findInPage"), url: v4.z.string().nullish(), pattern: v4.z.string().nullish() }) ]).optional(), sources: v4.z.array( v4.z.discriminatedUnion("type", [ v4.z.object({ type: v4.z.literal("url"), url: v4.z.string() }), v4.z.object({ type: v4.z.literal("api"), name: v4.z.string() }) ]) ).optional() }) ) ); var webSearchToolFactory = chunkOCS2GTEN_cjs.createProviderDefinedToolFactoryWithOutputSchema({ id: "openai.web_search", name: "web_search", inputSchema: webSearchInputSchema, outputSchema: webSearchOutputSchema }); var webSearch = (args = {}) => webSearchToolFactory(args); var webSearchPreviewArgsSchema = chunkOCS2GTEN_cjs.lazySchema( () => chunkOCS2GTEN_cjs.zodSchema( v4.z.object({ searchContextSize: v4.z.enum(["low", "medium", "high"]).optional(), userLocation: v4.z.object({ type: v4.z.literal("approximate"), country: v4.z.string().optional(), city: v4.z.string().optional(), region: v4.z.string().optional(), timezone: v4.z.string().optional() }).optional() }) ) ); var webSearchPreviewInputSchema = chunkOCS2GTEN_cjs.lazySchema( () => chunkOCS2GTEN_cjs.zodSchema(v4.z.object({})) ); var webSearchPreviewOutputSchema = chunkOCS2GTEN_cjs.lazySchema( () => chunkOCS2GTEN_cjs.zodSchema( v4.z.object({ action: v4.z.discriminatedUnion("type", [ v4.z.object({ type: v4.z.literal("search"), query: v4.z.string().optional() }), v4.z.object({ type: v4.z.literal("openPage"), url: v4.z.string().nullish() }), v4.z.object({ type: v4.z.literal("findInPage"), url: v4.z.string().nullish(), pattern: v4.z.string().nullish() }) ]).optional() }) ) ); var webSearchPreview = chunkOCS2GTEN_cjs.createProviderDefinedToolFactoryWithOutputSchema({ id: "openai.web_search_preview", name: "web_search_preview", inputSchema: webSearchPreviewInputSchema, outputSchema: webSearchPreviewOutputSchema }); var openaiTools = { /** * The Code Interpreter tool allows models to write and run Python code in a * sandboxed environment to solve complex problems in domains like data analysis, * coding, and math. * * @param container - The container to use for the code interpreter. * * Must have name `code_interpreter`. */ codeInterpreter, /** * File search is a tool available in the Responses API. It enables models to * retrieve information in a knowledge base of previously uploaded files through * semantic and keyword search. * * Must have name `file_search`. * * @param vectorStoreIds - The vector store IDs to use for the file search. * @param maxNumResults - The maximum number of results to return. * @param ranking - The ranking options to use for the file search. * @param filters - The filters to use for the file search. */ fileSearch: fileSearch2, /** * The image generation tool allows you to generate images using a text prompt, * and optionally image inputs. It leverages the GPT Image model, * and automatically optimizes text inputs for improved performance. * * Must have name `image_generation`. * * @param size - Image dimensions (e.g., 1024x1024, 1024x1536) * @param quality - Rendering quality (e.g. low, medium, high) * @param format - File output format * @param compression - Compression level (0-100%) for JPEG and WebP formats * @param background - Transparent or opaque */ imageGeneration, /** * Local shell is a tool that allows agents to run shell commands locally * on a machine you or the user provides. * * Supported models: `gpt-5-codex` and `codex-mini-latest` * * Must have name `local_shell`. */ localShell, /** * Web search allows models to access up-to-date information from the internet * and provide answers with sourced citations. * * Must have name `web_search_preview`. * * @param searchContextSize - The search context size to use for the web search. * @param userLocation - The user location to use for the web search. * * @deprecated Use `webSearch` instead. */ webSearchPreview, /** * Web search allows models to access up-to-date information from the internet * and provide answers with sourced citations. * * Must have name `web_search`. * * @param filters - The filters to use for the web search. * @param searchContextSize - The search context size to use for the web search. * @param userLocation - The user location to use for the web search. */ webSearch }; function isFileId(data, prefixes) { if (!prefixes) return false; return prefixes.some((prefix) => data.startsWith(prefix)); } async function convertToOpenAIResponsesInput({ prompt, systemMessageMode, fileIdPrefixes, store, hasLocalShellTool = false }) { var _a, _b, _c, _d, _e, _f; let input = []; const warnings = []; for (const { role, content } of prompt) { switch (role) { case "system": { switch (systemMessageMode) { case "system": { input.push({ role: "system", content }); break; } case "developer": { input.push({ role: "developer", content }); break; } case "remove": { warnings.push({ type: "other", message: "system messages are removed for this model" }); break; } default: { const _exhaustiveCheck = systemMessageMode; throw new Error( `Unsupported system message mode: ${_exhaustiveCheck}` ); } } break; } case "user": { input.push({ role: "user", content: content.map((part, index) => { var _a2, _b2, _c2; switch (part.type) { case "text": { return { type: "input_text", text: part.text }; } case "file": { if (part.mediaType.startsWith("image/")) { const mediaType = part.mediaType === "image/*" ? "image/jpeg" : part.mediaType; return { type: "input_image", ...part.data instanceof URL ? { image_url: part.data.toString() } : typeof part.data === "string" && isFileId(part.data, fileIdPrefixes) ? { file_id: part.data } : { image_url: `data:${mediaType};base64,${chunkOCS2GTEN_cjs.convertToBase64(part.data)}` }, detail: (_b2 = (_a2 = part.providerOptions) == null ? void 0 : _a2.openai) == null ? void 0 : _b2.imageDetail }; } else if (part.mediaType === "application/pdf") { if (part.data instanceof URL) { return { type: "input_file", file_url: part.data.toString() }; } return { type: "input_file", ...typeof part.data === "string" && isFileId(part.data, fileIdPrefixes) ? { file_id: part.data } : { filename: (_c2 = part.filename) != null ? _c2 : `part-${index}.pdf`, file_data: `data:application/pdf;base64,${chunkOCS2GTEN_cjs.convertToBase64(part.data)}` } }; } else { throw new chunkOCS2GTEN_cjs.UnsupportedFunctionalityError({ functionality: `file part media type ${part.mediaType}` }); } } } }) }); break; } case "assistant": { const reasoningMessages = {}; for (const part of content) { switch (part.type) { case "text": { const id = (_b = (_a = part.providerOptions) == null ? void 0 : _a.openai) == null ? void 0 : _b.itemId; const phase = (_d = (_c = part.providerOptions) == null ? void 0 : _c.openai) == null ? void 0 : _d.phase; if (store && id != null) { input.push({ type: "item_reference", id }); break; } input.push({ role: "assistant", content: [{ type: "output_text", text: part.text }], id, ...phase != null && { phase } }); break; } case "tool-call": { if (part.providerExecuted) { break; } const id = (_f = (_e = part.providerOptions) == null ? void 0 : _e.openai) == null ? void 0 : _f.itemId; if (store && id != null) { input.push({ type: "item_reference", id }); break; } if (hasLocalShellTool && part.toolName === "local_shell") { const parsedInput = await chunkOCS2GTEN_cjs.validateTypes({ value: part.input, schema: localShellInputSchema }); input.push({ type: "local_shell_call", call_id: part.toolCallId, id, action: { type: "exec", command: parsedInput.action.command, timeout_ms: parsedInput.action.timeoutMs, user: parsedInput.action.user, working_directory: parsedInput.action.workingDirectory, env: parsedInput.action.env } }); break; } input.push({ type: "function_call", call_id: part.toolCallId, name: part.toolName, arguments: JSON.stringify(part.input), id }); break; } // assistant tool result parts are from provider-executed tools: case "tool-result": { if (store) { input.push({ type: "item_reference", id: part.toolCallId }); } else { warnings.push({ type: "other", message: `Results for OpenAI tool ${part.toolName} are not sent to the API when store is false` }); } break; } case "reasoning": { const providerOptions = await chunkOCS2GTEN_cjs.parseProviderOptions({ provider: "openai", providerOptions: part.providerOptions, schema: openaiResponsesReasoningProviderOptionsSchema }); const reasoningId = providerOptions == null ? void 0 : providerOptions.itemId; if (reasoningId != null) { const reasoningMessage = reasoningMessages[reasoningId]; if (store) { if (reasoningMessage === void 0) { input.push({ type: "item_reference", id: reasoningId }); reasoningMessages[reasoningId] = { type: "reasoning", id: reasoningId, summary: [] }; } } else { const summaryParts = []; if (part.text.length > 0) { summaryParts.push({ type: "summary_text", text: part.text }); } else if (reasoningMessage !== void 0) { warnings.push({ type: "other", message: `Cannot append empty reasoning part to existing reasoning sequence. Skipping reasoning part: ${JSON.stringify(part)}.` }); } if (reasoningMessage === void 0) { reasoningMessages[reasoningId] = { type: "reasoning", id: reasoningId, encrypted_content: providerOptions == null ? void 0 : providerOptions.reasoningEncryptedContent, summary: summaryParts }; input.push(reasoningMessages[reasoningId]); } else { reasoningMessage.summary.push(...summaryParts); if ((providerOptions == null ? void 0 : providerOptions.reasoningEncryptedContent) != null) { reasoningMessage.encrypted_content = providerOptions.reasoningEncryptedContent; } } } } else { warnings.push({ type: "other", message: `Non-OpenAI reasoning parts are not supported. Skipping reasoning part: ${JSON.stringify(part)}.` }); } break; } } } break; } case "tool": { for (const part of content) { const output = part.output; if (hasLocalShellTool && part.toolName === "local_shell" && output.type === "json") { const parsedOutput = await chunkOCS2GTEN_cjs.validateTypes({ value: output.value, schema: localShellOutputSchema }); input.push({ type: "local_shell_call_output", call_id: part.toolCallId, output: parsedOutput.output }); break; } let contentValue; switch (output.type) { case "text": case "error-text": contentValue = output.value; break; case "json": case "error-json": contentValue = JSON.stringify(output.value); break; case "content": contentValue = output.value.map((item) => { switch (item.type) { case "text": { return { type: "input_text", text: item.text }; } case "media": { return item.mediaType.startsWith("image/") ? { type: "input_image", image_url: `data:${item.mediaType};base64,${item.data}` } : { type: "input_file", filename: "data", file_data: `data:${item.mediaType};base64,${item.data}` }; } } }); break; } input.push({ type: "function_call_output", call_id: part.toolCallId, output: contentValue }); } break; } default: { const _exhaustiveCheck = role; throw new Error(`Unsupported role: ${_exhaustiveCheck}`); } } } if (!store && input.some( (item) => "type" in item && item.type === "reasoning" && item.encrypted_content == null )) { warnings.push({ type: "other", message: "Reasoning parts without encrypted content are not supported when store is false. Skipping reasoning parts." }); input = input.filter( (item) => !("type" in item) || item.type !== "reasoning" || item.encrypted_content != null ); } return { input, warnings }; } var openaiResponsesReasoningProviderOptionsSchema = v4.z.object({ itemId: v4.z.string().nullish(), reasoningEncryptedContent: v4.z.string().nullish() }); function mapOpenAIResponseFinishReason({ finishReason, hasFunctionCall }) { switch (finishReason) { case void 0: case null: return hasFunctionCall ? "tool-calls" : "stop"; case "max_output_tokens": return "length"; case "content_filter": return "content-filter"; default: return hasFunctionCall ? "tool-calls" : "unknown"; } } var openaiResponsesChunkSchema = chunkOCS2GTEN_cjs.lazyValidator( () => chunkOCS2GTEN_cjs.zodSchema( v4.z.union([ v4.z.object({ type: v4.z.literal("response.output_text.delta"), item_id: v4.z.string(), delta: v4.z.string(), logprobs: v4.z.array( v4.z.object({ token: v4.z.string(), logprob: v4.z.number(), top_logprobs: v4.z.array( v4.z.object({ token: v4.z.string(), logprob: v4.z.number() }) ) }) ).nullish() }), v4.z.object({ type: v4.z.enum(["response.completed", "response.incomplete"]), response: v4.z.object({ incomplete_details: v4.z.object({ reason: v4.z.string() }).nullish(), usage: v4.z.object({ input_tokens: v4.z.number(), input_tokens_details: v4.z.object({ cached_tokens: v4.z.number().nullish() }).nullish(), output_tokens: v4.z.number(), output_tokens_details: v4.z.object({ reasoning_tokens: v4.z.number().nullish() }).nullish() }), service_tier: v4.z.string().nullish() }) }), v4.z.object({ type: v4.z.literal("response.created"), response: v4.z.object({ id: v4.z.string(), created_at: v4.z.number(), model: v4.z.string(), service_tier: v4.z.string().nullish() }) }), v4.z.object({ type: v4.z.literal("response.output_item.added"), output_index: v4.z.number(), item: v4.z.discriminatedUnion("type", [ v4.z.object({ type: v4.z.literal("message"), id: v4.z.string(), phase: v4.z.enum(["commentary", "final_answer"]).nullish() }), v4.z.object({ type: v4.z.literal("reasoning"), id: v4.z.string(), encrypted_content: v4.z.string().nullish() }), v4.z.object({ type: v4.z.literal("function_call"), id: v4.z.string(), call_id: v4.z.string(), name: v4.z.string(), arguments: v4.z.string() }), v4.z.object({ type: v4.z.literal("web_search_call"), id: v4.z.string(), status: v4.z.string() }), v4.z.object({ type: v4.z.literal("computer_call"), id: v4.z.string(), status: v4.z.string() }), v4.z.object({ type: v4.z.literal("file_search_call"), id: v4.z.string() }), v4.z.object({ type: v4.z.literal("image_generation_call"), id: v4.z.string() }), v4.z.object({ type: v4.z.literal("code_interpreter_call"), id: v4.z.string(), container_id: v4.z.string(), code: v4.z.string().nullable(), outputs: v4.z.array( v4.z.discriminatedUnion("type", [ v4.z.object({ type: v4.z.literal("logs"), logs: v4.z.string() }), v4.z.object({ type: v4.z.literal("image"), url: v4.z.string() }) ]) ).nullable(), status: v4.z.string() }) ]) }), v4.z.object({ type: v4.z.literal("response.output_item.done"), output_index: v4.z.number(), item: v4.z.discriminatedUnion("type", [ v4.z.object({ type: v4.z.literal("message"), id: v4.z.string(), phase: v4.z.enum(["commentary", "final_answer"]).nullish() }), v4.z.object({ type: v4.z.literal("reasoning"), id: v4.z.string(), encrypted_content: v4.z.string().nullish() }), v4.z.object({ type: v4.z.literal("function_call"), id: v4.z.string(), call_id: v4.z.string(), name: v4.z.string(), arguments: v4.z.string(), status: v4.z.literal("completed") }), v4.z.object({ type: v4.z.literal("code_interpreter_call"), id: v4.z.string(), code: v4.z.string().nullable(), container_id: v4.z.string(), outputs: v4.z.array( v4.z.discriminatedUnion("type", [ v4.z.object({ type: v4.z.literal("logs"), logs: v4.z.string() }), v4.z.object({ type: v4.z.literal("image"), url: v4.z.string() }) ]) ).nullable() }), v4.z.object({ type: v4.z.literal("image_generation_call"), id: v4.z.string(), result: v4.z.string() }), v4.z.object({ type: v4.z.literal("web_search_call"), id: v4.z.string(), status: v4.z.string(), action: v4.z.discriminatedUnion("type", [ v4.z.object({ type: v4.z.literal("search"), query: v4.z.string().nullish(), sources: v4.z.array( v4.z.discriminatedUnion("type", [ v4.z.object({ type: v4.z.literal("url"), url: v4.z.string() }), v4.z.object({ type: v4.z.literal("api"), name: v4.z.string() }) ]) ).nullish() }), v4.z.object({ type: v4.z.literal("open_page"), url: v4.z.string().nullish() }), v4.z.object({ type: v4.z.literal("find_in_page"), url: v4.z.string().nullish(), pattern: v4.z.string().nullish() }) ]).nullish() }), v4.z.object({ type: v4.z.literal("file_search_call"), id: v4.z.string(), queries: v4.z.array(v4.z.string()), results: v4.z.array( v4.z.object({ attributes: v4.z.record(v4.z.string(), v4.z.unknown()), file_id: v4.z.string(), filename: v4.z.string(), score: v4.z.number(), text: v4.z.string() }) ).nullish() }), v4.z.object({ type: v4.z.literal("local_shell_call"), id: v4.z.string(), call_id: v4.z.string(), action: v4.z.object({ type: v4.z.literal("exec"), command: v4.z.array(v4.z.string()), timeout_ms: v4.z.number().optional(), user: v4.z.string().optional(), working_directory: v4.z.string().optional(), env: v4.z.record(v4.z.string(), v4.z.string()).optional() }) }), v4.z.object({ type: v4.z.literal("computer_call"), id: v4.z.string(), status: v4.z.literal("completed") }) ]) }), v4.z.object({ type: v4.z.literal("response.function_call_arguments.delta"), item_id: v4.z.string(), output_index: v4.z.number(), delta: v4.z.string() }), v4.z.object({ type: v4.z.literal("response.image_generation_call.partial_image"), item_id: v4.z.string(), output_index: v4.z.number(), partial_image_b64: v4.z.string() }), v4.z.object({ type: v4.z.literal("response.code_interpreter_call_code.delta"), item_id: v4.z.string(), output_index: v4.z.number(), delta: v4.z.string() }), v4.z.object({ type: v4.z.literal("response.code_interpreter_call_code.done"), item_id: v4.z.string(), output_index: v4.z.number(), code: v4.z.string() }), v4.z.object({ type: v4.z.literal("response.output_text.annotation.added"), annotation: v4.z.discriminatedUnion("type", [ v4.z.object({ type: v4.z.literal("url_citation"), start_index: v4.z.number(), end_index: v4.z.number(), url: v4.z.string(), title: v4.z.string() }), v4.z.object({ type: v4.z.literal("file_citation"), file_id: v4.z.string(), filename: v4.z.string().nullish(), index: v4.z.number().nullish(), start_index: v4.z.number().nullish(), end_index: v4.z.number().nullish(), quote: v4.z.string().nullish() }) ]) }), v4.z.object({ type: v4.z.literal("response.reasoning_summary_part.added"), item_id: v4.z.string(), summary_index: v4.z.number() }), v4.z.object({ type: v4.z.literal("response.reasoning_summary_text.delta"), item_id: v4.z.string(), summary_index: v4.z.number(), delta: v4.z.string() }), v4.z.object({ type: v4.z.literal("response.reasoning_summary_part.done"), item_id: v4.z.string(), summary_index: v4.z.number() }), v4.z.object({ type: v4.z.literal("error"), sequence_number: v4.z.number(), error: v4.z.object({ type: v4.z.string(), code: v4.z.string(), message: v4.z.string(), param: v4.z.string().nullish() }) }), v4.z.object({ type: v4.z.string() }).loose().transform((value) => ({ type: "unknown_chunk", message: value.type })) // fallback for unknown chunks ]) ) ); var openaiResponsesResponseSchema = chunkOCS2GTEN_cjs.lazyValidator( () => chunkOCS2GTEN_cjs.zodSchema( v4.z.object({ id: v4.z.string().optional(), created_at: v4.z.number().optional(), error: v4.z.object({ message: v4.z.string(), type: v4.z.string(), param: v4.z.string().nullish(), code: v4.z.string() }).nullish(), model: v4.z.string().optional(), output: v4.z.array( v4.z.discriminatedUnion("type", [ v4.z.object({ type: v4.z.literal("message"), role: v4.z.literal("assistant"), id: v4.z.string(), phase: v4.z.enum(["commentary", "final_answer"]).nullish(), content: v4.z.array( v4.z.object({ type: v4.z.literal("output_text"), text: v4.z.string(), logprobs: v4.z.array( v4.z.object({ token: v4.z.string(), logprob: v4.z.number(), top_logprobs: v4.z.array( v4.z.object({ token: v4.z.string(), logprob: v4.z.number() }) ) }) ).nullish(), annotations: v4.z.array( v4.z.discriminatedUnion("type", [ v4.z.object({ type: v4.z.literal("url_citation"), start_index: v4.z.number(), end_index: v4.z.number(), url: v4.z.string(), title: v4.z.string() }), v4.z.object({ type: v4.z.literal("file_citation"), file_id: v4.z.string(), filename: v4.z.string().nullish(), index: v4.z.number().nullish(), start_index: v4.z.number().nullish(), end_index: v4.z.number().nullish(), quote: v4.z.string().nullish() }), v4.z.object({ type: v4.z.literal("container_file_citation"), container_id: v4.z.string(), file_id: v4.z.string(), filename: v4.z.string().nullish(), start_index: v4.z.number().nullish(), end_index: v4.z.number().nullish(), index: v4.z.number().nullish() }), v4.z.object({ type: v4.z.literal("file_path"), file_id: v4.z.string(), index: v4.z.number().nullish() }) ]) ) }) ) }), v4.z.object({ type: v4.z.literal("web_search_call"), id: v4.z.string(), status: v4.z.string(), action: v4.z.discriminatedUnion("type", [ v4.z.object({ type: v4.z.literal("search"), query: v4.z.string().nullish(), sources: v4.z.array( v4.z.discriminatedUnion("type", [ v4.z.object({ type: v4.z.literal("url"), url: v4.z.string() }), v4.z.object({ type: v4.z.literal("api"), name: v4.z.string() }) ]) ).nullish() }), v4.z.object({ type: v4.z.literal("open_page"), url: v4.z.string().nullish() }), v4.z.object({ type: v4.z.literal("find_in_page"), url: v4.z.string().nullish(), pattern: v4.z.string().nullish() }) ]).nullish() }), v4.z.object({ type: v4.z.literal("file_search_call"), id: v4.z.string(), queries: v4.z.array(v4.z.string()), results: v4.z.array( v4.z.object({ attributes: v4.z.record( v4.z.string(), v4.z.union([v4.z.string(), v4.z.number(), v4.z.boolean()]) ), file_id: v4.z.string(), filename: v4.z.string(), score: v4.z.number(), text: v4.z.string() }) ).nullish() }), v4.z.object({ type: v4.z.literal("code_interpreter_call"), id: v4.z.string(), code: v4.z.string().nullable(), container_id: v4.z.string(), outputs: v4.z.array( v4.z.discriminatedUnion("type", [ v4.z.object({ type: v4.z.literal("logs"), logs: v4.z.string() }), v4.z.object({ type: v4.z.literal("image"), url: v4.z.string() }) ]) ).nullable() }), v4.z.object({ type: v4.z.literal("image_generation_call"), id: v4.z.string(), result: v4.z.string() }), v4.z.object({ type: v4.z.literal("local_shell_call"), id: v4.z.string(), call_id: v4.z.string(), action: v4.z.object({ type: v4.z.literal("exec"), command: v4.z.array(v4.z.string()), timeout_ms: v4.z.number().optional(), user: v4.z.string().optional(), working_directory: v4.z.string().optional(), env: v4.z.record(v4.z.string(), v4.z.string()).optional() }) }), v4.z.object({ type: v4.z.literal("function_call"), call_id: v4.z.string(), name: v4.z.string(), arguments: v4.z.string(), id: v4.z.string() }), v4.z.object({ type: v4.z.literal("computer_call"), id: v4.z.string(), status: v4.z.string().optional() }), v4.z.object({ type: v4.z.literal("reasoning"), id: v4.z.string(), encrypted_content: v4.z.string().nullish(), summary: v4.z.array( v4.z.object({ type: v4.z.literal("summary_text"), text: v4.z.string() }) ) }) ]) ).optional(), service_tier: v4.z.string().nullish(), incomplete_details: v4.z.object({ reason: v4.z.string() }).nullish(), usage: v4.z.object({ input_tokens: v4.z.number(), input_tokens_details: v4.z.object({ cached_tokens: v4.z.number().nullish() }).nullish(), output_tokens: v4.z.number(), output_tokens_details: v4.z.object({ reasoning_tokens: v4.z.number().nullish() }).nullish() }).optional() }) ) ); var TOP_LOGPROBS_MAX = 20; var openaiResponsesProviderOptionsSchema = chunkOCS2GTEN_cjs.lazyValidator( () => chunkOCS2GTEN_cjs.zodSchema( v4.z.object({ conversation: v4.z.string().nullish(), include: v4.z.array( v4.z.enum([ "reasoning.encrypted_content", // handled internally by default, only needed for unknown reasoning models "file_search_call.results", "message.output_text.logprobs" ]) ).nullish(), instructions: v4.z.string().nullish(), /** * Return the log probabilities of the tokens. * * Setting to true will return the log probabilities of the tokens that * were generated. * * Setting to a number will return the log probabilities of the top n * tokens that were generated. * * @see https://platform.openai.com/docs/api-reference/responses/create * @see https://cookbook.openai.com/examples/using_logprobs */ logprobs: v4.z.union([v4.z.boolean(), v4.z.number().min(1).max(TOP_LOGPROBS_MAX)]).optional(), /** * The maximum number of total calls to built-in tools that can be processed in a response. * This maximum number applies across all built-in tool calls, not per individual tool. * Any further attempts to call a tool by the model will be ignored. */ maxToolCalls: v4.z.number().nullish(), metadata: v4.z.any().nullish(), parallelToolCalls: v4.z.boolean().nullish(), previousResponseId: v4.z.string().nullish(), promptCacheKey: v4.z.string().nullish(), /** * The retention policy for the prompt cache. * - 'in_memory': Default. Standard prompt caching behavior. * - '24h': Extended prompt caching that keeps cached prefixes active for up to 24 hours. * Currently only available for 5.1 series models. * * @default 'in_memory' */ promptCacheRetention: v4.z.enum(["in_memory", "24h"]).nullish(), /** * Reasoning effort for reasoning models. Defaults to `medium`. If you use * `providerOptions` to set the `reasoningEffort` option, this model setting will be ignored. * Valid values: 'none' | 'minimal' | 'low' | 'medium' | 'high' | 'xhigh' * * The 'none' type for `reasoningEffort` is only available for OpenAI's GPT-5.1 * models. Also, the 'xhigh' type for `reasoningEffort` is only available for * OpenAI's GPT-5.1-Codex-Max model. Setting `reasoningEffort` to 'none' or 'xhigh' with unsupported models will result in * an error. */ reasoningEffort: v4.z.string().nullish(), reasoningSummary: v4.z.string().nullish(), safetyIdentifier: v4.z.string().nullish(), serviceTier: v4.z.enum(["auto", "flex", "priority", "default"]).nullish(), store: v4.z.boolean().nullish(), strictJsonSchema: v4.z.boolean().nullish(), textVerbosity: v4.z.enum(["low", "medium", "high"]).nullish(), truncation: v4.z.enum(["auto", "disabled"]).nullish(), user: v4.z.string().nullish() }) ) ); async function prepareResponsesTools({ tools, toolChoice, strictJsonSchema }) { tools = (tools == null ? void 0 : tools.length) ? tools : void 0; const toolWarnings = []; if (tools == null) { return { tools: void 0, toolChoice: void 0, toolWarnings }; } const openaiTools2 = []; for (const tool of tools) { switch (tool.type) { case "function": openaiTools2.push({ type: "function", name: tool.name, description: tool.description, parameters: tool.inputSchema, strict: strictJsonSchema }); break; case "provider-defined": { switch (tool.id) { case "openai.file_search": { const args = await chunkOCS2GTEN_cjs.validateTypes({ value: tool.args, schema: fileSearchArgsSchema2 }); openaiTools2.push({ type: "file_search", vector_store_ids: args.vectorStoreIds, max_num_results: args.maxNumResults, ranking_options: args.ranking ? { ranker: args.ranking.ranker, score_threshold: args.ranking.scoreThreshold } : void 0, filters: args.filters }); break; } case "openai.local_shell": { openaiTools2.push({ type: "local_shell" }); break; } case "openai.web_search_preview": { const args = await chunkOCS2GTEN_cjs.validateTypes({ value: tool.args, schema: webSearchPreviewArgsSchema }); openaiTools2.push({ type: "web_search_preview", search_context_size: args.searchContextSize, user_location: args.userLocation }); break; } case "openai.web_search": { const args = await chunkOCS2GTEN_cjs.validateTypes({ value: tool.args, schema: webSearchArgsSchema }); openaiTools2.push({ type: "web_search", filters: args.filters != null ? { allowed_domains: args.filters.allowedDomains } : void 0, external_web_access: args.externalWebAccess, search_context_size: args.searchContextSize, user_location: args.userLocation }); break; } case "openai.code_interpreter": { const args = await chunkOCS2GTEN_cjs.validateTypes({ value: tool.args, schema: codeInterpreterArgsSchema }); openaiTools2.push({ type: "code_interpreter", container: args.container == null ? { type: "auto", file_ids: void 0 } : typeof args.container === "string" ? args.container : { type: "auto", file_ids: args.container.fileIds } }); break; } case "openai.image_generation": { const args = await chunkOCS2GTEN_cjs.validateTypes({ value: tool.args, schema: imageGenerationArgsSchema }); openaiTools2.push({ type: "image_generation", background: args.background, input_fidelity: args.inputFidelity, input_image_mask: args.inputImageMask ? { file_id: args.inputImageMask.fileId, image_url: args.inputImageMask.imageUrl } : void 0, model: args.model, size: args.size, quality: args.quality, moderation: args.moderation, output_format: args.outputFormat, output_compression: args.outputCompression }); break; } } break; } default: toolWarnings.push({ type: "unsupported-tool", tool }); break; } } if (toolChoice == null) { return { tools: openaiTools2, toolChoice: void 0, toolWarnings }; } const type = toolChoice.type; switch (type) { case "auto": case "none": case "required": return { tools: openaiTools2, toolChoice: type, toolWarnings }; case "tool": return { tools: openaiTools2, toolChoice: toolChoice.toolName === "code_interpreter" || toolChoice.toolName === "file_search" || toolChoice.toolName === "image_generation" || toolChoice.toolName === "web_search_preview" || toolChoice.toolName === "web_search" ? { type: toolChoice.toolName } : { type: "function", name: toolChoice.toolName }, toolWarnings }; default: { const _exhaustiveCheck = type; throw new chunkOCS2GTEN_cjs.UnsupportedFunctionalityError({ functionality: `tool choice type: ${_exhaustiveCheck}` }); } } } var OpenAIResponsesLanguageModel = class { constructor(modelId, config) { this.specificationVersion = "v2"; this.supportedUrls = { "image/*": [/^https?:\/\/.*$/], "application/pdf": [/^https?:\/\/.*$/] }; this.modelId = modelId; this.config = config; } get provider() { return this.config.provider; } async getArgs({ maxOutputTokens, temperature, stopSequences, topP, topK, presencePenalty, frequencyPenalty, seed, prompt, providerOptions, tools, toolChoice, responseFormat }) { var _a, _b, _c, _d; const warnings = []; const modelCapabilities = getOpenAILanguageModelCapabilities(this.modelId); if (topK != null) { warnings.push({ type: "unsupported-setting", setting: "topK" }); } if (seed != null) { warnings.push({ type: "unsupported-setting", setting: "seed" }); } if (presencePenalty != null) { warnings.push({ type: "unsupported-setting", setting: "presencePenalty" }); } if (frequencyPenalty != null) { warnings.push({ type: "unsupported-setting", setting: "frequencyPenalty" }); } if (stopSequences != null) { warnings.push({ type: "unsupported-setting", setting: "stopSequences" }); } const openaiOptions = await chunkOCS2GTEN_cjs.parseProviderOptions({ provider: "openai", providerOptions, schema: openaiResponsesProviderOptionsSchema }); if ((openaiOptions == null ? void 0 : openaiOptions.conversation) && (openaiOptions == null ? void 0 : openaiOptions.previousResponseId)) { warnings.push({ type: "unsupported-setting", setting: "conversation", details: "conversation and previousResponseId cannot be used together" }); } const { input, warnings: inputWarnings } = await convertToOpenAIResponsesInput({ prompt, systemMessageMode: modelCapabilities.systemMessageMode, fileIdPrefixes: this.config.fileIdPrefixes, store: (_a = openaiOptions == null ? void 0 : openaiOptions.store) != null ? _a : true, hasLocalShellTool: hasOpenAITool("openai.local_shell") }); warnings.push(...inputWarnings); const strictJsonSchema = (_b = openaiOptions == null ? void 0 : openaiOptions.strictJsonSchema) != null ? _b : false; let include = openaiOptions == null ? void 0 : openaiOptions.include; function addInclude(key) { if (include == null) { include = [key]; } else if (!include.includes(key)) { include = [...include, key]; } } function hasOpenAITool(id) { return (tools == null ? void 0 : tools.find( (tool) => tool.type === "provider-defined" && tool.id === id )) != null; } const topLogprobs = typeof (openaiOptions == null ? void 0 : openaiOptions.logprobs) === "number" ? openaiOptions == null ? void 0 : openaiOptions.logprobs : (openaiOptions == null ? void 0 : openaiOptions.logprobs) === true ? TOP_LOGPROBS_MAX : void 0; if (topLogprobs) { addInclude("message.output_text.logprobs"); } const webSearchToolName = (_c = tools == null ? void 0 : tools.find( (tool) => tool.type === "provider-defined" && (tool.id === "openai.web_search" || tool.id === "openai.web_search_preview") )) == null ? void 0 : _c.name; if (webSearchToolName) { addInclude("web_search_call.action.sources"); } if (hasOpenAITool("openai.code_interpreter")) { addInclude("code_interpreter_call.outputs"); } const store = openaiOptions == null ? void 0 : openaiOptions.store; if (store === false && modelCapabilities.isReasoningModel) { addInclude("reasoning.encrypted_content"); } const baseArgs = { model: this.modelId, input, temperature, top_p: topP, max_output_tokens: maxOutputTokens, ...((responseFormat == null ? void 0 : responseFormat.type) === "json" || (openaiOptions == null ? void 0 : openaiOptions.textVerbosity)) && { text: { ...(responseFormat == null ? void 0 : responseFormat.type) === "json" && { format: responseFormat.schema != null ? { type: "json_schema", strict: strictJsonSchema, name: (_d = responseFormat.name) != null ? _d : "response", description: responseFormat.description, schema: responseFormat.schema } : { type: "json_object" } }, ...(openaiOptions == null ? void 0 : openaiOptions.textVerbosity) && { verbosity: openaiOptions.textVerbosity } } }, // provider options: conversation: openaiOptions == null ? void 0 : openaiOptions.conversation, max_tool_calls: openaiOptions == null ? void 0 : openaiOptions.maxToolCalls, metadata: openaiOptions == null ? void 0 : openaiOptions.metadata, parallel_tool_calls: openaiOptions == null ? void 0 : openaiOptions.parallelToolCalls, previous_response_id: openaiOptions == null ? void 0 : openaiOptions.previousResponseId, store, user: openaiOptions == null ? void 0 : openaiOptions.user, instructions: openaiOptions == null ? void 0 : openaiOptions.instructions, service_tier: openaiOptions == null ? void 0 : openaiOptions.serviceTier, include, prompt_cache_key: openaiOptions == null ? void 0 : openaiOptions.promptCacheKey, prompt_cache_retention: openaiOptions == null ? void 0 : openaiOptions.promptCacheRetention, safety_identifier: openaiOptions == null ? void 0 : openaiOptions.safetyIdentifier, top_logprobs: topLogprobs, truncation: openaiOptions == null ? void 0 : openaiOptions.truncation, // model-specific settings: ...modelCapabilities.isReasoningModel && ((openaiOptions == null ? void 0 : openaiOptions.reasoningEffort) != null || (openaiOptions == null ? void 0 : openaiOptions.reasoningSummary) != null) && { reasoning: { ...(openaiOptions == null ? void 0 : openaiOptions.reasoningEffort) != null && { effort: openaiOptions.reasoningEffort }, ...(openaiOptions == null ? void 0 : openaiOptions.reasoningSummary) != null && { summary: openaiOptions.reasoningSummary } } } }; if (modelCapabilities.isReasoningModel) { if (!((openaiOptions == null ? void 0 : openaiOptions.reasoningEffort) === "none" && modelCapabilities.supportsNonReasoningParameters)) { if (baseArgs.temperature != null) { baseArgs.temperature = void 0; warnings.push({ type: "unsupported-setting", setting: "temperature", details: "temperature is not supported for reasoning models" }); } if (baseArgs.top_p != null) { baseArgs.top_p = void 0; warnings.push({ type: "unsupported-setting", setting: "topP", details: "topP is not supported for reasoning models" }); } } } else { if ((openaiOptions == null ? void 0 : openaiOptions.reasoningEffort) != null) { warnings.push({ type: "unsupported-setting", setting: "reasoningEffort", details: "reasoningEffort is not supported for non-reasoning models" }); } if ((openaiOptions == null ? void 0 : openaiOptions.reasoningSummary) != null) { warnings.push({ type: "unsupported-setting", setting: "reasoningSummary", details: "reasoningSummary is not supported for non-reasoning models" }); } } if ((openaiOptions == null ? void 0 : openaiOptions.serviceTier) === "flex" && !modelCapabilities.supportsFlexProcessing) { warnings.push({ type: "unsupported-setting", setting: "serviceTier", details: "flex processing is only available for o3, o4-mini, and gpt-5 models" }); delete baseArgs.service_tier; } if ((openaiOptions == null ? void 0 : openaiOptions.serviceTier) === "priority" && !modelCapabilities.supportsPriorityProcessing) { warnings.push({ type: "unsupported-setting", setting: "serviceTier", details: "priority processing is only available for supported models (gpt-4, gpt-5, gpt-5-mini, o3, o4-mini) and requires Enterprise access. gpt-5-nano is not supported" }); delete baseArgs.service_tier; } const { tools: openaiTools2, toolChoice: openaiToolChoice, toolWarnings } = await prepareResponsesTools({ tools, toolChoice, strictJsonSchema }); return { webSearchToolName, args: { ...baseArgs, tools: openaiTools2, tool_choice: openaiToolChoice }, warnings: [...warnings, ...toolWarnings], store }; } async doGenerate(options) { var _a, _b, _c, _d, _e, _f, _g, _h, _i, _j, _k, _l, _m, _n, _o, _p, _q, _r, _s, _t, _u, _v, _w, _x, _y, _z, _A, _B; const { args: body, warnings, webSearchToolName } = await this.getArgs(options); const url = this.config.url({ path: "/responses", modelId: this.modelId }); const providerKey = this.config.provider.replace(".responses", ""); const { responseHeaders, value: response, rawValue: rawResponse } = await chunkOCS2GTEN_cjs.postJsonToApi({ url, headers: chunkOCS2GTEN_cjs.combineHeaders(this.config.headers(), options.headers), body, failedResponseHandler: openaiFailedResponseHandler, successfulResponseHandler: chunkOCS2GTEN_cjs.createJsonResponseHandler( openaiResponsesResponseSchema ), abortSignal: options.abortSignal, fetch: this.config.fetch }); if (response.error) { throw new chunkOCS2GTEN_cjs.APICallError({ message: response.error.message, url, requestBodyValues: body, statusCode: 400, responseHeaders, responseBody: rawResponse, isRetryable: false }); } const content = []; const logprobs = []; let hasFunctionCall = false; for (const part of response.output) { switch (part.type) { case "reasoning": { if (part.summary.length === 0) { part.summary.push({ type: "summary_text", text: "" }); } for (const summary of part.summary) { content.push({ type: "reasoning", text: summary.text, providerMetadata: { [providerKey]: { itemId: part.id, reasoningEncryptedContent: (_a = part.encrypted_content) != null ? _a : null } } }); } break; } case "image_generation_call": { content.push({ type: "tool-call", toolCallId: part.id, toolName: "image_generation", input: "{}", providerExecuted: true }); content.push({ type: "tool-result", toolCallId: part.id, toolName: "image_generation", result: { result: part.result }, providerExecuted: true }); break; } case "local_shell_call": { content.push({ type: "tool-call", toolCallId: part.call_id, toolName: "local_shell", input: JSON.stringify({ action: part.action }), providerMetadata: { [providerKey]: { itemId: part.id } } }); break; } case "message": { for (const contentPart of part.content) { if (((_c = (_b = options.providerOptions) == null ? void 0 : _b.openai) == null ? void 0 : _c.logprobs) && contentPart.logprobs) { logprobs.push(contentPart.logprobs); } content.push({ type: "text", text: contentPart.text, providerMetadata: { [providerKey]: { itemId: part.id, ...part.phase != null && { phase: part.phase } } } }); for (const annotation of contentPart.annotations) { if (annotation.type === "url_citation") { content.push({ type: "source", sourceType: "url", id: (_f = (_e = (_d = this.config).generateId) == null ? void 0 : _e.call(_d)) != null ? _f : chunkOCS2GTEN_cjs.generateId(), url: annotation.url, title: annotation.title }); } else if (annotation.type === "file_citation") { content.push({ type: "source", sourceType: "document", id: (_i = (_h = (_g = this.config).generateId) == null ? void 0 : _h.call(_g)) != null ? _i : chunkOCS2GTEN_cjs.generateId(), mediaType: "text/plain", title: (_k = (_j = annotation.quote) != null ? _j : annotation.filename) != null ? _k : "Document", filename: (_l = annotation.filename) != null ? _l : annotation.file_id, ...annotation.file_id ? { providerMetadata: { [providerKey]: { fileId: annotation.file_id } } } : {} }); } else if (annotation.type === "container_file_citation") { content.push({ type: "source", sourceType: "document", id: (_o = (_n = (_m = this.config).generateId) == null ? void 0 : _n.call(_m)) != null ? _o : chunkOCS2GTEN_cjs.generateId(), mediaType: "text/plain", title: (_q = (_p = annotation.filename) != null ? _p : annotation.file_id) != null ? _q : "Document", filename: (_r = annotation.filename) != null ? _r : annotation.file_id, providerMetadata: { [providerKey]: { fileId: annotation.file_id, containerId: annotation.container_id, ...annotation.index != null ? { index: annotation.index } : {} } } }); } else if (annotation.type === "file_path") { content.push({ type: "source", sourceType: "document", id: (_u = (_t = (_s = this.config).generateId) == null ? void 0 : _t.call(_s)) != null ? _u : chunkOCS2GTEN_cjs.generateId(), mediaType: "application/octet-stream", title: annotation.file_id, filename: annotation.file_id, providerMetadata: { [providerKey]: { fileId: annotation.file_id, ...annotation.index != null ? { index: annotation.index } : {} } } }); } } } break; } case "function_call": { hasFunctionCall = true; content.push({ type: "tool-call", toolCallId: part.call_id, toolName: part.name, input: part.arguments, providerMetadata: { [providerKey]: { itemId: part.id } } }); break; } case "web_search_call": { content.push({ type: "tool-call", toolCallId: part.id, toolName: webSearchToolName != null ? webSearchToolName : "web_search", input: JSON.stringify({}), providerExecuted: true }); content.push({ type: "tool-result", toolCallId: part.id, toolName: webSearchToolName != null ? webSearchToolName : "web_search", result: mapWebSearchOutput(part.action), providerExecuted: true }); break; } case "computer_call": { content.push({ type: "tool-call", toolCallId: part.id, toolName: "computer_use", input: "", providerExecuted: true }); content.push({ type: "tool-result", toolCallId: part.id, toolName: "computer_use", result: { type: "computer_use_tool_result", status: part.status || "completed" }, providerExecuted: true }); break; } case "file_search_call": { content.push({ type: "tool-call", toolCallId: part.id, toolName: "file_search", input: "{}", providerExecuted: true }); content.push({ type: "tool-result", toolCallId: part.id, toolName: "file_search", result: { queries: part.queries, results: (_w = (_v = part.results) == null ? void 0 : _v.map((result) => ({ attributes: result.attributes, fileId: result.file_id, filename: result.filename, score: result.score, text: result.text }))) != null ? _w : null }, providerExecuted: true }); break; } case "code_interpreter_call": { content.push({ type: "tool-call", toolCallId: part.id, toolName: "code_interpreter", input: JSON.stringify({ code: part.code, containerId: part.container_id }), providerExecuted: true }); content.push({ type: "tool-result", toolCallId: part.id, toolName: "code_interpreter", result: { outputs: part.outputs }, providerExecuted: true }); break; } } } const providerMetadata = { [providerKey]: { ...response.id != null ? { responseId: response.id } : {} } }; if (logprobs.length > 0) { providerMetadata[providerKey].logprobs = logprobs; } if (typeof response.service_tier === "string") { providerMetadata[providerKey].serviceTier = response.service_tier; } const usage = response.usage; return { content, finishReason: mapOpenAIResponseFinishReason({ finishReason: (_x = response.incomplete_details) == null ? void 0 : _x.reason, hasFunctionCall }), usage: { inputTokens: usage.input_tokens, outputTokens: usage.output_tokens, totalTokens: usage.input_tokens + usage.output_tokens, reasoningTokens: (_z = (_y = usage.output_tokens_details) == null ? void 0 : _y.reasoning_tokens) != null ? _z : void 0, cachedInputTokens: (_B = (_A = usage.input_tokens_details) == null ? void 0 : _A.cached_tokens) != null ? _B : void 0 }, request: { body }, response: { id: response.id, timestamp: new Date(response.created_at * 1e3), modelId: response.model, headers: responseHeaders, body: rawResponse }, providerMetadata, warnings }; } async doStream(options) { const { args: body, warnings, webSearchToolName, store } = await this.getArgs(options); const { responseHeaders, value: response } = await chunkOCS2GTEN_cjs.postJsonToApi({ url: this.config.url({ path: "/responses", modelId: this.modelId }), headers: chunkOCS2GTEN_cjs.combineHeaders(this.config.headers(), options.headers), body: { ...body, stream: true }, failedResponseHandler: openaiFailedResponseHandler, successfulResponseHandler: chunkOCS2GTEN_cjs.createEventSourceResponseHandler( openaiResponsesChunkSchema ), abortSignal: options.abortSignal, fetch: this.config.fetch }); const self = this; const providerKey = this.config.provider.replace(".responses", ""); let finishReason = "unknown"; const usage = { inputTokens: void 0, outputTokens: void 0, totalTokens: void 0 }; const logprobs = []; let responseId = null; const ongoingToolCalls = {}; const ongoingAnnotations = []; let activeMessagePhase; let hasFunctionCall = false; const activeReasoning = {}; let serviceTier; return { stream: response.pipeThrough( new TransformStream({ start(controller) { controller.enqueue({ type: "stream-start", warnings }); }, transform(chunk, controller) { var _a, _b, _c, _d, _e, _f, _g, _h, _i, _j, _k, _l, _m, _n, _o, _p, _q, _r, _s, _t, _u, _v, _w, _x; if (options.includeRawChunks) { controller.enqueue({ type: "raw", rawValue: chunk.rawValue }); } if (!chunk.success) { finishReason = "error"; controller.enqueue({ type: "error", error: chunk.error }); return; } const value = chunk.value; if (isResponseOutputItemAddedChunk(value)) { if (value.item.type === "function_call") { ongoingToolCalls[value.output_index] = { toolName: value.item.name, toolCallId: value.item.call_id }; controller.enqueue({ type: "tool-input-start", id: value.item.call_id, toolName: value.item.name }); } else if (value.item.type === "web_search_call") { ongoingToolCalls[value.output_index] = { toolName: webSearchToolName != null ? webSearchToolName : "web_search", toolCallId: value.item.id }; controller.enqueue({ type: "tool-input-start", id: value.item.id, toolName: webSearchToolName != null ? webSearchToolName : "web_search", providerExecuted: true }); controller.enqueue({ type: "tool-input-end", id: value.item.id }); controller.enqueue({ type: "tool-call", toolCallId: value.item.id, toolName: webSearchToolName != null ? webSearchToolName : "web_search", input: JSON.stringify({}), providerExecuted: true }); } else if (value.item.type === "computer_call") { ongoingToolCalls[value.output_index] = { toolName: "computer_use", toolCallId: value.item.id }; controller.enqueue({ type: "tool-input-start", id: value.item.id, toolName: "computer_use", providerExecuted: true }); } else if (value.item.type === "code_interpreter_call") { ongoingToolCalls[value.output_index] = { toolName: "code_interpreter", toolCallId: value.item.id, codeInterpreter: { containerId: value.item.container_id } }; controller.enqueue({ type: "tool-input-start", id: value.item.id, toolName: "code_interpreter", providerExecuted: true }); controller.enqueue({ type: "tool-input-delta", id: value.item.id, delta: `{"containerId":"${value.item.container_id}","code":"` }); } else if (value.item.type === "file_search_call") { controller.enqueue({ type: "tool-call", toolCallId: value.item.id, toolName: "file_search", input: "{}", providerExecuted: true }); } else if (value.item.type === "image_generation_call") { controller.enqueue({ type: "tool-call", toolCallId: value.item.id, toolName: "image_generation", input: "{}", providerExecuted: true }); } else if (value.item.type === "message") { ongoingAnnotations.splice(0, ongoingAnnotations.length); activeMessagePhase = (_a = value.item.phase) != null ? _a : void 0; controller.enqueue({ type: "text-start", id: value.item.id, providerMetadata: { [providerKey]: { itemId: value.item.id, ...value.item.phase != null && { phase: value.item.phase } } } }); } else if (isResponseOutputItemAddedChunk(value) && value.item.type === "reasoning") { activeReasoning[value.item.id] = { encryptedContent: value.item.encrypted_content, summaryParts: { 0: "active" } }; controller.enqueue({ type: "reasoning-start", id: `${value.item.id}:0`, providerMetadata: { [providerKey]: { itemId: value.item.id, reasoningEncryptedContent: (_b = value.item.encrypted_content) != null ? _b : null } } }); } } else if (isResponseOutputItemDoneChunk(value)) { if (value.item.type === "message") { const phase = (_c = value.item.phase) != null ? _c : activeMessagePhase; activeMessagePhase = void 0; controller.enqueue({ type: "text-end", id: value.item.id, providerMetadata: { [providerKey]: { itemId: value.item.id, ...phase != null && { phase }, ...ongoingAnnotations.length > 0 && { annotations: ongoingAnnotations } } } }); } else if (value.item.type === "function_call") { ongoingToolCalls[value.output_index] = void 0; hasFunctionCall = true; controller.enqueue({ type: "tool-input-end", id: value.item.call_id }); controller.enqueue({ type: "tool-call", toolCallId: value.item.call_id, toolName: value.item.name, input: value.item.arguments, providerMetadata: { [providerKey]: { itemId: value.item.id } } }); } else if (value.item.type === "web_search_call") { ongoingToolCalls[value.output_index] = void 0; controller.enqueue({ type: "tool-result", toolCallId: value.item.id, toolName: webSearchToolName != null ? webSearchToolName : "web_search", result: mapWebSearchOutput(value.item.action), providerExecuted: true }); } else if (value.item.type === "computer_call") { ongoingToolCalls[value.output_index] = void 0; controller.enqueue({ type: "tool-input-end", id: value.item.id }); controller.enqueue({ type: "tool-call", toolCallId: value.item.id, toolName: "computer_use", input: "", providerExecuted: true }); controller.enqueue({ type: "tool-result", toolCallId: value.item.id, toolName: "computer_use", result: { type: "computer_use_tool_result", status: value.item.status || "completed" }, providerExecuted: true }); } else if (value.item.type === "file_search_call") { ongoingToolCalls[value.output_index] = void 0; controller.enqueue({ type: "tool-result", toolCallId: value.item.id, toolName: "file_search", result: { queries: value.item.queries, results: (_e = (_d = value.item.results) == null ? void 0 : _d.map((result) => ({ attributes: result.attributes, fileId: result.file_id, filename: result.filename, score: result.score, text: result.text }))) != null ? _e : null }, providerExecuted: true }); } else if (value.item.type === "code_interpreter_call") { ongoingToolCalls[value.output_index] = void 0; controller.enqueue({ type: "tool-result", toolCallId: value.item.id, toolName: "code_interpreter", result: { outputs: value.item.outputs }, providerExecuted: true }); } else if (value.item.type === "image_generation_call") { controller.enqueue({ type: "tool-result", toolCallId: value.item.id, toolName: "image_generation", result: { result: value.item.result }, providerExecuted: true }); } else if (value.item.type === "local_shell_call") { ongoingToolCalls[value.output_index] = void 0; controller.enqueue({ type: "tool-call", toolCallId: value.item.call_id, toolName: "local_shell", input: JSON.stringify({ action: { type: "exec", command: value.item.action.command, timeoutMs: value.item.action.timeout_ms, user: value.item.action.user, workingDirectory: value.item.action.working_directory, env: value.item.action.env } }), providerMetadata: { [providerKey]: { itemId: value.item.id } } }); } else if (value.item.type === "reasoning") { const activeReasoningPart = activeReasoning[value.item.id]; const summaryPartIndices = Object.entries( activeReasoningPart.summaryParts ).filter( ([_, status]) => status === "active" || status === "can-conclude" ).map(([summaryIndex]) => summaryIndex); for (const summaryIndex of summaryPartIndices) { controller.enqueue({ type: "reasoning-end", id: `${value.item.id}:${summaryIndex}`, providerMetadata: { [providerKey]: { itemId: value.item.id, reasoningEncryptedContent: (_f = value.item.encrypted_content) != null ? _f : null } } }); } delete activeReasoning[value.item.id]; } } else if (isResponseFunctionCallArgumentsDeltaChunk(value)) { const toolCall = ongoingToolCalls[value.output_index]; if (toolCall != null) { controller.enqueue({ type: "tool-input-delta", id: toolCall.toolCallId, delta: value.delta }); } } else if (isResponseCodeInterpreterCallCodeDeltaChunk(value)) { const toolCall = ongoingToolCalls[value.output_index]; if (toolCall != null) { controller.enqueue({ type: "tool-input-delta", id: toolCall.toolCallId, // The delta is code, which is embedding in a JSON string. // To escape it, we use JSON.stringify and slice to remove the outer quotes. delta: JSON.stringify(value.delta).slice(1, -1) }); } } else if (isResponseCodeInterpreterCallCodeDoneChunk(value)) { const toolCall = ongoingToolCalls[value.output_index]; if (toolCall != null) { controller.enqueue({ type: "tool-input-delta", id: toolCall.toolCallId, delta: '"}' }); controller.enqueue({ type: "tool-input-end", id: toolCall.toolCallId }); controller.enqueue({ type: "tool-call", toolCallId: toolCall.toolCallId, toolName: "code_interpreter", input: JSON.stringify({ code: value.code, containerId: toolCall.codeInterpreter.containerId }), providerExecuted: true }); } } else if (isResponseCreatedChunk(value)) { responseId = value.response.id; controller.enqueue({ type: "response-metadata", id: value.response.id, timestamp: new Date(value.response.created_at * 1e3), modelId: value.response.model }); } else if (isTextDeltaChunk(value)) { controller.enqueue({ type: "text-delta", id: value.item_id, delta: value.delta }); if (((_h = (_g = options.providerOptions) == null ? void 0 : _g.openai) == null ? void 0 : _h.logprobs) && value.logprobs) { logprobs.push(value.logprobs); } } else if (value.type === "response.reasoning_summary_part.added") { if (value.summary_index > 0) { const activeReasoningPart = activeReasoning[value.item_id]; activeReasoningPart.summaryParts[value.summary_index] = "active"; for (const summaryIndex of Object.keys( activeReasoningPart.summaryParts )) { if (activeReasoningPart.summaryParts[summaryIndex] === "can-conclude") { controller.enqueue({ type: "reasoning-end", id: `${value.item_id}:${summaryIndex}`, providerMetadata: { [providerKey]: { itemId: value.item_id } } }); activeReasoningPart.summaryParts[summaryIndex] = "concluded"; } } controller.enqueue({ type: "reasoning-start", id: `${value.item_id}:${value.summary_index}`, providerMetadata: { [providerKey]: { itemId: value.item_id, reasoningEncryptedContent: (_j = (_i = activeReasoning[value.item_id]) == null ? void 0 : _i.encryptedContent) != null ? _j : null } } }); } } else if (value.type === "response.reasoning_summary_text.delta") { controller.enqueue({ type: "reasoning-delta", id: `${value.item_id}:${value.summary_index}`, delta: value.delta, providerMetadata: { [providerKey]: { itemId: value.item_id } } }); } else if (value.type === "response.reasoning_summary_part.done") { if (store) { controller.enqueue({ type: "reasoning-end", id: `${value.item_id}:${value.summary_index}`, providerMetadata: { [providerKey]: { itemId: value.item_id } } }); activeReasoning[value.item_id].summaryParts[value.summary_index] = "concluded"; } else { activeReasoning[value.item_id].summaryParts[value.summary_index] = "can-conclude"; } } else if (isResponseFinishedChunk(value)) { finishReason = mapOpenAIResponseFinishReason({ finishReason: (_k = value.response.incomplete_details) == null ? void 0 : _k.reason, hasFunctionCall }); usage.inputTokens = value.response.usage.input_tokens; usage.outputTokens = value.response.usage.output_tokens; usage.totalTokens = value.response.usage.input_tokens + value.response.usage.output_tokens; usage.reasoningTokens = (_m = (_l = value.response.usage.output_tokens_details) == null ? void 0 : _l.reasoning_tokens) != null ? _m : void 0; usage.cachedInputTokens = (_o = (_n = value.response.usage.input_tokens_details) == null ? void 0 : _n.cached_tokens) != null ? _o : void 0; if (typeof value.response.service_tier === "string") { serviceTier = value.response.service_tier; } } else if (isResponseAnnotationAddedChunk(value)) { ongoingAnnotations.push(value.annotation); if (value.annotation.type === "url_citation") { controller.enqueue({ type: "source", sourceType: "url", id: (_r = (_q = (_p = self.config).generateId) == null ? void 0 : _q.call(_p)) != null ? _r : chunkOCS2GTEN_cjs.generateId(), url: value.annotation.url, title: value.annotation.title }); } else if (value.annotation.type === "file_citation") { controller.enqueue({ type: "source", sourceType: "document", id: (_u = (_t = (_s = self.config).generateId) == null ? void 0 : _t.call(_s)) != null ? _u : chunkOCS2GTEN_cjs.generateId(), mediaType: "text/plain", title: (_w = (_v = value.annotation.quote) != null ? _v : value.annotation.filename) != null ? _w : "Document", filename: (_x = value.annotation.filename) != null ? _x : value.annotation.file_id, ...value.annotation.file_id ? { providerMetadata: { [providerKey]: { fileId: value.annotation.file_id } } } : {} }); } } else if (isErrorChunk(value)) { controller.enqueue({ type: "error", error: value }); } }, flush(controller) { const providerMetadata = { [providerKey]: { responseId } }; if (logprobs.length > 0) { providerMetadata[providerKey].logprobs = logprobs; } if (serviceTier !== void 0) { providerMetadata[providerKey].serviceTier = serviceTier; } controller.enqueue({ type: "finish", finishReason, usage, providerMetadata }); } }) ), request: { body }, response: { headers: responseHeaders } }; } }; function isTextDeltaChunk(chunk) { return chunk.type === "response.output_text.delta"; } function isResponseOutputItemDoneChunk(chunk) { return chunk.type === "response.output_item.done"; } function isResponseFinishedChunk(chunk) { return chunk.type === "response.completed" || chunk.type === "response.incomplete"; } function isResponseCreatedChunk(chunk) { return chunk.type === "response.created"; } function isResponseFunctionCallArgumentsDeltaChunk(chunk) { return chunk.type === "response.function_call_arguments.delta"; } function isResponseCodeInterpreterCallCodeDeltaChunk(chunk) { return chunk.type === "response.code_interpreter_call_code.delta"; } function isResponseCodeInterpreterCallCodeDoneChunk(chunk) { return chunk.type === "response.code_interpreter_call_code.done"; } function isResponseOutputItemAddedChunk(chunk) { return chunk.type === "response.output_item.added"; } function isResponseAnnotationAddedChunk(chunk) { return chunk.type === "response.output_text.annotation.added"; } function isErrorChunk(chunk) { return chunk.type === "error"; } function mapWebSearchOutput(action) { var _a; if (action == null) { return {}; } switch (action.type) { case "search": return { action: { type: "search", query: (_a = action.query) != null ? _a : void 0 }, // include sources when provided by the Responses API (behind include flag) ...action.sources != null && { sources: action.sources } }; case "open_page": return { action: { type: "openPage", url: action.url } }; case "find_in_page": return { action: { type: "findInPage", url: action.url, pattern: action.pattern } }; } } var openaiSpeechProviderOptionsSchema = chunkOCS2GTEN_cjs.lazyValidator( () => chunkOCS2GTEN_cjs.zodSchema( v4.z.object({ instructions: v4.z.string().nullish(), speed: v4.z.number().min(0.25).max(4).default(1).nullish() }) ) ); var OpenAISpeechModel = class { constructor(modelId, config) { this.modelId = modelId; this.config = config; this.specificationVersion = "v2"; } get provider() { return this.config.provider; } async getArgs({ text, voice = "alloy", outputFormat = "mp3", speed, instructions, language, providerOptions }) { const warnings = []; const openAIOptions = await chunkOCS2GTEN_cjs.parseProviderOptions({ provider: "openai", providerOptions, schema: openaiSpeechProviderOptionsSchema }); const requestBody = { model: this.modelId, input: text, voice, response_format: "mp3", speed, instructions }; if (outputFormat) { if (["mp3", "opus", "aac", "flac", "wav", "pcm"].includes(outputFormat)) { requestBody.response_format = outputFormat; } else { warnings.push({ type: "unsupported-setting", setting: "outputFormat", details: `Unsupported output format: ${outputFormat}. Using mp3 instead.` }); } } if (openAIOptions) { const speechModelOptions = {}; for (const key in speechModelOptions) { const value = speechModelOptions[key]; if (value !== void 0) { requestBody[key] = value; } } } if (language) { warnings.push({ type: "unsupported-setting", setting: "language", details: `OpenAI speech models do not support language selection. Language parameter "${language}" was ignored.` }); } return { requestBody, warnings }; } async doGenerate(options) { var _a, _b, _c; const currentDate = (_c = (_b = (_a = this.config._internal) == null ? void 0 : _a.currentDate) == null ? void 0 : _b.call(_a)) != null ? _c : /* @__PURE__ */ new Date(); const { requestBody, warnings } = await this.getArgs(options); const { value: audio, responseHeaders, rawValue: rawResponse } = await chunkOCS2GTEN_cjs.postJsonToApi({ url: this.config.url({ path: "/audio/speech", modelId: this.modelId }), headers: chunkOCS2GTEN_cjs.combineHeaders(this.config.headers(), options.headers), body: requestBody, failedResponseHandler: openaiFailedResponseHandler, successfulResponseHandler: chunkOCS2GTEN_cjs.createBinaryResponseHandler(), abortSignal: options.abortSignal, fetch: this.config.fetch }); return { audio, warnings, request: { body: JSON.stringify(requestBody) }, response: { timestamp: currentDate, modelId: this.modelId, headers: responseHeaders, body: rawResponse } }; } }; var openaiTranscriptionResponseSchema = chunkOCS2GTEN_cjs.lazyValidator( () => chunkOCS2GTEN_cjs.zodSchema( v4.z.object({ text: v4.z.string(), language: v4.z.string().nullish(), duration: v4.z.number().nullish(), words: v4.z.array( v4.z.object({ word: v4.z.string(), start: v4.z.number(), end: v4.z.number() }) ).nullish(), segments: v4.z.array( v4.z.object({ id: v4.z.number(), seek: v4.z.number(), start: v4.z.number(), end: v4.z.number(), text: v4.z.string(), tokens: v4.z.array(v4.z.number()), temperature: v4.z.number(), avg_logprob: v4.z.number(), compression_ratio: v4.z.number(), no_speech_prob: v4.z.number() }) ).nullish() }) ) ); var openAITranscriptionProviderOptions = chunkOCS2GTEN_cjs.lazyValidator( () => chunkOCS2GTEN_cjs.zodSchema( v4.z.object({ /** * Additional information to include in the transcription response. */ include: v4.z.array(v4.z.string()).optional(), /** * The language of the input audio in ISO-639-1 format. */ language: v4.z.string().optional(), /** * An optional text to guide the model's style or continue a previous audio segment. */ prompt: v4.z.string().optional(), /** * The sampling temperature, between 0 and 1. * @default 0 */ temperature: v4.z.number().min(0).max(1).default(0).optional(), /** * The timestamp granularities to populate for this transcription. * @default ['segment'] */ timestampGranularities: v4.z.array(v4.z.enum(["word", "segment"])).default(["segment"]).optional() }) ) ); var languageMap = { afrikaans: "af", arabic: "ar", armenian: "hy", azerbaijani: "az", belarusian: "be", bosnian: "bs", bulgarian: "bg", catalan: "ca", chinese: "zh", croatian: "hr", czech: "cs", danish: "da", dutch: "nl", english: "en", estonian: "et", finnish: "fi", french: "fr", galician: "gl", german: "de", greek: "el", hebrew: "he", hindi: "hi", hungarian: "hu", icelandic: "is", indonesian: "id", italian: "it", japanese: "ja", kannada: "kn", kazakh: "kk", korean: "ko", latvian: "lv", lithuanian: "lt", macedonian: "mk", malay: "ms", marathi: "mr", maori: "mi", nepali: "ne", norwegian: "no", persian: "fa", polish: "pl", portuguese: "pt", romanian: "ro", russian: "ru", serbian: "sr", slovak: "sk", slovenian: "sl", spanish: "es", swahili: "sw", swedish: "sv", tagalog: "tl", tamil: "ta", thai: "th", turkish: "tr", ukrainian: "uk", urdu: "ur", vietnamese: "vi", welsh: "cy" }; var OpenAITranscriptionModel = class { constructor(modelId, config) { this.modelId = modelId; this.config = config; this.specificationVersion = "v2"; } get provider() { return this.config.provider; } async getArgs({ audio, mediaType, providerOptions }) { const warnings = []; const openAIOptions = await chunkOCS2GTEN_cjs.parseProviderOptions({ provider: "openai", providerOptions, schema: openAITranscriptionProviderOptions }); const formData = new FormData(); const blob = audio instanceof Uint8Array ? new Blob([audio]) : new Blob([chunkOCS2GTEN_cjs.convertBase64ToUint8Array(audio)]); formData.append("model", this.modelId); const fileExtension = chunkOCS2GTEN_cjs.mediaTypeToExtension(mediaType); formData.append( "file", new File([blob], "audio", { type: mediaType }), `audio.${fileExtension}` ); if (openAIOptions) { const transcriptionModelOptions = { include: openAIOptions.include, language: openAIOptions.language, prompt: openAIOptions.prompt, // https://platform.openai.com/docs/api-reference/audio/createTranscription#audio_createtranscription-response_format // prefer verbose_json to get segments for models that support it response_format: [ "gpt-4o-transcribe", "gpt-4o-mini-transcribe" ].includes(this.modelId) ? "json" : "verbose_json", temperature: openAIOptions.temperature, timestamp_granularities: openAIOptions.timestampGranularities }; for (const [key, value] of Object.entries(transcriptionModelOptions)) { if (value != null) { if (Array.isArray(value)) { for (const item of value) { formData.append(`${key}[]`, String(item)); } } else { formData.append(key, String(value)); } } } } return { formData, warnings }; } async doGenerate(options) { var _a, _b, _c, _d, _e, _f, _g, _h; const currentDate = (_c = (_b = (_a = this.config._internal) == null ? void 0 : _a.currentDate) == null ? void 0 : _b.call(_a)) != null ? _c : /* @__PURE__ */ new Date(); const { formData, warnings } = await this.getArgs(options); const { value: response, responseHeaders, rawValue: rawResponse } = await chunkOCS2GTEN_cjs.postFormDataToApi({ url: this.config.url({ path: "/audio/transcriptions", modelId: this.modelId }), headers: chunkOCS2GTEN_cjs.combineHeaders(this.config.headers(), options.headers), formData, failedResponseHandler: openaiFailedResponseHandler, successfulResponseHandler: chunkOCS2GTEN_cjs.createJsonResponseHandler( openaiTranscriptionResponseSchema ), abortSignal: options.abortSignal, fetch: this.config.fetch }); const language = response.language != null && response.language in languageMap ? languageMap[response.language] : void 0; return { text: response.text, segments: (_g = (_f = (_d = response.segments) == null ? void 0 : _d.map((segment) => ({ text: segment.text, startSecond: segment.start, endSecond: segment.end }))) != null ? _f : (_e = response.words) == null ? void 0 : _e.map((word) => ({ text: word.word, startSecond: word.start, endSecond: word.end }))) != null ? _g : [], language, durationInSeconds: (_h = response.duration) != null ? _h : void 0, warnings, response: { timestamp: currentDate, modelId: this.modelId, headers: responseHeaders, body: rawResponse } }; } }; var VERSION2 = "2.0.106" ; function createOpenAI2(options = {}) { var _a, _b; const baseURL = (_a = chunkOCS2GTEN_cjs.withoutTrailingSlash( chunkOCS2GTEN_cjs.loadOptionalSetting({ settingValue: options.baseURL, environmentVariableName: "OPENAI_BASE_URL" }) )) != null ? _a : "https://api.openai.com/v1"; const providerName = (_b = options.name) != null ? _b : "openai"; const getHeaders = () => chunkOCS2GTEN_cjs.withUserAgentSuffix( { Authorization: `Bearer ${chunkOCS2GTEN_cjs.loadApiKey({ apiKey: options.apiKey, environmentVariableName: "OPENAI_API_KEY", description: "OpenAI" })}`, "OpenAI-Organization": options.organization, "OpenAI-Project": options.project, ...options.headers }, `ai-sdk/openai/${VERSION2}` ); const createChatModel = (modelId) => new OpenAIChatLanguageModel(modelId, { provider: `${providerName}.chat`, url: ({ path }) => `${baseURL}${path}`, headers: getHeaders, fetch: options.fetch }); const createCompletionModel = (modelId) => new OpenAICompletionLanguageModel(modelId, { provider: `${providerName}.completion`, url: ({ path }) => `${baseURL}${path}`, headers: getHeaders, fetch: options.fetch }); const createEmbeddingModel = (modelId) => new OpenAIEmbeddingModel(modelId, { provider: `${providerName}.embedding`, url: ({ path }) => `${baseURL}${path}`, headers: getHeaders, fetch: options.fetch }); const createImageModel = (modelId) => new OpenAIImageModel(modelId, { provider: `${providerName}.image`, url: ({ path }) => `${baseURL}${path}`, headers: getHeaders, fetch: options.fetch }); const createTranscriptionModel = (modelId) => new OpenAITranscriptionModel(modelId, { provider: `${providerName}.transcription`, url: ({ path }) => `${baseURL}${path}`, headers: getHeaders, fetch: options.fetch }); const createSpeechModel = (modelId) => new OpenAISpeechModel(modelId, { provider: `${providerName}.speech`, url: ({ path }) => `${baseURL}${path}`, headers: getHeaders, fetch: options.fetch }); const createLanguageModel = (modelId) => { if (new.target) { throw new Error( "The OpenAI model function cannot be called with the new keyword." ); } return createResponsesModel(modelId); }; const createResponsesModel = (modelId) => { return new OpenAIResponsesLanguageModel(modelId, { provider: `${providerName}.responses`, url: ({ path }) => `${baseURL}${path}`, headers: getHeaders, fetch: options.fetch, fileIdPrefixes: ["file-"] }); }; const provider = function(modelId) { return createLanguageModel(modelId); }; provider.languageModel = createLanguageModel; provider.chat = createChatModel; provider.completion = createCompletionModel; provider.responses = createResponsesModel; provider.embedding = createEmbeddingModel; provider.textEmbedding = createEmbeddingModel; provider.textEmbeddingModel = createEmbeddingModel; provider.image = createImageModel; provider.imageModel = createImageModel; provider.transcription = createTranscriptionModel; provider.transcriptionModel = createTranscriptionModel; provider.speech = createSpeechModel; provider.speechModel = createSpeechModel; provider.tools = openaiTools; return provider; } createOpenAI2(); // src/llm/model/embedding-router.ts var MASTRA_GATEWAY_ID = "mastra"; function trimTrailingSlashes(value) { let end = value.length; while (end > 0 && value.charCodeAt(end - 1) === 47) { end -= 1; } return value.slice(0, end); } function getMastraGatewayBaseUrl(raw = process.env["MASTRA_GATEWAY_URL"]) { const baseUrl = raw?.trim() || "https://gateway-api.mastra.ai"; const withoutTrailingSlashes = trimTrailingSlashes(baseUrl); const withoutVersion = withoutTrailingSlashes.endsWith("/v1") ? withoutTrailingSlashes.slice(0, -"/v1".length) : withoutTrailingSlashes; return `${withoutVersion}/v1`; } var EMBEDDING_MODELS = [ // OpenAI { id: "text-embedding-3-small", provider: "openai", dimensions: 1536, maxInputTokens: 8191, description: "OpenAI text-embedding-3-small model" }, { id: "text-embedding-3-large", provider: "openai", dimensions: 3072, maxInputTokens: 8191, description: "OpenAI text-embedding-3-large model" }, { id: "text-embedding-ada-002", provider: "openai", dimensions: 1536, maxInputTokens: 8191, description: "OpenAI text-embedding-ada-002 model" }, // Google { id: "gemini-embedding-001", provider: "google", dimensions: 768, maxInputTokens: 2048, description: "Google gemini-embedding-001 model" } ]; var ModelRouterEmbeddingModel = class { specificationVersion = "v2"; modelId; provider; maxEmbeddingsPerCall = 2048; supportsParallelCalls = true; providerModel; constructor(config) { let normalizedConfig; if (typeof config === "string") { const parts = config.split("/"); if (parts[0] === MASTRA_GATEWAY_ID) { if (parts.length < 3) { throw new Error(`Invalid model string format: "${config}". Expected format: "mastra/provider/model"`); } normalizedConfig = { providerId: MASTRA_GATEWAY_ID, modelId: parts.slice(1).join("/") }; } else { if (parts.length !== 2) { throw new Error(`Invalid model string format: "${config}". Expected format: "provider/model"`); } const [providerId, modelId] = parts; normalizedConfig = { providerId, modelId }; } } else if ("providerId" in config && "modelId" in config) { normalizedConfig = { providerId: config.providerId, modelId: config.modelId, url: config.url, apiKey: config.apiKey, headers: config.headers }; } else { const parts = config.id.split("/"); if (parts[0] === MASTRA_GATEWAY_ID) { if (parts.length < 3) { throw new Error(`Invalid model string format: "${config.id}". Expected format: "mastra/provider/model"`); } normalizedConfig = { providerId: MASTRA_GATEWAY_ID, modelId: parts.slice(1).join("/"), url: config.url, apiKey: config.apiKey, headers: config.headers }; } else { if (parts.length !== 2) { throw new Error(`Invalid model string format: "${config.id}". Expected format: "provider/model"`); } const [providerId, modelId] = parts; normalizedConfig = { providerId, modelId, url: config.url, apiKey: config.apiKey, headers: config.headers }; } } this.provider = normalizedConfig.providerId; this.modelId = normalizedConfig.modelId; if (normalizedConfig.providerId === MASTRA_GATEWAY_ID) { const apiKey = normalizedConfig.apiKey ?? process.env["MASTRA_GATEWAY_API_KEY"]; if (!apiKey) { throw new Error("API key not found for provider mastra. Set MASTRA_GATEWAY_API_KEY"); } this.providerModel = chunkOCS2GTEN_cjs.createOpenAICompatible({ name: MASTRA_GATEWAY_ID, apiKey, baseURL: getMastraGatewayBaseUrl(normalizedConfig.url), headers: { "User-Agent": chunkOCS2GTEN_cjs.MASTRA_USER_AGENT, ...normalizedConfig.headers } }).textEmbeddingModel(normalizedConfig.modelId); } else if (normalizedConfig.url) { const apiKey = normalizedConfig.apiKey || ""; this.providerModel = chunkOCS2GTEN_cjs.createOpenAICompatible({ name: normalizedConfig.providerId, apiKey, baseURL: normalizedConfig.url, headers: normalizedConfig.headers }).textEmbeddingModel(normalizedConfig.modelId); } else { const registry = chunkDURT53SS_cjs.GatewayRegistry.getInstance(); const providerConfig = registry.getProviderConfig(normalizedConfig.providerId); if (!providerConfig) { throw new Error(`Unknown provider: ${normalizedConfig.providerId}`); } let apiKey = normalizedConfig.apiKey; if (!apiKey) { const apiKeyEnvVar = providerConfig.apiKeyEnvVar; if (Array.isArray(apiKeyEnvVar)) { for (const envVar of apiKeyEnvVar) { apiKey = process.env[envVar]; if (apiKey) break; } } else { apiKey = process.env[apiKeyEnvVar]; } } if (!apiKey) { const envVarDisplay = Array.isArray(providerConfig.apiKeyEnvVar) ? providerConfig.apiKeyEnvVar.join(" or ") : providerConfig.apiKeyEnvVar; throw new Error(`API key not found for provider ${normalizedConfig.providerId}. Set ${envVarDisplay}`); } if (normalizedConfig.providerId === "openai") { this.providerModel = createOpenAI2({ apiKey }).textEmbeddingModel( normalizedConfig.modelId ); } else if (normalizedConfig.providerId === "google") { this.providerModel = createGoogleGenerativeAI({ apiKey }).textEmbedding( normalizedConfig.modelId ); } else { if (!providerConfig.url) { throw new Error(`Provider ${normalizedConfig.providerId} does not have a URL configured`); } this.providerModel = chunkOCS2GTEN_cjs.createOpenAICompatible({ name: normalizedConfig.providerId, apiKey, baseURL: providerConfig.url }).textEmbeddingModel(normalizedConfig.modelId); } } if (this.providerModel.maxEmbeddingsPerCall !== void 0) { this.maxEmbeddingsPerCall = this.providerModel.maxEmbeddingsPerCall; } if (this.providerModel.supportsParallelCalls !== void 0) { this.supportsParallelCalls = this.providerModel.supportsParallelCalls; } } async doEmbed(args) { const result = await this.providerModel.doEmbed(args); const warnings = result.warnings ?? []; return { ...result, warnings }; } }; exports.ChunkFrom = ChunkFrom; exports.EMBEDDING_MODELS = EMBEDDING_MODELS; exports.ModelRouterEmbeddingModel = ModelRouterEmbeddingModel; exports.ModelRouterLanguageModel = ModelRouterLanguageModel; exports.attachModelStreamTransport = attachModelStreamTransport; exports.defaultGateways = defaultGateways; exports.readModelStreamTransport = readModelStreamTransport; exports.resolveModelAuth = resolveModelAuth; exports.resolveModelConfig = resolveModelConfig; //# sourceMappingURL=chunk-AWVVTLZF.cjs.map //# sourceMappingURL=chunk-AWVVTLZF.cjs.map