OpenAI Adapters (#1859)

* embeddings support in openai-adapters

* rerank support in openai-adapters

* cohere embed/rerank

* continue-proxy reranker and embeddings providers

* test for openai-adapters

* embeddings provider and reranker for continue proxy
This commit is contained in:
Nate Sesti 2024-07-28 18:22:37 -07:00 • committed by GitHub
parent bfef33f63b
commit ff821ff159
No known key found for this signature in database
GPG key ID: B5690EEEBB952194
33 changed files with 4625 additions and 60 deletions

24
.vscode/launch.json vendored
View file

@ -68,7 +68,10 @@
"${workspaceFolder}/extensions/vscode/out/extension.js",
"/Users/natesesti/.continue/config.ts"
],
"preLaunchTask": "vscode-extension:build"
"preLaunchTask": "vscode-extension:build",
"env": {
"CONTROL_PLANE_ENV": "local"
}
},
// Has to be run after starting the server (separately or using the compound configuration)
{
@ -112,5 +115,24 @@
"console": "integratedTerminal",
"internalConsoleOptions": "neverOpen"
}
// {
// "name": "[openai-adapters] Jest Test Debugger, Current Open File",
// "type": "node",
// "request": "launch",
// "runtimeArgs": [
// "--inspect-brk",
// "${workspaceRoot}/packages/openai-adapters/node_modules/jest/bin/jest.js",
// "--runInBand",
// "--config",
// "${workspaceRoot}/packages/openai-adapters/jest.config.mjs",
// "${relativeFile}"
// ],
// "cwd": "${workspaceRoot}/packages/openai-adapters",
// "console": "integratedTerminal",
// "internalConsoleOptions": "neverOpen",
// "env": {
// "NODE_OPTIONS": "--experimental-vm-modules"
// }
// }
]
}

View file

@ -4,8 +4,10 @@ import {
IdeSettings,
SerializedContinueConfig,
} from "../..";
import { ContinueProxyReranker } from "../../context/rerankers/ContinueProxyReranker";
import { ControlPlaneClient } from "../../control-plane/client";
import { TeamAnalytics } from "../../control-plane/TeamAnalytics";
import ContinueProxyEmbeddingsProvider from "../../indexing/embeddings/ContinueProxyEmbeddingsProvider";
import ContinueProxy from "../../llm/llms/stubs/ContinueProxy";
import { Telemetry } from "../../util/posthog";
import { loadFullConfigNode } from "../load";
@ -65,5 +67,16 @@ export default async function doLoadConfig(
},
);
if (newConfig.embeddingsProvider?.providerName === "continue-proxy") {
(
newConfig.embeddingsProvider as ContinueProxyEmbeddingsProvider
).workOsAccessToken = workOsAccessToken;
}
if (newConfig.reranker?.name === "continue-proxy") {
(newConfig.reranker as ContinueProxyReranker).workOsAccessToken =
workOsAccessToken;
}
return newConfig;
}

View file

@ -0,0 +1,46 @@
import fetch from "node-fetch";
import { CONTROL_PLANE_URL } from "../../control-plane/client.js";
import { Chunk, Reranker } from "../../index.js";
export class ContinueProxyReranker implements Reranker {
name = "continue-proxy";
private _workOsAccessToken: string | undefined = undefined;
get workOsAccessToken(): string | undefined {
return this._workOsAccessToken;
}
set workOsAccessToken(value: string | undefined) {
if (this._workOsAccessToken !== value) {
this._workOsAccessToken = value;
this.params.apiKey = value!;
}
}
constructor(
private readonly params: {
apiKey: string;
model?: string;
},
) {}
async rerank(query: string, chunks: Chunk[]): Promise<number[]> {
const url = new URL("/model-proxy/v1/rerank", CONTROL_PLANE_URL);
const resp = await fetch(url, {
method: "POST",
headers: {
"Content-Type": "application/json",
Authorization: `Bearer ${this.params.apiKey}`,
},
body: JSON.stringify({
query,
documents: chunks.map((chunk) => chunk.content),
model: this.params.model,
}),
});
const data: any = await resp.json();
const results = data.data.sort((a: any, b: any) => a.index - b.index);
return results.map((result: any) => result.relevance_score);
}
}

View file

@ -1,14 +1,16 @@
import { RerankerName } from "../../index.js";
import { CohereReranker } from "./cohere.js";
import { ContinueProxyReranker } from "./ContinueProxyReranker.js";
import { FreeTrialReranker } from "./freeTrial.js";
import { LLMReranker } from "./llm.js";
import { HuggingFaceTEIReranker } from "./tei.js";
import { VoyageReranker } from "./voyage.js";
import {HuggingFaceTEIReranker} from "./tei.js"
export const AllRerankers: { [key in RerankerName]: any } = {
cohere: CohereReranker,
llm: LLMReranker,
voyage: VoyageReranker,
"free-trial": FreeTrialReranker,
"huggingface-tei": HuggingFaceTEIReranker
"huggingface-tei": HuggingFaceTEIReranker,
"continue-proxy": ContinueProxyReranker,
};

