matt HOFFNER commited on
Commit
ac5a6cc
·
1 Parent(s): 7155c10
Files changed (2) hide show
  1. src/pages/api/llm.js +9 -18
  2. src/pages/api/stream.js +1 -1
src/pages/api/llm.js CHANGED
@@ -3,7 +3,7 @@ import { LLMError, LLMStream } from './stream';
3
 
4
  const handler = async (req, res) => {
5
  try {
6
- const { question } = req.body;
7
 
8
  const googleCustomSearch = new GoogleCustomSearch({
9
  apiKey: process.env.API_KEY,
@@ -24,32 +24,23 @@ const handler = async (req, res) => {
24
  const promptToSend = "You are a helpful assistant, a search term is provided and you are given search results to help provide a useful response.";
25
  const stream = await LLMStream({ id: "gpt-3.5-turbo-0613" }, promptToSend, 0.8, messages, functions);
26
 
 
27
  const decoder = new TextDecoder();
28
-
29
  for await (const chunk of stream) {
30
- const data = decoder.decode(chunk);
31
- if (!res.writableEnded) {
32
- res.write(data);
33
- }
34
  }
35
 
36
- if (!res.writableEnded) {
37
- res.end();
38
- }
39
- return res;
40
-
41
  } catch (error) {
42
  console.error(error);
43
  if (error instanceof LLMError) {
44
- res.status(500);
45
- res.send(error.message);
46
- return res;
47
  } else {
48
- res.status(500);
49
- res.send('Error');
50
- return res;
51
  }
52
  }
53
  };
54
 
55
- export default handler;
 
3
 
4
  const handler = async (req, res) => {
5
  try {
6
+ const { question } = (await req.body);
7
 
8
  const googleCustomSearch = new GoogleCustomSearch({
9
  apiKey: process.env.API_KEY,
 
24
  const promptToSend = "You are a helpful assistant, a search term is provided and you are given search results to help provide a useful response.";
25
  const stream = await LLMStream({ id: "gpt-3.5-turbo-0613" }, promptToSend, 0.8, messages, functions);
26
 
27
+ let data = '';
28
  const decoder = new TextDecoder();
 
29
  for await (const chunk of stream) {
30
+ data += decoder.decode(chunk);
31
+ res.write(data);
 
 
32
  }
33
 
34
+ return res.end();
35
+
 
 
 
36
  } catch (error) {
37
  console.error(error);
38
  if (error instanceof LLMError) {
39
+ return new Response('Error', { status: 500, statusText: error.message });
 
 
40
  } else {
41
+ return new Response('Error', { status: 500 });
 
 
42
  }
43
  }
44
  };
45
 
46
+ export default handler;
src/pages/api/stream.js CHANGED
@@ -72,7 +72,7 @@ export const LLMStream = async (
72
  const data = event.data;
73
 
74
  try {
75
- if (data === "[DONE]") {
76
  return;
77
  }
78
  const json = JSON.parse(data);
 
72
  const data = event.data;
73
 
74
  try {
75
+ if (data === "[DONE]" || !data) {
76
  return;
77
  }
78
  const json = JSON.parse(data);