Break out into NPM modules (#1726)

* config.json types

* export all schemas

* break out request logic into packages

* update openai adapters to export body types

* update packaging of npm modules

* update packages
This commit is contained in:
Nate Sesti 2024-07-11 22:12:42 -07:00 • committed by GitHub
parent 7182bc75ac
commit 58f252a3a3
No known key found for this signature in database
GPG key ID: B5690EEEBB952194
29 changed files with 7756 additions and 257 deletions

View file

@ -1,3 +1,4 @@
import { ConfigJson } from "@continuedev/config-types";
import {
ContinueConfig,
IDE,
@ -5,7 +6,6 @@ import {
SerializedContinueConfig,
} from "../..";
import { ControlPlaneClient } from "../../control-plane/client";
import { ControlPlaneSettings } from "../../control-plane/schema";
import { TeamAnalytics } from "../../control-plane/TeamAnalytics";
import { Telemetry } from "../../util/posthog";
import {
@ -26,7 +26,7 @@ export default class ControlPlaneProfileLoader implements IProfileLoader {
readonly profileId: string;
profileTitle: string;
workspaceSettings: ControlPlaneSettings | undefined;
workspaceSettings: ConfigJson | undefined;
constructor(
private readonly workspaceId: string,
@ -55,7 +55,7 @@ export default class ControlPlaneProfileLoader implements IProfileLoader {
this.profileId,
)) as any);
// First construct a SerializedContinueConfig from the ControlPlaneSettings
// First construct a SerializedContinueConfig from the ControlPlaneSettings (TODO)
const serializedConfig: SerializedContinueConfig = {
models: settings.models,
tabAutocompleteModel: settings.tabAutocompleteModel,

View file

@ -1,5 +1,5 @@
import { Analytics } from "@continuedev/config-types";
import os from "node:os";
import { ControlPlaneAnalytics } from "./schema";
export class TeamAnalytics {
static client: any = undefined;
@ -24,7 +24,7 @@ export class TeamAnalytics {
}
static async setup(
config: ControlPlaneAnalytics,
config: Analytics,
uniqueId: string,
extensionVersion: string,
) {

View file

@ -1,6 +1,6 @@
import { ConfigJson } from "@continuedev/config-types";
import fetch, { RequestInit, Response } from "node-fetch";
import { ModelDescription } from "..";
import { ControlPlaneSettings } from "./schema";
export interface ControlPlaneSessionInfo {
accessToken: string;
@ -13,7 +13,7 @@ export interface ControlPlaneSessionInfo {
export interface ControlPlaneWorkspace {
id: string;
name: string;
settings: ControlPlaneSettings;
settings: ConfigJson;
}
export interface ControlPlaneModelDescription extends ModelDescription {}
@ -78,9 +78,7 @@ export class ControlPlaneClient {
return (await resp.json()) as any;
}
async getSettingsForWorkspace(
workspaceId: string,
): Promise<ControlPlaneSettings> {
async getSettingsForWorkspace(workspaceId: string): Promise<ConfigJson> {
const userId = await this.userId;
if (!userId) {
throw new Error("No user id");

View file

@ -1,128 +0,0 @@
import { z } from "zod";
const modelDescriptionSchema = z.object({
title: z.string(),
provider: z.enum([
"openai",
"anthropic",
"cohere",
"ollama",
"huggingface-tgi",
"huggingface-inference-api",
"replicate",
"gemini",
"mistral",
"bedrock",
"cloudflare",
"azure",
]),
model: z.string(),
apiKey: z.string().optional(),
apiBase: z.string().optional(),
contextLength: z.number().optional(),
template: z
.enum([
"llama2",
"alpaca",
"zephyr",
"phi2",
"phind",
"anthropic",
"chatml",
"none",
"openchat",
"deepseek",
"xwin-coder",
"neural-chat",
"codellama-70b",
"llava",
"gemma",
"llama3",
])
.optional(),
completionOptions: z
.object({
temperature: z.number().optional(),
topP: z.number().optional(),
topK: z.number().optional(),
minP: z.number().optional(),
presencePenalty: z.number().optional(),
frequencyPenalty: z.number().optional(),
mirostat: z.number().optional(),
stop: z.array(z.string()).optional(),
maxTokens: z.number().optional(),
numThreads: z.number().optional(),
keepAlive: z.number().optional(),
raw: z.boolean().optional(),
stream: z.boolean().optional(),
})
.optional(),
systemMessage: z.string().optional(),
requestOptions: z
.object({
timeout: z.number().optional(),
verifySsl: z.boolean().optional(),
caBundlePath: z.union([z.string(), z.array(z.string())]).optional(),
proxy: z.string().optional(),
headers: z.record(z.string()).optional(),
extraBodyProperties: z.record(z.any()).optional(),
noProxy: z.array(z.string()).optional(),
})
.optional(),
promptTemplates: z.record(z.string()).optional(),
});
const embeddingsProviderSchema = z.object({
provider: z.enum([
"transformers.js",
"ollama",
"openai",
"cohere",
"free-trial",
"gemini",
]),
apiBase: z.string().optional(),
apiKey: z.string().optional(),
model: z.string().optional(),
engine: z.string().optional(),
apiType: z.string().optional(),
apiVersion: z.string().optional(),
requestOptions: z
.object({
timeout: z.number().optional(),
verifySsl: z.boolean().optional(),
caBundlePath: z.union([z.string(), z.array(z.string())]).optional(),
proxy: z.string().optional(),
headers: z.record(z.string()).optional(),
extraBodyProperties: z.record(z.any()).optional(),
noProxy: z.array(z.string()).optional(),
})
.optional(),
});
const rerankerSchema = z.object({
name: z.enum(["cohere", "voyage", "llm"]),
params: z.record(z.any()).optional(),
});
const analyticsSchema = z.object({
url: z.string().optional(),
clientKey: z.string().optional(),
});
export type ControlPlaneAnalytics = z.infer<typeof analyticsSchema>;
const devDataSchema = z.object({
url: z.string().optional(),
});
export const controlPlaneSettingsSchema = z.object({
models: z.array(modelDescriptionSchema),
tabAutocompleteModel: modelDescriptionSchema,
embeddingsModel: embeddingsProviderSchema,
reranker: rerankerSchema,
analytics: analyticsSchema,
devData: devDataSchema,
});
export type ControlPlaneSettings = z.infer<typeof controlPlaneSettingsSchema>;

View file

@ -11,6 +11,7 @@
"dependencies": {
"@aws-sdk/client-bedrock-runtime": "^3.574.0",
"@aws-sdk/credential-providers": "^3.596.0",
"@continuedev/config-types": "^1.0.6",
"@mozilla/readability": "^0.5.0",
"@octokit/rest": "^20.0.2",
"@types/jsdom": "^21.1.6",
@ -3928,6 +3929,14 @@
"node": ">=14.21.3"
}
},
"node_modules/@continuedev/config-types": {
"version": "1.0.6",
"resolved": "https://registry.npmjs.org/@continuedev/config-types/-/config-types-1.0.6.tgz",
"integrity": "sha512-JTlaGtsNW9vfSPcDJBn+I2vcs0wWRFIQcN3sa6pBFg2fj8W6qcMZoYUdzoU/+X+2ZT8OKcbomWfP2+qW0uuy6A==",
"dependencies": {
"zod": "^3.23.8"
}
},
"node_modules/@esbuild/android-arm": {
"version": "0.17.19",
"resolved": "https://registry.npmjs.org/@esbuild/android-arm/-/android-arm-0.17.19.tgz",

View file

@ -31,6 +31,7 @@
"dependencies": {
"@aws-sdk/client-bedrock-runtime": "^3.574.0",
"@aws-sdk/credential-providers": "^3.596.0",
"@continuedev/config-types": "^1.0.6",
"@mozilla/readability": "^0.5.0",
"@octokit/rest": "^20.0.2",
"@types/jsdom": "^21.1.6",

View file

@ -1,13 +1,16 @@
{
"name": "control-plane-types",
"version": "1.0.0",
"name": "@continuedev/config-types",
"version": "1.0.4",
"lockfileVersion": 3,
"requires": true,
"packages": {
"": {
"name": "control-plane-types",
"version": "1.0.0",
"name": "@continuedev/config-types",
"version": "1.0.4",
"license": "Apache-2.0",
"dependencies": {
"zod": "^3.23.8"
},
"devDependencies": {
"typescript": "^5.5.2"
}
@ -24,6 +27,14 @@
"engines": {
"node": ">=14.17"
}
},
"node_modules/zod": {
"version": "3.23.8",
"resolved": "https://registry.npmjs.org/zod/-/zod-3.23.8.tgz",
"integrity": "sha512-XBx9AXhXktjUqnepgTiE5flcKIYWi/rme0Eaj+5Y0lftuGBq+jyRu/md4WnuxqgP1ubdpNCsYEYPxrzVHD8d6g==",
"funding": {
"url": "https://github.com/sponsors/colinhacks"
}
}
}
}

View file

@ -1,15 +1,20 @@
{
"name": "control-plane-types",
"version": "1.0.0",
"name": "@continuedev/config-types",
"version": "1.0.6",
"description": "",
"main": "dist/index.js",
"types": "dist/index.d.ts",
"type": "module",
"scripts": {
"test": "echo \"Error: no test specified\" && exit 1"
"test": "echo \"Error: no test specified\" && exit 1",
"build": "tsc"
},
"author": "Nate Sesti and Ty Dunn",
"license": "Apache-2.0",
"devDependencies": {
"typescript": "^5.5.2"
},
"dependencies": {
"zod": "^3.23.8"
}
}

File diff suppressed because it is too large Load diff

View file

@ -0,0 +1,207 @@
import { z } from "zod";
export const completionOptionsSchema = z.object({
temperature: z.number().optional(),
topP: z.number().optional(),
topK: z.number().optional(),
minP: z.number().optional(),
presencePenalty: z.number().optional(),
frequencyPenalty: z.number().optional(),
mirostat: z.number().optional(),
stop: z.array(z.string()).optional(),
maxTokens: z.number().optional(),
numThreads: z.number().optional(),
keepAlive: z.number().optional(),
raw: z.boolean().optional(),
stream: z.boolean().optional(),
});
export type CompletionOptions = z.infer<typeof completionOptionsSchema>;
export const clientCertificateOptionsSchema = z.object({
cert: z.string(),
key: z.string(),
passphrase: z.string().optional(),
});
export type ClientCertificateOptions = z.infer<
typeof clientCertificateOptionsSchema
>;
export const requestOptionsSchema = z.object({
timeout: z.number().optional(),
verifySsl: z.boolean().optional(),
caBundlePath: z.union([z.string(), z.array(z.string())]).optional(),
proxy: z.string().optional(),
headers: z.record(z.string()).optional(),
extraBodyProperties: z.record(z.any()).optional(),
noProxy: z.array(z.string()).optional(),
clientCertificate: clientCertificateOptionsSchema.optional(),
});
export type RequestOptions = z.infer<typeof requestOptionsSchema>;
export const modelDescriptionSchema = z.object({
title: z.string(),
provider: z.enum([
"openai",
"anthropic",
"cohere",
"ollama",
"huggingface-tgi",
"huggingface-inference-api",
"replicate",
"gemini",
"mistral",
"bedrock",
"cloudflare",
"azure",
"continue-proxy",
]),
model: z.string(),
apiKey: z.string().optional(),
apiBase: z.string().optional(),
contextLength: z.number().optional(),
template: z
.enum([
"llama2",
"alpaca",
"zephyr",
"phi2",
"phind",
"anthropic",
"chatml",
"none",
"openchat",
"deepseek",
"xwin-coder",
"neural-chat",
"codellama-70b",
"llava",
"gemma",
"llama3",
])
.optional(),
completionOptions: completionOptionsSchema.optional(),
systemMessage: z.string().optional(),
requestOptions: z
.object({
timeout: z.number().optional(),
verifySsl: z.boolean().optional(),
caBundlePath: z.union([z.string(), z.array(z.string())]).optional(),
proxy: z.string().optional(),
headers: z.record(z.string()).optional(),
extraBodyProperties: z.record(z.any()).optional(),
noProxy: z.array(z.string()).optional(),
})
.optional(),
promptTemplates: z.record(z.string()).optional(),
});
export type ModelDescription = z.infer<typeof modelDescriptionSchema>;
export const embeddingsProviderSchema = z.object({
provider: z.enum([
"transformers.js",
"ollama",
"openai",
"cohere",
"free-trial",
"gemini",
"continue-proxy",
]),
apiBase: z.string().optional(),
apiKey: z.string().optional(),
model: z.string().optional(),
engine: z.string().optional(),
apiType: z.string().optional(),
apiVersion: z.string().optional(),
requestOptions: requestOptionsSchema.optional(),
});
export type EmbeddingsProvider = z.infer<typeof embeddingsProviderSchema>;
export const uiOptionsSchema = z.object({
codeBlockToolbarPosition: z.enum(["top", "bottom"]).optional(),
fontSize: z.number().optional(),
displayRawMarkdown: z.boolean().optional(),
});
export type UiOptions = z.infer<typeof uiOptionsSchema>;
export const tabAutocompleteOptionsSchema = z.object({
disable: z.boolean(),
useCopyBuffer: z.boolean(),
useSuffix: z.boolean(),
maxPromptTokens: z.number(),
debounceDelay: z.number(),
maxSuffixPercentage: z.number(),
prefixPercentage: z.number(),
template: z.string().optional(),
multilineCompletions: z.enum(["always", "never", "auto"]),
slidingWindowPrefixPercentage: z.number(),
slidingWindowSize: z.number(),
maxSnippetPercentage: z.number(),
recentlyEditedSimilarityThreshold: z.number(),
useCache: z.boolean(),
onlyMyCode: z.boolean(),
useOtherFiles: z.boolean(),
useRecentlyEdited: z.boolean(),
recentLinePrefixMatchMinLength: z.number(),
disableInFiles: z.array(z.string()).optional(),
useImports: z.boolean().optional(),
});
export type TabAutocompleteOptions = z.infer<
typeof tabAutocompleteOptionsSchema
>;
export const slashCommandSchema = z.object({
name: z.string(),
description: z.string(),
params: z.record(z.any()).optional(),
});
export type SlashCommand = z.infer<typeof slashCommandSchema>;
export const customCommandSchema = z.object({
name: z.string(),
description: z.string(),
params: z.record(z.any()).optional(),
});
export type CustomCommand = z.infer<typeof customCommandSchema>;
export const contextProviderSchema = z.object({
name: z.string(),
params: z.record(z.string(), z.any()),
});
export type ContextProvider = z.infer<typeof contextProviderSchema>;
export const rerankerSchema = z.object({
name: z.enum(["cohere", "voyage", "llm", "continue-proxy"]),
params: z.record(z.any()).optional(),
});
export type Reranker = z.infer<typeof rerankerSchema>;
export const analyticsSchema = z.object({
url: z.string().optional(),
clientKey: z.string().optional(),
});
export type Analytics = z.infer<typeof analyticsSchema>;
export const devDataSchema = z.object({
url: z.string().optional(),
});
export type DevData = z.infer<typeof devDataSchema>;
export const configJsonSchema = z.object({
models: z.array(modelDescriptionSchema),
tabAutocompleteModel: modelDescriptionSchema.optional(),
embeddingsProvider: embeddingsProviderSchema.optional(),
reranker: rerankerSchema.optional(),
analytics: analyticsSchema,
devData: devDataSchema,
allowAnonymousTelemetry: z.boolean().optional(),
systemMessage: z.string().optional(),
completionOptions: completionOptionsSchema.optional(),
requestOptions: requestOptionsSchema.optional(),
slashCommands: z.array(slashCommandSchema).optional(),
customCommands: z.array(customCommandSchema).optional(),
contextProviders: z.array(contextProviderSchema).optional(),
disableIndexing: z.boolean().optional(),
tabAutocompleteOptions: tabAutocompleteOptionsSchema.optional(),
ui: uiOptionsSchema.optional(),
});
export type ConfigJson = z.infer<typeof configJsonSchema>;

View file

@ -0,0 +1,23 @@
{
"compilerOptions": {
"target": "ESNext",
"module": "NodeNext",
"useDefineForClassFields": true,
"lib": ["DOM", "ESNext"],
"allowJs": true,
"skipLibCheck": true,
"esModuleInterop": true,
"allowSyntheticDefaultImports": true,
"strict": true,
"forceConsistentCasingInFileNames": true,
"moduleResolution": "NodeNext",
"resolveJsonModule": true,
"isolatedModules": true,
"noEmitOnError": false,
"types": ["node"],
"outDir": "dist",
"declaration": true
// "sourceMap": true
},
"include": ["src/**/*"]
}

View file

@ -1,4 +0,0 @@
export interface Test {
a: string;
b: number;
}

View file

@ -1,108 +0,0 @@
{
"compilerOptions": {
/* Visit https://aka.ms/tsconfig to read more about this file */
/* Projects */
// "incremental": true, /* Save .tsbuildinfo files to allow for incremental compilation of projects. */
// "composite": true, /* Enable constraints that allow a TypeScript project to be used with project references. */
// "tsBuildInfoFile": "./.tsbuildinfo", /* Specify the path to .tsbuildinfo incremental compilation file. */
// "disableSourceOfProjectReferenceRedirect": true, /* Disable preferring source files instead of declaration files when referencing composite projects. */
// "disableSolutionSearching": true, /* Opt a project out of multi-project reference checking when editing. */
// "disableReferencedProjectLoad": true, /* Reduce the number of projects loaded automatically by TypeScript. */
/* Language and Environment */
"target": "es2016", /* Set the JavaScript language version for emitted JavaScript and include compatible library declarations. */
// "lib": [], /* Specify a set of bundled library declaration files that describe the target runtime environment. */
// "jsx": "preserve", /* Specify what JSX code is generated. */
// "experimentalDecorators": true, /* Enable experimental support for legacy experimental decorators. */
// "emitDecoratorMetadata": true, /* Emit design-type metadata for decorated declarations in source files. */
// "jsxFactory": "", /* Specify the JSX factory function used when targeting React JSX emit, e.g. 'React.createElement' or 'h'. */
// "jsxFragmentFactory": "", /* Specify the JSX Fragment reference used for fragments when targeting React JSX emit e.g. 'React.Fragment' or 'Fragment'. */
// "jsxImportSource": "", /* Specify module specifier used to import the JSX factory functions when using 'jsx: react-jsx*'. */
// "reactNamespace": "", /* Specify the object invoked for 'createElement'. This only applies when targeting 'react' JSX emit. */
// "noLib": true, /* Disable including any library files, including the default lib.d.ts. */
// "useDefineForClassFields": true, /* Emit ECMAScript-standard-compliant class fields. */
// "moduleDetection": "auto", /* Control what method is used to detect module-format JS files. */
/* Modules */
"module": "commonjs", /* Specify what module code is generated. */
// "rootDir": "./", /* Specify the root folder within your source files. */
// "moduleResolution": "node10", /* Specify how TypeScript looks up a file from a given module specifier. */
// "baseUrl": "./", /* Specify the base directory to resolve non-relative module names. */
// "paths": {}, /* Specify a set of entries that re-map imports to additional lookup locations. */
// "rootDirs": [], /* Allow multiple folders to be treated as one when resolving modules. */
// "typeRoots": [], /* Specify multiple folders that act like './node_modules/@types'. */
// "types": [], /* Specify type package names to be included without being referenced in a source file. */
// "allowUmdGlobalAccess": true, /* Allow accessing UMD globals from modules. */
// "moduleSuffixes": [], /* List of file name suffixes to search when resolving a module. */
// "allowImportingTsExtensions": true, /* Allow imports to include TypeScript file extensions. Requires '--moduleResolution bundler' and either '--noEmit' or '--emitDeclarationOnly' to be set. */
// "resolvePackageJsonExports": true, /* Use the package.json 'exports' field when resolving package imports. */
// "resolvePackageJsonImports": true, /* Use the package.json 'imports' field when resolving imports. */
// "customConditions": [], /* Conditions to set in addition to the resolver-specific defaults when resolving imports. */
// "resolveJsonModule": true, /* Enable importing .json files. */
// "allowArbitraryExtensions": true, /* Enable importing files with any extension, provided a declaration file is present. */
// "noResolve": true, /* Disallow 'import's, 'require's or '<reference>'s from expanding the number of files TypeScript should add to a project. */
/* JavaScript Support */
// "allowJs": true, /* Allow JavaScript files to be a part of your program. Use the 'checkJS' option to get errors from these files. */
// "checkJs": true, /* Enable error reporting in type-checked JavaScript files. */
// "maxNodeModuleJsDepth": 1, /* Specify the maximum folder depth used for checking JavaScript files from 'node_modules'. Only applicable with 'allowJs'. */
/* Emit */
// "declaration": true, /* Generate .d.ts files from TypeScript and JavaScript files in your project. */
// "declarationMap": true, /* Create sourcemaps for d.ts files. */
// "emitDeclarationOnly": true, /* Only output d.ts files and not JavaScript files. */
// "sourceMap": true, /* Create source map files for emitted JavaScript files. */
// "inlineSourceMap": true, /* Include sourcemap files inside the emitted JavaScript. */
// "outFile": "./", /* Specify a file that bundles all outputs into one JavaScript file. If 'declaration' is true, also designates a file that bundles all .d.ts output. */
// "outDir": "./", /* Specify an output folder for all emitted files. */
// "removeComments": true, /* Disable emitting comments. */
// "noEmit": true, /* Disable emitting files from a compilation. */
// "importHelpers": true, /* Allow importing helper functions from tslib once per project, instead of including them per-file. */
// "downlevelIteration": true, /* Emit more compliant, but verbose and less performant JavaScript for iteration. */
// "sourceRoot": "", /* Specify the root path for debuggers to find the reference source code. */
// "mapRoot": "", /* Specify the location where debugger should locate map files instead of generated locations. */
// "inlineSources": true, /* Include source code in the sourcemaps inside the emitted JavaScript. */
// "emitBOM": true, /* Emit a UTF-8 Byte Order Mark (BOM) in the beginning of output files. */
// "newLine": "crlf", /* Set the newline character for emitting files. */
// "stripInternal": true, /* Disable emitting declarations that have '@internal' in their JSDoc comments. */
// "noEmitHelpers": true, /* Disable generating custom helper functions like '__extends' in compiled output. */
// "noEmitOnError": true, /* Disable emitting files if any type checking errors are reported. */
// "preserveConstEnums": true, /* Disable erasing 'const enum' declarations in generated code. */
// "declarationDir": "./", /* Specify the output directory for generated declaration files. */
/* Interop Constraints */
// "isolatedModules": true, /* Ensure that each file can be safely transpiled without relying on other imports. */
// "verbatimModuleSyntax": true, /* Do not transform or elide any imports or exports not marked as type-only, ensuring they are written in the output file's format based on the 'module' setting. */
// "isolatedDeclarations": true, /* Require sufficient annotation on exports so other tools can trivially generate declaration files. */
// "allowSyntheticDefaultImports": true, /* Allow 'import x from y' when a module doesn't have a default export. */
"esModuleInterop": true, /* Emit additional JavaScript to ease support for importing CommonJS modules. This enables 'allowSyntheticDefaultImports' for type compatibility. */
// "preserveSymlinks": true, /* Disable resolving symlinks to their realpath. This correlates to the same flag in node. */
"forceConsistentCasingInFileNames": true, /* Ensure that casing is correct in imports. */
/* Type Checking */
"strict": true, /* Enable all strict type-checking options. */
// "noImplicitAny": true, /* Enable error reporting for expressions and declarations with an implied 'any' type. */
// "strictNullChecks": true, /* When type checking, take into account 'null' and 'undefined'. */
// "strictFunctionTypes": true, /* When assigning functions, check to ensure parameters and the return values are subtype-compatible. */
// "strictBindCallApply": true, /* Check that the arguments for 'bind', 'call', and 'apply' methods match the original function. */
// "strictPropertyInitialization": true, /* Check for class properties that are declared but not set in the constructor. */
// "noImplicitThis": true, /* Enable error reporting when 'this' is given the type 'any'. */
// "useUnknownInCatchVariables": true, /* Default catch clause variables as 'unknown' instead of 'any'. */
// "alwaysStrict": true, /* Ensure 'use strict' is always emitted. */
// "noUnusedLocals": true, /* Enable error reporting when local variables aren't read. */
// "noUnusedParameters": true, /* Raise an error when a function parameter isn't read. */
// "exactOptionalPropertyTypes": true, /* Interpret optional property types as written, rather than adding 'undefined'. */
// "noImplicitReturns": true, /* Enable error reporting for codepaths that do not explicitly return in a function. */
// "noFallthroughCasesInSwitch": true, /* Enable error reporting for fallthrough cases in switch statements. */
// "noUncheckedIndexedAccess": true, /* Add 'undefined' to a type when accessed using an index. */
// "noImplicitOverride": true, /* Ensure overriding members in derived classes are marked with an override modifier. */
// "noPropertyAccessFromIndexSignature": true, /* Enforces using indexed accessors for keys declared using an indexed type. */
// "allowUnusedLabels": true, /* Disable error reporting for unused labels. */
// "allowUnreachableCode": true, /* Disable error reporting for unreachable code. */
/* Completeness */
// "skipDefaultLibCheck": true, /* Skip type checking .d.ts files that are included with TypeScript. */
"skipLibCheck": true /* Skip type checking all .d.ts files. */
}
}

7
packages/fetch/jest.config.d.ts vendored Normal file
View file

@ -0,0 +1,7 @@
/**
* For a detailed explanation regarding each configuration property, visit:
* https://jestjs.io/docs/configuration
*/
import type { Config } from 'jest';
declare const config: Config;
export default config;

View file

@ -0,0 +1,143 @@
/**
* For a detailed explanation regarding each configuration property, visit:
* https://jestjs.io/docs/configuration
*/
const config = {
// All imported modules in your tests should be mocked automatically
// automock: false,
// Stop running tests after `n` failures
// bail: 0,
// The directory where Jest should store its cached dependency information
// cacheDirectory: "/private/var/folders/n_/c3r8w0s95xl271j98y2lzhz80000gn/T/jest_dx",
// Automatically clear mock calls, instances, contexts and results before every test
clearMocks: true,
// Indicates whether the coverage information should be collected while executing the test
collectCoverage: true,
// An array of glob patterns indicating a set of files for which coverage information should be collected
// collectCoverageFrom: undefined,
// The directory where Jest should output its coverage files
coverageDirectory: "coverage",
// An array of regexp pattern strings used to skip coverage collection
// coveragePathIgnorePatterns: [
// "/node_modules/"
// ],
// Indicates which provider should be used to instrument code for coverage
coverageProvider: "v8",
// A list of reporter names that Jest uses when writing coverage reports
// coverageReporters: [
// "json",
// "text",
// "lcov",
// "clover"
// ],
// An object that configures minimum threshold enforcement for coverage results
// coverageThreshold: undefined,
// A path to a custom dependency extractor
// dependencyExtractor: undefined,
// Make calling deprecated APIs throw helpful error messages
// errorOnDeprecated: false,
// The default configuration for fake timers
// fakeTimers: {
// "enableGlobally": false
// },
// Force coverage collection from ignored files using an array of glob patterns
// forceCoverageMatch: [],
// A path to a module which exports an async function that is triggered once before all test suites
// globalSetup: undefined,
// A path to a module which exports an async function that is triggered once after all test suites
// globalTeardown: undefined,
// A set of global variables that need to be available in all test environments
// globals: {},
// The maximum amount of workers used to run your tests. Can be specified as % or a number. E.g. maxWorkers: 10% will use 10% of your CPU amount + 1 as the maximum worker number. maxWorkers: 2 will use a maximum of 2 workers.
// maxWorkers: "50%",
// An array of directory names to be searched recursively up from the requiring module's location
// moduleDirectories: [
// "node_modules"
// ],
// An array of file extensions your modules use
// moduleFileExtensions: [
// "js",
// "mjs",
// "cjs",
// "jsx",
// "ts",
// "tsx",
// "json",
// "node"
// ],
// A map from regular expressions to module names or to arrays of module names that allow to stub out resources with a single module
// moduleNameMapper: {},
// An array of regexp pattern strings, matched against all module paths before considered 'visible' to the module loader
// modulePathIgnorePatterns: [],
// Activates notifications for test results
// notify: false,
// An enum that specifies notification mode. Requires { notify: true }
// notifyMode: "failure-change",
// A preset that is used as a base for Jest's configuration
// preset: undefined,
// Run tests from one or more projects
// projects: undefined,
// Use this configuration option to add custom reporters to Jest
// reporters: undefined,
// Automatically reset mock state before every test
// resetMocks: false,
// Reset the module registry before running each individual test
// resetModules: false,
// A path to a custom resolver
// resolver: undefined,
// Automatically restore mock state and implementation before every test
// restoreMocks: false,
// The root directory that Jest should scan for tests and modules within
// rootDir: undefined,
// A list of paths to directories that Jest should use to search for files in
// roots: [
// "<rootDir>"
// ],
// Allows you to use a custom runner instead of Jest's default test runner
// runner: "jest-runner",
// The paths to modules that run some code to configure or set up the testing environment before each test
// setupFiles: [],
// A list of paths to modules that run some code to configure or set up the testing framework before each test
// setupFilesAfterEnv: [],
// The number of seconds after which a test is considered as slow and reported as such in the results.
// slowTestThreshold: 5,
// A list of paths to snapshot serializer modules Jest should use for snapshot testing
// snapshotSerializers: [],
// The test environment that will be used for testing
// testEnvironment: "jest-environment-node",
// Options that will be passed to the testEnvironment
// testEnvironmentOptions: {},
// Adds a location field to test results
// testLocationInResults: false,
// The glob patterns Jest uses to detect test files
// testMatch: [
// "**/__tests__/**/*.[jt]s?(x)",
// "**/?(*.)+(spec|test).[tj]s?(x)"
// ],
// An array of regexp pattern strings that are matched against all test paths, matched tests are skipped
// testPathIgnorePatterns: [
// "/node_modules/"
// ],
// The regexp pattern or array of patterns that Jest uses to detect test files
// testRegex: [],
// This option allows the use of a custom results processor
// testResultsProcessor: undefined,
// This option allows use of a custom test runner
// testRunner: "jest-circus/runner",
// A map from regular expressions to paths to transformers
// transform: undefined,
// An array of regexp pattern strings that are matched against all source file paths, matched files will skip transformation
// transformIgnorePatterns: [
// "/node_modules/",
// "\\.pnp\\.[^\\/]+$"
// ],
// An array of regexp pattern strings that are matched against all modules before the module loader will automatically return a mock for them
// unmockedModulePathPatterns: undefined,
// Indicates whether each individual test should be reported during the run
// verbose: undefined,
// An array of regexp patterns that are matched against all source file paths before re-running tests in watch mode
// watchPathIgnorePatterns: [],
// Whether to use watchman for file crawling
// watchman: true,
};
export default config;

View file

@ -0,0 +1,199 @@
/**
* For a detailed explanation regarding each configuration property, visit:
* https://jestjs.io/docs/configuration
*/
import type {Config} from 'jest';
const config: Config = {
// All imported modules in your tests should be mocked automatically
// automock: false,
// Stop running tests after `n` failures
// bail: 0,
// The directory where Jest should store its cached dependency information
// cacheDirectory: "/private/var/folders/n_/c3r8w0s95xl271j98y2lzhz80000gn/T/jest_dx",
// Automatically clear mock calls, instances, contexts and results before every test
clearMocks: true,
// Indicates whether the coverage information should be collected while executing the test
collectCoverage: true,
// An array of glob patterns indicating a set of files for which coverage information should be collected
// collectCoverageFrom: undefined,
// The directory where Jest should output its coverage files
coverageDirectory: "coverage",
// An array of regexp pattern strings used to skip coverage collection
// coveragePathIgnorePatterns: [
// "/node_modules/"
// ],
// Indicates which provider should be used to instrument code for coverage
coverageProvider: "v8",
// A list of reporter names that Jest uses when writing coverage reports
// coverageReporters: [
// "json",
// "text",
// "lcov",
// "clover"
// ],
// An object that configures minimum threshold enforcement for coverage results
// coverageThreshold: undefined,
// A path to a custom dependency extractor
// dependencyExtractor: undefined,
// Make calling deprecated APIs throw helpful error messages
// errorOnDeprecated: false,
// The default configuration for fake timers
// fakeTimers: {
// "enableGlobally": false
// },
// Force coverage collection from ignored files using an array of glob patterns
// forceCoverageMatch: [],
// A path to a module which exports an async function that is triggered once before all test suites
// globalSetup: undefined,
// A path to a module which exports an async function that is triggered once after all test suites
// globalTeardown: undefined,
// A set of global variables that need to be available in all test environments
// globals: {},
// The maximum amount of workers used to run your tests. Can be specified as % or a number. E.g. maxWorkers: 10% will use 10% of your CPU amount + 1 as the maximum worker number. maxWorkers: 2 will use a maximum of 2 workers.
// maxWorkers: "50%",
// An array of directory names to be searched recursively up from the requiring module's location
// moduleDirectories: [
// "node_modules"
// ],
// An array of file extensions your modules use
// moduleFileExtensions: [
// "js",
// "mjs",
// "cjs",
// "jsx",
// "ts",
// "tsx",
// "json",
// "node"
// ],
// A map from regular expressions to module names or to arrays of module names that allow to stub out resources with a single module
// moduleNameMapper: {},
// An array of regexp pattern strings, matched against all module paths before considered 'visible' to the module loader
// modulePathIgnorePatterns: [],
// Activates notifications for test results
// notify: false,
// An enum that specifies notification mode. Requires { notify: true }
// notifyMode: "failure-change",
// A preset that is used as a base for Jest's configuration
// preset: undefined,
// Run tests from one or more projects
// projects: undefined,
// Use this configuration option to add custom reporters to Jest
// reporters: undefined,
// Automatically reset mock state before every test
// resetMocks: false,
// Reset the module registry before running each individual test
// resetModules: false,
// A path to a custom resolver
// resolver: undefined,
// Automatically restore mock state and implementation before every test
// restoreMocks: false,
// The root directory that Jest should scan for tests and modules within
// rootDir: undefined,
// A list of paths to directories that Jest should use to search for files in
// roots: [
// "<rootDir>"
// ],
// Allows you to use a custom runner instead of Jest's default test runner
// runner: "jest-runner",
// The paths to modules that run some code to configure or set up the testing environment before each test
// setupFiles: [],
// A list of paths to modules that run some code to configure or set up the testing framework before each test
// setupFilesAfterEnv: [],
// The number of seconds after which a test is considered as slow and reported as such in the results.
// slowTestThreshold: 5,
// A list of paths to snapshot serializer modules Jest should use for snapshot testing
// snapshotSerializers: [],
// The test environment that will be used for testing
// testEnvironment: "jest-environment-node",
// Options that will be passed to the testEnvironment
// testEnvironmentOptions: {},
// Adds a location field to test results
// testLocationInResults: false,
// The glob patterns Jest uses to detect test files
// testMatch: [
// "**/__tests__/**/*.[jt]s?(x)",
// "**/?(*.)+(spec|test).[tj]s?(x)"
// ],
// An array of regexp pattern strings that are matched against all test paths, matched tests are skipped
// testPathIgnorePatterns: [
// "/node_modules/"
// ],
// The regexp pattern or array of patterns that Jest uses to detect test files
// testRegex: [],
// This option allows the use of a custom results processor
// testResultsProcessor: undefined,
// This option allows use of a custom test runner
// testRunner: "jest-circus/runner",
// A map from regular expressions to paths to transformers
// transform: undefined,
// An array of regexp pattern strings that are matched against all source file paths, matched files will skip transformation
// transformIgnorePatterns: [
// "/node_modules/",
// "\\.pnp\\.[^\\/]+$"
// ],
// An array of regexp pattern strings that are matched against all modules before the module loader will automatically return a mock for them
// unmockedModulePathPatterns: undefined,
// Indicates whether each individual test should be reported during the run
// verbose: undefined,
// An array of regexp patterns that are matched against all source file paths before re-running tests in watch mode
// watchPathIgnorePatterns: [],
// Whether to use watchman for file crawling
// watchman: true,
};
export default config;

3665
packages/fetch/package-lock.json generated Normal file

File diff suppressed because it is too large Load diff

View file

@ -0,0 +1,25 @@
{
"name": "@continuedev/fetch",
"version": "1.0.2",
"description": "",
"main": "dist/index.js",
"types": "dist/index.d.ts",
"type": "module",
"scripts": {
"test": "jest",
"build": "tsc"
},
"author": "Nate Sesti and Ty Dunn",
"license": "Apache-2.0",
"dependencies": {
"@continuedev/config-types": "^1.0.5",
"follow-redirects": "^1.15.6",
"http-proxy-agent": "^7.0.2",
"https-proxy-agent": "^7.0.5",
"node-fetch": "^3.3.2"
},
"devDependencies": {
"@types/follow-redirects": "^1.14.4",
"jest": "^29.7.0"
}
}

117
packages/fetch/src/fetch.ts Normal file
View file

@ -0,0 +1,117 @@
import { RequestOptions } from "@continuedev/config-types/src/index.js";
import * as followRedirects from "follow-redirects";
import { HttpProxyAgent } from "http-proxy-agent";
import { globalAgent } from "https";
import { HttpsProxyAgent } from "https-proxy-agent";
import fetch, { RequestInit, Response } from "node-fetch";
import * as fs from "node:fs";
import tls from "node:tls";
const { http, https } = (followRedirects as any).default;
export function fetchwithRequestOptions(
url_: URL | string,
init?: RequestInit,
requestOptions?: RequestOptions,
): Promise<Response> {
let url = url_;
if (typeof url === "string") {
url = new URL(url);
}
const TIMEOUT = 7200; // 7200 seconds = 2 hours
let globalCerts: string[] = [];
if (process.env.IS_BINARY) {
if (Array.isArray(globalAgent.options.ca)) {
globalCerts = [...globalAgent.options.ca.map((cert) => cert.toString())];
} else if (typeof globalAgent.options.ca !== "undefined") {
globalCerts.push(globalAgent.options.ca.toString());
}
}
const ca = Array.from(new Set([...tls.rootCertificates, ...globalCerts]));
const customCerts =
typeof requestOptions?.caBundlePath === "string"
? [requestOptions?.caBundlePath]
: requestOptions?.caBundlePath;
if (customCerts) {
ca.push(
...customCerts.map((customCert) => fs.readFileSync(customCert, "utf8")),
);
}
const timeout = (requestOptions?.timeout ?? TIMEOUT) * 1000; // measured in ms
const agentOptions: { [key: string]: any } = {
ca,
rejectUnauthorized: requestOptions?.verifySsl,
timeout,
sessionTimeout: timeout,
keepAlive: true,
keepAliveMsecs: timeout,
};
// Handle ClientCertificateOptions
if (requestOptions?.clientCertificate) {
agentOptions.cert = fs.readFileSync(
requestOptions.clientCertificate.cert,
"utf8",
);
agentOptions.key = fs.readFileSync(
requestOptions.clientCertificate.key,
"utf8",
);
if (requestOptions.clientCertificate.passphrase) {
agentOptions.passphrase = requestOptions.clientCertificate.passphrase;
}
}
const proxy = requestOptions?.proxy;
// Create agent
const protocol = url.protocol === "https:" ? https : http;
const agent =
proxy && !requestOptions?.noProxy?.includes(url.hostname)
? protocol === https
? new HttpsProxyAgent(proxy, agentOptions)
: new HttpProxyAgent(proxy, agentOptions)
: new protocol.Agent(agentOptions);
let headers: { [key: string]: string } = {};
for (const [key, value] of Object.entries(init?.headers || {})) {
headers[key] = value as string;
}
headers = {
...headers,
...requestOptions?.headers,
};
// Replace localhost with 127.0.0.1
if (url.hostname === "localhost") {
url.hostname = "127.0.0.1";
}
// add extra body properties if provided
let updatedBody: string | undefined = undefined;
try {
if (requestOptions?.extraBodyProperties && typeof init?.body === "string") {
const parsedBody = JSON.parse(init.body);
updatedBody = JSON.stringify({
...parsedBody,
...requestOptions.extraBodyProperties,
});
}
} catch (e) {
console.log("Unable to parse HTTP request body: ", e);
}
// fetch the request with the provided options
const resp = fetch(url, {
...init,
body: updatedBody ?? init?.body,
headers: headers,
agent: agent,
});
return resp;
}

View file

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

View file

@ -0,0 +1,113 @@
export async function* toAsyncIterable(
nodeReadable: NodeJS.ReadableStream,
): AsyncGenerator<Uint8Array> {
for await (const chunk of nodeReadable) {
yield chunk as Uint8Array;
}
}
export async function* streamResponse(
response: Response,
): AsyncGenerator<string> {
if (response.status !== 200) {
throw new Error(await response.text());
}
if (!response.body) {
throw new Error("No response body returned.");
}
// Get the major version of Node.js
const nodeMajorVersion = parseInt(process.versions.node.split(".")[0], 10);
if (nodeMajorVersion >= 20) {
// Use the new API for Node 20 and above
const stream = (ReadableStream as any).from(response.body);
for await (const chunk of stream.pipeThrough(
new TextDecoderStream("utf-8"),
)) {
yield chunk;
}
} else {
// Fallback for Node versions below 20
// Streaming with this method doesn't work as version 20+ does
const decoder = new TextDecoder("utf-8");
const nodeStream = response.body as unknown as NodeJS.ReadableStream;
for await (const chunk of toAsyncIterable(nodeStream)) {
yield decoder.decode(chunk, { stream: true });
}
}
}
function parseDataLine(line: string): any {
const json = line.startsWith("data: ")
? line.slice("data: ".length)
: line.slice("data:".length);
try {
const data = JSON.parse(json);
if (data.error) {
throw new Error(`Error streaming response: ${data.error}`);
}
return data;
} catch (e) {
throw new Error(`Malformed JSON sent from server: ${json}`);
}
}
function parseSseLine(line: string): { done: boolean; data: any } {
if (line.startsWith("data: [DONE]")) {
return { done: true, data: undefined };
}
if (line.startsWith("data:")) {
return { done: false, data: parseDataLine(line) };
}
if (line.startsWith(": ping")) {
return { done: true, data: undefined };
}
return { done: false, data: undefined };
}
export async function* streamSse(response: Response): AsyncGenerator<any> {
let buffer = "";
for await (const value of streamResponse(response)) {
buffer += value;
let position: number;
while ((position = buffer.indexOf("\n")) >= 0) {
const line = buffer.slice(0, position);
buffer = buffer.slice(position + 1);
const { done, data } = parseSseLine(line);
if (done) {
break;
}
if (data) {
yield data;
}
}
}
if (buffer.length > 0) {
const { done, data } = parseSseLine(buffer);
if (!done && data) {
yield data;
}
}
}
export async function* streamJSON(response: Response): AsyncGenerator<any> {
let buffer = "";
for await (const value of streamResponse(response)) {
buffer += value;
let position;
while ((position = buffer.indexOf("\n")) >= 0) {
const line = buffer.slice(0, position);
const data = JSON.parse(line);
yield data;
buffer = buffer.slice(position + 1);
}
}
}

View file

@ -0,0 +1,23 @@
{
"compilerOptions": {
"target": "ESNext",
"module": "NodeNext",
"useDefineForClassFields": true,
"lib": ["DOM", "ESNext"],
"allowJs": true,
"skipLibCheck": true,
"esModuleInterop": true,
"allowSyntheticDefaultImports": true,
"strict": true,
"forceConsistentCasingInFileNames": true,
"moduleResolution": "NodeNext",
"resolveJsonModule": true,
"isolatedModules": true,
"noEmitOnError": false,
"types": ["node"],
"outDir": "dist",
"declaration": true
// "sourceMap": true
},
"include": ["src/**/*"]
}

546
packages/openai-adapters/package-lock.json generated Normal file
View file

@ -0,0 +1,546 @@
{
"name": "@continuedev/openai-adapters",
"version": "1.0.3",
"lockfileVersion": 3,
"requires": true,
"packages": {
"": {
"name": "@continuedev/openai-adapters",
"version": "1.0.3",
"license": "Apache-2.0",
"dependencies": {
"@azure/openai": "^1.0.0-beta.12",
"@continuedev/config-types": "^1.0.5",
"@continuedev/fetch": "^1.0.1",
"node-fetch": "^3.3.2",
"openai": "^4.52.5"
},
"devDependencies": {
"@types/follow-redirects": "^1.14.4"
}
},
"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/@continuedev/config-types": {
"version": "1.0.5",
"resolved": "https://registry.npmjs.org/@continuedev/config-types/-/config-types-1.0.5.tgz",
"integrity": "sha512-Uv3JWKmpgSo9cMhZb2hWoJgR2ezuAn3CenEziWT/5d7mddPLzvuuHgFX6aDjLVVMojS1ul0rpfAd2LGxEb6nDQ==",
"dependencies": {
"zod": "^3.23.8"
}
},
"node_modules/@continuedev/fetch": {
"version": "1.0.1",
"resolved": "https://registry.npmjs.org/@continuedev/fetch/-/fetch-1.0.1.tgz",
"integrity": "sha512-vUFyP48WxdeAoVJUmN0nzk5FCiGfMWiW5SZEvJoSmzJMigHEfbsW/2kRCI9hu9LFRw4drN+Wo3fktG7Lb1MabA==",
"dependencies": {
"@continuedev/config-types": "^1.0.5",
"follow-redirects": "^1.15.6",
"http-proxy-agent": "^7.0.2",
"https-proxy-agent": "^7.0.5",
"node-fetch": "^3.3.2"
}
},
"node_modules/@types/follow-redirects": {
"version": "1.14.4",
"resolved": "https://registry.npmjs.org/@types/follow-redirects/-/follow-redirects-1.14.4.tgz",
"integrity": "sha512-GWXfsD0Jc1RWiFmMuMFCpXMzi9L7oPDVwxUnZdg89kDNnqsRfUKXEtUYtA98A6lig1WXH/CYY/fvPW9HuN5fTA==",
"dev": true,
"dependencies": {
"@types/node": "*"
}
},
"node_modules/@types/node": {
"version": "18.19.39",
"resolved": "https://registry.npmjs.org/@types/node/-/node-18.19.39.tgz",
"integrity": "sha512-nPwTRDKUctxw3di5b4TfT3I0sWDiWoPQCZjXhvdkINntwr8lcoVCKsTgnXeRubKIlfnV+eN/HYk6Jb40tbcEAQ==",
"dependencies": {
"undici-types": "~5.26.4"
}
},
"node_modules/@types/node-fetch": {
"version": "2.6.11",
"resolved": "https://registry.npmjs.org/@types/node-fetch/-/node-fetch-2.6.11.tgz",
"integrity": "sha512-24xFj9R5+rfQJLRyM56qh+wnVSYhyXC2tkoBndtY0U+vubqNsYXGjufB2nn8Q6gt0LrARwL6UBtMCSVCwl4B1g==",
"dependencies": {
"@types/node": "*",
"form-data": "^4.0.0"
}
},
"node_modules/abort-controller": {
"version": "3.0.0",
"resolved": "https://registry.npmjs.org/abort-controller/-/abort-controller-3.0.0.tgz",
"integrity": "sha512-h8lQ8tacZYnR3vNQTgibj+tODHI5/+l06Au2Pcriv/Gmet0eaj4TwWH41sO9wnHDiQsEj19q0drzdWdeAHtweg==",
"dependencies": {
"event-target-shim": "^5.0.0"
},
"engines": {
"node": ">=6.5"
}
},
"node_modules/agent-base": {
"version": "7.1.1",
"resolved": "https://registry.npmjs.org/agent-base/-/agent-base-7.1.1.tgz",
"integrity": "sha512-H0TSyFNDMomMNJQBn8wFV5YC/2eJ+VXECwOadZJT554xP6cODZHPX3H9QMQECxvrgiSOP1pHjy1sMWQVYJOUOA==",
"dependencies": {
"debug": "^4.3.4"
},
"engines": {
"node": ">= 14"
}
},
"node_modules/agentkeepalive": {
"version": "4.5.0",
"resolved": "https://registry.npmjs.org/agentkeepalive/-/agentkeepalive-4.5.0.tgz",
"integrity": "sha512-5GG/5IbQQpC9FpkRGsSvZI5QYeSCzlJHdpBQntCsuTOxhKD8lqKhrleg2Yi7yvMIf82Ycmmqln9U8V9qwEiJew==",
"dependencies": {
"humanize-ms": "^1.2.1"
},
"engines": {
"node": ">= 8.0.0"
}
},
"node_modules/asynckit": {
"version": "0.4.0",
"resolved": "https://registry.npmjs.org/asynckit/-/asynckit-0.4.0.tgz",
"integrity": "sha512-Oei9OH4tRh0YqU3GxhX79dM/mwVgvbZJaSNaRk+bshkj0S5cfHcgYakreBjrHwatXKbz+IoIdYLxrKim2MjW0Q=="
},
"node_modules/combined-stream": {
"version": "1.0.8",
"resolved": "https://registry.npmjs.org/combined-stream/-/combined-stream-1.0.8.tgz",
"integrity": "sha512-FQN4MRfuJeHf7cBbBMJFXhKSDq+2kAArBlmRBvcvFE5BB1HZKXtSFASDhdlz9zOYwxh8lDdnvmMOe/+5cdoEdg==",
"dependencies": {
"delayed-stream": "~1.0.0"
},
"engines": {
"node": ">= 0.8"
}
},
"node_modules/data-uri-to-buffer": {
"version": "4.0.1",
"resolved": "https://registry.npmjs.org/data-uri-to-buffer/-/data-uri-to-buffer-4.0.1.tgz",
"integrity": "sha512-0R9ikRb668HB7QDxT1vkpuUBtqc53YyAwMwGeUFKRojY/NWKvdZ+9UYtRfGmhqNbRkTSVpMbmyhXipFFv2cb/A==",
"engines": {
"node": ">= 12"
}
},
"node_modules/debug": {
"version": "4.3.5",
"resolved": "https://registry.npmjs.org/debug/-/debug-4.3.5.tgz",
"integrity": "sha512-pt0bNEmneDIvdL1Xsd9oDQ/wrQRkXDT4AUWlNZNPKvW5x/jyO9VFXkJUP07vQ2upmw5PlaITaPKc31jK13V+jg==",
"dependencies": {
"ms": "2.1.2"
},
"engines": {
"node": ">=6.0"
},
"peerDependenciesMeta": {
"supports-color": {
"optional": true
}
}
},
"node_modules/debug/node_modules/ms": {
"version": "2.1.2",
"resolved": "https://registry.npmjs.org/ms/-/ms-2.1.2.tgz",
"integrity": "sha512-sGkPx+VjMtmA6MX27oA4FBFELFCZZ4S4XqeGOXCv68tT+jb3vk/RyaKWP0PTKyWtmLSM0b+adUTEvbs1PEaH2w=="
},
"node_modules/delayed-stream": {
"version": "1.0.0",
"resolved": "https://registry.npmjs.org/delayed-stream/-/delayed-stream-1.0.0.tgz",
"integrity": "sha512-ZySD7Nf91aLB0RxL4KGrKHBXl7Eds1DAmEdcoVawXnLD7SDhpNgtuII2aAkg7a7QS41jxPSZ17p4VdGnMHk3MQ==",
"engines": {
"node": ">=0.4.0"
}
},
"node_modules/event-target-shim": {
"version": "5.0.1",
"resolved": "https://registry.npmjs.org/event-target-shim/-/event-target-shim-5.0.1.tgz",
"integrity": "sha512-i/2XbnSz/uxRCU6+NdVJgKWDTM427+MqYbkQzD321DuCQJUqOuJKIA0IM2+W2xtYHdKOmZ4dR6fExsd4SXL+WQ==",
"engines": {
"node": ">=6"
}
},
"node_modules/fetch-blob": {
"version": "3.2.0",
"resolved": "https://registry.npmjs.org/fetch-blob/-/fetch-blob-3.2.0.tgz",
"integrity": "sha512-7yAQpD2UMJzLi1Dqv7qFYnPbaPx7ZfFK6PiIxQ4PfkGPyNyl2Ugx+a/umUonmKqjhM4DnfbMvdX6otXq83soQQ==",
"funding": [
{
"type": "github",
"url": "https://github.com/sponsors/jimmywarting"
},
{
"type": "paypal",
"url": "https://paypal.me/jimmywarting"
}
],
"dependencies": {
"node-domexception": "^1.0.0",
"web-streams-polyfill": "^3.0.3"
},
"engines": {
"node": "^12.20 || >= 14.13"
}
},
"node_modules/follow-redirects": {
"version": "1.15.6",
"resolved": "https://registry.npmjs.org/follow-redirects/-/follow-redirects-1.15.6.tgz",
"integrity": "sha512-wWN62YITEaOpSK584EZXJafH1AGpO8RVgElfkuXbTOrPX4fIfOyEpW/CsiNd8JdYrAoOvafRTOEnvsO++qCqFA==",
"funding": [
{
"type": "individual",
"url": "https://github.com/sponsors/RubenVerborgh"
}
],
"engines": {
"node": ">=4.0"
},
"peerDependenciesMeta": {
"debug": {
"optional": true
}
}
},
"node_modules/form-data": {
"version": "4.0.0",
"resolved": "https://registry.npmjs.org/form-data/-/form-data-4.0.0.tgz",
"integrity": "sha512-ETEklSGi5t0QMZuiXoA/Q6vcnxcLQP5vdugSpuAyi6SVGi2clPPp+xgEhuMaHC+zGgn31Kd235W35f7Hykkaww==",
"dependencies": {
"asynckit": "^0.4.0",
"combined-stream": "^1.0.8",
"mime-types": "^2.1.12"
},
"engines": {
"node": ">= 6"
}
},
"node_modules/form-data-encoder": {
"version": "1.7.2",
"resolved": "https://registry.npmjs.org/form-data-encoder/-/form-data-encoder-1.7.2.tgz",
"integrity": "sha512-qfqtYan3rxrnCk1VYaA4H+Ms9xdpPqvLZa6xmMgFvhO32x7/3J/ExcTd6qpxM0vH2GdMI+poehyBZvqfMTto8A=="
},
"node_modules/formdata-node": {
"version": "4.4.1",
"resolved": "https://registry.npmjs.org/formdata-node/-/formdata-node-4.4.1.tgz",
"integrity": "sha512-0iirZp3uVDjVGt9p49aTaqjk84TrglENEDuqfdlZQ1roC9CWlPk6Avf8EEnZNcAqPonwkG35x4n3ww/1THYAeQ==",
"dependencies": {
"node-domexception": "1.0.0",
"web-streams-polyfill": "4.0.0-beta.3"
},
"engines": {
"node": ">= 12.20"
}
},
"node_modules/formdata-node/node_modules/web-streams-polyfill": {
"version": "4.0.0-beta.3",
"resolved": "https://registry.npmjs.org/web-streams-polyfill/-/web-streams-polyfill-4.0.0-beta.3.tgz",
"integrity": "sha512-QW95TCTaHmsYfHDybGMwO5IJIM93I/6vTRk+daHTWFPhwh+C8Cg7j7XyKrwrj8Ib6vYXe0ocYNrmzY4xAAN6ug==",
"engines": {
"node": ">= 14"
}
},
"node_modules/formdata-polyfill": {
"version": "4.0.10",
"resolved": "https://registry.npmjs.org/formdata-polyfill/-/formdata-polyfill-4.0.10.tgz",
"integrity": "sha512-buewHzMvYL29jdeQTVILecSaZKnt/RJWjoZCF5OW60Z67/GmSLBkOFM7qh1PI3zFNtJbaZL5eQu1vLfazOwj4g==",
"dependencies": {
"fetch-blob": "^3.1.2"
},
"engines": {
"node": ">=12.20.0"
}
},
"node_modules/http-proxy-agent": {
"version": "7.0.2",
"resolved": "https://registry.npmjs.org/http-proxy-agent/-/http-proxy-agent-7.0.2.tgz",
"integrity": "sha512-T1gkAiYYDWYx3V5Bmyu7HcfcvL7mUrTWiM6yOfa3PIphViJ/gFPbvidQ+veqSOHci/PxBcDabeUNCzpOODJZig==",
"dependencies": {
"agent-base": "^7.1.0",
"debug": "^4.3.4"
},
"engines": {
"node": ">= 14"
}
},
"node_modules/https-proxy-agent": {
"version": "7.0.5",
"resolved": "https://registry.npmjs.org/https-proxy-agent/-/https-proxy-agent-7.0.5.tgz",
"integrity": "sha512-1e4Wqeblerz+tMKPIq2EMGiiWW1dIjZOksyHWSUm1rmuvw/how9hBHZ38lAGj5ID4Ik6EdkOw7NmWPy6LAwalw==",
"dependencies": {
"agent-base": "^7.0.2",
"debug": "4"
},
"engines": {
"node": ">= 14"
}
},
"node_modules/humanize-ms": {
"version": "1.2.1",
"resolved": "https://registry.npmjs.org/humanize-ms/-/humanize-ms-1.2.1.tgz",
"integrity": "sha512-Fl70vYtsAFb/C06PTS9dZBo7ihau+Tu/DNCk/OyHhea07S+aeMWpFFkUaXRa8fI+ScZbEI8dfSxwY7gxZ9SAVQ==",
"dependencies": {
"ms": "^2.0.0"
}
},
"node_modules/mime-db": {
"version": "1.52.0",
"resolved": "https://registry.npmjs.org/mime-db/-/mime-db-1.52.0.tgz",
"integrity": "sha512-sPU4uV7dYlvtWJxwwxHD0PuihVNiE7TyAbQ5SWxDCB9mUYvOgroQOwYQQOKPJ8CIbE+1ETVlOoK1UC2nU3gYvg==",
"engines": {
"node": ">= 0.6"
}
},
"node_modules/mime-types": {
"version": "2.1.35",
"resolved": "https://registry.npmjs.org/mime-types/-/mime-types-2.1.35.tgz",
"integrity": "sha512-ZDY+bPm5zTTF+YpCrAU9nK0UgICYPT0QtT1NZWFv4s++TNkcgVaT0g6+4R2uI4MjQjzysHB1zxuWL50hzaeXiw==",
"dependencies": {
"mime-db": "1.52.0"
},
"engines": {
"node": ">= 0.6"
}
},
"node_modules/ms": {
"version": "2.1.3",
"resolved": "https://registry.npmjs.org/ms/-/ms-2.1.3.tgz",
"integrity": "sha512-6FlzubTLZG3J2a/NVCAleEhjzq5oxgHyaCU9yYXvcLsvoVaHJq/s5xXI6/XXP6tz7R9xAOtHnSO/tXtF3WRTlA=="
},
"node_modules/node-domexception": {
"version": "1.0.0",
"resolved": "https://registry.npmjs.org/node-domexception/-/node-domexception-1.0.0.tgz",
"integrity": "sha512-/jKZoMpw0F8GRwl4/eLROPA3cfcXtLApP0QzLmUT/HuPCZWyB7IY9ZrMeKw2O/nFIqPQB3PVM9aYm0F312AXDQ==",
"funding": [
{
"type": "github",
"url": "https://github.com/sponsors/jimmywarting"
},
{
"type": "github",
"url": "https://paypal.me/jimmywarting"
}
],
"engines": {
"node": ">=10.5.0"
}
},
"node_modules/node-fetch": {
"version": "3.3.2",
"resolved": "https://registry.npmjs.org/node-fetch/-/node-fetch-3.3.2.tgz",
"integrity": "sha512-dRB78srN/l6gqWulah9SrxeYnxeddIG30+GOqK/9OlLVyLg3HPnr6SqOWTWOXKRwC2eGYCkZ59NNuSgvSrpgOA==",
"dependencies": {
"data-uri-to-buffer": "^4.0.0",
"fetch-blob": "^3.1.4",
"formdata-polyfill": "^4.0.10"
},
"engines": {
"node": "^12.20.0 || ^14.13.1 || >=16.0.0"
},
"funding": {
"type": "opencollective",
"url": "https://opencollective.com/node-fetch"
}
},
"node_modules/openai": {
"version": "4.52.5",
"resolved": "https://registry.npmjs.org/openai/-/openai-4.52.5.tgz",
"integrity": "sha512-qqH8GsyPE3z06took/2uWOGqRcrZNlRoPAsihpg4jsl0+2Dfelnw6HDDMep0EI2Cfzw75nn3vHRZehep/IZzxg==",
"dependencies": {
"@types/node": "^18.11.18",
"@types/node-fetch": "^2.6.4",
"abort-controller": "^3.0.0",
"agentkeepalive": "^4.2.1",
"form-data-encoder": "1.7.2",
"formdata-node": "^4.3.2",
"node-fetch": "^2.6.7",
"web-streams-polyfill": "^3.2.1"
},
"bin": {
"openai": "bin/cli"
}
},
"node_modules/openai/node_modules/node-fetch": {
"version": "2.7.0",
"resolved": "https://registry.npmjs.org/node-fetch/-/node-fetch-2.7.0.tgz",
"integrity": "sha512-c4FRfUm/dbcWZ7U+1Wq0AwCyFL+3nt2bEw05wfxSz+DWpWsitgmSgYmy2dQdWyKC1694ELPqMs/YzUSNozLt8A==",
"dependencies": {
"whatwg-url": "^5.0.0"
},
"engines": {
"node": "4.x || >=6.0.0"
},
"peerDependencies": {
"encoding": "^0.1.0"
},
"peerDependenciesMeta": {
"encoding": {
"optional": true
}
}
},
"node_modules/tr46": {
"version": "0.0.3",
"resolved": "https://registry.npmjs.org/tr46/-/tr46-0.0.3.tgz",
"integrity": "sha512-N3WMsuqV66lT30CrXNbEjx4GEwlow3v6rr4mCcv6prnfwhS01rkgyFdjPNBYd9br7LpXV1+Emh01fHnq2Gdgrw=="
},
"node_modules/tslib": {
"version": "2.6.3",
"resolved": "https://registry.npmjs.org/tslib/-/tslib-2.6.3.tgz",
"integrity": "sha512-xNvxJEOUiWPGhUuUdQgAJPKOOJfGnIyKySOc09XkKsgdUV/3E2zvwZYdejjmRgPCgcym1juLH3226yA7sEFJKQ=="
},
"node_modules/undici-types": {
"version": "5.26.5",
"resolved": "https://registry.npmjs.org/undici-types/-/undici-types-5.26.5.tgz",
"integrity": "sha512-JlCMO+ehdEIKqlFxk6IfVoAUVmgz7cU7zD/h9XZ0qzeosSHmUJVOzSQvvYSYWXkFXC+IfLKSIffhv0sVZup6pA=="
},
"node_modules/web-streams-polyfill": {
"version": "3.3.3",
"resolved": "https://registry.npmjs.org/web-streams-polyfill/-/web-streams-polyfill-3.3.3.tgz",
"integrity": "sha512-d2JWLCivmZYTSIoge9MsgFCZrt571BikcWGYkjC1khllbTeDlGqZ2D8vD8E/lJa8WGWbb7Plm8/XJYV7IJHZZw==",
"engines": {
"node": ">= 8"
}
},
"node_modules/webidl-conversions": {
"version": "3.0.1",
"resolved": "https://registry.npmjs.org/webidl-conversions/-/webidl-conversions-3.0.1.tgz",
"integrity": "sha512-2JAn3z8AR6rjK8Sm8orRC0h/bcl/DqL7tRPdGZ4I1CjdF+EaMLmYxBHyXuKL849eucPFhvBoxMsflfOb8kxaeQ=="
},
"node_modules/whatwg-url": {
"version": "5.0.0",
"resolved": "https://registry.npmjs.org/whatwg-url/-/whatwg-url-5.0.0.tgz",
"integrity": "sha512-saE57nupxk6v3HY35+jzBwYa0rKSy0XR8JSxZPwgLr7ys0IBzhGviA1/TUGJLmSVqs8pb9AnvICXEuOHLprYTw==",
"dependencies": {
"tr46": "~0.0.3",
"webidl-conversions": "^3.0.0"
}
},
"node_modules/zod": {
"version": "3.23.8",
"resolved": "https://registry.npmjs.org/zod/-/zod-3.23.8.tgz",
"integrity": "sha512-XBx9AXhXktjUqnepgTiE5flcKIYWi/rme0Eaj+5Y0lftuGBq+jyRu/md4WnuxqgP1ubdpNCsYEYPxrzVHD8d6g==",
"funding": {
"url": "https://github.com/sponsors/colinhacks"
}
}
}
}

View file

@ -0,0 +1,24 @@
{
"name": "@continuedev/openai-adapters",
"version": "1.0.4",
"description": "",
"main": "dist/index.js",
"types": "dist/index.d.ts",
"type": "module",
"scripts": {
"test": "echo \"Error: no test specified\" && exit 1",
"build": "tsc"
},
"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/fetch": "^1.0.1",
"node-fetch": "^3.3.2",
"openai": "^4.52.5"
},
"devDependencies": {
"@types/follow-redirects": "^1.14.4"
}
}

View file

@ -0,0 +1,220 @@
import { AzureKeyCredential, OpenAIClient } from "@azure/openai";
import { ModelDescription } from "@continuedev/config-types/src/index.js";
import dotenv from "dotenv";
import {
Completion,
CompletionCreateParamsNonStreaming,
CompletionCreateParamsStreaming,
} from "openai/resources/completions.js";
import {
ChatCompletion,
ChatCompletionChunk,
ChatCompletionCreateParamsNonStreaming,
ChatCompletionCreateParamsStreaming,
} from "openai/resources/index.js";
import { BaseLlmApi, FimCreateParamsStreaming } 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;
private config: ModelDescription;
constructor(config: ModelDescription) {
this.config = config;
let proxyOptions;
const PROXY = HTTPS_PROXY ?? HTTP_PROXY;
if (PROXY) {
const url = new URL(PROXY);
proxyOptions = {
host: url.hostname,
port: Number(url.port),
};
}
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,
) {
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,
};
}
async chatCompletionNonStream(
body: ChatCompletionCreateParamsNonStreaming,
): Promise<ChatCompletion> {
const completion = await this.client.getChatCompletions(
this.config.model,
body.messages,
this._bodyToOptions(body),
);
return {
...completion,
object: "chat.completion",
model: this.config.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,
},
})),
};
}
async *chatCompletionStream(
body: ChatCompletionCreateParamsStreaming,
): AsyncGenerator<ChatCompletionChunk> {
const events = await this.client.streamChatCompletions(
this.config.model,
body.messages,
this._bodyToOptions(body),
);
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: this.config.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,
): Promise<Completion> {
const { prompt, logprobs, ...restOfBody } = body;
const messages = [
{
role: "user" as any,
content: prompt as any,
},
];
const resp = await this.chatCompletionNonStream({
messages,
...restOfBody,
});
return {
...resp,
object: "text_completion",
choices: resp.choices.map((choice) => ({
...choice,
text: choice.message.content ?? "",
finish_reason: "stop",
logprobs: null,
})),
};
}
async *completionStream(
body: CompletionCreateParamsStreaming,
): AsyncGenerator<Completion> {
const { prompt, logprobs, ...restOfBody } = body;
const messages = [
{
role: "user" as any,
content: prompt as any,
},
];
for await (const event of this.chatCompletionStream({
messages,
...restOfBody,
})) {
yield {
...event,
object: "text_completion",
choices: event.choices.map((choice) => ({
...choice,
text: choice.delta.content ?? "",
finish_reason: "stop",
logprobs: null,
})),
};
}
}
fimStream(
body: FimCreateParamsStreaming,
): AsyncGenerator<ChatCompletionChunk> {
throw new Error(
"Azure OpenAI does not support fill-in-the-middle (FIM) completions.",
);
}
}

View file

@ -0,0 +1,84 @@
import { ModelDescription } from "@continuedev/config-types";
import { streamSse } from "@continuedev/fetch";
import fetch from "node-fetch";
import { OpenAI } from "openai/index.mjs";
import {
ChatCompletion,
ChatCompletionChunk,
ChatCompletionCreateParamsNonStreaming,
ChatCompletionCreateParamsStreaming,
Completion,
CompletionCreateParamsNonStreaming,
CompletionCreateParamsStreaming,
} from "openai/resources/index.mjs";
import { BaseLlmApi, FimCreateParamsStreaming } from "./base.js";
export class OpenAIApi implements BaseLlmApi {
openai: OpenAI;
constructor(protected config: ModelDescription) {
this.openai = new OpenAI({
apiKey: config.apiKey,
baseURL: config.apiBase,
});
}
async chatCompletionNonStream(
body: ChatCompletionCreateParamsNonStreaming,
): Promise<ChatCompletion> {
const response = await this.openai.chat.completions.create(body);
return response;
}
async *chatCompletionStream(
body: ChatCompletionCreateParamsStreaming,
): AsyncGenerator<ChatCompletionChunk, any, unknown> {
const response = await this.openai.chat.completions.create(body);
for await (const result of response) {
yield result;
}
}
async completionNonStream(
body: CompletionCreateParamsNonStreaming,
): Promise<Completion> {
const response = await this.openai.completions.create(body);
return response;
}
async *completionStream(
body: CompletionCreateParamsStreaming,
): AsyncGenerator<Completion, any, unknown> {
const response = await this.openai.completions.create(body);
for await (const result of response) {
yield result;
}
}
async *fimStream(
body: FimCreateParamsStreaming,
): AsyncGenerator<ChatCompletionChunk, any, unknown> {
const endpoint = new URL("fim/completions", this.config.apiBase);
const resp = await fetch(endpoint, {
method: "POST",
body: JSON.stringify({
model: body.model,
prompt: body.prompt,
suffix: body.suffix,
max_tokens: body.max_tokens,
temperature: body.temperature,
top_p: body.top_p,
frequency_penalty: body.frequency_penalty,
presence_penalty: body.presence_penalty,
stop: body.stop,
stream: true,
}),
headers: {
"Content-Type": "application/json",
Accept: "application/json",
"x-api-key": this.config.apiKey ?? "",
Authorization: `Bearer ${this.config.apiKey}`,
},
});
for await (const chunk of streamSse(resp as any)) {
if (chunk.choices && chunk.choices.length > 0) {
yield chunk;
}
}
}
}

View file

@ -0,0 +1,41 @@
import {
ChatCompletion,
ChatCompletionChunk,
ChatCompletionCreateParamsNonStreaming,
ChatCompletionCreateParamsStreaming,
Completion,
CompletionCreateParamsNonStreaming,
CompletionCreateParamsStreaming,
} from "openai/resources/index.mjs";
export interface FimCreateParamsStreaming
extends CompletionCreateParamsStreaming {
suffix: string;
}
export interface BaseLlmApi {
// Chat, no stream
chatCompletionNonStream(
body: ChatCompletionCreateParamsNonStreaming,
): Promise<ChatCompletion>;
// Chat, stream
chatCompletionStream(
body: ChatCompletionCreateParamsStreaming,
): AsyncGenerator<ChatCompletionChunk>;
// Completion, no stream
completionNonStream(
body: CompletionCreateParamsNonStreaming,
): Promise<Completion>;
// Completion, stream
completionStream(
body: CompletionCreateParamsStreaming,
): AsyncGenerator<Completion>;
// FIM, stream
fimStream(
body: FimCreateParamsStreaming,
): AsyncGenerator<ChatCompletionChunk>;
}

View file

@ -0,0 +1,30 @@
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";
dotenv.config();
export function constructLlmApi(config: ModelDescription): BaseLlmApi {
switch (config.provider) {
case "openai":
return new OpenAIApi(config);
case "azure":
return new AzureOpenAIApi(config);
default:
throw new Error(`Unsupported LLM API format: ${config.provider}`);
}
}
export {
type ChatCompletion,
type ChatCompletionChunk,
type ChatCompletionCreateParams,
type ChatCompletionCreateParamsNonStreaming,
type ChatCompletionCreateParamsStreaming,
type Completion,
type CompletionCreateParams,
type CompletionCreateParamsNonStreaming,
type CompletionCreateParamsStreaming,
} from "openai/resources/index.mjs";

View file

@ -0,0 +1,23 @@
{
"compilerOptions": {
"target": "ESNext",
"module": "NodeNext",
"useDefineForClassFields": true,
"lib": ["DOM", "ESNext"],
"allowJs": true,
"skipLibCheck": true,
"esModuleInterop": true,
"allowSyntheticDefaultImports": true,
"strict": true,
"forceConsistentCasingInFileNames": true,
"moduleResolution": "NodeNext",
"resolveJsonModule": true,
"isolatedModules": true,
"noEmitOnError": false,
"types": ["node"],
"outDir": "dist",
"declaration": true
// "sourceMap": true
},
"include": ["src/**/*"]
}