Skip to content

Instantly share code, notes, and snippets.

@vinodkiran
Created October 17, 2023 10:12
Show Gist options
  • Select an option

  • Save vinodkiran/b4795a8be49b97b2c409c7eaab804196 to your computer and use it in GitHub Desktop.

Select an option

Save vinodkiran/b4795a8be49b97b2c409c7eaab804196 to your computer and use it in GitHub Desktop.
import { ConsoleCallbackHandler } from "langchain/callbacks";
import { MongoDBAtlasVectorSearch } from "langchain/vectorstores/mongodb_atlas";
import { OpenAI } from "langchain/llms/openai";
import { RetrievalQAChain } from "langchain/chains";
import { MongoClient } from "mongodb";
import { CohereEmbedding s} from "langchain/embeddings/cohere";
import dotenv from "dotenv";
dotenv.config();
// Define the main function to run the entire process
export async function run() {
const model = new OpenAI({
temperature: 0.8,
modelName: "gpt-3.5-turbo",
callbacks: [new ConsoleCallbackHandler()],
});
console.log("Using :: " + model.modelName + " temperature: " + model.temperature);
console.log("Connecting to MongoDB...");
const client = new MongoClient(process.env.MONGODB_ATLAS_URI);
try {
const namespace = "langchain.test2";
const [dbName, collectionName] = namespace.split(".");
const collection = client.db(dbName).collection(collectionName);
const query = "Tell me about NATO alliance";
const vectorStore = new MongoDBAtlasVectorSearch (
new CohereEmbeddings(),
{
collection: collection,
indexName: "default1",
textKey: "text",
embeddingKey: "embedding"
}
);
// Initialize a retriever wrapper around the vector store
const vectorStoreRetriever = vectorStore.asRetriever();
console.log("MongoDB similaritySearchVectorWithScore...");
const results = await vectorStore.similaritySearchVectorWithScore (
await vectorStore.embeddings.embedQuery(query),
5
);
console.log("MongoDB returned...");
console.log(results);
// Create a chain that uses the OpenAI LLM and vector store.
const chain = RetrievalQAChain.fromLLM(model, vectorStoreRetriever);
const res = await chain.call({
query: query,
});
console.log({ res });
} finally {
await client.close();
}
}
run();
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment