Skip to content

Commit

Permalink
feat: openai 支持网页端调用
Browse files Browse the repository at this point in the history
  • Loading branch information
weaigc committed Sep 22, 2023
1 parent 5a928c4 commit 5b7b6dc
Show file tree
Hide file tree
Showing 2 changed files with 29 additions and 3 deletions.
10 changes: 7 additions & 3 deletions src/pages/api/chat/completions.ts
Original file line number Diff line number Diff line change
Expand Up @@ -37,6 +37,7 @@ function parseOpenAIMessage(request: APIRequest) {
return {
prompt: request.messages?.reverse().find((message) => message.role === 'user')?.content,
stream: request.stream,
model: request.model,
};
}

Expand All @@ -55,10 +56,11 @@ function responseOpenAIMessage(content: string, id?: string): APIResponse {
}

export default async function handler(req: NextApiRequest, res: NextApiResponse) {
const { prompt, stream } = parseOpenAIMessage(req.body);
if (req.method !== 'POST') return res.status(403).end()
const { prompt, stream, model } = parseOpenAIMessage(req.body);
let { id } = req.body
const chatbot = new BingWebBot({
endpoint: 'http://127.0.0.1:3000' || req.headers.origin,
endpoint: req.headers.origin || `http://127.0.0.1:${process.env.PORT}`,
cookie: `BING_IP=${process.env.BING_IP}`
})
id ||= JSON.stringify(chatbot.createConversation())
Expand All @@ -71,10 +73,12 @@ export default async function handler(req: NextApiRequest, res: NextApiResponse)
const abortController = new AbortController()
assert(prompt, 'messages can\'t be empty!')

const toneType = model as BingConversationStyle
chatbot.sendMessage({
prompt,
options: {
bingConversationStyle: BingConversationStyle.Creative,
bingConversationStyle: Object.values(BingConversationStyle)
.includes(toneType) ? toneType : BingConversationStyle.Creative,
conversation: JSON.parse(id) as ConversationInfoBase
},
signal: abortController.signal,
Expand Down
22 changes: 22 additions & 0 deletions src/pages/middleware.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,22 @@
import { NextRequest, NextResponse } from 'next/server';

export function middleware(request: NextRequest) {
// retrieve the current response
const res = NextResponse.next()

// add the CORS headers to the response
res.headers.append('Access-Control-Allow-Credentials', 'true')
res.headers.append('Access-Control-Allow-Origin', `https://${request.headers.get('host')}`)
res.headers.append('Access-Control-Allow-Methods', 'GET,DELETE,PATCH,POST,PUT')
res.headers.append(
'Access-Control-Allow-Headers',
'X-CSRF-Token, X-Requested-With, Accept, Accept-Version, Content-Length, Content-MD5, Content-Type, Date, X-Api-Version'
)

return res
}

// specify the path regex to apply the middleware to
export const config = {
matcher: '/api/chat/completions',
}

0 comments on commit 5b7b6dc

Please sign in to comment.