@shenghuabi/openai 1.1.47 → 1.2.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/index.js CHANGED
@@ -30,37 +30,50 @@ 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,
40
39
  ChatMessageItemDefine: () => ChatMessageItemDefine,
41
40
  ChatMessageListDefine: () => ChatMessageListDefine,
42
- ChatParamsItemDefine: () => ChatParamsItemDefine,
43
- ChatParamsListDefine: () => ChatParamsListDefine,
44
- ChatProviderService: () => ChatProviderService,
45
- InputChatOptionsDefine: () => InputChatOptionsDefine,
41
+ CompatSchema: () => CompatSchema,
42
+ InputChoiceSchema: () => InputChoiceSchema,
43
+ InputSchema: () => InputSchema,
44
+ ModelConfigDefine: () => ModelConfigDefine,
45
+ ModelSchema: () => ModelSchema,
46
+ ModelThinkingLevelSchema: () => ModelThinkingLevelSchema,
46
47
  OPENAI_MODULE: () => OPENAI_MODULE,
48
+ OpenAICompletionsCompatSchema: () => OpenAICompletionsCompatSchema,
47
49
  OpenAIConfigToken: () => OpenAIConfigToken,
50
+ OpenAIResponsesCompatSchema: () => OpenAIResponsesCompatSchema,
51
+ OutputSchema: () => OutputSchema,
48
52
  SystemChatCompletionContent: () => SystemChatCompletionContent,
49
53
  SystemChatMessage: () => SystemChatMessage,
54
+ ThinkingLevelSchema: () => ThinkingLevelSchema,
50
55
  UserChatCompletionContent: () => UserChatCompletionContent,
51
56
  UserChatMessage: () => UserChatMessage,
52
- VendorOptionsDefine: () => VendorOptionsDefine,
57
+ complete: () => import_pi_ai4.complete,
53
58
  createAssistantMessage: () => createAssistantMessage,
59
+ createChatStream: () => createChatStream,
60
+ createDynamicResponse: () => createDynamicResponse,
54
61
  createSystemMessage: () => createSystemMessage,
55
- createUserMessage: () => createUserMessage
62
+ createUserMessage: () => createUserMessage,
63
+ fauxAssistantMessage: () => import_pi_ai4.fauxAssistantMessage,
64
+ fauxText: () => import_pi_ai4.fauxText,
65
+ fauxThinking: () => import_pi_ai4.fauxThinking,
66
+ getModelConfig: () => getModelConfig,
67
+ registerMockProvider: () => registerMockProvider,
68
+ stream: () => import_pi_ai4.stream
56
69
  });
57
70
  module.exports = __toCommonJS(openai_exports);
58
71
 
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");
72
+ // packages/openai/chat/token.ts
73
+ var import_static_injector = require("static-injector");
74
+ var OpenAIConfigToken = new import_static_injector.InjectionToken(
75
+ "OpenAIConfig"
76
+ );
64
77
 
65
78
  // packages/openai/chat/message.define.ts
66
79
  var v = __toESM(require("valibot"), 1);
@@ -105,389 +118,6 @@ var ChatMessageItemDefine = v.union([
105
118
  ]);
106
119
  var ChatMessageListDefine = v.array(ChatMessageItemDefine);
107
120
 
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(
396
- 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
- };
490
-
491
121
  // packages/openai/chat/util/create.ts
492
122
  function createSystemMessage() {
493
123
  return { role: "system" };
@@ -505,557 +135,603 @@ function createAssistantMessage(text = "") {
505
135
  };
506
136
  }
507
137
 
508
- // packages/openai/chat/const.ts
509
- var ThinkList = [
510
- "think",
511
- "thinking",
512
- "reason",
513
- "reasoning",
514
- "thought",
515
- "Thought"
516
- ];
138
+ // packages/openai/chat/module.ts
139
+ var OPENAI_MODULE = {
140
+ provider: [],
141
+ token: { OpenAIConfigToken }
142
+ };
143
+
144
+ // packages/openai/chat/chat.ts
145
+ var import_pi_ai2 = require("@earendil-works/pi-ai");
517
146
 
