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 | 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 19x 19x 19x 19x 19x 19x 1x 19x 6x 6x 19x 19x 19x 19x 19x 19x 19x 19x 19x 19x 19x 2x 2x 2x 2x 2x 2x 2x 2x 17x 17x 19x 19x 10x 10x 10x 17x 17x 17x 17x 17x 17x 13x 13x 17x 17x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x | /**
* AgentKits — LLM Chat Module
*
* Multi-provider LLM chat/completion with unified interface.
* Supports: OpenAI, Gemini, Ollama, DashScope (Qwen), DeepSeek, Zhipu (GLM), Moonshot (Kimi), or any OpenAI-compatible endpoint.
*
* Usage:
* import { createChat } from 'agentkits/llm';
* const chat = createChat({ provider: 'deepseek', apiKey: '...' });
* const reply = await chat.complete('Explain quantum computing');
*/
import OpenAI from 'openai';
import type { ChatCompletionMessageParam } from 'openai/resources/chat/completions';
import { AuthenticationError, ModelNotFoundError, ProviderError, RateLimitError, TimeoutError, ValidationError } from '../errors/index.js';
// ── Types ──────────────────────────────────────────────────────────
export type LLMProvider =
| 'openai'
| 'gemini'
| 'ollama'
| 'dashscope'
| 'deepseek'
| 'zhipu'
| 'moonshot'
| 'minimax'
| 'grok'
| 'cohere'
| 'yi'
| 'baichuan'
| 'siliconflow'
| 'stepfun'
| 'fireworks'
| 'together'
| 'groq'
| 'perplexity'
| 'custom';
export interface ChatConfig {
provider?: LLMProvider;
model?: string;
apiKey?: string;
baseUrl?: string;
temperature?: number;
maxTokens?: number;
}
export interface ChatMessage {
role: 'system' | 'user' | 'assistant';
content: string | MessageContent[];
}
/** Multi-modal content part */
export type MessageContent =
| { type: 'text'; text: string }
| { type: 'image_url'; image_url: { url: string; detail?: 'auto' | 'low' | 'high' } };
export interface ChatResponse {
content: string;
model: string;
usage?: {
promptTokens: number;
completionTokens: number;
totalTokens: number;
};
finishReason?: string;
}
export interface StreamChunk {
content: string;
done: boolean;
}
export interface ChatClient {
/** Simple completion — send a string, get a string back */
complete(prompt: string, options?: { system?: string; temperature?: number; maxTokens?: number }): Promise<string>;
/** Full chat with message history */
chat(messages: ChatMessage[], options?: { temperature?: number; maxTokens?: number }): Promise<ChatResponse>;
/** Streaming chat */
stream(messages: ChatMessage[], options?: { temperature?: number; maxTokens?: number }): AsyncIterable<StreamChunk>;
/** Current resolved config */
readonly config: Readonly<ResolvedChatConfig>;
}
interface ResolvedChatConfig {
provider: LLMProvider;
model: string;
baseUrl?: string;
temperature: number;
maxTokens: number;
}
// ── Provider Defaults ──────────────────────────────────────────────
interface ProviderDefaults {
model: string;
baseUrl?: string;
}
const PROVIDERS: Record<LLMProvider, ProviderDefaults> = {
openai: { model: 'gpt-4o' },
gemini: { model: 'gemini-2.5-flash', baseUrl: 'https://generativelanguage.googleapis.com/v1beta/openai/' },
ollama: { model: 'llama3.3', baseUrl: 'http://localhost:11434/v1' },
dashscope: { model: 'qwen-max', baseUrl: 'https://dashscope.aliyuncs.com/compatible-mode/v1' },
deepseek: { model: 'deepseek-chat', baseUrl: 'https://api.deepseek.com/v1' },
zhipu: { model: 'glm-4-plus', baseUrl: 'https://open.bigmodel.cn/api/paas/v4' },
moonshot: { model: 'moonshot-v1-auto', baseUrl: 'https://api.moonshot.cn/v1' },
minimax: { model: 'MiniMax-Text-01', baseUrl: 'https://api.minimax.chat/v1' },
grok: { model: 'grok-3', baseUrl: 'https://api.x.ai/v1' },
cohere: { model: 'command-r-plus', baseUrl: 'https://api.cohere.com/v2' },
yi: { model: 'yi-large', baseUrl: 'https://api.lingyiwanwu.com/v1' },
baichuan: { model: 'Baichuan4', baseUrl: 'https://api.baichuan-ai.com/v1' },
siliconflow: { model: 'deepseek-ai/DeepSeek-V3', baseUrl: 'https://api.siliconflow.cn/v1' },
stepfun: { model: 'step-2-16k', baseUrl: 'https://api.stepfun.com/v1' },
fireworks: { model: 'accounts/fireworks/models/llama-v3p1-70b-instruct', baseUrl: 'https://api.fireworks.ai/inference/v1' },
together: { model: 'meta-llama/Meta-Llama-3.1-70B-Instruct-Turbo', baseUrl: 'https://api.together.xyz/v1' },
groq: { model: 'llama-3.3-70b-versatile', baseUrl: 'https://api.groq.com/openai/v1' },
perplexity: { model: 'sonar-pro', baseUrl: 'https://api.perplexity.ai' },
custom: { model: 'gpt-4o' },
};
const ENV_MAP: Record<LLMProvider, { keyEnv: string[]; urlEnv?: string }> = {
openai: { keyEnv: ['OPENAI_API_KEY'], urlEnv: 'OPENAI_BASE_URL' },
gemini: { keyEnv: ['GEMINI_API_KEY', 'GOOGLE_API_KEY'] },
ollama: { keyEnv: [], urlEnv: 'OLLAMA_BASE_URL' },
dashscope: { keyEnv: ['DASHSCOPE_API_KEY'], urlEnv: 'DASHSCOPE_BASE_URL' },
deepseek: { keyEnv: ['DEEPSEEK_API_KEY'], urlEnv: 'DEEPSEEK_BASE_URL' },
zhipu: { keyEnv: ['ZHIPU_API_KEY'], urlEnv: 'ZHIPU_BASE_URL' },
moonshot: { keyEnv: ['MOONSHOT_API_KEY'], urlEnv: 'MOONSHOT_BASE_URL' },
minimax: { keyEnv: ['MINIMAX_API_KEY'], urlEnv: 'MINIMAX_BASE_URL' },
grok: { keyEnv: ['XAI_API_KEY'], urlEnv: 'XAI_BASE_URL' },
cohere: { keyEnv: ['COHERE_API_KEY'], urlEnv: 'COHERE_BASE_URL' },
yi: { keyEnv: ['YI_API_KEY'], urlEnv: 'YI_BASE_URL' },
baichuan: { keyEnv: ['BAICHUAN_API_KEY'], urlEnv: 'BAICHUAN_BASE_URL' },
siliconflow: { keyEnv: ['SILICONFLOW_API_KEY'], urlEnv: 'SILICONFLOW_BASE_URL' },
stepfun: { keyEnv: ['STEPFUN_API_KEY'], urlEnv: 'STEPFUN_BASE_URL' },
fireworks: { keyEnv: ['FIREWORKS_API_KEY'], urlEnv: 'FIREWORKS_BASE_URL' },
together: { keyEnv: ['TOGETHER_API_KEY'], urlEnv: 'TOGETHER_BASE_URL' },
groq: { keyEnv: ['GROQ_API_KEY'], urlEnv: 'GROQ_BASE_URL' },
perplexity: { keyEnv: ['PERPLEXITY_API_KEY'], urlEnv: 'PERPLEXITY_BASE_URL' },
custom: { keyEnv: ['AGENTKIT_API_KEY'], urlEnv: 'AGENTKIT_BASE_URL' },
};
function resolveFromEnv(provider: LLMProvider): { apiKey?: string; baseUrl?: string } {
const map = ENV_MAP[provider];
const apiKey = map.keyEnv.map(k => process.env[k]).find(Boolean);
const baseUrl = map.urlEnv ? process.env[map.urlEnv] : undefined;
return { apiKey, baseUrl };
}
// ── Error Wrapping ─────────────────────────────────────────────────
function wrapProviderError(err: unknown, provider: string): never {
if (err instanceof ProviderError) throw err; // already wrapped
const e = err as any;
const status = e?.status ?? e?.statusCode ?? e?.response?.status;
const msg = e?.message ?? String(err);
if (status === 401 || status === 403) {
throw new AuthenticationError(msg, { provider, statusCode: status });
}
if (status === 429) {
const retryAfter = e?.headers?.['retry-after']
? parseInt(e.headers['retry-after'], 10) * 1000
: undefined;
throw new RateLimitError(msg, { provider, retryAfter });
}
if (status === 404) {
throw new ModelNotFoundError(msg, { provider });
}
if (e?.code === 'ETIMEDOUT' || e?.code === 'ECONNABORTED' || msg.includes('timeout')) {
throw new TimeoutError(msg, { provider });
}
throw new ProviderError(msg, { provider, statusCode: status });
}
// ── Factory ────────────────────────────────────────────────────────
export function createChat(userConfig: ChatConfig = {}): ChatClient {
const provider = userConfig.provider
?? (process.env.AGENTKIT_LLM_PROVIDER as LLMProvider | undefined)
?? 'openai';
const defaults = PROVIDERS[provider] ?? PROVIDERS.openai;
const env = resolveFromEnv(provider);
const resolved: ResolvedChatConfig = {
provider,
model: userConfig.model ?? process.env.AGENTKIT_LLM_MODEL ?? defaults.model,
baseUrl: userConfig.baseUrl ?? env.baseUrl ?? defaults.baseUrl,
temperature: userConfig.temperature ?? 0.7,
maxTokens: userConfig.maxTokens ?? 4096,
};
const apiKey = userConfig.apiKey ?? env.apiKey ?? (provider === 'ollama' ? 'ollama' : undefined);
if (!apiKey && provider !== 'ollama') {
const envVars = ENV_MAP[provider].keyEnv;
const envHint = envVars.length > 0
? `Set ${envVars.join(' or ')} environment variable, or pass apiKey in config.`
: `Pass apiKey in config.`;
throw new AuthenticationError(
`Missing API key for provider "${provider}". ${envHint}`,
{ provider, statusCode: 401 },
);
}
const clientOpts: Record<string, unknown> = {};
if (apiKey) clientOpts.apiKey = apiKey;
if (resolved.baseUrl) clientOpts.baseURL = resolved.baseUrl;
if (provider !== 'openai') {
clientOpts.organization = null;
clientOpts.project = null;
}
const client = new OpenAI(clientOpts as any);
return {
async complete(prompt, options = {}) {
try {
const messages: ChatCompletionMessageParam[] = [];
if (options.system) messages.push({ role: 'system', content: options.system });
messages.push({ role: 'user', content: prompt });
const response = await client.chat.completions.create({
model: resolved.model,
messages,
temperature: options.temperature ?? resolved.temperature,
max_tokens: options.maxTokens ?? resolved.maxTokens,
});
return response.choices[0]?.message?.content ?? '';
} catch (err) { wrapProviderError(err, resolved.provider); }
},
async chat(messages, options = {}) {
try {
const response = await client.chat.completions.create({
model: resolved.model,
messages: messages as ChatCompletionMessageParam[],
temperature: options.temperature ?? resolved.temperature,
max_tokens: options.maxTokens ?? resolved.maxTokens,
});
const choice = response.choices[0];
return {
content: choice?.message?.content ?? '',
model: response.model,
usage: response.usage ? {
promptTokens: response.usage.prompt_tokens,
completionTokens: response.usage.completion_tokens,
totalTokens: response.usage.total_tokens,
} : undefined,
finishReason: choice?.finish_reason ?? undefined,
};
} catch (err) { wrapProviderError(err, resolved.provider); }
},
async *stream(messages, options = {}) {
try {
const stream = await client.chat.completions.create({
model: resolved.model,
messages: messages as ChatCompletionMessageParam[],
temperature: options.temperature ?? resolved.temperature,
max_tokens: options.maxTokens ?? resolved.maxTokens,
stream: true,
});
for await (const chunk of stream) {
const delta = chunk.choices[0]?.delta?.content ?? '';
const done = chunk.choices[0]?.finish_reason !== null && chunk.choices[0]?.finish_reason !== undefined;
if (delta || done) {
yield { content: delta, done };
}
}
} catch (err) { wrapProviderError(err, resolved.provider); }
},
get config() {
return resolved;
},
};
}
// ── Convenience ────────────────────────────────────────────────────
export function listProviders(): Array<{ id: LLMProvider; model: string; region: string }> {
return [
{ id: 'openai', model: 'gpt-4o', region: 'Global' },
{ id: 'gemini', model: 'gemini-2.5-flash', region: 'Global' },
{ id: 'ollama', model: 'llama3.3', region: 'Local' },
{ id: 'dashscope', model: 'qwen-max', region: 'Global (Alibaba Cloud)' },
{ id: 'deepseek', model: 'deepseek-chat', region: 'Global' },
{ id: 'zhipu', model: 'glm-4-plus', region: 'Global (Zhipu AI)' },
{ id: 'moonshot', model: 'moonshot-v1-auto', region: 'Global (Moonshot)' },
{ id: 'minimax', model: 'MiniMax-Text-01', region: 'Global (MiniMax)' },
{ id: 'grok', model: 'grok-3', region: 'Global (xAI)' },
{ id: 'cohere', model: 'command-r-plus', region: 'Global (Cohere)' },
{ id: 'yi', model: 'yi-large', region: 'Global (01.AI)' },
{ id: 'baichuan', model: 'Baichuan4', region: 'Global (Baichuan)' },
{ id: 'siliconflow', model: 'deepseek-ai/DeepSeek-V3', region: 'Global (SiliconFlow)' },
{ id: 'stepfun', model: 'step-2-16k', region: 'Global (Stepfun)' },
{ id: 'fireworks', model: 'llama-v3p1-70b-instruct', region: 'Global (Fireworks AI)' },
{ id: 'together', model: 'Meta-Llama-3.1-70B', region: 'Global (Together AI)' },
{ id: 'groq', model: 'llama-3.3-70b-versatile', region: 'Global (Groq)' },
{ id: 'perplexity', model: 'sonar-pro', region: 'Global (Perplexity)' },
{ id: 'custom', model: 'configurable', region: 'Any' },
];
}
|