feat(embeddings): add gemini provider (#1362)

* docs(walkthroughs): use correct table name for 'tag_catalog'

* feat(embeddings): add gemini

* duplicate code deletion

* docs(contributing): update incorrect instructions

* revert eslint changes

* docs(embeddings): use correct gemini model name

* Delete package.json
This commit is contained in:
Patrick Erichsen 2024-06-04 18:14:16 -05:00 • committed by GitHub
parent 6b902a452c
commit 5224572408
No known key found for this signature in database
GPG key ID: B5690EEEBB952194
25 changed files with 2515 additions and 2070 deletions

5
.gitignore vendored
View file

@ -163,4 +163,7 @@ continue_server.dist
Icon
Icon?
.continue
.continue
# Sandbox env default file
extensions/vscode/manual-testing-sandbox/example.ts

View file

@ -79,7 +79,7 @@ nvm use
1. The new VS Code window with the extension is referred to as the _Host VS Code_
2. The window you started debugging from is referred to as the _Main VS Code_
4. To package the extension, run `npm package` in the `extensions/vscode` directory. This will generate `extensions/vscode/build/continue-patch.vsix`, which you can install by right-clicking and selecting "Install Extension VSIX".
4. To package the extension, run `npm run package` in the `extensions/vscode` directory. This will generate `extensions/vscode/build/continue-{VERSION}.vsix`, which you can install by right-clicking and selecting "Install Extension VSIX".
##### Debugging

View file

@ -85,6 +85,7 @@
"yaml": "^2.4.2"
},
"devDependencies": {
"@google/generative-ai": "^0.11.4",
"@biomejs/biome": "1.6.4",
"@types/follow-redirects": "^1.14.4",
"@types/jest": "^29.5.11",

View file

@ -1,27 +1,30 @@
{
"root": true,
"parser": "@typescript-eslint/parser",
"parserOptions": {
"ecmaVersion": 6,
"sourceType": "module"
},
"extends": ["plugin:require-extensions/recommended"],
"plugins": ["@typescript-eslint", "import", "require-extensions"],
"rules": {
"quotes": ["warn", "double", {}],
"import/extensions": ["error", "always", {
"js": "never",
"jsx": "never",
"ts": "never",
"tsx": "never"
}],
"@typescript-eslint/naming-convention": "warn",
"@typescript-eslint/semi": "warn",
"curly": "warn",
"eqeqeq": "warn",
"no-throw-literal": "warn",
"semi": "off"
},
"ignorePatterns": ["out", "dist", "**/*.d.ts"]
}
"root": true,
"parser": "@typescript-eslint/parser",
"parserOptions": {
"ecmaVersion": 6,
"sourceType": "module"
},
"extends": ["plugin:require-extensions/recommended"],
"plugins": ["@typescript-eslint", "import", "require-extensions"],
"rules": {
"quotes": ["warn", "double", {}],
"import/extensions": [
"error",
"always",
{
"js": "never",
"jsx": "never",
"ts": "never",
"tsx": "never"
}
],
"@typescript-eslint/naming-convention": "warn",
"@typescript-eslint/semi": "warn",
"curly": "warn",
"eqeqeq": "warn",
"no-throw-literal": "warn",
"semi": "off"
},
"ignorePatterns": ["out", "dist", "**/*.d.ts"]
}

View file

