> For the complete documentation index, see [llms.txt](https://docs.snapfix.com/llms.txt). Markdown versions of documentation pages are available by appending `.md` to page URLs; this page is available as [Markdown](https://docs.snapfix.com/engineering-reference/api/ai.md).

# AI API

{% hint style="info" %}
Draft, written by an agent and not yet checked by a person ([how to read these docs](https://docs.snapfix.com/how-to-read.md)). [Source on GitHub](https://github.com/snapfix/docs/blob/main/spec/api/ai.md).
{% endhint %}

AI suggestions while creating a task, the suggestion service behind them, Simon (the AI assistant), and the older chatbot and voice task actions.

* **Services:** `api_php_live_v2` at `https://z4.snapfix.com` (`/v1/app`, `/v1/guest`); `php-apis` at `https://z1.snapfix.com/api/snapfix/index.php`; `php-apis web` at `https://z1.snapfix.com/api/snapfix/web/index.php`; `snapfix_ai_agent` (Simon) at `https://ai-agent.snapfix.com` \[[ASK-8](https://github.com/snapfix/docs/blob/main/ASK.md#ask-8-confirm-the-environments), [ASK-13](https://github.com/snapfix/docs/blob/main/ASK.md#ask-13-which-services-and-scheduled-jobs-run-in-production)]; `aitask_pyserver`, whose host isn't in any repo: api\_php\_live\_v2 reads it from `AI_SUGGESTION_URL` (api\_php\_live\_v2 @ ef3c4319f6, `config/ai_suggestions.php:17`) \[[ASK-12](https://github.com/snapfix/docs/blob/main/ASK.md#ask-12-which-settings-do-the-production-api-servers-use)].
* **Simon versions:** the Simon sections describe `snapfix_ai_agent` `main` @ e5e18caef5 (service `snapfix-simon-agent-v2` 0.3.0), which runs on the test host `https://ai-agent-test.snapfix.com`. Production, `https://ai-agent.snapfix.com`, runs the older agent (`snapfix-taskops-agent` 0.2.0, the code in `app/` on the branches `refactor/development`, `development` and `master-deprecated`). It also serves `GET /simon/sessions`, `DELETE /simon/sessions`, `PATCH /simon/sessions/{session_id}`, `GET` and `DELETE /simon/jobs/{job_id}`, `POST /simon/feedback` and `/brand-standards/*`, and its `GET /simon/session/{session_id}` returns the session's `turns` (snapfix\_ai\_agent @ bcbd010, `app/api/simon.py:93-338`, `app/modules/brand_standards/router.py`; production answers `401` without a token on those routes and its root page names the service, probed 2026-11-14) \[[ASK-13](https://github.com/snapfix/docs/blob/main/ASK.md#ask-13-which-services-and-scheduled-jobs-run-in-production)].
* **Auth:** api\_php\_live\_v2: user token (authpy JWT in `Authorization: Bearer`) and the `/v1/app` checks on `/v1/app/tasks/suggestions/*`; one shared Basic login on `/v1/guest/suggestions/*`, which is also in public web bundles. Neither copy checks that the caller belongs to the site or group a request names. php-apis: user token (Bearer JWT, if `JWT_AUTH_ENABLED` is on \[[ASK-12](https://github.com/snapfix/docs/blob/main/ASK.md#ask-12-which-settings-do-the-production-api-servers-use)]); the actions act on the user named in the request, not the token's user. snapfix\_ai\_agent: user token, decoded without checking its signature. aitask\_pyserver: the `/api/v1/ai-task` routes need Basic auth only when `AI_TASK_BASIC_AUTH_USERNAME` and `AI_TASK_BASIC_AUTH_PASSWORD` are both set; both are empty in the repo, and with either one blank nothing is checked \[[ASK-12](https://github.com/snapfix/docs/blob/main/ASK.md#ask-12-which-settings-do-the-production-api-servers-use), [ASK-176](https://github.com/snapfix/docs/blob/main/ASK.md#ask-176-which-ai-suggestion-settings-and-logins-does-production-use)]. The experiment routes need no login.
* **Used by:** web\_app\_v2 (task creation's suggestions, the Simon panel), iOS and Android (task creation, Simon, voice tasks, the AI log sync), qr\_forms (the QR form's title and room suggestions), authpy (the QR form's room, area, tag and assignee suggestions), api\_php\_live\_v2 (forwards the suggestion routes to aitask\_pyserver, and asks it about Open API and vendor API tasks), Kubernetes (Simon's health probes); 45 of the 69 endpoints have no known caller.
* **Answers and errors:** the api\_php\_live\_v2 envelope and the codes every `/v1/app` route can return are in [Tasks: common errors](https://docs.snapfix.com/engineering-reference/api/tasks.md#common-errors). php-apis answers HTTP `200` with `result` `false` for its own errors ([Responses](https://docs.snapfix.com/engineering-reference/api.md#responses)). aitask\_pyserver answers with the [AI task envelope](#ai-task-envelope), `status` `success` or `fail`, also for its errors; only its login (`401`) and validation (`422`) errors are FastAPI's `{"detail": ...}`. Simon answers JSON with `status` `true`, a chat turn as server-sent events, and its errors before a stream starts as FastAPI's `{"detail": ...}`. Each section lists its own errors.
* **Logs:** api\_php\_live\_v2 writes each call to its request log, with the response when it is under about 100 KB, and writes each suggestion call's request fields and answer to its Laravel log; `redact` removes only `apiKey`. php-apis stores each request body and each response under about 100 KB in its daily request log. aitask\_pyserver writes a row to [`ai_token_usage`](https://docs.snapfix.com/engineering-reference/db/tables/ai_token_usage.md) for each answered AI call, with up to 500 characters of the request's title and messages and up to 1,000 of the answer, unless `AI_TASK_TOKEN_USAGE_LOG_ENABLED` is off; no code in the repos deletes these rows. Simon saves each turn in `simon_messages` \[[ASK-179](https://github.com/snapfix/docs/blob/main/ASK.md#ask-179-which-database-does-snapfix-ai-use-in-production-and-are-the-ai_agent_-tables-still-used)].

| Method | Path                                                                          | Service            | Purpose                                                                                                                                                                          |
| ------ | ----------------------------------------------------------------------------- | ------------------ | -------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- |
| POST   | [`/v1/app/tasks/suggestions/areas`](#post-v1apptaskssuggestionsareas)         | api\_php\_live\_v2 | Suggest areas for a new or open task                                                                                                                                             |
| POST   | [`/v1/app/tasks/suggestions/assignees`](#post-v1apptaskssuggestionsassignees) | api\_php\_live\_v2 | Suggest assignees for a new or open task                                                                                                                                         |
| POST   | [`/v1/app/tasks/suggestions/group`](#post-v1apptaskssuggestionsgroup)         | api\_php\_live\_v2 | Suggest a group for a new task                                                                                                                                                   |
| POST   | [`/v1/app/tasks/suggestions/rooms`](#post-v1apptaskssuggestionsrooms)         | api\_php\_live\_v2 | Suggest rooms for a new or open task                                                                                                                                             |
| POST   | [`/v1/app/tasks/suggestions/tags`](#post-v1apptaskssuggestionstags)           | api\_php\_live\_v2 | Suggest tags for a new or open task                                                                                                                                              |
| POST   | [`/v1/app/tasks/suggestions/title`](#post-v1apptaskssuggestionstitle)         | api\_php\_live\_v2 | Suggest a title for a new task from its photo or text                                                                                                                            |
| POST   | [`/v1/guest/suggestions/areas`](#post-v1guestsuggestionsareas)                | api\_php\_live\_v2 | Suggest areas for a new task, without login                                                                                                                                      |
| POST   | [`/v1/guest/suggestions/assignees`](#post-v1guestsuggestionsassignees)        | api\_php\_live\_v2 | Suggest assignees for a new task, without login                                                                                                                                  |
| POST   | `/v1/guest/suggestions/group`                                                 | api\_php\_live\_v2 | Suggest a group for a new task, without login (no caller)                                                                                                                        |
| POST   | [`/v1/guest/suggestions/rooms`](#post-v1guestsuggestionsrooms)                | api\_php\_live\_v2 | Suggest rooms for a new task, without login                                                                                                                                      |
| POST   | [`/v1/guest/suggestions/tags`](#post-v1guestsuggestionstags)                  | api\_php\_live\_v2 | Suggest tags for a new task, without login                                                                                                                                       |
| POST   | [`/v1/guest/suggestions/title`](#post-v1guestsuggestionstitle)                | api\_php\_live\_v2 | Suggest a title for a new task, without login                                                                                                                                    |
| ANY    | `?action=ai_voice_task`                                                       | php-apis           | Fill in the titles, images and transcripts of today's voice tasks, at every site (no caller)                                                                                     |
| ANY    | `?action=chatbot_check_jobcreate_permission`                                  | php-apis           | Chatbot: check whether the user may create tasks (no caller)                                                                                                                     |
| ANY    | `?action=chatbot_check_usercreate_permission`                                 | php-apis           | Chatbot: check whether the user may create users (no caller)                                                                                                                     |
| ANY    | `?action=chatbot_create_job`                                                  | php-apis           | Chatbot: create a task (no caller)                                                                                                                                               |
| ANY    | `?action=chatbot_create_user`                                                 | php-apis           | Chatbot: create a user (no caller)                                                                                                                                               |
| ANY    | `?action=chatbot_list_business`                                               | php-apis           | Chatbot: list groups (no caller)                                                                                                                                                 |
| ANY    | `?action=chatbot_list_parent`                                                 | php-apis           | Chatbot: list sites (no caller)                                                                                                                                                  |
| ANY    | `?action=chatbot_read_users`                                                  | php-apis           | Chatbot: read users (no caller)                                                                                                                                                  |
| ANY    | `?action=chatbot_validate_parent_user`                                        | php-apis           | Chatbot: read a site user (no caller)                                                                                                                                            |
| POST   | [`?action=save_ai_job_log`](#post-actionsave_ai_job_log)                      | php-apis           | Save the AI job log rows the apps queued                                                                                                                                         |
| POST   | [`?action=upload_voice_task_file`](#post-actionupload_voice_task_file)        | php-apis           | Upload a voice task file; the AI step is switched off \[[ASK-15](https://github.com/snapfix/docs/blob/main/ASK.md#ask-15-is-snapfix-ai-for-voice-tasks-switched-off-on-purpose)] |
| ANY    | `?action=aicontextbusinesses`                                                 | php-apis web       | AI context: groups (no caller)                                                                                                                                                   |
| ANY    | `?action=aicontextpermissions`                                                | php-apis web       | AI context: permissions (no caller)                                                                                                                                              |
| ANY    | `?action=aireportsredirect`                                                   | php-apis web       | Tell a caller whether a large analytics request belongs in Reports; reads no data (`aiReportsRedirectHints`) (no caller)                                                         |
| ANY    | `?action=auto_assign_tasks`                                                   | php-apis web       | Auto-assign tasks (`AIFunctions::autoAssignTasks`) (no caller)                                                                                                                   |
| ANY    | `?action=webcust_create_voice_job`                                            | php-apis web       | Create a task from a voice recording (no caller)                                                                                                                                 |
| POST   | [`/simon/chat/stream`](#post-simonchatstream)                                 | snapfix\_ai\_agent | Chat with Simon; answers with server-sent events                                                                                                                                 |
| GET    | [`/simon/messages`](#get-simonmessages)                                       | snapfix\_ai\_agent | Get a chat session's messages                                                                                                                                                    |
| GET    | [`/simon/session/{session_id}`](#get-simonsessionsession_id)                  | snapfix\_ai\_agent | Get a chat session; returns only its ID                                                                                                                                          |
| DELETE | [`/simon/session/{session_id}`](#delete-simonsessionsession_id)               | snapfix\_ai\_agent | Delete a chat session                                                                                                                                                            |
| GET    | [`/health`](#get-health)                                                      | snapfix\_ai\_agent | Health check: `status`, `service` and `version`                                                                                                                                  |
| POST   | [`/api/v1/ai-task/area`](#post-apiv1ai-taskarea)                              | aitask\_pyserver   | Suggest areas                                                                                                                                                                    |
| POST   | [`/api/v1/ai-task/assignee`](#post-apiv1ai-taskassignee)                      | aitask\_pyserver   | Suggest the assignee                                                                                                                                                             |
| POST   | `/api/v1/ai-task/assignee-local-01`                                           | aitask\_pyserver   | Legacy version of `/api/v1/ai-task/assignee` (no caller)                                                                                                                         |
| POST   | [`/api/v1/ai-task/group`](#post-apiv1ai-taskgroup)                            | aitask\_pyserver   | Suggest the group                                                                                                                                                                |
| POST   | `/api/v1/ai-task/group-local-01`                                              | aitask\_pyserver   | Legacy version of `/api/v1/ai-task/group` (no caller)                                                                                                                            |
| POST   | [`/api/v1/ai-task/room`](#post-apiv1ai-taskroom)                              | aitask\_pyserver   | Suggest rooms                                                                                                                                                                    |
| POST   | [`/api/v1/ai-task/tag`](#post-apiv1ai-tasktag)                                | aitask\_pyserver   | Suggest tags                                                                                                                                                                     |
| POST   | `/api/v1/ai-task/tag-local-01`                                                | aitask\_pyserver   | Legacy version of `/api/v1/ai-task/tag` (no caller)                                                                                                                              |
| POST   | [`/api/v1/ai-task/title`](#post-apiv1ai-tasktitle)                            | aitask\_pyserver   | Suggest a title from the task's photo or text, and cache the description and tags under `imageCtx`                                                                               |
| POST   | `/api/v1/ai-task/title-local-01`                                              | aitask\_pyserver   | Legacy version of `/api/v1/ai-task/title` (no caller)                                                                                                                            |
| POST   | `/caption/blip`                                                               | aitask\_pyserver   | Experiment: caption with BLIP (no caller)                                                                                                                                        |
| POST   | `/ocr/tesseract`                                                              | aitask\_pyserver   | Experiment: text recognition with Tesseract (no caller)                                                                                                                          |
| POST   | `/pipeline/blip-openai`                                                       | aitask\_pyserver   | Experiment: BLIP then OpenAI (no caller)                                                                                                                                         |
| POST   | `/retrieval/clip-qdrant`                                                      | aitask\_pyserver   | Experiment: CLIP retrieval from Qdrant (no caller)                                                                                                                               |
| POST   | `/retrieval/clip-qdrant/seed`                                                 | aitask\_pyserver   | Experiment: seed the CLIP retrieval index in Qdrant (no caller)                                                                                                                  |
| POST   | `/suggest/assignee/bge-qdrant-only`                                           | aitask\_pyserver   | Experiment: suggest an assignee with BGE embeddings and Qdrant only (no caller)                                                                                                  |
| POST   | `/suggest/assignee/blip-openai-sentence-qdrant`                               | aitask\_pyserver   | Experiment: suggest an assignee with BLIP, OpenAI, sentence embeddings and Qdrant (no caller)                                                                                    |
| POST   | `/suggest/assignee/custom-scoring`                                            | aitask\_pyserver   | Experiment: suggest an assignee with custom scoring (no caller)                                                                                                                  |
| POST   | `/suggest/assignee/llm-openai-rank`                                           | aitask\_pyserver   | Experiment: rank assignees with OpenAI (no caller)                                                                                                                               |
| GET    | `/suggest/assignee/ml-lightgbm/status`                                        | aitask\_pyserver   | Experiment: status of the LightGBM assignee model (no caller)                                                                                                                    |
| POST   | `/suggest/assignee/rag-anthropic-rank`                                        | aitask\_pyserver   | Experiment: rank assignees with retrieval and Anthropic (no caller)                                                                                                              |
| POST   | `/suggest/assignee/rag-kb/seed`                                               | aitask\_pyserver   | Experiment: seed the assignee knowledge base (no caller)                                                                                                                         |
| POST   | `/suggest/assignee/rag-openai-rank`                                           | aitask\_pyserver   | Experiment: rank assignees with retrieval and OpenAI (no caller)                                                                                                                 |
| POST   | `/suggest/assignee/rule-workload-only`                                        | aitask\_pyserver   | Experiment: suggest an assignee by workload rules only (no caller)                                                                                                               |
| POST   | `/suggest/group/anthropic-vision-pick`                                        | aitask\_pyserver   | Experiment: pick a group with Anthropic vision (no caller)                                                                                                                       |
| POST   | `/suggest/group/blip-openai-clip-qdrant`                                      | aitask\_pyserver   | Experiment: suggest a group with BLIP, OpenAI, CLIP and Qdrant (no caller)                                                                                                       |
| POST   | `/suggest/group/clip-qdrant`                                                  | aitask\_pyserver   | Experiment: suggest a group with CLIP and Qdrant (no caller)                                                                                                                     |
| POST   | `/suggest/group/clip-qdrant/seed`                                             | aitask\_pyserver   | Experiment: seed the CLIP group index (no caller)                                                                                                                                |
| GET    | `/suggest/group/ml-classical/status`                                          | aitask\_pyserver   | Experiment: status of the classical machine-learning group model (no caller)                                                                                                     |
| POST   | `/suggest/group/openai-vision-pick`                                           | aitask\_pyserver   | Experiment: pick a group with OpenAI vision (no caller)                                                                                                                          |
| POST   | `/suggest/group/sentence-openai-shortlist`                                    | aitask\_pyserver   | Experiment: suggest a group from a sentence-embedding shortlist and OpenAI (no caller)                                                                                           |
| POST   | `/suggest/group/sentence-qdrant`                                              | aitask\_pyserver   | Experiment: suggest a group with sentence embeddings and Qdrant (no caller)                                                                                                      |
| POST   | `/suggest/group/sentence-qdrant/seed`                                         | aitask\_pyserver   | Experiment: seed the sentence-embedding group index (no caller)                                                                                                                  |
| POST   | `/vision/anthropic`                                                           | aitask\_pyserver   | Experiment: vision with Anthropic (no caller)                                                                                                                                    |
| POST   | `/vision/gemini`                                                              | aitask\_pyserver   | Experiment: vision with Google Gemini (no caller)                                                                                                                                |
| POST   | `/vision/openai`                                                              | aitask\_pyserver   | Experiment: vision with OpenAI (no caller)                                                                                                                                       |

Notes on the table:

* Rows marked "(no caller)" have no caller in any client or service repo; a call counts only when the calling code runs. Whether to keep them is open \[[ASK-11](https://github.com/snapfix/docs/blob/main/ASK.md#ask-11-which-unused-api-endpoints-are-still-needed)]. `aicontextbusinesses`, `aicontextpermissions` and `aireportsredirect` may serve an AI tool outside these repos. What the uncalled routes can do is in [Uncalled routes](#uncalled-routes).
* `save_ai_job_log` is `POST` because both apps send it that way; the stub had `ANY`. The php-apis dispatchers accept any method except `OPTIONS` ([Requests](https://docs.snapfix.com/engineering-reference/api.md#requests)).
* Five of the six guest routes have callers: qr\_forms calls `title` and `rooms`, and authpy calls `rooms`, `areas`, `tags` and `assignees`. Nothing calls the guest group route.
* `GET /health` (Simon) is not in the stub; it has a row because the service's own Helm chart probes it.
* The apps also call Simon paths that only production's older agent serves: [Calls only production serves](#calls-only-production-serves).

## Related routes

* **Uploads:** `POST /v1/app/upload/image`, `/video`, `/voice` and `/document` are in [Files](https://docs.snapfix.com/engineering-reference/api/files.md). When the site's switch for that file type is on (`fAiImageEnable`, `fAiVideoEnable`, `fAiVoiceEnable` or `fAiDocumentEnable`), they also send the file to the AI provider for tags, a summary and, for audio and video, a transcript, and they wait for it before they answer. The three request flags default to `1` (api\_php\_live\_v2 @ ef3c4319f6, `app/Http/Requests/v1/AudioUploadRequest.php:34-36`, `app/Http/Controllers/v1/Versions/v1_0/App/FileUploadController.php:58`, `:97`, `:138`, `:181`).
* **Open API and vendor API tasks:** `POST /v1/public/tasks` and `POST /v1/xvendor/tasks` ([Open API](https://docs.snapfix.com/engineering-reference/api/open-api.md)) ask the [group route](#post-apiv1ai-taskgroup) for the group when a request has no group, with `snapfixSource` `public` or `x-vendor` and the caller's API key in the body; a site with AI suggestions off must send a group. On a site with AI suggestions on, a queued job (`ApplyAiTaskSuggestions`) then asks the [tag](#post-apiv1ai-tasktag), [assignee](#post-apiv1ai-taskassignee), [room](#post-apiv1ai-taskroom) and [area](#post-apiv1ai-taskarea) routes and fills what the request left out (api\_php\_live\_v2 @ ef3c4319f6, `app/Http/Controllers/v1/Versions/v1_0/XVendor/JobController.php:209-227`, `:632-634`, `app/Services/Suggestions/AiTaskCreationService.php:101-111`, `:139-170`).
* **The QR pipeline's task changes:** authpy applies the guest suggestions through `/v1/internal/tasks/room-add`, `area-add`, `tag/multi` and `assign/multi` ([Internal](https://docs.snapfix.com/engineering-reference/api/internal.md)).
* **Auto Assign:** the housekeeping auto-assign routes are in [Housekeeping](https://docs.snapfix.com/engineering-reference/api/housekeeping.md). Which provider runs in production is open \[[ASK-91](https://github.com/snapfix/docs/blob/main/ASK.md#ask-91-which-auto-assign-provider-runs-in-production-and-may-it-send-data-to-an-ai-service)].
* **Screens and features:** [AI screens](https://docs.snapfix.com/how-the-apps-work/screens/ai.md), [Voice task](https://docs.snapfix.com/how-the-apps-work/screens/tasks/voice-task.md), [Snapfix Recommends](https://docs.snapfix.com/product/features/ai/snapfix-recommends.md) and [Snapfix AI](https://docs.snapfix.com/product/features/ai/snapfix-ai.md).

## How the suggestion routes work

The six suggestion routes come in two copies on api\_php\_live\_v2: one for signed-in users (`/v1/app/tasks/suggestions/*`) and one for guests (`/v1/guest/suggestions/*`). Both copies run the same handlers, and neither does AI work itself: each call becomes one call to aitask\_pyserver (api\_php\_live\_v2 @ ef3c4319f6, `routes/job.php:109-117`, `routes/guest.php:36-44`, `app/Traits/Job/JobSuggestions.php:22-123`).

```mermaid
sequenceDiagram
    participant C as App or QR form
    participant L as api_php_live_v2
    participant A as aitask_pyserver
    participant O as OpenAI
    C->>L: POST .../suggestions/title (photo)
    L->>A: POST /api/v1/ai-task/title (uploaded_image)
    A->>O: photo or text
    A-->>L: title, imageCtx
    L-->>C: title, imageRef
    C->>L: POST .../suggestions/group, tags, ... (imageRef)
    L->>A: POST /api/v1/ai-task/group, tag, ... (imageCtx)
    A->>O: text and the site's or group's names
    A-->>L: matches
    L-->>C: suggestion list
```

* **Forwarding:** the provider posts to `AI_SUGGESTION_URL` plus `/api/v1/ai-task/` and `title`, `group`, `tag`, `assignee`, `room` or `area`, as multipart, with its own Basic login (`AI_SUGGESTION_USERNAME`, `AI_SUGGESTION_PASSWORD`) (`app/Services/Suggestions/Providers/AISuggestionsServiceProvider.php:19-54`). `SUGGESTIONS_PROVIDER` picks the provider, `ai` by default (`config/ai_suggestions.php:11`). No timeout or retry is set: both lines are commented out (`AISuggestionsServiceProvider.php:28-29`).
* **Field names:** only the fields the route's rules name are passed on. The provider renames `parentUuid` to `siteUUID`, `businessUuid` to `groupUUID` and `imageRef` to `imageCtx`, and sends `file` as `uploaded_image` (`AISuggestionsServiceProvider.php:197-212`, `:265-282`). No rule names `jobUuid`, so it never reaches aitask\_pyserver; the title route drops `parentUuid` and `businessUuid`, and the group, rooms and areas routes drop `businessUuid`.
* **The caller:** on `/v1/app` the provider adds the signed-in user's ID as `userUUID` to every call (`AISuggestionsServiceProvider.php:43-45`; the user is set in `app/Http/Middleware/Authorize.php:41-48`). Guest calls have no user. aitask\_pyserver reads `userUUID` only on the [group route](#post-apiv1ai-taskgroup).
* **The photo once:** the title answer's `imageRef` is aitask\_pyserver's `imageCtx`, the key of the task's context (title, description, tags and messages) in Redis. It lives 24 hours (`AI_TASK_CACHE_TTL_SECONDS`, 86400 by default) under the prefix `ai_task:ctx:` (aitask\_pyserver @ 877304ec49, `app/config.py:187-188`). The clients send it to the other routes instead of the photo. A key is not tied to the site or user that made it.
* **The site's switch:** aitask\_pyserver refuses a site whose `fAiSuggestionEnabled` in [`tPri_SettingsParent`](https://docs.snapfix.com/engineering-reference/db/tables/tpri_settingsparent.md) is not `1`, but only when the request names a site (`app/api/v1/ai_task/router.py:210-229`). The title routes name no site, so the switch never applies to titles; the tag and assignee routes skip it for a blank site. The clients check the setting before they ask: the web reads the site's `aiSuggestionEnabled` (web\_app\_v2 @ 0989b8e685, `src/app/services/task/task-suggestion-helper/task-suggestion-helper.service.ts:61-63`), and qr\_forms asks only when the form's details say `aiSuggestionEnabled` is `1` (qr\_forms @ bdfc4f20a5, `src/app/pages/forms/components/report-issues-form/report-issues-form.component.ts:76`).
* **Membership:** no route checks that the caller belongs to the named site or group, so the tags, assignee, rooms and areas answers show names and IDs from any site or group whose ID the caller sends. Only the group route narrows its candidates, by `userUUID`.
* **Failures:** the provider turns any answer that is not HTTP 2xx with `status` `success`, and any exception, into an empty suggestion, and the route still answers `200`: `title` and `imageRef` `null` for titles, `[[]]` for groups, `[]` for the others (`AISuggestionsServiceProvider.php:49-77`). A site with the switch off, a photo over aitask\_pyserver's 6 MB limit, an expired `imageRef` and an AI outage all look like "no suggestion".
* **Guest callers:** qr\_forms calls the guest title route after the first photo on a QR form, then the guest rooms route with the title answer's `imageRef` (qr\_forms @ bdfc4f20a5, `src/app/services/form/form.service.ts:41-70`). After a QR form is posted to authpy's `/qr-form/<uuid>` with an `imageRef`, authpy runs a background pipeline: it calls the guest rooms, areas, tags and assignees routes at once, 30 seconds each, then adds the first room and area, every tag and every assignee to the new task through the internal task routes. A room picked on the form replaces the suggested room (authpy @ 5d5758661c, `model/feature_qrform.py:1027-1031`, `:1121-1243`, `:1311-1450`). The pipeline is on in code (`QR_SUGGESTIONS_PIPELINE_ENABLED`, `:1040`), and it uses the site of the group named in the posted form data. It reads the guest API's base URL (`LARAVEL_GUEST_API_URL`) and the value it sends as the `authorization` header (`LARAVEL_BASE_AUTH_TOKEN`) from `security.json`, which is not in the repo \[[ASK-176](https://github.com/snapfix/docs/blob/main/ASK.md#ask-176-which-ai-suggestion-settings-and-logins-does-production-use)]. A failed call is logged and the task keeps no suggestion.

## POST /v1/app/tasks/suggestions/areas

Suggests the area of a site that a task's photo or text points to. The new task form, and the task's page once the task exists, call it.

* **Auth:** user token and the `/v1/app` checks. The route does not check that the caller belongs to the site in `parentUuid`, so any signed-in user can ask for any site's areas.
* **Used by:** web (`TaskSuggestionHttpService.getSuggestionAreas`, from `task-rooms-and-areas-dialog.component.ts:299`, `task-create-dialog.component.ts:1534` and `task-suggestion-helper.service.ts:202`); iOS (`AITaskSuggestionViewModel.requestSuggestionsConcurrently`, from "Tag your task" and the task's page: ios @ aa31967ac8, `SnapFix/TagRequire/TagRequiredVC.swift:1763`, `SnapFix/MessagesVC/MessagesVC+AISuggestion.swift:65`); Android (`AiSuggestionsRepository.getAiAreaSuggestions`, from `TagRequiredDialog.java:497` and `JobChatFragment.java:15716`).

**Request** (multipart form, or JSON without a file)

| Name         | In   | Type   | Required        | Rules                                                                                                                  |
| ------------ | ---- | ------ | --------------- | ---------------------------------------------------------------------------------------------------------------------- |
| `parentUuid` | body | string | yes             | The site. Sent on as `siteUUID`                                                                                        |
| `title`      | body | string | one of the four | The task's title or text                                                                                               |
| `file`       | body | file   | one of the four | A photo: `jpg`, `jpeg`, `png` or `gif`, up to `FILE_MAX_SIZE` (102400 KB by default). Sent on as `uploaded_image`      |
| `imageRef`   | body | string | one of the four | The `imageRef` of an earlier [title answer](#title-suggestion-object). Sent on as `imageCtx`                           |
| `messages`   | body | string | one of the four | A JSON array of strings, such as the task's chat messages, passed on unchanged. aitask\_pyserver refuses anything else |

The clients also send `businessUuid` and `jobUuid`, which this route drops. The rules are in `app/Http/Requests/v1/Suggestions/AreaRoomRequest.php:15-26`.

**Response** `200`: a list with at most one [suggestion object](#suggestion-object), the first area of the site that matched. It is empty when nothing matched or the AI step failed.

```json
{
  "status": "success",
  "message": "Operation was successful",
  "data": [ { "uuid": "301", "name": "Lobby" } ]
}
```

**Errors:** [common errors](https://docs.snapfix.com/engineering-reference/api/tasks.md#common-errors); `422` with the first failed rule's message when `parentUuid` is missing, when none of the four content fields is sent, or when the file is not one of the image types ("The file field must be a file of type: jpg, jpeg, png, gif.") or is too big ("The file field must not be greater than 102400 kilobytes.") (`lang/en/validation.php:92`, `:97`).

**Side effects:** none in Snapfix's tables. One call to the [area route](#post-apiv1ai-taskarea) of aitask\_pyserver.

## POST /v1/app/tasks/suggestions/assignees

Suggests the members of a group who fit a task, from their past work in that group.

* **Auth:** user token and the `/v1/app` checks. The route does not check that the caller belongs to the group, so any signed-in user gets the names and user IDs of a group's members by sending its UUID.
* **Used by:** web (`TaskSuggestionHttpService.getSuggestionAssignees`, from `task-users-dialog.component.ts:317`, and from `task-create-dialog.component.ts:1539` and `task-suggestion-helper.service.ts:178` only when the caller's `aiAutoAssignEnabled` is on: `task-suggestion-helper.service.ts:65-67`); iOS (as [areas](#post-v1apptaskssuggestionsareas), when the user may assign and use AI auto-assign: `MessagesVC+AISuggestion.swift:233`); Android (`AiSuggestionsRepository.getAiAssigneesSuggestions`, from `TagRequiredDialog.java:489` and `JobChatFragment.java:15697`).

**Request** (multipart form, or JSON without a file)

| Name                                    | In   | Type   | Required        | Rules                                                      |
| --------------------------------------- | ---- | ------ | --------------- | ---------------------------------------------------------- |
| `parentUuid`                            | body | string | yes             | The site. Sent on as `siteUUID`                            |
| `businessUuid`                          | body | string | yes             | The group whose members are ranked. Sent on as `groupUUID` |
| `title`, `file`, `imageRef`, `messages` | body |        | one of the four | As for [areas](#post-v1apptaskssuggestionsareas)           |

**Response** `200`: a list of [suggestion objects](#suggestion-object), the user's ID as `uuid` and the name, best pick first: at most two with the default `AI_TASK_ASSIGNEE_TOP_N` (aitask\_pyserver @ 877304ec49, `app/config.py:238`). The AI's reasons and confidence are not passed on. The list is empty when no member has past work in the group or the AI step failed.

```json
{
  "status": "success",
  "message": "Operation was successful",
  "data": [ { "uuid": "200", "name": "Jane Smith" } ]
}
```

**Errors:** [common errors](https://docs.snapfix.com/engineering-reference/api/tasks.md#common-errors); `422` when `parentUuid` or `businessUuid` is missing, when no content field is sent, or for a bad file, as for areas.

**Side effects:** none in Snapfix's tables. One call to the [assignee route](#post-apiv1ai-taskassignee).

## POST /v1/app/tasks/suggestions/group

Suggests the group for a new task from its photo or text.

* **Auth:** user token and the `/v1/app` checks. The route checks no membership of the site. The provider sends the caller's `userUUID`, so aitask\_pyserver picks only among the site's groups where the caller is an admin or may create tasks (aitask\_pyserver @ 877304ec49, `app/api/v1/ai_task/router.py:730-735`, `:764`).
* **Used by:** web (`TaskSuggestionHttpService.getSuggestionGroup`, from `task-create-dialog.component.ts:583`); iOS (`AITaskSuggestionViewModel.requestGroupSuggestion`, from `ChatCreateTaskVC.swift:410` and `GuideAddUserSelectGroupVC.swift:875`); Android (`AiSuggestionsRepository.getAiGroupSuggestions`, from `GroupSelectFragment.java:475`, `CreateTaskBottomSheet.kt:452` and `RoomGroupSelectionBottomSheet.kt:205`).

**Request** (multipart form, or JSON without a file)

| Name                                    | In   | Type   | Required        | Rules                                            |
| --------------------------------------- | ---- | ------ | --------------- | ------------------------------------------------ |
| `parentUuid`                            | body | string | yes             | The site. Sent on as `siteUUID`                  |
| `title`, `file`, `imageRef`, `messages` | body |        | one of the four | As for [areas](#post-v1apptaskssuggestionsareas) |

**Response** `200`: a list with one [suggestion object](#suggestion-object): the group's `uuid`, `name` and `image` (`null` when the group has none).

```json
{
  "status": "success",
  "message": "Operation was successful",
  "data": [ { "uuid": "400", "name": "Housekeeping", "image": null } ]
}
```

When no group comes back, `data` is `[[]]`, not `[]`, because the handler wraps the empty answer in a list (`app/Traits/Job/JobSuggestions.php:49`). A site with AI suggestions off gets the same.

**Errors:** [common errors](https://docs.snapfix.com/engineering-reference/api/tasks.md#common-errors); `422` when `parentUuid` is missing, when no content field is sent, or for a bad file.

**Side effects:** none in Snapfix's tables. One call to the [group route](#post-apiv1ai-taskgroup).

## POST /v1/app/tasks/suggestions/rooms

Suggests the room of a site that a task's text names, for the new task form and the task's page.

* **Auth:** user token and the `/v1/app` checks. The route does not check that the caller belongs to the site, so any signed-in user can ask for any site's rooms.
* **Used by:** web (`TaskSuggestionHttpService.getSuggestionRooms`, from `task-rooms-and-areas-dialog.component.ts:279`, `task-create-dialog.component.ts:1533` and `task-suggestion-helper.service.ts:191`); iOS (as [areas](#post-v1apptaskssuggestionsareas)); Android (`AiSuggestionsRepository.getAiRoomSuggestions`, from `TagRequiredDialog.java:496` and `:507`, and `JobChatFragment.java:15710`).

**Request:** as [areas](#post-v1apptaskssuggestionsareas).

**Response** `200`: a list with at most one [suggestion object](#suggestion-object): the first room aitask\_pyserver matched to a room of the site. Names it could not match are left out. Empty when nothing matched.

```json
{
  "status": "success",
  "message": "Operation was successful",
  "data": [ { "uuid": "500", "name": "Room 101" } ]
}
```

**Errors:** as [areas](#post-v1apptaskssuggestionsareas).

**Side effects:** none in Snapfix's tables. One call to the [room route](#post-apiv1ai-taskroom).

## POST /v1/app/tasks/suggestions/tags

Suggests tags for a task from the tag folders of a group.

* **Auth:** user token and the `/v1/app` checks. The route does not check that the caller belongs to the group, so any signed-in user can read any group's tag names.
* **Used by:** web (`TaskSuggestionHttpService.getSuggestionTags`, from `task-tags-dialog.component.ts:378`, `task-tag-header-dialog.component.ts:247`, `task-create-dialog.component.ts:1535` and `task-suggestion-helper.service.ts:213`); iOS (as [areas](#post-v1apptaskssuggestionsareas)); Android (`AiSuggestionsRepository.getAiTagSuggestions`, from `TagRequiredDialog.java:484` and `JobChatFragment.java:15704`).

**Request** (multipart form, or JSON without a file)

| Name                                    | In   | Type   | Required        | Rules                                                                                 |
| --------------------------------------- | ---- | ------ | --------------- | ------------------------------------------------------------------------------------- |
| `parentUuid`                            | body | string | yes             | The site. Sent on as `siteUUID`; it also decides whether the AI may propose a new tag |
| `businessUuid`                          | body | string | yes             | The group whose tag folders are searched. Sent on as `groupUUID`                      |
| `title`, `file`, `imageRef`, `messages` | body |        | one of the four | As for [areas](#post-v1apptaskssuggestionsareas)                                      |

**Response** `200`: a list of [suggestion objects](#suggestion-object) with `uuid`, `name` and `tagHeaderUuid` (the tag folder). A tag the AI proposes as new has `uuid` `null`. The AI's confidence is not passed on (`AISuggestionsServiceProvider.php:113-126`).

```json
{
  "status": "success",
  "message": "Operation was successful",
  "data": [
    { "uuid": "500", "name": "Leaking tap", "tagHeaderUuid": "600" },
    { "uuid": null, "name": "Water damage", "tagHeaderUuid": "600" }
  ]
}
```

**Errors:** [common errors](https://docs.snapfix.com/engineering-reference/api/tasks.md#common-errors); `422` when `parentUuid` or `businessUuid` is missing, when no content field is sent, or for a bad file.

**Side effects:** none in Snapfix's tables. One call to the [tag route](#post-apiv1ai-tasktag).

## POST /v1/app/tasks/suggestions/title

Suggests a title for a new task from its photo or its text, and returns the `imageRef` that the other suggestion routes take instead of the photo.

* **Auth:** user token and the `/v1/app` checks. The request names no site, so the site's AI switch is never checked, and the site's title style never applies.
* **Used by:** web (`TaskSuggestionHttpService.getSuggestionTitle`, from `task-create-dialog.component.ts:490`, only when the user adds a photo); iOS (`AITaskSuggestionViewModel.requestTitleSuggestion`, from `ChatCreateTaskVC.swift:382` and `ImageEditVC.swift:242`); Android (`AiSuggestionsRepository.getAiTaskNameSuggestions`, from `ImageEditActivity.java:1194` and `CreateTaskBottomSheet.kt:335`, `:430`, `:514` and `:530`).

**Request** (multipart form, or JSON without a file)

| Name       | In   | Type   | Required         | Rules                                                                                                                                                                                                                                              |
| ---------- | ---- | ------ | ---------------- | -------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- |
| `file`     | body | file   | one of the three | A photo: `jpg`, `jpeg`, `png` or `gif`, up to `FILE_MAX_SIZE`. Sent on as `uploaded_image`                                                                                                                                                         |
| `title`    | body | string | one of the three | The text typed so far                                                                                                                                                                                                                              |
| `messages` | body | string | one of the three | A JSON array of strings. The web sends up to 31 chat messages around the one a task is made from (web\_app\_v2 @ 0989b8e685, `src/app/pages/chat/chat-message-list/chat-message-list.component.ts:1253-1264`); the apps send the task's chat texts |

The rule set has no `imageRef`, so each title call sends the photo again (`app/Http/Requests/v1/Suggestions/TitleRequest.php:15-24`). All three clients also send `parentUuid`, the web and iOS `businessUuid`, and iOS `jobUuid` and `targetLanguage` (the app's language) (ios @ aa31967ac8, `SnapFix/ImageEditVC.swift:232-240`, `SnapFix/Asset/ViewModel/CreateTask.swift:381-384`); the route drops them, so titles follow neither the site's style nor the user's language \[[ASK-178](https://github.com/snapfix/docs/blob/main/ASK.md#ask-178-should-ai-titles-follow-the-users-language)].

**Response** `200`: a [title suggestion object](#title-suggestion-object). Both fields are `null` when the AI finds nothing or fails.

```json
{
  "status": "success",
  "message": "Operation was successful",
  "data": { "title": "Leaking tap in Room 101", "imageRef": "4c1f0e9b2d7a" }
}
```

**Errors:** [common errors](https://docs.snapfix.com/engineering-reference/api/tasks.md#common-errors); `422` when none of the three fields is sent, or for a bad file.

**Side effects:** none in Snapfix's tables. One call to the [title route](#post-apiv1ai-tasktitle), which caches the task's context for the other routes.

## POST /v1/guest/suggestions/areas

The guest copy of [areas](#post-v1apptaskssuggestionsareas), for tasks reported through QR forms.

* **Auth:** the shared guest Basic login only. No user is set, so no `userUUID` is sent, and nothing checks the site named.
* **Used by:** authpy's QR pipeline (`featureQrSuggestionsFetcher._fetchAreas`, authpy @ 5d5758661c, `model/feature_qrform.py:1147-1170`; see [Guest callers](#how-the-suggestion-routes-work)). It sends `parentUuid`, `imageRef` and `title`.

**Request and response:** as [areas](#post-v1apptaskssuggestionsareas).

**Errors:**

* `401` `{"error": "Unauthorized."}` with `WWW-Authenticate: Basic` for a missing or wrong login (api\_php\_live\_v2 @ ef3c4319f6, `app/Http/Middleware/AuthorizeGuestApi.php:16-27`).
* `400` from the blacklist ([Blocking and rate limits](https://docs.snapfix.com/engineering-reference/api.md#blocking-and-rate-limits)).
* `422` as for the app route.
* `500` "An unexpected error occurred. Please try again later." when the guest limits are reached: 60 calls a minute and 1,000 a day, per IP because no user is set (`app/Providers/RouteServiceProvider.php:107-117`, `:140-149`). The error handler turns the throttle error into a server error, so these limits never answer `429` (`app/Exceptions/Handler.php:80-81`, `:117-123`). authpy's calls all come from its own server, so every QR report shares one limit.

**Side effects:** as the app route, with no user.

## POST /v1/guest/suggestions/assignees

The guest copy of [assignees](#post-v1apptaskssuggestionsassignees), for tasks reported through QR forms.

* **Auth:** the shared guest Basic login only. Nothing checks the site or group named, so a caller with only that login can read the member names of any group it has the ID of.
* **Used by:** authpy's QR pipeline (`_fetchAssignees`, `model/feature_qrform.py:1198-1222`). It sends `parentUuid`, `businessUuid`, `title` and `imageRef`, and then assigns every user the answer names to the new task.

**Request and response:** as [assignees](#post-v1apptaskssuggestionsassignees).

**Errors:** as the [guest areas route](#post-v1guestsuggestionsareas).

**Side effects:** as the app route, with no user. The ranking, and its OpenAI call in the default mode, runs for every QR report that authpy sends.

## POST /v1/guest/suggestions/rooms

The guest copy of [rooms](#post-v1apptaskssuggestionsrooms), for QR forms.

* **Auth:** the shared guest Basic login only. Nothing checks the site named.
* **Used by:** qr\_forms (`FormService.getRoomsSuggestions`, qr\_forms @ bdfc4f20a5, `src/app/services/form/form.service.ts:59-67`, from `report-issues-form.component.ts:100` and `dynamic-form.component.ts:134`), after the guest title answer gives an `imageRef`; it sends `imageRef` and the form's `parentUuid` and preselects the room. authpy's QR pipeline (`_fetchRooms`, `model/feature_qrform.py:1121-1145`) sends `parentUuid`, `businessUuid`, `title` and `imageRef`; the route drops `businessUuid`.

**Request and response:** as [rooms](#post-v1apptaskssuggestionsrooms).

**Errors:** as the [guest areas route](#post-v1guestsuggestionsareas).

**Side effects:** as the app route, with no user.

## POST /v1/guest/suggestions/tags

The guest copy of [tags](#post-v1apptaskssuggestionstags), for tasks reported through QR forms.

* **Auth:** the shared guest Basic login only. Nothing checks the site or group named.
* **Used by:** authpy's QR pipeline (`_fetchTags`, `model/feature_qrform.py:1172-1196`). It sends `parentUuid`, `businessUuid`, `title` and `imageRef`.

**Request and response:** as [tags](#post-v1apptaskssuggestionstags).

**Errors:** as the [guest areas route](#post-v1guestsuggestionsareas).

**Side effects:** as the app route, with no user.

## POST /v1/guest/suggestions/title

The guest copy of [title](#post-v1apptaskssuggestionstitle), for QR forms.

* **Auth:** the shared guest Basic login only. Anyone with the login can run the paid AI title suggestion, within the guest limits. The request names no site, so the site's AI switch is never checked.
* **Used by:** qr\_forms (`FormService.getSuggestionTitle`, `src/app/services/form/form.service.ts:41-48`, from `report-issues-form.component.ts:80` and `dynamic-form.component.ts:108`), after the first photo on a form whose details say `aiSuggestionEnabled` is `1`. It sends only `file`, fills the form's title field with the answer, and keeps `imageRef` for the rooms call and the form post.

**Request and response:** as [title](#post-v1apptaskssuggestionstitle).

**Errors:** as the [guest areas route](#post-v1guestsuggestionsareas).

**Side effects:** as the app route, with no user.

## POST ?action=save\_ai\_job\_log

Saves rows of the AI job log: for each suggestion, what the AI suggested and what the user chose instead. The apps keep the rows on the device and send them during sync. They are written as rows of [`log_ai_job`](https://docs.snapfix.com/engineering-reference/db/tables/log_ai_job.md).

* **Auth:** user token (Bearer JWT, if `JWT_AUTH_ENABLED` is on \[[ASK-12](https://github.com/snapfix/docs/blob/main/ASK.md#ask-12-which-settings-do-the-production-api-servers-use)]). The action saves the user named in each row, not the token's user, and it does not check access to the task a row names (php-apis @ 238ca4414e, `html/api/snapfix/index.php:520-527`, `htmlphp/api/snapfix/class/class.functions.php:38826-38963`).
* **Used by:** Android (sync task `LOG_AI_JOB`, android @ 86068bfeea, `app/src/main/java/gmail/com/snapfixapp/data/repository/SyncRepository.kt:887-901`, sent with `SyncRemoteDataSource.post`; the local rows are deleted after a success); iOS (sync step `LogAiJob`, `TaskManager.getLogAiJob`, ios @ aa31967ac8, `Managers/TaskManager.swift:289-290`, `:3628-3665`, up to 500 rows a call). Both send `POST` with a JSON body.

**Request** (JSON body)

| Name                                            | In       | Type             | Required | Rules                                                                                                                        |
| ----------------------------------------------- | -------- | ---------------- | -------- | ---------------------------------------------------------------------------------------------------------------------------- |
| `insert_data`                                   | body     | array of objects | yes      | One object per log row. An empty body answers "Data cannot be blank!"                                                        |
| `uuid`                                          | each row | string           | no       | The row's ID. With the queue on, a missing one gets a new ID; the direct save leaves it empty                                |
| `uuid_tJob`                                     | each row | string           | no       | The task the suggestion was for. Not checked                                                                                 |
| `category`                                      | each row | string           | no       | `group`, `title`, `assignee`, `tag-ex` (an existing tag), `tag-new`, `room` or `area`                                        |
| `suggestion`                                    | each row | JSON             | no       | What the AI suggested                                                                                                        |
| `overwritten`                                   | each row | JSON             | no       | What the user chose instead, or `null` when the suggestion was kept (ios @ aa31967ac8, `SnapFix/LogJobStatus.swift:300-326`) |
| `fCreatedTs`, `fModifiedTs`                     | each row | integer          | no       | Times in ms. Missing times are filled in by the server                                                                       |
| `uuid_tUser_CreatedBy`, `uuid_tUser_ModifiedBy` | each row | string           | no       | The user who made the change, saved as sent                                                                                  |

Both apps send all nine row fields (android @ 86068bfeea, `app/src/main/java/gmail/com/snapfixapp/utils/JsonParserUtils.java:2224-2232`). Each row is saved with every column it names, as the generic save does ([Requests](https://docs.snapfix.com/engineering-reference/api.md#requests)).

**Response** `200`: the counts of the save.

```json
{
  "result": true,
  "message": "Please find the processed record count",
  "total_record_count": 2,
  "inserted_record_count": 2,
  "updated_record_count": 0,
  "insert_failed_record_count": 0,
  "update_failed_record_count": 0,
  "serverTs": 1794387595000
}
```

The direct save also returns `trigger_auto_archive` (an empty list here) (`class.functions.php:1214-1218`).

**Errors:** `200` with `result` `false`: "Data cannot be blank!" (no body); the same counts with `result` `false` when a row fails in the direct save; "something went wrong" or another exception text otherwise ([Responses](https://docs.snapfix.com/engineering-reference/api.md#responses)).

**Side effects:** with `LEGACY_QUEUE_SUPPORT` on \[[ASK-12](https://github.com/snapfix/docs/blob/main/ASK.md#ask-12-which-settings-do-the-production-api-servers-use)], each row becomes a sync queue entry in [`tPri_Queue`](https://docs.snapfix.com/engineering-reference/db/tables/tpri_queue.md). With it off, each row is inserted into `log_ai_job`, or updates the row that has the same `uuid`. No time log and no push.

## POST ?action=upload\_voice\_task\_file

Uploads the recording of a voice task and returns its URL. The AI step that would fill in a title, an image and a transcript is switched off \[[ASK-15](https://github.com/snapfix/docs/blob/main/ASK.md#ask-15-is-snapfix-ai-for-voice-tasks-switched-off-on-purpose)].

* **Auth:** user token (Bearer JWT, if `JWT_AUTH_ENABLED` is on \[[ASK-12](https://github.com/snapfix/docs/blob/main/ASK.md#ask-12-which-settings-do-the-production-api-servers-use)]). The action reads no user.
* **Used by:** iOS (`APIManager.UPLOAD_VOICE_TASK_FILE`, from `HomeVC+VoiceTask.swift:440` and `Voice Task/CreateVoiceTaskVC.swift:306`); Android (`uploadVoiceFileToAIServer`, android @ 86068bfeea, `app/src/main/java/gmail/com/snapfixapp/viewModels/TaskCreationViewModel.kt:694` and `app/src/main/java/gmail/com/snapfixapp/viewModels/TaskViewModel.java:2576`, after a voice task is created). Both send a multipart `POST`.

**Request** (multipart form)

| Name            | In   | Type | Required | Rules                                                                                                                                                                                                                                                                                |
| --------------- | ---- | ---- | -------- | ------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------ |
| `uploaded_file` | body | file | yes      | The recording. iOS names it `<random ID>.m4a` (ios @ aa31967ac8, `APIManagers/APIManager.swift:2066`). At most `MAX_UPLOADERSIZE`; the type is not checked, because that check is commented out (php-apis @ 238ca4414e, `htmlphp/api/snapfix/class/class.functions.php:35782-35786`) |

**Response** `200`:

```json
{
  "result": true,
  "message": "success",
  "data": {
    "file_url": "https://bucket.example.com/file/9d2f6c1e-0b7a-4c51-8e3a-2f6b1d0c9e47/voice-note.m4a",
    "fTitle": "",
    "fImage": "",
    "transcript": ""
  },
  "serverTs": 1794387595000
}
```

`fTitle`, `fImage` and `transcript` are always empty strings, with `result` `true`, because the upload passes `TRUE` to the AI step, which then returns at once (`class.functions.php:35717-35720`, `:35817-35833`) \[[ASK-15](https://github.com/snapfix/docs/blob/main/ASK.md#ask-15-is-snapfix-ai-for-voice-tasks-switched-off-on-purpose)].

**Errors:** `200` with `result` `false` and the message: the `WRONG_PARAM` message when no file is sent (`:35767`); the `MAX_SIZE_REACHED` message when the file is too big (`:35749-35750`); "failed to upload the file" when no URL comes back (`:35816`); "invalid params" otherwise (`:35812`, `:35836`).

**Side effects:** stores the recording in the documents bucket under `file/<random ID>/<file name sent>`, with the `public-read` ACL, so anyone with the URL can download it without signing in (php-apis @ 238ca4414e, `html/api/snapfix/s3.php:192-273`, ACL at `:250` and `:260`). No database rows. No call goes to the voice AI host \[[ASK-15](https://github.com/snapfix/docs/blob/main/ASK.md#ask-15-is-snapfix-ai-for-voice-tasks-switched-off-on-purpose)], and the AI step after a voice message is saved is commented out too (`html/api/snapfix/index.php:4549-4552`).

## POST /simon/chat/stream

Runs one turn of Simon, the AI assistant, and streams the answer as server-sent events. The first call of a chat sends the command `__simon:open__`, which returns the starter chips without a model call.

* **Auth:** user token in `Authorization: Bearer`. Simon reads the user from the token's `identity` claim without checking the signature (snapfix\_ai\_agent @ e5e18caef5, `src/api/auth.py:14-42`). It reads the site's data through the Snapfix APIs with the caller's token, and those reads first check that the caller has groups at the site (`GET` the caller's groups with `source=multisite`) (`src/snapfix/businesses/__init__.py:81-100`). A site the caller can't use ends the turn with an `internal_error` event, not an access error. A task or group open on screen that the caller can't use is ignored.
* **Used by:** web (`SimonHttpService.streamChat`, from `simon-panel.component.ts:475` and `:524`); iOS (`SimonAIStreamClient`, ios @ aa31967ac8, `SnapFix/SimonAI/SimonAIStreamClient.swift:88-92`, from `SimonAIViewModel.swift:929`); Android (`SimonRepository.sendMessage` through `SimonSseClient`, android @ 86068bfeea, `app/src/main/java/gmail/com/snapfixapp/network/simon/SimonSseClient.kt:39-42`, from `SimonStreamManager.kt:84`).

**Request** (JSON body, camelCase names)

| Name                          | In     | Type   | Required | Rules                                                                                                                                           |
| ----------------------------- | ------ | ------ | -------- | ----------------------------------------------------------------------------------------------------------------------------------------------- |
| `command`                     | body   | string | yes      | The user's message or a chip's value, 1 to 4,000 characters. `__simon:open__` opens a chat                                                      |
| `sessionId`                   | body   | string | yes      | The chat's ID, made by the client, 1 to 128 characters                                                                                          |
| `propertyContext`             | body   | object | no       | Where the user is in the app: `parentUuid` (the site), `buildingUuid`, `businessUuid` (the group on screen) and `taskUuid` (the task on screen) |
| `clarificationAnswers`        | body   | array  | no       | Answers to Simon's questions: `id` (string), `value` (string, at least 1 character) and `questionIndex` (1-based)                               |
| `Authorization`               | header | string | yes      | `Bearer` and the access token                                                                                                                   |
| `parentUuid` or `parent-uuid` | header | string | no       | The site, used when the body names none. Every command except `__simon:open__` needs a site                                                     |

The server also accepts the snake\_case field names (`session_id`, `property_context`), but every client sends camelCase (`src/api/models.py:18-47`). The web and Android also send `groupUuid` and `taskUuid` headers on some calls; Simon reads neither.

**Response** `200` (`text/event-stream`): a sequence of [Simon stream events](#simon-stream-events) that ends with `done`, or with `error` when the turn fails. A failed turn still answers `200`.

```
event: token
data: {"delta":"You have 3 open tasks "}

event: done
data: {"message":"You have 3 open tasks in Room 101.","sessionId":"chat-123","interactive":null,"awaitingInput":false,"followUpSuggestions":[]}
```

**Errors:**

* Before the stream, `401` `{"detail": ...}`: "Authorization Bearer token required", "Access token expired" (with `WWW-Authenticate: Bearer`), "Invalid access token" or "User identity missing from token" (`src/api/auth.py:19-37`).
* `400` `{"detail": "parentUuid is required"}` when a command other than `__simon:open__` names no site (`src/api/routes.py:95-98`).
* `422` with FastAPI's `detail` list for a bad body, such as a missing `sessionId` or a `command` over 4,000 characters.
* In the stream, an `error` event: `usage_limit_exceeded` "This property has reached its monthly Simon usage limit. Please contact your administrator." (or "Your account has reached ..." for the user's budget), not retryable; `unauthorized` "Your session has expired. Please sign in again." when a Snapfix call answers `401`, not retryable; `internal_error` "Something went wrong. Please try again." for anything else, retryable (`src/api/stream.py:93-127`, `:242-247`).

**Side effects:**

* Checks the site's and the user's monthly token budgets before any model call; no budget row means no limit (`src/usage/__init__.py:35-57`). Records each turn's token counts in `simon_usage` (`:17-32`).
* Calls the Snapfix APIs with the caller's token at `snapfix_api_base_url` (`src/config.py:29-31`). Changes Simon prepares, such as a new task, wait for the user's confirmation and then run through those APIs as the user.
* Sends the message, recent turns and tool results to OpenAI (`src/agent/runner.py:46`) \[[ASK-177](https://github.com/snapfix/docs/blob/main/ASK.md#ask-177-do-the-customer-terms-cover-sending-task-text-photos-recordings-and-chats-to-ai-providers)].
* After each turn except `__simon:open__`, saves the user's text (or the joined answers) and Simon's final reply to `simon_messages`, under a key of the token's user, the site and the chat ID (`src/api/history.py:9-16`, `src/agent/runner.py:50-52`) \[[ASK-179](https://github.com/snapfix/docs/blob/main/ASK.md#ask-179-which-database-does-snapfix-ai-use-in-production-and-are-the-ai_agent_-tables-still-used)]. iOS also sends `__simon:dismiss_starters__` as a turn, which runs the model and is saved.

## GET /simon/messages

Returns one page of a chat's saved messages, oldest first: the newest page, or the page before a cursor.

* **Auth:** user token; its signature isn't checked, so a forged token can read another user's chat when the site and chat ID are known. The chat is found by the token's user, the site header and the chat ID (`src/api/routes.py:61-78`, `:91-98`).
* **Used by:** web (`SimonHttpService.getMessages`, from `simon-panel.component.ts:422`, after `GET /simon/session`, and `:451` for older pages). iOS has the call (`SimonAIRestAPI.fetchMessages`, `SnapFix/SimonAI/SimonAIStreamClient.swift:424-434`), but makes it only after `GET /simon/sessions` returns a chat, which no service serves, so iOS never loads the history today (`SnapFix/SimonAI/SimonAIViewModel.swift:330-361`).

**Request**

| Name                          | In     | Type    | Required | Rules                                                    |
| ----------------------------- | ------ | ------- | -------- | -------------------------------------------------------- |
| `sessionId`                   | query  | string  | yes      | The chat's ID, 1 to 128 characters                       |
| `limit`                       | query  | integer | no       | 1 to 50; default 20                                      |
| `before`                      | query  | integer | no       | A message ID, at least 1: returns messages older than it |
| `parentUuid` or `parent-uuid` | header | string  | yes      | The site                                                 |

**Response** `200`: `status` `true`, and `data` with `sessionId`, `messages` (each a [Simon message object](#simon-message-object)), `hasMore`, `nextBefore` and `limit`. `nextBefore` is the ID of the oldest message on the page when `hasMore` is `true`, else `null`; send it as `before` for the next older page.

```json
{
  "status": true,
  "data": {
    "sessionId": "chat-123",
    "messages": [
      { "id": 41, "role": "user", "content": "Create a task for Room 101", "ts": "2026-11-13T09:15:00Z" },
      { "id": 42, "role": "assistant", "content": "Done. The task is created.", "ts": "2026-11-13T09:15:04Z" }
    ],
    "hasMore": false,
    "nextBefore": null,
    "limit": 20
  }
}
```

**Errors:** `401` as for the [chat stream](#post-simonchatstream); `400` `{"detail": "parentUuid is required"}`; `422` for a missing `sessionId`, or a `limit` or `before` out of range.

**Side effects:** none. It reads the chat's `simon_messages` rows (`src/api/history.py:19-39`).

## GET /simon/session/{session\_id}

Answers with the chat ID it was given. It does not look the chat up, so every ID gets the same answer.

* **Auth:** user token; its signature isn't checked. No site header is needed (`src/api/routes.py:55-58`).
* **Used by:** web (`SimonHttpService.getSession`, from `simon-panel.component.ts:420`; the web checks that the ID matches, then loads the messages); Android (`SimonRepository.restoreSession`, android @ 86068bfeea, `app/src/main/java/gmail/com/snapfixapp/repository/SimonRepository.kt:92-104`, from `SimonChatViewModel.kt:93`). Android reads a `turns` list from the answer, which Simon doesn't send, so its restored chats come back empty.

**Request**

| Name         | In   | Type   | Required | Rules                              |
| ------------ | ---- | ------ | -------- | ---------------------------------- |
| `session_id` | path | string | yes      | The chat's ID, 1 to 128 characters |

**Response** `200`:

```json
{
  "status": true,
  "data": { "sessionId": "chat-123" }
}
```

**Errors:** `401` as for the [chat stream](#post-simonchatstream); `422` for an ID over 128 characters.

**Side effects:** none.

## DELETE /simon/session/{session\_id}

Deletes a chat for the caller: its model memory, its pending confirmations and its saved messages. Other chats and the usage rows stay.

* **Auth:** user token; its signature isn't checked, so a forged token can delete another user's chat when the site and chat ID are known (`src/api/routes.py:81-88`).
* **Used by:** web (`SimonHttpService.deleteSession` through `clearSession$`, from `simon-panel.component.ts:374`, the panel's "Refresh"; the site goes in the `parent-uuid` header that the web adds to every request: web\_app\_v2 @ 0989b8e685, `src/app/services/http/http.service.ts:130`); Android (`SimonRepository.clearSession`, `SimonRepository.kt:114-122`, from `SimonChatViewModel.kt:187`, a new chat). iOS has the call (`SimonAIStreamClient.swift:437-441`) but nothing calls it.

**Request**

| Name                          | In     | Type   | Required | Rules                              |
| ----------------------------- | ------ | ------ | -------- | ---------------------------------- |
| `session_id`                  | path   | string | yes      | The chat's ID, 1 to 128 characters |
| `parentUuid` or `parent-uuid` | header | string | yes      | The site                           |

**Response** `200`:

```json
{
  "status": true,
  "message": "Session cleared",
  "sessionId": "chat-123"
}
```

**Errors:** `401` as for the [chat stream](#post-simonchatstream); `400` `{"detail": "parentUuid is required"}`; `422` for an ID over 128 characters.

**Side effects:** clears the chat's model memory and pending confirmations (`src/agent/runner.py:91-94`) and deletes its `simon_messages` rows (`src/api/history.py:42-46`).

## GET /health

Says that Simon is up.

* **Auth:** none.
* **Used by:** Kubernetes, external: the startup, readiness and liveness probes in the service's Helm chart (snapfix\_ai\_agent @ e5e18caef5, `chart/templates/deployment.yaml:166-181`).

**Request:** none.

**Response** `200` (`src/main.py:63-76`):

```json
{ "status": "ok", "service": "snapfix-simon-agent-v2", "version": "1.0.0" }
```

`version` is the build's version, which CI sets from the git tag (`src/config.py:19-22`).

**Errors:** none of its own.

**Side effects:** none.

## POST /api/v1/ai-task/area

Lists the areas of a site that a task's text names. It is aitask\_pyserver's route; the apps reach it only through api\_php\_live\_v2.

* **Auth:** Basic login when both `AI_TASK_BASIC_AUTH_USERNAME` and `AI_TASK_BASIC_AUTH_PASSWORD` are set, otherwise none (aitask\_pyserver @ 877304ec49, `app/api/v1/ai_task/auth.py:15-40`, `app/config.py:190-191`) \[[ASK-12](https://github.com/snapfix/docs/blob/main/ASK.md#ask-12-which-settings-do-the-production-api-servers-use), [ASK-176](https://github.com/snapfix/docs/blob/main/ASK.md#ask-176-which-ai-suggestion-settings-and-logins-does-production-use)]. No user is read, and the site is trusted.
* **Used by:** api\_php\_live\_v2 (`AISuggestionsServiceProvider::getAreasSuggestions`, `app/Services/Suggestions/Providers/AISuggestionsServiceProvider.php:171-189`), behind the [app](#post-v1apptaskssuggestionsareas) and [guest](#post-v1guestsuggestionsareas) areas routes and the Open API's queued job ([Related routes](#related-routes)).

**Request** (multipart form; `debug` in the query)

| Name                   | In    | Type    | Required        | Rules                                                                                                                                                                                                                                                 |
| ---------------------- | ----- | ------- | --------------- | ----------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- |
| `siteUUID`             | form  | string  | yes             | The site. Missing: `422`; blank: `400` "siteUUID is required". The site's AI switch must be on                                                                                                                                                        |
| `imageCtx`             | form  | string  | one of the four | A key from an earlier [title call](#post-apiv1ai-tasktitle). When it is set, the cached context is used and the photo and messages are not; an unknown or expired key gives `400` "imageCtx missing or expired in Redis". Any caller may send any key |
| `uploaded_image`       | file  | file    | one of the four | A photo of up to 6 MB; a larger one gives `400` "uploaded\_image too large (max 6 MB)", after the whole file is read                                                                                                                                  |
| `title`                | form  | string  | one of the four | The task's title. With `imageCtx`, it is stored on the cached context as the user's title (`app/api/v1/ai_task/router.py:388-393`)                                                                                                                    |
| `messages`             | form  | string  | one of the four | A JSON array of strings; blank items are dropped. Anything else gives `400`: "messages must be a JSON array", "messages\[i] must be a string" or "messages: invalid JSON (…)" (`router.py:126-144`)                                                   |
| `groupUUID`, `jobUUID` | form  | string  | no              | Used only in the cache key and the usage row. api\_php\_live\_v2 sends neither here                                                                                                                                                                   |
| `debug`                | query | integer | no              | `1` adds `models` and `timings_ms` to `data`                                                                                                                                                                                                          |

Without `imageCtx`, the route first runs the [title](#post-apiv1ai-tasktitle) step (OpenAI, then a Redis write) and works on its context (`router.py:366-431`).

**Response** `200`: the [AI task envelope](#ai-task-envelope) with `data.areas`, the site's areas that matched, each with `uuid` and `name`. Names that match no area of the site are left out, so the list can be empty.

```json
{
  "status": "success",
  "message": "Processed successfully.",
  "data": { "areas": [ { "uuid": "301", "name": "Lobby" } ] }
}
```

**Errors:** in the envelope with `status` `fail`, except `401` and `422`:

* `400`: "siteUUID is required"; "AI suggestions are disabled for this site (tPri\_SettingsParent.fAiSuggestionEnabled is not 1)."; the `imageCtx`, photo and `messages` messages above; "Provide imageCtx, or without it pass uploaded\_image, title, or messages (at least one)"; "Cached context has no title, description, or messages for area extract".
* `401` `{"detail": "Authentication required"}` or `{"detail": "Invalid authentication credentials"}` when the Basic login is on and missing or wrong.
* `422`: FastAPI's `detail` list when `siteUUID` is missing.
* `502`: "MySQL AI settings check failed: …"; "MySQL area list error: …"; "Area extract error: …"; "Title pipeline error: …" from the title step.
* `503`: a setup error from the title step, such as "OPENAI\_API\_KEY is not set".

**Side effects:**

* Reads the live areas of the site's buildings (`tPri_Area`) (`app/services/ai_task_mysql.py:400-427`). A site with no area gets an empty list without an OpenAI call.
* When the text names an area of the site, uses it without OpenAI. Otherwise sends the text and up to 500 of the site's area names, numbered, to OpenAI, which names the matches (`app/services/ai_task_location.py:172-200`, `router.py:1544-1556`) \[[ASK-177](https://github.com/snapfix/docs/blob/main/ASK.md#ask-177-do-the-customer-terms-cover-sending-task-text-photos-recordings-and-chats-to-ai-providers)].
* Writes an [`ai_token_usage`](https://docs.snapfix.com/engineering-reference/db/tables/ai_token_usage.md) row with the request's title and messages and the matched names ([Logs](#ai-api)).

## POST /api/v1/ai-task/assignee

Ranks the members of a group for a task, from the task's text and the members' past work in the group.

* **Auth:** as [area](#post-apiv1ai-taskarea). No user is read, and the group is not checked against the site or any caller.
* **Used by:** api\_php\_live\_v2 (`getAssigneesSuggestions`, `AISuggestionsServiceProvider.php:131-143`), behind the app and guest assignees routes and the Open API's queued job (`app/Services/Suggestions/AiTaskCreationService.php:303-305`).

**Request** (multipart form)

| Name                                                                  | In   | Type   | Required | Rules                                                                                                                  |
| --------------------------------------------------------------------- | ---- | ------ | -------- | ---------------------------------------------------------------------------------------------------------------------- |
| `siteUUID`                                                            | form | string | yes      | The site. Missing: `422`. A blank value is accepted, and then the AI switch is not checked                             |
| `groupUUID`                                                           | form | string | yes      | The group whose members are ranked. Missing: `422`; blank: `400` "groupUUID is required". Not checked against the site |
| `imageCtx`, `uploaded_image`, `title`, `messages`, `jobUUID`, `debug` |      |        |          | As for [area](#post-apiv1ai-taskarea)                                                                                  |

**Response** `200`: the envelope with `data.users`, best first and at most `AI_TASK_ASSIGNEE_TOP_N` (2 by default): `uuid_tUser`, `name`, `reasoning` (a short text) and `confidence` (0 to 1). api\_php\_live\_v2 passes on only the ID and the name.

```json
{
  "status": "success",
  "message": "Processed successfully.",
  "data": {
    "users": [
      { "uuid_tUser": "200", "name": "Jane Smith", "reasoning": "Has closed similar tasks in this group", "confidence": 0.82 }
    ]
  }
}
```

How the pick works: when the text names a member of the group, that member is picked without OpenAI (`app/services/ai_task_nl_resolve.py:181-193`). Otherwise, in the default `hybrid` mode (`app/config.py:175`), a score from each member's completed work and open tasks picks a shortlist of up to 8, which goes to OpenAI with the task's title and description. The members are numbered there, not named, with their open-task counts, last activity and sign-in times, and the titles and resolution times of tasks they completed in the group (`app/services/assignee_insights.py:332-359`, `:902-950`) \[[ASK-177](https://github.com/snapfix/docs/blob/main/ASK.md#ask-177-do-the-customer-terms-cover-sending-task-text-photos-recordings-and-chats-to-ai-providers)]. When OpenAI gives no valid pick, the top scores are used.

**Errors:**

* `400`: "groupUUID is required"; the AI-disabled message; the `imageCtx`, photo and `messages` messages; "Provide imageCtx, or without it pass uploaded\_image, title, or messages (at least one)"; "Cached context has no title, description, or messages for assignee pick".
* `401` and `422` as for [area](#post-apiv1ai-taskarea).
* `404`: "No users in tPri\_UserBusiness for this group (fDeleted=0)" when the group has no live members; "No assignee recommendation: no group members with past completed jobs in insight data (seed assignee insight tables or check group scope)." when no pick comes out (`router.py:1113-1130`).
* `502`: "Assignee insight error: …"; "Title pipeline error: …". In the `openai` mode, "OpenAI returned no assignees from the candidate list; try again or adjust prompt" replaces the second `404`.
* `503`: the message of a setup error.

**Side effects:** reads the group's members and their insight rows. Calls OpenAI as above. Writes an `ai_token_usage` row with the picked user IDs as the answer (`router.py:1151-1170`).

## POST /api/v1/ai-task/group

Picks the group for a task among the site's task groups. With a `userUUID`, only the groups where that user is an admin or may create tasks count.

* **Auth:** as [area](#post-apiv1ai-taskarea). No user token is read: the filter takes `userUUID` from the form, and the `public` and `x-vendor` sources skip it.
* **Used by:** api\_php\_live\_v2 (`getGroupSuggestions`, `AISuggestionsServiceProvider.php:95-108`): behind the app group route, with the signed-in user's `userUUID`, and for Open API and vendor API tasks without a group, with `snapfixSource` `public` or `x-vendor` (`app/Services/Suggestions/AiTaskCreationService.php:101-111`, `:139-146`). The guest group route would reach it too, but nothing calls that route.

**Request** (multipart form)

| Name                                                       | In     | Type   | Required | Rules                                                                                                                                                                                                                                                                                                                   |
| ---------------------------------------------------------- | ------ | ------ | -------- | ----------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- |
| `siteUUID`                                                 | form   | string | yes      | The site. Missing: `422`; blank: `400` "siteUUID is required". The AI switch must be on                                                                                                                                                                                                                                 |
| `userUUID`                                                 | form   | string | no       | Limits the candidates to the groups where the user has a live [`tPri_UserBusiness`](https://docs.snapfix.com/engineering-reference/db/tables/tpri_userbusiness.md) row with the admin type or `perJobCreateNew` 1 (`app/services/ai_task_mysql.py:13-128`). Ignored for `public` and `x-vendor`                         |
| `snapfixSource`                                            | form   | string | no       | `public` or `x-vendor` skips the `userUUID` filter and takes the closest group. The `X-Snapfix-Source` header wins when both are sent. api\_php\_live\_v2 sends `public` or `x-vendor` for Open API and vendor API tasks (api\_php\_live\_v2 @ ef3c4319f6, `app/Services/Suggestions/AiTaskCreationService.php:95-111`) |
| `X-Snapfix-Source`                                         | header | string | no       | The same values. No repo sends this header                                                                                                                                                                                                                                                                              |
| `groupUUID`, `jobUUID`                                     | form   | string | no       | Used only in the cache key; they don't limit the candidates                                                                                                                                                                                                                                                             |
| `imageCtx`, `uploaded_image`, `title`, `messages`, `debug` |        |        |          | As for [area](#post-apiv1ai-taskarea)                                                                                                                                                                                                                                                                                   |

**Response** `200`: the envelope with `data.groupUUID`, `groupName` and `groupImage`, the group's image URL (`fImage`). `groupImage` is left out when the group has none (`router.py:964-973`).

```json
{
  "status": "success",
  "message": "Processed successfully.",
  "data": { "groupUUID": "400", "groupName": "Housekeeping" }
}
```

How the pick works: the candidates are the site's live, active task groups. OpenAI gets their names, numbered, with the task's text and picks one (`app/services/ai_task_group_llm.py:319-367`) \[[ASK-177](https://github.com/snapfix/docs/blob/main/ASK.md#ask-177-do-the-customer-terms-cover-sending-task-text-photos-recordings-and-chats-to-ai-providers)]. With `public` or `x-vendor`, it takes the closest group when the model is at least 15% sure (`AI_TASK_GROUP_INTERNAL_MIN_CONFIDENCE`, `app/config.py:227`) \[[ASK-187](https://github.com/snapfix/docs/blob/main/ASK.md#ask-187-should-open-api-and-vendor-api-tasks-without-a-group-go-to-the-closest-group-at-15-confidence)]. With `x-vendor` on a site listed in the `AI_TASK_GROUP_XVENDOR_*` settings, only the groups configured there are candidates (`app/config.py:228-237`, `router.py:816-866`).

**Errors:**

* `400`: "siteUUID is required"; the AI-disabled message; the `imageCtx`, photo and `messages` messages; "Provide imageCtx, or without it pass uploaded\_image, title, or messages (at least one)"; "Cached context has no title, description, or messages for group pick".
* `401` and `422` as for [area](#post-apiv1ai-taskarea).
* `404`: "No business groups found for this user under the site (requires tPri\_UserBusiness admin type or perJobCreateNew=1)", or "No business groups found for this site in MySQL" without a filter; "OpenAI did not match any listed group (UNKNOWN or unrecognized name)", or "OpenAI did not pick a listed group (unrecognized name)" for `public` and `x-vendor`; for those two only, "Closest group confidence … is below internal threshold …".
* `502`: "MySQL AI settings check failed: …"; "MySQL group list error: …"; "OpenAI group pick error: …"; "Title pipeline error: …".
* `503`: "OPENAI\_API\_KEY is not set", or another setup error.

**Side effects:** reads `tPri_SettingsParent`, the site's groups in `tPri_Business`, and `tPri_UserBusiness` when filtered. Runs the title step when there is no `imageCtx`. Calls OpenAI as above. Writes an `ai_token_usage` row for a pick, and for the "no listed group" and low-confidence failures, with the request's title and messages and the picked group's name (`router.py:866-963`).

## POST /api/v1/ai-task/room

Lists the rooms a task's text names, matched to the site's rooms.

* **Auth:** as [area](#post-apiv1ai-taskarea). No user is read, and the site is trusted.
* **Used by:** api\_php\_live\_v2 (`getRoomsSuggestions`, `AISuggestionsServiceProvider.php:148-166`), behind the app and guest rooms routes and the Open API's queued job.

**Request** (multipart form)

| Name                                                       | In   | Type   | Required | Rules                                                                                   |
| ---------------------------------------------------------- | ---- | ------ | -------- | --------------------------------------------------------------------------------------- |
| `siteUUID`                                                 | form | string | yes      | The site. Missing: `422`; blank: `400` "siteUUID is required". The AI switch must be on |
| `groupUUID`, `jobUUID`                                     | form | string | no       | Used only in the cache key and the usage row                                            |
| `imageCtx`, `uploaded_image`, `title`, `messages`, `debug` |      |        |          | As for [area](#post-apiv1ai-taskarea)                                                   |

**Response** `200`: the envelope with `data.rooms`, one entry per room the text names: the site's room `uuid` and `name`, or `uuid` `null` and the name from the text when no room of the site matches. api\_php\_live\_v2 keeps only the first entry with a `uuid`.

```json
{
  "status": "success",
  "message": "Processed successfully.",
  "data": { "rooms": [ { "uuid": "500", "name": "Room 101" }, { "uuid": null, "name": "Room 999" } ] }
}
```

**Errors:**

* `400`: "siteUUID is required"; the AI-disabled message; the `imageCtx`, photo and `messages` messages; "Provide imageCtx, or without it pass uploaded\_image, title, or messages (at least one)"; "Cached context has no title, description, or messages for room extract".
* `401` and `422` as for [area](#post-apiv1ai-taskarea).
* `502`: "MySQL AI settings check failed: …"; "Room extract error: …" for any MySQL or OpenAI failure, a missing `OPENAI_API_KEY` included; "Title pipeline error: …".
* `503`: a setup error from the title step.

**Side effects:** reads every live room of the site's live buildings, with no limit (`app/services/ai_task_mysql.py:371-398`). When the text names a room of the site, uses it without OpenAI; otherwise sends only the text to OpenAI to pull out room names, and matches them to the site's rooms itself (`app/services/ai_task_location.py:105-153`) \[[ASK-177](https://github.com/snapfix/docs/blob/main/ASK.md#ask-177-do-the-customer-terms-cover-sending-task-text-photos-recordings-and-chats-to-ai-providers)]. Writes an `ai_token_usage` row with the request's title and messages and the room names.

## POST /api/v1/ai-task/tag

Suggests tags from the tag folders and tags a group can use: existing tags first, then at most one proposed new tag.

* **Auth:** as [area](#post-apiv1ai-taskarea). No user is read, and the tags are read for `groupUUID` without checking that the group belongs to `siteUUID` or to any caller.
* **Used by:** api\_php\_live\_v2 (`getTagSuggestions`, `AISuggestionsServiceProvider.php:113-126`), behind the app and guest tags routes and the Open API's queued job.

**Request** (multipart form)

| Name                                                                  | In   | Type   | Required | Rules                                                                                                                                                                                                                                     |
| --------------------------------------------------------------------- | ---- | ------ | -------- | ----------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- |
| `siteUUID`                                                            | form | string | yes      | The site. Missing: `422`. A blank value is accepted, and then the AI switch is not checked and no new tag is proposed. A site whose settings row has `fAiUseOnlyExistingTag` 0 allows a new tag (`app/services/ai_task_mysql.py:493-510`) |
| `groupUUID`                                                           | form | string | yes      | The group whose tag folders are used. Missing: `422`; blank: `400` "groupUUID is required"                                                                                                                                                |
| `imageCtx`, `uploaded_image`, `title`, `messages`, `jobUUID`, `debug` |      |        |          | As for [area](#post-apiv1ai-taskarea)                                                                                                                                                                                                     |

**Response** `200`: the envelope with `data.tags`. Each has `uuid` (`null` for a proposed new tag), `name`, `tagFolderUUID`, `tagFolderName` and `confidence` (0 to 1).

```json
{
  "status": "success",
  "message": "Processed successfully.",
  "data": {
    "tags": [
      { "uuid": "500", "name": "Leaking tap", "tagFolderUUID": "600", "tagFolderName": "Maintenance", "confidence": 0.92 },
      { "uuid": null, "name": "Water damage", "tagFolderUUID": "600", "tagFolderName": "Maintenance", "confidence": 0.85 }
    ]
  }
}
```

* An existing tag needs a confidence above 0.7, and at most 24 come back (`AI_TASK_TAG_SEARCH_LIMIT`).
* A new tag needs a confidence above 0.8 and `suggest` true while `AI_TASK_TAG_NEW_RESPECT_CONFIDENCE_GATE` is on, which is the default. With it off, those checks are skipped, and a placeholder new tag is added when the model proposes none (`app/services/ai_task_tag_openai.py:229-245`, `app/config.py:247-248`) \[[ASK-176](https://github.com/snapfix/docs/blob/main/ASK.md#ask-176-which-ai-suggestion-settings-and-logins-does-production-use)].
* When the text names tags of the group, those come back without OpenAI. A group with no tag folders gives `"tags": []`.

**Errors:**

* `400`: "groupUUID is required"; the AI-disabled message; the `imageCtx`, photo and `messages` messages; "Provide imageCtx, or without it pass uploaded\_image, title, or messages (at least one)".
* `401` and `422` as for [area](#post-apiv1ai-taskarea).
* `502`: "MySQL AI settings check failed: …"; "MySQL parent tag policy check failed: …"; "Tag suggestion error: …"; "Title pipeline error: …".
* `503`: "OPENAI\_API\_KEY is not set", or another setup error.

**Side effects:** reads `tPri_SettingsParent`, the group's tag folders (`tPri_TagHeader`, `tPri_BusinessTagHeaderRule`) and their live tags (`tPri_Tag`), with no limit. Unless the text names a tag, sends the text and every folder and tag name of the group to OpenAI \[[ASK-177](https://github.com/snapfix/docs/blob/main/ASK.md#ask-177-do-the-customer-terms-cover-sending-task-text-photos-recordings-and-chats-to-ai-providers)]. Writes an `ai_token_usage` row with the request's title and messages.

## POST /api/v1/ai-task/title

Suggests a title from a task's photo or text. It caches the task's context (title, description, tags and messages) under the `imageCtx` it returns, and the other routes read that key.

* **Auth:** as [area](#post-apiv1ai-taskarea). No user is read. The AI switch is checked only for a non-blank `siteUUID`, which api\_php\_live\_v2 never sends here.
* **Used by:** api\_php\_live\_v2 (`getTitleSuggestions`, `AISuggestionsServiceProvider.php:82-90`), behind the app and guest title routes.

**Request** (multipart form)

| Name                   | In    | Type    | Required               | Rules                                                                                                                                                                                                                                                                                                                             |
| ---------------------- | ----- | ------- | ---------------------- | --------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- |
| `uploaded_image`       | file  | file    | one of the first three | A photo of up to 6 MB. Before it goes to OpenAI, it is scaled so its longer side is at most `AI_TASK_TITLE_VISION_MAX_IMAGE_SIDE` pixels (1024 by default; 0 keeps the original)                                                                                                                                                  |
| `title`                | form  | string  | one of the first three | The text typed so far                                                                                                                                                                                                                                                                                                             |
| `messages`             | form  | string  | one of the first three | As for [area](#post-apiv1ai-taskarea)                                                                                                                                                                                                                                                                                             |
| `imageCtx`             | form  | string  | no                     | A key from an earlier call. With a non-empty `title`, the route stores the title on that context as the user's title and answers without OpenAI. Without `title`: `400` "When imageCtx is set, pass non-empty title to update Redis context for downstream routes."; an unknown key: `400` "imageCtx missing or expired in Redis" |
| `siteUUID`             | form  | string  | no                     | When it is not blank, the AI switch is checked, and the site's title style applies when `AI_TASK_TITLE_STYLE_LEARNING_ENABLED` is on (off by default) \[[ASK-176](https://github.com/snapfix/docs/blob/main/ASK.md#ask-176-which-ai-suggestion-settings-and-logins-does-production-use)]. api\_php\_live\_v2 doesn't send it      |
| `groupUUID`, `jobUUID` | form  | string  | no                     | Used only in the prompt's scope line and the cache key                                                                                                                                                                                                                                                                            |
| `debug`                | query | integer | no                     | `1` adds `models` and `timings_ms`                                                                                                                                                                                                                                                                                                |

Without `imageCtx`, one of the first three is needed: `400` "Provide uploaded\_image, title, or messages (at least one)".

**Response** `200`: the envelope with `data.title` and `data.imageCtx`. `imageCtx` is a SHA-256 hex digest of the photo's hash, the title, the messages, the site, the group and the job; the Redis key is `AI_TASK_CACHE_KEY_PREFIX` plus it (`app/services/ai_task_title.py:349-370`, `app/services/redis_cache.py:22-23`). The answer has no description or tags; the other routes read them from the cache.

```json
{
  "status": "success",
  "message": "Processed successfully.",
  "data": {
    "title": "Water leak under the basin in Room 101",
    "imageCtx": "0123456789abcdef0123456789abcdef0123456789abcdef0123456789abcdef"
  }
}
```

**Errors:**

* `200` with `status` `fail` and `data` `{"title": "", "imageCtx": ""}`: "No usable title, description, or tags were produced (e.g. blank or unreadable image). Nothing was cached; imageCtx is empty." api\_php\_live\_v2 treats it as no suggestion.
* `400`: the `imageCtx` messages above; "Provide uploaded\_image, title, or messages (at least one)"; the photo and `messages` messages; the AI-disabled message (only with a site).
* `401` as for [area](#post-apiv1ai-taskarea).
* `502`: "MySQL AI settings check failed: …"; "Title pipeline error: …" for an OpenAI or Redis failure.
* `503`: "OPENAI\_API\_KEY is not set", or another setup error.

**Side effects:**

* Sends the photo (resized) or the text, with the messages and the scope IDs, to OpenAI, unless the same request is already cached (`AI_TASK_TITLE_OPENAI_READ_CACHE`, on by default). `AI_TASK_TITLE_USE_OPENAI` does not apply to this route (`app/services/ai_task_title.py:270-311`, `router.py:244-363`) \[[ASK-177](https://github.com/snapfix/docs/blob/main/ASK.md#ask-177-do-the-customer-terms-cover-sending-task-text-photos-recordings-and-chats-to-ai-providers)].
* Writes the context to Redis for 24 hours.
* With a site and title style learning on, reads the site's title style and may run one more model rewrite (`app/config.py:265-266`).
* Writes an `ai_token_usage` row with the suggested title as the answer, and with the request's title and messages when no photo was sent (`router.py:642-662`, `app/services/ai_token_usage.py:52-74`).

## Calls only production serves

The apps call these paths. Production's older agent serves them (see Simon versions above), but `main` does not, so they break when `main` replaces it \[[ASK-13](https://github.com/snapfix/docs/blob/main/ASK.md#ask-13-which-services-and-scheduled-jobs-run-in-production)]:

* `GET /simon/sessions`: iOS asks for the newest chat with it each time Simon opens (ios @ aa31967ac8, `SnapFix/SimonAI/SimonAIStreamClient.swift:413-421`, from `SnapFix/SimonAI/SimonAIViewModel.swift:335`). Production returns it (snapfix\_ai\_agent @ bcbd010, `app/api/simon.py:165`). `main` has no such route (snapfix\_ai\_agent @ e5e18caef5, `src/api/routes.py:28-88`), so there the call fails and iOS starts a new chat each time.
* `GET /brand-standards/documents/{id}`: the web document viewer (web\_app\_v2 @ 0989b8e685, `src/app/pages/document-viewer/document-viewer.component.ts:113`), iOS (`SnapFix/SimonAI/SimonAIStreamClient.swift:451-455`, from `SnapFix/SimonAI/SimonAIViewModel.swift:479`) and Android (android @ 86068bfeea, `app/src/main/java/gmail/com/snapfixapp/repository/SimonRepository.kt:149-155`) call it on the Simon host. Production serves it (snapfix\_ai\_agent @ bcbd010, `app/modules/brand_standards/router.py:28`, `:101`), for the site named in the `parentUuid` header, without checking that the caller belongs to that site. `main` searches the site's documents in a Qdrant collection named `brand_chunks` for its answers (`src/config.py:100`), but serves no route that returns a document \[[ASK-180](https://github.com/snapfix/docs/blob/main/ASK.md#ask-180-which-service-indexes-and-serves-the-brand-standards-documents-and-does-it-check-the-callers-site-and-group)].

Four more Simon calls are defined in client code and never made: `POST /simon/feedback`, and `GET` and `DELETE /simon/jobs/{id}`, on the web (web\_app\_v2 @ 0989b8e685, `src/app/services/simon/simon-http/simon-http.service.ts:147-174`) \[[ASK-185](https://github.com/snapfix/docs/blob/main/ASK.md#ask-185-should-the-snapfix-ai-job-and-feedback-calls-be-built-or-removed)], and `DELETE /simon/sessions` on iOS (`SnapFix/SimonAI/SimonAIStreamClient.swift:443-446`). Production serves all four (snapfix\_ai\_agent @ bcbd010, `app/api/simon.py:197`, `:294`, `:315`, `:337`); `main` serves none of them.

## Uncalled routes

Rows marked "(no caller)" have no section. Some of them do harm if they are called:

* `?action=ai_voice_task` runs one batch for the whole platform. It sends the voice recordings of the tasks created today, at every site, to the Snapfix AI host (`https://apiai.snapfix.com`) with an API key written into the code, and writes the returned titles, images and transcripts into those tasks as `admin`. Any signed-in user can start it (php-apis @ 238ca4414e, `html/api/snapfix/index.php:1246-1249`, `htmlphp/api/snapfix/class/class.functions.php:35511-35648`, `:35717-35738`).
* The chatbot actions look up any user by email address or mobile number and return the user's row, create users, and create tasks in any group, with the user and the group taken from the request. None checks the caller's rights, and `chatbot_validate_parent_user` also writes the request's `parent_uuid` into its SQL (`htmlphp/api/snapfix/class/chatbot.functions.php:76-171`, `:113`).
* `aicontextbusinesses` and `aicontextpermissions` return the caller's groups and permissions. They take the user from the token payload, whose signature the dispatcher checks only while `JWT_AUTH_ENABLED` is on (`htmlphp/api/snapfix/class/tasks.functions.php:283-348`, `:1403-1416`). `aireportsredirect` reads no data: it says whether a request with the `intent` `analytics`, `historical_trend` or `export` and more than 500 estimated rows belongs in Reports (`:350-371`).
* `auto_assign_tasks` sends a site's housekeeping tasks, its rooms with their guest status, and the staff's shifts to OpenAI through php-apis's own calls (`htmlphp/api/snapfix/class/ai.functions.php:197`, `:919-1700`), a second Auto Assign path next to api\_php\_live\_v2's \[[ASK-91](https://github.com/snapfix/docs/blob/main/ASK.md#ask-91-which-auto-assign-provider-runs-in-production-and-may-it-send-data-to-an-ai-service)].
* `POST /v1/guest/suggestions/group` would run the [group route](#post-apiv1ai-taskgroup) with no user, so every task group of the site would be a candidate.
* The experiment routes send uploaded images to OpenAI, Anthropic or Google Gemini, and `/suggest/assignee/llm-openai-rank` also sends each candidate's user ID and workload counts to OpenAI (aitask\_pyserver @ 877304ec49, `app/services/assignee_suggest.py:83-95`). None needs a login.
* The `*-local-01` routes are the older pipelines: BLIP and OpenAI for titles, CLIP and Qdrant for groups, BGE and Qdrant for assignees and tags (`app/api/v1/ai_task/router.py:443`, `:670`, `:976-981`, `:1178-1182`). Apart from the title one, they take only an existing `imageCtx`.

## Suggestion object

An item in the `data` list of the group, tags, assignees, rooms and areas routes of api\_php\_live\_v2 (api\_php\_live\_v2 @ ef3c4319f6, `app/Services/Suggestions/Providers/AISuggestionsServiceProvider.php:95-189`, `app/Http/Resources/v1/JobData/SuggestionsResource.php:14-29`).

| Field           | Type           | Meaning                                                                     |
| --------------- | -------------- | --------------------------------------------------------------------------- |
| `uuid`          | string or null | The group, tag, user, room or area. `null` for a tag the AI proposes as new |
| `name`          | string         | The name as stored, or the proposed tag's name                              |
| `image`         | string or null | Groups only: the group's image URL, `null` when it has none                 |
| `tagHeaderUuid` | string or null | Tags only: the tag folder                                                   |

The rooms and areas routes return at most one item, and the group route exactly one, or `[[]]` when there is none.

## Title suggestion object

The `data` of the [app](#post-v1apptaskssuggestionstitle) and [guest](#post-v1guestsuggestionstitle) title routes (`AISuggestionsServiceProvider.php:82-90`).

| Field      | Type           | Meaning                                                                                                     |
| ---------- | -------------- | ----------------------------------------------------------------------------------------------------------- |
| `title`    | string or null | The suggested title; `null` when there is none                                                              |
| `imageRef` | string or null | The key of the cached task context. The clients send it to the other suggestion routes instead of the photo |

## AI task envelope

The answer of every `/api/v1/ai-task/*` route (aitask\_pyserver @ 877304ec49, `app/schemas_ai_task.py:10-15`, `app/api/v1/ai_task/router.py:180-207`).

| Field     | Type           | Meaning                                                            |
| --------- | -------------- | ------------------------------------------------------------------ |
| `status`  | string         | `success` or `fail`                                                |
| `message` | string         | "Processed successfully." on success; the reason on `fail`         |
| `data`    | object or null | The route's answer; `null` on most failures, partial data on a few |

A `fail` answer carries HTTP `400`, `404`, `502` or `503`, or `200` for a title with nothing usable. The login and validation errors (`401`, `422`) are FastAPI's `{"detail": ...}` instead. api\_php\_live\_v2 reads `data` only from an HTTP 2xx answer with `status` `success` ([How the suggestion routes work](#how-the-suggestion-routes-work)).

## Simon stream events

The events of [POST /simon/chat/stream](#post-simonchatstream). Each is an `event: <name>` line and a `data:` line with JSON, camelCase names (snapfix\_ai\_agent @ e5e18caef5, `src/api/stream.py:76-196`, `src/api/models.py:50-180`).

| Event                 | Data                                                                                                                                        | Meaning                                                                                                                 |
| --------------------- | ------------------------------------------------------------------------------------------------------------------------------------------- | ----------------------------------------------------------------------------------------------------------------------- |
| `token`               | `delta`                                                                                                                                     | A piece of the reply, as it is written                                                                                  |
| `step`                | `label`                                                                                                                                     | What Simon is doing, such as "Finding tasks…"                                                                           |
| `interactive`         | `id`, `type` (`choices`, `confirm`, `summary` or `bulk_review`), `prompt`, `choices`, `questions`, `title`, `fields`, `actions`, `metadata` | Chips, questions or a summary to confirm. Each choice has `id`, `label`, `value` (sent back as the command) and `style` |
| `task_created`        | `tool` (`create_task`), `draft`, `task`                                                                                                     | One task was created; `task` is a task card                                                                             |
| `bulk_task_batch`     | `batchId`, `draft`, `items`                                                                                                                 | New tasks to review, one per room. Each item has `draftId`, `selected`, `location` (`kind`, `name`) and a task card     |
| `bulk_task_committed` | `batchId`, `draftId`, `status` (`created` or `failed`), `task`, `error`                                                                     | The outcome of one task of an approved batch                                                                            |
| `done`                | `message`, `sessionId`, `interactive`, `awaitingInput`, `followUpSuggestions`                                                               | The turn ended; `message` is the final reply, and each follow-up has `label` and `command`                              |
| `error`               | `code` (`internal_error`, `unauthorized` or `usage_limit_exceeded`), `message`, `retryable`                                                 | The turn failed ([errors](#post-simonchatstream))                                                                       |

A task card has `uuid`, `reference`, `title`, `business` (`uuid`, `name`), `rooms`, `assignees`, `status` (`name`, the colour, and `label`) and `priorityLevel`. The open command answers with an `interactive` block of four starter chips ("Show my open tasks", "Which rooms are dirty?", "Who is on call today?", "Create a task") and a `done` with an empty `message` (`src/api/stream.py:39-44`, `:80-90`).

## Simon message object

One saved message in [GET /simon/messages](#get-simonmessages) (`src/api/models.py:182-186`).

| Field     | Type    | Meaning                                          |
| --------- | ------- | ------------------------------------------------ |
| `id`      | integer | The message's ID, the paging cursor for `before` |
| `role`    | string  | `user` or `assistant`                            |
| `content` | string  | The text                                         |
| `ts`      | string  | When it was saved, ISO 8601                      |


---

# Agent Instructions
This documentation is published with GitBook. GitBook is the documentation platform designed so that both humans and AI agents can read, navigate, and reason over technical content effectively. Learn more at gitbook.com.

## Querying This Documentation
If you need additional information that is not directly available in this page, you can query the documentation by asking a question.

Perform an HTTP GET request on the following URL with the `ask` and `goal` query parameters:

```
GET https://docs.snapfix.com/engineering-reference/api/ai.md?ask=<question>&goal=<user_goal>
```

`ask` is the immediate question: it should be specific, self-contained, and written in natural language.
`goal` is what the user is ultimately trying to achieve, the reason they need the answer. Sharing it helps GitBook give you a better, more relevant answer. A goal is most helpful when it describes the outcome the user wants rather than restating the question. For example, with `ask=how do I create an API token`, a goal like `automate deployments from our CI pipeline` lets GitBook tailor the answer to that use case.

The response will contain a direct answer to the question and relevant excerpts and sources from the documentation.

Use this mechanism when the answer is not explicitly present in the current page, you need clarification or additional context, or you want to retrieve related documentation sections.
