llm-api-purity-check 0.0.0-stage → 1.2.0

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/src/client.mjs ADDED
@@ -0,0 +1,338 @@
1
+ /**
2
+ * Zero-dependency LLM API client supporting:
3
+ * - openai-chat (/v1/chat/completions)
4
+ * - openai-responses (/v1/responses)
5
+ * - anthropic (/v1/messages)
6
+ *
7
+ * Captures real streaming TTFT, chunk cadence, fake-stream heuristics,
8
+ * response.model / ID metadata, cache usage fields, and /v1/responses echo fields.
9
+ */
10
+
11
+ export function inferProtocol(model, explicitProtocol) {
12
+ if (explicitProtocol) {
13
+ const p = explicitProtocol.trim().toLowerCase();
14
+ if (['openai-chat', 'openai_chat', 'chat'].includes(p)) return 'openai-chat';
15
+ if (['openai-responses', 'openai_responses', 'responses'].includes(p)) return 'openai-responses';
16
+ if (['anthropic', 'anthropic-messages', 'anthropic_messages', 'claude'].includes(p)) return 'anthropic';
17
+ throw new Error(`Unsupported --protocol "${explicitProtocol}". Use: openai-chat | openai-responses | anthropic`);
18
+ }
19
+ const m = String(model || '').toLowerCase();
20
+ if (/claude|opus|sonnet|haiku|fable/.test(m)) return 'anthropic';
21
+ return 'openai-chat';
22
+ }
23
+
24
+ export function buildEndpointUrl(baseUrl, protocol) {
25
+ const clean = String(baseUrl || '').trim().replace(/\/+$/, '');
26
+ if (!clean) throw new Error('Missing --base-url');
27
+ if (protocol === 'anthropic') {
28
+ if (clean.endsWith('/v1/messages')) return clean;
29
+ if (clean.endsWith('/v1')) return `${clean}/messages`;
30
+ return `${clean}/v1/messages`;
31
+ }
32
+ if (protocol === 'openai-responses') {
33
+ if (clean.endsWith('/v1/responses')) return clean;
34
+ if (clean.endsWith('/v1')) return `${clean}/responses`;
35
+ return `${clean}/v1/responses`;
36
+ }
37
+ if (clean.endsWith('/v1/chat/completions')) return clean;
38
+ if (clean.endsWith('/v1')) return `${clean}/chat/completions`;
39
+ return `${clean}/v1/chat/completions`;
40
+ }
41
+
42
+ function buildHeaders(apiKey, protocol) {
43
+ if (protocol === 'anthropic') {
44
+ return {
45
+ 'content-type': 'application/json',
46
+ 'x-api-key': apiKey,
47
+ 'anthropic-version': '2023-06-01',
48
+ };
49
+ }
50
+ return {
51
+ 'content-type': 'application/json',
52
+ authorization: `Bearer ${apiKey}`,
53
+ };
54
+ }
55
+
56
+ function buildPayload({
57
+ protocol,
58
+ model,
59
+ system,
60
+ userPrompt,
61
+ stream,
62
+ maxTokens,
63
+ temperature,
64
+ enableAnthropicCacheControl,
65
+ tools,
66
+ }) {
67
+ if (protocol === 'anthropic') {
68
+ const body = {
69
+ model,
70
+ max_tokens: maxTokens,
71
+ stream: Boolean(stream),
72
+ messages: [{ role: 'user', content: userPrompt }],
73
+ };
74
+ if (typeof temperature === 'number') body.temperature = temperature;
75
+ if (system) {
76
+ body.system = enableAnthropicCacheControl
77
+ ? [{ type: 'text', text: system, cache_control: { type: 'ephemeral' } }]
78
+ : system;
79
+ }
80
+ if (tools && tools.length > 0) body.tools = tools;
81
+ return body;
82
+ }
83
+
84
+ if (protocol === 'openai-responses') {
85
+ const body = {
86
+ model,
87
+ input: userPrompt,
88
+ max_output_tokens: maxTokens,
89
+ stream: Boolean(stream),
90
+ };
91
+ if (system) body.instructions = system;
92
+ if (typeof temperature === 'number') body.temperature = temperature;
93
+ if (tools && tools.length > 0) body.tools = tools;
94
+ return body;
95
+ }
96
+
97
+ const messages = [];
98
+ if (system) messages.push({ role: 'system', content: system });
99
+ messages.push({ role: 'user', content: userPrompt });
100
+ const body = {
101
+ model,
102
+ messages,
103
+ max_tokens: maxTokens,
104
+ stream: Boolean(stream),
105
+ };
106
+ if (stream) body.stream_options = { include_usage: true };
107
+ if (typeof temperature === 'number') body.temperature = temperature;
108
+ if (tools && tools.length > 0) body.tools = tools;
109
+ return body;
110
+ }
111
+
112
+ function normalizeUsage(rawUsage, protocol) {
113
+ if (!rawUsage || typeof rawUsage !== 'object') {
114
+ return { inputTokens: null, outputTokens: null, cachedTokens: null, cacheCreationTokens: null };
115
+ }
116
+ if (protocol === 'anthropic') {
117
+ const baseIn = Number(rawUsage.input_tokens ?? 0);
118
+ const cacheRead = rawUsage.cache_read_input_tokens != null ? Number(rawUsage.cache_read_input_tokens) : 0;
119
+ const cacheCreate =
120
+ rawUsage.cache_creation_input_tokens != null ? Number(rawUsage.cache_creation_input_tokens) : 0;
121
+ return {
122
+ inputTokens: baseIn + cacheRead + cacheCreate,
123
+ outputTokens: rawUsage.output_tokens != null ? Number(rawUsage.output_tokens) : null,
124
+ cachedTokens: cacheRead,
125
+ cacheCreationTokens: cacheCreate,
126
+ };
127
+ }
128
+ const inputTokens = rawUsage.prompt_tokens ?? rawUsage.input_tokens ?? null;
129
+ const outputTokens = rawUsage.completion_tokens ?? rawUsage.output_tokens ?? null;
130
+ const cachedTokens =
131
+ rawUsage.prompt_tokens_details?.cached_tokens ??
132
+ rawUsage.input_tokens_details?.cached_tokens ??
133
+ rawUsage.cache_read_input_tokens ??
134
+ 0;
135
+ return {
136
+ inputTokens: inputTokens != null ? Number(inputTokens) : null,
137
+ outputTokens: outputTokens != null ? Number(outputTokens) : null,
138
+ cachedTokens: Number(cachedTokens || 0),
139
+ cacheCreationTokens: null,
140
+ };
141
+ }
142
+
143
+ export async function callLlm({
144
+ baseUrl,
145
+ apiKey,
146
+ protocol,
147
+ model,
148
+ system = '',
149
+ userPrompt,
150
+ stream = false,
151
+ maxTokens = 1024,
152
+ temperature,
153
+ enableAnthropicCacheControl = false,
154
+ tools,
155
+ extraHeaders,
156
+ timeoutMs = 90000,
157
+ }) {
158
+ const url = buildEndpointUrl(baseUrl, protocol);
159
+ const headers = {
160
+ ...buildHeaders(apiKey, protocol),
161
+ ...(extraHeaders && typeof extraHeaders === 'object' ? extraHeaders : {}),
162
+ };
163
+ const payload = buildPayload({
164
+ protocol,
165
+ model,
166
+ system,
167
+ userPrompt,
168
+ stream,
169
+ maxTokens,
170
+ temperature,
171
+ enableAnthropicCacheControl,
172
+ tools,
173
+ });
174
+
175
+ const controller = new AbortController();
176
+ const timer = setTimeout(() => controller.abort(), timeoutMs);
177
+ const startedAt = performance.now();
178
+
179
+ try {
180
+ const resp = await fetch(url, {
181
+ method: 'POST',
182
+ headers,
183
+ body: JSON.stringify(payload),
184
+ signal: controller.signal,
185
+ });
186
+
187
+ if (!resp.ok) {
188
+ const errBody = await resp.text().catch(() => '');
189
+ throw new Error(`HTTP ${resp.status} from ${url}: ${errBody.slice(0, 300)}`);
190
+ }
191
+
192
+ if (!stream) {
193
+ const data = await resp.json();
194
+ const totalMs = Math.round(performance.now() - startedAt);
195
+ let text = '';
196
+ let responseModel = data.model || null;
197
+ let responseId = data.id || null;
198
+ let echoInstructions = null;
199
+ let echoTools = null;
200
+
201
+ if (protocol === 'anthropic') {
202
+ const blocks = Array.isArray(data.content) ? data.content : [];
203
+ text = blocks.filter((b) => b?.type === 'text').map((b) => b.text).join('');
204
+ } else if (protocol === 'openai-responses') {
205
+ if (typeof data.output_text === 'string') {
206
+ text = data.output_text;
207
+ } else if (Array.isArray(data.output)) {
208
+ text = data.output
209
+ .flatMap((o) => (Array.isArray(o.content) ? o.content : []))
210
+ .filter((c) => c?.type === 'output_text' || c?.type === 'text')
211
+ .map((c) => c.text || '')
212
+ .join('');
213
+ }
214
+ if (typeof data.instructions === 'string') echoInstructions = data.instructions;
215
+ if (Array.isArray(data.tools)) echoTools = data.tools;
216
+ } else {
217
+ text = data.choices?.[0]?.message?.content || '';
218
+ }
219
+
220
+ return {
221
+ ok: true,
222
+ text,
223
+ totalMs,
224
+ ttftMs: totalMs,
225
+ chunkCount: 1,
226
+ fakeStreamSuspect: false,
227
+ responseModel,
228
+ responseId,
229
+ usage: normalizeUsage(data.usage, protocol),
230
+ echoInstructions,
231
+ echoTools,
232
+ };
233
+ }
234
+
235
+ // Streaming SSE parser
236
+ const reader = resp.body.getReader();
237
+ const decoder = new TextDecoder('utf-8');
238
+ let buffer = '';
239
+ let text = '';
240
+ let firstTokenAt = null;
241
+ let chunkCount = 0;
242
+ let maxChunkChars = 0;
243
+ let responseModel = null;
244
+ let responseId = null;
245
+ let rawUsage = null;
246
+ let echoInstructions = null;
247
+ let echoTools = null;
248
+
249
+ while (true) {
250
+ const { value, done } = await reader.read();
251
+ if (done) break;
252
+ buffer += decoder.decode(value, { stream: true });
253
+ const lines = buffer.split(/\r?\n/);
254
+ buffer = lines.pop() || '';
255
+
256
+ for (const line of lines) {
257
+ const trimmed = line.trim();
258
+ if (!trimmed.startsWith('data:')) continue;
259
+ const dataStr = trimmed.slice(5).trim();
260
+ if (!dataStr || dataStr === '[DONE]') continue;
261
+ let evt;
262
+ try {
263
+ evt = JSON.parse(dataStr);
264
+ } catch {
265
+ continue;
266
+ }
267
+
268
+ if (evt.model && !responseModel) responseModel = evt.model;
269
+ if (evt.id && !responseId) responseId = evt.id;
270
+
271
+ if (protocol === 'anthropic') {
272
+ if (evt.type === 'message_start' && evt.message) {
273
+ if (evt.message.model) responseModel = evt.message.model;
274
+ if (evt.message.id) responseId = evt.message.id;
275
+ if (evt.message.usage) rawUsage = { ...(rawUsage || {}), ...evt.message.usage };
276
+ }
277
+ if (evt.type === 'content_block_delta' && evt.delta?.type === 'text_delta' && evt.delta.text) {
278
+ const delta = evt.delta.text;
279
+ if (firstTokenAt === null) firstTokenAt = performance.now();
280
+ chunkCount += 1;
281
+ if (delta.length > maxChunkChars) maxChunkChars = delta.length;
282
+ text += delta;
283
+ }
284
+ if (evt.type === 'message_delta' && evt.usage) {
285
+ rawUsage = { ...(rawUsage || {}), ...evt.usage };
286
+ }
287
+ } else if (protocol === 'openai-responses') {
288
+ if (evt.response) {
289
+ if (evt.response.model) responseModel = evt.response.model;
290
+ if (evt.response.id) responseId = evt.response.id;
291
+ if (typeof evt.response.instructions === 'string') echoInstructions = evt.response.instructions;
292
+ if (Array.isArray(evt.response.tools)) echoTools = evt.response.tools;
293
+ if (evt.response.usage) rawUsage = evt.response.usage;
294
+ }
295
+ if (evt.type === 'response.output_text.delta' && typeof evt.delta === 'string' && evt.delta) {
296
+ if (firstTokenAt === null) firstTokenAt = performance.now();
297
+ chunkCount += 1;
298
+ if (evt.delta.length > maxChunkChars) maxChunkChars = evt.delta.length;
299
+ text += evt.delta;
300
+ }
301
+ } else {
302
+ const delta = evt.choices?.[0]?.delta?.content;
303
+ if (typeof delta === 'string' && delta.length > 0) {
304
+ if (firstTokenAt === null) firstTokenAt = performance.now();
305
+ chunkCount += 1;
306
+ if (delta.length > maxChunkChars) maxChunkChars = delta.length;
307
+ text += delta;
308
+ }
309
+ if (evt.usage) rawUsage = evt.usage;
310
+ }
311
+ }
312
+ }
313
+
314
+ const totalMs = Math.round(performance.now() - startedAt);
315
+ const ttftMs = firstTokenAt !== null ? Math.round(firstTokenAt - startedAt) : totalMs;
316
+ const decodeMs = Math.max(1, totalMs - ttftMs);
317
+ // Heuristic: if >= 160 chars arrived in <= 2 chunks or >85% of output dumped in one chunk with near-zero decode time
318
+ const fakeStreamSuspect =
319
+ text.length >= 160 && (chunkCount <= 2 || (maxChunkChars / text.length >= 0.85 && decodeMs < 120));
320
+
321
+ return {
322
+ ok: true,
323
+ text,
324
+ totalMs,
325
+ ttftMs,
326
+ decodeMs,
327
+ chunkCount,
328
+ fakeStreamSuspect,
329
+ responseModel,
330
+ responseId,
331
+ usage: normalizeUsage(rawUsage, protocol),
332
+ echoInstructions,
333
+ echoTools,
334
+ };
335
+ } finally {
336
+ clearTimeout(timer);
337
+ }
338
+ }