| 343 | |
| 344 | // AI 调用函数 |
| 345 | function normalizedBaseUrl(baseUrl: string): string { |
| 346 | // 允许用户填写根地址、末尾 / 或常见的 /v1;具体端点由插件统一追加。 |
| 347 | return baseUrl.replace(/\/+$/, "").replace(/\/v1(?:beta)?$/i, ""); |
| 348 | } |
| 349 | |
| 350 | function detectProtocol( |
| 351 | provider: CustomProvider, |
| 352 | ): Exclude<ProviderProtocol, "auto"> { |
| 353 | if (provider.type && provider.type !== "auto" && provider.type !== "openai") { |
| 354 | return provider.type; |
| 355 | } |
| 356 | |
| 357 | const model = provider.model.toLowerCase(); |
| 358 | if (model.startsWith("gemini")) return "gemini"; |
| 359 | if (model.startsWith("claude")) return "anthropic"; |
| 360 | if (/^(gpt-5|o[1-9])/.test(model)) return "responses"; |
| 361 | return "chat"; |
| 362 | } |
| 363 | |
| 364 | function apiErrorDetail(error: unknown): string { |
| 365 | if (axios.isAxiosError(error)) { |
| 366 | return JSON.stringify(error.response?.data ?? error.message); |
| 367 | } |
| 368 | return String((error as any)?.message ?? error); |
| 369 | } |
| 370 | |
| 371 | async function callChatCompletions( |
| 372 | apiKey: string, |
| 373 | baseUrl: string, |
| 374 | model: string, |
| 375 | input: string, |
| 376 | timeout: number, |
| 377 | ): Promise<string> { |
| 378 | const response = await axios.post( |
| 379 | `${normalizedBaseUrl(baseUrl)}/v1/chat/completions`, |
| 380 | { model, messages: [{ role: "user", content: input }], max_tokens: 2000 }, |
| 381 | { |
| 382 | headers: { |
| 383 | Authorization: `Bearer ${apiKey}`, |
| 384 | "Content-Type": "application/json", |