diff --git a/.github/workflows/pr_checks.yaml b/.github/workflows/pr_checks.yaml index 25a1b9a1e..919ae0fe7 100644 --- a/.github/workflows/pr_checks.yaml +++ b/.github/workflows/pr_checks.yaml @@ -435,6 +435,8 @@ jobs: MISTRAL_API_KEY: ${{ secrets.MISTRAL_API_KEY }} AZURE_OPENAI_API_KEY: ${{ secrets.AZURE_OPENAI_API_KEY }} AZURE_FOUNDRY_API_KEY: ${{ secrets.AZURE_FOUNDRY_API_KEY }} + AZURE_FOUNDRY_MISTRAL_SMALL_API_KEY: ${{ secrets.AZURE_FOUNDRY_MISTRAL_SMALL_API_KEY }} + AZURE_OPENAI_GPT41_API_KEY: ${{ secrets.AZURE_OPENAI_GPT41_API_KEY }} package-tests: runs-on: ubuntu-latest diff --git a/.gitignore b/.gitignore index d3ad46eaf..0e528088c 100644 --- a/.gitignore +++ b/.gitignore @@ -146,6 +146,7 @@ Icon? *.notes.md notes.md +*.notes.md manual-testing-sandbox/.idea/** manual-testing-sandbox/.continue/** diff --git a/core/package-lock.json b/core/package-lock.json index f6eabcae4..a499a0c0c 100644 --- a/core/package-lock.json +++ b/core/package-lock.json @@ -16,7 +16,7 @@ "@continuedev/config-yaml": "file:../packages/config-yaml", "@continuedev/fetch": "^1.0.13", "@continuedev/llm-info": "^1.0.8", - "@continuedev/openai-adapters": "^1.0.25", + "@continuedev/openai-adapters": "^1.0.32", "@modelcontextprotocol/sdk": "^1.12.0", "@mozilla/readability": "^0.5.0", "@octokit/rest": "^20.1.1", @@ -949,22 +949,6 @@ } } }, - "node_modules/@azure-rest/core-client": { - "version": "1.4.0", - "resolved": "https://registry.npmjs.org/@azure-rest/core-client/-/core-client-1.4.0.tgz", - "integrity": "sha512-ozTDPBVUDR5eOnMIwhggbnVmOrka4fXCs8n8mvUo4WLLc38kki6bAOByDoVZZPz/pZy2jMt2kwfpvy/UjALj6w==", - "dependencies": { - "@azure/abort-controller": "^2.0.0", - "@azure/core-auth": "^1.3.0", - "@azure/core-rest-pipeline": "^1.5.0", - "@azure/core-tracing": "^1.0.1", - "@azure/core-util": "^1.0.0", - "tslib": "^2.6.2" - }, - "engines": { - "node": ">=18.0.0" - } - }, "node_modules/@azure/abort-controller": { "version": "2.1.2", "resolved": "https://registry.npmjs.org/@azure/abort-controller/-/abort-controller-2.1.2.tgz", @@ -1062,17 +1046,6 @@ "node": ">=18.0.0" } }, - "node_modules/@azure/core-sse": { - "version": "2.1.3", - "resolved": "https://registry.npmjs.org/@azure/core-sse/-/core-sse-2.1.3.tgz", - "integrity": "sha512-KSSdIKy8kvWCpYr8Hzpu22j3wcXsVTYE0IlgmI1T/aHvBDsLgV91y90UTfVWnuiuApRLCCVC4gS09ApBGOmYQA==", - "dependencies": { - "tslib": "^2.6.2" - }, - "engines": { - "node": ">=18.0.0" - } - }, "node_modules/@azure/core-tracing": { "version": "1.2.0", "resolved": "https://registry.npmjs.org/@azure/core-tracing/-/core-tracing-1.2.0.tgz", @@ -1211,24 +1184,6 @@ "uuid": "dist/bin/uuid" } }, - "node_modules/@azure/openai": { - "version": "1.0.0-beta.13", - "resolved": "https://registry.npmjs.org/@azure/openai/-/openai-1.0.0-beta.13.tgz", - "integrity": "sha512-oHE5ScnPTXALmyEBgqokZlYVT7F76EfrKjMWF+YcFJdUxk9Adhvht2iL5v+QpmlAIMdkih1q8DkTs/tApDjBpw==", - "deprecated": "The Azure OpenAI client library for JavaScript beta has been retired. Please migrate to the stable OpenAI SDK for JavaScript using the migration guide: https://github.com/Azure/azure-sdk-for-js/blob/main/sdk/openai/openai/MIGRATION.md.", - "dependencies": { - "@azure-rest/core-client": "^1.1.7", - "@azure/core-auth": "^1.4.0", - "@azure/core-rest-pipeline": "^1.13.0", - "@azure/core-sse": "^2.0.0", - "@azure/core-util": "^1.4.0", - "@azure/logger": "^1.0.3", - "tslib": "^2.4.0" - }, - "engines": { - "node": ">=18.0.0" - } - }, "node_modules/@babel/code-frame": { "version": "7.26.2", "resolved": "https://registry.npmjs.org/@babel/code-frame/-/code-frame-7.26.2.tgz", @@ -2945,15 +2900,13 @@ "integrity": "sha512-/htL7p4li3zQSwn9bXkI23WRpZNklWTPzRSSG3Fd5gvYW8cizjhlf7OzeDdKxBfi1S0lpqMm0VwHlx3KjMKLpw==" }, "node_modules/@continuedev/openai-adapters": { - "version": "1.0.25", - "resolved": "https://registry.npmjs.org/@continuedev/openai-adapters/-/openai-adapters-1.0.25.tgz", - "integrity": "sha512-YG7bcAlUk3BnqIOZw+ClmxmZU6G3OaaZqbhfqgiCnJem5i7oDy0pkAVHjig4iRTQkpvDokKmBXCH9wmQNRbWNw==", - "license": "Apache-2.0", + "version": "1.0.32", + "resolved": "https://registry.npmjs.org/@continuedev/openai-adapters/-/openai-adapters-1.0.32.tgz", + "integrity": "sha512-teNzbpcsa7Y0eBk+dxlLDo0m43sWI5txTYMIk6ezyS0cZAKFJODDB0Gkp3aEHXbD8mDE7H5dDSlM23ohKCirAA==", "dependencies": { - "@azure/openai": "^1.0.0-beta.12", "@continuedev/config-types": "^1.0.5", "@continuedev/config-yaml": "^1.0.51", - "@continuedev/fetch": "^1.0.10", + "@continuedev/fetch": "^1.0.11", "dotenv": "^16.5.0", "json-schema": "^0.4.0", "node-fetch": "^3.3.2", diff --git a/core/package.json b/core/package.json index 370896a6f..84dc95350 100644 --- a/core/package.json +++ b/core/package.json @@ -53,7 +53,7 @@ "@continuedev/config-yaml": "file:../packages/config-yaml", "@continuedev/fetch": "^1.0.13", "@continuedev/llm-info": "^1.0.8", - "@continuedev/openai-adapters": "^1.0.25", + "@continuedev/openai-adapters": "^1.0.32", "@modelcontextprotocol/sdk": "^1.12.0", "@mozilla/readability": "^0.5.0", "@octokit/rest": "^20.1.1", diff --git a/extensions/vscode/package-lock.json b/extensions/vscode/package-lock.json index 349212a6a..8d4221fa2 100644 --- a/extensions/vscode/package-lock.json +++ b/extensions/vscode/package-lock.json @@ -109,7 +109,7 @@ "@continuedev/config-yaml": "file:../packages/config-yaml", "@continuedev/fetch": "^1.0.13", "@continuedev/llm-info": "^1.0.8", - "@continuedev/openai-adapters": "^1.0.25", + "@continuedev/openai-adapters": "^1.0.32", "@modelcontextprotocol/sdk": "^1.12.0", "@mozilla/readability": "^0.5.0", "@octokit/rest": "^20.1.1", diff --git a/gui/package-lock.json b/gui/package-lock.json index a9d589b98..a56200472 100644 --- a/gui/package-lock.json +++ b/gui/package-lock.json @@ -113,7 +113,7 @@ "@continuedev/config-yaml": "file:../packages/config-yaml", "@continuedev/fetch": "^1.0.13", "@continuedev/llm-info": "^1.0.8", - "@continuedev/openai-adapters": "^1.0.25", + "@continuedev/openai-adapters": "^1.0.32", "@modelcontextprotocol/sdk": "^1.12.0", "@mozilla/readability": "^0.5.0", "@octokit/rest": "^20.1.1", diff --git a/packages/openai-adapters/package-lock.json b/packages/openai-adapters/package-lock.json index 4eac677b3..1d88a8b5e 100644 --- a/packages/openai-adapters/package-lock.json +++ b/packages/openai-adapters/package-lock.json @@ -1,18 +1,17 @@ { "name": "@continuedev/openai-adapters", - "version": "1.0.22", + "version": "1.0.36", "lockfileVersion": 3, "requires": true, "packages": { "": { "name": "@continuedev/openai-adapters", - "version": "1.0.22", + "version": "1.0.36", "license": "Apache-2.0", "dependencies": { - "@azure/openai": "^1.0.0-beta.12", "@continuedev/config-types": "^1.0.5", "@continuedev/config-yaml": "^1.0.51", - "@continuedev/fetch": "^1.0.10", + "@continuedev/fetch": "^1.0.11", "dotenv": "^16.5.0", "json-schema": "^0.4.0", "node-fetch": "^3.3.2", @@ -43,126 +42,6 @@ "node": ">=6.0.0" } }, - "node_modules/@azure-rest/core-client": { - "version": "1.4.0", - "resolved": "https://registry.npmjs.org/@azure-rest/core-client/-/core-client-1.4.0.tgz", - "integrity": "sha512-ozTDPBVUDR5eOnMIwhggbnVmOrka4fXCs8n8mvUo4WLLc38kki6bAOByDoVZZPz/pZy2jMt2kwfpvy/UjALj6w==", - "dependencies": { - "@azure/abort-controller": "^2.0.0", - "@azure/core-auth": "^1.3.0", - "@azure/core-rest-pipeline": "^1.5.0", - "@azure/core-tracing": "^1.0.1", - "@azure/core-util": "^1.0.0", - "tslib": "^2.6.2" - }, - "engines": { - "node": ">=18.0.0" - } - }, - "node_modules/@azure/abort-controller": { - "version": "2.1.2", - "resolved": "https://registry.npmjs.org/@azure/abort-controller/-/abort-controller-2.1.2.tgz", - "integrity": "sha512-nBrLsEWm4J2u5LpAPjxADTlq3trDgVZZXHNKabeXZtpq3d3AbN/KGO82R87rdDz5/lYB024rtEf10/q0urNgsA==", - "dependencies": { - "tslib": "^2.6.2" - }, - "engines": { - "node": ">=18.0.0" - } - }, - "node_modules/@azure/core-auth": { - "version": "1.7.2", - "resolved": "https://registry.npmjs.org/@azure/core-auth/-/core-auth-1.7.2.tgz", - "integrity": "sha512-Igm/S3fDYmnMq1uKS38Ae1/m37B3zigdlZw+kocwEhh5GjyKjPrXKO2J6rzpC1wAxrNil/jX9BJRqBshyjnF3g==", - "dependencies": { - "@azure/abort-controller": "^2.0.0", - "@azure/core-util": "^1.1.0", - "tslib": "^2.6.2" - }, - "engines": { - "node": ">=18.0.0" - } - }, - "node_modules/@azure/core-rest-pipeline": { - "version": "1.16.2", - "resolved": "https://registry.npmjs.org/@azure/core-rest-pipeline/-/core-rest-pipeline-1.16.2.tgz", - "integrity": "sha512-Hnhm/PG9/SQ07JJyLDv3l9Qr8V3xgAe1hFoBYzt6LaalMxfL/ZqFaZf/bz5VN3pMcleCPwl8ivlS2Fjxq/iC8Q==", - "dependencies": { - "@azure/abort-controller": "^2.0.0", - "@azure/core-auth": "^1.4.0", - "@azure/core-tracing": "^1.0.1", - "@azure/core-util": "^1.9.0", - "@azure/logger": "^1.0.0", - "http-proxy-agent": "^7.0.0", - "https-proxy-agent": "^7.0.0", - "tslib": "^2.6.2" - }, - "engines": { - "node": ">=18.0.0" - } - }, - "node_modules/@azure/core-sse": { - "version": "2.1.2", - "resolved": "https://registry.npmjs.org/@azure/core-sse/-/core-sse-2.1.2.tgz", - "integrity": "sha512-yf+pFIu8yCzXu9RbH2+8kp9vITIKJLHgkLgFNA6hxiDHK3fxeP596cHUj4c8Cm8JlooaUnYdHmF84KCZt3jbmw==", - "dependencies": { - "tslib": "^2.6.2" - }, - "engines": { - "node": ">=18.0.0" - } - }, - "node_modules/@azure/core-tracing": { - "version": "1.1.2", - "resolved": "https://registry.npmjs.org/@azure/core-tracing/-/core-tracing-1.1.2.tgz", - "integrity": "sha512-dawW9ifvWAWmUm9/h+/UQ2jrdvjCJ7VJEuCJ6XVNudzcOwm53BFZH4Q845vjfgoUAM8ZxokvVNxNxAITc502YA==", - "dependencies": { - "tslib": "^2.6.2" - }, - "engines": { - "node": ">=18.0.0" - } - }, - "node_modules/@azure/core-util": { - "version": "1.9.1", - "resolved": "https://registry.npmjs.org/@azure/core-util/-/core-util-1.9.1.tgz", - "integrity": "sha512-OLsq0etbHO1MA7j6FouXFghuHrAFGk+5C1imcpQ2e+0oZhYF07WLA+NW2Vqs70R7d+zOAWiWM3tbE1sXcDN66g==", - "dependencies": { - "@azure/abort-controller": "^2.0.0", - "tslib": "^2.6.2" - }, - "engines": { - "node": ">=18.0.0" - } - }, - "node_modules/@azure/logger": { - "version": "1.1.3", - "resolved": "https://registry.npmjs.org/@azure/logger/-/logger-1.1.3.tgz", - "integrity": "sha512-J8/cIKNQB1Fc9fuYqBVnrppiUtW+5WWJPCj/tAokC5LdSTwkWWttN+jsRgw9BLYD7JDBx7PceiqOBxJJ1tQz3Q==", - "dependencies": { - "tslib": "^2.6.2" - }, - "engines": { - "node": ">=18.0.0" - } - }, - "node_modules/@azure/openai": { - "version": "1.0.0-beta.12", - "resolved": "https://registry.npmjs.org/@azure/openai/-/openai-1.0.0-beta.12.tgz", - "integrity": "sha512-qKblxr6oVa8GsyNzY+/Ub9VmEsPYKhBrUrPaNEQiM+qrxnBPVm9kaeqGFFb/U78Q2zOabmhF9ctYt3xBW0nWnQ==", - "dependencies": { - "@azure-rest/core-client": "^1.1.7", - "@azure/core-auth": "^1.4.0", - "@azure/core-rest-pipeline": "^1.13.0", - "@azure/core-sse": "^2.0.0", - "@azure/core-util": "^1.4.0", - "@azure/logger": "^1.0.3", - "tslib": "^2.4.0" - }, - "engines": { - "node": ">=18.0.0" - } - }, "node_modules/@babel/code-frame": { "version": "7.24.7", "resolved": "https://registry.npmjs.org/@babel/code-frame/-/code-frame-7.24.7.tgz", @@ -716,9 +595,9 @@ } }, "node_modules/@continuedev/fetch": { - "version": "1.0.10", - "resolved": "https://registry.npmjs.org/@continuedev/fetch/-/fetch-1.0.10.tgz", - "integrity": "sha512-RBUXtm/VDz+9Itgw+CxrHXwVXoHCAedGzPOgA7gS5HZ9lObaeCJgEfzmfbln1ocFsfqSFmn5X5wSE7DHgfxpVA==", + "version": "1.0.11", + "resolved": "https://registry.npmjs.org/@continuedev/fetch/-/fetch-1.0.11.tgz", + "integrity": "sha512-GRYqAdV3DhRxg463zeSzOdVIk/bhjuuxAxzX0fG35Kz6sHUsU2wr7SDY91zO2ataYUkjnbOa3q1xIpnRnOoRHA==", "dependencies": { "@continuedev/config-types": "^1.0.5", "follow-redirects": "^1.15.6", @@ -4271,11 +4150,6 @@ } } }, - "node_modules/tslib": { - "version": "2.6.3", - "resolved": "https://registry.npmjs.org/tslib/-/tslib-2.6.3.tgz", - "integrity": "sha512-xNvxJEOUiWPGhUuUdQgAJPKOOJfGnIyKySOc09XkKsgdUV/3E2zvwZYdejjmRgPCgcym1juLH3226yA7sEFJKQ==" - }, "node_modules/type-detect": { "version": "4.0.8", "resolved": "https://registry.npmjs.org/type-detect/-/type-detect-4.0.8.tgz", diff --git a/packages/openai-adapters/package.json b/packages/openai-adapters/package.json index ca4e60a12..08c1581b6 100644 --- a/packages/openai-adapters/package.json +++ b/packages/openai-adapters/package.json @@ -1,6 +1,6 @@ { "name": "@continuedev/openai-adapters", - "version": "1.0.26", + "version": "1.0.36", "description": "", "main": "dist/index.js", "types": "dist/index.d.ts", @@ -12,10 +12,9 @@ "author": "Nate Sesti and Ty Dunn", "license": "Apache-2.0", "dependencies": { - "@azure/openai": "^1.0.0-beta.12", "@continuedev/config-types": "^1.0.5", "@continuedev/config-yaml": "^1.0.51", - "@continuedev/fetch": "^1.0.10", + "@continuedev/fetch": "^1.0.11", "dotenv": "^16.5.0", "json-schema": "^0.4.0", "node-fetch": "^3.3.2", diff --git a/packages/openai-adapters/src/apis/Azure.ts b/packages/openai-adapters/src/apis/Azure.ts new file mode 100644 index 000000000..57f48c3e0 --- /dev/null +++ b/packages/openai-adapters/src/apis/Azure.ts @@ -0,0 +1,108 @@ +import { OpenAI } from "openai/index"; +import { + ChatCompletionChunk, + ChatCompletionCreateParams, + ChatCompletionCreateParamsStreaming, +} from "openai/resources/index"; +import { z } from "zod"; +import { AzureConfigSchema } from "../types.js"; +import { customFetch } from "../util.js"; +import { OpenAIApi } from "./OpenAI.js"; + +export class AzureApi extends OpenAIApi { + constructor(private azureConfig: z.infer) { + super({ + ...azureConfig, + provider: "openai", + }); + + this.openai = new OpenAI({ + apiKey: azureConfig.apiKey, + baseURL: this._getAzureBaseURL(azureConfig), + defaultQuery: azureConfig.env?.apiVersion + ? { "api-version": azureConfig.env.apiVersion } + : {}, + fetch: customFetch(azureConfig.requestOptions), + }); + } + + /** + * Default is `azure-openai`, but previously was `azure` + * @param apiType + * @returns + */ + private _isAzureOpenAI(apiType?: string): boolean { + return apiType === "azure-openai" || apiType === "azure"; + } + + private _getAzureBaseURL(config: z.infer): string { + const baseURL = new URL(this.apiBase).toString().replace(/\/$/, ""); + + // Default is `azure-openai` in docs, but previously was `azure` + if (this._isAzureOpenAI(config.env?.apiType)) { + if (!config.env?.deployment) { + throw new Error( + "Azure deployment is required if `apiType` is `azure-openai` or `azure`", + ); + } + + return `${baseURL}/openai/deployments/${config.env.deployment}`; + } + + return baseURL; + } + + /** + * Filters out empty text content parts from messages. + * + * Azure models may not support empty content parts, which can cause issues. + * This function removes any text content parts that are empty or contain only whitespace. + */ + private _filterEmptyContentParts( + body: T, + ): T { + const result = { ...body }; + + result.messages = result.messages.map((message: any) => { + if (Array.isArray(message.content)) { + const filteredContent = message.content.filter((part: any) => { + return !( + part.type === "text" && + (!part.text || part.text.trim() === "") + ); + }); + return { + ...message, + content: + filteredContent.length > 0 ? filteredContent : message.content, + }; + } + return message; + }) as any; + + return result; + } + + modifyChatBody(body: T): T { + let modifiedBody = super.modifyChatBody(body); + modifiedBody = this._filterEmptyContentParts(modifiedBody); + return modifiedBody; + } + + async *chatCompletionStream( + body: ChatCompletionCreateParamsStreaming, + signal: AbortSignal, + ): AsyncGenerator { + const response = await this.openai.chat.completions.create( + this.modifyChatBody(body), + { signal }, + ); + + for await (const result of response) { + // Skip chunks with no choices (common with Azure content filtering) + if (result.choices && result.choices.length > 0) { + yield result; + } + } + } +} diff --git a/packages/openai-adapters/src/apis/AzureOpenAI.ts b/packages/openai-adapters/src/apis/AzureOpenAI.ts deleted file mode 100644 index fc9fbdda8..000000000 --- a/packages/openai-adapters/src/apis/AzureOpenAI.ts +++ /dev/null @@ -1,274 +0,0 @@ -import { AzureKeyCredential, OpenAIClient } from "@azure/openai"; - -import dotenv from "dotenv"; -import { - Completion, - CompletionCreateParamsNonStreaming, - CompletionCreateParamsStreaming, -} from "openai/resources/completions.js"; -import { - ChatCompletion, - ChatCompletionChunk, - ChatCompletionCreateParamsNonStreaming, - ChatCompletionCreateParamsStreaming, - CreateEmbeddingResponse, - EmbeddingCreateParams, - Model, -} from "openai/resources/index.js"; -import { AzureConfig } from "../types.js"; -import { embedding } from "../util.js"; -import { - BaseLlmApi, - CreateRerankResponse, - FimCreateParamsStreaming, - RerankCreateParams, -} from "./base.js"; - -dotenv.config(); - -const HTTPS_PROXY = process.env.HTTPS_PROXY; -const HTTP_PROXY = process.env.HTTP_PROXY; - -const MS_TOKEN = 30; - -export class AzureOpenAIApi implements BaseLlmApi { - private client: OpenAIClient; - - constructor(private config: AzureConfig) { - let proxyOptions; - const PROXY = HTTPS_PROXY ?? HTTP_PROXY; - if (PROXY) { - const url = new URL(PROXY); - proxyOptions = { - host: (url.protocol ? url.protocol + "//" : "") + url.hostname, - port: Number(url.port || 80), - username: url.username, - password: url.password, - }; - } - - if (!config.apiBase || !config.apiKey) { - throw new Error("Azure OpenAI API requires apiBase and apiKey"); - } - - this.client = new OpenAIClient( - config.apiBase, - new AzureKeyCredential(config.apiKey), - { - proxyOptions, - }, - ); - } - - private _bodyToOptions( - body: - | ChatCompletionCreateParamsStreaming - | ChatCompletionCreateParamsNonStreaming, - signal: AbortSignal, - ) { - return { - maxTokens: body.max_tokens ?? undefined, - temperature: body.temperature ?? undefined, - topP: body.top_p ?? undefined, - frequencyPenalty: body.frequency_penalty ?? undefined, - presencePenalty: body.presence_penalty ?? undefined, - stop: - typeof body.stop === "string" ? [body.stop] : (body.stop ?? undefined), - abortSignal: signal, - }; - } - - async chatCompletionNonStream( - body: ChatCompletionCreateParamsNonStreaming, - signal: AbortSignal, - ): Promise { - const completion = await this.client.getChatCompletions( - body.model, - body.messages, - this._bodyToOptions(body, signal), - ); - return { - ...completion, - object: "chat.completion", - model: body.model, - created: completion.created.getTime(), - usage: completion.usage - ? { - total_tokens: completion.usage.totalTokens, - completion_tokens: completion.usage.completionTokens, - prompt_tokens: completion.usage.promptTokens, - } - : undefined, - choices: completion.choices.map((choice) => ({ - ...choice, - logprobs: null, - finish_reason: "stop", - message: { - role: "assistant", - content: choice.message?.content ?? null, - refusal: null, - }, - })), - }; - } - async *chatCompletionStream( - body: ChatCompletionCreateParamsStreaming, - signal: AbortSignal, - ): AsyncGenerator { - const events = await this.client.streamChatCompletions( - body.model, - body.messages, - this._bodyToOptions(body, signal), - ); - - const eventBuffer: ChatCompletionChunk[] = []; - let done = false; - let tokensOutput = 0; - const ms = MS_TOKEN; - (async () => { - for await (const event of events) { - eventBuffer.push({ - ...event, - object: "chat.completion.chunk", - model: body.model, - created: event.created.getTime(), - choices: event.choices.map((choice: any) => ({ - ...choice, - logprobs: undefined, - finish_reason: null, - delta: { - role: (choice.delta?.role as any) ?? "assistant", - content: choice.delta?.content ?? "", - }, - })), - usage: undefined, - }); - } - done = true; - })(); - - while (!done) { - if (eventBuffer.length > 0) { - const event = eventBuffer.shift()!; - yield event; - tokensOutput += event.choices[0]?.delta.content?.length ?? 0; - } else { - await new Promise((resolve) => setTimeout(resolve, 5)); - continue; - } - - if (tokensOutput < 100 && eventBuffer.length > 30) { - await new Promise((resolve) => setTimeout(resolve, ms / 3)); - } else if (eventBuffer.length < 12) { - await new Promise((resolve) => - setTimeout(resolve, ms + 20 * (12 - eventBuffer.length)), - ); - } else if (eventBuffer.length > 40) { - await new Promise((resolve) => setTimeout(resolve, ms / 2)); - } else { - // await new Promise((resolve) => setTimeout(resolve, Math.max(25, 50 - 2 * eventBuffer.length))); - await new Promise((resolve) => setTimeout(resolve, ms)); - } - } - - for (const event of eventBuffer) yield event; - } - async completionNonStream( - body: CompletionCreateParamsNonStreaming, - signal: AbortSignal, - ): Promise { - const { prompt, logprobs, ...restOfBody } = body; - const messages = [ - { - role: "user" as any, - content: prompt as any, - }, - ]; - const resp = await this.chatCompletionNonStream( - { - messages, - ...restOfBody, - }, - signal, - ); - return { - ...resp, - object: "text_completion", - choices: resp.choices.map((choice) => ({ - ...choice, - text: choice.message.content ?? "", - finish_reason: "stop", - logprobs: null, - })), - }; - } - async *completionStream( - body: CompletionCreateParamsStreaming, - signal: AbortSignal, - ): AsyncGenerator { - const { prompt, logprobs, ...restOfBody } = body; - const messages = [ - { - role: "user" as any, - content: prompt as any, - }, - ]; - for await (const event of this.chatCompletionStream( - { - messages, - ...restOfBody, - }, - signal, - )) { - yield { - ...event, - object: "text_completion", - usage: { - completion_tokens: event.usage?.completion_tokens ?? 0, - prompt_tokens: event.usage?.prompt_tokens ?? 0, - total_tokens: event.usage?.total_tokens ?? 0, - }, - choices: event.choices.map((choice) => ({ - ...choice, - text: choice.delta.content ?? "", - finish_reason: "stop", - logprobs: null, - })), - }; - } - } - fimStream( - body: FimCreateParamsStreaming, - ): AsyncGenerator { - throw new Error( - "Azure OpenAI does not support fill-in-the-middle (FIM) completions.", - ); - } - - async embed(body: EmbeddingCreateParams): Promise { - const input = typeof body.input === "string" ? [body.input] : body.input; - const response = await this.client.getEmbeddings(body.model, input as any, { - dimensions: body.dimensions, - model: body.model, - }); - - const output = embedding({ - data: response.data.map((item) => item.embedding), - model: body.model, - usage: { - prompt_tokens: response.usage.promptTokens, - total_tokens: response.usage.totalTokens, - }, - }); - - return output; - } - - async rerank(body: RerankCreateParams): Promise { - throw new Error("Azure OpenAI does not support reranking."); - } - - list(): Promise { - throw new Error("Method not implemented."); - } -} diff --git a/packages/openai-adapters/src/apis/OpenAI.ts b/packages/openai-adapters/src/apis/OpenAI.ts index 745b94186..81a4b1c73 100644 --- a/packages/openai-adapters/src/apis/OpenAI.ts +++ b/packages/openai-adapters/src/apis/OpenAI.ts @@ -33,7 +33,6 @@ export class OpenAIApi implements BaseLlmApi { fetch: customFetch(config.requestOptions), }); } - modifyChatBody(body: T): T { // o-series models - only apply for official OpenAI API const isOfficialOpenAIAPI = this.apiBase === "https://api.openai.com/v1/"; @@ -70,6 +69,7 @@ export class OpenAIApi implements BaseLlmApi { ); return response; } + async *chatCompletionStream( body: ChatCompletionCreateParamsStreaming, signal: AbortSignal, diff --git a/packages/openai-adapters/src/apis/WatsonX.ts b/packages/openai-adapters/src/apis/WatsonX.ts index 3962662d2..2f1e197fc 100644 --- a/packages/openai-adapters/src/apis/WatsonX.ts +++ b/packages/openai-adapters/src/apis/WatsonX.ts @@ -35,14 +35,6 @@ export class WatsonXApi implements BaseLlmApi { this.deploymentId = config.env.deploymentId; } - private async getHeaders(): Promise> { - const bearer = await this.getBearerToken(); - return { - "Content-Type": "application/json", - Authorization: `Bearer ${bearer.token}`, - }; - } - async getBearerToken(): Promise<{ token: string; expiration: number }> { if (this.apiBase?.includes("cloud.ibm.com")) { // watsonx SaaS @@ -64,48 +56,80 @@ export class WatsonXApi implements BaseLlmApi { }; } else { // watsonx Software - if (!this.config.apiKey?.includes(":")) { - // Using ZenApiKey auth - return { - token: this.config.apiKey ?? "", - expiration: -1, - }; - } else { - // Using username/password auth - const userPass = this.config.apiKey?.split(":"); - const wxToken = (await ( - await customFetch(this.config.requestOptions)( - `${this.apiBase}/icp4d-api/v1/authorize`, - { - method: "POST", - headers: { - "Content-Type": "application/json", - Accept: "application/json", - }, - body: JSON.stringify({ - username: userPass[0], - password: userPass[1], - }), + // if (this.config.env.bearerTokenRequired) { + // In certain WatsonX environments, ZenApiKey authentication is disabled, + // and it's necessary to call this endpoint with username+api_key to get a bearer token. + // See the docs: https://www.ibm.com/docs/en/watsonx/w-and-w/2.1.0?topic=keys-generating-bearer-token + // Ask @sestinj why the rest is commented out. + const base64Decoded = Buffer.from( + this.config.apiKey ?? "", + "base64", + ).toString(); + const [username, api_key] = base64Decoded.split(":"); + + const wxToken = (await ( + await customFetch(this.config.requestOptions)( + new URL("icp4d-api/v1/authorize", this.apiBase), + { + method: "POST", + headers: { + "Content-Type": "application/json", + Accept: "application/json", }, - ) - ).json()) as any; - const wxTokenExpiry = (await ( - await customFetch(this.config.requestOptions)( - `${this.apiBase}/usermgmt/v1/user/tokenExpiry`, - { - method: "GET", - headers: { - Accept: "application/json", - Authorization: `Bearer ${wxToken["token"]}`, - }, - }, - ) - ).json()) as any; - return { - token: wxToken["token"], - expiration: wxTokenExpiry["exp"], - }; - } + body: JSON.stringify({ + username: username?.trim(), + api_key: api_key?.trim(), + }), + }, + ) + ).json()) as any; + + return { + token: wxToken["access_token"] ?? wxToken["token"], + expiration: 0, + }; + // } else if (!this.config.apiKey?.includes(":")) { + // // Using ZenApiKey auth + // return { + // token: this.config.apiKey ?? "", + // expiration: -1, + // }; + // } else { + // // Using username/password auth + // const userPass = this.config.apiKey?.split(":"); + // const wxToken = (await ( + // await customFetch(this.config.requestOptions)( + // `${this.apiBase}/icp4d-api/v1/authorize`, + // { + // method: "POST", + // headers: { + // "Content-Type": "application/json", + // Accept: "application/json", + // }, + // body: JSON.stringify({ + // username: userPass[0], + // password: userPass[1], + // }), + // }, + // ) + // ).json()) as any; + // const wxTokenExpiry = (await ( + // await customFetch(this.config.requestOptions)( + // `${this.apiBase}/usermgmt/v1/user/tokenExpiry`, + // { + // method: "GET", + // headers: { + // Accept: "application/json", + // Authorization: `Bearer ${wxToken["token"]}`, + // }, + // }, + // ) + // ).json()) as any; + // return { + // token: wxToken["token"], + // expiration: wxTokenExpiry["exp"], + // }; + // } } } @@ -153,6 +177,17 @@ export class WatsonXApi implements BaseLlmApi { return payload; } + private async getHeaders(): Promise> { + const bearer = await this.getBearerToken(); + // const isZenApiKey = bearer.expiration === -1; + + return { + "Content-Type": "application/json", + // Authorization: `${isZenApiKey ? "ZenApiKey" : "Bearer"} ${bearer.token}`, + Authorization: `Bearer ${bearer.token}`, + }; + } + async chatCompletionNonStream( body: ChatCompletionCreateParamsNonStreaming, signal: AbortSignal, @@ -181,7 +216,11 @@ export class WatsonXApi implements BaseLlmApi { ): AsyncGenerator { const url = this.getEndpoint("chat"); const headers = await this.getHeaders(); - const stringifiedBody = JSON.stringify(this._convertBody(body)); + const stringifiedBody = JSON.stringify({ + time_limit: 8000, + ...this._convertBody(body), + stream: true, + }); const response = await customFetch(this.config.requestOptions)(url, { method: "POST", headers, diff --git a/packages/openai-adapters/src/index.ts b/packages/openai-adapters/src/index.ts index eea617cf7..9f0cf341c 100644 --- a/packages/openai-adapters/src/index.ts +++ b/packages/openai-adapters/src/index.ts @@ -1,7 +1,7 @@ import dotenv from "dotenv"; import { z } from "zod"; import { AnthropicApi } from "./apis/Anthropic.js"; -import { AzureOpenAIApi } from "./apis/AzureOpenAI.js"; +import { AzureApi } from "./apis/Azure.js"; import { CohereApi } from "./apis/Cohere.js"; import { DeepSeekApi } from "./apis/DeepSeek.js"; import { GeminiApi } from "./apis/Gemini.js"; @@ -32,7 +32,7 @@ export function constructLlmApi(config: LLMConfig): BaseLlmApi | undefined { case "openai": return new OpenAIApi(config); case "azure": - return new AzureOpenAIApi(config); + return new AzureApi(config); case "cohere": return new CohereApi(config); case "anthropic": diff --git a/packages/openai-adapters/src/test/main.test.ts b/packages/openai-adapters/src/test/main.test.ts index 3a5e6f979..c1e1ff29a 100644 --- a/packages/openai-adapters/src/test/main.test.ts +++ b/packages/openai-adapters/src/test/main.test.ts @@ -4,11 +4,16 @@ import { DEEPSEEK_API_BASE } from "../apis/DeepSeek.js"; import { INCEPTION_API_BASE } from "../apis/Inception.js"; import { OpenAIApi } from "../apis/OpenAI.js"; import { constructLlmApi } from "../index.js"; -import { getLlmApi, testChat, testCompletion, testEmbed } from "./util.js"; +import { getLlmApi, testChat, testEmbed } from "./util.js"; dotenv.config(); -function testConfig(config: ModelConfig) { +export interface TestConfigOptions { + skipTools: boolean; +} + +function testConfig(_config: ModelConfig & { options?: TestConfigOptions }) { + const { options, ...config } = _config; const model = config.model; const api = getLlmApi({ provider: config.provider as any, @@ -17,16 +22,12 @@ function testConfig(config: ModelConfig) { env: config.env, }); - if (false) { - testCompletion(api, model); - } - if ( ["chat", "summarize", "edit", "apply"].some((role) => config.roles?.includes(role as any), ) ) { - testChat(api, model); + testChat(api, model, options); } if (config.roles?.includes("embed")) { @@ -38,7 +39,7 @@ function testConfig(config: ModelConfig) { } } -const TESTS: Omit[] = [ +const TESTS: Omit[] = [ { provider: "openai", model: "gpt-4o", @@ -106,6 +107,26 @@ const TESTS: Omit[] = [ // apiKey: process.env.COHERE_API_KEY!, // roles: ["rerank"], // }, + { + provider: "azure", + model: "gpt-4.1", + apiBase: "https://continue-openai.openai.azure.com", + apiKey: process.env.AZURE_OPENAI_GPT41_API_KEY, + env: { + deployment: "gpt-4.1", + apiVersion: "2024-02-15-preview", + apiType: "azure-openai", + }, + roles: ["chat"], + }, + { + provider: "azure", + model: "mistral-small-2503", + apiBase: "https://nate-0276-resource.services.ai.azure.com/models", + apiKey: process.env.AZURE_FOUNDRY_MISTRAL_SMALL_API_KEY, + roles: ["chat"], + options: { skipTools: true }, + }, ]; TESTS.forEach((config) => { diff --git a/packages/openai-adapters/src/test/util.ts b/packages/openai-adapters/src/test/util.ts index ba4490f2a..03c3d7f4a 100644 --- a/packages/openai-adapters/src/test/util.ts +++ b/packages/openai-adapters/src/test/util.ts @@ -1,5 +1,6 @@ import { BaseLlmApi, constructLlmApi } from "../index.js"; import { LLMConfig } from "../types.js"; +import { TestConfigOptions } from "./main.test.js"; export function getLlmApi(config: LLMConfig) { const api = constructLlmApi(config); @@ -8,7 +9,6 @@ export function getLlmApi(config: LLMConfig) { } return api; } - export function testEmbed(api: BaseLlmApi, model: string) { test("should successfully embed", async () => { const response = await api.embed({ @@ -73,7 +73,11 @@ export function testFim(api: BaseLlmApi, model: string) { }); } -export function testChat(api: BaseLlmApi, model: string) { +export function testChat( + api: BaseLlmApi, + model: string, + options?: TestConfigOptions, +) { test("should successfully stream chat", async () => { const stream = api.chatCompletionStream( { @@ -155,7 +159,6 @@ export function testChat(api: BaseLlmApi, model: string) { let completion = ""; for await (const result of stream) { completion += result.choices[0].delta.content ?? ""; - expect(result.choices.length).toBeGreaterThan(0); } expect(completion.length).toBeGreaterThan(0); @@ -201,124 +204,125 @@ export function testChat(api: BaseLlmApi, model: string) { expect(completion?.startsWith("RESPONSE: ")).toBe(true); }); - test("Tool Call works", async () => { - let args = ""; - let isFirstChunk = true; - for await (const chunk of api.chatCompletionStream( - { - messages: [ - { - role: "user", - content: - "Hi, my name is Nate. Please call the say_hello function to respond to me.", - }, - ], - tools: [ - { - function: { - name: "say_hello", - description: "Say Hello", - parameters: { - type: "object", - properties: { - name: { - type: "string", - description: "The name of the person to greet", + if (options?.skipTools === false) { + test("Tool Call works", async () => { + let args = ""; + let isFirstChunk = true; + for await (const chunk of api.chatCompletionStream( + { + messages: [ + { + role: "user", + content: + "Hi, my name is Nate. Please call the say_hello function to respond to me.", + }, + ], + tools: [ + { + function: { + name: "say_hello", + description: "Say Hello", + parameters: { + type: "object", + properties: { + name: { + type: "string", + description: "The name of the person to greet", + }, }, }, }, + type: "function", }, + ], + tool_choice: { type: "function", + function: { + name: "say_hello", + }, }, - ], - tool_choice: { - type: "function", - function: { - name: "say_hello", - }, + stream: true, + model, }, - stream: true, - model, - }, - new AbortController().signal, - )) { - const toolCall = chunk.choices[0].delta.tool_calls?.[0]; - if (!toolCall) { - continue; + new AbortController().signal, + )) { + const toolCall = chunk.choices[0].delta.tool_calls?.[0]; + if (!toolCall) { + continue; + } + args += toolCall.function?.arguments ?? ""; + + expect(chunk.choices[0].delta.tool_calls).toHaveLength(1); + + if (isFirstChunk) { + isFirstChunk = false; + expect(toolCall.id).toBeDefined(); + expect(toolCall.function!.name).toBe("say_hello"); + } } - args += toolCall.function?.arguments ?? ""; - expect(chunk.choices[0].delta.tool_calls).toHaveLength(1); + const parsedArgs = JSON.parse(args); + expect(parsedArgs.name).toBe("Nate"); + }); - if (isFirstChunk) { - isFirstChunk = false; - expect(toolCall.id).toBeDefined(); - expect(toolCall.function!.name).toBe("say_hello"); - } - } - - const parsedArgs = JSON.parse(args); - expect(parsedArgs.name).toBe("Nate"); - }); - - test("Tool Call second message works", async () => { - let response = ""; - for await (const chunk of api.chatCompletionStream( - { - messages: [ - { - role: "user", - content: - "Hi, my name is Nate. Please call the say_hello function to respond to me, then respond to me again.", - }, - { - role: "assistant", - tool_calls: [ - { - function: { - arguments: '{"name":"Nate"}', - name: "say_hello", + test("Tool Call second message works", async () => { + let response = ""; + for await (const chunk of api.chatCompletionStream( + { + messages: [ + { + role: "user", + content: + "Hi, my name is Nate. Please call the say_hello function to respond to me, then respond to me again.", + }, + { + role: "assistant", + tool_calls: [ + { + function: { + arguments: '{"name":"Nate"}', + name: "say_hello", + }, + id: "tool_call_1", + type: "function", }, - id: "tool_call_1", - type: "function", - }, - ], - }, - { - role: "tool", - tool_call_id: "tool_call_1", - content: "Nate was greeted", - }, - ], - tools: [ - { - function: { - name: "say_hello", - description: "Say Hello", - parameters: { - type: "object", - properties: { - name: { - type: "string", - description: "The name of the person to greet", + ], + }, + { + role: "tool", + tool_call_id: "tool_call_1", + content: "Nate was greeted", + }, + ], + tools: [ + { + function: { + name: "say_hello", + description: "Say Hello", + parameters: { + type: "object", + properties: { + name: { + type: "string", + description: "The name of the person to greet", + }, }, }, }, + type: "function", }, - type: "function", - }, - ], - stream: true, - model, - }, - new AbortController().signal, - )) { - console.log(JSON.stringify(chunk, null, 2)); - response += chunk.choices[0].delta.content ?? ""; - } + ], + stream: true, + model, + }, + new AbortController().signal, + )) { + response += chunk.choices[0].delta.content ?? ""; + } - expect(response.length).toBeGreaterThan(0); - }); + expect(response.length).toBeGreaterThan(0); + }); + } } export function testCompletion(api: BaseLlmApi, model: string) { diff --git a/packages/openai-adapters/src/types.ts b/packages/openai-adapters/src/types.ts index fd7ad94db..2f26a4c80 100644 --- a/packages/openai-adapters/src/types.ts +++ b/packages/openai-adapters/src/types.ts @@ -84,6 +84,19 @@ export type CohereConfig = z.infer; export const AzureConfigSchema = OpenAIConfigSchema.extend({ provider: z.literal("azure"), + env: z + .object({ + apiVersion: z.string().optional(), + apiType: z + .union([ + z.literal("azure-foundry"), + z.literal("azure-openai"), + z.literal("azure"), // Legacy + ]) + .optional(), + deployment: z.string().optional(), + }) + .optional(), }); export type AzureConfig = z.infer; diff --git a/packages/openai-adapters/src/util.ts b/packages/openai-adapters/src/util.ts index 16681e8d4..3fd87e112 100644 --- a/packages/openai-adapters/src/util.ts +++ b/packages/openai-adapters/src/util.ts @@ -1,6 +1,5 @@ import { RequestOptions } from "@continuedev/config-types"; import { fetchwithRequestOptions } from "@continuedev/fetch"; -import fetch from "node-fetch"; import { ChatCompletionChunk, CompletionUsage, @@ -137,13 +136,7 @@ export function model(options: { id: string; owned_by?: string }): Model { }; } -export function maybeCustomFetch(requestOptions: RequestOptions | undefined) { - return requestOptions - ? (url: any, init: any) => - fetchwithRequestOptions(url, init, requestOptions) - : undefined; -} - export function customFetch(requestOptions: RequestOptions | undefined) { - return maybeCustomFetch(requestOptions) ?? fetch; + return (url: any, init: any) => + fetchwithRequestOptions(url, init, requestOptions); } diff --git a/packages/openai-adapters/tsconfig.json b/packages/openai-adapters/tsconfig.json index 63587b995..dad27ccc6 100644 --- a/packages/openai-adapters/tsconfig.json +++ b/packages/openai-adapters/tsconfig.json @@ -16,8 +16,8 @@ "noEmitOnError": false, "types": ["node", "jest"], "outDir": "dist", - "declaration": true - // "sourceMap": true + "declaration": true, + "sourceMap": true }, "include": ["src/**/*"] }