cladogram 0.5.5-beta.8 → 0.6.0-beta.1

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -1,146 +0,0 @@
1
- /**
2
- * OpenAI 兼容协议流式适配器(支持 OpenAI / DeepSeek / 通义 / Kimi / OpenRouter / Ollama)。
3
- *
4
- * 解析 SSE `data: {...}` 增量帧,输出 Clado 统一事件:
5
- * - thinking_delta(兼容 reasoning_content / reasoning)
6
- * - text_delta
7
- * - tool_call_start
8
- * 返回完整的 assistant message(供多轮上下文拼接)与 stopReason。
9
- */
10
-
11
- function finalizeToolCalls(byIndex) {
12
- return [...byIndex.entries()]
13
- .sort((a, b) => a[0] - b[0])
14
- .map(([, call]) => ({
15
- id: call.id || ('call_' + Math.random().toString(36).slice(2, 10)),
16
- type: 'function',
17
- function: { name: call.name || 'unknown', arguments: call.arguments || '{}' },
18
- }));
19
- }
20
-
21
- export async function streamOpenAI({
22
- baseUrl,
23
- apiKey,
24
- model,
25
- messages,
26
- tools,
27
- signal,
28
- onEvent = () => {},
29
- fetchImpl = fetch,
30
- }) {
31
- const url = String(baseUrl || 'https://api.openai.com/v1').replace(/\/+$/, '') + '/chat/completions';
32
- const response = await fetchImpl(url, {
33
- method: 'POST',
34
- headers: {
35
- 'content-type': 'application/json',
36
- authorization: `Bearer ${apiKey}`,
37
- },
38
- body: JSON.stringify({
39
- model,
40
- messages,
41
- ...(tools?.length ? { tools, tool_choice: 'auto' } : {}),
42
- stream: true,
43
- }),
44
- signal,
45
- });
46
-
47
- if (!response.ok) {
48
- const body = await response.text().catch(() => '');
49
- throw new Error(`OpenAI 兼容接口失败(HTTP ${response.status})${body ? ':' + body.slice(0, 240) : ''}`);
50
- }
51
-
52
- const contentType = response.headers?.get?.('content-type') || '';
53
- if (!contentType.includes('text/event-stream') || !response.body) {
54
- // 兼容不返回 SSE 的代理或测试 mock
55
- const data = await response.json();
56
- const choice = data?.choices?.[0];
57
- const msg = choice?.message;
58
- if (!msg) throw new Error('LLM 未返回有效消息。');
59
- const thinking = msg.reasoning_content || msg.reasoning || '';
60
- if (thinking) onEvent({ type: 'thinking_delta', text: thinking });
61
- if (msg.content) onEvent({ type: 'text_delta', text: msg.content });
62
- for (const tc of msg.tool_calls || []) {
63
- onEvent({ type: 'tool_call_start', id: tc.id, name: tc.function?.name });
64
- }
65
- return {
66
- message: {
67
- role: 'assistant',
68
- content: msg.content ?? null,
69
- ...(msg.tool_calls?.length ? { tool_calls: msg.tool_calls } : {}),
70
- },
71
- thinking,
72
- stopReason: choice?.finish_reason || 'stop',
73
- };
74
- }
75
-
76
- const reader = response.body.getReader();
77
- const decoder = new TextDecoder();
78
- let buffer = '';
79
- let content = '';
80
- let thinking = '';
81
- let finishReason = 'stop';
82
- const toolCalls = new Map();
83
- const announced = new Set();
84
-
85
- function processLine(line) {
86
- const trimmed = line.trim();
87
- if (!trimmed || !trimmed.startsWith('data:')) return;
88
- const raw = trimmed.slice(5).trim();
89
- if (!raw || raw === '[DONE]') return;
90
- let chunk;
91
- try { chunk = JSON.parse(raw); } catch { return; }
92
- const choice = chunk?.choices?.[0];
93
- if (!choice) return;
94
- if (choice.finish_reason) finishReason = choice.finish_reason;
95
- const delta = choice.delta || {};
96
- const thought = delta.reasoning_content || delta.reasoning || '';
97
- if (thought) {
98
- thinking += thought;
99
- onEvent({ type: 'thinking_delta', text: thought });
100
- }
101
- if (delta.content) {
102
- content += delta.content;
103
- onEvent({ type: 'text_delta', text: delta.content });
104
- }
105
- if (Array.isArray(delta.tool_calls)) {
106
- for (const part of delta.tool_calls) {
107
- const idx = typeof part.index === 'number' ? part.index : 0;
108
- const entry = toolCalls.get(idx) || { id: '', name: '', arguments: '' };
109
- if (part.id) entry.id = part.id;
110
- if (part.function?.name) entry.name += part.function.name;
111
- if (part.function?.arguments) entry.arguments += part.function.arguments;
112
- toolCalls.set(idx, entry);
113
- if (entry.name && !announced.has(idx)) {
114
- announced.add(idx);
115
- onEvent({ type: 'tool_call_start', id: entry.id || `call_${idx}`, name: entry.name });
116
- }
117
- }
118
- }
119
- }
120
-
121
- try {
122
- while (true) {
123
- const { value, done } = await reader.read();
124
- if (done) break;
125
- buffer += decoder.decode(value, { stream: true });
126
- const lines = buffer.split(/\r?\n/);
127
- buffer = lines.pop() || '';
128
- for (const line of lines) processLine(line);
129
- }
130
- buffer += decoder.decode();
131
- if (buffer.trim()) processLine(buffer);
132
- } finally {
133
- reader.releaseLock();
134
- }
135
-
136
- const finalCalls = finalizeToolCalls(toolCalls);
137
- return {
138
- message: {
139
- role: 'assistant',
140
- content: content || null,
141
- ...(finalCalls.length ? { tool_calls: finalCalls } : {}),
142
- },
143
- thinking,
144
- stopReason: finishReason,
145
- };
146
- }