Vela
commited on
Commit
Β·
f7f0991
1
Parent(s):
bd5a98c
modified frontend
Browse files- src/backend/__pycache__/main.cpython-313.pyc +0 -0
- src/backend/api_routes/__pycache__/chat_history_db_api.cpython-313.pyc +0 -0
- src/backend/api_routes/__pycache__/knowledge_base_api.cpython-313.pyc +0 -0
- src/backend/api_routes/chat_history_db_api.py +2 -3
- src/backend/api_routes/knowledge_base_api.py +12 -5
- src/backend/main.py +5 -5
- src/backend/services/__pycache__/llm_model_service.cpython-313.pyc +0 -0
- src/backend/services/__pycache__/pinecone_service.cpython-313.pyc +0 -0
- src/backend/services/__pycache__/supabase_service.cpython-313.pyc +0 -0
- src/backend/services/llm_model_service.py +26 -14
- src/backend/services/pinecone_service.py +20 -25
- src/backend/services/supabase_service.py +0 -1
- src/frontend/app/__pycache__/common_functions.cpython-313.pyc +0 -0
- src/frontend/app/__pycache__/pinecone_data_handler.cpython-313.pyc +0 -0
- src/frontend/app/common_functions.py +142 -35
- src/frontend/home.py +53 -45
- src/frontend/images/health_care_baner_2.jpg +0 -0
- src/frontend/images/health_care_baner_3.gif +0 -0
- src/frontend/pages/Admin_Portal.py +28 -16
- src/frontend/pages/Knowledge_Base_Explorer.py +14 -12
- src/frontend/pages/__pycache__/Admin_Portal.cpython-313.pyc +0 -0
- src/frontend/pages/__pycache__/Knowledge_Base_Explorer.cpython-313.pyc +0 -0
- src/frontend/pages/chatbot.py +13 -12
src/backend/__pycache__/main.cpython-313.pyc
CHANGED
Binary files a/src/backend/__pycache__/main.cpython-313.pyc and b/src/backend/__pycache__/main.cpython-313.pyc differ
|
|
src/backend/api_routes/__pycache__/chat_history_db_api.cpython-313.pyc
CHANGED
Binary files a/src/backend/api_routes/__pycache__/chat_history_db_api.cpython-313.pyc and b/src/backend/api_routes/__pycache__/chat_history_db_api.cpython-313.pyc differ
|
|
src/backend/api_routes/__pycache__/knowledge_base_api.cpython-313.pyc
CHANGED
Binary files a/src/backend/api_routes/__pycache__/knowledge_base_api.cpython-313.pyc and b/src/backend/api_routes/__pycache__/knowledge_base_api.cpython-313.pyc differ
|
|
src/backend/api_routes/chat_history_db_api.py
CHANGED
@@ -1,4 +1,4 @@
|
|
1 |
-
from fastapi import APIRouter,HTTPException,status
|
2 |
from services.schemas import ChatHistoryRequest
|
3 |
from services import supabase_service
|
4 |
from utils import logger
|
@@ -18,9 +18,9 @@ def store_chat_history(chat_history : ChatHistoryRequest):
|
|
18 |
|
19 |
@router.get('/get-history')
|
20 |
def get_chat_history(conversation_id: str):
|
|
|
21 |
try:
|
22 |
chat_history = supabase_service.get_chat_history(conversation_id)
|
23 |
-
logger.info(f"Chat history retrieved successfully for conversation ID: {conversation_id}")
|
24 |
return chat_history
|
25 |
except Exception as e:
|
26 |
logger.error(f"Error retrieving chat history for ID {conversation_id}: {e}")
|
@@ -29,7 +29,6 @@ def get_chat_history(conversation_id: str):
|
|
29 |
detail="Failed to retrieve chat history. Please try again later."
|
30 |
)
|
31 |
|
32 |
-
|
33 |
|
34 |
|
35 |
|
|
|
1 |
+
from fastapi import APIRouter,HTTPException,status,Query
|
2 |
from services.schemas import ChatHistoryRequest
|
3 |
from services import supabase_service
|
4 |
from utils import logger
|
|
|
18 |
|
19 |
@router.get('/get-history')
|
20 |
def get_chat_history(conversation_id: str):
|
21 |
+
"""Retrieves chat history from Supabase for a given conversation ID."""
|
22 |
try:
|
23 |
chat_history = supabase_service.get_chat_history(conversation_id)
|
|
|
24 |
return chat_history
|
25 |
except Exception as e:
|
26 |
logger.error(f"Error retrieving chat history for ID {conversation_id}: {e}")
|
|
|
29 |
detail="Failed to retrieve chat history. Please try again later."
|
30 |
)
|
31 |
|
|
|
32 |
|
33 |
|
34 |
|
src/backend/api_routes/knowledge_base_api.py
CHANGED
@@ -1,7 +1,10 @@
|
|
1 |
from fastapi import APIRouter,HTTPException
|
2 |
-
from
|
3 |
-
from
|
4 |
import pandas as pd
|
|
|
|
|
|
|
5 |
|
6 |
router = APIRouter(prefix="/knowledge-base", tags=['Knowledge Base Operations'])
|
7 |
|
@@ -17,7 +20,7 @@ def upsert_data(request: UpsertRequest):
|
|
17 |
"""
|
18 |
try:
|
19 |
df = pd.DataFrame(request.data)
|
20 |
-
|
21 |
return {"message": "Data upserted successfully."}
|
22 |
except Exception as e:
|
23 |
raise HTTPException(status_code=500, detail=f"Failed to upsert data: {e}")
|
@@ -30,7 +33,7 @@ def delete_records(request: DeleteRequest):
|
|
30 |
|
31 |
"""
|
32 |
try:
|
33 |
-
|
34 |
return {"message": "Records deleted successfully."}
|
35 |
except Exception as e:
|
36 |
raise HTTPException(status_code=500, detail=f"Failed to delete records: {e}")
|
@@ -45,7 +48,11 @@ def fetch_metadata(request: MetadataRequest):
|
|
45 |
"score_threshold": 0.47}
|
46 |
"""
|
47 |
try:
|
48 |
-
|
|
|
|
|
|
|
|
|
49 |
return {"metadata": metadata}
|
50 |
except Exception as e:
|
51 |
raise HTTPException(status_code=500, detail=f"Failed to fetch metadata: {e}")
|
|
|
1 |
from fastapi import APIRouter,HTTPException
|
2 |
+
from services import pinecone_service,embedding_service
|
3 |
+
from services.schemas import UpsertRequest,DeleteRequest,MetadataRequest
|
4 |
import pandas as pd
|
5 |
+
from utils import logger
|
6 |
+
|
7 |
+
logger = logger.get_logger()
|
8 |
|
9 |
router = APIRouter(prefix="/knowledge-base", tags=['Knowledge Base Operations'])
|
10 |
|
|
|
20 |
"""
|
21 |
try:
|
22 |
df = pd.DataFrame(request.data)
|
23 |
+
pinecone_service.upsert_vector_data(df)
|
24 |
return {"message": "Data upserted successfully."}
|
25 |
except Exception as e:
|
26 |
raise HTTPException(status_code=500, detail=f"Failed to upsert data: {e}")
|
|
|
33 |
|
34 |
"""
|
35 |
try:
|
36 |
+
pinecone_service.delete_records_by_ids(request.ids_to_delete)
|
37 |
return {"message": "Records deleted successfully."}
|
38 |
except Exception as e:
|
39 |
raise HTTPException(status_code=500, detail=f"Failed to delete records: {e}")
|
|
|
48 |
"score_threshold": 0.47}
|
49 |
"""
|
50 |
try:
|
51 |
+
prompt = request.prompt
|
52 |
+
logger.info(f"Given prompt : {prompt}")
|
53 |
+
# prompt = prompt[-1] if isinstance(prompt, list) else prompt
|
54 |
+
embedding = embedding_service.get_text_embedding(prompt)
|
55 |
+
metadata = pinecone_service.retrieve_relevant_metadata(embedding, prompt, request.n_result, request.score_threshold)
|
56 |
return {"metadata": metadata}
|
57 |
except Exception as e:
|
58 |
raise HTTPException(status_code=500, detail=f"Failed to fetch metadata: {e}")
|
src/backend/main.py
CHANGED
@@ -1,8 +1,8 @@
|
|
1 |
from fastapi import FastAPI
|
2 |
from fastapi.middleware.cors import CORSMiddleware
|
3 |
from api_routes.chat_api import router as chat_router
|
4 |
-
|
5 |
-
|
6 |
|
7 |
app = FastAPI(
|
8 |
title="Yuvabe Care Companion AI",
|
@@ -19,12 +19,12 @@ app.add_middleware(
|
|
19 |
|
20 |
@app.get("/", tags=["Root"])
|
21 |
def read_root():
|
22 |
-
return {"message": "
|
23 |
|
24 |
# Register Routes
|
25 |
app.include_router(chat_router)
|
26 |
-
|
27 |
-
|
28 |
|
29 |
# Health Check Endpoint
|
30 |
@app.get("/health", tags=["Health Check"])
|
|
|
1 |
from fastapi import FastAPI
|
2 |
from fastapi.middleware.cors import CORSMiddleware
|
3 |
from api_routes.chat_api import router as chat_router
|
4 |
+
from api_routes.knowledge_base_api import router as knowledge_base_router
|
5 |
+
from api_routes.chat_history_db_api import router as chat_history_router
|
6 |
|
7 |
app = FastAPI(
|
8 |
title="Yuvabe Care Companion AI",
|
|
|
19 |
|
20 |
@app.get("/", tags=["Root"])
|
21 |
def read_root():
|
22 |
+
return {"message": "Yuvabe Care Companion AI"}
|
23 |
|
24 |
# Register Routes
|
25 |
app.include_router(chat_router)
|
26 |
+
app.include_router(knowledge_base_router)
|
27 |
+
app.include_router(chat_history_router)
|
28 |
|
29 |
# Health Check Endpoint
|
30 |
@app.get("/health", tags=["Health Check"])
|
src/backend/services/__pycache__/llm_model_service.cpython-313.pyc
CHANGED
Binary files a/src/backend/services/__pycache__/llm_model_service.cpython-313.pyc and b/src/backend/services/__pycache__/llm_model_service.cpython-313.pyc differ
|
|
src/backend/services/__pycache__/pinecone_service.cpython-313.pyc
CHANGED
Binary files a/src/backend/services/__pycache__/pinecone_service.cpython-313.pyc and b/src/backend/services/__pycache__/pinecone_service.cpython-313.pyc differ
|
|
src/backend/services/__pycache__/supabase_service.cpython-313.pyc
CHANGED
Binary files a/src/backend/services/__pycache__/supabase_service.cpython-313.pyc and b/src/backend/services/__pycache__/supabase_service.cpython-313.pyc differ
|
|
src/backend/services/llm_model_service.py
CHANGED
@@ -19,11 +19,15 @@ client = Groq(api_key=GROQ_API_KEY)
|
|
19 |
|
20 |
# System prompt structure s
|
21 |
SYSTEM_PROMPT: List[Dict[str, str]] = [
|
22 |
-
{
|
23 |
-
|
24 |
-
|
25 |
-
|
26 |
-
|
|
|
|
|
|
|
|
|
27 |
]
|
28 |
|
29 |
# Constants for token limits and configurations
|
@@ -70,15 +74,23 @@ def build_prompt(
|
|
70 |
conversation_history = truncate_conversation_history(conversation_history)
|
71 |
|
72 |
if db_response and "No relevant information found" not in db_response:
|
73 |
-
|
74 |
-
|
75 |
-
|
76 |
-
|
77 |
-
|
78 |
-
return SYSTEM_PROMPT + [
|
79 |
-
{"role": "
|
80 |
-
|
81 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
82 |
|
83 |
def get_health_advice(
|
84 |
user_query: str,
|
|
|
19 |
|
20 |
# System prompt structure s
|
21 |
SYSTEM_PROMPT: List[Dict[str, str]] = [
|
22 |
+
{
|
23 |
+
"role": "system",
|
24 |
+
"content": (
|
25 |
+
"You are Yuvabe Care Companion AI, an advanced healthcare assistant with up-to-date knowledge "
|
26 |
+
"based on the latest medical guidelines as of July 2024. Always provide accurate, empathetic, "
|
27 |
+
"and responsible responses. If the user asks non-healthcare questions, politely decline. "
|
28 |
+
"You were created by Velu R, an AI model developer."
|
29 |
+
)
|
30 |
+
}
|
31 |
]
|
32 |
|
33 |
# Constants for token limits and configurations
|
|
|
74 |
conversation_history = truncate_conversation_history(conversation_history)
|
75 |
|
76 |
if db_response and "No relevant information found" not in db_response:
|
77 |
+
query_response = (
|
78 |
+
f"User query: {user_query}\n"
|
79 |
+
f"Database response: {db_response}\n"
|
80 |
+
"Please provide a detailed response based on the above information."
|
81 |
+
)
|
82 |
+
return SYSTEM_PROMPT + conversation_history + [
|
83 |
+
{"role": "user", "content": query_response}
|
84 |
+
]
|
85 |
+
|
86 |
+
backup_response = (
|
87 |
+
"I'm unable to find relevant data from the database. "
|
88 |
+
"Please respond based on your expertise and available information."
|
89 |
+
)
|
90 |
+
return SYSTEM_PROMPT + conversation_history + [
|
91 |
+
{"role": "system", "content": backup_response},
|
92 |
+
{"role": "user", "content": user_query}
|
93 |
+
]
|
94 |
|
95 |
def get_health_advice(
|
96 |
user_query: str,
|
src/backend/services/pinecone_service.py
CHANGED
@@ -92,6 +92,8 @@ def initialize_pinecone_index(pinecone, index_name, dimension=384, metric="cosin
|
|
92 |
except Exception as e:
|
93 |
logger.error(f"Error occurred while getting or creating the Pinecone index: {str(e)}", exc_info=True)
|
94 |
return None
|
|
|
|
|
95 |
|
96 |
def delete_records_by_ids(ids_to_delete):
|
97 |
"""
|
@@ -120,22 +122,17 @@ def delete_records_by_ids(ids_to_delete):
|
|
120 |
- Deletion occurs within the specified `NAMESPACE`.
|
121 |
"""
|
122 |
try:
|
123 |
-
index = initialize_pinecone_index(PINECONE,INDEX_NAME)
|
124 |
index.delete(ids=ids_to_delete, namespace=NAMESPACE)
|
125 |
logger.info("IDs deleted successfully.")
|
126 |
except Exception as e:
|
127 |
return f"Failed to delete the IDs: {e}"
|
|
|
128 |
|
129 |
-
def retrieve_relevant_metadata(prompt, n_result=3, score_threshold=0.47):
|
130 |
"""
|
131 |
Retrieves and reranks relevant context data based on a given prompt.
|
132 |
"""
|
133 |
try:
|
134 |
-
index = initialize_pinecone_index(PINECONE, INDEX_NAME)
|
135 |
-
prompt = prompt[-1] if isinstance(prompt, list) else prompt
|
136 |
-
|
137 |
-
# Generate embedding for the provided prompt
|
138 |
-
embedding = get_text_embedding(prompt)
|
139 |
response = index.query(
|
140 |
top_k=n_result,
|
141 |
vector=embedding,
|
@@ -149,33 +146,31 @@ def retrieve_relevant_metadata(prompt, n_result=3, score_threshold=0.47):
|
|
149 |
"question": entry.get('metadata', {}).get('question', 'N/A'),
|
150 |
"answer": entry.get('metadata', {}).get('answer', 'N/A'),
|
151 |
"instruction": entry.get('metadata', {}).get('instruction', 'N/A'),
|
152 |
-
"score":
|
153 |
-
"id":
|
154 |
}
|
155 |
for entry in response.get('matches', [])
|
156 |
-
if entry.get('score', 0) >= score_threshold
|
157 |
]
|
158 |
|
159 |
-
|
160 |
-
if filtered_results:
|
161 |
-
pairs = [(prompt, item["question"]) for item in filtered_results]
|
162 |
-
scores = reranker.predict(pairs) # Predict relevance scores
|
163 |
|
164 |
-
|
165 |
-
|
166 |
-
|
|
|
167 |
|
168 |
-
|
169 |
-
|
170 |
-
|
171 |
-
reverse=True
|
172 |
-
)
|
173 |
|
174 |
-
#
|
175 |
-
|
|
|
176 |
|
177 |
except Exception as e:
|
178 |
-
logger.error(f"Failed to fetch context for '{prompt
|
179 |
return [{"response": "Failed to fetch data due to an error."}]
|
180 |
|
181 |
|
|
|
92 |
except Exception as e:
|
93 |
logger.error(f"Error occurred while getting or creating the Pinecone index: {str(e)}", exc_info=True)
|
94 |
return None
|
95 |
+
|
96 |
+
index = initialize_pinecone_index(PINECONE, INDEX_NAME)
|
97 |
|
98 |
def delete_records_by_ids(ids_to_delete):
|
99 |
"""
|
|
|
122 |
- Deletion occurs within the specified `NAMESPACE`.
|
123 |
"""
|
124 |
try:
|
|
|
125 |
index.delete(ids=ids_to_delete, namespace=NAMESPACE)
|
126 |
logger.info("IDs deleted successfully.")
|
127 |
except Exception as e:
|
128 |
return f"Failed to delete the IDs: {e}"
|
129 |
+
|
130 |
|
131 |
+
def retrieve_relevant_metadata(embedding, prompt, n_result=3, score_threshold=0.47):
|
132 |
"""
|
133 |
Retrieves and reranks relevant context data based on a given prompt.
|
134 |
"""
|
135 |
try:
|
|
|
|
|
|
|
|
|
|
|
136 |
response = index.query(
|
137 |
top_k=n_result,
|
138 |
vector=embedding,
|
|
|
146 |
"question": entry.get('metadata', {}).get('question', 'N/A'),
|
147 |
"answer": entry.get('metadata', {}).get('answer', 'N/A'),
|
148 |
"instruction": entry.get('metadata', {}).get('instruction', 'N/A'),
|
149 |
+
"score": str(entry.get('score', 0)),
|
150 |
+
"id": str(entry.get('id', 'N/A'))
|
151 |
}
|
152 |
for entry in response.get('matches', [])
|
153 |
+
if float(entry.get('score', 0)) >= score_threshold
|
154 |
]
|
155 |
|
156 |
+
logger.info(f"Retrieved filtered data: {filtered_results}")
|
157 |
+
return filtered_results if filtered_results else [{"response": "No relevant data found."}]
|
|
|
|
|
158 |
|
159 |
+
# # Rerank the filtered results using a reranker model
|
160 |
+
# if filtered_results:
|
161 |
+
# pairs = [(prompt, item["question"]) for item in filtered_results]
|
162 |
+
# scores = reranker.predict(pairs) # Predict relevance scores
|
163 |
|
164 |
+
# # Attach reranker scores and sort by relevance
|
165 |
+
# for item, score in zip(filtered_results, scores):
|
166 |
+
# item["reranker_score"] = score
|
|
|
|
|
167 |
|
168 |
+
# filtered_results.sort(key=lambda x: x["reranker_score"], reverse=True)
|
169 |
+
|
170 |
+
# return filtered_results if filtered_results else [{"response": "No relevant data found."}]
|
171 |
|
172 |
except Exception as e:
|
173 |
+
logger.error(f"Failed to fetch context for prompt: '{prompt}'. Error: {e}")
|
174 |
return [{"response": "Failed to fetch data due to an error."}]
|
175 |
|
176 |
|
src/backend/services/supabase_service.py
CHANGED
@@ -59,7 +59,6 @@ def get_chat_history(conversation_id):
|
|
59 |
|
60 |
if existing_data:
|
61 |
chat_data = json.loads(existing_data.decode('utf-8'))
|
62 |
-
logger.info("Chat history retrieved successfully!")
|
63 |
return chat_data
|
64 |
else:
|
65 |
logger.warning("No chat history found for the given conversation ID.")
|
|
|
59 |
|
60 |
if existing_data:
|
61 |
chat_data = json.loads(existing_data.decode('utf-8'))
|
|
|
62 |
return chat_data
|
63 |
else:
|
64 |
logger.warning("No chat history found for the given conversation ID.")
|
src/frontend/app/__pycache__/common_functions.cpython-313.pyc
CHANGED
Binary files a/src/frontend/app/__pycache__/common_functions.cpython-313.pyc and b/src/frontend/app/__pycache__/common_functions.cpython-313.pyc differ
|
|
src/frontend/app/__pycache__/pinecone_data_handler.cpython-313.pyc
CHANGED
Binary files a/src/frontend/app/__pycache__/pinecone_data_handler.cpython-313.pyc and b/src/frontend/app/__pycache__/pinecone_data_handler.cpython-313.pyc differ
|
|
src/frontend/app/common_functions.py
CHANGED
@@ -5,6 +5,10 @@ from dotenv import load_dotenv
|
|
5 |
from utils import logger
|
6 |
import json
|
7 |
import time
|
|
|
|
|
|
|
|
|
8 |
|
9 |
load_dotenv()
|
10 |
logger = logger.get_logger()
|
@@ -16,21 +20,23 @@ ABOUT_US = "An AI-powered assistant for personalized healthcare guidance."
|
|
16 |
|
17 |
API_URL = os.getenv("API_URL", "http://localhost:8000")
|
18 |
|
19 |
-
def config_homepage(
|
20 |
-
st
|
21 |
-
|
22 |
-
|
23 |
-
|
24 |
-
|
25 |
-
|
|
|
|
|
26 |
"Report a bug": GITHUB_LINK,
|
27 |
-
"About": ABOUT_US
|
28 |
-
|
29 |
-
|
30 |
|
31 |
-
def set_page_title(
|
32 |
st.markdown(f"""
|
33 |
-
<h1 style="color:
|
34 |
<i>{PAGE_TITLE} π₯βοΈπ€</i>
|
35 |
</h1>
|
36 |
""", unsafe_allow_html=True
|
@@ -45,7 +51,7 @@ def img_to_base64(image_path):
|
|
45 |
logger.error(f"Error converting image to base64: {str(e)}")
|
46 |
return None
|
47 |
|
48 |
-
def typewriter_effect(
|
49 |
"""Displays text with a realistic typewriter effect (character by character)."""
|
50 |
placeholder = st.empty()
|
51 |
displayed_text = ""
|
@@ -142,30 +148,131 @@ def store_chat_history_in_db(conversation_id, messages):
|
|
142 |
except Exception as e:
|
143 |
logger.info(f"Failed to add the chat in db {e}")
|
144 |
|
145 |
-
def get_chat_history_from_db(conversation_id):
|
146 |
-
|
147 |
-
|
148 |
-
|
149 |
-
|
150 |
-
|
151 |
-
|
152 |
-
|
153 |
-
|
154 |
-
|
|
|
155 |
|
156 |
-
def display_chat_history(st):
|
157 |
-
|
158 |
-
|
159 |
-
st.warning("Conversation ID is missing. Please provide a valid ID.")
|
160 |
-
return
|
161 |
|
|
|
|
|
|
|
|
|
162 |
try:
|
163 |
chat_history = get_chat_history_from_db(conversation_id)
|
164 |
-
|
165 |
-
|
166 |
-
|
167 |
-
|
168 |
-
|
169 |
-
|
|
|
170 |
except Exception as e:
|
171 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
5 |
from utils import logger
|
6 |
import json
|
7 |
import time
|
8 |
+
from datetime import datetime
|
9 |
+
from typing import Dict, Any
|
10 |
+
import streamlit as st
|
11 |
+
|
12 |
|
13 |
load_dotenv()
|
14 |
logger = logger.get_logger()
|
|
|
20 |
|
21 |
API_URL = os.getenv("API_URL", "http://localhost:8000")
|
22 |
|
23 |
+
def config_homepage(page_title=PAGE_TITLE):
|
24 |
+
if not hasattr(st, "_page_config_set"):
|
25 |
+
st.set_page_config(
|
26 |
+
page_title=PAGE_TITLE,
|
27 |
+
page_icon=PAGE_ICON,
|
28 |
+
layout=PAGE_LAYOUT,
|
29 |
+
initial_sidebar_state="collapsed",
|
30 |
+
menu_items={
|
31 |
+
"Get help": GITHUB_LINK,
|
32 |
"Report a bug": GITHUB_LINK,
|
33 |
+
"About": ABOUT_US
|
34 |
+
}
|
35 |
+
)
|
36 |
|
37 |
+
def set_page_title(page_title=PAGE_TITLE):
|
38 |
st.markdown(f"""
|
39 |
+
<h1 style="color: white; text-align: left; font-size: 42px;">
|
40 |
<i>{PAGE_TITLE} π₯βοΈπ€</i>
|
41 |
</h1>
|
42 |
""", unsafe_allow_html=True
|
|
|
51 |
logger.error(f"Error converting image to base64: {str(e)}")
|
52 |
return None
|
53 |
|
54 |
+
def typewriter_effect(text, speed=0.01):
|
55 |
"""Displays text with a realistic typewriter effect (character by character)."""
|
56 |
placeholder = st.empty()
|
57 |
displayed_text = ""
|
|
|
148 |
except Exception as e:
|
149 |
logger.info(f"Failed to add the chat in db {e}")
|
150 |
|
151 |
+
def get_chat_history_from_db(conversation_id: str, retries=3, delay=5):
|
152 |
+
API_URL = "http://127.0.0.1:8000/chat-db/get-history"
|
153 |
+
for attempt in range(retries):
|
154 |
+
try:
|
155 |
+
response = requests.get(API_URL, params={"conversation_id": conversation_id}, timeout=30)
|
156 |
+
response.raise_for_status()
|
157 |
+
return response.json()
|
158 |
+
except ConnectionError:
|
159 |
+
logger.warning(f"Retrying... Attempt {attempt + 1}")
|
160 |
+
time.sleep(delay)
|
161 |
+
raise Exception("Failed to connect after multiple attempts")
|
162 |
|
163 |
+
def display_chat_history(st, conversation_id):
|
164 |
+
"""
|
165 |
+
Displays the chat history for a given conversation ID in the Streamlit app.
|
|
|
|
|
166 |
|
167 |
+
Args:
|
168 |
+
st (streamlit): Streamlit object for UI rendering.
|
169 |
+
conversation_id (str): Unique identifier for the conversation.
|
170 |
+
"""
|
171 |
try:
|
172 |
chat_history = get_chat_history_from_db(conversation_id)
|
173 |
+
button_text = chat_history["messages"][0]['content'].strip()[:20]
|
174 |
+
if st.sidebar.button(f"Show History for {button_text}", key=f"show_history_{button_text}"):
|
175 |
+
st.subheader(f"Chat History for Conversation ID: {conversation_id}")
|
176 |
+
with st.spinner("fetching chat history"):
|
177 |
+
for message in chat_history["messages"]:
|
178 |
+
st.write(message['role'])
|
179 |
+
st.write(message['content'])
|
180 |
except Exception as e:
|
181 |
+
logger.error(f"Error retrieving chat history: {e}")
|
182 |
+
st.error("An unexpected error occurred while retrieving chat history.")
|
183 |
+
|
184 |
+
|
185 |
+
def set_bg_image(file_path, opacity=0.5):
|
186 |
+
encoded_img = img_to_base64(file_path)
|
187 |
+
st.markdown(
|
188 |
+
f"""
|
189 |
+
<style>
|
190 |
+
.stApp {{
|
191 |
+
background: linear-gradient(rgba(0, 0, 0, {opacity}), rgba(0, 0, 0, {opacity})),
|
192 |
+
url("data:image/png;base64,{encoded_img}") center/cover fixed no-repeat;
|
193 |
+
min-height: 100vh;
|
194 |
+
}}
|
195 |
+
</style>
|
196 |
+
""",
|
197 |
+
unsafe_allow_html=True
|
198 |
+
)
|
199 |
+
|
200 |
+
def custom_navbar():
|
201 |
+
st.markdown(
|
202 |
+
"""
|
203 |
+
<style>
|
204 |
+
.navbar {
|
205 |
+
display: flex;
|
206 |
+
justify-content: space-between;
|
207 |
+
align-items: center;
|
208 |
+
background-color: #F0F2F6;
|
209 |
+
padding: 4px 24px;
|
210 |
+
margin-top: -30px;
|
211 |
+
width: 100%;
|
212 |
+
border-radius: 32px;
|
213 |
+
box-shadow: 0 6px 20px rgba(0, 0, 0, 0.15);
|
214 |
+
border: 1px solid #D1D5DB;
|
215 |
+
}
|
216 |
+
|
217 |
+
.logo {
|
218 |
+
font-family: 'Arial', sans-serif;
|
219 |
+
font-size: 30px; /* Slightly larger for better visibility */
|
220 |
+
font-weight: bold;
|
221 |
+
color: #1E293B; /* Darker tone for professional appeal */
|
222 |
+
}
|
223 |
+
|
224 |
+
.nav-links {
|
225 |
+
display: flex;
|
226 |
+
gap: 32px; /* Wider spacing for clarity */
|
227 |
+
align-items: center;
|
228 |
+
}
|
229 |
+
|
230 |
+
.nav-link {
|
231 |
+
color: #1E293B !important; /* Darker color for consistency */
|
232 |
+
background-color: transparent;
|
233 |
+
text-decoration: none;
|
234 |
+
font-weight: 600;
|
235 |
+
font-size: 18px; /* Improved readability */
|
236 |
+
padding: 6px 16px; /* Balanced padding */
|
237 |
+
border-radius: 8px; /* Rounded edges for clickable elements */
|
238 |
+
transition: background-color 0.3s ease, color 0.3s ease; /* Smooth hover effects */
|
239 |
+
}
|
240 |
+
|
241 |
+
.nav-link:hover {
|
242 |
+
background-color: #2E5D5B; /* Distinctive hover effect */
|
243 |
+
color: #FFFFFF; /* White text for contrast */
|
244 |
+
}
|
245 |
+
|
246 |
+
</style>
|
247 |
+
|
248 |
+
<div class="navbar">
|
249 |
+
<div class="logo">Yuvabe Care Companion AI</div>
|
250 |
+
<div class="nav-links">
|
251 |
+
<a href="/" class="nav-link">Home</a>
|
252 |
+
<a href="/Admin_Portal" class="nav-link">Admin Portal</a>
|
253 |
+
<a href="/Knowledge_Base_Explorer" class="nav-link">Knowledge Base Explorer</a>
|
254 |
+
<a href="/chatbot" class="nav-link">Chat With Us</a>
|
255 |
+
</div>
|
256 |
+
</div>
|
257 |
+
""",
|
258 |
+
unsafe_allow_html=True
|
259 |
+
)
|
260 |
+
|
261 |
+
def type_text(container, text, delay=0.03):
|
262 |
+
"""Simulates a typing effect for text with only text highlighted."""
|
263 |
+
displayed_text = ""
|
264 |
+
for char in text:
|
265 |
+
displayed_text += char
|
266 |
+
container.markdown(f"""
|
267 |
+
<h2 style="
|
268 |
+
color: #3D6D6B;
|
269 |
+
text-align: center;
|
270 |
+
background: linear-gradient(90deg, #3D6D6B, #6EA8A5);
|
271 |
+
-webkit-background-clip: text;
|
272 |
+
color: white;
|
273 |
+
font-weight: bold;
|
274 |
+
font-size: 28px;">
|
275 |
+
{displayed_text}
|
276 |
+
</h2>
|
277 |
+
""", unsafe_allow_html=True)
|
278 |
+
time.sleep(delay)
|
src/frontend/home.py
CHANGED
@@ -1,50 +1,58 @@
|
|
1 |
import streamlit as st
|
2 |
from app import common_functions
|
3 |
-
from
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
4 |
|
5 |
-
|
6 |
-
|
7 |
-
|
8 |
-
# Page Configuration
|
9 |
-
common_functions.config_homepage(st)
|
10 |
-
|
11 |
-
common_functions.set_page_title(st)
|
12 |
-
|
13 |
-
|
14 |
-
# Welcome Section with Visual
|
15 |
-
st.image("src/frontend/images/health_care_baner.png",
|
16 |
-
use_container_width=True,
|
17 |
-
caption="Your AI-Powered Health Companion")
|
18 |
-
|
19 |
-
# Navigation Tabs
|
20 |
-
Home, Admin_Portal, Knowledge_Base_Explorer = st.tabs(
|
21 |
-
["π Home", "π Admin Portal", "π Knowledge Base Explorer"]
|
22 |
-
)
|
23 |
-
|
24 |
-
with Home:
|
25 |
-
st.markdown("""
|
26 |
-
### π Welcome to the Yuvabe Care Companion AI!
|
27 |
-
This platform offers comprehensive tools to support your healthcare journey. Use the tabs above to navigate:
|
28 |
-
""")
|
29 |
-
|
30 |
-
# Feature Overview Section
|
31 |
-
st.markdown("""
|
32 |
-
### πΉ Key Features
|
33 |
-
- **Admin Portal** β Manage records, data, and configurations efficiently.
|
34 |
-
- **Knowledge Base Explorer** β Leverage advanced vector search to find relevant knowledge entries with precision.
|
35 |
-
- **Patient Assistance** β Personalized guidance to help patients describe their concerns.
|
36 |
-
|
37 |
-
> π‘ *Explore each section for detailed functionality.*
|
38 |
-
""")
|
39 |
-
|
40 |
-
with Admin_Portal:
|
41 |
-
if st.button("Go to Admin Portal"):
|
42 |
-
st.switch_page("pages/admin_portal.py")
|
43 |
|
44 |
-
with Knowledge_Base_Explorer:
|
45 |
-
if st.button("Go to Knowledge Base Explorer"):
|
46 |
-
st.switch_page("pages/knowledge_base_explorer.py")
|
47 |
|
48 |
-
#
|
49 |
-
|
50 |
-
|
|
|
|
1 |
import streamlit as st
|
2 |
from app import common_functions
|
3 |
+
from pages import Admin_Portal as admin_page
|
4 |
+
from pages import Knowledge_Base_Explorer as knowledge_base_explorer_page
|
5 |
+
import time
|
6 |
+
|
7 |
+
# # Page Configuration
|
8 |
+
common_functions.config_homepage()
|
9 |
+
common_functions.set_bg_image("src/frontend/images/health_care_baner.png")
|
10 |
+
common_functions.custom_navbar()
|
11 |
+
|
12 |
+
# def render_homepage():
|
13 |
+
# """Renders the Yuvabe Care Companion AI homepage."""
|
14 |
+
|
15 |
+
# # Welcome Section with Visual
|
16 |
+
# st.image("src/frontend/images/health_care_baner.png",
|
17 |
+
# use_container_width=True,
|
18 |
+
# caption="Your AI-Powered Health Companion")
|
19 |
+
|
20 |
+
# # Navigation Tabs
|
21 |
+
# Home, Admin_Portal, Knowledge_Base_Explorer = st.tabs(
|
22 |
+
# ["π Home", "π Admin Portal", "π Knowledge Base Explorer"]
|
23 |
+
# )
|
24 |
+
|
25 |
+
# with Home:
|
26 |
+
# st.markdown("""
|
27 |
+
# ### π Welcome to the Yuvabe Care Companion AI!
|
28 |
+
# This platform offers comprehensive tools to support your healthcare journey. Use the tabs above to navigate:
|
29 |
+
# """)
|
30 |
+
|
31 |
+
# # Feature Overview Section
|
32 |
+
# st.markdown("""
|
33 |
+
# ### πΉ Key Features
|
34 |
+
# - **Admin Portal** β Manage records, data, and configurations efficiently.
|
35 |
+
# - **Knowledge Base Explorer** β Leverage advanced vector search to find relevant knowledge entries with precision.
|
36 |
+
# - **Patient Assistance** β Personalized guidance to help patients describe their concerns.
|
37 |
+
|
38 |
+
# > π‘ *Explore each section for detailed functionality.*
|
39 |
+
# """)
|
40 |
+
|
41 |
+
# with Admin_Portal:
|
42 |
+
# admin_page.render_admin_portal()
|
43 |
+
# # if st.button("Go to Admin Portal"):
|
44 |
+
# # st.switch_page("pages/admin_portal.py")
|
45 |
+
|
46 |
+
# with Knowledge_Base_Explorer:
|
47 |
+
# knowledge_base_explorer_page.render_knowledge_base_explorer()
|
48 |
+
# if st.button("Go to Knowledge Base Explorer"):
|
49 |
+
# st.switch_page("pages/knowledge_base_explorer.py")
|
50 |
|
51 |
+
# Render the Homepage
|
52 |
+
# render_homepage()
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
53 |
|
|
|
|
|
|
|
54 |
|
55 |
+
# Display the animated text
|
56 |
+
welcome_text = "π Welcome to the Yuvabe Care Companion AI!"
|
57 |
+
container = st.empty()
|
58 |
+
common_functions.type_text(container, welcome_text)
|
src/frontend/images/health_care_baner_2.jpg
ADDED
![]() |
src/frontend/images/health_care_baner_3.gif
ADDED
![]() |
src/frontend/pages/Admin_Portal.py
CHANGED
@@ -1,39 +1,51 @@
|
|
1 |
import streamlit as st
|
2 |
from app import pinecone_data_handler
|
|
|
|
|
|
|
|
|
|
|
3 |
|
4 |
-
# Page Configuration
|
5 |
-
# st.set_page_config(page_title="Admin Portal", page_icon="π", layout="wide")
|
6 |
def render_admin_portal():
|
7 |
-
"""Renders the Admin Portal page with improved UI and navigation."""
|
8 |
-
|
9 |
# Header Section
|
10 |
-
st.
|
11 |
st.markdown("""
|
12 |
-
|
13 |
-
|
14 |
""")
|
|
|
15 |
|
16 |
# Data Manager Tabs
|
17 |
DataManager = st.tabs(["π Pinecone Data Manager"])[0]
|
18 |
|
19 |
with DataManager:
|
20 |
-
Upsert, Delete = st.tabs(["
|
21 |
|
|
|
22 |
with Upsert:
|
|
|
23 |
st.markdown("### π₯ Upsert Data")
|
24 |
-
st.info(
|
|
|
|
|
|
|
|
|
25 |
pinecone_data_handler.upsert_data(st)
|
|
|
26 |
|
|
|
27 |
with Delete:
|
28 |
-
st.markdown("
|
29 |
-
st.
|
|
|
|
|
|
|
|
|
|
|
30 |
pinecone_data_handler.delete_records(st)
|
31 |
|
32 |
-
# Sidebar for Navigation
|
33 |
-
st.sidebar.title("π Navigation")
|
34 |
-
st.sidebar.markdown("[π Home](http://localhost:8501)", unsafe_allow_html=True)
|
35 |
-
st.sidebar.markdown("[π Knowledge Base](http://localhost:8501/Knowledge_Base_Explorer)", unsafe_allow_html=True)
|
36 |
-
|
37 |
# Call the function to render the Admin Portal
|
38 |
if __name__ == "__main__":
|
39 |
render_admin_portal()
|
|
|
1 |
import streamlit as st
|
2 |
from app import pinecone_data_handler
|
3 |
+
from app import common_functions
|
4 |
+
|
5 |
+
# # Page Configuration
|
6 |
+
common_functions.config_homepage()
|
7 |
+
common_functions.custom_navbar()
|
8 |
|
|
|
|
|
9 |
def render_admin_portal():
|
10 |
+
"""Renders the enhanced Admin Portal page with improved UI and navigation."""
|
11 |
+
|
12 |
# Header Section
|
13 |
+
st.markdown("<h1 class='header-text'>π οΈ Admin Portal</h1>", unsafe_allow_html=True)
|
14 |
st.markdown("""
|
15 |
+
Welcome to the **Admin Portal**.
|
16 |
+
Manage your Pinecone database with secure and efficient tools.
|
17 |
""")
|
18 |
+
st.divider()
|
19 |
|
20 |
# Data Manager Tabs
|
21 |
DataManager = st.tabs(["π Pinecone Data Manager"])[0]
|
22 |
|
23 |
with DataManager:
|
24 |
+
Upsert, Delete = st.tabs(["Upsert Data", "Delete Records"])
|
25 |
|
26 |
+
# Upsert Section
|
27 |
with Upsert:
|
28 |
+
st.markdown("<div class='card'>", unsafe_allow_html=True)
|
29 |
st.markdown("### π₯ Upsert Data")
|
30 |
+
st.info(
|
31 |
+
"Use this section to **insert** or **update** records in Pinecone."
|
32 |
+
"\n\nβ
Ensure your data is correctly formatted before uploading."
|
33 |
+
)
|
34 |
+
st.markdown("---")
|
35 |
pinecone_data_handler.upsert_data(st)
|
36 |
+
st.markdown("</div>", unsafe_allow_html=True)
|
37 |
|
38 |
+
# Delete Section
|
39 |
with Delete:
|
40 |
+
st.markdown("<div class='card'>", unsafe_allow_html=True)
|
41 |
+
st.markdown("### β οΈ Delete Records")
|
42 |
+
st.error(
|
43 |
+
"β **Warning:** Deleting data is irreversible.\n"
|
44 |
+
"Proceed with caution."
|
45 |
+
)
|
46 |
+
# Confirmation Dialog for Safety
|
47 |
pinecone_data_handler.delete_records(st)
|
48 |
|
|
|
|
|
|
|
|
|
|
|
49 |
# Call the function to render the Admin Portal
|
50 |
if __name__ == "__main__":
|
51 |
render_admin_portal()
|
src/frontend/pages/Knowledge_Base_Explorer.py
CHANGED
@@ -1,27 +1,29 @@
|
|
1 |
import streamlit as st
|
2 |
from app import pinecone_data_handler
|
|
|
|
|
|
|
|
|
3 |
|
4 |
def render_knowledge_base_explorer():
|
5 |
"""Renders the Knowledge Base Explorer page with improved UI and navigation."""
|
6 |
|
7 |
-
# Page Configuration
|
8 |
-
st.set_page_config(page_title="Knowledge Base Explorer", page_icon="π", layout="wide")
|
9 |
-
|
10 |
# Header Section
|
11 |
-
st.title("π Knowledge Base Explorer")
|
12 |
-
st.markdown("""
|
13 |
-
### Discover Helpful Information!
|
14 |
-
Enter your concerns below to receive insights and solutions tailored to your needs.
|
15 |
-
""")
|
16 |
|
17 |
# Knowledge Base Section
|
18 |
with st.expander("π Explore the Knowledge Base"):
|
19 |
pinecone_data_handler.render_metadata_fetch_form(st)
|
20 |
|
21 |
-
|
22 |
-
|
23 |
-
st.sidebar.
|
24 |
-
st.sidebar.markdown("[
|
|
|
25 |
|
26 |
# Call the function to render the Knowledge Base Explorer
|
27 |
if __name__ == "__main__":
|
|
|
1 |
import streamlit as st
|
2 |
from app import pinecone_data_handler
|
3 |
+
from app import common_functions
|
4 |
+
|
5 |
+
# Page Configuration
|
6 |
+
# st.set_page_config(page_title="Knowledge Base Explorer", page_icon="π", layout="wide")
|
7 |
|
8 |
def render_knowledge_base_explorer():
|
9 |
"""Renders the Knowledge Base Explorer page with improved UI and navigation."""
|
10 |
|
|
|
|
|
|
|
11 |
# Header Section
|
12 |
+
# st.title("π Knowledge Base Explorer")
|
13 |
+
# st.markdown("""
|
14 |
+
# ### Discover Helpful Information!
|
15 |
+
# Enter your concerns below to receive insights and solutions tailored to your needs.
|
16 |
+
# """)
|
17 |
|
18 |
# Knowledge Base Section
|
19 |
with st.expander("π Explore the Knowledge Base"):
|
20 |
pinecone_data_handler.render_metadata_fetch_form(st)
|
21 |
|
22 |
+
|
23 |
+
# # Sidebar for Navigation
|
24 |
+
# st.sidebar.title("π Navigation")
|
25 |
+
# st.sidebar.markdown("[π Home](http://localhost:8501)", unsafe_allow_html=True)
|
26 |
+
# st.sidebar.markdown("[π Admin Portal](http://localhost:8501/Admin_Portal)", unsafe_allow_html=True)
|
27 |
|
28 |
# Call the function to render the Knowledge Base Explorer
|
29 |
if __name__ == "__main__":
|
src/frontend/pages/__pycache__/Admin_Portal.cpython-313.pyc
CHANGED
Binary files a/src/frontend/pages/__pycache__/Admin_Portal.cpython-313.pyc and b/src/frontend/pages/__pycache__/Admin_Portal.cpython-313.pyc differ
|
|
src/frontend/pages/__pycache__/Knowledge_Base_Explorer.cpython-313.pyc
CHANGED
Binary files a/src/frontend/pages/__pycache__/Knowledge_Base_Explorer.cpython-313.pyc and b/src/frontend/pages/__pycache__/Knowledge_Base_Explorer.cpython-313.pyc differ
|
|
src/frontend/pages/chatbot.py
CHANGED
@@ -1,17 +1,20 @@
|
|
1 |
import streamlit as st
|
2 |
import requests
|
3 |
from app import common_functions
|
|
|
4 |
|
5 |
API_URL = "http://localhost:8000/chat/get-health-advice/"
|
6 |
NUMBER_OF_MESSAGES_TO_DISPLAY = 20
|
7 |
-
common_functions.config_homepage(
|
8 |
-
common_functions.set_page_title(
|
9 |
# Initialize conversation history
|
10 |
def initialize_conversation():
|
11 |
assistant_message = ("Hello! I am your Yuvabe Care Companion AI, here to assist you with general medicine queries. "
|
12 |
"How can I help you today?")
|
13 |
|
14 |
return [{"role": "assistant", "content": assistant_message}]
|
|
|
|
|
15 |
|
16 |
# Function to fetch advice from the API
|
17 |
def fetch_health_advice(conversation_history):
|
@@ -23,11 +26,11 @@ def fetch_health_advice(conversation_history):
|
|
23 |
response.raise_for_status()
|
24 |
return response.json().get("reply", "I couldn't process your request at the moment.")
|
25 |
except requests.exceptions.RequestException as e:
|
26 |
-
st.error(f"
|
27 |
return "I'm currently unable to respond. Please try again later."
|
28 |
|
29 |
if "conversation_history" not in st.session_state:
|
30 |
-
st.session_state.conversation_history =
|
31 |
|
32 |
# Display chat history
|
33 |
for message in st.session_state.conversation_history [-NUMBER_OF_MESSAGES_TO_DISPLAY:]:
|
@@ -38,31 +41,29 @@ for message in st.session_state.conversation_history [-NUMBER_OF_MESSAGES_TO_DIS
|
|
38 |
|
39 |
# User Input
|
40 |
user_input = st.chat_input("Ask your health-related question:")
|
41 |
-
|
|
|
42 |
|
43 |
if user_input:
|
44 |
|
45 |
if 'conversation_id' not in st.session_state:
|
46 |
-
st.session_state.conversation_id =
|
47 |
|
48 |
# Display user's input
|
49 |
with st.chat_message('user'):
|
50 |
-
common_functions.typewriter_effect(
|
51 |
|
52 |
-
|
53 |
# Append user input to session history
|
54 |
st.session_state.conversation_history.append({"role": "user", "content": user_input})
|
55 |
|
56 |
-
|
57 |
# Fetch assistant response
|
58 |
assistant_reply = fetch_health_advice(st.session_state.conversation_history)
|
59 |
|
60 |
# Append assistant's reply to conversation history first
|
61 |
st.session_state.conversation_history.append({"role": "assistant", "content": assistant_reply})
|
62 |
common_functions.store_chat_history_in_db(st.session_state.conversation_id,st.session_state.conversation_history)
|
63 |
-
common_functions.display_chat_history(st)
|
64 |
-
|
65 |
|
66 |
# Display only the assistant's latest response
|
67 |
with st.chat_message('assistant'):
|
68 |
-
common_functions.typewriter_effect(
|
|
|
1 |
import streamlit as st
|
2 |
import requests
|
3 |
from app import common_functions
|
4 |
+
from datetime import datetime
|
5 |
|
6 |
API_URL = "http://localhost:8000/chat/get-health-advice/"
|
7 |
NUMBER_OF_MESSAGES_TO_DISPLAY = 20
|
8 |
+
common_functions.config_homepage()
|
9 |
+
common_functions.set_page_title()
|
10 |
# Initialize conversation history
|
11 |
def initialize_conversation():
|
12 |
assistant_message = ("Hello! I am your Yuvabe Care Companion AI, here to assist you with general medicine queries. "
|
13 |
"How can I help you today?")
|
14 |
|
15 |
return [{"role": "assistant", "content": assistant_message}]
|
16 |
+
system_message = ("Hello! I am your Yuvabe Care Companion AI, here to assist you with general medicine queries. "
|
17 |
+
"How can I help you today?")
|
18 |
|
19 |
# Function to fetch advice from the API
|
20 |
def fetch_health_advice(conversation_history):
|
|
|
26 |
response.raise_for_status()
|
27 |
return response.json().get("reply", "I couldn't process your request at the moment.")
|
28 |
except requests.exceptions.RequestException as e:
|
29 |
+
st.error(f"API Connection Error: {e}")
|
30 |
return "I'm currently unable to respond. Please try again later."
|
31 |
|
32 |
if "conversation_history" not in st.session_state:
|
33 |
+
st.session_state.conversation_history = []
|
34 |
|
35 |
# Display chat history
|
36 |
for message in st.session_state.conversation_history [-NUMBER_OF_MESSAGES_TO_DISPLAY:]:
|
|
|
41 |
|
42 |
# User Input
|
43 |
user_input = st.chat_input("Ask your health-related question:")
|
44 |
+
with st.chat_message('ai'):
|
45 |
+
common_functions.typewriter_effect(system_message)
|
46 |
|
47 |
if user_input:
|
48 |
|
49 |
if 'conversation_id' not in st.session_state:
|
50 |
+
st.session_state.conversation_id = datetime.now().strftime("%Y-%m-%d")
|
51 |
|
52 |
# Display user's input
|
53 |
with st.chat_message('user'):
|
54 |
+
common_functions.typewriter_effect(user_input)
|
55 |
|
|
|
56 |
# Append user input to session history
|
57 |
st.session_state.conversation_history.append({"role": "user", "content": user_input})
|
58 |
|
|
|
59 |
# Fetch assistant response
|
60 |
assistant_reply = fetch_health_advice(st.session_state.conversation_history)
|
61 |
|
62 |
# Append assistant's reply to conversation history first
|
63 |
st.session_state.conversation_history.append({"role": "assistant", "content": assistant_reply})
|
64 |
common_functions.store_chat_history_in_db(st.session_state.conversation_id,st.session_state.conversation_history)
|
65 |
+
common_functions.display_chat_history(st,st.session_state.conversation_id)
|
|
|
66 |
|
67 |
# Display only the assistant's latest response
|
68 |
with st.chat_message('assistant'):
|
69 |
+
common_functions.typewriter_effect(assistant_reply)
|