USER
Help me build an AI powered Ayurvedic assistant App called Ayurfix.
The App is a conversational AI bot with Agentic workflows and RAG architecture.
This App has 2 agents, a triage agent and a diagnostic agent.
The triage agent greets the user, conducts an in depth interview and creates a detailed report to reflect the patient’s current situation.
This report is then sent off to the diagnostic agent which then uses this to provide diagnosis to the user.
Both the agents use ayurvedic knowledge base which is a vector database filled with Ayurvedic knowledge in order to provide accurate results.
For example, the traige agent uses the knowledge base to come up with the most relevent and accurate questions to ask the user based on the chat context.
In the same way, the diagnostic agent uses the knowledge base to provide accurate diagnosis based off the report.
We shall use the following tech stack ::
1. LlamaIndex
2. Qdrant vector database
3. GoogleGenerativeAI with Google Gemini API for both embeddings and as the LLM.
For prototyping, we will build this in a Google Colab notebook.
I have already populated the vector database with ayurvedic knowledge, all we have to do is build the App and connect it to Qdrant.
Here is the sample reference code ::
from llama_index import VectorStoreIndex, ServiceContext
from llama_index.vector_stores import QdrantVectorStore
from llama_index.storage.storage_context import StorageContext
from llama_index.memory import ChatMemoryBuffer
from llama_index.chat_engine import ContextChatEngine
from qdrant_client import QdrantClient
from llama_index.embeddings import GeminiEmbedding
# Set up Gemini
llm = Gemini(model_name="gemini-pro")
embed_model = GeminiEmbedding(model_name="models/embedding-001")
# Qdrant setup
QDRANT_URL = "https://your-qdrant-cluster-url.qdrant.tech"
QDRANT_API_KEY = "your_qdrant_api_key_here"
qdrant_client = QdrantClient(url=QDRANT_URL, api_key=QDRANT_API_KEY)
vector_store = QdrantVectorStore(
client=qdrant_client,
collection_name="your_collection",
relevance_score_fn="cosine"
)
# Create ServiceContext and StorageContext
service_context = ServiceContext.from_defaults(llm=llm, embed_model=embed_model)
storage_context = StorageContext.from_defaults(vector_store=vector_store)
# Create index
index = VectorStoreIndex.from_vector_store(
vector_store,
service_context=service_context
)
# Set up memory
memory = ChatMemoryBuffer.from_defaults(token_limit=1500)
# Create chat engine with memory
chat_engine = ContextChatEngine.from_defaults(
index=index,
service_context=service_context,
memory=memory,
system_prompt="You are a helpful AI assistant. Use the given context to answer questions."
)
# Chat loop
while True:
user_input = input("User: ")
if user_input.lower() in ["exit", "quit", "q"]:
break
response = chat_engine.chat(user_input)
print(f"Assistant: {response}")
Here are the dependencies ::
!pip install llama-index llama-index-llms-google google-generativeai llama-index-vector-stores-qdrant qdrant-clientASSISTANT
Building **Ayurfix**, an AI-powered Ayurvedic assistant App, is an exciting project that combines conversational AI with Ayurvedic principles to provide personalized health insights. Below, I'll guide you through the process of setting up Ayurfix using the specified tech stack, structuring the two-agent system (Triage and Diagnostic), and ensuring seamless interaction between them using Agentic workflows and Retrieval-Augmented Generation (RAG) architecture.
## Table of Contents
1. [Architecture Overview](#architecture-overview)
2. [Environment Setup](#environment-setup)
3. [Connecting to Qdrant Vector Database](#connecting-to-qdrant-vector-database)
4. [Implementing the Triage Agent](#implementing-the-triage-agent)
5. [Implementing the Diagnostic Agent](#implementing-the-diagnostic-agent)
6. [Workflow Management](#workflow-management)
7. [Sample Interaction](#sample-interaction)
8. [Next Steps and Deployment](#next-steps-and-deployment)
---
## Architecture Overview

*Note: Replace the image link with an actual architecture diagram if available.*
**Components:**
1. **User Interface:** Interface through which users interact with Ayurfix (e.g., chat interface in a web app or Colab notebook).
2. **Triage Agent:** Conducts an in-depth interview with the user to gather relevant health information.
3. **Diagnostic Agent:** Analyzes the report generated by the Triage Agent to provide a diagnosis based on Ayurvedic principles.
4. **Ayurvedic Knowledge Base:** A vector database (Qdrant) containing Ayurvedic knowledge, used by both agents for accurate responses.
5. **RAG Architecture:** Combines retrieval (from the knowledge base) and generation (using LLM) to provide contextually relevant answers.
---
## Environment Setup
First, ensure that all necessary dependencies are installed in your Google Colab environment.
```python
# Install dependencies
!pip install llama-index
!pip install llama-index-llms-google
!pip install google-generativeai
!pip install llama-index-vector-stores-qdrant
!pip install qdrant-client
```
**Import Necessary Libraries:**
```python
from llama_index import VectorStoreIndex, ServiceContext
from llama_index.vector_stores import QdrantVectorStore
from llama_index.storage.storage_context import StorageContext
from llama_index.memory import ChatMemoryBuffer
from llama_index.chat_engine import ContextChatEngine
from qdrant_client import QdrantClient
from llama_index.embeddings import GeminiEmbedding
from google.generativeai import Gemini # Ensure proper import based on actual library
```
---
## Connecting to Qdrant Vector Database
Assuming you've already populated your Qdrant vector database with Ayurvedic knowledge, we'll connect to this database to enable both agents to retrieve relevant information.
```python
# Initialize Gemini LLM and Embedding Model
llm = Gemini(model_name="gemini-pro")
embed_model = GeminiEmbedding(model_name="models/embedding-001")
# Qdrant configuration
QDRANT_URL = "https://your-qdrant-cluster-url.qdrant.tech"
QDRANT_API_KEY = "your_qdrant_api_key_here"
COLLECTION_NAME = "ayurvedic_knowledge"
# Initialize Qdrant Client
qdrant_client = QdrantClient(url=QDRANT_URL, api_key=QDRANT_API_KEY)
# Initialize Qdrant Vector Store
vector_store = QdrantVectorStore(
client=qdrant_client,
collection_name=COLLECTION_NAME,
relevance_score_fn="cosine"
)
# Create ServiceContext and StorageContext
service_context = ServiceContext.from_defaults(llm=llm, embed_model=embed_model)
storage_context = StorageContext.from_defaults(vector_store=vector_store)
# Create VectorStoreIndex
index = VectorStoreIndex.from_vector_store(
vector_store,
service_context=service_context
)
```
---
## Implementing the Triage Agent
The Triage Agent is responsible for:
1. Greeting the user.
2. Conducting an in-depth interview.
3. Generating a detailed report of the patient's current situation.
We'll design the Triage Agent to use the Ayurvedic knowledge base to ask relevant questions based on the user's responses.
```python
class TriageAgent:
def __init__(self, index, service_context):
self.chat_engine = ContextChatEngine.from_defaults(
index=index,
service_context=service_context,
memory=ChatMemoryBuffer.from_defaults(token_limit=1500),
system_prompt="You are an Ayurvedic Triage Assistant. Greet the user and ask relevant questions to assess their health."
)
self.report = {}
def conduct_interview(self):
print("Triage Agent: Welcome to Ayurfix! I'm here to assist you with your Ayurvedic health assessment.")
while True:
user_input = input("User: ")
if user_input.lower() in ["done", "finish", "quit", "q"]:
break
response = self.chat_engine.chat(user_input)
print(f"Triage Agent: {response}")
# Here, you can implement parsing of user_input and responses to build the report
# For simplicity, let's assume the Triage Agent summarizes the information
self.report[user_input] = response
return self.report
# Initialize Triage Agent
triage_agent = TriageAgent(index=index, service_context=service_context)
# Conduct Interview
triage_report = triage_agent.conduct_interview()
print("\nTriage Report:")
print(triage_report)
```
**Notes:**
- The Triage Agent uses `ContextChatEngine` to maintain the context of the conversation.
- User inputs are processed until the user decides to finish the interview by typing commands like "done" or "quit".
- The `report` dictionary stores the user's responses, which can be structured more formally as needed.
---
## Implementing the Diagnostic Agent
The Diagnostic Agent analyzes the report generated by the Triage Agent and provides a diagnosis based on Ayurvedic principles.
```python
class DiagnosticAgent:
def __init__(self, index, service_context):
self.chat_engine = ContextChatEngine.from_defaults(
index=index,
service_context=service_context,
memory=ChatMemoryBuffer.from_defaults(token_limit=1500),
system_prompt="You are an Ayurvedic Diagnostic Assistant. Analyze the following patient report and provide a diagnosis based on Ayurvedic principles."
)
def diagnose(self, report):
# Convert the report dictionary into a formatted string
formatted_report = "\n".join([f"{key}: {value}" for key, value in report.items()])
prompt = f"Patient Report:\n{formatted_report}\n\nPlease provide a detailed Ayurvedic diagnosis."
response = self.chat_engine.chat(prompt)
return response
# Initialize Diagnostic Agent
diagnostic_agent = DiagnosticAgent(index=index, service_context=service_context)
# Get Diagnosis
diagnosis = diagnostic_agent.diagnose(triage_report)
print("\nDiagnostic Report:")
print(diagnosis)
```
**Notes:**
- The Diagnostic Agent takes the `triage_report` as input.
- It formats the report into a string that can be easily interpreted by the LLM.
- The agent then generates a diagnosis based on the Ayurvedic knowledge base.
---
## Workflow Management
To ensure smooth interaction between the Triage and Diagnostic agents, we'll manage the workflow within the Colab notebook. Here's how the complete flow works:
1. **User interacts with the Triage Agent:** Provides initial health information.
2. **Triage Agent generates a report:** Summarizes the user's inputs.
3. **Diagnostic Agent analyzes the report:** Provides a diagnosis based on Ayurveda.
Let's encapsulate this workflow into a single function for ease of use.
```python
def Ayurfix_workflow():
# Initialize Agents
triage_agent = TriageAgent(index=index, service_context=service_context)
diagnostic_agent = DiagnosticAgent(index=index, service_context=service_context)
# Conduct Triage
print("=== Ayurfix Triage ===")
triage_report = triage_agent.conduct_interview()
# Display Triage Report
print("\n=== Triage Report ===")
for key, value in triage_report.items():
print(f"{key}: {value}")
# Diagnose
print("\n=== Diagnostic Report ===")
diagnosis = diagnostic_agent.diagnose(triage_report)
print(diagnosis)
```
**Run the Workflow:**
```python
Ayurfix_workflow()
```
**User Interaction Flow:**
```
=== Ayurfix Triage ===
Triage Agent: Welcome to Ayurfix! I'm here to assist you with your Ayurvedic health assessment.
User: I have been experiencing headaches and fatigue lately.
Triage Agent: I'm sorry to hear that. Can you tell me more about the nature of your headaches? For example, when do they occur and how intense are they?
User: They usually occur in the late afternoon and are quite intense.
...
User: done
=== Triage Report ===
I have been experiencing headaches and fatigue lately.: I'm sorry to hear that. Can you tell me more about the nature of your headaches? For example, when do they occur and how intense are they?
...
=== Diagnostic Report ===
[Diagnostic response based on Ayurvedic principles]
```
---
## Sample Interaction
Let's walk through a sample interaction to illustrate how Ayurfix operates.
```
=== Ayurfix Triage ===
Triage Agent: Welcome to Ayurfix! I'm here to assist you with your Ayurvedic health assessment.
User: I have been feeling very tired and have frequent indigestion.
Triage Agent: I'm sorry to hear that. Can you describe when you started feeling this way and any other symptoms you've noticed?
User: It started about two weeks ago, and I've also been experiencing bloating after meals.
Triage Agent: Thank you for the information. Have there been any changes in your diet or lifestyle recently?
User: Yes, I've been eating more spicy foods and working longer hours.
Triage Agent: Understood. Spicy foods and increased stress can affect your digestive system. Have you noticed any changes in your sleep patterns?
User: I've been having trouble sleeping and often wake up feeling restless.
User: done
=== Triage Report ===
I have been feeling very tired and have frequent indigestion.: I'm sorry to hear that. Can you describe when you started feeling this way and any other symptoms you've noticed?
It started about two weeks ago, and I've also been experiencing bloating after meals.: Thank you for the information. Have there been any changes in your diet or lifestyle recently?
Yes, I've been eating more spicy foods and working longer hours.: Understood. Spicy foods and increased stress can affect your digestive system. Have you noticed any changes in your sleep patterns?
I've been having trouble sleeping and often wake up feeling restless.:
=== Diagnostic Report ===
Based on the provided information, it appears that you might be experiencing an imbalance in your Vata dosha, which governs movement and can be affected by stress and dietary changes. The increase in spicy foods and hectic lifestyle may have aggravated your digestive system (Agni), leading to indigestion and bloating. Additionally, disrupted sleep patterns further indicate Vata imbalance. It's recommended to follow a Vata-pacifying diet, incorporate relaxation techniques such as yoga or meditation, and establish a regular sleep routine to restore balance.
```
---
## Next Steps and Deployment
### 1. Enhancing the Agents
- **Report Structuring:** Instead of a simple dictionary, structure the report using predefined categories (e.g., symptoms, duration, dietary habits).
- **Validation:** Implement validation to ensure that the user provides all necessary information before proceeding to diagnosis.
- **Error Handling:** Handle unexpected inputs gracefully to maintain a smooth user experience.
### 2. Developing a User Interface
While prototyping in Google Colab is effective, developing a user-friendly interface will make Ayurfix more accessible.
- **Web Application:** Use frameworks like **Streamlit**, **Flask**, or **Django** to build a web-based interface.
- **Mobile Application:** Consider using **React Native** or **Flutter** for cross-platform mobile apps.
- **Chat Interface:** Integrate with messaging platforms like **Telegram**, **WhatsApp**, or **Facebook Messenger**.
### 3. Securing the Application
- **API Keys:** Ensure that sensitive information like Qdrant API keys and Gemini credentials are securely stored, possibly using environment variables or secure storage services.
- **Data Privacy:** Implement proper data handling practices to protect user data, complying with regulations like GDPR.
### 4. Scaling and Optimization
- **Performance Tuning:** Optimize responses for speed and accuracy by refining prompts and leveraging efficient vector search techniques.
- **Monitoring:** Set up monitoring to track usage, performance, and potential issues.
- **Continuous Learning:** Update the Ayurvedic knowledge base regularly to incorporate the latest research and insights.
### 5. Deployment
- **Cloud Deployment:** Deploy Ayurfix on cloud platforms like **Google Cloud Platform**, **AWS**, or **Azure** for scalability and reliability.
- **Containerization:** Use **Docker** to containerize the application, ensuring consistency across environments.
- **CI/CD Pipelines:** Implement Continuous Integration and Continuous Deployment pipelines for streamlined updates and maintenance.
---
## Conclusion
Building **Ayurfix** involves integrating advanced AI technologies with traditional Ayurvedic knowledge to provide personalized health assessments. By leveraging LlamaIndex, Qdrant, and Google Gemini, you can create a robust and intelligent assistant that guides users through their health journeys. The outlined steps provide a comprehensive roadmap, from initial setup to deploying a fully functional application. As you progress, consider enhancing the user experience, securing the platform, and scaling the infrastructure to accommodate a growing user base.
Feel free to ask for further assistance or clarifications as you develop Ayurfix!