mdn-chatbot / src /pages /api /chat-search.ts
lwdgit's picture
feat: 接入chatgpt
f61b332
import { NextApiRequest, NextApiResponse } from 'next'
import ChatGPT from 'gpt-web';
import { search } from './search';
const chatbot = new ChatGPT(process.env.OPENAI_EMAIL!, process.env.OPENAI_PASSWORD!);
export default async function handler(req: NextApiRequest, res: NextApiResponse) {
const text = String(req.query.text);
const limit = String(req.query.limit || 3);
console.log('limit', limit);
res.setHeader('Content-Type', 'text/stream; charset=UTF-8');
if (!text.trim()) {
return res.end('text不能为空');
}
console.log('search', text);
const searchResults = await search(text, parseInt(limit, 10))
const knownledge: string[] = [];
if (searchResults) {
searchResults.forEach(data => {
const { title, text } = data.payload as any;
knownledge.push(`
Q: ${title}
A: ${text}
`.trim());
});
}
const prompt = [
"你是一个研发小助手,名字叫研发小助手。请学习下面的知识回答问题,并按照示例格式仿写。如果内容不相关就返回未查到相关信息:\n\n",
knownledge.join('\n'),
'Q: ' + text + '\nA: '
].join('\n');
console.log('prompt', prompt);
let lastLen = 0;
res.setHeader('Content-Type', 'text/stream; charset=UTF-8');
const response = await chatbot.chat(String(prompt), {
onMessage: (msg: string) => {
res.write(msg.slice(lastLen));
res.flushHeaders();
lastLen = msg.length;
},
});
res.end(response.slice(lastLen));
console.log('done');
}