makechain.ts 1.9 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152
  1. import { OpenAI } from 'langchain/llms';
  2. import { LLMChain, ChatVectorDBQAChain, loadQAChain } from 'langchain/chains';
  3. import { HNSWLib, SupabaseVectorStore } from 'langchain/vectorstores';
  4. import { PromptTemplate } from 'langchain/prompts';
  5. const CONDENSE_PROMPT =
  6. PromptTemplate.fromTemplate(`Given the following conversation and a follow up question, rephrase the follow up question to be a standalone question.
  7. Chat History:
  8. {chat_history}
  9. Follow Up Input: {question}
  10. Standalone question:`);
  11. const QA_PROMPT = PromptTemplate.fromTemplate(
  12. `You are an AI assistant and a Notion expert. You are given the following extracted parts of a long document and a question. Provide a conversational answer based on the context provided.
  13. You should only use hyperlinks as references that are explicitly listed as a source in the context below. Do NOT make up a hyperlink that is not listed below.
  14. If you can't find the answer in the context below, just say "Hmm, I'm not sure." Don't try to make up an answer.
  15. If the question is not related to Notion, notion api or the context provided, politely inform them that you are tuned to only answer questions that are related to Notion.
  16. Choose the most relevant link that matches the context provided:
  17. Question: {question}
  18. =========
  19. {context}
  20. =========
  21. Answer in Markdown:`,
  22. );
  23. export const makeChain = (
  24. vectorstore: SupabaseVectorStore,
  25. onTokenStream?: (token: string) => void,
  26. ) => {
  27. const questionGenerator = new LLMChain({
  28. llm: new OpenAI({ temperature: 0 }),
  29. prompt: CONDENSE_PROMPT,
  30. });
  31. const docChain = loadQAChain(
  32. new OpenAI({
  33. temperature: 0,
  34. streaming: Boolean(onTokenStream),
  35. callbackManager: {
  36. handleNewToken: onTokenStream,
  37. },
  38. }),
  39. { prompt: QA_PROMPT },
  40. );
  41. return new ChatVectorDBQAChain({
  42. vectorstore,
  43. combineDocumentsChain: docChain,
  44. questionGeneratorChain: questionGenerator,
  45. });
  46. };