Skip to content

Commit 13af2f8

Browse files
authored
Merge branch 'main' into release/v0.1.5
2 parents 7489ef3 + 5c738cd commit 13af2f8

3 files changed

Lines changed: 51 additions & 56 deletions

File tree

‎app/database/db.py‎

Lines changed: 14 additions & 21 deletions
Original file line numberDiff line numberDiff line change
@@ -26,27 +26,11 @@
2626

2727
async def get_user_by_waid(wa_id: str) -> Optional[User]:
2828
"""
29-
Get user by WhatsApp ID with basic relationships loaded.
30-
"""
31-
async with get_session() as session:
32-
try:
33-
# Load only taught_classes, without nested relationships
34-
statement = (
35-
select(User)
36-
.where(User.wa_id == wa_id)
37-
.options(selectinload(User.taught_classes)) # type: ignore
38-
)
39-
result = await session.execute(statement)
40-
return result.scalar_one_or_none()
41-
except Exception as e:
42-
logger.error(f"Failed to query user {wa_id}: {str(e)}")
43-
raise Exception(f"Failed to query user: {str(e)}")
29+
Get user by WhatsApp ID with FULL class hierarchy loaded.
30+
Always loads: User -> taught_classes -> class_ -> subject_
4431
45-
46-
async def get_user_by_waid_with_classes(wa_id: str) -> Optional[User]:
47-
"""
48-
Get user by WhatsApp ID with full class hierarchy loaded.
49-
Loads: User -> taught_classes -> class_ -> subject_
32+
This is the ONLY method to fetch users - it loads everything needed.
33+
All data is loaded while the session is open, then returned from memory.
5034
"""
5135
async with get_session() as session:
5236
try:
@@ -61,7 +45,16 @@ async def get_user_by_waid_with_classes(wa_id: str) -> Optional[User]:
6145
)
6246
)
6347
result = await session.execute(statement)
64-
return result.scalar_one_or_none()
48+
user = result.scalar_one_or_none()
49+
50+
# Access relationships to trigger loading while session is still open
51+
if user and user.taught_classes:
52+
for tc in user.taught_classes:
53+
# Access attributes to ensure they're loaded
54+
_ = tc.class_id
55+
_ = tc.teacher_id
56+
57+
return user
6558
except Exception as e:
6659
logger.error(f"Failed to query user {wa_id}: {str(e)}")
6760
raise Exception(f"Failed to query user: {str(e)}")

‎app/services/messaging_service.py‎

Lines changed: 16 additions & 5 deletions
Original file line numberDiff line numberDiff line change
@@ -42,11 +42,20 @@
4242
r"\\gamma|\\pi|\\theta|\\[|\\]|\\(|\\)|\$)"
4343
)
4444

45-
LATEX_CONVERTER_SYSTEM_PROMPT = (
46-
"You are a conversion assistant. Rewrite any provided content as valid LaTeX "
47-
"that can be inserted inside a document body. Do not include markdown, "
48-
"preambles, explanations, or surrounding fences—only the LaTeX content."
49-
)
45+
LATEX_CONVERTER_SYSTEM_PROMPT = """
46+
You are a LaTeX transcriber.
47+
48+
Task: Convert the user's input into LaTeX that can be inserted inside a document body.
49+
50+
Hard rules:
51+
- Do NOT solve, answer, explain, or add any new content.
52+
- Do NOT remove any content.
53+
- Preserve the original meaning, order, and intent exactly.
54+
- If the input contains questions or instructions, keep them as text.
55+
- Only convert formatting to LaTeX (e.g., headings -> \section, lists -> itemize).
56+
- Keep all numbers, math expressions, and wording unchanged except for required LaTeX syntax.
57+
- Output ONLY LaTeX. No markdown, no preamble, no commentary.
58+
"""
5059

5160
LATEX_TEMPLATE = r"""
5261
\documentclass[11pt]{article}
@@ -87,6 +96,7 @@ async def convert_text_to_latex(content: str) -> str | None:
8796
tools=None,
8897
tool_choice=None,
8998
run_name="latex_conversion",
99+
temperature=0.0,
90100
metadata={"phase": "latex_conversion"},
91101
)
92102
except Exception as exc:
@@ -220,6 +230,7 @@ async def handle_chat_message(
220230
# TODO: all this part must be improved. Main goal is to avoid the extra LLM call.
221231
if looks_like_latex(llm_content):
222232
latex_ready_content = await convert_text_to_latex(llm_content)
233+
223234
if latex_ready_content is None:
224235
self.logger.warning(
225236
"Latex conversion returned empty result; using original content."

‎app/services/request_service.py‎

Lines changed: 21 additions & 30 deletions
Original file line numberDiff line numberDiff line change
@@ -24,7 +24,6 @@ async def handle_request(request: Request) -> JSONResponse:
2424
Handles HTTP requests to the 'webhooks' and 'flows' endpoints.
2525
"""
2626
try:
27-
2827
body = await request.json()
2928

