@yuva-devlab/ai-client 0.0.0-stage → 0.2.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.
- package/LICENSE +21 -0
- package/README.md +170 -2
- package/dist/index.cjs +1266 -0
- package/dist/index.cjs.map +1 -0
- package/dist/index.d.cts +1256 -0
- package/dist/index.d.ts +1256 -0
- package/dist/index.js +1233 -0
- package/dist/index.js.map +1 -0
- package/package.json +50 -3
package/dist/index.d.cts
ADDED
|
@@ -0,0 +1,1256 @@
|
|
|
1
|
+
import { z } from 'zod';
|
|
2
|
+
import { DomainError, ErrorCode } from '@yuva-devlab/errors';
|
|
3
|
+
|
|
4
|
+
/**
|
|
5
|
+
* @file packages/ai-client/src/constants/endpoints.constants.ts
|
|
6
|
+
* @description Centralized API endpoint URLs and protocols for AI providers across DevLab.
|
|
7
|
+
*
|
|
8
|
+
* All base URLs, API versions, and host paths are maintained here in a single location
|
|
9
|
+
* so version bumps and endpoint migrations never require searching through adapter code.
|
|
10
|
+
*
|
|
11
|
+
* @module @yuva-devlab/ai-client
|
|
12
|
+
*/
|
|
13
|
+
/**
|
|
14
|
+
* Canonical default endpoints for external AI model provider APIs.
|
|
15
|
+
*/
|
|
16
|
+
declare const AI_ENDPOINTS: Readonly<{
|
|
17
|
+
/** Local or edge Ollama REST service endpoint */
|
|
18
|
+
OLLAMA_DEFAULT_BASE_URL: "http://127.0.0.1:11434";
|
|
19
|
+
/** Groq OpenAI-compatible v1 chat completions endpoint */
|
|
20
|
+
GROQ_DEFAULT_BASE_URL: "https://api.groq.com/openai/v1";
|
|
21
|
+
/** OpenAI standard v1 REST API endpoint */
|
|
22
|
+
OPENAI_DEFAULT_BASE_URL: "https://api.openai.com/v1";
|
|
23
|
+
/** Anthropic Claude v1 REST messages API endpoint */
|
|
24
|
+
ANTHROPIC_DEFAULT_BASE_URL: "https://api.anthropic.com/v1";
|
|
25
|
+
/** Google Gemini Generative Language v1beta endpoint */
|
|
26
|
+
GOOGLE_GEMINI_DEFAULT_BASE_URL: "https://generativelanguage.googleapis.com/v1beta";
|
|
27
|
+
/** Required Anthropic API version header value */
|
|
28
|
+
ANTHROPIC_VERSION_HEADER: "2023-06-01";
|
|
29
|
+
}>;
|
|
30
|
+
|
|
31
|
+
/**
|
|
32
|
+
* @file packages/ai-client/src/constants/models.constants.ts
|
|
33
|
+
* @description Centralized catalog of default model identifiers across providers.
|
|
34
|
+
*
|
|
35
|
+
* Update model versions (e.g. gemma4, qwen2.5, llama-3.3, gemini-2.5) in this single file.
|
|
36
|
+
*
|
|
37
|
+
* @module @yuva-devlab/ai-client
|
|
38
|
+
*/
|
|
39
|
+
/**
|
|
40
|
+
* Standard default model names assigned to providers when none is explicitly specified in the request.
|
|
41
|
+
*/
|
|
42
|
+
declare const AI_DEFAULT_MODELS: Readonly<{
|
|
43
|
+
/** Default Ollama local model */
|
|
44
|
+
OLLAMA: "qwen2.5:7b";
|
|
45
|
+
/** Default Groq ultra-low latency model */
|
|
46
|
+
GROQ: "llama-3.3-70b-versatile";
|
|
47
|
+
/** Default Google Gemini model */
|
|
48
|
+
GOOGLE: "gemini-2.5-flash";
|
|
49
|
+
/** Default OpenAI model */
|
|
50
|
+
OPENAI: "gpt-4o-mini";
|
|
51
|
+
/** Default Anthropic Claude model */
|
|
52
|
+
ANTHROPIC: "claude-3-5-haiku-latest";
|
|
53
|
+
}>;
|
|
54
|
+
|
|
55
|
+
/**
|
|
56
|
+
* @file packages/ai-client/src/constants/execution.constants.ts
|
|
57
|
+
* @description Centralized execution parameters, default timeouts, and sampling parameters.
|
|
58
|
+
* @module @yuva-devlab/ai-client
|
|
59
|
+
*/
|
|
60
|
+
/**
|
|
61
|
+
* Standard execution limits and operational defaults for AI model queries.
|
|
62
|
+
*/
|
|
63
|
+
declare const AI_EXECUTION_DEFAULTS: Readonly<{
|
|
64
|
+
/** Default sampling temperature for balanced determinism and coherence */
|
|
65
|
+
DEFAULT_TEMPERATURE: 0.7;
|
|
66
|
+
/** Default per-request completion timeout in milliseconds (60 seconds) */
|
|
67
|
+
DEFAULT_TIMEOUT_MS: 60000;
|
|
68
|
+
/** Default upper bound for output token generation */
|
|
69
|
+
DEFAULT_MAX_OUTPUT_TOKENS: 4096;
|
|
70
|
+
/** Default retry limit for self-healing structured JSON output extraction */
|
|
71
|
+
DEFAULT_MAX_REPAIR_RETRIES: 2;
|
|
72
|
+
}>;
|
|
73
|
+
|
|
74
|
+
/**
|
|
75
|
+
* @file packages/ai-client/src/types/message.types.ts
|
|
76
|
+
* @description Canonical conversation turns, message roles, and tool call payload schemas for DevLab AI models.
|
|
77
|
+
* @module @yuva-devlab/ai-client
|
|
78
|
+
*/
|
|
79
|
+
|
|
80
|
+
/**
|
|
81
|
+
* Standardized message role enum in canonical UPPERCASE format.
|
|
82
|
+
* Maps 1:1 with model conversational roles across OpenAI, Anthropic, Google, and Ollama.
|
|
83
|
+
*/
|
|
84
|
+
declare const MessageRole: {
|
|
85
|
+
/** System directives establishing model persona, safety guidelines, and tool catalog */
|
|
86
|
+
readonly SYSTEM: "SYSTEM";
|
|
87
|
+
/** End-user input turn */
|
|
88
|
+
readonly USER: "USER";
|
|
89
|
+
/** Assistant generative completion turn or previous reasoning trace */
|
|
90
|
+
readonly ASSISTANT: "ASSISTANT";
|
|
91
|
+
/** Return output payload from an executed tool or external function */
|
|
92
|
+
readonly TOOL: "TOOL";
|
|
93
|
+
};
|
|
94
|
+
type MessageRole = (typeof MessageRole)[keyof typeof MessageRole];
|
|
95
|
+
/**
|
|
96
|
+
* Zod schema validating a structured tool invocation requested by a model.
|
|
97
|
+
*/
|
|
98
|
+
declare const ToolCallSchema: z.ZodObject<{
|
|
99
|
+
/** Unique tool call identifier assigned by the model provider */
|
|
100
|
+
id: z.ZodString;
|
|
101
|
+
/** Name of the tool or function requested to execute */
|
|
102
|
+
name: z.ZodString;
|
|
103
|
+
/** Parsed arguments dictionary conforming to the tool's input schema */
|
|
104
|
+
arguments: z.ZodRecord<z.ZodString, z.ZodUnknown>;
|
|
105
|
+
}, "strip", z.ZodTypeAny, {
|
|
106
|
+
id: string;
|
|
107
|
+
name: string;
|
|
108
|
+
arguments: Record<string, unknown>;
|
|
109
|
+
}, {
|
|
110
|
+
id: string;
|
|
111
|
+
name: string;
|
|
112
|
+
arguments: Record<string, unknown>;
|
|
113
|
+
}>;
|
|
114
|
+
type ToolCall = z.infer<typeof ToolCallSchema>;
|
|
115
|
+
/**
|
|
116
|
+
* Canonical AI message representation for conversations across all DevLab models.
|
|
117
|
+
*/
|
|
118
|
+
declare const AIMessageSchema: z.ZodObject<{
|
|
119
|
+
/** Conversational role of the turn */
|
|
120
|
+
role: z.ZodEnum<["SYSTEM", "USER", "ASSISTANT", "TOOL"]>;
|
|
121
|
+
/** Primary text content of the message */
|
|
122
|
+
content: z.ZodString;
|
|
123
|
+
/** Optional author username, agent name, or tool identifier */
|
|
124
|
+
name: z.ZodOptional<z.ZodString>;
|
|
125
|
+
/** Optional structured tool calls emitted by the model */
|
|
126
|
+
toolCalls: z.ZodOptional<z.ZodArray<z.ZodObject<{
|
|
127
|
+
/** Unique tool call identifier assigned by the model provider */
|
|
128
|
+
id: z.ZodString;
|
|
129
|
+
/** Name of the tool or function requested to execute */
|
|
130
|
+
name: z.ZodString;
|
|
131
|
+
/** Parsed arguments dictionary conforming to the tool's input schema */
|
|
132
|
+
arguments: z.ZodRecord<z.ZodString, z.ZodUnknown>;
|
|
133
|
+
}, "strip", z.ZodTypeAny, {
|
|
134
|
+
id: string;
|
|
135
|
+
name: string;
|
|
136
|
+
arguments: Record<string, unknown>;
|
|
137
|
+
}, {
|
|
138
|
+
id: string;
|
|
139
|
+
name: string;
|
|
140
|
+
arguments: Record<string, unknown>;
|
|
141
|
+
}>, "many">>;
|
|
142
|
+
/** Associated tool call ID when role is TOOL */
|
|
143
|
+
toolCallId: z.ZodOptional<z.ZodString>;
|
|
144
|
+
}, "strip", z.ZodTypeAny, {
|
|
145
|
+
role: "SYSTEM" | "USER" | "ASSISTANT" | "TOOL";
|
|
146
|
+
content: string;
|
|
147
|
+
name?: string | undefined;
|
|
148
|
+
toolCalls?: {
|
|
149
|
+
id: string;
|
|
150
|
+
name: string;
|
|
151
|
+
arguments: Record<string, unknown>;
|
|
152
|
+
}[] | undefined;
|
|
153
|
+
toolCallId?: string | undefined;
|
|
154
|
+
}, {
|
|
155
|
+
role: "SYSTEM" | "USER" | "ASSISTANT" | "TOOL";
|
|
156
|
+
content: string;
|
|
157
|
+
name?: string | undefined;
|
|
158
|
+
toolCalls?: {
|
|
159
|
+
id: string;
|
|
160
|
+
name: string;
|
|
161
|
+
arguments: Record<string, unknown>;
|
|
162
|
+
}[] | undefined;
|
|
163
|
+
toolCallId?: string | undefined;
|
|
164
|
+
}>;
|
|
165
|
+
type AIMessage = z.infer<typeof AIMessageSchema>;
|
|
166
|
+
/**
|
|
167
|
+
* Constructs a validated user message turn.
|
|
168
|
+
*
|
|
169
|
+
* @example
|
|
170
|
+
* ```typescript
|
|
171
|
+
* const msg = createUserMessage("Analyze this quarterly report", "analyst_bob");
|
|
172
|
+
* ```
|
|
173
|
+
*
|
|
174
|
+
* @param content - User's textual query or prompt.
|
|
175
|
+
* @param name - Optional author identifier for multi-user chat sessions.
|
|
176
|
+
* @returns Fully constructed AIMessage.
|
|
177
|
+
*/
|
|
178
|
+
declare function createUserMessage(content: string, name?: string): AIMessage;
|
|
179
|
+
/**
|
|
180
|
+
* Constructs a validated system prompt turn.
|
|
181
|
+
*
|
|
182
|
+
* @example
|
|
183
|
+
* ```typescript
|
|
184
|
+
* const sys = createSystemMessage("You are an autonomous SRE triage specialist.");
|
|
185
|
+
* ```
|
|
186
|
+
*
|
|
187
|
+
* @param content - System instructions establishing model behavior.
|
|
188
|
+
* @returns Fully constructed AIMessage.
|
|
189
|
+
*/
|
|
190
|
+
declare function createSystemMessage(content: string): AIMessage;
|
|
191
|
+
/**
|
|
192
|
+
* Constructs a validated assistant completion turn.
|
|
193
|
+
*
|
|
194
|
+
* @example
|
|
195
|
+
* ```typescript
|
|
196
|
+
* const assistant = createAssistantMessage("I will check the Kubernetes logs for you.");
|
|
197
|
+
* ```
|
|
198
|
+
*
|
|
199
|
+
* @param content - Assistant text response.
|
|
200
|
+
* @param toolCalls - Optional tool invocations requested by the model.
|
|
201
|
+
* @returns Fully constructed AIMessage.
|
|
202
|
+
*/
|
|
203
|
+
declare function createAssistantMessage(content: string, toolCalls?: ToolCall[]): AIMessage;
|
|
204
|
+
/**
|
|
205
|
+
* Constructs a validated tool result message turn.
|
|
206
|
+
*
|
|
207
|
+
* @example
|
|
208
|
+
* ```typescript
|
|
209
|
+
* const toolResult = createToolResultMessage("call_123", JSON.stringify({ status: "healthy" }), "healthcheck");
|
|
210
|
+
* ```
|
|
211
|
+
*
|
|
212
|
+
* @param toolCallId - ID of the originating tool invocation.
|
|
213
|
+
* @param content - Stringified output of the tool execution.
|
|
214
|
+
* @param name - Optional name of the tool executed.
|
|
215
|
+
* @returns Fully constructed AIMessage.
|
|
216
|
+
*/
|
|
217
|
+
declare function createToolResultMessage(toolCallId: string, content: string, name?: string): AIMessage;
|
|
218
|
+
|
|
219
|
+
/**
|
|
220
|
+
* @file packages/ai-client/src/types/request.types.ts
|
|
221
|
+
* @description Canonical request schemas and execution options for LLM provider completions.
|
|
222
|
+
* @module @yuva-devlab/ai-client
|
|
223
|
+
*/
|
|
224
|
+
|
|
225
|
+
/**
|
|
226
|
+
* Standard request options for LLM completions.
|
|
227
|
+
*
|
|
228
|
+
* @example
|
|
229
|
+
* ```typescript
|
|
230
|
+
* const options: LLMRequestOptions = {
|
|
231
|
+
* model: "gemma4:31b-cloud",
|
|
232
|
+
* temperature: 0.2,
|
|
233
|
+
* maxTokens: 2048,
|
|
234
|
+
* responseFormat: "json_object",
|
|
235
|
+
* timeoutMs: 30000,
|
|
236
|
+
* };
|
|
237
|
+
* ```
|
|
238
|
+
*/
|
|
239
|
+
declare const LLMRequestOptionsSchema: z.ZodObject<{
|
|
240
|
+
/** Model identifier string (e.g. "gemma4:31b-cloud", "qwen2.5:7b", "llama-3.3-70b-versatile") */
|
|
241
|
+
model: z.ZodString;
|
|
242
|
+
/** Sampling temperature: 0.0 deterministic to 1.0+ creative (defaults to AI_EXECUTION_DEFAULTS.DEFAULT_TEMPERATURE) */
|
|
243
|
+
temperature: z.ZodDefault<z.ZodNumber>;
|
|
244
|
+
/** Maximum completion output tokens */
|
|
245
|
+
maxTokens: z.ZodOptional<z.ZodNumber>;
|
|
246
|
+
/** Nucleus sampling probability cutoff */
|
|
247
|
+
topP: z.ZodOptional<z.ZodNumber>;
|
|
248
|
+
/** Optional stop sequences causing generation to cease */
|
|
249
|
+
stop: z.ZodOptional<z.ZodArray<z.ZodString, "many">>;
|
|
250
|
+
/** Response format enforcement (e.g. json_object or text) */
|
|
251
|
+
responseFormat: z.ZodDefault<z.ZodEnum<["text", "json_object"]>>;
|
|
252
|
+
/** Per-request timeout limit in milliseconds (defaults to AI_EXECUTION_DEFAULTS.DEFAULT_TIMEOUT_MS) */
|
|
253
|
+
timeoutMs: z.ZodDefault<z.ZodNumber>;
|
|
254
|
+
}, "strip", z.ZodTypeAny, {
|
|
255
|
+
model: string;
|
|
256
|
+
temperature: number;
|
|
257
|
+
responseFormat: "text" | "json_object";
|
|
258
|
+
timeoutMs: number;
|
|
259
|
+
maxTokens?: number | undefined;
|
|
260
|
+
topP?: number | undefined;
|
|
261
|
+
stop?: string[] | undefined;
|
|
262
|
+
}, {
|
|
263
|
+
model: string;
|
|
264
|
+
temperature?: number | undefined;
|
|
265
|
+
maxTokens?: number | undefined;
|
|
266
|
+
topP?: number | undefined;
|
|
267
|
+
stop?: string[] | undefined;
|
|
268
|
+
responseFormat?: "text" | "json_object" | undefined;
|
|
269
|
+
timeoutMs?: number | undefined;
|
|
270
|
+
}>;
|
|
271
|
+
type LLMRequestOptions = z.infer<typeof LLMRequestOptionsSchema>;
|
|
272
|
+
/**
|
|
273
|
+
* Full completion request payload combining options and conversation turns.
|
|
274
|
+
*
|
|
275
|
+
* @example
|
|
276
|
+
* ```typescript
|
|
277
|
+
* const req: LLMRequest = {
|
|
278
|
+
* model: "qwen2.5:7b",
|
|
279
|
+
* messages: [
|
|
280
|
+
* createUserMessage("What are the key architectural tenets of DevLab?"),
|
|
281
|
+
* ],
|
|
282
|
+
* temperature: 0.5,
|
|
283
|
+
* timeoutMs: 45000,
|
|
284
|
+
* };
|
|
285
|
+
* ```
|
|
286
|
+
*/
|
|
287
|
+
declare const LLMRequestSchema: z.ZodObject<{
|
|
288
|
+
/** Model identifier string (e.g. "gemma4:31b-cloud", "qwen2.5:7b", "llama-3.3-70b-versatile") */
|
|
289
|
+
model: z.ZodString;
|
|
290
|
+
/** Sampling temperature: 0.0 deterministic to 1.0+ creative (defaults to AI_EXECUTION_DEFAULTS.DEFAULT_TEMPERATURE) */
|
|
291
|
+
temperature: z.ZodDefault<z.ZodNumber>;
|
|
292
|
+
/** Maximum completion output tokens */
|
|
293
|
+
maxTokens: z.ZodOptional<z.ZodNumber>;
|
|
294
|
+
/** Nucleus sampling probability cutoff */
|
|
295
|
+
topP: z.ZodOptional<z.ZodNumber>;
|
|
296
|
+
/** Optional stop sequences causing generation to cease */
|
|
297
|
+
stop: z.ZodOptional<z.ZodArray<z.ZodString, "many">>;
|
|
298
|
+
/** Response format enforcement (e.g. json_object or text) */
|
|
299
|
+
responseFormat: z.ZodDefault<z.ZodEnum<["text", "json_object"]>>;
|
|
300
|
+
/** Per-request timeout limit in milliseconds (defaults to AI_EXECUTION_DEFAULTS.DEFAULT_TIMEOUT_MS) */
|
|
301
|
+
timeoutMs: z.ZodDefault<z.ZodNumber>;
|
|
302
|
+
} & {
|
|
303
|
+
/** Ordered conversation history */
|
|
304
|
+
messages: z.ZodArray<z.ZodObject<{
|
|
305
|
+
role: z.ZodEnum<["SYSTEM", "USER", "ASSISTANT", "TOOL"]>;
|
|
306
|
+
content: z.ZodString;
|
|
307
|
+
name: z.ZodOptional<z.ZodString>;
|
|
308
|
+
toolCalls: z.ZodOptional<z.ZodArray<z.ZodObject<{
|
|
309
|
+
id: z.ZodString;
|
|
310
|
+
name: z.ZodString;
|
|
311
|
+
arguments: z.ZodRecord<z.ZodString, z.ZodUnknown>;
|
|
312
|
+
}, "strip", z.ZodTypeAny, {
|
|
313
|
+
id: string;
|
|
314
|
+
name: string;
|
|
315
|
+
arguments: Record<string, unknown>;
|
|
316
|
+
}, {
|
|
317
|
+
id: string;
|
|
318
|
+
name: string;
|
|
319
|
+
arguments: Record<string, unknown>;
|
|
320
|
+
}>, "many">>;
|
|
321
|
+
toolCallId: z.ZodOptional<z.ZodString>;
|
|
322
|
+
}, "strip", z.ZodTypeAny, {
|
|
323
|
+
role: "SYSTEM" | "USER" | "ASSISTANT" | "TOOL";
|
|
324
|
+
content: string;
|
|
325
|
+
name?: string | undefined;
|
|
326
|
+
toolCalls?: {
|
|
327
|
+
id: string;
|
|
328
|
+
name: string;
|
|
329
|
+
arguments: Record<string, unknown>;
|
|
330
|
+
}[] | undefined;
|
|
331
|
+
toolCallId?: string | undefined;
|
|
332
|
+
}, {
|
|
333
|
+
role: "SYSTEM" | "USER" | "ASSISTANT" | "TOOL";
|
|
334
|
+
content: string;
|
|
335
|
+
name?: string | undefined;
|
|
336
|
+
toolCalls?: {
|
|
337
|
+
id: string;
|
|
338
|
+
name: string;
|
|
339
|
+
arguments: Record<string, unknown>;
|
|
340
|
+
}[] | undefined;
|
|
341
|
+
toolCallId?: string | undefined;
|
|
342
|
+
}>, "many">;
|
|
343
|
+
}, "strip", z.ZodTypeAny, {
|
|
344
|
+
model: string;
|
|
345
|
+
temperature: number;
|
|
346
|
+
responseFormat: "text" | "json_object";
|
|
347
|
+
timeoutMs: number;
|
|
348
|
+
messages: {
|
|
349
|
+
role: "SYSTEM" | "USER" | "ASSISTANT" | "TOOL";
|
|
350
|
+
content: string;
|
|
351
|
+
name?: string | undefined;
|
|
352
|
+
toolCalls?: {
|
|
353
|
+
id: string;
|
|
354
|
+
name: string;
|
|
355
|
+
arguments: Record<string, unknown>;
|
|
356
|
+
}[] | undefined;
|
|
357
|
+
toolCallId?: string | undefined;
|
|
358
|
+
}[];
|
|
359
|
+
maxTokens?: number | undefined;
|
|
360
|
+
topP?: number | undefined;
|
|
361
|
+
stop?: string[] | undefined;
|
|
362
|
+
}, {
|
|
363
|
+
model: string;
|
|
364
|
+
messages: {
|
|
365
|
+
role: "SYSTEM" | "USER" | "ASSISTANT" | "TOOL";
|
|
366
|
+
content: string;
|
|
367
|
+
name?: string | undefined;
|
|
368
|
+
toolCalls?: {
|
|
369
|
+
id: string;
|
|
370
|
+
name: string;
|
|
371
|
+
arguments: Record<string, unknown>;
|
|
372
|
+
}[] | undefined;
|
|
373
|
+
toolCallId?: string | undefined;
|
|
374
|
+
}[];
|
|
375
|
+
temperature?: number | undefined;
|
|
376
|
+
maxTokens?: number | undefined;
|
|
377
|
+
topP?: number | undefined;
|
|
378
|
+
stop?: string[] | undefined;
|
|
379
|
+
responseFormat?: "text" | "json_object" | undefined;
|
|
380
|
+
timeoutMs?: number | undefined;
|
|
381
|
+
}>;
|
|
382
|
+
type LLMRequest = z.infer<typeof LLMRequestSchema>;
|
|
383
|
+
|
|
384
|
+
/**
|
|
385
|
+
* @file packages/ai-client/src/types/response.types.ts
|
|
386
|
+
* @description Standardized LLM provider completion output and streaming chunk schemas.
|
|
387
|
+
* @module @yuva-devlab/ai-client
|
|
388
|
+
*/
|
|
389
|
+
|
|
390
|
+
/**
|
|
391
|
+
* Standard completion termination reason in canonical UPPERCASE format.
|
|
392
|
+
*/
|
|
393
|
+
declare const FinishReason: {
|
|
394
|
+
/** Generation finished naturally at a stop sequence or end of turn */
|
|
395
|
+
readonly STOP: "STOP";
|
|
396
|
+
/** Generation stopped due to hitting maxTokens limit */
|
|
397
|
+
readonly LENGTH: "LENGTH";
|
|
398
|
+
/** Model emitted one or more structured tool calls */
|
|
399
|
+
readonly TOOL_CALLS: "TOOL_CALLS";
|
|
400
|
+
/** Generation blocked by safety filters or policy guardrails */
|
|
401
|
+
readonly CONTENT_FILTER: "CONTENT_FILTER";
|
|
402
|
+
/** Generation aborted due to an internal execution error */
|
|
403
|
+
readonly ERROR: "ERROR";
|
|
404
|
+
};
|
|
405
|
+
type FinishReason = (typeof FinishReason)[keyof typeof FinishReason];
|
|
406
|
+
/**
|
|
407
|
+
* Token consumption metrics for accounting and billing meters.
|
|
408
|
+
*/
|
|
409
|
+
declare const LLMUsageSchema: z.ZodObject<{
|
|
410
|
+
/** Prompt / context tokens evaluated */
|
|
411
|
+
promptTokens: z.ZodDefault<z.ZodNumber>;
|
|
412
|
+
/** Tokens generated in completion */
|
|
413
|
+
completionTokens: z.ZodDefault<z.ZodNumber>;
|
|
414
|
+
/** Total tokens processed */
|
|
415
|
+
totalTokens: z.ZodDefault<z.ZodNumber>;
|
|
416
|
+
}, "strip", z.ZodTypeAny, {
|
|
417
|
+
promptTokens: number;
|
|
418
|
+
completionTokens: number;
|
|
419
|
+
totalTokens: number;
|
|
420
|
+
}, {
|
|
421
|
+
promptTokens?: number | undefined;
|
|
422
|
+
completionTokens?: number | undefined;
|
|
423
|
+
totalTokens?: number | undefined;
|
|
424
|
+
}>;
|
|
425
|
+
type LLMUsage = z.infer<typeof LLMUsageSchema>;
|
|
426
|
+
/**
|
|
427
|
+
* Standard complete response output returned by any LLM adapter.
|
|
428
|
+
*
|
|
429
|
+
* @example
|
|
430
|
+
* ```typescript
|
|
431
|
+
* const response: LLMResponse = {
|
|
432
|
+
* text: "Hello world!",
|
|
433
|
+
* finishReason: FinishReason.STOP,
|
|
434
|
+
* usage: { promptTokens: 10, completionTokens: 4, totalTokens: 14 },
|
|
435
|
+
* model: "gemma4:31b-cloud",
|
|
436
|
+
* durationMs: 420,
|
|
437
|
+
* };
|
|
438
|
+
* ```
|
|
439
|
+
*/
|
|
440
|
+
declare const LLMResponseSchema: z.ZodObject<{
|
|
441
|
+
/** Generated completion text */
|
|
442
|
+
text: z.ZodString;
|
|
443
|
+
/** Canonical termination reason */
|
|
444
|
+
finishReason: z.ZodEnum<["STOP", "LENGTH", "TOOL_CALLS", "CONTENT_FILTER", "ERROR"]>;
|
|
445
|
+
/** Token usage statistics */
|
|
446
|
+
usage: z.ZodObject<{
|
|
447
|
+
/** Prompt / context tokens evaluated */
|
|
448
|
+
promptTokens: z.ZodDefault<z.ZodNumber>;
|
|
449
|
+
/** Tokens generated in completion */
|
|
450
|
+
completionTokens: z.ZodDefault<z.ZodNumber>;
|
|
451
|
+
/** Total tokens processed */
|
|
452
|
+
totalTokens: z.ZodDefault<z.ZodNumber>;
|
|
453
|
+
}, "strip", z.ZodTypeAny, {
|
|
454
|
+
promptTokens: number;
|
|
455
|
+
completionTokens: number;
|
|
456
|
+
totalTokens: number;
|
|
457
|
+
}, {
|
|
458
|
+
promptTokens?: number | undefined;
|
|
459
|
+
completionTokens?: number | undefined;
|
|
460
|
+
totalTokens?: number | undefined;
|
|
461
|
+
}>;
|
|
462
|
+
/** Optional tool invocations emitted by the model */
|
|
463
|
+
toolCalls: z.ZodOptional<z.ZodArray<z.ZodObject<{
|
|
464
|
+
id: z.ZodString;
|
|
465
|
+
name: z.ZodString;
|
|
466
|
+
arguments: z.ZodRecord<z.ZodString, z.ZodUnknown>;
|
|
467
|
+
}, "strip", z.ZodTypeAny, {
|
|
468
|
+
id: string;
|
|
469
|
+
name: string;
|
|
470
|
+
arguments: Record<string, unknown>;
|
|
471
|
+
}, {
|
|
472
|
+
id: string;
|
|
473
|
+
name: string;
|
|
474
|
+
arguments: Record<string, unknown>;
|
|
475
|
+
}>, "many">>;
|
|
476
|
+
/** Model that generated the completion */
|
|
477
|
+
model: z.ZodString;
|
|
478
|
+
/** Wall-clock execution time in milliseconds */
|
|
479
|
+
durationMs: z.ZodOptional<z.ZodNumber>;
|
|
480
|
+
}, "strip", z.ZodTypeAny, {
|
|
481
|
+
model: string;
|
|
482
|
+
text: string;
|
|
483
|
+
finishReason: "STOP" | "LENGTH" | "TOOL_CALLS" | "CONTENT_FILTER" | "ERROR";
|
|
484
|
+
usage: {
|
|
485
|
+
promptTokens: number;
|
|
486
|
+
completionTokens: number;
|
|
487
|
+
totalTokens: number;
|
|
488
|
+
};
|
|
489
|
+
toolCalls?: {
|
|
490
|
+
id: string;
|
|
491
|
+
name: string;
|
|
492
|
+
arguments: Record<string, unknown>;
|
|
493
|
+
}[] | undefined;
|
|
494
|
+
durationMs?: number | undefined;
|
|
495
|
+
}, {
|
|
496
|
+
model: string;
|
|
497
|
+
text: string;
|
|
498
|
+
finishReason: "STOP" | "LENGTH" | "TOOL_CALLS" | "CONTENT_FILTER" | "ERROR";
|
|
499
|
+
usage: {
|
|
500
|
+
promptTokens?: number | undefined;
|
|
501
|
+
completionTokens?: number | undefined;
|
|
502
|
+
totalTokens?: number | undefined;
|
|
503
|
+
};
|
|
504
|
+
toolCalls?: {
|
|
505
|
+
id: string;
|
|
506
|
+
name: string;
|
|
507
|
+
arguments: Record<string, unknown>;
|
|
508
|
+
}[] | undefined;
|
|
509
|
+
durationMs?: number | undefined;
|
|
510
|
+
}>;
|
|
511
|
+
type LLMResponse = z.infer<typeof LLMResponseSchema>;
|
|
512
|
+
/**
|
|
513
|
+
* Incremental token chunk emitted during streaming completions.
|
|
514
|
+
*/
|
|
515
|
+
interface LLMStreamChunk {
|
|
516
|
+
/** Delta text token */
|
|
517
|
+
delta: string;
|
|
518
|
+
/** Finish reason if this chunk is the final stream message */
|
|
519
|
+
finishReason?: FinishReason;
|
|
520
|
+
/** Cumulative token usage if supplied by the provider */
|
|
521
|
+
usage?: LLMUsage;
|
|
522
|
+
}
|
|
523
|
+
|
|
524
|
+
/**
|
|
525
|
+
* @file packages/ai-client/src/types/credentials.types.ts
|
|
526
|
+
* @description Standardized typed credentials and resolver contracts following Big 3 SDK specifications.
|
|
527
|
+
*
|
|
528
|
+
* Eliminates implicit global process.env coupling by enforcing explicit configuration,
|
|
529
|
+
* dynamic credential resolvers (BYOK / Vault / Secrets Manager), and actionable error guidance.
|
|
530
|
+
*
|
|
531
|
+
* @module @yuva-devlab/ai-client
|
|
532
|
+
*/
|
|
533
|
+
|
|
534
|
+
/**
|
|
535
|
+
* Standard credential and connection properties for any AI provider.
|
|
536
|
+
*
|
|
537
|
+
* @example
|
|
538
|
+
* ```typescript
|
|
539
|
+
* const creds: ProviderCredentials = {
|
|
540
|
+
* apiKey: "sk-proj-...",
|
|
541
|
+
* baseUrl: "https://api.openai.com/v1",
|
|
542
|
+
* defaultModel: "gpt-4o",
|
|
543
|
+
* };
|
|
544
|
+
* ```
|
|
545
|
+
*/
|
|
546
|
+
interface ProviderCredentials {
|
|
547
|
+
/** Authentication API key or bearer token */
|
|
548
|
+
readonly apiKey?: string;
|
|
549
|
+
/** Custom base endpoint URL */
|
|
550
|
+
readonly baseUrl?: string;
|
|
551
|
+
/** Optional organization or tenant routing identifier */
|
|
552
|
+
readonly organizationId?: string;
|
|
553
|
+
/** Default model identifier if not specified in request */
|
|
554
|
+
readonly defaultModel?: string;
|
|
555
|
+
}
|
|
556
|
+
/**
|
|
557
|
+
* Dynamic asynchronous credential resolver function.
|
|
558
|
+
* Enables integration with AWS Secrets Manager, GCP Secret Manager, or multi-tenant BYOK databases.
|
|
559
|
+
*
|
|
560
|
+
* @example
|
|
561
|
+
* ```typescript
|
|
562
|
+
* const vaultResolver: CredentialResolver = async () => {
|
|
563
|
+
* const secret = await vaultClient.getSecret("ai/openai");
|
|
564
|
+
* return { apiKey: secret.token };
|
|
565
|
+
* };
|
|
566
|
+
* ```
|
|
567
|
+
*/
|
|
568
|
+
type CredentialResolver = () => Promise<ProviderCredentials> | ProviderCredentials;
|
|
569
|
+
/**
|
|
570
|
+
* Actionable error thrown when an adapter is invoked without necessary credentials.
|
|
571
|
+
* Provides clear instructions and hints to the developer or consuming agent.
|
|
572
|
+
*
|
|
573
|
+
* @example
|
|
574
|
+
* ```typescript
|
|
575
|
+
* throw new MissingCredentialError("OpenAI", "OPENAI_API_KEY");
|
|
576
|
+
* ```
|
|
577
|
+
*/
|
|
578
|
+
declare class MissingCredentialError extends DomainError<typeof ErrorCode.UNAUTHORIZED> {
|
|
579
|
+
constructor(providerName: string, envVarHint: string);
|
|
580
|
+
}
|
|
581
|
+
|
|
582
|
+
/**
|
|
583
|
+
* @file packages/ai-client/src/types/provider.interface.ts
|
|
584
|
+
* @description Master provider-agnostic interface implemented by all AI model adapters.
|
|
585
|
+
* @module @yuva-devlab/ai-client
|
|
586
|
+
*/
|
|
587
|
+
|
|
588
|
+
/**
|
|
589
|
+
* Universal interface for LLM adapters across local, edge, and cloud providers.
|
|
590
|
+
*
|
|
591
|
+
* All adapters (Ollama, Groq, Google, OpenAI, Anthropic, FallbackCascade)
|
|
592
|
+
* implement this exact interface to enable seamless polymorphism.
|
|
593
|
+
*
|
|
594
|
+
* @example
|
|
595
|
+
* ```typescript
|
|
596
|
+
* const provider: ILLMProvider = new OpenAIAdapter({ apiKey: "..." });
|
|
597
|
+
* const res = await provider.complete({
|
|
598
|
+
* model: "gpt-4o-mini",
|
|
599
|
+
* messages: [createUserMessage("Hello!")],
|
|
600
|
+
* });
|
|
601
|
+
* console.log(res.text);
|
|
602
|
+
* ```
|
|
603
|
+
*/
|
|
604
|
+
interface ILLMProvider {
|
|
605
|
+
/** Unique provider slug (e.g. "ollama", "groq", "google", "openai", "anthropic", "fallback-cascade") */
|
|
606
|
+
readonly name: string;
|
|
607
|
+
/**
|
|
608
|
+
* Executes a synchronous full completion against the model.
|
|
609
|
+
*
|
|
610
|
+
* @param request - Validated request payload containing model, messages, and options.
|
|
611
|
+
* @returns Complete model response including text, finish reason, and token usage metrics.
|
|
612
|
+
*/
|
|
613
|
+
complete(request: LLMRequest): Promise<LLMResponse>;
|
|
614
|
+
/**
|
|
615
|
+
* Streams completion tokens incrementally as they are generated by the model.
|
|
616
|
+
*
|
|
617
|
+
* @param request - Validated request payload containing model, messages, and options.
|
|
618
|
+
* @returns Async iterable yielding token delta chunks.
|
|
619
|
+
*/
|
|
620
|
+
stream(request: LLMRequest): AsyncIterable<LLMStreamChunk>;
|
|
621
|
+
/**
|
|
622
|
+
* Optional token estimation utility for budget and quota calculations.
|
|
623
|
+
*
|
|
624
|
+
* @param text - Input text string to count.
|
|
625
|
+
* @returns Estimated token count.
|
|
626
|
+
*/
|
|
627
|
+
countTokens?(text: string): Promise<number>;
|
|
628
|
+
}
|
|
629
|
+
|
|
630
|
+
/**
|
|
631
|
+
* @file packages/ai-client/src/config/env-resolver.ts
|
|
632
|
+
* @description Safe runtime environment credential loader for opt-in consumer usage.
|
|
633
|
+
*
|
|
634
|
+
* Utilizes centralized endpoints and default models from the constants module.
|
|
635
|
+
*
|
|
636
|
+
* @module @yuva-devlab/ai-client
|
|
637
|
+
*/
|
|
638
|
+
|
|
639
|
+
/**
|
|
640
|
+
* Maps standard environment variables for supported AI providers into a typed credentials object.
|
|
641
|
+
*
|
|
642
|
+
* @example
|
|
643
|
+
* ```typescript
|
|
644
|
+
* const creds = resolveEnvCredentials("groq");
|
|
645
|
+
* console.log(creds.apiKey);
|
|
646
|
+
* ```
|
|
647
|
+
*
|
|
648
|
+
* @param provider - Name of the provider (case-insensitive).
|
|
649
|
+
* @returns Resolved ProviderCredentials from ambient environment if available.
|
|
650
|
+
*/
|
|
651
|
+
declare function resolveEnvCredentials(provider: string): ProviderCredentials;
|
|
652
|
+
|
|
653
|
+
/**
|
|
654
|
+
* @file packages/ai-client/src/adapters/ollama/ollama.types.ts
|
|
655
|
+
* @description Wire types, configuration interfaces, and message mappers for the Ollama adapter.
|
|
656
|
+
* @module @yuva-devlab/ai-client
|
|
657
|
+
*/
|
|
658
|
+
|
|
659
|
+
/**
|
|
660
|
+
* Configuration options for initializing the OllamaAdapter.
|
|
661
|
+
*/
|
|
662
|
+
interface OllamaAdapterConfig {
|
|
663
|
+
/** Base URL for Ollama daemon (defaults to AI_ENDPOINTS.OLLAMA_DEFAULT_BASE_URL) */
|
|
664
|
+
baseUrl?: string;
|
|
665
|
+
/** Default model name if not specified in request */
|
|
666
|
+
defaultModel?: string;
|
|
667
|
+
/** Optional dynamic credential resolver for remote Ollama clusters */
|
|
668
|
+
credentials?: CredentialResolver;
|
|
669
|
+
}
|
|
670
|
+
/**
|
|
671
|
+
* Low-level wire format message payload expected by Ollama /api/chat.
|
|
672
|
+
*/
|
|
673
|
+
interface OllamaWireMessage {
|
|
674
|
+
role: string;
|
|
675
|
+
content: string;
|
|
676
|
+
tool_name?: string;
|
|
677
|
+
}
|
|
678
|
+
/**
|
|
679
|
+
* Low-level chunk payload streamed or returned by Ollama /api/chat.
|
|
680
|
+
*/
|
|
681
|
+
interface OllamaChatResponseChunk {
|
|
682
|
+
model?: string;
|
|
683
|
+
message?: OllamaWireMessage;
|
|
684
|
+
done?: boolean;
|
|
685
|
+
done_reason?: string;
|
|
686
|
+
prompt_eval_count?: number;
|
|
687
|
+
eval_count?: number;
|
|
688
|
+
}
|
|
689
|
+
/**
|
|
690
|
+
* Converts canonical AIMessage conversation turns to Ollama's wire format.
|
|
691
|
+
*
|
|
692
|
+
* @param messages - Canonical conversation history turns.
|
|
693
|
+
* @returns Array of Ollama wire format messages.
|
|
694
|
+
*/
|
|
695
|
+
declare function mapOllamaMessages(messages: LLMRequest["messages"]): OllamaWireMessage[];
|
|
696
|
+
|
|
697
|
+
/**
|
|
698
|
+
* @file packages/ai-client/src/adapters/ollama/ollama.adapter.ts
|
|
699
|
+
* @description Native Ollama HTTP adapter supporting local models and NDJSON streaming.
|
|
700
|
+
* @module @yuva-devlab/ai-client
|
|
701
|
+
*/
|
|
702
|
+
|
|
703
|
+
/**
|
|
704
|
+
* Ollama adapter executing completions via local or edge Ollama daemon instances.
|
|
705
|
+
*
|
|
706
|
+
* @example
|
|
707
|
+
* ```typescript
|
|
708
|
+
* const adapter = new OllamaAdapter({ baseUrl: "http://localhost:11434" });
|
|
709
|
+
* const res = await adapter.complete({
|
|
710
|
+
* model: "qwen2.5:7b",
|
|
711
|
+
* messages: [createUserMessage("Explain binary search trees")],
|
|
712
|
+
* });
|
|
713
|
+
* ```
|
|
714
|
+
*/
|
|
715
|
+
declare class OllamaAdapter implements ILLMProvider {
|
|
716
|
+
readonly name = "ollama";
|
|
717
|
+
private readonly config;
|
|
718
|
+
/**
|
|
719
|
+
* Initializes the Ollama adapter with optional configuration.
|
|
720
|
+
*
|
|
721
|
+
* @param config - Adapter connection and model configuration.
|
|
722
|
+
*/
|
|
723
|
+
constructor(config?: OllamaAdapterConfig);
|
|
724
|
+
/**
|
|
725
|
+
* Resolves effective connection parameters from explicit config, dynamic resolver, or ambient environment.
|
|
726
|
+
*/
|
|
727
|
+
private resolveCredentials;
|
|
728
|
+
/**
|
|
729
|
+
* Executes a full non-streaming completion request against Ollama's /api/chat endpoint.
|
|
730
|
+
*
|
|
731
|
+
* @param request - Validated completion request.
|
|
732
|
+
* @returns Complete model response with token usage metrics.
|
|
733
|
+
*/
|
|
734
|
+
complete(request: LLMRequest): Promise<LLMResponse>;
|
|
735
|
+
/**
|
|
736
|
+
* Initiates an NDJSON stream for token-by-token completion generation.
|
|
737
|
+
*
|
|
738
|
+
* @param request - Validated completion request.
|
|
739
|
+
* @returns Async iterable emitting token delta chunks.
|
|
740
|
+
*/
|
|
741
|
+
stream(request: LLMRequest): AsyncIterable<LLMStreamChunk>;
|
|
742
|
+
}
|
|
743
|
+
|
|
744
|
+
/**
|
|
745
|
+
* @file packages/ai-client/src/adapters/groq/groq.types.ts
|
|
746
|
+
* @description Wire types and configuration interfaces for Groq OpenAI-compatible endpoints.
|
|
747
|
+
* @module @yuva-devlab/ai-client
|
|
748
|
+
*/
|
|
749
|
+
|
|
750
|
+
/**
|
|
751
|
+
* Configuration options for initializing the GroqAdapter.
|
|
752
|
+
*/
|
|
753
|
+
interface GroqAdapterConfig {
|
|
754
|
+
/** Groq API authentication key */
|
|
755
|
+
apiKey?: string;
|
|
756
|
+
/** Custom base URL (defaults to AI_ENDPOINTS.GROQ_DEFAULT_BASE_URL) */
|
|
757
|
+
baseUrl?: string;
|
|
758
|
+
/** Default model identifier */
|
|
759
|
+
defaultModel?: string;
|
|
760
|
+
/** Optional dynamic credential resolver for secret managers */
|
|
761
|
+
credentials?: CredentialResolver;
|
|
762
|
+
}
|
|
763
|
+
/**
|
|
764
|
+
* Wire message schema for OpenAI-compatible completions.
|
|
765
|
+
*/
|
|
766
|
+
interface OpenAiWireMessage {
|
|
767
|
+
role: string;
|
|
768
|
+
content: string;
|
|
769
|
+
}
|
|
770
|
+
/**
|
|
771
|
+
* Wire response payload returned by Groq completions.
|
|
772
|
+
*/
|
|
773
|
+
interface GroqCompletionResponse {
|
|
774
|
+
choices: Array<{
|
|
775
|
+
message?: {
|
|
776
|
+
content?: string;
|
|
777
|
+
};
|
|
778
|
+
finish_reason?: string;
|
|
779
|
+
}>;
|
|
780
|
+
usage?: {
|
|
781
|
+
prompt_tokens: number;
|
|
782
|
+
completion_tokens: number;
|
|
783
|
+
total_tokens: number;
|
|
784
|
+
};
|
|
785
|
+
}
|
|
786
|
+
/**
|
|
787
|
+
* Converts canonical messages to wire format.
|
|
788
|
+
*
|
|
789
|
+
* @param messages - Canonical conversation turns.
|
|
790
|
+
* @returns Wire format messages.
|
|
791
|
+
*/
|
|
792
|
+
declare function mapGroqMessages(messages: LLMRequest["messages"]): OpenAiWireMessage[];
|
|
793
|
+
|
|
794
|
+
/**
|
|
795
|
+
* @file packages/ai-client/src/adapters/groq/groq.adapter.ts
|
|
796
|
+
* @description Ultra-low latency cloud inference adapter for Groq OpenAI-compatible endpoints.
|
|
797
|
+
* @module @yuva-devlab/ai-client
|
|
798
|
+
*/
|
|
799
|
+
|
|
800
|
+
/**
|
|
801
|
+
* Groq adapter routing inference to Groq LPU hardware clusters.
|
|
802
|
+
*
|
|
803
|
+
* @example
|
|
804
|
+
* ```typescript
|
|
805
|
+
* const adapter = new GroqAdapter({ apiKey: "gsk_..." });
|
|
806
|
+
* const res = await adapter.complete({
|
|
807
|
+
* model: "llama-3.3-70b-versatile",
|
|
808
|
+
* messages: [createUserMessage("Summarize the architectural diffs")],
|
|
809
|
+
* });
|
|
810
|
+
* ```
|
|
811
|
+
*/
|
|
812
|
+
declare class GroqAdapter implements ILLMProvider {
|
|
813
|
+
readonly name = "groq";
|
|
814
|
+
private readonly config;
|
|
815
|
+
/**
|
|
816
|
+
* Initializes the Groq adapter.
|
|
817
|
+
*
|
|
818
|
+
* @param config - Connection options and credentials.
|
|
819
|
+
*/
|
|
820
|
+
constructor(config?: GroqAdapterConfig);
|
|
821
|
+
/**
|
|
822
|
+
* Resolves authentication credentials and connection endpoint.
|
|
823
|
+
*/
|
|
824
|
+
private resolveCredentials;
|
|
825
|
+
/**
|
|
826
|
+
* Executes a full non-streaming completion request.
|
|
827
|
+
*
|
|
828
|
+
* @param request - Validated completion request.
|
|
829
|
+
* @returns Complete model response.
|
|
830
|
+
*/
|
|
831
|
+
complete(request: LLMRequest): Promise<LLMResponse>;
|
|
832
|
+
/**
|
|
833
|
+
* Initiates an SSE stream emitting token deltas incrementally.
|
|
834
|
+
*
|
|
835
|
+
* @param request - Validated completion request.
|
|
836
|
+
* @returns Async iterable emitting token deltas.
|
|
837
|
+
*/
|
|
838
|
+
stream(request: LLMRequest): AsyncIterable<LLMStreamChunk>;
|
|
839
|
+
}
|
|
840
|
+
|
|
841
|
+
/**
|
|
842
|
+
* @file packages/ai-client/src/adapters/google/google.types.ts
|
|
843
|
+
* @description Wire types, configuration interfaces, and body builders for the Google Gemini adapter.
|
|
844
|
+
* @module @yuva-devlab/ai-client
|
|
845
|
+
*/
|
|
846
|
+
|
|
847
|
+
/**
|
|
848
|
+
* Configuration options for initializing GoogleAdapter.
|
|
849
|
+
*/
|
|
850
|
+
interface GoogleAdapterConfig {
|
|
851
|
+
/** Google AI Studio API key */
|
|
852
|
+
apiKey?: string;
|
|
853
|
+
/** Base URL for Gemini endpoint (defaults to AI_ENDPOINTS.GOOGLE_GEMINI_DEFAULT_BASE_URL) */
|
|
854
|
+
baseUrl?: string;
|
|
855
|
+
/** Default Gemini model (defaults to AI_DEFAULT_MODELS.GOOGLE) */
|
|
856
|
+
defaultModel?: string;
|
|
857
|
+
/** Optional dynamic credential resolver for secret vaults */
|
|
858
|
+
credentials?: CredentialResolver;
|
|
859
|
+
}
|
|
860
|
+
interface GeminiCandidate {
|
|
861
|
+
content?: {
|
|
862
|
+
parts?: Array<{
|
|
863
|
+
text?: string;
|
|
864
|
+
}>;
|
|
865
|
+
};
|
|
866
|
+
finishReason?: string;
|
|
867
|
+
}
|
|
868
|
+
interface GeminiResponse {
|
|
869
|
+
candidates?: GeminiCandidate[];
|
|
870
|
+
usageMetadata?: {
|
|
871
|
+
promptTokenCount?: number;
|
|
872
|
+
candidatesTokenCount?: number;
|
|
873
|
+
totalTokenCount?: number;
|
|
874
|
+
};
|
|
875
|
+
}
|
|
876
|
+
/**
|
|
877
|
+
* Builds the native Google Gemini request payload.
|
|
878
|
+
*
|
|
879
|
+
* @param request - Canonical LLMRequest payload.
|
|
880
|
+
* @returns JSON-serializable Gemini request body.
|
|
881
|
+
*/
|
|
882
|
+
declare function buildGeminiRequestBody(request: LLMRequest): Record<string, unknown>;
|
|
883
|
+
|
|
884
|
+
/**
|
|
885
|
+
* @file packages/ai-client/src/adapters/google/google.adapter.ts
|
|
886
|
+
* @description Native Google Gemini API adapter for Gemini 2.5 Flash / Pro models.
|
|
887
|
+
* @module @yuva-devlab/ai-client
|
|
888
|
+
*/
|
|
889
|
+
|
|
890
|
+
/**
|
|
891
|
+
* Google AI Studio / Gemini provider adapter.
|
|
892
|
+
*
|
|
893
|
+
* @example
|
|
894
|
+
* ```typescript
|
|
895
|
+
* const adapter = new GoogleAdapter({ apiKey: "AIzaSy..." });
|
|
896
|
+
* const res = await adapter.complete({
|
|
897
|
+
* model: "gemini-2.5-flash",
|
|
898
|
+
* messages: [createUserMessage("Write a quick sort in TypeScript")],
|
|
899
|
+
* });
|
|
900
|
+
* ```
|
|
901
|
+
*/
|
|
902
|
+
declare class GoogleAdapter implements ILLMProvider {
|
|
903
|
+
readonly name = "google";
|
|
904
|
+
private readonly config;
|
|
905
|
+
/**
|
|
906
|
+
* Initializes the Google Gemini adapter.
|
|
907
|
+
*
|
|
908
|
+
* @param config - Connection options and credentials.
|
|
909
|
+
*/
|
|
910
|
+
constructor(config?: GoogleAdapterConfig);
|
|
911
|
+
/**
|
|
912
|
+
* Resolves authentication credentials and model defaults.
|
|
913
|
+
*/
|
|
914
|
+
private resolveCredentials;
|
|
915
|
+
/**
|
|
916
|
+
* Executes a full non-streaming completion via Google AI Studio generateContent.
|
|
917
|
+
*
|
|
918
|
+
* @param request - Validated completion request.
|
|
919
|
+
* @returns Complete model response.
|
|
920
|
+
*/
|
|
921
|
+
complete(request: LLMRequest): Promise<LLMResponse>;
|
|
922
|
+
/**
|
|
923
|
+
* Streams token chunks incrementally using Server-Sent Events.
|
|
924
|
+
*
|
|
925
|
+
* @param request - Validated completion request.
|
|
926
|
+
* @returns Async iterable yielding token delta chunks.
|
|
927
|
+
*/
|
|
928
|
+
stream(request: LLMRequest): AsyncIterable<LLMStreamChunk>;
|
|
929
|
+
}
|
|
930
|
+
|
|
931
|
+
/**
|
|
932
|
+
* @file packages/ai-client/src/adapters/openai/openai.types.ts
|
|
933
|
+
* @description Wire types, configuration interfaces, and helpers for OpenAI Chat Completions.
|
|
934
|
+
* @module @yuva-devlab/ai-client
|
|
935
|
+
*/
|
|
936
|
+
|
|
937
|
+
/**
|
|
938
|
+
* Configuration options for initializing OpenAIAdapter.
|
|
939
|
+
*/
|
|
940
|
+
interface OpenAIAdapterConfig {
|
|
941
|
+
/** OpenAI API authentication key */
|
|
942
|
+
apiKey?: string;
|
|
943
|
+
/** Custom base URL (defaults to AI_ENDPOINTS.OPENAI_DEFAULT_BASE_URL) */
|
|
944
|
+
baseUrl?: string;
|
|
945
|
+
/** Default model identifier (defaults to AI_DEFAULT_MODELS.OPENAI) */
|
|
946
|
+
defaultModel?: string;
|
|
947
|
+
/** Optional dynamic credential resolver for secret managers */
|
|
948
|
+
credentials?: CredentialResolver;
|
|
949
|
+
}
|
|
950
|
+
interface OpenAiCompletionResponse {
|
|
951
|
+
choices: Array<{
|
|
952
|
+
message?: {
|
|
953
|
+
content?: string;
|
|
954
|
+
};
|
|
955
|
+
finish_reason?: string;
|
|
956
|
+
}>;
|
|
957
|
+
usage?: {
|
|
958
|
+
prompt_tokens: number;
|
|
959
|
+
completion_tokens: number;
|
|
960
|
+
total_tokens: number;
|
|
961
|
+
};
|
|
962
|
+
}
|
|
963
|
+
/**
|
|
964
|
+
* Converts canonical messages to OpenAI wire format.
|
|
965
|
+
*
|
|
966
|
+
* @param messages - Canonical conversation history turns.
|
|
967
|
+
* @returns Array of OpenAI wire messages.
|
|
968
|
+
*/
|
|
969
|
+
declare function mapOpenAiMessages(messages: LLMRequest["messages"]): {
|
|
970
|
+
role: string;
|
|
971
|
+
content: string;
|
|
972
|
+
}[];
|
|
973
|
+
|
|
974
|
+
/**
|
|
975
|
+
* @file packages/ai-client/src/adapters/openai/openai.adapter.ts
|
|
976
|
+
* @description Standard OpenAI Chat Completions API adapter (GPT-4o, GPT-4o-mini).
|
|
977
|
+
* @module @yuva-devlab/ai-client
|
|
978
|
+
*/
|
|
979
|
+
|
|
980
|
+
/**
|
|
981
|
+
* Standard OpenAI adapter executing completions via OpenAI API.
|
|
982
|
+
*
|
|
983
|
+
* @example
|
|
984
|
+
* ```typescript
|
|
985
|
+
* const adapter = new OpenAIAdapter({ apiKey: "sk-proj-..." });
|
|
986
|
+
* const res = await adapter.complete({
|
|
987
|
+
* model: "gpt-4o-mini",
|
|
988
|
+
* messages: [createUserMessage("Explain transactional outbox pattern")],
|
|
989
|
+
* });
|
|
990
|
+
* ```
|
|
991
|
+
*/
|
|
992
|
+
declare class OpenAIAdapter implements ILLMProvider {
|
|
993
|
+
readonly name = "openai";
|
|
994
|
+
private readonly config;
|
|
995
|
+
/**
|
|
996
|
+
* Initializes the OpenAI adapter.
|
|
997
|
+
*
|
|
998
|
+
* @param config - Connection options and credentials.
|
|
999
|
+
*/
|
|
1000
|
+
constructor(config?: OpenAIAdapterConfig);
|
|
1001
|
+
/**
|
|
1002
|
+
* Resolves authentication credentials and endpoint.
|
|
1003
|
+
*/
|
|
1004
|
+
private resolveCredentials;
|
|
1005
|
+
/**
|
|
1006
|
+
* Executes a full non-streaming completion request.
|
|
1007
|
+
*
|
|
1008
|
+
* @param request - Validated completion request.
|
|
1009
|
+
* @returns Complete model response.
|
|
1010
|
+
*/
|
|
1011
|
+
complete(request: LLMRequest): Promise<LLMResponse>;
|
|
1012
|
+
/**
|
|
1013
|
+
* Initiates an SSE stream emitting token deltas incrementally.
|
|
1014
|
+
*
|
|
1015
|
+
* @param request - Validated completion request.
|
|
1016
|
+
* @returns Async iterable emitting token deltas.
|
|
1017
|
+
*/
|
|
1018
|
+
stream(request: LLMRequest): AsyncIterable<LLMStreamChunk>;
|
|
1019
|
+
}
|
|
1020
|
+
|
|
1021
|
+
/**
|
|
1022
|
+
* @file packages/ai-client/src/adapters/anthropic/anthropic.types.ts
|
|
1023
|
+
* @description Wire types, configuration interfaces, and helpers for Anthropic Messages API.
|
|
1024
|
+
* @module @yuva-devlab/ai-client
|
|
1025
|
+
*/
|
|
1026
|
+
|
|
1027
|
+
/**
|
|
1028
|
+
* Configuration options for initializing AnthropicAdapter.
|
|
1029
|
+
*/
|
|
1030
|
+
interface AnthropicAdapterConfig {
|
|
1031
|
+
/** Anthropic API authentication key */
|
|
1032
|
+
apiKey?: string;
|
|
1033
|
+
/** Custom base URL (defaults to AI_ENDPOINTS.ANTHROPIC_DEFAULT_BASE_URL) */
|
|
1034
|
+
baseUrl?: string;
|
|
1035
|
+
/** Default Claude model identifier (defaults to AI_DEFAULT_MODELS.ANTHROPIC) */
|
|
1036
|
+
defaultModel?: string;
|
|
1037
|
+
/** Optional dynamic credential resolver for secret managers */
|
|
1038
|
+
credentials?: CredentialResolver;
|
|
1039
|
+
}
|
|
1040
|
+
interface AnthropicResponse {
|
|
1041
|
+
content: Array<{
|
|
1042
|
+
type: string;
|
|
1043
|
+
text?: string;
|
|
1044
|
+
}>;
|
|
1045
|
+
stop_reason: string;
|
|
1046
|
+
usage: {
|
|
1047
|
+
input_tokens: number;
|
|
1048
|
+
output_tokens: number;
|
|
1049
|
+
};
|
|
1050
|
+
}
|
|
1051
|
+
/**
|
|
1052
|
+
* Extracts system prompt and non-system turns for Anthropic's Messages format.
|
|
1053
|
+
*
|
|
1054
|
+
* @param messages - Canonical conversation turns.
|
|
1055
|
+
* @returns Separated system string and wire message turns.
|
|
1056
|
+
*/
|
|
1057
|
+
declare function extractAnthropicSystemAndMessages(messages: LLMRequest["messages"]): {
|
|
1058
|
+
system?: string;
|
|
1059
|
+
messages: Array<{
|
|
1060
|
+
role: string;
|
|
1061
|
+
content: string;
|
|
1062
|
+
}>;
|
|
1063
|
+
};
|
|
1064
|
+
|
|
1065
|
+
/**
|
|
1066
|
+
* @file packages/ai-client/src/adapters/anthropic/anthropic.adapter.ts
|
|
1067
|
+
* @description Anthropic Claude Messages API adapter (Claude 3.5 Sonnet / Haiku).
|
|
1068
|
+
* @module @yuva-devlab/ai-client
|
|
1069
|
+
*/
|
|
1070
|
+
|
|
1071
|
+
/**
|
|
1072
|
+
* Anthropic adapter communicating via the v1/messages protocol.
|
|
1073
|
+
*
|
|
1074
|
+
* @example
|
|
1075
|
+
* ```typescript
|
|
1076
|
+
* const adapter = new AnthropicAdapter({ apiKey: "sk-ant-..." });
|
|
1077
|
+
* const res = await adapter.complete({
|
|
1078
|
+
* model: "claude-3-5-haiku-latest",
|
|
1079
|
+
* messages: [createUserMessage("Write an SRE runbook for disk pressure")],
|
|
1080
|
+
* });
|
|
1081
|
+
* ```
|
|
1082
|
+
*/
|
|
1083
|
+
declare class AnthropicAdapter implements ILLMProvider {
|
|
1084
|
+
readonly name = "anthropic";
|
|
1085
|
+
private readonly config;
|
|
1086
|
+
/**
|
|
1087
|
+
* Initializes the Anthropic adapter.
|
|
1088
|
+
*
|
|
1089
|
+
* @param config - Connection options and credentials.
|
|
1090
|
+
*/
|
|
1091
|
+
constructor(config?: AnthropicAdapterConfig);
|
|
1092
|
+
/**
|
|
1093
|
+
* Resolves authentication credentials and endpoint.
|
|
1094
|
+
*/
|
|
1095
|
+
private resolveCredentials;
|
|
1096
|
+
/**
|
|
1097
|
+
* Executes a full non-streaming completion request.
|
|
1098
|
+
*
|
|
1099
|
+
* @param request - Validated completion request.
|
|
1100
|
+
* @returns Complete model response.
|
|
1101
|
+
*/
|
|
1102
|
+
complete(request: LLMRequest): Promise<LLMResponse>;
|
|
1103
|
+
/**
|
|
1104
|
+
* Streams completion tokens.
|
|
1105
|
+
*
|
|
1106
|
+
* @param request - Validated completion request.
|
|
1107
|
+
* @returns Async iterable yielding token deltas.
|
|
1108
|
+
*/
|
|
1109
|
+
stream(request: LLMRequest): AsyncIterable<LLMStreamChunk>;
|
|
1110
|
+
}
|
|
1111
|
+
|
|
1112
|
+
/**
|
|
1113
|
+
* @file packages/ai-client/src/cascade/fallback-cascade.ts
|
|
1114
|
+
* @description Intelligent multi-tier fallback cascade routing across local and cloud providers.
|
|
1115
|
+
*
|
|
1116
|
+
* Implements high-availability AI completion by attempting execution on primary providers
|
|
1117
|
+
* (e.g. local Ollama) and gracefully falling back to secondary tiers (Groq, Gemini, OpenAI)
|
|
1118
|
+
* upon rate limits, timeouts, or transient connection errors.
|
|
1119
|
+
*
|
|
1120
|
+
* @module @yuva-devlab/ai-client
|
|
1121
|
+
*/
|
|
1122
|
+
|
|
1123
|
+
/**
|
|
1124
|
+
* Options configuring the FallbackCascade provider.
|
|
1125
|
+
*/
|
|
1126
|
+
interface FallbackCascadeOptions {
|
|
1127
|
+
/** Ordered list of provider adapters to attempt in sequence */
|
|
1128
|
+
providers: ILLMProvider[];
|
|
1129
|
+
}
|
|
1130
|
+
/**
|
|
1131
|
+
* Composite ILLMProvider that cascades requests down a priority-ordered provider list.
|
|
1132
|
+
*
|
|
1133
|
+
* @example
|
|
1134
|
+
* ```typescript
|
|
1135
|
+
* const cascade = new FallbackCascade({
|
|
1136
|
+
* providers: [new OllamaAdapter(), new GroqAdapter(), new OpenAIAdapter()],
|
|
1137
|
+
* });
|
|
1138
|
+
* const res = await cascade.complete(request);
|
|
1139
|
+
* ```
|
|
1140
|
+
*/
|
|
1141
|
+
declare class FallbackCascade implements ILLMProvider {
|
|
1142
|
+
readonly name = "fallback-cascade";
|
|
1143
|
+
private readonly providers;
|
|
1144
|
+
/**
|
|
1145
|
+
* Initializes the cascade with candidate providers.
|
|
1146
|
+
*
|
|
1147
|
+
* @param options - Cascade options containing providers array.
|
|
1148
|
+
*/
|
|
1149
|
+
constructor(options: FallbackCascadeOptions);
|
|
1150
|
+
/**
|
|
1151
|
+
* Attempts completion through the provider cascade until one succeeds.
|
|
1152
|
+
*
|
|
1153
|
+
* @param request - Validated completion request.
|
|
1154
|
+
* @returns Successful LLMResponse from the first healthy provider.
|
|
1155
|
+
*/
|
|
1156
|
+
complete(request: LLMRequest): Promise<LLMResponse>;
|
|
1157
|
+
/**
|
|
1158
|
+
* Attempts streaming through the provider cascade until one connects.
|
|
1159
|
+
*
|
|
1160
|
+
* @param request - Validated completion request.
|
|
1161
|
+
* @returns Async iterable emitting token chunks from the first healthy provider.
|
|
1162
|
+
*/
|
|
1163
|
+
stream(request: LLMRequest): AsyncIterable<LLMStreamChunk>;
|
|
1164
|
+
}
|
|
1165
|
+
|
|
1166
|
+
/**
|
|
1167
|
+
* @file packages/ai-client/src/schema/structured-output.ts
|
|
1168
|
+
* @description Type-safe structured output extractor with automatic JSON repair and Zod validation.
|
|
1169
|
+
* @module @yuva-devlab/ai-client
|
|
1170
|
+
*/
|
|
1171
|
+
|
|
1172
|
+
/**
|
|
1173
|
+
* Configuration options for extracting structured schema objects.
|
|
1174
|
+
*/
|
|
1175
|
+
interface ExtractStructuredOutputOptions<T> {
|
|
1176
|
+
/** Target provider executing completions */
|
|
1177
|
+
provider: ILLMProvider;
|
|
1178
|
+
/** Base completion request */
|
|
1179
|
+
request: LLMRequest;
|
|
1180
|
+
/** Zod schema validating the output */
|
|
1181
|
+
schema: z.ZodType<T>;
|
|
1182
|
+
/** Maximum self-healing JSON repair rounds before failing (defaults to AI_EXECUTION_DEFAULTS.DEFAULT_MAX_REPAIR_RETRIES) */
|
|
1183
|
+
maxRepairRetries?: number;
|
|
1184
|
+
}
|
|
1185
|
+
/**
|
|
1186
|
+
* Executes a completion request and parses the output into a strictly validated Zod schema.
|
|
1187
|
+
* Automatically initiates self-healing repair rounds with the model if JSON syntax or schema fails.
|
|
1188
|
+
*
|
|
1189
|
+
* @example
|
|
1190
|
+
* ```typescript
|
|
1191
|
+
* const UserProfileSchema = z.object({ name: z.string(), age: z.number() });
|
|
1192
|
+
* const user = await extractStructuredOutput({
|
|
1193
|
+
* provider,
|
|
1194
|
+
* request: { model: "qwen2.5:7b", messages: [createUserMessage("Generate a user")] },
|
|
1195
|
+
* schema: UserProfileSchema,
|
|
1196
|
+
* });
|
|
1197
|
+
* console.log(user.name);
|
|
1198
|
+
* ```
|
|
1199
|
+
*
|
|
1200
|
+
* @param options - Extraction options including provider, request, schema, and maxRepairRetries.
|
|
1201
|
+
* @returns Fully validated typed object matching schema.
|
|
1202
|
+
*/
|
|
1203
|
+
declare function extractStructuredOutput<T>(options: ExtractStructuredOutputOptions<T>): Promise<T>;
|
|
1204
|
+
|
|
1205
|
+
/**
|
|
1206
|
+
* @file packages/ai-client/src/factory/provider-factory.ts
|
|
1207
|
+
* @description Unified factory resolving LLM provider adapters and multi-tier cascades from environment.
|
|
1208
|
+
* @module @yuva-devlab/ai-client
|
|
1209
|
+
*/
|
|
1210
|
+
|
|
1211
|
+
/**
|
|
1212
|
+
* Standard provider type identifiers.
|
|
1213
|
+
*/
|
|
1214
|
+
type ProviderType = "ollama" | "groq" | "google" | "openai" | "anthropic" | "cascade";
|
|
1215
|
+
/**
|
|
1216
|
+
* Creates an instance of an LLM provider adapter matching the specified type.
|
|
1217
|
+
*
|
|
1218
|
+
* @example
|
|
1219
|
+
* ```typescript
|
|
1220
|
+
* const groq = createProvider("groq", { apiKey: "gsk_..." });
|
|
1221
|
+
* const ollama = createProvider("ollama", { baseUrl: "http://127.0.0.1:11434" });
|
|
1222
|
+
* ```
|
|
1223
|
+
*
|
|
1224
|
+
* @param type - Target provider type slug.
|
|
1225
|
+
* @param config - Optional configuration dictionary.
|
|
1226
|
+
* @returns Instantiated ILLMProvider.
|
|
1227
|
+
*/
|
|
1228
|
+
declare function createProvider(type: ProviderType, config?: Record<string, unknown>): ILLMProvider;
|
|
1229
|
+
/**
|
|
1230
|
+
* Automatically inspects ambient environment and builds an ordered cascade of available providers.
|
|
1231
|
+
*
|
|
1232
|
+
* Priority order:
|
|
1233
|
+
* 1. Local Ollama (always registered as offline/local tier)
|
|
1234
|
+
* 2. Groq (if GROQ_API_KEY is present)
|
|
1235
|
+
* 3. Google Gemini (if GEMINI_API_KEY is present)
|
|
1236
|
+
* 4. OpenAI (if OPENAI_API_KEY is present)
|
|
1237
|
+
* 5. Anthropic (if ANTHROPIC_API_KEY is present)
|
|
1238
|
+
*
|
|
1239
|
+
* @returns Ordered array of configured ILLMProvider adapters.
|
|
1240
|
+
*/
|
|
1241
|
+
declare function createCascadeCandidates(): ILLMProvider[];
|
|
1242
|
+
/**
|
|
1243
|
+
* Creates the default provider for the current environment.
|
|
1244
|
+
* If specific AI_PROVIDER env var is specified, uses that; otherwise returns a robust FallbackCascade.
|
|
1245
|
+
*
|
|
1246
|
+
* @example
|
|
1247
|
+
* ```typescript
|
|
1248
|
+
* const client = createDefaultProvider();
|
|
1249
|
+
* const response = await client.complete(request);
|
|
1250
|
+
* ```
|
|
1251
|
+
*
|
|
1252
|
+
* @returns Instantiated ILLMProvider ready for completion.
|
|
1253
|
+
*/
|
|
1254
|
+
declare function createDefaultProvider(): ILLMProvider;
|
|
1255
|
+
|
|
1256
|
+
export { type AIMessage, AIMessageSchema, AI_DEFAULT_MODELS, AI_ENDPOINTS, AI_EXECUTION_DEFAULTS, AnthropicAdapter, type AnthropicAdapterConfig, type AnthropicResponse, type CredentialResolver, type ExtractStructuredOutputOptions, FallbackCascade, type FallbackCascadeOptions, FinishReason, type GeminiCandidate, type GeminiResponse, GoogleAdapter, type GoogleAdapterConfig, GroqAdapter, type GroqAdapterConfig, type GroqCompletionResponse, type ILLMProvider, type LLMRequest, type LLMRequestOptions, LLMRequestOptionsSchema, LLMRequestSchema, type LLMResponse, LLMResponseSchema, type LLMStreamChunk, type LLMUsage, LLMUsageSchema, MessageRole, MissingCredentialError, OllamaAdapter, type OllamaAdapterConfig, type OllamaChatResponseChunk, type OllamaWireMessage, OpenAIAdapter, type OpenAIAdapterConfig, type OpenAiCompletionResponse, type OpenAiWireMessage, type ProviderCredentials, type ProviderType, type ToolCall, ToolCallSchema, buildGeminiRequestBody, createAssistantMessage, createCascadeCandidates, createDefaultProvider, createProvider, createSystemMessage, createToolResultMessage, createUserMessage, extractAnthropicSystemAndMessages, extractStructuredOutput, mapGroqMessages, mapOllamaMessages, mapOpenAiMessages, resolveEnvCredentials };
|