@shenghuabi/openai 1.1.47 → 1.2.2

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/index.js CHANGED
@@ -30,37 +30,51 @@ var __toCommonJS = (mod) => __copyProps(__defProp({}, "__esModule", { value: tru
30
30
  // packages/openai/index.ts
31
31
  var openai_exports = {};
32
32
  __export(openai_exports, {
33
+ AnthropicMessagesCompatSchema: () => AnthropicMessagesCompatSchema,
33
34
  AssistantChatCompletionContent: () => AssistantChatCompletionContent,
34
35
  AssistantChatMessage: () => AssistantChatMessage,
35
36
  ChatCompletionContentPart: () => ChatCompletionContentPart,
36
37
  ChatCompletionContentPartImage: () => ChatCompletionContentPartImage,
37
38
  ChatCompletionContentPartStr: () => ChatCompletionContentPartStr,
38
- ChatHistoryService: () => ChatHistoryService,
39
- ChatItemDefine: () => ChatItemDefine,
39
+ ChatMessageCommonItemDefine: () => ChatMessageCommonItemDefine,
40
40
  ChatMessageItemDefine: () => ChatMessageItemDefine,
41
41
  ChatMessageListDefine: () => ChatMessageListDefine,
42
- ChatParamsItemDefine: () => ChatParamsItemDefine,
43
- ChatParamsListDefine: () => ChatParamsListDefine,
44
- ChatProviderService: () => ChatProviderService,
45
- InputChatOptionsDefine: () => InputChatOptionsDefine,
42
+ CompatSchema: () => CompatSchema,
43
+ InputChoiceSchema: () => InputChoiceSchema,
44
+ InputSchema: () => InputSchema,
45
+ ModelConfigDefine: () => ModelConfigDefine,
46
+ ModelSchema: () => ModelSchema,
47
+ ModelThinkingLevelSchema: () => ModelThinkingLevelSchema,
46
48
  OPENAI_MODULE: () => OPENAI_MODULE,
49
+ OpenAICompletionsCompatSchema: () => OpenAICompletionsCompatSchema,
47
50
  OpenAIConfigToken: () => OpenAIConfigToken,
51
+ OpenAIResponsesCompatSchema: () => OpenAIResponsesCompatSchema,
52
+ OutputSchema: () => OutputSchema,
48
53
  SystemChatCompletionContent: () => SystemChatCompletionContent,
49
54
  SystemChatMessage: () => SystemChatMessage,
55
+ ThinkingLevelSchema: () => ThinkingLevelSchema,
50
56
  UserChatCompletionContent: () => UserChatCompletionContent,
51
57
  UserChatMessage: () => UserChatMessage,
52
- VendorOptionsDefine: () => VendorOptionsDefine,
58
+ complete: () => import_pi_ai4.complete,
53
59
  createAssistantMessage: () => createAssistantMessage,
60
+ createChatStream: () => createChatStream,
61
+ createDynamicResponse: () => createDynamicResponse,
54
62
  createSystemMessage: () => createSystemMessage,
55
- createUserMessage: () => createUserMessage
63
+ createUserMessage: () => createUserMessage,
64
+ fauxAssistantMessage: () => import_pi_ai4.fauxAssistantMessage,
65
+ fauxText: () => import_pi_ai4.fauxText,
66
+ fauxThinking: () => import_pi_ai4.fauxThinking,
67
+ getModelConfig: () => getModelConfig,
68
+ registerMockProvider: () => registerMockProvider,
69
+ stream: () => import_pi_ai4.stream
56
70
  });
57
71
  module.exports = __toCommonJS(openai_exports);
58
72
 
59
- // packages/openai/chat/service.ts
60
- var import_static_injector3 = require("static-injector");
61
-
62
- // packages/openai/chat/vendor/openai.ts
63
- var import_openai = require("openai");
73
+ // packages/openai/chat/token.ts
74
+ var import_static_injector = require("static-injector");
75
+ var OpenAIConfigToken = new import_static_injector.InjectionToken(
76
+ "OpenAIConfig"
77
+ );
64
78
 
65
79
  // packages/openai/chat/message.define.ts
66
80
  var v = __toESM(require("valibot"), 1);
@@ -70,8 +84,7 @@ var ChatCompletionContentPartStr = v.object({
70
84
  });
71
85
  var ChatCompletionContentPartImage = v.object({
72
86
  image_url: v.object({
73
- url: v.string(),
74
- detail: v.optional(v.picklist(["auto", "low", "high"]))
87
+ url: v.string()
75
88
  }),
76
89
  type: v.optional(v.literal("image_url"), "image_url")
77
90
  });
@@ -103,390 +116,11 @@ var ChatMessageItemDefine = v.union([
103
116
  UserChatMessage,
104
117
  AssistantChatMessage
105
118
  ]);
106
- var ChatMessageListDefine = v.array(ChatMessageItemDefine);
107
-
108
- // packages/openai/chat/vendor/openai.ts
109
- var v2 = __toESM(require("valibot"), 1);
110
- var OpenAIChat = class {
111
- constructor(options) {
112
- this.options = options;
113
- }
114
- options;
115
- instance;
116
- extraBody = {};
117
- extraHeaders = {};
118
- init() {
119
- this.instance = new import_openai.OpenAI({
120
- apiKey: this.options.apiKey || " ",
121
- baseURL: this.options.baseURL ?? void 0
122
- });
123
- }
124
- async #createStream(input, options) {
125
- return await this.instance.chat.completions.create(input, { headers: this.extraHeaders, ...options }).catch(async (error) => {
126
- if (options?.tryPull?.(error)) {
127
- await options?.pullModel(this.options.model);
128
- return this.#createStream(input, {
129
- ...options,
130
- tryPull: () => false
131
- });
132
- }
133
- throw error;
134
- });
135
- }
136
- async *stream(input, options) {
137
- const input2 = {
138
- ...input,
139
- messages: input.messages,
140
- model: this.options.model,
141
- stream: true,
142
- max_tokens: this.options.max_tokens,
143
- top_p: this.options.top_p,
144
- temperature: this.options.temperature,
145
- frequency_penalty: this.options.frequency_penalty,
146
- presence_penalty: this.options.presence_penalty,
147
- seed: this.options.seed,
148
- stop: this.options.stop,
149
- ...this.extraBody
150
- };
151
- const result = await this.#createStream(input2, options);
152
- let isThinking = 0;
153
- for await (const item of result) {
154
- try {
155
- if (!item.choices[0].finish_reason) {
156
- if (typeof item.choices[0].delta.reasoning_content === "string" || typeof item.choices[0].delta.reasoning === "string") {
157
- if (isThinking === 0) {
158
- isThinking = 1;
159
- yield "<thinking>";
160
- }
161
- const result2 = item.choices[0].delta.reasoning_content ?? item.choices[0].delta.reasoning;
162
- if (result2) {
163
- yield result2;
164
- }
165
- } else if (typeof item.choices[0].delta.content === "string") {
166
- if (isThinking === 1) {
167
- yield "</thinking>";
168
- isThinking = 2;
169
- }
170
- const result2 = item.choices[0].delta.content;
171
- if (result2) {
172
- yield result2;
173
- }
174
- }
175
- }
176
- } catch (error) {
177
- throw error;
178
- }
179
- }
180
- }
181
- // 工具调用,暂时不清楚怎么调用...是返回工具,还是返回对话
182
- async callTool(input, options) {
183
- const result = await this.instance.chat.completions.create(
184
- {
185
- ...input,
186
- messages: v2.parse(ChatMessageListDefine, input.messages),
187
- model: this.options.model,
188
- max_tokens: this.options.max_tokens,
189
- top_p: this.options.top_p,
190
- temperature: this.options.temperature,
191
- frequency_penalty: this.options.frequency_penalty,
192
- presence_penalty: this.options.presence_penalty,
193
- seed: this.options.seed,
194
- stop: this.options.stop,
195
- ...this.extraBody,
196
- stream: false
197
- },
198
- { headers: this.extraHeaders, ...options }
199
- );
200
- const isTool = !!result.choices[0].message.tool_calls;
201
- if (isTool) {
202
- const data = result.choices[0].message.tool_calls[0].function;
203
- return {
204
- type: "function",
205
- function: {
206
- name: data.name,
207
- arguments: JSON.parse(data.arguments)
208
- }
209
- };
210
- }
211
- return { type: "text", text: result.choices[0].message.content };
212
- }
213
- };
214
-
215
- // packages/openai/chat/vendor/openai-compatible.factory.ts
216
- var VendorObject = {
217
- "360": { options: { baseURL: "https://ai.360.cn", modelList: [] } },
218
- azure: { options: { baseURL: "", modelList: [] } },
219
- moonshot: { options: { baseURL: "https://api.moonshot.cn", modelList: [] } },
220
- baichuan: {
221
- options: { baseURL: "https://api.baichuan-ai.com", modelList: [] }
222
- },
223
- minimax: { options: { baseURL: "https://api.minimax.chat", modelList: [] } },
224
- mistralai: { options: { baseURL: "https://api.mistral.ai", modelList: [] } },
225
- groq: {
226
- options: { baseURL: "https://api.groq.com/openai", modelList: [] }
227
- },
228
- lingyiwanwu: {
229
- options: { baseURL: "https://api.lingyiwanwu.com", modelList: [] }
230
- },
231
- stepfun: { options: { baseURL: "https://api.stepfun.com", modelList: [] } },
232
- deepseek: { options: { baseURL: "https://api.deepseek.com", modelList: [] } },
233
- "together.ai": {
234
- options: { baseURL: "https://api.together.xyz", modelList: [] }
235
- },
236
- volcengine: {
237
- options: {
238
- baseURL: "https://ark.cn-beijing.volces.com/api/v3",
239
- modelList: []
240
- }
241
- },
242
- novita: {
243
- options: { baseURL: "https://api.novita.ai/v3/openai", modelList: [] }
244
- },
245
- siliconflow: {
246
- options: { baseURL: "https://api.siliconflow.cn", modelList: [] }
247
- },
248
- // 官网明确兼容
249
- // https://help.aliyun.com/zh/model-studio/developer-reference/use-qwen-by-calling-api?spm=a2c6h.13066369.question.5.3a0e527bbxeJLJ#4ec3e641c294d
250
- tongyi: {
251
- options: {
252
- baseURL: "https://dashscope.aliyuncs.com/compatible-mode/v1",
253
- modelList: []
254
- }
255
- },
256
- // 文档上看是一样的
257
- // https://open.bigmodel.cn/dev/api/normal-model/glm-4
258
- zhipu: {
259
- options: {
260
- baseURL: "https://open.bigmodel.cn/api/paas/v4",
261
- modelList: []
262
- }
263
- },
264
- // 明确兼容
265
- // https://www.xfyun.cn/doc/spark/HTTP%E8%B0%83%E7%94%A8%E6%96%87%E6%A1%A3.html#_7-%E4%BD%BF%E7%94%A8openai-sdk%E8%AF%B7%E6%B1%82%E7%A4%BA%E4%BE%8B
266
- spark: {
267
- options: {
268
- baseURL: "https://spark-api-open.xf-yun.com/v1",
269
- modelList: []
270
- }
271
- },
272
- // 官方兼容
273
- // https://cloud.tencent.com/document/product/1729/111007
274
- hunyuan: {
275
- options: {
276
- baseURL: "https://api.hunyuan.cloud.tencent.com/v1",
277
- modelList: []
278
- }
279
- }
280
- };
281
- function createCompatibleFactory(options) {
282
- const vendorConfig = VendorObject[options.vendor];
283
- return new OpenAIChat({
284
- ...options,
285
- baseURL: vendorConfig.options.baseURL
286
- });
287
- }
288
-
289
- // packages/openai/chat/vendor/genmini/genmini.ts
290
- var import_generative_ai = require("@google/generative-ai");
291
-
292
- // packages/openai/chat/vendor/genmini/message.define.ts
293
- var v3 = __toESM(require("valibot"), 1);
294
- var import_util = require("@cyia/util");
295
- function messageContentTransform(list) {
296
- return list.map((item) => item.type === "text" ? { text: item.text } : void 0).filter(import_util.isTruthy);
297
- }
298
- var GenminiSystemMessageDefine = v3.pipe(
299
- SystemChatMessage,
300
- v3.transform((item) => ({
301
- role: "system",
302
- parts: messageContentTransform(item.content)
303
- }))
304
- );
305
- var GenminiChatMessageListDefine = v3.pipe(
306
- v3.array(
307
- v3.union([
308
- v3.pipe(
309
- UserChatMessage,
310
- v3.transform((item) => ({
311
- role: "user",
312
- parts: messageContentTransform(item.content)
313
- }))
314
- ),
315
- v3.pipe(
316
- AssistantChatMessage,
317
- v3.transform((item) => ({
318
- role: "model",
319
- parts: messageContentTransform(item.content)
320
- }))
321
- )
322
- ])
323
- )
324
- );
325
-
326
- // packages/openai/chat/vendor/genmini/genmini.ts
327
- var v4 = __toESM(require("valibot"), 1);
328
- var GeminiChat = class extends OpenAIChat {
329
- #ggai;
330
- init() {
331
- this.#ggai = new import_generative_ai.GoogleGenerativeAI(this.options.apiKey);
332
- }
333
- async *stream(input, options) {
334
- const model = this.#ggai.getGenerativeModel({
335
- model: this.options.model,
336
- generationConfig: {
337
- topP: this.options.top_p,
338
- temperature: this.options.temperature,
339
- maxOutputTokens: this.options.max_tokens
340
- }
341
- });
342
- const messages = input.messages;
343
- const data = {};
344
- if (messages[0].role === "system") {
345
- const system = messages.shift();
346
- data.systemInstruction = v4.parse(GenminiSystemMessageDefine, system);
347
- }
348
- data.history = v4.parse(GenminiChatMessageListDefine, messages);
349
- const lastMessage = data.history.pop();
350
- const chat = model.startChat(data);
351
- const result = await chat.sendMessageStream(lastMessage.parts, {
352
- signal: options?.signal
353
- });
354
- for await (const chunk of result.stream) {
355
- const chunkText = chunk.text();
356
- yield chunkText;
357
- }
358
- }
359
- };
360
-
361
- // packages/openai/chat/vendor/anthropic/anthropic.ts
362
- var import_sdk = __toESM(require("@anthropic-ai/sdk"), 1);
363
-
364
- // packages/openai/chat/vendor/anthropic/message.define.ts
365
- var import_util2 = require("@cyia/util");
366
- var v5 = __toESM(require("valibot"), 1);
367
- function baseImageSplit(str) {
368
- const mimeTypeIndex = str.indexOf(";");
369
- const dataStartIndex = str.indexOf(",", mimeTypeIndex);
370
- return {
371
- mimeType: str.slice(5, mimeTypeIndex),
372
- data: str.slice(dataStartIndex + 1)
373
- };
374
- }
375
- var AnthropicSystemMessageDefine = v5.pipe(
376
- SystemChatCompletionContent,
377
- v5.transform(
378
- (list) => list.map((item) => item.type === "text" ? item : void 0).filter(import_util2.isTruthy)
379
- )
380
- );
381
- function contentConvert(part) {
382
- if (part.type === "text") {
383
- return part;
384
- }
385
- const result = baseImageSplit(part.image_url.url);
386
- return {
387
- type: "image",
388
- source: {
389
- type: "base64",
390
- media_type: result.mimeType,
391
- data: result.data
392
- }
393
- };
394
- }
395
- var UserMessageDefine = v5.pipe(
119
+ var ChatMessageCommonItemDefine = v.union([
396
120
  UserChatMessage,
397
- v5.transform((item) => ({
398
- ...item,
399
- content: item.content.map(contentConvert)
400
- }))
401
- );
402
- var AssistantMessageDefine = v5.pipe(
403
- AssistantChatMessage,
404
- v5.transform((item) => ({
405
- ...item,
406
- content: item.content.map(contentConvert)
407
- }))
408
- );
409
- var AnthropicChatMessageListDefine = v5.array(
410
- v5.union([UserMessageDefine, AssistantMessageDefine])
411
- );
412
-
413
- // packages/openai/chat/vendor/anthropic/anthropic.ts
414
- var import_util3 = require("@cyia/util");
415
- var v6 = __toESM(require("valibot"), 1);
416
- var AnthropicChat = class extends OpenAIChat {
417
- client;
418
- init() {
419
- this.client = new import_sdk.default({ apiKey: this.options.apiKey });
420
- }
421
- async *stream(input, options) {
422
- const body = {
423
- model: this.options.model,
424
- max_tokens: this.options.max_tokens,
425
- top_p: this.options.top_p,
426
- temperature: this.options.temperature,
427
- stream: true
428
- };
429
- if (input.messages[0].role === "system") {
430
- const system = input.messages.shift().content;
431
- body.system = v6.parse(AnthropicSystemMessageDefine, system);
432
- }
433
- body.messages = v6.parse(AnthropicChatMessageListDefine, input.messages);
434
- const result = this.client.messages.stream(body, {
435
- signal: options?.signal
436
- });
437
- const aga = (0, import_util3.createAsyncGeneratorAdapter)();
438
- result.once("end", () => aga.complete());
439
- result.on("text", (text) => {
440
- aga.next(text);
441
- });
442
- for await (const item of aga.getData()) {
443
- yield item;
444
- }
445
- }
446
- async callTool(input, options) {
447
- const body = {};
448
- if (input.messages[0].role === "system") {
449
- const system = input.messages.shift().content;
450
- body.system = v6.parse(AnthropicSystemMessageDefine, system);
451
- }
452
- body.messages = v6.parse(AnthropicChatMessageListDefine, input.messages);
453
- const result = await this.client.messages.create(
454
- {
455
- ...body,
456
- model: this.options.model,
457
- max_tokens: this.options.max_tokens,
458
- top_p: this.options.top_p,
459
- temperature: this.options.temperature,
460
- stream: false,
461
- tools: input.tools.map((item) => ({
462
- name: item.function.name,
463
- description: item.function.description,
464
- input_schema: item.function.parameters
465
- }))
466
- },
467
- {
468
- signal: options?.signal
469
- }
470
- );
471
- const isToolResult = result.content.find(
472
- (item) => item.type === "tool_use"
473
- );
474
- if (isToolResult) {
475
- return {
476
- type: "function",
477
- function: {
478
- name: isToolResult.name,
479
- arguments: isToolResult.input
480
- }
481
- };
482
- }
483
- const text = result.content.find((item) => item.type === "text");
484
- return {
485
- type: "text",
486
- text: text.text
487
- };
488
- }
489
- };
121
+ AssistantChatMessage
122
+ ]);
123
+ var ChatMessageListDefine = v.array(ChatMessageItemDefine);
490
124
 