518
- // packages/openai/chat/options.define.ts
147
+ // packages/openai/chat/util/get-custom-provider.ts
148
+ var v3 = __toESM(require("valibot"), 1);
149
+ var import_pi_ai = require("@earendil-works/pi-ai");
150
+
151
+ // packages/openai/chat/provider.define.ts
152
+ var v2 = __toESM(require("valibot"), 1);
153
+ var KnownProviderDefine = v2.pipe(
154
+ v2.picklist([
155
+ "amazon-bedrock",
156
+ "anthropic",
157
+ "google",
158
+ "google-vertex",
159
+ "openai",
160
+ "azure-openai-responses",
161
+ "openai-codex",
162
+ "deepseek",
163
+ "github-copilot",
164
+ "xai",
165
+ "groq",
166
+ "cerebras",
167
+ "openrouter",
168
+ "vercel-ai-gateway",
169
+ "zai",
170
+ "mistral",
171
+ "minimax",
172
+ "minimax-cn",
173
+ "moonshotai",
174
+ "moonshotai-cn",
175
+ "huggingface",
176
+ "fireworks",
177
+ "together",
178
+ "opencode",
179
+ "opencode-go",
180
+ "kimi-coding",
181
+ "cloudflare-workers-ai",
182
+ "cloudflare-ai-gateway",
183
+ "xiaomi",
184
+ "xiaomi-token-plan-cn",
185
+ "xiaomi-token-plan-ams",
186
+ "xiaomi-token-plan-sgp",
187
+ "ant-ling",
188
+ "nvidia",
189
+ "zai-coding-cn",
190
+ /** 自定义 */
191
+ "openai-completions",
192
+ "openai-responses",
193
+ "anthropic-messages"
194
+ ]),
195
+ v2.title("提供商"),
196
+ v2.description(`'openai-completions','openai-responses','anthropic-messages',为自定义提供商`)
197
+ );
198
+
199
+ // packages/openai/chat/util/get-custom-provider.ts
519
200
  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
