sightbox/API_INTEGRATION.md

364 lines
12 KiB
Markdown

# Bettersight Intelligence — API Integration Guide
For another app/agent that wants to call this backend as a service. This
covers everything needed to authenticate and hit every endpoint correctly —
request shapes, response shapes, SSE event formats, and the failure modes
you'll actually hit. Source of truth is the code under `backend/routes/`,
`backend/services/`, and `backend/middleware/`; this doc is a snapshot of it
as of 2026-09-03. If something here disagrees with the code, trust the code.
---
## 1. Base URLs
Two separate services, both required:
| Service | Purpose | Local dev default |
|---|---|---|
| Flask API | Everything under `/api/*` and `/health` | `http://localhost:5050` |
| PocketBase | Auth only (`/api/collections/users/auth-with-password`) | `http://localhost:8090` |
The Flask backend has **no login route of its own** — you authenticate
directly against PocketBase, then send the resulting token to Flask on every
request. Flask validates it against PocketBase on every single request (not
cached), so there's no separate "register with Flask" step.
---
## 2. Authentication
### 2.1 Get a token
```
POST {POCKETBASE_URL}/api/collections/users/auth-with-password
Content-Type: application/json
{"identity": "user@example.com", "password": "..."}
```
Response `200`:
```json
{"token": "eyJhbGciOi...", "record": {"id": "...", "role": "staff", "department": "GENERAL", "tenant": "...", ...}}
```
Non-2xx → `{"message": "..."}` from PocketBase directly (not this app's
error shape).
### 2.2 Use it
Every Flask endpoint below except `/health` requires:
```
Authorization: <token>
```
or
```
Authorization: Bearer <token>
```
(Both accepted — the `Bearer ` prefix is stripped if present, then the bare
token is what actually gets validated against PocketBase.)
**You cannot obtain a user account through this API.** New tenants and their
first admin user are provisioned by the platform operator via
`/api/platform/tenants` (superuser-only, not documented here since it's not
a service you'd integrate against). Get credentials from Jason directly.
### 2.3 What the token gets you
`client_id` (tenant) and permissions are derived **entirely** from the
token server-side — there is no `client_id` or `tenant_id` field you can
pass in a request body to select a tenant or escalate access. Every
endpoint below operates only on the token's own tenant.
Role → permissions (fixed, not configurable per-request):
| Role | `allowed_classes` | Department-scoped? | `can_admin` |
|---|---|---|---|
| `staff` | PUBLIC, INTERNAL | yes (own dept + GENERAL) | no |
| `manager` | PUBLIC, INTERNAL, CONFIDENTIAL | yes (own dept + GENERAL) | no |
| `admin` | PUBLIC, INTERNAL, CONFIDENTIAL, RESTRICTED | no (all depts) | yes |
This determines what your query/generation calls can actually retrieve —
if you're getting thin or empty answers, check the account's role before
assuming the query is wrong.
---
## 3. Error shape (all endpoints)
```json
{"error": "human-readable message", "trace_id": "..."}
```
Status codes: `400` bad input / blocked query, `401` missing/invalid/expired
token, `403` wrong tenant or missing role permission, `404` not
found-or-not-yours (these two are indistinguishable on purpose — no
existence leaks across tenants), `413` file too large, `415` unsupported
file type, `422` file passed the type check but extraction failed, `429`
rate-limited, `500` internal error. Never expect a stack trace in the body.
---
## 4. Mode 1 — Quick Query
### `POST /api/query`
Ask a question against the caller's own knowledge base.
**Request:**
```json
{
"message": "What was our Q3 revenue?",
"conversation_id": "optional — omit to start a new conversation",
"document_ids": ["optional array — narrows retrieval to specific documents"]
}
```
- `message`: required, max 2000 chars. Text is inspected by a prompt-injection
guard *before* it reaches embedding — a detected attack returns a generic
`400` ("Your query could not be processed.") and never tells you why, so
don't try to parse the reason out of the response.
- `conversation_id`: omit on the first turn; the response returns one, reuse
it for follow-ups (last 10 turns of history are replayed as context).
- `document_ids`: optional. Not a security boundary — if you pass an ID
outside your tenant/permissions it just yields no extra results, it
doesn't error or leak anything.
**Response shape depends on the `Accept` header** — this is the one thing
most likely to trip you up:
#### 4a. Synchronous JSON (recommended for a server-to-server integration)
Send any `Accept` header that is *not* `text/event-stream` (e.g. omit it, or
send `application/json`).
```
POST /api/query
Authorization: <token>
Content-Type: application/json
Accept: application/json
{"message": "...", "conversation_id": null}
```
Response `200`:
```json
{
"answer": "Q3 revenue was $2.1M [Source: financials-q3.pdf, pg 4].",
"sources": ["financials-q3.pdf"],
"latency_ms": 1830,
"conversation_id": "generated-or-echoed-uuid",
"access_restricted": false
}
```
- `sources` is a **flat list of filenames**, deduplicated, in first-cited
order — not the raw retrieved chunks, only what the model actually cited.
- `access_restricted: true` means the answer text you got back IS the fixed
message below, not a real answer — see §7.
#### 4b. SSE streaming (what the browser chat UI uses)
```
Accept: text/event-stream
```
Response is `text/event-stream`, one `data: {...}\n\n` frame per event:
```
data: {"token": "Q3 "}
data: {"token": "revenue "}
data: {"token": "was..."}
data: {"done": true, "sources": [{"filename": "financials-q3.pdf", "page": 4}], "conversation_id": "...", "access_restricted": false}
```
- Token frames: `{"token": "<text chunk>"}`, concatenate in order for the
full answer.
- Final frame: `{"done": true, "sources": [...], "conversation_id": "...", "access_restricted": bool}`.
Note `sources` here is the **richer** `{filename, page}` object list, not
the flat string list from the JSON path.
- If access-restricted, you still get a normal-looking single-token frame
carrying the fixed message, then the `done` frame with `access_restricted: true`.
**If you're building a non-browser integration, use the JSON path (4a).**
It's simpler and it's the one that already has a real automated consumer
(`rag_eval.py`) exercising it as a regression test.
### `GET /api/conversations`
Sidebar-style list of the caller's tenant's recent conversations.
```json
{"conversations": [{...}]}
```
### `GET /api/conversations/{conversation_id}`
```json
{"conversation_id": "...", "messages": [{"role": "user|assistant", "content": "...", "sources": [...]}]}
```
A `conversation_id` from another tenant just returns an empty message list,
not a 404 or error.
---
## 5. Mode 2 — Document Generation
### `POST /api/generate`
Multipart form, **not** JSON:
```
POST /api/generate
Authorization: <token>
Content-Type: multipart/form-data
trigger_doc: <file> # required — the RFP/brief/tender
context: "optional free text" # optional
```
Same file rules as upload (§6.2). `context` goes through the same
injection guard as `message` in Quick Query.
**Always streams** — no JSON alternative for this endpoint, regardless of
`Accept` header. Response is `text/event-stream` with these event types, in
order:
```
data: {"type": "access_disclosure", "role": "staff", "classes_included": [...], "classes_excluded": [...], "departments_searched": [...], "documents_excluded": true, "liability_disclaimer": "..."}
data: {"type": "section_start", "section_name": "Executive Summary"}
data: {"type": "token", "section_name": "Executive Summary", "token": "Our organization..."}
... (many token events per section)
data: {"type": "section_complete", "section_name": "Executive Summary", "word_count": 412, "sources": [{"filename": "...", "page": 3}]}
... (section_start / token* / section_complete repeats per section)
data: {"type": "done", "job_id": "abc123", "download_url": "https://...presigned-r2-url"}
```
On failure mid-generation:
```
data: {"type": "error", "message": "..."}
```
Partial output up to the last completed section is preserved server-side
(check job status afterward — it isn't lost, just not in this stream).
Rate limit: **5 requests/hour per tenant** — expect `429`s if you're
hammering this in a test loop.
### `GET /api/generations`
```json
{"jobs": [{"job_id": "...", "trigger_doc_name": "...", "status": "generating|completed|failed", "sections_total": 5, "last_updated": "..."}]}
```
---
## 6. Knowledge base upload
### `POST /api/upload`
Multipart, one file field named `file`:
```
POST /api/upload
Authorization: <token>
Content-Type: multipart/form-data
file: <binary>
```
Response `202`:
```json
{"document_id": "...", "status": "queued", "filename": "original-name.pdf"}
```
This kicks off async ingestion (Docling → classification → chunk → embed →
index) — poll `/api/status/{document_id}` for progress (§6.3). Note: as of
the current build, a fresh upload needs a classification confirmation step
(`POST /api/admin/documents/{id}/classify`, admin-only) before it's fully
searchable — check `status` for `awaiting_classification` /
`pending_approval` states if answers seem to be missing a document you just
uploaded.
### 6.2 File constraints (applies to both `/api/upload` and `/api/generate`'s `trigger_doc`)
- Max size: 50MB
- Accepted MIME types (checked by magic bytes, not extension or declared
`Content-Type` alone): `application/pdf`, `application/msword`,
`.docx`, `application/vnd.ms-excel`, `.xlsx`, plus `image/jpeg`,
`image/png`, `image/tiff`, `image/bmp` (OCR'd via Docling)
- Rate limit: 10 requests/minute per tenant
### `GET /api/documents`
```json
{"documents": [{"document_id": "...", "filename": "...", "status": "..."}]}
```
Use this to build a picker for `document_ids` in `/api/query`.
### 6.3 Status polling
`GET /api/status/{document_id}`
```json
{"document_id": "...", "status": "queued|processing|indexed|failed|awaiting_classification|pending_approval", "progress": {"indexed": 12, "total": 20}, "error": null}
```
`GET /api/status/generation/{job_id}`
```json
{
"job_id": "...", "trigger_doc_name": "...", "status": "generating|completed|failed",
"progress": {"complete": 3, "total": 5},
"last_completed_section": "Executive Summary",
"error": null,
"download_url": "https://... (only when completed, regenerated fresh on every poll, valid ~72h)",
"sections": [{"section_name": "...", "content": "...", "sources": [...], "word_count": 412}],
"access_disclosure": {...}
}
```
---
## 7. Access-restricted vs. genuinely-empty answers
If retrieval finds nothing your account is allowed to see, but the topic
*does* exist elsewhere in the tenant's knowledge base at a class/department
you can't access, the API returns this exact fixed string as the answer
(not a normal "I don't know") and sets `access_restricted: true`:
> "I found references to this topic in your knowledge base, but the relevant
> documents are not accessible at your current permission level. Please
> contact your administrator if you believe you should have access."
Treat `access_restricted: true` as a distinct UI/handling case, not a normal
answer — don't just print it inline as if the model answered the question.
---
## 8. Misc
- `GET /health` — unauthenticated, `{"status": "ok", "qdrant": "ok", "pocketbase": "ok"}` or degraded.
- `GET /api/tenant` — caller's own tenant `{id, name, plan}`.
- CORS is locked to a configured origin — a browser-based integration from
an arbitrary origin will be blocked; a server-to-server integration
(no browser, no CORS preflight) is unaffected.
- No API keys — auth is exclusively the PocketBase session token above.
Tokens expire; a `401` mid-session means re-authenticate against
PocketBase, there's no refresh-token flow to call instead.
---
## 9. Minimal working example (JSON query, server-to-server)
```bash
# 1. Authenticate
TOKEN=$(curl -s -X POST "$POCKETBASE_URL/api/collections/users/auth-with-password" \
-H "Content-Type: application/json" \
-d '{"identity":"user@example.com","password":"..."}' | jq -r .token)
# 2. Query
curl -s -X POST "$API_BASE_URL/api/query" \
-H "Authorization: $TOKEN" \
-H "Content-Type: application/json" \
-H "Accept: application/json" \
-d '{"message": "What was our Q3 revenue?"}'
```