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
4 changes: 4 additions & 0 deletions .env.template
Original file line number Diff line number Diff line change
Expand Up @@ -48,6 +48,10 @@ MOCK_WHATSAPP=True # Set to True if you want to use the mock WhatsApp API and no
MOCK_WHATSAPP_API_URL=http://127.0.0.1:3000/api/whatsapp
MOCK_WHATSAPP_TOKEN=change-me-local-token
BUSINESS_ENV=False # Set to True if you want to use WhatsApp Flows in a verified business account
EXAM_GENERATION_LIMIT=5
EXAM_GENERATION_WINDOW_DAYS=7
EXAM_REUSE_WINDOW_MINUTES=30 # A repeated request for the same exam within this time returns that exam
EXAM_RESERVATION_TIMEOUT_MINUTES=30 # An unfinished exam generation stops counting against the limit after this time


""" Below credentials are only required not usiing Mock WhatsApp"""
Expand Down
4 changes: 4 additions & 0 deletions .env.template.simple
Original file line number Diff line number Diff line change
Expand Up @@ -40,6 +40,10 @@ MOCK_WHATSAPP=True
MOCK_WHATSAPP_API_URL=http://127.0.0.1:3000/api/whatsapp
MOCK_WHATSAPP_TOKEN=change-me-local-token
BUSINESS_ENV=False
EXAM_GENERATION_LIMIT=5
EXAM_GENERATION_WINDOW_DAYS=7
EXAM_REUSE_WINDOW_MINUTES=30 # A repeated request for the same exam within this time returns that exam
EXAM_RESERVATION_TIMEOUT_MINUTES=30 # An unfinished exam generation stops counting against the limit after this time

