{ "cells": [ { "cell_type": "code", "execution_count": null, "id": "b2ce30f7", "metadata": {}, "outputs": [], "source": [ "from typing import List, TypedDict\n", "\n", "from langchain_core.messages import BaseMessage, HumanMessage, AIMessage\n", "from langchain_core.tools import tool\n", "from langchain_core.runnables import RunnableLambda\n", "\n", "from langchain_ollama.chat_models import ChatOllama\n", "from langchain_qdrant import QdrantVectorStore\n", "from langchain_huggingface import HuggingFaceEmbeddings\n", "from langgraph.graph import StateGraph, END\n", "\n", "from qdrant_client import QdrantClient" ] }, { "cell_type": "code", "execution_count": null, "id": "c908314a", "metadata": {}, "outputs": [], "source": [ "OLLAMA_MODEL = \"mistral:latest\"\n", "COLLECTION_NAME = \"wellness_docs\"\n", "EMBEDDING_MODEL = \"intfloat/e5-large-v2\"\n", "QDRANT_URL = \"localhost\"\n", "QDRANT_PORT = 6333" ] }, { "cell_type": "code", "execution_count": null, "id": "a39b5287", "metadata": {}, "outputs": [ { "name": "stderr", "output_type": "stream", "text": [ "/Users/vishalpatel/Documents/Internship/Auro/chatbot/RAG-backend/.venv/lib/python3.13/site-packages/tqdm/auto.py:21: TqdmWarning: IProgress not found. Please update jupyter and ipywidgets. See https://ipywidgets.readthedocs.io/en/stable/user_install.html\n", " from .autonotebook import tqdm as notebook_tqdm\n" ] } ], "source": [ "llm = ChatOllama(model=OLLAMA_MODEL, temperature=0.1)\n", "\n", "embeddings = HuggingFaceEmbeddings(model_name=EMBEDDING_MODEL)\n", "\n", "try:\n", " client = QdrantClient(url=QDRANT_URL, port=QDRANT_PORT)\n", " vector_store = QdrantVectorStore(\n", " client=client,\n", " collection_name=COLLECTION_NAME,\n", " embedding=embeddings,\n", " )\n", "except Exception as e:\n", " raise RuntimeError(f\"Failed to connect to Qdrant: {e}\")" ] }, { "cell_type": "code", "execution_count": null, "id": "a71feb23", "metadata": {}, "outputs": [], "source": [ "class GraphState(TypedDict):\n", " \"\"\"\n", " Represents the state of a chat session, including input, output, history, memory,\n", " response, tool results, and user role for LangGraph\n", " \"\"\"\n", " input: str\n", " history: List[BaseMessage] #list of past messages\n", " response: str\n", " tool_results: dict\n", "\n", "from pydantic import BaseModel\n", "\n", "class ToolInput(BaseModel):\n", " prompt: str\n", " iteration: int = 1\n", " " ] }, { "cell_type": "code", "execution_count": null, "id": "fa76762f", "metadata": {}, "outputs": [], "source": [ "template = \"\"\"\n", "You are Auro-Chat, a helpful assistant trained on wellness products, blogs, and FAQs.\n", "\n", "IMPORTANT: Always refer to the **actual** prior conversation shown below. Do NOT invent past questions. \n", "In the conversation history, it is in the format of:\n", "- Human: The User's query\n", "- AI: What you responded to the query\n", "\n", "Use this information to know what questions the user asked previously\n", "\n", "Conversation History:\n", "{history}\n", "\n", "Contextual Knowledge:\n", "{agent_scratchpad}\n", "\n", "Question: {input}\n", "Answer:\n", "\n", "Keep your answer concise (maximum 3 sentences)\n", "\"\"\"" ] }, { "cell_type": "code", "execution_count": null, "id": "f6793397", "metadata": {}, "outputs": [], "source": [ "@tool('Retrieve')\n", "def retrieve_tool(query: str) -> List[dict[str, str]]:\n", " \"\"\"\n", " Retrieves relevant content from wellness product knowledge base, including blog posts, product descriptions, and FAQs.\n", " Returns a list of formatted strings with content and sources.\n", " \"\"\"\n", "\n", " docs = vector_store.similarity_search_with_score(query, k=10)\n", " return [\n", " {\"content\": doc.page_content, \"source\": doc.metadata.get(\"source\", \"unknown\"), 'score': score}\n", " for doc, score in docs if score > 0.8]\n", "\n", "\n", "all_tools = [retrieve_tool]\n", "\n", "tool_descriptions = \"\\n\".join(f\"{tool.name}: {tool.description}\" for tool in all_tools)\n", "tool_names = \", \".join(tool.name for tool in all_tools)" ] }, { "cell_type": "code", "execution_count": null, "id": "10097cf0", "metadata": {}, "outputs": [], "source": [ "def retrieve_node(state: GraphState) -> GraphState:\n", " query = state['input']\n", " tool_results = {}\n", "\n", " for tool in all_tools:\n", " try:\n", " tool_results[tool.name] = tool.invoke({'query': query})\n", " except Exception as e:\n", " tool_results[tool.name] = [{'content': f\"Tool {tool.name} failed: {str(e)}\", \"source\": \"system\"}]\n", " \n", " state['tool_results'] = tool_results\n", " return state" ] }, { "cell_type": "code", "execution_count": null, "id": "d0e4bf05", "metadata": {}, "outputs": [], "source": [ "def generate_answer(state: GraphState):\n", " \"\"\"\n", " This function generates an answer to the query using the llm and the context provided.\n", " \"\"\" \n", " query = state['input']\n", " \n", " history = state.get('history', [])\n", " history_text = \"\\n\".join(\n", " f\"Human: {m.content}\" if isinstance(m, HumanMessage) else f\"AI: {m.content}\"\n", " for m in history\n", " )\n", "\n", "\n", " intermediate_steps = state.get('tool_results', {})\n", "\n", " steps_string = \"\\n\".join(\n", " f\"{tool_name} Results:\\n\" + \"\\n\".join(\n", " f\"- {entry['content']}\" +\n", " (f\"\\n [Source]({entry['source']})\" if entry['source'].startswith(\"http\") else \"\")\n", " for entry in results\n", " )\n", " for tool_name, results in intermediate_steps.items() if results\n", " )\n", "\n", "\n", " print(\"STEPS STRING\", steps_string)\n", "\n", " prompt_input = template.format(\n", " input=query,\n", " #tools = tool_descriptions,\n", " #tool_names=tool_names,\n", " agent_scratchpad=steps_string,\n", " history=history_text\n", " )\n", "\n", " llm_response = llm.invoke(prompt_input)\n", "\n", " state['response'] = llm_response.content if hasattr(llm_response, 'content') else str(llm_response)\n", " \n", " state['history'].append(HumanMessage(content=query))\n", " state['history'].append(AIMessage(content=state['response']))\n", "\n", " return state\n" ] }, { "cell_type": "code", "execution_count": null, "id": "0f6d2e01", "metadata": {}, "outputs": [], "source": [ "graph = StateGraph(GraphState)\n", "\n", "#Add nodes to the graph\n", "graph.add_node(\"route_tool\", RunnableLambda(retrieve_node))\n", "graph.add_node(\"generate_response\", RunnableLambda(generate_answer))\n", "\n", "# Define the flow of the graph\n", "graph.set_entry_point(\"route_tool\")\n", "graph.add_edge(\"route_tool\", \"generate_response\")\n", "graph.add_edge(\"generate_response\", END)\n", "\n", "app = graph.compile()" ] }, { "cell_type": "code", "execution_count": null, "id": "b4748986", "metadata": {}, "outputs": [ { "name": "stdout", "output_type": "stream", "text": [ "\n", "{'Retrieve': [{'content': 'To learn more about the amazing properties of GSH, check out Auro founder Dr. Nayan Patel’s comprehensive guide Glutathione Revolution. Or learn more about Skincare for Acne and Antiaging or Glutathione Skincare.', 'source': '../data/blogs/blog_best-anti-aging-skincare-products-after-30.txt', 'score': 0.8876017}, {'content': 'The Auro GSH™ Antioxidant Delivery System is a patented, first-of-its-kind technology that delivers on the Glutathione Glow! The topical Glutathione optimizes antioxidant absorption with breakthrough transdermal uptake.\\xa0 It helps fight the radicals that the skin encounters to improve the look of fine lines, wrinkles, discoloration, dullness, dehydration, uneven tone, and texture.', 'source': '../data/blogs/blog_glutathione-ingredient-in-skincare-routine.txt', 'score': 0.88709044}, {'content': 'Auro Skincare offers ground-breaking sub-nanotechnology\\xa0that delivers GSH into the skin with a high rate of absorbability so that you know you’re getting the most from your investment.', 'source': '../data/blogs/blog_glutathione-cosmetics.txt', 'score': 0.88106173}, {'content': 'Auro’s Dr. Nayan Patel’s decades of research have led to developing the Auro GSH™ Antioxidant Delivery System. This patented, first-of-its-kind technology optimizes antioxidant absorption and efficacy as the delivery system infuses the skin with powerful ingredients in a cutting-edge way:\\xa0 sub-nano technology –\\xa0 so they can reach the inner layers of the skin for better absorption and brighter, glowing, younger-looking skin.', 'source': '../data/blogs/blog_resveratrol-glutathione-and-cycloastragenol-for-skincare.txt', 'score': 0.87564826}, {'content': 'Dr. Nayan Patel of Auro Wellness has been studying Glutathione for over two decades and has documented the effects of supplementation on overall health and vibrancy. Glutathione is hard to supplement due to the large size of the particle. IV and oral supplementation are unproven with a short window of efficacy, if at all. This led Dr. Patel to develop The Auro GSH™ Antioxidant Delivery System, which uses first-of-its-kind patented technology to optimize antioxidant absorption and effectiveness. The', 'source': '../data/blogs/blog_can-glutathione-guard-nerves-to-avoid-peripheral-neuropathy.txt', 'score': 0.87555146}, {'content': 'Dr. Nayan Patel of Auro Wellness, has dedicated over two decades to Glutathione research, observing its profound impact on the health and vitality of his clients. His commitment to enhancing Glutathione delivery mechanisms has established him as a global authority, culminating with the creation of the innovative Auro GSH™ Antioxidant Delivery System. This first-of-its-kind patented technology topically delivers this powerful antioxidant faster and with the highest efficacy, with just four sprays twice a', 'source': '../data/blogs/blog_cellular-vitality.txt', 'score': 0.87539625}, {'content': 'doses of Glutathione, or other antioxidants, to the skin in an absorbable way for maximum benefits. Auro GSH™is a patented solution to this challenge.\\xa0 Powered by sub-nano technology, it delivers antioxidants like Glutathione to the skin more potently than ever before.', 'source': '../data/blogs/blog_customer-spotlight-melody-guy.txt', 'score': 0.8745222}, {'content': 'GSH is particularly helpful in creating the best possible base for your cosmetic adventures. The Auro Skincare line has special formulations for the beginning and end of your day. Auro WAKE[Auro WAKE product page] first primes and protects the skin. Then Auro REST unlocks skin’s regenerative properties while you sleep. Both include the highest quality ingredients like Vitamins C and E and CoQ10 enzyme.', 'source': '../data/blogs/blog_glutathione-cosmetics.txt', 'score': 0.87449044}, {'content': 'As we age, we lose some of our ability to synthesize GSH. Exposure to toxins and other environmental hazards can also decimate our supply. That’s why Auro’s patented Skincare Protocol combines GSH along with trusted wrinkle-fighting ingredients like Vitamins C and E, using sub-nanotechnology to deliver a highly absorbable form of GSH right where you need it most!\\nTo learn more about the amazing benefits of glutathione, read “Glutathione Benefits for Skin”.', 'source': '../data/blogs/blog_natural-alternatives-to-botox.txt', 'score': 0.87365913}, {'content': 'If you prefer a limited ingredient glutathione supplement, check out the Auro GSH, which is intended for spot treatment and problem areas.\\xa0\\nGlutathione is finally being recognized for the amazing resource it is. Add these highly effective products to your cosmetics routine and watch your skin transform!', 'source': '../data/blogs/blog_glutathione-cosmetics.txt', 'score': 0.8731034}]}\n", " The Auro GSH™ Antioxidant Delivery System is a patented technology that delivers Glutathione, an antioxidant, to the skin for improved absorption and brighter, glowing, younger-looking skin. It uses sub-nano technology for high rates of absorbability. This innovation was developed by Dr. Nayan Patel of Auro Wellness.\n" ] } ], "source": [ "def run_query(input_data: dict) -> dict:\n", " return app.invoke(input_data)\n", "\n", "result = run_query({\n", " 'input': \"What is Auro GSH\",\n", " \"history\": []\n", "})\n", "\n", "print(result['tool_results'])\n", "print(result['response'])" ] }, { "cell_type": "code", "execution_count": null, "id": "b59db291", "metadata": {}, "outputs": [ { "name": "stdout", "output_type": "stream", "text": [ "Human: What is Auro GSH\n", "AI: The Auro GSH™ Antioxidant Delivery System is a patented technology that delivers Glutathione, an antioxidant, to the skin for improved absorption and brighter, glowing, younger-looking skin. It uses sub-nano technology for high rates of absorbability. This innovation was developed by Dr. Nayan Patel of Auro Wellness.\n", "{'Retrieve': [{'content': '“[Vitamin C is] a nutrient your body needs to form blood vessels, cartilage, muscle and collagen in bones. Vitamin C is also vital to your body’s healing process.”\\nAs an antioxidant, Vitamin C has strong anti-inflammatory properties. Combined with its ability to promote collagen production, this encourages skin cell turnover and reduces wrinkles and hyperpigmentation from UV exposure. Hence the growing demand for Vitamin C in skin products!', 'source': '../data/blogs/blog_glutathione-vitamin-c.txt', 'score': 0.8543478}, {'content': 'Topical Vitamin C can combat free radicals and improve the skin’s overall appearance. It fights free radicals by inhibiting the oxidation of molecules by neutralizing free radicals, thereby stopping them from causing cellular damage.\\xa0\\nApplying Vitamin C topically allows for a concentrated dose to be absorbed directly into the outer layers of the skin.\\xa0 But The Auro GSH™ Antioxidant Delivery System, a patented, first-of-its-kind technology, takes topical to the next level.', 'source': '../data/blogs/blog_the-results-are-in-and-the-pictures-dont-lie-auro-skincares-citrine-vitamin-c-radiance-complex-is-transforming-skin.txt', 'score': 0.85041165}, {'content': 'Auro has taken the power of Vitamin C and optimized its absorption and efficacy by transporting it to the skin with The Auro GSH™ Antioxidant Delivery System, a patented, first-of-its-kind technology. It has an unprecedented 25% concentration of Ascorbic Acid Vitamin C to help dramatically brighten the look of skin and defend against environmental stress.\\nThe power of Vitamin C and the skin:', 'source': '../data/blogs/blog_the-results-are-in-and-the-pictures-dont-lie-auro-skincares-citrine-vitamin-c-radiance-complex-is-transforming-skin.txt', 'score': 0.8464519}, {'content': 'Vitamin A can be a potent method of stimulating collagen growth and cell turnover. You will often see it in the form of retinol or retinoids. Retinol is a gentler version while retinoids often require a prescription.\\nNot just for colds, vitamin C also promotes collagen as well as brightening overall skin tone. This makes it particularly effective in treating hyperpigmentation and scarring.', 'source': '../data/blogs/blog_natural-antiaging-skincare.txt', 'score': 0.8422341}, {'content': 'Glutathione and Vitamin C: A Powerful Duo for Skincare\\nJust like glutathione (GSH), Vitamin C is an important nutrient for overall wellness. And also like glutathione, Vitamin C is becoming a staple in the skin care world. In fact, these antioxidants work together to protect the body and keep skin looking radiant!\\nHow the Body Uses Vitamin C\\nWhile most people recognize it as an ally for the immune system, preventing colds is only part of Vitamin C’s important work. As the Mayo Clinic puts it:', 'source': '../data/blogs/blog_glutathione-vitamin-c.txt', 'score': 0.84125614}, {'content': 'Our bodies can’t make Vitamin C on their own, so we absorb it from foods like red and green peppers, broccoli, brussels sprouts, strawberries, grapefruit, papaya, oranges, cantaloupe, and tangerine. Once processed, Vitamin C goes to work building tissues, disarming harmful free radicals, and boosting skin performance and appearance.\\xa0\\nHow Vitamin C Works with Glutathione', 'source': '../data/blogs/blog_glutathione-vitamin-c.txt', 'score': 0.83361804}, {'content': 'Adding a serum or spot treatment after cleansing and before moisturizing can be a great way to target problem areas or add flexibility to your routine. Discoloration from healed acne or sun exposure, for example, can be treated with brightening serums that use Vitamin C or niacinamide.\\nThere’s a wide variety of moisturizer options but you should have at least a lighter formula for the day and a nourishing, restorative version for nighttime. Other ingredients to consider include:', 'source': '../data/blogs/blog_skincare-for-acne-and-antiaging.txt', 'score': 0.8325646}, {'content': 'Only one company, Auro Skincare, offers skincare with glutathione and Vitamin C sub-nanotechnology delivery. Auro’s patented skincare protocol formulas safely and efficiently increase GSH and Vitamin C levels to fight signs of aging, improve skin health, and activate the body’s innate healing abilities.\\nGot any questions? Reach out to us\\xa0any time!', 'source': '../data/blogs/blog_glutathione-vitamin-c.txt', 'score': 0.83217305}, {'content': 'The power of Vitamin C and the skin:\\nOur skin is bombarded daily by free radicals – the biggest offenders are external forces like sun, pollution, and smoke, as well as stressors we put on our bodies – like stress, alcohol, bad diet, and more. These ALL affect our skin. When we tax ourselves with these free radicals, our skin has an inflammatory response and gets damaged. This leads to wrinkles, dark spots, uneven skin tone, and more.', 'source': '../data/blogs/blog_the-results-are-in-and-the-pictures-dont-lie-auro-skincares-citrine-vitamin-c-radiance-complex-is-transforming-skin.txt', 'score': 0.83104885}, {'content': 'It delivers antioxidants Glutathione, Vitamin C, and more to the skin more potently than ever before, in a highly absorbable way for maximum benefits. The sub-nano technology means that the powerful Vitamin C antioxidant can reach the inner layers of the skin, making it much more efficient.\\xa0\\nIn addition to the effective delivery of brightening and collagen-supporting Vitamin C,\\xa0 Citrine Vitamin C Radiance Complex also contains:', 'source': '../data/blogs/blog_the-results-are-in-and-the-pictures-dont-lie-auro-skincares-citrine-vitamin-c-radiance-complex-is-transforming-skin.txt', 'score': 0.8301624}]}\n", " The Auro Vitamin C Serum is a potent antioxidant solution that uses sub-nano technology for enhanced absorption. It contains an unprecedented 25% concentration of Ascorbic Acid Vitamin C to brighten skin and defend against environmental stressors. This serum is part of Auro Skincare's patented skincare protocol, which increases GSH and Vitamin C levels to fight signs of aging and improve overall skin health.\n" ] } ], "source": [ "result = run_query({\n", " 'input': \"Can you tell me about the Vitamin C Serum\",\n", " 'history': result['history']\n", "})\n", "\n", "print(result['tool_results'])\n", "print(result['response'])" ] }, { "cell_type": "code", "execution_count": null, "id": "3aac35cb", "metadata": {}, "outputs": [ { "name": "stdout", "output_type": "stream", "text": [ "Human: What is Auro GSH\n", "AI: The Auro GSH™ Antioxidant Delivery System is a patented technology that delivers Glutathione, an antioxidant, to the skin for improved absorption and brighter, glowing, younger-looking skin. It uses sub-nano technology for high rates of absorbability. This innovation was developed by Dr. Nayan Patel of Auro Wellness.\n", "Human: Can you tell me about the Vitamin C Serum\n", "AI: The Auro Vitamin C Serum is a potent antioxidant solution that uses sub-nano technology for enhanced absorption. It contains an unprecedented 25% concentration of Ascorbic Acid Vitamin C to brighten skin and defend against environmental stressors. This serum is part of Auro Skincare's patented skincare protocol, which increases GSH and Vitamin C levels to fight signs of aging and improve overall skin health.\n", "{'Retrieve': [{'content': 'Talk to your doctor if you have:\\nResources:', 'source': '../data/blogs/blog_acid-and-enzymes-for-indigestion.txt', 'score': 0.8052714}]}\n", " You asked about Auro GSH and its function, as well as the Auro Vitamin C Serum and its properties.\n" ] } ], "source": [ "result = run_query({\n", " 'input': \"What were the last 2 questions I asked about?\",\n", " 'history': result['history']\n", "})\n", "\n", "print(result['tool_results'])\n", "print(result['response'])" ] } ], "metadata": { "kernelspec": { "display_name": ".venv", "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.11.9" } }, "nbformat": 4, "nbformat_minor": 5 }