- }
201
+ var import_rxjs = require("rxjs");
202
+ function getCustomProvider(compat, model, name, input) {
203
+ return { ...input, id: model, api: compat, name };
204
+ }
205
+ function getModelConfig(input) {
206
+ if (input.provider === "faux") {
207
+ return {
208
+ model: input.config,
209
+ config: input
210
+ };
654
211
  }
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
- })
212
+ const config = v3.parse(ModelConfigDefine, input);
213
+ if (config.provider === "openai-completions" || config.provider === "openai-responses" || config.provider === "anthropic-messages") {
214
+ return {
215
+ model: getCustomProvider(
216
+ config.provider,
217
+ config.model,
218
+ config.name,
219
+ config.config
220
+ ),
221
+ config
222
+ };
223
+ }
224
+ return {
225
+ model: (0, import_pi_ai.getModel)(config.provider, config.model),
226
+ config
227
+ };
228
+ }
229
+ var ThinkingLevelSchema = v3.pipe(
230
+ v3.picklist(["minimal", "low", "medium", "high", "xhigh"]),
231
+ v3.title("思考等级"),
232
+ v3.description("模型思考的详细程度,从最小到最大")
233
+ );
234
+ var ModelThinkingLevelSchema = v3.pipe(
235
+ v3.picklist(["off", "minimal", "low", "medium", "high", "xhigh"]),
236
+ v3.title("模型思考等级"),
237
+ v3.description("关闭或设置模型思考的详细程度")
238
+ );
239
+ var OpenAICompletionsCompatSchema = v3.pipe(
240
+ v3.optional(
241
+ v3.object({
242
+ supportsStore: v3.optional(
243
+ v3.pipe(
244
+ v3.boolean(),
245
+ v3.title("支持存储"),
246
+ v3.description("是否支持服务端会话存储")
687
247
  )
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
248
+ ),
249
+ supportsDeveloperRole: v3.optional(
250
+ v3.pipe(
251
+ v3.boolean(),
252
+ v3.title("支持开发者角色"),
253
+ v3.description("是否支持 developer 系统消息角色")
254
+ )
255
+ ),
256
+ supportsReasoningEffort: v3.optional(
257
+ v3.pipe(
258
+ v3.boolean(),
259
+ v3.title("支持推理努力"),
260
+ v3.description("是否支持 reasoning_effort 参数")
261
+ )
262
+ ),
263
+ supportsUsageInStreaming: v3.optional(
264
+ v3.pipe(
265
+ v3.boolean(),
266
+ v3.title("流式用量"),
267
+ v3.description("流式输出中是否返回 usage 信息")
268
+ )
269
+ ),
270
+ maxTokensField: v3.optional(
271
+ v3.pipe(
272
+ v3.picklist(["max_completion_tokens", "max_tokens"]),
273
+ v3.title("最大 token 字段名"),
274
+ v3.description("指定最大 token 参数使用的是哪个字段名")
275
+ )
276
+ ),
277
+ requiresToolResultName: v3.optional(
278
+ v3.pipe(
279
+ v3.boolean(),
280
+ v3.title("需要工具结果名称"),
281
+ v3.description("是否要求工具结果消息包含 name 字段")
282
+ )
283
+ ),
284
+ requiresAssistantAfterToolResult: v3.optional(
285
+ v3.pipe(
286
+ v3.boolean(),
287
+ v3.title("需要助手回复"),
288
+ v3.description("工具结果后是否需要助手消息跟进")
289
+ )
290
+ ),
291
+ requiresThinkingAsText: v3.optional(
292
+ v3.pipe(
293
+ v3.boolean(),
294
+ v3.title("思考转文本"),
295
+ v3.description("是否将思考过程作为普通文本发送")
296
+ )
297
+ ),
298
+ requiresReasoningContentOnAssistantMessages: v3.optional(
299
+ v3.pipe(
300
+ v3.boolean(),
301
+ v3.title("推理内容在助手消息中"),
302
+ v3.description("是否在助手消息中包含推理内容")
303
+ )
304
+ ),
305
+ thinkingFormat: v3.optional(
306
+ v3.pipe(
307
+ v3.picklist([
308
+ "openai",
309
+ "openrouter",
310
+ "deepseek",
311
+ "together",
312
+ "zai",
313
+ "qwen",
314
+ "qwen-chat-template",
315
+ "string-thinking",
316
+ "ant-ling"
317
+ ]),
318
+ v3.title("思考格式"),
319
+ v3.description("指定 thinking 标签的序列化格式")
320
+ )
321
+ ),
322
+ openRouterRouting: v3.optional(
323
+ v3.pipe(
324
+ v3.unknown(),
325
+ v3.title("OpenRouter 路由"),
326
+ v3.description("自定义 OpenRouter 的路由配置")
327
+ )
328
+ ),
329
+ vercelGatewayRouting: v3.optional(
330
+ v3.pipe(
331
+ v3.unknown(),
332
+ v3.title("Vercel Gateway 路由"),
333
+ v3.description("自定义 Vercel AI Gateway 的路由配置")
334
+ )
335
+ ),
336
+ zaiToolStream: v3.optional(
337
+ v3.pipe(
338
+ v3.boolean(),
339
+ v3.title("ZAI 工具流式"),
340
+ v3.description("是否启用 ZAI 平台工具调用的流式输出")
341
+ )
342
+ ),
343
+ supportsStrictMode: v3.optional(
344
+ v3.pipe(
345
+ v3.boolean(),
346
+ v3.title("严格模式"),
347
+ v3.description("是否支持工具的 JSON Schema 严格校验")
348
+ )
349
+ ),
350
+ cacheControlFormat: v3.optional(
351
+ v3.pipe(
352
+ v3.literal("anthropic"),
353
+ v3.title("缓存控制格式"),
354
+ v3.description("指定缓存控制的语法格式")
355
+ )
356
+ ),
357
+ sendSessionAffinityHeaders: v3.optional(
358
+ v3.pipe(
359
+ v3.boolean(),
360
+ v3.title("发送会话亲和标头"),
361
+ v3.description("是否在请求中携带会话亲和性标头")
362
+ )
363
+ ),
364
+ supportsLongCacheRetention: v3.optional(
365
+ v3.pipe(
366
+ v3.boolean(),
367
+ v3.title("长期缓存保留"),
368
+ v3.description("是否支持长期缓存保留策略")
707
369
  )
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
370
  )
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")
371
+ })
372
+ ),
373
+ v3.title("OpenAI Completions 兼容配置"),
374
+ v3.description("针对 OpenAI Completions API 的兼容性覆写选项")
375
+ );
376
+ var OpenAIResponsesCompatSchema = v3.pipe(
377
+ v3.optional(
378
+ v3.object({
379
+ supportsDeveloperRole: v3.optional(
380
+ v3.pipe(
381
+ v3.boolean(),
382
+ v3.title("支持开发者角色"),
383
+ v3.description("是否支持 developer 系统消息角色")
780
384
  )
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)()
385
+ ),
386
+ sendSessionIdHeader: v3.optional(
387
+ v3.pipe(
388
+ v3.boolean(),
389
+ v3.title("发送会话 ID 标头"),
390
+ v3.description("是否在请求中携带 X-Session-ID 标头")
391
+ )
392
+ ),
393
+ supportsLongCacheRetention: v3.optional(
394
+ v3.pipe(
395
+ v3.boolean(),
396
+ v3.title("长期缓存保留"),
397
+ v3.description("是否支持长期缓存保留策略")
398
+ )
399
+ )
400
+ })
401
+ ),
402
+ v3.title("OpenAI Responses 兼容配置"),
403
+ v3.description("针对 OpenAI Responses API 的兼容性覆写选项")
807
404
  );
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)()
405
+ var AnthropicMessagesCompatSchema = v3.pipe(
406
+ v3.optional(
407
+ v3.object({
408
+ supportsEagerToolInputStreaming: v3.optional(
409
+ v3.pipe(
410
+ v3.boolean(),
411
+ v3.title(" eagerly 工具流式"),
412
+ v3.description("是否支持工具调用的 eager 模式流式输出")
413
+ )
414
+ ),
415
+ supportsLongCacheRetention: v3.optional(
416
+ v3.pipe(
417
+ v3.boolean(),
418
+ v3.title("长期缓存保留"),
419
+ v3.description("是否支持长期缓存保留策略")
420
+ )
421
+ ),
422
+ sendSessionAffinityHeaders: v3.optional(
423
+ v3.pipe(
424
+ v3.boolean(),
425
+ v3.title("发送会话亲和标头"),
426
+ v3.description("是否在请求中携带会话亲和性标头")
427
+ )
428
+ ),
429
+ supportsCacheControlOnTools: v3.optional(
430
+ v3.pipe(
431
+ v3.boolean(),
432
+ v3.title("工具缓存控制"),
433
+ v3.description("是否支持在 tool_use 消息中使用 cache_control")
434
+ )
435
+ ),
436
+ supportsTemperature: v3.optional(
437
+ v3.pipe(
438
+ v3.boolean(),
439
+ v3.title("支持温度参数"),
440
+ v3.description("模型/接口是否支持 temperature 参数")
441
+ )
442
+ ),
443
+ forceAdaptiveThinking: v3.optional(
444
+ v3.pipe(
445
+ v3.boolean(),
446
+ v3.title("强制自适应思考"),
447
+ v3.description("是否强制启用 adaptive thinking 模式")
448
+ )
449
+ ),
450
+ allowEmptySignature: v3.optional(
451
+ v3.pipe(
452
+ v3.boolean(),
453
+ v3.title("允许空签名"),
454
+ v3.description("是否允许工具调用不指定签名(sha256)")
455
+ )
825
456
  )
826
- )
457
+ })
827
458
  ),
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("厂商额外配置")
459
+ v3.title("Anthropic Messages 兼容配置"),
460
+ v3.description("针对 Anthropic Messages API 的兼容性覆写选项")
835
461
  );
