Spaces:
Paused
Paused
File size: 2,076 Bytes
f6091f7 29df9bc f6091f7 29df9bc f6091f7 29df9bc f6091f7 29df9bc f6091f7 |
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 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 |
import { Configuration, OpenAIApi } from "openai";
import { GoogleCustomSearch } from "openai-function-calling-tools";
export default async function handler(req, res) {
if (req.method !== 'POST') {
// Handle any other HTTP method
res.status(405).send({ error: 'Method Not Allowed', method: req.method });
return;
}
const QUESTION = req.body.question;
if (!QUESTION) {
res.status(400).send({ error: 'Question is missing in request body' });
return;
}
const configuration = new Configuration({
apiKey: process.env.OPENAI_API_KEY,
});
const openai = new OpenAIApi(configuration);
const messages = [
{
role: "user",
content: QUESTION,
},
];
const { googleCustomSearch, googleCustomSearchSchema } = new GoogleCustomSearch({
apiKey: process.env.GOOGLE_API_KEY,
googleCSEId: process.env.GOOGLE_CSE_ID,
});
const functions = {
googleCustomSearch,
};
const getCompletion = async (messages) => {
const response = await openai.createChatCompletion({
model: "gpt-3.5-turbo-0613",
messages,
functions: [googleCustomSearchSchema],
temperature: 0,
});
return response;
};
let response;
while (true) {
response = await getCompletion(messages);
if (response.data.choices[0].finish_reason === "stop") {
res.status(200).json({ result: response.data.choices[0].message.content });
break;
} else if (response.data.choices[0].finish_reason === "function_call") {
const fnName = response.data.choices[0].message.function_call.name;
const args = response.data.choices[0].message.function_call.arguments;
const fn = functions[fnName];
const result = await fn(...Object.values(JSON.parse(args)));
messages.push({
role: "assistant",
content: "",
function_call: {
name: fnName,
arguments: args,
},
});
messages.push({
role: "function",
name: fnName,
content: JSON.stringify({ result: result }),
});
}
}
}
|