37 lines
1.2 KiB
JavaScript
37 lines
1.2 KiB
JavaScript
import axios from 'axios';
|
|
import https from 'https';
|
|
import { getLLMConfig } from './config.js';
|
|
|
|
const httpsAgent = new https.Agent({ rejectUnauthorized: false });
|
|
|
|
export async function chat(systemPrompt, userContent) {
|
|
const { provider, apiKey, baseURL, model } = getLLMConfig();
|
|
if (!provider) throw new Error('未設定任何 LLM API Key');
|
|
|
|
console.log(` [LLM] provider=${provider} model=${model}`);
|
|
|
|
const headers = {
|
|
'Content-Type': 'application/json',
|
|
'Authorization': `Bearer ${apiKey}`,
|
|
};
|
|
if (provider === 'claude') headers['anthropic-version'] = '2023-06-01';
|
|
|
|
const resp = await axios.post(
|
|
`${baseURL.replace(/\/$/, '')}/chat/completions`,
|
|
{ model, messages: [{ role: 'system', content: systemPrompt }, { role: 'user', content: userContent }], temperature: 0.2 },
|
|
{ headers, timeout: 120000, httpsAgent }
|
|
);
|
|
return resp.data.choices[0].message.content;
|
|
}
|
|
|
|
export async function chatJSON(systemPrompt, userContent) {
|
|
try {
|
|
let text = await chat(systemPrompt, userContent);
|
|
text = text.trim().replace(/^```[^\n]*\n?/, '').replace(/```$/, '').trim();
|
|
return JSON.parse(text);
|
|
} catch (e) {
|
|
console.log(` [LLM] 解析失敗: ${e.message}`);
|
|
return [];
|
|
}
|
|
}
|