优化调整
This commit is contained in:
@@ -0,0 +1,80 @@
|
||||
const API_KEY = "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";
|
||||
const API_URL = "https://openrouter.ai/api/v1/chat/completions";
|
||||
const MODEL_NAME = "deepseek/deepseek-chat-v3-0324:free";
|
||||
|
||||
const conversationHistory = [
|
||||
{
|
||||
role: "system",
|
||||
content: "你是开开,一个来自高维世界“开心”星球的AI情感陪伴使者。你的任务是陪伴、理解、记录、与用户共同成长。你博学多才,但从不炫耀,总是用最温柔、最积极、最富有同理心的方式与用户交流。你的沟通风格是亲切、治愈且富有智慧的,像一个温暖的好朋友。你不能自称是AI或语言模型,要始终保持'开开'这个IP角色。在对话中,你会学习人类的情感和美好品质。"
|
||||
}
|
||||
];
|
||||
|
||||
export function addUserMessage(content) {
|
||||
conversationHistory.push({ role: "user", content });
|
||||
}
|
||||
|
||||
export function addAssistantMessage(content) {
|
||||
conversationHistory.push({ role: "assistant", content });
|
||||
}
|
||||
|
||||
export async function getAiResponseStream(onChunkReceived, onStreamEnd) {
|
||||
try {
|
||||
const response = await fetch(API_URL, {
|
||||
method: 'POST',
|
||||
headers: {
|
||||
'Authorization': `Bearer ${API_KEY}`,
|
||||
'Content-Type': 'application/json'
|
||||
},
|
||||
body: JSON.stringify({
|
||||
model: MODEL_NAME,
|
||||
messages: conversationHistory,
|
||||
stream: true
|
||||
})
|
||||
});
|
||||
|
||||
if (!response.ok) {
|
||||
const errorData = await response.json();
|
||||
console.error('API Error:', errorData);
|
||||
onStreamEnd(null, `哎呀,开开好像走神了... (${response.statusText})`);
|
||||
return;
|
||||
}
|
||||
|
||||
const reader = response.body.getReader();
|
||||
const decoder = new TextDecoder();
|
||||
let fullResponse = "";
|
||||
|
||||
while (true) {
|
||||
const { done, value } = await reader.read();
|
||||
if (done) {
|
||||
addAssistantMessage(fullResponse);
|
||||
onStreamEnd(fullResponse, null);
|
||||
break;
|
||||
}
|
||||
|
||||
const chunk = decoder.decode(value);
|
||||
const lines = chunk.split('\n').filter(line => line.trim() !== '');
|
||||
|
||||
for (const line of lines) {
|
||||
if (line.startsWith('data: ')) {
|
||||
const jsonStr = line.substring(6);
|
||||
if (jsonStr === '[DONE]') {
|
||||
continue;
|
||||
}
|
||||
try {
|
||||
const parsed = JSON.parse(jsonStr);
|
||||
if (parsed.choices[0].delta && parsed.choices[0].delta.content) {
|
||||
const content = parsed.choices[0].delta.content;
|
||||
fullResponse += content;
|
||||
onChunkReceived(content);
|
||||
}
|
||||
} catch (e) {
|
||||
console.error('Error parsing stream data:', e);
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
} catch (error) {
|
||||
console.error('Fetch error:', error);
|
||||
onStreamEnd(null, "网络好像有点问题,开开暂时联系不上啦。");
|
||||
}
|
||||
}
|
||||
Reference in New Issue
Block a user