|
| 1 | +import { CHAT_SETTING_LIMITS } from "@/lib/chat-setting-limits" |
| 2 | +import { checkApiKey, getServerProfile } from "@/lib/server-chat-helpers" |
| 3 | +import { ChatAPIPayload } from "@/types" |
| 4 | +import { OpenAIStream, StreamingTextResponse } from "ai" |
| 5 | +import OpenAI from "openai" |
| 6 | +import { ChatCompletionCreateParamsBase } from "openai/resources/chat/completions.mjs" |
| 7 | + |
| 8 | +export const runtime = "edge" |
| 9 | + |
| 10 | +export async function POST(request: Request) { |
| 11 | + const json = await request.json() |
| 12 | + const { chatSettings, messages } = json as ChatAPIPayload |
| 13 | + |
| 14 | + try { |
| 15 | + const profile = await getServerProfile() |
| 16 | + |
| 17 | + checkApiKey(profile.azure_openai_api_key, "Azure") |
| 18 | + |
| 19 | + const ENDPOINT = profile.azure_openai_endpoint |
| 20 | + const KEY = profile.azure_openai_api_key |
| 21 | + |
| 22 | + let DEPLOYMENT_ID = "" |
| 23 | + switch (chatSettings.model) { |
| 24 | + case "gpt-3.5-turbo-1106": |
| 25 | + DEPLOYMENT_ID = profile.azure_openai_35_turbo_id || "" |
| 26 | + break |
| 27 | + case "gpt-4-1106-preview": |
| 28 | + DEPLOYMENT_ID = profile.azure_openai_45_turbo_id || "" |
| 29 | + break |
| 30 | + case "gpt-4-vision-preview": |
| 31 | + DEPLOYMENT_ID = profile.azure_openai_45_vision_id || "" |
| 32 | + break |
| 33 | + default: |
| 34 | + return new Response(JSON.stringify({ message: "Model not found" }), { |
| 35 | + status: 400 |
| 36 | + }) |
| 37 | + } |
| 38 | + |
| 39 | + if (!ENDPOINT || !KEY || !DEPLOYMENT_ID) { |
| 40 | + return new Response( |
| 41 | + JSON.stringify({ message: "Azure resources not found" }), |
| 42 | + { |
| 43 | + status: 400 |
| 44 | + } |
| 45 | + ) |
| 46 | + } |
| 47 | + |
| 48 | + const azureOpenai = new OpenAI({ |
| 49 | + apiKey: KEY, |
| 50 | + baseURL: `${ENDPOINT}/openai/deployments/${DEPLOYMENT_ID}`, |
| 51 | + defaultQuery: { "api-version": "2023-07-01-preview" }, |
| 52 | + defaultHeaders: { "api-key": KEY } |
| 53 | + }) |
| 54 | + |
| 55 | + const response = await azureOpenai.chat.completions.create({ |
| 56 | + model: DEPLOYMENT_ID as ChatCompletionCreateParamsBase["model"], |
| 57 | + messages: messages as ChatCompletionCreateParamsBase["messages"], |
| 58 | + temperature: chatSettings.temperature, |
| 59 | + max_tokens: |
| 60 | + CHAT_SETTING_LIMITS[chatSettings.model].MAX_TOKEN_OUTPUT_LENGTH, |
| 61 | + stream: true |
| 62 | + }) |
| 63 | + |
| 64 | + const stream = OpenAIStream(response) |
| 65 | + |
| 66 | + return new StreamingTextResponse(stream) |
| 67 | + } catch (error: any) { |
| 68 | + const errorMessage = error.error?.message || "An unexpected error occurred" |
| 69 | + const errorCode = error.status || 500 |
| 70 | + return new Response(JSON.stringify({ message: errorMessage }), { |
| 71 | + status: errorCode |
| 72 | + }) |
| 73 | + } |
| 74 | +} |
0 commit comments