| 1 | import { OpenAI } from "openai/index"; |
| 2 | import { |
| 3 | ChatCompletionChunk, |
| 4 | ChatCompletionCreateParams, |
| 5 | ChatCompletionCreateParamsStreaming, |
| 6 | } from "openai/resources/index"; |
| 7 | import { z } from "zod"; |
| 8 | import { AzureConfigSchema } from "../types.js"; |
| 9 | import { customFetch } from "../util.js"; |
| 10 | import { OpenAIApi } from "./OpenAI.js"; |
| 11 | |
| 12 | export class AzureApi extends OpenAIApi { |
| 13 | constructor(private azureConfig: z.infer<typeof AzureConfigSchema>) { |
| 14 | super({ |
| 15 | ...azureConfig, |
| 16 | provider: "openai", |
| 17 | }); |
| 18 | |
| 19 | const { baseURL, defaultQuery } = this._getAzureBaseURL(azureConfig); |
| 20 | |
| 21 | this.openai = new OpenAI({ |
| 22 | apiKey: azureConfig.apiKey, |
| 23 | baseURL, |
| 24 | fetch: customFetch(azureConfig.requestOptions), |
| 25 | defaultQuery, |
| 26 | }); |
| 27 | } |
| 28 | |
| 29 | /** |
| 30 | * Default is `azure-openai`, but previously was `azure` |
| 31 | * @param apiType |
| 32 | * @returns |
| 33 | */ |
| 34 | private _isAzureOpenAI(apiType?: string): boolean { |
| 35 | return apiType === "azure-openai" || apiType === "azure"; |
| 36 | } |
| 37 | |
| 38 | private _getAzureBaseURL(config: z.infer<typeof AzureConfigSchema>): { |
| 39 | baseURL: string; |
| 40 | defaultQuery: Record<string, string>; |
| 41 | } { |
| 42 | const url = new URL(this.apiBase); |
| 43 | |
| 44 | // Copy search params to separate object for OpenAI |
| 45 | const queryParams: Record<string, string> = {}; |
| 46 | for (const [key, value] of url.searchParams.entries()) { |
| 47 | queryParams[key] = value; |
| 48 | } |
| 49 | |
| 50 | url.pathname = url.pathname.replace(/\/$/, ""); // Remove trailing slash if present |
| 51 | url.search = ""; // Clear original search params |
| 52 | |
| 53 | // Default is `azure-openai` in docs, but previously was `azure` |
| 54 | if (this._isAzureOpenAI(config.env?.apiType)) { |
| 55 | if (!config.env?.deployment) { |
| 56 | throw new Error( |
| 57 | "`env.deployment` is a required configuration property for Azure OpenAI", |
| 58 | ); |
| 59 | } |
| 60 | |
| 61 | if (!config.env?.apiVersion) { |
| 62 | throw new Error( |
| 63 | "`env.apiVersion` is a required configuration property for Azure OpenAI", |
| 64 | ); |
| 65 | } |
| 66 | |
| 67 | const basePathname = `openai/deployments/${config.env.deployment}`; |
| 68 | |
| 69 | url.pathname = |
| 70 | url.pathname === "/" ? basePathname : `${url.pathname}/${basePathname}`; |
| 71 | |
| 72 | queryParams["api-version"] = config.env.apiVersion; |
| 73 | } |
| 74 | |
| 75 | return { |
| 76 | baseURL: url.toString(), |
| 77 | defaultQuery: queryParams, |
| 78 | }; |
| 79 | } |
| 80 | |
| 81 | /** |
| 82 | * Filters out empty text content parts from messages. |
| 83 | * |
| 84 | * Azure models may not support empty content parts, which can cause issues. |
| 85 | * This function removes any text content parts that are empty or contain only whitespace. |
| 86 | */ |
| 87 | private _filterEmptyContentParts<T extends ChatCompletionCreateParams>( |
| 88 | body: T, |
| 89 | ): T { |
| 90 | const result = { ...body }; |
| 91 | |
| 92 | result.messages = result.messages.map((message: any) => { |
| 93 | if (Array.isArray(message.content)) { |
| 94 | const filteredContent = message.content.filter((part: any) => { |
| 95 | return !( |
| 96 | part.type === "text" && |
| 97 | (!part.text || part.text.trim() === "") |
| 98 | ); |
| 99 | }); |
| 100 | return { |
| 101 | ...message, |
| 102 | content: |
| 103 | filteredContent.length > 0 ? filteredContent : message.content, |
| 104 | }; |
| 105 | } |
| 106 | return message; |
| 107 | }) as any; |
| 108 | |
| 109 | return result; |
| 110 | } |
| 111 | |
| 112 | modifyChatBody<T extends ChatCompletionCreateParams>(body: T): T { |
| 113 | let modifiedBody = super.modifyChatBody(body); |
| 114 | modifiedBody = this._filterEmptyContentParts(modifiedBody); |
| 115 | return modifiedBody; |
| 116 | } |
| 117 | |
| 118 | async *chatCompletionStream( |
| 119 | body: ChatCompletionCreateParamsStreaming, |
| 120 | signal: AbortSignal, |
| 121 | ): AsyncGenerator<ChatCompletionChunk, any, unknown> { |
| 122 | const response = await this.openai.chat.completions.create( |
| 123 | this.modifyChatBody(body), |
| 124 | { signal }, |
| 125 | ); |
| 126 | |
| 127 | for await (const result of response) { |
| 128 | // Skip chunks with no choices (common with Azure content filtering) |
| 129 | if (result.choices && result.choices.length > 0) { |
| 130 | yield result; |
| 131 | } |
| 132 | } |
| 133 | } |
| 134 | } |