import { ChatOpenAI } from "langchain/chat_models/openai"; import { HNSWLib } from "langchain/vectorstores/hnswlib"; import { OpenAIEmbeddings } from "langchain/embeddings/openai"; import { PromptTemplate } from "langchain/prompts"; import { RunnableSequence, RunnablePassthrough, } from "langchain/schema/runnable"; import { StringOutputParser } from "langchain/schema/output_parser"; import { Document } from "langchain/document"; const model = new ChatOpenAI({}); const vectorStore = await HNSWLib.fromTexts( ["mitochondria is the powerhouse of the cell"], [{ id: 1 }], new OpenAIEmbeddings() ); const retriever = vectorStore.asRetriever(); const prompt = PromptTemplate.fromTemplate(`Answer the question based only on the following context: {context} Question: {question}`); const serializeDocs = (docs: Document[]) => docs.map((doc) => doc.pageContent).join("\n"); const chain = RunnableSequence.from([ { context: retriever.pipe(serializeDocs), question: new RunnablePassthrough(), }, prompt, model, new StringOutputParser(), ]); const result = await chain.invoke("What is the powerhouse of the cell?"); console.log(result); /* "The powerhouse of the cell is the mitochondria." */