836
- var ChatParamsItemDefine = v7.pipe(
837
- v7.intersect([
838
- ChatItemDefine,
839
- v7.object({ vendorOptions: VendorOptionsDefine })
462
+ var CompatSchema = v3.pipe(
463
+ v3.union([
464
+ OpenAICompletionsCompatSchema,
465
+ OpenAIResponsesCompatSchema,
466
+ AnthropicMessagesCompatSchema
840
467
  ]),
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")
468
+ v3.title("兼容配置"),
469
+ v3.description(
470
+ "模型 API 兼容性覆写选项,支持 OpenAI Completions、OpenAI Responses、Anthropic Messages 三种格式"
471
+ )
844
472
  );
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
- })
473
+ var InputChoiceSchema = v3.pipe(
474
+ v3.picklist(["text", "image"]),
475
+ v3.title("输入类型"),
476
+ v3.description("支持的输入模态类型")
853
477
  );
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"
478
+ var InputSchema = v3.pipe(
479
+ v3.array(InputChoiceSchema),
480
+ v3.title("输入类型列表"),
481
+ v3.description("该模型支持的用户输入类型,如 text 文本或 image 图片")
482
+ );
483
+ var HeadersSchema = v3.pipe(
484
+ v3.record(v3.string(), v3.string()),
485
+ v3.title("自定义请求头"),
486
+ v3.description("额外的 HTTP 请求头键值对配置")
487
+ );
488
+ var CostSchema = v3.pipe(
489
+ v3.optional(
490
+ v3.object({
491
+ input: v3.pipe(
492
+ v3.number(),
493
+ v3.title("输入单价"),
494
+ v3.description("每 token 输入费用")
495
+ ),
496
+ output: v3.pipe(
497
+ v3.number(),
498
+ v3.title("输出单价"),
499
+ v3.description("每 token 输出费用")
500
+ ),
501
+ cacheRead: v3.pipe(
502
+ v3.number(),
503
+ v3.title("缓存读取单价"),
504
+ v3.description("从缓存读取每 token 的费用")
505
+ ),
506
+ cacheWrite: v3.pipe(
507
+ v3.number(),
508
+ v3.title("缓存写入单价"),
509
+ v3.description("写入缓存每 token 的费用")
510
+ )
511
+ }),
512
+ { input: 0, output: 0, cacheRead: 0, cacheWrite: 0 }
513
+ ),
514
+ v3.title("费用配置"),
515
+ v3.description("模型各操作类型的 token 计价标准")
516
+ );
517
+ var ThinkingLevelMapSchema = v3.pipe(
518
+ v3.record(
519
+ ModelThinkingLevelSchema,
520
+ v3.pipe(
521
+ v3.nullish(v3.string()),
522
+ v3.title("配置值"),
523
+ v3.description("对应思考等级的具体配置字符串,null 表示未设置")
524
+ )
525
+ ),
526
+ v3.title("思考等级配置映射"),
527
+ v3.description("各思考等级对应的具体配置参数映射")
528
+ );
529
+ var ModelSchema = v3.pipe(
530
+ v3.object({
531
+ provider: v3.pipe(
532
+ v3.optional(v3.string(), "default"),
533
+ v3.title("厂商"),
534
+ v3.description("模型提供商,如 openai / anthropic / llama")
535
+ ),
536
+ baseUrl: v3.pipe(
537
+ v3.string(),
538
+ v3.title("基础 URL"),
539
+ v3.description("API 请求的基础地址")
540
+ ),
541
+ reasoning: v3.pipe(
542
+ v3.optional(v3.boolean(), false),
543
+ v3.title("支持推理"),
544
+ v3.description("该模型是否支持思考/推理模式")
545
+ ),
546
+ // thinkingLevelMap: v.optional(
547
+ // v.pipe(
548
+ // v.optional(ThinkingLevelMapSchema),
549
+ // v.title('思考等级配置'),
550
+ // v.description('各思考等级的具体参数配置映射'),
551
+ // ),
552
+ // ),
553
+ input: v3.pipe(
554
+ v3.optional(InputSchema, ["text", "image"]),
555
+ v3.title("输入类型"),
556
+ v3.description("支持的输入模态类型")
557
+ ),
558
+ cost: v3.pipe(
559
+ CostSchema,
560
+ v3.title("费用配置"),
561
+ v3.description("模型 token 计价标准")
562
+ ),
563
+ contextWindow: v3.pipe(
564
+ v3.pipe(v3.optional(v3.number(), 99999999)),
565
+ v3.title("上下文窗口"),
566
+ v3.description("模型支持的上下文最大 token 数")
567
+ ),
568
+ maxTokens: v3.pipe(
569
+ v3.pipe(v3.optional(v3.number(), 99999999)),
570
+ v3.title("最大输出 tokens"),
571
+ v3.description("单次请求允许的最大输出 token 数")
572
+ ),
573
+ headers: v3.optional(
574
+ v3.pipe(
575
+ v3.optional(HeadersSchema),
576
+ v3.title("自定义请求头"),
577
+ v3.description("额外的 HTTP 请求头配置")
578
+ )
579
+ ),
580
+ compat: v3.pipe(
581
+ v3.optional(CompatSchema, { supportsDeveloperRole: false }),
582
+ v3.title("兼容配置"),
583
+ v3.description("API 兼容性覆写选项")
584
+ )
585
+ }),
586
+ v3.title("模型定义"),
587
+ v3.description(
588
+ "pi-ai 模型的核心配置结构,包含模型标识、API 参数、费用及兼容性设置"
589
+ )
590
+ );
591
+ var OutputSchema = InputSchema;
592
+ var ModelConfigDefine = v3.pipe(
593
+ v3.object({
594
+ provider: KnownProviderDefine,
595
+ model: v3.pipe(v3.string(), v3.title("模型名")),
596
+ name: v3.pipe(
597
+ v3.optional(v3.string()),
598
+ v3.title("配置名"),
599
+ v3.description("模型的配置名称(默认为模型名)")
600
+ ),
601
+ /** provider是自定义时使用 */
602
+ apiKey: v3.pipe(v3.optional(v3.string()), v3.title("apiKey")),
603
+ config: v3.pipe(
604
+ v3.optional(ModelSchema),
605
+ (0, import_view_angular_core.hideWhen)({
606
+ disabled: true,
607
+ listen(fn, field) {
608
+ return fn({ list: [["..", "provider"]] }).pipe(
609
+ (0, import_rxjs.map)(
610
+ ({ list: [value] }) => !(value === "openai-completions" || value === "openai-responses" || value === "anthropic-messages")
611
+ )
612
+ );
613
+ }
614
+ })
615
+ )
616
+ }),
617
+ v3.transform((item) => ({ ...item, name: item.name ?? item.model }))
862
618
  );
863
619
 
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 = [];
620
+ // packages/openai/chat/chat.ts
621
+ var import_util = require("@cyia/util");
622
+ function createChatStream(input) {
623
+ const result = getModelConfig(input);
624
+ return (context, options, extra) => {
625
+ context.messages = (0, import_util.deepClone)(context.messages);
626
+ const sysIndex = context.messages.findIndex(
627
+ (item) => item.role === "system"
628
+ );
629
+ if (sysIndex !== -1) {
630
+ const item = context.messages[sysIndex];
631
+ context.messages.splice(sysIndex, 1);
632
+ context.systemPrompt = item.content[0].text;
633
+ }
634
+ const createStream = () => (0, import_pi_ai2.stream)(result.model, context, {
635
+ ...options,
636
+ apiKey: options?.apiKey ?? result.config.apiKey,
637
+ onPayload(payload, model) {
638
+ payload = options?.onPayload?.(payload, model) ?? payload;
639
+ if (model.api === "openai-completions") {
640
+ return {
641
+ ...payload,
642
+ response_format: extra?.response_format
643
+ };
901
644
  }
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);
645
+ return payload;
907
646
  }
908
647
  });
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
- };
934
-
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);
957
- }
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;
648
+ let currentStream = createStream();
649
+ const config = extra?.injector?.get(OpenAIConfigToken);
650
+ return (async function* () {
651
+ let hasRetry = false;
652
+ while (true) {
653
+ let retry = false;
654
+ for await (const item of currentStream) {
655
+ if (item.type === "error") {
656
+ if (item.error.errorMessage?.includes("404") && item.error.errorMessage?.includes(
657
+ "no router for requested model"
658
+ ) && !hasRetry) {
659
+ if (config?.().tryPull?.()) {
660
+ await config().pullModel?.(input.model);
661
+ retry = true;
662
+ break;
663
+ }
664
+ }
993
665
  }
666
+ yield item;
994
667
  }
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
- }
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;
668
+ if (!retry || hasRetry) {
669
+ break;
1022
670
  }
1023
- return obj;
1024
- },
1025
- callTool: (input2, options2) => instance.callTool(input2, options2)
1026
- };
1027
- }
1028
- };
671
+ hasRetry = true;
672
+ currentStream = createStream();
673
+ }
674
+ })();
675
+ };
676
+ }
1029
677
 
