-
Notifications
You must be signed in to change notification settings - Fork 59
Commit
This commit does not belong to any branch on this repository, and may belong to a fork outside of the repository.
Merge pull request #148 from tegnike/feature/fix-several-external-ser…
…vice-endpoint いくつかのエンドポイント不具合を対応
- Loading branch information
Showing
6 changed files
with
107 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 |
---|---|---|
@@ -1,69 +1,81 @@ | ||
import { OpenAI } from 'openai' | ||
import { Message } from '../messages/messages' | ||
import { ChatCompletionMessageParam } from 'openai/resources' | ||
|
||
export async function getOpenAIChatResponse( | ||
messages: Message[], | ||
apiKey: string, | ||
model: string | ||
) { | ||
if (!apiKey) { | ||
throw new Error('Invalid API Key') | ||
} | ||
|
||
const openai = new OpenAI({ | ||
apiKey: apiKey, | ||
dangerouslyAllowBrowser: true, | ||
}) | ||
|
||
const data = await openai.chat.completions.create({ | ||
model: model, | ||
messages: messages as ChatCompletionMessageParam[], | ||
const response = await fetch('/api/openai', { | ||
method: 'POST', | ||
headers: { | ||
'Content-Type': 'application/json', | ||
}, | ||
body: JSON.stringify({ messages, apiKey, model }), | ||
}) | ||
|
||
const [aiRes] = data.choices | ||
const message = aiRes.message?.content || '回答生成時にエラーが発生しました。' | ||
|
||
return { message: message } | ||
const data = await response.json() | ||
return { message: data.message } | ||
} | ||
|
||
export async function getOpenAIChatResponseStream( | ||
messages: Message[], | ||
apiKey: string, | ||
model: string | ||
) { | ||
if (!apiKey) { | ||
throw new Error('Invalid API Key') | ||
const response = await fetch('/api/openai', { | ||
method: 'POST', | ||
headers: { | ||
'Content-Type': 'application/json', | ||
}, | ||
body: JSON.stringify({ messages, apiKey, model, stream: true }), | ||
}) | ||
|
||
if (!response.ok) { | ||
throw new Error('OpenAI APIリクエストに失敗しました') | ||
} | ||
|
||
const openai = new OpenAI({ | ||
apiKey: apiKey, | ||
dangerouslyAllowBrowser: true, | ||
}) | ||
if (!response.body) { | ||
throw new Error('OpenAI APIレスポンスが空です') | ||
} | ||
|
||
const stream = await openai.chat.completions.create({ | ||
model: model, | ||
messages: messages as ChatCompletionMessageParam[], | ||
stream: true, | ||
max_tokens: 200, | ||
}) | ||
const reader = response.body.getReader() | ||
const decoder = new TextDecoder('utf-8') | ||
|
||
const res = new ReadableStream({ | ||
async start(controller: ReadableStreamDefaultController) { | ||
try { | ||
for await (const chunk of stream) { | ||
const messagePiece = chunk.choices[0].delta.content | ||
if (!!messagePiece) { | ||
controller.enqueue(messagePiece) | ||
return new ReadableStream({ | ||
async start(controller) { | ||
while (true) { | ||
const { done, value } = await reader.read() | ||
|
||
if (done) { | ||
break | ||
} | ||
|
||
const chunk = decoder.decode(value) | ||
const lines = chunk.split('\n') | ||
|
||
for (const line of lines) { | ||
if (line.startsWith('data:')) { | ||
const data = line.substring(5).trim() | ||
if (data !== '[DONE]') { | ||
const event = JSON.parse(data) | ||
switch (event.type) { | ||
case 'content_block_delta': | ||
controller.enqueue(event.text) | ||
break | ||
case 'error': | ||
throw new Error( | ||
`OpenAI API error: ${JSON.stringify(event.error)}` | ||
) | ||
case 'message_stop': | ||
controller.close() | ||
return | ||
} | ||
} | ||
} | ||
} | ||
} catch (error) { | ||
controller.error(error) | ||
} finally { | ||
controller.close() | ||
} | ||
|
||
controller.close() | ||
}, | ||
}) | ||
|
||
return res | ||
} |
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,47 @@ | ||
import { NextApiRequest, NextApiResponse } from 'next' | ||
import OpenAI from 'openai' | ||
import { Message } from '@/features/messages/messages' | ||
|
||
export default async function handler( | ||
req: NextApiRequest, | ||
res: NextApiResponse | ||
) { | ||
const { messages, apiKey, model, stream } = req.body | ||
|
||
const client = new OpenAI({ apiKey }) | ||
|
||
if (stream) { | ||
res.writeHead(200, { | ||
'Content-Type': 'text/event-stream', | ||
'Cache-Control': 'no-cache', | ||
Connection: 'keep-alive', | ||
}) | ||
|
||
const stream = await client.chat.completions.create({ | ||
model: model, | ||
messages: messages, | ||
stream: true, | ||
max_tokens: 200, | ||
}) | ||
|
||
for await (const chunk of stream) { | ||
const messagePiece = chunk.choices[0].delta.content | ||
if (messagePiece) { | ||
res.write( | ||
`data: ${JSON.stringify({ type: 'content_block_delta', text: messagePiece })}\n\n` | ||
) | ||
} | ||
} | ||
|
||
res.write(`data: ${JSON.stringify({ type: 'message_stop' })}\n\n`) | ||
res.end() | ||
} else { | ||
const response = await client.chat.completions.create({ | ||
model: model, | ||
messages: messages, | ||
max_tokens: 200, | ||
}) | ||
|
||
res.status(200).json({ message: response.choices[0].message.content }) | ||
} | ||
} |
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