Elffuss BraidHub

kikocis/continue public

307109b747b3 · 3.7 KiBRawPermalink
1import { OpenAI } from "openai/index";
2import {
3 ChatCompletionChunk,
4 ChatCompletionCreateParams,
5 ChatCompletionCreateParamsStreaming,
6} from "openai/resources/index";
7import { z } from "zod";
8import { AzureConfigSchema } from "../types.js";
9import { customFetch } from "../util.js";
10import { OpenAIApi } from "./OpenAI.js";
11
12export 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 url.pathname = `${url.pathname}/openai/deployments/${config.env.deployment}`;
67
68 queryParams["api-version"] = config.env.apiVersion;
69 }
70
71 return {
72 baseURL: url.toString(),
73 defaultQuery: queryParams,
74 };
75 }
76
77 /**
78 * Filters out empty text content parts from messages.
79 *
80 * Azure models may not support empty content parts, which can cause issues.
81 * This function removes any text content parts that are empty or contain only whitespace.
82 */
83 private _filterEmptyContentParts<T extends ChatCompletionCreateParams>(
84 body: T,
85 ): T {
86 const result = { ...body };
87
88 result.messages = result.messages.map((message: any) => {
89 if (Array.isArray(message.content)) {
90 const filteredContent = message.content.filter((part: any) => {
91 return !(
92 part.type === "text" &&
93 (!part.text || part.text.trim() === "")
94 );
95 });
96 return {
97 ...message,
98 content:
99 filteredContent.length > 0 ? filteredContent : message.content,
100 };
101 }
102 return message;
103 }) as any;
104
105 return result;
106 }
107
108 modifyChatBody<T extends ChatCompletionCreateParams>(body: T): T {
109 let modifiedBody = super.modifyChatBody(body);
110 modifiedBody = this._filterEmptyContentParts(modifiedBody);
111 return modifiedBody;
112 }
113
114 async *chatCompletionStream(
115 body: ChatCompletionCreateParamsStreaming,
116 signal: AbortSignal,
117 ): AsyncGenerator<ChatCompletionChunk, any, unknown> {
118 const response = await this.openai.chat.completions.create(
119 this.modifyChatBody(body),
120 { signal },
121 );
122
123 for await (const result of response) {
124 // Skip chunks with no choices (common with Azure content filtering)
125 if (result.choices && result.choices.length > 0) {
126 yield result;
127 }
128 }
129 }
130}