Skip to main content

Jina Embeddings

The JinaEmbeddings class utilizes the Jina API to generate embeddings for given text inputs. This guide will walk you through the setup and usage of the JinaEmbeddings class, helping you integrate it into your project seamlessly.

Installation​

Install the @langchain/community package as shown below:

npm i @langchain/community

Initialization​

With this integration, you can use the Jina embeddings model to get embeddings for your text data. Here is the link to the embeddings models.

First, you need to sign up on the Jina website and get the API token from here. You can copy model names from the dropdown in the api playground.

To use the JinaEmbeddings class, you need an API token from Jina. You can pass this token directly to the constructor or set it as an environment variable (JINA_API_KEY).

Basic Usage​

Here’s how to create an instance of JinaEmbeddings:

import { JinaEmbeddings } from "@langchain/community/embeddings/jina";

const embeddings = new JinaEmbeddings({
apiToken: "YOUR_API_TOKEN",
model: "jina-embeddings-v2-base-en", // Optional, defaults to "jina-embeddings-v2-base-en"
});

If the apiToken is not provided, it will be read from the JINA_API_KEY environment variable.

Generating Embeddings​

Embedding a Single Query​

To generate embeddings for a single text query, use the embedQuery method:

const embedding = await embeddings.embedQuery(
"What would be a good company name for a company that makes colorful socks?"
);
console.log(embedding);

Embedding Multiple Documents​

To generate embeddings for multiple documents, use the embedDocuments method.

const documents = [
"Document 1 text...",
"Document 2 text...",
"Document 3 text...",
];

const embeddingsArray = await embeddings.embedDocuments(documents);
console.log(embeddingsArray);

Error Handling​

If the API token is not provided and cannot be found in the environment variables, an error will be thrown:

try {
const embeddings = new JinaEmbeddings();
} catch (error) {
console.error("Jina API token not found");
}

Example​

Here’s a complete example of how to set up and use the JinaEmbeddings class:

import { JinaEmbeddings } from "@langchain/community/embeddings/jina";

const embeddings = new JinaEmbeddings({
apiToken: "YOUR_API_TOKEN",
model: "jina-embeddings-v2-base-en",
});

async function runExample() {
const queryEmbedding = await embeddings.embedQuery("Example query text.");
console.log("Query Embedding:", queryEmbedding);

const documents = ["Text 1", "Text 2", "Text 3"];
const documentEmbeddings = await embeddings.embedDocuments(documents);
console.log("Document Embeddings:", documentEmbeddings);
}

runExample();

Feedback and Support​

For feedback or questions, please contact support@jina.ai.


Was this page helpful?


You can also leave detailed feedback on GitHub.