Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Added filter to ChromaDB vector store + update chroma package. #1348

Merged
merged 4 commits into from
May 23, 2023
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
15 changes: 15 additions & 0 deletions examples/src/indexes/vector_stores/chroma/fromTexts.ts
Original file line number Diff line number Diff line change
Expand Up @@ -34,3 +34,18 @@ console.log(response);
}
]
*/

// You can also filter by metadata
const filteredResponse = await vectorStore.similaritySearch("scared", 2, {
id: 1,
});

console.log(filteredResponse);
/*
[
Document {
pageContent: 'Achilles: Yiikes! What is that?',
metadata: { id: 1 }
}
]
*/
4 changes: 2 additions & 2 deletions langchain/package.json
Original file line number Diff line number Diff line change
Expand Up @@ -377,7 +377,7 @@
"apify-client": "^2.7.1",
"axios": "^0.26.0",
"cheerio": "^1.0.0-rc.12",
"chromadb": "^1.4.0",
"chromadb": "^1.4.2",
"cohere-ai": "^5.0.2",
"d3-dsv": "^2.0.0",
"dotenv": "^16.0.3",
Expand Down Expand Up @@ -431,7 +431,7 @@
"apify-client": "^2.7.1",
"axios": "*",
"cheerio": "^1.0.0-rc.12",
"chromadb": "^1.4.0",
"chromadb": "^1.4.2",
"cohere-ai": "^5.0.2",
"d3-dsv": "^2.0.0",
"epub2": "^3.0.1",
Expand Down
53 changes: 39 additions & 14 deletions langchain/src/vectorstores/chroma.ts
Original file line number Diff line number Diff line change
Expand Up @@ -10,14 +10,18 @@ export type ChromaLibArgs =
url?: string;
numDimensions?: number;
collectionName?: string;
filter?: object;
}
| {
index?: ChromaClientT;
numDimensions?: number;
collectionName?: string;
filter?: object;
};

