{ "cells": [ { "cell_type": "markdown", "metadata": {}, "source": [ "# Run the Oura App Assistant" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "Here, we retrieve the most relevant chunks based on the user's query and incorporate into a prompt sent to the LLM for a response." ] }, { "cell_type": "code", "execution_count": null, "metadata": {}, "outputs": [], "source": [ "import ollama\n", "from openai import OpenAI\n", "import chromadb\n", "from sentence_transformers import SentenceTransformer\n", "import os\n", "from dotenv import load_dotenv\n", "\n", "load_dotenv()\n", "\n", "# Use a basic sentence transformer finetuned for text similarity tasks\n", "model = SentenceTransformer(\"sentence-transformers/all-MiniLM-L6-v2\")\n", "\n", "ollama.pull(\"mistral\")\n", "\n", "def embedding_func(text):\n", " return model.encode(text, convert_to_numpy=True) \n", "\n", "# Initialize ChromaDB (runs locally)\n", "chroma_client = chromadb.PersistentClient(path=\"./chroma_db\") \n", "\n", "# Create or load a collection with metadata support\n", "collection = chroma_client.get_or_create_collection(\n", " name=\"oura_chunks\",\n", " metadata={\"hnsw:space\": \"cosine\"} \n", ")\n", "\n", "# Query LLM (Ollama Mistral model)\n", "def query_ollama(query, context):\n", " # Construct prompt with instructions, context, and query\n", " prompt = (\n", " \"You are an expert assistant answering questions about the Oura Ring app.\\n\"\n", " \"Based on the following context, please answer the user's question.\\n\"\n", " \"Only use the provided context for your response. If you cannot find a relevant answer, state that the query is out of scope.\\n\"\n", " \"Cite the most relevant article, section, and link that are directly found in the provided context.\\n\"\n", " \"Do not provide links that are not found in the provided context.\\n\\n\"\n", " f\"{context}\\n\\n\"\n", " f\"User's Question: {query}\"\n", " )\n", " # Submit prompt and get response\n", " response = ollama.chat(model=\"mistral\", messages=[{\"role\": \"user\", \"content\": prompt}])\n", " return response[\"message\"][\"content\"]\n", "\n", "# Query LLM (OpenAI GPT-4 model)\n", "def query_openai(query, context):\n", " client = OpenAI(api_key=os.getenv(\"OPENAI_API_KEY\"))\n", "\n", " # Add instructions to the system message\n", " system_message = {\"role\": \"system\", \n", " \"content\": \"You are an expert assistant answering questions about the Oura Ring app.\\n\"\n", " \"Use only the provided context for your responses.\\n\"\n", " \"If you do not find relevant information, clearly state that the question is out of scope.\\n\"\n", " \"Always cite the most relevant article, section, and link that are directly found in the provided context.\\n\"\n", " \"Do not provide links that are not found in the provided context.\"}\n", " \n", " # Add the user's input\n", " user_message = {\"role\": \"user\", \"content\": query}\n", "\n", " # Submit system message for response\n", " completion = client.chat.completions.create(\n", " model=\"gpt-4\", \n", " messages=[\n", " system_message, \n", " {\"role\": \"assistant\", \"content\": context}, \n", " user_message \n", " ],\n", " )\n", " \n", " # Output the chatbot's response\n", " return completion.choices[0].message.content\n", "\n", "# Query ChromaDB for relevant chunks\n", "def retrieve_relevant_chunks(query, n_results=5):\n", " query_embedding = embedding_func(query).tolist() \n", " results = collection.query(\n", " query_embeddings=[query_embedding], \n", " n_results=n_results\n", " )\n", " return results\n", "\n", "# Perform RAG (Retrieve + Generate) with Ollama/OpenAI\n", "def perform_rag(query, provider=\"ollama\"):\n", " # Retrieve relevant chunks from ChromaDB\n", " results = retrieve_relevant_chunks(query, n_results=5)\n", " \n", " # Combine the retrieved chunks for LLM input\n", " relevant_chunks = []\n", " for document, metadata, distance in zip(results[\"documents\"][0],results[\"metadatas\"][0],results[\"distances\"][0]):\n", " # Apply relatively lenient filter to return most relevant chunks\n", " if distance > 0.75:\n", " continue\n", " # Structure chunks to include all relevant metadata\n", " relevant_chunks.append(f'\\nArticle Title: {metadata[\"article_title\"]}\\nSection Title: {metadata[\"section_title\"]}\\nArticle Link: {metadata[\"link\"]}\\nRelevance Score: {100*round(1 - distance, 2)}\\nArticle Content: {document}\\n')\n", " if len(relevant_chunks) < 1:\n", " context = f'\\nArticle Title: No Relevant Article\\nSection Title: No Relevant Article\\nArticle Link: No Relevant Article\\nRelevance Score: No Relevant Article\\nArticle Content: No Relevant Article\\n'\n", " else:\n", " context = \"\\n\".join(relevant_chunks) \n", "\n", " if provider == \"ollama\":\n", " # Query Ollama Mistral for a response\n", " answer = query_ollama(query, context)\n", " elif provider == \"openai\":\n", " # Query OpenAI gpt-4 for a response\n", " answer = query_openai(query, context)\n", " else:\n", " print(\"Invalid ChatBot provider, please select either ollama or openai!\")\n", " \n", " return answer\n", "\n" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "# Qualitative Evaluation" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "For the qualitative evaluation, I provide each model with three sets of queries: 1) Relevant Queries, 2) Non-Relevant Queries, 3) Troubleshooting Queries, and 4) Subjective Queries. These queries highlight the model's ability to correctly answer questions relevant to the Oura app, identify when the question is out of scope, provide some coaching for troubleshooting and summarize subjective queries about the Oura App. " ] }, { "cell_type": "code", "execution_count": null, "metadata": {}, "outputs": [], "source": [ "\n", "providers = {\"Ollama (Mistral) Evaluation\": \"ollama\", \n", " \"Open AI (GPT-4) Evaluation\": \"openai\"}\n", "query_types = {\"Relevant Queries\": [\n", "\"How can I set the language for the Oura App?\",\n", "\"Does the Oura App provide information about sleep quality?\"],\n", "\"Non-Relevant Queries\": [\"How can I order a hamburger?\",\n", " \"How can I order an Oura ring for my dog?\"],\n", "\"Troubleshooting Queries\": [\"What should I do if my Oura Ring is not syncing with the Oura App?\",\n", " \"What should I do if my Oura Ring is not syncing with Apple Health?\"],\n", "\"Subjective Queries\": [\"Do users generally prefer the Oura App instead of the Apple Health App?\"]}" ] }, { "cell_type": "code", "execution_count": null, "metadata": {}, "outputs": [], "source": [ "\n", "for provider in providers.keys():\n", " print(\"================================================================================\")\n", " print(provider)\n", " for query_type in query_types.keys():\n", " print(f\"********************** {query_type} **********************\")\n", " for idx,question in enumerate(query_types[query_type]):\n", " print(\"------------------------------------------------------------\")\n", " answer = perform_rag(question, providers[provider])\n", " output_string = f\"{idx+1}) Question: {question}\\nAnswer: {answer}\\n\\n\"\n", " print(output_string)\n", "\n" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "# Local Deployment to Gradio" ] }, { "cell_type": "code", "execution_count": null, "metadata": {}, "outputs": [], "source": [ "import gradio as gr\n", "\n", "def ask_oura_assistant(user_input, provider):\n", " if \"ollama\" in provider.lower():\n", " return perform_rag(user_input, \"ollama\")\n", " elif \"openai\" in provider.lower():\n", " return perform_rag(user_input, \"openai\")\n", "\n", "demo = gr.Interface(\n", " fn=ask_oura_assistant, \n", " inputs=[\n", " gr.Textbox(label=\"Ask a question...\"), \n", " gr.Dropdown([\"OpenAI (GPT-4)\", \"Ollama (Mistral)\"], label=\"Select Provider\") \n", " ],\n", " outputs=\"text\", \n", " title=\"Oura Ring App Assistant\",\n", " description=\"Ask me anything about the Oura Ring app! Select your provider before submitting.\")\n", "\n", "demo.launch()" ] }, { "cell_type": "code", "execution_count": null, "metadata": {}, "outputs": [], "source": [] } ], "metadata": { "kernelspec": { "display_name": "ouraDemo", "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.16" } }, "nbformat": 4, "nbformat_minor": 2 }