How to connect with weaviate and stored the all the embedding #5649
Unanswered
lakshya29154
asked this question in
Q&A
Replies: 1 comment 1 reply
-
To connect to Weaviate and store your embeddings, you can use the
Here is the updated code: import * as fs from "fs";
import { config } from 'dotenv';
import { createHash } from 'crypto';
import { RecursiveCharacterTextSplitter } from "langchain/text_splitter";
import { OpenAIEmbeddings } from "@langchain/openai";
import weaviate, { ApiKey } from "weaviate-ts-client";
import { WeaviateStore } from "@langchain/weaviate";
config();
const OPENAI_API_KEY = process.env.OPENAI_API_KEY;
function generateHash(text) {
return createHash('sha256').update(text).digest('hex');
}
async function splitTextIntoChunks(text) {
const splitter = new RecursiveCharacterTextSplitter({ chunkSize: 1000, chunkOverlap: 200 });
const documents = await splitter.createDocuments([text]);
return documents.map(doc => doc.pageContent);
}
async function generateEmbeddings(textChunks) {
const embeddings = new OpenAIEmbeddings({ apiKey: process.env.OPENAI_API_KEY });
const vectors = [];
for (const chunk of textChunks) {
const vector = await embeddings.embedQuery(chunk);
console.log("Generated Vector:", vector); // Log to check the vector
if (vector && vector.length > 0) {
vectors.push({ chunk, vector });
} else {
console.error("Invalid or empty vector generated for chunk:", chunk);
}
}
return vectors;
}
async function main() {
try {
const specFilePath = './swagger.json';
const jsonData = fs.readFileSync(specFilePath, 'utf8');
// Generate SHA256 hash of JSON data
const hash = generateHash(jsonData);
const textChunks = await splitTextIntoChunks(jsonData);
console.log("Text chunk", textChunks);
// Generate embeddings for JSON data
const embeddings = await generateEmbeddings(textChunks);
console.log("Embeddings", embeddings);
// Initialize Weaviate client
const client = weaviate.client({
scheme: process.env.WEAVIATE_SCHEME || "https",
host: process.env.WEAVIATE_HOST || "localhost",
apiKey: new ApiKey(process.env.WEAVIATE_API_KEY || "default"),
});
// Create a store and fill it with some texts + metadata
await WeaviateStore.fromTexts(
textChunks,
textChunks.map(chunk => ({ hash })),
new OpenAIEmbeddings(),
{
client,
indexName: "Test",
textKey: "text",
metadataKeys: ["hash"],
}
);
console.log('Embeddings stored successfully.');
} catch (error) {
console.error('Error:', error);
}
}
main(); This code initializes the Weaviate client, creates a |
Beta Was this translation helpful? Give feedback.
1 reply
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Uh oh!
There was an error while loading. Please reload this page.
-
Checked other resources
Commit to Help
Example Code
Description
Here now I want to connect to weaviate and store my all embedding in we aviate
System Info
all ok
Beta Was this translation helpful? Give feedback.
All reactions