@weisiren000/oiiai 0.1.2 → 0.1.4

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/dist/index.mjs CHANGED
@@ -1,36 +1,381 @@
1
+ // src/providers/openrouter.ts
2
+ import { OpenRouter } from "@openrouter/sdk";
3
+
4
+ // src/providers/__model-detection__.ts
5
+ var THINKING_MODEL_PATTERNS = [
6
+ // 明确的思考/推理标识
7
+ /[-_]think(?:ing)?(?:[-_:]|$)/i,
8
+ // *-think, *-thinking
9
+ /[-_]reason(?:ing)?(?:[-_:]|$)/i,
10
+ // *-reason, *-reasoning
11
+ /[-_]cot(?:[-_:]|$)/i,
12
+ // chain-of-thought
13
+ /[-_]reflect(?:ion)?(?:[-_:]|$)/i,
14
+ // reflection models
15
+ // 知名推理模型系列
16
+ /\bo1[-_]?/i,
17
+ // OpenAI o1 系列
18
+ /\bo3[-_]?/i,
19
+ // OpenAI o3 系列
20
+ /\br1[-_]?/i,
21
+ // DeepSeek R1 等
22
+ /\bqwq\b/i,
23
+ // Qwen QwQ
24
+ /\bn1[-_]?/i,
25
+ // nex-n1 等
26
+ // 通用思考关键词(较低优先级)
27
+ /think/i
28
+ // 包含 think
29
+ ];
30
+ var DIRECT_ANSWER_PATTERNS = [
31
+ /[-_]chat$/i,
32
+ // *-chat (结尾)
33
+ /[-_]instruct/i,
34
+ // *-instruct
35
+ /[-_]turbo/i,
36
+ // *-turbo
37
+ /[-_]flash/i,
38
+ // gemini-flash 等快速模型
39
+ /[-_]lite[-_v]/i,
40
+ // lite 版本(但不匹配 lite 结尾,避免误判)
41
+ /[-_]fast/i
42
+ // fast 模型
43
+ ];
44
+ var PROBLEMATIC_MODEL_PATTERNS = [
45
+ /nova[-_]?\d*[-_]lite/i
46
+ // Amazon Nova Lite 系列
47
+ ];
48
+ function isProblematicModel(modelId) {
49
+ return PROBLEMATIC_MODEL_PATTERNS.some((pattern) => pattern.test(modelId));
50
+ }
51
+ function detectByModelName(modelId) {
52
+ const normalizedId = modelId.toLowerCase();
53
+ const isThinkingPattern = THINKING_MODEL_PATTERNS.some(
54
+ (pattern) => pattern.test(normalizedId)
55
+ );
56
+ const isDirectPattern = DIRECT_ANSWER_PATTERNS.some(
57
+ (pattern) => pattern.test(normalizedId)
58
+ );
59
+ const isProblematic = isProblematicModel(normalizedId);
60
+ if (isThinkingPattern) {
61
+ return {
62
+ behavior: "thinking-first",
63
+ supportsReasoningConfig: true,
64
+ recommendedMinTokens: 500,
65
+ confidence: 0.7,
66
+ detectedBy: "pattern"
67
+ };
68
+ }
69
+ if (isDirectPattern) {
70
+ return {
71
+ behavior: "direct-answer",
72
+ supportsReasoningConfig: false,
73
+ // 问题模型需要更多 token
74
+ recommendedMinTokens: isProblematic ? 300 : 100,
75
+ confidence: 0.6,
76
+ detectedBy: "pattern"
77
+ };
78
+ }
79
+ return {
80
+ behavior: "unknown",
81
+ supportsReasoningConfig: false,
82
+ recommendedMinTokens: isProblematic ? 300 : 200,
83
+ confidence: 0.3,
84
+ detectedBy: "pattern"
85
+ };
86
+ }
87
+ var modelCharacteristicsCache = /* @__PURE__ */ new Map();
88
+ function detectByResponse(modelId, result) {
89
+ const hasReasoning = !!result.reasoning && result.reasoning.length > 0;
90
+ const hasContent = !!result.content && result.content.trim().length > 0;
91
+ const reasoningLength = result.reasoning?.length ?? 0;
92
+ const contentLength = result.content?.length ?? 0;
93
+ let behavior;
94
+ let supportsReasoningConfig = false;
95
+ let recommendedMinTokens = 200;
96
+ if (hasReasoning && !hasContent) {
97
+ behavior = "thinking-first";
98
+ supportsReasoningConfig = true;
99
+ recommendedMinTokens = Math.max(500, reasoningLength + 200);
100
+ } else if (hasReasoning && hasContent) {
101
+ if (reasoningLength > contentLength * 2) {
102
+ behavior = "thinking-first";
103
+ supportsReasoningConfig = true;
104
+ recommendedMinTokens = 500;
105
+ } else {
106
+ behavior = "hybrid";
107
+ supportsReasoningConfig = true;
108
+ recommendedMinTokens = 300;
109
+ }
110
+ } else if (hasContent && !hasReasoning) {
111
+ behavior = "direct-answer";
112
+ supportsReasoningConfig = false;
113
+ recommendedMinTokens = 100;
114
+ } else {
115
+ behavior = "unknown";
116
+ recommendedMinTokens = 500;
117
+ }
118
+ const characteristics = {
119
+ behavior,
120
+ supportsReasoningConfig,
121
+ recommendedMinTokens,
122
+ confidence: 0.9,
123
+ detectedBy: "runtime"
124
+ };
125
+ modelCharacteristicsCache.set(modelId, characteristics);
126
+ return characteristics;
127
+ }
128
+ function getModelCharacteristics(modelId) {
129
+ const cached = modelCharacteristicsCache.get(modelId);
130
+ if (cached) {
131
+ return { ...cached, detectedBy: "cache" };
132
+ }
133
+ return detectByModelName(modelId);
134
+ }
135
+ var DEFAULT_FALLBACK_CONFIG = {
136
+ enabled: true,
137
+ returnReasoningAsContent: true,
138
+ extractConclusionFromReasoning: true,
139
+ autoRetryWithMoreTokens: false,
140
+ // 默认关闭自动重试,避免额外消耗
141
+ retryTokenIncrement: 300,
142
+ maxRetries: 2
143
+ };
144
+ function extractConclusionFromReasoning(reasoning) {
145
+ if (!reasoning) return null;
146
+ const conclusionPatterns = [
147
+ /(?:therefore|thus|so|hence|finally|in conclusion|the answer is|result is)[:\s]*(.+?)(?:\n|$)/i,
148
+ /(?:答案是|结论是|因此|所以|最终)[::\s]*(.+?)(?:\n|$)/,
149
+ /(?:\*\*answer\*\*|\*\*result\*\*)[:\s]*(.+?)(?:\n|$)/i,
150
+ /=\s*(.+?)(?:\n|$)/
151
+ // 数学等式结果
152
+ ];
153
+ for (const pattern of conclusionPatterns) {
154
+ const match = reasoning.match(pattern);
155
+ if (match && match[1]) {
156
+ return match[1].trim();
157
+ }
158
+ }
159
+ const paragraphs = reasoning.split(/\n\n+/).filter((p) => p.trim());
160
+ if (paragraphs.length > 0) {
161
+ const lastParagraph = paragraphs[paragraphs.length - 1].trim();
162
+ if (lastParagraph.length < 500) {
163
+ return lastParagraph;
164
+ }
165
+ }
166
+ return null;
167
+ }
168
+ function applyFallbackStrategy(result, config = {}) {
169
+ const finalConfig = { ...DEFAULT_FALLBACK_CONFIG, ...config };
170
+ if (result.content && result.content.trim().length > 0) {
171
+ return {
172
+ content: result.content,
173
+ didFallback: false,
174
+ originalReasoning: result.reasoning
175
+ };
176
+ }
177
+ if (!finalConfig.enabled) {
178
+ return {
179
+ content: "",
180
+ didFallback: false,
181
+ originalReasoning: result.reasoning
182
+ };
183
+ }
184
+ if (finalConfig.extractConclusionFromReasoning && result.reasoning) {
185
+ const conclusion = extractConclusionFromReasoning(result.reasoning);
186
+ if (conclusion) {
187
+ return {
188
+ content: conclusion,
189
+ didFallback: true,
190
+ fallbackReason: "extracted_conclusion_from_reasoning",
191
+ originalReasoning: result.reasoning
192
+ };
193
+ }
194
+ }
195
+ if (finalConfig.returnReasoningAsContent && result.reasoning) {
196
+ return {
197
+ content: result.reasoning,
198
+ didFallback: true,
199
+ fallbackReason: "returned_reasoning_as_content",
200
+ originalReasoning: result.reasoning
201
+ };
202
+ }
203
+ return {
204
+ content: "",
205
+ didFallback: false,
206
+ fallbackReason: "no_fallback_available",
207
+ originalReasoning: result.reasoning
208
+ };
209
+ }
210
+ function adjustOptionsForModel(modelId, options) {
211
+ const characteristics = getModelCharacteristics(modelId);
212
+ if (characteristics.behavior === "thinking-first" && (!options.maxTokens || options.maxTokens < characteristics.recommendedMinTokens)) {
213
+ return {
214
+ ...options,
215
+ maxTokens: Math.max(
216
+ options.maxTokens ?? 0,
217
+ characteristics.recommendedMinTokens
218
+ )
219
+ };
220
+ }
221
+ return options;
222
+ }
223
+ function getRecommendedConfig(modelId, scenario = "simple") {
224
+ const characteristics = getModelCharacteristics(modelId);
225
+ if (characteristics.behavior !== "thinking-first") {
226
+ return {};
227
+ }
228
+ const configs = {
229
+ simple: {
230
+ maxTokens: 300,
231
+ reasoning: { effort: "low" }
232
+ },
233
+ math: {
234
+ maxTokens: 600,
235
+ reasoning: { effort: "high" }
236
+ },
237
+ reasoning: {
238
+ maxTokens: 800,
239
+ reasoning: { effort: "medium" }
240
+ },
241
+ fast: {
242
+ maxTokens: 200,
243
+ reasoning: { effort: "off" }
244
+ }
245
+ };
246
+ return configs[scenario] ?? configs.simple;
247
+ }
248
+ var ModelDetection = {
249
+ detectByModelName,
250
+ detectByResponse,
251
+ getModelCharacteristics,
252
+ applyFallbackStrategy,
253
+ adjustOptionsForModel,
254
+ getRecommendedConfig,
255
+ extractConclusionFromReasoning,
256
+ isProblematicModel,
257
+ clearCache: () => modelCharacteristicsCache.clear()
258
+ };
259
+
1
260
  // src/providers/__base__.ts
