{ "cells": [ { "cell_type": "code", "execution_count": 1, "metadata": {}, "outputs": [], "source": [ "import os\n", "import openai\n", "\n", "from langchain_openai.chat_models import ChatOpenAI\n", "from langchain.chains import ConversationalRetrievalChain\n", "from langchain_openai import OpenAIEmbeddings\n", "from langchain.text_splitter import RecursiveCharacterTextSplitter\n", "from langchain_community.document_loaders import TextLoader\n", "from langchain_community.vectorstores import Chroma\n", "from langchain.memory import ConversationBufferWindowMemory" ] }, { "cell_type": "code", "execution_count": 2, "metadata": {}, "outputs": [], "source": [ "from dotenv import load_dotenv, find_dotenv\n", "_ = load_dotenv(find_dotenv()) # read local .env file\n", "\n", "openai.api_key = os.environ['OPENAI_API_KEY']\n", "\n", "llm_name = \"gpt-3.5-turbo\"" ] }, { "cell_type": "code", "execution_count": 3, "metadata": {}, "outputs": [], "source": [ "def load_db(file, chain_type, k):\n", " # load transcript\n", " transcript = TextLoader(file).load()\n", " # split documents\n", " text_splitter = RecursiveCharacterTextSplitter(chunk_size=500, chunk_overlap=70)\n", " docs = text_splitter.split_documents(transcript)\n", " # define embedding\n", " embeddings = OpenAIEmbeddings() # will be different for Cohere AI\n", " # create vector database from data\n", " db = Chroma.from_documents(docs, embeddings)\n", " # define retriever\n", " retriever = db.as_retriever(search_type=\"similarity\", search_kwargs={\"k\": k})\n", " # retrieval_chain = create_retrieval_chain(retriever, combine_docs_chain)\n", "\n", " # create a chatbot chain. Memory is managed externally.\n", " qa = ConversationalRetrievalChain.from_llm(\n", " llm = ChatOpenAI(temperature=0), #### Prompt Template is yet to be created\n", " chain_type=chain_type, #### Refine \n", " retriever=retriever, \n", " return_source_documents=True,\n", " return_generated_question=True,\n", " # memory=memory\n", " )\n", " \n", " return qa " ] }, { "cell_type": "code", "execution_count": 4, "metadata": {}, "outputs": [], "source": [ "def buffer(history, buff):\n", " # basically a filter function\n", " # takes the chat history, ensures only buff latest elements exist\n", " if len(history) > buff :\n", " print(len(history)>buff)\n", " return history[-buff:]\n", " else:\n", " return history" ] }, { "cell_type": "code", "execution_count": 5, "metadata": {}, "outputs": [], "source": [ "chat_history = []" ] }, { "cell_type": "code", "execution_count": 6, "metadata": {}, "outputs": [ { "name": "stderr", "output_type": "stream", "text": [ "/home/maxx/.conda/envs/vcdeploy/lib/python3.10/site-packages/langchain_core/_api/deprecation.py:117: LangChainDeprecationWarning: The function `__call__` was deprecated in LangChain 0.1.0 and will be removed in 0.2.0. Use invoke instead.\n", " warn_deprecated(\n" ] } ], "source": [ "qa = load_db(\"./sample.txt\", 'stuff', 4)\n", "query = \"Namaste! I need your help\"\n", "result = qa({'question': query, 'chat_history': chat_history}) #######################################" ] }, { "cell_type": "code", "execution_count": 7, "metadata": {}, "outputs": [ { "data": { "text/plain": [ "langchain.chains.conversational_retrieval.base.ConversationalRetrievalChain" ] }, "execution_count": 7, "metadata": {}, "output_type": "execute_result" } ], "source": [ "type(qa)" ] }, { "cell_type": "code", "execution_count": 7, "metadata": {}, "outputs": [ { "data": { "text/plain": [ "\"Namaste! I'm here to help. What do you need assistance with?\"" ] }, "execution_count": 7, "metadata": {}, "output_type": "execute_result" } ], "source": [ "answer = result['answer']\n", "answer" ] }, { "cell_type": "code", "execution_count": 8, "metadata": {}, "outputs": [ { "data": { "text/plain": [ "{'question': 'Namaste! I need your help',\n", " 'chat_history': [],\n", " 'answer': \"Namaste! I'm here to help. What do you need assistance with?\",\n", " 'source_documents': [Document(page_content='~160~Aurora nodded and waved her magic wand, casting a spell that spread throughout the forest. From that day on, the animals frolicked and played in harmony, their hearts filled with joy and gratitude.\\n~180~As Sammy climbed down from the Golden Acorn Tree, he felt a warm glow of happiness inside. He may have only found one golden acorn, but he had discovered something even more precious – the power of kindness and the magic of friendship.', metadata={'source': './sample.txt'}),\n", " Document(page_content='~40~One sunny morning, as Sammy scampered through the trees, he stumbled upon a mysterious path he had never seen before. Intrigued, he decided to follow it. The path led him deeper and deeper into the forest until he reached a clearing filled with colorful flowers and fluttering butterflies.', metadata={'source': './sample.txt'}),\n", " Document(page_content='~120~\"Yes, indeed! And I am here to grant you a wish for finding the Golden Acorn Tree,\" said Aurora with a smile.\\n~140~Sammy thought for a moment, his little squirrel brain buzzing with ideas. Finally, he knew exactly what he wanted. \"I wish for all the animals in the forest to be happy and healthy forever,\" he declared.', metadata={'source': './sample.txt'}),\n", " Document(page_content='~10~Once upon a time in the lush green forest,\\n~13~there lived a curious little squirrel named Sammy.\\n~25~Sammy had soft, brown fur and big, bright eyes that sparkled with excitement. He loved exploring every nook and cranny of the forest, searching for new adventures.', metadata={'source': './sample.txt'})],\n", " 'generated_question': 'Namaste! I need your help'}" ] }, "execution_count": 8, "metadata": {}, "output_type": "execute_result" } ], "source": [ "result" ] }, { "cell_type": "code", "execution_count": 19, "metadata": {}, "outputs": [], "source": [ "chat_history.extend([(query, result['answer'])])\n", "chat_history = buffer(chat_history,3)" ] }, { "cell_type": "code", "execution_count": 20, "metadata": {}, "outputs": [], "source": [ "query = \"What is the moral of the story?\"\n", "result = qa({\"question\": query, \"chat_history\": chat_history}) #######################################" ] }, { "cell_type": "code", "execution_count": 21, "metadata": {}, "outputs": [ { "data": { "text/plain": [ "{'question': 'What is the moral of the story?',\n", " 'chat_history': [('Namaste! I need your help',\n", " \"Namaste! I'm here to help. What do you need assistance with?\")],\n", " 'answer': 'The moral of the story is that kindness, friendship, courage, and love can lead to magical adventures and wonderful experiences.',\n", " 'source_documents': [Document(page_content='~160~Aurora nodded and waved her magic wand, casting a spell that spread throughout the forest. From that day on, the animals frolicked and played in harmony, their hearts filled with joy and gratitude.\\n~180~As Sammy climbed down from the Golden Acorn Tree, he felt a warm glow of happiness inside. He may have only found one golden acorn, but he had discovered something even more precious – the power of kindness and the magic of friendship.', metadata={'source': './sample.txt'}),\n", " Document(page_content='~200~And so, with a twinkle in his eye and a skip in his step, Sammy the squirrel continued his adventures in the enchanted forest, knowing that with a little bit of courage and a lot of love, anything was possible.\\n~220~The end.', metadata={'source': './sample.txt'}),\n", " Document(page_content='~40~One sunny morning, as Sammy scampered through the trees, he stumbled upon a mysterious path he had never seen before. Intrigued, he decided to follow it. The path led him deeper and deeper into the forest until he reached a clearing filled with colorful flowers and fluttering butterflies.', metadata={'source': './sample.txt'}),\n", " Document(page_content='~80~Excitedly, Sammy climbed up the tree and plucked a golden acorn from a branch. Suddenly, he heard a tiny voice coming from the acorn. \"Hello there, young squirrel! I am Aurora, the guardian of the Golden Acorn Tree,\" said the voice.\\n~100~Sammy looked around in amazement until he spotted a tiny fairy perched on the golden acorn. \"Wow, you\\'re a fairy!\" exclaimed Sammy, his eyes shining with delight.', metadata={'source': './sample.txt'})],\n", " 'generated_question': 'What is the moral of the story?'}" ] }, "execution_count": 21, "metadata": {}, "output_type": "execute_result" } ], "source": [ "result" ] }, { "cell_type": "code", "execution_count": 22, "metadata": {}, "outputs": [ { "data": { "text/plain": [ "'The moral of the story is that kindness, friendship, courage, and love can lead to magical adventures and wonderful experiences.'" ] }, "execution_count": 22, "metadata": {}, "output_type": "execute_result" } ], "source": [ "answer = result['answer']\n", "answer" ] }, { "cell_type": "code", "execution_count": 23, "metadata": {}, "outputs": [], "source": [ "chat_history.extend([(query,result['answer'])])\n", "chat_history = buffer(chat_history,3)" ] }, { "cell_type": "code", "execution_count": 24, "metadata": {}, "outputs": [], "source": [ "query = \"Can you give a relevant title to the story?\"\n", "result = qa({\"question\": query, \"chat_history\": chat_history}) #######################################" ] }, { "cell_type": "code", "execution_count": 25, "metadata": {}, "outputs": [ { "data": { "text/plain": [ "{'question': 'Can you give a relevant title to the story?',\n", " 'chat_history': [('Namaste! I need your help',\n", " \"Namaste! I'm here to help. What do you need assistance with?\"),\n", " ('What is the moral of the story?',\n", " 'The moral of the story is that kindness, friendship, courage, and love can lead to magical adventures and wonderful experiences.')],\n", " 'answer': 'A relevant title for the story could be \"Sammy\\'s Enchanted Forest Adventure.\"',\n", " 'source_documents': [Document(page_content='~40~One sunny morning, as Sammy scampered through the trees, he stumbled upon a mysterious path he had never seen before. Intrigued, he decided to follow it. The path led him deeper and deeper into the forest until he reached a clearing filled with colorful flowers and fluttering butterflies.', metadata={'source': './sample.txt'}),\n", " Document(page_content='~160~Aurora nodded and waved her magic wand, casting a spell that spread throughout the forest. From that day on, the animals frolicked and played in harmony, their hearts filled with joy and gratitude.\\n~180~As Sammy climbed down from the Golden Acorn Tree, he felt a warm glow of happiness inside. He may have only found one golden acorn, but he had discovered something even more precious – the power of kindness and the magic of friendship.', metadata={'source': './sample.txt'}),\n", " Document(page_content='~200~And so, with a twinkle in his eye and a skip in his step, Sammy the squirrel continued his adventures in the enchanted forest, knowing that with a little bit of courage and a lot of love, anything was possible.\\n~220~The end.', metadata={'source': './sample.txt'}),\n", " Document(page_content='~10~Once upon a time in the lush green forest,\\n~13~there lived a curious little squirrel named Sammy.\\n~25~Sammy had soft, brown fur and big, bright eyes that sparkled with excitement. He loved exploring every nook and cranny of the forest, searching for new adventures.', metadata={'source': './sample.txt'})],\n", " 'generated_question': 'What is a relevant title for the story?'}" ] }, "execution_count": 25, "metadata": {}, "output_type": "execute_result" } ], "source": [ "result" ] }, { "cell_type": "code", "execution_count": 26, "metadata": {}, "outputs": [ { "data": { "text/plain": [ "'A relevant title for the story could be \"Sammy\\'s Enchanted Forest Adventure.\"'" ] }, "execution_count": 26, "metadata": {}, "output_type": "execute_result" } ], "source": [ "answer = result['answer']\n", "answer" ] }, { "cell_type": "code", "execution_count": 27, "metadata": {}, "outputs": [], "source": [ "chat_history.extend([(query,result['answer'])])\n", "chat_history = buffer(chat_history,3)" ] }, { "cell_type": "code", "execution_count": 28, "metadata": {}, "outputs": [], "source": [ "query = \"which timestamp resembles moral of the story?\"\n", "result = qa({\"question\": query, \"chat_history\": chat_history}) #######################################" ] }, { "cell_type": "code", "execution_count": 29, "metadata": {}, "outputs": [ { "data": { "text/plain": [ "'The timestamp ~180~ where Sammy discovers the power of kindness and the magic of friendship best represents the moral of the story.'" ] }, "execution_count": 29, "metadata": {}, "output_type": "execute_result" } ], "source": [ "answer = result['answer']\n", "answer" ] }, { "cell_type": "code", "execution_count": 30, "metadata": {}, "outputs": [ { "name": "stdout", "output_type": "stream", "text": [ "True\n" ] } ], "source": [ "chat_history.extend([(query,result['answer'])])\n", "chat_history = buffer(chat_history,3)" ] }, { "cell_type": "code", "execution_count": 31, "metadata": {}, "outputs": [ { "data": { "text/plain": [ "[('What is the moral of the story?',\n", " 'The moral of the story is that kindness, friendship, courage, and love can lead to magical adventures and wonderful experiences.'),\n", " ('Can you give a relevant title to the story?',\n", " 'A relevant title for the story could be \"Sammy\\'s Enchanted Forest Adventure.\"'),\n", " ('which timestamp resembles moral of the story?',\n", " 'The timestamp ~180~ where Sammy discovers the power of kindness and the magic of friendship best represents the moral of the story.')]" ] }, "execution_count": 31, "metadata": {}, "output_type": "execute_result" } ], "source": [ "chat_history" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "---" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "**The Defalut Buffer Memory that store entire chat and provides it as context to the next conversation** ⬆" ] }, { "cell_type": "markdown", "metadata": {}, "source": [] }, { "cell_type": "markdown", "metadata": {}, "source": [] }, { "cell_type": "markdown", "metadata": {}, "source": [ "- Memory : Conv Buffer Window Memory (k=6) / Conv Summ Buff Memory (max_token_limit=650)\n", "- Chain Type : Refine\n", "- Prompt : Template Fine-Tuning\n", "- Deployment : Gunicorn / Streamlit ? " ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "References: \n", "https://python.langchain.com/docs/use_cases/question_answering/" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "https://python.langchain.com/docs/modules/memory/types/token_buffer" ] }, { "cell_type": "code", "execution_count": 15, "metadata": {}, "outputs": [ { "data": { "text/plain": [ "'~40~One sunny morning, as Sammy scampered through the trees, he stumbled upon a mysterious path he had never seen before. Intrigued, he decided to follow it. The path led him deeper and deeper into the forest until he reached a clearing filled with colorful flowers and fluttering butterflies.'" ] }, "execution_count": 15, "metadata": {}, "output_type": "execute_result" } ], "source": [ "dict(result['source_documents'][1])['page_content']" ] }, { "cell_type": "code", "execution_count": 34, "metadata": {}, "outputs": [], "source": [ "import re\n", "pattern = r'~(\\d+)~'" ] }, { "cell_type": "code", "execution_count": 38, "metadata": {}, "outputs": [], "source": [ "backlinked_docs = [result['source_documents'][i].page_content for i in range(len(result['source_documents']))]\n", "timestamps = list(map(lambda s: int(re.search(pattern, s).group(1)) if re.search(pattern, s) else None, backlinked_docs))\n" ] }, { "cell_type": "code", "execution_count": 39, "metadata": {}, "outputs": [ { "data": { "text/plain": [ "{'timestamps': [160, 40, 120, 10],\n", " 'answer': \"Namaste! I'm here to help. What do you need assistance with?\"}" ] }, "execution_count": 39, "metadata": {}, "output_type": "execute_result" } ], "source": [ "dict(timestamps=timestamps, answer=result['answer'])" ] } ], "metadata": { "kernelspec": { "display_name": "vchad", "language": "python", "name": "python3" }, "language_info": { "codemirror_mode": { "name": "ipython", "version": 3 }, "file_extension": ".py", "mimetype": "text/x-python", "name": "python", "nbconvert_exporter": "python", "pygments_lexer": "ipython3", "version": "3.10.13" } }, "nbformat": 4, "nbformat_minor": 2 }