491
125
  // packages/openai/chat/util/create.ts
492
126
  function createSystemMessage() {
@@ -505,557 +139,666 @@ function createAssistantMessage(text = "") {
505
139
  };
506
140
  }
507
141
 
508
- // packages/openai/chat/const.ts
509
- var ThinkList = [
510
- "think",
511
- "thinking",
512
- "reason",
513
- "reasoning",
514
- "thought",
515
- "Thought"
516
- ];
142
+ // packages/openai/chat/module.ts
143
+ var OPENAI_MODULE = {
144
+ provider: [],
145
+ token: { OpenAIConfigToken }
146
+ };
147
+
148
+ // packages/openai/chat/chat.ts
149
+ var import_pi_ai2 = require("@earendil-works/pi-ai");
150
+
151
+ // packages/openai/chat/util/get-custom-provider.ts
152
+ var v3 = __toESM(require("valibot"), 1);
153
+ var import_pi_ai = require("@earendil-works/pi-ai");
154
+
155
+ // packages/openai/chat/provider.define.ts
156
+ var v2 = __toESM(require("valibot"), 1);
157
+ var KnownProviderDefine = v2.pipe(
158
+ v2.picklist([
159
+ "amazon-bedrock",
160
+ "anthropic",
161
+ "google",
162
+ "google-vertex",
163
+ "openai",
164
+ "azure-openai-responses",
165
+ "openai-codex",
166
+ "deepseek",
167
+ "github-copilot",
168
+ "xai",
169
+ "groq",
170
+ "cerebras",
171
+ "openrouter",
172
+ "vercel-ai-gateway",
173
+ "zai",
174
+ "mistral",
175
+ "minimax",
176
+ "minimax-cn",
177
+ "moonshotai",
178
+ "moonshotai-cn",
179
+ "huggingface",
180
+ "fireworks",
181
+ "together",
182
+ "opencode",
183
+ "opencode-go",
184
+ "kimi-coding",
185
+ "cloudflare-workers-ai",
186
+ "cloudflare-ai-gateway",
187
+ "xiaomi",
188
+ "xiaomi-token-plan-cn",
189
+ "xiaomi-token-plan-ams",
190
+ "xiaomi-token-plan-sgp",
191
+ "ant-ling",
192
+ "nvidia",
193
+ "zai-coding-cn",
194
+ /** 自定义 */
195
+ "openai-completions",
196
+ "openai-responses",
197
+ "anthropic-messages"
198
+ ]),
199
+ v2.title("提供商"),
200
+ v2.description(`'openai-completions','openai-responses','anthropic-messages',为自定义提供商`)
201
+ );
517
202
 
