universal-llm-client 4.5.0 → 4.5.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.
Files changed (174) hide show
  1. package/CHANGELOG.md +12 -0
  2. package/README.md +2 -0
  3. package/dist/ai-model.d.ts +0 -1
  4. package/dist/ai-model.js +0 -1
  5. package/dist/auditor.d.ts +0 -1
  6. package/dist/auditor.js +0 -1
  7. package/dist/client.d.ts +0 -1
  8. package/dist/client.js +0 -1
  9. package/dist/gemma-channel.d.ts +0 -1
  10. package/dist/gemma-channel.js +0 -1
  11. package/dist/gemma-diffusion.d.ts +0 -1
  12. package/dist/gemma-diffusion.js +0 -1
  13. package/dist/http.d.ts +0 -1
  14. package/dist/http.js +0 -1
  15. package/dist/index.d.ts +0 -1
  16. package/dist/index.js +0 -1
  17. package/dist/interfaces.d.ts +0 -1
  18. package/dist/interfaces.js +0 -1
  19. package/dist/mcp.d.ts +0 -1
  20. package/dist/mcp.js +0 -1
  21. package/dist/providers/anthropic.d.ts +0 -1
  22. package/dist/providers/anthropic.js +0 -1
  23. package/dist/providers/google.d.ts +0 -1
  24. package/dist/providers/google.js +0 -1
  25. package/dist/providers/index.d.ts +0 -1
  26. package/dist/providers/index.js +0 -1
  27. package/dist/providers/ollama.d.ts +0 -1
  28. package/dist/providers/ollama.js +0 -1
  29. package/dist/providers/openai.d.ts +2 -1
  30. package/dist/providers/openai.js +303 -74
  31. package/dist/router.d.ts +0 -1
  32. package/dist/router.js +0 -1
  33. package/dist/stream-decoder.d.ts +0 -1
  34. package/dist/stream-decoder.js +0 -1
  35. package/dist/structured-output.d.ts +0 -1
  36. package/dist/structured-output.js +0 -1
  37. package/dist/thinking.d.ts +0 -1
  38. package/dist/thinking.js +0 -1
  39. package/dist/tools.d.ts +0 -1
  40. package/dist/tools.js +0 -1
  41. package/dist/zod-adapter.d.ts +0 -1
  42. package/dist/zod-adapter.js +0 -1
  43. package/package.json +1 -2
  44. package/dist/ai-model.d.ts.map +0 -1
  45. package/dist/ai-model.js.map +0 -1
  46. package/dist/auditor.d.ts.map +0 -1
  47. package/dist/auditor.js.map +0 -1
  48. package/dist/client.d.ts.map +0 -1
  49. package/dist/client.js.map +0 -1
  50. package/dist/gemma-channel.d.ts.map +0 -1
  51. package/dist/gemma-channel.js.map +0 -1
  52. package/dist/gemma-diffusion.d.ts.map +0 -1
  53. package/dist/gemma-diffusion.js.map +0 -1
  54. package/dist/http.d.ts.map +0 -1
  55. package/dist/http.js.map +0 -1
  56. package/dist/index.d.ts.map +0 -1
  57. package/dist/index.js.map +0 -1
  58. package/dist/interfaces.d.ts.map +0 -1
  59. package/dist/interfaces.js.map +0 -1
  60. package/dist/mcp.d.ts.map +0 -1
  61. package/dist/mcp.js.map +0 -1
  62. package/dist/providers/anthropic.d.ts.map +0 -1
  63. package/dist/providers/anthropic.js.map +0 -1
  64. package/dist/providers/google.d.ts.map +0 -1
  65. package/dist/providers/google.js.map +0 -1
  66. package/dist/providers/index.d.ts.map +0 -1
  67. package/dist/providers/index.js.map +0 -1
  68. package/dist/providers/ollama.d.ts.map +0 -1
  69. package/dist/providers/ollama.js.map +0 -1
  70. package/dist/providers/openai.d.ts.map +0 -1
  71. package/dist/providers/openai.js.map +0 -1
  72. package/dist/router.d.ts.map +0 -1
  73. package/dist/router.js.map +0 -1
  74. package/dist/stream-decoder.d.ts.map +0 -1
  75. package/dist/stream-decoder.js.map +0 -1
  76. package/dist/structured-output.d.ts.map +0 -1
  77. package/dist/structured-output.js.map +0 -1
  78. package/dist/thinking.d.ts.map +0 -1
  79. package/dist/thinking.js.map +0 -1
  80. package/dist/tools.d.ts.map +0 -1
  81. package/dist/tools.js.map +0 -1
  82. package/dist/zod-adapter.d.ts.map +0 -1
  83. package/dist/zod-adapter.js.map +0 -1
  84. package/src/ai-model.ts +0 -400
  85. package/src/auditor.ts +0 -213
  86. package/src/client.ts +0 -402
  87. package/src/debug/debug-google-streaming.ts +0 -97
  88. package/src/debug/debug-tool-execution.ts +0 -86
  89. package/src/debug/test-lmstudio-tools.ts +0 -155
  90. package/src/demos/README.md +0 -47
  91. package/src/demos/basic/universal-llm-examples.ts +0 -161
  92. package/src/demos/diffusion-gemma/.env +0 -29
  93. package/src/demos/diffusion-gemma/.env.example +0 -27
  94. package/src/demos/diffusion-gemma/CLAUDE.md +0 -95
  95. package/src/demos/diffusion-gemma/README.md +0 -59
  96. package/src/demos/diffusion-gemma/canvas.ts +0 -1606
  97. package/src/demos/diffusion-gemma/docker-compose.yml +0 -29
  98. package/src/demos/diffusion-gemma/probe-stream.ts +0 -51
  99. package/src/demos/diffusion-gemma/probe-tools.ts +0 -55
  100. package/src/demos/diffusion-gemma/server.ts +0 -1205
  101. package/src/demos/diffusion-gemma/start-vllm.sh +0 -98
  102. package/src/demos/mcp/astrid-memory-demo.ts +0 -295
  103. package/src/demos/mcp/astrid-persona-memory.ts +0 -357
  104. package/src/demos/mcp/mcp-mongodb-demo.ts +0 -275
  105. package/src/demos/mcp/simple-astrid-memory.ts +0 -148
  106. package/src/demos/mcp/simple-mcp-demo.ts +0 -68
  107. package/src/demos/mcp/working-mcp-demo.ts +0 -62
  108. package/src/demos/model-alias-demo.ts +0 -0
  109. package/src/demos/tools/RAG_MEMORY_INTEGRATION.md +0 -267
  110. package/src/demos/tools/astrid-memory-demo.ts +0 -270
  111. package/src/demos/tools/astrid-production-memory-clean.ts +0 -785
  112. package/src/demos/tools/astrid-production-memory.ts +0 -558
  113. package/src/demos/tools/basic-translation-test.ts +0 -66
  114. package/src/demos/tools/chromadb-similarity-tuning.ts +0 -390
  115. package/src/demos/tools/clean-multilingual-conversation.ts +0 -209
  116. package/src/demos/tools/clean-translation-test.ts +0 -119
  117. package/src/demos/tools/clean-universal-multilingual-test.ts +0 -131
  118. package/src/demos/tools/complete-rag-demo.ts +0 -369
  119. package/src/demos/tools/complete-tool-demo.ts +0 -132
  120. package/src/demos/tools/demo-tool-calling.ts +0 -124
  121. package/src/demos/tools/dynamic-language-switching-test.ts +0 -251
  122. package/src/demos/tools/hybrid-thinking-test.ts +0 -154
  123. package/src/demos/tools/memory-integration-test.ts +0 -420
  124. package/src/demos/tools/multilingual-memory-system.ts +0 -802
  125. package/src/demos/tools/ondemand-translation-demo.ts +0 -655
  126. package/src/demos/tools/production-tool-demo.ts +0 -245
  127. package/src/demos/tools/revolutionary-multilingual-test.ts +0 -151
  128. package/src/demos/tools/rigorous-language-analysis.ts +0 -218
  129. package/src/demos/tools/test-universal-memory-system.ts +0 -126
  130. package/src/demos/tools/translation-integration-guide.ts +0 -346
  131. package/src/demos/tools/universal-memory-system.ts +0 -560
  132. package/src/gemma-channel.ts +0 -47
  133. package/src/gemma-diffusion.ts +0 -167
  134. package/src/http.ts +0 -261
  135. package/src/index.ts +0 -180
  136. package/src/interfaces.ts +0 -843
  137. package/src/mcp.ts +0 -345
  138. package/src/providers/anthropic.ts +0 -796
  139. package/src/providers/google.ts +0 -840
  140. package/src/providers/index.ts +0 -8
  141. package/src/providers/ollama.ts +0 -503
  142. package/src/providers/openai.ts +0 -587
  143. package/src/router.ts +0 -785
  144. package/src/stream-decoder.ts +0 -535
  145. package/src/structured-output.ts +0 -759
  146. package/src/test-scripts/test-advanced-tools.ts +0 -310
  147. package/src/test-scripts/test-google-deep-research.ts +0 -33
  148. package/src/test-scripts/test-google-streaming-enhanced.ts +0 -147
  149. package/src/test-scripts/test-google-streaming.ts +0 -63
  150. package/src/test-scripts/test-google-system-prompt-comprehensive.ts +0 -189
  151. package/src/test-scripts/test-google-thinking.ts +0 -46
  152. package/src/test-scripts/test-mcp-config.ts +0 -28
  153. package/src/test-scripts/test-mcp-connection.ts +0 -29
  154. package/src/test-scripts/test-system-message-positions.ts +0 -163
  155. package/src/test-scripts/test-system-prompt-improvement-demo.ts +0 -83
  156. package/src/test-scripts/test-tool-calling.ts +0 -231
  157. package/src/test-scripts/test-vllm-qwen36.ts +0 -256
  158. package/src/tests/ai-model.test.ts +0 -1614
  159. package/src/tests/auditor.test.ts +0 -224
  160. package/src/tests/gemma-diffusion.test.ts +0 -115
  161. package/src/tests/http.test.ts +0 -200
  162. package/src/tests/interfaces.test.ts +0 -117
  163. package/src/tests/providers/anthropic.test.ts +0 -118
  164. package/src/tests/providers/google.test.ts +0 -841
  165. package/src/tests/providers/ollama.test.ts +0 -1034
  166. package/src/tests/providers/openai.test.ts +0 -1511
  167. package/src/tests/router.test.ts +0 -254
  168. package/src/tests/stream-decoder.test.ts +0 -263
  169. package/src/tests/structured-output.test.ts +0 -1450
  170. package/src/tests/thinking.test.ts +0 -65
  171. package/src/tests/tools.test.ts +0 -175
  172. package/src/thinking.ts +0 -73
  173. package/src/tools.ts +0 -246
  174. package/src/zod-adapter.ts +0 -72