@ -28,7 +28,7 @@ import {
SlashCommand,
} from "../index.js";
import TransformersJsEmbeddingsProvider from "../indexing/embeddings/TransformersJsEmbeddingsProvider.js";
import { AllEmbeddingsProviders } from "../indexing/embeddings/index.js";
import { allEmbeddingsProviders } from "../indexing/embeddings/index.js";
import { BaseLLM } from "../llm/index.js";
import CustomLLMClass from "../llm/llms/CustomLLM.js";
import FreeTrial from "../llm/llms/FreeTrial.js";
@ -336,7 +336,7 @@ async function intermediateToFinalConfig(
| undefined;
if (embeddingsProviderDescription?.provider) {
const { provider, ...options } = embeddingsProviderDescription;
const embeddingsProviderClass = AllEmbeddingsProviders[provider];
const embeddingsProviderClass = allEmbeddingsProviders[provider];
if (embeddingsProviderClass) {
if (
embeddingsProviderClass.name === "_TransformersJsEmbeddingsProvider"

3
core/index.d.ts vendored
View file

@ -688,7 +688,8 @@ export type EmbeddingsProviderName =
| "ollama"
| "openai"
| "cohere"
| "free-trial";
| "free-trial"
| "gemini";
export interface EmbedOptions {
apiBase?: string;

View file

@ -1,24 +1,60 @@
import { EmbedOptions, EmbeddingsProvider, FetchFunction } from "../../index.js";
import {
EmbedOptions,
EmbeddingsProvider,
FetchFunction,
} from "../../index.js";
class BaseEmbeddingsProvider implements EmbeddingsProvider {
export interface IBaseEmbeddingsProvider extends EmbeddingsProvider {
options: EmbedOptions;
fetch: FetchFunction;
static defaultOptions: Partial<EmbedOptions> | undefined = undefined;
defaultOptions?: EmbedOptions;
maxBatchSize?: number;
}
get id(): string {
throw new Error("Method not implemented.");
}
abstract class BaseEmbeddingsProvider implements IBaseEmbeddingsProvider {
static maxBatchSize: IBaseEmbeddingsProvider["maxBatchSize"];
static defaultOptions: IBaseEmbeddingsProvider["defaultOptions"];
constructor(options: EmbedOptions, fetch: FetchFunction) {
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;
this.id = this.options.model || this.constructor.name;
}
embed(chunks: string[]): Promise<number[][]> {
throw new Error("Method not implemented.");
abstract embed(chunks: string[]): Promise<number[][]>;
static getBatchedChunks(chunks: string[]): string[][] {
if (!this.maxBatchSize) {
console.warn(
`${this.getBatchedChunks.name} should only be called if 'maxBatchSize' is defined`,
);
return [chunks];
}
if (chunks.length > this.maxBatchSize) {
return [chunks];
}
const batchedChunks = [];
for (let i = 0; i < chunks.length; i += this.maxBatchSize) {
const batchSizedChunk = chunks.slice(i, i + this.maxBatchSize);
batchedChunks.push(batchSizedChunk);
}
return batchedChunks;
}
}

View file

@ -11,10 +11,6 @@ class CohereEmbeddingsProvider extends BaseEmbeddingsProvider {
model: "embed-english-v3.0",
};
get id(): string {
return this.options.model ?? "cohere";
}
async embed(chunks: string[]) {
if (!this.options.apiBase?.endsWith("/")) {
this.options.apiBase += "/";

View file

@ -7,10 +7,6 @@ class DeepInfraEmbeddingsProvider extends BaseEmbeddingsProvider {
model: "sentence-transformers/all-MiniLM-L6-v2",
};
get id(): string {
return this.options.model ?? "deepinfra";
}
async embed(chunks: string[]) {
const fetchWithBackoff = () =>
withExponentialBackoff<Response>(() =>

View file

@ -7,14 +7,11 @@ import BaseEmbeddingsProvider from "./BaseEmbeddingsProvider.js";
class FreeTrialEmbeddingsProvider extends BaseEmbeddingsProvider {
static maxBatchSize = 128;
static defaultOptions: Partial<EmbedOptions> | undefined = {
model: "voyage-code-2",
};
get id(): string {
return FreeTrialEmbeddingsProvider.defaultOptions?.model!;
}
async embed(chunks: string[]) {
const batchedChunks = [];
for (

View file

@ -0,0 +1,72 @@
import { Response } from "node-fetch";
import { withExponentialBackoff } from "../../util/withExponentialBackoff.js";
import BaseEmbeddingsProvider, {
IBaseEmbeddingsProvider,
} from "./BaseEmbeddingsProvider.js";
import {
EmbedContentRequest,
EmbedContentResponse,
} from "@google/generative-ai";
/**
* [View the Gemini Text Embedding docs.](https://ai.google.dev/gemini-api/docs/models/gemini#text-embedding-and-embedding)
*/
class GeminiEmbeddingsProvider extends BaseEmbeddingsProvider {
static maxBatchSize = 2048;
static defaultOptions = {
apiBase: "https://generativelanguage.googleapis.com/v1/",
model: "models/text-embedding-004",
};
get urlPath(): string {
return `${this.options.model}:embedContent`;
}
async getSingleBatchEmbedding(batch: string[]) {
const body: EmbedContentRequest = {
content: {
/**
* Listed as optional in the [docs](https://ai.google.dev/api/rest/v1/Content)
* but is required in the interface.
*/
role: "user",
parts: batch.map((part) => ({ text: part })),
},
};
const fetchWithBackoff = () =>
withExponentialBackoff<Response>(() =>
this.fetch(new URL(this.urlPath, this.options.apiBase), {
method: "POST",
body: JSON.stringify(body),
headers: {
// eslint-disable-next-line @typescript-eslint/naming-convention
"x-goog-api-key": this.options.apiKey,
// eslint-disable-next-line @typescript-eslint/naming-convention
"Content-Type": "application/json",
},
}),
);
const resp = await fetchWithBackoff();
if (!resp.ok) {
throw new Error(await resp.text());
}
const data = (await resp.json()) as EmbedContentResponse;
return data.embedding.values;
}
async embed(chunks: string[]) {
const batches = GeminiEmbeddingsProvider.getBatchedChunks(chunks);
return await Promise.all(
batches.map((batch) => this.getSingleBatchEmbedding(batch)),
);
}
}
export default GeminiEmbeddingsProvider;

View file

@ -1,6 +1,8 @@
import { EmbedOptions, FetchFunction } from "../../index.js";
import { withExponentialBackoff } from "../../util/withExponentialBackoff.js";
import BaseEmbeddingsProvider from "./BaseEmbeddingsProvider.js";
import BaseEmbeddingsProvider, {
IBaseEmbeddingsProvider,
} from "./BaseEmbeddingsProvider.js";
async function embedOne(
chunk: string,
@ -18,6 +20,7 @@ async function embedOne(
}),
);
const resp = await fetchWithBackoff();
if (!resp.ok) {
throw new Error(`Failed to embed chunk: ${await resp.text()}`);
}
@ -26,14 +29,11 @@ async function embedOne(
}
class OllamaEmbeddingsProvider extends BaseEmbeddingsProvider {
static defaultOptions: Partial<EmbedOptions> | undefined = {
static defaultOptions: IBaseEmbeddingsProvider["defaultOptions"] = {
apiBase: "http://localhost:11434/",
model: "nomic-embed-text",
};
get id(): string {
return this.options.model ?? "ollama";
}
async embed(chunks: string[]) {
const results: any = [];
for (const chunk of chunks) {

View file

@ -13,10 +13,6 @@ class OpenAIEmbeddingsProvider extends BaseEmbeddingsProvider {
model: "text-embedding-3-small",
};
get id(): string {
return this.options.model ?? "openai";
}
async embed(chunks: string[]) {
if (!this.options.apiBase?.endsWith("/")) {
this.options.apiBase += "/";

View file

@ -37,17 +37,10 @@ class EmbeddingsPipeline {
}
export class TransformersJsEmbeddingsProvider extends BaseEmbeddingsProvider {
static MaxGroupSize: number = 4;
static maxGroupSize: number = 4;
constructor(modelPath?: string) {
constructor() {
super({ model: "all-MiniLM-L2-v6" }, () => Promise.resolve(null));
if (modelPath) {
// env.localModelPath = modelPath;
}
}
get id(): string {
return EmbeddingsPipeline.model;
}
async embed(chunks: string[]) {
@ -65,11 +58,11 @@ export class TransformersJsEmbeddingsProvider extends BaseEmbeddingsProvider {
for (
let i = 0;
i < chunks.length;
i += TransformersJsEmbeddingsProvider.MaxGroupSize
i += TransformersJsEmbeddingsProvider.maxGroupSize
) {
const chunkGroup = chunks.slice(
i,
i + TransformersJsEmbeddingsProvider.MaxGroupSize,
i + TransformersJsEmbeddingsProvider.maxGroupSize,
);
const output = await extractor(chunkGroup, {
pooling: "mean",

View file

@ -42,11 +42,11 @@ parentPort.on("message", async (chunks) => {
for (
let i = 0;
i < chunks.length;
i += TransformersJsEmbeddingsProvider.MaxGroupSize
i += TransformersJsEmbeddingsProvider.maxGroupSize
) {
const chunkGroup = chunks.slice(
i,
i + TransformersJsEmbeddingsProvider.MaxGroupSize,
i + TransformersJsEmbeddingsProvider.maxGroupSize,
);
const output = await extractor(chunkGroup, {
pooling: "mean",

View file

@ -1,16 +1,26 @@
import { EmbeddingsProviderName } from "../../index.js";
import BaseEmbeddingsProvider from "./BaseEmbeddingsProvider.js";
import CohereEmbeddingsProvider from "./CohereEmbeddingsProvider.js";
import FreeTrialEmbeddingsProvider from "./FreeTrialEmbeddingsProvider.js";
import OllamaEmbeddingsProvider from "./OllamaEmbeddingsProvider.js";
import OpenAIEmbeddingsProvider from "./OpenAIEmbeddingsProvider.js";
import TransformersJsEmbeddingsProvider from "./TransformersJsEmbeddingsProvider.js";
import GeminiEmbeddingsProvider from "./GeminiEmbeddingsProvider.js";
export const AllEmbeddingsProviders: {
[key in EmbeddingsProviderName]: any;
} = {
type EmbeddingsProviderConstructor = new (
...args: any[]
) => BaseEmbeddingsProvider;
export const allEmbeddingsProviders: Record<
EmbeddingsProviderName,
EmbeddingsProviderConstructor
> = {
ollama: OllamaEmbeddingsProvider,
// eslint-disable-next-line @typescript-eslint/naming-convention
"transformers.js": TransformersJsEmbeddingsProvider,
openai: OpenAIEmbeddingsProvider,
cohere: CohereEmbeddingsProvider,
// eslint-disable-next-line @typescript-eslint/naming-convention
"free-trial": FreeTrialEmbeddingsProvider,
gemini: GeminiEmbeddingsProvider,
};

10
core/package-lock.json generated
View file

@ -54,6 +54,7 @@
},
"devDependencies": {
"@biomejs/biome": "1.6.4",
"@google/generative-ai": "^0.11.4",
"@types/follow-redirects": "^1.14.4",
"@types/jest": "^29.5.11",
"@types/jquery": "^3.5.29",
@ -1895,6 +1896,15 @@
"integrity": "sha512-k2Ty1JcVojjJFwrg/ThKi2ujJ7XNLYaFGNB/bWT9wGR+oSMJHMa5w+CUq6p/pVrKeNNgA7pCqEcjSnHVoqJQFw==",
"optional": true
},
"node_modules/@google/generative-ai": {
"version": "0.11.4",
"resolved": "https://registry.npmjs.org/@google/generative-ai/-/generative-ai-0.11.4.tgz",
"integrity": "sha512-hlw+E9Prv9aUIQISRnLSXi4rukFqKe5WhxPvzBccTvIvXjw2BHMFOJWSC/Gq7WE0W+L/qRHGmYxopmx9qjrB9w==",
"dev": true,
"engines": {
"node": ">=18.0.0"
}
},
"node_modules/@huggingface/jinja": {
"version": "0.1.3",
"resolved": "https://registry.npmjs.org/@huggingface/jinja/-/jinja-0.1.3.tgz",

View file

@ -12,6 +12,7 @@
"author": "Nate Sesti and Ty Dunn",
"license": "Apache-2.0",
"devDependencies": {
"@google/generative-ai": "^0.11.4",
"@biomejs/biome": "1.6.4",
"@types/follow-redirects": "^1.14.4",
"@types/jest": "^29.5.11",
@ -37,7 +38,6 @@
"@typescript-eslint/eslint-plugin": "^7.8.0",
"@typescript-eslint/parser": "^7.8.0",
"@xenova/transformers": "2.14.0",
"onnxruntime-node": "1.14.0",
"adf-to-md": "^1.1.0",
"axios": "^1.6.7",
"cheerio": "^1.0.0-rc.12",
@ -57,6 +57,7 @@
"node-fetch": "^3.3.2",
"node-html-markdown": "^1.3.0",
"ollama": "^0.4.6",
"onnxruntime-node": "1.14.0",
"openai": "^4.20.1",
"pg": "^8.11.3",
"posthog-node": "^3.6.3",

View file

@ -103,8 +103,7 @@ Voyage AI offers the best embeddings for code with their voyage-code-2 model. Af
"embeddingsProvider": {
"provider": "openai",
"model": "voyage-code-2",
"apiBase": "
https://api.voyageai.com/v1/",
"apiBase": "https://api.voyageai.com/v1/",
"apiKey": "<VOYAGE_API_KEY>"
}
}
@ -165,13 +164,28 @@ Configuration for the `embed-english-v3.0` model. This is the default.
"embeddingsProvider": {
"provider": "cohere",
"model": "embed-english-v3.0",
"apiKey": "YOUR_API_KEY"
"apiKey": "<COHERE_API_KEY>"
}
}
```
See Cohere's [embeddings](https://docs.cohere.com/docs/embed-2) for available models. Only embedding models v3 and higher are supported.
### Gemini
Gemini's _Text Embedding_ model is optimized for creating embeddings with 768 dimensions for text of up to 2,048 tokens.
As of May 2024, the only available embedding model from Gemini is [`text-embedding-004`](https://ai.google.dev/gemini-api/docs/models/gemini#text-embedding-and-embedding).
```json title="~/.continue/config.json"
{
"embeddingsProvider": {
"provider": "gemini",
"apiKey": "<GEMINI_API_KEY>"
}
}
```
### Writing a custom `EmbeddingsProvider`
If you have your own API capable of generating embeddings, Continue makes it easy to write a custom `EmbeddingsProvider`. All you have to do is write a function that converts strings to arrays of numbers, and add this to your config in `config.ts`. Here's an example:
@ -201,6 +215,6 @@ export function modifyConfig(config: Config): Config {
Continue respects `.gitignore` files in order to determine which files should not be indexed. If you'd like to exclude additional files, you can add them to a `.continueignore` file, which follows the exact same rules as `.gitignore`.
If you want to see exactly what files Continue has indexed, the metadata is stored in `~/.continue/index/index.sqlite`. You can use a tool like [DB Browser for SQLite](https://sqlitebrowser.org/) to view the `tags_catalog` table within this file.
If you want to see exactly what files Continue has indexed, the metadata is stored in `~/.continue/index/index.sqlite`. You can use a tool like [DB Browser for SQLite](https://sqlitebrowser.org/) to view the `tag_catalog` table within this file.
If you need to force a refresh of the index, reload the VS Code window with `cmd/ctrl + shift + p` + "Reload Window".

View file

@ -1814,7 +1814,8 @@
"ollama",
"openai",
"cohere",
"free-trial"
"free-trial",
"gemini"
]
},
"model": {
@ -1838,20 +1839,20 @@
"if": {
"properties": {
"provider": {
"enum": ["ollama"]
"enum": ["cohere"]
}
},
"required": ["provider"]
},
"then": {
"required": ["model"]
"required": ["apiKey"]
}
},
{
"if": {
"properties": {
"provider": {
"enum": ["cohere"]
"enum": ["gemini"]
}
},
"required": ["provider"]

View file

@ -1814,7 +1814,8 @@
"ollama",
"openai",
"cohere",
"free-trial"
"free-trial",
"gemini"
]
},
"model": {
@ -1838,20 +1839,20 @@
"if": {
"properties": {
"provider": {
"enum": ["ollama"]
"enum": ["cohere"]
}
},
"required": ["provider"]
},
"then": {
"required": ["model"]
"required": ["apiKey"]
}
},
{
"if": {
"properties": {
"provider": {
"enum": ["cohere"]
"enum": ["gemini"]
}
},
"required": ["provider"]

View file

@ -1814,7 +1814,8 @@
"ollama",
"openai",
"cohere",
"free-trial"
"free-trial",
"gemini"
]
},
"model": {
@ -1838,20 +1839,20 @@
"if": {
"properties": {
"provider": {
"enum": ["ollama"]
"enum": ["cohere"]
}
},
"required": ["provider"]
},
"then": {
"required": ["model"]
"required": ["apiKey"]
}
},
{
"if": {
"properties": {
"provider": {
"enum": ["cohere"]
"enum": ["gemini"]
}
},
"required": ["provider"]

View file

@ -2015,7 +2015,8 @@
"ollama",
"openai",
"cohere",
"free-trial"
"free-trial",
"gemini"
]
},
"model": {
@ -2041,9 +2042,7 @@
"if": {
"properties": {
"provider": {
"enum": [
"ollama"
]
"enum": ["cohere"]
}
},
"required": [
@ -2051,18 +2050,14 @@
]
},
"then": {
"required": [
"model"
]
"required": ["apiKey"]
}
},
{
"if": {
"properties": {
"provider": {
"enum": [
"cohere"
]
"enum": ["gemini"]
}
},
"required": [

View file

@ -135,6 +135,7 @@
"yaml": "^2.4.2"
},
"devDependencies": {
"@google/generative-ai": "^0.11.4",
"@biomejs/biome": "1.6.4",
"@types/follow-redirects": "^1.14.4",
"@types/jest": "^29.5.11",

4247
gui/package-lock.json generated

File diff suppressed because it is too large Load diff