518
- // packages/openai/chat/options.define.ts
203
+ // packages/openai/chat/util/get-custom-provider.ts
519
204
  var import_view_angular_core = require("@piying/view-angular-core");
520
- var v7 = __toESM(require("valibot"), 1);
521
- var import_valibot_visit = require("@piying/valibot-visit");
522
- var VendorList = [
523
- {
524
- value: "openai",
525
- label: "openai",
526
- options: {
527
- baseURL: "",
528
- modelList: [],
529
- description: "如果是openai兼容的厂商,需要设置baseURL"
530
- }
531
- },
532
- {
533
- value: "360",
534
- label: "360",
535
- options: { baseURL: "https://ai.360.cn", modelList: [] }
536
- },
537
- {
538
- value: "azure",
539
- label: "azure",
540
- options: { baseURL: "", modelList: [] }
541
- },
542
- {
543
- value: "moonshot",
544
- label: "moonshot",
545
- options: { baseURL: "https://api.moonshot.cn", modelList: [] }
546
- },
547
- {
548
- value: "baichuan",
549
- label: "baichuan",
550
- options: { baseURL: "https://api.baichuan-ai.com", modelList: [] }
551
- },
552
- {
553
- value: "minimax",
554
- label: "minimax",
555
- options: { baseURL: "https://api.minimax.chat", modelList: [] }
556
- },
557
- {
558
- value: "mistralai",
559
- label: "mistralai",
560
- options: { baseURL: "https://api.mistral.ai", modelList: [] }
561
- },
562
- {
563
- value: "groq",
564
- label: "groq",
565
- options: { baseURL: "https://api.groq.com/openai", modelList: [] }
566
- },
567
- {
568
- value: "lingyiwanwu",
569
- label: "lingyiwanwu",
570
- options: { baseURL: "https://api.lingyiwanwu.com", modelList: [] }
571
- },
572
- {
573
- value: "stepfun",
574
- label: "stepfun",
575
- options: { baseURL: "https://api.stepfun.com", modelList: [] }
576
- },
577
- {
578
- value: "deepseek",
579
- label: "deepseek",
580
- options: { baseURL: "https://api.deepseek.com", modelList: [] }
581
- },
582
- {
583
- value: "together.ai",
584
- label: "together.ai",
585
- options: { baseURL: "https://api.together.xyz", modelList: [] }
586
- },
587
- {
588
- value: "volcengine",
589
- label: "volcengine",
590
- options: {
591
- baseURL: "https://ark.cn-beijing.volces.com/api/v3",
592
- modelList: []
593
- }
594
- },
595
- {
596
- value: "novita",
597
- label: "novita",
598
- options: { baseURL: "https://api.novita.ai/v3/openai", modelList: [] }
599
- },
600
- {
601
- value: "siliconflow",
602
- label: "siliconflow",
603
- options: { baseURL: "https://api.siliconflow.cn", modelList: [] }
604
- },
605
- {
606
- value: "tongyi",
607
- label: "tongyi",
608
- options: {
609
- baseURL: "https://dashscope.aliyuncs.com/compatible-mode/v1",
610
- modelList: []
611
- }
612
- },
613
- {
614
- value: "zhipu",
615
- label: "zhipu",
616
- options: {
617
- baseURL: "https://open.bigmodel.cn/api/paas/v4",
618
- modelList: []
619
- }
620
- },
621
- {
622
- value: "spark",
623
- label: "spark",
624
- options: {
625
- baseURL: "https://spark-api-open.xf-yun.com/v1",
626
- modelList: []
627
- }
628
- },
629
- {
630
- value: "hunyuan",
631
- label: "hunyuan",
632
- options: {
633
- baseURL: "https://api.hunyuan.cloud.tencent.com/v1",
634
- modelList: []
635
- }
636
- },
637
- {
638
- value: "gemini",
639
- label: "gemini",
640
- options: {
641
- baseURL: "",
642
- modelList: [],
643
- description: "非openai兼容,手动适配,如果有问题欢迎报告"
644
- }
645
- },
646
- {
647
- value: "claude",
648
- label: "claude",
649
- options: {
650
- baseURL: "",
651
- modelList: [],
652
- description: "非openai兼容,手动适配,如果有问题欢迎报告"
653
- }
205
+ var import_rxjs = require("rxjs");
206
+ function getCustomProvider(compat, model, name, input) {
207
+ return { ...input, id: model, api: compat, name };
208
+ }
209
+ function getModelConfig(input) {
210
+ if (input.provider === "faux") {
211
+ return {
212
+ model: input.config,
213
+ config: input
214
+ };
654
215
  }
655
- ];
656
- var vendorOptionsDescribe = `## 通用参数
657
- - \`extraOptions\`字段用于覆盖默认字段
658
- \`\`\`json
659
- {"厂商名(与vendor字段相同)":{ "extraOptions":{"temperature":0.1,"topP":0.8,"maxTokens":8192,"baseURL":"http://127.0.0.1:11434/v1","apiKey":" "} }
660
- \`\`\`
661
- `;
662
- var InputWrapper = (0, import_valibot_visit.metadataPipe)(import_view_angular_core.actions.wrappers.set(["tooltip", "label"]));
663
- var ChatItemDefine = v7.pipe(
664
- v7.intersect([
665
- v7.pipe(
666
- v7.object({
667
- name: v7.pipe(v7.string(), v7.title("配置名")),
668
- vendor: v7.pipe(
669
- v7.optional(
670
- v7.picklist(VendorList.map((item) => item.value)),
671
- "openai"
672
- ),
673
- v7.description("大语言模型提供的厂商"),
674
- v7.title("对话厂商"),
675
- v7.metadata({
676
- enumOptions: VendorList.map((item) => ({
677
- label: item.label,
678
- description: [
679
- item.options.description ? item.options.description : "",
680
- item.options.baseURL ? `链接: ${item.options.baseURL}` : ""
681
- ].filter(Boolean).join("\n")
682
- }))
683
- }),
684
- import_view_angular_core.actions.inputs.patch({
685
- options: VendorList
686
- })
216
+ const config = v3.parse(ModelConfigDefine, input);
217
+ if (config.provider === "openai-completions" || config.provider === "openai-responses" || config.provider === "anthropic-messages") {
218
+ return {
219
+ model: getCustomProvider(
220
+ config.provider,
221
+ config.model,
222
+ config.name,
223
+ config.config
224
+ ),
225
+ config
226
+ };
227
+ }
228
+ return {
229
+ model: (0, import_pi_ai.getModel)(config.provider, config.model),
230
+ config
231
+ };
232
+ }
233
+ var ThinkingLevelSchema = v3.pipe(
234
+ v3.picklist(["minimal", "low", "medium", "high", "xhigh"]),
235
+ v3.title("思考等级"),
236
+ v3.description("模型思考的详细程度,从最小到最大")
237
+ );
238
+ var ModelThinkingLevelSchema = v3.pipe(
239
+ v3.picklist(["off", "minimal", "low", "medium", "high", "xhigh"]),
240
+ v3.title("模型思考等级"),
241
+ v3.description("关闭或设置模型思考的详细程度")
242
+ );
243
+ var OpenAICompletionsCompatSchema = v3.pipe(
244
+ v3.optional(
245
+ v3.object({
246
+ supportsStore: v3.optional(
247
+ v3.pipe(
248
+ v3.boolean(),
249
+ v3.title("支持存储"),
250
+ v3.description("是否支持服务端会话存储")
687
251
  )
688
- }),
689
- import_view_angular_core.actions.wrappers.patch(["div"]),
690
- import_view_angular_core.actions.class.top("flex *:flex-1 gap-2 items-center")
691
- ),
692
- v7.pipe(
693
- v7.object({
694
- baseURL: v7.pipe(
695
- v7.optional(v7.string(), "http://127.0.0.1:11434/v1"),
696
- v7.title("地址"),
697
- v7.description("openai兼容接口"),
698
- ...InputWrapper
699
- ),
700
- model: v7.pipe(
701
- v7.optional(v7.string(), `qwen3:8b`),
702
- v7.title("模型"),
703
- v7.description(
704
- "## 模型名\n### ollama模型推荐\n- `qwen3:8b`\n- `qwen3:14b`,`deepseek-r1:7b`,`deepseek-r1:14b`\n### 图片对话模型\n- `minicpm-v:8b`"
705
- ),
706
- ...InputWrapper
252
+ ),
253
+ supportsDeveloperRole: v3.optional(
254
+ v3.pipe(
255
+ v3.boolean(),
256
+ v3.title("支持开发者角色"),
257
+ v3.description("是否支持 developer 系统消息角色")
258
+ )
259
+ ),
260
+ supportsReasoningEffort: v3.optional(
261
+ v3.pipe(
262
+ v3.boolean(),
263
+ v3.title("支持推理努力"),
264
+ v3.description("是否支持 reasoning_effort 参数")
265
+ )
266
+ ),
267
+ supportsUsageInStreaming: v3.optional(
268
+ v3.pipe(
269
+ v3.boolean(),
270
+ v3.title("流式用量"),
271
+ v3.description("流式输出中是否返回 usage 信息")
272
+ )
273
+ ),
274
+ maxTokensField: v3.optional(
275
+ v3.pipe(
276
+ v3.picklist(["max_completion_tokens", "max_tokens"]),
277
+ v3.title("最大 token 字段名"),
278
+ v3.description("指定最大 token 参数使用的是哪个字段名")
279
+ )
280
+ ),
281
+ requiresToolResultName: v3.optional(
282
+ v3.pipe(
283
+ v3.boolean(),
284
+ v3.title("需要工具结果名称"),
285
+ v3.description("是否要求工具结果消息包含 name 字段")
286
+ )
287
+ ),
288
+ requiresAssistantAfterToolResult: v3.optional(
289
+ v3.pipe(
290
+ v3.boolean(),
291
+ v3.title("需要助手回复"),
292
+ v3.description("工具结果后是否需要助手消息跟进")
293
+ )
294
+ ),
295
+ requiresThinkingAsText: v3.optional(
296
+ v3.pipe(
297
+ v3.boolean(),
298
+ v3.title("思考转文本"),
299
+ v3.description("是否将思考过程作为普通文本发送")
300
+ )
301
+ ),
302
+ requiresReasoningContentOnAssistantMessages: v3.optional(
303
+ v3.pipe(
304
+ v3.boolean(),
305
+ v3.title("推理内容在助手消息中"),
306
+ v3.description("是否在助手消息中包含推理内容")
307
+ )
308
+ ),
309
+ thinkingFormat: v3.optional(
310
+ v3.pipe(
311
+ v3.picklist([
312
+ "openai",
313
+ "openrouter",
314
+ "deepseek",
315
+ "together",
316
+ "zai",
317
+ "qwen",
318
+ "qwen-chat-template",
319
+ "string-thinking",
320
+ "ant-ling"
321
+ ]),
322
+ v3.title("思考格式"),
323
+ v3.description("指定 thinking 标签的序列化格式")
324
+ )
325
+ ),
326
+ openRouterRouting: v3.optional(
327
+ v3.pipe(
328
+ v3.unknown(),
329
+ v3.title("OpenRouter 路由"),
330
+ v3.description("自定义 OpenRouter 的路由配置")
331
+ )
332
+ ),
333
+ vercelGatewayRouting: v3.optional(
334
+ v3.pipe(
335
+ v3.unknown(),
336
+ v3.title("Vercel Gateway 路由"),
337
+ v3.description("自定义 Vercel AI Gateway 的路由配置")
338
+ )
339
+ ),
340
+ zaiToolStream: v3.optional(
341
+ v3.pipe(
342
+ v3.boolean(),
343
+ v3.title("ZAI 工具流式"),
344
+ v3.description("是否启用 ZAI 平台工具调用的流式输出")
345
+ )
346
+ ),
347
+ supportsStrictMode: v3.optional(
348
+ v3.pipe(
349
+ v3.boolean(),
350
+ v3.title("严格模式"),
351
+ v3.description("是否支持工具的 JSON Schema 严格校验")
352
+ )
353
+ ),
354
+ cacheControlFormat: v3.optional(
355
+ v3.pipe(
356
+ v3.literal("anthropic"),
357
+ v3.title("缓存控制格式"),
358
+ v3.description("指定缓存控制的语法格式")
359
+ )
360
+ ),
361
+ sendSessionAffinityHeaders: v3.optional(
362
+ v3.pipe(
363
+ v3.boolean(),
364
+ v3.title("发送会话亲和标头"),
365
+ v3.description("是否在请求中携带会话亲和性标头")
366
+ )
367
+ ),
368
+ supportsLongCacheRetention: v3.optional(
369
+ v3.pipe(
370
+ v3.boolean(),
371
+ v3.title("长期缓存保留"),
372
+ v3.description("是否支持长期缓存保留策略")
707
373
  )
708
- }),
709
- import_view_angular_core.actions.wrappers.patch([
710
- {
711
- type: "div",
712
- attributes: { class: "flex *:flex-1 gap-2 items-center" }
713
- }
714
- ])
715
- ),
716
- v7.object({
717
- apiKey: v7.pipe(
718
- v7.optional(v7.string()),
719
- v7.description("本地部署默认可以不填"),
720
- v7.title("apiKey")
721
374
  )
722
- }),
723
- v7.pipe(
724
- v7.object({
725
- max_tokens: v7.pipe(v7.optional(v7.number(), 8192), v7.title("max_tokens")),
726
- top_p: v7.pipe(
727
- v7.optional(v7.number(), 0.8),
728
- v7.minValue(0),
729
- v7.maxValue(10),
730
- v7.description(`核采样(nucleus sampling)是温度采样的另一种替代方法,模型会考虑累积概率质量达到 top_p 的 token。例如,当 top_p 设为 0.1 时,仅考虑累积概率前 10% 的 token。
731
-
732
- 我们通常建议调整 top_p 或温度参数,但不要同时调整两者。`),
733
- ...InputWrapper,
734
- v7.title("top_p")
735
- ),
736
- temperature: v7.pipe(
737
- v7.optional(v7.pipe(v7.number(), v7.minValue(0), v7.maxValue(2)), 0.1),
738
- v7.description(
739
- "采样温度应设置在0到2之间。较高的值(如0.8)会使输出更随机,而较低的值(如0.2)则会使输出更集中且确定。我们通常建议仅调整此参数或top_p,而不同时调整两者。"
740
- ),
741
- ...InputWrapper,
742
- v7.title("temperature")
743
- ),
744
- frequency_penalty: v7.pipe(
745
- v7.optional(v7.pipe(v7.number(), v7.minValue(-2), v7.maxValue(2))),
746
- v7.description(
747
- "取值范围为-2.0至2.0。正值会根据当前文本中已有标记的频率对新标记进行惩罚,从而降低模型逐字重复相同内容的概率。"
748
- ),
749
- ...InputWrapper,
750
- v7.title("frequency_penalty")
751
- ),
752
- presence_penalty: v7.pipe(
753
- v7.optional(v7.pipe(v7.number(), v7.minValue(-2), v7.maxValue(2))),
754
- v7.description(
755
- "数值介于-2.0至2.0之间。正值会基于新标记是否已在当前文本中出现,对新标记施加惩罚,从而提升模型讨论新话题的可能性。"
756
- ),
757
- ...InputWrapper,
758
- v7.title("presence_penalty")
759
- ),
760
- seed: v7.pipe(
761
- v7.optional(v7.pipe(v7.number())),
762
- v7.description(
763
- "若已指定,系统将尽力确保采样具有确定性,即使用相同种子和参数的重复请求将返回相同结果。确定性无法保证,请通过 system_fingerprint 响应参数监控后端变化。"
764
- ),
765
- ...InputWrapper,
766
- v7.title("seed")
767
- ),
768
- stop: v7.pipe(
769
- v7.optional(v7.pipe(v7.array(v7.pipe(v7.string())), v7.maxLength(4))),
770
- v7.description(
771
- "最多可指定4个停止序列,API将在生成到该序列时停止,返回的文本中不包含该停止序列。"
772
- ),
773
- (0, import_view_angular_core.asControl)(),
774
- (0, import_view_angular_core.setComponent)("chip-input-list"),
775
- import_view_angular_core.actions.inputs.patch({
776
- addOnBlur: true
777
- }),
778
- ...InputWrapper,
779
- v7.title("stop")
375
+ })
376
+ ),
377
+ v3.title("OpenAI Completions 兼容配置"),
378
+ v3.description("针对 OpenAI Completions API 的兼容性覆写选项")
379
+ );
380
+ var OpenAIResponsesCompatSchema = v3.pipe(
381
+ v3.optional(
382
+ v3.object({
383
+ supportsDeveloperRole: v3.optional(
384
+ v3.pipe(
385
+ v3.boolean(),
386
+ v3.title("支持开发者角色"),
387
+ v3.description("是否支持 developer 系统消息角色")
780
388
  )
781
- // top_logprobs: v.pipe(
782
- // v.optional(v.pipe(v.number(), v.minValue(0), v.maxValue(20))),
783
- // v.description(
784
- // '一个介于0和20之间的整数,用于指定在每个标记位置返回的最可能的标记数量,每个标记均关联对应的对数概率。若使用此参数,则必须将logprobs设置为true。',
785
- // ),
786
- // ),
787
- // verbosity: v.pipe(
788
- // v.optional(v.picklist(['low', 'medium', 'high'])),
789
- // v.description(
790
- // `控制模型回复的详细程度。数值越低,回复越简洁;数值越高,回复越详细。当前支持的取值为低、中和高。`,
791
- // ),
792
- // ),
793
- // reasoning_effort: v.pipe(
794
- // v.optional(v.picklist(['minimal', 'low', 'medium', 'high'])),
795
- // v.description(
796
- // `控制模型回复的详细程度。数值越低,回复越简洁;数值越高,回复越详细。当前支持的取值为低、中和高。`,
797
- // ),
798
- // ),
799
- }),
800
- import_view_angular_core.actions.wrappers.patch(["div"]),
801
- import_view_angular_core.actions.class.top("grid gap-2")
802
- )
803
- ]),
804
- import_view_angular_core.actions.wrappers.patch(["div"]),
805
- import_view_angular_core.actions.class.top("grid gap-2"),
806
- (0, import_valibot_visit.asVirtualGroup)()
389
+ ),
390
+ sendSessionIdHeader: v3.optional(
391
+ v3.pipe(
392
+ v3.boolean(),
393
+ v3.title("发送会话 ID 标头"),
394
+ v3.description("是否在请求中携带 X-Session-ID 标头")
395
+ )
396
+ ),
397
+ supportsLongCacheRetention: v3.optional(
398
+ v3.pipe(
399
+ v3.boolean(),
400
+ v3.title("长期缓存保留"),
401
+ v3.description("是否支持长期缓存保留策略")
402
+ )
403
+ )
404
+ })
405
+ ),
406
+ v3.title("OpenAI Responses 兼容配置"),
407
+ v3.description("针对 OpenAI Responses API 的兼容性覆写选项")
807
408
  );
808
- var VendorOptionsDefine = v7.pipe(
809
- v7.optional(
810
- v7.record(
811
- v7.string(),
812
- v7.pipe(
813
- v7.intersect([
814
- v7.object({
815
- /** @internal */
816
- extraOptions: v7.pipe(
817
- v7.optional((0, import_valibot_visit.omitIntersect)(ChatItemDefine, ["name", "vendor"])),
818
- v7.description(`附加配置`)
819
- )
820
- })
821
- ]),
822
- import_view_angular_core.actions.wrappers.patch(["div"]),
823
- import_view_angular_core.actions.class.top("grid gap-2"),
824
- (0, import_valibot_visit.asVirtualGroup)()
409
+ var AnthropicMessagesCompatSchema = v3.pipe(
410
+ v3.optional(
411
+ v3.object({
412
+ supportsEagerToolInputStreaming: v3.optional(
413
+ v3.pipe(
414
+ v3.boolean(),
415
+ v3.title(" eagerly 工具流式"),
416
+ v3.description("是否支持工具调用的 eager 模式流式输出")
417
+ )
418
+ ),
419
+ supportsLongCacheRetention: v3.optional(
420
+ v3.pipe(
421
+ v3.boolean(),
422
+ v3.title("长期缓存保留"),
423
+ v3.description("是否支持长期缓存保留策略")
424
+ )
425
+ ),
426
+ sendSessionAffinityHeaders: v3.optional(
427
+ v3.pipe(
428
+ v3.boolean(),
429
+ v3.title("发送会话亲和标头"),
430
+ v3.description("是否在请求中携带会话亲和性标头")
431
+ )
432
+ ),
433
+ supportsCacheControlOnTools: v3.optional(
434
+ v3.pipe(
435
+ v3.boolean(),
436
+ v3.title("工具缓存控制"),
437
+ v3.description("是否支持在 tool_use 消息中使用 cache_control")
438
+ )
439
+ ),
440
+ supportsTemperature: v3.optional(
441
+ v3.pipe(
442
+ v3.boolean(),
443
+ v3.title("支持温度参数"),
444
+ v3.description("模型/接口是否支持 temperature 参数")
445
+ )
446
+ ),
447
+ forceAdaptiveThinking: v3.optional(
448
+ v3.pipe(
449
+ v3.boolean(),
450
+ v3.title("强制自适应思考"),
451
+ v3.description("是否强制启用 adaptive thinking 模式")
452
+ )
453
+ ),
454
+ allowEmptySignature: v3.optional(
455
+ v3.pipe(
456
+ v3.boolean(),
457
+ v3.title("允许空签名"),
458
+ v3.description("是否允许工具调用不指定签名(sha256)")
459
+ )
825
460
  )
826
- )
461
+ })
827
462
  ),
828
- v7.description(vendorOptionsDescribe),
829
- (0, import_view_angular_core.setComponent)("rest-chip-group"),
830
- import_view_angular_core.actions.inputs.patch({
831
- optionalkeyList: VendorList.map((item) => item.value),
832
- placeholder: "请设置额外配置"
833
- }),
834
- v7.title("厂商额外配置")
463
+ v3.title("Anthropic Messages 兼容配置"),
464
+ v3.description("针对 Anthropic Messages API 的兼容性覆写选项")
835
465
  );
836
- var ChatParamsItemDefine = v7.pipe(
837
- v7.intersect([
838
- ChatItemDefine,
839
- v7.object({ vendorOptions: VendorOptionsDefine })
466
+ var CompatSchema = v3.pipe(
467
+ v3.union([
468
+ OpenAICompletionsCompatSchema,
469
+ OpenAIResponsesCompatSchema,
470
+ AnthropicMessagesCompatSchema
840
471
  ]),
841
- (0, import_valibot_visit.asVirtualGroup)(),
842
- import_view_angular_core.actions.wrappers.patch(["div"]),
843
- import_view_angular_core.actions.class.top("grid gap-2")
472
+ v3.title("兼容配置"),
473
+ v3.description(
474
+ "模型 API 兼容性覆写选项,支持 OpenAI Completions、OpenAI Responses、Anthropic Messages 三种格式"
475
+ )
844
476
  );
845
- var ChatParamsListDefine = v7.pipe(
846
- v7.array(ChatParamsItemDefine),
847
- (0, import_view_angular_core.setComponent)("label-chip-array"),
848
- v7.description("对话模型列表,目前用于切换使用"),
849
- import_view_angular_core.actions.inputs.patch({
850
- displayKey: "name",
851
- placeholder: "请添加配置"
852
- })
477
+ var InputChoiceSchema = v3.pipe(
478
+ v3.picklist(["text", "image"]),
479
+ v3.title("输入类型"),
480
+ v3.description("支持的输入模态类型")
853
481
  );
854
- var InputChatOptionsDefine = (0, import_valibot_visit.omitIntersect)(ChatParamsItemDefine, [
855
- "name"
856
- ]);
857
-
858
- // packages/openai/chat/token.ts
859
- var import_static_injector = require("static-injector");
860
- var OpenAIConfigToken = new import_static_injector.InjectionToken(
861
- "OpenAIConfig"
482
+ var InputSchema = v3.pipe(
483
+ v3.array(InputChoiceSchema),
484
+ v3.title("输入类型列表"),
485
+ v3.description("该模型支持的用户输入类型,如 text 文本或 image 图片")
862
486
  );
863
-
864
- // packages/openai/chat/chat.history.service.ts
865
- var import_static_injector2 = require("static-injector");
866
- var import_es_toolkit = require("es-toolkit");
867
- var import_rxjs = require("rxjs");
868
- var import_vfs2 = require("@cyia/vfs2");
869
- var fs = __toESM(require("fs"), 1);
870
- var import_yaml = require("yaml");
871
- var import_dayjs = __toESM(require("dayjs"), 1);
872
- var import_util4 = require("@cyia/util");
873
- var ChatHistoryService = class {
874
- #update$ = (0, import_static_injector2.signal)(0);
875
- /** 外部监听更新用 */
876
- update$$ = (0, import_static_injector2.computed)(() => this.#update$());
877
- #logMap = /* @__PURE__ */ new Map();
878
- #config = (0, import_static_injector2.inject)(OpenAIConfigToken);
879
- #dir() {
880
- return this.#config().history.dir;
881
- }
882
- #createNewListen(fileName) {
883
- const filePath = import_vfs2.path.join(this.#dir(), `${fileName}.yml`);
884
- const instance = new import_rxjs.Subject();
885
- instance.pipe(
886
- (0, import_rxjs.bufferWhen)(() => instance.pipe((0, import_rxjs.debounceTime)(2e3))),
887
- (0, import_rxjs.filter)((list) => !!list.length)
888
- ).subscribe(async (inputList) => {
889
- if (!fs.existsSync(this.#dir())) {
890
- await fs.promises.mkdir(this.#dir(), { recursive: true });
891
- }
892
- try {
893
- let list = [];
894
- if (await fs.existsSync(filePath)) {
895
- const content = await fs.promises.readFile(filePath, {
896
- encoding: "utf-8"
897
- });
898
- list = (0, import_yaml.parse)(content);
899
- } else {
900
- list = [];
487
+ var HeadersSchema = v3.pipe(
488
+ v3.record(v3.string(), v3.string()),
489
+ v3.title("自定义请求头"),
490
+ v3.description("额外的 HTTP 请求头键值对配置")
491
+ );
492
+ var CostSchema = v3.pipe(
493
+ v3.optional(
494
+ v3.object({
495
+ input: v3.pipe(
496
+ v3.number(),
497
+ v3.title("输入单价"),
498
+ v3.description("每 token 输入费用")
499
+ ),
500
+ output: v3.pipe(
501
+ v3.number(),
502
+ v3.title("输出单价"),
503
+ v3.description("每 token 输出费用")
504
+ ),
505
+ cacheRead: v3.pipe(
506
+ v3.number(),
507
+ v3.title("缓存读取单价"),
508
+ v3.description("从缓存读取每 token 的费用")
509
+ ),
510
+ cacheWrite: v3.pipe(
511
+ v3.number(),
512
+ v3.title("缓存写入单价"),
513
+ v3.description("写入缓存每 token 的费用")
514
+ )
515
+ }),
516
+ { input: 0, output: 0, cacheRead: 0, cacheWrite: 0 }
517
+ ),
518
+ v3.title("费用配置"),
519
+ v3.description("模型各操作类型的 token 计价标准")
520
+ );
521
+ var ThinkingLevelMapSchema = v3.pipe(
522
+ v3.record(
523
+ ModelThinkingLevelSchema,
524
+ v3.pipe(
525
+ v3.nullish(v3.string()),
526
+ v3.title("配置值"),
527
+ v3.description("对应思考等级的具体配置字符串,null 表示未设置")
528
+ )
529
+ ),
530
+ v3.title("思考等级配置映射"),
531
+ v3.description("各思考等级对应的具体配置参数映射")
532
+ );
533
+ var ModelSchema = v3.pipe(
534
+ v3.object({
535
+ provider: v3.pipe(
536
+ v3.optional(v3.string(), "default"),
537
+ v3.title("厂商"),
538
+ v3.description("模型提供商,如 openai / anthropic / llama")
539
+ ),
540
+ baseUrl: v3.pipe(
541
+ v3.string(),
542
+ v3.title("基础 URL"),
543
+ v3.description("API 请求的基础地址")
544
+ ),
545
+ reasoning: v3.pipe(
546
+ v3.optional(v3.boolean(), false),
547
+ v3.title("支持推理"),
548
+ v3.description("该模型是否支持思考/推理模式")
549
+ ),
550
+ // thinkingLevelMap: v.optional(
551
+ // v.pipe(
552
+ // v.optional(ThinkingLevelMapSchema),
553
+ // v.title('思考等级配置'),
554
+ // v.description('各思考等级的具体参数配置映射'),
555
+ // ),
556
+ // ),
557
+ input: v3.pipe(
558
+ v3.optional(InputSchema, ["text", "image"]),
559
+ v3.title("输入类型"),
560
+ v3.description("支持的输入模态类型")
561
+ ),
562
+ cost: v3.pipe(
563
+ CostSchema,
564
+ v3.title("费用配置"),
565
+ v3.description("模型 token 计价标准")
566
+ ),
567
+ contextWindow: v3.pipe(
568
+ v3.pipe(v3.optional(v3.number(), 99999999)),
569
+ v3.title("上下文窗口"),
570
+ v3.description("模型支持的上下文最大 token 数")
571
+ ),
572
+ maxTokens: v3.pipe(
573
+ v3.pipe(v3.optional(v3.number(), 99999999)),
574
+ v3.title("最大输出 tokens"),
575
+ v3.description("单次请求允许的最大输出 token 数")
576
+ ),
577
+ headers: v3.optional(
578
+ v3.pipe(
579
+ v3.optional(HeadersSchema),
580
+ v3.title("自定义请求头"),
581
+ v3.description("额外的 HTTP 请求头配置")
582
+ )
583
+ ),
584
+ compat: v3.pipe(
585
+ v3.optional(CompatSchema, { supportsDeveloperRole: false }),
586
+ v3.title("兼容配置"),
587
+ v3.description("API 兼容性覆写选项")
588
+ )
589
+ }),
590
+ v3.title("模型定义"),
591
+ v3.description(
592
+ "pi-ai 模型的核心配置结构,包含模型标识、API 参数、费用及兼容性设置"
593
+ )
594
+ );
595
+ var OutputSchema = InputSchema;
596
+ var ModelConfigDefine = v3.pipe(
597
+ v3.object({
598
+ provider: KnownProviderDefine,
599
+ model: v3.pipe(v3.string(), v3.title("模型名")),
600
+ name: v3.pipe(
601
+ v3.optional(v3.string()),
602
+ v3.title("配置名"),
603
+ v3.description("模型的配置名称(默认为模型名)")
604
+ ),
605
+ /** provider是自定义时使用 */
606
+ apiKey: v3.pipe(v3.optional(v3.string()), v3.title("apiKey")),
607
+ config: v3.pipe(
608
+ v3.optional(ModelSchema),
609
+ (0, import_view_angular_core.hideWhen)({
610
+ disabled: true,
611
+ listen(fn, field) {
612
+ return fn({ list: [["..", "provider"]] }).pipe(
613
+ (0, import_rxjs.map)(
614
+ ({ list: [value] }) => !(value === "openai-completions" || value === "openai-responses" || value === "anthropic-messages")
615
+ )
616
+ );
901
617
  }
902
- list.unshift(...inputList.reverse());
903
- await fs.promises.writeFile(filePath, (0, import_yaml.stringify)(list));
904
- this.#update$.update((a) => a + 1);
905
- } catch (error) {
906
- this.#config().captureException(error);
907
- }
908
- });
909
- this.#logMap.set(fileName, instance);
910
- return instance;
911
- }
912
- save(messages, options, config) {
913
- if (!this.#config().history.enable) {
914
- return;
915
- }
916
- try {
917
- const fileName = (0, import_dayjs.default)().format("YYYY-MM-DD");
918
- const message$ = this.#logMap.get(fileName) ?? this.#createNewListen(fileName);
919
- const item = {
920
- date: (0, import_dayjs.default)().valueOf(),
921
- messages,
922
- options: (0, import_es_toolkit.omitBy)(options, import_util4.isEmptyInput),
923
- config
924
- };
925
- message$.next(item);
926
- } catch (error) {
927
- try {
928
- this.#config().captureException(error);
929
- } catch (error2) {
930
- }
931
- }
932
- }
933
- };
618
+ })
619
+ )
620
+ }),
621
+ v3.transform((item) => ({ ...item, name: item.name ?? item.model }))
622
+ );
934
623
 
935
- // packages/openai/chat/service.ts
936
- var v8 = __toESM(require("valibot"), 1);
937
- var ChatProviderService = class {
938
- #config = (0, import_static_injector3.inject)(OpenAIConfigToken);
939
- #chatHistory = (0, import_static_injector3.inject)(ChatHistoryService);
940
- create(input) {
941
- let options = v8.parse(InputChatOptionsDefine, input);
942
- let instance;
943
- const extraOptions = options.vendorOptions?.[options.vendor]?.["extraOptions"];
944
- options = {
945
- ...extraOptions,
946
- ...options,
947
- apiKey: options.apiKey?.trim() || extraOptions?.apiKey || " "
948
- };
949
- if (!options.vendor || options.vendor === "openai") {
950
- instance = new OpenAIChat(options);
951
- } else if (options.vendor === "gemini") {
952
- instance = new GeminiChat(options);
953
- } else if (options.vendor === "claude") {
954
- instance = new AnthropicChat(options);
955
- } else {
956
- instance = createCompatibleFactory(options);
624
+ // packages/openai/chat/chat.ts
625
+ var import_util = require("@cyia/util");
626
+ var v4 = __toESM(require("valibot"), 1);
627
+ function createChatStream(input) {
628
+ const result = getModelConfig(input);
629
+ return (context, options, extra) => {
630
+ context.messages = (0, import_util.deepClone)(context.messages);
631
+ const PiPUserConvertDefine = v4.pipe(
632
+ UserChatMessage,
633
+ v4.transform(
634
+ (item) => ({
635
+ role: "user",
636
+ timestamp: Date.now(),
637
+ content: item.content.map((item2) => {
638
+ if (item2.type === "text") {
639
+ return item2;
640
+ } else {
641
+ const match = item2.image_url.url.match(
642
+ /^data:([^;]+);base64,(.+)$/
643
+ );
644
+ return {
645
+ type: "image",
646
+ mimeType: match[1],
647
+ data: match[2]
648
+ };
649
+ }
650
+ })
651
+ })
652
+ )
653
+ );
654
+ const PiPAssConvertDefine = v4.pipe(
655
+ AssistantChatMessage,
656
+ v4.transform(
657
+ (item) => ({
658
+ role: "assistant",
659
+ timestamp: Date.now(),
660
+ content: item.content.map((item2) => item2),
661
+ api: result.model.api,
662
+ provider: result.model.provider,
663
+ usage: {
664
+ cacheRead: 0,
665
+ cacheWrite: 0,
666
+ cost: {
667
+ input: 0,
668
+ output: 0,
669
+ cacheRead: 0,
670
+ cacheWrite: 0,
671
+ total: 0
672
+ },
673
+ input: 0,
674
+ output: 0,
675
+ totalTokens: 0
676
+ },
677
+ stopReason: "stop",
678
+ model: result.model.api
679
+ })
680
+ )
681
+ );
682
+ const sysIndex = context.messages.findIndex(
683
+ (item) => item.role === "system"
684
+ );
685
+ if (sysIndex !== -1) {
686
+ const item = context.messages[sysIndex];
687
+ context.messages.splice(sysIndex, 1);
688
+ context.systemPrompt = item.content[0].text;
957
689
  }
958
- instance.init();
959
- const openAIOptions = this.#config;
960
- const chatHistory = this.#chatHistory;
961
- const fn = async function* (...args) {
962
- const result = instance.stream(args[0], {
963
- ...args[1],
964
- tryPull: openAIOptions().tryPull,
965
- pullModel: openAIOptions().pullModel
966
- });
967
- let content = "";
968
- let isThink = false;
969
- let thinkStart = 0;
970
- let thinkEnd;
971
- let start = true;
972
- let isThinking = false;
973
- let contentEnd;
974
- let lastEmit;
975
- for await (const delta of result) {
976
- content += delta;
977
- if (start) {
978
- start = false;
979
- const result2 = ThinkList.find(
980
- (item) => delta.startsWith(`<${item}>`)
981
- );
982
- if (result2) {
983
- isThink = true;
984
- thinkStart = result2.length + 2;
985
- isThinking = true;
986
- }
987
- } else if (isThink && thinkEnd === void 0) {
988
- const result2 = ThinkList.find((item) => delta === `</${item}>`);
989
- if (result2) {
990
- contentEnd = content.length;
991
- thinkEnd = content.length - result2.length - 3;
992
- isThinking = false;
690
+ const createStream = () => (0, import_pi_ai2.stream)(
691
+ result.model,
692
+ {
693
+ ...context,
694
+ messages: v4.parse(
695
+ v4.array(v4.union([PiPUserConvertDefine, PiPAssConvertDefine])),
696
+ context.messages
697
+ )
698
+ },
699
+ {
700
+ ...options,
701
+ apiKey: options?.apiKey ?? result.config.apiKey,
702
+ onPayload(payload, model) {
703
+ payload = options?.onPayload?.(payload, model) ?? payload;
704
+ if (model.api === "openai-completions") {
705
+ return {
706
+ ...payload,
707
+ response_format: extra?.response_format
708
+ };
993
709
  }
710
+ return payload;
994
711
  }
995
- lastEmit = {
996
- content: isThink ? (contentEnd ? content.slice(contentEnd) : "").trim() : content,
997
- isThinking,
998
- delta,
999
- thinkContent: isThink ? content.slice(thinkStart, thinkEnd).trim() : void 0
1000
- };
1001
- yield lastEmit;
1002
- }
1003
- const lastMessage = createAssistantMessage(
1004
- isThink ? contentEnd ? content.slice(contentEnd) : "" : content
1005
- );
1006
- if (lastEmit?.thinkContent) {
1007
- lastMessage.thinkContent = lastEmit.thinkContent;
1008
712
  }
1009
- chatHistory.save(
1010
- [...args[0].messages, lastMessage],
1011
- { ...args[0], messages: void 0 },
1012
- options
1013
- );
1014
- };
1015
- return {
1016
- stream: fn,
1017
- chat: async (...args) => {
1018
- const result = fn(...args);
1019
- let obj;
1020
- for await (const element of result) {
1021
- obj = element;
713
+ );
714
+ let currentStream = createStream();
715
+ const config = extra?.injector?.get(OpenAIConfigToken);
716
+ return (async function* () {
717
+ let hasRetry = false;
718
+ while (true) {
719
+ let retry = false;
720
+ for await (const item of currentStream) {
721
+ if (item.type === "error") {
722
+ if (item.error.errorMessage?.includes("404") && item.error.errorMessage?.includes(
723
+ "no router for requested model"
724
+ ) && !hasRetry) {
725
+ if (config?.().tryPull?.()) {
726
+ await config().pullModel?.(input.model);
727
+ retry = true;
728
+ break;
729
+ }
730
+ }
731
+ }
732
+ yield item;
1022
733
  }
1023
- return obj;
1024
- },
1025
- callTool: (input2, options2) => instance.callTool(input2, options2)
1026
- };
1027
- }
1028
- };
734
+ if (!retry || hasRetry) {
735
+ break;
736
+ }
737
+ hasRetry = true;
738
+ currentStream = createStream();
739
+ }
740
+ })();
741
+ };
742
+ }
1029
743
 
1030
- // packages/openai/chat/module.ts
1031
- var OPENAI_MODULE = {
1032
- provider: [ChatProviderService, ChatHistoryService],
1033
- token: { OpenAIConfigToken }
1034
- };
744
+ // packages/openai/index.ts
745
+ var import_pi_ai4 = require("@earendil-works/pi-ai");
746
+
747
+ // packages/openai/chat/util/faux-provider.ts
748
+ var import_pi_ai3 = require("@earendil-works/pi-ai");
749
+ function createDynamicResponse(responseFactory) {
750
+ return async (context, _options, state) => {
751
+ const responses = responseFactory(context, state.callCount);
752
+ const content = Array.isArray(responses) ? responses.map((r) => (0, import_pi_ai3.fauxText)(r)) : (0, import_pi_ai3.fauxText)(responses);
753
+ return (0, import_pi_ai3.fauxAssistantMessage)(content);
754
+ };
755
+ }
756
+ function registerMockProvider(options) {
757
+ const registration = (0, import_pi_ai3.registerFauxProvider)(options);
758
+ return {
759
+ model: registration.getModel(),
760
+ setResponses: (responses) => registration.setResponses(responses),
761
+ unregister: () => registration.unregister()
762
+ };
763
+ }
1035
764
  // Annotate the CommonJS export names for ESM import in node:
1036
765
  0 && (module.exports = {
766
+ AnthropicMessagesCompatSchema,
1037
767
  AssistantChatCompletionContent,
1038
768
  AssistantChatMessage,
1039
769
  ChatCompletionContentPart,
1040
770
  ChatCompletionContentPartImage,
1041
771
  ChatCompletionContentPartStr,
1042
- ChatHistoryService,
1043
- ChatItemDefine,
772
+ ChatMessageCommonItemDefine,
1044
773
  ChatMessageItemDefine,
1045
774
  ChatMessageListDefine,
1046
- ChatParamsItemDefine,
1047
- ChatParamsListDefine,
1048
- ChatProviderService,
1049
- InputChatOptionsDefine,
775
+ CompatSchema,
776
+ InputChoiceSchema,
777
+ InputSchema,
778
+ ModelConfigDefine,
779
+ ModelSchema,
780
+ ModelThinkingLevelSchema,
1050
781
  OPENAI_MODULE,
782
+ OpenAICompletionsCompatSchema,
1051
783
  OpenAIConfigToken,
784
+ OpenAIResponsesCompatSchema,
785
+ OutputSchema,
1052
786
  SystemChatCompletionContent,
1053
787
  SystemChatMessage,
788
+ ThinkingLevelSchema,
1054
789
  UserChatCompletionContent,
1055
790
  UserChatMessage,
1056
- VendorOptionsDefine,
791
+ complete,
1057
792
  createAssistantMessage,
793
+ createChatStream,
794
+ createDynamicResponse,
1058
795
  createSystemMessage,
1059
- createUserMessage
796
+ createUserMessage,
797
+ fauxAssistantMessage,
798
+ fauxText,
799
+ fauxThinking,
800
+ getModelConfig,
801
+ registerMockProvider,
802
+ stream
1060
803
  });
1061
804
  //# sourceMappingURL=index.js.map