Skip to content

Commit

Permalink
[ENH] Add JinaEmbedding TypeScript client (#1406)
Browse files Browse the repository at this point in the history
## Description of changes

Add TypeScript client for Jina Embeddings as suggested in #1324 

Docs PR: chroma-core/docs#173

---------

Signed-off-by: Joan Fontanals Martinez <[email protected]>
  • Loading branch information
JoanFM authored Dec 13, 2023
1 parent 0bc493c commit 3939974
Show file tree
Hide file tree
Showing 2 changed files with 47 additions and 0 deletions.
46 changes: 46 additions & 0 deletions clients/js/src/embeddings/JinaEmbeddingFunction.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,46 @@
import { IEmbeddingFunction } from "./IEmbeddingFunction";

export class JinaEmbeddingFunction implements IEmbeddingFunction {
private model_name: string;
private api_url: string;
private headers: { [key: string]: string };

constructor({ jinaai_api_key, model_name }: { jinaai_api_key: string; model_name?: string }) {
this.model_name = model_name || 'jina-embeddings-v2-base-en';
this.api_url = 'https://api.jina.ai/v1/embeddings';
this.headers = {
Authorization: `Bearer ${jinaai_api_key}`,
'Accept-Encoding': 'identity',
'Content-Type': 'application/json',
};
}

public async generate(texts: string[]) {
try {
const response = await fetch(this.api_url, {
method: 'POST',
headers: this.headers,
body: JSON.stringify({
input: texts,
model: this.model_name,
}),
});

const data = (await response.json()) as { data: any[]; detail: string };
if (!data || !data.data) {
throw new Error(data.detail);
}

const embeddings: any[] = data.data;
const sortedEmbeddings = embeddings.sort((a, b) => a.index - b.index);

return sortedEmbeddings.map((result) => result.embedding);
} catch (error) {
if (error instanceof Error) {
throw new Error(`Error calling Jina AI API: ${error.message}`);
} else {
throw new Error(`Error calling Jina AI API: ${error}`);
}
}
}
}
1 change: 1 addition & 0 deletions clients/js/src/index.ts
Original file line number Diff line number Diff line change
Expand Up @@ -36,3 +36,4 @@ export {
DeleteParams
} from './types';
export { HuggingFaceEmbeddingServerFunction } from './embeddings/HuggingFaceEmbeddingServerFunction';
export { JinaEmbeddingFunction } from './embeddings/JinaEmbeddingFunction';

0 comments on commit 3939974

Please sign in to comment.