/* Conversational Retrieval Chain */
import { ChatOpenAI } from "langchain/chat_models/openai";
import { OpenAIEmbeddings } from "langchain/embeddings/openai";
import { PromptTemplate } from "langchain/prompts";
import {
RunnableSequence,
RunnablePassthrough,
} from "langchain/schema/runnable";
import { MemoryVectorStore } from "langchain/vectorstores/memory";
import { StringOutputParser } from "langchain/schema/output_parser";
const model = new ChatOpenAI({});
const vectorStore = await MemoryVectorStore.fromTexts(
[
"mitochondria is the powerhouse of the cell",
"mitochondria is made of lipids",
],
[{ id: 1 }, { id: 2 }],
new OpenAIEmbeddings(),
);
const retriever = vectorStore.asRetriever();
const condenseQuestionTemplate = `Given the following conversation and a follow up question,
rephrase the follow up question to be a standalone question.
Chat History:
{chat_history}
Follow Up Input: {question}
Standalone question:
`;
const CONDENSE_QUESTION_PROMPT = PromptTemplate.fromTemplate(
condenseQuestionTemplate
);
const answerTemplate = `Answer the question based only on the following context:
{context}
Question: {question}
`;
const ANSWER_PROMPT = PromptTemplate.fromTemplate(answerTemplate);
const conversationalRetrievalQAChain;
const result1 = await conversationalRetrievalQAChain.invoke({
question: "What is the powerhouse of the cell?",
chat_history: [],
});
console.log(result1);
/*
AIMessage { content: "The powerhouse of the cell is the mitochondria." }
*/
const result2 = await conversationalRetrievalQAChain.invoke({
question: "What are they made out of?",
chat_history: [
[
"What is the powerhouse of the cell?",
"The powerhouse of the cell is the mitochondria.",
],
],
});
console.log(result2);
/*
AIMessage { content: "Mitochondria are made out of lipids." }
*/