zhipu-ai-provider
Version:
Vercel AI SDK Custom Provider for Services from Zhipu (Z.ai)
1 lines • 944 kB
Source Map (JSON)
{"version":3,"sources":["../src/zhipu-provider.ts","../src/zhipu-chat-language-model.ts","../node_modules/.pnpm/zod@4.3.5/node_modules/zod/v4/classic/external.js","../node_modules/.pnpm/zod@4.3.5/node_modules/zod/v4/core/index.js","../node_modules/.pnpm/zod@4.3.5/node_modules/zod/v4/core/core.js","../node_modules/.pnpm/zod@4.3.5/node_modules/zod/v4/core/util.js","../node_modules/.pnpm/zod@4.3.5/node_modules/zod/v4/core/errors.js","../node_modules/.pnpm/zod@4.3.5/node_modules/zod/v4/core/parse.js","../node_modules/.pnpm/zod@4.3.5/node_modules/zod/v4/core/regexes.js","../node_modules/.pnpm/zod@4.3.5/node_modules/zod/v4/core/checks.js","../node_modules/.pnpm/zod@4.3.5/node_modules/zod/v4/core/doc.js","../node_modules/.pnpm/zod@4.3.5/node_modules/zod/v4/core/versions.js","../node_modules/.pnpm/zod@4.3.5/node_modules/zod/v4/core/schemas.js","../node_modules/.pnpm/zod@4.3.5/node_modules/zod/v4/locales/index.js","../node_modules/.pnpm/zod@4.3.5/node_modules/zod/v4/locales/ar.js","../node_modules/.pnpm/zod@4.3.5/node_modules/zod/v4/locales/az.js","../node_modules/.pnpm/zod@4.3.5/node_modules/zod/v4/locales/be.js","../node_modules/.pnpm/zod@4.3.5/node_modules/zod/v4/locales/bg.js","../node_modules/.pnpm/zod@4.3.5/node_modules/zod/v4/locales/ca.js","../node_modules/.pnpm/zod@4.3.5/node_modules/zod/v4/locales/cs.js","../node_modules/.pnpm/zod@4.3.5/node_modules/zod/v4/locales/da.js","../node_modules/.pnpm/zod@4.3.5/node_modules/zod/v4/locales/de.js","../node_modules/.pnpm/zod@4.3.5/node_modules/zod/v4/locales/en.js","../node_modules/.pnpm/zod@4.3.5/node_modules/zod/v4/locales/eo.js","../node_modules/.pnpm/zod@4.3.5/node_modules/zod/v4/locales/es.js","../node_modules/.pnpm/zod@4.3.5/node_modules/zod/v4/locales/fa.js","../node_modules/.pnpm/zod@4.3.5/node_modules/zod/v4/locales/fi.js","../node_modules/.pnpm/zod@4.3.5/node_modules/zod/v4/locales/fr.js","../node_modules/.pnpm/zod@4.3.5/node_modules/zod/v4/locales/fr-CA.js","../node_modules/.pnpm/zod@4.3.5/node_modules/zod/v4/locales/he.js","../node_modules/.pnpm/zod@4.3.5/node_modules/zod/v4/locales/hu.js","../node_modules/.pnpm/zod@4.3.5/node_modules/zod/v4/locales/hy.js","../node_modules/.pnpm/zod@4.3.5/node_modules/zod/v4/locales/id.js","../node_modules/.pnpm/zod@4.3.5/node_modules/zod/v4/locales/is.js","../node_modules/.pnpm/zod@4.3.5/node_modules/zod/v4/locales/it.js","../node_modules/.pnpm/zod@4.3.5/node_modules/zod/v4/locales/ja.js","../node_modules/.pnpm/zod@4.3.5/node_modules/zod/v4/locales/ka.js","../node_modules/.pnpm/zod@4.3.5/node_modules/zod/v4/locales/km.js","../node_modules/.pnpm/zod@4.3.5/node_modules/zod/v4/locales/kh.js","../node_modules/.pnpm/zod@4.3.5/node_modules/zod/v4/locales/ko.js","../node_modules/.pnpm/zod@4.3.5/node_modules/zod/v4/locales/lt.js","../node_modules/.pnpm/zod@4.3.5/node_modules/zod/v4/locales/mk.js","../node_modules/.pnpm/zod@4.3.5/node_modules/zod/v4/locales/ms.js","../node_modules/.pnpm/zod@4.3.5/node_modules/zod/v4/locales/nl.js","../node_modules/.pnpm/zod@4.3.5/node_modules/zod/v4/locales/no.js","../node_modules/.pnpm/zod@4.3.5/node_modules/zod/v4/locales/ota.js","../node_modules/.pnpm/zod@4.3.5/node_modules/zod/v4/locales/ps.js","../node_modules/.pnpm/zod@4.3.5/node_modules/zod/v4/locales/pl.js","../node_modules/.pnpm/zod@4.3.5/node_modules/zod/v4/locales/pt.js","../node_modules/.pnpm/zod@4.3.5/node_modules/zod/v4/locales/ru.js","../node_modules/.pnpm/zod@4.3.5/node_modules/zod/v4/locales/sl.js","../node_modules/.pnpm/zod@4.3.5/node_modules/zod/v4/locales/sv.js","../node_modules/.pnpm/zod@4.3.5/node_modules/zod/v4/locales/ta.js","../node_modules/.pnpm/zod@4.3.5/node_modules/zod/v4/locales/th.js","../node_modules/.pnpm/zod@4.3.5/node_modules/zod/v4/locales/tr.js","../node_modules/.pnpm/zod@4.3.5/node_modules/zod/v4/locales/uk.js","../node_modules/.pnpm/zod@4.3.5/node_modules/zod/v4/locales/ua.js","../node_modules/.pnpm/zod@4.3.5/node_modules/zod/v4/locales/ur.js","../node_modules/.pnpm/zod@4.3.5/node_modules/zod/v4/locales/uz.js","../node_modules/.pnpm/zod@4.3.5/node_modules/zod/v4/locales/vi.js","../node_modules/.pnpm/zod@4.3.5/node_modules/zod/v4/locales/zh-CN.js","../node_modules/.pnpm/zod@4.3.5/node_modules/zod/v4/locales/zh-TW.js","../node_modules/.pnpm/zod@4.3.5/node_modules/zod/v4/locales/yo.js","../node_modules/.pnpm/zod@4.3.5/node_modules/zod/v4/core/registries.js","../node_modules/.pnpm/zod@4.3.5/node_modules/zod/v4/core/api.js","../node_modules/.pnpm/zod@4.3.5/node_modules/zod/v4/core/to-json-schema.js","../node_modules/.pnpm/zod@4.3.5/node_modules/zod/v4/core/json-schema-processors.js","../node_modules/.pnpm/zod@4.3.5/node_modules/zod/v4/core/json-schema-generator.js","../node_modules/.pnpm/zod@4.3.5/node_modules/zod/v4/core/json-schema.js","../node_modules/.pnpm/zod@4.3.5/node_modules/zod/v4/classic/schemas.js","../node_modules/.pnpm/zod@4.3.5/node_modules/zod/v4/classic/checks.js","../node_modules/.pnpm/zod@4.3.5/node_modules/zod/v4/classic/iso.js","../node_modules/.pnpm/zod@4.3.5/node_modules/zod/v4/classic/errors.js","../node_modules/.pnpm/zod@4.3.5/node_modules/zod/v4/classic/parse.js","../node_modules/.pnpm/zod@4.3.5/node_modules/zod/v4/classic/compat.js","../node_modules/.pnpm/zod@4.3.5/node_modules/zod/v4/classic/from-json-schema.js","../node_modules/.pnpm/zod@4.3.5/node_modules/zod/v4/classic/coerce.js","../src/convert-to-zhipu-chat-messages.ts","../src/get-response-metadata.ts","../src/map-zhipu-finish-reason.ts","../src/zhipu-error.ts","../src/zhipu-embedding-model.ts","../src/zhipu-image-model.ts","../src/zhipu-image-options.ts"],"sourcesContent":["import {\n EmbeddingModelV3,\n ImageModelV3,\n LanguageModelV3,\n ProviderV3,\n} from \"@ai-sdk/provider\";\nimport {\n FetchFunction,\n loadApiKey,\n withoutTrailingSlash,\n} from \"@ai-sdk/provider-utils\";\nimport { ZhipuChatLanguageModel } from \"./zhipu-chat-language-model\";\nimport { ZhipuChatModelId, ZhipuChatSettings } from \"./zhipu-chat-settings\";\nimport { ZhipuEmbeddingModel } from \"./zhipu-embedding-model\";\nimport {\n ZhipuEmbeddingModelId,\n ZhipuEmbeddingSettings,\n} from \"./zhipu-embedding-settings\";\nimport { ZhipuImageModel } from \"./zhipu-image-model\";\nimport { ZhipuImageModelId } from \"./zhipu-image-options\";\n\nexport interface ZhipuProvider extends ProviderV3 {\n (modelId: ZhipuChatModelId, settings?: ZhipuChatSettings): LanguageModelV3;\n\n languageModel(\n modelId: ZhipuChatModelId,\n settings?: ZhipuChatSettings,\n ): LanguageModelV3;\n\n chat(\n modelId: ZhipuChatModelId,\n settings?: ZhipuChatSettings,\n ): LanguageModelV3;\n\n /** @deprecated Use embedding or embeddingModel instead */\n textEmbeddingModel(\n modelId: ZhipuEmbeddingModelId,\n settings?: ZhipuEmbeddingSettings,\n ): EmbeddingModelV3;\n\n embedding(\n modelId: ZhipuEmbeddingModelId,\n settings?: ZhipuEmbeddingSettings,\n ): EmbeddingModelV3;\n\n embeddingModel(\n modelId: ZhipuEmbeddingModelId,\n settings?: ZhipuEmbeddingSettings,\n ): EmbeddingModelV3;\n\n image(modelId: ZhipuImageModelId): ImageModelV3;\n\n imageModel(modelId: ZhipuImageModelId): ImageModelV3;\n}\n\nexport interface ZhipuProviderSettings {\n baseURL?: string;\n apiKey?: string;\n headers?: Record<string, string>;\n fetch?: FetchFunction;\n}\n\nexport function createZhipu(\n options: ZhipuProviderSettings = {},\n): ZhipuProvider {\n const baseURL =\n withoutTrailingSlash(options.baseURL) ??\n \"https://open.bigmodel.cn/api/paas/v4\";\n\n const getHeaders = () => ({\n Authorization: `Bearer ${loadApiKey({\n apiKey: options.apiKey,\n environmentVariableName: \"ZHIPU_API_KEY\",\n description: \"ZHIPU API key\",\n })}`,\n ...options.headers,\n });\n\n const createChatModel = (\n modelId: ZhipuChatModelId,\n settings: ZhipuChatSettings = {},\n ) =>\n new ZhipuChatLanguageModel(modelId, settings, {\n provider: \"zhipu.chat\",\n baseURL,\n headers: getHeaders,\n fetch: options.fetch,\n });\n\n const createEmbeddingModel = (\n modelId: ZhipuEmbeddingModelId,\n settings: ZhipuEmbeddingSettings = {},\n ) =>\n new ZhipuEmbeddingModel(modelId, settings, {\n provider: \"zhipu.embedding\",\n baseURL,\n headers: getHeaders,\n fetch: options.fetch,\n });\n\n const createImageModel = (modelId: ZhipuImageModelId) =>\n new ZhipuImageModel(modelId, {\n provider: \"zhipu.image\",\n url: ({ path }) => `${baseURL}${path}`,\n headers: getHeaders,\n fetch: options.fetch,\n _internal: {\n currentDate: () => new Date(),\n },\n });\n\n const provider = Object.assign(\n function (modelId: ZhipuChatModelId, settings?: ZhipuChatSettings) {\n if (new.target) {\n throw new Error(\n \"The Zhipu model function cannot be called with the new keyword.\",\n );\n }\n\n return createChatModel(modelId, settings);\n } as unknown as ZhipuProvider,\n {\n specificationVersion: \"v3\" as const,\n languageModel: createChatModel,\n chat: createChatModel,\n /** @deprecated Use embedding or embeddingModel instead */\n textEmbeddingModel: createEmbeddingModel,\n embedding: createEmbeddingModel,\n embeddingModel: createEmbeddingModel,\n image: createImageModel,\n imageModel: createImageModel,\n },\n );\n\n return provider;\n}\n\nexport const zhipu = createZhipu();\nexport const zai = createZhipu({ baseURL: \"https://api.z.ai/api/paas/v4\" });\n","import {\n InvalidResponseDataError,\n LanguageModelV3,\n LanguageModelV3Content,\n LanguageModelV3FinishReason,\n LanguageModelV3StreamPart,\n LanguageModelV3Usage,\n SharedV3Warning,\n} from \"@ai-sdk/provider\";\nimport {\n combineHeaders,\n createEventSourceResponseHandler,\n createJsonResponseHandler,\n FetchFunction,\n generateId,\n isParsableJson,\n ParseResult,\n postJsonToApi,\n} from \"@ai-sdk/provider-utils\";\nimport { z } from \"zod\";\nimport { convertToZhipuChatMessages } from \"./convert-to-zhipu-chat-messages\";\nimport { getResponseMetadata } from \"./get-response-metadata\";\nimport { mapZhipuFinishReason } from \"./map-zhipu-finish-reason\";\nimport { ZhipuChatModelId, ZhipuChatSettings } from \"./zhipu-chat-settings\";\nimport { zhipuFailedResponseHandler } from \"./zhipu-error\";\n\ntype ZhipuChatConfig = {\n provider: string;\n baseURL: string;\n isMultiModel?: boolean;\n isReasoningModel?: boolean;\n headers: () => Record<string, string | undefined>;\n fetch?: FetchFunction;\n};\n\ntype ZhipuWebSearchResult = z.infer<typeof zhipuWebSearchItemSchema>;\n\nexport class ZhipuChatLanguageModel implements LanguageModelV3 {\n readonly specificationVersion = \"v3\" as const;\n readonly supportedUrls: Record<string, RegExp[]> = {\n \"image/*\": [/^data:image\\/[a-zA-Z]+;base64,/, /^https?:\\/\\/.+$/i],\n \"video/*\": [/^https?:\\/\\/.+\\.(mp4|webm|ogg)$/i],\n };\n\n readonly modelId: ZhipuChatModelId;\n readonly settings: ZhipuChatSettings;\n\n private readonly config: ZhipuChatConfig;\n\n constructor(\n modelId: ZhipuChatModelId,\n settings: ZhipuChatSettings,\n config: ZhipuChatConfig,\n ) {\n this.modelId = modelId.toLocaleLowerCase();\n this.settings = settings;\n this.config = config;\n this.config.isMultiModel = this.modelId.includes(\"v\");\n this.config.isReasoningModel =\n this.modelId.includes(\"z\") ||\n this.modelId.includes(\"thinking\") ||\n settings.thinking?.type === \"enabled\";\n }\n\n get provider(): string {\n return this.config.provider;\n }\n\n private unsupported(\n feature: string,\n details?: string,\n ): Extract<SharedV3Warning, { type: \"unsupported\" }> {\n return { type: \"unsupported\", feature, details };\n }\n\n private getArgs({\n prompt,\n maxOutputTokens,\n temperature,\n topP,\n topK,\n frequencyPenalty,\n presencePenalty,\n stopSequences,\n responseFormat,\n seed,\n tools,\n toolChoice,\n }: Parameters<LanguageModelV3[\"doGenerate\"]>[0]) {\n const warnings: SharedV3Warning[] = [];\n\n if (\n !this.config.isMultiModel &&\n prompt.every(\n (msg) =>\n msg.role === \"user\" &&\n !msg.content.every((part) => part.type === \"text\"),\n )\n ) {\n warnings.push({\n type: \"other\",\n message: \"Non-vision models does not support message parts\",\n });\n }\n\n if (topK != null) {\n warnings.push(this.unsupported(\"topK\"));\n }\n\n if (frequencyPenalty != null) {\n warnings.push(this.unsupported(\"frequencyPenalty\"));\n }\n\n if (presencePenalty != null) {\n warnings.push(this.unsupported(\"presencePenalty\"));\n }\n\n if (stopSequences != null && this.config.isMultiModel) {\n warnings.push(\n this.unsupported(\n \"stopSequences\",\n \"Stop sequences are not supported for vision model\",\n ),\n );\n }\n\n if (stopSequences != null && stopSequences.length > 1) {\n warnings.push(\n this.unsupported(\"stopSequences\", \"Only supports one stop sequence\"),\n );\n }\n\n if (seed != null) {\n warnings.push(this.unsupported(\"seed\"));\n }\n\n if (\n responseFormat &&\n responseFormat.type === \"json\" &&\n (this.config.isMultiModel || this.config.isReasoningModel)\n ) {\n warnings.push(\n this.unsupported(\n \"responseFormat\",\n \"JSON response format is not supported with vision and reasoning models.\",\n ),\n );\n }\n\n if (tools && tools.length > 0 && this.config.isMultiModel) {\n warnings.push(\n this.unsupported(\n \"tools\",\n \"Tools are not supported with vision models.\",\n ),\n );\n }\n\n if (\n tools &&\n tools.length > 0 &&\n tools.some((tool) => tool.type !== \"function\")\n ) {\n warnings.push(\n this.unsupported(\"tools\", \"Provider-defined tools are not implemented\"),\n );\n }\n\n if (\n responseFormat &&\n responseFormat.type === \"json\" &&\n responseFormat.schema\n ) {\n warnings.push(\n this.unsupported(\n \"responseFormat\",\n \"Structured output with schema is not supported, use json response format instead.\",\n ),\n );\n }\n\n if (toolChoice?.type != null && toolChoice.type !== \"auto\") {\n warnings.push(\n this.unsupported(\"toolChoice\", \"Only 'auto' tool choice is supported\"),\n );\n }\n\n const baseArgs = {\n model: this.modelId,\n user_id: this.settings.userId,\n do_sample: this.settings.doSample,\n request_id: this.settings.requestId,\n thinking: this.settings.thinking\n ? {\n type: this.settings.thinking.type,\n ...(this.settings.thinking.clearThinking !== undefined && {\n clear_thinking: this.settings.thinking.clearThinking,\n }),\n }\n : undefined,\n max_tokens: maxOutputTokens,\n temperature,\n top_p: topP,\n response_format:\n responseFormat?.type === \"json\" ? { type: \"json_object\" } : undefined,\n messages: convertToZhipuChatMessages(prompt),\n tool_choice: \"auto\",\n tools:\n tools\n ?.filter((tool) => tool.type === \"function\")\n .map((tool) => ({\n type: \"function\" as const,\n function: {\n name: tool.name,\n description: tool.description ?? undefined,\n parameters: tool.inputSchema,\n },\n })) ?? undefined,\n };\n\n return { args: baseArgs, warnings };\n }\n\n private mapUsage(\n usage:\n | {\n prompt_tokens: number;\n completion_tokens?: number | null;\n total_tokens?: number | null;\n }\n | null\n | undefined,\n ): LanguageModelV3Usage {\n return {\n inputTokens: {\n total: usage?.prompt_tokens,\n noCache: undefined,\n cacheRead: undefined,\n cacheWrite: undefined,\n },\n outputTokens: {\n total: usage?.completion_tokens ?? undefined,\n text: usage?.completion_tokens ?? undefined,\n reasoning: undefined,\n },\n raw: usage\n ? {\n prompt_tokens: usage.prompt_tokens,\n completion_tokens: usage.completion_tokens ?? undefined,\n total_tokens: usage.total_tokens ?? undefined,\n }\n : undefined,\n };\n }\n\n private buildSourceContent(\n webSearch: ZhipuWebSearchResult[] | ZhipuWebSearchResult | null | undefined,\n ): LanguageModelV3Content[] {\n const items =\n webSearch == null\n ? []\n : Array.isArray(webSearch)\n ? webSearch\n : [webSearch];\n\n return items.map((item, index) => ({\n type: \"source\",\n sourceType: \"url\",\n id: item.link || `source-${index}`,\n url: item.link,\n title: item.title || undefined,\n providerMetadata: {\n zhipu: {\n icon: item.icon,\n media: item.media,\n content: item.content,\n },\n },\n }));\n }\n\n async doGenerate(\n options: Parameters<LanguageModelV3[\"doGenerate\"]>[0],\n ): Promise<Awaited<ReturnType<LanguageModelV3[\"doGenerate\"]>>> {\n const { args, warnings } = this.getArgs(options);\n const providerOptions = options.providerOptions || {};\n const zhipuOptions = providerOptions.zhipu || {};\n const fullArgs = { ...args, ...zhipuOptions };\n\n const {\n value: response,\n rawValue: rawResponse,\n responseHeaders,\n } = await postJsonToApi({\n url: `${this.config.baseURL}/chat/completions`,\n headers: combineHeaders(this.config.headers(), options.headers),\n body: fullArgs,\n failedResponseHandler: zhipuFailedResponseHandler,\n successfulResponseHandler: createJsonResponseHandler(\n zhipuChatResponseSchema,\n ),\n abortSignal: options.abortSignal,\n fetch: this.config.fetch,\n });\n\n const responseData = response as z.infer<typeof zhipuChatResponseSchema>;\n const choice = responseData.choices[0];\n const content: LanguageModelV3Content[] = [];\n const responseText = choice.message.content;\n const responseReasoningText = choice.message.reasoning_content;\n\n if (responseReasoningText) {\n content.push({\n type: \"reasoning\",\n text: responseReasoningText,\n });\n }\n\n if (responseText) {\n if (this.config.isReasoningModel && responseText.includes(\"<think>\")) {\n const reasoningText = responseText\n .split(\"<think>\")[1]\n ?.split(\"</think>\")[0];\n const text = responseText.split(\"</think>\")[1];\n\n if (reasoningText) {\n content.push({ type: \"reasoning\", text: reasoningText });\n }\n\n if (text) {\n content.push({ type: \"text\", text });\n }\n } else {\n content.push({\n type: \"text\",\n text: responseText,\n });\n }\n }\n\n if (choice.message.tool_calls) {\n for (const toolCall of choice.message.tool_calls) {\n content.push({\n type: \"tool-call\",\n toolCallId: toolCall.id,\n toolName: toolCall.function.name,\n input: toolCall.function.arguments,\n providerExecuted: false,\n });\n }\n }\n\n content.push(...this.buildSourceContent(responseData.web_search));\n\n return {\n content,\n finishReason: mapZhipuFinishReason(choice.finish_reason),\n usage: this.mapUsage(responseData.usage),\n request: { body: fullArgs },\n response: {\n ...getResponseMetadata(responseData),\n headers: responseHeaders,\n body: rawResponse,\n },\n warnings,\n };\n }\n\n async doStream(\n options: Parameters<LanguageModelV3[\"doStream\"]>[0],\n ): Promise<Awaited<ReturnType<LanguageModelV3[\"doStream\"]>>> {\n const { args, warnings } = this.getArgs(options);\n const providerOptions = options.providerOptions || {};\n const zhipuOptions = providerOptions.zhipu || {};\n const body = { ...args, ...zhipuOptions, stream: true };\n\n const { responseHeaders, value: response } = await postJsonToApi({\n url: `${this.config.baseURL}/chat/completions`,\n headers: combineHeaders(this.config.headers(), options.headers),\n body,\n failedResponseHandler: zhipuFailedResponseHandler,\n successfulResponseHandler:\n createEventSourceResponseHandler(zhipuChatChunkSchema),\n abortSignal: options.abortSignal,\n fetch: this.config.fetch,\n });\n\n const toolCalls: Array<{\n id: string;\n toolName: string;\n input: string;\n hasFinished: boolean;\n }> = [];\n\n let finishReason: LanguageModelV3FinishReason = {\n unified: \"other\",\n raw: undefined,\n };\n let usage: LanguageModelV3Usage = this.mapUsage(undefined);\n let isFirstChunk = true;\n let isActiveReasoning = false;\n let isActiveText = false;\n\n return {\n stream: response.pipeThrough(\n new TransformStream<\n ParseResult<z.infer<typeof zhipuChatChunkSchema>>,\n LanguageModelV3StreamPart\n >({\n transform(chunk, controller) {\n if (options.includeRawChunks) {\n controller.enqueue({ type: \"raw\", rawValue: chunk.rawValue });\n }\n\n if (!chunk.success) {\n finishReason = { unified: \"error\", raw: \"parse_error\" };\n controller.enqueue({ type: \"error\", error: chunk.error });\n return;\n }\n\n const value = chunk.value;\n\n if (isFirstChunk) {\n isFirstChunk = false;\n controller.enqueue({\n type: \"stream-start\",\n warnings,\n });\n controller.enqueue({\n type: \"response-metadata\",\n ...getResponseMetadata(value),\n });\n }\n\n if (\"error\" in value) {\n finishReason = { unified: \"error\", raw: \"provider_error\" };\n controller.enqueue({ type: \"error\", error: value.error });\n return;\n }\n\n if (value.usage != null) {\n usage = {\n inputTokens: {\n total: value.usage.prompt_tokens ?? undefined,\n noCache: undefined,\n cacheRead: undefined,\n cacheWrite: undefined,\n },\n outputTokens: {\n total: value.usage.completion_tokens ?? undefined,\n text: value.usage.completion_tokens ?? undefined,\n reasoning: undefined,\n },\n raw: {\n prompt_tokens: value.usage.prompt_tokens,\n completion_tokens: value.usage.completion_tokens ?? undefined,\n total_tokens: value.usage.total_tokens ?? undefined,\n },\n };\n }\n\n const choice = value.choices[0];\n\n if (choice?.finish_reason != null) {\n if (choice.finish_reason === \"network_error\") {\n finishReason = { unified: \"error\", raw: choice.finish_reason };\n controller.enqueue({\n type: \"error\",\n error: new Error(\"Error: Network Error\"),\n });\n return;\n }\n\n finishReason = mapZhipuFinishReason(choice.finish_reason);\n }\n\n if (choice?.delta == null) {\n return;\n }\n\n const delta = choice.delta;\n\n if (delta.reasoning_content != null) {\n if (!isActiveReasoning) {\n controller.enqueue({\n type: \"reasoning-start\",\n id: \"reasoning-0\",\n });\n isActiveReasoning = true;\n }\n\n controller.enqueue({\n id: \"reasoning-0\",\n type: \"reasoning-delta\",\n delta: delta.reasoning_content,\n });\n }\n\n if (delta.content != null) {\n if (!isActiveText) {\n controller.enqueue({ type: \"text-start\", id: \"txt-0\" });\n isActiveText = true;\n }\n\n controller.enqueue({\n id: \"txt-0\",\n type: \"text-delta\",\n delta: delta.content,\n });\n }\n\n if (delta.tool_calls != null) {\n for (const toolCallDelta of delta.tool_calls) {\n const index = toolCallDelta.index;\n\n if (toolCalls[index] == null) {\n if (toolCallDelta.id == null) {\n throw new InvalidResponseDataError({\n data: toolCallDelta,\n message: `Expected 'id' to be a string.`,\n });\n }\n\n if (toolCallDelta.function?.name == null) {\n throw new InvalidResponseDataError({\n data: toolCallDelta,\n message: `Expected 'function.name' to be a string.`,\n });\n }\n\n toolCalls[index] = {\n id: toolCallDelta.id,\n toolName: toolCallDelta.function.name,\n input: toolCallDelta.function.arguments ?? \"\",\n hasFinished: false,\n };\n\n controller.enqueue({\n type: \"tool-input-start\",\n id: toolCallDelta.id,\n toolName: toolCallDelta.function.name,\n providerExecuted: false,\n });\n\n if (toolCallDelta.function.arguments) {\n controller.enqueue({\n type: \"tool-input-delta\",\n id: toolCallDelta.id,\n delta: toolCallDelta.function.arguments,\n });\n }\n\n if (isParsableJson(toolCalls[index].input)) {\n controller.enqueue({\n type: \"tool-input-end\",\n id: toolCalls[index].id,\n });\n controller.enqueue({\n type: \"tool-call\",\n toolCallId: toolCalls[index].id ?? generateId(),\n toolName: toolCalls[index].toolName,\n input: toolCalls[index].input,\n });\n toolCalls[index].hasFinished = true;\n }\n\n continue;\n }\n\n const toolCall = toolCalls[index];\n\n if (toolCall.hasFinished) {\n continue;\n }\n\n if (toolCallDelta.function?.arguments != null) {\n toolCall.input += toolCallDelta.function.arguments;\n }\n\n controller.enqueue({\n type: \"tool-input-delta\",\n id: toolCall.id,\n delta: toolCallDelta.function?.arguments ?? \"\",\n });\n\n if (isParsableJson(toolCall.input)) {\n controller.enqueue({\n type: \"tool-input-end\",\n id: toolCall.id,\n });\n controller.enqueue({\n type: \"tool-call\",\n toolCallId: toolCall.id ?? generateId(),\n toolName: toolCall.toolName,\n input: toolCall.input,\n });\n toolCall.hasFinished = true;\n }\n }\n }\n\n const sources = Array.isArray(value.web_search)\n ? value.web_search\n : value.web_search != null\n ? [value.web_search]\n : [];\n\n for (const [index, source] of sources.entries()) {\n controller.enqueue({\n type: \"source\",\n sourceType: \"url\",\n id: source.link || `source-${index}`,\n url: source.link,\n title: source.title || undefined,\n providerMetadata: {\n zhipu: {\n icon: source.icon,\n media: source.media,\n content: source.content,\n },\n },\n });\n }\n },\n flush(controller) {\n if (isActiveReasoning) {\n controller.enqueue({\n type: \"reasoning-end\",\n id: \"reasoning-0\",\n });\n }\n\n if (isActiveText) {\n controller.enqueue({\n type: \"text-end\",\n id: \"txt-0\",\n });\n }\n\n controller.enqueue({\n type: \"finish\",\n finishReason,\n usage,\n });\n },\n }),\n ),\n request: { body },\n response: { headers: responseHeaders },\n };\n }\n}\n\nconst zhipuWebSearchItemSchema = z.object({\n icon: z.string().catch(\"\"),\n title: z.string().catch(\"\"),\n link: z.string().catch(\"\"),\n media: z.string().catch(\"\"),\n content: z.string().catch(\"\"),\n});\n\nconst zhipuChatResponseSchema = z.object({\n id: z.string().nullish(),\n created: z.number().nullish(),\n model: z.string().nullish(),\n choices: z.array(\n z.object({\n message: z.object({\n role: z.literal(\"assistant\"),\n content: z.string().nullish(),\n reasoning_content: z.string().nullish(),\n tool_calls: z\n .array(\n z.object({\n id: z.string(),\n index: z.number().nullish(),\n type: z.literal(\"function\"),\n function: z.object({ name: z.string(), arguments: z.string() }),\n }),\n )\n .nullish(),\n }),\n index: z.number(),\n finish_reason: z.string().nullish(),\n }),\n ),\n usage: z.object({\n prompt_tokens: z.number(),\n completion_tokens: z.number().nullish(),\n total_tokens: z.number().nullish(),\n }),\n web_search: z\n .union([zhipuWebSearchItemSchema, z.array(zhipuWebSearchItemSchema)])\n .nullish(),\n});\n\nconst zhipuChatChunkSchema = z.object({\n id: z.string().nullish(),\n created: z.number().nullish(),\n model: z.string().nullish(),\n choices: z.array(\n z.object({\n delta: z.object({\n role: z.enum([\"assistant\"]).optional(),\n content: z.string().nullish(),\n reasoning_content: z.string().nullish(),\n tool_calls: z\n .array(\n z.object({\n id: z.string().optional(),\n index: z.number(),\n type: z.literal(\"function\").optional(),\n function: z\n .object({\n name: z.string().optional(),\n arguments: z.string().optional(),\n })\n .optional(),\n }),\n )\n .nullish(),\n }),\n finish_reason: z.string().nullish(),\n index: z.number(),\n }),\n ),\n usage: z\n .object({\n prompt_tokens: z.number(),\n completion_tokens: z.number().nullish(),\n total_tokens: z.number().nullish(),\n })\n .nullish(),\n web_search: z\n .union([zhipuWebSearchItemSchema, z.array(zhipuWebSearchItemSchema)])\n .nullish(),\n});\n","export * as core from \"../core/index.js\";\nexport * from \"./schemas.js\";\nexport * from \"./checks.js\";\nexport * from \"./errors.js\";\nexport * from \"./parse.js\";\nexport * from \"./compat.js\";\n// zod-specified\nimport { config } from \"../core/index.js\";\nimport en from \"../locales/en.js\";\nconfig(en());\nexport { globalRegistry, registry, config, $output, $input, $brand, clone, regexes, treeifyError, prettifyError, formatError, flattenError, TimePrecision, util, NEVER, } from \"../core/index.js\";\nexport { toJSONSchema } from \"../core/json-schema-processors.js\";\nexport { fromJSONSchema } from \"./from-json-schema.js\";\nexport * as locales from \"../locales/index.js\";\n// iso\n// must be exported from top-level\n// https://github.com/colinhacks/zod/issues/4491\nexport { ZodISODateTime, ZodISODate, ZodISOTime, ZodISODuration } from \"./iso.js\";\nexport * as iso from \"./iso.js\";\nexport * as coerce from \"./coerce.js\";\n","export * from \"./core.js\";\nexport * from \"./parse.js\";\nexport * from \"./errors.js\";\nexport * from \"./schemas.js\";\nexport * from \"./checks.js\";\nexport * from \"./versions.js\";\nexport * as util from \"./util.js\";\nexport * as regexes from \"./regexes.js\";\nexport * as locales from \"../locales/index.js\";\nexport * from \"./registries.js\";\nexport * from \"./doc.js\";\nexport * from \"./api.js\";\nexport * from \"./to-json-schema.js\";\nexport { toJSONSchema } from \"./json-schema-processors.js\";\nexport { JSONSchemaGenerator } from \"./json-schema-generator.js\";\nexport * as JSONSchema from \"./json-schema.js\";\n","/** A special constant with type `never` */\nexport const NEVER = Object.freeze({\n status: \"aborted\",\n});\nexport /*@__NO_SIDE_EFFECTS__*/ function $constructor(name, initializer, params) {\n function init(inst, def) {\n if (!inst._zod) {\n Object.defineProperty(inst, \"_zod\", {\n value: {\n def,\n constr: _,\n traits: new Set(),\n },\n enumerable: false,\n });\n }\n if (inst._zod.traits.has(name)) {\n return;\n }\n inst._zod.traits.add(name);\n initializer(inst, def);\n // support prototype modifications\n const proto = _.prototype;\n const keys = Object.keys(proto);\n for (let i = 0; i < keys.length; i++) {\n const k = keys[i];\n if (!(k in inst)) {\n inst[k] = proto[k].bind(inst);\n }\n }\n }\n // doesn't work if Parent has a constructor with arguments\n const Parent = params?.Parent ?? Object;\n class Definition extends Parent {\n }\n Object.defineProperty(Definition, \"name\", { value: name });\n function _(def) {\n var _a;\n const inst = params?.Parent ? new Definition() : this;\n init(inst, def);\n (_a = inst._zod).deferred ?? (_a.deferred = []);\n for (const fn of inst._zod.deferred) {\n fn();\n }\n return inst;\n }\n Object.defineProperty(_, \"init\", { value: init });\n Object.defineProperty(_, Symbol.hasInstance, {\n value: (inst) => {\n if (params?.Parent && inst instanceof params.Parent)\n return true;\n return inst?._zod?.traits?.has(name);\n },\n });\n Object.defineProperty(_, \"name\", { value: name });\n return _;\n}\n////////////////////////////// UTILITIES ///////////////////////////////////////\nexport const $brand = Symbol(\"zod_brand\");\nexport class $ZodAsyncError extends Error {\n constructor() {\n super(`Encountered Promise during synchronous parse. Use .parseAsync() instead.`);\n }\n}\nexport class $ZodEncodeError extends Error {\n constructor(name) {\n super(`Encountered unidirectional transform during encode: ${name}`);\n this.name = \"ZodEncodeError\";\n }\n}\nexport const globalConfig = {};\nexport function config(newConfig) {\n if (newConfig)\n Object.assign(globalConfig, newConfig);\n return globalConfig;\n}\n","// functions\nexport function assertEqual(val) {\n return val;\n}\nexport function assertNotEqual(val) {\n return val;\n}\nexport function assertIs(_arg) { }\nexport function assertNever(_x) {\n throw new Error(\"Unexpected value in exhaustive check\");\n}\nexport function assert(_) { }\nexport function getEnumValues(entries) {\n const numericValues = Object.values(entries).filter((v) => typeof v === \"number\");\n const values = Object.entries(entries)\n .filter(([k, _]) => numericValues.indexOf(+k) === -1)\n .map(([_, v]) => v);\n return values;\n}\nexport function joinValues(array, separator = \"|\") {\n return array.map((val) => stringifyPrimitive(val)).join(separator);\n}\nexport function jsonStringifyReplacer(_, value) {\n if (typeof value === \"bigint\")\n return value.toString();\n return value;\n}\nexport function cached(getter) {\n const set = false;\n return {\n get value() {\n if (!set) {\n const value = getter();\n Object.defineProperty(this, \"value\", { value });\n return value;\n }\n throw new Error(\"cached value already set\");\n },\n };\n}\nexport function nullish(input) {\n return input === null || input === undefined;\n}\nexport function cleanRegex(source) {\n const start = source.startsWith(\"^\") ? 1 : 0;\n const end = source.endsWith(\"$\") ? source.length - 1 : source.length;\n return source.slice(start, end);\n}\nexport function floatSafeRemainder(val, step) {\n const valDecCount = (val.toString().split(\".\")[1] || \"\").length;\n const stepString = step.toString();\n let stepDecCount = (stepString.split(\".\")[1] || \"\").length;\n if (stepDecCount === 0 && /\\d?e-\\d?/.test(stepString)) {\n const match = stepString.match(/\\d?e-(\\d?)/);\n if (match?.[1]) {\n stepDecCount = Number.parseInt(match[1]);\n }\n }\n const decCount = valDecCount > stepDecCount ? valDecCount : stepDecCount;\n const valInt = Number.parseInt(val.toFixed(decCount).replace(\".\", \"\"));\n const stepInt = Number.parseInt(step.toFixed(decCount).replace(\".\", \"\"));\n return (valInt % stepInt) / 10 ** decCount;\n}\nconst EVALUATING = Symbol(\"evaluating\");\nexport function defineLazy(object, key, getter) {\n let value = undefined;\n Object.defineProperty(object, key, {\n get() {\n if (value === EVALUATING) {\n // Circular reference detected, return undefined to break the cycle\n return undefined;\n }\n if (value === undefined) {\n value = EVALUATING;\n value = getter();\n }\n return value;\n },\n set(v) {\n Object.defineProperty(object, key, {\n value: v,\n // configurable: true,\n });\n // object[key] = v;\n },\n configurable: true,\n });\n}\nexport function objectClone(obj) {\n return Object.create(Object.getPrototypeOf(obj), Object.getOwnPropertyDescriptors(obj));\n}\nexport function assignProp(target, prop, value) {\n Object.defineProperty(target, prop, {\n value,\n writable: true,\n enumerable: true,\n configurable: true,\n });\n}\nexport function mergeDefs(...defs) {\n const mergedDescriptors = {};\n for (const def of defs) {\n const descriptors = Object.getOwnPropertyDescriptors(def);\n Object.assign(mergedDescriptors, descriptors);\n }\n return Object.defineProperties({}, mergedDescriptors);\n}\nexport function cloneDef(schema) {\n return mergeDefs(schema._zod.def);\n}\nexport function getElementAtPath(obj, path) {\n if (!path)\n return obj;\n return path.reduce((acc, key) => acc?.[key], obj);\n}\nexport function promiseAllObject(promisesObj) {\n const keys = Object.keys(promisesObj);\n const promises = keys.map((key) => promisesObj[key]);\n return Promise.all(promises).then((results) => {\n const resolvedObj = {};\n for (let i = 0; i < keys.length; i++) {\n resolvedObj[keys[i]] = results[i];\n }\n return resolvedObj;\n });\n}\nexport function randomString(length = 10) {\n const chars = \"abcdefghijklmnopqrstuvwxyz\";\n let str = \"\";\n for (let i = 0; i < length; i++) {\n str += chars[Math.floor(Math.random() * chars.length)];\n }\n return str;\n}\nexport function esc(str) {\n return JSON.stringify(str);\n}\nexport function slugify(input) {\n return input\n .toLowerCase()\n .trim()\n .replace(/[^\\w\\s-]/g, \"\")\n .replace(/[\\s_-]+/g, \"-\")\n .replace(/^-+|-+$/g, \"\");\n}\nexport const captureStackTrace = (\"captureStackTrace\" in Error ? Error.captureStackTrace : (..._args) => { });\nexport function isObject(data) {\n return typeof data === \"object\" && data !== null && !Array.isArray(data);\n}\nexport const allowsEval = cached(() => {\n // @ts-ignore\n if (typeof navigator !== \"undefined\" && navigator?.userAgent?.includes(\"Cloudflare\")) {\n return false;\n }\n try {\n const F = Function;\n new F(\"\");\n return true;\n }\n catch (_) {\n return false;\n }\n});\nexport function isPlainObject(o) {\n if (isObject(o) === false)\n return false;\n // modified constructor\n const ctor = o.constructor;\n if (ctor === undefined)\n return true;\n if (typeof ctor !== \"function\")\n return true;\n // modified prototype\n const prot = ctor.prototype;\n if (isObject(prot) === false)\n return false;\n // ctor doesn't have static `isPrototypeOf`\n if (Object.prototype.hasOwnProperty.call(prot, \"isPrototypeOf\") === false) {\n return false;\n }\n return true;\n}\nexport function shallowClone(o) {\n if (isPlainObject(o))\n return { ...o };\n if (Array.isArray(o))\n return [...o];\n return o;\n}\nexport function numKeys(data) {\n let keyCount = 0;\n for (const key in data) {\n if (Object.prototype.hasOwnProperty.call(data, key)) {\n keyCount++;\n }\n }\n return keyCount;\n}\nexport const getParsedType = (data) => {\n const t = typeof data;\n switch (t) {\n case \"undefined\":\n return \"undefined\";\n case \"string\":\n return \"string\";\n case \"number\":\n return Number.isNaN(data) ? \"nan\" : \"number\";\n case \"boolean\":\n return \"boolean\";\n case \"function\":\n return \"function\";\n case \"bigint\":\n return \"bigint\";\n case \"symbol\":\n return \"symbol\";\n case \"object\":\n if (Array.isArray(data)) {\n return \"array\";\n }\n if (data === null) {\n return \"null\";\n }\n if (data.then && typeof data.then === \"function\" && data.catch && typeof data.catch === \"function\") {\n return \"promise\";\n }\n if (typeof Map !== \"undefined\" && data instanceof Map) {\n return \"map\";\n }\n if (typeof Set !== \"undefined\" && data instanceof Set) {\n return \"set\";\n }\n if (typeof Date !== \"undefined\" && data instanceof Date) {\n return \"date\";\n }\n // @ts-ignore\n if (typeof File !== \"undefined\" && data instanceof File) {\n return \"file\";\n }\n return \"object\";\n default:\n throw new Error(`Unknown data type: ${t}`);\n }\n};\nexport const propertyKeyTypes = new Set([\"string\", \"number\", \"symbol\"]);\nexport const primitiveTypes = new Set([\"string\", \"number\", \"bigint\", \"boolean\", \"symbol\", \"undefined\"]);\nexport function escapeRegex(str) {\n return str.replace(/[.*+?^${}()|[\\]\\\\]/g, \"\\\\$&\");\n}\n// zod-specific utils\nexport function clone(inst, def, params) {\n const cl = new inst._zod.constr(def ?? inst._zod.def);\n if (!def || params?.parent)\n cl._zod.parent = inst;\n return cl;\n}\nexport function normalizeParams(_params) {\n const params = _params;\n if (!params)\n return {};\n if (typeof params === \"string\")\n return { error: () => params };\n if (params?.message !== undefined) {\n if (params?.error !== undefined)\n throw new Error(\"Cannot specify both `message` and `error` params\");\n params.error = params.message;\n }\n delete params.message;\n if (typeof params.error === \"string\")\n return { ...params, error: () => params.error };\n return params;\n}\nexport function createTransparentProxy(getter) {\n let target;\n return new Proxy({}, {\n get(_, prop, receiver) {\n target ?? (target = getter());\n return Reflect.get(target, prop, receiver);\n },\n set(_, prop, value, receiver) {\n target ?? (target = getter());\n return Reflect.set(target, prop, value, receiver);\n },\n has(_, prop) {\n target ?? (target = getter());\n return Reflect.has(target, prop);\n },\n deleteProperty(_, prop) {\n target ?? (target = getter());\n return Reflect.deleteProperty(target, prop);\n },\n ownKeys(_) {\n target ?? (target = getter());\n return Reflect.ownKeys(target);\n },\n getOwnPropertyDescriptor(_, prop) {\n target ?? (target = getter());\n return Reflect.getOwnPropertyDescriptor(target, prop);\n },\n defineProperty(_, prop, descriptor) {\n target ?? (target = getter());\n return Reflect.defineProperty(target, prop, descriptor);\n },\n });\n}\nexport function stringifyPrimitive(value) {\n if (typeof value === \"bigint\")\n return value.toString() + \"n\";\n if (typeof value === \"string\")\n return `\"${value}\"`;\n return `${value}`;\n}\nexport function optionalKeys(shape) {\n return Object.keys(shape).filter((k) => {\n return shape[k]._zod.optin === \"optional\" && shape[k]._zod.optout === \"optional\";\n });\n}\nexport const NUMBER_FORMAT_RANGES = {\n safeint: [Number.MIN_SAFE_INTEGER, Number.MAX_SAFE_INTEGER],\n int32: [-2147483648, 2147483647],\n uint32: [0, 4294967295],\n float32: [-3.4028234663852886e38, 3.4028234663852886e38],\n float64: [-Number.MAX_VALUE, Number.MAX_VALUE],\n};\nexport const BIGINT_FORMAT_RANGES = {\n int64: [/* @__PURE__*/ BigInt(\"-9223372036854775808\"), /* @__PURE__*/ BigInt(\"9223372036854775807\")],\n uint64: [/* @__PURE__*/ BigInt(0), /* @__PURE__*/ BigInt(\"18446744073709551615\")],\n};\nexport function pick(schema, mask) {\n const currDef = schema._zod.def;\n const checks = currDef.checks;\n const hasChecks = checks && checks.length > 0;\n if (hasChecks) {\n throw new Error(\".pick() cannot be used on object schemas containing refinements\");\n }\n const def = mergeDefs(schema._zod.def, {\n get shape() {\n const newShape = {};\n for (const key in mask) {\n if (!(key in currDef.shape)) {\n throw new Error(`Unrecognized key: \"${key}\"`);\n }\n if (!mask[key])\n continue;\n newShape[key] = currDef.shape[key];\n }\n assignProp(this, \"shape\", newShape); // self-caching\n return newShape;\n },\n checks: [],\n });\n return clone(schema, def);\n}\nexport function omit(schema, mask) {\n const currDef = schema._zod.def;\n const checks = currDef.checks;\n const hasChecks = checks && checks.length > 0;\n if (hasChecks) {\n throw new Error(\".omit() cannot be used on object schemas containing refinements\");\n }\n const def = mergeDefs(schema._zod.def, {\n get shape() {\n const newShape = { ...schema._zod.def.shape };\n for (const key in mask) {\n if (!(key in currDef.shape)) {\n throw new Error(`Unrecognized key: \"${key}\"`);\n }\n if (!mask[key])\n continue;\n delete newShape[key];\n }\n assignProp(this, \"shape\", newShape); // self-caching\n return newShape;\n },\n checks: [],\n });\n return clone(schema, def);\n}\nexport function extend(schema, shape) {\n if (!isPlainObject(shape)) {\n throw new Error(\"Invalid input to extend: expected a plain object\");\n }\n const checks = schema._zod.def.checks;\n const hasChecks = checks && checks.length > 0;\n if (hasChecks) {\n // Only throw if new shape overlaps with existing shape\n // Use getOwnPropertyDescriptor to check key existence without accessing values\n const existingShape = schema._zod.def.shape;\n for (const key in shape) {\n if (Object.getOwnPropertyDescriptor(existingShape, key) !== undefined) {\n throw new Error(\"Cannot overwrite keys on object schemas containing refinements. Use `.safeExtend()` instead.\");\n }\n }\n }\n const def = mergeDefs(schema._zod.def, {\n get shape() {\n const _shape = { ...schema._zod.def.shape, ...shape };\n assignProp(this, \"sha