matt HOFFNER commited on
Commit
7155c10
·
1 Parent(s): e5b6f72

refactor stream

Browse files
Files changed (1) hide show
  1. src/pages/api/llm.js +19 -10
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 } = (await req.body);
7
 
8
  const googleCustomSearch = new GoogleCustomSearch({
9
  apiKey: process.env.API_KEY,
@@ -21,26 +21,35 @@ const handler = async (req, res) => {
21
  googleCustomSearch
22
  };
23
 
24
- let 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;
 
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,
 
21
  googleCustomSearch
22
  };
23
 
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;