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