universal-llm-client 4.0.0 → 4.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.
Files changed (127) hide show
  1. package/dist/ai-model.d.ts +20 -22
  2. package/dist/ai-model.d.ts.map +1 -1
  3. package/dist/ai-model.js +26 -23
  4. package/dist/ai-model.js.map +1 -1
  5. package/dist/client.d.ts +5 -5
  6. package/dist/client.d.ts.map +1 -1
  7. package/dist/client.js +17 -9
  8. package/dist/client.js.map +1 -1
  9. package/dist/http.d.ts +2 -0
  10. package/dist/http.d.ts.map +1 -1
  11. package/dist/http.js +1 -0
  12. package/dist/http.js.map +1 -1
  13. package/dist/index.d.ts +3 -3
  14. package/dist/index.d.ts.map +1 -1
  15. package/dist/index.js +4 -4
  16. package/dist/index.js.map +1 -1
  17. package/dist/interfaces.d.ts +49 -11
  18. package/dist/interfaces.d.ts.map +1 -1
  19. package/dist/interfaces.js +14 -0
  20. package/dist/interfaces.js.map +1 -1
  21. package/dist/providers/anthropic.d.ts +56 -0
  22. package/dist/providers/anthropic.d.ts.map +1 -0
  23. package/dist/providers/anthropic.js +524 -0
  24. package/dist/providers/anthropic.js.map +1 -0
  25. package/dist/providers/google.d.ts +5 -0
  26. package/dist/providers/google.d.ts.map +1 -1
  27. package/dist/providers/google.js +64 -8
  28. package/dist/providers/google.js.map +1 -1
  29. package/dist/providers/index.d.ts +1 -0
  30. package/dist/providers/index.d.ts.map +1 -1
  31. package/dist/providers/index.js +1 -0
  32. package/dist/providers/index.js.map +1 -1
  33. package/dist/providers/ollama.d.ts.map +1 -1
  34. package/dist/providers/ollama.js +38 -11
  35. package/dist/providers/ollama.js.map +1 -1
  36. package/dist/providers/openai.d.ts.map +1 -1
  37. package/dist/providers/openai.js +9 -7
  38. package/dist/providers/openai.js.map +1 -1
  39. package/dist/router.d.ts +13 -33
  40. package/dist/router.d.ts.map +1 -1
  41. package/dist/router.js +33 -57
  42. package/dist/router.js.map +1 -1
  43. package/dist/stream-decoder.d.ts +29 -2
  44. package/dist/stream-decoder.d.ts.map +1 -1
  45. package/dist/stream-decoder.js +39 -11
  46. package/dist/stream-decoder.js.map +1 -1
  47. package/dist/structured-output.d.ts +107 -181
  48. package/dist/structured-output.d.ts.map +1 -1
  49. package/dist/structured-output.js +137 -192
  50. package/dist/structured-output.js.map +1 -1
  51. package/dist/zod-adapter.d.ts +44 -0
  52. package/dist/zod-adapter.d.ts.map +1 -0
  53. package/dist/zod-adapter.js +61 -0
  54. package/dist/zod-adapter.js.map +1 -0
  55. package/package.json +9 -1
  56. package/src/ai-model.ts +350 -0
  57. package/src/auditor.ts +213 -0
  58. package/src/client.ts +402 -0
  59. package/src/debug/debug-google-streaming.ts +97 -0
  60. package/src/debug/debug-tool-execution.ts +86 -0
  61. package/src/debug/test-lmstudio-tools.ts +155 -0
  62. package/src/demos/README.md +47 -0
  63. package/src/demos/basic/universal-llm-examples.ts +161 -0
  64. package/src/demos/mcp/astrid-memory-demo.ts +295 -0
  65. package/src/demos/mcp/astrid-persona-memory.ts +357 -0
  66. package/src/demos/mcp/mcp-mongodb-demo.ts +275 -0
  67. package/src/demos/mcp/simple-astrid-memory.ts +148 -0
  68. package/src/demos/mcp/simple-mcp-demo.ts +68 -0
  69. package/src/demos/mcp/working-mcp-demo.ts +62 -0
  70. package/src/demos/model-alias-demo.ts +0 -0
  71. package/src/demos/tools/RAG_MEMORY_INTEGRATION.md +267 -0
  72. package/src/demos/tools/astrid-memory-demo.ts +270 -0
  73. package/src/demos/tools/astrid-production-memory-clean.ts +785 -0
  74. package/src/demos/tools/astrid-production-memory.ts +558 -0
  75. package/src/demos/tools/basic-translation-test.ts +66 -0
  76. package/src/demos/tools/chromadb-similarity-tuning.ts +390 -0
  77. package/src/demos/tools/clean-multilingual-conversation.ts +209 -0
  78. package/src/demos/tools/clean-translation-test.ts +119 -0
  79. package/src/demos/tools/clean-universal-multilingual-test.ts +131 -0
  80. package/src/demos/tools/complete-rag-demo.ts +369 -0
  81. package/src/demos/tools/complete-tool-demo.ts +132 -0
  82. package/src/demos/tools/demo-tool-calling.ts +124 -0
  83. package/src/demos/tools/dynamic-language-switching-test.ts +251 -0
  84. package/src/demos/tools/hybrid-thinking-test.ts +154 -0
  85. package/src/demos/tools/memory-integration-test.ts +420 -0
  86. package/src/demos/tools/multilingual-memory-system.ts +802 -0
  87. package/src/demos/tools/ondemand-translation-demo.ts +655 -0
  88. package/src/demos/tools/production-tool-demo.ts +245 -0
  89. package/src/demos/tools/revolutionary-multilingual-test.ts +151 -0
  90. package/src/demos/tools/rigorous-language-analysis.ts +218 -0
  91. package/src/demos/tools/test-universal-memory-system.ts +126 -0
  92. package/src/demos/tools/translation-integration-guide.ts +346 -0
  93. package/src/demos/tools/universal-memory-system.ts +560 -0
  94. package/src/http.ts +247 -0
  95. package/src/index.ts +161 -0
  96. package/src/interfaces.ts +657 -0
  97. package/src/mcp.ts +345 -0
  98. package/src/providers/anthropic.ts +762 -0
  99. package/src/providers/google.ts +620 -0
  100. package/src/providers/index.ts +8 -0
  101. package/src/providers/ollama.ts +469 -0
  102. package/src/providers/openai.ts +392 -0
  103. package/src/router.ts +780 -0
  104. package/src/stream-decoder.ts +361 -0
  105. package/src/structured-output.ts +759 -0
  106. package/src/test-scripts/test-advanced-tools.ts +310 -0
  107. package/src/test-scripts/test-google-streaming-enhanced.ts +147 -0
  108. package/src/test-scripts/test-google-streaming.ts +63 -0
  109. package/src/test-scripts/test-google-system-prompt-comprehensive.ts +189 -0
  110. package/src/test-scripts/test-mcp-config.ts +28 -0
  111. package/src/test-scripts/test-mcp-connection.ts +29 -0
  112. package/src/test-scripts/test-system-message-positions.ts +163 -0
  113. package/src/test-scripts/test-system-prompt-improvement-demo.ts +83 -0
  114. package/src/test-scripts/test-tool-calling.ts +231 -0
  115. package/src/tests/ai-model.test.ts +1614 -0
  116. package/src/tests/auditor.test.ts +224 -0
  117. package/src/tests/http.test.ts +200 -0
  118. package/src/tests/interfaces.test.ts +117 -0
  119. package/src/tests/providers/google.test.ts +660 -0
  120. package/src/tests/providers/ollama.test.ts +954 -0
  121. package/src/tests/providers/openai.test.ts +1122 -0
  122. package/src/tests/router.test.ts +254 -0
  123. package/src/tests/stream-decoder.test.ts +179 -0
  124. package/src/tests/structured-output.test.ts +1450 -0
  125. package/src/tests/tools.test.ts +175 -0
  126. package/src/tools.ts +246 -0
  127. package/src/zod-adapter.ts +72 -0
