export default async (
{ userRequest, systemPrompt, openaiSecret, model, temperature },
{ logging, req: ctx = {}},
) => {
// Create a new Readable stream for writing the response
let writeStream = (ctx.body = new Readable());
writeStream._read = function () {}; // Make the writeStream readable
writeStream.pipe(ctx.res); // Pipe the writeStream to the response object to send data to the client
ctx.type = "text/undefined-content";
// Set response headers
Object.assign(ctx.response.headers, {
"Transfer-Encoding": "chunked",
Connection: "keep-alive",
});
// Initialize OpenAI API client
const openai = new OpenAI({
apiKey: openaiSecret,
});
try {
// Make an asynchronous call to OpenAI API to get stream response
const completion = await openai.beta.chat.completions.stream(
{
model,
temperature,
messages: [
{
role: "system",
content: systemPrompt,
},
{
role: "user",
content: userRequest,
},
],
stream: true,
},
{
responseType: "stream",
},
);
// Stream data from completion to the writeStream
const response = await streamer(writeStream, completion);
return response;
} catch (error) {
// Handle errors if any
logging.log(error);
return "";
}
};
export default async (
{ userRequest, systemPrompt, openaiSecret, model, temperature },
{ logging, req: ctx = {}},
) => {
// Create a new Readable stream for writing the response
let writeStream = (ctx.body = new Readable());
writeStream._read = function () {}; // Make the writeStream readable
writeStream.pipe(ctx.res); // Pipe the writeStream to the response object to send data to the client
ctx.type = "text/undefined-content";
// Set response headers
Object.assign(ctx.response.headers, {
"Transfer-Encoding": "chunked",
Connection: "keep-alive",
});
// Initialize OpenAI API client
const openai = new OpenAI({
apiKey: openaiSecret,
});
try {
// Make an asynchronous call to OpenAI API to get stream response
const completion = await openai.beta.chat.completions.stream(
{
model,
temperature,
messages: [
{
role: "system",
content: systemPrompt,
},
{
role: "user",
content: userRequest,
},
],
stream: true,
},
{
responseType: "stream",
},
);
// Stream data from completion to the writeStream
const response = await streamer(writeStream, completion);
return response;
} catch (error) {
// Handle errors if any
logging.log(error);
return "";
}
};