feat: init

This commit is contained in:
Joel
2023-04-14 20:35:08 +08:00
parent 8acd8f6fbd
commit 97d3a6277d
77 changed files with 5299 additions and 0 deletions

20
app/api/utils/common.ts Normal file
View File

@ -0,0 +1,20 @@
import { type NextRequest } from 'next/server'
import { APP_ID, API_KEY } from '@/config'
import { ChatClient } from '../sdk'
const userPrefix = `user_${APP_ID}:`;
const uuid = require('uuid')
export const getInfo = (request: NextRequest) => {
const sessionId = request.cookies.get('session_id')?.value || uuid.v4();
const user = userPrefix + sessionId;
return {
sessionId,
user
}
}
export const setSession = (sessionId: string) => {
return { 'Set-Cookie': `session_id=${sessionId}` }
}
export const client = new ChatClient(API_KEY)

25
app/api/utils/stream.ts Normal file
View File

@ -0,0 +1,25 @@
export async function OpenAIStream(res: { body: any }) {
const reader = res.body.getReader();
const stream = new ReadableStream({
// https://developer.mozilla.org/en-US/docs/Web/API/Streams_API/Using_readable_streams
// https://github.com/whichlight/chatgpt-api-streaming/blob/master/pages/api/OpenAIStream.ts
start(controller) {
return pump();
function pump() {
return reader.read().then(({ done, value }: any) => {
// When no more data needs to be consumed, close the stream
if (done) {
controller.close();
return;
}
// Enqueue the next data chunk into our target stream
controller.enqueue(value);
return pump();
});
}
},
});
return stream;
}