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 325 326 327 328 329 330 331 332 333 334 335 336 337 338 339 340 341 342 343 344 345 346 347 348 349 350 351 352 353 354 355 356 357 358 359 360 361 362 363 364 365 366 367 368 369 370 371 372 373 374 375 376 377 378 379 380 381 382 383 384 385 386 387 388 389 390 391 392 393 394 395 396 397 398 399 400 401 402 403 404 405 406 407 408 409 410 411 412 413 414 415 416 417 418 419 420 421 422 423 424 425 426 427 428 429 430 431 432 433 434 435 436 437 438 439 440 441 442 443 444 445 446 447 448 449 450 451 452 453 454 455 456 457 458 459 460 461 462 463 464 465 466 467 468 469 470 471 472 473 474 475 476 477 478 479 480 481 482 483 484 485 486 487 488 489 490 491 492 493 494 495 496 497 498 499 500 501 502 503 504 505 506 507 508 509 510 511 512 513 514 515 516 517 518 519 520 521 522 523 524 525 526 527 528 529 530 531 532 533 534 535 536 537 538 539 540 541 542 543 544 545 546 547 548 549 550 551 552 553 554 555 556 557 558 559 560 561 562 563 564 565 566 567 568 569 570 571 572 573 574 575 576 577 578 579 580 581 582 583 584 585 586 587 | /** * LLM Service Adapter - Unified LLM interface for L4 self-evolution engines * * Provides a unified interface for: * - ReflectionEngine: Semantic analysis + deep reflection * - ContextCompactor: High-quality summarization * - MemoryExtractor: Semantic importance scoring * * Supports multiple backends: * - OpenAI (GPT-4, GPT-3.5) * - Volcengine (Doubao) * - OpenFang Gateway (passthrough) * * Part of ZCLAW L4 Self-Evolution capability. */ import { DEFAULT_MODEL_ID, DEFAULT_OPENAI_BASE_URL } from '../constants/models'; // === Types === export type LLMProvider = 'openai' | 'volcengine' | 'gateway' | 'mock'; export interface LLMConfig { provider: LLMProvider; model?: string; apiKey?: string; apiBase?: string; maxTokens?: number; temperature?: number; timeout?: number; } export interface LLMMessage { role: 'system' | 'user' | 'assistant'; content: string; } export interface LLMResponse { content: string; tokensUsed?: { input: number; output: number; }; model?: string; latencyMs?: number; } export interface LLMServiceAdapter { complete(messages: LLMMessage[], options?: Partial<LLMConfig>): Promise<LLMResponse>; isAvailable(): boolean; getProvider(): LLMProvider; } // === Default Configs === const DEFAULT_CONFIGS: Record<LLMProvider, LLMConfig> = { openai: { provider: 'openai', model: DEFAULT_MODEL_ID, apiBase: DEFAULT_OPENAI_BASE_URL, maxTokens: 2000, temperature: 0.7, timeout: 30000, }, volcengine: { provider: 'volcengine', model: 'doubao-pro-32k', apiBase: 'https://ark.cn-beijing.volces.com/api/v3', maxTokens: 2000, temperature: 0.7, timeout: 30000, }, gateway: { provider: 'gateway', apiBase: '/api/llm', maxTokens: 2000, temperature: 0.7, timeout: 60000, }, mock: { provider: 'mock', maxTokens: 100, temperature: 0, timeout: 100, }, }; // === Storage === const LLM_CONFIG_KEY = 'zclaw-llm-config'; // === Mock Adapter (for testing) === class MockLLMAdapter implements LLMServiceAdapter { constructor(_config: LLMConfig) { // Config is stored for future use (e.g., custom mock behavior based on config) } async complete(messages: LLMMessage[]): Promise<LLMResponse> { // Simulate latency await new Promise((resolve) => setTimeout(resolve, 50)); const lastMessage = messages[messages.length - 1]; const content = lastMessage?.content || ''; // Generate mock response based on content type let response = '[Mock LLM Response] '; if (content.includes('reflect') || content.includes('反思')) { response += JSON.stringify({ patterns: [ { observation: '用户经常询问代码优化相关问题', frequency: 5, sentiment: 'positive', evidence: ['多次讨论性能优化', '关注代码质量'], }, ], improvements: [ { area: '代码解释', suggestion: '可以提供更详细的代码注释', priority: 'medium', }, ], identityProposals: [], }); } else if (content.includes('summarize') || content.includes('摘要')) { response += '这是一个关于对话内容的摘要,包含了主要讨论的要点和结论。'; } else if (content.includes('importance') || content.includes('重要性')) { response += JSON.stringify({ memories: [ { content: '用户偏好简洁的回答', importance: 7, type: 'preference' }, ], }); } else { response += 'Processed: ' + content.slice(0, 50); } return { content: response, tokensUsed: { input: content.length / 4, output: response.length / 4 }, model: 'mock-model', latencyMs: 50, }; } isAvailable(): boolean { return true; } getProvider(): LLMProvider { return 'mock'; } } // === OpenAI Adapter === class OpenAILLMAdapter implements LLMServiceAdapter { private config: LLMConfig; constructor(config: LLMConfig) { this.config = { ...DEFAULT_CONFIGS.openai, ...config }; } async complete(messages: LLMMessage[], options?: Partial<LLMConfig>): Promise<LLMResponse> { const config = { ...this.config, ...options }; const startTime = Date.now(); if (!config.apiKey) { throw new Error('[OpenAI] API key not configured'); } const response = await fetch(`${config.apiBase}/chat/completions`, { method: 'POST', headers: { 'Content-Type': 'application/json', Authorization: `Bearer ${config.apiKey}`, }, body: JSON.stringify({ model: config.model, messages, max_tokens: config.maxTokens, temperature: config.temperature, }), signal: AbortSignal.timeout(config.timeout || 30000), }); if (!response.ok) { const errorBody = await response.text(); // Log full error in development only if (import.meta.env.DEV) { console.error('[OpenAI] API error:', errorBody); } // Return sanitized error to caller throw new Error(`[OpenAI] API error: ${response.status} - Request failed`); } const data = await response.json(); const latencyMs = Date.now() - startTime; return { content: data.choices[0]?.message?.content || '', tokensUsed: { input: data.usage?.prompt_tokens || 0, output: data.usage?.completion_tokens || 0, }, model: data.model, latencyMs, }; } isAvailable(): boolean { return !!this.config.apiKey; } getProvider(): LLMProvider { return 'openai'; } } // === Volcengine Adapter === class VolcengineLLMAdapter implements LLMServiceAdapter { private config: LLMConfig; constructor(config: LLMConfig) { this.config = { ...DEFAULT_CONFIGS.volcengine, ...config }; } async complete(messages: LLMMessage[], options?: Partial<LLMConfig>): Promise<LLMResponse> { const config = { ...this.config, ...options }; const startTime = Date.now(); if (!config.apiKey) { throw new Error('[Volcengine] API key not configured'); } const response = await fetch(`${config.apiBase}/chat/completions`, { method: 'POST', headers: { 'Content-Type': 'application/json', Authorization: `Bearer ${config.apiKey}`, }, body: JSON.stringify({ model: config.model, messages, max_tokens: config.maxTokens, temperature: config.temperature, }), signal: AbortSignal.timeout(config.timeout || 30000), }); if (!response.ok) { const errorBody = await response.text(); // Log full error in development only if (import.meta.env.DEV) { console.error('[Volcengine] API error:', errorBody); } // Return sanitized error to caller throw new Error(`[Volcengine] API error: ${response.status} - Request failed`); } const data = await response.json(); const latencyMs = Date.now() - startTime; return { content: data.choices[0]?.message?.content || '', tokensUsed: { input: data.usage?.prompt_tokens || 0, output: data.usage?.completion_tokens || 0, }, model: data.model, latencyMs, }; } isAvailable(): boolean { return !!this.config.apiKey; } getProvider(): LLMProvider { return 'volcengine'; } } // === Gateway Adapter (pass through to OpenFang or internal Kernel) === class GatewayLLMAdapter implements LLMServiceAdapter { private config: LLMConfig; constructor(config: LLMConfig) { this.config = { ...DEFAULT_CONFIGS.gateway, ...config }; } async complete(messages: LLMMessage[], options?: Partial<LLMConfig>): Promise<LLMResponse> { const config = { ...this.config, ...options }; const startTime = Date.now(); // Build a single prompt from messages const systemMessage = messages.find(m => m.role === 'system')?.content || ''; const userMessage = messages.find(m => m.role === 'user')?.content || ''; // Combine system and user messages into a single prompt const fullPrompt = systemMessage ? `${systemMessage}\n\n${userMessage}` : userMessage; // Check if running in Tauri with internal kernel // Use the same detection as kernel-client.ts const isTauri = typeof window !== 'undefined' && '__TAURI_INTERNALS__' in window; if (isTauri) { // Use internal Kernel via Tauri invoke try { const { invoke } = await import('@tauri-apps/api/core'); // Get the default agent ID from connectionStore or use the first agent const agentId = localStorage.getItem('zclaw-default-agent-id'); const response = await invoke<{ content: string; input_tokens: number; output_tokens: number }>('agent_chat', { request: { agentId: agentId || null, // null will use default agent message: fullPrompt, }, }); const latencyMs = Date.now() - startTime; return { content: response.content || '', tokensUsed: { input: response.input_tokens || 0, output: response.output_tokens || 0, }, latencyMs, }; } catch (err) { console.warn('[LLMService] Kernel chat failed, falling back to mock:', err); // Return empty response instead of throwing return { content: '', tokensUsed: { input: 0, output: 0 }, latencyMs: Date.now() - startTime, }; } } // External Gateway mode: Use OpenFang's chat endpoint const agentId = localStorage.getItem('zclaw-default-agent-id') || 'default'; const response = await fetch(`/api/agents/${agentId}/message`, { method: 'POST', headers: { 'Content-Type': 'application/json', }, body: JSON.stringify({ message: fullPrompt, max_tokens: config.maxTokens, temperature: config.temperature ?? 0.3, // Lower temperature for extraction tasks }), signal: AbortSignal.timeout(config.timeout || 60000), }); if (!response.ok) { const error = await response.text(); // If agent not found, try without agent ID (direct /api/chat) if (response.status === 404) { const fallbackResponse = await fetch('/api/chat', { method: 'POST', headers: { 'Content-Type': 'application/json' }, body: JSON.stringify({ message: fullPrompt, max_tokens: config.maxTokens, temperature: config.temperature ?? 0.3, }), signal: AbortSignal.timeout(config.timeout || 60000), }); if (!fallbackResponse.ok) { throw new Error(`[Gateway] Both endpoints failed: ${fallbackResponse.status}`); } const data = await fallbackResponse.json(); const latencyMs = Date.now() - startTime; return { content: data.response || data.content || '', tokensUsed: { input: data.input_tokens || 0, output: data.output_tokens || 0 }, latencyMs, }; } throw new Error(`[Gateway] API error: ${response.status} - ${error}`); } const data = await response.json(); const latencyMs = Date.now() - startTime; return { content: data.response || data.content || '', tokensUsed: { input: data.input_tokens || 0, output: data.output_tokens || 0 }, latencyMs, }; } isAvailable(): boolean { // Gateway is available if we're in browser (can connect to OpenFang) return typeof window !== 'undefined'; } getProvider(): LLMProvider { return 'gateway'; } } // === Factory === let cachedAdapter: LLMServiceAdapter | null = null; export function createLLMAdapter(config?: Partial<LLMConfig>): LLMServiceAdapter { const savedConfig = loadConfig(); const finalConfig = { ...savedConfig, ...config }; switch (finalConfig.provider) { case 'openai': return new OpenAILLMAdapter(finalConfig); case 'volcengine': return new VolcengineLLMAdapter(finalConfig); case 'gateway': return new GatewayLLMAdapter(finalConfig); case 'mock': default: return new MockLLMAdapter(finalConfig); } } export function getLLMAdapter(): LLMServiceAdapter { if (!cachedAdapter) { cachedAdapter = createLLMAdapter(); } return cachedAdapter; } export function resetLLMAdapter(): void { cachedAdapter = null; } // === Config Management === export function loadConfig(): LLMConfig { if (typeof window === 'undefined') { return DEFAULT_CONFIGS.mock; } try { const saved = localStorage.getItem(LLM_CONFIG_KEY); if (saved) { return JSON.parse(saved); } } catch { // Ignore parse errors } // Default to gateway (OpenFang passthrough) for L4 self-evolution return DEFAULT_CONFIGS.gateway; } export function saveConfig(config: LLMConfig): void { if (typeof window === 'undefined') return; // Don't save API key to localStorage for security const safeConfig = { ...config }; delete safeConfig.apiKey; localStorage.setItem(LLM_CONFIG_KEY, JSON.stringify(safeConfig)); resetLLMAdapter(); } // === Prompt Templates === export const LLM_PROMPTS = { reflection: { system: `你是一个 AI Agent 的自我反思引擎。分析最近的对话历史,识别行为模式,并生成改进建议。 输出 JSON 格式: { "patterns": [ { "observation": "观察到的模式描述", "frequency": 数字, "sentiment": "positive/negative/neutral", "evidence": ["证据1", "证据2"] } ], "improvements": [ { "area": "改进领域", "suggestion": "具体建议", "priority": "high/medium/low" } ], "identityProposals": [] }`, user: (context: string) => `分析以下对话历史,进行自我反思: ${context} 请识别行为模式(积极和消极),并提供具体的改进建议。`, }, compaction: { system: `你是一个对话摘要专家。将长对话压缩为简洁的摘要,保留关键信息。 要求: 1. 保留所有重要决策和结论 2. 保留用户偏好和约束 3. 保留未完成的任务 4. 保持时间顺序 5. 摘要应能在后续对话中替代原始内容`, user: (messages: string) => `请将以下对话压缩为简洁摘要,保留关键信息: ${messages}`, }, extraction: { system: `你是一个记忆提取专家。从对话中提取值得长期记住的信息。 提取类型: - fact: 用户告知的事实(如"我的公司叫XXX") - preference: 用户的偏好(如"我喜欢简洁的回答") - lesson: 本次对话的经验教训 - task: 未完成的任务或承诺 输出 JSON 数组: [ { "content": "记忆内容", "type": "fact/preference/lesson/task", "importance": 1-10, "tags": ["标签1", "标签2"] } ]`, user: (conversation: string) => `从以下对话中提取值得长期记住的信息: ${conversation} 如果没有值得记忆的内容,返回空数组 []。`, }, }; // === Helper Functions === export async function llmReflect(context: string, adapter?: LLMServiceAdapter): Promise<string> { const llm = adapter || getLLMAdapter(); const response = await llm.complete([ { role: 'system', content: LLM_PROMPTS.reflection.system }, { role: 'user', content: LLM_PROMPTS.reflection.user(context) }, ]); return response.content; } export async function llmCompact(messages: string, adapter?: LLMServiceAdapter): Promise<string> { const llm = adapter || getLLMAdapter(); const response = await llm.complete([ { role: 'system', content: LLM_PROMPTS.compaction.system }, { role: 'user', content: LLM_PROMPTS.compaction.user(messages) }, ]); return response.content; } export async function llmExtract( conversation: string, adapter?: LLMServiceAdapter ): Promise<string> { const llm = adapter || getLLMAdapter(); const response = await llm.complete([ { role: 'system', content: LLM_PROMPTS.extraction.system }, { role: 'user', content: LLM_PROMPTS.extraction.user(conversation) }, ]); return response.content; } |