Press n or j to go to the next uncovered block, b, p or k for the previous block.
| 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 | 1x 1x 1x 1x 1x 1x 54x 54x 54x 54x 54x 54x 54x 54x 54x 54x 47x 47x 54x 6x 6x 6x 6x 6x 54x 47x 47x 47x 47x 47x 48x 1x 1x 1x 1x 54x 54x 54x 1x 1x 54x 54x 54x 54x 54x 54x 54x 54x 54x 54x 54x 54x 3x 3x 54x 27x 27x 27x 27x 27x 27x 27x 1x 1x 1x 1x 1x 1x 27x 27x 27x 27x 27x 27x 27x 27x 1x 1x 27x 27x 27x 27x 30x 30x 30x 30x 30x 30x 30x 30x 30x 30x 30x 30x 30x 30x 25x 30x 1x 1x 1x 24x 30x 30x 30x 30x 30x 30x 30x 30x 30x 30x 30x 30x 30x 6x 6x 3x 3x 6x 30x 6x 27x 54x 8x 8x 8x 8x 8x 8x 8x 8x 8x 8x 8x 8x 8x 8x 8x 8x 8x 8x 8x 8x 8x 8x 8x 8x 8x 8x 1x 1x 1x 8x 8x 6x 6x 6x 8x 23x 23x 22x 22x 22x 37x 37x 5x 5x 5x 32x 32x 37x 37x 37x 37x 37x 37x 37x 37x 37x 1x 37x 17x 8x 6x 6x 1x 8x 54x 1x 1x 54x 2x 2x 54x 30x 30x 30x 30x 30x 30x 30x 30x 30x 30x 30x 25x 30x 30x 30x 30x 54x | import {
type LLMProvider,
type LLMCapabilities,
type LLMPrompt,
type LLMGenerateOptions,
type LLMResponse,
type LLMStreamChunk,
PromptBuilder,
} from '@agentix-e/nl2spel';
import { PROVIDER_PRESETS, type ProviderPreset } from './provider-presets.js';
interface ChatCompletionResponse {
id?: string;
object?: string;
created?: number;
model: string;
choices?: Array<{
index?: number;
message?: {
role?: string;
content?: string | null;
};
finish_reason?: string | null;
}>;
usage?: {
prompt_tokens?: number;
completion_tokens?: number;
total_tokens?: number;
};
error?: {
message?: string;
type?: string;
code?: string;
};
}
export interface OpenAICompatibleConfig {
/** Predefined provider name (openai/deepseek/glm/copilot/hunyuan/minimax/kimi) */
provider?: string;
/** Custom config (used when provider is empty or not found) */
custom?: {
name: string;
baseURL: string;
apiKey: string;
model: string;
maxContextTokens?: number;
};
/** API key (overrides preset default) */
apiKey?: string;
/** Model name (overrides preset default) */
model?: string;
/** Maximum context tokens (overrides preset default) */
maxContextTokens?: number;
/** Custom request headers */
headers?: Record<string, string>;
}
function defaultPromptBuilder(): PromptBuilder {
return new PromptBuilder();
}
export class OpenAICompatibleProvider implements LLMProvider {
public readonly name: string;
public readonly capabilities: LLMCapabilities;
private readonly baseURL: string;
private readonly apiKey: string;
private readonly model: string;
private readonly headers: Record<string, string>;
private readonly _promptBuilder: PromptBuilder;
constructor(config: OpenAICompatibleConfig, promptBuilder?: PromptBuilder) {
let preset: ProviderPreset | null = null;
if (config.provider && PROVIDER_PRESETS[config.provider]) {
preset = PROVIDER_PRESETS[config.provider]!;
}
if (config.custom) {
this.name = config.custom.name;
this.baseURL = config.custom.baseURL;
this.apiKey = config.custom.apiKey;
this.model = config.custom.model;
this.headers = {};
} else if (preset) {
this.name = preset.name;
this.baseURL = preset.baseURL;
this.apiKey = config.apiKey ?? '';
this.model = config.model ?? preset.defaultModel;
this.headers = { ...preset.headers };
} else {
throw new Error(
'OpenAICompatibleProvider requires either a known "provider" name or a "custom" config',
);
}
// Allow overriding apiKey and model via config
if (config.apiKey) this.apiKey = config.apiKey;
if (config.model) this.model = config.model;
// Merge headers
if (config.headers) {
Object.assign(this.headers, config.headers);
}
this._promptBuilder = promptBuilder ?? defaultPromptBuilder();
const maxTokens = config.maxContextTokens ?? preset?.maxContextTokens ?? 128000;
const streaming = preset?.supportsStreaming ?? true;
this.capabilities = {
maxContextTokens: maxTokens,
supportsGrammarConstraint: false,
supportsStreaming: streaming,
supportsStructuredOutput: preset?.supportsStructuredOutput ?? false,
offlineAvailable: false,
};
}
async isAvailable(): Promise<boolean> {
return !!this.apiKey;
}
async generate(prompt: LLMPrompt, options?: LLMGenerateOptions): Promise<LLMResponse> {
const startTime = Date.now();
const model = options?.model ?? this.model;
const messages = [
{ role: 'system', content: prompt.system },
{ role: 'user', content: prompt.user },
];
// Include few-shot examples as part of user message if not already in it
if (prompt.examples.length > 0 && !prompt.user.includes('Few-Shot')) {
const exampleText = prompt.examples.map((e) => `NL: ${e.nl}\nSpEL: ${e.spel}`).join('\n\n');
messages.push({
role: 'user',
content: `Examples:\n${exampleText}\n\nInput: ${prompt.user}`,
});
}
const body: Record<string, unknown> = {
model,
messages,
temperature: options?.temperature ?? 0.1,
max_tokens: options?.maxTokens ?? 512,
top_p: options?.topP ?? 0.9,
};
if (options?.stopSequences) {
body.stop = options.stopSequences;
}
const timeout = options?.timeout ?? 30000;
const maxRetries = options?.maxRetries ?? 2;
let lastError: Error | null = null;
for (let retry = 0; retry <= maxRetries; retry++) {
try {
const response = await this.fetchWithTimeout(
`${this.baseURL}/chat/completions`,
{
method: 'POST',
headers: {
'Content-Type': 'application/json',
Authorization: `Bearer ${this.apiKey}`,
...this.headers,
},
body: JSON.stringify(body),
},
timeout,
);
const data = (await response.json()) as ChatCompletionResponse;
if (!response.ok) {
const errorMsg = data?.error?.message ?? `HTTP ${response.status}`;
throw new Error(`API error (${response.status}): ${errorMsg}`);
}
const choice = data.choices?.[0];
return {
text: choice?.message?.content?.trim() || '',
model: data.model!,
usage: {
promptTokens: data.usage?.prompt_tokens ?? 0,
completionTokens: data.usage?.completion_tokens ?? 0,
totalTokens: data.usage?.total_tokens ?? 0,
},
latencyMs: Date.now() - startTime,
finishReason: (choice!.finish_reason ?? 'stop') as LLMResponse['finishReason'],
providerName: this.name,
};
} catch (err) {
lastError = err as Error;
if (retry < maxRetries) {
await new Promise((r) => setTimeout(r, 1000 * (retry + 1)));
}
}
}
// lastError is always set when all providers fail
throw lastError!;
}
async *generateStream(
prompt: LLMPrompt,
options?: LLMGenerateOptions,
): AsyncIterable<LLMStreamChunk> {
const model = options?.model ?? this.model;
const messages = [
{ role: 'system', content: prompt.system },
{ role: 'user', content: prompt.user },
];
const body: Record<string, unknown> = {
model,
messages,
temperature: options?.temperature ?? 0.1,
max_tokens: options?.maxTokens ?? 512,
top_p: options?.topP ?? 0.9,
stream: true,
};
const response = await fetch(`${this.baseURL}/chat/completions`, {
method: 'POST',
headers: {
'Content-Type': 'application/json',
Authorization: `Bearer ${this.apiKey}`,
...this.headers,
},
body: JSON.stringify(body),
});
if (!response.ok) {
const err = await response.text();
throw new Error(`API error (${response.status}): ${err}`);
}
const reader = response.body?.getReader();
if (!reader) throw new Error('No response body');
const decoder = new TextDecoder();
let accumulated = '';
try {
while (true) {
const { done, value } = await reader.read();
if (done) break;
const chunk = decoder.decode(value, { stream: true });
const lines = chunk.split('\n').filter((l) => l.startsWith('data: '));
for (const line of lines) {
const data = line.slice(6).trim();
if (data === '[DONE]') {
yield { delta: '', accumulated, done: true, finishReason: 'stop' };
return;
}
try {
const parsed = JSON.parse(data);
const delta = parsed.choices?.[0]?.delta?.content ?? '';
accumulated += delta;
yield {
delta,
accumulated,
done: false,
finishReason: parsed.choices?.[0]?.finish_reason,
};
} catch {
// Skip malformed lines
}
}
}
} finally {
reader.releaseLock();
}
yield { delta: '', accumulated, done: true, finishReason: 'stop' };
}
/**
* Set the PromptBuilder (convenient for injecting mocks in tests)
*/
setPromptBuilder(builder: PromptBuilder): void {
(this as any)._promptBuilder = builder;
}
/**
* Get the PromptBuilder
*/
getPromptBuilder(): PromptBuilder {
return this._promptBuilder;
}
private async fetchWithTimeout(
url: string,
init: RequestInit,
timeoutMs: number,
): Promise<Response> {
const controller = new AbortController();
const timeoutId = setTimeout(() => controller.abort(), timeoutMs);
try {
const response = await fetch(url, {
...init,
signal: controller.signal,
});
return response;
} finally {
clearTimeout(timeoutId);
}
}
}
|