3029
request_type = get_request_type(body)
@@ -67,23 +66,30 @@ async def handle_valid_message(body: dict) -> JSONResponse:
6766
# Extract message information
6867
message_info = extract_message_info(body)
6968

70-
message = extract_message(message_info.get("message") or {})
69+
message_content = extract_message(message_info.get("message") or {})
7170

72-
if not message:
71+
if not message_content:
7372
logger.warning("Empty message received")
7473
return JSONResponse(
7574
content={"status": "error", "message": "Invalid message"},
7675
status_code=400,
7776
)
7877

78+
# Store extracted message content in message_info for use downstream
79+
message_info["extracted_content"] = message_content
80+
7981
# Main message routing logic
8082
return await handle_chat_message(message_info["wa_id"], message_info)
8183

8284

8385
async def handle_chat_message(phone_number: str, message_info: dict) -> JSONResponse:
84-
"""Main entry point for handling all valid WhatsApp messages based on user state"""
86+
"""Main entry point for handling all valid WhatsApp messages based on user state
8587
86-
# Try to get existing user
88+
Fetch all data upfront with one method.
89+
All data is loaded while session is open, then used from memory.
90+
"""
91+
92+
# Fetch user with FULL data (one method does everything)
8793
user = await db.get_user_by_waid(phone_number)
8894

8995
if not user:
@@ -101,19 +107,18 @@ async def handle_chat_message(phone_number: str, message_info: dict) -> JSONResp
101107
match user.state:
102108
case enums.UserState.blocked:
103109
return await state_client.handle_blocked(user)
104-
case enums.UserState.in_review: # Handle registered but unapproved users
110+
111+
case enums.UserState.in_review:
105112
return await state_client.handle_in_review_user(user)
113+
106114
case enums.UserState.approved:
107115
# Users approved by dashboard - send welcome message and transition to onboarding
108-
# Persist the triggering user message but don't process it
109116
assert user.id is not None
110117
await db.create_new_message(
111118
models.Message(
112119
user_id=user.id,
113120
role=enums.MessageRole.user,
114-
content=message_info.get("message", {})
115-
.get("text", {})
116-
.get("body", ""),
121+
content=message_info.get("extracted_content", ""),
117122
)
118123
)
119124

@@ -122,21 +127,18 @@ async def handle_chat_message(phone_number: str, message_info: dict) -> JSONResp
122127
return welcome_response
123128

124129
case enums.UserState.inactive:
125-
# Users who haven't been active - reactivate them then process normally
130+
# Reactivate user
126131
reactivate_response = await state_client.handle_inactive_user(user)
127132
if reactivate_response.status_code != 200:
128133
return reactivate_response
129134

130-
# User is now active, process their message normally
131-
# Create user message record
135+
# Process their message
132136
assert user.id is not None
133137
user_message = await db.create_new_message(
134138
models.Message(
135139
user_id=user.id,
136140
role=enums.MessageRole.user,
137-
content=message_info.get("message", {})
138-
.get("text", {})
139-
.get("body", ""),
141+
content=message_info.get("extracted_content", ""),
140142
)
141143
)
142144
return await state_client.handle_active(user, message_info, user_message)
@@ -148,33 +150,22 @@ async def handle_chat_message(phone_number: str, message_info: dict) -> JSONResp
148150
models.Message(
149151
user_id=user.id,
150152
role=enums.MessageRole.user,
151-
content=message_info.get("message", {})
152-
.get("text", {})
153-
.get("body", ""),
153+
content=message_info.get("extracted_content", ""),
154154
)
155155
)
156156
return await state_client.handle_onboarding(user)
157157

158158
case enums.UserState.active:
159-
# Reload user with full class information for LLM processing
160-
user = await db.get_user_by_waid_with_classes(phone_number)
161-
162-
if not user:
163-
logger.error(f"User {phone_number} not found on reload (should exist)")
164-
return JSONResponse(content={"status": "error"}, status_code=500)
165-
166-
# Create user message record
167159
assert user.id is not None
168160
user_message = await db.create_new_message(
169161
models.Message(
170162
user_id=user.id,
171163
role=enums.MessageRole.user,
172-
content=message_info.get("message", {})
173-
.get("text", {})
174-
.get("body", ""),
164+
content=message_info.get("extracted_content", ""),
175165
)
176166
)
177167
return await state_client.handle_active(user, message_info, user_message)
168+
178169
case _:
179170
logger.warning(f"Unknown user state: {user.state}")
180171
return JSONResponse(content={"status": "error"}, status_code=400)

0 commit comments

Comments
 (0)