esp-ai-plugin-llm-ollama
Version:
ollama
108 lines (93 loc) • 4.17 kB
JavaScript
const axios = require('axios');
// 避免每个用户重复创建对象
const device_open_obj = {};
module.exports = {
// 插件名字
name: "esp-ai-plugin-llm-ollama",
// 插件类型 LLM | TTS | IAT
type: "LLM",
main({ devLog, log, llm_config, is_pre_connect,text, llmServerErrorCb, llm_init_messages = [], llm_historys = [], cb, llm_params_set, logWSServer, connectServerBeforeCb, connectServerCb }) {
try {
const { MODEL,URL,...other_config } = llm_config;
if (!MODEL) return log.error(`请配给 Ollama 配置 MODEL 参数。`);
if (!URL) return log.error(`请配给 Ollama 配置 URL 参数。`);
// 预先连接函数
async function preConnect() {
// some code...
// 如果你不理解,可以不用写任何逻辑
}
if (is_pre_connect) {
preConnect()
return;
}
// 如果关闭后 message 还没有被关闭,需要定义一个标志控制
let shouldClose = false;
// 这个对象是固定写法,每个 TTS 都必须按这个结构定义
const texts = {
all_text: "",
count_text: "",
index: 0,
};
// 告诉框架要开始连接 LLM 服务了
connectServerBeforeCb();
// 设置baseURL,明确指定使用IPv4的localhost地址
axios.defaults.baseURL = URL;
async function main() {
try {
const response = await axios.post('/api/chat ', {
"model": MODEL,
"stream": true,
'messages': [
...llm_init_messages,
...llm_historys,
{
"role": "user", "content": text
},
],
});
connectServerCb(true);
logWSServer({
close: () => {
connectServerCb(false);
shouldClose = true;
}
});
const dataLines = response.data.split('\n');
// 将返回的数据(本身是文本格式,包含多行JSON对象)按行分割成数组
for (const line of dataLines) {
if (line.trim()) {
const jsonData = JSON.parse(line);
const chunk_text = jsonData.message.content || "";
//console.log('LLM 输出 :', chunk_text);
if (shouldClose) break;
devLog === 2 && log.llm_info('LLM 输出 :', chunk_text);
texts["count_text"] += chunk_text;
cb({ text, texts, chunk_text: chunk_text });
}
}
if (shouldClose) return;
cb({
text,
is_over: true,
texts,
shouldClose,
});
connectServerCb(false);
devLog && log.llm_info('===');
devLog && log.llm_info(texts["count_text"]);
devLog && log.llm_info('===');
devLog && log.llm_info('LLM connect close!\n');
} catch (error) {
console.log(error);
llmServerErrorCb("OllamaLLM 报错: " + error);
connectServerCb(false);
}
}
main();
} catch (err) {
console.log(err);
log.error("Ollama LLM 插件错误:", err);
connectServerCb(false);
}
}
};