feature: modify and delete driver trips
Browse filesFiles changed (19)
- .github/prompts/plan-mergeDriverChecksAddTripTools.prompt.mdAdded+61
- app/ai/orchestrator.py+1-2
- app/ai/tool_schemas.py+153
- app/api/routes.py+3-3
- app/database/supabase.py+90
- app/models/domain.py+2
- app/services/conversation_service.py+125-2
- app/services/trip_indexing.py+4
- app/tools/handlers.py+291-7
- app/whatsapp/client.py+33-2
- app/whatsapp/parser.py+33-2
- app/whatsapp/trip_selection.pyAdded+91
- prompts/system_driver.md+3
- supabase/migrations/202606140001_customer_session_data.sqlAdded+2
- tests/conftest.py+76
- tests/test_conversation_service.py+132
- tests/test_tool_schemas.py+3-1
- tests/test_tools.py+114
- tests/test_trip_selection.pyAdded+28
12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061## Plan: Merge driver checks & add trip modify/delete tools
TL;DR: Merge `check_driver_info` and `check_driver_trips` into a single `check_driver_dashboard` tool that returns driver profile, registered vehicles, and upcoming trips. Add `update_driver_trip` and `delete_driver_trip` tools (prefer soft-cancel) with schemas, handlers, DB methods, indexing calls, and tests.
**Steps**1. Update schemas (`app/ai/tool_schemas.py`): - Add `_CHECK_DRIVER_DASHBOARD` for `check_driver_dashboard` (no parameters). - Add `_UPDATE_DRIVER_TRIP` and `_DELETE_DRIVER_TRIP` for `update_driver_trip` and `delete_driver_trip`. - Replace `check_driver_info` and `check_driver_trips` entries in `_TOOLS_BY_MODE["driver"]` with `check_driver_dashboard`, and add the two new tool names to the driver mode list.
2. Implement merged handler (`app/tools/handlers.py`): - Add `check_driver_dashboard(self, arguments)` that: - Resolves driver by phone (existing helper), fetches registered vehicles and upcoming trips (reuse `list_driver_trips`), and returns a structured JSON payload combining profile, vehicles, and trips summaries. - Place the method next to existing `check_driver_info`/`check_driver_trips` logic and remove or keep old helpers as internal functions if useful.
3. Implement update/delete handlers (`app/tools/handlers.py`): - `update_driver_trip(self, arguments)`: - Validate `trip_id` and driver ownership (`get_driver_by_phone` + `get_trip_by_id`). - Accept only allowed fields: `departure`, `destination`, `departure_date`, `departure_time`, `vehicle_type`, `available_seats`, `total_seats`, `price`. - Call repository `update_driver_trip(trip_id, updates)` and reindex the trip. - Return the updated trip record. - `delete_driver_trip(self, arguments)`: - Validate ownership. - Prefer soft-cancel: call repository `cancel_driver_trip(trip_id)` that sets `status = "cancelled"`. - Remove/unindex from vector index and return cancelled trip.
4. Add DB methods (`app/database/supabase.py`): - `async def update_driver_trip(self, trip_id: str, updates: dict) -> dict` — update allowed columns and return the updated row. - `async def cancel_driver_trip(self, trip_id: str) -> dict` — set `status` to `cancelled` (soft delete) and return updated row. - Follow existing style/patterns used by `create_driver_trip` and `get_trip_by_id`.
5. Indexing updates (`app/services/trip_indexing.py`): - Add `async def unindex_trip(trip_id: str)` or `delete_from_index(trip_id)` to remove vectors. - Ensure `update_driver_trip` calls `index_trip` after DB update and `cancel_driver_trip` calls `unindex_trip`.
6. Registration / wiring: - No registry code changes required: `conversation_service._tool_registry()` registers tools from `_TOOLS_BY_MODE` automatically once names are updated.
7. Tests: - Update `tests/conftest.py` FakeRepository to implement `update_driver_trip` and `cancel_driver_trip` behaviors. - Replace or update tests that call `check_driver_info` / `check_driver_trips` to assert the merged `check_driver_dashboard` behavior in `tests/test_tools.py`. - Add tests for `update_driver_trip` and `delete_driver_trip` mirroring existing handler test patterns.
8. Docs & prompts: - Update `prompts/system_driver.md` to document the merged tool and the new modify/delete tools so the model calls them appropriately.
**Verification**1. Run unit tests: `pytest -q` and ensure all tests pass (focus on `tests/test_tools.py`).2. Run targeted tests: `pytest -q tests/test_tools.py::test_check_driver_dashboard` and new tests for update/delete.3. Manual local sanity: call the tool handlers via the existing orchestrator test harness in `tests/test_ai_orchestrator.py`.4. Verify indexing: after update, trip appears in index with new values; after cancel, it's unindexed.
**Decisions & assumptions**- Use soft-cancel (`status = "cancelled"`) instead of hard delete to preserve audit/history and avoid breaking references.- Require driver ownership verification before allowing update/delete.- Limit updatable fields to the set listed above; price/seats allowed, but payments/refunds are out of scope.
**Further considerations**1. Notifications: consider notifying booked passengers when a trip is modified/cancelled (out of scope for this change).2. Concurrency: consider optimistic locking/versioning if concurrent edits are possible.3. Permissions & audit logs: ensure handlers record who made the change (phone/driver id) for traceability.88 unmodified lines899091929293959495969788 unmodified lines if content: return content raise ProviderError(f"{provider.name} returned an empty response") logger.info("----++-----"+str(response)) working_messages.append(_assistant_tool_message(response)) for tool_call in response.tool_calls: # logger.warning("++++++++"+str(tool_call)+ "&&&"+ str(registry)) logger.warning("++++++++"+str(tool_call)+ "&&&"+ str(registry)) result = await _execute_tool_call(registry, tool_call) logger.warning("+++++++++++++"+str(result)) working_messages.append(272 unmodified lines27327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242341 unmodified lines46546646746846947047147247347411 unmodified lines486487488489490491492493494495272 unmodified lines },}
_INITIATE_TRIP_ACTION = { "type": "function", "function": { "name": "initiate_trip_action", "description": ( "Start delete or modify flow for one of the driver's upcoming trips. " "The system sends a numbered list of active trips to the driver in plain text." ), "parameters": { "type": "object", "properties": { "action_type": { "type": "string", "enum": ["DELETE", "MODIFY"], "description": "Whether the driver wants to cancel or edit a trip.", }, "travel_date": { "type": "string", "description": ( "Optional trip date filter as YYYY-MM-DD in Asia/Aden when the " "driver mentioned a specific day such as today or tomorrow." ), }, "travel_time": { "type": "string", "enum": ["صباح", "ظهر", "ليل"], "description": "Optional departure time bucket filter in Arabic.", }, }, "required": ["action_type"], "additionalProperties": False, }, },}
_UPDATE_TRIP_FIELD = { "type": "function", "function": { "name": "update_trip_field", "description": ( "Update one field on the trip the driver selected for editing. " "trip_id is resolved automatically from the active edit session." ), "parameters": { "type": "object", "properties": { "field": { "type": "string", "enum": [ "departure", "destination", "departure_date", "departure_time", "pickup_time", "vehicle_type", "available_seats", "total_seats", "price", ], "description": "Trip field to update.", }, "value": { "type": "string", "description": ( "New value for the field. Use YYYY-MM-DD for dates, HH:MM for " "pickup_time, Arabic city names for route fields, and English " "digits for seats and price." ), }, }, "required": ["field", "value"], "additionalProperties": False, }, },}
_DELETE_TRIP_BY_NUMBER = { "type": "function", "function": { "name": "delete_trip_by_number", "description": ( "Cancel an upcoming active trip using the driver-visible trip number. " "Trip numbers are assigned in ascending order from oldest to newest." ), "parameters": { "type": "object", "properties": { "trip_number": { "type": "integer", "minimum": 1, "description": "The one-based number of the trip from the driver trip list.", }, }, "required": ["trip_number"], "additionalProperties": False, }, },}
_MODIFY_TRIP_BY_NUMBER = { "type": "function", "function": { "name": "modify_trip_by_number", "description": ( "Modify one field of an active driver trip using the driver-visible trip number. " "Trip numbers are assigned in ascending order from oldest to newest." ), "parameters": { "type": "object", "properties": { "trip_number": { "type": "integer", "minimum": 1, "description": "The one-based number of the trip from the driver trip list.", }, "field": { "type": "string", "enum": [ "departure", "destination", "departure_date", "departure_time", "pickup_time", "vehicle_type", "available_seats", "total_seats", "price", ], "description": "The trip field to update.", }, "value": { "type": "string", "description": ( "New value for the field. Use YYYY-MM-DD for dates, HH:MM for " "pickup_time, Arabic city names for route fields, and English " "digits for seats and price." ), }, }, "required": ["trip_number", "field", "value"], "additionalProperties": False, }, },}
_SWITCH_TO_DRIVER = { "type": "function", "function": {41 unmodified lines "check_driver_trips": _CHECK_DRIVER_TRIPS, "add_driver_car": _ADD_DRIVER_CAR, "add_trip_by_driver": _ADD_TRIP_BY_DRIVER, "initiate_trip_action": _INITIATE_TRIP_ACTION, "update_trip_field": _UPDATE_TRIP_FIELD, "delete_trip_by_number": _DELETE_TRIP_BY_NUMBER, "modify_trip_by_number": _MODIFY_TRIP_BY_NUMBER, "switch_to_driver": _SWITCH_TO_DRIVER, "switch_to_passenger": _SWITCH_TO_PASSENGER,}11 unmodified lines "check_driver_trips", "add_driver_car", "add_trip_by_driver", "delete_trip_by_number", "modify_trip_by_number", "initiate_trip_action", "update_trip_field", "switch_to_passenger", ], "passenger": [136 unmodified lines13713813914014014114214343 unmodified lines187188189190190191192193194195195196197198136 unmodified lines tool_results: list[dict[str, Any]] = [] registry = container.conversation._tool_registry( {"id": "admin-debug", "remoteJid": "", "name": "admin-debug"}, sender_phone="admin-debug", remoteJid="admin-debug", user_mode="passenger", )
43 unmodified lines tool_results: list[dict[str, Any]] = [] customer = { "id": "debug", "remoteJid": request.client_number, "remoteJid": "823904580238", "name": "driver-debug", } registry = container.conversation._tool_registry( customer, sender_phone=request.client_number, remoteJid=request.client_number, user_mode="driver", )
82 unmodified lines8384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142186 unmodified lines329330331332333334335336337338339340341342149 unmodified lines49249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452582 unmodified lines data = _response_data(response) return data[0] if isinstance(data, list) else data
async def get_customer_session(self, customer_id: str) -> dict[str, Any]: response = await ( self.client.table("customers") .select("session_data") .eq("id", customer_id) .maybe_single() .execute() ) data = _response_data(response) or {} session_data = data.get("session_data") return session_data if isinstance(session_data, dict) else {}
async def update_customer_session( self, *, customer_id: str, session_data: dict[str, Any], ) -> dict[str, Any]: response = await ( self.client.table("customers") .update({"session_data": session_data}) .eq("id", customer_id) .execute() ) data = _response_data(response) return data[0] if isinstance(data, list) else data
async def set_customer_session_field( self, *, customer_id: str, key: str, value: Any, ) -> dict[str, Any]: session_data = await self.get_customer_session(customer_id) session_data[key] = value return await self.update_customer_session( customer_id=customer_id, session_data=session_data, )
async def clear_customer_session_field( self, *, customer_id: str, key: str, ) -> dict[str, Any]: session_data = await self.get_customer_session(customer_id) session_data.pop(key, None) return await self.update_customer_session( customer_id=customer_id, session_data=session_data, )
async def message_exists(self, whatsapp_message_id: str) -> bool: response = await ( self.client.table("messages")186 unmodified lines data = _response_data(response) return len(data) if isinstance(data, list) else len(trip_embeddings)
async def delete_trip_embedding(self, trip_id: str) -> None: await ( self.client.table("driver_trip_embeddings") .delete() .eq("trip_id", trip_id) .execute() )
def _apply_departure_request_filter( self, query: Any,149 unmodified lines trip = data[0] if isinstance(data, list) else data return await self.get_trip_by_id(str(trip["id"])) or trip
async def update_driver_trip( self, trip_id: str, updates: dict[str, Any], ) -> dict[str, Any]: if not updates: raise ValueError("updates must not be empty") response = await ( self.client.table("driver_trips") .update(updates) .eq("id", trip_id) .execute() ) data = _response_data(response) updated = data[0] if isinstance(data, list) else data return await self.get_trip_by_id(str(updated.get("id") or trip_id)) or updated
async def cancel_driver_trip(self, trip_id: str) -> dict[str, Any]: response = await ( self.client.table("driver_trips") .update({"status": "cancelled"}) .eq("id", trip_id) .execute() ) data = _response_data(response) updated = data[0] if isinstance(data, list) else data return await self.get_trip_by_id(str(updated.get("id") or trip_id)) or updated
async def create_booking_lead( self, *,12 unmodified lines131415161718192012 unmodified lines timestamp: str | None = None profile_name: str | None = None phone_number_id: str | None = None message_type: str = "text" interactive_reply_id: str | None = None raw: dict[str, Any] = field(default_factory=dict)
7 unmodified lines89101111121314151617181916 unmodified lines3637383940414243444533 unmodified lines7980818283848516 unmodified lines1021031041051061071081091101111121041131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312327 unmodified linesfrom app.database.supabase import SupabaseRepositoryfrom app.models.domain import UserMode, WhatsAppInboundMessagefrom app.services.embedding_service import JinaEmbeddingServicefrom app.services.trip_indexing import unindex_tripfrom app.tools.handlers import FalsaToolHandlersfrom app.tools.handlers import FalsaToolHandlers, _trip_summaryfrom app.tools.registry import ToolRegistryfrom app.utils.time import now_in_timezonefrom app.whatsapp.client import WhatsAppClientfrom app.whatsapp.trip_selection import parse_trip_action_reply
logger = logging.getLogger(__name__)
16 unmodified lines "check_driver_trips", "add_driver_car", "add_trip_by_driver", "delete_trip_by_number", "modify_trip_by_number", "initiate_trip_action", "update_trip_field", "switch_to_passenger", ], "passenger": [33 unmodified lines remote_jid=inbound.remoteJid, name=inbound.profile_name, )
current_message = await self.repository.create_message( customer_id=str(customer["id"]), sender_type="customer",16 unmodified lines registry=registry, )
await self.whatsapp.send_text(inbound.remoteJid, reply)
await self.repository.create_message( customer_id=str(customer["id"]), sender_type="assistant", message=reply, metadata={"provider_flow": "groq_primary_hf_fallback", "user_mode": user_mode}, ) await self.whatsapp.send_text(inbound.remoteJid, reply)
return reply
async def _handle_trip_interactive_reply( self, inbound: WhatsAppInboundMessage, customer: dict[str, Any], *, action: str, trip_id: str, ) -> str | None: current_message = await self.repository.create_message( customer_id=str(customer["id"]), sender_type="customer", message=inbound.text, whatsapp_message_id=inbound.message_id, metadata={ "whatsapp": inbound.raw, "timestamp": inbound.timestamp, "interactive_reply_id": inbound.interactive_reply_id, }, )
driver = await self.repository.get_driver_by_remoteJid(inbound.remoteJid) if not driver: reply = ( "لا يوجد حساب سائق مرتبط بهذا الرفم" "من فضللك, سجل كحساب سائق اولا" ) await self._store_and_send_assistant_reply( customer, inbound.remoteJid, reply, user_mode=_resolve_user_mode(customer), ) return reply
trip = await self.repository.get_trip_by_id(trip_id) if not trip or str(trip.get("driver_id")) != str(driver["id"]): reply = "That trip could not be found for your account." await self._store_and_send_assistant_reply( customer, inbound.remoteJid, reply, user_mode=_resolve_user_mode(customer), ) return reply
if action == "DELETE": await self.repository.cancel_driver_trip(trip_id) await unindex_trip(repository=self.repository, trip_id=trip_id) reply = "Success! Your trip has been canceled." await self._store_and_send_assistant_reply( customer, inbound.remoteJid, reply, user_mode="driver", ) return reply
if action == "MODIFY": await self.repository.set_customer_session_field( customer_id=str(customer["id"]), key="active_edit_trip_id", value=trip_id, ) summary = _trip_summary(trip) route = f"{summary.get('departure')} -> {summary.get('destination')}" time_label = summary.get("departure_time") or summary.get("departure_time_type") system_note = ( f"SYSTEM: Driver selected trip {trip_id} ({route}, {time_label}) to modify. " "Ask them what details they want to change." ) user_mode = "driver" registry = self._tool_registry( customer, remoteJid=inbound.remoteJid, user_mode=user_mode, ) context = await self.repository.get_recent_context_messages( customer_id=str(customer["id"]), current_message_id=str(current_message["id"]), limit=4, ) messages = self._ai_messages(context, user_mode=user_mode) messages.append({"role": "system", "content": system_note}) reply = await self.ai.generate_reply( messages=messages, tools=get_tool_schemas(user_mode), registry=registry, ) await self._store_and_send_assistant_reply( customer, inbound.remoteJid, reply, user_mode=user_mode, ) return reply
return None
async def _store_and_send_assistant_reply( self, customer: dict[str, Any], remoteJid: str, reply: str, *, user_mode: UserMode, ) -> None: await self.repository.create_message( customer_id=str(customer["id"]), sender_type="assistant", message=reply, metadata={"provider_flow": "trip_interactive_reply", "user_mode": user_mode}, ) await self.whatsapp.send_text(remoteJid, reply)
def _tool_registry( self, customer: dict[str, Any],36 unmodified lines3738394041424344454636 unmodified lines await repository.upsert_trip_embeddings([record])
async def unindex_trip(*, repository: SupabaseRepository, trip_id: str) -> None: await repository.delete_trip_embedding(trip_id)
def _first_or_dict(value: Any) -> dict[str, Any] | None: if isinstance(value, list): return value[0] if value else None3 unmodified lines4567789104 unmodified lines15161718192021227 unmodified lines24925025125225325425525625725825926028 unmodified lines28929029128528628729229329429514 unmodified lines310311312308313314315316193 unmodified lines510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791149 unmodified lines94194294366394494594666694794894995011 unmodified lines9629639649659669679689699703 unmodified linesfrom app.database.supabase import SupabaseRepositoryfrom app.models.domain import ToolResultfrom app.services.embedding_service import JinaEmbeddingServicefrom app.services.trip_indexing import index_tripfrom app.services.trip_indexing import index_trip, unindex_tripfrom app.utils.departure import ( _parse_date_value, normalize_departure_bucket,4 unmodified lines trip_satisfies_departure_request,)from app.whatsapp.client import WhatsAppClient, WhatsAppClientErrorfrom app.whatsapp.trip_selection import build_trip_selection_list, build_trip_selection_text
class FalsaToolHandlers:227 unmodified lines }, )
async def _summarize_trips(self, trips: list[dict[str, Any]]) -> list[dict[str, Any]]: return [ _trip_summary(trip, trip_number=index + 1) for index, trip in enumerate(trips) ]
async def check_driver_info(self, arguments: dict[str, Any]) -> ToolResult: driver = await self.repository.get_driver_by_remoteJid(self.remoteJid) if not driver:28 unmodified lines } for car in cars ], "active_trips": [ _trip_summary(trip) for trip in upcoming_trips ], "active_trips": await self._summarize_trips(upcoming_trips), }, )
14 unmodified lines ok=True, data={ "driver_id": driver["id"], "upcoming_trips": [_trip_summary(trip) for trip in trips], "upcoming_trips": await self._summarize_trips(trips), "count": len(trips), "message": ( "No upcoming active trips found."193 unmodified lines }, )
async def initiate_trip_action(self, arguments: dict[str, Any]) -> ToolResult: action_type = _optional_string(arguments.get("action_type")) if action_type not in {"DELETE", "MODIFY"}: return ToolResult( ok=False, data={}, error="action_type must be DELETE or MODIFY", )
driver = await self.repository.get_driver_by_remoteJid(self.remoteJid) if not driver: return ToolResult( ok=False, data={"action": "create_driver_account"}, error=( "No driver account for this WhatsApp number. " "Ask the sender to register with create_driver_account first." ), )
trips = await self.repository.list_driver_trips(str(driver["id"])) travel_date = _optional_string(arguments.get("travel_date")) travel_time = _optional_string(arguments.get("travel_time")) departure_request = parse_departure_request( travel_date=travel_date, travel_time=travel_time, ) if departure_request.departure_date or departure_request.departure_time: trips = [ trip for trip in trips if trip_satisfies_departure_request(trip, departure_request) ]
if not trips: return ToolResult( ok=True, data={ "count": 0, "message": "No trips found. Ask the user for clarification.", }, )
body = build_trip_selection_text(trips=trips, action_type=action_type) try: await self.whatsapp.send_text(self.remoteJid, body) except WhatsAppClientError as exc: return ToolResult( ok=False, data={"count": len(trips)}, error=f"Failed to send WhatsApp trip selection text: {exc}", )
return ToolResult( ok=True, data={ "count": len(trips), "action_type": action_type, "message": ( "Sent a numbered trip list to the driver via WhatsApp. " "Ask them to reply with the trip number." ), }, )
async def delete_trip_by_number(self, arguments: dict[str, Any]) -> ToolResult: driver = await self.repository.get_driver_by_remoteJid(self.remoteJid) if not driver: return ToolResult( ok=False, data={"action": "create_driver_account"}, error=( "No driver account for this WhatsApp number. " "Ask the sender to register with create_driver_account first." ), )
trip_number = _optional_int(arguments.get("trip_number")) if trip_number is None or trip_number < 1: return ToolResult(ok=False, data={}, error="trip_number must be an integer >= 1")
trips = await self.repository.list_driver_trips(str(driver["id"])) if trip_number > len(trips): return ToolResult( ok=False, data={"count": len(trips)}, error=f"trip_number must be between 1 and {len(trips)}", )
trip = trips[trip_number - 1] await self.repository.cancel_driver_trip(str(trip["id"])) await unindex_trip(repository=self.repository, trip_id=str(trip["id"]))
return ToolResult( ok=True, data={ "trip_number": trip_number, "trip_id": trip.get("id"), "trip": _trip_summary(trip, trip_number=trip_number), "message": "Success! Your trip has been canceled.", }, )
async def modify_trip_by_number(self, arguments: dict[str, Any]) -> ToolResult: print("\n modefing our new \n") driver = await self.repository.get_driver_by_remoteJid(self.remoteJid) if not driver: return ToolResult( ok=False, data={"action": "create_driver_account"}, error=( "No driver account for this WhatsApp number. " "Ask the sender to register with create_driver_account first." ), )
trip_number = _optional_int(arguments.get("trip_number")) field = _optional_string(arguments.get("field")) value = _optional_string(arguments.get("value")) if trip_number is None or trip_number < 1: return ToolResult(ok=False, data={}, error="trip_number must be an integer >= 1") if not field or value is None: return ToolResult(ok=False, data={}, error="field and value are required")
trips = await self.repository.list_driver_trips(str(driver["id"])) if trip_number > len(trips): return ToolResult( ok=False, data={"count": len(trips)}, error=f"trip_number must be between 1 and {len(trips)}", )
trip = trips[trip_number - 1] updates, error = await self._build_trip_field_update( driver_id=str(driver["id"]), field=field, value=value, ) if error: return ToolResult(ok=False, data={}, error=error)
updated_trip = await self.repository.update_driver_trip(str(trip["id"]), updates) await index_trip( repository=self.repository, embeddings=self.embeddings, embedding_model=self.embedding_model, trip=updated_trip, )
return ToolResult( ok=True, data={ "trip_number": trip_number, "trip_id": updated_trip.get("id"), "field": field, "value": value, "trip": _trip_summary(updated_trip, trip_number=trip_number), "message": "Trip updated successfully.", }, )
async def update_trip_field(self, arguments: dict[str, Any]) -> ToolResult: driver = await self.repository.get_driver_by_remoteJid(self.remoteJid) if not driver: return ToolResult( ok=False, data={"action": "create_driver_account"}, error=( "No driver account for this WhatsApp number. " "Ask the sender to register with create_driver_account first." ), )
session = await self.repository.get_customer_session(str(self.customer["id"])) trip_id = _optional_string(session.get("active_edit_trip_id")) if not trip_id: return ToolResult( ok=False, data={}, error=( "No trip is selected for editing. " "Use initiate_trip_action with MODIFY first." ), )
trip = await self.repository.get_trip_by_id(trip_id) if not trip: return ToolResult(ok=False, data={}, error="Trip was not found") if str(trip.get("driver_id")) != str(driver["id"]): return ToolResult(ok=False, data={}, error="Trip does not belong to this driver") if trip.get("status") != "active": return ToolResult(ok=False, data={}, error="Trip is not active")
field = _optional_string(arguments.get("field")) value = _optional_string(arguments.get("value")) if not field or value is None: return ToolResult(ok=False, data={}, error="field and value are required")
updates, error = await self._build_trip_field_update( driver_id=str(driver["id"]), field=field, value=value, ) if error: return ToolResult(ok=False, data={}, error=error)
updated_trip = await self.repository.update_driver_trip(trip_id, updates) await index_trip( repository=self.repository, embeddings=self.embeddings, embedding_model=self.embedding_model, trip=updated_trip, ) await self.repository.clear_customer_session_field( customer_id=str(self.customer["id"]), key="active_edit_trip_id", )
return ToolResult( ok=True, data={ "trip_id": trip_id, "field": field, "value": value, "trip": _trip_summary(updated_trip), "message": "Trip updated successfully.", }, )
async def _build_trip_field_update( self, *, driver_id: str, field: str, value: str, ) -> tuple[dict[str, Any], str | None]: if field in {"departure", "destination"}: return {field: value}, None
if field == "departure_date": parsed_date = _parse_date_value(value) if not parsed_date: return {}, "departure_date must be YYYY-MM-DD" return {"departure_date": parsed_date.isoformat()}, None
if field in {"departure_time", "pickup_time"}: bucket = normalize_departure_bucket(value) if not bucket: return {}, "departure_time must be morning, noon, night, or HH:MM" return {"departure_time": bucket}, None
if field == "vehicle_type": cars = await self.repository.list_driver_cars(driver_id) matched_car = _resolve_driver_car(cars, vehicle_type=value) if not matched_car: return {}, f"No registered vehicle matches '{value}'" return {"car_id": str(matched_car["id"])}, None
if field in {"available_seats", "total_seats"}: seats = _optional_int(value) if seats is None: return {}, f"{field} must be an integer" if field == "available_seats" and seats < 0: return {}, "available_seats must be at least 0" if field == "total_seats" and seats < 1: return {}, "total_seats must be at least 1" return {field: seats}, None
if field == "price": price = _optional_price(value) if price is None or price < 0: return {}, "price must be zero or greater" return {"price": price}, None
return {}, f"Unsupported field: {field}"
async def switch_to_driver(self, arguments: dict[str, Any]) -> ToolResult: driver = await self.repository.get_driver_by_remoteJid(self.remoteJid) if not driver:149 unmodified lines return True
def _trip_summary(trip: dict[str, Any]) -> dict[str, Any]:def _trip_summary(trip: dict[str, Any], *, trip_number: int | None = None) -> dict[str, Any]: driver = _first_or_dict(trip.get("drivers")) or {} car = _first_or_dict(trip.get("driver_cars")) or {} return { summary = { "trip_id": trip.get("trip_id") or trip.get("id"), "departure": trip.get("departure"), "destination": trip.get("destination"),11 unmodified lines "similarity": trip.get("similarity"), "time_difference_minutes": trip.get("time_difference_minutes"), } if trip_number is not None: summary["trip_number"] = trip_number return summary
def _sort_trip_summaries(trips: list[dict[str, Any]]) -> list[dict[str, Any]]:16 unmodified lines1718192021222223242526262728293014 unmodified lines45464748495051525354555657585960616263646566676869707172737475767716 unmodified lines base = self._settings.whatsapp_graph_url.rstrip("/") version = self._settings.whatsapp_api_version.strip("/") phone_number_id = self._settings.whatsapp_phone_number_id print(base) return f"{base}/{version}/{phone_number_id}/messages"
async def send_text(self, to_phone: str, text: str) -> dict: async def send_text(self, remoteJid: str, text: str) -> dict: payload = { "messaging_product": "whatsapp", "recipient_type": "individual", "to": to_phone, "to": remoteJid, "type": "text", "text": {"preview_url": False, "body": text}, }14 unmodified lines )
return response.json()
async def send_interactive_list( self, remoteJid: str, interactive: dict[str, Any], ) -> dict: payload = { "messaging_product": "whatsapp", "recipient_type": "individual", "to": remoteJid, "type": "interactive", "interactive": interactive, } headers = { "Authorization": f"Bearer {self._settings.whatsapp_access_token}", "Content-Type": "application/json", }
if self._client is not None: response = await self._client.post(self._messages_url, json=payload, headers=headers) else: async with httpx.AsyncClient(timeout=self._settings.request_timeout_seconds) as client: response = await client.post(self._messages_url, json=payload, headers=headers)
if response.status_code >= 400: raise WhatsAppClientError( f"WhatsApp API failed with {response.status_code}: {response.text}" )
return response.json()1 unmodified line2345567815 unmodified lines24252627282930313233343536373839404142434445464748495051525354555657585960616263356465666768697071721 unmodified line
from app.models.domain import WhatsAppInboundMessage
SUPPORTED_MESSAGE_TYPES = {"text"}SUPPORTED_MESSAGE_TYPES = {"text", "interactive"}
def parse_inbound_messages(payload: dict[str, Any]) -> list[WhatsAppInboundMessage]:15 unmodified lines
remoteJid = message.get("from") message_id = message.get("id")
text = message.get("text", {}).get("body") if not remoteJid or not message_id or text is None: continue
if message_type == "text": text = message.get("text", {}).get("body") if text is None: continue messages.append( WhatsAppInboundMessage( message_id=message_id, remoteJid=remoteJid, text=text, timestamp=message.get("timestamp"), profile_name=contacts_by_wa_id.get(remoteJid), phone_number_id=phone_number_id, message_type="text", raw=message, ) ) continue
interactive = message.get("interactive", {}) if interactive.get("type") != "list_reply": continue
list_reply = interactive.get("list_reply", {}) reply_id = list_reply.get("id") if not reply_id: continue
title = list_reply.get("title") or reply_id messages.append( WhatsAppInboundMessage( message_id=message_id, remoteJid=remoteJid, text=text, text=title, timestamp=message.get("timestamp"), profile_name=contacts_by_wa_id.get(remoteJid), phone_number_id=phone_number_id, message_type="interactive", interactive_reply_id=reply_id, raw=message, ) )12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091from typing import Any
from app.utils.departure import trip_departure_bucket, trip_departure_date
_BUCKET_LABELS = { "morning": "صباحا", "noon": "ظهرا", "night": "مساء",}
_ACTION_DESCRIPTIONS = { "DELETE": "🗑️ اختر رقم الرحله التي تريد حذفها من فضلك", "MODIFY": "✏️ يمكنك ارسال رقم الرحلة التي تريد تعديلها",}_PERFFIX= "قائمة الرحلات المسجله في حسابك لدينا\n\n"+("-"*7)
def parse_trip_action_reply(reply_id: str) -> tuple[str, str] | None: if "_" not in reply_id: return None action, trip_id = reply_id.split("_", 1) if action not in {"DELETE", "MODIFY"} or not trip_id: return None return action, trip_id
def build_trip_selection_list( *, trips: list[dict[str, Any]], action_type: str,) -> dict[str, Any]: action = action_type.upper() suffix = _ACTION_DESCRIPTIONS.get(action, "") rows = [ f""" [{str(trips.index(trip))}] :الرحلة رقم \n {_trip_row_description(trip)} """ for trip in trips[:10] ] rows_text = "\n".join(rows) return { "type": "text", "text": { "body": f"{_PERFFIX} {rows_text} {suffix}"
} }
def build_trip_selection_text( *, trips: list[dict[str, Any]], action_type: str,) -> str: action = action_type.upper() suffix = { "DELETE": "ارسل رقم الرحلة التي تريد حذفها.", "MODIFY": "ارسل رقم الرحلة التي تريد تعديلها.", }.get(action, "")
lines = [ f"قائمة الرحلات المسجلة لك:\n" ] for index, trip in enumerate(trips, start=1): parsed_date = trip_departure_date(trip) bucket = trip_departure_bucket(trip) bucket_text = _BUCKET_LABELS.get(bucket, "") if bucket else "" date_text = parsed_date.isoformat() if parsed_date else str(trip.get("departure_date") or "") lines.append( f"{index}. {trip.get('departure', '')} → {trip.get('destination', '')} | {date_text} | {bucket_text} | seats: {trip.get('available_seats')} / {trip.get('total_seats')} | price: {trip.get('price')}" ) lines.append("") lines.append(suffix) return "\n".join(lines)
def _trip_row_description(trip: dict[str, Any]) -> str: departure = str(trip.get("departure") or "") destination = str(trip.get("destination") or "") parsed_date = trip_departure_date(trip) date_text = parsed_date.isoformat() if parsed_date else "" bucket = trip_departure_bucket(trip) bucket_text = _BUCKET_LABELS.get(bucket, "") if bucket else "" return ( f"🚌 {departure} → {destination}\n" f"📅 التاريخ: {date_text}\n" f"🕰️ الوقت: {bucket_text}" )7 unmodified lines89101112131415167 unmodified lines- Use `check_driver_trips` when the driver wants upcoming active trips.- Use `add_driver_car` to register a vehicle. Only `name` is required.- Use `add_trip_by_driver` to publish a trip. Collect route, `departure_date`, and `departure_time`.- When a driver asks to delete, cancel, edit, or modify an existing trip, do not use WhatsApp interactive list responses. Instead invoke `initiate_trip_action` to send the driver a numbered list of their active trips, then let the driver reply with the trip number.- When the driver replies with a trip number, use `delete_trip_by_number` or `modify_trip_by_number` as appropriate; the tool will map the one-based trip number to the trip ID using the active trip list ordered from oldest to newest.- After the driver selects a trip to modify, use `modify_trip_by_number` with `trip_number`, `field`, and `value`. Do not pass `trip_id` directly.- For function arguments, use Arabic text for `departure`, `destination`, `vehicle_type`, and time bucket labels. Keep digits and exact times in English format.- Never pass `phone_number` in tool arguments; the WhatsApp session supplies it.- Never invent trips, prices, or booking confirmations.12alter table public.customers add column if not exists session_data jsonb not null default '{}'::jsonb;128 unmodified lines12913013113213313413524 unmodified lines160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210175 unmodified lines38638738838939039139239339439539639739839940040140240340440540640740840941018 unmodified lines4294304314324334344351 unmodified line437438439440441442443444445446447448449450451452128 unmodified lines "name": name, "preferred_language": preferred_language, "user_mode": None, "session_data": {}, } self.customers_by_remote_jid[remote_jid] = customer elif name:24 unmodified lines return customer raise KeyError(customer_id)
async def get_customer_session(self, customer_id: str) -> dict[str, Any]: for customer in self.customers_by_phone.values(): if customer["id"] == customer_id: return dict(customer.get("session_data") or {}) return {}
async def update_customer_session( self, *, customer_id: str, session_data: dict[str, Any], ) -> dict[str, Any]: for customer in self.customers_by_phone.values(): if customer["id"] == customer_id: customer["session_data"] = session_data return customer raise KeyError(customer_id)
async def set_customer_session_field( self, *, customer_id: str, key: str, value: Any, ) -> dict[str, Any]: session_data = await self.get_customer_session(customer_id) session_data[key] = value return await self.update_customer_session( customer_id=customer_id, session_data=session_data, )
async def clear_customer_session_field( self, *, customer_id: str, key: str, ) -> dict[str, Any]: session_data = await self.get_customer_session(customer_id) session_data.pop(key, None) return await self.update_customer_session( customer_id=customer_id, session_data=session_data, )
async def message_exists(self, whatsapp_message_id: str) -> bool: return any( message.get("whatsapp_message_id") == whatsapp_message_id175 unmodified lines async def get_trip_by_id(self, trip_id: str) -> dict[str, Any] | None: return self.trips_by_id.get(trip_id)
async def update_driver_trip( self, trip_id: str, updates: dict[str, Any], ) -> dict[str, Any]: trip = self.trips_by_id[trip_id] trip.update(updates) return trip
async def cancel_driver_trip(self, trip_id: str) -> dict[str, Any]: trip = self.trips_by_id[trip_id] trip["status"] = "cancelled" return trip
async def delete_trip_embedding(self, trip_id: str) -> None: self.trip_embeddings = [ row for row in self.trip_embeddings if row.get("trip_id") != trip_id ]
async def upsert_trip_embeddings(self, trip_embeddings: list[dict[str, Any]]) -> int: self.trip_embeddings.extend(trip_embeddings) return len(trip_embeddings)18 unmodified lines def __init__(self, *, fail: bool = False) -> None: self.fail = fail self.sent: list[tuple[str, str]] = [] self.interactive_lists: list[tuple[str, dict[str, Any]]] = []
async def send_text(self, to_phone: str, text: str) -> dict[str, Any]: if self.fail:1 unmodified line self.sent.append((to_phone, text)) return {"messages": [{"id": "sent"}]}
async def send_interactive_list( self, to_phone: str, interactive: dict[str, Any], ) -> dict[str, Any]: if self.fail: raise RuntimeError("send failed") self.interactive_lists.append((to_phone, interactive)) return {"messages": [{"id": "sent-interactive"}]}
class FakeAI: def __init__(self, reply: str = "Here is your reply") -> None:121 unmodified lines122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256121 unmodified lines "switch_to_driver", } assert "travel booking assistant" in ai.calls[0]["messages"][0]["content"]
@pytest.mark.asyncioasync def test_conversation_uses_driver_tools_when_user_mode_is_driver(settings): repository = FakeRepository() customer = await repository.upsert_customer(remote_jid="967700000010", name="Ali") customer["user_mode"] = "driver" ai = FakeAI(reply="Driver reply") whatsapp = FakeWhatsApp() service = ConversationService( repository=repository, embeddings=FakeEmbeddings(), whatsapp=whatsapp, ai=ai, settings=settings, )
await service.handle_inbound_message( WhatsAppInboundMessage( message_id="wamid.driver", from_phone="967700000010", text="Check my trips", profile_name="Ali", ) )
tool_names = {tool["function"]["name"] for tool in ai.calls[0]["tools"]} assert tool_names == { "about_falsa", "check_driver_info", "check_driver_trips", "add_driver_car", "add_trip_by_driver", "delete_trip_by_number", "modify_trip_by_number", "initiate_trip_action", "update_trip_field", "switch_to_passenger", }
@pytest.mark.asyncioasync def test_conversation_handles_delete_interactive_reply(settings): repository = FakeRepository() customer = await repository.upsert_customer(phone_number="967700000010", name="Ali") customer["user_mode"] = "driver" repository.drivers_by_phone["967700000010"] = { "id": "driver-1", "name": "Ali", "phone_number": "967700000010", } repository.trips_by_id["trip-1"] = { "id": "trip-1", "driver_id": "driver-1", "departure": "Aden", "destination": "Mukalla", "departure_date": "2026-12-01", "departure_time": "morning", "status": "active", "driver_cars": {"car_type": "SUV"}, "drivers": {"name": "Ali"}, } repository.trip_embeddings.append({"trip_id": "trip-1"}) ai = FakeAI() service = ConversationService( repository=repository, embeddings=FakeEmbeddings(), whatsapp=FakeWhatsApp(), ai=ai, settings=settings, )
reply = await service.handle_inbound_message( WhatsAppInboundMessage( message_id="wamid.delete", from_phone="967700000010", text="Noon - Mukalla", message_type="interactive", interactive_reply_id="DELETE_trip-1", ) )
assert reply == "Success! Your trip has been canceled." assert repository.trips_by_id["trip-1"]["status"] == "cancelled" assert repository.trip_embeddings == [] assert ai.calls == []
@pytest.mark.asyncioasync def test_conversation_handles_modify_interactive_reply(settings): repository = FakeRepository() customer = await repository.upsert_customer(phone_number="967700000010", name="Ali") customer["user_mode"] = "driver" repository.drivers_by_phone["967700000010"] = { "id": "driver-1", "name": "Ali", "phone_number": "967700000010", } repository.trips_by_id["trip-1"] = { "id": "trip-1", "driver_id": "driver-1", "departure": "Aden", "destination": "Mukalla", "departure_date": "2026-12-01", "departure_time": "morning", "status": "active", "driver_cars": {"car_type": "SUV"}, "drivers": {"name": "Ali"}, } ai = FakeAI(reply="What would you like to change?") service = ConversationService( repository=repository, embeddings=FakeEmbeddings(), whatsapp=FakeWhatsApp(), ai=ai, settings=settings, )
reply = await service.handle_inbound_message( WhatsAppInboundMessage( message_id="wamid.modify", from_phone="967700000010", text="Morning - Mukalla", message_type="interactive", interactive_reply_id="MODIFY_trip-1", ) )
assert reply == "What would you like to change?" session = await repository.get_customer_session(customer["id"]) assert session["active_edit_trip_id"] == "trip-1" assert ai.calls[0]["messages"][-1]["content"].startswith("SYSTEM: Driver selected trip trip-1")14 unmodified lines15161718192021227 unmodified lines303132313314 unmodified lines names = {schema["function"]["name"] for schema in get_tool_schemas("driver")} assert "search_trips" not in names assert "create_booking_lead" not in names assert "initiate_trip_action" in names assert "update_trip_field" in names assert "switch_to_passenger" in names
7 unmodified lines
def test_all_tool_schemas_include_every_tool(): names = {schema["function"]["name"] for schema in get_all_tool_schemas()} assert len(names) == 10 assert len(names) == 14520 unmodified lines521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637520 unmodified lines assert result.ok is True assert customer["user_mode"] == "passenger" assert customer["name"] == "Existing"
def _driver_setup(repository: FakeRepository, *, phone: str = "967700000010") -> None: repository.drivers_by_phone[phone] = { "id": "driver-1", "name": "Ali", "phone_number": phone, } repository.trips_by_id["trip-1"] = { "id": "trip-1", "driver_id": "driver-1", "departure": "عدن", "destination": "المكلا", "departure_date": "2026-12-01", "departure_time": "morning", "available_seats": 2, "total_seats": 4, "price": "80.00", "status": "active", "driver_cars": {"car_type": "SUV"}, "drivers": {"name": "Ali"}, }
@pytest.mark.asyncioasync def test_initiate_trip_action_sends_whatsapp_list(): repository = FakeRepository() whatsapp = FakeWhatsApp() _driver_setup(repository) handlers = make_handlers( repository=repository, whatsapp=whatsapp, sender_phone="967700000010", )
result = await handlers.initiate_trip_action({"action_type": "DELETE"})
assert result.ok is True assert result.data["count"] == 1 assert "Pausing for response" in result.data["message"] assert len(whatsapp.interactive_lists) == 1 _, interactive = whatsapp.interactive_lists[0] assert interactive["action"]["sections"][0]["rows"][0]["id"] == "DELETE_trip-1"
@pytest.mark.asyncioasync def test_initiate_trip_action_returns_no_trips_message(): repository = FakeRepository() _driver_setup(repository) repository.trips_by_id.clear() handlers = make_handlers(repository=repository, sender_phone="967700000010")
result = await handlers.initiate_trip_action({"action_type": "MODIFY"})
assert result.ok is True assert result.data["count"] == 0 assert "No trips found" in result.data["message"]
@pytest.mark.asyncioasync def test_delete_trip_by_number_cancels_trip(): repository = FakeRepository() _driver_setup(repository) handlers = make_handlers(repository=repository, sender_phone="967700000010")
result = await handlers.delete_trip_by_number({"trip_number": 1})
assert result.ok is True assert result.data["trip_number"] == 1 assert result.data["trip_id"] == "trip-1" assert repository.trips_by_id["trip-1"]["status"] == "cancelled"
@pytest.mark.asyncioasync def test_modify_trip_by_number_updates_trip_field(): repository = FakeRepository() _driver_setup(repository) handlers = make_handlers(repository=repository, sender_phone="967700000010")
result = await handlers.modify_trip_by_number( {"trip_number": 1, "field": "departure", "value": "تعز"} )
assert result.ok is True assert result.data["trip_number"] == 1 assert result.data["field"] == "departure" assert result.data["value"] == "تعز" assert repository.trips_by_id["trip-1"]["departure"] == "تعز"
@pytest.mark.asyncioasync def test_update_trip_field_uses_active_session_and_clears_it(): repository = FakeRepository() customer = await repository.upsert_customer(phone_number="967700000010") await repository.set_customer_session_field( customer_id=customer["id"], key="active_edit_trip_id", value="trip-1", ) _driver_setup(repository) handlers = make_handlers( repository=repository, customer=customer, sender_phone="967700000010", )
result = await handlers.update_trip_field( {"field": "pickup_time", "value": "15:00"}, )
assert result.ok is True assert repository.trips_by_id["trip-1"]["departure_time"] == "noon" assert await repository.get_customer_session(customer["id"]) == {} assert len(repository.trip_embeddings) == 112345678910111213141516171819202122232425262728from app.whatsapp.trip_selection import build_trip_selection_list, parse_trip_action_reply
def test_parse_trip_action_reply(): assert parse_trip_action_reply("DELETE_trip-1") == ("DELETE", "trip-1") assert parse_trip_action_reply("MODIFY_abc-123") == ("MODIFY", "abc-123") assert parse_trip_action_reply("bad") is None
def test_build_trip_selection_list_text_message(): result = build_trip_selection_list( trips=[ { "id": "trip-1", "departure": "Aden", "destination": "Very Long Destination Name Here", "departure_date": "2026-12-01", "departure_time": "noon", } ], action_type="DELETE", )
assert result["type"] == "text" body = result["text"]["body"] assert "📋" in body assert "🗑️" in body assert "قائمة الرحلات" in body.github/prompts/plan-mergeDriverChecksAddTripTools.prompt.mdAdded+61
app/ai/orchestrator.py+1-2
app/ai/tool_schemas.py+153
app/api/routes.py+3-3
app/database/supabase.py+90
app/models/domain.py+2
app/services/conversation_service.py+125-2
app/services/trip_indexing.py+4
app/tools/handlers.py+291-7
app/whatsapp/client.py+33-2
app/whatsapp/parser.py+33-2
app/whatsapp/trip_selection.pyAdded+91
prompts/system_driver.md+3
supabase/migrations/202606140001_customer_session_data.sqlAdded+2
tests/conftest.py+76
tests/test_conversation_service.py+132
tests/test_tool_schemas.py+3-1
tests/test_tools.py+114
tests/test_trip_selection.pyAdded+28