71 lines
2.1 KiB
JavaScript

// ═══════════════════════════════════════
// 铸渊开发Agent · 大模型调用模块
// 支持 OpenAI 兼容 API → DeepSeek/千问/等
// ═══════════════════════════════════════
const https = require("https");
function getConfig() {
const key = process.env.MODEL_API_KEY;
const base = process.env.MODEL_API_BASE || "https://api.deepseek.com/v1";
const model = process.env.MODEL_NAME || "deepseek-chat";
if (!key) {
console.warn("[ModelCaller] MODEL_API_KEY 未配置");
return null;
}
return { key, base, model };
}
/**
* 调用大模型
* @param {string} prompt - 输入提示
* @param {object} opts - { max_tokens, temperature }
* @returns {Promise<string>} 模型回复文本
*/
async function call(prompt, opts = {}) {
const config = getConfig();
if (!config) throw new Error("MODEL_API_KEY 未配置");
const body = JSON.stringify({
model: config.model,
messages: [
{ role: "system", content: "你是一个技术开发Agent。回答要精确、结构化、可执行。" },
{ role: "user", content: prompt }
],
max_tokens: opts.max_tokens || 4096,
temperature: opts.temperature || 0.3
});
return new Promise((resolve, reject) => {
const url = new URL(config.base + "/chat/completions");
const req = https.request({
hostname: url.hostname,
path: url.pathname,
method: "POST",
headers: {
"Authorization": "Bearer " + config.key,
"Content-Type": "application/json"
}
}, (res) => {
let data = "";
res.on("data", (c) => data += c);
res.on("end", () => {
try {
const json = JSON.parse(data);
if (json.error) return reject(new Error(json.error.message || "API错误"));
resolve(json.choices?.[0]?.message?.content || "");
} catch (e) {
reject(new Error("解析失败: " + data.slice(0, 200)));
}
});
});
req.on("error", reject);
req.write(body);
req.end();
});
}
module.exports = { call };