@ai-sdk/zai 0.0.0 → 1.0.1

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/dist/index.mjs ADDED
@@ -0,0 +1,290 @@
1
+ // src/zai-provider.ts
2
+ import {
3
+ NoSuchModelError
4
+ } from "@ai-sdk/provider";
5
+ import {
6
+ loadApiKey,
7
+ withoutTrailingSlash,
8
+ withUserAgentSuffix
9
+ } from "@ai-sdk/provider-utils";
10
+
11
+ // src/version.ts
12
+ var VERSION = true ? "1.0.1" : "0.0.0-test";
13
+
14
+ // src/zai-chat-language-model.ts
15
+ import { OpenAICompatibleChatLanguageModel } from "@ai-sdk/openai-compatible";
16
+ import {
17
+ parseProviderOptions
18
+ } from "@ai-sdk/provider-utils";
19
+
20
+ // src/zai-chat-language-model-options.ts
21
+ import { z } from "zod/v4";
22
+ var zaiLanguageModelChatOptions = z.object({
23
+ /**
24
+ * Enables or disables sampling. When disabled, temperature and topP do not
25
+ * take effect.
26
+ */
27
+ doSample: z.boolean().optional(),
28
+ /**
29
+ * Controls model thinking and whether reasoning from earlier turns is kept.
30
+ */
31
+ thinking: z.object({
32
+ type: z.enum(["enabled", "disabled"]).optional(),
33
+ clearThinking: z.boolean().optional()
34
+ }).optional(),
35
+ /**
36
+ * Controls reasoning effort for GLM-5.2 and later models.
37
+ */
38
+ reasoningEffort: z.enum(["none", "minimal", "low", "medium", "high", "xhigh", "max"]).optional(),
39
+ /**
40
+ * Enables incremental function-call argument streaming on supported models.
41
+ */
42
+ toolStream: z.boolean().optional(),
43
+ /**
44
+ * A caller-provided request identifier between 6 and 64 characters.
45
+ */
46
+ requestId: z.string().min(6).max(64).optional(),
47
+ /**
48
+ * A non-sensitive end-user identifier between 6 and 128 characters.
49
+ */
50
+ userId: z.string().min(6).max(128).optional()
51
+ });
52
+
53
+ // src/zai-error.ts
54
+ import { z as z2 } from "zod/v4";
55
+ var zaiErrorDetailsSchema = z2.object({
56
+ code: z2.union([z2.number(), z2.string()]).nullish(),
57
+ message: z2.string()
58
+ });
59
+ var zaiErrorSchema = z2.union([
60
+ zaiErrorDetailsSchema,
61
+ z2.object({ error: zaiErrorDetailsSchema })
62
+ ]);
63
+ var zaiErrorStructure = {
64
+ errorSchema: zaiErrorSchema,
65
+ errorToMessage: (data) => "error" in data ? data.error.message : data.message
66
+ };
67
+
68
+ // src/zai-chat-language-model.ts
69
+ function transformZaiRequestBody(args) {
70
+ const {
71
+ doSample,
72
+ frequency_penalty: _frequencyPenalty,
73
+ presence_penalty: _presencePenalty,
74
+ requestId,
75
+ seed: _seed,
76
+ thinking,
77
+ toolStream,
78
+ user: _user,
79
+ userId,
80
+ verbosity: _verbosity,
81
+ ...restArgs
82
+ } = args;
83
+ return {
84
+ ...restArgs,
85
+ ...doSample !== void 0 && { do_sample: doSample },
86
+ ...thinking !== void 0 && {
87
+ thinking: {
88
+ ...thinking.type !== void 0 && { type: thinking.type },
89
+ ...thinking.clearThinking !== void 0 && {
90
+ clear_thinking: thinking.clearThinking
91
+ }
92
+ }
93
+ },
94
+ ...toolStream !== void 0 && { tool_stream: toolStream },
95
+ ...requestId !== void 0 && { request_id: requestId },
96
+ ...userId !== void 0 && { user_id: userId }
97
+ };
98
+ }
99
+ function mapZaiFinishReason(finishReason, rawFinishReason) {
100
+ switch (rawFinishReason) {
101
+ case "sensitive":
102
+ return "content-filter";
103
+ case "model_context_window_exceeded":
104
+ return "length";
105
+ case "network_error":
106
+ return "error";
107
+ default:
108
+ return finishReason;
109
+ }
110
+ }
111
+ function getRawFinishReason(responseBody) {
112
+ if (responseBody == null || typeof responseBody !== "object") {
113
+ return void 0;
114
+ }
115
+ const choices = responseBody.choices;
116
+ if (!Array.isArray(choices) || choices.length === 0) {
117
+ return void 0;
118
+ }
119
+ const choice = choices[0];
120
+ if (choice == null || typeof choice !== "object") {
121
+ return void 0;
122
+ }
123
+ const finishReason = choice.finish_reason;
124
+ return typeof finishReason === "string" ? finishReason : void 0;
125
+ }
126
+ var ZaiChatLanguageModel = class extends OpenAICompatibleChatLanguageModel {
127
+ constructor(modelId, config) {
128
+ const headers = config.headers;
129
+ super(modelId, {
130
+ provider: config.provider,
131
+ url: ({ path }) => `${config.baseURL}${path}`,
132
+ headers: () => headers == null ? {} : typeof headers === "function" ? headers() : headers,
133
+ fetch: config.fetch,
134
+ errorStructure: zaiErrorStructure,
135
+ transformRequestBody: transformZaiRequestBody,
136
+ supportedUrls: () => ({
137
+ "image/*": [/^https?:\/\//],
138
+ "video/*": [/^https?:\/\//]
139
+ })
140
+ });
141
+ }
142
+ async prepareCallOptions(options) {
143
+ const warnings = [];
144
+ const zaiOptions = await parseProviderOptions({
145
+ provider: "zai",
146
+ providerOptions: options.providerOptions,
147
+ schema: zaiLanguageModelChatOptions
148
+ });
149
+ if (options.frequencyPenalty != null) {
150
+ warnings.push({
151
+ type: "unsupported-setting",
152
+ setting: "frequencyPenalty"
153
+ });
154
+ }
155
+ if (options.presencePenalty != null) {
156
+ warnings.push({
157
+ type: "unsupported-setting",
158
+ setting: "presencePenalty"
159
+ });
160
+ }
161
+ if (options.seed != null) {
162
+ warnings.push({ type: "unsupported-setting", setting: "seed" });
163
+ }
164
+ let tools = options.tools;
165
+ let toolChoice = options.toolChoice;
166
+ if ((toolChoice == null ? void 0 : toolChoice.type) === "none") {
167
+ tools = void 0;
168
+ toolChoice = void 0;
169
+ } else if (toolChoice != null && toolChoice.type !== "auto") {
170
+ warnings.push({
171
+ type: "unsupported-setting",
172
+ setting: "toolChoice",
173
+ details: "Z.AI currently supports only automatic tool selection."
174
+ });
175
+ toolChoice = void 0;
176
+ }
177
+ const normalizedOptions = {
178
+ ...options,
179
+ frequencyPenalty: void 0,
180
+ presencePenalty: void 0,
181
+ seed: void 0,
182
+ tools,
183
+ toolChoice,
184
+ providerOptions: zaiOptions == null ? options.providerOptions : {
185
+ ...options.providerOptions,
186
+ zai: zaiOptions
187
+ }
188
+ };
189
+ return { normalizedOptions, warnings };
190
+ }
191
+ async doGenerate(options) {
192
+ var _a;
193
+ const { normalizedOptions, warnings } = await this.prepareCallOptions(options);
194
+ const result = await super.doGenerate(normalizedOptions);
195
+ return {
196
+ ...result,
197
+ finishReason: mapZaiFinishReason(
198
+ result.finishReason,
199
+ getRawFinishReason((_a = result.response) == null ? void 0 : _a.body)
200
+ ),
201
+ warnings: [...result.warnings, ...warnings]
202
+ };
203
+ }
204
+ async doStream(options) {
205
+ const originalIncludeRawChunks = options.includeRawChunks;
206
+ const { normalizedOptions, warnings } = await this.prepareCallOptions(options);
207
+ const result = await super.doStream({
208
+ ...normalizedOptions,
209
+ includeRawChunks: true
210
+ });
211
+ let rawFinishReason;
212
+ return {
213
+ ...result,
214
+ stream: result.stream.pipeThrough(
215
+ new TransformStream({
216
+ transform(part, controller) {
217
+ var _a;
218
+ if (part.type === "stream-start") {
219
+ controller.enqueue({
220
+ ...part,
221
+ warnings: [...part.warnings, ...warnings]
222
+ });
223
+ return;
224
+ }
225
+ if (part.type === "raw") {
226
+ rawFinishReason = (_a = getRawFinishReason(part.rawValue)) != null ? _a : rawFinishReason;
227
+ if (originalIncludeRawChunks) {
228
+ controller.enqueue(part);
229
+ }
230
+ return;
231
+ }
232
+ if (part.type === "finish") {
233
+ controller.enqueue({
234
+ ...part,
235
+ finishReason: mapZaiFinishReason(
236
+ part.finishReason,
237
+ rawFinishReason
238
+ )
239
+ });
240
+ return;
241
+ }
242
+ controller.enqueue(part);
243
+ }
244
+ })
245
+ )
246
+ };
247
+ }
248
+ };
249
+
250
+ // src/zai-provider.ts
251
+ function createZai(options = {}) {
252
+ var _a;
253
+ const baseURL = (_a = withoutTrailingSlash(options.baseURL)) != null ? _a : "https://api.z.ai/api/paas/v4";
254
+ const getHeaders = () => withUserAgentSuffix(
255
+ {
256
+ Authorization: `Bearer ${loadApiKey({
257
+ apiKey: options.apiKey,
258
+ environmentVariableName: "ZAI_API_KEY",
259
+ description: "Z.AI API key"
260
+ })}`,
261
+ ...options.headers
262
+ },
263
+ `ai-sdk/zai/${VERSION}`
264
+ );
265
+ const createLanguageModel = (modelId) => new ZaiChatLanguageModel(modelId, {
266
+ provider: "zai.chat",
267
+ baseURL,
268
+ headers: getHeaders,
269
+ fetch: options.fetch
270
+ });
271
+ const provider = (modelId) => createLanguageModel(modelId);
272
+ provider.specificationVersion = "v2";
273
+ provider.languageModel = createLanguageModel;
274
+ provider.chatModel = createLanguageModel;
275
+ provider.chat = createLanguageModel;
276
+ provider.textEmbeddingModel = (modelId) => {
277
+ throw new NoSuchModelError({ modelId, modelType: "textEmbeddingModel" });
278
+ };
279
+ provider.imageModel = (modelId) => {
280
+ throw new NoSuchModelError({ modelId, modelType: "imageModel" });
281
+ };
282
+ return provider;
283
+ }
284
+ var zai = createZai();
285
+ export {
286
+ VERSION,
287
+ createZai,
288
+ zai
289
+ };
290
+ //# sourceMappingURL=index.mjs.map
@@ -0,0 +1 @@
1
+ {"version":3,"sources":["../src/zai-provider.ts","../src/version.ts","../src/zai-chat-language-model.ts","../src/zai-chat-language-model-options.ts","../src/zai-error.ts"],"sourcesContent":["import {\n NoSuchModelError,\n type LanguageModelV2,\n type ProviderV2,\n} from '@ai-sdk/provider';\nimport {\n loadApiKey,\n withoutTrailingSlash,\n withUserAgentSuffix,\n type FetchFunction,\n} from '@ai-sdk/provider-utils';\nimport { VERSION } from './version';\nimport { ZaiChatLanguageModel } from './zai-chat-language-model';\nimport type { ZaiChatModelId } from './zai-chat-options';\n\nexport interface ZaiProviderSettings {\n /**\n * Z.AI API key. Defaults to the `ZAI_API_KEY` environment variable.\n */\n apiKey?: string;\n\n /**\n * Base URL for API calls. Defaults to\n * `https://api.z.ai/api/paas/v4`.\n */\n baseURL?: string;\n\n /**\n * Custom headers to include in requests.\n */\n headers?: Record<string, string>;\n\n /**\n * Custom fetch implementation.\n */\n fetch?: FetchFunction;\n}\n\nexport interface ZaiProvider extends ProviderV2 {\n /**\n * Creates a Z.AI chat model for text generation.\n */\n (modelId: ZaiChatModelId): LanguageModelV2;\n\n /**\n * Creates a Z.AI language model.\n */\n languageModel(modelId: ZaiChatModelId): LanguageModelV2;\n\n /**\n * Creates a Z.AI chat model.\n */\n chatModel(modelId: ZaiChatModelId): LanguageModelV2;\n\n /**\n * Creates a Z.AI chat model.\n */\n chat(modelId: ZaiChatModelId): LanguageModelV2;\n}\n\nexport function createZai(options: ZaiProviderSettings = {}): ZaiProvider {\n const baseURL =\n withoutTrailingSlash(options.baseURL) ?? 'https://api.z.ai/api/paas/v4';\n\n const getHeaders = () =>\n withUserAgentSuffix(\n {\n Authorization: `Bearer ${loadApiKey({\n apiKey: options.apiKey,\n environmentVariableName: 'ZAI_API_KEY',\n description: 'Z.AI API key',\n })}`,\n ...options.headers,\n },\n `ai-sdk/zai/${VERSION}`,\n );\n\n const createLanguageModel = (modelId: ZaiChatModelId) =>\n new ZaiChatLanguageModel(modelId, {\n provider: 'zai.chat',\n baseURL,\n headers: getHeaders,\n fetch: options.fetch,\n });\n\n const provider = (modelId: ZaiChatModelId) => createLanguageModel(modelId);\n\n provider.specificationVersion = 'v2' as const;\n provider.languageModel = createLanguageModel;\n provider.chatModel = createLanguageModel;\n provider.chat = createLanguageModel;\n\n provider.textEmbeddingModel = (modelId: string) => {\n throw new NoSuchModelError({ modelId, modelType: 'textEmbeddingModel' });\n };\n provider.imageModel = (modelId: string) => {\n throw new NoSuchModelError({ modelId, modelType: 'imageModel' });\n };\n\n return provider;\n}\n\nexport const zai = createZai();\n","// Version string of this package injected at build time.\ndeclare const __PACKAGE_VERSION__: string | undefined;\nexport const VERSION: string =\n typeof __PACKAGE_VERSION__ !== 'undefined'\n ? __PACKAGE_VERSION__\n : '0.0.0-test';\n","import { OpenAICompatibleChatLanguageModel } from '@ai-sdk/openai-compatible';\nimport type {\n LanguageModelV2,\n LanguageModelV2CallOptions,\n LanguageModelV2CallWarning,\n LanguageModelV2FinishReason,\n LanguageModelV2StreamPart,\n} from '@ai-sdk/provider';\nimport {\n parseProviderOptions,\n type FetchFunction,\n} from '@ai-sdk/provider-utils';\nimport type { ZaiChatModelId } from './zai-chat-options';\nimport { zaiLanguageModelChatOptions } from './zai-chat-language-model-options';\nimport { zaiErrorStructure } from './zai-error';\n\nexport type ZaiChatConfig = {\n provider: string;\n baseURL: string;\n headers?:\n | Record<string, string | undefined>\n | (() => Record<string, string | undefined>);\n fetch?: FetchFunction;\n};\n\nfunction transformZaiRequestBody(\n args: Record<string, any>,\n): Record<string, any> {\n const {\n doSample,\n frequency_penalty: _frequencyPenalty,\n presence_penalty: _presencePenalty,\n requestId,\n seed: _seed,\n thinking,\n toolStream,\n user: _user,\n userId,\n verbosity: _verbosity,\n ...restArgs\n } = args;\n\n return {\n ...restArgs,\n ...(doSample !== undefined && { do_sample: doSample }),\n ...(thinking !== undefined && {\n thinking: {\n ...(thinking.type !== undefined && { type: thinking.type }),\n ...(thinking.clearThinking !== undefined && {\n clear_thinking: thinking.clearThinking,\n }),\n },\n }),\n ...(toolStream !== undefined && { tool_stream: toolStream }),\n ...(requestId !== undefined && { request_id: requestId }),\n ...(userId !== undefined && { user_id: userId }),\n };\n}\n\nfunction mapZaiFinishReason(\n finishReason: LanguageModelV2FinishReason,\n rawFinishReason: string | undefined,\n): LanguageModelV2FinishReason {\n switch (rawFinishReason) {\n case 'sensitive':\n return 'content-filter';\n case 'model_context_window_exceeded':\n return 'length';\n case 'network_error':\n return 'error';\n default:\n return finishReason;\n }\n}\n\nfunction getRawFinishReason(responseBody: unknown): string | undefined {\n if (responseBody == null || typeof responseBody !== 'object') {\n return undefined;\n }\n\n const choices = (responseBody as { choices?: unknown }).choices;\n if (!Array.isArray(choices) || choices.length === 0) {\n return undefined;\n }\n\n const choice = choices[0];\n if (choice == null || typeof choice !== 'object') {\n return undefined;\n }\n\n const finishReason = (choice as { finish_reason?: unknown }).finish_reason;\n return typeof finishReason === 'string' ? finishReason : undefined;\n}\n\nexport class ZaiChatLanguageModel\n extends OpenAICompatibleChatLanguageModel\n implements LanguageModelV2\n{\n constructor(modelId: ZaiChatModelId, config: ZaiChatConfig) {\n const headers = config.headers;\n\n super(modelId, {\n provider: config.provider,\n url: ({ path }) => `${config.baseURL}${path}`,\n headers: () =>\n headers == null\n ? {}\n : typeof headers === 'function'\n ? headers()\n : headers,\n fetch: config.fetch,\n errorStructure: zaiErrorStructure,\n transformRequestBody: transformZaiRequestBody,\n supportedUrls: () => ({\n 'image/*': [/^https?:\\/\\//],\n 'video/*': [/^https?:\\/\\//],\n }),\n });\n }\n\n private async prepareCallOptions(options: LanguageModelV2CallOptions) {\n const warnings: LanguageModelV2CallWarning[] = [];\n\n const zaiOptions = await parseProviderOptions({\n provider: 'zai',\n providerOptions: options.providerOptions,\n schema: zaiLanguageModelChatOptions,\n });\n\n if (options.frequencyPenalty != null) {\n warnings.push({\n type: 'unsupported-setting',\n setting: 'frequencyPenalty',\n });\n }\n if (options.presencePenalty != null) {\n warnings.push({\n type: 'unsupported-setting',\n setting: 'presencePenalty',\n });\n }\n if (options.seed != null) {\n warnings.push({ type: 'unsupported-setting', setting: 'seed' });\n }\n\n let tools = options.tools;\n let toolChoice = options.toolChoice;\n\n if (toolChoice?.type === 'none') {\n tools = undefined;\n toolChoice = undefined;\n } else if (toolChoice != null && toolChoice.type !== 'auto') {\n warnings.push({\n type: 'unsupported-setting',\n setting: 'toolChoice',\n details: 'Z.AI currently supports only automatic tool selection.',\n });\n toolChoice = undefined;\n }\n\n const normalizedOptions: LanguageModelV2CallOptions = {\n ...options,\n frequencyPenalty: undefined,\n presencePenalty: undefined,\n seed: undefined,\n tools,\n toolChoice,\n providerOptions:\n zaiOptions == null\n ? options.providerOptions\n : {\n ...options.providerOptions,\n zai: zaiOptions,\n },\n };\n\n return { normalizedOptions, warnings };\n }\n\n async doGenerate(\n options: Parameters<LanguageModelV2['doGenerate']>[0],\n ): Promise<Awaited<ReturnType<LanguageModelV2['doGenerate']>>> {\n const { normalizedOptions, warnings } =\n await this.prepareCallOptions(options);\n const result = await super.doGenerate(normalizedOptions);\n\n return {\n ...result,\n finishReason: mapZaiFinishReason(\n result.finishReason,\n getRawFinishReason(result.response?.body),\n ),\n warnings: [...result.warnings, ...warnings],\n };\n }\n\n async doStream(\n options: Parameters<LanguageModelV2['doStream']>[0],\n ): Promise<Awaited<ReturnType<LanguageModelV2['doStream']>>> {\n const originalIncludeRawChunks = options.includeRawChunks;\n const { normalizedOptions, warnings } =\n await this.prepareCallOptions(options);\n const result = await super.doStream({\n ...normalizedOptions,\n includeRawChunks: true,\n });\n\n let rawFinishReason: string | undefined;\n\n return {\n ...result,\n stream: result.stream.pipeThrough(\n new TransformStream<\n LanguageModelV2StreamPart,\n LanguageModelV2StreamPart\n >({\n transform(part, controller) {\n if (part.type === 'stream-start') {\n controller.enqueue({\n ...part,\n warnings: [...part.warnings, ...warnings],\n });\n return;\n }\n\n if (part.type === 'raw') {\n rawFinishReason =\n getRawFinishReason(part.rawValue) ?? rawFinishReason;\n if (originalIncludeRawChunks) {\n controller.enqueue(part);\n }\n return;\n }\n\n if (part.type === 'finish') {\n controller.enqueue({\n ...part,\n finishReason: mapZaiFinishReason(\n part.finishReason,\n rawFinishReason,\n ),\n });\n return;\n }\n\n controller.enqueue(part);\n },\n }),\n ),\n };\n }\n}\n","import { z } from 'zod/v4';\n\nexport const zaiLanguageModelChatOptions = z.object({\n /**\n * Enables or disables sampling. When disabled, temperature and topP do not\n * take effect.\n */\n doSample: z.boolean().optional(),\n\n /**\n * Controls model thinking and whether reasoning from earlier turns is kept.\n */\n thinking: z\n .object({\n type: z.enum(['enabled', 'disabled']).optional(),\n clearThinking: z.boolean().optional(),\n })\n .optional(),\n\n /**\n * Controls reasoning effort for GLM-5.2 and later models.\n */\n reasoningEffort: z\n .enum(['none', 'minimal', 'low', 'medium', 'high', 'xhigh', 'max'])\n .optional(),\n\n /**\n * Enables incremental function-call argument streaming on supported models.\n */\n toolStream: z.boolean().optional(),\n\n /**\n * A caller-provided request identifier between 6 and 64 characters.\n */\n requestId: z.string().min(6).max(64).optional(),\n\n /**\n * A non-sensitive end-user identifier between 6 and 128 characters.\n */\n userId: z.string().min(6).max(128).optional(),\n});\n\nexport type ZaiLanguageModelChatOptions = z.infer<\n typeof zaiLanguageModelChatOptions\n>;\n","import type { ProviderErrorStructure } from '@ai-sdk/openai-compatible';\nimport { z } from 'zod/v4';\n\nconst zaiErrorDetailsSchema = z.object({\n code: z.union([z.number(), z.string()]).nullish(),\n message: z.string(),\n});\n\nconst zaiErrorSchema = z.union([\n zaiErrorDetailsSchema,\n z.object({ error: zaiErrorDetailsSchema }),\n]);\n\nexport type ZaiErrorData = z.infer<typeof zaiErrorSchema>;\n\nexport const zaiErrorStructure: ProviderErrorStructure<ZaiErrorData> = {\n errorSchema: zaiErrorSchema,\n errorToMessage: data => ('error' in data ? data.error.message : data.message),\n};\n"],"mappings":";AAAA;AAAA,EACE;AAAA,OAGK;AACP;AAAA,EACE;AAAA,EACA;AAAA,EACA;AAAA,OAEK;;;ACRA,IAAM,UACX,OACI,UACA;;;ACLN,SAAS,yCAAyC;AAQlD;AAAA,EACE;AAAA,OAEK;;;ACXP,SAAS,SAAS;AAEX,IAAM,8BAA8B,EAAE,OAAO;AAAA;AAAA;AAAA;AAAA;AAAA,EAKlD,UAAU,EAAE,QAAQ,EAAE,SAAS;AAAA;AAAA;AAAA;AAAA,EAK/B,UAAU,EACP,OAAO;AAAA,IACN,MAAM,EAAE,KAAK,CAAC,WAAW,UAAU,CAAC,EAAE,SAAS;AAAA,IAC/C,eAAe,EAAE,QAAQ,EAAE,SAAS;AAAA,EACtC,CAAC,EACA,SAAS;AAAA;AAAA;AAAA;AAAA,EAKZ,iBAAiB,EACd,KAAK,CAAC,QAAQ,WAAW,OAAO,UAAU,QAAQ,SAAS,KAAK,CAAC,EACjE,SAAS;AAAA;AAAA;AAAA;AAAA,EAKZ,YAAY,EAAE,QAAQ,EAAE,SAAS;AAAA;AAAA;AAAA;AAAA,EAKjC,WAAW,EAAE,OAAO,EAAE,IAAI,CAAC,EAAE,IAAI,EAAE,EAAE,SAAS;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,UAAU;AAAA,IACV;AAAA,IACA,SAAS;AAAA,IACT,OAAO,QAAQ;AAAA,EACjB,CAAC;AAEH,QAAM,WAAW,CAAC,YAA4B,oBAAoB,OAAO;AAEzE,WAAS,uBAAuB;AAChC,WAAS,gBAAgB;AACzB,WAAS,YAAY;AACrB,WAAS,OAAO;AAEhB,WAAS,qBAAqB,CAAC,YAAoB;AACjD,UAAM,IAAI,iBAAiB,EAAE,SAAS,WAAW,qBAAqB,CAAC;AAAA,EACzE;AACA,WAAS,aAAa,CAAC,YAAoB;AACzC,UAAM,IAAI,iBAAiB,EAAE,SAAS,WAAW,aAAa,CAAC;AAAA,EACjE;AAEA,SAAO;AACT;AAEO,IAAM,MAAM,UAAU;","names":["z"]}
@@ -0,0 +1,159 @@
1
+ ---
2
+ title: Z.AI
3
+ description: Learn how to use Z.AI's GLM models with the AI SDK.
4
+ ---
5
+
6
+ # Z.AI Provider
7
+
8
+ The [Z.AI](https://z.ai/) provider gives you access to GLM language and vision models through the Z.AI API.
9
+
10
+ API keys can be created in the [Z.AI API key console](https://z.ai/manage-apikey/apikey-list).
11
+
12
+ ## Setup
13
+
14
+ The Z.AI provider is available through the `@ai-sdk/zai` package. Install it with:
15
+
16
+ <InstallPackages packages="@ai-sdk/zai" />
17
+
18
+ Set the `ZAI_API_KEY` environment variable:
19
+
20
+ ```bash
21
+ ZAI_API_KEY=your-api-key
22
+ ```
23
+
24
+ ## Provider Instance
25
+
26
+ Import the default provider instance `zai` from `@ai-sdk/zai`:
27
+
28
+ ```ts
29
+ import { zai } from '@ai-sdk/zai';
30
+ ```
31
+
32
+ For custom configuration, use `createZai`:
33
+
34
+ ```ts
35
+ import { createZai } from '@ai-sdk/zai';
36
+
37
+ const zai = createZai({
38
+ apiKey: process.env.ZAI_API_KEY,
39
+ baseURL: 'https://api.z.ai/api/paas/v4',
40
+ });
41
+ ```
42
+
43
+ The provider accepts these optional settings:
44
+
45
+ - **apiKey** _string_
46
+
47
+ API key sent in the `Authorization` header. It defaults to the `ZAI_API_KEY` environment variable.
48
+
49
+ - **baseURL** _string_
50
+
51
+ URL prefix for API requests. It defaults to `https://api.z.ai/api/paas/v4`.
52
+
53
+ - **headers** _Record&lt;string, string&gt;_
54
+
55
+ Additional request headers.
56
+
57
+ - **fetch** _FetchFunction_
58
+
59
+ Custom fetch implementation, for example to intercept requests in middleware.
60
+
61
+ ## Language Models
62
+
63
+ Create a language model by passing its model id to the provider:
64
+
65
+ ```ts
66
+ import { zai } from '@ai-sdk/zai';
67
+ import { generateText } from 'ai';
68
+
69
+ const { text } = await generateText({
70
+ model: zai('glm-5.3'),
71
+ prompt: 'Explain quantum entanglement in simple terms.',
72
+ });
73
+ ```
74
+
75
+ Current model families include GLM 5, GLM 4.7, GLM 4.6, GLM 4.5, and the GLM vision models. Model availability changes over time; see the [Z.AI model documentation](https://docs.z.ai/guides/llm) for the current catalog.
76
+
77
+ The provider supports:
78
+
79
+ - text generation and streaming
80
+ - reasoning output and reasoning history
81
+ - function calling, including incremental tool-call streaming
82
+ - JSON object output
83
+ - URL-based image and video inputs on compatible vision models
84
+
85
+ ## Provider Options
86
+
87
+ Z.AI-specific options can be passed through `providerOptions.zai`:
88
+
89
+ ```ts
90
+ import { zai } from '@ai-sdk/zai';
91
+ import { generateText } from 'ai';
92
+
93
+ const result = await generateText({
94
+ model: zai('glm-5.3'),
95
+ prompt: 'Compare two approaches to implementing a rate limiter.',
96
+ providerOptions: {
97
+ zai: {
98
+ thinking: { type: 'enabled', clearThinking: true },
99
+ reasoningEffort: 'high',
100
+ requestId: 'request-123456',
101
+ userId: 'user-123456',
102
+ },
103
+ },
104
+ });
105
+ ```
106
+
107
+ The following options are available:
108
+
109
+ - **doSample** _boolean_
110
+
111
+ Enables sampling. When disabled, `temperature` and `topP` do not take effect.
112
+
113
+ - **thinking** _object_
114
+
115
+ Controls thinking with `type: 'enabled' | 'disabled'`. Set `clearThinking` to `false` to retain reasoning from previous assistant messages.
116
+
117
+ - **reasoningEffort** _'none' | 'minimal' | 'low' | 'medium' | 'high' | 'xhigh' | 'max'_
118
+
119
+ Controls reasoning effort on supported models.
120
+
121
+ - **toolStream** _boolean_
122
+
123
+ Enables incremental function-call argument streaming on supported models.
124
+
125
+ - **requestId** _string_
126
+
127
+ A caller-provided request id between 6 and 64 characters.
128
+
129
+ - **userId** _string_
130
+
131
+ A non-sensitive end-user id between 6 and 128 characters.
132
+
133
+ ## Streaming Tool Calls
134
+
135
+ Enable `toolStream` when you want supported GLM models to stream function-call arguments incrementally:
136
+
137
+ ```ts
138
+ import { zai } from '@ai-sdk/zai';
139
+ import { streamText, tool } from 'ai';
140
+ import { z } from 'zod';
141
+
142
+ const result = streamText({
143
+ model: zai('glm-5.3'),
144
+ prompt: 'What is the weather in San Francisco?',
145
+ tools: {
146
+ weather: tool({
147
+ description: 'Get the weather for a city',
148
+ inputSchema: z.object({ city: z.string() }),
149
+ }),
150
+ },
151
+ providerOptions: {
152
+ zai: { toolStream: true },
153
+ },
154
+ });
155
+
156
+ for await (const part of result.fullStream) {
157
+ console.log(part);
158
+ }
159
+ ```
package/package.json CHANGED
@@ -1,23 +1,78 @@
1
1
  {
2
2
  "name": "@ai-sdk/zai",
3
- "version": "0.0.0",
4
- "description": "AI SDK provider for Z.ai",
3
+ "version": "1.0.1",
4
+ "type": "commonjs",
5
5
  "license": "Apache-2.0",
6
- "type": "module",
7
- "main": "./index.js",
8
- "exports": {
9
- ".": "./index.js"
10
- },
6
+ "sideEffects": false,
7
+ "main": "./dist/index.js",
8
+ "module": "./dist/index.mjs",
9
+ "types": "./dist/index.d.ts",
11
10
  "files": [
12
- "index.js",
11
+ "dist/**/*",
12
+ "docs/**/*",
13
+ "src",
14
+ "!src/**/*.test.ts",
15
+ "!src/**/*.test-d.ts",
16
+ "!src/**/__snapshots__",
17
+ "!src/**/__fixtures__",
18
+ "CHANGELOG.md",
13
19
  "README.md"
14
20
  ],
21
+ "directories": {
22
+ "doc": "./docs"
23
+ },
24
+ "exports": {
25
+ "./package.json": "./package.json",
26
+ ".": {
27
+ "types": "./dist/index.d.ts",
28
+ "import": "./dist/index.mjs",
29
+ "require": "./dist/index.js"
30
+ }
31
+ },
32
+ "dependencies": {
33
+ "@ai-sdk/openai-compatible": "1.0.52",
34
+ "@ai-sdk/provider": "2.0.3",
35
+ "@ai-sdk/provider-utils": "3.0.35"
36
+ },
37
+ "devDependencies": {
38
+ "@types/node": "20.17.24",
39
+ "tsup": "^8",
40
+ "typescript": "5.8.3",
41
+ "zod": "3.25.76",
42
+ "@vercel/ai-tsconfig": "0.0.0"
43
+ },
44
+ "peerDependencies": {
45
+ "zod": "^3.25.76 || ^4.1.8"
46
+ },
47
+ "engines": {
48
+ "node": ">=18"
49
+ },
15
50
  "publishConfig": {
16
- "access": "public"
51
+ "access": "public",
52
+ "provenance": true
17
53
  },
54
+ "homepage": "https://ai-sdk.dev/docs",
18
55
  "repository": {
19
56
  "type": "git",
20
- "url": "git+https://github.com/vercel/ai.git",
57
+ "url": "https://github.com/vercel/ai",
21
58
  "directory": "packages/zai"
59
+ },
60
+ "bugs": {
61
+ "url": "https://github.com/vercel/ai/issues"
62
+ },
63
+ "keywords": [
64
+ "ai"
65
+ ],
66
+ "description": "The Z.AI provider for the AI SDK contains language model support for Z.AI's GLM models.",
67
+ "scripts": {
68
+ "build": "pnpm clean && tsup --tsconfig tsconfig.build.json",
69
+ "build:watch": "pnpm clean && tsup --watch",
70
+ "clean": "del-cli dist docs *.tsbuildinfo",
71
+ "type-check": "tsc --build",
72
+ "test": "pnpm test:node && pnpm test:edge",
73
+ "test:update": "pnpm test:node -u",
74
+ "test:watch": "vitest --config vitest.node.config.js",
75
+ "test:edge": "vitest --config vitest.edge.config.js --run",
76
+ "test:node": "vitest --config vitest.node.config.js --run"
22
77
  }
23
- }
78
+ }
package/src/index.ts ADDED
@@ -0,0 +1,6 @@
1
+ export type { ZaiLanguageModelChatOptions } from './zai-chat-language-model-options';
2
+ export type { ZaiChatModelId } from './zai-chat-options';
3
+ export type { ZaiErrorData } from './zai-error';
4
+ export { createZai, zai } from './zai-provider';
5
+ export type { ZaiProvider, ZaiProviderSettings } from './zai-provider';
6
+ export { VERSION } from './version';
package/src/version.ts ADDED
@@ -0,0 +1,6 @@
1
+ // Version string of this package injected at build time.
2
+ declare const __PACKAGE_VERSION__: string | undefined;
3
+ export const VERSION: string =
4
+ typeof __PACKAGE_VERSION__ !== 'undefined'
5
+ ? __PACKAGE_VERSION__
6
+ : '0.0.0-test';
@@ -0,0 +1,45 @@
1
+ import { z } from 'zod/v4';
2
+
3
+ export const zaiLanguageModelChatOptions = z.object({
4
+ /**
5
+ * Enables or disables sampling. When disabled, temperature and topP do not
6
+ * take effect.
7
+ */
8
+ doSample: z.boolean().optional(),
9
+
10
+ /**
11
+ * Controls model thinking and whether reasoning from earlier turns is kept.
12
+ */
13
+ thinking: z
14
+ .object({
15
+ type: z.enum(['enabled', 'disabled']).optional(),
16
+ clearThinking: z.boolean().optional(),
17
+ })
18
+ .optional(),
19
+
20
+ /**
21
+ * Controls reasoning effort for GLM-5.2 and later models.
22
+ */
23
+ reasoningEffort: z
24
+ .enum(['none', 'minimal', 'low', 'medium', 'high', 'xhigh', 'max'])
25
+ .optional(),
26
+
27
+ /**
28
+ * Enables incremental function-call argument streaming on supported models.
29
+ */
30
+ toolStream: z.boolean().optional(),
31
+
32
+ /**
33
+ * A caller-provided request identifier between 6 and 64 characters.
34
+ */
35
+ requestId: z.string().min(6).max(64).optional(),
36
+
37
+ /**
38
+ * A non-sensitive end-user identifier between 6 and 128 characters.
39
+ */
40
+ userId: z.string().min(6).max(128).optional(),
41
+ });
42
+
43
+ export type ZaiLanguageModelChatOptions = z.infer<
44
+ typeof zaiLanguageModelChatOptions
45
+ >;