Spaces:
Sleeping
Sleeping
File size: 1,508 Bytes
f61b332 |
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 |
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');
}
|