* 初始化 LLM
()
| 39 | * 初始化 LLM |
| 40 | */ |
| 41 | public async init(): Promise<void> { |
| 42 | if (!this.config) { |
| 43 | throw new Error('LLM 未配置,请先调用 configure()'); |
| 44 | } |
| 45 | |
| 46 | if (this.isInitialized) { |
| 47 | this.log('LLM 已经初始化'); |
| 48 | return; |
| 49 | } |
| 50 | |
| 51 | const { provider, apiKey, model, baseURL } = this.config; |
| 52 | |
| 53 | // 获取默认配置 |
| 54 | const defaultConfig = getProviderConfig(provider); |
| 55 | |
| 56 | // 验证API密钥(优先使用传入的,然后是环境变量) |
| 57 | let finalApiKey: string; |
| 58 | try { |
| 59 | // 导入validateApiKey函数 |
| 60 | const { validateApiKey } = await import('../config/defaults.js'); |
| 61 | finalApiKey = validateApiKey(provider, apiKey); |
| 62 | } catch (error) { |
| 63 | throw new Error(`API密钥验证失败: ${(error as Error).message}`); |
| 64 | } |
| 65 | |
| 66 | const finalModel = model || defaultConfig.defaultModel; |
| 67 | |
| 68 | this.log(`初始化 ${provider} LLM...`); |
| 69 | |
| 70 | // 创建 LLM 实例 |
| 71 | switch (provider) { |
| 72 | case 'qwen': |
| 73 | this.llm = new QwenLLM( |
| 74 | { |
| 75 | apiKey: finalApiKey, |
| 76 | baseURL: baseURL || defaultConfig.baseURL, |
| 77 | }, |
| 78 | finalModel |
| 79 | ); |
| 80 | break; |
| 81 | case 'volcengine': |
| 82 | this.llm = new VolcEngineLLM( |
| 83 | { |
| 84 | apiKey: finalApiKey, |
| 85 | baseURL: baseURL || defaultConfig.baseURL, |
| 86 | }, |
| 87 | finalModel |
| 88 | ); |
| 89 | break; |
| 90 | default: |
| 91 | throw new Error(`不支持的 LLM 提供商: ${provider}`); |
| 92 | } |
| 93 | |
| 94 | // 初始化 LLM |
| 95 | await this.llm.init(); |
| 96 | this.isInitialized = true; |
| 97 | this.log(`${provider} LLM 初始化完成`); |
| 98 | } |
no test coverage detected