This repository has been archived by the owner on Mar 14, 2024. It is now read-only.
Commit
This commit does not belong to any branch on this repository, and may belong to a fork outside of the repository.
Step 4: Streaming chat completions from an Astro API endpoint
- Loading branch information
1 parent
ef630f3
commit 7668f2f
Showing
3 changed files
with
216 additions
and
0 deletions.
There are no files selected for viewing
Some generated files are not rendered by default. Learn more about how customized files appear on GitHub.
Oops, something went wrong.
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,37 @@ | ||
import type { APIRoute } from 'astro'; | ||
import OpenAI from 'openai'; | ||
import { OpenAIStream, StreamingTextResponse } from 'ai'; | ||
|
||
const openai = new OpenAI({ | ||
apiKey: String(import.meta.env.OPENAI_API_KEY), | ||
}); | ||
|
||
export const POST: APIRoute = async ({ request }) => { | ||
const { prompt } = await request.json(); | ||
|
||
const response = await openai.chat.completions.create({ | ||
model: 'gpt-3.5-turbo', | ||
messages: [ | ||
{ | ||
role: 'system', | ||
content: | ||
'You are an AI writing assistant that continues existing text based on context from prior text. ' + | ||
'Give more weight/priority to the later characters than the beginning ones. ' + | ||
'Limit your response to no more than 200 characters, but make sure to construct complete sentences.', | ||
}, | ||
{ | ||
role: 'user', | ||
content: prompt, | ||
}, | ||
], | ||
temperature: 0.7, | ||
top_p: 1, | ||
frequency_penalty: 0, | ||
presence_penalty: 0, | ||
stream: true, | ||
n: 1, | ||
}); | ||
|
||
const stream = OpenAIStream(response) | ||
return new StreamingTextResponse(stream) | ||
} |