Spaces:
Build error
Build error
File size: 9,878 Bytes
dbeb6e8 eb99659 dbeb6e8 eb99659 dbeb6e8 eb99659 dbeb6e8 eb99659 dbeb6e8 | 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 | {
"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
}
|