-
Notifications
You must be signed in to change notification settings - Fork 2.4k
Commit
This commit does not belong to any branch on this repository, and may belong to a fork outside of the repository.
feat(nx-dev): move openai call to edge function (#18747)
- Loading branch information
Showing
3 changed files
with
101 additions
and
48 deletions.
There are no files selected for viewing
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,45 @@ | ||
import { NextRequest } from 'next/server'; | ||
|
||
const openAiKey = process.env['NX_OPENAI_KEY']; | ||
export const config = { | ||
runtime: 'edge', | ||
}; | ||
|
||
export default async function handler(request: NextRequest) { | ||
const { action, input } = await request.json(); | ||
|
||
let apiUrl = 'https://api.openai.com/v1/'; | ||
|
||
if (action === 'embedding') { | ||
apiUrl += 'embeddings'; | ||
} else if (action === 'chatCompletion') { | ||
apiUrl += 'chat/completions'; | ||
} else if (action === 'moderation') { | ||
apiUrl += 'moderations'; | ||
} else { | ||
return new Response('Invalid action', { status: 400 }); | ||
} | ||
|
||
try { | ||
const response = await fetch(apiUrl, { | ||
method: 'POST', | ||
headers: { | ||
Authorization: `Bearer ${openAiKey}`, | ||
'Content-Type': 'application/json', | ||
}, | ||
body: JSON.stringify(input), | ||
}); | ||
|
||
const responseData = await response.json(); | ||
|
||
return new Response(JSON.stringify(responseData), { | ||
status: response.status, | ||
headers: { | ||
'content-type': 'application/json', | ||
}, | ||
}); | ||
} catch (e) { | ||
console.error('Error processing the request:', e.message); | ||
return new Response(e.message, { status: 500 }); | ||
} | ||
} |
bd76b62
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
Successfully deployed to the following URLs:
nx-dev – ./
nx-dev-git-master-nrwl.vercel.app
nx.dev
nx-dev-nrwl.vercel.app
nx-five.vercel.app