Metadata-Version: 2.5
Name: gentiq
Version: 1.0.0a4
Summary: A FastAPI and Pydantic AI backend for AI chat apps: auth, chat history, streaming, plans and usage metering, and an admin API.
Project-URL: Homepage, https://github.com/arxyzan/gentiq
Project-URL: Repository, https://github.com/arxyzan/gentiq
Project-URL: Documentation, https://github.com/arxyzan/gentiq#readme
Project-URL: Issues, https://github.com/arxyzan/gentiq/issues
Author-email: Aryan Shekarlaban <arxyzan@gmail.com>
License: Apache-2.0
Keywords: ai,chatbot,fastapi,framework,pydantic-ai
Classifier: Development Status :: 4 - Beta
Classifier: Framework :: FastAPI
Classifier: Intended Audience :: Developers
Classifier: License :: OSI Approved :: Apache Software License
Classifier: Programming Language :: Python :: 3.13
Requires-Python: >=3.13
Requires-Dist: argon2-cffi>=23.1.0
Requires-Dist: email-validator>=2.0.0
Requires-Dist: fastapi>=0.129.0
Requires-Dist: genai-prices>=0.1.8
Requires-Dist: httpx2>=2.12.0
Requires-Dist: prometheus-client>=0.21.0
Requires-Dist: pydantic-ai-slim[anthropic,google,logfire,mcp,openai,ui]<3,>=2.49.0
Requires-Dist: pyjwt>=2.11.0
Requires-Dist: python-multipart>=0.0.22
Requires-Dist: sse-starlette>=3.2.0
Requires-Dist: starlette>=0.52.1
Requires-Dist: uvicorn>=0.40.0
Provides-Extra: engines
Requires-Dist: minio>=7.2.20; extra == 'engines'
Requires-Dist: pymongo>=4.16.0; extra == 'engines'
Description-Content-Type: text/markdown

# Gentiq Backend Framework (Python)

