Merge branch 'main' into fix/check-mcp-available-attributes
This commit is contained in:
commit
6b402ea14e
220 changed files with 2904 additions and 3283 deletions
4
.github/workflows/main.yaml
vendored
4
.github/workflows/main.yaml
vendored
|
|
@ -49,11 +49,11 @@ jobs:
|
|||
platform: alpine
|
||||
arch: x64
|
||||
npm_config_arch: x64
|
||||
- os: macos-12 # should migrate this to the newer x64 version of macos-14
|
||||
- os: macos-13
|
||||
platform: darwin
|
||||
arch: x64
|
||||
npm_config_arch: x64
|
||||
- os: macos-12 # same here, especially
|
||||
- os: macos-13
|
||||
platform: darwin
|
||||
arch: arm64
|
||||
npm_config_arch: arm64
|
||||
|
|
|
|||
4
.github/workflows/preview.yaml
vendored
4
.github/workflows/preview.yaml
vendored
|
|
@ -49,11 +49,11 @@ jobs:
|
|||
platform: alpine
|
||||
arch: x64
|
||||
npm_config_arch: x64
|
||||
- os: macos-12 # should migrate this to the newer x64 version of macos-14
|
||||
- os: macos-13
|
||||
platform: darwin
|
||||
arch: x64
|
||||
npm_config_arch: x64
|
||||
- os: macos-12 # same here, especially
|
||||
- os: macos-13
|
||||
platform: darwin
|
||||
arch: arm64
|
||||
npm_config_arch: arm64
|
||||
|
|
|
|||
|
|
@ -59,6 +59,10 @@ export class CompletionProvider {
|
|||
return undefined;
|
||||
}
|
||||
|
||||
if (llm.model === undefined && llm.completionOptions?.model !== undefined) {
|
||||
llm.model = llm.completionOptions.model
|
||||
}
|
||||
|
||||
// Ignore empty API keys for Mistral since we currently write
|
||||
// a template provider without one during onboarding
|
||||
if (llm.providerName === "mistral" && llm.apiKey === "") {
|
||||
|
|
|
|||
|
|
@ -29,14 +29,23 @@ export class ImportDefinitionsService {
|
|||
return this.cache.get(filepath);
|
||||
}
|
||||
|
||||
private async _getFileInfo(filepath: string): Promise<FileInfo> {
|
||||
private async _getFileInfo(filepath: string): Promise<FileInfo | null> {
|
||||
const parser = await getParserForFile(filepath);
|
||||
if (!parser) {
|
||||
return {
|
||||
imports: {},
|
||||
};
|
||||
}
|
||||
const ast = parser.parse(await this.ide.readFile(filepath), undefined, {
|
||||
|
||||
let fileContents: string | undefined = undefined;
|
||||
try {
|
||||
fileContents = await this.ide.readFile(filepath);
|
||||
} catch (err) {
|
||||
// File removed
|
||||
return null;
|
||||
}
|
||||
|
||||
const ast = parser.parse(fileContents, undefined, {
|
||||
includedRanges: [
|
||||
{
|
||||
startIndex: 0,
|
||||
|
|
|
|||
|
|
@ -10,6 +10,7 @@ import {
|
|||
showWhateverWeHaveAtXMs,
|
||||
skipPrefixes,
|
||||
stopAtLines,
|
||||
stopAtLinesExact,
|
||||
stopAtRepeatingLines,
|
||||
stopAtSimilarLine,
|
||||
streamWithNewLines,
|
||||
|
|
@ -42,6 +43,12 @@ export class StreamTransformPipeline {
|
|||
let lineGenerator = streamLines(charGenerator);
|
||||
|
||||
lineGenerator = stopAtLines(lineGenerator, fullStop);
|
||||
const lineBelowCursor = this.getLineBelowCursor(helper);
|
||||
if (lineBelowCursor.trim() !== "") {
|
||||
lineGenerator = stopAtLinesExact(lineGenerator, fullStop, [
|
||||
lineBelowCursor,
|
||||
]);
|
||||
}
|
||||
lineGenerator = stopAtRepeatingLines(lineGenerator, fullStop);
|
||||
lineGenerator = avoidEmptyComments(
|
||||
lineGenerator,
|
||||
|
|
|
|||
|
|
@ -2,7 +2,6 @@ import { distance } from "fastest-levenshtein";
|
|||
|
||||
import { DiffLine } from "../../..";
|
||||
import { LineStream } from "../../../diff/util";
|
||||
import { BRACKETS, BRACKETS_REVERSE } from "../BracketMatchingService";
|
||||
|
||||
export type LineFilter = (args: {
|
||||
lines: LineStream;
|
||||
|
|
@ -270,6 +269,20 @@ export async function* stopAtLines(
|
|||
}
|
||||
}
|
||||
|
||||
export async function* stopAtLinesExact(
|
||||
stream: LineStream,
|
||||
fullStop: () => void,
|
||||
linesToStopAt: string[],
|
||||
): LineStream {
|
||||
for await (const line of stream) {
|
||||
if (linesToStopAt.some((stopAt) => line === stopAt)) {
|
||||
fullStop();
|
||||
break;
|
||||
}
|
||||
yield line;
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Filters a LineStream, skipping specified prefixes on the first line.
|
||||
* @param {LineStream} lines - The input stream of lines.
|
||||
|
|
|
|||
|
|
@ -810,8 +810,7 @@ func main() {}`,
|
|||
}`,
|
||||
expectedCompletion: `string
|
||||
State string
|
||||
ZipCode string
|
||||
}`,
|
||||
ZipCode string`,
|
||||
},
|
||||
|
||||
{
|
||||
|
|
@ -1118,8 +1117,7 @@ impl Calculator {
|
|||
self.result /= number;
|
||||
} else {
|
||||
println!("Cannot divide by zero.");
|
||||
}
|
||||
}`,
|
||||
}`,
|
||||
},
|
||||
{
|
||||
description: "Should autocomplete Rust struct definition",
|
||||
|
|
@ -1600,8 +1598,7 @@ interface User {
|
|||
age: number;
|
||||
}`,
|
||||
expectedCompletion: `mail: string;
|
||||
age: number;
|
||||
}`,
|
||||
age: number;`,
|
||||
},
|
||||
{
|
||||
description: "Should autocomplete TypeScript interface declarations",
|
||||
|
|
@ -1853,8 +1850,7 @@ let john = { FirstName = "John"; LastName = "Doe"; Age = 30 }`,
|
|||
Address: string
|
||||
}`,
|
||||
expectedCompletion: `
|
||||
Address: string
|
||||
}`,
|
||||
Address: string`,
|
||||
},
|
||||
|
||||
{
|
||||
|
|
|
|||
|
|
@ -1,7 +1,7 @@
|
|||
import fs from "node:fs";
|
||||
import path from "node:path";
|
||||
|
||||
import Mock from "../../../llm/llms/Mock";
|
||||
import MockLLM from "../../../llm/llms/Mock";
|
||||
import { testConfigHandler, testIde } from "../../../test/fixtures";
|
||||
import { CompletionProvider } from "../../CompletionProvider";
|
||||
import { AutocompleteInput } from "../../util/types";
|
||||
|
|
@ -30,7 +30,7 @@ export async function testAutocompleteFiltering(
|
|||
const { prefix, suffix } = parseFimExample(test.input);
|
||||
|
||||
// Setup necessary objects
|
||||
const llm = new Mock({
|
||||
const llm = new MockLLM({
|
||||
model: "mock",
|
||||
});
|
||||
llm.completion = test.llmOutput;
|
||||
|
|
|
|||
|
|
@ -3,6 +3,7 @@ import * as fs from "fs";
|
|||
import os from "os";
|
||||
import path from "path";
|
||||
|
||||
import { fetchwithRequestOptions } from "@continuedev/fetch";
|
||||
import * as JSONC from "comment-json";
|
||||
import * as tar from "tar";
|
||||
|
||||
|
|
@ -19,8 +20,8 @@ import {
|
|||
IDE,
|
||||
IdeSettings,
|
||||
IdeType,
|
||||
ILLM,
|
||||
ModelDescription,
|
||||
Reranker,
|
||||
RerankerDescription,
|
||||
SerializedContinueConfig,
|
||||
SlashCommand,
|
||||
|
|
@ -29,6 +30,7 @@ import {
|
|||
slashCommandFromDescription,
|
||||
slashFromCustomCommand,
|
||||
} from "../commands/index.js";
|
||||
import { AllRerankers } from "../context/allRerankers";
|
||||
import MCPConnectionSingleton from "../context/mcp";
|
||||
import CodebaseContextProvider from "../context/providers/CodebaseContextProvider";
|
||||
import ContinueProxyContextProvider from "../context/providers/ContinueProxyContextProvider";
|
||||
|
|
@ -36,30 +38,29 @@ import CustomContextProviderClass from "../context/providers/CustomContextProvid
|
|||
import FileContextProvider from "../context/providers/FileContextProvider";
|
||||
import { contextProviderClassFromName } from "../context/providers/index";
|
||||
import PromptFilesContextProvider from "../context/providers/PromptFilesContextProvider";
|
||||
import { AllRerankers } from "../context/rerankers/index";
|
||||
import { LLMReranker } from "../context/rerankers/llm";
|
||||
import { allEmbeddingsProviders } from "../indexing/embeddings";
|
||||
import TransformersJsEmbeddingsProvider from "../indexing/embeddings/TransformersJsEmbeddingsProvider";
|
||||
import { allEmbeddingsProviders } from "../indexing/allEmbeddingsProviders";
|
||||
import { BaseLLM } from "../llm";
|
||||
import { llmFromDescription } from "../llm/llms";
|
||||
import CustomLLMClass from "../llm/llms/CustomLLM";
|
||||
import FreeTrial from "../llm/llms/FreeTrial";
|
||||
import { LLMReranker } from "../llm/llms/llm";
|
||||
import TransformersJsEmbeddingsProvider from "../llm/llms/TransformersJsEmbeddingsProvider";
|
||||
import { allTools } from "../tools";
|
||||
import { copyOf } from "../util";
|
||||
import { fetchwithRequestOptions } from "../util/fetchWithOptions";
|
||||
import { GlobalContext } from "../util/GlobalContext";
|
||||
import mergeJson from "../util/merge";
|
||||
import {
|
||||
DEFAULT_CONFIG_TS_CONTENTS,
|
||||
getConfigJsPath,
|
||||
getConfigJsPathForRemote,
|
||||
getConfigJsonPath,
|
||||
getConfigJsonPathForRemote,
|
||||
getConfigJsPath,
|
||||
getConfigJsPathForRemote,
|
||||
getConfigTsPath,
|
||||
getContinueDotEnv,
|
||||
getEsbuildBinaryPath,
|
||||
readAllGlobalPromptFiles,
|
||||
} from "../util/paths";
|
||||
|
||||
import {
|
||||
defaultContextProvidersJetBrains,
|
||||
defaultContextProvidersVsCode,
|
||||
|
|
@ -470,7 +471,7 @@ async function intermediateToFinalConfig(
|
|||
}
|
||||
|
||||
// Reranker
|
||||
if (config.reranker && !(config.reranker as Reranker | undefined)?.rerank) {
|
||||
if (config.reranker && !(config.reranker as ILLM | undefined)?.rerank) {
|
||||
const { name, params } = config.reranker as RerankerDescription;
|
||||
const rerankerClass = AllRerankers[name];
|
||||
|
||||
|
|
@ -548,7 +549,7 @@ function finalToBrowserConfig(
|
|||
disableIndexing: final.disableIndexing,
|
||||
disableSessionTitles: final.disableSessionTitles,
|
||||
userToken: final.userToken,
|
||||
embeddingsProvider: final.embeddingsProvider?.id,
|
||||
embeddingsProvider: final.embeddingsProvider?.embeddingId,
|
||||
ui: final.ui,
|
||||
experimental: final.experimental,
|
||||
docs: final.docs,
|
||||
|
|
|
|||
|
|
@ -5,12 +5,10 @@ import {
|
|||
IdeSettings,
|
||||
SerializedContinueConfig,
|
||||
} from "../../";
|
||||
import { ContinueProxyReranker } from "../../context/rerankers/ContinueProxyReranker.js";
|
||||
import { ControlPlaneProxyInfo } from "../../control-plane/analytics/IAnalyticsProvider.js";
|
||||
import { ControlPlaneClient } from "../../control-plane/client.js";
|
||||
import { controlPlaneEnv } from "../../control-plane/env.js";
|
||||
import { TeamAnalytics } from "../../control-plane/TeamAnalytics.js";
|
||||
import ContinueProxyEmbeddingsProvider from "../../indexing/embeddings/ContinueProxyEmbeddingsProvider";
|
||||
import ContinueProxy from "../../llm/llms/stubs/ContinueProxy";
|
||||
import { Telemetry } from "../../util/posthog";
|
||||
import { TTS } from "../../util/tts";
|
||||
|
|
@ -111,13 +109,11 @@ async function injectControlPlaneProxyInfo(
|
|||
);
|
||||
|
||||
if (config.embeddingsProvider?.providerName === "continue-proxy") {
|
||||
(
|
||||
config.embeddingsProvider as ContinueProxyEmbeddingsProvider
|
||||
).controlPlaneProxyInfo = info;
|
||||
(config.embeddingsProvider as ContinueProxy).controlPlaneProxyInfo = info;
|
||||
}
|
||||
|
||||
if (config.reranker?.name === "continue-proxy") {
|
||||
(config.reranker as ContinueProxyReranker).controlPlaneProxyInfo = info;
|
||||
if (config.reranker?.providerName === "continue-proxy") {
|
||||
(config.reranker as ContinueProxy).controlPlaneProxyInfo = info;
|
||||
}
|
||||
|
||||
return config;
|
||||
|
|
|
|||
17
core/context/allRerankers.ts
Normal file
17
core/context/allRerankers.ts
Normal file
|
|
@ -0,0 +1,17 @@
|
|||
import Bedrock from "../llm/llms/Bedrock";
|
||||
import Cohere from "../llm/llms/Cohere";
|
||||
import FreeTrial from "../llm/llms/FreeTrial";
|
||||
import HuggingFaceTEI from "../llm/llms/HuggingFaceTEI";
|
||||
import { LLMReranker } from "../llm/llms/llm";
|
||||
import ContinueProxy from "../llm/llms/stubs/ContinueProxy";
|
||||
import Voyage from "../llm/llms/Voyage";
|
||||
|
||||
export const AllRerankers: { [key: string]: any } = {
|
||||
cohere: Cohere,
|
||||
bedrock: Bedrock,
|
||||
llm: LLMReranker,
|
||||
voyage: Voyage,
|
||||
"free-trial": FreeTrial,
|
||||
"huggingface-tei": HuggingFaceTEI,
|
||||
"continue-proxy": ContinueProxy,
|
||||
};
|
||||
|
|
@ -1,44 +0,0 @@
|
|||
import fetch from "node-fetch";
|
||||
|
||||
import { ControlPlaneProxyInfo } from "../../control-plane/analytics/IAnalyticsProvider.js";
|
||||
import { Chunk, Reranker } from "../../index.js";
|
||||
|
||||
export class ContinueProxyReranker implements Reranker {
|
||||
name = "continue-proxy";
|
||||
|
||||
private _controlPlaneProxyInfo?: ControlPlaneProxyInfo;
|
||||
|
||||
set controlPlaneProxyInfo(value: ControlPlaneProxyInfo) {
|
||||
this.params.apiKey = value.workOsAccessToken!;
|
||||
this._controlPlaneProxyInfo = value;
|
||||
}
|
||||
|
||||
constructor(
|
||||
private readonly params: {
|
||||
apiKey: string;
|
||||
model?: string;
|
||||
},
|
||||
) {}
|
||||
|
||||
async rerank(query: string, chunks: Chunk[]): Promise<number[]> {
|
||||
const url = new URL(
|
||||
"openai/v1/rerank",
|
||||
this._controlPlaneProxyInfo?.controlPlaneProxyUrl,
|
||||
);
|
||||
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);
|
||||
}
|
||||
}
|
||||
|
|
@ -1,99 +0,0 @@
|
|||
import {
|
||||
BedrockRuntimeClient,
|
||||
InvokeModelCommand,
|
||||
} from "@aws-sdk/client-bedrock-runtime";
|
||||
import { fromIni } from "@aws-sdk/credential-providers";
|
||||
import { Chunk, Reranker, RerankerName } from "../../index.js";
|
||||
|
||||
export class BedrockReranker implements Reranker {
|
||||
name: RerankerName = "bedrock";
|
||||
|
||||
static defaultOptions = {
|
||||
region: "us-east-1",
|
||||
model: "amazon.rerank-v1:0",
|
||||
profile: "bedrock",
|
||||
};
|
||||
|
||||
private supportedModels = ["amazon.rerank-v1:0", "cohere.rerank-v3-5:0"];
|
||||
|
||||
constructor(
|
||||
private readonly params: {
|
||||
region?: string;
|
||||
model?: string;
|
||||
profile?: string;
|
||||
} = {},
|
||||
) {
|
||||
if (params.model && !this.supportedModels.includes(params.model)) {
|
||||
throw new Error(
|
||||
`Unsupported model: ${params.model}. Supported models are: ${this.supportedModels.join(", ")}`,
|
||||
);
|
||||
}
|
||||
}
|
||||
|
||||
async rerank(query: string, chunks: Chunk[]): Promise<number[]> {
|
||||
if (!query || !chunks.length) {
|
||||
throw new Error("Query and chunks must not be empty");
|
||||
}
|
||||
|
||||
try {
|
||||
const credentials = await this._getCredentials();
|
||||
const client = new BedrockRuntimeClient({
|
||||
region: this.params.region ?? BedrockReranker.defaultOptions.region,
|
||||
credentials,
|
||||
});
|
||||
|
||||
const model = this.params.model ?? BedrockReranker.defaultOptions.model;
|
||||
|
||||
// Base payload for both models
|
||||
const payload: any = {
|
||||
query: query,
|
||||
documents: chunks.map((chunk) => chunk.content),
|
||||
top_n: chunks.length,
|
||||
};
|
||||
|
||||
// Add api_version for Cohere model
|
||||
if (model.startsWith("cohere.rerank")) {
|
||||
payload.api_version = 2;
|
||||
}
|
||||
|
||||
const input = {
|
||||
body: JSON.stringify(payload),
|
||||
modelId: model,
|
||||
accept: "*/*",
|
||||
contentType: "application/json",
|
||||
};
|
||||
|
||||
const command = new InvokeModelCommand(input);
|
||||
const response = await client.send(command);
|
||||
|
||||
if (!response.body) {
|
||||
throw new Error("Empty response received from Bedrock");
|
||||
}
|
||||
|
||||
const responseBody = JSON.parse(new TextDecoder().decode(response.body));
|
||||
|
||||
// Sort results by index to maintain original order
|
||||
return responseBody.results
|
||||
.sort((a: any, b: any) => a.index - b.index)
|
||||
.map((result: any) => result.relevance_score);
|
||||
} catch (error) {
|
||||
console.error("Error in BedrockReranker.rerank:", error);
|
||||
throw error;
|
||||
}
|
||||
}
|
||||
|
||||
private async _getCredentials() {
|
||||
try {
|
||||
const credentials = await fromIni({
|
||||
profile: this.params.profile ?? BedrockReranker.defaultOptions.profile,
|
||||
ignoreCache: true,
|
||||
})();
|
||||
return credentials;
|
||||
} catch (e) {
|
||||
console.warn(
|
||||
`AWS profile with name ${this.params.profile ?? BedrockReranker.defaultOptions.profile} not found in ~/.aws/credentials, using default profile`,
|
||||
);
|
||||
return await fromIni()();
|
||||
}
|
||||
}
|
||||
}
|
||||
|
|
@ -1,48 +0,0 @@
|
|||
import fetch from "node-fetch";
|
||||
|
||||
import { Chunk, Reranker } from "../../index.js";
|
||||
|
||||
export class CohereReranker implements Reranker {
|
||||
name = "cohere";
|
||||
|
||||
static defaultOptions = {
|
||||
apiBase: "https://api.cohere.ai/v1/",
|
||||
model: "rerank-english-v3.0",
|
||||
};
|
||||
|
||||
constructor(
|
||||
private readonly params: {
|
||||
apiBase?: string;
|
||||
apiKey: string;
|
||||
model?: string;
|
||||
},
|
||||
) {}
|
||||
|
||||
async rerank(query: string, chunks: Chunk[]): Promise<number[]> {
|
||||
let apiBase = this.params.apiBase ?? CohereReranker.defaultOptions.apiBase;
|
||||
if (!apiBase.endsWith("/")) {
|
||||
apiBase += "/";
|
||||
}
|
||||
|
||||
const resp = await fetch(new URL("rerank", apiBase), {
|
||||
method: "POST",
|
||||
headers: {
|
||||
Authorization: `Bearer ${this.params.apiKey}`,
|
||||
"Content-Type": "application/json",
|
||||
},
|
||||
body: JSON.stringify({
|
||||
model: this.params.model ?? CohereReranker.defaultOptions.model,
|
||||
query,
|
||||
documents: chunks.map((chunk) => chunk.content),
|
||||
}),
|
||||
});
|
||||
|
||||
if (!resp.ok) {
|
||||
throw new Error(await resp.text());
|
||||
}
|
||||
|
||||
const data = (await resp.json()) as any;
|
||||
const results = data.results.sort((a: any, b: any) => a.index - b.index);
|
||||
return results.map((result: any) => result.relevance_score);
|
||||
}
|
||||
}
|
||||
|
|
@ -1,34 +0,0 @@
|
|||
import fetch from "node-fetch";
|
||||
|
||||
import { getHeaders } from "../../continueServer/stubs/headers.js";
|
||||
import { TRIAL_PROXY_URL } from "../../control-plane/client.js";
|
||||
import { Chunk, Reranker } from "../../index.js";
|
||||
|
||||
export class FreeTrialReranker implements Reranker {
|
||||
name = "free-trial";
|
||||
|
||||
async rerank(query: string, chunks: Chunk[]): Promise<number[]> {
|
||||
if (chunks.length === 0) {
|
||||
return [];
|
||||
}
|
||||
const resp = await fetch(new URL("rerank", TRIAL_PROXY_URL), {
|
||||
method: "POST",
|
||||
headers: {
|
||||
"Content-Type": "application/json",
|
||||
...(await getHeaders()),
|
||||
},
|
||||
body: JSON.stringify({
|
||||
query,
|
||||
documents: chunks.map((chunk) => chunk.content),
|
||||
}),
|
||||
});
|
||||
|
||||
if (!resp.ok) {
|
||||
throw new Error(await resp.text());
|
||||
}
|
||||
|
||||
const data = (await resp.json()) as any;
|
||||
const results = data.sort((a: any, b: any) => a.index - b.index);
|
||||
return results.map((result: any) => result.relevance_score);
|
||||
}
|
||||
}
|
||||
|
|
@ -1,19 +0,0 @@
|
|||
import { RerankerName } from "../../index.js";
|
||||
|
||||
import { BedrockReranker } from "./bedrock.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";
|
||||
|
||||
export const AllRerankers: { [key in RerankerName]: any } = {
|
||||
cohere: CohereReranker,
|
||||
bedrock: BedrockReranker,
|
||||
llm: LLMReranker,
|
||||
voyage: VoyageReranker,
|
||||
"free-trial": FreeTrialReranker,
|
||||
"huggingface-tei": HuggingFaceTEIReranker,
|
||||
"continue-proxy": ContinueProxyReranker,
|
||||
};
|
||||
|
|
@ -1,59 +0,0 @@
|
|||
import fetch from "node-fetch";
|
||||
|
||||
import { Chunk, Reranker } from "../../index.js";
|
||||
|
||||
export class HuggingFaceTEIReranker implements Reranker {
|
||||
name = "huggingface-tei";
|
||||
|
||||
static defaultOptions = {
|
||||
apiBase: "http://localhost:8080",
|
||||
truncate: true,
|
||||
truncation_direction: "Right"
|
||||
};
|
||||
|
||||
constructor(
|
||||
private readonly params: {
|
||||
apiBase?: string;
|
||||
truncate?: boolean;
|
||||
truncation_direction?: string;
|
||||
apiKey?: string;
|
||||
},
|
||||
) {}
|
||||
|
||||
async rerank(query: string, chunks: Chunk[]): Promise<number[]> {
|
||||
let apiBase = this.params.apiBase ?? HuggingFaceTEIReranker.defaultOptions.apiBase;
|
||||
if (!apiBase.endsWith("/")) {
|
||||
apiBase += "/";
|
||||
}
|
||||
|
||||
const headers: Record<string, string> = {
|
||||
"Content-Type": "application/json",
|
||||
};
|
||||
|
||||
if (this.params.apiKey) {
|
||||
headers["Authorization"] = `Bearer ${this.params.apiKey}`;
|
||||
}
|
||||
|
||||
const resp = await fetch(new URL("rerank", apiBase), {
|
||||
method: "POST",
|
||||
headers,
|
||||
body: JSON.stringify({
|
||||
query: query,
|
||||
return_text: false,
|
||||
raw_scores: false,
|
||||
texts: chunks.map((chunk) => chunk.content),
|
||||
truncation_direction: this.params.truncation_direction ?? HuggingFaceTEIReranker.defaultOptions.truncation_direction,
|
||||
truncate: this.params.truncate ?? HuggingFaceTEIReranker.defaultOptions.truncate
|
||||
}),
|
||||
});
|
||||
|
||||
if (!resp.ok) {
|
||||
throw new Error(await resp.text());
|
||||
}
|
||||
|
||||
const data = (await resp.json()) as any;
|
||||
// Resort into original order and extract scores
|
||||
const results = data.sort((a: any, b: any) => a.index - b.index);
|
||||
return results.map((result: any) => result.score);
|
||||
}
|
||||
}
|
||||
|
|
@ -110,7 +110,8 @@ export default class BaseRetrievalPipeline implements IRetrievalPipeline {
|
|||
const fileChunks = chunkDocument({
|
||||
filepath,
|
||||
contents,
|
||||
maxChunkSize: this.options.config.embeddingsProvider.maxChunkSize,
|
||||
maxChunkSize:
|
||||
this.options.config.embeddingsProvider.maxEmbeddingChunkSize,
|
||||
digest: filepath,
|
||||
});
|
||||
|
||||
|
|
|
|||
|
|
@ -66,7 +66,6 @@ This is the question that you should select relevant files for: "${input}"`;
|
|||
new AbortController().signal,
|
||||
);
|
||||
const content = renderChatMessage(response);
|
||||
console.debug("Repo map retrieval response: ", content);
|
||||
|
||||
if (!content.includes("\n")) {
|
||||
return [];
|
||||
|
|
|
|||
|
|
@ -1,7 +1,7 @@
|
|||
import path from "path";
|
||||
|
||||
import { BranchAndDir, ContextItem, ContextProviderExtras } from "../../";
|
||||
import TransformersJsEmbeddingsProvider from "../../indexing/embeddings/TransformersJsEmbeddingsProvider";
|
||||
import TransformersJsEmbeddingsProvider from "../../llm/llms/TransformersJsEmbeddingsProvider";
|
||||
import { resolveRelativePathInWorkspace } from "../../util/ideUtils";
|
||||
import { INSTRUCTIONS_BASE_ITEM } from "../providers/utils";
|
||||
|
||||
|
|
|
|||
10
core/core.ts
10
core/core.ts
|
|
@ -1,5 +1,6 @@
|
|||
import path from "path";
|
||||
|
||||
import { fetchwithRequestOptions } from "@continuedev/fetch";
|
||||
import ignore from "ignore";
|
||||
import { v4 as uuidv4 } from "uuid";
|
||||
|
||||
|
|
@ -27,7 +28,6 @@ import { callTool } from "./tools/callTool";
|
|||
import { ChatDescriber } from "./util/chatDescriber";
|
||||
import { logDevData } from "./util/devdata";
|
||||
import { DevDataSqliteDb } from "./util/devdataSqlite";
|
||||
import { fetchwithRequestOptions } from "./util/fetchWithOptions";
|
||||
import { GlobalContext } from "./util/GlobalContext";
|
||||
import historyManager from "./util/history";
|
||||
import { editConfigJson, setupInitialDotContinueDirectory } from "./util/paths";
|
||||
|
|
@ -366,7 +366,6 @@ export class Core {
|
|||
msg: Message<ToCoreProtocol["llm/streamChat"][0]>,
|
||||
) {
|
||||
const config = await configHandler.loadConfig();
|
||||
|
||||
// Stop TTS on new StreamChat
|
||||
if (config.experimental?.readResponseTTS) {
|
||||
void TTS.kill();
|
||||
|
|
@ -735,7 +734,7 @@ export class Core {
|
|||
});
|
||||
on("indexing/setPaused", async (msg) => {
|
||||
if (msg.data.type === "docs") {
|
||||
this.docsService.setPaused(msg.data.id, msg.data.paused);
|
||||
// this.docsService.setPaused(msg.data.id, msg.data.paused);
|
||||
}
|
||||
});
|
||||
on("docs/getSuggestedDocs", async (msg) => {
|
||||
|
|
@ -860,10 +859,7 @@ export class Core {
|
|||
this.indexingCancellationController &&
|
||||
!this.indexingCancellationController.signal.aborted
|
||||
) {
|
||||
return console.debug(
|
||||
"Codebase indexing already in progress, skipping indexing of files\n" +
|
||||
files.join("\n"),
|
||||
);
|
||||
return;
|
||||
}
|
||||
this.indexingCancellationController = new AbortController();
|
||||
for await (const update of (await this.codebaseIndexerPromise).refreshFiles(
|
||||
|
|
|
|||
|
|
@ -19,6 +19,14 @@ describe("Test myers diff function", () => {
|
|||
E
|
||||
`;
|
||||
const diffLines = myersDiff(linesA, linesB);
|
||||
console.log(diffLines);
|
||||
expect(diffLines).toEqual([
|
||||
{ type: "same", line: "A" },
|
||||
{ type: "same", line: "B" },
|
||||
{ type: "old", line: "C" },
|
||||
{ type: "old", line: "D" },
|
||||
{ type: "new", line: "C'" },
|
||||
{ type: "new", line: "D'" },
|
||||
{ type: "same", line: "E" },
|
||||
]);
|
||||
});
|
||||
});
|
||||
|
|
|
|||
|
|
@ -1,4 +1,4 @@
|
|||
import { ChatMessage, ModelProvider } from "../..";
|
||||
import { ChatMessage } from "../..";
|
||||
import { dedent } from "../../util";
|
||||
|
||||
export const UNCHANGED_CODE = "UNCHANGED CODE";
|
||||
|
|
@ -52,7 +52,7 @@ function claude35SonnetLazyApplyPrompt(
|
|||
|
||||
export function lazyApplyPromptForModel(
|
||||
model: string,
|
||||
provider: ModelProvider,
|
||||
provider: string,
|
||||
): LazyApplyPrompt | undefined {
|
||||
if (model.includes("sonnet")) {
|
||||
return claude35SonnetLazyApplyPrompt;
|
||||
|
|
|
|||
234
core/index.d.ts
vendored
234
core/index.d.ts
vendored
|
|
@ -1,6 +1,5 @@
|
|||
import Parser from "web-tree-sitter";
|
||||
import { GetGhTokenArgs } from "./protocol/ide";
|
||||
|
||||
declare global {
|
||||
interface Window {
|
||||
ide?: "vscode";
|
||||
|
|
@ -59,14 +58,7 @@ export interface IndexingStatus {
|
|||
type: "docs";
|
||||
progress: number;
|
||||
description: string;
|
||||
status:
|
||||
| "indexing"
|
||||
| "complete"
|
||||
| "paused"
|
||||
| "failed"
|
||||
| "aborted"
|
||||
| "deleted"
|
||||
| "pending";
|
||||
status: "indexing" | "complete" | "paused" | "failed" | "aborted" | "pending";
|
||||
embeddingsProviderId: string;
|
||||
isReindexing?: boolean;
|
||||
debugInfo?: string;
|
||||
|
|
@ -83,7 +75,7 @@ export type PromptTemplateFunction = (
|
|||
export type PromptTemplate = string | PromptTemplateFunction;
|
||||
|
||||
export interface ILLM extends LLMOptions {
|
||||
get providerName(): ModelProvider;
|
||||
get providerName(): string;
|
||||
|
||||
uniqueId: string;
|
||||
model: string;
|
||||
|
|
@ -108,6 +100,11 @@ export interface ILLM extends LLMOptions {
|
|||
region?: string;
|
||||
projectId?: string;
|
||||
|
||||
// Embedding options
|
||||
embeddingId: string;
|
||||
maxEmbeddingChunkSize: number;
|
||||
maxEmbeddingBatchSize: number;
|
||||
|
||||
complete(
|
||||
prompt: string,
|
||||
signal: AbortSignal,
|
||||
|
|
@ -139,6 +136,10 @@ export interface ILLM extends LLMOptions {
|
|||
options?: LLMFullCompletionOptions,
|
||||
): Promise<ChatMessage>;
|
||||
|
||||
embed(chunks: string[]): Promise<number[][]>;
|
||||
|
||||
rerank(query: string, chunks: Chunk[]): Promise<number[]>;
|
||||
|
||||
countTokens(text: string): number;
|
||||
|
||||
supportsImages(): boolean;
|
||||
|
|
@ -175,8 +176,8 @@ export type FetchFunction = (url: string | URL, init?: any) => Promise<any>;
|
|||
export interface ContextProviderExtras {
|
||||
config: ContinueConfig;
|
||||
fullInput: string;
|
||||
embeddingsProvider: EmbeddingsProvider;
|
||||
reranker: Reranker | undefined;
|
||||
embeddingsProvider: ILLM;
|
||||
reranker: ILLM | undefined;
|
||||
llm: ILLM;
|
||||
ide: IDE;
|
||||
selectedCode: RangeInFile[];
|
||||
|
|
@ -459,6 +460,11 @@ export interface LLMOptions {
|
|||
|
||||
useLegacyCompletionsEndpoint?: boolean;
|
||||
|
||||
// Embedding options
|
||||
embeddingId?: string;
|
||||
maxEmbeddingChunkSize?: number;
|
||||
maxEmbeddingBatchSize?: number;
|
||||
|
||||
// Cloudflare options
|
||||
accountId?: string;
|
||||
|
||||
|
|
@ -770,151 +776,6 @@ type TemplateType =
|
|||
| "granite"
|
||||
| "llama3";
|
||||
|
||||
type ModelProvider =
|
||||
| "openai"
|
||||
| "free-trial"
|
||||
| "anthropic"
|
||||
| "cohere"
|
||||
| "together"
|
||||
| "ollama"
|
||||
| "huggingface-tgi"
|
||||
| "huggingface-inference-api"
|
||||
| "kindo"
|
||||
| "llama.cpp"
|
||||
| "replicate"
|
||||
| "text-gen-webui"
|
||||
| "lmstudio"
|
||||
| "llamafile"
|
||||
| "gemini"
|
||||
| "mistral"
|
||||
| "bedrock"
|
||||
| "bedrockimport"
|
||||
| "sagemaker"
|
||||
| "deepinfra"
|
||||
| "flowise"
|
||||
| "groq"
|
||||
| "continue-proxy"
|
||||
| "fireworks"
|
||||
| "custom"
|
||||
| "cloudflare"
|
||||
| "deepseek"
|
||||
| "azure"
|
||||
| "openai-aiohttp"
|
||||
| "msty"
|
||||
| "watsonx"
|
||||
| "openrouter"
|
||||
| "sambanova"
|
||||
| "nvidia"
|
||||
| "vllm"
|
||||
| "mock"
|
||||
| "cerebras"
|
||||
| "askSage"
|
||||
| "vertexai"
|
||||
| "nebius"
|
||||
| "xAI"
|
||||
| "moonshot"
|
||||
| "siliconflow"
|
||||
| "function-network";
|
||||
|
||||
export type ModelName =
|
||||
| "AUTODETECT"
|
||||
// OpenAI
|
||||
| "gpt-3.5-turbo"
|
||||
| "gpt-3.5-turbo-16k"
|
||||
| "gpt-4"
|
||||
| "gpt-3.5-turbo-0613"
|
||||
| "gpt-4-32k"
|
||||
| "gpt-4o"
|
||||
| "gpt-4o-mini"
|
||||
| "gpt-4-turbo"
|
||||
| "gpt-4-turbo-preview"
|
||||
| "gpt-4-vision-preview"
|
||||
| "o1-preview"
|
||||
| "o1-mini"
|
||||
// Mistral
|
||||
| "codestral-latest"
|
||||
| "open-mistral-7b"
|
||||
| "open-mixtral-8x7b"
|
||||
| "open-mixtral-8x22b"
|
||||
| "mistral-small-latest"
|
||||
| "mistral-large-latest"
|
||||
| "mistral-7b"
|
||||
| "mistral-8x7b"
|
||||
| "mistral-8x22b"
|
||||
| "mistral-tiny"
|
||||
| "mistral-small"
|
||||
| "mistral-medium"
|
||||
| "mistral-embed"
|
||||
| "mistral-nemo"
|
||||
// Llama 2
|
||||
| "llama2-7b"
|
||||
| "llama2-13b"
|
||||
| "llama2-70b"
|
||||
| "codellama-7b"
|
||||
| "codellama-13b"
|
||||
| "codellama-34b"
|
||||
| "codellama-70b"
|
||||
// Llama 3
|
||||
| "llama3-8b"
|
||||
| "llama3-70b"
|
||||
// Llama 3.1
|
||||
| "llama3.1-8b"
|
||||
| "llama3.1-70b"
|
||||
| "llama3.1-405b"
|
||||
// Llama 3.2
|
||||
| "llama3.2-1b"
|
||||
| "llama3.2-3b"
|
||||
| "llama3.2-11b"
|
||||
| "llama3.2-90b"
|
||||
// xAI
|
||||
| "grok-beta"
|
||||
// Other Open-source
|
||||
| "phi2"
|
||||
| "phi-3-mini"
|
||||
| "phi-3-medium"
|
||||
| "phind-codellama-34b"
|
||||
| "wizardcoder-7b"
|
||||
| "wizardcoder-13b"
|
||||
| "wizardcoder-34b"
|
||||
| "zephyr-7b"
|
||||
| "codeup-13b"
|
||||
| "deepseek-7b"
|
||||
| "deepseek-33b"
|
||||
| "deepseek-2-lite"
|
||||
| "neural-chat-7b"
|
||||
| "gemma-7b-it"
|
||||
| "gemma2-2b-it"
|
||||
| "gemma2-9b-it"
|
||||
| "olmo-7b"
|
||||
| "qwen-coder2.5-7b"
|
||||
// Anthropic
|
||||
| "claude-3-5-sonnet-latest"
|
||||
| "claude-3-5-sonnet-20240620"
|
||||
| "claude-3-opus-20240229"
|
||||
| "claude-3-sonnet-20240229"
|
||||
| "claude-3-haiku-20240307"
|
||||
| "claude-2.1"
|
||||
| "claude-2"
|
||||
// Cohere
|
||||
| "command-r"
|
||||
| "command-r-plus"
|
||||
// Gemini
|
||||
| "gemini-pro"
|
||||
| "gemini-1.5-pro-latest"
|
||||
| "gemini-1.5-pro"
|
||||
| "gemini-1.5-flash-latest"
|
||||
| "gemini-1.5-flash"
|
||||
// Tab autocomplete
|
||||
| "deepseek-1b"
|
||||
| "starcoder-1b"
|
||||
| "starcoder-3b"
|
||||
| "starcoder2-3b"
|
||||
| "stable-code-3b"
|
||||
// Moonshot
|
||||
| "moonshot-v1-8k"
|
||||
| "moonshot-v1-32k"
|
||||
| "moonshot-v1-128k";
|
||||
|
||||
export interface RequestOptions {
|
||||
timeout?: number;
|
||||
verifySsl?: boolean;
|
||||
|
|
@ -1015,7 +876,7 @@ export interface ModelCapability {
|
|||
|
||||
export interface ModelDescription {
|
||||
title: string;
|
||||
provider: ModelProvider;
|
||||
provider: string;
|
||||
model: string;
|
||||
apiKey?: string;
|
||||
apiBase?: string;
|
||||
|
|
@ -1030,28 +891,6 @@ export interface ModelDescription {
|
|||
cacheBehavior?: CacheBehavior;
|
||||
}
|
||||
|
||||
export type EmbeddingsProviderName =
|
||||
| "sagemaker"
|
||||
| "bedrock"
|
||||
| "huggingface-tei"
|
||||
| "transformers.js"
|
||||
| "ollama"
|
||||
| "openai"
|
||||
| "cohere"
|
||||
| "lmstudio"
|
||||
| "free-trial"
|
||||
| "gemini"
|
||||
| "continue-proxy"
|
||||
| "deepinfra"
|
||||
| "nvidia"
|
||||
| "voyage"
|
||||
| "mistral"
|
||||
| "nebius"
|
||||
| "vertexai"
|
||||
| "watsonx"
|
||||
| "function-network"
|
||||
| "siliconflow";
|
||||
|
||||
export interface EmbedOptions {
|
||||
apiBase?: string;
|
||||
apiKey?: string;
|
||||
|
|
@ -1073,35 +912,12 @@ export interface EmbedOptions {
|
|||
}
|
||||
|
||||
export interface EmbeddingsProviderDescription extends EmbedOptions {
|
||||
provider: EmbeddingsProviderName;
|
||||
provider: string;
|
||||
}
|
||||
|
||||
export interface EmbeddingsProvider {
|
||||
id: string;
|
||||
providerName: EmbeddingsProviderName;
|
||||
maxChunkSize: number;
|
||||
|
||||
embed(chunks: string[]): Promise<number[][]>;
|
||||
}
|
||||
|
||||
export type RerankerName =
|
||||
| "cohere"
|
||||
| "bedrock"
|
||||
| "voyage"
|
||||
| "llm"
|
||||
| "free-trial"
|
||||
| "huggingface-tei"
|
||||
| "continue-proxy";
|
||||
|
||||
export interface RerankerDescription {
|
||||
name: RerankerName;
|
||||
params?: { [key: string]: any };
|
||||
}
|
||||
|
||||
export interface Reranker {
|
||||
name: string;
|
||||
|
||||
rerank(query: string, chunks: Chunk[]): Promise<number[]>;
|
||||
params?: { [key: string]: any };
|
||||
}
|
||||
|
||||
export interface TabAutocompleteOptions {
|
||||
|
|
@ -1319,7 +1135,7 @@ export interface Config {
|
|||
/** An optional token to identify a user. Not used by Continue unless you write custom coniguration that requires such a token */
|
||||
userToken?: string;
|
||||
/** The provider used to calculate embeddings. If left empty, Continue will use transformers.js to calculate the embeddings with all-MiniLM-L6-v2 */
|
||||
embeddingsProvider?: EmbeddingsProviderDescription | EmbeddingsProvider;
|
||||
embeddingsProvider?: EmbeddingsProviderDescription | ILLM;
|
||||
/** The model that Continue will use for tab autocompletions. */
|
||||
tabAutocompleteModel?:
|
||||
| CustomLLM
|
||||
|
|
@ -1330,7 +1146,7 @@ export interface Config {
|
|||
/** UI styles customization */
|
||||
ui?: ContinueUIConfig;
|
||||
/** Options for the reranker */
|
||||
reranker?: RerankerDescription | Reranker;
|
||||
reranker?: RerankerDescription | ILLM;
|
||||
/** Experimental configuration */
|
||||
experimental?: ExperimentalConfig;
|
||||
/** Analytics configuration */
|
||||
|
|
@ -1349,11 +1165,11 @@ export interface ContinueConfig {
|
|||
disableSessionTitles?: boolean;
|
||||
disableIndexing?: boolean;
|
||||
userToken?: string;
|
||||
embeddingsProvider: EmbeddingsProvider;
|
||||
embeddingsProvider: ILLM;
|
||||
tabAutocompleteModels?: ILLM[];
|
||||
tabAutocompleteOptions?: Partial<TabAutocompleteOptions>;
|
||||
ui?: ContinueUIConfig;
|
||||
reranker?: Reranker;
|
||||
reranker?: ILLM;
|
||||
experimental?: ExperimentalConfig;
|
||||
analytics?: AnalyticsConfig;
|
||||
docs?: SiteIndexingConfig[];
|
||||
|
|
|
|||
|
|
@ -135,7 +135,6 @@ describe("CodebaseIndexer", () => {
|
|||
del: number,
|
||||
) {
|
||||
const plan = await getIndexPlan();
|
||||
console.log("PLAN: ", plan);
|
||||
expect(plan.compute).toHaveLength(compute);
|
||||
expect(plan.addTag).toHaveLength(addTag);
|
||||
expect(plan.removeTag).toHaveLength(removeTag);
|
||||
|
|
|
|||
|
|
@ -17,7 +17,6 @@ import {
|
|||
RefreshIndexResults,
|
||||
} from "./types.js";
|
||||
import { walkDirAsync } from "./walkDir.js";
|
||||
import { getBasename } from "../util/index.js";
|
||||
|
||||
export class PauseToken {
|
||||
constructor(private _paused: boolean) {}
|
||||
|
|
@ -83,7 +82,7 @@ export class CodebaseIndexer {
|
|||
this.ide.readFile.bind(this.ide),
|
||||
pathSep,
|
||||
this.continueServerClient,
|
||||
config.embeddingsProvider.maxChunkSize,
|
||||
config.embeddingsProvider.maxEmbeddingChunkSize,
|
||||
), // Chunking must come first
|
||||
new LanceDbIndex(
|
||||
config.embeddingsProvider,
|
||||
|
|
|
|||
|
|
@ -7,7 +7,7 @@ import { IContinueServerClient } from "../continueServer/interface.js";
|
|||
import {
|
||||
BranchAndDir,
|
||||
Chunk,
|
||||
EmbeddingsProvider,
|
||||
ILLM,
|
||||
IndexTag,
|
||||
IndexingProgressUpdate,
|
||||
} from "../index.js";
|
||||
|
|
@ -40,11 +40,11 @@ type ChunkMap = Map<string, ItemWithChunks>;
|
|||
export class LanceDbIndex implements CodebaseIndex {
|
||||
relativeExpectedTime: number = 13;
|
||||
get artifactId(): string {
|
||||
return `vectordb::${this.embeddingsProvider.id}`;
|
||||
return `vectordb::${this.embeddingsProvider.embeddingId}`;
|
||||
}
|
||||
|
||||
constructor(
|
||||
private readonly embeddingsProvider: EmbeddingsProvider,
|
||||
private readonly embeddingsProvider: ILLM,
|
||||
private readonly readFile: (filepath: string) => Promise<string>,
|
||||
private readonly pathSep: string,
|
||||
private readonly continueServerClient?: IContinueServerClient,
|
||||
|
|
@ -148,7 +148,7 @@ export class LanceDbIndex implements CodebaseIndex {
|
|||
const chunkParams = {
|
||||
filepath: item.path,
|
||||
contents: content,
|
||||
maxChunkSize: this.embeddingsProvider.maxChunkSize,
|
||||
maxChunkSize: this.embeddingsProvider.maxEmbeddingChunkSize,
|
||||
digest: item.cacheKey,
|
||||
};
|
||||
|
||||
|
|
@ -168,7 +168,7 @@ export class LanceDbIndex implements CodebaseIndex {
|
|||
return await this.embeddingsProvider.embed(chunks.map((c) => c.content));
|
||||
} catch (err) {
|
||||
throw new Error(
|
||||
`Failed to generate embeddings for ${chunks.length} chunks with provider: ${this.embeddingsProvider.id}: ${err}`,
|
||||
`Failed to generate embeddings for ${chunks.length} chunks with provider: ${this.embeddingsProvider.embeddingId}: ${err}`,
|
||||
{ cause: err },
|
||||
);
|
||||
}
|
||||
|
|
|
|||
49
core/indexing/allEmbeddingsProviders.ts
Normal file
49
core/indexing/allEmbeddingsProviders.ts
Normal file
|
|
@ -0,0 +1,49 @@
|
|||
import { ILLM } from "../index.js";
|
||||
import Bedrock from "../llm/llms/Bedrock.js";
|
||||
import Cohere from "../llm/llms/Cohere.js";
|
||||
import DeepInfra from "../llm/llms/DeepInfra.js";
|
||||
import FreeTrial from "../llm/llms/FreeTrial.js";
|
||||
import FunctionNetwork from "../llm/llms/FunctionNetwork.js";
|
||||
import Gemini from "../llm/llms/Gemini.js";
|
||||
import HuggingFaceTEIEmbeddingsProvider from "../llm/llms/HuggingFaceTEI.js";
|
||||
import LMStudio from "../llm/llms/LMStudio.js";
|
||||
import Mistral from "../llm/llms/Mistral.js";
|
||||
import Nebius from "../llm/llms/Nebius.js";
|
||||
import Nvidia from "../llm/llms/Nvidia.js";
|
||||
import Ollama from "../llm/llms/Ollama.js";
|
||||
import OpenAI from "../llm/llms/OpenAI.js";
|
||||
import SageMaker from "../llm/llms/SageMaker.js";
|
||||
import SiliconFlow from "../llm/llms/SiliconFlow.js";
|
||||
import ContinueProxy from "../llm/llms/stubs/ContinueProxy.js";
|
||||
import TransformersJsEmbeddingsProvider from "../llm/llms/TransformersJsEmbeddingsProvider.js";
|
||||
import VertexAI from "../llm/llms/VertexAI.js";
|
||||
import Voyage from "../llm/llms/Voyage.js";
|
||||
import WatsonX from "../llm/llms/WatsonX.js";
|
||||
|
||||
type EmbeddingsProviderConstructor = new (...args: any[]) => ILLM;
|
||||
|
||||
export const allEmbeddingsProviders: Record<
|
||||
string,
|
||||
EmbeddingsProviderConstructor
|
||||
> = {
|
||||
sagemaker: SageMaker,
|
||||
bedrock: Bedrock,
|
||||
ollama: Ollama,
|
||||
"transformers.js": TransformersJsEmbeddingsProvider,
|
||||
openai: OpenAI,
|
||||
cohere: Cohere,
|
||||
"free-trial": FreeTrial,
|
||||
"function-network": FunctionNetwork,
|
||||
"huggingface-tei": HuggingFaceTEIEmbeddingsProvider,
|
||||
gemini: Gemini,
|
||||
"continue-proxy": ContinueProxy,
|
||||
deepinfra: DeepInfra,
|
||||
nvidia: Nvidia,
|
||||
voyage: Voyage,
|
||||
mistral: Mistral,
|
||||
nebius: Nebius,
|
||||
vertexai: VertexAI,
|
||||
watsonx: WatsonX,
|
||||
lmstudio: LMStudio,
|
||||
siliconflow: SiliconFlow,
|
||||
};
|
||||
|
|
@ -4,9 +4,9 @@
|
|||
import { ConfigHandler } from "../../config/ConfigHandler.js";
|
||||
import { ControlPlaneClient } from "../../control-plane/client.js";
|
||||
import { SiteIndexingConfig } from "../../index.js";
|
||||
import FreeTrial from "../../llm/llms/FreeTrial.js";
|
||||
import FileSystemIde from "../../util/filesystem.js";
|
||||
import { editConfigJson } from "../../util/paths.js";
|
||||
import FreeTrialEmbeddingsProvider from "../embeddings/FreeTrialEmbeddingsProvider.js";
|
||||
|
||||
import DocsService from "./DocsService.js";
|
||||
import preIndexedDocs from "./preIndexedDocs.js";
|
||||
|
|
@ -113,7 +113,7 @@ describe.skip("DocsService Integration Tests", () => {
|
|||
editConfigJson((config) => ({
|
||||
...config,
|
||||
embeddingsProvider: {
|
||||
provider: FreeTrialEmbeddingsProvider.providerName,
|
||||
provider: FreeTrial.providerName,
|
||||
},
|
||||
}));
|
||||
|
||||
|
|
@ -5,15 +5,16 @@ import lancedb, { Connection } from "vectordb";
|
|||
import {
|
||||
Chunk,
|
||||
ContinueConfig,
|
||||
EmbeddingsProvider,
|
||||
IDE,
|
||||
IdeInfo,
|
||||
ILLM,
|
||||
IndexingStatus,
|
||||
SiteIndexingConfig,
|
||||
IdeInfo,
|
||||
} from "../..";
|
||||
import { ConfigHandler } from "../../config/ConfigHandler";
|
||||
import { addContextProvider } from "../../config/util";
|
||||
import DocsContextProvider from "../../context/providers/DocsContextProvider";
|
||||
import TransformersJsEmbeddingsProvider from "../../llm/llms/TransformersJsEmbeddingsProvider";
|
||||
import { FromCoreProtocol, ToCoreProtocol } from "../../protocol";
|
||||
import { fetchFavicon, getFaviconBase64 } from "../../util/fetchFavicon";
|
||||
import { GlobalContext } from "../../util/GlobalContext";
|
||||
|
|
@ -24,7 +25,6 @@ import {
|
|||
getLanceDbPath,
|
||||
} from "../../util/paths";
|
||||
import { Telemetry } from "../../util/posthog";
|
||||
import TransformersJsEmbeddingsProvider from "../embeddings/TransformersJsEmbeddingsProvider";
|
||||
|
||||
import { Article, chunkArticle, pageToArticle } from "./article";
|
||||
import DocsCrawler from "./DocsCrawler";
|
||||
|
|
@ -37,12 +37,6 @@ import {
|
|||
} from "./preIndexed";
|
||||
import preIndexedDocs from "./preIndexedDocs";
|
||||
|
||||
// Progress heuristic values
|
||||
// subpages -> embeddings -> delete from db -> add to db
|
||||
const PROGRESS_AT_EMBEDDING = 0.5;
|
||||
const PROGRESS_AT_DELETE_OPERATIONS = 0.7;
|
||||
const PROGRESS_AT_ADD_OPERATIONS = 0.8;
|
||||
|
||||
// Purposefully lowercase because lancedb converts
|
||||
export interface LanceDbDocsRow {
|
||||
title: string;
|
||||
|
|
@ -69,7 +63,6 @@ export type AddParams = {
|
|||
favicon?: string;
|
||||
};
|
||||
|
||||
|
||||
/*
|
||||
General process:
|
||||
- On config update:
|
||||
|
|
@ -163,7 +156,7 @@ export default class DocsService {
|
|||
const sharedStatus = {
|
||||
type: "docs" as IndexingStatus["type"],
|
||||
id: doc.startUrl,
|
||||
embeddingsProviderId: this.config.embeddingsProvider.id,
|
||||
embeddingsProviderId: this.config.embeddingsProvider.embeddingId,
|
||||
isReindexing: false,
|
||||
title: doc.title,
|
||||
debugInfo: `max depth: ${doc.maxDepth}`,
|
||||
|
|
@ -207,19 +200,19 @@ export default class DocsService {
|
|||
}
|
||||
|
||||
// NOTE Pausing not supported for docs yet
|
||||
setPaused(startUrl: string, pause: boolean) {
|
||||
const status = this.statuses.get(startUrl);
|
||||
if (status) {
|
||||
this.handleStatusUpdate({
|
||||
...status,
|
||||
status: pause ? "paused" : "indexing",
|
||||
});
|
||||
}
|
||||
}
|
||||
// setPaused(startUrl: string, pause: boolean) {
|
||||
// const status = this.statuses.get(startUrl);
|
||||
// if (status) {
|
||||
// this.handleStatusUpdate({
|
||||
// ...status,
|
||||
// status: pause ? "paused" : "indexing",
|
||||
// });
|
||||
// }
|
||||
// }
|
||||
|
||||
isPaused(startUrl: string) {
|
||||
return this.statuses.get(startUrl)?.status === "paused";
|
||||
}
|
||||
// isPaused(startUrl: string) {
|
||||
// return this.statuses.get(startUrl)?.status === "paused";
|
||||
// }
|
||||
|
||||
/*
|
||||
* Currently, we generate and host embeddings for pre-indexed docs using transformers.
|
||||
|
|
@ -236,15 +229,13 @@ export default class DocsService {
|
|||
|
||||
async isUsingUnsupportedPreIndexedEmbeddingsProvider() {
|
||||
const isPreIndexedDocsProvider =
|
||||
this.config.embeddingsProvider.id ===
|
||||
DocsService.preIndexedDocsEmbeddingsProvider.id;
|
||||
this.config.embeddingsProvider.embeddingId ===
|
||||
DocsService.preIndexedDocsEmbeddingsProvider.embeddingId;
|
||||
const canUsePreindexedDocs = await this.canUsePreindexedDocs();
|
||||
return isPreIndexedDocsProvider && !canUsePreindexedDocs;
|
||||
}
|
||||
|
||||
async getEmbeddingsProvider(
|
||||
isPreIndexedDoc: boolean = false,
|
||||
): Promise<EmbeddingsProvider> {
|
||||
async getEmbeddingsProvider(isPreIndexedDoc: boolean = false): Promise<ILLM> {
|
||||
const canUsePreindexedDocs = await this.canUsePreindexedDocs();
|
||||
|
||||
if (canUsePreindexedDocs && isPreIndexedDoc) {
|
||||
|
|
@ -287,7 +278,7 @@ export default class DocsService {
|
|||
);
|
||||
if (
|
||||
!curEmbeddingsProviderId ||
|
||||
curEmbeddingsProviderId !== newConfig.embeddingsProvider.id
|
||||
curEmbeddingsProviderId !== newConfig.embeddingsProvider.embeddingId
|
||||
) {
|
||||
// If not set, we're initializing
|
||||
const currentDocs = await this.listMetadata();
|
||||
|
|
@ -384,20 +375,13 @@ export default class DocsService {
|
|||
const indexExists = await this.hasMetadata(startUrl);
|
||||
|
||||
// Build status update - most of it is fixed values
|
||||
const fixedStatus: Pick<
|
||||
const fixedStatus: Omit<
|
||||
IndexingStatus,
|
||||
| "type"
|
||||
| "id"
|
||||
| "embeddingsProviderId"
|
||||
| "isReindexing"
|
||||
| "debugInfo"
|
||||
| "icon"
|
||||
| "url"
|
||||
| "title"
|
||||
"progress" | "description" | "status"
|
||||
> = {
|
||||
type: "docs",
|
||||
id: siteIndexingConfig.startUrl,
|
||||
embeddingsProviderId: embeddingsProvider.id,
|
||||
embeddingsProviderId: embeddingsProvider.embeddingId,
|
||||
isReindexing: reIndex && indexExists,
|
||||
title: siteIndexingConfig.title,
|
||||
debugInfo: `max depth: ${siteIndexingConfig.maxDepth}`,
|
||||
|
|
@ -406,7 +390,6 @@ export default class DocsService {
|
|||
};
|
||||
|
||||
// Clear current indexes if reIndexing
|
||||
//
|
||||
if (indexExists) {
|
||||
if (reIndex) {
|
||||
await this.deleteIndexes(startUrl);
|
||||
|
|
@ -453,9 +436,9 @@ export default class DocsService {
|
|||
description: `Finding subpages (${page.path})`,
|
||||
status: "indexing",
|
||||
progress:
|
||||
0.3 * estimatedProgress +
|
||||
Math.min(0.2, (0.2 * processedPages) / 500),
|
||||
// For the first 50%, 30% is sum of series 1/(2^n) and the other 20% is based on number of files/ 500 max
|
||||
0.15 * estimatedProgress +
|
||||
Math.min(0.35, (0.35 * processedPages) / 500),
|
||||
// For the first 50%, 15% is sum of series 1/(2^n) and the other 35% is based on number of files/ 500 max
|
||||
});
|
||||
|
||||
const article = pageToArticle(page);
|
||||
|
|
@ -465,7 +448,11 @@ export default class DocsService {
|
|||
articles.push(article);
|
||||
|
||||
processedPages++;
|
||||
await new Promise((resolve) => setTimeout(resolve, 100)); // Locks down GUI if no sleeping
|
||||
|
||||
// Locks down GUI if no sleeping
|
||||
// Wait proportional to how many docs are indexing
|
||||
const toWait = 100 * this.docsIndexingQueue.size + 50;
|
||||
await new Promise((resolve) => setTimeout(resolve, toWait));
|
||||
}
|
||||
|
||||
void Telemetry.capture("docs_pages_crawled", {
|
||||
|
|
@ -476,8 +463,6 @@ export default class DocsService {
|
|||
const embeddings: number[][] = [];
|
||||
|
||||
// Create embeddings of retrieved articles
|
||||
console.debug(`Creating embeddings for ${articles.length} articles`);
|
||||
|
||||
for (let i = 0; i < articles.length; i++) {
|
||||
const article = articles[i];
|
||||
|
||||
|
|
@ -494,7 +479,7 @@ export default class DocsService {
|
|||
try {
|
||||
const chunkedArticle = chunkArticle(
|
||||
article,
|
||||
embeddingsProvider.maxChunkSize,
|
||||
embeddingsProvider.maxEmbeddingChunkSize,
|
||||
);
|
||||
|
||||
const chunkedArticleContents = chunkedArticle.map(
|
||||
|
|
@ -609,7 +594,7 @@ export default class DocsService {
|
|||
|
||||
const data = await downloadFromS3(
|
||||
S3Buckets.continueIndexedDocs,
|
||||
getS3Filename(embeddingsProvider.id, title),
|
||||
getS3Filename(embeddingsProvider.embeddingId, title),
|
||||
);
|
||||
|
||||
const siteEmbeddings = JSON.parse(data) as SiteIndexingResults;
|
||||
|
|
@ -641,7 +626,7 @@ export default class DocsService {
|
|||
if (await this.isUsingUnsupportedPreIndexedEmbeddingsProvider()) {
|
||||
await this.ide.showToast(
|
||||
"error",
|
||||
`${DocsService.preIndexedDocsEmbeddingsProvider.id} is configured as ` +
|
||||
`${DocsService.preIndexedDocsEmbeddingsProvider.embeddingId} is configured as ` +
|
||||
"the embeddings provider, but it cannot be used with JetBrains. " + // TODO "with this IDE"
|
||||
"Please select a different embeddings provider to use the '@docs' " +
|
||||
"context provider.",
|
||||
|
|
@ -802,7 +787,7 @@ export default class DocsService {
|
|||
this.handleStatusUpdate({
|
||||
type: "docs",
|
||||
id: doc.startUrl,
|
||||
embeddingsProviderId: this.config.embeddingsProvider.id,
|
||||
embeddingsProviderId: this.config.embeddingsProvider.embeddingId,
|
||||
isReindexing: false,
|
||||
title: doc.title,
|
||||
debugInfo: "Config sync: not changed",
|
||||
|
|
@ -885,7 +870,7 @@ export default class DocsService {
|
|||
await this.getEmbeddingsProvider(isPreIndexedDoc);
|
||||
|
||||
const tableName = this.sanitizeLanceTableName(
|
||||
`${DocsService.lanceTableName}${embeddingsProvider.id}`,
|
||||
`${DocsService.lanceTableName}${embeddingsProvider.embeddingId}`,
|
||||
);
|
||||
|
||||
return tableName;
|
||||
|
|
@ -1020,13 +1005,10 @@ export default class DocsService {
|
|||
}
|
||||
|
||||
async delete(startUrl: string) {
|
||||
this.docsIndexingQueue.delete(startUrl);
|
||||
this.abort(startUrl);
|
||||
await this.deleteIndexes(startUrl);
|
||||
this.deleteFromConfig(startUrl);
|
||||
|
||||
const status = this.statuses.get(startUrl);
|
||||
if (status) {
|
||||
this.handleStatusUpdate({ ...status, status: "deleted" });
|
||||
}
|
||||
this.messenger?.send("refreshSubmenuItems", undefined);
|
||||
}
|
||||
|
||||
|
|
@ -1045,14 +1027,17 @@ export default class DocsService {
|
|||
}
|
||||
|
||||
console.log(
|
||||
`Reindexing non-preindexed docs with new embeddings provider: ${embeddingsProvider.id}`,
|
||||
`Reindexing non-preindexed docs with new embeddings provider: ${embeddingsProvider.embeddingId}`,
|
||||
);
|
||||
await Promise.allSettled(docs.map((doc) => this.indexAndAdd(doc)));
|
||||
|
||||
// Important that this only is invoked after we have successfully
|
||||
// cleared and reindex the docs so that the table cannot end up in an
|
||||
// invalid state.
|
||||
this.globalContext.update("curEmbeddingsProviderId", embeddingsProvider.id);
|
||||
this.globalContext.update(
|
||||
"curEmbeddingsProviderId",
|
||||
embeddingsProvider.embeddingId,
|
||||
);
|
||||
|
||||
console.log("Completed reindexing of all non-preindexed docs");
|
||||
}
|
||||
|
|
|
|||
|
|
@ -336,6 +336,18 @@ const preIndexedDocs: Record<
|
|||
rootUrl: "https://go.dev",
|
||||
faviconUrl: "https://go.dev/favicon.ico",
|
||||
},
|
||||
"https://api.flutter.dev": {
|
||||
title: "Flutter",
|
||||
startUrl: "https://api.flutter.dev",
|
||||
rootUrl: "https://api.flutter.dev",
|
||||
faviconUrl: "https://api.flutter.dev/flutter/static-assets/favicon.png",
|
||||
},
|
||||
"https://api.dart.dev": {
|
||||
title: "Dart",
|
||||
startUrl: "https://api.dart.dev",
|
||||
rootUrl: "https://api.dart.dev",
|
||||
faviconUrl: "https://api.dart.dev/static-assets/favicon.png",
|
||||
},
|
||||
};
|
||||
|
||||
export default preIndexedDocs;
|
||||
|
|
|
|||
|
|
@ -1,76 +0,0 @@
|
|||
import {
|
||||
EmbedOptions,
|
||||
EmbeddingsProvider,
|
||||
EmbeddingsProviderName,
|
||||
FetchFunction,
|
||||
} from "../../index.js";
|
||||
import { DEFAULT_MAX_CHUNK_SIZE } from "../../llm/constants.js";
|
||||
|
||||
export interface IBaseEmbeddingsProvider extends EmbeddingsProvider {
|
||||
options: EmbedOptions;
|
||||
fetch: FetchFunction;
|
||||
defaultOptions?: EmbedOptions;
|
||||
maxBatchSize?: number;
|
||||
}
|
||||
|
||||
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"];
|
||||
|
||||
constructor(
|
||||
options: IBaseEmbeddingsProvider["options"],
|
||||
fetch: IBaseEmbeddingsProvider["fetch"],
|
||||
) {
|
||||
// Overwrite default options with any runtime options
|
||||
this.options = {
|
||||
...(this.constructor as typeof BaseEmbeddingsProvider).defaultOptions,
|
||||
...options,
|
||||
};
|
||||
this.fetch = fetch;
|
||||
// Include the `max_chunk_size` if it is not the default, since we need to create other indices for different chunk_sizes
|
||||
if (this.maxChunkSize !== DEFAULT_MAX_CHUNK_SIZE) {
|
||||
this.id = `${this.constructor.name}::${this.options.model}::${this.maxChunkSize}`;
|
||||
} else {
|
||||
this.id = `${this.constructor.name}::${this.options.model}`;
|
||||
}
|
||||
}
|
||||
defaultOptions?: EmbedOptions | undefined;
|
||||
get maxBatchSize(): number | undefined {
|
||||
return this.options.maxBatchSize ?? (this.constructor as typeof BaseEmbeddingsProvider).maxBatchSize;
|
||||
}
|
||||
|
||||
abstract embed(chunks: string[]): Promise<number[][]>;
|
||||
|
||||
get maxChunkSize(): number {
|
||||
return this.options.maxChunkSize ?? DEFAULT_MAX_CHUNK_SIZE;
|
||||
}
|
||||
|
||||
getBatchedChunks(chunks: string[]): string[][] {
|
||||
if (!this.maxBatchSize) {
|
||||
console.warn(
|
||||
`${this.getBatchedChunks.name} should only be called if 'maxBatchSize' is defined`,
|
||||
);
|
||||
|
||||
return [chunks];
|
||||
}
|
||||
|
||||
const batchedChunks = [];
|
||||
|
||||
for (let i = 0; i < chunks.length; i += this.maxBatchSize) {
|
||||
batchedChunks.push(chunks.slice(i, i + this.maxBatchSize));
|
||||
}
|
||||
|
||||
return batchedChunks;
|
||||
}
|
||||
}
|
||||
|
||||
export default BaseEmbeddingsProvider;
|
||||
|
|
@ -1,122 +0,0 @@
|
|||
import {
|
||||
BedrockRuntimeClient,
|
||||
InvokeModelCommand,
|
||||
} from "@aws-sdk/client-bedrock-runtime";
|
||||
import { fromIni } from "@aws-sdk/credential-providers";
|
||||
|
||||
import { EmbeddingsProviderName, EmbedOptions, FetchFunction } from "../../index.js";
|
||||
|
||||
import BaseEmbeddingsProvider from "./BaseEmbeddingsProvider.js";
|
||||
|
||||
interface ModelConfig {
|
||||
formatPayload: (text: string) => any;
|
||||
extractEmbeddings: (responseBody: any) => number[][];
|
||||
}
|
||||
|
||||
class BedrockEmbeddingsProvider extends BaseEmbeddingsProvider {
|
||||
static providerName: EmbeddingsProviderName = "bedrock";
|
||||
static defaultOptions: Partial<EmbedOptions> = {
|
||||
model: "amazon.titan-embed-text-v2:0",
|
||||
region: "us-east-1"
|
||||
};
|
||||
profile?: string | undefined;
|
||||
|
||||
constructor(options: EmbedOptions, fetch: FetchFunction) {
|
||||
super(options, fetch);
|
||||
this.options.model = this.options.model || BedrockEmbeddingsProvider.defaultOptions.model!;
|
||||
if (!options.apiBase) {
|
||||
options.apiBase = `https://bedrock-runtime.${options.region}.amazonaws.com`;
|
||||
}
|
||||
|
||||
if (options.profile) {
|
||||
this.profile = options.profile;
|
||||
} else {
|
||||
this.profile = "bedrock";
|
||||
}
|
||||
}
|
||||
|
||||
async embed(chunks: string[]): Promise<number[][]> {
|
||||
const credentials = await this._getCredentials();
|
||||
const client = new BedrockRuntimeClient({
|
||||
region: this.options.region,
|
||||
credentials: {
|
||||
accessKeyId: credentials.accessKeyId,
|
||||
secretAccessKey: credentials.secretAccessKey,
|
||||
sessionToken: credentials.sessionToken || "",
|
||||
},
|
||||
});
|
||||
|
||||
return (
|
||||
await Promise.all(
|
||||
chunks.map(async (chunk) => {
|
||||
const input = this._generateInvokeModelCommandInput(chunk);
|
||||
const command = new InvokeModelCommand(input);
|
||||
const response = await client.send(command);
|
||||
if (response.body) {
|
||||
const responseBody = JSON.parse(new TextDecoder().decode(response.body));
|
||||
return this._extractEmbeddings(responseBody);
|
||||
}
|
||||
return [];
|
||||
}),
|
||||
)
|
||||
).flat();
|
||||
}
|
||||
|
||||
private _generateInvokeModelCommandInput(text: string): any {
|
||||
const modelConfig = this._getModelConfig();
|
||||
const payload = modelConfig.formatPayload(text);
|
||||
|
||||
return {
|
||||
body: JSON.stringify(payload),
|
||||
modelId: this.options.model,
|
||||
accept: "*/*",
|
||||
contentType: "application/json",
|
||||
};
|
||||
}
|
||||
|
||||
private _extractEmbeddings(responseBody: any): number[][] {
|
||||
const modelConfig = this._getModelConfig();
|
||||
return modelConfig.extractEmbeddings(responseBody);
|
||||
}
|
||||
|
||||
private _getModelConfig() {
|
||||
const modelConfigs: { [key: string]: ModelConfig } = {
|
||||
"cohere": {
|
||||
formatPayload: (text: string) => ({
|
||||
texts: [text],
|
||||
input_type: "search_document",
|
||||
truncate: "END",
|
||||
}),
|
||||
extractEmbeddings: (responseBody: any) => responseBody.embeddings || [],
|
||||
},
|
||||
"amazon.titan-embed": {
|
||||
formatPayload: (text: string) => ({
|
||||
inputText: text,
|
||||
}),
|
||||
extractEmbeddings: (responseBody: any) => responseBody.embedding ? [responseBody.embedding] : [],
|
||||
},
|
||||
};
|
||||
|
||||
const modelPrefix = Object.keys(modelConfigs).find(prefix => this.options.model!.startsWith(prefix));
|
||||
if (!modelPrefix) {
|
||||
throw new Error(`Unsupported model: ${this.options.model}`);
|
||||
}
|
||||
return modelConfigs[modelPrefix];
|
||||
}
|
||||
|
||||
private async _getCredentials() {
|
||||
try {
|
||||
return await fromIni({
|
||||
profile: this.profile,
|
||||
ignoreCache: true
|
||||
})();
|
||||
} catch (e) {
|
||||
console.warn(
|
||||
`AWS profile with name ${this.profile} not found in ~/.aws/credentials, using default profile`,
|
||||
);
|
||||
return await fromIni()();
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
export default BedrockEmbeddingsProvider;
|
||||
|
|
@ -1,58 +0,0 @@
|
|||
import { Response } from "node-fetch";
|
||||
|
||||
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",
|
||||
};
|
||||
|
||||
async embed(chunks: string[]) {
|
||||
if (!this.options.apiBase?.endsWith("/")) {
|
||||
this.options.apiBase += "/";
|
||||
}
|
||||
|
||||
const batchedChunks = this.getBatchedChunks(chunks);
|
||||
return (
|
||||
await Promise.all(
|
||||
batchedChunks.map(async (batch) => {
|
||||
const fetchWithBackoff = () =>
|
||||
withExponentialBackoff<Response>(() =>
|
||||
this.fetch(new URL("embed", this.options.apiBase), {
|
||||
method: "POST",
|
||||
body: JSON.stringify({
|
||||
texts: batch,
|
||||
model: this.options.model,
|
||||
input_type: "search_document",
|
||||
embedding_types: ["float"],
|
||||
truncate: "END",
|
||||
}),
|
||||
headers: {
|
||||
Authorization: `Bearer ${this.options.apiKey}`,
|
||||
"Content-Type": "application/json",
|
||||
},
|
||||
}),
|
||||
);
|
||||
const resp = await fetchWithBackoff();
|
||||
|
||||
if (!resp.ok) {
|
||||
throw new Error(await resp.text());
|
||||
}
|
||||
|
||||
const data = (await resp.json()) as any;
|
||||
return data.embeddings.float;
|
||||
}),
|
||||
)
|
||||
).flat();
|
||||
}
|
||||
}
|
||||
|
||||
export default CohereEmbeddingsProvider;
|
||||
|
|
@ -1,18 +0,0 @@
|
|||
import { ControlPlaneProxyInfo } from "../../control-plane/analytics/IAnalyticsProvider.js";
|
||||
import { EmbeddingsProviderName } from "../../index.js";
|
||||
|
||||
import OpenAIEmbeddingsProvider from "./OpenAIEmbeddingsProvider.js";
|
||||
|
||||
class ContinueProxyEmbeddingsProvider extends OpenAIEmbeddingsProvider {
|
||||
static providerName: EmbeddingsProviderName = "continue-proxy";
|
||||
|
||||
set controlPlaneProxyInfo(value: ControlPlaneProxyInfo) {
|
||||
this.options.apiKey = value.workOsAccessToken;
|
||||
this.options.apiBase = new URL(
|
||||
"openai/v1",
|
||||
value.controlPlaneProxyUrl,
|
||||
).toString();
|
||||
}
|
||||
}
|
||||
|
||||
export default ContinueProxyEmbeddingsProvider;
|
||||
|
|
@ -1,32 +0,0 @@
|
|||
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",
|
||||
};
|
||||
|
||||
async embed(chunks: string[]) {
|
||||
const fetchWithBackoff = () =>
|
||||
withExponentialBackoff<Response>(() =>
|
||||
this.fetch(
|
||||
`https://api.deepinfra.com/v1/inference/${this.options.model}`,
|
||||
{
|
||||
method: "POST",
|
||||
headers: {
|
||||
Authorization: `bearer ${this.options.apiKey}`,
|
||||
},
|
||||
body: JSON.stringify({ inputs: chunks }),
|
||||
},
|
||||
),
|
||||
);
|
||||
const resp = await fetchWithBackoff();
|
||||
const data = await resp.json();
|
||||
return data.embeddings;
|
||||
}
|
||||
}
|
||||
|
||||
export default DeepInfraEmbeddingsProvider;
|
||||
|
|
@ -1,66 +0,0 @@
|
|||
import { Response } from "node-fetch";
|
||||
|
||||
import { getHeaders } from "../../continueServer/stubs/headers.js";
|
||||
import { TRIAL_PROXY_URL } from "../../control-plane/client.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 = {
|
||||
model: "voyage-code-2",
|
||||
};
|
||||
|
||||
constructor(options: EmbedOptions, fetch: FetchFunction) {
|
||||
super(options, fetch);
|
||||
this.options.model = FreeTrialEmbeddingsProvider.defaultOptions?.model;
|
||||
this.id = `${this.constructor.name}::${this.options.model}`;
|
||||
}
|
||||
|
||||
async embed(chunks: string[]) {
|
||||
const batchedChunks = this.getBatchedChunks(chunks);
|
||||
return (
|
||||
await Promise.all(
|
||||
batchedChunks.map(async (batch) => {
|
||||
if (batch.length === 0) {
|
||||
return [];
|
||||
}
|
||||
const fetchWithBackoff = () =>
|
||||
withExponentialBackoff<Response>(async () =>
|
||||
this.fetch(new URL("embeddings", TRIAL_PROXY_URL), {
|
||||
method: "POST",
|
||||
body: JSON.stringify({
|
||||
input: batch,
|
||||
model: this.options.model,
|
||||
}),
|
||||
headers: {
|
||||
"Content-Type": "application/json",
|
||||
...(await getHeaders()),
|
||||
},
|
||||
}),
|
||||
);
|
||||
const resp = await fetchWithBackoff();
|
||||
|
||||
if (resp.status !== 200) {
|
||||
throw new Error(
|
||||
`Failed to embed: ${resp.status} ${await resp.text()}`,
|
||||
);
|
||||
}
|
||||
|
||||
const data = (await resp.json()) as any;
|
||||
return data.embeddings;
|
||||
}),
|
||||
)
|
||||
).flat();
|
||||
}
|
||||
}
|
||||
|
||||
export default FreeTrialEmbeddingsProvider;
|
||||
|
|
@ -1,69 +0,0 @@
|
|||
import { Response } from "node-fetch";
|
||||
|
||||
import { EmbeddingsProviderName, EmbedOptions } from "../../index.js";
|
||||
import { withExponentialBackoff } from "../../util/withExponentialBackoff.js";
|
||||
|
||||
import BaseEmbeddingsProvider from "./BaseEmbeddingsProvider.js";
|
||||
|
||||
class FunctionNetworkEmbeddingsProvider extends BaseEmbeddingsProvider {
|
||||
static providerName: EmbeddingsProviderName = "function-network";
|
||||
static maxBatchSize = 128;
|
||||
|
||||
static defaultOptions: Partial<EmbedOptions> | undefined = {
|
||||
apiBase: "https://api.function.network/v1/",
|
||||
model: "baai/bge-base-en-v1.5",
|
||||
};
|
||||
|
||||
private _getEndpoint() {
|
||||
if (!this.options.apiBase) {
|
||||
throw new Error(
|
||||
"No API base URL provided. Please set the 'apiBase' option in config.json",
|
||||
);
|
||||
}
|
||||
|
||||
this.options.apiBase = this.options.apiBase.endsWith("/")
|
||||
? this.options.apiBase
|
||||
: `${this.options.apiBase}/`;
|
||||
return new URL("embeddings", this.options.apiBase);
|
||||
}
|
||||
|
||||
async embed(chunks: string[]) {
|
||||
const batchedChunks = this.getBatchedChunks(chunks);
|
||||
return (
|
||||
await Promise.all(
|
||||
batchedChunks.map(async (batch) => {
|
||||
if (batch.length === 0) {
|
||||
return [];
|
||||
}
|
||||
|
||||
const fetchWithBackoff = () =>
|
||||
withExponentialBackoff<Response>(() =>
|
||||
this.fetch(this._getEndpoint(), {
|
||||
method: "POST",
|
||||
body: JSON.stringify({
|
||||
input: batch,
|
||||
model: this.options.model,
|
||||
}),
|
||||
headers: {
|
||||
Authorization: `Bearer ${this.options.apiKey}`,
|
||||
"Content-Type": "application/json",
|
||||
},
|
||||
}),
|
||||
);
|
||||
const resp = await fetchWithBackoff();
|
||||
|
||||
if (!resp.ok) {
|
||||
throw new Error(await resp.text());
|
||||
}
|
||||
|
||||
const data = (await resp.json()) as any;
|
||||
return data.data.map(
|
||||
(result: { embedding: number[] }) => result.embedding,
|
||||
);
|
||||
}),
|
||||
)
|
||||
).flat();
|
||||
}
|
||||
}
|
||||
|
||||
export default FunctionNetworkEmbeddingsProvider;
|
||||
|
|
@ -1,69 +0,0 @@
|
|||
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 = 100;
|
||||
|
||||
static defaultOptions = {
|
||||
apiBase: "https://generativelanguage.googleapis.com/v1/",
|
||||
model: "models/text-embedding-004",
|
||||
};
|
||||
|
||||
get urlPath(): string {
|
||||
return `${this.options.model}:batchEmbedContents`;
|
||||
}
|
||||
|
||||
async getSingleBatchEmbedding(batch: string[]) {
|
||||
// Batch embed endpoint: https://ai.google.dev/api/embeddings?authuser=1#EmbedContentRequest
|
||||
const requests = batch.map((text) => ({
|
||||
model: this.options.model,
|
||||
content: {
|
||||
role: "user",
|
||||
parts: [{ text }],
|
||||
},
|
||||
}));
|
||||
|
||||
const fetchWithBackoff = () =>
|
||||
withExponentialBackoff<Response>(() =>
|
||||
this.fetch(new URL(this.urlPath, this.options.apiBase), {
|
||||
method: "POST",
|
||||
body: JSON.stringify({
|
||||
requests,
|
||||
}),
|
||||
headers: {
|
||||
"x-goog-api-key": this.options.apiKey,
|
||||
"Content-Type": "application/json",
|
||||
},
|
||||
}),
|
||||
);
|
||||
|
||||
const resp = await fetchWithBackoff();
|
||||
|
||||
if (!resp.ok) {
|
||||
throw new Error(await resp.text());
|
||||
}
|
||||
|
||||
const data = (await resp.json()) as any;
|
||||
|
||||
return data.embeddings.map((embedding: any) => embedding.values);
|
||||
}
|
||||
|
||||
async embed(chunks: string[]) {
|
||||
const batchedChunks = this.getBatchedChunks(chunks);
|
||||
|
||||
const results = await Promise.all(
|
||||
batchedChunks.map((batch) => this.getSingleBatchEmbedding(batch)),
|
||||
);
|
||||
return results.flat();
|
||||
}
|
||||
}
|
||||
|
||||
export default GeminiEmbeddingsProvider;
|
||||
|
|
@ -1,14 +0,0 @@
|
|||
import { EmbeddingsProviderName, EmbedOptions } from "../..";
|
||||
|
||||
import OpenAIEmbeddingsProvider from "./OpenAIEmbeddingsProvider";
|
||||
|
||||
class LMStudioEmbeddingsProvider extends OpenAIEmbeddingsProvider {
|
||||
static providerName: EmbeddingsProviderName = "lmstudio";
|
||||
|
||||
static defaultOptions: Partial<EmbedOptions> | undefined = {
|
||||
apiBase: "http://localhost:1234/v1",
|
||||
model: "nomic-ai/nomic-embed-text-v1.5-GGUF",
|
||||
};
|
||||
}
|
||||
|
||||
export default LMStudioEmbeddingsProvider;
|
||||
|
|
@ -1,15 +0,0 @@
|
|||
import { EmbeddingsProviderName, EmbedOptions } from "../../index.js";
|
||||
|
||||
import OpenAIEmbeddingsProvider from "./OpenAIEmbeddingsProvider.js";
|
||||
|
||||
class MistralEmbeddingsProvider extends OpenAIEmbeddingsProvider {
|
||||
static providerName: EmbeddingsProviderName = "mistral";
|
||||
static maxBatchSize = 128;
|
||||
|
||||
static defaultOptions: Partial<EmbedOptions> | undefined = {
|
||||
apiBase: "https://api.mistral.ai/v1/",
|
||||
model: "mistral-embed",
|
||||
};
|
||||
}
|
||||
|
||||
export default MistralEmbeddingsProvider;
|
||||
|
|
@ -1,14 +0,0 @@
|
|||
import { EmbeddingsProviderName, EmbedOptions } from "../..";
|
||||
|
||||
import OpenAIEmbeddingsProvider from "./OpenAIEmbeddingsProvider";
|
||||
|
||||
class NebiusEmbeddingsProvider extends OpenAIEmbeddingsProvider {
|
||||
static providerName: EmbeddingsProviderName = "nebius";
|
||||
|
||||
static defaultOptions: Partial<EmbedOptions> | undefined = {
|
||||
apiBase: "https://api.studio.nebius.ai/v1/",
|
||||
model: "BAAI/bge-en-icl",
|
||||
};
|
||||
}
|
||||
|
||||
export default NebiusEmbeddingsProvider;
|
||||
|
|
@ -1,82 +0,0 @@
|
|||
import { Response } from "node-fetch";
|
||||
|
||||
import { EmbeddingsProviderName, EmbedOptions } from "../../index.js";
|
||||
import { withExponentialBackoff } from "../../util/withExponentialBackoff.js";
|
||||
|
||||
import BaseEmbeddingsProvider from "./BaseEmbeddingsProvider.js";
|
||||
|
||||
class NvidiaEmbeddingsProvider extends BaseEmbeddingsProvider {
|
||||
static maxBatchSize = 96;
|
||||
|
||||
static providerName: EmbeddingsProviderName = "nvidia";
|
||||
|
||||
static defaultOptions: Partial<EmbedOptions> | undefined = {
|
||||
apiBase: "https://integrate.api.nvidia.com/v1/",
|
||||
model: "nvidia/nv-embedqa-mistral-7b-v2",
|
||||
};
|
||||
|
||||
async embed(chunks: string[]) {
|
||||
|
||||
if (!this.options.apiBase?.endsWith("/")) {
|
||||
this.options.apiBase += "/";
|
||||
}
|
||||
|
||||
const batchedChunks = [];
|
||||
for (
|
||||
let i = 0;
|
||||
i < chunks.length;
|
||||
i += NvidiaEmbeddingsProvider.maxBatchSize
|
||||
) {
|
||||
batchedChunks.push(
|
||||
chunks.slice(i, i + NvidiaEmbeddingsProvider.maxBatchSize),
|
||||
);
|
||||
}
|
||||
return (
|
||||
await Promise.all(
|
||||
batchedChunks.map(async (batch) => {
|
||||
if (batch.length === 0) {
|
||||
return [];
|
||||
}
|
||||
|
||||
// Input list must be non empty and all elements must be non empty, therefore, for all empty elements replace it with a token
|
||||
const emptyToken = "[EMPTY]";
|
||||
for (let i = 0; i < batch.length; i++) {
|
||||
if (batch[i].trim() === "") {
|
||||
batch[i] = emptyToken;
|
||||
}
|
||||
}
|
||||
|
||||
const fetchWithBackoff = () =>
|
||||
withExponentialBackoff<Response>(() =>
|
||||
this.fetch(new URL("embeddings", this.options.apiBase), {
|
||||
method: "POST",
|
||||
body: JSON.stringify({
|
||||
input: batch,
|
||||
model: this.options.model,
|
||||
input_type: "passage",
|
||||
truncate: "END",
|
||||
}),
|
||||
headers: {
|
||||
Authorization: `Bearer ${this.options.apiKey}`,
|
||||
"Content-Type": "application/json",
|
||||
},
|
||||
}),
|
||||
);
|
||||
|
||||
const resp = await fetchWithBackoff();
|
||||
|
||||
if (!resp.ok) {
|
||||
throw new Error(await resp.text());
|
||||
}
|
||||
|
||||
const data = (await resp.json()) as any;
|
||||
return data.data.map(
|
||||
(result: { embedding: number[] }) => result.embedding,
|
||||
);
|
||||
}),
|
||||
)
|
||||
).flat();
|
||||
}
|
||||
}
|
||||
|
||||
export default NvidiaEmbeddingsProvider;
|
||||
|
|
@ -1,71 +0,0 @@
|
|||
import {
|
||||
EmbeddingsProviderName,
|
||||
EmbedOptions,
|
||||
FetchFunction,
|
||||
} from "../../index.js";
|
||||
import { withExponentialBackoff } from "../../util/withExponentialBackoff.js";
|
||||
|
||||
import BaseEmbeddingsProvider, {
|
||||
IBaseEmbeddingsProvider,
|
||||
} from "./BaseEmbeddingsProvider.js";
|
||||
|
||||
async function embedOneBatch(
|
||||
chunks: string[],
|
||||
options: EmbedOptions,
|
||||
customFetch: FetchFunction,
|
||||
) {
|
||||
const embedding = await withExponentialBackoff<number[][]>(async () => {
|
||||
let apiBase = options.apiBase!;
|
||||
|
||||
if (!apiBase.endsWith("/")) {
|
||||
apiBase += "/";
|
||||
}
|
||||
|
||||
const resp = await customFetch(new URL("api/embed", apiBase), {
|
||||
method: "POST",
|
||||
body: JSON.stringify({
|
||||
model: options.model,
|
||||
input: chunks,
|
||||
}),
|
||||
headers: {
|
||||
"Content-Type": "application/json",
|
||||
Authorization: `Bearer ${options.apiKey}`,
|
||||
},
|
||||
});
|
||||
|
||||
if (!resp.ok) {
|
||||
throw new Error(`Failed to embed chunk: ${await resp.text()}`);
|
||||
}
|
||||
|
||||
const data = await resp.json();
|
||||
const embedding: number[][] = data.embeddings;
|
||||
|
||||
if (!embedding || embedding.length === 0) {
|
||||
throw new Error("Ollama generated empty embedding");
|
||||
}
|
||||
return embedding;
|
||||
});
|
||||
|
||||
return embedding;
|
||||
}
|
||||
|
||||
class OllamaEmbeddingsProvider extends BaseEmbeddingsProvider {
|
||||
static providerName: EmbeddingsProviderName = "ollama";
|
||||
static defaultOptions: IBaseEmbeddingsProvider["defaultOptions"] = {
|
||||
apiBase: "http://localhost:11434/",
|
||||
model: "nomic-embed-text",
|
||||
maxBatchSize: 64,
|
||||
};
|
||||
|
||||
async embed(chunks: string[]) {
|
||||
const batchedChunks = this.getBatchedChunks(chunks);
|
||||
var results: number[][] = [];
|
||||
|
||||
for (const batch of batchedChunks) {
|
||||
results.push(...await embedOneBatch(batch, this.options, this.fetch));
|
||||
}
|
||||
return results;
|
||||
}
|
||||
}
|
||||
|
||||
export default OllamaEmbeddingsProvider;
|
||||
|
|
@ -1,80 +0,0 @@
|
|||
import { Response } from "node-fetch";
|
||||
|
||||
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;
|
||||
|
||||
static defaultOptions: Partial<EmbedOptions> | undefined = {
|
||||
apiBase: "https://api.openai.com/v1/",
|
||||
model: "text-embedding-3-small",
|
||||
apiVersion: "2024-02-15-preview",
|
||||
};
|
||||
|
||||
private _getEndpoint() {
|
||||
if (!this.options.apiBase) {
|
||||
throw new Error(
|
||||
"No API base URL provided. Please set the 'apiBase' option in config.json",
|
||||
);
|
||||
}
|
||||
|
||||
this.options.apiBase = this.options.apiBase.endsWith("/")
|
||||
? this.options.apiBase
|
||||
: `${this.options.apiBase}/`;
|
||||
|
||||
if (this.options.apiType === "azure") {
|
||||
return new URL(
|
||||
`openai/deployments/${this.options.deployment}/embeddings?api-version=${this.options.apiVersion}`,
|
||||
this.options.apiBase,
|
||||
);
|
||||
}
|
||||
return new URL("embeddings", this.options.apiBase);
|
||||
}
|
||||
|
||||
async embed(chunks: string[]) {
|
||||
const batchedChunks = this.getBatchedChunks(chunks);
|
||||
return (
|
||||
await Promise.all(
|
||||
batchedChunks.map(async (batch) => {
|
||||
if (batch.length === 0) {
|
||||
return [];
|
||||
}
|
||||
|
||||
const fetchWithBackoff = () =>
|
||||
withExponentialBackoff<Response>(() =>
|
||||
this.fetch(this._getEndpoint(), {
|
||||
method: "POST",
|
||||
body: JSON.stringify({
|
||||
input: batch,
|
||||
model: this.options.model,
|
||||
}),
|
||||
headers: {
|
||||
Authorization: `Bearer ${this.options.apiKey}`,
|
||||
"Content-Type": "application/json",
|
||||
"api-key": this.options.apiKey ?? "", // For Azure
|
||||
},
|
||||
}),
|
||||
);
|
||||
const resp = await fetchWithBackoff();
|
||||
|
||||
if (!resp.ok) {
|
||||
throw new Error(await resp.text());
|
||||
}
|
||||
|
||||
const data = (await resp.json()) as any;
|
||||
return data.data.map(
|
||||
(result: { embedding: number[] }) => result.embedding,
|
||||
);
|
||||
}),
|
||||
)
|
||||
).flat();
|
||||
}
|
||||
}
|
||||
|
||||
export default OpenAIEmbeddingsProvider;
|
||||
|
|
@ -1,114 +0,0 @@
|
|||
import {
|
||||
InvokeEndpointCommand,
|
||||
SageMakerRuntimeClient,
|
||||
} from "@aws-sdk/client-sagemaker-runtime";
|
||||
import { fromIni } from "@aws-sdk/credential-providers";
|
||||
|
||||
import {
|
||||
EmbeddingsProviderName,
|
||||
EmbedOptions,
|
||||
FetchFunction,
|
||||
} from "../../index.js";
|
||||
|
||||
import BaseEmbeddingsProvider from "./BaseEmbeddingsProvider.js";
|
||||
|
||||
|
||||
class SageMakerEmbeddingsProvider extends BaseEmbeddingsProvider {
|
||||
static providerName: EmbeddingsProviderName = "sagemaker";
|
||||
|
||||
static defaultOptions: Partial<EmbedOptions> | undefined = {
|
||||
region: "us-west-2",
|
||||
maxBatchSize: 1,
|
||||
};
|
||||
profile?: string | undefined;
|
||||
|
||||
constructor(options: EmbedOptions, fetch: FetchFunction) {
|
||||
super(options, fetch);
|
||||
if (!options.apiBase) {
|
||||
options.apiBase = `https://runtime.sagemaker.${options.region}.amazonaws.com`;
|
||||
}
|
||||
|
||||
if (options.profile) {
|
||||
this.profile = options.profile;
|
||||
} else {
|
||||
this.profile = "sagemaker";
|
||||
}
|
||||
}
|
||||
|
||||
async embed(chunks: string[]) {
|
||||
const credentials = await this._getCredentials();
|
||||
const client = new SageMakerRuntimeClient({
|
||||
region: this.options.region,
|
||||
credentials: {
|
||||
accessKeyId: credentials.accessKeyId,
|
||||
secretAccessKey: credentials.secretAccessKey,
|
||||
sessionToken: credentials.sessionToken || "",
|
||||
},
|
||||
});
|
||||
|
||||
const batchedChunks = this.getBatchedChunks(chunks);
|
||||
return (
|
||||
await Promise.all(
|
||||
batchedChunks.map(async (batch) => {
|
||||
const input = this._generateInvokeModelCommandInput(
|
||||
batch,
|
||||
this.options,
|
||||
);
|
||||
const command = new InvokeEndpointCommand(input);
|
||||
const response = await client.send(command);
|
||||
|
||||
if (response.Body) {
|
||||
const responseBody = JSON.parse(
|
||||
new TextDecoder().decode(response.Body),
|
||||
);
|
||||
// If the body contains a key called "embedding" or "embeddings", return the value, otherwise return the whole body
|
||||
if (responseBody.embedding) {
|
||||
return responseBody.embedding;
|
||||
} else if (responseBody.embeddings) {
|
||||
return responseBody.embeddings;
|
||||
} else {
|
||||
return responseBody;
|
||||
}
|
||||
}
|
||||
}),
|
||||
)
|
||||
).flat();
|
||||
}
|
||||
private _generateInvokeModelCommandInput(
|
||||
prompts: string | string[],
|
||||
options: EmbedOptions,
|
||||
): any {
|
||||
const payload = {
|
||||
inputs: prompts,
|
||||
normalize: true,
|
||||
// ...(options.requestOptions?.extraBodyProperties || {}),
|
||||
};
|
||||
|
||||
if (options.requestOptions?.extraBodyProperties) {
|
||||
Object.assign(payload, options.requestOptions.extraBodyProperties);
|
||||
}
|
||||
|
||||
return {
|
||||
EndpointName: this.options.model,
|
||||
Body: JSON.stringify(payload),
|
||||
ContentType: "application/json",
|
||||
CustomAttributes: "accept_eula=false",
|
||||
};
|
||||
}
|
||||
|
||||
private async _getCredentials() {
|
||||
try {
|
||||
return await fromIni({
|
||||
profile: this.profile,
|
||||
ignoreCache: true,
|
||||
})();
|
||||
} catch (e) {
|
||||
console.warn(
|
||||
`AWS profile with name ${this.profile} not found in ~/.aws/credentials, using default profile`,
|
||||
);
|
||||
return await fromIni()();
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
export default SageMakerEmbeddingsProvider;
|
||||
|
|
@ -1,14 +0,0 @@
|
|||
import { EmbeddingsProviderName, EmbedOptions } from "../..";
|
||||
|
||||
import OpenAIEmbeddingsProvider from "./OpenAIEmbeddingsProvider";
|
||||
|
||||
class SiliconFlowEmbeddingsProvider extends OpenAIEmbeddingsProvider {
|
||||
static providerName: EmbeddingsProviderName = "siliconflow";
|
||||
|
||||
static defaultOptions: Partial<EmbedOptions> | undefined = {
|
||||
apiBase: "https://api.siliconflow.cn/v1/",
|
||||
model: "BAAI/bge-m3",
|
||||
};
|
||||
}
|
||||
|
||||
export default SiliconFlowEmbeddingsProvider;
|
||||
|
|
@ -1,91 +0,0 @@
|
|||
import { GoogleAuth } from "google-auth-library";
|
||||
import { Response } from "node-fetch";
|
||||
|
||||
import { EmbeddingsProviderName, EmbedOptions, FetchFunction } from "../../index.js";
|
||||
import { withExponentialBackoff } from "../../util/withExponentialBackoff.js";
|
||||
|
||||
import BaseEmbeddingsProvider from "./BaseEmbeddingsProvider.js";
|
||||
|
||||
/**
|
||||
* [View the Vertex Text Embedding docs.](https://cloud.google.com/vertex-ai/generative-ai/docs/embeddings/get-text-embeddings)
|
||||
*/
|
||||
class VertexEmbeddingsProvider extends BaseEmbeddingsProvider {
|
||||
static providerName: EmbeddingsProviderName = "vertexai";
|
||||
declare apiBase: string;
|
||||
|
||||
|
||||
static defaultOptions: Partial<EmbedOptions> | undefined = {
|
||||
model: "text-embedding-004",
|
||||
maxBatchSize: 5,
|
||||
region: "us-central1"
|
||||
};
|
||||
|
||||
private clientPromise = new GoogleAuth({
|
||||
scopes: "https://www.googleapis.com/auth/cloud-platform",
|
||||
}).getClient();
|
||||
|
||||
private static getDefaultApiBaseFrom(options: EmbedOptions) {
|
||||
const { region, projectId } = options;
|
||||
if (!region || !projectId) {
|
||||
throw new Error(
|
||||
"region and projectId must be defined if apiBase is not provided",
|
||||
);
|
||||
}
|
||||
|
||||
return `https://${region}-aiplatform.googleapis.com/v1/projects/${projectId}/locations/${region}`;
|
||||
}
|
||||
|
||||
|
||||
|
||||
constructor(options: EmbedOptions, fetch: FetchFunction) {
|
||||
super(options, fetch);
|
||||
this.apiBase ??= VertexEmbeddingsProvider.getDefaultApiBaseFrom(options);
|
||||
|
||||
}
|
||||
|
||||
|
||||
|
||||
get urlPath(): string {
|
||||
return `/publishers/google/models/${this.options.model}:predict`;
|
||||
}
|
||||
|
||||
async embed(chunks: string[]) {
|
||||
const client = await this.clientPromise;
|
||||
const { token } = await client.getAccessToken();
|
||||
if (!token) {
|
||||
throw new Error(
|
||||
"Could not get an access token. Set up your Google Application Default Credentials.",
|
||||
);
|
||||
}
|
||||
const batchedChunks = this.getBatchedChunks(chunks);
|
||||
|
||||
return (
|
||||
await Promise.all(
|
||||
batchedChunks.map(async (batch) => {
|
||||
const fetchWithBackoff = () =>
|
||||
withExponentialBackoff<Response>(() =>
|
||||
this.fetch(new URL(this.apiBase + this.urlPath), {
|
||||
method: "POST",
|
||||
body: JSON.stringify({
|
||||
instances: batch.map((chunk) => ({ content: chunk })),
|
||||
}),
|
||||
headers: {
|
||||
"Content-Type": "application/json",
|
||||
Authorization: `Bearer ${token}`,
|
||||
},
|
||||
}),
|
||||
);
|
||||
const resp = await fetchWithBackoff();
|
||||
|
||||
if (!resp.ok) {
|
||||
throw new Error(await resp.text());
|
||||
}
|
||||
|
||||
const data = (await resp.json()) as any;
|
||||
return data.predictions.map((prediction: any) => prediction.embeddings.values);
|
||||
}),
|
||||
)
|
||||
).flat();
|
||||
}
|
||||
}
|
||||
export default VertexEmbeddingsProvider;
|
||||
|
|
@ -1,14 +0,0 @@
|
|||
import { EmbeddingsProviderName, EmbedOptions } from "../..";
|
||||
|
||||
import OpenAIEmbeddingsProvider from "./OpenAIEmbeddingsProvider";
|
||||
|
||||
class VoyageEmbeddingsProvider extends OpenAIEmbeddingsProvider {
|
||||
static providerName: EmbeddingsProviderName = "voyage";
|
||||
|
||||
static defaultOptions: Partial<EmbedOptions> | undefined = {
|
||||
apiBase: "https://api.voyageai.com/v1/",
|
||||
model: "voyage-code-2",
|
||||
};
|
||||
}
|
||||
|
||||
export default VoyageEmbeddingsProvider;
|
||||
|
|
@ -1,151 +0,0 @@
|
|||
import {
|
||||
EmbeddingsProviderName,
|
||||
EmbedOptions,
|
||||
FetchFunction,
|
||||
} from "../../index.js";
|
||||
import { withExponentialBackoff } from "../../util/withExponentialBackoff.js";
|
||||
|
||||
import BaseEmbeddingsProvider, {
|
||||
IBaseEmbeddingsProvider,
|
||||
} from "./BaseEmbeddingsProvider.js";
|
||||
|
||||
let accessToken = {
|
||||
expiration: 0,
|
||||
token: "",
|
||||
};
|
||||
|
||||
|
||||
class WatsonxEmbeddingsProvider extends BaseEmbeddingsProvider {
|
||||
static providerName: EmbeddingsProviderName = "watsonx";
|
||||
static maxBatchSize = 1000;
|
||||
static defaultOptions: Partial<EmbedOptions> | undefined = {
|
||||
model: "ibm/slate-125m-english-rtrvr-v2",
|
||||
};
|
||||
|
||||
async getBearerToken(): Promise<{ token: string; expiration: number }> {
|
||||
if (
|
||||
this.options.apiBase?.includes("cloud.ibm.com")
|
||||
) {
|
||||
// watsonx SaaS
|
||||
const wxToken = await (
|
||||
await fetch(
|
||||
`https://iam.cloud.ibm.com/identity/token?apikey=${this.options.apiKey}&grant_type=urn:ibm:params:oauth:grant-type:apikey`,
|
||||
{
|
||||
method: "POST",
|
||||
headers: {
|
||||
"Content-Type": "application/x-www-form-urlencoded",
|
||||
Accept: "application/json",
|
||||
},
|
||||
},
|
||||
)
|
||||
).json();
|
||||
return {
|
||||
token: wxToken["access_token"],
|
||||
expiration: wxToken["expiration"],
|
||||
};
|
||||
} else {
|
||||
// watsonx Software
|
||||
if (!this.options.apiKey?.includes(":")) {
|
||||
// Using ZenApiKey auth
|
||||
return {
|
||||
token: this.options.apiKey ?? "",
|
||||
expiration: -1,
|
||||
};
|
||||
} else {
|
||||
// Using username/password auth
|
||||
const userPass = this.options.apiKey?.split(":");
|
||||
const wxToken = await (
|
||||
await fetch(`${this.options.apiBase}/icp4d-api/v1/authorize`, {
|
||||
method: "POST",
|
||||
headers: {
|
||||
"Content-Type": "application/json",
|
||||
Accept: "application/json",
|
||||
},
|
||||
body: JSON.stringify({
|
||||
username: userPass[0],
|
||||
password: userPass[1],
|
||||
}),
|
||||
})
|
||||
).json();
|
||||
const wxTokenExpiry = await (
|
||||
await fetch(
|
||||
`${this.options.apiBase}/usermgmt/v1/user/tokenExpiry`,
|
||||
{
|
||||
method: "GET",
|
||||
headers: {
|
||||
Accept: "application/json",
|
||||
Authorization: `Bearer ${wxToken["token"]}`,
|
||||
},
|
||||
},
|
||||
)
|
||||
).json();
|
||||
return {
|
||||
token: wxToken["token"],
|
||||
expiration: wxTokenExpiry["exp"],
|
||||
};
|
||||
}
|
||||
}
|
||||
}
|
||||
async getSingleBatchEmbedding(batch: string[]) {
|
||||
var now = new Date().getTime() / 1000;
|
||||
if (
|
||||
accessToken === undefined ||
|
||||
now > accessToken.expiration ||
|
||||
accessToken.token === undefined
|
||||
) {
|
||||
accessToken = await this.getBearerToken();
|
||||
} else {
|
||||
console.log(
|
||||
`Reusing token (expires in ${(accessToken.expiration - now) / 60
|
||||
} mins)`,
|
||||
);
|
||||
}
|
||||
return await withExponentialBackoff<number[][]>(async () => {
|
||||
const payload: any = {
|
||||
inputs: batch,
|
||||
parameters: {
|
||||
truncate_input_tokens: 500,
|
||||
return_options: { input_text: false },
|
||||
},
|
||||
model_id: this.options.model,
|
||||
project_id: this.options.projectId,
|
||||
};
|
||||
const headers = {
|
||||
"Content-Type": "application/json",
|
||||
Authorization: `${accessToken.expiration === -1 ? "ZenApiKey" : "Bearer"
|
||||
} ${accessToken.token}`,
|
||||
};
|
||||
const resp = await this.fetch(
|
||||
new URL(
|
||||
`${this.options.apiBase}/ml/v1/text/embeddings?version=${this.options.apiVersion}`,
|
||||
),
|
||||
{
|
||||
method: "POST",
|
||||
body: JSON.stringify(payload),
|
||||
headers: headers,
|
||||
},
|
||||
);
|
||||
|
||||
if (!resp.ok) {
|
||||
throw new Error(`Failed to embed chunk: ${await resp.text()}`);
|
||||
}
|
||||
const data = await resp.json();
|
||||
const embeddings = data.results;
|
||||
|
||||
if (!embeddings || embeddings.length === 0) {
|
||||
throw new Error("Watsonx generated empty embedding");
|
||||
}
|
||||
return embeddings.map((e: any) => e.embedding);
|
||||
});
|
||||
}
|
||||
|
||||
async embed(chunks: string[]) {
|
||||
const batchedChunks = this.getBatchedChunks(chunks);
|
||||
const results = await Promise.all(
|
||||
batchedChunks.map((batch) => this.getSingleBatchEmbedding(batch)),
|
||||
);
|
||||
return results.flat();
|
||||
}
|
||||
}
|
||||
|
||||
export default WatsonxEmbeddingsProvider;
|
||||
|
|
@ -1,53 +0,0 @@
|
|||
import { EmbeddingsProviderName } from "../../index.js";
|
||||
|
||||
import BaseEmbeddingsProvider from "./BaseEmbeddingsProvider.js";
|
||||
import BedrockEmbeddingsProvider from "./BedrockEmbeddingsProvider.js";
|
||||
import CohereEmbeddingsProvider from "./CohereEmbeddingsProvider.js";
|
||||
import ContinueProxyEmbeddingsProvider from "./ContinueProxyEmbeddingsProvider.js";
|
||||
import DeepInfraEmbeddingsProvider from "./DeepInfraEmbeddingsProvider.js";
|
||||
import FreeTrialEmbeddingsProvider from "./FreeTrialEmbeddingsProvider.js";
|
||||
import FunctionNetworkEmbeddingsProvider from "./FunctionNetworkEmbeddingsProvider.js";
|
||||
import GeminiEmbeddingsProvider from "./GeminiEmbeddingsProvider.js";
|
||||
import HuggingFaceTEIEmbeddingsProvider from "./HuggingFaceTEIEmbeddingsProvider.js";
|
||||
import LMStudioEmbeddingsProvider from "./LMStudio.js";
|
||||
import MistralEmbeddingsProvider from "./MistralEmbeddingsProvider.js";
|
||||
import NebiusEmbeddingsProvider from "./NebiusEmbeddingsProvider.js";
|
||||
import NvidiaEmbeddingsProvider from "./NvidiaEmbeddingsProvider.js";
|
||||
import OllamaEmbeddingsProvider from "./OllamaEmbeddingsProvider.js";
|
||||
import OpenAIEmbeddingsProvider from "./OpenAIEmbeddingsProvider.js";
|
||||
import SageMakerEmbeddingsProvider from "./SageMakerEmbeddingsProvider.js";
|
||||
import SiliconFlowEmbeddingsProvider from "./SiliconFlowEmbeddingsProvider.js";
|
||||
import TransformersJsEmbeddingsProvider from "./TransformersJsEmbeddingsProvider.js";
|
||||
import VertexEmbeddingsProvider from "./VertexEmbeddingsProvider.js";
|
||||
import VoyageEmbeddingsProvider from "./VoyageEmbeddingsProvider.js";
|
||||
import WatsonxEmbeddingsProvider from "./WatsonxEmbeddingsProvider.js";
|
||||
|
||||
type EmbeddingsProviderConstructor = new (
|
||||
...args: any[]
|
||||
) => BaseEmbeddingsProvider;
|
||||
|
||||
export const allEmbeddingsProviders: Record<
|
||||
EmbeddingsProviderName,
|
||||
EmbeddingsProviderConstructor
|
||||
> = {
|
||||
sagemaker: SageMakerEmbeddingsProvider,
|
||||
bedrock: BedrockEmbeddingsProvider,
|
||||
ollama: OllamaEmbeddingsProvider,
|
||||
"transformers.js": TransformersJsEmbeddingsProvider,
|
||||
openai: OpenAIEmbeddingsProvider,
|
||||
cohere: CohereEmbeddingsProvider,
|
||||
"free-trial": FreeTrialEmbeddingsProvider,
|
||||
"function-network": FunctionNetworkEmbeddingsProvider,
|
||||
"huggingface-tei": HuggingFaceTEIEmbeddingsProvider,
|
||||
gemini: GeminiEmbeddingsProvider,
|
||||
"continue-proxy": ContinueProxyEmbeddingsProvider,
|
||||
deepinfra: DeepInfraEmbeddingsProvider,
|
||||
nvidia: NvidiaEmbeddingsProvider,
|
||||
voyage: VoyageEmbeddingsProvider,
|
||||
mistral: MistralEmbeddingsProvider,
|
||||
nebius: NebiusEmbeddingsProvider,
|
||||
vertexai: VertexEmbeddingsProvider,
|
||||
watsonx: WatsonxEmbeddingsProvider,
|
||||
lmstudio: LMStudioEmbeddingsProvider,
|
||||
siliconflow: SiliconFlowEmbeddingsProvider,
|
||||
};
|
||||
|
|
@ -1,4 +1,4 @@
|
|||
import { ModelCapability, ModelProvider, TemplateType } from "../index.js";
|
||||
import { ModelCapability, TemplateType } from "../index.js";
|
||||
|
||||
import {
|
||||
anthropicTemplateMessages,
|
||||
|
|
@ -36,7 +36,7 @@ import {
|
|||
zephyrEditPrompt,
|
||||
} from "./templates/edit.js";
|
||||
|
||||
const PROVIDER_HANDLES_TEMPLATING: ModelProvider[] = [
|
||||
const PROVIDER_HANDLES_TEMPLATING: string[] = [
|
||||
"lmstudio",
|
||||
"openai",
|
||||
"ollama",
|
||||
|
|
@ -52,7 +52,7 @@ const PROVIDER_HANDLES_TEMPLATING: ModelProvider[] = [
|
|||
"watsonx",
|
||||
];
|
||||
|
||||
const PROVIDER_SUPPORTS_IMAGES: ModelProvider[] = [
|
||||
const PROVIDER_SUPPORTS_IMAGES: string[] = [
|
||||
"openai",
|
||||
"ollama",
|
||||
"gemini",
|
||||
|
|
@ -92,7 +92,7 @@ function modelSupportsTools(modelName: string) {
|
|||
}
|
||||
|
||||
function modelSupportsImages(
|
||||
provider: ModelProvider,
|
||||
provider: string,
|
||||
model: string,
|
||||
title: string | undefined,
|
||||
capabilities: ModelCapability | undefined,
|
||||
|
|
@ -115,7 +115,7 @@ function modelSupportsImages(
|
|||
|
||||
return false;
|
||||
}
|
||||
const PARALLEL_PROVIDERS: ModelProvider[] = [
|
||||
const PARALLEL_PROVIDERS: string[] = [
|
||||
"anthropic",
|
||||
"bedrock",
|
||||
"sagemaker",
|
||||
|
|
@ -134,10 +134,7 @@ const PARALLEL_PROVIDERS: ModelProvider[] = [
|
|||
"function-network",
|
||||
];
|
||||
|
||||
function llmCanGenerateInParallel(
|
||||
provider: ModelProvider,
|
||||
model: string,
|
||||
): boolean {
|
||||
function llmCanGenerateInParallel(provider: string, model: string): boolean {
|
||||
if (provider === "openai") {
|
||||
return model.includes("gpt");
|
||||
}
|
||||
|
|
@ -241,7 +238,7 @@ function autodetectTemplateType(model: string): TemplateType | undefined {
|
|||
|
||||
function autodetectTemplateFunction(
|
||||
model: string,
|
||||
provider: ModelProvider,
|
||||
provider: string,
|
||||
explicitTemplate: TemplateType | undefined = undefined,
|
||||
) {
|
||||
if (
|
||||
|
|
|
|||
|
|
@ -30,11 +30,13 @@ const TOKEN_BUFFER_FOR_SAFETY = 350;
|
|||
const PROXY_URL = "http://localhost:65433";
|
||||
|
||||
const DEFAULT_MAX_CHUNK_SIZE = 500; // 512 - buffer for safety (in case of differing tokenizers)
|
||||
const DEFAULT_MAX_BATCH_SIZE = 64;
|
||||
|
||||
export {
|
||||
CONTEXT_LENGTH_FOR_MODEL,
|
||||
DEFAULT_ARGS,
|
||||
DEFAULT_CONTEXT_LENGTH,
|
||||
DEFAULT_MAX_BATCH_SIZE,
|
||||
DEFAULT_MAX_CHUNK_SIZE,
|
||||
DEFAULT_MAX_TOKENS,
|
||||
PROXY_URL,
|
||||
|
|
|
|||
|
|
@ -1,9 +1,9 @@
|
|||
import { ChatMessage, LLMOptions, ModelProvider } from "..";
|
||||
import { ChatMessage, LLMOptions } from "..";
|
||||
|
||||
import { BaseLLM } from ".";
|
||||
|
||||
class DummyLLM extends BaseLLM {
|
||||
static providerName: ModelProvider = "openai";
|
||||
static providerName = "openai";
|
||||
static defaultOptions: Partial<LLMOptions> = {
|
||||
model: "dummy-model",
|
||||
contextLength: 200_000,
|
||||
|
|
@ -123,7 +123,7 @@ describe("BaseLLM", () => {
|
|||
expect(baseLLM.supportsPrefill()).toBe(false);
|
||||
|
||||
class PrefillLLM extends BaseLLM {
|
||||
static providerName: ModelProvider = "ollama";
|
||||
static providerName = "ollama";
|
||||
}
|
||||
const prefillLLM = new PrefillLLM({ model: "some-model" });
|
||||
expect(prefillLLM.supportsPrefill()).toBe(true);
|
||||
|
|
|
|||
|
|
@ -1,16 +1,17 @@
|
|||
import { fetchwithRequestOptions } from "@continuedev/fetch";
|
||||
import { findLlmInfo } from "@continuedev/llm-info";
|
||||
import { BaseLlmApi, constructLlmApi } from "@continuedev/openai-adapters";
|
||||
import Handlebars from "handlebars";
|
||||
|
||||
import {
|
||||
CacheBehavior,
|
||||
ChatMessage,
|
||||
Chunk,
|
||||
CompletionOptions,
|
||||
ILLM,
|
||||
LLMFullCompletionOptions,
|
||||
LLMOptions,
|
||||
ModelCapability,
|
||||
ModelName,
|
||||
ModelProvider,
|
||||
PromptLog,
|
||||
PromptTemplate,
|
||||
RequestOptions,
|
||||
|
|
@ -18,12 +19,11 @@ import {
|
|||
} from "../index.js";
|
||||
import { logDevData } from "../util/devdata.js";
|
||||
import { DevDataSqliteDb } from "../util/devdataSqlite.js";
|
||||
import { fetchwithRequestOptions } from "../util/fetchWithOptions.js";
|
||||
import mergeJson from "../util/merge.js";
|
||||
import { renderChatMessage } from "../util/messageContent.js";
|
||||
import { Telemetry } from "../util/posthog.js";
|
||||
import { withExponentialBackoff } from "../util/withExponentialBackoff.js";
|
||||
|
||||
import { renderChatMessage } from "../util/messageContent.js";
|
||||
import {
|
||||
autodetectPromptTemplates,
|
||||
autodetectTemplateFunction,
|
||||
|
|
@ -34,6 +34,8 @@ import {
|
|||
CONTEXT_LENGTH_FOR_MODEL,
|
||||
DEFAULT_ARGS,
|
||||
DEFAULT_CONTEXT_LENGTH,
|
||||
DEFAULT_MAX_BATCH_SIZE,
|
||||
DEFAULT_MAX_CHUNK_SIZE,
|
||||
DEFAULT_MAX_TOKENS,
|
||||
} from "./constants.js";
|
||||
import {
|
||||
|
|
@ -41,13 +43,19 @@ import {
|
|||
countTokens,
|
||||
pruneRawPromptFromTop,
|
||||
} from "./countTokens.js";
|
||||
import CompletionOptionsForModels from "./templates/options.js";
|
||||
import {
|
||||
fromChatCompletionChunk,
|
||||
LlmApiRequestType,
|
||||
toChatBody,
|
||||
toCompleteBody,
|
||||
toFimBody,
|
||||
} from "./openaiTypeConverters.js";
|
||||
|
||||
export abstract class BaseLLM implements ILLM {
|
||||
static providerName: ModelProvider;
|
||||
static providerName: string;
|
||||
static defaultOptions: Partial<LLMOptions> | undefined = undefined;
|
||||
|
||||
get providerName(): ModelProvider {
|
||||
get providerName(): string {
|
||||
return (this.constructor as typeof BaseLLM).providerName;
|
||||
}
|
||||
|
||||
|
|
@ -114,12 +122,20 @@ export abstract class BaseLLM implements ILLM {
|
|||
projectId?: string;
|
||||
accountId?: string;
|
||||
aiGatewaySlug?: string;
|
||||
profile?: string | undefined;
|
||||
|
||||
// For IBM watsonx
|
||||
deploymentId?: string;
|
||||
|
||||
// Embedding options
|
||||
embeddingId: string;
|
||||
maxEmbeddingChunkSize: number;
|
||||
maxEmbeddingBatchSize: number;
|
||||
|
||||
private _llmOptions: LLMOptions;
|
||||
|
||||
private openaiAdapter?: BaseLlmApi;
|
||||
|
||||
constructor(_options: LLMOptions) {
|
||||
this._llmOptions = _options;
|
||||
|
||||
|
|
@ -157,12 +173,6 @@ export abstract class BaseLLM implements ILLM {
|
|||
)
|
||||
: DEFAULT_MAX_TOKENS),
|
||||
};
|
||||
if (CompletionOptionsForModels[options.model as ModelName]) {
|
||||
this.completionOptions = mergeJson(
|
||||
this.completionOptions,
|
||||
CompletionOptionsForModels[options.model as ModelName] ?? {},
|
||||
);
|
||||
}
|
||||
this.requestOptions = options.requestOptions;
|
||||
this.promptTemplates = {
|
||||
...autodetectPromptTemplates(options.model, templateType),
|
||||
|
|
@ -196,6 +206,20 @@ export abstract class BaseLLM implements ILLM {
|
|||
this.apiType = options.apiType;
|
||||
this.region = options.region;
|
||||
this.projectId = options.projectId;
|
||||
this.profile = options.profile;
|
||||
|
||||
this.openaiAdapter = constructLlmApi({
|
||||
provider: this.providerName as any,
|
||||
apiKey: this.apiKey ?? "",
|
||||
apiBase: this.apiBase,
|
||||
requestOptions: this.requestOptions,
|
||||
});
|
||||
|
||||
this.maxEmbeddingBatchSize =
|
||||
options.maxEmbeddingBatchSize ?? DEFAULT_MAX_BATCH_SIZE;
|
||||
this.maxEmbeddingChunkSize =
|
||||
options.maxEmbeddingChunkSize ?? DEFAULT_MAX_CHUNK_SIZE;
|
||||
this.embeddingId = `${this.constructor.name}::${this.model}::${this.maxEmbeddingChunkSize}`;
|
||||
}
|
||||
|
||||
listModels(): Promise<string[]> {
|
||||
|
|
@ -431,6 +455,15 @@ export abstract class BaseLLM implements ILLM {
|
|||
throw new Error("Not implemented");
|
||||
}
|
||||
|
||||
protected useOpenAIAdapterFor: (LlmApiRequestType | "*")[] = [];
|
||||
|
||||
private shouldUseOpenAIAdapter(requestType: LlmApiRequestType) {
|
||||
return (
|
||||
this.useOpenAIAdapterFor.includes(requestType) ||
|
||||
this.useOpenAIAdapterFor.includes("*")
|
||||
);
|
||||
}
|
||||
|
||||
async *streamFim(
|
||||
prefix: string,
|
||||
suffix: string,
|
||||
|
|
@ -452,14 +485,30 @@ export abstract class BaseLLM implements ILLM {
|
|||
}
|
||||
|
||||
let completion = "";
|
||||
for await (const chunk of this._streamFim(
|
||||
prefix,
|
||||
suffix,
|
||||
signal,
|
||||
completionOptions,
|
||||
)) {
|
||||
completion += chunk;
|
||||
yield chunk;
|
||||
|
||||
if (this.shouldUseOpenAIAdapter("streamFim") && this.openaiAdapter) {
|
||||
const stream = this.openaiAdapter.fimStream(
|
||||
toFimBody(prefix, suffix, completionOptions),
|
||||
signal,
|
||||
);
|
||||
for await (const chunk of stream) {
|
||||
const result = fromChatCompletionChunk(chunk);
|
||||
if (result) {
|
||||
const content = renderChatMessage(result);
|
||||
completion += content;
|
||||
yield content;
|
||||
}
|
||||
}
|
||||
} else {
|
||||
for await (const chunk of this._streamFim(
|
||||
prefix,
|
||||
suffix,
|
||||
signal,
|
||||
completionOptions,
|
||||
)) {
|
||||
completion += chunk;
|
||||
yield chunk;
|
||||
}
|
||||
}
|
||||
|
||||
this._logTokensGenerated(
|
||||
|
|
@ -509,13 +558,27 @@ export abstract class BaseLLM implements ILLM {
|
|||
|
||||
let completion = "";
|
||||
try {
|
||||
for await (const chunk of this._streamComplete(
|
||||
prompt,
|
||||
signal,
|
||||
completionOptions,
|
||||
)) {
|
||||
completion += chunk;
|
||||
yield chunk;
|
||||
if (this.shouldUseOpenAIAdapter("streamComplete") && this.openaiAdapter) {
|
||||
for await (const chunk of this.openaiAdapter.completionStream(
|
||||
{
|
||||
...toCompleteBody(prompt, completionOptions),
|
||||
stream: true,
|
||||
},
|
||||
signal,
|
||||
)) {
|
||||
const content = chunk.choices[0]?.text ?? "";
|
||||
completion += content;
|
||||
yield content;
|
||||
}
|
||||
} else {
|
||||
for await (const chunk of this._streamComplete(
|
||||
prompt,
|
||||
signal,
|
||||
completionOptions,
|
||||
)) {
|
||||
completion += chunk;
|
||||
yield chunk;
|
||||
}
|
||||
}
|
||||
} finally {
|
||||
this._logTokensGenerated(completionOptions.model, prompt, completion);
|
||||
|
|
@ -561,7 +624,19 @@ export abstract class BaseLLM implements ILLM {
|
|||
}
|
||||
}
|
||||
|
||||
const completion = await this._complete(prompt, signal, completionOptions);
|
||||
let completion: string;
|
||||
if (this.shouldUseOpenAIAdapter("complete") && this.openaiAdapter) {
|
||||
const result = await this.openaiAdapter.completionNonStream(
|
||||
{
|
||||
...toCompleteBody(prompt, completionOptions),
|
||||
stream: false,
|
||||
},
|
||||
signal,
|
||||
);
|
||||
completion = result.choices[0].text;
|
||||
} else {
|
||||
completion = await this._complete(prompt, signal, completionOptions);
|
||||
}
|
||||
|
||||
this._logTokensGenerated(completionOptions.model, prompt, completion);
|
||||
|
||||
|
|
@ -619,13 +694,29 @@ export abstract class BaseLLM implements ILLM {
|
|||
yield { role: "assistant", content: chunk };
|
||||
}
|
||||
} else {
|
||||
for await (const chunk of this._streamChat(
|
||||
messages,
|
||||
signal,
|
||||
completionOptions,
|
||||
)) {
|
||||
completion += chunk.content;
|
||||
yield chunk;
|
||||
if (this.shouldUseOpenAIAdapter("streamChat") && this.openaiAdapter) {
|
||||
const stream = this.openaiAdapter.chatCompletionStream(
|
||||
{
|
||||
...toChatBody(messages, completionOptions),
|
||||
stream: true,
|
||||
},
|
||||
signal,
|
||||
);
|
||||
for await (const chunk of stream) {
|
||||
const result = fromChatCompletionChunk(chunk);
|
||||
if (result) {
|
||||
yield result;
|
||||
}
|
||||
}
|
||||
} else {
|
||||
for await (const chunk of this._streamChat(
|
||||
messages,
|
||||
signal,
|
||||
completionOptions,
|
||||
)) {
|
||||
completion += chunk.content;
|
||||
yield chunk;
|
||||
}
|
||||
}
|
||||
}
|
||||
} catch (error) {
|
||||
|
|
@ -647,7 +738,64 @@ export abstract class BaseLLM implements ILLM {
|
|||
};
|
||||
}
|
||||
|
||||
// biome-ignore lint/correctness/useYield: Purposefully not implemented
|
||||
getBatchedChunks(chunks: string[]): string[][] {
|
||||
const batchedChunks = [];
|
||||
|
||||
for (let i = 0; i < chunks.length; i += this.maxEmbeddingBatchSize) {
|
||||
batchedChunks.push(chunks.slice(i, i + this.maxEmbeddingBatchSize));
|
||||
}
|
||||
|
||||
return batchedChunks;
|
||||
}
|
||||
|
||||
async embed(chunks: string[]): Promise<number[][]> {
|
||||
const batches = this.getBatchedChunks(chunks);
|
||||
|
||||
return (
|
||||
await Promise.all(
|
||||
batches.map(async (batch) => {
|
||||
if (batch.length === 0) {
|
||||
return [];
|
||||
}
|
||||
|
||||
const embeddings = await withExponentialBackoff<number[][]>(
|
||||
async () => {
|
||||
if (this.shouldUseOpenAIAdapter("embed") && this.openaiAdapter) {
|
||||
const result = await this.openaiAdapter.embed({
|
||||
model: this.model,
|
||||
input: chunks,
|
||||
});
|
||||
return result.data.map((chunk) => chunk.embedding);
|
||||
}
|
||||
|
||||
return await this._embed(chunks);
|
||||
},
|
||||
);
|
||||
|
||||
return embeddings;
|
||||
}),
|
||||
)
|
||||
).flat();
|
||||
}
|
||||
|
||||
async rerank(query: string, chunks: Chunk[]): Promise<number[]> {
|
||||
if (this.shouldUseOpenAIAdapter("rerank") && this.openaiAdapter) {
|
||||
const results = await this.openaiAdapter.rerank({
|
||||
model: this.model,
|
||||
query,
|
||||
documents: chunks.map((chunk) => chunk.content),
|
||||
});
|
||||
|
||||
// Put them in the order they were given
|
||||
const sortedResults = results.data.sort((a, b) => a.index - b.index);
|
||||
return sortedResults.map((result) => result.relevance_score);
|
||||
}
|
||||
|
||||
throw new Error(
|
||||
`Reranking is not supported for provider type ${this.providerName}`,
|
||||
);
|
||||
}
|
||||
|
||||
protected async *_streamComplete(
|
||||
prompt: string,
|
||||
signal: AbortSignal,
|
||||
|
|
@ -688,6 +836,12 @@ export abstract class BaseLLM implements ILLM {
|
|||
return completion;
|
||||
}
|
||||
|
||||
protected async _embed(chunks: string[]): Promise<number[][]> {
|
||||
throw new Error(
|
||||
`Embedding is not supported for provider type ${this.providerName}`,
|
||||
);
|
||||
}
|
||||
|
||||
countTokens(text: string): number {
|
||||
return countTokens(text, this.model);
|
||||
}
|
||||
|
|
|
|||
|
|
@ -1,15 +1,10 @@
|
|||
import {
|
||||
ChatMessage,
|
||||
CompletionOptions,
|
||||
LLMOptions,
|
||||
ModelProvider,
|
||||
} from "../../index.js";
|
||||
import { ChatMessage, CompletionOptions, LLMOptions } from "../../index.js";
|
||||
import { renderChatMessage, stripImages } from "../../util/messageContent.js";
|
||||
import { BaseLLM } from "../index.js";
|
||||
import { streamSse } from "../stream.js";
|
||||
|
||||
class Anthropic extends BaseLLM {
|
||||
static providerName: ModelProvider = "anthropic";
|
||||
static providerName = "anthropic";
|
||||
static defaultOptions: Partial<LLMOptions> = {
|
||||
model: "claude-3-5-sonnet-latest",
|
||||
contextLength: 200_000,
|
||||
|
|
|
|||
|
|
@ -1,13 +1,8 @@
|
|||
import {
|
||||
ChatMessage,
|
||||
CompletionOptions,
|
||||
LLMOptions,
|
||||
ModelProvider,
|
||||
} from "../../index.js";
|
||||
import { ChatMessage, CompletionOptions, LLMOptions } from "../../index.js";
|
||||
import { BaseLLM } from "../index.js";
|
||||
|
||||
class Asksage extends BaseLLM {
|
||||
static providerName: ModelProvider = "askSage";
|
||||
static providerName = "askSage";
|
||||
static defaultOptions: Partial<LLMOptions> = {
|
||||
apiBase: "https://api.asksage.ai/server/",
|
||||
model: "gpt-4o",
|
||||
|
|
@ -62,13 +57,15 @@ class Asksage extends BaseLLM {
|
|||
temperature: options.temperature ?? 0.0,
|
||||
live: options.live ?? 0,
|
||||
model: this._convertModelName(options.model),
|
||||
system_prompt: options.systemPrompt ?? "You are an expert software developer. You give helpful and concise responses.",
|
||||
system_prompt:
|
||||
options.systemPrompt ??
|
||||
"You are an expert software developer. You give helpful and concise responses.",
|
||||
tools: options.tools,
|
||||
tool_choice: options.toolChoice,
|
||||
};
|
||||
|
||||
Object.keys(args).forEach(
|
||||
(key) => args[key] === undefined && delete args[key]
|
||||
(key) => args[key] === undefined && delete args[key],
|
||||
);
|
||||
|
||||
return args;
|
||||
|
|
@ -89,7 +86,7 @@ class Asksage extends BaseLLM {
|
|||
protected _getEndpoint(endpoint: string) {
|
||||
if (!this.apiBase) {
|
||||
throw new Error(
|
||||
"No API base URL provided. Please set the 'apiBase' option."
|
||||
"No API base URL provided. Please set the 'apiBase' option.",
|
||||
);
|
||||
}
|
||||
|
||||
|
|
@ -99,7 +96,7 @@ class Asksage extends BaseLLM {
|
|||
protected async _complete(
|
||||
prompt: string,
|
||||
signal: AbortSignal,
|
||||
options: CompletionOptions
|
||||
options: CompletionOptions,
|
||||
): Promise<string> {
|
||||
if (typeof prompt !== "string" || prompt.trim() === "") {
|
||||
throw new Error("Prompt must be a non-empty string.");
|
||||
|
|
@ -117,7 +114,7 @@ class Asksage extends BaseLLM {
|
|||
|
||||
if (!response.ok) {
|
||||
throw new Error(
|
||||
`API request failed with status ${response.status}: ${response.statusText}`
|
||||
`API request failed with status ${response.status}: ${response.statusText}`,
|
||||
);
|
||||
}
|
||||
|
||||
|
|
@ -128,7 +125,7 @@ class Asksage extends BaseLLM {
|
|||
protected async *_streamComplete(
|
||||
prompt: string,
|
||||
signal: AbortSignal,
|
||||
options: CompletionOptions
|
||||
options: CompletionOptions,
|
||||
): AsyncGenerator<string> {
|
||||
const completion = await this._complete(prompt, signal, options);
|
||||
yield completion;
|
||||
|
|
@ -137,7 +134,7 @@ class Asksage extends BaseLLM {
|
|||
protected async *_streamChat(
|
||||
messages: ChatMessage[],
|
||||
signal: AbortSignal,
|
||||
options: CompletionOptions
|
||||
options: CompletionOptions,
|
||||
): AsyncGenerator<ChatMessage> {
|
||||
const args = this._convertArgs(options, messages);
|
||||
|
||||
|
|
@ -145,12 +142,12 @@ class Asksage extends BaseLLM {
|
|||
method: "POST",
|
||||
headers: this._getHeaders(),
|
||||
body: JSON.stringify(args),
|
||||
signal
|
||||
signal,
|
||||
});
|
||||
|
||||
if (!response.ok) {
|
||||
throw new Error(
|
||||
`API request failed with status ${response.status}: ${response.statusText}`
|
||||
`API request failed with status ${response.status}: ${response.statusText}`,
|
||||
);
|
||||
}
|
||||
|
||||
|
|
@ -169,4 +166,4 @@ class Asksage extends BaseLLM {
|
|||
}
|
||||
}
|
||||
|
||||
export default Asksage;
|
||||
export default Asksage;
|
||||
|
|
|
|||
|
|
@ -1,9 +1,9 @@
|
|||
import { LLMOptions, ModelProvider } from "../../index.js";
|
||||
import { LLMOptions } from "../../index.js";
|
||||
|
||||
import OpenAI from "./OpenAI.js";
|
||||
|
||||
class Azure extends OpenAI {
|
||||
static providerName: ModelProvider = "azure";
|
||||
static providerName = "azure";
|
||||
|
||||
protected supportsPrediction(model: string): boolean {
|
||||
return false;
|
||||
|
|
|
|||
|
|
@ -1,32 +1,33 @@
|
|||
import {
|
||||
BedrockRuntimeClient,
|
||||
ConverseStreamCommand,
|
||||
InvokeModelCommand,
|
||||
} from "@aws-sdk/client-bedrock-runtime";
|
||||
import { fromIni } from "@aws-sdk/credential-providers";
|
||||
|
||||
import {
|
||||
ChatMessage,
|
||||
Chunk,
|
||||
CompletionOptions,
|
||||
LLMOptions,
|
||||
MessageContent,
|
||||
ModelProvider,
|
||||
} from "../../index.js";
|
||||
import { renderChatMessage } from "../../util/messageContent.js";
|
||||
import { BaseLLM } from "../index.js";
|
||||
|
||||
/**
|
||||
* Bedrock class implements AWS Bedrock LLM integration.
|
||||
* It handles streaming completions and chat messages using AWS Bedrock runtime.
|
||||
* Supports both text and image inputs through Claude 3 models.
|
||||
*/
|
||||
interface ModelConfig {
|
||||
formatPayload: (text: string) => any;
|
||||
extractEmbeddings: (responseBody: any) => number[][];
|
||||
}
|
||||
|
||||
class Bedrock extends BaseLLM {
|
||||
static providerName: ModelProvider = "bedrock";
|
||||
static providerName = "bedrock";
|
||||
static defaultOptions: Partial<LLMOptions> = {
|
||||
region: "us-east-1",
|
||||
model: "anthropic.claude-3-sonnet-20240229-v1:0",
|
||||
contextLength: 200_000,
|
||||
profile: "bedrock",
|
||||
};
|
||||
profile?: string | undefined;
|
||||
|
||||
constructor(options: LLMOptions) {
|
||||
super(options);
|
||||
|
|
@ -180,6 +181,131 @@ class Bedrock extends BaseLLM {
|
|||
return await fromIni()();
|
||||
}
|
||||
}
|
||||
|
||||
// EMBED //
|
||||
async embed(chunks: string[]): Promise<number[][]> {
|
||||
const credentials = await this._getCredentials();
|
||||
const client = new BedrockRuntimeClient({
|
||||
region: this.region,
|
||||
credentials: {
|
||||
accessKeyId: credentials.accessKeyId,
|
||||
secretAccessKey: credentials.secretAccessKey,
|
||||
sessionToken: credentials.sessionToken || "",
|
||||
},
|
||||
});
|
||||
|
||||
return (
|
||||
await Promise.all(
|
||||
chunks.map(async (chunk) => {
|
||||
const input = this._generateInvokeModelCommandInput(chunk);
|
||||
const command = new InvokeModelCommand(input);
|
||||
const response = await client.send(command);
|
||||
if (response.body) {
|
||||
const responseBody = JSON.parse(
|
||||
new TextDecoder().decode(response.body),
|
||||
);
|
||||
return this._extractEmbeddings(responseBody);
|
||||
}
|
||||
return [];
|
||||
}),
|
||||
)
|
||||
).flat();
|
||||
}
|
||||
|
||||
private _generateInvokeModelCommandInput(text: string): any {
|
||||
const modelConfig = this._getModelConfig();
|
||||
const payload = modelConfig.formatPayload(text);
|
||||
|
||||
return {
|
||||
body: JSON.stringify(payload),
|
||||
modelId: this.model,
|
||||
accept: "*/*",
|
||||
contentType: "application/json",
|
||||
};
|
||||
}
|
||||
|
||||
private _extractEmbeddings(responseBody: any): number[][] {
|
||||
const modelConfig = this._getModelConfig();
|
||||
return modelConfig.extractEmbeddings(responseBody);
|
||||
}
|
||||
|
||||
private _getModelConfig() {
|
||||
const modelConfigs: { [key: string]: ModelConfig } = {
|
||||
cohere: {
|
||||
formatPayload: (text: string) => ({
|
||||
texts: [text],
|
||||
input_type: "search_document",
|
||||
truncate: "END",
|
||||
}),
|
||||
extractEmbeddings: (responseBody: any) => responseBody.embeddings || [],
|
||||
},
|
||||
"amazon.titan-embed": {
|
||||
formatPayload: (text: string) => ({
|
||||
inputText: text,
|
||||
}),
|
||||
extractEmbeddings: (responseBody: any) =>
|
||||
responseBody.embedding ? [responseBody.embedding] : [],
|
||||
},
|
||||
};
|
||||
|
||||
const modelPrefix = Object.keys(modelConfigs).find((prefix) =>
|
||||
this.model!.startsWith(prefix),
|
||||
);
|
||||
if (!modelPrefix) {
|
||||
throw new Error(`Unsupported model: ${this.model}`);
|
||||
}
|
||||
return modelConfigs[modelPrefix];
|
||||
}
|
||||
|
||||
async rerank(query: string, chunks: Chunk[]): Promise<number[]> {
|
||||
if (!query || !chunks.length) {
|
||||
throw new Error("Query and chunks must not be empty");
|
||||
}
|
||||
|
||||
try {
|
||||
const credentials = await this._getCredentials();
|
||||
const client = new BedrockRuntimeClient({
|
||||
region: this.region,
|
||||
credentials,
|
||||
});
|
||||
|
||||
// Base payload for both models
|
||||
const payload: any = {
|
||||
query: query,
|
||||
documents: chunks.map((chunk) => chunk.content),
|
||||
top_n: chunks.length,
|
||||
};
|
||||
|
||||
// Add api_version for Cohere model
|
||||
if (this.model.startsWith("cohere.rerank")) {
|
||||
payload.api_version = 2;
|
||||
}
|
||||
|
||||
const input = {
|
||||
body: JSON.stringify(payload),
|
||||
modelId: this.model,
|
||||
accept: "*/*",
|
||||
contentType: "application/json",
|
||||
};
|
||||
|
||||
const command = new InvokeModelCommand(input);
|
||||
const response = await client.send(command);
|
||||
|
||||
if (!response.body) {
|
||||
throw new Error("Empty response received from Bedrock");
|
||||
}
|
||||
|
||||
const responseBody = JSON.parse(new TextDecoder().decode(response.body));
|
||||
|
||||
// Sort results by index to maintain original order
|
||||
return responseBody.results
|
||||
.sort((a: any, b: any) => a.index - b.index)
|
||||
.map((result: any) => result.relevance_score);
|
||||
} catch (error) {
|
||||
console.error("Error in BedrockReranker.rerank:", error);
|
||||
throw error;
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
export default Bedrock;
|
||||
|
|
|
|||
|
|
@ -4,21 +4,16 @@ import {
|
|||
} from "@aws-sdk/client-bedrock-runtime";
|
||||
import { fromIni } from "@aws-sdk/credential-providers";
|
||||
|
||||
import {
|
||||
CompletionOptions,
|
||||
LLMOptions,
|
||||
ModelProvider,
|
||||
} from "../../index.js";
|
||||
import { CompletionOptions, LLMOptions } from "../../index.js";
|
||||
import { BaseLLM } from "../index.js";
|
||||
|
||||
class BedrockImport extends BaseLLM {
|
||||
static providerName: ModelProvider = "bedrockimport";
|
||||
static providerName = "bedrockimport";
|
||||
static defaultOptions: Partial<LLMOptions> = {
|
||||
region: "us-east-1"
|
||||
region: "us-east-1",
|
||||
};
|
||||
// the BedRock imported custom model ARN
|
||||
modelArn?: string | undefined;
|
||||
profile?: string | undefined;
|
||||
|
||||
constructor(options: LLMOptions) {
|
||||
super(options);
|
||||
|
|
@ -52,7 +47,7 @@ class BedrockImport extends BaseLLM {
|
|||
|
||||
const input = this._generateInvokeModelCommandInput(prompt, options);
|
||||
const command = new InvokeModelWithResponseStreamCommand(input);
|
||||
const response = await client.send(command, {abortSignal: signal});
|
||||
const response = await client.send(command, { abortSignal: signal });
|
||||
|
||||
if (response.body) {
|
||||
for await (const item of response.body) {
|
||||
|
|
@ -69,23 +64,22 @@ class BedrockImport extends BaseLLM {
|
|||
options: CompletionOptions,
|
||||
): any {
|
||||
const payload = {
|
||||
prompt: prompt
|
||||
prompt: prompt,
|
||||
};
|
||||
|
||||
return {
|
||||
body: JSON.stringify(payload),
|
||||
modelId: this.modelArn,
|
||||
accept: "application/json",
|
||||
contentType: "application/json"
|
||||
contentType: "application/json",
|
||||
};
|
||||
}
|
||||
|
||||
private async _getCredentials() {
|
||||
try {
|
||||
return await
|
||||
fromIni({
|
||||
return await fromIni({
|
||||
profile: this.profile,
|
||||
ignoreCache: true
|
||||
ignoreCache: true,
|
||||
})();
|
||||
} catch (e) {
|
||||
console.warn(
|
||||
|
|
|
|||
|
|
@ -1,9 +1,9 @@
|
|||
import { LLMOptions, ModelProvider } from "../../index.js";
|
||||
import { LLMOptions } from "../../index.js";
|
||||
|
||||
import OpenAI from "./OpenAI.js";
|
||||
|
||||
class Cerebras extends OpenAI {
|
||||
static providerName: ModelProvider = "cerebras";
|
||||
static providerName = "cerebras";
|
||||
static defaultOptions: Partial<LLMOptions> = {
|
||||
apiBase: "https://api.cerebras.ai/v1/",
|
||||
};
|
||||
|
|
|
|||
|
|
@ -1,10 +1,10 @@
|
|||
import { ChatMessage, CompletionOptions, ModelProvider } from "../../index.js";
|
||||
import { ChatMessage, CompletionOptions } from "../../index.js";
|
||||
import { renderChatMessage } from "../../util/messageContent.js";
|
||||
import { BaseLLM } from "../index.js";
|
||||
import { streamSse } from "../stream.js";
|
||||
|
||||
export default class Cloudflare extends BaseLLM {
|
||||
static providerName: ModelProvider = "cloudflare";
|
||||
static providerName = "cloudflare";
|
||||
|
||||
private _convertArgs(options: CompletionOptions) {
|
||||
const finalOptions = {
|
||||
|
|
|
|||
|
|
@ -1,17 +1,18 @@
|
|||
import {
|
||||
ChatMessage,
|
||||
Chunk,
|
||||
CompletionOptions,
|
||||
LLMOptions,
|
||||
ModelProvider,
|
||||
} from "../../index.js";
|
||||
import { renderChatMessage } from "../../util/messageContent.js";
|
||||
import { BaseLLM } from "../index.js";
|
||||
import { streamJSON } from "../stream.js";
|
||||
|
||||
class Cohere extends BaseLLM {
|
||||
static providerName: ModelProvider = "cohere";
|
||||
static providerName = "cohere";
|
||||
static defaultOptions: Partial<LLMOptions> = {
|
||||
apiBase: "https://api.cohere.ai/v1",
|
||||
maxEmbeddingBatchSize: 96,
|
||||
};
|
||||
static maxStopSequences = 5;
|
||||
|
||||
|
|
@ -90,6 +91,53 @@ class Cohere extends BaseLLM {
|
|||
}
|
||||
}
|
||||
}
|
||||
|
||||
protected async _embed(chunks: string[]): Promise<number[][]> {
|
||||
const resp = await this.fetch(new URL("embed", this.apiBase), {
|
||||
method: "POST",
|
||||
body: JSON.stringify({
|
||||
texts: chunks,
|
||||
model: this.model,
|
||||
input_type: "search_document",
|
||||
embedding_types: ["float"],
|
||||
truncate: "END",
|
||||
}),
|
||||
headers: {
|
||||
Authorization: `Bearer ${this.apiKey}`,
|
||||
"Content-Type": "application/json",
|
||||
},
|
||||
});
|
||||
|
||||
if (!resp.ok) {
|
||||
throw new Error(await resp.text());
|
||||
}
|
||||
|
||||
const data = (await resp.json()) as any;
|
||||
return data.embeddings.float;
|
||||
}
|
||||
|
||||
async rerank(query: string, chunks: Chunk[]): Promise<number[]> {
|
||||
const resp = await fetch(new URL("rerank", this.apiBase), {
|
||||
method: "POST",
|
||||
headers: {
|
||||
Authorization: `Bearer ${this.apiKey}`,
|
||||
"Content-Type": "application/json",
|
||||
},
|
||||
body: JSON.stringify({
|
||||
model: this.model,
|
||||
query,
|
||||
documents: chunks.map((chunk) => chunk.content),
|
||||
}),
|
||||
});
|
||||
|
||||
if (!resp.ok) {
|
||||
throw new Error(await resp.text());
|
||||
}
|
||||
|
||||
const data = (await resp.json()) as any;
|
||||
const results = data.results.sort((a: any, b: any) => a.index - b.index);
|
||||
return results.map((result: any) => result.relevance_score);
|
||||
}
|
||||
}
|
||||
|
||||
export default Cohere;
|
||||
|
|
|
|||
|
|
@ -1,13 +1,8 @@
|
|||
import {
|
||||
ChatMessage,
|
||||
CompletionOptions,
|
||||
CustomLLM,
|
||||
ModelProvider,
|
||||
} from "../../index.js";
|
||||
import { ChatMessage, CompletionOptions, CustomLLM } from "../../index.js";
|
||||
import { BaseLLM } from "../index.js";
|
||||
|
||||
class CustomLLMClass extends BaseLLM {
|
||||
get providerName(): ModelProvider {
|
||||
get providerName() {
|
||||
return "custom";
|
||||
}
|
||||
|
||||
|
|
|
|||
|
|
@ -1,13 +1,29 @@
|
|||
import { LLMOptions, ModelProvider } from "../../index.js";
|
||||
import { LLMOptions } from "../../index.js";
|
||||
|
||||
import OpenAI from "./OpenAI.js";
|
||||
|
||||
class DeepInfra extends OpenAI {
|
||||
static providerName: ModelProvider = "deepinfra";
|
||||
static providerName = "deepinfra";
|
||||
static defaultOptions: Partial<LLMOptions> = {
|
||||
apiBase: "https://api.deepinfra.com/v1/openai/",
|
||||
};
|
||||
maxStopWords: number | undefined = 16;
|
||||
|
||||
protected async _embed(chunks: string[]): Promise<number[][]> {
|
||||
const resp = await this.fetch(
|
||||
`https://api.deepinfra.com/v1/inference/${this.model}`,
|
||||
{
|
||||
method: "POST",
|
||||
headers: {
|
||||
Authorization: `bearer ${this.apiKey}`,
|
||||
},
|
||||
body: JSON.stringify({ inputs: chunks }),
|
||||
},
|
||||
);
|
||||
|
||||
const data = await resp.json();
|
||||
return data.embeddings;
|
||||
}
|
||||
}
|
||||
|
||||
export default DeepInfra;
|
||||
|
|
|
|||
|
|
@ -1,11 +1,11 @@
|
|||
import { CompletionOptions, LLMOptions, ModelProvider } from "../../index.js";
|
||||
import { CompletionOptions, LLMOptions } from "../../index.js";
|
||||
import { streamSse } from "../stream.js";
|
||||
import { osModelsEditPrompt } from "../templates/edit.js";
|
||||
|
||||
import OpenAI from "./OpenAI.js";
|
||||
|
||||
class Deepseek extends OpenAI {
|
||||
static providerName: ModelProvider = "deepseek";
|
||||
static providerName = "deepseek";
|
||||
static defaultOptions: Partial<LLMOptions> = {
|
||||
apiBase: "https://api.deepseek.com/",
|
||||
model: "deepseek-coder",
|
||||
|
|
@ -46,7 +46,7 @@ class Deepseek extends OpenAI {
|
|||
Accept: "application/json",
|
||||
Authorization: `Bearer ${this.apiKey}`,
|
||||
},
|
||||
signal
|
||||
signal,
|
||||
});
|
||||
for await (const chunk of streamSse(resp)) {
|
||||
yield chunk.choices[0].text;
|
||||
|
|
|
|||
|
|
@ -1,9 +1,9 @@
|
|||
import { LLMOptions, ModelProvider } from "../../index.js";
|
||||
import { LLMOptions } from "../../index.js";
|
||||
|
||||
import OpenAI from "./OpenAI.js";
|
||||
|
||||
class Fireworks extends OpenAI {
|
||||
static providerName: ModelProvider = "fireworks";
|
||||
static providerName = "fireworks";
|
||||
static defaultOptions: Partial<LLMOptions> = {
|
||||
apiBase: "https://api.fireworks.ai/inference/v1",
|
||||
};
|
||||
|
|
|
|||
|
|
@ -1,11 +1,6 @@
|
|||
import socketIOClient, { Socket } from "socket.io-client";
|
||||
|
||||
import {
|
||||
ChatMessage,
|
||||
CompletionOptions,
|
||||
LLMOptions,
|
||||
ModelProvider,
|
||||
} from "../../index.js";
|
||||
import { ChatMessage, CompletionOptions, LLMOptions } from "../../index.js";
|
||||
import { renderChatMessage } from "../../util/messageContent.js";
|
||||
import { BaseLLM } from "../index.js";
|
||||
|
||||
|
|
@ -58,7 +53,7 @@ interface IFlowiseProviderLLMOptions extends LLMOptions {
|
|||
}
|
||||
|
||||
class Flowise extends BaseLLM {
|
||||
static providerName: ModelProvider = "flowise";
|
||||
static providerName = "flowise";
|
||||
static defaultOptions: Partial<IFlowiseProviderLLMOptions> = {
|
||||
apiBase: "http://localhost:3000",
|
||||
};
|
||||
|
|
|
|||
|
|
@ -1,15 +1,29 @@
|
|||
import { TRIAL_FIM_MODEL } from "../../config/onboarding.js";
|
||||
import { getHeaders } from "../../continueServer/stubs/headers.js";
|
||||
import { TRIAL_PROXY_URL } from "../../control-plane/client.js";
|
||||
import { ChatMessage, CompletionOptions, ModelProvider } from "../../index.js";
|
||||
import {
|
||||
ChatMessage,
|
||||
Chunk,
|
||||
CompletionOptions,
|
||||
LLMOptions,
|
||||
} from "../../index.js";
|
||||
import { BaseLLM } from "../index.js";
|
||||
import { streamResponse } from "../stream.js";
|
||||
|
||||
class FreeTrial extends BaseLLM {
|
||||
static providerName: ModelProvider = "free-trial";
|
||||
static providerName = "free-trial";
|
||||
static defaultOptions: Partial<LLMOptions> | undefined = {
|
||||
maxEmbeddingBatchSize: 128,
|
||||
model: "voyage-code-2",
|
||||
};
|
||||
|
||||
private ghAuthToken: string | undefined = undefined;
|
||||
|
||||
constructor(options: LLMOptions) {
|
||||
super(options);
|
||||
this.embeddingId = `${this.constructor.name}::${this.model}`;
|
||||
}
|
||||
|
||||
setupGhAuthToken(ghAuthToken: string | undefined) {
|
||||
this.ghAuthToken = ghAuthToken;
|
||||
}
|
||||
|
|
@ -142,7 +156,7 @@ class FreeTrial extends BaseLLM {
|
|||
};
|
||||
completion += chunk;
|
||||
}
|
||||
this._countTokens(completion, args.model, false);
|
||||
await this._countTokens(completion, args.model, false);
|
||||
}
|
||||
|
||||
supportsFim(): boolean {
|
||||
|
|
@ -174,7 +188,7 @@ class FreeTrial extends BaseLLM {
|
|||
yield value;
|
||||
completion += value;
|
||||
}
|
||||
this._countTokens(completion, args.model, false);
|
||||
await this._countTokens(completion, args.model, false);
|
||||
} catch (e: any) {
|
||||
if (e.message.startsWith("HTTP 429")) {
|
||||
throw new Error(
|
||||
|
|
@ -197,6 +211,52 @@ class FreeTrial extends BaseLLM {
|
|||
"gemini-1.5-pro-latest",
|
||||
];
|
||||
}
|
||||
|
||||
protected async _embed(chunks: string[]): Promise<number[][]> {
|
||||
const resp = await this.fetch(new URL("embeddings", TRIAL_PROXY_URL), {
|
||||
method: "POST",
|
||||
body: JSON.stringify({
|
||||
input: chunks,
|
||||
model: this.model,
|
||||
}),
|
||||
headers: {
|
||||
"Content-Type": "application/json",
|
||||
...(await getHeaders()),
|
||||
},
|
||||
});
|
||||
|
||||
if (resp.status !== 200) {
|
||||
throw new Error(`Failed to embed: ${resp.status} ${await resp.text()}`);
|
||||
}
|
||||
|
||||
const data = (await resp.json()) as any;
|
||||
return data.embeddings;
|
||||
}
|
||||
|
||||
async rerank(query: string, chunks: Chunk[]): Promise<number[]> {
|
||||
if (chunks.length === 0) {
|
||||
return [];
|
||||
}
|
||||
const resp = await this.fetch(new URL("rerank", TRIAL_PROXY_URL), {
|
||||
method: "POST",
|
||||
headers: {
|
||||
"Content-Type": "application/json",
|
||||
...(await getHeaders()),
|
||||
},
|
||||
body: JSON.stringify({
|
||||
query,
|
||||
documents: chunks.map((chunk) => chunk.content),
|
||||
}),
|
||||
});
|
||||
|
||||
if (!resp.ok) {
|
||||
throw new Error(await resp.text());
|
||||
}
|
||||
|
||||
const data = (await resp.json()) as any;
|
||||
const results = data.sort((a: any, b: any) => a.index - b.index);
|
||||
return results.map((result: any) => result.relevance_score);
|
||||
}
|
||||
}
|
||||
|
||||
export default FreeTrial;
|
||||
|
|
|
|||
|
|
@ -1,12 +1,13 @@
|
|||
import { LLMOptions, ModelProvider } from "../../index.js";
|
||||
import { LLMOptions } from "../../index.js";
|
||||
|
||||
import OpenAI from "./OpenAI.js";
|
||||
|
||||
class FunctionNetwork extends OpenAI {
|
||||
static providerName: ModelProvider = "function-network";
|
||||
static providerName = "function-network";
|
||||
static defaultOptions: Partial<LLMOptions> = {
|
||||
apiBase: "https://api.function.network/v1/",
|
||||
model: "meta/llama-3.1-70b-instruct",
|
||||
maxEmbeddingBatchSize: 128,
|
||||
};
|
||||
|
||||
private static modelConversion: { [key: string]: string } = {
|
||||
|
|
@ -36,6 +37,27 @@ class FunctionNetwork extends OpenAI {
|
|||
public supportsPrefill(): boolean {
|
||||
return false;
|
||||
}
|
||||
|
||||
protected async _embed(chunks: string[]): Promise<number[][]> {
|
||||
const resp = await this.fetch(new URL("embeddings", this.apiBase), {
|
||||
method: "POST",
|
||||
body: JSON.stringify({
|
||||
input: chunks,
|
||||
model: this.model,
|
||||
}),
|
||||
headers: {
|
||||
Authorization: `Bearer ${this.apiKey}`,
|
||||
"Content-Type": "application/json",
|
||||
},
|
||||
});
|
||||
|
||||
if (!resp.ok) {
|
||||
throw new Error(await resp.text());
|
||||
}
|
||||
|
||||
const data = (await resp.json()) as any;
|
||||
return data.data.map((result: { embedding: number[] }) => result.embedding);
|
||||
}
|
||||
}
|
||||
|
||||
export default FunctionNetwork;
|
||||
|
|
|
|||
|
|
@ -3,19 +3,19 @@ import {
|
|||
CompletionOptions,
|
||||
LLMOptions,
|
||||
MessagePart,
|
||||
ModelProvider,
|
||||
} from "../../index.js";
|
||||
import { renderChatMessage } from "../../util/messageContent.js";
|
||||
import { BaseLLM } from "../index.js";
|
||||
import { streamResponse } from "../stream.js";
|
||||
|
||||
class Gemini extends BaseLLM {
|
||||
static providerName: ModelProvider = "gemini";
|
||||
static providerName = "gemini";
|
||||
|
||||
static defaultOptions: Partial<LLMOptions> = {
|
||||
model: "gemini-pro",
|
||||
apiBase: "https://generativelanguage.googleapis.com/v1beta/",
|
||||
maxStopWords: 5,
|
||||
maxEmbeddingBatchSize: 100,
|
||||
};
|
||||
|
||||
// Function to convert completion options to Gemini format
|
||||
|
|
@ -245,10 +245,39 @@ class Gemini extends BaseLLM {
|
|||
const data = await response.json();
|
||||
yield { role: "assistant", content: data.candidates[0].content };
|
||||
}
|
||||
}
|
||||
|
||||
async function delay(seconds: number) {
|
||||
return new Promise((resolve) => setTimeout(resolve, seconds * 1000));
|
||||
async _embed(batch: string[]): Promise<number[][]> {
|
||||
// Batch embed endpoint: https://ai.google.dev/api/embeddings?authuser=1#EmbedContentRequest
|
||||
const requests = batch.map((text) => ({
|
||||
model: this.model,
|
||||
content: {
|
||||
role: "user",
|
||||
parts: [{ text }],
|
||||
},
|
||||
}));
|
||||
|
||||
const resp = await this.fetch(
|
||||
new URL(`${this.model}:batchEmbedContents`, this.apiBase),
|
||||
{
|
||||
method: "POST",
|
||||
body: JSON.stringify({
|
||||
requests,
|
||||
}),
|
||||
headers: {
|
||||
"x-goog-api-key": this.apiKey,
|
||||
"Content-Type": "application/json",
|
||||
} as any,
|
||||
},
|
||||
);
|
||||
|
||||
if (!resp.ok) {
|
||||
throw new Error(await resp.text());
|
||||
}
|
||||
|
||||
const data = (await resp.json()) as any;
|
||||
|
||||
return data.embeddings.map((embedding: any) => embedding.values);
|
||||
}
|
||||
}
|
||||
|
||||
export default Gemini;
|
||||
|
|
|
|||
|
|
@ -1,9 +1,9 @@
|
|||
import { LLMOptions, ModelProvider } from "../../index.js";
|
||||
import { LLMOptions } from "../../index.js";
|
||||
|
||||
import OpenAI from "./OpenAI.js";
|
||||
|
||||
class Groq extends OpenAI {
|
||||
static providerName: ModelProvider = "groq";
|
||||
static providerName = "groq";
|
||||
static defaultOptions: Partial<LLMOptions> = {
|
||||
apiBase: "https://api.groq.com/openai/v1/",
|
||||
};
|
||||
|
|
|
|||
|
|
@ -1,9 +1,9 @@
|
|||
import { CompletionOptions, ModelProvider } from "../../index.js";
|
||||
import { CompletionOptions } from "../../index.js";
|
||||
import { BaseLLM } from "../index.js";
|
||||
import { streamSse } from "../stream.js";
|
||||
|
||||
class HuggingFaceInferenceAPI extends BaseLLM {
|
||||
static providerName: ModelProvider = "huggingface-inference-api";
|
||||
static providerName = "huggingface-inference-api";
|
||||
|
||||
private _convertArgs(options: CompletionOptions) {
|
||||
return {
|
||||
|
|
@ -37,7 +37,7 @@ class HuggingFaceInferenceAPI extends BaseLLM {
|
|||
stream: true,
|
||||
parameters: this._convertArgs(options),
|
||||
}),
|
||||
signal
|
||||
signal,
|
||||
});
|
||||
|
||||
async function* stream() {
|
||||
|
|
|
|||
|
|
@ -1,36 +1,29 @@
|
|||
import { Response } from "node-fetch";
|
||||
|
||||
import {
|
||||
EmbeddingsProviderName,
|
||||
EmbedOptions,
|
||||
FetchFunction,
|
||||
} from "../../index.js";
|
||||
import { Chunk, LLMOptions } from "../../index.js";
|
||||
import { withExponentialBackoff } from "../../util/withExponentialBackoff.js";
|
||||
import { BaseLLM } from "../index.js";
|
||||
|
||||
import BaseEmbeddingsProvider from "./BaseEmbeddingsProvider.js";
|
||||
class HuggingFaceTEIEmbeddingsProvider extends BaseLLM {
|
||||
static providerName = "huggingface-tei";
|
||||
|
||||
class HuggingFaceTEIEmbeddingsProvider extends BaseEmbeddingsProvider {
|
||||
static providerName: EmbeddingsProviderName = "huggingface-tei";
|
||||
private _maxBatchSize?: number;
|
||||
get maxBatchSize(): number | undefined {
|
||||
return this._maxBatchSize ?? super.maxBatchSize;
|
||||
}
|
||||
|
||||
static defaultOptions: Partial<EmbedOptions> | undefined = {
|
||||
static defaultOptions: Partial<LLMOptions> | undefined = {
|
||||
apiBase: "http://localhost:8080",
|
||||
model: "tei",
|
||||
};
|
||||
|
||||
constructor(options: EmbedOptions, fetch: FetchFunction) {
|
||||
super(options, fetch);
|
||||
// without this extra slash the last portion of the path will be dropped from the URL when using the node.js URL constructor
|
||||
if (!this.options.apiBase?.endsWith("/")) {
|
||||
this.options.apiBase += "/";
|
||||
}
|
||||
this.doInfoRequest().then((response) => {
|
||||
this.options.model = response.model_id;
|
||||
this._maxBatchSize = response.max_client_batch_size;
|
||||
});
|
||||
constructor(options: LLMOptions) {
|
||||
super(options);
|
||||
|
||||
this.doInfoRequest()
|
||||
.then((response) => {
|
||||
this.model = response.model_id;
|
||||
this.maxEmbeddingBatchSize = response.max_client_batch_size;
|
||||
})
|
||||
.catch((error) => {
|
||||
console.error(
|
||||
"Failed to fetch info from HuggingFace TEI Embeddings Provider:",
|
||||
error,
|
||||
);
|
||||
});
|
||||
}
|
||||
|
||||
async embed(chunks: string[]) {
|
||||
|
|
@ -44,7 +37,7 @@ class HuggingFaceTEIEmbeddingsProvider extends BaseEmbeddingsProvider {
|
|||
|
||||
async doEmbedRequest(batch: string[]): Promise<number[][]> {
|
||||
const resp = await withExponentialBackoff<Response>(() =>
|
||||
this.fetch(new URL("embed", this.options.apiBase), {
|
||||
this.fetch(new URL("embed", this.apiBase), {
|
||||
method: "POST",
|
||||
body: JSON.stringify({
|
||||
inputs: batch,
|
||||
|
|
@ -67,7 +60,7 @@ class HuggingFaceTEIEmbeddingsProvider extends BaseEmbeddingsProvider {
|
|||
|
||||
async doInfoRequest(): Promise<TEIInfoResponse> {
|
||||
const resp = await withExponentialBackoff<Response>(() =>
|
||||
this.fetch(new URL("info", this.options.apiBase), {
|
||||
this.fetch(new URL("info", this.apiBase), {
|
||||
method: "GET",
|
||||
}),
|
||||
);
|
||||
|
|
@ -76,6 +69,38 @@ class HuggingFaceTEIEmbeddingsProvider extends BaseEmbeddingsProvider {
|
|||
}
|
||||
return (await resp.json()) as TEIInfoResponse;
|
||||
}
|
||||
|
||||
async rerank(query: string, chunks: Chunk[]): Promise<number[]> {
|
||||
const headers: Record<string, string> = {
|
||||
"Content-Type": "application/json",
|
||||
};
|
||||
|
||||
if (this.apiKey) {
|
||||
headers["Authorization"] = `Bearer ${this.apiKey}`;
|
||||
}
|
||||
|
||||
const resp = await fetch(new URL("rerank", this.apiBase), {
|
||||
method: "POST",
|
||||
headers,
|
||||
body: JSON.stringify({
|
||||
query: query,
|
||||
return_text: false,
|
||||
raw_scores: false,
|
||||
texts: chunks.map((chunk) => chunk.content),
|
||||
truncation_direction: "Right",
|
||||
truncate: true,
|
||||
}),
|
||||
});
|
||||
|
||||
if (!resp.ok) {
|
||||
throw new Error(await resp.text());
|
||||
}
|
||||
|
||||
const data = (await resp.json()) as any;
|
||||
// Resort into original order and extract scores
|
||||
const results = data.sort((a: any, b: any) => a.index - b.index);
|
||||
return results.map((result: any) => result.score);
|
||||
}
|
||||
}
|
||||
|
||||
class TEIEmbedError extends Error {
|
||||
|
|
@ -1,10 +1,10 @@
|
|||
import { CompletionOptions, LLMOptions, ModelProvider } from "../../index.js";
|
||||
import { CompletionOptions, LLMOptions } from "../../index.js";
|
||||
import { BaseLLM } from "../index.js";
|
||||
import { streamSse } from "../stream.js";
|
||||
|
||||
class HuggingFaceTGI extends BaseLLM {
|
||||
private static MAX_STOP_TOKENS = 4;
|
||||
static providerName: ModelProvider = "huggingface-tgi";
|
||||
static providerName = "huggingface-tgi";
|
||||
static defaultOptions: Partial<LLMOptions> = {
|
||||
apiBase: "http://localhost:8080/",
|
||||
};
|
||||
|
|
@ -61,7 +61,7 @@ class HuggingFaceTGI extends BaseLLM {
|
|||
"Content-Type": "application/json",
|
||||
},
|
||||
body: JSON.stringify({ inputs: prompt, parameters: args }),
|
||||
signal
|
||||
signal,
|
||||
},
|
||||
);
|
||||
|
||||
|
|
|
|||
|
|
@ -1,17 +1,17 @@
|
|||
import { LLMOptions, ModelProvider } from "../..";
|
||||
import { LLMOptions } from "../..";
|
||||
|
||||
import OpenAI from "./OpenAI";
|
||||
|
||||
class Kindo extends OpenAI {
|
||||
static providerName: ModelProvider = "kindo";
|
||||
static defaultOptions: Partial<LLMOptions> = {
|
||||
apiBase: "https://llm.kindo.ai/v1",
|
||||
requestOptions: {
|
||||
headers: {
|
||||
"kindo-token-transaction-type": "CONTINUE"
|
||||
}
|
||||
}
|
||||
};
|
||||
static providerName = "kindo";
|
||||
static defaultOptions: Partial<LLMOptions> = {
|
||||
apiBase: "https://llm.kindo.ai/v1",
|
||||
requestOptions: {
|
||||
headers: {
|
||||
"kindo-token-transaction-type": "CONTINUE",
|
||||
},
|
||||
},
|
||||
};
|
||||
}
|
||||
|
||||
export default Kindo;
|
||||
export default Kindo;
|
||||
|
|
|
|||
|
|
@ -1,9 +1,9 @@
|
|||
import { LLMOptions, ModelProvider } from "../../index.js";
|
||||
import { LLMOptions } from "../../index.js";
|
||||
|
||||
import OpenAI from "./OpenAI.js";
|
||||
|
||||
class LMStudio extends OpenAI {
|
||||
static providerName: ModelProvider = "lmstudio";
|
||||
static providerName = "lmstudio";
|
||||
static defaultOptions: Partial<LLMOptions> = {
|
||||
apiBase: "http://localhost:1234/v1/",
|
||||
};
|
||||
|
|
|
|||
|
|
@ -1,9 +1,9 @@
|
|||
import { CompletionOptions, LLMOptions, ModelProvider } from "../../index.js";
|
||||
import { CompletionOptions, LLMOptions } from "../../index.js";
|
||||
import { BaseLLM } from "../index.js";
|
||||
import { streamSse } from "../stream.js";
|
||||
|
||||
class LlamaCpp extends BaseLLM {
|
||||
static providerName: ModelProvider = "llama.cpp";
|
||||
static providerName = "llama.cpp";
|
||||
static defaultOptions: Partial<LLMOptions> = {
|
||||
apiBase: "http://127.0.0.1:8080/",
|
||||
};
|
||||
|
|
@ -43,7 +43,7 @@ class LlamaCpp extends BaseLLM {
|
|||
stream: true,
|
||||
...this._convertArgs(options, prompt),
|
||||
}),
|
||||
signal
|
||||
signal,
|
||||
});
|
||||
|
||||
for await (const value of streamSse(resp)) {
|
||||
|
|
|
|||
|
|
@ -1,9 +1,7 @@
|
|||
import { ModelProvider } from "../../index.js";
|
||||
|
||||
import LlamaCpp from "./LlamaCpp.js";
|
||||
|
||||
class Llamafile extends LlamaCpp {
|
||||
static providerName: ModelProvider = "llamafile";
|
||||
static providerName = "llamafile";
|
||||
}
|
||||
|
||||
export default Llamafile;
|
||||
|
|
|
|||
|
|
@ -1,16 +1,17 @@
|
|||
import { ChatMessage, LLMOptions, ModelProvider } from "../../index.js";
|
||||
import { ChatMessage, LLMOptions } from "../../index.js";
|
||||
import { gptEditPrompt } from "../templates/edit.js";
|
||||
|
||||
import OpenAI from "./OpenAI.js";
|
||||
|
||||
class Mistral extends OpenAI {
|
||||
static providerName: ModelProvider = "mistral";
|
||||
static providerName = "mistral";
|
||||
static defaultOptions: Partial<LLMOptions> = {
|
||||
apiBase: "https://api.mistral.ai/v1/",
|
||||
model: "codestral-latest",
|
||||
promptTemplates: {
|
||||
edit: gptEditPrompt,
|
||||
},
|
||||
maxEmbeddingBatchSize: 128,
|
||||
};
|
||||
|
||||
constructor(options: LLMOptions) {
|
||||
|
|
|
|||
|
|
@ -1,9 +1,9 @@
|
|||
import { ChatMessage, CompletionOptions, ModelProvider } from "../../index.js";
|
||||
import { ChatMessage, CompletionOptions } from "../../index.js";
|
||||
import { BaseLLM } from "../index.js";
|
||||
|
||||
class Mock extends BaseLLM {
|
||||
class MockLLM extends BaseLLM {
|
||||
public completion: string = "Test Completion";
|
||||
static providerName: ModelProvider = "mock";
|
||||
static providerName = "mock";
|
||||
|
||||
protected async *_streamComplete(
|
||||
prompt: string,
|
||||
|
|
@ -27,4 +27,4 @@ class Mock extends BaseLLM {
|
|||
}
|
||||
}
|
||||
|
||||
export default Mock;
|
||||
export default MockLLM;
|
||||
|
|
|
|||
|
|
@ -1,11 +1,11 @@
|
|||
import { CompletionOptions, LLMOptions, ModelProvider } from "../../index.js";
|
||||
import { CompletionOptions, LLMOptions } from "../../index.js";
|
||||
import { streamSse } from "../stream.js";
|
||||
import { osModelsEditPrompt } from "../templates/edit.js";
|
||||
|
||||
import OpenAI from "./OpenAI.js";
|
||||
|
||||
class Moonshot extends OpenAI {
|
||||
static providerName: ModelProvider = "moonshot";
|
||||
static providerName = "moonshot";
|
||||
static defaultOptions: Partial<LLMOptions> = {
|
||||
apiBase: "https://api.moonshot.cn/v1/",
|
||||
model: "moonshot-v1-8k",
|
||||
|
|
@ -50,7 +50,7 @@ class Moonshot extends OpenAI {
|
|||
Accept: "application/json",
|
||||
Authorization: `Bearer ${this.apiKey}`,
|
||||
},
|
||||
signal
|
||||
signal,
|
||||
});
|
||||
for await (const chunk of streamSse(resp)) {
|
||||
yield chunk.choices[0].delta.content;
|
||||
|
|
|
|||
|
|
@ -1,9 +1,9 @@
|
|||
import { LLMOptions, ModelProvider } from "../../index.js";
|
||||
import { LLMOptions } from "../../index.js";
|
||||
|
||||
import Ollama from "./Ollama.js";
|
||||
|
||||
class Msty extends Ollama {
|
||||
static providerName: ModelProvider = "msty";
|
||||
static providerName = "msty";
|
||||
static defaultOptions: Partial<LLMOptions> = {
|
||||
apiBase: "http://localhost:10000",
|
||||
model: "codellama-7b",
|
||||
|
|
|
|||
|
|
@ -1,9 +1,9 @@
|
|||
import { LLMOptions, ModelProvider } from "../..";
|
||||
import { LLMOptions } from "../..";
|
||||
|
||||
import OpenAI from "./OpenAI";
|
||||
|
||||
class Nebius extends OpenAI {
|
||||
static providerName: ModelProvider = "nebius";
|
||||
static providerName = "nebius";
|
||||
static defaultOptions: Partial<LLMOptions> = {
|
||||
apiBase: "https://api.studio.nebius.ai/v1/",
|
||||
useLegacyCompletionsEndpoint: false,
|
||||
|
|
|
|||
|
|
@ -1,33 +1,39 @@
|
|||
import { LLMOptions, ModelProvider, ChatMessage } from "../../index.js";
|
||||
import { LLMOptions } from "../../index.js";
|
||||
|
||||
import OpenAI from "./OpenAI.js";
|
||||
|
||||
class Nvidia extends OpenAI {
|
||||
// NVIDIA NIMs currently limits the number of stops for Starcoder 2 to 4
|
||||
// https://docs.api.nvidia.com/nim/reference/bigcode-starcoder2-7b-infer
|
||||
protected maxStopWordsStarCoder = 4;
|
||||
static providerName: ModelProvider = "nvidia";
|
||||
maxStopWords = 4;
|
||||
static providerName = "nvidia";
|
||||
static defaultOptions: Partial<LLMOptions> = {
|
||||
apiBase: "https://integrate.api.nvidia.com/v1/",
|
||||
useLegacyCompletionsEndpoint: false,
|
||||
maxEmbeddingBatchSize: 96,
|
||||
};
|
||||
|
||||
protected _convertArgs(options: any, messages: ChatMessage[]) {
|
||||
const url = new URL(this.apiBase!);
|
||||
const finalOptions = {
|
||||
messages: messages.map(this._convertMessage),
|
||||
model: this._convertModelName(options.model),
|
||||
max_tokens: options.maxTokens,
|
||||
temperature: options.temperature,
|
||||
top_p: options.topP,
|
||||
frequency_penalty: options.frequencyPenalty,
|
||||
presence_penalty: options.presencePenalty,
|
||||
stop: options.model.includes("starcoder2")
|
||||
? options.stop?.slice(0, this.maxStopWordsStarCoder)
|
||||
: options.stop,
|
||||
};
|
||||
protected async _embed(chunks: string[]): Promise<number[][]> {
|
||||
const resp = await this.fetch(new URL("embeddings", this.apiBase), {
|
||||
method: "POST",
|
||||
body: JSON.stringify({
|
||||
input: chunks,
|
||||
model: this.model,
|
||||
input_type: "passage",
|
||||
truncate: "END",
|
||||
}),
|
||||
headers: {
|
||||
Authorization: `Bearer ${this.apiKey}`,
|
||||
"Content-Type": "application/json",
|
||||
},
|
||||
});
|
||||
|
||||
return finalOptions;
|
||||
if (!resp.ok) {
|
||||
throw new Error(await resp.text());
|
||||
}
|
||||
|
||||
const data = (await resp.json()) as any;
|
||||
return data.data.map((result: { embedding: number[] }) => result.embedding);
|
||||
}
|
||||
}
|
||||
|
||||
|
|
|
|||
|
|
@ -1,9 +1,4 @@
|
|||
import {
|
||||
ChatMessage,
|
||||
CompletionOptions,
|
||||
LLMOptions,
|
||||
ModelProvider,
|
||||
} from "../../index.js";
|
||||
import { ChatMessage, CompletionOptions, LLMOptions } from "../../index.js";
|
||||
import { renderChatMessage } from "../../util/messageContent.js";
|
||||
import { BaseLLM } from "../index.js";
|
||||
import { streamResponse } from "../stream.js";
|
||||
|
|
@ -59,10 +54,11 @@ interface ChatOptions extends BaseOptions {
|
|||
}
|
||||
|
||||
class Ollama extends BaseLLM {
|
||||
static providerName: ModelProvider = "ollama";
|
||||
static providerName = "ollama";
|
||||
static defaultOptions: Partial<LLMOptions> = {
|
||||
apiBase: "http://localhost:11434/",
|
||||
model: "codellama-7b",
|
||||
maxEmbeddingBatchSize: 64,
|
||||
};
|
||||
|
||||
private fimSupported: boolean = false;
|
||||
|
|
@ -405,6 +401,32 @@ class Ollama extends BaseLLM {
|
|||
);
|
||||
}
|
||||
}
|
||||
|
||||
protected async _embed(chunks: string[]): Promise<number[][]> {
|
||||
const resp = await this.fetch(new URL("api/embed", this.apiBase), {
|
||||
method: "POST",
|
||||
body: JSON.stringify({
|
||||
model: this.model,
|
||||
input: chunks,
|
||||
}),
|
||||
headers: {
|
||||
"Content-Type": "application/json",
|
||||
Authorization: `Bearer ${this.apiKey}`,
|
||||
},
|
||||
});
|
||||
|
||||
if (!resp.ok) {
|
||||
throw new Error(`Failed to embed chunk: ${await resp.text()}`);
|
||||
}
|
||||
|
||||
const data = await resp.json();
|
||||
const embedding: number[][] = data.embeddings;
|
||||
|
||||
if (!embedding || embedding.length === 0) {
|
||||
throw new Error("Ollama generated empty embedding");
|
||||
}
|
||||
return embedding;
|
||||
}
|
||||
}
|
||||
|
||||
export default Ollama;
|
||||
|
|
|
|||
|
|
@ -1,12 +1,18 @@
|
|||
import { ChatCompletionCreateParams } from "openai/resources/index";
|
||||
|
||||
import {
|
||||
ChatMessage,
|
||||
CompletionOptions,
|
||||
LLMOptions,
|
||||
ModelProvider,
|
||||
Tool,
|
||||
} from "../../index.js";
|
||||
import { renderChatMessage } from "../../util/messageContent.js";
|
||||
import { BaseLLM } from "../index.js";
|
||||
import {
|
||||
fromChatCompletionChunk,
|
||||
LlmApiRequestType,
|
||||
toChatBody,
|
||||
} from "../openaiTypeConverters.js";
|
||||
import { streamSse } from "../stream.js";
|
||||
|
||||
const NON_CHAT_MODELS = [
|
||||
|
|
@ -51,48 +57,20 @@ class OpenAI extends BaseLLM {
|
|||
this.apiVersion = options.apiVersion ?? "2023-07-01-preview";
|
||||
}
|
||||
|
||||
static providerName: ModelProvider = "openai";
|
||||
static defaultOptions: Partial<LLMOptions> = {
|
||||
static providerName = "openai";
|
||||
static defaultOptions: Partial<LLMOptions> | undefined = {
|
||||
apiBase: "https://api.openai.com/v1/",
|
||||
maxEmbeddingBatchSize: 128,
|
||||
};
|
||||
|
||||
protected _convertMessage(message: ChatMessage) {
|
||||
if (message.role === "tool") {
|
||||
return {
|
||||
role: "tool",
|
||||
content: message.content,
|
||||
tool_call_id: message.toolCallId,
|
||||
};
|
||||
}
|
||||
|
||||
if (typeof message.content === "string") {
|
||||
return message;
|
||||
} else if (!message.content.some((item) => item.type !== "text")) {
|
||||
// If no multi-media is in the message, just send as text
|
||||
// for compatibility with OpenAI "compatible" servers
|
||||
// that don't support multi-media format
|
||||
return {
|
||||
...message,
|
||||
content: message.content.map((item) => item.text).join(""),
|
||||
};
|
||||
}
|
||||
|
||||
const parts = message.content.map((part) => {
|
||||
const msg: any = {
|
||||
type: part.type,
|
||||
text: part.text,
|
||||
};
|
||||
if (part.type === "imageUrl") {
|
||||
msg.image_url = { ...part.imageUrl, detail: "auto" };
|
||||
msg.type = "image_url";
|
||||
}
|
||||
return msg;
|
||||
});
|
||||
return {
|
||||
...message,
|
||||
content: parts,
|
||||
};
|
||||
}
|
||||
protected useOpenAIAdapterFor: (LlmApiRequestType | "*")[] = [
|
||||
"chat",
|
||||
"embed",
|
||||
"list",
|
||||
"rerank",
|
||||
"streamChat",
|
||||
"streamFim",
|
||||
];
|
||||
|
||||
protected _convertModelName(model: string): string {
|
||||
return model;
|
||||
|
|
@ -121,33 +99,32 @@ class OpenAI extends BaseLLM {
|
|||
};
|
||||
}
|
||||
|
||||
protected _convertArgs(options: CompletionOptions, messages: ChatMessage[]) {
|
||||
protected getMaxStopWords(): number {
|
||||
const url = new URL(this.apiBase!);
|
||||
const tools = options.tools?.map(this.convertTool);
|
||||
|
||||
const finalOptions: any = {
|
||||
messages: messages.map(this._convertMessage),
|
||||
model: this._convertModelName(options.model),
|
||||
max_tokens: options.maxTokens,
|
||||
temperature: options.temperature,
|
||||
top_p: options.topP,
|
||||
frequency_penalty: options.frequencyPenalty,
|
||||
presence_penalty: options.presencePenalty,
|
||||
stream: options.stream ?? true,
|
||||
stop:
|
||||
// Jan + Azure OpenAI don't truncate and will throw an error
|
||||
this.maxStopWords !== undefined
|
||||
? options.stop?.slice(0, this.maxStopWords)
|
||||
: url.host === "api.deepseek.com"
|
||||
? options.stop?.slice(0, 16)
|
||||
: url.port === "1337" ||
|
||||
url.host === "api.openai.com" ||
|
||||
url.host === "api.groq.com" ||
|
||||
this.apiType === "azure"
|
||||
? options.stop?.slice(0, 4)
|
||||
: options.stop,
|
||||
tools,
|
||||
};
|
||||
if (this.maxStopWords !== undefined) {
|
||||
return this.maxStopWords;
|
||||
} else if (url.host === "api.deepseek.com") {
|
||||
return 16;
|
||||
} else if (
|
||||
url.port === "1337" ||
|
||||
url.host === "api.openai.com" ||
|
||||
url.host === "api.groq.com" ||
|
||||
this.apiType === "azure"
|
||||
) {
|
||||
return 4;
|
||||
} else {
|
||||
return Infinity;
|
||||
}
|
||||
}
|
||||
|
||||
protected _convertArgs(
|
||||
options: CompletionOptions,
|
||||
messages: ChatMessage[],
|
||||
): ChatCompletionCreateParams {
|
||||
const finalOptions = toChatBody(messages, options);
|
||||
|
||||
finalOptions.stop = options.stop?.slice(0, this.getMaxStopWords());
|
||||
|
||||
// OpenAI o1-preview and o1-mini:
|
||||
if (this.isO1Model(options.model)) {
|
||||
|
|
@ -310,26 +287,9 @@ class OpenAI extends BaseLLM {
|
|||
}
|
||||
|
||||
for await (const value of streamSse(response)) {
|
||||
if (value.choices?.[0]?.delta?.content) {
|
||||
yield {
|
||||
role: "assistant",
|
||||
content: value.choices[0].delta.content,
|
||||
};
|
||||
} else if (value.choices?.[0]?.delta?.tool_calls) {
|
||||
yield {
|
||||
role: "assistant",
|
||||
content: "",
|
||||
toolCalls: value.choices?.[0]?.delta?.tool_calls.map(
|
||||
(tool_call: any) => ({
|
||||
id: tool_call.id,
|
||||
type: tool_call.type,
|
||||
function: {
|
||||
name: tool_call.function.name,
|
||||
arguments: tool_call.function.arguments,
|
||||
},
|
||||
}),
|
||||
),
|
||||
};
|
||||
const chunk = fromChatCompletionChunk(value);
|
||||
if (chunk) {
|
||||
yield chunk;
|
||||
}
|
||||
}
|
||||
}
|
||||
|
|
@ -377,6 +337,44 @@ class OpenAI extends BaseLLM {
|
|||
const data = await response.json();
|
||||
return data.data.map((m: any) => m.id);
|
||||
}
|
||||
|
||||
private _getEmbedEndpoint() {
|
||||
if (!this.apiBase) {
|
||||
throw new Error(
|
||||
"No API base URL provided. Please set the 'apiBase' option in config.json",
|
||||
);
|
||||
}
|
||||
|
||||
if (this.apiType === "azure") {
|
||||
return new URL(
|
||||
`openai/deployments/${this.deployment}/embeddings?api-version=${this.apiVersion}`,
|
||||
this.apiBase,
|
||||
);
|
||||
}
|
||||
return new URL("embeddings", this.apiBase);
|
||||
}
|
||||
|
||||
protected async _embed(chunks: string[]): Promise<number[][]> {
|
||||
const resp = await this.fetch(this._getEmbedEndpoint(), {
|
||||
method: "POST",
|
||||
body: JSON.stringify({
|
||||
input: chunks,
|
||||
model: this.model,
|
||||
}),
|
||||
headers: {
|
||||
Authorization: `Bearer ${this.apiKey}`,
|
||||
"Content-Type": "application/json",
|
||||
"api-key": this.apiKey ?? "", // For Azure
|
||||
},
|
||||
});
|
||||
|
||||
if (!resp.ok) {
|
||||
throw new Error(await resp.text());
|
||||
}
|
||||
|
||||
const data = (await resp.json()) as any;
|
||||
return data.data.map((result: { embedding: number[] }) => result.embedding);
|
||||
}
|
||||
}
|
||||
|
||||
export default OpenAI;
|
||||
|
|
|
|||
|
|
@ -1,10 +1,10 @@
|
|||
import { LLMOptions, ModelProvider } from "../../index.js";
|
||||
import { LLMOptions } from "../../index.js";
|
||||
import { osModelsEditPrompt } from "../templates/edit.js";
|
||||
|
||||
import OpenAI from "./OpenAI.js";
|
||||
|
||||
class OpenRouter extends OpenAI {
|
||||
static providerName: ModelProvider = "openrouter";
|
||||
static providerName = "openrouter";
|
||||
static defaultOptions: Partial<LLMOptions> = {
|
||||
apiBase: "https://openrouter.ai/api/v1/",
|
||||
model: "gpt-4o-mini",
|
||||
|
|
|
|||
|
|
@ -1,6 +1,6 @@
|
|||
import ReplicateClient from "replicate";
|
||||
|
||||
import { CompletionOptions, LLMOptions, ModelProvider } from "../../index.js";
|
||||
import { CompletionOptions, LLMOptions } from "../../index.js";
|
||||
import { BaseLLM } from "../index.js";
|
||||
|
||||
class Replicate extends BaseLLM {
|
||||
|
|
@ -35,19 +35,19 @@ class Replicate extends BaseLLM {
|
|||
"phind-codellama-34b": "kcaverly/phind-codellama-34b-v2-gguf" as any,
|
||||
};
|
||||
|
||||
static providerName: ModelProvider = "replicate";
|
||||
static providerName = "replicate";
|
||||
private _replicate: ReplicateClient;
|
||||
|
||||
private _convertArgs(
|
||||
options: CompletionOptions,
|
||||
prompt: string,
|
||||
signal: AbortSignal
|
||||
): [`${string}/${string}:${string}`, { input: any, signal: AbortSignal }] {
|
||||
signal: AbortSignal,
|
||||
): [`${string}/${string}:${string}`, { input: any; signal: AbortSignal }] {
|
||||
return [
|
||||
Replicate.MODEL_IDS[options.model] || (options.model as any),
|
||||
{
|
||||
input: { prompt, message: prompt },
|
||||
signal
|
||||
signal,
|
||||
},
|
||||
];
|
||||
}
|
||||
|
|
|
|||
|
|
@ -1,26 +1,25 @@
|
|||
import {
|
||||
InvokeEndpointCommand,
|
||||
InvokeEndpointWithResponseStreamCommand,
|
||||
SageMakerRuntimeClient
|
||||
SageMakerRuntimeClient,
|
||||
} from "@aws-sdk/client-sagemaker-runtime";
|
||||
import { fromIni } from "@aws-sdk/credential-providers";
|
||||
|
||||
// @ts-ignore
|
||||
import jinja from "jinja-js";
|
||||
|
||||
import {
|
||||
ChatMessage,
|
||||
CompletionOptions,
|
||||
LLMOptions,
|
||||
ModelProvider
|
||||
} from "../../index.js";
|
||||
import { ChatMessage, CompletionOptions, LLMOptions } from "../../index.js";
|
||||
import { BaseLLM } from "../index.js";
|
||||
|
||||
class SageMaker extends BaseLLM {
|
||||
private static PROFILE_NAME: string = "sagemaker";
|
||||
static providerName: ModelProvider = "sagemaker";
|
||||
private static DEFAULT_PROFILE_NAME: string = "sagemaker";
|
||||
|
||||
static providerName = "sagemaker";
|
||||
|
||||
static defaultOptions: Partial<LLMOptions> = {
|
||||
region: "us-west-2",
|
||||
contextLength: 200_000,
|
||||
maxEmbeddingBatchSize: 1,
|
||||
};
|
||||
|
||||
constructor(options: LLMOptions) {
|
||||
|
|
@ -28,6 +27,8 @@ class SageMaker extends BaseLLM {
|
|||
if (!options.apiBase) {
|
||||
this.apiBase = `https://runtime.sagemaker.${options.region}.amazonaws.com`;
|
||||
}
|
||||
|
||||
this.profile ??= SageMaker.DEFAULT_PROFILE_NAME;
|
||||
}
|
||||
|
||||
protected async *_streamComplete(
|
||||
|
|
@ -62,19 +63,16 @@ class SageMaker extends BaseLLM {
|
|||
if ("choices" in data) {
|
||||
if ("delta" in data.choices[0]) {
|
||||
text = data.choices[0].delta.content;
|
||||
}
|
||||
else {
|
||||
} else {
|
||||
text = data.choices[0].text;
|
||||
}
|
||||
}
|
||||
else if ("token" in data) {
|
||||
} else if ("token" in data) {
|
||||
text = data.token.text;
|
||||
}
|
||||
if (text !== undefined) {
|
||||
yield text;
|
||||
}
|
||||
} catch (e) {
|
||||
}
|
||||
} catch (e) {}
|
||||
buffer = buffer.slice(position + 1);
|
||||
}
|
||||
}
|
||||
|
|
@ -114,19 +112,16 @@ class SageMaker extends BaseLLM {
|
|||
if ("choices" in data) {
|
||||
if ("delta" in data.choices[0]) {
|
||||
text = data.choices[0].delta.content;
|
||||
}
|
||||
else {
|
||||
} else {
|
||||
text = data.choices[0].text;
|
||||
}
|
||||
}
|
||||
else if ("token" in data) {
|
||||
} else if ("token" in data) {
|
||||
text = data.token.text;
|
||||
}
|
||||
if (text !== undefined) {
|
||||
yield { role: "assistant", content: text };
|
||||
}
|
||||
} catch (e) {
|
||||
}
|
||||
} catch (e) {}
|
||||
buffer = buffer.slice(position + 1);
|
||||
}
|
||||
}
|
||||
|
|
@ -136,16 +131,61 @@ class SageMaker extends BaseLLM {
|
|||
private async _getCredentials() {
|
||||
try {
|
||||
return await fromIni({
|
||||
profile: SageMaker.PROFILE_NAME,
|
||||
profile: this.profile,
|
||||
})();
|
||||
} catch (e) {
|
||||
console.warn(
|
||||
`AWS profile with name ${SageMaker.PROFILE_NAME} not found in ~/.aws/credentials, using default profile`,
|
||||
`AWS profile with name ${this.profile} not found in ~/.aws/credentials, using default profile`,
|
||||
);
|
||||
return await fromIni()();
|
||||
}
|
||||
}
|
||||
|
||||
async embed(chunks: string[]) {
|
||||
const credentials = await this._getCredentials();
|
||||
const client = new SageMakerRuntimeClient({
|
||||
region: this.region,
|
||||
credentials: {
|
||||
accessKeyId: credentials.accessKeyId,
|
||||
secretAccessKey: credentials.secretAccessKey,
|
||||
sessionToken: credentials.sessionToken || "",
|
||||
},
|
||||
});
|
||||
|
||||
const input = this._generateInvokeModelCommandInput(chunks);
|
||||
const command = new InvokeEndpointCommand(input);
|
||||
const response = await client.send(command);
|
||||
|
||||
if (response.Body) {
|
||||
const responseBody = JSON.parse(new TextDecoder().decode(response.Body));
|
||||
// If the body contains a key called "embedding" or "embeddings", return the value, otherwise return the whole body
|
||||
if (responseBody.embedding) {
|
||||
return responseBody.embedding;
|
||||
} else if (responseBody.embeddings) {
|
||||
return responseBody.embeddings;
|
||||
} else {
|
||||
return responseBody;
|
||||
}
|
||||
}
|
||||
}
|
||||
private _generateInvokeModelCommandInput(prompts: string | string[]): any {
|
||||
const payload = {
|
||||
inputs: prompts,
|
||||
normalize: true,
|
||||
// ...(options.requestOptions?.extraBodyProperties || {}),
|
||||
};
|
||||
|
||||
if (this.requestOptions?.extraBodyProperties) {
|
||||
Object.assign(payload, this.requestOptions.extraBodyProperties);
|
||||
}
|
||||
|
||||
return {
|
||||
EndpointName: this.model,
|
||||
Body: JSON.stringify(payload),
|
||||
ContentType: "application/json",
|
||||
CustomAttributes: "accept_eula=false",
|
||||
};
|
||||
}
|
||||
}
|
||||
|
||||
interface SageMakerModelToolkit {
|
||||
|
|
@ -157,19 +197,20 @@ interface SageMakerModelToolkit {
|
|||
}
|
||||
|
||||
class MessageAPIToolkit implements SageMakerModelToolkit {
|
||||
constructor(private sagemaker: SageMaker) { }
|
||||
constructor(private sagemaker: SageMaker) {}
|
||||
generateCommand(
|
||||
messages: ChatMessage[],
|
||||
prompt: string,
|
||||
options: CompletionOptions,
|
||||
): InvokeEndpointWithResponseStreamCommand {
|
||||
|
||||
if ("chat_template" in this.sagemaker.completionOptions) {
|
||||
// for some model you can apply chat_template to the model
|
||||
let prompt = jinja.compile(this.sagemaker.completionOptions.chat_template).render(
|
||||
{ messages: messages, add_generation_prompt: true },
|
||||
{ autoEscape: false }
|
||||
);
|
||||
let prompt = jinja
|
||||
.compile(this.sagemaker.completionOptions.chat_template)
|
||||
.render(
|
||||
{ messages: messages, add_generation_prompt: true },
|
||||
{ autoEscape: false },
|
||||
);
|
||||
const payload = {
|
||||
inputs: prompt,
|
||||
parameters: this.sagemaker.completionOptions,
|
||||
|
|
@ -182,8 +223,7 @@ class MessageAPIToolkit implements SageMakerModelToolkit {
|
|||
ContentType: "application/json",
|
||||
CustomAttributes: "accept_eula=false",
|
||||
});
|
||||
}
|
||||
else {
|
||||
} else {
|
||||
const payload = {
|
||||
messages: messages,
|
||||
max_tokens: options.maxTokens,
|
||||
|
|
@ -203,11 +243,10 @@ class MessageAPIToolkit implements SageMakerModelToolkit {
|
|||
CustomAttributes: "accept_eula=false",
|
||||
});
|
||||
}
|
||||
|
||||
}
|
||||
}
|
||||
class CompletionAPIToolkit implements SageMakerModelToolkit {
|
||||
constructor(private sagemaker: SageMaker) { }
|
||||
constructor(private sagemaker: SageMaker) {}
|
||||
generateCommand(
|
||||
messages: ChatMessage[],
|
||||
prompt: string,
|
||||
|
|
|
|||
|
|
@ -1,10 +1,9 @@
|
|||
import OpenAI from "./OpenAI.js";
|
||||
|
||||
import type { LLMOptions, ModelProvider } from "../../index.js";
|
||||
|
||||
import type { LLMOptions } from "../../index.js";
|
||||
|
||||
class SambaNova extends OpenAI {
|
||||
static providerName: ModelProvider = "sambanova";
|
||||
static providerName = "sambanova";
|
||||
static defaultOptions: Partial<LLMOptions> = {
|
||||
apiBase: "https://api.sambanova.ai/v1/",
|
||||
};
|
||||
|
|
|
|||
|
|
@ -1,11 +1,11 @@
|
|||
import { CompletionOptions, LLMOptions, ModelProvider } from "../../index.js";
|
||||
import { CompletionOptions, LLMOptions } from "../../index.js";
|
||||
import { streamSse } from "../stream.js";
|
||||
import { osModelsEditPrompt } from "../templates/edit.js";
|
||||
|
||||
import OpenAI from "./OpenAI.js";
|
||||
|
||||
class SiliconFlow extends OpenAI {
|
||||
static providerName: ModelProvider = "siliconflow";
|
||||
static providerName = "siliconflow";
|
||||
static defaultOptions: Partial<LLMOptions> = {
|
||||
apiBase: "https://api.siliconflow.cn/v1/",
|
||||
model: "Qwen/Qwen2.5-Coder-32B-Instruct",
|
||||
|
|
@ -46,13 +46,12 @@ class SiliconFlow extends OpenAI {
|
|||
Accept: "application/json",
|
||||
Authorization: `Bearer ${this.apiKey}`,
|
||||
},
|
||||
signal
|
||||
signal,
|
||||
});
|
||||
for await (const chunk of streamSse(resp)) {
|
||||
yield chunk.choices[0].text;
|
||||
}
|
||||
}
|
||||
|
||||
}
|
||||
|
||||
export default SiliconFlow;
|
||||
|
|
|
|||
39
core/llm/llms/Test.ts
Normal file
39
core/llm/llms/Test.ts
Normal file
|
|
@ -0,0 +1,39 @@
|
|||
import { ChatMessage, CompletionOptions } from "../../index.js";
|
||||
import { BaseLLM } from "../index.js";
|
||||
|
||||
const RESPONSES: Record<string, string> = {
|
||||
"How are you?": "I'm fine",
|
||||
};
|
||||
|
||||
const HARDCODED_CHAT_RESPONSE = "THIS IS A HARDCODED RESPONSE";
|
||||
|
||||
class TestLLM extends BaseLLM {
|
||||
static providerName = "test";
|
||||
|
||||
private findResponse(prompt: string) {
|
||||
return Object.entries(RESPONSES).find(([key]) => prompt.includes(key))?.[1];
|
||||
}
|
||||
|
||||
protected async *_streamComplete(
|
||||
prompt: string,
|
||||
signal: AbortSignal,
|
||||
options: CompletionOptions,
|
||||
): AsyncGenerator<string> {
|
||||
yield this.findResponse(prompt) || `PROMPT: ${prompt}`;
|
||||
}
|
||||
|
||||
protected async *_streamChat(
|
||||
messages: ChatMessage[],
|
||||
signal: AbortSignal,
|
||||
options: CompletionOptions,
|
||||
): AsyncGenerator<ChatMessage> {
|
||||
for (const char of HARDCODED_CHAT_RESPONSE) {
|
||||
yield {
|
||||
role: "assistant",
|
||||
content: char,
|
||||
};
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
export default TestLLM;
|
||||
|
|
@ -1,9 +1,9 @@
|
|||
import { LLMOptions, ModelProvider } from "../../index.js";
|
||||
import { LLMOptions } from "../../index.js";
|
||||
|
||||
import OpenAI from "./OpenAI.js";
|
||||
|
||||
class TextGenWebUI extends OpenAI {
|
||||
static providerName: ModelProvider = "text-gen-webui";
|
||||
static providerName = "text-gen-webui";
|
||||
static defaultOptions: Partial<LLMOptions> = {
|
||||
apiBase: "http://localhost:5000/v1/",
|
||||
};
|
||||
|
|
|
|||
|
|
@ -1,14 +1,9 @@
|
|||
import OpenAI from "./OpenAI.js";
|
||||
|
||||
import type {
|
||||
CompletionOptions,
|
||||
LLMOptions,
|
||||
ModelProvider,
|
||||
} from "../../index.js";
|
||||
|
||||
import type { CompletionOptions, LLMOptions } from "../../index.js";
|
||||
|
||||
class Together extends OpenAI {
|
||||
static providerName: ModelProvider = "together";
|
||||
static providerName = "together";
|
||||
static defaultOptions: Partial<LLMOptions> = {
|
||||
apiBase: "https://api.together.xyz/v1/",
|
||||
};
|
||||
|
|
@ -44,7 +39,11 @@ class Together extends OpenAI {
|
|||
signal: AbortSignal,
|
||||
options: CompletionOptions,
|
||||
): AsyncGenerator<string> {
|
||||
for await (const chunk of this._legacystreamComplete(prompt,signal, options)) {
|
||||
for await (const chunk of this._legacystreamComplete(
|
||||
prompt,
|
||||
signal,
|
||||
options,
|
||||
)) {
|
||||
yield chunk;
|
||||
}
|
||||
}
|
||||
|
|
|
|||
|
|
@ -1,12 +1,11 @@
|
|||
import path from "path";
|
||||
|
||||
import { EmbeddingsProviderName } from "../../index.js";
|
||||
import { LLMOptions } from "../../index.js";
|
||||
import { BaseLLM } from "../../llm/index.js";
|
||||
// @ts-ignore
|
||||
// prettier-ignore
|
||||
import { type PipelineType } from "../../vendor/modules/@xenova/transformers/src/transformers.js";
|
||||
|
||||
import BaseEmbeddingsProvider from "./BaseEmbeddingsProvider.js";
|
||||
|
||||
class EmbeddingsPipeline {
|
||||
static task: PipelineType = "feature-extraction";
|
||||
static model = "all-MiniLM-L6-v2";
|
||||
|
|
@ -39,16 +38,18 @@ class EmbeddingsPipeline {
|
|||
}
|
||||
}
|
||||
|
||||
export class TransformersJsEmbeddingsProvider extends BaseEmbeddingsProvider {
|
||||
static providerName: EmbeddingsProviderName = "transformers.js";
|
||||
export class TransformersJsEmbeddingsProvider extends BaseLLM {
|
||||
static providerName = "transformers.js";
|
||||
static maxGroupSize: number = 1;
|
||||
static model: string = "all-MiniLM-L6-v2";
|
||||
static mockVector: number[] = Array.from({ length: 384 }).fill(2) as number[];
|
||||
|
||||
static defaultOptions: Partial<LLMOptions> | undefined = {
|
||||
model: TransformersJsEmbeddingsProvider.model,
|
||||
};
|
||||
|
||||
constructor() {
|
||||
super({ model: TransformersJsEmbeddingsProvider.model }, () =>
|
||||
Promise.resolve(null),
|
||||
);
|
||||
super({ model: TransformersJsEmbeddingsProvider.model });
|
||||
}
|
||||
|
||||
async embed(chunks: string[]) {
|
||||
|
|
@ -1,11 +1,6 @@
|
|||
import { GoogleAuth } from "google-auth-library";
|
||||
|
||||
import {
|
||||
ChatMessage,
|
||||
CompletionOptions,
|
||||
LLMOptions,
|
||||
ModelProvider,
|
||||
} from "../../index.js";
|
||||
import { ChatMessage, CompletionOptions, LLMOptions } from "../../index.js";
|
||||
import { renderChatMessage } from "../../util/messageContent.js";
|
||||
import { BaseLLM } from "../index.js";
|
||||
import { streamResponse, streamSse } from "../stream.js";
|
||||
|
|
@ -14,12 +9,17 @@ import Anthropic from "./Anthropic.js";
|
|||
import Gemini from "./Gemini.js";
|
||||
|
||||
class VertexAI extends BaseLLM {
|
||||
static providerName: ModelProvider = "vertexai";
|
||||
static providerName = "vertexai";
|
||||
declare apiBase: string;
|
||||
declare vertexProvider: string;
|
||||
declare anthropicInstance: Anthropic;
|
||||
declare geminiInstance: Gemini;
|
||||
|
||||
static defaultOptions: Partial<LLMOptions> | undefined = {
|
||||
maxEmbeddingBatchSize: 5,
|
||||
region: "us-central1",
|
||||
};
|
||||
|
||||
private clientPromise = new GoogleAuth({
|
||||
scopes: "https://www.googleapis.com/auth/cloud-platform",
|
||||
}).getClient();
|
||||
|
|
@ -434,6 +434,39 @@ class VertexAI extends BaseLLM {
|
|||
supportsFim(): boolean {
|
||||
return ["code-gecko", "codestral-latest"].includes(this.model);
|
||||
}
|
||||
|
||||
protected async _embed(chunks: string[]): Promise<number[][]> {
|
||||
const client = await this.clientPromise;
|
||||
const { token } = await client.getAccessToken();
|
||||
if (!token) {
|
||||
throw new Error(
|
||||
"Could not get an access token. Set up your Google Application Default Credentials.",
|
||||
);
|
||||
}
|
||||
|
||||
const resp = await this.fetch(
|
||||
new URL(this.apiBase + `/publishers/google/models/${this.model}:predict`),
|
||||
{
|
||||
method: "POST",
|
||||
body: JSON.stringify({
|
||||
instances: chunks.map((chunk) => ({ content: chunk })),
|
||||
}),
|
||||
headers: {
|
||||
"Content-Type": "application/json",
|
||||
Authorization: `Bearer ${token}`,
|
||||
},
|
||||
},
|
||||
);
|
||||
|
||||
if (!resp.ok) {
|
||||
throw new Error(await resp.text());
|
||||
}
|
||||
|
||||
const data = (await resp.json()) as any;
|
||||
return data.predictions.map(
|
||||
(prediction: any) => prediction.embeddings.values,
|
||||
);
|
||||
}
|
||||
}
|
||||
|
||||
async function delay(seconds: number) {
|
||||
|
|
|
|||
|
|
@ -1,9 +1,9 @@
|
|||
import { LLMOptions, ModelProvider } from "../../index.js";
|
||||
import { LLMOptions } from "../../index.js";
|
||||
|
||||
import OpenAI from "./OpenAI.js";
|
||||
|
||||
class Vllm extends OpenAI {
|
||||
static providerName: ModelProvider = "vllm";
|
||||
static providerName = "vllm";
|
||||
constructor(options: LLMOptions) {
|
||||
super(options);
|
||||
this._setupCompletionOptions();
|
||||
|
|
|
|||
|
|
@ -1,21 +1,13 @@
|
|||
import fetch from "node-fetch";
|
||||
import { Chunk, LLMOptions } from "../../index.js";
|
||||
|
||||
import { Chunk, Reranker } from "../../index.js";
|
||||
import OpenAI from "./OpenAI.js";
|
||||
|
||||
export class VoyageReranker implements Reranker {
|
||||
name = "voyage";
|
||||
|
||||
constructor(
|
||||
private readonly params: {
|
||||
apiKey: string;
|
||||
model?: string;
|
||||
apiBase?: string;
|
||||
},
|
||||
) {}
|
||||
|
||||
private get apiBase() {
|
||||
return this.params.apiBase ?? "https://api.voyageai.com/v1/";
|
||||
}
|
||||
class Voyage extends OpenAI {
|
||||
static providerName = "voyage";
|
||||
static defaultOptions: Partial<LLMOptions> | undefined = {
|
||||
apiBase: "https://api.voyageai.com/v1/",
|
||||
maxEmbeddingBatchSize: 128,
|
||||
};
|
||||
|
||||
async rerank(query: string, chunks: Chunk[]): Promise<number[]> {
|
||||
if (!query || chunks.length === 0) {
|
||||
|
|
@ -26,12 +18,12 @@ export class VoyageReranker implements Reranker {
|
|||
method: "POST",
|
||||
headers: {
|
||||
"Content-Type": "application/json",
|
||||
Authorization: `Bearer ${this.params.apiKey}`,
|
||||
Authorization: `Bearer ${this.apiKey}`,
|
||||
},
|
||||
body: JSON.stringify({
|
||||
query,
|
||||
documents: chunks.map((chunk) => chunk.content),
|
||||
model: this.params.model ?? "rerank-2",
|
||||
model: this.model ?? "rerank-2",
|
||||
}),
|
||||
});
|
||||
|
||||
|
|
@ -48,3 +40,5 @@ export class VoyageReranker implements Reranker {
|
|||
return results.map((result) => result.relevance_score);
|
||||
}
|
||||
}
|
||||
|
||||
export default Voyage;
|
||||
Some files were not shown because too many files have changed in this diff Show more
Loading…
Add table
Reference in a new issue