paper-ai-release-24-07-21/components/chatAI.tsx

197 lines
6.3 KiB
TypeScript
Raw Normal View History

2024-01-18 15:46:18 +08:00
import { Transforms } from "slate";
import { Editor } from "slate";
import { extractText } from "@/utils/others/slateutils";
import {
updateBracketNumbersInDeltaKeepSelection,
convertToSuperscript,
} from "@/utils/others/quillutils";
//redux不能在普通函数使用
2024-01-18 15:46:18 +08:00
interface ChatData {
choices: Array<{
delta: {
content?: string;
};
}>;
}
2024-01-21 23:08:25 +08:00
function isValidApiKey(apiKey: string) {
return apiKey && apiKey.trim() !== "";
}
2024-01-18 15:46:18 +08:00
const sendMessageToOpenAI = async (
2024-01-20 13:43:31 +08:00
content: string,
2024-01-18 15:46:18 +08:00
editor: Editor,
2024-01-20 13:43:31 +08:00
selectedModel: "gpt3.5",
2024-01-21 23:08:25 +08:00
apiKey: string,
upsreamUrl: string,
2024-01-18 23:22:23 +08:00
prompt?: string
2024-01-18 15:46:18 +08:00
) => {
2024-01-20 13:43:31 +08:00
//识别应该使用的模型
2024-01-21 23:08:25 +08:00
let model = selectedModel === "gpt3.5" ? "gpt-3.5-turbo" : "gpt-4";
console.log("upstreamUrl", upsreamUrl);
2024-01-18 15:46:18 +08:00
// 设置API请求参数
const requestOptions = {
method: "POST",
headers: {
"Content-Type": "application/json",
2024-01-28 14:58:46 +08:00
// "Upstream-Url": upsreamUrl,
2024-01-21 23:08:25 +08:00
Authorization:
"Bearer " +
(isValidApiKey(apiKey)
? apiKey
: process.env.NEXT_PUBLIC_OPENAI_API_KEY),
2024-01-18 15:46:18 +08:00
},
body: JSON.stringify({
2024-01-20 13:43:31 +08:00
model: model,
2024-01-18 15:46:18 +08:00
stream: true,
messages: [
{
role: "system",
2024-01-21 23:08:25 +08:00
content:
prompt ||
`作为论文写作助手,您的主要任务是根据用户提供的研究主题和上下文,以及相关的研究论文,来撰写和完善学术论文。在撰写过程中,请注意以下要点:
2024-01-18 15:46:18 +08:00
1.使
2024-01-28 19:01:11 +08:00
2.使 [1]***[1]*
2024-01-18 15:46:18 +08:00
3.
4.
5.使,
2024-01-19 15:36:41 +08:00
6.
2024-01-18 23:22:23 +08:00
...[1],...[2]`,
2024-01-18 15:46:18 +08:00
},
{
role: "user",
content: content,
},
],
}),
};
console.log("请求的内容\n", content);
// 发送API请求
let response;
2024-01-18 15:46:18 +08:00
try {
2024-01-28 14:58:46 +08:00
response = await fetch(
2024-01-28 15:14:53 +08:00
(upsreamUrl || process.env.NEXT_PUBLIC_AI_URL) + "/v1/chat/completions",
2024-01-28 14:58:46 +08:00
requestOptions
);
if (!response.ok) {
throw new Error("Server responded with an error");
}
2024-01-18 15:46:18 +08:00
const reader = response.body.getReader();
const decoder = new TextDecoder();
2024-01-31 22:52:37 +08:00
//开始结束前先进行换行
2024-01-30 12:05:34 +08:00
editor.insertText(editor.getSelection().index, "\n");
2024-01-31 22:52:37 +08:00
await processResult(reader, decoder, editor);
2024-01-18 15:46:18 +08:00
convertToSuperscript(editor);
updateBracketNumbersInDeltaKeepSelection(editor);
} catch (error) {
console.error("Error:", error);
// 如果有响应,返回响应的原始内容
if (response) {
const rawResponse = await response.text();
throw new Error(`Error: ${error.message}, Response: ${rawResponse}`);
}
// 如果没有响应,只抛出错误
2024-01-21 23:08:25 +08:00
throw error;
2024-01-18 15:46:18 +08:00
}
};
2024-01-21 23:08:25 +08:00
const getTopicFromAI = async (
userMessage: string,
prompt: string,
apiKey: string
) => {
2024-01-18 23:22:23 +08:00
// 设置API请求参数
const requestOptions = {
method: "POST",
headers: {
"Content-Type": "application/json",
2024-01-21 23:08:25 +08:00
Authorization:
"Bearer " +
(isValidApiKey(apiKey)
? apiKey
: process.env.NEXT_PUBLIC_OPENAI_API_KEY),
2024-01-18 23:22:23 +08:00
},
body: JSON.stringify({
model: "gpt-3.5-turbo",
stream: false,
messages: [
{
role: "system",
content: prompt,
},
{
role: "user",
content: userMessage,
},
],
}),
};
2024-01-29 13:35:24 +08:00
const response = await fetch(
process.env.NEXT_PUBLIC_AI_URL + "/v1/chat/completions",
requestOptions
);
2024-01-19 15:36:41 +08:00
const data = await response.json();
2024-01-21 23:08:25 +08:00
const topic = data.choices[0].message.content;
return topic; // 获取并返回回复
2024-01-18 23:22:23 +08:00
};
2024-01-20 13:43:31 +08:00
// 给getTopicFromAI函数创建别名
// export const getFromAI = sendMessageToOpenAI;
2024-01-28 11:45:15 +08:00
async function processResult(reader, decoder, editor) {
let buffer = "";
2024-01-18 15:46:18 +08:00
while (true) {
const { done, value } = await reader.read();
if (done) {
console.log("Stream finished");
break;
}
2024-01-28 11:45:15 +08:00
buffer += decoder.decode(value, { stream: true });
2024-01-28 19:01:11 +08:00
// console.log("buffer", buffer);
2024-01-28 11:45:15 +08:00
// 处理缓冲区中的所有完整的 JSON 对象
let boundary;
2024-01-28 14:58:46 +08:00
try {
while ((boundary = buffer.indexOf("}\n")) !== -1) {
// 找到一个完整的 JSON 对象的边界
let jsonStr = buffer.substring(0, boundary + 1);
buffer = buffer.substring(boundary + 2);
2024-01-28 19:01:11 +08:00
// console.log("jsonStr", jsonStr);
2024-01-18 15:46:18 +08:00
2024-01-28 14:58:46 +08:00
// 尝试解析 JSON 对象
try {
// 如果 jsonStr 以 "data: " 开头,就移除这个前缀
// 移除字符串首尾的空白字符
jsonStr = jsonStr.trim();
jsonStr = jsonStr.substring(6);
let dataObject = JSON.parse(jsonStr);
2024-01-29 13:35:24 +08:00
// console.log("dataObject", dataObject);
2024-01-28 14:58:46 +08:00
// 处理 dataObject 中的 content
if (dataObject.choices && dataObject.choices.length > 0) {
let content =
dataObject.choices[0].message?.content ||
dataObject.choices[0].delta?.content;
if (content) {
// 在当前光标位置插入文本
editor.focus();
2024-01-28 14:58:46 +08:00
editor.insertText(editor.getSelection().index, content);
2024-01-29 13:35:24 +08:00
// console.log("成功插入:", content);
2024-01-28 14:58:46 +08:00
}
2024-01-18 15:46:18 +08:00
}
2024-01-28 14:58:46 +08:00
} catch (error) {
// console.error("Failed to parse JSON object:", jsonStr);
2024-01-28 14:58:46 +08:00
console.error("Error:", error);
break;
2024-01-18 15:46:18 +08:00
}
2024-01-28 11:45:15 +08:00
}
2024-01-28 14:58:46 +08:00
} catch (error) {
break;
2024-01-18 15:46:18 +08:00
}
}
}
2024-01-18 23:22:23 +08:00
export { getTopicFromAI, sendMessageToOpenAI };