package/src/http.ts ADDED
@@ -0,0 +1,247 @@
1
+ /**
2
+ * Universal LLM Client v3 — HTTP Utilities
3
+ *
4
+ * Zero-dependency HTTP layer using native fetch.
5
+ * Works on Node 22+, Bun, Deno, and browsers.
6
+ */
7
+
8
+ import type { LLMClientOptions } from './interfaces.js';
9
+
10
+ // ============================================================================
11
+ // Types
12
+ // ============================================================================
13
+
14
+ export interface HttpRequestOptions {
15
+ method?: 'GET' | 'POST';
16
+ headers?: Record<string, string>;
17
+ body?: unknown;
18
+ timeout?: number;
19
+ signal?: AbortSignal;
20
+ }
21
+
22
+ export interface HttpResponse<T = unknown> {
23
+ ok: boolean;
24
+ status: number;
25
+ data: T;
26
+ /** Response headers (when available) */
27
+ headers?: Headers;
28
+ }
29
+
30
+ // ============================================================================
31
+ // HTTP Request
32
+ // ============================================================================
33
+
34
+ /**
35
+ * Make an HTTP request with timeout and error handling.
36
+ * Uses native fetch (available in all target runtimes).
37
+ */
38
+ export async function httpRequest<T = unknown>(
39
+ url: string,
40
+ options: HttpRequestOptions = {},
41
+ ): Promise<HttpResponse<T>> {
42
+ const { method = 'GET', headers = {}, body, timeout = 30000, signal } = options;
43
+
44
+ const controller = new AbortController();
45
+ const timeoutId = setTimeout(() => controller.abort(), timeout);
46
+
47
+ // Combine external signal with timeout
48
+ const combinedSignal = signal
49
+ ? AbortSignal.any([signal, controller.signal])
50
+ : controller.signal;
51
+
52
+ try {
53
+ const response = await fetch(url, {
54
+ method,
55
+ headers: {
56
+ 'Content-Type': 'application/json',
57
+ ...headers,
58
+ },
59
+ body: body ? JSON.stringify(body) : undefined,
60
+ signal: combinedSignal,
61
+ });
62
+
63
+ clearTimeout(timeoutId);
64
+
65
+ if (!response.ok) {
66
+ const errorText = await response.text().catch(() => 'Unknown error');
67
+ throw new Error(`HTTP ${response.status}: ${errorText}`);
68
+ }
69
+
70
+ const data = (await response.json()) as T;
71
+
72
+ return {
73
+ ok: response.ok,
74
+ status: response.status,
75
+ data,
76
+ headers: response.headers,
77
+ };
78
+ } catch (error) {
79
+ clearTimeout(timeoutId);
80
+
81
+ if (error instanceof Error && error.name === 'AbortError') {
82
+ throw new Error(`Request timeout after ${timeout}ms: ${url}`);
83
+ }
84
+ throw error;
85
+ }
86
+ }
87
+
88
+ // ============================================================================
89
+ // Streaming HTTP
90
+ // ============================================================================
91
+
92
+ /**
93
+ * Make a streaming HTTP request.
94
+ * Yields raw string chunks as they arrive.
95
+ */
96
+ export async function* httpStream(
97
+ url: string,
98
+ options: HttpRequestOptions = {},
99
+ ): AsyncGenerator<string, void, unknown> {
100
+ const { method = 'POST', headers = {}, body, timeout = 120000, signal } = options;
101
+
102
+ const controller = new AbortController();
103
+ const timeoutId = setTimeout(() => controller.abort(), timeout);
104
+
105
+ const combinedSignal = signal
106
+ ? AbortSignal.any([signal, controller.signal])
107
+ : controller.signal;
108
+
109
+ try {
110
+ const response = await fetch(url, {
111
+ method,
112
+ headers: {
113
+ 'Content-Type': 'application/json',
114
+ ...headers,
115
+ },
116
+ body: body ? JSON.stringify(body) : undefined,
117
+ signal: combinedSignal,
118
+ });
119
+
120
+ clearTimeout(timeoutId);
121
+
122
+ if (!response.ok) {
123
+ const errorText = await response.text().catch(() => 'Unknown error');
124
+ throw new Error(`HTTP ${response.status}: ${errorText}`);
125
+ }
126
+
127
+ if (!response.body) {
128
+ throw new Error('No response body for streaming');
129
+ }
130
+
131
+ const reader = response.body.getReader();
132
+ const decoder = new TextDecoder();
133
+
134
+ try {
135
+ while (true) {
136
+ const { done, value } = await reader.read();
137
+ if (done) break;
138
+ yield decoder.decode(value, { stream: true });
139
+ }
140
+ } finally {
141
+ reader.releaseLock();
142
+ }
143
+ } catch (error) {
144
+ clearTimeout(timeoutId);
145
+
146
+ if (error instanceof Error && error.name === 'AbortError') {
147
+ throw new Error(`Stream timeout after ${timeout}ms: ${url}`);
148
+ }
149
+ throw error;
150
+ }
151
+ }
152
+
153
+ // ============================================================================
154
+ // Protocol Parsers
155
+ // ============================================================================
156
+
157
+ /**
158
+ * Parse NDJSON (newline-delimited JSON) stream.
159
+ * Used by Ollama's streaming API.
160
+ */
161
+ export async function* parseNDJSON<T = unknown>(
162
+ stream: AsyncGenerator<string>,
163
+ ): AsyncGenerator<T, void, unknown> {
164
+ let buffer = '';
165
+
166
+ for await (const chunk of stream) {
167
+ buffer += chunk;
168
+ const lines = buffer.split('\n');
169
+ buffer = lines.pop() ?? '';
170
+
171
+ for (const line of lines) {
172
+ const trimmed = line.trim();
173
+ if (!trimmed) continue;
174
+
175
+ try {
176
+ yield JSON.parse(trimmed) as T;
177
+ } catch {
178
+ // Skip invalid JSON lines
179
+ }
180
+ }
181
+ }
182
+
183
+ // Handle remaining buffer
184
+ if (buffer.trim()) {
185
+ try {
186
+ yield JSON.parse(buffer) as T;
187
+ } catch {
188
+ // Skip invalid JSON
189
+ }
190
+ }
191
+ }
192
+
193
+ /**
194
+ * Parse Server-Sent Events stream.
195
+ * Used by OpenAI-compatible APIs and LlamaCpp/vLLM.
196
+ */
197
+ export async function* parseSSE(
198
+ stream: AsyncGenerator<string>,
199
+ ): AsyncGenerator<{ event?: string; data: string }, void, unknown> {
200
+ let buffer = '';
201
+
202
+ for await (const chunk of stream) {
203
+ buffer += chunk;
204
+
205
+ // Split by double newlines (SSE event delimiter)
206
+ const events = buffer.split('\n\n');
207
+ buffer = events.pop() ?? '';
208
+
209
+ for (const event of events) {
210
+ const lines = event.split('\n');
211
+ let eventType: string | undefined;
212
+ const dataLines: string[] = [];
213
+
214
+ for (const line of lines) {
215
+ if (line.startsWith('event:')) {
216
+ eventType = line.slice(6).trim();
217
+ } else if (line.startsWith('data:')) {
218
+ dataLines.push(line.slice(5).trim());
219
+ }
220
+ }
221
+
222
+ const data = dataLines.join('\n');
223
+ if (data && data !== '[DONE]') {
224
+ yield { event: eventType, data };
225
+ }
226
+ }
227
+ }
228
+ }
229
+
230
+ // ============================================================================
231
+ // Header Utilities
232
+ // ============================================================================
233
+
234
+ /**
235
+ * Build standard headers for LLM API requests.
236
+ */
237
+ export function buildHeaders(options: LLMClientOptions): Record<string, string> {
238
+ const headers: Record<string, string> = {
239
+ 'Content-Type': 'application/json',
240
+ };
241
+
242
+ if (options.apiKey) {
243
+ headers['Authorization'] = `Bearer ${options.apiKey}`;
244
+ }
245
+
246
+ return headers;
247
+ }
package/src/index.ts ADDED
@@ -0,0 +1,161 @@
1
+ /**
2
+ * Universal LLM Client v3
3
+ *
4
+ * A universal LLM client with transparent provider failover,
5
+ * streaming tool execution, pluggable reasoning, and native observability.
6
+ *
7
+ * @module universal-llm-client
8
+ */
9
+
10
+ // ============================================================================
11
+ // Public API — The Universal Client
12
+ // ============================================================================
13
+
14
+ export { AIModel } from './ai-model.js';
15
+
16
+ // ============================================================================
17
+ // Types & Interfaces
18
+ // ============================================================================
19
+
20
+ export {
21
+ // Enums
22
+ AIModelApiType,
23
+ AIModelType,
24
+ // Config
25
+ type AIModelConfig,
26
+ type ProviderConfig,
27
+ type LLMClientOptions,
28
+ // Messages
29
+ type LLMChatMessage,
30
+ type LLMMessageContent,
31
+ type LLMContentPart,
32
+ type LLMTextContent,
33
+ type LLMImageContent,
34
+ type LLMAudioContent,
35
+ // Responses
36
+ type LLMChatResponse,
37
+ type TokenUsageInfo,
38
+ // Tools
39
+ type LLMToolCall,
40
+ type LLMToolDefinition,
41
+ type LLMFunction,
42
+ type ToolHandler,
43
+ type ToolExecutionResult,
44
+ type ToolRegistry,
45
+ type ToolRegistryEntry,
46
+ // Options
47
+ type ChatOptions,
48
+ type ResponseFormat,
49
+ type OutputOptions,
50
+ // Model info
51
+ type ModelMetadata,
52
+ // Helpers
53
+ textContent,
54
+ imageContent,
55
+ multimodalMessage,
56
+ extractTextContent,
57
+ hasImages,
58
+ audioContent,
59
+ hasAudio,
60
+ } from './interfaces.js';
61
+
62
+ // ============================================================================
63
+ // Observability
64
+ // ============================================================================
65
+
66
+ export {
67
+ type Auditor,
68
+ type AuditEvent,
69
+ type AuditEventType,
70
+ NoopAuditor,
71
+ ConsoleAuditor,
72
+ BufferedAuditor,
73
+ } from './auditor.js';
74
+
75
+ // ============================================================================
76
+ // Stream Decoding
77
+ // ============================================================================
78
+
79
+ export {
80
+ type StreamDecoder,
81
+ type DecodedEvent,
82
+ type DecoderCallback,
83
+ type DecoderType,
84
+ type DecoderOptions,
85
+ type DecoderFactory,
86
+ createDecoder,
87
+ registerDecoder,
88
+ getRegisteredDecoders,
89
+ PassthroughDecoder,
90
+ StandardChatDecoder,
91
+ InterleavedReasoningDecoder,
92
+ } from './stream-decoder.js';
93
+
94
+ // ============================================================================
95
+ // Tool Utilities
96
+ // ============================================================================
97
+
98
+ export {
99
+ ToolBuilder,
100
+ ToolExecutor,
101
+ createTimeTool,
102
+ createRandomNumberTool,
103
+ } from './tools.js';
104
+
105
+ // ============================================================================
106
+ // HTTP Utilities (for advanced use cases)
107
+ // ============================================================================
108
+
109
+ export {
110
+ httpRequest,
111
+ httpStream,
112
+ parseNDJSON,
113
+ parseSSE,
114
+ buildHeaders,
115
+ type HttpRequestOptions,
116
+ type HttpResponse,
117
+ } from './http.js';
118
+
119
+ // ============================================================================
120
+ // MCP Integration
121
+ // ============================================================================
122
+
123
+ export {
124
+ MCPToolBridge,
125
+ type MCPBridgeConfig,
126
+ type MCPServerConfig,
127
+ type MCPTool,
128
+ } from './mcp.js';
129
+
130
+ // ============================================================================
131
+ // Structured Output
132
+ // ============================================================================
133
+
134
+ export {
135
+ StructuredOutputError,
136
+ type StructuredOutputErrorOptions,
137
+ type StructuredOutputOptions,
138
+ type StructuredOutputResult,
139
+ type StructuredOutputSuccess,
140
+ type StructuredOutputFailure,
141
+ type JSONSchema,
142
+ type SchemaProvider,
143
+ type ProviderSchema,
144
+ type SchemaConfig,
145
+ isStructuredOutputSuccess,
146
+ isStructuredOutputFailure,
147
+ // Schema conversion utilities
148
+ normalizeJsonSchema,
149
+ convertToProviderSchema,
150
+ stripUnsupportedFeatures,
151
+ getJsonSchema,
152
+ getJsonSchemaFromConfig,
153
+ // Validation functions
154
+ parseStructured,
155
+ tryParseStructured,
156
+ validateStructuredOutput,
157
+ stripJsonFences,
158
+ // Streaming parser
159
+ StreamingJsonParser,
160
+ type StreamingStructuredResult,
161
+ } from './structured-output.js';