1030
- // packages/openai/chat/module.ts
1031
- var OPENAI_MODULE = {
1032
- provider: [ChatProviderService, ChatHistoryService],
1033
- token: { OpenAIConfigToken }
1034
- };
678
+ // packages/openai/index.ts
679
+ var import_pi_ai4 = require("@earendil-works/pi-ai");
680
+
681
+ // packages/openai/chat/util/faux-provider.ts
682
+ var import_pi_ai3 = require("@earendil-works/pi-ai");
683
+ function createDynamicResponse(responseFactory) {
684
+ return async (context, _options, state) => {
685
+ const responses = responseFactory(context, state.callCount);
686
+ const content = Array.isArray(responses) ? responses.map((r) => (0, import_pi_ai3.fauxText)(r)) : (0, import_pi_ai3.fauxText)(responses);
687
+ return (0, import_pi_ai3.fauxAssistantMessage)(content);
688
+ };
689
+ }
690
+ function registerMockProvider(options) {
691
+ const registration = (0, import_pi_ai3.registerFauxProvider)(options);
692
+ return {
693
+ model: registration.getModel(),
694
+ setResponses: (responses) => registration.setResponses(responses),
695
+ unregister: () => registration.unregister()
696
+ };
697
+ }
1035
698
  // Annotate the CommonJS export names for ESM import in node:
1036
699
  0 && (module.exports = {
700
+ AnthropicMessagesCompatSchema,
1037
701
  AssistantChatCompletionContent,
1038
702
  AssistantChatMessage,
1039
703
  ChatCompletionContentPart,
1040
704
  ChatCompletionContentPartImage,
1041
705
  ChatCompletionContentPartStr,
1042
- ChatHistoryService,
1043
- ChatItemDefine,
1044
706
  ChatMessageItemDefine,
1045
707
  ChatMessageListDefine,
1046
- ChatParamsItemDefine,
1047
- ChatParamsListDefine,
1048
- ChatProviderService,
1049
- InputChatOptionsDefine,
708
+ CompatSchema,
709
+ InputChoiceSchema,
710
+ InputSchema,
711
+ ModelConfigDefine,
712
+ ModelSchema,
713
+ ModelThinkingLevelSchema,
1050
714
  OPENAI_MODULE,
715
+ OpenAICompletionsCompatSchema,
1051
716
  OpenAIConfigToken,
717
+ OpenAIResponsesCompatSchema,
718
+ OutputSchema,
1052
719
  SystemChatCompletionContent,
1053
720
  SystemChatMessage,
721
+ ThinkingLevelSchema,
1054
722
  UserChatCompletionContent,
1055
723
  UserChatMessage,
1056
- VendorOptionsDefine,
724
+ complete,
1057
725
  createAssistantMessage,
726
+ createChatStream,
727
+ createDynamicResponse,
1058
728
  createSystemMessage,
1059
- createUserMessage
729
+ createUserMessage,
730
+ fauxAssistantMessage,
731
+ fauxText,
732
+ fauxThinking,
733
+ getModelConfig,
734
+ registerMockProvider,
735
+ stream
1060
736
  });
1061
737
  //# sourceMappingURL=index.js.map