View file

@ -18,9 +18,10 @@ export interface ControlPlaneWorkspace {
export interface ControlPlaneModelDescription extends ModelDescription {}
// export const CONTROL_PLANE_URL = "http://localhost:3001";
export const CONTROL_PLANE_URL =
"https://control-plane-api-service-i3dqylpbqa-uc.a.run.app";
process.env.CONTROL_PLANE_ENV === "local"
? "http://localhost:3001"
: "https://control-plane-api-service-i3dqylpbqa-uc.a.run.app";
export class ControlPlaneClient {
private static URL = CONTROL_PLANE_URL;

8
core/index.d.ts vendored
View file

@ -739,7 +739,9 @@ export type EmbeddingsProviderName =
| "openai"
| "cohere"
| "free-trial"
| "gemini";
| "gemini"
| "continue-proxy"
| "deepinfra";
export interface EmbedOptions {
apiBase?: string;
@ -758,6 +760,7 @@ export interface EmbeddingsProviderDescription extends EmbedOptions {
export interface EmbeddingsProvider {
id: string;
providerName: EmbeddingsProviderName;
maxChunkSize: number;
embed(chunks: string[]): Promise<number[][]>;
}
@ -767,7 +770,8 @@ export type RerankerName =
| "voyage"
| "llm"
| "free-trial"
| "huggingface-tei";
| "huggingface-tei"
| "continue-proxy";
export interface RerankerDescription {
name: RerankerName;

View file

@ -1,6 +1,7 @@
import {
EmbedOptions,
EmbeddingsProvider,
EmbeddingsProviderName,
FetchFunction,
} from "../../index.js";
@ -17,6 +18,11 @@ abstract class BaseEmbeddingsProvider implements IBaseEmbeddingsProvider {
static maxBatchSize: IBaseEmbeddingsProvider["maxBatchSize"];
static defaultOptions: IBaseEmbeddingsProvider["defaultOptions"];
static providerName: EmbeddingsProviderName;
get providerName(): EmbeddingsProviderName {
return (this.constructor as typeof BaseEmbeddingsProvider).providerName;
}
options: IBaseEmbeddingsProvider["options"];
fetch: IBaseEmbeddingsProvider["fetch"];
id: IBaseEmbeddingsProvider["id"];
@ -38,6 +44,8 @@ abstract class BaseEmbeddingsProvider implements IBaseEmbeddingsProvider {
this.id = `${this.constructor.name}::${this.options.model}`;
}
}
defaultOptions?: EmbedOptions | undefined;
maxBatchSize?: number | undefined;
abstract embed(chunks: string[]): Promise<number[][]>;

View file

@ -1,11 +1,13 @@
import { Response } from "node-fetch";
import { EmbedOptions } from "../../index.js";
import { EmbeddingsProviderName, EmbedOptions } from "../../index.js";
import { withExponentialBackoff } from "../../util/withExponentialBackoff.js";
import BaseEmbeddingsProvider from "./BaseEmbeddingsProvider.js";
class CohereEmbeddingsProvider extends BaseEmbeddingsProvider {
static maxBatchSize = 96;
static providerName: EmbeddingsProviderName = "cohere";
static defaultOptions: Partial<EmbedOptions> | undefined = {
apiBase: "https://api.cohere.ai/v1/",
model: "embed-english-v3.0",

View file

@ -0,0 +1,25 @@
import { EmbeddingsProviderName, EmbedOptions } from "../..";
import { CONTROL_PLANE_URL } from "../../control-plane/client";
import OpenAIEmbeddingsProvider from "./OpenAIEmbeddingsProvider";
class ContinueProxyEmbeddingsProvider extends OpenAIEmbeddingsProvider {
static providerName: EmbeddingsProviderName = "continue-proxy";
static defaultOptions: Partial<EmbedOptions> | undefined = {
apiBase: new URL("/model-proxy/v1", CONTROL_PLANE_URL).toString(),
};
private _workOsAccessToken: string | undefined = undefined;
get workOsAccessToken(): string | undefined {
return this._workOsAccessToken;
}
set workOsAccessToken(value: string | undefined) {
if (this._workOsAccessToken !== value) {
this._workOsAccessToken = value;
this.options.apiKey = value;
}
}
}
export default ContinueProxyEmbeddingsProvider;

View file

@ -1,8 +1,9 @@
import { EmbedOptions } from "../../index.js";
import { EmbeddingsProviderName, EmbedOptions } from "../../index.js";
import { withExponentialBackoff } from "../../util/withExponentialBackoff.js";
import BaseEmbeddingsProvider from "./BaseEmbeddingsProvider.js";
class DeepInfraEmbeddingsProvider extends BaseEmbeddingsProvider {
static providerName: EmbeddingsProviderName = "deepinfra";
static defaultOptions: Partial<EmbedOptions> | undefined = {
model: "sentence-transformers/all-MiniLM-L6-v2",
};

View file

@ -1,11 +1,16 @@
import { Response } from "node-fetch";
import { getHeaders } from "../../continueServer/stubs/headers.js";
import { constants } from "../../deploy/constants.js";
import { EmbedOptions, FetchFunction } from "../../index.js";
import {
EmbeddingsProviderName,
EmbedOptions,
FetchFunction,
} from "../../index.js";
import { withExponentialBackoff } from "../../util/withExponentialBackoff.js";
import BaseEmbeddingsProvider from "./BaseEmbeddingsProvider.js";
class FreeTrialEmbeddingsProvider extends BaseEmbeddingsProvider {
static providerName: EmbeddingsProviderName = "free-trial";
static maxBatchSize = 128;
static defaultOptions: Partial<EmbedOptions> | undefined = {

View file

@ -1,17 +1,17 @@
import { Response } from "node-fetch";
import { withExponentialBackoff } from "../../util/withExponentialBackoff.js";
import BaseEmbeddingsProvider, {
IBaseEmbeddingsProvider,
} from "./BaseEmbeddingsProvider.js";
import {
EmbedContentRequest,
EmbedContentResponse,
} from "@google/generative-ai";
import { Response } from "node-fetch";
import { EmbeddingsProviderName } from "../../index.js";
import { withExponentialBackoff } from "../../util/withExponentialBackoff.js";
import BaseEmbeddingsProvider from "./BaseEmbeddingsProvider.js";
/**
* [View the Gemini Text Embedding docs.](https://ai.google.dev/gemini-api/docs/models/gemini#text-embedding-and-embedding)
*/
class GeminiEmbeddingsProvider extends BaseEmbeddingsProvider {
static providerName: EmbeddingsProviderName = "gemini";
static maxBatchSize = 2048;
static defaultOptions = {

View file

@ -1,10 +1,11 @@
import fetch, { Response } from "node-fetch";
import { EmbedOptions, FetchFunction } from "../..";
import { Response } from "node-fetch";
import { EmbeddingsProviderName, EmbedOptions, FetchFunction } from "../..";
import { withExponentialBackoff } from "../../util/withExponentialBackoff";
import BaseEmbeddingsProvider from "./BaseEmbeddingsProvider";
class HuggingFaceTEIEmbeddingsProvider extends BaseEmbeddingsProvider {
private maxBatchSize = 32;
static providerName: EmbeddingsProviderName = "huggingface-tei";
maxBatchSize = 32;
static defaultOptions: Partial<EmbedOptions> | undefined = {
apiBase: "http://localhost:8080",
@ -17,7 +18,7 @@ class HuggingFaceTEIEmbeddingsProvider extends BaseEmbeddingsProvider {
if (!this.options.apiBase?.endsWith("/")) {
this.options.apiBase += "/";
}
this.doInfoRequest().then(response => {
this.doInfoRequest().then((response) => {
this.options.model = response.model_id;
this.maxBatchSize = response.max_client_batch_size;
});
@ -26,7 +27,9 @@ class HuggingFaceTEIEmbeddingsProvider extends BaseEmbeddingsProvider {
async embed(chunks: string[]) {
const promises = [];
for (let i = 0; i < chunks.length; i += this.maxBatchSize) {
promises.push(this.doEmbedRequest(chunks.slice(i, i + this.maxBatchSize)));
promises.push(
this.doEmbedRequest(chunks.slice(i, i + this.maxBatchSize)),
);
}
const results = await Promise.all(promises);
return results.flat();
@ -37,11 +40,11 @@ class HuggingFaceTEIEmbeddingsProvider extends BaseEmbeddingsProvider {
this.fetch(new URL("embed", this.options.apiBase), {
method: "POST",
body: JSON.stringify({
inputs: batch
inputs: batch,
}),
headers: {
"Content-Type": "application/json",
}
},
}),
);
if (!resp.ok) {
@ -75,9 +78,9 @@ class TEIEmbedError extends Error {
}
type TEIEmbedErrorResponse = {
error: string
error_type: string
}
error: string;
error_type: string;
};
type TEIInfoResponse = {
model_id: string;
@ -86,7 +89,7 @@ type TEIInfoResponse = {
model_type: {
embedding: {
pooling: string;
}
};
};
max_concurrent_requests: number;
max_input_length: number;

View file

@ -1,4 +1,8 @@
import { EmbedOptions, FetchFunction } from "../../index.js";
import {
EmbeddingsProviderName,
EmbedOptions,
FetchFunction,
} from "../../index.js";
import { withExponentialBackoff } from "../../util/withExponentialBackoff.js";
import BaseEmbeddingsProvider, {
IBaseEmbeddingsProvider,
@ -41,6 +45,7 @@ async function embedOne(
}
class OllamaEmbeddingsProvider extends BaseEmbeddingsProvider {
static providerName: EmbeddingsProviderName = "ollama";
static defaultOptions: IBaseEmbeddingsProvider["defaultOptions"] = {
apiBase: "http://localhost:11434/",
model: "nomic-embed-text",

View file

@ -1,9 +1,10 @@
import { Response } from "node-fetch";
import { EmbedOptions } from "../../index.js";
import { EmbeddingsProviderName, EmbedOptions } from "../../index.js";
import { withExponentialBackoff } from "../../util/withExponentialBackoff.js";
import BaseEmbeddingsProvider from "./BaseEmbeddingsProvider.js";
class OpenAIEmbeddingsProvider extends BaseEmbeddingsProvider {
static providerName: EmbeddingsProviderName = "openai";
// https://platform.openai.com/docs/api-reference/embeddings/create is 2048
// but Voyage is 128
static maxBatchSize = 128;

View file

@ -1,4 +1,5 @@
import path from "path";
import { EmbeddingsProviderName } from "../../index.js";
// @ts-ignore
// prettier-ignore
import { type PipelineType } from "../../vendor/modules/@xenova/transformers/src/transformers.js";
@ -37,6 +38,7 @@ class EmbeddingsPipeline {
}
export class TransformersJsEmbeddingsProvider extends BaseEmbeddingsProvider {
static providerName: EmbeddingsProviderName = "transformers.js";
static maxGroupSize: number = 4;
static model: string = "all-MiniLM-L6-v2";

View file

@ -1,12 +1,14 @@
import { EmbeddingsProviderName } from "../../index.js";
import BaseEmbeddingsProvider from "./BaseEmbeddingsProvider.js";
import CohereEmbeddingsProvider from "./CohereEmbeddingsProvider.js";
import ContinueProxyEmbeddingsProvider from "./ContinueProxyEmbeddingsProvider.js";
import DeepInfraEmbeddingsProvider from "./DeepInfraEmbeddingsProvider.js";
import FreeTrialEmbeddingsProvider from "./FreeTrialEmbeddingsProvider.js";
import GeminiEmbeddingsProvider from "./GeminiEmbeddingsProvider.js";
import HuggingFaceTEIEmbeddingsProvider from "./HuggingFaceTEIEmbeddingsProvider.js";
import OllamaEmbeddingsProvider from "./OllamaEmbeddingsProvider.js";
import OpenAIEmbeddingsProvider from "./OpenAIEmbeddingsProvider.js";
import TransformersJsEmbeddingsProvider from "./TransformersJsEmbeddingsProvider.js";
import GeminiEmbeddingsProvider from "./GeminiEmbeddingsProvider.js";
type EmbeddingsProviderConstructor = new (
...args: any[]
@ -26,4 +28,6 @@ export const allEmbeddingsProviders: Record<
// eslint-disable-next-line @typescript-eslint/naming-convention
"huggingface-tei": HuggingFaceTEIEmbeddingsProvider,
gemini: GeminiEmbeddingsProvider,
"continue-proxy": ContinueProxyEmbeddingsProvider,
deepinfra: DeepInfraEmbeddingsProvider,
};

View file

@ -18,8 +18,10 @@ import { PromiseAdapter, promiseFromEvent } from "./promiseUtils";
export const AUTH_TYPE = "continue";
const AUTH_NAME = "Continue";
const CLIENT_ID = "client_01J0FW6XN8N2XJAECF7NE0Y65J"; // Production
// const CLIENT_ID = "client_01J0FW6XCPMJMQ3CG51RB4HBZQ"; // Staging
const CLIENT_ID =
process.env.CONTROL_PLANE_ENV === "local"
? "client_01J0FW6XCPMJMQ3CG51RB4HBZQ"
: "client_01J0FW6XN8N2XJAECF7NE0Y65J";
const SESSIONS_SECRET_KEY = `${AUTH_TYPE}.sessions`;
class UriEventHandler extends EventEmitter<Uri> implements UriHandler {

View file

@ -1,6 +1,6 @@
{
"name": "@continuedev/config-types",
"version": "1.0.10",
"version": "1.0.11",
"description": "",
"main": "dist/index.js",
"types": "dist/index.d.ts",

View file

@ -1,12 +1,12 @@
{
"name": "@continuedev/fetch",
"version": "1.0.0",
"version": "1.0.2",
"lockfileVersion": 3,
"requires": true,
"packages": {
"": {
"name": "@continuedev/fetch",
"version": "1.0.0",
"version": "1.0.2",
"license": "Apache-2.0",
"dependencies": {
"@continuedev/config-types": "^1.0.5",

View file

@ -1,6 +1,6 @@
{
"name": "@continuedev/fetch",
"version": "1.0.2",
"version": "1.0.3",
"description": "",
"main": "dist/index.js",
"types": "dist/index.d.ts",

View file

@ -1,8 +1,16 @@
export {
import {
streamJSON,
streamResponse,
streamSse,
toAsyncIterable,
} from "./stream.js";
export { fetchwithRequestOptions } from "./fetch.js";
import { fetchwithRequestOptions } from "./fetch.js";
export {
fetchwithRequestOptions,
streamJSON,
streamResponse,
streamSse,
toAsyncIterable,
};

View file

@ -0,0 +1,2 @@
.env
test

View file

@ -0,0 +1,22 @@
import path from "path";
import { fileURLToPath } from "url";
process.env.NODE_OPTIONS = "--experimental-vm-modules";
export default {
transform: {
"\\.[jt]sx?$": ["ts-jest", { useESM: true }],
},
moduleNameMapper: {
"(.+)\\.js": "$1",
},
extensionsToTreatAsEsm: [".ts"],
preset: "ts-jest/presets/default-esm",
testTimeout: 10000,
testEnvironment: "node",
globals: {
__dirname: path.dirname(fileURLToPath(import.meta.url)),
__filename: path.resolve(fileURLToPath(import.meta.url)),
},
};

File diff suppressed because it is too large Load diff

View file

@ -1,12 +1,12 @@
{
"name": "@continuedev/openai-adapters",
"version": "1.0.5",
"version": "1.0.7",
"description": "",
"main": "dist/index.js",
"types": "dist/index.d.ts",
"type": "module",
"scripts": {
"test": "echo \"Error: no test specified\" && exit 1",
"test": "NODE_OPTIONS=\"$NODE_OPTIONS --experimental-vm-modules\" npx jest",
"build": "tsc"
},
"author": "Nate Sesti and Ty Dunn",
@ -19,6 +19,8 @@
"openai": "^4.52.5"
},
"devDependencies": {
"@types/follow-redirects": "^1.14.4"
"@types/follow-redirects": "^1.14.4",
"ts-jest": "^29.2.3",
"ts-node": "^10.9.2"
}
}

View file

@ -1,6 +1,5 @@
import { AzureKeyCredential, OpenAIClient } from "@azure/openai";
import { ModelDescription } from "@continuedev/config-types/src/index.js";
import dotenv from "dotenv";
import {
Completion,
@ -12,8 +11,16 @@ import {
ChatCompletionChunk,
ChatCompletionCreateParamsNonStreaming,
ChatCompletionCreateParamsStreaming,
CreateEmbeddingResponse,
EmbeddingCreateParams,
} from "openai/resources/index.js";
import { BaseLlmApi, FimCreateParamsStreaming } from "./base.js";
import { LlmApiConfig } from "../index.js";
import {
BaseLlmApi,
CreateRerankResponse,
FimCreateParamsStreaming,
RerankCreateParams,
} from "./base.js";
dotenv.config();
@ -24,9 +31,9 @@ const MS_TOKEN = 30;
export class AzureOpenAIApi implements BaseLlmApi {
private client: OpenAIClient;
private config: ModelDescription;
private config: LlmApiConfig;
constructor(config: ModelDescription) {
constructor(config: LlmApiConfig) {
this.config = config;
let proxyOptions;
const PROXY = HTTPS_PROXY ?? HTTP_PROXY;
@ -71,14 +78,14 @@ export class AzureOpenAIApi implements BaseLlmApi {
body: ChatCompletionCreateParamsNonStreaming,
): Promise<ChatCompletion> {
const completion = await this.client.getChatCompletions(
this.config.model,
body.model,
body.messages,
this._bodyToOptions(body),
);
return {
...completion,
object: "chat.completion",
model: this.config.model,
model: body.model,
created: completion.created.getTime(),
usage: completion.usage
? {
@ -102,7 +109,7 @@ export class AzureOpenAIApi implements BaseLlmApi {
body: ChatCompletionCreateParamsStreaming,
): AsyncGenerator<ChatCompletionChunk> {
const events = await this.client.streamChatCompletions(
this.config.model,
body.model,
body.messages,
this._bodyToOptions(body),
);
@ -116,7 +123,7 @@ export class AzureOpenAIApi implements BaseLlmApi {
eventBuffer.push({
...event,
object: "chat.completion.chunk",
model: this.config.model,
model: body.model,
created: event.created.getTime(),
choices: event.choices.map((choice: any) => ({
...choice,
@ -217,4 +224,31 @@ export class AzureOpenAIApi implements BaseLlmApi {
"Azure OpenAI does not support fill-in-the-middle (FIM) completions.",
);
}
async embed(body: EmbeddingCreateParams): Promise<CreateEmbeddingResponse> {
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 = {
data: response.data.map((item) => ({
...item,
object: "embedding" as const,
})),
model: body.model,
object: "list" as const,
usage: {
prompt_tokens: response.usage.promptTokens,
total_tokens: response.usage.totalTokens,
},
};
return output;
}
async rerank(body: RerankCreateParams): Promise<CreateRerankResponse> {
throw new Error("Azure OpenAI does not support reranking.");
}
}

View file

@ -0,0 +1,116 @@
import fetch from "node-fetch";
import {
CreateEmbeddingResponse,
EmbeddingCreateParams,
} from "openai/resources/embeddings.mjs";
import {
ChatCompletion,
ChatCompletionChunk,
ChatCompletionCreateParamsNonStreaming,
ChatCompletionCreateParamsStreaming,
Completion,
CompletionCreateParamsNonStreaming,
CompletionCreateParamsStreaming,
} from "openai/resources/index.mjs";
import { LlmApiConfig } from "../index.js";
import {
BaseLlmApi,
CreateRerankResponse,
FimCreateParamsStreaming,
RerankCreateParams,
} from "./base.js";
// Cohere is OpenAI-compatible
export class CohereApi implements BaseLlmApi {
apiBase: string = "https://api.cohere.com/v1";
constructor(protected config: LlmApiConfig) {
this.apiBase = config.apiBase ?? this.apiBase;
if (!this.apiBase.endsWith("/")) {
this.apiBase += "/";
}
}
chatCompletionNonStream(
body: ChatCompletionCreateParamsNonStreaming,
): Promise<ChatCompletion> {
throw new Error("Method not implemented.");
}
chatCompletionStream(
body: ChatCompletionCreateParamsStreaming,
): AsyncGenerator<ChatCompletionChunk> {
throw new Error("Method not implemented.");
}
completionNonStream(
body: CompletionCreateParamsNonStreaming,
): Promise<Completion> {
throw new Error("Method not implemented.");
}
completionStream(
body: CompletionCreateParamsStreaming,
): AsyncGenerator<Completion> {
throw new Error("Method not implemented.");
}
fimStream(
body: FimCreateParamsStreaming,
): AsyncGenerator<ChatCompletionChunk> {
throw new Error("Method not implemented.");
}
async rerank(body: RerankCreateParams): Promise<CreateRerankResponse> {
const endpoint = new URL("rerank", this.apiBase);
const response = await fetch(endpoint, {
method: "POST",
body: JSON.stringify(body),
headers: {
"Content-Type": "application/json",
Accept: "application/json",
"x-api-key": this.config.apiKey ?? "",
Authorization: `Bearer ${this.config.apiKey}`,
},
});
const data = (await response.json()) as any;
return {
object: "list",
data: data.results.map((result: any) => ({
index: result.index,
relevance_score: result.relevance_score,
})),
model: body.model,
usage: {
total_tokens: 0,
},
};
}
async embed(body: EmbeddingCreateParams): Promise<CreateEmbeddingResponse> {
const url = new URL("/embed", this.apiBase);
const texts = typeof body.input === "string" ? [body.input] : body.input;
const response = await fetch(url, {
method: "POST",
headers: {
"Content-Type": "application/json",
Authorization: `Bearer ${this.config.apiKey}`,
},
body: JSON.stringify({
texts,
model: body.model,
input_type: "search_document",
}),
});
const data = (await response.json()) as any;
return {
object: "list",
model: body.model,
usage: {
total_tokens: 0,
prompt_tokens: 0,
},
data: data.embeddings.map((embedding: any, index: number) => ({
object: "embedding",
index,
embedding,
})),
};
}
}

View file

@ -1,4 +1,3 @@
import { ModelDescription } from "@continuedev/config-types";
import { streamSse } from "@continuedev/fetch";
import fetch from "node-fetch";
import { OpenAI } from "openai/index.mjs";
@ -11,14 +10,26 @@ import {
CompletionCreateParamsNonStreaming,
CompletionCreateParamsStreaming,
} from "openai/resources/index.mjs";
import { BaseLlmApi, FimCreateParamsStreaming } from "./base.js";
import { LlmApiConfig } from "../index.js";
import {
BaseLlmApi,
CreateRerankResponse,
FimCreateParamsStreaming,
RerankCreateParams,
} from "./base.js";
export class OpenAIApi implements BaseLlmApi {
openai: OpenAI;
constructor(protected config: ModelDescription) {
apiBase: string = "https://api.openai.com/v1/";
constructor(protected config: LlmApiConfig) {
this.apiBase = config.apiBase ?? this.apiBase;
if (!this.apiBase.endsWith("/")) {
this.apiBase += "/";
}
this.openai = new OpenAI({
apiKey: config.apiKey,
baseURL: config.apiBase,
baseURL: this.apiBase,
});
}
@ -53,7 +64,7 @@ export class OpenAIApi implements BaseLlmApi {
async *fimStream(
body: FimCreateParamsStreaming,
): AsyncGenerator<ChatCompletionChunk, any, unknown> {
const endpoint = new URL("fim/completions", this.config.apiBase);
const endpoint = new URL("fim/completions", this.apiBase);
const resp = await fetch(endpoint, {
method: "POST",
body: JSON.stringify({
@ -81,4 +92,27 @@ export class OpenAIApi implements BaseLlmApi {
}
}
}
async embed(
body: OpenAI.Embeddings.EmbeddingCreateParams,
): Promise<OpenAI.Embeddings.CreateEmbeddingResponse> {
const response = await this.openai.embeddings.create(body);
return response;
}
async rerank(body: RerankCreateParams): Promise<CreateRerankResponse> {
const endpoint = new URL("rerank", this.apiBase);
const response = await fetch(endpoint, {
method: "POST",
body: JSON.stringify(body),
headers: {
"Content-Type": "application/json",
Accept: "application/json",
"x-api-key": this.config.apiKey ?? "",
Authorization: `Bearer ${this.config.apiKey}`,
},
});
const data = await response.json();
return data as any;
}
}

View file

@ -6,6 +6,8 @@ import {
Completion,
CompletionCreateParamsNonStreaming,
CompletionCreateParamsStreaming,
CreateEmbeddingResponse,
EmbeddingCreateParams,
} from "openai/resources/index.mjs";
export interface FimCreateParamsStreaming
@ -13,6 +15,27 @@ export interface FimCreateParamsStreaming
suffix: string;
}
export interface RerankCreateParams {
query: string;
documents: string[];
model: string;
top_k?: number;
}
export interface CreateRerankItem {
relevance_score: number;
index: number;
}
export interface CreateRerankResponse {
object: "list";
data: CreateRerankItem[];
model: string;
usage: {
total_tokens: number;
};
}
export interface BaseLlmApi {
// Chat, no stream
chatCompletionNonStream(
@ -38,4 +61,10 @@ export interface BaseLlmApi {
fimStream(
body: FimCreateParamsStreaming,
): AsyncGenerator<ChatCompletionChunk>;
// Embeddings
embed(body: EmbeddingCreateParams): Promise<CreateEmbeddingResponse>;
// Reranking
rerank(body: RerankCreateParams): Promise<CreateRerankResponse>;
}

View file

@ -1,12 +1,19 @@
import { ModelDescription } from "@continuedev/config-types/src/index.js";
import dotenv from "dotenv";
import { AzureOpenAIApi } from "./apis/AzureOpenAI.js";
import { OpenAIApi } from "./apis/OpenAI.js";
import { BaseLlmApi } from "./apis/base.js";
import { CohereApi } from "./apis/Cohere.js";
import { OpenAIApi } from "./apis/OpenAI.js";
dotenv.config();
export function constructLlmApi(config: ModelDescription): BaseLlmApi {
export interface LlmApiConfig {
provider: string;
model: string;
apiKey: string;
apiBase?: string;
}
export function constructLlmApi(config: LlmApiConfig): BaseLlmApi {
switch (config.provider) {
case "openai":
return new OpenAIApi(config);
@ -17,6 +24,15 @@ export function constructLlmApi(config: ModelDescription): BaseLlmApi {
});
case "azure":
return new AzureOpenAIApi(config);
case "voyage":
return new OpenAIApi({
...config,
apiBase: "https://api.voyageai.com/v1/",
});
case "cohere":
return new CohereApi({
...config,
});
default:
throw new Error(`Unsupported LLM API format: ${config.provider}`);
}

View file

@ -0,0 +1,206 @@
import * as dotenv from "dotenv";
import { constructLlmApi, LlmApiConfig } from "../src/index.js";
dotenv.config();
function testEmbed(config: LlmApiConfig) {
test("should successfully embed", async () => {
const api = constructLlmApi(config);
const response = await api.embed({
model: config.model,
input: ["This is a test", "Hello world!"],
});
expect(response.model).toBe(config.model);
expect(response.object).toBe("list");
expect(response.data.length).toEqual(2);
response.data.forEach((val, index) => {
expect(val.index).toBe(index);
expect(val.object).toBe("embedding");
expect(val.embedding.some((v) => typeof v !== "number")).toBe(false);
});
});
}
function testRerank(config: LlmApiConfig) {
test("should successfully rerank", async () => {
const api = constructLlmApi(config);
const response = await api.rerank({
model: config.model,
query: "What is the capital of spain?",
documents: [
"The capital of spain is Madrid",
"The largest breed of dog is the Great Dane",
],
});
expect(response.model).toBe(config.model);
expect(response.object).toBe("list");
expect(response.data.length).toEqual(2);
response.data.forEach((val, index) => {
expect(val.index).toBe(index);
expect(typeof val.relevance_score).toBe("number");
});
expect(response.data[0].relevance_score).toBeGreaterThan(
response.data[1].relevance_score,
);
});
}
function testFim(config: LlmApiConfig) {
test("should successfully fim", async () => {
const api = constructLlmApi(config);
const response = api.fimStream({
model: config.model,
prompt: "This is a ",
suffix: " .",
stream: true,
});
let completion = "";
for await (const result of response) {
expect(result.choices.length).toBeGreaterThan(0);
expect(typeof result.choices[0].delta.content).toBe("string");
completion += result.choices[0].delta.content;
}
expect(completion.length).toBeGreaterThan(0);
});
}
function testConfig(config: LlmApiConfig, chatOnly: boolean = false) {
const api = constructLlmApi(config);
if (!chatOnly) {
test("should successfully stream complete", async () => {
const stream = api.completionStream({
model: config.model,
prompt: "Hello! Who are you?",
stream: true,
});
let completion = "";
for await (const result of stream) {
completion += result.choices[0].text ?? "";
expect(typeof result.choices[0].text).toBe("string");
expect(result.choices.length).toBeGreaterThan(0);
}
expect(completion.length).toBeGreaterThan(0);
});
test("should successfully non-stream complete", async () => {
const response = await api.completionNonStream({
model: config.model,
prompt: "Hello! Who are you?",
stream: false,
});
expect(response.choices.length).toBeGreaterThan(0);
const completion = response.choices[0].text;
expect(typeof completion).toBe("string");
expect(completion.length).toBeGreaterThan(0);
});
}
test("should successfully stream chat", async () => {
const stream = api.chatCompletionStream({
model: config.model,
messages: [{ role: "user", content: "Hello! Who are you?" }],
stream: true,
});
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);
});
test("should successfully non-stream chat", async () => {
const response = await api.chatCompletionNonStream({
model: config.model,
messages: [{ role: "user", content: "Hello! Who are you?" }],
stream: false,
});
expect(response.choices.length).toBeGreaterThan(0);
const completion = response.choices[0].message.content;
expect(typeof completion).toBe("string");
expect(completion?.length).toBeGreaterThan(0);
});
}
const COMPLETION_TESTS: ({ chatOnly?: boolean } & LlmApiConfig)[] = [
{
provider: "openai",
model: "gpt-4o-mini",
apiKey: process.env.OPENAI_API_KEY!,
chatOnly: true,
},
];
const FIM_TESTS: LlmApiConfig[] = [
{
provider: "openai",
model: "codestral-latest",
apiKey: process.env.MISTRAL_API_KEY!,
apiBase: "https://api.mistral.ai/v1",
},
];
const EMBEDDINGS_TESTS: LlmApiConfig[] = [
{
provider: "openai",
model: "text-embedding-3-small",
apiKey: process.env.OPENAI_API_KEY!,
},
{
provider: "openai",
model: "voyage-code-2",
apiKey: process.env.VOYAGE_API_KEY!,
apiBase: "https://api.voyageai.com/v1/",
},
{
provider: "cohere",
model: "embed-english-v3.0",
apiKey: process.env.COHERE_API_KEY!,
},
];
const RERANK_TESTS: LlmApiConfig[] = [
{
provider: "openai",
model: "rerank-lite-1",
apiKey: process.env.VOYAGE_API_KEY!,
apiBase: "https://api.voyageai.com/v1/",
},
{
provider: "cohere",
model: "rerank-english-v3.0",
apiKey: process.env.COHERE_API_KEY!,
},
];
describe("should successfully call all adapters", () => {
COMPLETION_TESTS.forEach((config) => {
const { chatOnly, ...rest } = config;
testConfig(rest, chatOnly);
});
EMBEDDINGS_TESTS.forEach((config) => {
testEmbed(config);
});
RERANK_TESTS.forEach((config) => {
testRerank(config);
});
// FIM_TESTS.forEach((config) => {
// testFim(config);
// });
});

View file

@ -14,7 +14,7 @@
"resolveJsonModule": true,
"isolatedModules": true,
"noEmitOnError": false,
"types": ["node"],
"types": ["node", "jest"],
"outDir": "dist",
"declaration": true
// "sourceMap": true