# Meta API credentials
META_API_VERSION="v22.0"
Expand Down
2 changes: 2 additions & 0 deletions app/assets/strings/english.yml
Original file line number Diff line number Diff line change
Expand Up @@ -40,6 +40,8 @@ tools:
notification: "📑 Generating exercises from the course content, please hold..."
generate_necta_style_exam:
notification: "📝 Generating a NECTA-style exam. This takes around 10 minutes, so please be patient and wait for the message with your exam and solution."
rate_limited: "You have reached the limit of {limit} exams in {window_days} days. You can generate a new exam from {next_available_date}."
in_progress: "Your exam is still being prepared. I'll send it here as soon as it's ready."
delivery_failed_exam_and_solution: "Sorry, something went wrong in creating the exam and exam solution."
delivery_failed_exam: "Sorry, something went wrong in generating the exam."
delivery_failed_solution: "Sorry, something went wrong in generating the exam solution."
Expand Down
12 changes: 9 additions & 3 deletions app/clients/agent_client.py
Original file line number Diff line number Diff line change
Expand Up @@ -83,13 +83,19 @@ async def _observe(
self.logger.info(f"Agent action: processing {len(tool_calls)} tool call(s).")
self.logger.debug(f"Tool calls: {tool_calls}")

unique_tools = {tool_call["function"]["name"] for tool_call in tool_calls}
# Calls a preflight already answered (e.g. exam limit reached) get no
# notification and do not run.
settled = await self.tool_manager.run_preflights(tool_calls, user)
settled_ids = {message.tool_call_id for message in settled}
to_run = [call for call in tool_calls if call["id"] not in settled_ids]

unique_tools = {tool_call["function"]["name"] for tool_call in to_run}
for tool_name in sorted(unique_tools - notified_tools):
await self._tool_call_notification(user, tool_name)
notified_tools.update(unique_tools)

tool_responses = await self.tool_manager.process_tool_calls(tool_calls, user)
return tool_responses
tool_responses = await self.tool_manager.process_tool_calls(to_run, user)
return settled + tool_responses

async def _force_final(
self,
Expand Down
6 changes: 6 additions & 0 deletions app/config.py
Original file line number Diff line number Diff line change
Expand Up @@ -78,6 +78,12 @@ class Settings(BaseSettings):
# Message limiting settings
message_character_limit: int = 65000

# Exam generation limiting settings
exam_generation_limit: int = Field(default=5, gt=0)
exam_generation_window_days: int = Field(default=7, gt=0)
exam_reuse_window_minutes: int = Field(default=30, gt=0)
exam_reservation_timeout_minutes: int = Field(default=30, gt=0)

# Database settings
database_url: SecretStr

Expand Down
228 changes: 227 additions & 1 deletion app/database/db.py
Original file line number Diff line number Diff line change
Expand Up @@ -2,7 +2,7 @@
import logging
from datetime import datetime, timedelta, timezone

from sqlalchemy import func, text
from sqlalchemy import func, text, update
from sqlalchemy.orm import selectinload
from sqlmodel import and_, delete, desc, exists, insert, or_, select
from sqlmodel.sql.expression import SelectOfScalar
Expand All @@ -14,6 +14,7 @@
Chunk,
Class,
ClassResource,
ExamGenerationReservation,
GeneratedExam,
Message,
Resource,
Expand All @@ -29,6 +30,10 @@
# parsed chunks hold whole chapters (over 1 MB of text).
MAX_CHUNK_CONTENT_CHARS = 8000

# First key of pg_advisory_xact_lock(namespace, user_id), so these locks cannot
# collide with other advisory locks keyed by user id.
EXAM_RESERVATION_LOCK_NAMESPACE = 364

# TODO: Add custom Exceptions for better error handling


Expand Down Expand Up @@ -144,6 +149,227 @@ async def get_exam_by_id(exam_id: str) -> GeneratedExam | None:
raise Exception(f"Failed to retrieve exam: {str(e)}")


async def _lock_exam_reservations(session, user_id: int) -> None:
"""Serialise one user's reservations until the transaction ends, across workers."""
await session.execute(
text("SELECT pg_advisory_xact_lock(:namespace, :user_id)"),
{"namespace": EXAM_RESERVATION_LOCK_NAMESPACE, "user_id": user_id},
)


def _require_timezone_aware(**values: datetime) -> None:
for name, value in values.items():
if value.tzinfo is None or value.utcoffset() is None:
raise ValueError(f"{name} must be timezone-aware.")


def _is_active_pending_slot(pending_since: datetime):
return and_(
ExamGenerationReservation.status == enums.ExamReservationStatus.pending,
ExamGenerationReservation.created_at >= pending_since,
)


def _is_counted_slot(window_start: datetime, pending_since: datetime):
"""Slots counted against the limit: completed since `window_start`, and
pending since `pending_since` (older pending ones belong to crashed runs)."""
return or_(
and_(
ExamGenerationReservation.status == enums.ExamReservationStatus.completed,
ExamGenerationReservation.created_at >= window_start,
),
_is_active_pending_slot(pending_since),
)


async def _check_exam_reservations(
session,
user_id: int,
request_key: str,
*,
limit: int,
window_start: datetime,
pending_since: datetime,
reuse_since: datetime,
) -> tuple[ExamGenerationReservation | None, bool]:
"""Return (same-request reservation, False) if one matches, else (None, slot_free).

A same request matches when it completed since `reuse_since` or is still
pending since `pending_since`.
"""
Reservation = ExamGenerationReservation
Status = enums.ExamReservationStatus

same_request = await session.execute(
select(Reservation)
.where(
Reservation.user_id == user_id,
Reservation.request_key == request_key,
or_(
and_(
Reservation.status == Status.completed,
Reservation.exam_id.is_not(None),
Reservation.completed_at >= reuse_since,
),
_is_active_pending_slot(pending_since),
),
)
.order_by(desc(Reservation.created_at))
.limit(1)
)
existing = same_request.scalar_one_or_none()
if existing is not None:
return existing, False

used = await session.execute(
select(func.count())
.select_from(Reservation)
.where(
Reservation.user_id == user_id,
_is_counted_slot(window_start, pending_since),
)
)
return None, used.scalar_one() < limit


async def reserve_exam_generation(
user_id: int,
request_key: str,
*,
limit: int,
window_start: datetime,
pending_since: datetime,
reuse_since: datetime,
) -> tuple[ExamGenerationReservation | None, bool]:
"""Atomically return the user's matching reservation or take a new slot.

Returns:
(existing, False): the same request is reusable or still in progress.
(new, True): a new pending reservation, taken under the limit.
(None, False): the limit is reached.
"""
_require_timezone_aware(
window_start=window_start, pending_since=pending_since, reuse_since=reuse_since
)

async with get_session() as session:
try:
await _lock_exam_reservations(session, user_id)
existing, slot_free = await _check_exam_reservations(
session,
user_id,
request_key,
limit=limit,
window_start=window_start,
pending_since=pending_since,
reuse_since=reuse_since,
)
if not slot_free:
return existing, False

reservation = ExamGenerationReservation(
user_id=user_id, request_key=request_key
)
session.add(reservation)
await session.flush()
return reservation, True
except Exception as e:
logger.error(
"Failed to reserve exam generation for user %s: %s", user_id, e
)
raise Exception(f"Failed to reserve exam generation: {str(e)}")


async def preview_exam_generation(
user_id: int,
request_key: str,
*,
limit: int,
window_start: datetime,
pending_since: datetime,
reuse_since: datetime,
) -> tuple[ExamGenerationReservation | None, bool]:
"""Read-only reserve_exam_generation: no lock, nothing written.

Returns:
(existing, False): the same request is reusable or still in progress.
(None, True): a slot is free.
(None, False): the limit is reached.
"""
_require_timezone_aware(
window_start=window_start, pending_since=pending_since, reuse_since=reuse_since
)

async with get_session() as session:
try:
return await _check_exam_reservations(
session,
user_id,
request_key,
limit=limit,
window_start=window_start,
pending_since=pending_since,
reuse_since=reuse_since,
)
except Exception as e:
logger.error(
"Failed to preview exam generation for user %s: %s", user_id, e
)
raise Exception(f"Failed to preview exam generation: {str(e)}")


async def get_oldest_counted_exam_slot_at(
user_id: int, *, window_start: datetime, pending_since: datetime
) -> datetime | None:
"""Creation time of the user's oldest slot still counted against the limit."""
_require_timezone_aware(window_start=window_start, pending_since=pending_since)

async with get_session() as session:
try:
result = await session.execute(
select(func.min(ExamGenerationReservation.created_at)).where(
ExamGenerationReservation.user_id == user_id,
_is_counted_slot(window_start, pending_since),
)
)
oldest = result.scalar_one()
except Exception as e:
logger.error("Failed to read exam slots for user %s: %s", user_id, e)
raise Exception(f"Failed to read exam slots: {str(e)}")

if oldest is not None and oldest.tzinfo is None:
return oldest.replace(tzinfo=timezone.utc)
return oldest


async def _update_exam_reservation(reservation_id: str, **values) -> None:
async with get_session() as session:
try:
await session.execute(
update(ExamGenerationReservation)
.where(ExamGenerationReservation.id == reservation_id)
.values(**values)
)
except Exception as e:
logger.error("Failed to update exam reservation %s: %s", reservation_id, e)
raise Exception(f"Failed to update exam reservation: {str(e)}")


async def mark_exam_reservation_completed(reservation_id: str, exam_id: str) -> None:
await _update_exam_reservation(
reservation_id,
status=enums.ExamReservationStatus.completed,
exam_id=exam_id,
completed_at=datetime.now(timezone.utc),
)


async def mark_exam_reservation_failed(reservation_id: str) -> None:
await _update_exam_reservation(
reservation_id, status=enums.ExamReservationStatus.failed
)


async def get_user_by_waid(wa_id: str) -> User | None:
"""
Get user by WhatsApp ID with FULL class hierarchy loaded.
Expand Down
6 changes: 6 additions & 0 deletions app/database/enums.py
Original file line number Diff line number Diff line change
Expand Up @@ -149,6 +149,12 @@ def display_format(self) -> str:
return f"{self.replace('_', ' ').title()} {emoji}".strip()


class ExamReservationStatus(str, Enum):
pending = "pending"
completed = "completed"
failed = "failed"


class ChunkType(str, Enum):
text = "text"
exercise = "exercise"
Expand Down
40 changes: 40 additions & 0 deletions app/database/models.py
Original file line number Diff line number Diff line change
@@ -1,5 +1,6 @@
from datetime import date, datetime, timezone
from typing import TYPE_CHECKING, Any, Optional
from uuid import uuid4

import sqlalchemy as sa
from pgvector.sqlalchemy import Vector
Expand Down Expand Up @@ -386,6 +387,45 @@ class GeneratedExam(SQLModel, table=True):
)


class ExamGenerationReservation(SQLModel, table=True):
"""One exam-generation slot, held from the request until the exam is saved."""

__tablename__ = "exam_generation_reservations" # type: ignore
__table_args__ = (
Index(
"ix_exam_generation_reservations_user_id_created_at",
"user_id",
"created_at",
),
)

""" FIELDS """
id: str = Field(
default_factory=lambda: str(uuid4()), primary_key=True, max_length=36
)
user_id: int = Field(foreign_key="users.id", ondelete="CASCADE")
request_key: str = Field(max_length=64)
status: enums.ExamReservationStatus = Field(
default=enums.ExamReservationStatus.pending, max_length=20
)
exam_id: Optional[str] = Field(
default=None,
foreign_key="generated_exams.id",
ondelete="SET NULL",
max_length=36,
)
created_at: datetime = Field(
default_factory=lambda: datetime.now(timezone.utc),
sa_type=DateTime(timezone=True), # type: ignore
sa_column_kwargs={"server_default": sa.func.now()},
nullable=False,
)
completed_at: Optional[datetime] = Field(
default=None,
sa_type=DateTime(timezone=True), # type: ignore
)


class Resource(SQLModel, table=True):
__tablename__ = "resources" # type: ignore
model_config = {"arbitrary_types_allowed": True} # type: ignore
Expand Down
Loading
Loading