`gentiq` is the Python half of Gentiq, built on [FastAPI](https://fastapi.tiangolo.com/) and [Pydantic AI](https://ai.pydantic.dev/). You give it a Pydantic AI agent; it gives you a FastAPI app with user accounts, chat history, streaming, plans and usage metering, and the API the Gentiq admin panel uses.

---

## Features

- **`GentiqApp`**: wraps an agent in a FastAPI application, served as `app.api`.
- **Pydantic AI agents**: your agent and tools stay plain Pydantic AI code, typed with `AgentDeps`.
- **`AgentDeps`**: every tool gets the current `User`, their own threads and your own context.
- **Plugins**: the admin panel's API (`gentiq.admin`), plans and quotas (`gentiq.billing`), voice input (`gentiq.voice`), maintenance jobs (`gentiq.jobs`) and metrics, the watchdog and maintenance mode (`gentiq.ops`) are optional, passed as `GentiqApp(plugins=[...])`, and you can write your own (`GentiqPlugin`).
- **Plans, credits and quotas**: each user is on a plan with calendar-aligned limits, a pool of credits, or unlimited, enforced on every turn.
- **Per-model cost accounting**: each request is priced by the provider and model that served it.
- **Pluggable persistence**: SQLite or MongoDB for data, the local filesystem or MinIO for files, or your own engine.
- **Authentication**: JWT sessions with separate user and admin signing keys, argon2id password hashing, permission-checked admin routes, and scoped keys for server-to-server calls.
- **Observability**: logs on stdout carrying the request id, optional Logfire tracing, and Prometheus metrics with the `Ops` plugin.

---

## Installation

Gentiq needs Python 3.13 or later.

```bash
pip install gentiq
```

The base install runs on SQLite and the local filesystem, so it needs no other services. For the MongoDB and MinIO engines:

```bash
pip install "gentiq[engines]"     # or: uv add "gentiq[engines]"
```

To develop an app against a local checkout of this repository, point uv at it:

```toml
# In your app's pyproject.toml; the path is relative to that file.
[tool.uv.sources]
gentiq = { path = "../gentiq/packages/gentiq-python", editable = true }
```

Inside this repository, the root uv workspace (`uv sync --all-packages --all-extras`) already installs it in editable mode.

---

## Quick Start

```python
from gentiq import AgentDeps, CORSConfig, GentiqApp
from pydantic_ai import Agent

# 1. Define your agent (typed with Gentiq dependencies)
agent = Agent("openai:gpt-5.1", deps_type=AgentDeps[None])

# 2. Boot the app
app = GentiqApp(
    agent,
    app_name="MyAI",
    app_version="1.2.3",
    # No CORS middleware is installed unless you ask for it. Omit this when the
    # frontend is same-origin or proxied; list every browser origin that calls
    # this API directly otherwise.
    cors=CORSConfig(allow_origins=["http://localhost:5173"]),
)

# GentiqApp.api is a regular FastAPI instance
# Run with: uv run uvicorn main:app.api --reload --port 8000
```

If your app already exposes a version constant, pass that value into `app_version` so Gentiq uses the same source of truth as the rest of your backend.

Everything after the agent is a keyword argument. Besides `context`, `app_name`, `app_version`,
`public_url`, `cors`, `logging`, `logfire`, `settings` and `plugins`, the options are grouped into
three config objects, each optional:

| Object | Holds |
|---|---|
| `StorageConfig` (`storage=`) | `db` and `files`: the database and file engines |
| `AuthConfig` (`auth=`) | `adapter`, `login_fields`, `rate_limit` and `extra_admin_permissions` |
| `ChatConfig` (`chat=`) | `title_agent`, `ask_user`, `follow_up_suggestions`, `show_reasoning`, `context_policy`, `run_options`, `attachment_types`, `features` and `usage_pricing` |

The sections below show each option in use. `GentiqApp`'s docstring documents them in one place.

### Settings and Environment

A `GentiqSettings` holds a deployment's secrets, limits and connections. `GentiqApp` reads one from
the environment when it is constructed (`GentiqSettings.from_env()`), or takes one you build:

```python
import os

from pydantic_ai import Agent

from gentiq import AgentDeps, GentiqApp, GentiqSettings


agent = Agent("openai:gpt-5.1", deps_type=AgentDeps[None])
settings = GentiqSettings(
    jwt_secret_key=os.environ["APP_SIGNING_KEY"],
    max_attachment_size=20 * 1024 * 1024,
)
app = GentiqApp(agent, settings=settings)
```

Importing `gentiq` reads nothing and configures nothing, so two apps with different settings can run
in one process. Gentiq reads no `.env` file: load one yourself before the agent is defined, as the
starter's `main.py` does with `python-dotenv`. The variables `from_env` reads, each the upper-case
name of a `GentiqSettings` field except `GENTIQ_METRICS_ENABLED` (`metrics_enabled`). An unset or
empty variable keeps the field's default:

| Variable | Notes |
| --- | --- |
| `JWT_SECRET_KEY` | **Required.** Signs user tokens. `GentiqApp` raises `InsecureConfigurationError` when it is missing, shorter than 32 characters, or a value from an example file. Generate one with `python -c "import secrets; print(secrets.token_hex(32))"`. |
| `ADMIN_SETUP_TOKEN` | The token the admin panel asks for to create the first admin (`setup_token` in `POST /api/admin/admins`). Unset, no first admin can be created. At least 16 characters. |
| `BACKEND_API_KEY` | The root key for server-to-server calls: every integration scope plus the admin API. Unset, there is no root key, and server-to-server calls need a scoped key. Give partner platforms a scoped key under the admin panel's **Settings → Integrations** rather than this one. |
| `ADMIN_JWT_SECRET_KEY` | Optional. Derived from `JWT_SECRET_KEY` when unset, so admin and user tokens are signed with different keys. If set, the same rules as `JWT_SECRET_KEY` apply. |
| `JWT_EXPIRATION_HOURS` / `ADMIN_JWT_EXPIRATION_HOURS` | Default 24 h and 8 h. |
| `LOGIN_FIELDS` | Comma-separated subset of `username`, `email`, `phone`. Defaults to `username`. `AuthConfig(login_fields=...)` wins. |
| `QUOTA_TIMEZONE` | IANA zone that calendar quota windows align to ("per day" resets at local midnight). Default `UTC`. |
| `QUOTA_CALENDAR` | `gregorian` or `persian`: the calendar monthly windows and plan lengths are counted in. Default: the timezone's own calendar (Persian for `Asia/Tehran` and `Asia/Kabul`). |
| `PUBLIC_URL` | Where the chat frontend is served, so the integration API can return a ready `login_url`. |
| `MAX_ATTACHMENT_SIZE` | In bytes. Default 10 MiB. |
| `MAX_REQUEST_BODY_SIZE` | Cap on a chat request's body, in bytes. Defaults to 4/3 of `MAX_ATTACHMENT_SIZE` plus 1 MiB, so an API client can still send a file base64-encoded inside it. |
| `ARGON2_TIME_COST` / `ARGON2_MEMORY_COST` / `ARGON2_PARALLELISM` | Password-hashing cost, sized for a small container by default. |
| `LOG_LEVEL` | Threshold for the app's and Gentiq's log records on stdout. Default `INFO`. |
| `LOG_FORMAT` | `text` (one readable line per record, the default) or `json` (one object per line, for Logstash, Elasticsearch and other log pipelines). Every line carries the request id, and during a chat turn the user and thread. See [the logging guide](../../monitoring/README.md#logs). |
| `LOG_COLOR` | `true`/`false` to color text logs or not. Unset: colored on a terminal only, following `NO_COLOR` and `FORCE_COLOR`. |
| `GENTIQ_METRICS_ENABLED` | `true` serves Prometheus metrics at `/metrics` (with the `Ops` plugin). `Ops(metrics=...)` wins. |
| `METRICS_TOKEN` | Bearer token a scraper must present at `/metrics`. Unset, the endpoint is open. |
| `LOGFIRE_TOKEN` | The Logfire token used when `GentiqApp(logfire=True)`. |
| `HTTP_PROXY` | Not a setting: `create_title_agent` and the built-in transcribers read it when they are created and given no `proxy`. |
| `MONGODB_URI`, `MONGODB_DB_NAME`, `MONGODB_USERNAME`, `MONGODB_PASSWORD` | Only for `StorageConfig(db="mongodb")`. |
| `MINIO_ENDPOINT`, `MINIO_ACCESS_KEY`, `MINIO_SECRET_KEY` | Only for `StorageConfig(files="minio")`, which connects without TLS. For TLS, pass `MinioEngine(..., secure=True)` instead. |

### Usage Cost Tracking

Usage is priced and snapshotted automatically, per request, against
[`genai-prices`](https://github.com/pydantic/genai-prices) — the rate data pydantic-ai already ships.
It covers every provider pydantic-ai supports, resolves aliases and dated snapshots
(`gpt-4o-2024-08-06` → `gpt-4o`), and carries cache-read, cache-write and audio rates, long-context
tiers, and rates that change over time. Each response is priced by the provider and model that
actually served it, so a `FallbackModel` run or a per-run model override is still billed correctly.

`UsagePricing` is an **override layer**, consulted first and empty by default. Use it for negotiated
or resale rates, or to correct a model the bundled data has wrong:

```python
from gentiq import AgentDeps, ChatConfig, GentiqApp, ModelPrice, UsagePricing
from pydantic_ai import Agent

agent = Agent("openai:gpt-5.1", deps_type=AgentDeps[None])
pricing = UsagePricing(
    prices={
        # Keys are "{provider}:{model}", matched case-insensitively.
        "openai:gpt-5.1": ModelPrice(
            input_per_million="1.50",
            output_per_million="12.00",
            cache_read_per_million="0.15",
        )
    }
)
app = GentiqApp(agent, chat=ChatConfig(usage_pricing=pricing))
```

`use_price_data=False` makes your rate card the only source of truth, leaving anything not listed
unpriced. The bundled data is in USD, so it is never consulted for a rate card in another currency:

```python
from gentiq import ModelPrice, UsagePricing

custom_pricing = UsagePricing(
    currency="EUR",
    prices={"openai:my-model": ModelPrice("2.00", "8.00")},
    use_price_data=False,
)
```

Only `input_per_million` and `output_per_million` are required; a bucket left as `None` is billed at
the rate of the bucket it is carved out of (cached input at the input rate, and so on) rather than at
zero. Each ledger row records the rates applied, the `price_source` (`override` or `genai-prices`)
and, when genai-prices billed the model under another name, the canonical model (`billed_as`).

---

### Plans & Usage Quotas

With the `Billing` plugin, Gentiq meters every chat turn and enforces what each user may use. It
supplies the mechanism — meters, windows, plans, credits, enforcement — and **your app owns the
catalogue**: which plans exist and what each allows. Without the plugin every user is unlimited, has
each declared feature's `default`, and the admin panel has no Plans tab.

Every user has exactly one kind of access at a time, the way a chat product works:

- **A plan** — limits that reset on the calendar: 200 messages a day, 2M tokens a month.
- **Credits** — a fixed number to spend, which never refills on its own.
- **Unlimited** — nothing is counted against them. This is the default.

```python
from gentiq import AgentDeps, ChatConfig, Feature, GentiqApp
from gentiq.billing import Billing, Limit, Plan, PlanDuration
from pydantic_ai import Agent

agent = Agent("openai:gpt-5.1", deps_type=AgentDeps[None])
billing = Billing(
    plans=[
        Plan(key="free", name="Free", limits=[Limit(meter="messages", amount=20, per="day")]),
        Plan(
            key="plus",
            name="Plus",
            duration=PlanDuration(per="year"),
            limits=[
                Limit(meter="tokens", amount=250_000, per="day"),
                Limit(meter="tokens", amount=2_000_000, per="week"),
                Limit(meter="messages", amount=10, per="minute"),
            ],
            features={"web_search": True},
        ),
    ],
    default_plan="free",  # or default_credits=500; with neither, users are unlimited
    quota_timezone="Asia/Tehran",
    week_start="saturday",
)
app = GentiqApp(
    agent,
    chat=ChatConfig(features=[Feature(key="web_search", name="Web search", default=False)]),
    plugins=[billing],
)
```

- **Meters.** `messages` (one accepted chat turn, reserved atomically so the limit holds under
  concurrent requests), `tokens`, `model_requests` and `cost` (microunits of your pricing currency),
  counted when the turn ends. Any other name is an app-defined meter you record from a tool.
- **Windows.** `per="minute" | "hour" | "day" | "week" | "month"` align to the calendar in
  `quota_timezone`: a day starts at local midnight, a week on `week_start`, a month on the 1st of
  the quota calendar's month — 1 Mehr rather than 1 October with `quota_calendar="persian"`, which
  is the default for `Asia/Tehran`. With `anchor="subscription"` a window counts from the day the
  subscription starts instead, in steps of `every` — a billing month that renews on the 14th, or
  every 2 days. These still reset on fixed points: days, weeks and months at local midnight, hours
  on the hour — never at the minute the plan was assigned. `per="subscription"` never resets while the assignment lasts.
- **Length.** A plan's `duration` — `PlanDuration(per="month", every=3)`, `PlanDuration(per="year")`
  — is how long it lasts once assigned; without one it lasts until changed. The limits apply inside
  it: the Plus plan above runs for a year, and allows 250k tokens a day and 2M a week throughout.
  A plan ends at local midnight: by default its length counts from the start of the day it was
  assigned (a month from 16 Sep ends on 16 Oct at 00:00); with `PlanDuration(per="month",
  align="calendar")` the period it was assigned in counts as the first, so it ends on the 1st of a
  month, the first day of a week, or 1 January (a month from 16 Sep ends on 1 Oct).
- **Subscriptions** put a user on a plan from `starts_at` (now, by default) for the plan's length,
  keyed by an `external_id` you choose (an order or enrolment id), so writing the same assignment
  twice is the same assignment. The end is never sent; it follows from the plan.
  A user has one at a time: a subscription that is created or changed ends any other it overlaps.
  One that ends simply stops applying, and the user is back on their credits or the default.
- **Nothing renews on its own.** Payment happens on your platform, so renewing is yours to say: when
  the user pays again, write a new subscription under the new order's `external_id`. To extend
  without a gap or an overlap, start it where the current one ends (`starts_at` = its `ends_at`).
- **Credits** count one meter — `credits_meter="messages" | "tokens" | "cost"`, tokens by default.
  They are granted per user from the admin panel or the integration API, or every user starts with
  `default_credits`.
- **Usage counts up.** A subscription that moves a user to a bigger plan mid-day gives them the
  difference; raising a plan's limit gives every subscriber headroom on their next message. Nothing
  runs on a schedule: a new window is a counter that does not exist yet. Usage is reset only by
  setting a user's access directly (see below) or by an admin resetting it.

What applies to a user, checked on every turn: your `Billing(resolve_plan=...)` hook if you pass one, then their
subscription, then their own credits, then the default access. The default is configured in code
(`default_plan` or `default_credits`) and can be changed by admins under **Settings → Usage &
access**, along with the credit unit, the quota timezone, the first day of the week, and whether the
chat's top bar shows users a meter of what they have left. A refused turn gets `429 quota_exceeded` with
`Retry-After` and the reset time, `402 credits_exhausted`, or `402 plan_expired` when a plan ended
and the default credits are gone too.

Admins set one user's access (default, a plan, credits, or unlimited) from
the users table, or many users' at once with **Change access**. Setting access to a plan, unlimited
or the default starts every window at zero. Plans declared in code are written
to the database at startup and are read-only under **Users → Plans**, where admins can create more.
A plan made there can be archived, so nobody new is put on it while current subscribers keep it, or
deleted: deleting a plan anyone is on asks for a plan to move them to. They are put on it as though an
admin had assigned it — starting today (or when a booked subscription would have), for its length,
with its limits — and the default access follows if it was the deleted plan
(`DELETE /api/admin/plans/{key}?replace_with=basic`, or `billing.service.delete_plan(key, replace_with=...)`).
Each user's analytics button in **Users** opens their usage over time. From your own code, use
`billing.service.set_access(user, {"mode": "plan", "plan": "student"}, source="app")`, where
`billing` is the plugin you passed (`app.plugin(Billing)` finds it). Like the
admin panel, it starts the plan at the beginning of today in the quota timezone, for the plan's
duration, with every window at zero. Your tools can read what the user is on
(`ctx.deps.entitlement`, None without `Billing`) and meter their own usage:

```python
from gentiq import AgentDeps
from pydantic_ai import Agent, RunContext

agent = Agent("openai:gpt-5.1", deps_type=AgentDeps[None])


async def search(query: str) -> str:
    raise NotImplementedError  # your search API


@agent.tool
async def web_search(ctx: RunContext[AgentDeps[None]], query: str) -> str:
    if not ctx.deps.has_feature("web_search"):
        return "Web search is not included in the user's plan."
    if ctx.deps.usage and not ctx.deps.usage.allows("web_searches"):
        return "The user has no web searches left today."
    results = await search(query)
    if ctx.deps.usage:
        ctx.deps.usage.record("web_searches")
    return results
```

#### Features per plan

Besides its limits, a plan can include or leave out **features**: a tool, a part of the UI, voice
input. Declare them with `ChatConfig(features=[...])`; with `Billing`, each gets a switch per plan
under **Users → Plans**, plans declared in code included. Without it, every user has each feature's
`default`.

```python
from gentiq import AgentDeps, ChatConfig, Feature, GentiqApp, requires_feature
from gentiq.billing import Billing, Plan
from pydantic_ai import Agent, RunContext

agent = Agent("openai:gpt-5.1", deps_type=AgentDeps[None])

DRAWING = Feature(key="drawing", name="Drawing", description="Figures and graphs in the answer")
DRAWING_INSTRUCTIONS = "Use the draw_figure tool when a figure explains the answer better than text."

app = GentiqApp(
    agent,
    chat=ChatConfig(features=[DRAWING]),
    plugins=[
        Billing(
            plans=[
                Plan(key="free", name="Free", features={"drawing": False}),
                Plan(key="plus", name="Plus"),  # includes drawing: its default is True
            ]
        )
    ],
)


# The model never sees the tool when the user's plan leaves drawing out.
@agent.tool(prepare=requires_feature("drawing"))
async def draw_figure(ctx: RunContext[AgentDeps[None]], request: str) -> str:
    raise NotImplementedError  # your drawing code


# Nor the instructions about it.
@agent.instructions
def drawing_instructions(ctx: RunContext[AgentDeps[None]]) -> str:
    return DRAWING_INSTRUCTIONS if ctx.deps.has_feature("drawing") else ""
```

- **Whether a plan includes one** is `True`/`False` under its key in the plan's `features`. A plan
  that doesn't say gets the feature's `default` (`True` unless you say otherwise), and so do users
  on no plan: unlimited, on credits, or on a custom subscription.
- **Admins switch them** on any plan. On a plan declared in code the switch is kept apart from the
  code, in the plan's `feature_overrides`, and survives redeploys; switched back to what the code
  says, the feature follows the code again. `PUT /api/admin/plans/{key}/features` with
  `{"features": {"drawing": true}}` does the same, `null` putting a feature back as declared.
- **Gentiq's own.** With the `Voice` plugin, voice input is a feature too, under `voice_input`: a plan
  without it has no microphone, and `POST /api/chat/transcribe` refuses its users with
  `403 feature_not_in_plan`. The global switch in **Settings → Chat** still turns it off for
  everyone.
- **In the browser**, `GET /api/users/me/entitlement` says which features the user has
  (`"features": {"drawing": false}`), and `useGentiqFeature("drawing")` reads it. Gate on the
  backend too: the browser can be told anything.
- **Anything else** in a plan's `features` is yours: gentiq passes it to the agent and the APIs and
  never reads it.

#### Sharing a plan between users

Every user belongs to exactly one **subscription group**, and plans and usage belong to the group.
A user nobody put in a group is a group of their own, so all of the above applies to them as
written. Users given the same `subscription_group` — an account, a household, a team — share one
plan and one set of counters: if the plan allows 500 messages a day, that is 500 for all of them
together, and any one of them can use all 500.

```python
from gentiq import AgentDeps, GentiqApp, User
from gentiq.billing import Billing
from pydantic_ai import Agent

agent = Agent("openai:gpt-5.1", deps_type=AgentDeps[None])
billing = Billing()
app = GentiqApp(agent, plugins=[billing])


def join_account(user: User) -> None:
    billing.service.set_subscription_group(user, "account-42", source="app")  # join, or move


def leave_account(user: User) -> None:
    billing.service.set_subscription_group(user, None, source="app")
```

- **A member has no plan of their own.** A subscription written, cancelled or set through any member
  is the group's, from the integration API, the admin panel and `billing.service` alike. Writing a
  new one for the group ends the group's previous one, as it does for a single user.
- **Joining is destructive.** It ends the user's own subscriptions and takes away their own
  credits; leaving restores neither, so a user who leaves is on the default access.
- **Groups take plans, not credits.** Granting credits to a member is refused with
  `409 credits_not_for_groups`. The default access is the group's too: four members of a group with
  no plan share one default allowance, not four.
- **Usage stays where it was counted.** Joining, leaving or moving never moves or resets usage, so
  adding, removing or re-creating members cannot create allowance.
- **Membership is a field on the user**, readable as `user.subscription_group`. A group has no record
  of its own, and its plan and usage are stored under the key `group:<id>` (`Subscription.group`
  gives the id back). A `resolve_plan` hook must return the same plan to every member. Without `Billing`, a group is
only that field: the admin panel and the integration API still set it.

Conversations, analytics and the usage ledger stay per user; each usage row records the `group` that
paid for it. Admins set a user's group when editing them under **Users**, and searching for a group
id lists its members.

### Linking Users From Another Platform

A platform that signs its own users in — a school portal, a SaaS dashboard — links them to the chat
through `/api/integration/v1`, with a scoped key under the admin panel's **Settings → Integrations**. The API
separates who the user is, what they may use, and whether they are here now, so that every call is
safe to repeat:

```text
PUT  /api/integration/v1/users/{external_id}                          profile (never touches usage)
PUT  /api/integration/v1/users/{external_id}/subscriptions/{order_id} assign a plan, idempotent
POST /api/integration/v1/sessions                                     sign the user in
```

Call `POST /sessions` each time the user opens the chat:

```json
{
  "user": { "external_id": "stu_48121", "name": "Sara" },
  "subscription": { "external_id": "enrolment-2026-fall", "plan": "student" },
  "redirect_path": "/"
}
```

The response carries a `token` for API clients and a single-use, two-minute `login_code` for
browsers: redirect to `login_url` (or your chat URL with `?code=`) and the frontend exchanges it, so
no bearer token travels in a URL. Mint a code per page render. A page loaded again with a spent or
expired code still signs in, but only if the browser already holds a session for the user that code
was issued for; anything else lands on the frontend's `RequireAuth` fallback (by default `/login`).
The `subscription` is optional; sending the same one on every
sign-in changes nothing, because it is keyed by its `external_id` and its end is worked out once,
from the stored start and the plan's length. Users are found by `external_id` only — never by email or username — unless you
pass `link_by` to adopt an existing account once.

Also available: `GET /users/{external_id}/usage`, `POST .../subscriptions/{id}/cancel`,
`POST /users/{external_id}/credits` with `{"amount": n}` (additive, so it requires an
`Idempotency-Key` header) and `GET /plans`. `POST /api/auth/user`, which signs a user in by login
field or `external_id` in one call, is deprecated in favour of these endpoints; it accepts
`external_id` and `subscription` too.

**Accounts with several profiles.** When your platform sells a plan to an *account* and each of the
account's *profiles* is a chat user, make the account a subscription group (see
[Sharing a plan between users](#sharing-a-plan-between-users)). On every sign-in, send the profile's
current account as `user.subscription_group`, and that account's current order as the subscription:

```json
{
  "user": { "external_id": "profile-17", "name": "Sara", "subscription_group": "account-42" },
  "subscription": { "external_id": "order-981", "plan": "family", "starts_at": "2026-09-01T00:00:00Z" }
}
```

The group is applied before the subscription, so the order is written for the group, and every
profile of the account uses the same plan and the same counters. Sending it again writes nothing.

| When | What happens |
| --- | --- |
| The first profile signs in after the purchase | It joins the group, and the order is written for the group. |
| Another profile signs in, including a new one | It joins the group and sees what the account has already used. |
| The account renews or upgrades | The next sign-in from any profile writes the new order, which moves everyone to it. To apply it at once, `PUT` it through any member. |
| A profile is removed from the account | Send `"subscription_group": null` on its next sign-in, or at once with `PUT /users/{external_id}`. Leaving the field out keeps the profile in the group. |
| The order is refunded | `POST .../subscriptions/order-981/cancel` through any member. |

`subscription_group` is also accepted by `PUT /users/{external_id}` and returned by every user
response. Group ids are permanent: reusing one inherits that group's plan and usage. Members can
see their group's id and subscription (including its metadata) through `/api/users/me`, so use
opaque ids.

## Advanced Customization

### Custom Application Context

You can inject any custom object (database pools, service clients, config) into your agent tools via the `context` parameter.

```python
from dataclasses import dataclass

from gentiq import AgentDeps, GentiqApp
from pydantic_ai import Agent, RunContext


@dataclass
class AppContext:
    weather_api_key: str


agent = Agent("openai:gpt-5.1", deps_type=AgentDeps[AppContext])


@agent.tool
async def get_weather(ctx: RunContext[AgentDeps[AppContext]], city: str) -> dict:
    api_key = ctx.deps.context.weather_api_key  # your context, as passed to GentiqApp
    return {"temp": 22, "city": city, "key_set": bool(api_key)}


app = GentiqApp(agent, context=AppContext(weather_api_key="secret"))
```

### Progress Updates From Tools

A tool can stream progress events to the frontend while it is still running, for work that takes a while. Each one reaches the chat stream as a `data-progress-update` chunk.

```python
from gentiq import AgentDeps, ProgressUpdateEvent
from pydantic_ai import Agent, RunContext

agent = Agent("openai:gpt-5.1", deps_type=AgentDeps[None])


@agent.tool
async def long_task(ctx: RunContext[AgentDeps[None]]) -> str:
    await ctx.deps.stream(
        ProgressUpdateEvent(
            tool_name="long_task", status="running", message="Analyzing data... this might take a moment."
        )
    )
    # ... perform work ...
    return "Task completed!"
```

### Custom Stream Parts

A tool can send the chat something of its own, such as a chart or a card, with `ctx.deps.emit(name, payload)`. It streams a `data-<name>` part whose `data` is the payload as a JSON object, and stores it right after the tool call, so a reload shows it in the same place. The model never sees it. On the frontend, register a renderer for `data-<name>` in the part registry.

```python
from gentiq import AgentDeps
from pydantic import BaseModel
from pydantic_ai import Agent, RunContext

agent = Agent("openai:gpt-5.1", deps_type=AgentDeps[None])


class Point(BaseModel):
    label: str
    value: float


class Chart(BaseModel):
    title: str
    points: list[Point]


@agent.tool
async def temperature_chart(ctx: RunContext[AgentDeps[None]], city: str) -> str:
    points = [Point(label="Mon", value=21), Point(label="Tue", value=19)]
    await ctx.deps.emit("chart", Chart(title=f"Temperatures in {city}", points=points))
    return "Showed the user the chart."
```

A payload can also be a plain mapping, as long as it is JSON-serializable. Names are lowercase letters, digits, `-` and `_`; the names Gentiq streams itself (`reference`, `message-id`, `progress-update`, `title`, `chat-finished`) and the ones older versions stored (`choice-question`, `follow-up-suggestions`) are refused.

### Tools That Ask First

A tool declared with Pydantic AI's `requires_approval=True` doesn't run when the model calls it. The
turn ends with the call waiting, stored as an `approval-requested` tool part, and the chat asks the
user to approve or deny it, after a reload too. The answer goes back to `POST /api/chat` (see
[Sending Messages](#sending-messages)), and the turn carries on in the same message: an approved call
runs, and a denied one returns the user's reason, or a refusal, to the model as its result.

```python
from pydantic_ai import Agent

from gentiq import AgentDeps

agent = Agent("openai:gpt-5.1", deps_type=AgentDeps[None])


@agent.tool_plain(requires_approval=True)
def delete_file(name: str) -> str:
    return f"Deleted {name}."
```

Gentiq lets every run end with `DeferredToolRequests`, so the agent's `output_type` needs nothing
added, unless the agent has output validators, which can't take a run's output type: give such an
agent `output_type=[YourOutput, DeferredToolRequests]` yourself. Without it the app fails at startup
(or, for an agent chosen per message, on that agent's turn) with a `ValueError` saying so. Only the thread's owner can
answer, only for calls the thread's last answer waits on, and the server keeps which tool was called
with what: the request carries nothing but yes or no and a reason.

### Tools the Browser Answers

A client tool is declared on the server, so the model can call it, but answered in the browser: a
date picker, the user's location, a confirmation in your own words. Register a function's
signature on a `ClientToolset`; its body never runs. Its parameters are what the model sends, its
docstring the description, and its return type what the browser must answer with. The call ends the
turn, stored as an `input-available` tool part; the browser answers it on `POST /api/chat` (see
[Sending Messages](#sending-messages)) and the turn carries on in the same message, with the output
as the call's result. On the client, a tool component answers through `useToolOutput`.

```python
from gentiq import AgentDeps, ClientToolset
from pydantic import BaseModel
from pydantic_ai import Agent


class PickedDate(BaseModel):
    date: str


browser = ClientToolset()


@browser.tool
def pick_date(question: str) -> PickedDate:
    """Ask the user to pick a date in a calendar."""
    raise NotImplementedError


agent = Agent("openai:gpt-5.1", deps_type=AgentDeps[None], toolsets=[browser])
```

The browser is untrusted, so the server checks each output against the return type and refuses one
that doesn't fit with `validation_error` (422). Only the thread's owner can answer, and only calls
the thread's last answer waits on. If the user sends a new message instead, the model reads the
call as failed (the user sent a new message instead of answering) and still sees what it asked.

### Questions With Buttons (`ask_user`)

`ChatConfig(ask_user=...)` gives the agent Gentiq's own client tool, `ask_user`: a question with
answers to pick from, shown as buttons on the composer, and an answer in the user's own words unless
the model sets `allow_custom` to false. `True` uses Gentiq's default policy on when to ask, and a
string is your own policy instead; the policy is part of the tool's description. The result the
model reads is `{"answer": "..."}`.

```python
from gentiq import AgentDeps, ChatConfig, GentiqApp
from pydantic_ai import Agent

agent = Agent("openai:gpt-5.1", deps_type=AgentDeps[None])
app = GentiqApp(agent, chat=ChatConfig(ask_user="Ask only when a request is genuinely ambiguous."))
```

### Follow-up Suggestions

`ChatConfig(follow_up_suggestions=...)` gives the agent Gentiq's `suggest_follow_ups` tool, which
shows one to three messages the user may send next under the latest finished answer. `True` uses
Gentiq's default policy and a string is your own. The model calls it like any tool, so a turn that
suggests costs one more model request.

```python
from gentiq import AgentDeps, ChatConfig, GentiqApp
from pydantic_ai import Agent

agent = Agent("openai:gpt-5.1", deps_type=AgentDeps[None])
app = GentiqApp(
    agent,
    chat=ChatConfig(
        follow_up_suggestions="Suggest practical next actions for developers; avoid generic prompts."
    ),
)
```

### Choosing the Model per Message

The client can send run options with each turn, such as the model to answer with. Declare what it
may choose as a Pydantic model and pass it as `ChatConfig(run_options=...)`; pass an agent resolver as the agent,
a function (or coroutine function) that takes the turn's `ChatContext` (`user`, `thread_id`, and
`options`, the validated run options) and returns the `Agent` for that turn.

```python
from typing import Literal

from gentiq import AgentDeps, ChatConfig, ChatContext, GentiqApp
from pydantic import BaseModel, ConfigDict
from pydantic_ai import Agent


class RunOptions(BaseModel):
    model_config = ConfigDict(extra="forbid")

    model: Literal["fast", "smart"] = "fast"


agents = {
    "fast": Agent("openai:gpt-5-mini", deps_type=AgentDeps[None]),
    "smart": Agent("openai:gpt-5.1", deps_type=AgentDeps[None]),
}


def pick_agent(ctx: ChatContext[RunOptions]) -> Agent[AgentDeps[None]]:
    return agents[ctx.options.model]


app = GentiqApp(pick_agent, chat=ChatConfig(run_options=RunOptions))
```

The client is untrusted, so the schema alone decides what it may choose: `{"model": "gpt-5-pro"}` is
refused with `validation_error` (422) before anything is stored, and options left out take the
schema's defaults. `Literal` fields and `extra="forbid"` keep the choice to what you list. The
resolver runs for every turn, answers to tool calls included, so it can also pick by user or plan
(`ctx.user`). To hand the options to tools, override `GentiqApp.create_agent_deps(ctx)`, which gets
the same `ChatContext`. On the React side, `GentiqProvider`'s `runOptions` sends them.

### The User's Own Threads

Tools don't get Gentiq's stores. `ctx.deps.threads` reads the signed-in user's own threads and
nobody else's, for example to search their past chats. It runs the query off the event loop.

```python
from gentiq import AgentDeps
from pydantic_ai import Agent, RunContext

agent = Agent("openai:gpt-5.1", deps_type=AgentDeps[None])


@agent.tool
async def search_past_chats(ctx: RunContext[AgentDeps[None]], query: str) -> list[str]:
    # Threads whose title or messages contain `query`, pinned first, then most recently active.
    threads = await ctx.deps.threads.list(query, limit=20)
    return [thread.title or "Untitled" for thread in threads]
```

A tool that needs more, such as your own database, gets it through your `context`.

### Recording Sub-agent Runs

When a tool delegates to another agent, that agent runs in its own Pydantic AI run, which the
admin panel does not show by default. Wrap it in `ctx.deps.capture_subagents(ctx)` to record the sub-agent's
full transcript (input, output, reasoning, tool calls) into the chat history — shown in the **admin
panel only**, never to the end user. Logging is always on inside the block; passing the tool's `ctx`
also rolls the sub-agent's tokens up into the thread's usage, priced at that sub-agent's own model
rates.

```python
from gentiq import AgentDeps
from pydantic_ai import Agent, RunContext

agent = Agent("openai:gpt-5.1", deps_type=AgentDeps[None])
forecast_agent = Agent("openai:gpt-5-mini", deps_type=AgentDeps[None])


@agent.tool
async def detailed_forecast(ctx: RunContext[AgentDeps[None]], city: str) -> str:
    async with ctx.deps.capture_subagents(ctx):
        result = await forecast_agent.run(f"Give a 5-day forecast for {city}.", deps=ctx.deps)
    return result.output
```

> Sub-agents driven via `.run_stream()` / `.iter()` are not captured.

### Admin Settings

`AppSettings` holds only what an admin changed under Settings: a field that is `None`, or a map
that is empty, is the app's code to decide. `GET /api/config` returns just those overrides, and
`PATCH /api/admin/settings` takes a field set to `null` as a reset to the default. Translations are
stored only for the strings an admin edited.

### Sessions

Each user and admin has a `token_version`, and every token carries the version it was issued under.
Bumping it ends every session at once:

- `POST /api/auth/logout` and `POST /api/admin/logout` sign the caller out on every device.
- A user changing their password through `PATCH /api/users/me` ends their other sessions; the
  response carries a new `token` for the one that made the change.
- An admin changing another admin's password, or resetting a user's token with
  `POST /api/admin/users/{id}/refresh-token`, ends that account's sessions.

A custom `AuthAdapter` receives the version in `create_user_token(user_id, token_version)` and
`create_admin_token(admin_id, token_version)`, and should refuse a token whose version no longer
matches `User.token_version` or `Admin.token_version`.

### Your Own Sign-in

`GentiqApp(auth=AuthConfig(adapter=...))` takes an `AuthAdapter`, which decides who sent each request. To let users in
with your app's own session, such as a cookie your backend sets or a token from an identity provider,
subclass `JWTAuth` and override `get_current_user`; admins keep signing in with Gentiq's tokens. The
user must exist in Gentiq: create or update them through the integration API (see
[Linking Users From Another Platform](#linking-users-from-another-platform)), keyed by the same
`external_id`.

```python
from fastapi import Request
from gentiq import AgentDeps, AuthConfig, GentiqApp, JWTAuth, User, get_gentiq
from pydantic_ai import Agent


def verify_session(cookie: str) -> str | None:
    """Your app's own check of its session cookie: the user's id in your app, or None."""
    ...


class HostSessionAuth(JWTAuth):
    def get_current_user(self, request: Request) -> User | None:
        cookie = request.cookies.get("session")
        external_id = verify_session(cookie) if cookie else None
        if external_id is None:
            return None
        return get_gentiq(request).user_store.get_user_by_external_id(external_id)


agent = Agent("openai:gpt-5.1", deps_type=AgentDeps[None])
app = GentiqApp(agent, auth=AuthConfig(adapter=HostSessionAuth()))
```

The app calls the adapter's `setup(settings)` with its own `GentiqSettings` when it is built, so
`JWTAuth` signs admins' tokens with the app's keys. Override `setup` in your own `AuthAdapter` to
read keys or limits from the settings.

`get_gentiq(request)` returns the `GentiqApp` serving a request, with its stores, settings and
services. A route you add to `app.api` can take it as a parameter instead: `gentiq: CurrentApp`.

On the frontend, pass an auth adapter with no token, and `credentials: 'include'` if the API is on
another origin (see the React package's README). Gentiq issues no cookie of its own, and its
sign-out ends only the tokens Gentiq issued.

### Sign-in Rate Limits

User and admin sign-in, sign-up, first-admin setup and login-code exchange are throttled: 20
attempts a minute per client address, and 10 failed sign-ins per account in 15 minutes, after which
that account is refused, even with the right password, until the window passes. A refused attempt
gets `too_many_attempts` (429) with `Retry-After`.

Counts are kept in each process's memory, so four workers allow four times the limit. To count
across workers and replicas, implement `RateLimiter` over a shared store such as Redis:

```python
from pydantic_ai import Agent

from gentiq import AgentDeps, AuthConfig, GentiqApp, RateLimitConfig, RateLimiter


class RedisRateLimiter(RateLimiter):
    def hit(self, key: str, limit: int, window_s: float) -> float | None:
        """Record an attempt; return seconds to wait if it is over the limit, else None."""
        raise NotImplementedError

    def blocked(self, key: str, limit: int, window_s: float) -> float | None:
        """Seconds to wait before an attempt is allowed, without recording one."""
        raise NotImplementedError


agent = Agent[AgentDeps[None]]("openai:gpt-4o")
app = GentiqApp(agent, auth=AuthConfig(rate_limit=RateLimitConfig(per_ip=60, limiter=RedisRateLimiter())))
```

`AuthConfig(rate_limit=False)` turns throttling off. Behind a reverse proxy, run uvicorn with `--proxy-headers`
and `--forwarded-allow-ips` set to the proxy's address, or every client is counted as the proxy.

### Attachments and Shared Chats

Users may attach the types in `DEFAULT_ATTACHMENT_TYPES`: PNG, JPEG, GIF and WebP images, PDF,
plain text, Markdown, CSV and JSON. Any other type is refused with `unsupported_media_type` (415).
Pass `ChatConfig(attachment_types=...)` to change the list; `"image/*"` allows a whole family:

```python
from pydantic_ai import Agent

from gentiq import DEFAULT_ATTACHMENT_TYPES, AgentDeps, ChatConfig, GentiqApp

agent = Agent[AgentDeps[None]]("openai:gpt-4o")
app = GentiqApp(agent, chat=ChatConfig(attachment_types=[*DEFAULT_ATTACHMENT_TYPES, "audio/mpeg"]))
```

A file is uploaded on its own, before the message that carries it:
`POST /api/chat/attachments?filename=<name>` with the file as the body and its media type as the
`Content-Type`. The answer is `{ id, filename, media_type, size }`, and the message's file part
names the file by that id:

```json
{ "type": "file", "mediaType": "image/png", "attachmentId": "att_3f2a…" }
```

Sending the message adds the file to its thread. A message naming a file the user didn't upload is
refused with `attachment_not_found` (404), and an upload no message names within 24 hours is
deleted. A file over `MAX_ATTACHMENT_SIZE` is refused with `request_too_large` (413). `GET
/api/config` lists the accepted types and the size limit under `attachments`, which the React
composer checks before uploading. A file part may still carry its bytes as a `data:` URL instead,
for API clients that send one message with everything in it; the browser never does.

Files are served with the type recorded when they were uploaded, never the one their name suggests,
with `X-Content-Type-Options: nosniff` and a sandboxing `Content-Security-Policy`. Only those four
image types are shown inline; everything else, SVG included, downloads.

A shared chat is a snapshot. Its public link serves the snapshot's attachments at
`/api/public/shared/{share_id}/attachments/{attachment_id}`, and nothing added to the thread later.
`DELETE /api/chat/threads/{thread_id}/share` revokes every link to a thread, and deleting the thread
does the same. Thread lists mark a thread with a link as `shared`.

### Voice Input

The `Voice` plugin gives the composer a microphone button. The user speaks, taps ✓, and what
they said lands in the composer at the caret, to edit and send like anything typed. Without the plugin,
the button isn't shown and `POST /api/chat/transcribe` doesn't exist.

```python
import os

from gentiq import AgentDeps, GentiqApp
from gentiq.voice import AgentTranscriber, GeminiTranscriber, OpenAITranscriber, Voice
from pydantic_ai import Agent

agent = Agent("openai:gpt-5.1", deps_type=AgentDeps[None])

# OpenAI, or anything that copies its /audio/transcriptions endpoint. `gpt-transcribe`, the
# default, is billed by the minute and priced out of the box.
app = GentiqApp(agent, plugins=[Voice(OpenAITranscriber("gpt-transcribe", language="fa"))])
app = GentiqApp(
    agent,
    plugins=[
        Voice(
            OpenAITranscriber(
                "whisper-large-v3-turbo",
                base_url="https://api.groq.com/openai/v1",
                api_key=os.environ["GROQ_API_KEY"],
            )
        )
    ],
)
app = GentiqApp(
    agent,
    plugins=[
        Voice(
            OpenAITranscriber(
                "Systran/faster-whisper-small",
                base_url="http://whisper:8000/v1",
                api_key="-",  # self-hosted
            )
        )
    ],
)

# Gemini's transcription model, with the key from GOOGLE_API_KEY. genai-prices has no price
# for it yet; see "What dictating costs" below.
app = GentiqApp(agent, plugins=[Voice(GeminiTranscriber("gemini-3.5-transcribe", language="fa"))])

# A general Gemini model, here through a gateway in front of the Gemini API
app = GentiqApp(
    agent,
    plugins=[
        Voice(
            GeminiTranscriber(
                "gemini-3.5-flash-lite",
                base_url="https://llm-gateway.example.com/gemini",
                api_key=os.environ["GATEWAY_KEY"],
            )
        )
    ],
)

# Any other Pydantic AI model that understands audio, as a Model or a model name
app = GentiqApp(agent, plugins=[Voice(AgentTranscriber("openai:gpt-4o-audio-preview", media_types=("audio/wav",)))])
```

Pydantic AI has no speech-to-text model of its own, so `Transcriber` is Gentiq's interface. For
anything else, such as a Whisper model loaded in-process, subclass it:

```python
import asyncio

from gentiq.voice import Transcriber


def run_whisper(audio: bytes) -> str:
    raise NotImplementedError  # your in-process model


class LocalWhisper(Transcriber):
    async def transcribe(self, audio: bytes, media_type: str) -> str:
        # A model running in-process blocks; keep it off the event loop.
        return await asyncio.to_thread(run_whisper, audio)
```

`media_type` is what the browser recorded in: `audio/webm` in Chrome, Edge and Firefox, and
`audio/mp4` in Safari. A transcriber can list the formats it accepts as `media_types`. The browser
then records in one of those if it can, and converts to 16 kHz mono WAV if it can't.
`GeminiTranscriber` with `gemini-3.5-transcribe` takes the browser's own recording as it is. With
a general Gemini model it lists the formats Gemini documents. Browsers record in none of those,
so the recordings arrive as WAV, which is 32 KB a second, roughly ten times the size of the
browser's own format. If your endpoint accepts WebM, pass `media_types=None` to skip the
conversion. If your users all speak one language, set `language=` on `OpenAITranscriber` or
`GeminiTranscriber` (an ISO code such as `"fa"`), or on `AgentTranscriber` (a name such as
`"Persian"`, added to its instructions). Otherwise the model guesses on every recording, and it can confuse neighbouring
languages, such as Persian with Arabic or Urdu. `max_bytes` caps the upload. It is 25 MiB by
default (OpenAI's limit), or 20 MiB, Gemini's request limit, for `GeminiTranscriber` and
`AgentTranscriber`. Recordings go to `POST /api/chat/transcribe`, and `/api/config` reports
`voice_input: true` so the frontend knows to show the button. Admins can turn voice input off for
everyone under **Settings → Chat**. Each recording is kept in the
storage engine with the attachments, under `voice/{user_id}/`, in the format the browser sent.
That includes recordings the user never sent.

#### What dictating costs

Each built-in transcriber answers with a Pydantic AI `ModelResponse`, and its usage is priced
with your `UsagePricing`, from the same genai-prices data as the chat's own turns. Token-billed
models such as `gpt-4o-transcribe` report tokens. Duration-billed ones such as `gpt-transcribe`,
`whisper-1` and Groq's Whisper report `audio_seconds`. The transcript goes back to the composer,
and the cost is kept until the user sends the message they dictated. That turn adds the cost
to its input cost, so it counts towards the thread's total and towards a plan's cost limit. A
retried turn doesn't pay for the same dictation twice. In the admin chat history, a dictated
message has a **Voice input** pill showing the model, how long the user spoke, and the cost,
with a button that downloads the recording. Shared snapshots of a thread show none of this.

A model genai-prices has no price for, such as `gemini-3.5-transcribe`, leaves the turn
`partial`. Give it a rate the same way as for any other model:

```python
from gentiq import ModelPrice, UsagePricing

UsagePricing(
    prices={
        # Illustrative rates per million tokens: take the real ones from Google's pricing page
        "google:gemini-3.5-transcribe": ModelPrice("0.50", "2.00", input_audio_per_million="1.00"),
        "openai:whisper-1": ModelPrice(0, 0, audio_per_hour="0.36"),  # billed by duration
    }
)
```

A custom transcriber that returns a plain `str` costs nothing. To have its calls priced, return
`transcription_response(text, RequestUsage(...), model=..., provider=...)` instead. The
transcriptions' records are in the `voice_inputs` collection. They hold the usage, the cost
and the recording's `object_name`, but not the transcript; the message the user sent is the
text that was kept.

### Maintenance Operations

Register migrations and one-off fixes as jobs runnable from the admin panel's **Operations** tab,
for the times you cannot get a shell on the production server. The job receives a `JobContext`
exposing the user, admin, chat and settings stores, `ctx.entitlements` (with `Billing`), the storage engine, the raw
DB engine (`ctx.engine`), validated `ctx.params`, a `ctx.dry_run` flag, and `ctx.log(...)`, whose
output is captured into the run record. They come with the `Jobs` plugin; register them with
`@jobs.job(...)`, or pass them as `Jobs([...])`.

```python
import re

from gentiq import AgentDeps, GentiqApp
from gentiq.jobs import JobContext, Jobs, ParamSpec
from pydantic_ai import Agent

agent = Agent("openai:gpt-5.1", deps_type=AgentDeps[None])
jobs = Jobs()
app = GentiqApp(agent, plugins=[jobs])


@jobs.job(
    id="count_users",
    name="Count users",
    description="Reports how many users exist. Safe to run anytime.",
    danger="safe",
    params=[ParamSpec(name="prefix", type="str", required=False, label="Name prefix")],
)
def count_users(ctx: JobContext) -> dict:
    prefix = (ctx.params.get("prefix") or "").strip()
    flt = {"name": {"$regex": f"^{re.escape(prefix)}", "$options": "i"}} if prefix else {}
    count = ctx.engine.count_documents("users", flt)
    ctx.log(f"Matched users: {count}")
    return {"count": count}
```

Operations are gated behind the admin `operations` permission. A job with `danger="destructive"` runs
only after the admin confirms it. `Jobs(enable_raw=True)` also lets admins run arbitrary Python from the
panel, after typing a confirmation phrase. It needs no permission beyond `operations`, so leave it off
unless every Operations admin should have what amounts to shell access.

#### Returning files

An operation can publish a downloadable artifact by returning a `JobFile`. The bytes go to the app's
storage engine (filesystem or MinIO); only the address travels in the run record.

```python
from gentiq import AgentDeps, GentiqApp
from gentiq.jobs import JobContext, Jobs
from pydantic_ai import Agent

agent = Agent("openai:gpt-5.1", deps_type=AgentDeps[None])
jobs = Jobs()
app = GentiqApp(agent, plugins=[jobs])


@jobs.job(id="export_users", name="Export users", danger="safe")
def export_users(ctx: JobContext) -> dict:
    users = ctx.engine.find_many("users", {})
    csv = "id,name\n" + "\n".join(f"{u['id']},{u.get('name') or ''}" for u in users)
    # Alternatives: ctx.save_path("/tmp/report.pdf") for a file on disk, or
    # ctx.file("reports/2026-01.pdf") to point at an object already in storage.
    return {"users": len(users), "export": ctx.save_file(csv, filename="users.csv")}
```

Return one on its own or nested anywhere in the result. In the run record each becomes an envelope
tagged with the reserved `__gentiq__` key (`gentiq.job_file/1`), which an application's own result
fields cannot collide with, and the run lists them under `files`, which the admin panel renders as
download buttons.

Artifacts are served from `GET /api/admin/jobs/runs/{run_id}/files/{index}` **by index**, so the
endpoint can only hand back files a job actually published, never arbitrary objects from the
storage backend. It requires the same `operations` permission as the rest of the tab.

### Login Handles

`login_fields` chooses which of `username`, `email` and `phone` a user can sign in with. Only enabled
fields are unique; the rest are ordinary, non-unique profile data. The real identity is always the
immutable user `id`, which is what JWTs carry.

```python
from gentiq import AgentDeps, AuthConfig, GentiqApp
from pydantic_ai import Agent

agent = Agent("openai:gpt-5.1", deps_type=AgentDeps[None])
app = GentiqApp(agent, auth=AuthConfig(login_fields=["email", "phone"]))
```

---

## Plugins

Optional subsystems are plugins, passed as `GentiqApp(plugins=[...])`. None run unless passed, and
the chat core never imports them. Gentiq ships five: `AdminAPI` (`gentiq.admin`, see
[The Admin API](#the-admin-api)), `Billing` (`gentiq.billing`, see [Plans & Usage Quotas](#plans--usage-quotas)), `Voice`
(`gentiq.voice`, see [Voice Input](#voice-input)), `Jobs` (`gentiq.jobs`, see
[Maintenance Operations](#maintenance-operations)) and `Ops` (`gentiq.ops`, see [Metrics and Maintenance Mode](#metrics-and-maintenance-mode)). `GET /api/config` lists the names of the plugins
an app runs under `plugins`, so the browser shows only what exists.

A plugin of your own subclasses `GentiqPlugin` and overrides the hooks it needs: `features()` adds
plan features, `setup(app)` runs once the stores exist, `routers()` adds routes under `/api`,
`public_config()` adds fields to `/api/config`, and `startup()` and `shutdown()` run with the app.
`app.plugin(Kind)` returns the app's plugin of that class. A plugin that limits usage replaces
`app.gate`, a `TurnGate`, in its `setup`: the chat asks it to admit each turn, and the `TurnPass` it
returns counts what the turn used, as `Billing` does. A plugin that watches the service replaces
`app.monitor`, a `ChatMonitor`: the chat asks it whether it is open and reports each turn's outcome
to it, as `Ops` does.

```python
from fastapi import APIRouter
from gentiq import AgentDeps, GentiqApp, GentiqPlugin
from pydantic_ai import Agent


class Ping(GentiqPlugin):
    name = "ping"

    def routers(self) -> list[APIRouter]:
        router = APIRouter()

        @router.get("/ping")
        def ping() -> dict[str, bool]:
            return {"ok": True}

        return [router]


agent = Agent("openai:gpt-5.1", deps_type=AgentDeps[None])
app = GentiqApp(agent, plugins=[Ping()])
```

### The Admin API

The admin panel's routes under `/api/admin` (first-admin setup, admin sign-in and accounts, users,
chat history, analytics, settings and the integration API's keys) are the `AdminAPI` plugin. Leave
it out and the app serves chat only: it issues no admin tokens, so the admin routes of `Billing`
and `Jobs` can't be reached either, nor `Ops`' Operations > Status routes.

```python
from gentiq import AgentDeps, GentiqApp
from gentiq.admin import AdminAPI
from pydantic_ai import Agent

agent = Agent("openai:gpt-5.1", deps_type=AgentDeps[None])
app = GentiqApp(agent, plugins=[AdminAPI()])
```

### Metrics and Maintenance Mode

Prometheus metrics, the internal watchdog and maintenance mode are the `Ops` plugin. It closes the
chat to new messages during maintenance (`POST /api/chat` and voice answer 503), puts the notice in
`GET /api/config` and `GET /api/status`, counts every turn, serves `/metrics` when metrics are on,
and adds the admin panel's Operations > Status routes under `/api/admin/status`. Without it the chat
is always open, the notice is never active, and nothing is counted.

```python
from gentiq import AgentDeps, GentiqApp, MaintenanceConfig
from gentiq.ops import Ops
from pydantic_ai import Agent

agent = Agent("openai:gpt-5.1", deps_type=AgentDeps[None])
app = GentiqApp(agent, plugins=[Ops(metrics=True, maintenance=MaintenanceConfig(poll_interval_s=60))])
```

`Ops` takes `metrics` (`True`, `False` or a `MetricsConfig`; unset, `GENTIQ_METRICS_ENABLED`
decides), `maintenance` (a `MaintenanceConfig`, or `False` to remove maintenance mode),
`watch_rules` (extra `WatchRule`s on top of the built-in ones) and `on_status_change` (called with
a `StatusChange` when a watch rule trips or recovers and when maintenance starts or ends).

## Pluggable Architecture

### Persistence Engines

Data goes to a database engine and files to a storage engine. By default these are SQLite, in a
file named after `app_name` (lowercased, so `gentiq app.db` when `app_name` is left out) in the
working directory, and the filesystem, under `./.storage`. MongoDB and MinIO are built in too,
configured from the environment variables above and installed with `gentiq[engines]`:

```python
from gentiq import AgentDeps, GentiqApp, StorageConfig
from pydantic_ai import Agent

agent = Agent("openai:gpt-5.1", deps_type=AgentDeps[None])
app = GentiqApp(agent, storage=StorageConfig(db="mongodb", files="minio"))
```

SQLite is for local development: it serves one process and serializes every read. When the app
starts on SQLite with a `public_url` that isn't this machine, it logs a warning saying to use
MongoDB. On SQLite, `create_index` builds indexes on the JSON fields, but doesn't enforce
`unique`.

Both parameters also accept an engine *instance*: a configured `SQLiteEngine`, `MongoEngine`,
`FileSystemEngine` or `MinioEngine`, or your own subclass of `DBEngine` or `StorageEngine`.

### Sending Messages

`POST /api/chat` takes the new message and the stored message it follows, and streams the reply as
a Vercel AI SDK UI message stream. The server holds the thread: it loads the history from the
store, so the model sees what was stored, never what a request says happened.

```json
{
  "threadId": "3f2a9c",
  "parentMessageId": "msg_asst_3f2a9c_1767225600000",
  "message": {
    "id": "msg_7d1e",
    "role": "user",
    "parts": [
      { "type": "text", "text": "And tomorrow?" },
      { "type": "file", "mediaType": "image/png", "attachmentId": "att_3f2a…" }
    ],
    "metadata": { "references": [], "voice_inputs": [] }
  }
}
```

- `threadId` is a new id the client picks, or one of the caller's threads. Without it the turn has
  no history and nothing is stored.
- `parentMessageId` is required: the id of the stored message the new one follows, or `null` for a
  thread's first message. An assistant message's id is the one its stream announced in
  `data-message-id`, and `GET /api/chat/threads/{id}` lists them, a page at a time.
- `message` is a user message of `text`, `file` and `data-reference` parts. Anything else,
  including the old `messages` history, is refused with `validation_error` (422).
- `options`, with either kind of request, are the turn's run options, checked against
  `ChatConfig(run_options=...)` (see [Choosing the Model per Message](#choosing-the-model-per-message)).
  An app without that schema refuses any.
- `external_user_id`, from a service account only, names the end user it speaks for in the admin
  panel.

Instead of `message`, a request can answer the tool calls the thread's last answer waits on (see
[Tools That Ask First](#tools-that-ask-first) and [Tools the Browser Answers](#tools-the-browser-answers)):
`parentMessageId` is that answer's id, `approvals` holds one `{ "id", "approved", "reason"? }` for
each call waiting for approval, by its part's `approval.id`, and `toolOutputs` one
`{ "id", "output" }` for each client tool call, by its part's `toolCallId`. Between them they answer
every waiting call. The stream continues that answer, so it starts without a `data-message-id`, and the
stored answer is rewritten with the calls' outcomes and what followed. An approval for an answer
that isn't the thread's last, or for a call that doesn't wait (another window answered it), is
`thread_changed` (409); leaving a waiting call unanswered, or an output its tool doesn't return, is
`validation_error` (422).

```json
{
  "threadId": "3f2a9c",
  "parentMessageId": "msg_asst_3f2a9c_1767225600000",
  "approvals": [{ "id": "call_8kq", "approved": false, "reason": "Keep that file" }]
}
```

Sending a stored message's id again after the same parent retries it: the replies that followed it
are deleted and the model answers again. A user message stored with no reply after the parent gives
way to the new one too. Anything else would delete replies the caller didn't know about, as when a
second window fell behind, so it's refused with `thread_changed` (409). A parent the thread doesn't
hold is `message_not_found` (404).

What the model sees of the history is the context policy's choice. The default, `token_budget()`,
keeps the most recent whole turns within 100,000 tokens, estimated as characters divided by four,
with each file counted as 1,000; a tool call always stays with its result. A stored file is read
back from storage only if its turn is kept. Pass your own budget, your own policy, or `None` to send
everything:

```python
from pydantic_ai import Agent
from pydantic_ai.messages import ModelMessage, ModelRequest, UserPromptPart

from gentiq import AgentDeps, ChatConfig, GentiqApp, token_budget

agent = Agent("openai:gpt-5.1", deps_type=AgentDeps[None])

# A smaller model: keep 30,000 estimated tokens of history.
app = GentiqApp(agent, chat=ChatConfig(context_policy=token_budget(30_000)))


# Or choose for yourself. A policy gets the history before the new message, oldest first, and may
# be a coroutine function, to summarise older turns with a model for instance.
def last_five_turns(history: list[ModelMessage]) -> list[ModelMessage]:
    # A turn starts at a request carrying the user's prompt. Cutting anywhere else could separate
    # a tool call from its result, which providers refuse.
    starts = [
        index
        for index, message in enumerate(history)
        if isinstance(message, ModelRequest) and any(isinstance(part, UserPromptPart) for part in message.parts)
    ]
    return history[starts[-5] :] if len(starts) > 5 else history


app = GentiqApp(agent, chat=ChatConfig(context_policy=last_five_turns))
```

### Turns That Outlive the Connection

A turn in a thread runs on the server to its end whether or not anyone reads it. A reload, a closed
tab or a dropped connection loses nothing: the answer is stored when the turn ends, and its stream
can be read again while it runs.

- The stream opens with a transient `data-turn` part, `{ "turn_id": "turn_…" }`, and ends with
  `data-chat-finished` and then `[DONE]`.
- `GET /api/chat/threads/{thread_id}/turns/{turn_id}/stream?after=N` sends the turn's stream from
  its event `N` on (the number of events read so far, `0` for all of it) and follows it until it
  ends. Only the thread's owner can read it; anyone else gets a 404.
- On the last page of `GET /api/chat/threads/{id}`, `turn` is the thread's last turn while it runs
  (`status: "running"`, read it from its stream) or when it failed (`status: "failed"`, with the
  error's code in `error`); otherwise it's `null`. The React SDK does both for you: a reloaded
  thread picks its running turn up, and a stream that drops reads on from where it broke off.

**Stopping.** Closing the connection doesn't stop a turn. `POST /api/chat/threads/{thread_id}/stop`
does, on whichever worker runs it: the model's run ends where it is, what it wrote so far is stored
as the answer and charged, and the stream ends as a finished one does. A new message in a thread
stops the turn running there too, and waits until its answer is stored, so the message can follow
that answer. A turn sent without a `threadId` has nothing to read again, so closing its connection
still stops it.

**Restarts.** Shutting down stops every running turn the same way and marks it failed with
`turn_interrupted`, which the stream ends with as an error part. A process that dies without
shutting down stops vouching for its turns; 20 seconds later the next reader marks them failed the
same way.

**Several workers.** Each turn's events are written to the database as they're produced (the
`turns` and `turn_events` collections), a fifth of a second at a time, and kept for a day. A
reader on the worker running the turn gets them as they come; a reader on another worker polls the
store twice a second, so it lags by up to about half a second. A stop asked through another worker
reaches the turn's worker within 5 seconds. Nothing needs sticky sessions.

### Stored Messages

A thread's messages are stored in one versioned schema, `gentiq.stores.message_schema`: each part
has the shape of a Vercel AI SDK UI message part, spelled in camelCase, the same as the chat stream
sends. `GET /api/chat/threads/{id}` returns those parts, so a reloaded thread matches what was
streamed. It returns a thread's last `limit` messages (50 unless given, at most 200), oldest
first, with `next_cursor`; pass that as `before` for the page before, until it's `null`. Messages written since 0.19 carry `schema_version: 2`.

Older messages aren't rewritten in storage, since a deployment can hold hundreds of thousands of
threads. `upgrade_thread_item` brings each one up to date as it's read, and a bulk backfill waits
until it's been tested on production data. A part that still doesn't fit the schema after upgrading
is left out of the response and logged with its message's id.

### Extending the API

`GentiqApp.api` is a standard FastAPI instance, so you can add your own routes, middleware and exception handlers, and protect them with Gentiq's authentication dependencies.

```python
from typing import Annotated

from fastapi import APIRouter, Depends
from gentiq import AgentDeps, GentiqApp, User, get_current_user
from pydantic_ai import Agent

agent = Agent("openai:gpt-5.1", deps_type=AgentDeps[None])
app = GentiqApp(agent)
router = APIRouter()


@router.get("/profile")
async def get_profile(user: Annotated[User, Depends(get_current_user)]):
    return {"name": user.name, "email": user.email}


app.add_router(router, prefix="/v1")
```

Other dependencies worth knowing: `get_current_admin` and `Depends(require_permission(...))` for
admin-only routes, and, for routes that take a thread id, `OwnedThreadId` (a `{thread_id}` path
parameter, checked to exist and belong to the caller) and `WritableThreadId` (the `X-Thread-Id`
header, checked to be absent, new, or owned by the caller). `Depends(verify_api_key)` admits only
callers presenting `BACKEND_API_KEY` as `x-api-key`, and answers anyone else with 401.

Gentiq's routes declare their response models, so FastAPI's schema at `/openapi.json` (browsable
at `/docs`) describes what each one returns. Give your own routes a return type too.

Adding a `CORSMiddleware` through `app.add_middleware(...)` **replaces** the one Gentiq installed from
`cors=...` rather than stacking a second one, which would send duplicate headers.
`app.api.add_middleware(...)` adds it without that check.

---

## License

Gentiq is licensed under the [Apache 2.0 License](../../LICENSE).
