Skip to content
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
3 changes: 3 additions & 0 deletions .gitignore
Original file line number Diff line number Diff line change
Expand Up @@ -3,3 +3,6 @@
node_modules
backend/__pycache__
backend/.env

__pycache__/
*.pyc
10 changes: 10 additions & 0 deletions backend/API/chatHistory.json
Original file line number Diff line number Diff line change
@@ -0,0 +1,10 @@
{
"session_id" : {
"query" : "some string in format",
"history": [
{ "role": "user", "parts": ["Hello"] },
{ "role": "model", "parts": ["Hi there! How can I help you today?"] },
{ "role": "user", "parts": ["Tell me about my plan benefits."] }
]
}
}
45 changes: 32 additions & 13 deletions backend/API/root.py
Original file line number Diff line number Diff line change
Expand Up @@ -12,12 +12,15 @@
from ..Chatbot.chatbot import get_chatbot_response
import asyncio

from uuid import uuid4 # for getting session id


app = FastAPI()

from fastapi.middleware.cors import CORSMiddleware

app.add_middleware(
CORSMiddleware, # type: ignore
CORSMiddleware, #type: ignore
allow_origins=["http://localhost:5173"],
# Allow frontend in React to connect
allow_credentials=True,
Expand All @@ -31,24 +34,30 @@

history = {}

chat_history = {}


@app.get("/")
def root():
return {"FastAPI Running!!!!!"}

@app.get("/session")
def get_session_id():
session_id = str(uuid4())
chat_history[session_id] = {} # Optional: initialize chat history
return {"sessionId" : session_id}

@app.post("/chat/message")
async def send_message(data: ChatBotMessage):
response = get_chatbot_response(data.message, history)
@app.post("/chat/message/{session_id}")
async def send_message(session_id: str, data: ChatBotMessage):
response = get_chatbot_response(data.message, chat_history[session_id])
return {"received": data.message, "response": response}


@app.post("/form/submit")
async def upload_pdfs(form_data: str = Form(...),
@app.post("/form/submit/{session_id}")
async def upload_pdfs(session_id: str, form_data: str = Form(...),
files: List[UploadFile] = File(...)):
# Process form data into dictionary
form_dict = json.loads(form_data)

form_dict = json.loads(form_data)
# Check against Pydantic Model
user_input = UserInputForm(**form_dict)
user_input = user_input.model_dump()
Expand All @@ -66,7 +75,7 @@ async def upload_pdfs(form_data: str = Form(...),
# upload to s3 and textract
# { "name": filename, "text": "TEXT RESULTS " }
results = await upload_and_extract(plans)
print(results)


# The weights:
weight = user_input['weights']
Expand All @@ -80,10 +89,8 @@ async def upload_pdfs(form_data: str = Form(...),
user_input['zip_code'] = location['zip_code']
user_input['city'] = location['city']
user_input['state'] = location['state']
user_input['household_size'] = coverage['household_size']
user_input['individual_bool'] = (coverage['household_size'] == 1)

weights = {k: v / 10 for k, v in weight.items()}
weights = {k: v/10 for k, v in weight.items()}

# The premiums:
async def process_plan(plan_name: str, plan_content: str,
Expand All @@ -105,8 +112,11 @@ async def process_plan(plan_name: str, plan_content: str,
# Run all tasks concurrently
results = await asyncio.gather(*tasks)


to_frontend = []

prompt = ""

# Store the results in the history
for name, unweighted_scores, weighted_scores, total_score, short_summary, plan_content in results:
# {'file_name': 'weighted_scores: dict, 'total_score': float, 'text': str}
Expand All @@ -118,9 +128,18 @@ async def process_plan(plan_name: str, plan_content: str,

to_frontend.append({
"name": name,
"weightedScores": unweighted_scores,
"weightedScores": weighted_scores,
"totalScore": total_score,
"shortSummary": short_summary
})
prompt += f"\n\nPlan Name: {name}\nTotal Score: {total_score}\nPlan Text: {short_summary}\n"

prompt += ("Please justify the ranking of each plan based on its strengths and weaknesses using the information above "
"Explain each plan clearly, highlighting what makes it better or worse compared to the others.\n")

session_history = chat_history.setdefault(session_id, {})
session_history["prompt"] = prompt


return to_frontend

17 changes: 5 additions & 12 deletions backend/Chatbot/chatbot.py
Original file line number Diff line number Diff line change
Expand Up @@ -6,31 +6,24 @@
load_dotenv()
api_key = os.getenv("GEMINI_API_KEY")

def get_chatbot_response(question: str, history: dict) -> str:
client = genai.Client(api_key=api_key)
# Combine plan textract stuff

combined_plans_text = ""

for key, value in history.items():
combined_plans_text += f"---\nPlan: {key}\n\n{value['text']}\n"

def get_chatbot_response(question: str, session_history: dict) -> str:
client = genai.Client(api_key=api_key)

query = session_history["prompt"]

# Prompting type
prompt = f"""You are a healthcare plan assistant. Only use the text provided to answer user questions.

Below is the text for multiple plans:
{combined_plans_text}

query += f"""You are a healthcare plan assistant. Only use the text provided to answer user questions.
Answer the following question ONLY from the text above:

Question: {question}
"""

response = client.models.generate_content(
model="gemini-2.0-flash",
contents=[prompt],
contents=[query],
)

# 5) Return the text response
Expand Down
4 changes: 4 additions & 0 deletions frontend/.gitignore
Original file line number Diff line number Diff line change
Expand Up @@ -44,3 +44,7 @@ amplifytools.xcconfig
.secret-*
**.sample
#amplify-do-not-edit-end


__pycache__/
*.pyc
4 changes: 3 additions & 1 deletion frontend/src/components/Chatbot.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -16,8 +16,10 @@ const Chatbot: React.FC<ChatbotProps> = ({messages, setMessages}) => {
setMessages((prev) => [...prev, { message: input, sender: "user" }]);

try {
// get the session id
const sessionId = localStorage.getItem("sessionId");
// Replace with your AI API (e.g., OpenAI, Rasa, Dialogflow, etc.)
const response = await fetch("http://127.0.0.1:8000/chat/message", {
const response = await fetch("http://127.0.0.1:8000/chat/message/"+sessionId, {
method: "POST",
headers: { "Content-Type": "application/json" },
body: JSON.stringify({ message: input }),
Expand Down
10 changes: 9 additions & 1 deletion frontend/src/pages/Input/Input.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -9,7 +9,7 @@ import Address from "../../components/form/Address";
import BudgetInfo from "../../components/form/BudgetInfo";
import UploadPdfs from "../../components/form/UploadPdfs";
import Rankings from "../../components/form/Rankings";
import { sendInputData } from "../sendInputAPI";
import {getSessionID, sendInputData} from "../sendInputAPI";
import {
validateContactInfo,
validateAddress,
Expand All @@ -36,6 +36,14 @@ const Input: React.FC<InputPageProps> = ({ results, setResults }) => {
}
setLoading(true);
const { files, costs, ...formDataWithoutFilesAndCosts } = formData;

setLoading(false);
setHasSubmittedInput(true);
// get session id and store it
const sessionId = await getSessionID();
localStorage.setItem("sessionId", sessionId);

// success = true, if form upload worked someone handle that..
const results = await sendInputData(
formDataWithoutFilesAndCosts,
files,
Expand Down
Loading