export class Chroma extends VectorStore {
declare FilterType: object;

index?: ChromaClientT;

collection?: Collection;
Expand All @@ -28,6 +32,8 @@ export class Chroma extends VectorStore {

url: string;

filter?: object;

constructor(embeddings: Embeddings, args: ChromaLibArgs) {
super(embeddings, args);
this.numDimensions = args.numDimensions;
Expand All @@ -38,6 +44,8 @@ export class Chroma extends VectorStore {
} else if ("url" in args) {
this.url = args.url || "http://localhost:8000";
}

this.filter = args.filter;
}

async addDocuments(documents: Document[]): Promise<void> {
Expand All @@ -52,11 +60,15 @@ export class Chroma extends VectorStore {
if (!this.collection) {
if (!this.index) {
const { ChromaClient } = await Chroma.imports();
this.index = new ChromaClient(this.url);
this.index = new ChromaClient({ path: this.url });
}
try {
this.collection = await this.index.getOrCreateCollection({
name: this.collectionName,
});
} catch (err) {
throw new Error(`Chroma getOrCreateCollection error: ${err}`);
}
this.collection = await this.index.getOrCreateCollection(
this.collectionName
);
}

return this.collection;
Expand All @@ -80,22 +92,35 @@ export class Chroma extends VectorStore {

const collection = await this.ensureCollection();
const docstoreSize = await collection.count();
await collection.add(
Array.from({ length: vectors.length }, (_, i) =>
await collection.add({
ids: Array.from({ length: vectors.length }, (_, i) =>
(docstoreSize + i).toString()
),
vectors,
documents.map(({ metadata }) => metadata),
documents.map(({ pageContent }) => pageContent)
);
embeddings: vectors,
metadatas: documents.map(({ metadata }) => metadata),
documents: documents.map(({ pageContent }) => pageContent),
});
}

async similaritySearchVectorWithScore(query: number[], k: number) {
async similaritySearchVectorWithScore(
query: number[],
k: number,
filter?: this["FilterType"]
) {
if (filter && this.filter) {
throw new Error("cannot provide both `filter` and `this.filter`");
}
const _filter = filter ?? this.filter;

const collection = await this.ensureCollection();

// similaritySearchVectorWithScore supports one query vector at a time
// chroma supports multiple query vectors at a time
const result = await collection.query(query, k);
const result = await collection.query({
query_embeddings: query,
n_results: k,
where: { ..._filter },
});

const { ids, distances, documents, metadatas } = result;
if (!ids || !distances || !documents || !metadatas) {
Expand All @@ -111,8 +136,8 @@ export class Chroma extends VectorStore {
for (let i = 0; i < firstIds.length; i += 1) {
results.push([
new Document({
pageContent: firstDocuments[i],
metadata: firstMetadatas[i],
pageContent: firstDocuments?.[i] ?? "",
metadata: firstMetadatas?.[i] ?? {},
}),
firstDistances[i],
]);
Expand Down
52 changes: 52 additions & 0 deletions langchain/src/vectorstores/tests/chroma.int.test.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,52 @@
/* eslint-disable no-process-env */
/* eslint-disable @typescript-eslint/no-non-null-assertion */
import { beforeEach, describe, expect, test } from "@jest/globals";
import { faker } from "@faker-js/faker";
import * as uuid from "uuid";
import { Document } from "../../document.js";
import { Chroma } from "../chroma.js";
import { OpenAIEmbeddings } from "../../embeddings/openai.js";

describe("Chroma", () => {
let chromaStore: Chroma;

beforeEach(async () => {
const embeddings = new OpenAIEmbeddings();
chromaStore = new Chroma(embeddings, {
url: "http://localhost:8000",
collectionName: "test-collection",
});
});

test("auto-generated ids", async () => {
const pageContent = faker.lorem.sentence(5);

await chromaStore.addDocuments([{ pageContent, metadata: { foo: "bar" } }]);

const results = await chromaStore.similaritySearch(pageContent, 1);

expect(results).toEqual([
new Document({ metadata: { foo: "bar" }, pageContent }),
]);
});

test("metadata filtering", async () => {
const pageContent = faker.lorem.sentence(5);
const id = uuid.v4();

await chromaStore.addDocuments([
{ pageContent, metadata: { foo: "bar" } },
{ pageContent, metadata: { foo: id } },
{ pageContent, metadata: { foo: "qux" } },
]);

// If the filter wasn't working, we'd get all 3 documents back
const results = await chromaStore.similaritySearch(pageContent, 3, {
foo: id,
});

expect(results).toEqual([
new Document({ metadata: { foo: id }, pageContent }),
]);
});
});
11 changes: 9 additions & 2 deletions yarn.lock
Original file line number Diff line number Diff line change
Expand Up @@ -10615,6 +10615,13 @@ __metadata:
languageName: node
linkType: hard

"chromadb@npm:^1.4.2":
version: 1.4.2
resolution: "chromadb@npm:1.4.2"
checksum: 6fe81e889ae3f6ac39c1a168bcabe12771b0a5271be503db47aa3f8e5c159e29e5eaa7387780fb08d8ef370a42ce58455de1f0622367cb62c4486dfb3b84c20f
languageName: node
linkType: hard

"chrome-trace-event@npm:^1.0.2":
version: 1.0.3
resolution: "chrome-trace-event@npm:1.0.3"
Expand Down Expand Up @@ -18015,7 +18022,7 @@ __metadata:
axios: ^0.26.0
binary-extensions: ^2.2.0
cheerio: ^1.0.0-rc.12
chromadb: ^1.4.0
chromadb: ^1.4.2
cohere-ai: ^5.0.2
d3-dsv: ^2.0.0
dotenv: ^16.0.3
Expand Down Expand Up @@ -18081,7 +18088,7 @@ __metadata:
apify-client: ^2.7.1
axios: "*"
cheerio: ^1.0.0-rc.12
chromadb: ^1.4.0
chromadb: ^1.4.2
cohere-ai: ^5.0.2
d3-dsv: ^2.0.0
epub2: ^3.0.1
Expand Down