2
261
  var BaseProvider = class {
262
+ /** 降级策略配置 */
263
+ fallbackConfig = DEFAULT_FALLBACK_CONFIG;
264
+ /** 是否启用自动参数调整 */
265
+ autoAdjustEnabled = true;
266
+ /**
267
+ * 配置降级策略
268
+ */
269
+ configureFallback(config) {
270
+ this.fallbackConfig = { ...this.fallbackConfig, ...config };
271
+ return this;
272
+ }
273
+ /**
274
+ * 启用/禁用自动参数调整
275
+ */
276
+ setAutoAdjust(enabled) {
277
+ this.autoAdjustEnabled = enabled;
278
+ return this;
279
+ }
280
+ /**
281
+ * 获取模型特性信息
282
+ */
283
+ getModelCharacteristics(modelId) {
284
+ return ModelDetection.getModelCharacteristics(modelId);
285
+ }
286
+ /**
287
+ * 智能聊天:自动检测模型特性并应用降级策略
288
+ */
289
+ async chatSmart(options) {
290
+ const adjustedOptions = this.autoAdjustEnabled ? ModelDetection.adjustOptionsForModel(options.model, options) : options;
291
+ const result = await this.chat(adjustedOptions);
292
+ ModelDetection.detectByResponse(options.model, result);
293
+ return result;
294
+ }
3
295
  /**
4
296
  * 简单对话:单轮问答(默认实现)
5
- * 对于思考模型,如果 content 为空则返回 reasoning
297
+ *
298
+ * 智能处理思考模型:
299
+ * 1. 自动检测模型类型
300
+ * 2. 为思考模型自动调整 maxTokens
301
+ * 3. 如果 content 为空,智能降级(提取结论或返回 reasoning)
6
302
  */
7
303
  async ask(model, question, options) {
8
- const result = await this.chat({
304
+ const { fallback, autoAdjust = this.autoAdjustEnabled, ...chatOptions } = options ?? {};
305
+ let finalOptions = {
9
306
  model,
10
307
  messages: [{ role: "user", content: question }],
11
- ...options
308
+ ...chatOptions
309
+ };
310
+ if (autoAdjust) {
311
+ finalOptions = ModelDetection.adjustOptionsForModel(model, finalOptions);
312
+ }
313
+ const result = await this.chat(finalOptions);
314
+ ModelDetection.detectByResponse(model, result);
315
+ const fallbackResult = ModelDetection.applyFallbackStrategy(result, {
316
+ ...this.fallbackConfig,
317
+ ...fallback
12
318
  });
13
- return result.content || result.reasoning || "";
319
+ return fallbackResult.content;
14
320
  }
15
321
  /**
16
322
  * 带系统提示的对话(默认实现)
17
- * 对于思考模型,如果 content 为空则返回 reasoning
323
+ *
324
+ * 智能处理思考模型:
325
+ * 1. 自动检测模型类型
326
+ * 2. 为思考模型自动调整 maxTokens
327
+ * 3. 如果 content 为空,智能降级(提取结论或返回 reasoning)
18
328
  */
19
329
  async askWithSystem(model, systemPrompt, userMessage, options) {
20
- const result = await this.chat({
330
+ const { fallback, autoAdjust = this.autoAdjustEnabled, ...chatOptions } = options ?? {};
331
+ let finalOptions = {
21
332
  model,
22
333
  messages: [
23
334
  { role: "system", content: systemPrompt },
24
335
  { role: "user", content: userMessage }
25
336
  ],
337
+ ...chatOptions
338
+ };
339
+ if (autoAdjust) {
340
+ finalOptions = ModelDetection.adjustOptionsForModel(model, finalOptions);
341
+ }
342
+ const result = await this.chat(finalOptions);
343
+ ModelDetection.detectByResponse(model, result);
344
+ const fallbackResult = ModelDetection.applyFallbackStrategy(result, {
345
+ ...this.fallbackConfig,
346
+ ...fallback
347
+ });
348
+ return fallbackResult.content;
349
+ }
350
+ /**
351
+ * 场景化问答:根据场景自动配置参数
352
+ *
353
+ * @param model 模型 ID
354
+ * @param question 问题
355
+ * @param scenario 场景类型
356
+ * - 'simple': 简单问答(默认)
357
+ * - 'math': 数学计算
358
+ * - 'reasoning': 逻辑推理
359
+ * - 'fast': 快速回答(关闭思考)
360
+ */
361
+ async askWithScenario(model, question, scenario = "simple", options) {
362
+ const recommendedConfig = ModelDetection.getRecommendedConfig(model, scenario);
363
+ return this.ask(model, question, {
364
+ ...recommendedConfig,
26
365
  ...options
27
366
  });
28
- return result.content || result.reasoning || "";
29
367
  }
30
368
  };
31
369
 
370
+ // src/providers/__types__.ts
371
+ var EFFORT_TOKEN_MAP = {
372
+ off: 0,
373
+ low: 1024,
374
+ medium: 4096,
375
+ high: 16384
376
+ };
377
+
32
378
  // src/providers/openrouter.ts
33
- import { OpenRouter } from "@openrouter/sdk";
34
379
  function extractTextContent(content) {
35
380
  if (typeof content === "string") {
36
381
  return content;
@@ -44,19 +389,19 @@ function extractTextContent(content) {
44
389
  }
45
390
  function buildReasoningParam(config) {
46
391
  if (!config) return void 0;
392
+ if (config.effort === "off") return void 0;
47
393
  const param = {};
48
- if (config.effort !== void 0) {
394
+ if (config.effort) {
49
395
  param.effort = config.effort;
50
396
  }
51
- if (config.maxTokens !== void 0) {
52
- param.max_tokens = config.maxTokens;
397
+ if (config.budgetTokens !== void 0) {
398
+ param.max_tokens = config.budgetTokens;
399
+ } else if (config.effort && EFFORT_TOKEN_MAP[config.effort]) {
400
+ param.max_tokens = EFFORT_TOKEN_MAP[config.effort];
53
401
  }
54
402
  if (config.exclude !== void 0) {
55
403
  param.exclude = config.exclude;
56
404
  }
57
- if (config.enabled !== void 0) {
58
- param.enabled = config.enabled;
59
- }
60
405
  return Object.keys(param).length > 0 ? param : void 0;
61
406
  }
62
407
  var OpenRouterProvider = class extends BaseProvider {
@@ -70,7 +415,13 @@ var OpenRouterProvider = class extends BaseProvider {
70
415
  * 发送聊天请求(非流式)
71
416
  */
72
417
  async chat(options) {
73
- const { model, messages, temperature = 0.7, maxTokens, reasoning } = options;
418
+ const {
419
+ model,
420
+ messages,
421
+ temperature = 0.7,
422
+ maxTokens,
423
+ reasoning
424
+ } = options;
74
425
  const reasoningParam = buildReasoningParam(reasoning);
75
426
  const requestParams = {
76
427
  model,
@@ -105,7 +456,13 @@ var OpenRouterProvider = class extends BaseProvider {
105
456
  * 发送流式聊天请求
106
457
  */
107
458
  async *chatStream(options) {
108
- const { model, messages, temperature = 0.7, maxTokens, reasoning } = options;
459
+ const {
460
+ model,
461
+ messages,
462
+ temperature = 0.7,
463
+ maxTokens,
464
+ reasoning
465
+ } = options;
109
466
  const reasoningParam = buildReasoningParam(reasoning);
110
467
  const requestParams = {
111
468
  model,
@@ -117,7 +474,9 @@ var OpenRouterProvider = class extends BaseProvider {
117
474
  if (reasoningParam) {
118
475
  requestParams.reasoning = reasoningParam;
119
476
  }
120
- const stream = await this.client.chat.send(requestParams);
477
+ const stream = await this.client.chat.send(
478
+ requestParams
479
+ );
121
480
  for await (const chunk of stream) {
122
481
  const delta = chunk.choices?.[0]?.delta;
123
482
  if (!delta) continue;
@@ -159,8 +518,1271 @@ var OpenRouterProvider = class extends BaseProvider {
159
518
  }));
160
519
  }
161
520
  };
521
+
522
+ // src/providers/gemini.ts
523
+ var BASE_URL = "https://generativelanguage.googleapis.com/v1beta/openai";
524
+ function extractTextContent2(content) {
525
+ if (typeof content === "string") {
526
+ return content;
527
+ }
528
+ if (Array.isArray(content)) {
529
+ return content.filter(
530
+ (item) => typeof item === "object" && item !== null && item.type === "text" && typeof item.text === "string"
531
+ ).map((item) => item.text).join("");
532
+ }
533
+ return "";
534
+ }
535
+ var GeminiProvider = class extends BaseProvider {
536
+ name = "gemini";
537
+ apiKey;
538
+ baseUrl;
539
+ constructor(config) {
540
+ super();
541
+ if (typeof config === "string") {
542
+ this.apiKey = config;
543
+ this.baseUrl = BASE_URL;
544
+ } else {
545
+ this.apiKey = config.apiKey;
546
+ this.baseUrl = config.baseUrl ?? BASE_URL;
547
+ }
548
+ }
549
+ /**
550
+ * 发送聊天请求(非流式)
551
+ */
552
+ async chat(options) {
553
+ const {
554
+ model,
555
+ messages,
556
+ temperature = 0.7,
557
+ maxTokens,
558
+ reasoning
559
+ } = options;
560
+ const body = {
561
+ model,
562
+ messages,
563
+ temperature,
564
+ stream: false
565
+ };
566
+ if (maxTokens) {
567
+ body.max_tokens = maxTokens;
568
+ }
569
+ if (reasoning?.effort && reasoning.effort !== "off") {
570
+ body.reasoning_effort = reasoning.effort;
571
+ }
572
+ const response = await fetch(`${this.baseUrl}/chat/completions`, {
573
+ method: "POST",
574
+ headers: {
575
+ "Content-Type": "application/json",
576
+ Authorization: `Bearer ${this.apiKey}`
577
+ },
578
+ body: JSON.stringify(body)
579
+ });
580
+ if (!response.ok) {
581
+ const error = await response.text();
582
+ throw new Error(`Gemini API error: ${response.status} ${error}`);
583
+ }
584
+ const result = await response.json();
585
+ const choice = result.choices?.[0];
586
+ if (!choice) {
587
+ throw new Error("No response from model");
588
+ }
589
+ const msg = choice.message;
590
+ const reasoningContent = msg?.reasoning_content ?? null;
591
+ return {
592
+ content: extractTextContent2(msg?.content),
593
+ reasoning: reasoningContent ? extractTextContent2(reasoningContent) : null,
594
+ model: result.model ?? model,
595
+ usage: {
596
+ promptTokens: result.usage?.prompt_tokens ?? 0,
597
+ completionTokens: result.usage?.completion_tokens ?? 0,
598
+ totalTokens: result.usage?.total_tokens ?? 0
599
+ },
600
+ finishReason: choice.finish_reason ?? null
601
+ };
602
+ }
603
+ /**
604
+ * 发送流式聊天请求
605
+ */
606
+ async *chatStream(options) {
607
+ const {
608
+ model,
609
+ messages,
610
+ temperature = 0.7,
611
+ maxTokens,
612
+ reasoning
613
+ } = options;
614
+ const body = {
615
+ model,
616
+ messages,
617
+ temperature,
618
+ stream: true
619
+ };
620
+ if (maxTokens) {
621
+ body.max_tokens = maxTokens;
622
+ }
623
+ if (reasoning?.effort && reasoning.effort !== "off") {
624
+ body.reasoning_effort = reasoning.effort;
625
+ }
626
+ const response = await fetch(`${this.baseUrl}/chat/completions`, {
627
+ method: "POST",
628
+ headers: {
629
+ "Content-Type": "application/json",
630
+ Authorization: `Bearer ${this.apiKey}`
631
+ },
632
+ body: JSON.stringify(body)
633
+ });
634
+ if (!response.ok) {
635
+ const error = await response.text();
636
+ throw new Error(`Gemini API error: ${response.status} ${error}`);
637
+ }
638
+ const reader = response.body?.getReader();
639
+ if (!reader) {
640
+ throw new Error("No response body");
641
+ }
642
+ const decoder = new TextDecoder();
643
+ let buffer = "";
644
+ try {
645
+ while (true) {
646
+ const { done, value } = await reader.read();
647
+ if (done) break;
648
+ buffer += decoder.decode(value, { stream: true });
649
+ const lines = buffer.split("\n");
650
+ buffer = lines.pop() ?? "";
651
+ for (const line of lines) {
652
+ const trimmed = line.trim();
653
+ if (!trimmed || trimmed === "data: [DONE]") continue;
654
+ if (!trimmed.startsWith("data: ")) continue;
655
+ try {
656
+ const data = JSON.parse(trimmed.slice(6));
657
+ const delta = data.choices?.[0]?.delta;
658
+ if (!delta) continue;
659
+ const thought = delta.reasoning_content ?? delta.thoughts;
660
+ if (thought) {
661
+ yield {
662
+ type: "reasoning",
663
+ text: extractTextContent2(thought)
664
+ };
665
+ }
666
+ if (delta.content) {
667
+ yield {
668
+ type: "content",
669
+ text: extractTextContent2(delta.content)
670
+ };
671
+ }
672
+ } catch {
673
+ }
674
+ }
675
+ }
676
+ } finally {
677
+ reader.releaseLock();
678
+ }
679
+ }
680
+ };
681
+
682
+ // src/providers/groq.ts
683
+ var BASE_URL2 = "https://api.groq.com/openai/v1";
684
+ function extractTextContent3(content) {
685
+ if (typeof content === "string") {
686
+ return content;
687
+ }
688
+ if (Array.isArray(content)) {
689
+ return content.filter(
690
+ (item) => typeof item === "object" && item !== null && item.type === "text" && typeof item.text === "string"
691
+ ).map((item) => item.text).join("");
692
+ }
693
+ return "";
694
+ }
695
+ var GroqProvider = class extends BaseProvider {
696
+ name = "groq";
697
+ apiKey;
698
+ baseUrl;
699
+ constructor(config) {
700
+ super();
701
+ if (typeof config === "string") {
702
+ this.apiKey = config;
703
+ this.baseUrl = BASE_URL2;
704
+ } else {
705
+ this.apiKey = config.apiKey;
706
+ this.baseUrl = config.baseUrl ?? BASE_URL2;
707
+ }
708
+ }
709
+ /**
710
+ * 发送聊天请求(非流式)
711
+ */
712
+ async chat(options) {
713
+ const { model, messages, temperature = 1, maxTokens, reasoning } = options;
714
+ const body = {
715
+ model,
716
+ messages,
717
+ temperature,
718
+ stream: false,
719
+ top_p: 1
720
+ };
721
+ if (maxTokens) {
722
+ body.max_completion_tokens = maxTokens;
723
+ }
724
+ if (reasoning?.effort && reasoning.effort !== "off") {
725
+ body.reasoning_format = "parsed";
726
+ } else if (reasoning?.effort === "off") {
727
+ body.include_reasoning = false;
728
+ }
729
+ const response = await fetch(`${this.baseUrl}/chat/completions`, {
730
+ method: "POST",
731
+ headers: {
732
+ "Content-Type": "application/json",
733
+ Authorization: `Bearer ${this.apiKey}`
734
+ },
735
+ body: JSON.stringify(body)
736
+ });
737
+ if (!response.ok) {
738
+ const error = await response.text();
739
+ throw new Error(`Groq API error: ${response.status} ${error}`);
740
+ }
741
+ const result = await response.json();
742
+ const choice = result.choices?.[0];
743
+ if (!choice) {
744
+ throw new Error("No response from model");
745
+ }
746
+ const msg = choice.message;
747
+ const reasoningContent = msg?.reasoning_content ?? msg?.reasoning ?? null;
748
+ return {
749
+ content: extractTextContent3(msg?.content),
750
+ reasoning: reasoningContent ? extractTextContent3(reasoningContent) : null,
751
+ model: result.model ?? model,
752
+ usage: {
753
+ promptTokens: result.usage?.prompt_tokens ?? 0,
754
+ completionTokens: result.usage?.completion_tokens ?? 0,
755
+ totalTokens: result.usage?.total_tokens ?? 0
756
+ },
757
+ finishReason: choice.finish_reason ?? null
758
+ };
759
+ }
760
+ /**
761
+ * 发送流式聊天请求
762
+ */
763
+ async *chatStream(options) {
764
+ const { model, messages, temperature = 1, maxTokens, reasoning } = options;
765
+ const body = {
766
+ model,
767
+ messages,
768
+ temperature,
769
+ stream: true,
770
+ top_p: 1
771
+ };
772
+ if (maxTokens) {
773
+ body.max_completion_tokens = maxTokens;
774
+ }
775
+ if (reasoning?.effort && reasoning.effort !== "off") {
776
+ body.reasoning_format = "parsed";
777
+ } else if (reasoning?.effort === "off") {
778
+ body.include_reasoning = false;
779
+ }
780
+ const response = await fetch(`${this.baseUrl}/chat/completions`, {
781
+ method: "POST",
782
+ headers: {
783
+ "Content-Type": "application/json",
784
+ Authorization: `Bearer ${this.apiKey}`
785
+ },
786
+ body: JSON.stringify(body)
787
+ });
788
+ if (!response.ok) {
789
+ const error = await response.text();
790
+ throw new Error(`Groq API error: ${response.status} ${error}`);
791
+ }
792
+ const reader = response.body?.getReader();
793
+ if (!reader) {
794
+ throw new Error("No response body");
795
+ }
796
+ const decoder = new TextDecoder();
797
+ let buffer = "";
798
+ try {
799
+ while (true) {
800
+ const { done, value } = await reader.read();
801
+ if (done) break;
802
+ buffer += decoder.decode(value, { stream: true });
803
+ const lines = buffer.split("\n");
804
+ buffer = lines.pop() ?? "";
805
+ for (const line of lines) {
806
+ const trimmed = line.trim();
807
+ if (!trimmed || trimmed === "data: [DONE]") continue;
808
+ if (!trimmed.startsWith("data: ")) continue;
809
+ try {
810
+ const data = JSON.parse(trimmed.slice(6));
811
+ const delta = data.choices?.[0]?.delta;
812
+ if (!delta) continue;
813
+ const reasoningContent = delta.reasoning_content ?? delta.reasoning;
814
+ if (reasoningContent) {
815
+ yield {
816
+ type: "reasoning",
817
+ text: extractTextContent3(reasoningContent)
818
+ };
819
+ }
820
+ if (delta.content) {
821
+ yield {
822
+ type: "content",
823
+ text: extractTextContent3(delta.content)
824
+ };
825
+ }
826
+ } catch {
827
+ }
828
+ }
829
+ }
830
+ } finally {
831
+ reader.releaseLock();
832
+ }
833
+ }
834
+ };
835
+
836
+ // src/providers/huggingface.ts
837
+ var BASE_URL3 = "https://router.huggingface.co/v1";
838
+ function extractTextContent4(content) {
839
+ if (typeof content === "string") {
840
+ return content;
841
+ }
842
+ if (Array.isArray(content)) {
843
+ return content.filter(
844
+ (item) => typeof item === "object" && item !== null && item.type === "text" && typeof item.text === "string"
845
+ ).map((item) => item.text).join("");
846
+ }
847
+ return "";
848
+ }
849
+ var HuggingFaceProvider = class extends BaseProvider {
850
+ name = "huggingface";
851
+ apiKey;
852
+ baseUrl;
853
+ constructor(config) {
854
+ super();
855
+ if (typeof config === "string") {
856
+ this.apiKey = config;
857
+ this.baseUrl = BASE_URL3;
858
+ } else {
859
+ this.apiKey = config.apiKey;
860
+ this.baseUrl = config.baseUrl ?? BASE_URL3;
861
+ }
862
+ }
863
+ /**
864
+ * 发送聊天请求(非流式)
865
+ *
866
+ * reasoning 参数说明:
867
+ * - HuggingFace 是模型聚合平台,thinking 支持取决于具体模型
868
+ * - 如果模型支持,会返回 reasoning_content
869
+ */
870
+ async chat(options) {
871
+ const { model, messages, temperature = 0.7, maxTokens, reasoning } = options;
872
+ const body = {
873
+ model,
874
+ messages,
875
+ temperature,
876
+ stream: false
877
+ };
878
+ if (maxTokens) {
879
+ body.max_tokens = maxTokens;
880
+ }
881
+ if (reasoning?.effort && reasoning.effort !== "off") {
882
+ body.reasoning_effort = reasoning.effort;
883
+ }
884
+ const response = await fetch(`${this.baseUrl}/chat/completions`, {
885
+ method: "POST",
886
+ headers: {
887
+ "Content-Type": "application/json",
888
+ Authorization: `Bearer ${this.apiKey}`
889
+ },
890
+ body: JSON.stringify(body)
891
+ });
892
+ if (!response.ok) {
893
+ const error = await response.text();
894
+ throw new Error(`HuggingFace API error: ${response.status} ${error}`);
895
+ }
896
+ const result = await response.json();
897
+ const choice = result.choices?.[0];
898
+ if (!choice) {
899
+ throw new Error("No response from model");
900
+ }
901
+ const msg = choice.message;
902
+ const reasoningContent = msg?.reasoning_content ?? null;
903
+ return {
904
+ content: extractTextContent4(msg?.content),
905
+ reasoning: reasoningContent ? extractTextContent4(reasoningContent) : null,
906
+ model: result.model ?? model,
907
+ usage: {
908
+ promptTokens: result.usage?.prompt_tokens ?? 0,
909
+ completionTokens: result.usage?.completion_tokens ?? 0,
910
+ totalTokens: result.usage?.total_tokens ?? 0
911
+ },
912
+ finishReason: choice.finish_reason ?? null
913
+ };
914
+ }
915
+ /**
916
+ * 发送流式聊天请求
917
+ */
918
+ async *chatStream(options) {
919
+ const { model, messages, temperature = 0.7, maxTokens, reasoning } = options;
920
+ const body = {
921
+ model,
922
+ messages,
923
+ temperature,
924
+ stream: true
925
+ };
926
+ if (maxTokens) {
927
+ body.max_tokens = maxTokens;
928
+ }
929
+ if (reasoning?.effort && reasoning.effort !== "off") {
930
+ body.reasoning_effort = reasoning.effort;
931
+ }
932
+ const response = await fetch(`${this.baseUrl}/chat/completions`, {
933
+ method: "POST",
934
+ headers: {
935
+ "Content-Type": "application/json",
936
+ Authorization: `Bearer ${this.apiKey}`
937
+ },
938
+ body: JSON.stringify(body)
939
+ });
940
+ if (!response.ok) {
941
+ const error = await response.text();
942
+ throw new Error(`HuggingFace API error: ${response.status} ${error}`);
943
+ }
944
+ const reader = response.body?.getReader();
945
+ if (!reader) {
946
+ throw new Error("No response body");
947
+ }
948
+ const decoder = new TextDecoder();
949
+ let buffer = "";
950
+ try {
951
+ while (true) {
952
+ const { done, value } = await reader.read();
953
+ if (done) break;
954
+ buffer += decoder.decode(value, { stream: true });
955
+ const lines = buffer.split("\n");
956
+ buffer = lines.pop() ?? "";
957
+ for (const line of lines) {
958
+ const trimmed = line.trim();
959
+ if (!trimmed || trimmed === "data: [DONE]") continue;
960
+ if (!trimmed.startsWith("data: ")) continue;
961
+ try {
962
+ const data = JSON.parse(trimmed.slice(6));
963
+ const delta = data.choices?.[0]?.delta;
964
+ if (!delta) continue;
965
+ if (delta.reasoning_content) {
966
+ yield {
967
+ type: "reasoning",
968
+ text: extractTextContent4(delta.reasoning_content)
969
+ };
970
+ }
971
+ if (delta.content) {
972
+ yield {
973
+ type: "content",
974
+ text: extractTextContent4(delta.content)
975
+ };
976
+ }
977
+ } catch {
978
+ }
979
+ }
980
+ }
981
+ } finally {
982
+ reader.releaseLock();
983
+ }
984
+ }
985
+ };
986
+
987
+ // src/providers/modelscope.ts
988
+ var BASE_URL4 = "https://api-inference.modelscope.cn/v1";
989
+ function extractTextContent5(content) {
990
+ if (typeof content === "string") {
991
+ return content;
992
+ }
993
+ if (Array.isArray(content)) {
994
+ return content.filter(
995
+ (item) => typeof item === "object" && item !== null && item.type === "text" && typeof item.text === "string"
996
+ ).map((item) => item.text).join("");
997
+ }
998
+ return "";
999
+ }
1000
+ var ModelScopeProvider = class extends BaseProvider {
1001
+ name = "modelscope";
1002
+ apiKey;
1003
+ baseUrl;
1004
+ constructor(config) {
1005
+ super();
1006
+ if (typeof config === "string") {
1007
+ this.apiKey = config;
1008
+ this.baseUrl = BASE_URL4;
1009
+ } else {
1010
+ this.apiKey = config.apiKey;
1011
+ this.baseUrl = config.baseUrl ?? BASE_URL4;
1012
+ }
1013
+ }
1014
+ /**
1015
+ * 发送聊天请求(非流式)
1016
+ */
1017
+ async chat(options) {
1018
+ const {
1019
+ model,
1020
+ messages,
1021
+ temperature = 0.7,
1022
+ maxTokens,
1023
+ reasoning
1024
+ } = options;
1025
+ const body = {
1026
+ model,
1027
+ messages,
1028
+ temperature,
1029
+ stream: false
1030
+ };
1031
+ if (maxTokens) {
1032
+ body.max_tokens = maxTokens;
1033
+ }
1034
+ if (reasoning?.effort) {
1035
+ if (reasoning.effort === "off") {
1036
+ body.enable_thinking = false;
1037
+ } else {
1038
+ body.enable_thinking = true;
1039
+ }
1040
+ }
1041
+ const response = await fetch(`${this.baseUrl}/chat/completions`, {
1042
+ method: "POST",
1043
+ headers: {
1044
+ "Content-Type": "application/json",
1045
+ Authorization: `Bearer ${this.apiKey}`
1046
+ },
1047
+ body: JSON.stringify(body)
1048
+ });
1049
+ if (!response.ok) {
1050
+ const error = await response.text();
1051
+ throw new Error(`ModelScope API error: ${response.status} ${error}`);
1052
+ }
1053
+ const result = await response.json();
1054
+ const choice = result.choices?.[0];
1055
+ if (!choice) {
1056
+ throw new Error("No response from model");
1057
+ }
1058
+ const msg = choice.message;
1059
+ const reasoningContent = msg?.reasoning_content ?? null;
1060
+ return {
1061
+ content: extractTextContent5(msg?.content),
1062
+ reasoning: reasoningContent ? extractTextContent5(reasoningContent) : null,
1063
+ model: result.model ?? model,
1064
+ usage: {
1065
+ promptTokens: result.usage?.prompt_tokens ?? 0,
1066
+ completionTokens: result.usage?.completion_tokens ?? 0,
1067
+ totalTokens: result.usage?.total_tokens ?? 0
1068
+ },
1069
+ finishReason: choice.finish_reason ?? null
1070
+ };
1071
+ }
1072
+ /**
1073
+ * 发送流式聊天请求
1074
+ */
1075
+ async *chatStream(options) {
1076
+ const {
1077
+ model,
1078
+ messages,
1079
+ temperature = 0.7,
1080
+ maxTokens,
1081
+ reasoning
1082
+ } = options;
1083
+ const body = {
1084
+ model,
1085
+ messages,
1086
+ temperature,
1087
+ stream: true
1088
+ };
1089
+ if (maxTokens) {
1090
+ body.max_tokens = maxTokens;
1091
+ }
1092
+ if (reasoning?.effort) {
1093
+ if (reasoning.effort === "off") {
1094
+ body.enable_thinking = false;
1095
+ } else {
1096
+ body.enable_thinking = true;
1097
+ }
1098
+ }
1099
+ const response = await fetch(`${this.baseUrl}/chat/completions`, {
1100
+ method: "POST",
1101
+ headers: {
1102
+ "Content-Type": "application/json",
1103
+ Authorization: `Bearer ${this.apiKey}`
1104
+ },
1105
+ body: JSON.stringify(body)
1106
+ });
1107
+ if (!response.ok) {
1108
+ const error = await response.text();
1109
+ throw new Error(`ModelScope API error: ${response.status} ${error}`);
1110
+ }
1111
+ const reader = response.body?.getReader();
1112
+ if (!reader) {
1113
+ throw new Error("No response body");
1114
+ }
1115
+ const decoder = new TextDecoder();
1116
+ let buffer = "";
1117
+ try {
1118
+ while (true) {
1119
+ const { done, value } = await reader.read();
1120
+ if (done) break;
1121
+ buffer += decoder.decode(value, { stream: true });
1122
+ const lines = buffer.split("\n");
1123
+ buffer = lines.pop() ?? "";
1124
+ for (const line of lines) {
1125
+ const trimmed = line.trim();
1126
+ if (!trimmed || trimmed === "data: [DONE]") continue;
1127
+ if (!trimmed.startsWith("data: ")) continue;
1128
+ try {
1129
+ const data = JSON.parse(trimmed.slice(6));
1130
+ const delta = data.choices?.[0]?.delta;
1131
+ if (!delta) continue;
1132
+ if (delta.reasoning_content) {
1133
+ yield {
1134
+ type: "reasoning",
1135
+ text: extractTextContent5(delta.reasoning_content)
1136
+ };
1137
+ }
1138
+ if (delta.content) {
1139
+ yield {
1140
+ type: "content",
1141
+ text: extractTextContent5(delta.content)
1142
+ };
1143
+ }
1144
+ } catch {
1145
+ }
1146
+ }
1147
+ }
1148
+ } finally {
1149
+ reader.releaseLock();
1150
+ }
1151
+ }
1152
+ };
1153
+
1154
+ // src/providers/deepseek.ts
1155
+ var BASE_URL5 = "https://api.deepseek.com";
1156
+ function extractTextContent6(content) {
1157
+ if (typeof content === "string") {
1158
+ return content;
1159
+ }
1160
+ if (Array.isArray(content)) {
1161
+ return content.filter(
1162
+ (item) => typeof item === "object" && item !== null && item.type === "text" && typeof item.text === "string"
1163
+ ).map((item) => item.text).join("");
1164
+ }
1165
+ return "";
1166
+ }
1167
+ var DeepSeekProvider = class extends BaseProvider {
1168
+ name = "deepseek";
1169
+ apiKey;
1170
+ baseUrl;
1171
+ constructor(config) {
1172
+ super();
1173
+ if (typeof config === "string") {
1174
+ this.apiKey = config;
1175
+ this.baseUrl = BASE_URL5;
1176
+ } else {
1177
+ this.apiKey = config.apiKey;
1178
+ this.baseUrl = config.baseUrl ?? BASE_URL5;
1179
+ }
1180
+ }
1181
+ /**
1182
+ * 发送聊天请求(非流式)
1183
+ *
1184
+ * reasoning 参数说明:
1185
+ * - effort 不为 'off' 时启用 thinking 模式
1186
+ * - maxTokens 独立控制输出长度,不受 effort 影响
1187
+ */
1188
+ async chat(options) {
1189
+ const {
1190
+ model,
1191
+ messages,
1192
+ temperature = 0.7,
1193
+ maxTokens,
1194
+ reasoning
1195
+ } = options;
1196
+ const body = {
1197
+ model,
1198
+ messages,
1199
+ temperature,
1200
+ stream: false
1201
+ };
1202
+ if (maxTokens) {
1203
+ body.max_tokens = maxTokens;
1204
+ }
1205
+ if (reasoning?.effort && reasoning.effort !== "off") {
1206
+ body.thinking = { type: "enabled" };
1207
+ }
1208
+ const response = await fetch(`${this.baseUrl}/chat/completions`, {
1209
+ method: "POST",
1210
+ headers: {
1211
+ "Content-Type": "application/json",
1212
+ Authorization: `Bearer ${this.apiKey}`
1213
+ },
1214
+ body: JSON.stringify(body)
1215
+ });
1216
+ if (!response.ok) {
1217
+ const error = await response.text();
1218
+ throw new Error(`DeepSeek API error: ${response.status} ${error}`);
1219
+ }
1220
+ const result = await response.json();
1221
+ const choice = result.choices?.[0];
1222
+ if (!choice) {
1223
+ throw new Error("No response from model");
1224
+ }
1225
+ const msg = choice.message;
1226
+ const reasoningContent = msg?.reasoning_content ?? null;
1227
+ return {
1228
+ content: extractTextContent6(msg?.content),
1229
+ reasoning: reasoningContent ? extractTextContent6(reasoningContent) : null,
1230
+ model: result.model ?? model,
1231
+ usage: {
1232
+ promptTokens: result.usage?.prompt_tokens ?? 0,
1233
+ completionTokens: result.usage?.completion_tokens ?? 0,
1234
+ totalTokens: result.usage?.total_tokens ?? 0
1235
+ },
1236
+ finishReason: choice.finish_reason ?? null
1237
+ };
1238
+ }
1239
+ /**
1240
+ * 发送流式聊天请求
1241
+ */
1242
+ async *chatStream(options) {
1243
+ const {
1244
+ model,
1245
+ messages,
1246
+ temperature = 0.7,
1247
+ maxTokens,
1248
+ reasoning
1249
+ } = options;
1250
+ const body = {
1251
+ model,
1252
+ messages,
1253
+ temperature,
1254
+ stream: true
1255
+ };
1256
+ if (maxTokens) {
1257
+ body.max_tokens = maxTokens;
1258
+ }
1259
+ if (reasoning?.effort && reasoning.effort !== "off") {
1260
+ body.thinking = { type: "enabled" };
1261
+ }
1262
+ const response = await fetch(`${this.baseUrl}/chat/completions`, {
1263
+ method: "POST",
1264
+ headers: {
1265
+ "Content-Type": "application/json",
1266
+ Authorization: `Bearer ${this.apiKey}`
1267
+ },
1268
+ body: JSON.stringify(body)
1269
+ });
1270
+ if (!response.ok) {
1271
+ const error = await response.text();
1272
+ throw new Error(`DeepSeek API error: ${response.status} ${error}`);
1273
+ }
1274
+ const reader = response.body?.getReader();
1275
+ if (!reader) {
1276
+ throw new Error("No response body");
1277
+ }
1278
+ const decoder = new TextDecoder();
1279
+ let buffer = "";
1280
+ try {
1281
+ while (true) {
1282
+ const { done, value } = await reader.read();
1283
+ if (done) break;
1284
+ buffer += decoder.decode(value, { stream: true });
1285
+ const lines = buffer.split("\n");
1286
+ buffer = lines.pop() ?? "";
1287
+ for (const line of lines) {
1288
+ const trimmed = line.trim();
1289
+ if (!trimmed || trimmed === "data: [DONE]") continue;
1290
+ if (!trimmed.startsWith("data: ")) continue;
1291
+ try {
1292
+ const data = JSON.parse(trimmed.slice(6));
1293
+ const delta = data.choices?.[0]?.delta;
1294
+ if (!delta) continue;
1295
+ if (delta.reasoning_content) {
1296
+ yield {
1297
+ type: "reasoning",
1298
+ text: extractTextContent6(delta.reasoning_content)
1299
+ };
1300
+ }
1301
+ if (delta.content) {
1302
+ yield {
1303
+ type: "content",
1304
+ text: extractTextContent6(delta.content)
1305
+ };
1306
+ }
1307
+ } catch {
1308
+ }
1309
+ }
1310
+ }
1311
+ } finally {
1312
+ reader.releaseLock();
1313
+ }
1314
+ }
1315
+ };
1316
+
1317
+ // src/providers/poe.ts
1318
+ var BASE_URL6 = "https://api.poe.com/v1";
1319
+ function extractTextContent7(content) {
1320
+ if (typeof content === "string") {
1321
+ return content;
1322
+ }
1323
+ if (Array.isArray(content)) {
1324
+ return content.filter(
1325
+ (item) => typeof item === "object" && item !== null && item.type === "text" && typeof item.text === "string"
1326
+ ).map((item) => item.text).join("");
1327
+ }
1328
+ return "";
1329
+ }
1330
+ function extractThinkingFromContent(content) {
1331
+ const thinkMatch = content.match(/<think>([\s\S]*?)<\/think>/);
1332
+ if (thinkMatch) {
1333
+ const thinking = thinkMatch[1].trim();
1334
+ const cleanContent = content.replace(/<think>[\s\S]*?<\/think>/, "").trim();
1335
+ return { thinking, content: cleanContent };
1336
+ }
1337
+ const thinkingMatch = content.match(
1338
+ /^\*Thinking\.{0,3}\*\s*\n((?:>.*(?:\n|$))+)/
1339
+ );
1340
+ if (thinkingMatch) {
1341
+ const thinking = thinkingMatch[1].split("\n").map((line) => line.replace(/^>\s?/, "")).join("\n").trim();
1342
+ const cleanContent = content.replace(thinkingMatch[0], "").trim();
1343
+ return { thinking, content: cleanContent };
1344
+ }
1345
+ return { thinking: "", content };
1346
+ }
1347
+ function buildExtraBody(reasoning) {
1348
+ if (!reasoning || reasoning.effort === "off") {
1349
+ return void 0;
1350
+ }
1351
+ const extraBody = {};
1352
+ if (reasoning.effort) {
1353
+ extraBody.reasoning_effort = reasoning.effort;
1354
+ }
1355
+ if (reasoning.budgetTokens !== void 0) {
1356
+ extraBody.thinking_budget = reasoning.budgetTokens;
1357
+ } else if (reasoning.effort && EFFORT_TOKEN_MAP[reasoning.effort]) {
1358
+ extraBody.thinking_budget = EFFORT_TOKEN_MAP[reasoning.effort];
1359
+ }
1360
+ return Object.keys(extraBody).length > 0 ? extraBody : void 0;
1361
+ }
1362
+ var PoeProvider = class extends BaseProvider {
1363
+ name = "poe";
1364
+ apiKey;
1365
+ baseUrl;
1366
+ constructor(config) {
1367
+ super();
1368
+ if (typeof config === "string") {
1369
+ this.apiKey = config;
1370
+ this.baseUrl = BASE_URL6;
1371
+ } else {
1372
+ this.apiKey = config.apiKey;
1373
+ this.baseUrl = config.baseUrl ?? BASE_URL6;
1374
+ }
1375
+ }
1376
+ /**
1377
+ * 发送聊天请求(非流式)
1378
+ */
1379
+ async chat(options) {
1380
+ const { model, messages, temperature = 0.7, maxTokens, reasoning } = options;
1381
+ const body = {
1382
+ model,
1383
+ messages,
1384
+ temperature,
1385
+ stream: false
1386
+ };
1387
+ if (maxTokens) {
1388
+ body.max_tokens = maxTokens;
1389
+ }
1390
+ const extraBody = buildExtraBody(reasoning);
1391
+ if (extraBody) {
1392
+ Object.assign(body, extraBody);
1393
+ }
1394
+ const response = await fetch(`${this.baseUrl}/chat/completions`, {
1395
+ method: "POST",
1396
+ headers: {
1397
+ "Content-Type": "application/json",
1398
+ Authorization: `Bearer ${this.apiKey}`
1399
+ },
1400
+ body: JSON.stringify(body)
1401
+ });
1402
+ if (!response.ok) {
1403
+ const error = await response.text();
1404
+ throw new Error(`Poe API error: ${response.status} ${error}`);
1405
+ }
1406
+ const result = await response.json();
1407
+ const choice = result.choices?.[0];
1408
+ if (!choice) {
1409
+ throw new Error("No response from model");
1410
+ }
1411
+ const msg = choice.message;
1412
+ let reasoningContent = msg?.reasoning_content ?? null;
1413
+ let contentText = extractTextContent7(msg?.content);
1414
+ if (!reasoningContent && contentText) {
1415
+ const extracted = extractThinkingFromContent(contentText);
1416
+ if (extracted.thinking) {
1417
+ reasoningContent = extracted.thinking;
1418
+ contentText = extracted.content;
1419
+ }
1420
+ }
1421
+ return {
1422
+ content: contentText,
1423
+ reasoning: reasoningContent ? extractTextContent7(reasoningContent) : null,
1424
+ model: result.model ?? model,
1425
+ usage: {
1426
+ promptTokens: result.usage?.prompt_tokens ?? 0,
1427
+ completionTokens: result.usage?.completion_tokens ?? 0,
1428
+ totalTokens: result.usage?.total_tokens ?? 0
1429
+ },
1430
+ finishReason: choice.finish_reason ?? null
1431
+ };
1432
+ }
1433
+ /**
1434
+ * 发送流式聊天请求
1435
+ */
1436
+ async *chatStream(options) {
1437
+ const { model, messages, temperature = 0.7, maxTokens, reasoning } = options;
1438
+ const body = {
1439
+ model,
1440
+ messages,
1441
+ temperature,
1442
+ stream: true
1443
+ };
1444
+ if (maxTokens) {
1445
+ body.max_tokens = maxTokens;
1446
+ }
1447
+ const extraBody = buildExtraBody(reasoning);
1448
+ if (extraBody) {
1449
+ Object.assign(body, extraBody);
1450
+ }
1451
+ const response = await fetch(`${this.baseUrl}/chat/completions`, {
1452
+ method: "POST",
1453
+ headers: {
1454
+ "Content-Type": "application/json",
1455
+ Authorization: `Bearer ${this.apiKey}`
1456
+ },
1457
+ body: JSON.stringify(body)
1458
+ });
1459
+ if (!response.ok) {
1460
+ const error = await response.text();
1461
+ throw new Error(`Poe API error: ${response.status} ${error}`);
1462
+ }
1463
+ const reader = response.body?.getReader();
1464
+ if (!reader) {
1465
+ throw new Error("No response body");
1466
+ }
1467
+ const decoder = new TextDecoder();
1468
+ let buffer = "";
1469
+ let thinkingMode = "none";
1470
+ let contentBuffer = "";
1471
+ try {
1472
+ while (true) {
1473
+ const { done, value } = await reader.read();
1474
+ if (done) break;
1475
+ buffer += decoder.decode(value, { stream: true });
1476
+ const lines = buffer.split("\n");
1477
+ buffer = lines.pop() ?? "";
1478
+ for (const line of lines) {
1479
+ const trimmed = line.trim();
1480
+ if (!trimmed || trimmed === "data: [DONE]") continue;
1481
+ if (!trimmed.startsWith("data: ")) continue;
1482
+ try {
1483
+ const data = JSON.parse(trimmed.slice(6));
1484
+ const delta = data.choices?.[0]?.delta;
1485
+ if (!delta) continue;
1486
+ if (delta.reasoning_content) {
1487
+ yield {
1488
+ type: "reasoning",
1489
+ text: extractTextContent7(delta.reasoning_content)
1490
+ };
1491
+ continue;
1492
+ }
1493
+ if (delta.content) {
1494
+ const text = extractTextContent7(delta.content);
1495
+ contentBuffer += text;
1496
+ while (true) {
1497
+ if (thinkingMode === "none") {
1498
+ const thinkStart = contentBuffer.indexOf("<think>");
1499
+ if (thinkStart !== -1) {
1500
+ if (thinkStart > 0) {
1501
+ yield { type: "content", text: contentBuffer.slice(0, thinkStart) };
1502
+ }
1503
+ contentBuffer = contentBuffer.slice(thinkStart + 7);
1504
+ thinkingMode = "think_tag";
1505
+ continue;
1506
+ }
1507
+ const thinkingMatch = contentBuffer.match(/^\*Thinking\.{0,3}\*\s*\n/);
1508
+ if (thinkingMatch) {
1509
+ contentBuffer = contentBuffer.slice(thinkingMatch[0].length);
1510
+ thinkingMode = "markdown_thinking";
1511
+ continue;
1512
+ }
1513
+ if (contentBuffer.length > 0) {
1514
+ const keepLen = Math.min(15, contentBuffer.length);
1515
+ const output = contentBuffer.slice(0, -keepLen) || "";
1516
+ if (output) {
1517
+ yield { type: "content", text: output };
1518
+ contentBuffer = contentBuffer.slice(-keepLen);
1519
+ }
1520
+ }
1521
+ break;
1522
+ } else if (thinkingMode === "think_tag") {
1523
+ const endIdx = contentBuffer.indexOf("</think>");
1524
+ if (endIdx !== -1) {
1525
+ yield { type: "reasoning", text: contentBuffer.slice(0, endIdx) };
1526
+ contentBuffer = contentBuffer.slice(endIdx + 8);
1527
+ thinkingMode = "none";
1528
+ continue;
1529
+ }
1530
+ if (contentBuffer.length > 8) {
1531
+ yield { type: "reasoning", text: contentBuffer.slice(0, -8) };
1532
+ contentBuffer = contentBuffer.slice(-8);
1533
+ }
1534
+ break;
1535
+ } else if (thinkingMode === "markdown_thinking") {
1536
+ if (contentBuffer.startsWith(">")) {
1537
+ thinkingMode = "markdown_quote";
1538
+ continue;
1539
+ }
1540
+ if (contentBuffer.length > 0 && !contentBuffer.startsWith(">")) {
1541
+ thinkingMode = "none";
1542
+ continue;
1543
+ }
1544
+ break;
1545
+ } else if (thinkingMode === "markdown_quote") {
1546
+ const newlineIdx = contentBuffer.indexOf("\n");
1547
+ if (newlineIdx !== -1) {
1548
+ const quoteLine = contentBuffer.slice(0, newlineIdx);
1549
+ contentBuffer = contentBuffer.slice(newlineIdx + 1);
1550
+ if (quoteLine.startsWith(">")) {
1551
+ const thinkText = quoteLine.replace(/^>\s?/, "");
1552
+ yield { type: "reasoning", text: thinkText + "\n" };
1553
+ continue;
1554
+ }
1555
+ if (quoteLine.trim() === "") {
1556
+ yield { type: "reasoning", text: "\n" };
1557
+ continue;
1558
+ }
1559
+ thinkingMode = "none";
1560
+ yield { type: "content", text: quoteLine + "\n" };
1561
+ continue;
1562
+ }
1563
+ break;
1564
+ }
1565
+ }
1566
+ }
1567
+ } catch {
1568
+ }
1569
+ }
1570
+ }
1571
+ if (contentBuffer.length > 0) {
1572
+ if (thinkingMode === "think_tag" || thinkingMode === "markdown_quote") {
1573
+ yield { type: "reasoning", text: contentBuffer };
1574
+ } else {
1575
+ yield { type: "content", text: contentBuffer };
1576
+ }
1577
+ }
1578
+ } finally {
1579
+ reader.releaseLock();
1580
+ }
1581
+ }
1582
+ };
1583
+
1584
+ // src/providers/nova.ts
1585
+ var BASE_URL7 = "https://api.nova.amazon.com/v1";
1586
+ function extractTextContent8(content) {
1587
+ if (typeof content === "string") {
1588
+ return content;
1589
+ }
1590
+ if (Array.isArray(content)) {
1591
+ return content.filter(
1592
+ (item) => typeof item === "object" && item !== null && item.type === "text" && typeof item.text === "string"
1593
+ ).map((item) => item.text).join("");
1594
+ }
1595
+ return "";
1596
+ }
1597
+ var NovaProvider = class extends BaseProvider {
1598
+ name = "nova";
1599
+ apiKey;
1600
+ baseUrl;
1601
+ constructor(config) {
1602
+ super();
1603
+ if (typeof config === "string") {
1604
+ this.apiKey = config;
1605
+ this.baseUrl = BASE_URL7;
1606
+ } else {
1607
+ this.apiKey = config.apiKey;
1608
+ this.baseUrl = config.baseUrl ?? BASE_URL7;
1609
+ }
1610
+ }
1611
+ /**
1612
+ * 发送聊天请求(非流式)
1613
+ *
1614
+ * 注意:
1615
+ * - Nova API 的 temperature 范围是 0-1(不是 0-2)
1616
+ * - Nova 2 Lite 支持 extended thinking (reasoningConfig)
1617
+ * - effort 映射为 maxReasoningEffort
1618
+ */
1619
+ async chat(options) {
1620
+ const { model, messages, temperature = 0.7, maxTokens, reasoning } = options;
1621
+ const body = {
1622
+ model,
1623
+ messages,
1624
+ temperature,
1625
+ stream: false
1626
+ };
1627
+ if (maxTokens) {
1628
+ body.max_tokens = maxTokens;
1629
+ }
1630
+ if (reasoning?.effort && reasoning.effort !== "off") {
1631
+ body.reasoningConfig = {
1632
+ type: "enabled",
1633
+ maxReasoningEffort: reasoning.effort
1634
+ // low/medium/high
1635
+ };
1636
+ }
1637
+ const response = await fetch(`${this.baseUrl}/chat/completions`, {
1638
+ method: "POST",
1639
+ headers: {
1640
+ "Content-Type": "application/json",
1641
+ Authorization: `Bearer ${this.apiKey}`
1642
+ },
1643
+ body: JSON.stringify(body)
1644
+ });
1645
+ if (!response.ok) {
1646
+ const error = await response.text();
1647
+ throw new Error(`Nova API error: ${response.status} ${error}`);
1648
+ }
1649
+ const result = await response.json();
1650
+ const choice = result.choices?.[0];
1651
+ if (!choice) {
1652
+ throw new Error("No response from model");
1653
+ }
1654
+ const msg = choice.message;
1655
+ const reasoningContent = msg?.reasoning_content ?? null;
1656
+ return {
1657
+ content: extractTextContent8(msg?.content),
1658
+ reasoning: reasoningContent ? extractTextContent8(reasoningContent) : null,
1659
+ model: result.model ?? model,
1660
+ usage: {
1661
+ promptTokens: result.usage?.prompt_tokens ?? 0,
1662
+ completionTokens: result.usage?.completion_tokens ?? 0,
1663
+ totalTokens: result.usage?.total_tokens ?? 0
1664
+ },
1665
+ finishReason: choice.finish_reason ?? null
1666
+ };
1667
+ }
1668
+ /**
1669
+ * 发送流式聊天请求
1670
+ */
1671
+ async *chatStream(options) {
1672
+ const { model, messages, temperature = 0.7, maxTokens, reasoning } = options;
1673
+ const body = {
1674
+ model,
1675
+ messages,
1676
+ temperature,
1677
+ stream: true
1678
+ };
1679
+ if (maxTokens) {
1680
+ body.max_tokens = maxTokens;
1681
+ }
1682
+ if (reasoning?.effort && reasoning.effort !== "off") {
1683
+ body.reasoningConfig = {
1684
+ type: "enabled",
1685
+ maxReasoningEffort: reasoning.effort
1686
+ };
1687
+ }
1688
+ const response = await fetch(`${this.baseUrl}/chat/completions`, {
1689
+ method: "POST",
1690
+ headers: {
1691
+ "Content-Type": "application/json",
1692
+ Authorization: `Bearer ${this.apiKey}`
1693
+ },
1694
+ body: JSON.stringify(body)
1695
+ });
1696
+ if (!response.ok) {
1697
+ const error = await response.text();
1698
+ throw new Error(`Nova API error: ${response.status} ${error}`);
1699
+ }
1700
+ const reader = response.body?.getReader();
1701
+ if (!reader) {
1702
+ throw new Error("No response body");
1703
+ }
1704
+ const decoder = new TextDecoder();
1705
+ let buffer = "";
1706
+ try {
1707
+ while (true) {
1708
+ const { done, value } = await reader.read();
1709
+ if (done) break;
1710
+ buffer += decoder.decode(value, { stream: true });
1711
+ const lines = buffer.split("\n");
1712
+ buffer = lines.pop() ?? "";
1713
+ for (const line of lines) {
1714
+ const trimmed = line.trim();
1715
+ if (!trimmed || trimmed === "data: [DONE]") continue;
1716
+ if (!trimmed.startsWith("data: ")) continue;
1717
+ try {
1718
+ const data = JSON.parse(trimmed.slice(6));
1719
+ const delta = data.choices?.[0]?.delta;
1720
+ if (!delta) continue;
1721
+ if (delta.reasoning_content) {
1722
+ yield {
1723
+ type: "reasoning",
1724
+ text: extractTextContent8(delta.reasoning_content)
1725
+ };
1726
+ }
1727
+ if (delta.content) {
1728
+ yield {
1729
+ type: "content",
1730
+ text: extractTextContent8(delta.content)
1731
+ };
1732
+ }
1733
+ } catch {
1734
+ }
1735
+ }
1736
+ }
1737
+ } finally {
1738
+ reader.releaseLock();
1739
+ }
1740
+ }
1741
+ };
1742
+
1743
+ // src/providers/__factory__.ts
1744
+ function createProvider(config) {
1745
+ const { provider, apiKey, baseUrl } = config;
1746
+ switch (provider) {
1747
+ case "openrouter":
1748
+ return new OpenRouterProvider(apiKey);
1749
+ case "gemini":
1750
+ return new GeminiProvider(baseUrl ? { apiKey, baseUrl } : apiKey);
1751
+ case "groq":
1752
+ return new GroqProvider(baseUrl ? { apiKey, baseUrl } : apiKey);
1753
+ case "huggingface":
1754
+ return new HuggingFaceProvider(baseUrl ? { apiKey, baseUrl } : apiKey);
1755
+ case "modelscope":
1756
+ return new ModelScopeProvider(baseUrl ? { apiKey, baseUrl } : apiKey);
1757
+ case "deepseek":
1758
+ return new DeepSeekProvider(baseUrl ? { apiKey, baseUrl } : apiKey);
1759
+ case "poe":
1760
+ return new PoeProvider(baseUrl ? { apiKey, baseUrl } : apiKey);
1761
+ case "nova":
1762
+ return new NovaProvider(baseUrl ? { apiKey, baseUrl } : apiKey);
1763
+ default:
1764
+ throw new Error(`Unknown provider: ${provider}`);
1765
+ }
1766
+ }
1767
+ var ai = {
1768
+ openrouter: (apiKey, baseUrl) => createProvider({ provider: "openrouter", apiKey, baseUrl }),
1769
+ gemini: (apiKey, baseUrl) => createProvider({ provider: "gemini", apiKey, baseUrl }),
1770
+ groq: (apiKey, baseUrl) => createProvider({ provider: "groq", apiKey, baseUrl }),
1771
+ huggingface: (apiKey, baseUrl) => createProvider({ provider: "huggingface", apiKey, baseUrl }),
1772
+ modelscope: (apiKey, baseUrl) => createProvider({ provider: "modelscope", apiKey, baseUrl }),
1773
+ deepseek: (apiKey, baseUrl) => createProvider({ provider: "deepseek", apiKey, baseUrl }),
1774
+ poe: (apiKey, baseUrl) => createProvider({ provider: "poe", apiKey, baseUrl }),
1775
+ nova: (apiKey, baseUrl) => createProvider({ provider: "nova", apiKey, baseUrl })
1776
+ };
162
1777
  export {
163
1778
  BaseProvider,
164
- OpenRouterProvider
1779
+ EFFORT_TOKEN_MAP,
1780
+ GeminiProvider,
1781
+ GroqProvider,
1782
+ HuggingFaceProvider,
1783
+ ModelScopeProvider,
1784
+ OpenRouterProvider,
1785
+ ai,
1786
+ createProvider
165
1787
  };
166
1788
  //# sourceMappingURL=index.mjs.map