package/src/ai-model.ts DELETED
@@ -1,400 +0,0 @@
1
- /**
2
- * Universal LLM Client v3 — AIModel (The Universal Client)
3
- *
4
- * The only public-facing class. Developers configure one model with
5
- * multiple provider backends for transparent failover.
6
- *
7
- * Provider classes are internal — the user never imports them.
8
- */
9
-
10
- import {
11
- AIModelApiType,
12
- type AIModelConfig,
13
- type ProviderConfig,
14
- type LLMClientOptions,
15
- type LLMChatMessage,
16
- type LLMChatResponse,
17
- type ChatOptions,
18
- type ModelMetadata,
19
- type LLMFunction,
20
- type ToolHandler,
21
- type DeepResearchOptions,
22
- type DeepResearchResult,
23
- type DeepResearchEvent,
24
- } from './interfaces.js';
25
- import type { DecodedEvent } from './stream-decoder.js';
26
- import { Router, type RouterConfig, type ProviderStatus } from './router.js';
27
- import type { Auditor } from './auditor.js';
28
- import { NoopAuditor } from './auditor.js';
29
- import { OllamaClient } from './providers/ollama.js';
30
- import { OpenAICompatibleClient } from './providers/openai.js';
31
- import { GoogleClient } from './providers/google.js';
32
- import { AnthropicClient } from './providers/anthropic.js';
33
- import { BaseLLMClient } from './client.js';
34
- import {
35
- type StructuredOutputResult,
36
- type SchemaConfig,
37
- } from './structured-output.js';
38
-
39
- // ============================================================================
40
- // Default Provider URLs
41
- // ============================================================================
42
-
43
- const DEFAULT_URLS: Record<string, string> = {
44
- ollama: 'http://localhost:11434',
45
- openai: 'https://api.openai.com',
46
- llamacpp: 'http://localhost:8080',
47
- anthropic: 'https://api.anthropic.com',
48
- // google and vertex build their own URLs internally
49
- };
50
-
51
- // ============================================================================
52
- // AIModel — The Universal Client
53
- // ============================================================================
54
-
55
- export class AIModel {
56
- private router: Router;
57
- private auditor: Auditor;
58
- private config: AIModelConfig;
59
-
60
- constructor(config: AIModelConfig) {
61
- this.config = config;
62
- this.auditor = config.auditor ?? new NoopAuditor();
63
-
64
- const routerConfig: RouterConfig = {
65
- retriesPerProvider: config.retries ?? 2,
66
- auditor: this.auditor,
67
- };
68
- this.router = new Router(routerConfig);
69
-
70
- // Initialize providers in order
71
- for (let i = 0; i < config.providers.length; i++) {
72
- const providerConfig = config.providers[i]!;
73
- const client = this.createClient(providerConfig);
74
- const id = `${this.normalizeType(providerConfig.type)}-${i}`;
75
-
76
- this.router.addProvider({
77
- id,
78
- client,
79
- priority: providerConfig.priority ?? i,
80
- modelOverride: providerConfig.model,
81
- });
82
- }
83
- }
84
-
85
- // ========================================================================
86
- // Chat
87
- // ========================================================================
88
-
89
- /** Send a chat request with automatic failover across providers */
90
- async chat(
91
- messages: LLMChatMessage[],
92
- options?: ChatOptions,
93
- ): Promise<LLMChatResponse> {
94
- return this.router.chat(messages, options);
95
- }
96
-
97
- /** Chat with automatic tool execution (multi-turn loop) */
98
- async chatWithTools(
99
- messages: LLMChatMessage[],
100
- options?: ChatOptions & { maxIterations?: number },
101
- ): Promise<LLMChatResponse> {
102
- return this.router.chatWithTools(messages, options);
103
- }
104
-
105
- /** Stream chat response with pluggable decoder strategy */
106
- async *chatStream(
107
- messages: LLMChatMessage[],
108
- options?: ChatOptions,
109
- ): AsyncGenerator<DecodedEvent, LLMChatResponse | void, unknown> {
110
- return yield* this.router.chatStream(messages, options);
111
- }
112
-
113
- // ========================================================================
114
- // Structured Output
115
- // ========================================================================
116
-
117
- /**
118
- * Generate structured output from the LLM with automatic failover.
119
- * Validates the response against the provided Zod schema.
120
- * Throws StructuredOutputError on validation failure.
121
- *
122
- * @template T The output type
123
- * @param config Schema configuration (JSON Schema + optional validator)
124
- * @param messages Chat messages to send
125
- * @param options Additional options (temperature, maxTokens, etc.)
126
- * @returns Promise resolving to validated structured output
127
- * @throws StructuredOutputError if JSON parsing fails or validation fails
128
- *
129
- * @example
130
- * ```typescript
131
- * import { fromZod } from 'universal-llm-client/zod';
132
- * const UserConfig = fromZod(z.object({
133
- * name: z.string(),
134
- * age: z.number(),
135
- * }));
136
- *
137
- * const user = await model.generateStructured(UserConfig, [
138
- * { role: 'user', content: 'Generate a user profile' },
139
- * ]);
140
- * // user.name: string, user.age: number
141
- * ```
142
- */
143
- async generateStructured<T>(
144
- config: SchemaConfig<T>,
145
- messages: LLMChatMessage[],
146
- options?: ChatOptions,
147
- ): Promise<T> {
148
- return this.router.generateStructured(config, messages, options);
149
- }
150
-
151
- /**
152
- * Try to generate structured output, returning a result object instead of throwing.
153
- * Same as generateStructured but returns { ok: true, value } on success
154
- * and { ok: false, error, rawOutput } on failure.
155
- *
156
- * @template T The output type
157
- * @param config Schema configuration (JSON Schema + optional validator)
158
- * @param messages Chat messages to send
159
- * @param options Additional options (temperature, maxTokens, etc.)
160
- * @returns StructuredOutputResult<T> - either success with value or failure with error
161
- *
162
- * @example
163
- * ```typescript
164
- * const result = await model.tryParseStructured(config, messages);
165
- *
166
- * if (result.ok) {
167
- * console.log('User:', result.value.name);
168
- * } else {
169
- * console.log('Error:', result.error.message);
170
- * console.log('Raw output:', result.rawOutput);
171
- * }
172
- * ```
173
- */
174
- async tryParseStructured<T>(
175
- config: SchemaConfig<T>,
176
- messages: LLMChatMessage[],
177
- options?: ChatOptions,
178
- ): Promise<StructuredOutputResult<T>> {
179
- return this.router.tryParseStructured(config, messages, options);
180
- }
181
-
182
- /**
183
- * Stream structured output with partial validated objects.
184
- *
185
- * Yields partial validated objects as JSON generates, then returns the
186
- * complete validated object on stream completion.
187
- *
188
- * For invalid partial JSON, no yield occurs (partial validation is best-effort).
189
- * On stream completion, if the final JSON fails validation, throws StructuredOutputError.
190
- *
191
- * @template T The output type
192
- * @param config Schema configuration (JSON Schema + optional validator)
193
- * @param messages Chat messages to send
194
- * @param options Additional options (temperature, maxTokens, etc.)
195
- * @yields Partial validated objects as the JSON stream progresses
196
- * @returns Complete validated object on stream completion
197
- * @throws StructuredOutputError if final validation fails
198
- *
199
- * @example
200
- * ```typescript
201
- * import { fromZod } from 'universal-llm-client/zod';
202
- * const UserConfig = fromZod(z.object({
203
- * name: z.string(),
204
- * age: z.number(),
205
- * }));
206
- *
207
- * const stream = model.generateStructuredStream(UserConfig, [
208
- * { role: 'user', content: 'Generate a user' },
209
- * ]);
210
- *
211
- * for await (const partial of stream) {
212
- * console.log('Partial user:', partial);
213
- * }
214
- * ```
215
- */
216
- async *generateStructuredStream<T>(
217
- config: SchemaConfig<T>,
218
- messages: LLMChatMessage[],
219
- options?: ChatOptions,
220
- ): AsyncGenerator<T, T, unknown> {
221
- return yield* this.router.generateStructuredStream(config, messages, options);
222
- }
223
-
224
- // ========================================================================
225
- // Embeddings
226
- // ========================================================================
227
-
228
- /** Generate embedding for a single text */
229
- async embed(text: string): Promise<number[]> {
230
- return this.router.embed(text);
231
- }
232
-
233
- /** Generate embeddings for multiple texts */
234
- async embedArray(texts: string[]): Promise<number[][]> {
235
- return this.router.embedArray(texts);
236
- }
237
-
238
- // ========================================================================
239
- // Deep Research (Gemini-only)
240
- // ========================================================================
241
-
242
- private getGoogleClient(method: string): GoogleClient {
243
- const googleClients = this.router.getClients().filter(
244
- (c): c is GoogleClient => c instanceof GoogleClient,
245
- );
246
- // Prefer an AI Studio client — Vertex AI doesn't support Deep Research.
247
- const aiStudio = googleClients.find(c => c.supportsDeepResearch());
248
- if (aiStudio) return aiStudio;
249
- if (googleClients.length > 0) {
250
- throw new Error(
251
- `${method} requires an AI Studio Google provider (type: "google"); Vertex AI is not supported for Deep Research.`,
252
- );
253
- }
254
- throw new Error(
255
- `${method} requires a Google provider (type: "google"). None is configured.`,
256
- );
257
- }
258
-
259
- /**
260
- * Run an agentic Deep Research interaction (Gemini only): creates it and
261
- * polls until completion. Throws if no Google provider is configured.
262
- */
263
- async deepResearch(input: string, options?: DeepResearchOptions): Promise<DeepResearchResult> {
264
- return this.getGoogleClient('deepResearch').deepResearch(input, options);
265
- }
266
-
267
- /**
268
- * Stream a Deep Research interaction's intermediate thought/text/step events
269
- * (Gemini only), returning the final result. Throws if no Google provider.
270
- */
271
- async *deepResearchStream(
272
- input: string,
273
- options?: DeepResearchOptions,
274
- ): AsyncGenerator<DeepResearchEvent, DeepResearchResult, unknown> {
275
- return yield* this.getGoogleClient('deepResearchStream').deepResearchStream(input, options);
276
- }
277
-
278
- // ========================================================================
279
- // Tool Registration
280
- // ========================================================================
281
-
282
- /** Register a tool callable by the LLM (broadcast to all providers) */
283
- registerTool(
284
- name: string,
285
- description: string,
286
- parameters: LLMFunction['parameters'],
287
- handler: ToolHandler,
288
- ): void {
289
- this.router.registerTool(name, description, parameters, handler);
290
- }
291
-
292
- /** Register multiple tools at once */
293
- registerTools(
294
- tools: Array<{
295
- name: string;
296
- description: string;
297
- parameters: LLMFunction['parameters'];
298
- handler: ToolHandler;
299
- }>,
300
- ): void {
301
- this.router.registerTools(tools);
302
- }
303
-
304
- // ========================================================================
305
- // Model Management
306
- // ========================================================================
307
-
308
- /** Get available models from all configured providers */
309
- async getModels(): Promise<string[]> {
310
- return this.router.getModels();
311
- }
312
-
313
- /** Get metadata about the current model (context length, capabilities) */
314
- async getModelInfo(): Promise<ModelMetadata> {
315
- return this.router.getModelInfo();
316
- }
317
-
318
- /** Switch model at runtime (updates all providers) */
319
- setModel(name: string): void {
320
- this.config.model = name;
321
- // The model name change will be picked up by the providers
322
- // through the router on next request
323
- }
324
-
325
- /** Get the current model name */
326
- get model(): string {
327
- return this.config.model;
328
- }
329
-
330
- // ========================================================================
331
- // Provider Status
332
- // ========================================================================
333
-
334
- /** Get health/status of all configured providers */
335
- getProviderStatus(): ProviderStatus[] {
336
- return this.router.getStatus();
337
- }
338
-
339
- // ========================================================================
340
- // Lifecycle
341
- // ========================================================================
342
-
343
- /** Clean shutdown — flush auditor, disconnect MCP, etc. */
344
- async dispose(): Promise<void> {
345
- await this.auditor.flush?.();
346
- }
347
-
348
- // ========================================================================
349
- // Internal: Provider Factory
350
- // ========================================================================
351
-
352
- private createClient(providerConfig: ProviderConfig): BaseLLMClient {
353
- const type = this.normalizeType(providerConfig.type);
354
- const modelName = providerConfig.model ?? this.config.model;
355
-
356
- const clientOptions: LLMClientOptions = {
357
- model: modelName,
358
- url: providerConfig.url ?? DEFAULT_URLS[type] ?? '',
359
- apiType: type as AIModelApiType,
360
- apiKey: providerConfig.apiKey,
361
- timeout: this.config.timeout ?? 30000,
362
- retries: this.config.retries ?? 2,
363
- debug: this.config.debug ?? false,
364
- defaultParameters: this.config.defaultParameters,
365
- // Preserve `undefined` (not set) vs explicit false so providers can
366
- // decide whether to send a thinking toggle at all.
367
- thinking: this.config.thinking,
368
- region: providerConfig.region,
369
- apiVersion: providerConfig.apiVersion,
370
- extraHeaders: providerConfig.headers,
371
- queryParams: providerConfig.queryParams,
372
- authHeader: providerConfig.authHeader,
373
- authPrefix: providerConfig.authPrefix,
374
- apiBasePath: providerConfig.apiBasePath,
375
- };
376
-
377
- switch (type) {
378
- case 'ollama':
379
- return new OllamaClient(clientOptions, this.auditor);
380
-
381
- case 'openai':
382
- case 'llamacpp':
383
- return new OpenAICompatibleClient(clientOptions, this.auditor);
384
-
385
- case 'google':
386
- case 'vertex':
387
- return new GoogleClient(clientOptions, this.auditor);
388
-
389
- case 'anthropic':
390
- return new AnthropicClient(clientOptions, this.auditor);
391
-
392
- default:
393
- throw new Error(`Unknown provider type: ${type}`);
394
- }
395
- }
396
-
397
- private normalizeType(type: string): string {
398
- return type.toLowerCase();
399
- }
400
- }
package/src/auditor.ts DELETED
@@ -1,213 +0,0 @@
1
- /**
2
- * Universal LLM Client v3 — Auditor (Observability)
3
- *
4
- * Every LLM interaction (request, response, tool call, retry, failover)
5
- * is recorded through the Auditor interface. Frameworks inject their own
6
- * Auditor for dashboards, cost tracking, or behavioral scoring.
7
- */
8
-
9
- import type { TokenUsageInfo, ToolExecutionResult } from './interfaces.js';
10
-
11
- // ============================================================================
12
- // Audit Event
13
- // ============================================================================
14
-
15
- export type AuditEventType =
16
- | 'request'
17
- | 'response'
18
- | 'stream_start'
19
- | 'stream_end'
20
- | 'tool_call'
21
- | 'tool_result'
22
- | 'error'
23
- | 'retry'
24
- | 'failover'
25
- | 'structured_request'
26
- | 'structured_response'
27
- | 'structured_validation_error';
28
-
29
- export interface AuditEvent {
30
- /** Unix timestamp in ms */
31
- timestamp: number;
32
- /** Event type */
33
- type: AuditEventType;
34
- /** Provider that generated this event */
35
- provider?: string;
36
- /** Model name */
37
- model?: string;
38
- /** Duration in ms (for request/response pairs) */
39
- duration?: number;
40
- /** Token usage (for response events) */
41
- usage?: TokenUsageInfo;
42
- /** Tool execution details (for tool_call/tool_result events) */
43
- toolExecution?: ToolExecutionResult;
44
- /** Error message (for error/retry events) */
45
- error?: string;
46
- /** Arbitrary metadata for framework-specific data */
47
- metadata?: Record<string, unknown>;
48
- /** Schema name for structured output events */
49
- schemaName?: string;
50
- /** Raw output snippet for validation errors */
51
- rawOutput?: string;
52
- }
53
-
54
- // ============================================================================
55
- // Auditor Interface
56
- // ============================================================================
57
-
58
- /**
59
- * Interface for LLM observability.
60
- *
61
- * Implement this to capture all LLM lifecycle events.
62
- * The library calls `record()` at every interaction point.
63
- */
64
- export interface Auditor {
65
- /** Record an audit event */
66
- record(event: AuditEvent): void;
67
- /** Flush any buffered events (optional) */
68
- flush?(): Promise<void>;
69
- }
70
-
71
- // ============================================================================
72
- // Built-in Auditors
73
- // ============================================================================
74
-
75
- /**
76
- * Zero-overhead auditor that discards all events.
77
- * Used as the default when no auditor is configured.
78
- */
79
- export class NoopAuditor implements Auditor {
80
- record(_event: AuditEvent): void {
81
- // Intentionally empty
82
- }
83
- }
84
-
85
- /**
86
- * Structured console logging auditor.
87
- * Useful for development and debugging.
88
- */
89
- export class ConsoleAuditor implements Auditor {
90
- private prefix: string;
91
-
92
- constructor(prefix: string = '[LLM]') {
93
- this.prefix = prefix;
94
- }
95
-
96
- record(event: AuditEvent): void {
97
- const parts = [
98
- this.prefix,
99
- event.type.toUpperCase(),
100
- event.provider ? `[${event.provider}]` : '',
101
- event.model ? `(${event.model})` : '',
102
- ].filter(Boolean);
103
-
104
- switch (event.type) {
105
- case 'request':
106
- console.log(parts.join(' '), '→');
107
- break;
108
- case 'response':
109
- console.log(
110
- parts.join(' '),
111
- event.duration ? `${event.duration}ms` : '',
112
- event.usage ? `${event.usage.totalTokens} tokens` : '',
113
- );
114
- break;
115
- case 'stream_start':
116
- console.log(parts.join(' '), 'streaming...');
117
- break;
118
- case 'stream_end':
119
- console.log(
120
- parts.join(' '),
121
- 'done',
122
- event.duration ? `${event.duration}ms` : '',
123
- );
124
- break;
125
- case 'tool_call':
126
- console.log(parts.join(' '), event.toolExecution?.tool_call_id ?? '');
127
- break;
128
- case 'tool_result':
129
- console.log(
130
- parts.join(' '),
131
- event.toolExecution?.error ? '❌' : '✅',
132
- event.toolExecution?.duration ? `${event.toolExecution.duration}ms` : '',
133
- );
134
- break;
135
- case 'error':
136
- console.error(parts.join(' '), event.error ?? 'Unknown error');
137
- break;
138
- case 'retry':
139
- console.warn(parts.join(' '), event.error ?? '', event.metadata ?? '');
140
- break;
141
- case 'failover':
142
- console.warn(parts.join(' '), '→', event.metadata?.['nextProvider'] ?? '');
143
- break;
144
- case 'structured_request':
145
- console.log(
146
- parts.join(' '),
147
- `schema=${event.schemaName ?? 'unknown'}`,
148
- '→',
149
- );
150
- break;
151
- case 'structured_response':
152
- console.log(
153
- parts.join(' '),
154
- event.duration ? `${event.duration}ms` : '',
155
- `schema=${event.schemaName ?? 'unknown'}`,
156
- );
157
- break;
158
- case 'structured_validation_error':
159
- console.error(
160
- parts.join(' '),
161
- `schema=${event.schemaName ?? 'unknown'}`,
162
- event.error ?? 'Validation failed',
163
- event.rawOutput ? `raw=${event.rawOutput.slice(0, 50)}...` : '',
164
- );
165
- break;
166
- }
167
- }
168
- }
169
-
170
- /**
171
- * Buffered auditor that collects events for batch processing.
172
- * Useful for custom sinks (OpenTelemetry, DataDog, databases, etc.)
173
- */
174
- export class BufferedAuditor implements Auditor {
175
- private events: AuditEvent[] = [];
176
- private maxBufferSize: number;
177
- private onFlush?: (events: AuditEvent[]) => Promise<void>;
178
-
179
- constructor(options: {
180
- maxBufferSize?: number;
181
- onFlush?: (events: AuditEvent[]) => Promise<void>;
182
- } = {}) {
183
- this.maxBufferSize = options.maxBufferSize ?? 1000;
184
- this.onFlush = options.onFlush;
185
- }
186
-
187
- record(event: AuditEvent): void {
188
- this.events.push(event);
189
- if (this.events.length >= this.maxBufferSize) {
190
- // Auto-flush when buffer is full (fire and forget)
191
- this.flush().catch(() => {});
192
- }
193
- }
194
-
195
- /** Get all buffered events */
196
- getEvents(): ReadonlyArray<AuditEvent> {
197
- return this.events;
198
- }
199
-
200
- /** Flush buffered events to the configured sink */
201
- async flush(): Promise<void> {
202
- if (this.events.length === 0) return;
203
- const batch = this.events.splice(0);
204
- if (this.onFlush) {
205
- await this.onFlush(batch);
206
- }
207
- }
208
-
209
- /** Clear all buffered events without flushing */
210
- clear(): void {
211
- this.events.length = 0;
212
- }
213
- }