Skip to content

feat: implement medicine and BP handlers with clean history and intent fix#164

Open
pranjal9091 wants to merge 2 commits intoAOSSIE-Org:mainfrom
pranjal9091:fix-final-handlers-gsoc
Open

feat: implement medicine and BP handlers with clean history and intent fix#164
pranjal9091 wants to merge 2 commits intoAOSSIE-Org:mainfrom
pranjal9091:fix-final-handlers-gsoc

Conversation

@pranjal9091
Copy link

@pranjal9091 pranjal9091 commented Jan 9, 2026

Hi @bhavik-mangla ,

I have created this new clean PR to address the issues from the previous one (#157). I have completely reset the branch history to remove all accidental environment files and untracked node_modules, ensuring a clean commit with only the necessary changes.

Key Changes & Fixes:

Intent Classification: Updated agent/intent.py to correctly detect "medicine" and "blood_pressure" keywords, which were previously falling into the general intent.

AI Handlers: Registered and implemented specialized handlers for logging medicines and blood pressure readings in agent/agent.py.

Database Integration: Added SQLite logic to medicine.py and blood_pressure.py to persist user health logs.

Frontend Fixes: Resolved the "Unable to resolve module" error by adding @react-native-async-storage/async-storage and fixed the context fetching error in ChatScreen.jsx.

Testing Status: Verified on iOS Simulator. AI now correctly logs medicine (e.g., "I took 1 tablet of Iron") and BP (e.g., "My BP is 120/80") with appropriate responses.

Files Changed (6):

Backend/app.py

Backend/agent/agent.py

Backend/agent/intent.py

Backend/agent/handlers/medicine.py

Backend/agent/handlers/blood_pressure.py

Frontend/src/Screens/ChatScreen.jsx
image

Ready for review!

Summary by CodeRabbit

  • New Features

    • Medicine logging for pregnancy supplements with reminders
    • Blood pressure tracking with validation and alert messages
    • Weekly health insights report aggregating recent data
  • Improvements

    • Streamlined chat UI with persistent device identity and simpler backend calls
    • Stricter query validation and clearer error responses
    • More robust server/agent initialization and logging
  • Chores

    • Removed cache-related admin endpoints and related cache controls

✏️ Tip: You can customize this high-level summary in your review settings.

@coderabbitai
Copy link
Contributor

coderabbitai bot commented Jan 9, 2026

📝 Walkthrough

Walkthrough

Adds intent recognition and three new handlers (medicine, blood_pressure, insights), routes matching intents directly to handlers that persist to the DB, removes several cache-management methods from the agent, hardens the Flask /agent endpoint, and refactors the frontend chat screen to call the backend directly with persistent device ID.

Changes

Cohort / File(s) Summary
New handlers
Backend/agent/handlers/blood_pressure.py, Backend/agent/handlers/medicine.py, Backend/agent/handlers/insights.py
Three new handler modules added: blood pressure parsing/validation and logging; medicine intake detection and logging with adherence tips; weekly insights aggregation from DB. Each exposes handle(query, user_context) and includes DB interactions and error handling.
Agent core & intent
Backend/agent/agent.py, Backend/agent/intent.py
Intent classification extended for medicine, blood_pressure, and get_insights. Agent run now logs intent, delegates recognized public intents directly to handlers using user_context, falls back to vector-store context + LLM otherwise. Removed public cache-management methods (update_cache, invalidate_cache, refresh_cache_and_embeddings, get_cache_stats, cleanup_cache).
Backend API
Backend/app.py
/agent endpoint hardened to require JSON string query, adds idempotent agent/db initialization with logging and unified error responses; several auxiliary endpoints removed.
Frontend chat UI
Frontend/src/Screens/ChatScreen.jsx
Large refactor to a self-contained chat screen: base URL validation, persistent device ID via AsyncStorage, simplified local state for conversation and generation, direct POSTs to /agent with timeout/retries, Markdown rendering, and a minimal FlatList-based UI.

Sequence Diagram(s)

sequenceDiagram
    participant User
    participant Frontend as ChatScreen
    participant Backend as Flask/Agent
    participant Intent as IntentClassifier
    participant Handler as SpecializedHandler
    participant DB as Database

    User->>Frontend: Send message (query)
    Frontend->>Backend: POST /agent { query, user_id, user_context }
    Backend->>Intent: classify_intent(query)
    Intent-->>Backend: returns intent
    alt intent in {medicine,blood_pressure,get_insights}
        Backend->>Handler: dispatch handler.handle(query, user_context)
        Handler->>DB: open_db() / insert/select relevant tables
        DB-->>Handler: success/failure
        Handler-->>Backend: response message
    else other intent
        Backend->>DB: retrieve vector-store / context for user
        Backend->>Backend: build LLM prompt with context + user_context
        Backend-->>Frontend: LLM response
    end
    Backend-->>Frontend: handler or LLM result
    Frontend->>User: render assistant response
Loading

Estimated code review effort

🎯 4 (Complex) | ⏱️ ~50 minutes

Possibly related PRs

Poem

🐰 I hopped in with a clever plan,

Logged pulses and the vitamin can.
Intents now find their proper nest,
DBs record each health request.
A little hop for data cheer—well done, my human friend!

🚥 Pre-merge checks | ✅ 2 | ❌ 1
❌ Failed checks (1 warning)
Check name Status Explanation Resolution
Docstring Coverage ⚠️ Warning Docstring coverage is 37.50% which is insufficient. The required threshold is 80.00%. Write docstrings for the functions missing them to satisfy the coverage threshold.
✅ Passed checks (2 passed)
Check name Status Explanation
Description Check ✅ Passed Check skipped - CodeRabbit’s high-level summary is enabled.
Title check ✅ Passed The title accurately summarizes the main changes: implementing medicine and BP handlers and fixing intent classification, which are the core features in this PR.

✏️ Tip: You can configure your own custom pre-merge checks in the settings.

✨ Finishing touches
  • 📝 Generate docstrings

Thanks for using CodeRabbit! It's free for OSS, and your support helps us grow. If you like it, consider giving us a shout-out.

❤️ Share

Comment @coderabbitai help to get the list of available commands and usage tips.

Copy link
Contributor

@coderabbitai coderabbitai bot left a comment

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Actionable comments posted: 6

🤖 Fix all issues with AI agents
In @Backend/agent/handlers/blood_pressure.py:
- Around line 10-11: The handler in blood_pressure.py opens the Flask
request-scoped DB via open_db() and then calls db.close() in the finally block,
which will break further DB operations in the same request; remove the explicit
db.close() calls (the finally block or lines that call db.close()) so the Flask
g-scoped connection lifecycle (open_db()/teardown) manages closing
automatically—update the functions that call open_db() in this module to stop
closing the connection explicitly.
- Line 23: The code reads week = user_context.get('week_number', 1') but the
context uses the key 'current_week'; update the lookup to use
user_context.get('current_week', 1) (adjust any variable name 'week' usages
accordingly) so the handler reads the actual week value from the same key used
elsewhere (refer to the 'week' assignment and 'user_context' usage in
blood_pressure.py).

In @Backend/agent/handlers/medicine.py:
- Around line 10-11: The handler calls open_db() and then explicitly calls
db.close(), which closes the Flask request-scoped connection stored on g and
leaves g.db pointing to a closed connection; remove the explicit db.close() (and
any finally block that calls it) from the functions in medicine.py so the
connection lifecycle is managed by Flask; ensure the application has a teardown
handler (e.g. a @app.teardown_appcontext function in db/db.py that closes g.db)
and reference open_db, g.db, and the teardown_appcontext handler when making
this change.
- Line 22: The handler is reading the wrong context key; replace the use of
'week_number' with 'current_week' in the code that sets week (currently "week =
user_context.get('week_number', 1)") so it pulls the agent-provided value; keep
the same default fallback (1) and update any references in the same function
(e.g., the handler in medicine.py that assigns week) to use 'current_week' to
ensure the correct week is used.

In @Backend/agent/intent.py:
- Around line 13-14: The branch that returns "medicine" currently triggers on
the generic token "took", which causes false positives; update the condition in
the intent detection (the elif that returns "medicine") to either remove the
standalone "took" check or require it to match a medicine context (e.g., use a
regex like r"\btook (a )?(pill|tablet|dose|medicine|medication)\b" or require
both "took" and a medicine keyword present), so the intent only fires when
"took" appears with a medication-related word.
- Around line 15-16: The current condition checking `elif "bp" in query or
"blood pressure" in query or "/" in query` is too broad and causes false
positives and misordering with the `medicine` intent; import the `re` module,
replace the `"/"` check with a regex that matches numeric BP formats (e.g., use
re.search for a pattern like r'\b\d{2,3}/\d{2,3}\b' to detect readings such as
"120/80") in the `elif "bp" in query or "blood pressure" in query ...` branch
that returns "blood_pressure", and move this blood_pressure check to run before
the branch that returns "medicine" so inputs like "I took my BP 120/80" are
classified as "blood_pressure".
🧹 Nitpick comments (4)
Backend/agent/handlers/medicine.py (1)

30-33: Minor: Use f-string conversion flag for consistency.

Per static analysis, prefer {e!s} over str(e) for consistency with modern Python idioms. The broad Exception catch is acceptable here as a safety net.

Suggested fix
     except sqlite3.Error as e:
-        return f"Database error: {str(e)}"
+        return f"Database error: {e!s}"
     except Exception as e:
-        return f"Unexpected error: {str(e)}"
+        return f"Unexpected error: {e!s}"
Frontend/src/Screens/ChatScreen.jsx (3)

36-48: substr is deprecated; use substring or slice instead.

String.prototype.substr is deprecated. Use substring or slice for better compatibility.

Proposed fix
-          id = `user-${Date.now()}-${Math.random().toString(36).substr(2, 9)}`;
+          id = `user-${Date.now()}-${Math.random().toString(36).slice(2, 11)}`;

62-69: Consider logging or handling non-2xx responses for debugging.

When response.ok is false, the function silently returns null, losing valuable error information. Consider logging the status code or error response body for debugging purposes.

Suggested improvement
       if (response.ok) {
         const data = await response.json();
         return data.response;
       }
+      console.warn(`Backend returned ${response.status}`);
       return null;

88-93: Same substr deprecation issue.

Apply the same fix as the user ID generation.

Proposed fix
     const userMessage = { 
-      id: `${Date.now()}-${Math.random().toString(36).substr(2, 4)}`, 
+      id: `${Date.now()}-${Math.random().toString(36).slice(2, 6)}`, 
       role: "user", 
       content: trimmedInput 
     };
📜 Review details

Configuration used: defaults

Review profile: CHILL

Plan: Pro

📥 Commits

Reviewing files that changed from the base of the PR and between 8893922 and 88aa884.

📒 Files selected for processing (6)
  • Backend/agent/agent.py
  • Backend/agent/handlers/blood_pressure.py
  • Backend/agent/handlers/medicine.py
  • Backend/agent/intent.py
  • Backend/app.py
  • Frontend/src/Screens/ChatScreen.jsx
🧰 Additional context used
🧬 Code graph analysis (4)
Backend/agent/handlers/blood_pressure.py (2)
Backend/db/db.py (1)
  • open_db (8-13)
Backend/agent/handlers/medicine.py (1)
  • handle (5-35)
Backend/agent/agent.py (7)
Backend/agent/handlers/blood_pressure.py (1)
  • handle (5-37)
Backend/agent/handlers/medicine.py (1)
  • handle (5-35)
Backend/agent/handlers/guidelines.py (1)
  • handle (3-28)
Backend/agent/vector_store.py (2)
  • register_vector_store_updater (27-29)
  • update_guidelines_in_vector_store (40-102)
Backend/agent/intent.py (1)
  • classify_intent (2-19)
Backend/agent/context.py (1)
  • get_relevant_context_from_vector_store (58-75)
Backend/agent/prompt.py (1)
  • build_prompt (1-52)
Backend/agent/handlers/medicine.py (3)
Backend/db/db.py (1)
  • open_db (8-13)
Backend/agent/handlers/blood_pressure.py (1)
  • handle (5-37)
Frontend/src/Screens/MedicineScreen.jsx (2)
  • name (17-17)
  • dose (18-18)
Backend/app.py (2)
Backend/db/db.py (1)
  • first_time_setup (20-25)
Backend/agent/agent.py (2)
  • get_agent (59-63)
  • run (39-56)
🪛 Ruff (0.14.10)
Backend/agent/handlers/blood_pressure.py

31-31: Consider moving this statement to an else block

(TRY300)


33-33: Use explicit conversion flag

Replace with conversion flag

(RUF010)


34-34: Do not catch blind exception: Exception

(BLE001)


35-35: Use explicit conversion flag

Replace with conversion flag

(RUF010)

Backend/agent/handlers/medicine.py

29-29: Consider moving this statement to an else block

(TRY300)


31-31: Use explicit conversion flag

Replace with conversion flag

(RUF010)


32-32: Do not catch blind exception: Exception

(BLE001)


33-33: Use explicit conversion flag

Replace with conversion flag

(RUF010)

🔇 Additional comments (9)
Backend/app.py (3)

41-58: LGTM!

The /agent endpoint has proper request validation, type checking for the query, and appropriate error handling with logging. The default user_id provides backward compatibility.


60-62: LGTM!

Good practice binding to 127.0.0.1 and deriving debug mode from the FLASK_DEBUG environment variable.


32-39: No action needed. The initialization code is safe and does not require Flask application context.

The first_time_setup() function uses direct sqlite3.connect() instead of Flask's g object, and get_agent() only instantiates the agent with the database path without accessing Flask's context. The open_db() function (which does use g) is called within request handlers, where Flask context is available.

Backend/agent/handlers/blood_pressure.py (1)

13-21: LGTM!

The regex pattern correctly handles common BP input formats, and the validation ranges are reasonable for blood pressure readings.

Frontend/src/Screens/ChatScreen.jsx (2)

14-22: LGTM!

Good defensive URL validation with a sensible localhost fallback. The try-catch handles malformed URLs gracefully.


140-186: LGTM!

The UI implementation properly integrates theming, handles keyboard behavior for both platforms, and provides a clean chat interface.

Backend/agent/agent.py (3)

16-17: LGTM!

The new medicine and blood pressure handlers are properly imported and registered in the dispatch dictionary. The intent-to-handler mapping is consistent with the intent classification in intent.py.

Also applies to: 26-27


39-56: LGTM!

The run method has good defensive programming with context fallback, helpful intent logging for debugging, and proper exception handling that captures the full traceback.


58-63: LGTM!

Standard singleton pattern for agent initialization.

Comment on lines +13 to +14
elif "medicine" in query or "took" in query or "tablet" in query or "pill" in query:
return "medicine"
Copy link
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

⚠️ Potential issue | 🟡 Minor

The keyword "took" is too generic and may cause false positives.

The word "took" appears in many non-medicine contexts (e.g., "I took a walk", "I took notes"). Consider requiring a combination of keywords or using a regex pattern that looks for medicine-related context.

Suggested improvement
-    elif "medicine" in query or "took" in query or "tablet" in query or "pill" in query:
+    elif "medicine" in query or "tablet" in query or "pill" in query or ("took" in query and any(kw in query for kw in ["mg", "tablet", "pill", "capsule", "dose"])):
         return "medicine"
📝 Committable suggestion

‼️ IMPORTANT
Carefully review the code before committing. Ensure that it accurately replaces the highlighted code, contains no missing lines, and has no issues with indentation. Thoroughly test & benchmark the code to ensure it meets the requirements.

Suggested change
elif "medicine" in query or "took" in query or "tablet" in query or "pill" in query:
return "medicine"
elif "medicine" in query or "tablet" in query or "pill" in query or ("took" in query and any(kw in query for kw in ["mg", "tablet", "pill", "capsule", "dose"])):
return "medicine"
🤖 Prompt for AI Agents
In @Backend/agent/intent.py around lines 13 - 14, The branch that returns
"medicine" currently triggers on the generic token "took", which causes false
positives; update the condition in the intent detection (the elif that returns
"medicine") to either remove the standalone "took" check or require it to match
a medicine context (e.g., use a regex like r"\btook (a
)?(pill|tablet|dose|medicine|medication)\b" or require both "took" and a
medicine keyword present), so the intent only fires when "took" appears with a
medication-related word.

Comment on lines +15 to +16
elif "bp" in query or "blood pressure" in query or "/" in query:
return "blood_pressure"
Copy link
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

⚠️ Potential issue | 🟠 Major

Overly broad "/" pattern will cause false positives.

The "/" character alone as a trigger for blood_pressure intent will match URLs, date formats (e.g., "1/2/2026"), file paths, and fractions. This could misclassify many unrelated queries.

Additionally, the ordering creates an issue: a query like "I took my BP 120/80" would be classified as "medicine" (due to "took") rather than "blood_pressure".

Proposed fix: Use a more specific BP pattern
-    elif "bp" in query or "blood pressure" in query or "/" in query:
+    elif "bp" in query or "blood pressure" in query or re.search(r'\d{2,3}\s*/\s*\d{2,3}', query):
         return "blood_pressure"

This requires adding import re at the top of the file. The pattern specifically matches numeric BP readings like "120/80".

Committable suggestion skipped: line range outside the PR's diff.

🤖 Prompt for AI Agents
In @Backend/agent/intent.py around lines 15 - 16, The current condition checking
`elif "bp" in query or "blood pressure" in query or "/" in query` is too broad
and causes false positives and misordering with the `medicine` intent; import
the `re` module, replace the `"/"` check with a regex that matches numeric BP
formats (e.g., use re.search for a pattern like r'\b\d{2,3}/\d{2,3}\b' to detect
readings such as "120/80") in the `elif "bp" in query or "blood pressure" in
query ...` branch that returns "blood_pressure", and move this blood_pressure
check to run before the branch that returns "medicine" so inputs like "I took my
BP 120/80" are classified as "blood_pressure".

Copy link
Contributor

@coderabbitai coderabbitai bot left a comment

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Actionable comments posted: 5

🤖 Fix all issues with AI agents
In @Backend/agent/handlers/blood_pressure.py:
- Line 24: The handler is reading the wrong context key ('week_number') so it
always defaults to 1; update the user_context lookups to use 'current_week'
instead: change the assignment that uses user_context.get('week_number', 1) to
user_context.get('current_week', 1) in the blood_pressure handler and apply the
same change in the medicine and insights handlers so all handlers use the same
'current_week' key as the agent and prompt builder.

In @Backend/agent/handlers/insights.py:
- Line 12: The handler reads the wrong context key; change the user_context
lookup in insights.py from user_context.get('week_number', 1) to
user_context.get('current_week', 1) (keeping the local variable name `week` or
rename to `current_week` if you prefer) so it matches the other handlers and
uses the `current_week` key consistently when extracting the week value from
`user_context`.
- Around line 33-34: The current computation of avg_sys and avg_dia uses integer
division which truncates precision; change the calculations to use float
division (replace // with /) when computing averages from bp_rows in the
insights handler (avg_sys, avg_dia computed from bp_rows), and update any
response formatting that expects integers to preserve or round decimals (e.g.,
round to one or two decimal places) so the returned BP averages maintain
required medical precision.

In @Backend/agent/handlers/medicine.py:
- Line 19: The code reads the week from the wrong context key: change
user_context.get('week_number', 1) to user_context.get('current_week', 1) so the
handler in medicine.py uses the same context key as the blood_pressure handler;
update any dependent uses of the local variable week if they assume the new key
but no further logic changes are required.
🧹 Nitpick comments (4)
Backend/agent/handlers/blood_pressure.py (1)

46-49: Use explicit string conversion for consistency.

Consider using f-string conversion flags for consistency with modern Python style.

✨ Proposed style improvement
     except sqlite3.Error as e:
-        return f"Database error: {str(e)}"
+        return f"Database error: {e!s}"
     except Exception as e:
-        return f"Unexpected error: {str(e)}"
+        return f"Unexpected error: {e!s}"
Backend/agent/handlers/medicine.py (1)

2-2: Remove unused import.

The datetime import is not used in this file.

♻️ Proposed fix
-from datetime import datetime
 from db.db import open_db
Backend/agent/handlers/insights.py (2)

2-2: Remove unused import.

The timedelta import is not used in this file.

♻️ Proposed fix
-from datetime import datetime, timedelta
+from datetime import datetime
 from db.db import open_db

5-5: Remove unused parameter or utilize it for filtering.

The query parameter is not used in the function. Either remove it to match the handler signature, or consider using it to filter insights (e.g., "show me my BP insights").

📜 Review details

Configuration used: defaults

Review profile: CHILL

Plan: Pro

📥 Commits

Reviewing files that changed from the base of the PR and between 88aa884 and 9907e99.

📒 Files selected for processing (5)
  • Backend/agent/agent.py
  • Backend/agent/handlers/blood_pressure.py
  • Backend/agent/handlers/insights.py
  • Backend/agent/handlers/medicine.py
  • Backend/agent/intent.py
🚧 Files skipped from review as they are similar to previous changes (1)
  • Backend/agent/intent.py
🧰 Additional context used
🧬 Code graph analysis (2)
Backend/agent/handlers/insights.py (3)
Backend/db/db.py (1)
  • open_db (8-13)
Backend/agent/handlers/blood_pressure.py (1)
  • handle (5-51)
Backend/agent/handlers/medicine.py (1)
  • handle (5-44)
Backend/agent/agent.py (9)
Backend/agent/context.py (1)
  • get_relevant_context_from_vector_store (58-75)
Backend/agent/intent.py (1)
  • classify_intent (1-23)
Backend/agent/llm.py (1)
  • run_llm (1-38)
Backend/agent/prompt.py (1)
  • build_prompt (1-52)
Backend/agent/cache.py (2)
  • get_context_cache (523-530)
  • get_context (170-196)
Backend/agent/handlers/blood_pressure.py (1)
  • handle (5-51)
Backend/agent/handlers/medicine.py (1)
  • handle (5-44)
Backend/agent/handlers/guidelines.py (1)
  • handle (3-28)
Backend/agent/vector_store.py (1)
  • update_guidelines_in_vector_store (40-102)
🪛 Ruff (0.14.10)
Backend/agent/handlers/insights.py

5-5: Unused function argument: query

(ARG001)


54-54: Consider moving this statement to an else block

(TRY300)


56-56: Do not catch blind exception: Exception

(BLE001)


57-57: Use explicit conversion flag

Replace with conversion flag

(RUF010)

Backend/agent/handlers/medicine.py

37-37: Consider moving this statement to an else block

(TRY300)


40-40: Use explicit conversion flag

Replace with conversion flag

(RUF010)


41-41: Do not catch blind exception: Exception

(BLE001)


42-42: Use explicit conversion flag

Replace with conversion flag

(RUF010)

Backend/agent/handlers/blood_pressure.py

47-47: Use explicit conversion flag

Replace with conversion flag

(RUF010)


48-48: Do not catch blind exception: Exception

(BLE001)


49-49: Use explicit conversion flag

Replace with conversion flag

(RUF010)

🔇 Additional comments (7)
Backend/agent/handlers/blood_pressure.py (1)

13-22: BP parsing and validation implemented correctly.

The regex pattern supports multiple BP formats (/, over, -) and physiological range validation provides good defensive programming.

Backend/agent/handlers/medicine.py (2)

13-26: Medicine identification and logging logic implemented correctly.

The approach of matching known pregnancy supplements (iron, folic acid, calcium) with a fallback to "medicine" is sensible and defensive.


29-35: Excellent proactive reminder feature.

The logic to remind users about missing medications enhances user experience and promotes better adherence to pregnancy supplement regimens.

Backend/agent/handlers/insights.py (1)

14-52: Insights aggregation logic is well-structured.

The 7-day lookback window, adherence percentage calculation, and formatted response provide valuable health summary information.

Backend/agent/agent.py (3)

17-18: New handler integrations implemented correctly.

The medicine and blood_pressure handlers are properly imported and registered in the dispatch dictionary, along with the get_insights intent.

Also applies to: 27-29


46-46: Default context structure is correct.

Line 46 correctly uses current_week as the context key. This is the authoritative structure that the handlers should follow. Note that the handlers are currently using week_number instead, which needs to be fixed (see comments in the handler files).


48-48: Logging improvements enhance observability.

The addition of intent logging and structured exception logging will help with debugging and monitoring agent behavior.

Also applies to: 57-58

if not (70 <= systolic <= 250 and 40 <= diastolic <= 150):
return "BP values out of valid range. Please check and try again."

week = user_context.get('week_number', 1)
Copy link
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

⚠️ Potential issue | 🔴 Critical

Critical: Inconsistent user context key across handlers.

Line 24 uses week_number but the agent (Backend/agent/agent.py line 46) provides current_week in the default context, and the prompt builder (Backend/agent/prompt.py) also expects current_week. This mismatch will cause the week to always default to 1.

🔧 Proposed fix for context key consistency
-        week = user_context.get('week_number', 1)
+        week = user_context.get('current_week', 1)

Apply the same fix to Backend/agent/handlers/medicine.py line 19 and Backend/agent/handlers/insights.py line 12.

📝 Committable suggestion

‼️ IMPORTANT
Carefully review the code before committing. Ensure that it accurately replaces the highlighted code, contains no missing lines, and has no issues with indentation. Thoroughly test & benchmark the code to ensure it meets the requirements.

Suggested change
week = user_context.get('week_number', 1)
week = user_context.get('current_week', 1)
🤖 Prompt for AI Agents
In @Backend/agent/handlers/blood_pressure.py at line 24, The handler is reading
the wrong context key ('week_number') so it always defaults to 1; update the
user_context lookups to use 'current_week' instead: change the assignment that
uses user_context.get('week_number', 1) to user_context.get('current_week', 1)
in the blood_pressure handler and apply the same change in the medicine and
insights handlers so all handlers use the same 'current_week' key as the agent
and prompt builder.

Comment on lines +35 to +44
if systolic >= 140 or diastolic >= 90:
return (f"🚨 **URGENT ALERT**: Your BP is {systolic}/{diastolic}. This is classified as High Blood Pressure (Hypertension). "
"In pregnancy, this requires immediate attention. Please rest and **contact your doctor right away**.")

elif systolic <= 90 or diastolic <= 60:
return (f"⚠️ **WARNING**: Your BP is {systolic}/{diastolic}, which is low. "
"Ensure you are hydrated and notify your healthcare provider if you feel faint.")

else:
return f"✅ Recorded BP: {systolic}/{diastolic} for week {week}. Your reading is within the healthy range."
Copy link
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

⚠️ Potential issue | 🟡 Minor

🧩 Analysis chain

🌐 Web query:

pregnancy-induced hypertension PIH blood pressure thresholds guidelines ACOG 2024

💡 Result:

Short answer — ACOG (current guidance) uses 140/90 mm Hg as the treatment/initiation threshold for chronic hypertension in pregnancy (based on the CHAP trial guidance) and retains ≥160/110 mm Hg as the definition of severe (acute) maternal hypertension that requires immediate evaluation/treatment. See ACOG acute‑hypertension/preeclampsia algorithms and related practice guidance for management details. [1][2][3]

Sources

  • ACOG Practice Advisory: integration of CHAP study — treat chronic hypertension in pregnancy at threshold 140/90 mm Hg (reaffirmed). [1]
  • ACOG Acute Hypertension in Pregnancy & Postpartum algorithm — defines severe/urgent BP ≥160/110 mm Hg and gives management steps. [2]
  • ACOG Practice Bulletin (gestational hypertension/preeclampsia) — defines severe range as ≥160/110 and diagnostic criteria. [3]

🌐 Web query:

low blood pressure hypotension pregnancy threshold systolic 90 diastolic 60 guidelines

💡 Result:

Short answer: Major obstetric guidelines do not define a fixed numeric "hypotension" cutoff for pregnancy the way they do for hypertension. Clinically, values around <90/60 mmHg are commonly used as a practical threshold for low blood pressure, but trials and observational studies often use slightly different cutoffs (for example persistent SBP <100 mmHg and/or DBP <60 mmHg). Symptoms, hemodynamic instability, and fetal concerns determine evaluation and treatment rather than a single universal number. (acog.org)

Key points:

  • ACOG and major pregnancy guidelines emphasize thresholds for hypertension (e.g., ≥140/90 mmHg) and severe hypertension (≥160/110 mmHg) but do not set a formal numeric definition for maternal hypotension in routine pregnancy care. (acog.org)
  • Practical/common clinical threshold: <90/60 mmHg is widely used to label blood pressure as "low"; persistent values (study examples: SBP <100 mmHg or DBP <60 mmHg) have been studied for associations with uteroplacental blood‑flow changes. Symptoms and persistence matter. (pregnancybirthbaby.org.au)
  • Management depends on symptoms (dizziness, syncope), cause (volume depletion, vasodilation, medications, sepsis, hemorrhage), fetal status, and hemodynamic signs — not a single numeric cutoff. For any symptomatic or persistent low BP in pregnancy, contact obstetric care promptly. (pmc.ncbi.nlm.nih.gov)

If you’d like, I can pull specific guideline text or studies (PDFs) and list exact numeric cutoffs used in research or provide management steps for symptomatic hypotension.

Citations:


Clarify BP alert thresholds and align with ACOG severity definitions.

The high BP threshold (140/90 mmHg) aligns with ACOG's chronic hypertension treatment threshold but not acute hypertension. ACOG defines ≥160/110 mmHg as severe/urgent hypertension requiring immediate evaluation—yet the code labels 140/90 as "URGENT ALERT," which overstates the severity. The low BP threshold (≤90/60 mmHg) lacks formal ACOG guidance; clinically, <90/60 is used as a practical marker, but guidelines emphasize that symptoms, persistence, and clinical context should guide evaluation rather than numeric cutoffs alone.

Consider:

  • Distinguishing between chronic hypertension (≥140/90) and acute severe hypertension (≥160/110) in alerts
  • Noting that low BP evaluation depends on symptoms and persistence, not the numeric threshold alone
  • Removing the "URGENT" framing from the 140/90 alert or reserving it for ≥160/110

"""
db = open_db()
try:
week = user_context.get('week_number', 1)
Copy link
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

⚠️ Potential issue | 🔴 Critical

Critical: Same context key inconsistency.

This line has the same issue as the other handlers. Use current_week instead of week_number.

🤖 Prompt for AI Agents
In @Backend/agent/handlers/insights.py at line 12, The handler reads the wrong
context key; change the user_context lookup in insights.py from
user_context.get('week_number', 1) to user_context.get('current_week', 1)
(keeping the local variable name `week` or rename to `current_week` if you
prefer) so it matches the other handlers and uses the `current_week` key
consistently when extracting the week value from `user_context`.

Comment on lines +33 to +34
avg_sys = sum(r[0] for r in bp_rows) // len(bp_rows)
avg_dia = sum(r[1] for r in bp_rows) // len(bp_rows)
Copy link
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

🛠️ Refactor suggestion | 🟠 Major

Use float division for precise BP averages.

Integer division (//) truncates decimal values, which could hide important variations in BP readings. For medical data, precision matters.

📊 Proposed fix for precision
-            avg_sys = sum(r[0] for r in bp_rows) // len(bp_rows)
-            avg_dia = sum(r[1] for r in bp_rows) // len(bp_rows)
+            avg_sys = round(sum(r[0] for r in bp_rows) / len(bp_rows), 1)
+            avg_dia = round(sum(r[1] for r in bp_rows) / len(bp_rows), 1)

Update the response format to handle float values:

-            f"🩺 **Blood Pressure:** Avg {avg_sys}/{avg_dia} mmHg\n"
+            f"🩺 **Blood Pressure:** Avg {avg_sys:.1f}/{avg_dia:.1f} mmHg\n"
🤖 Prompt for AI Agents
In @Backend/agent/handlers/insights.py around lines 33 - 34, The current
computation of avg_sys and avg_dia uses integer division which truncates
precision; change the calculations to use float division (replace // with /)
when computing averages from bp_rows in the insights handler (avg_sys, avg_dia
computed from bp_rows), and update any response formatting that expects integers
to preserve or round decimals (e.g., round to one or two decimal places) so the
returned BP averages maintain required medical precision.

# Identify which medicine the user is logging
logged_med = next((med for med in required_meds if med in query_lower), "medicine")

week = user_context.get('week_number', 1)
Copy link
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

⚠️ Potential issue | 🔴 Critical

Critical: Same context key inconsistency.

This line has the same issue as Backend/agent/handlers/blood_pressure.py line 24. Use current_week instead of week_number to match the context structure provided by the agent.

🤖 Prompt for AI Agents
In @Backend/agent/handlers/medicine.py at line 19, The code reads the week from
the wrong context key: change user_context.get('week_number', 1) to
user_context.get('current_week', 1) so the handler in medicine.py uses the same
context key as the blood_pressure handler; update any dependent uses of the
local variable week if they assume the new key but no further logic changes are
required.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

1 participant