Skip to content

About

No description, website, or topics provided.

Resources

Stars

0 stars

Watchers

0 watching

Forks

Latest commit

 

History

1 Commit

Folders and files

Repository files navigation

Janmitra Backend

The Python side of Janmitra. A citizen photographs a civic problem; an autonomous agent classifies it, finds the responsible municipal department, drafts a formal complaint, files it, and tracks it to resolution. This service is what the Android app talks to, plus the agent that does the work behind it.

Run it

python3 -m venv .venv && .venv/bin/pip install -r requirements.txt
.venv/bin/uvicorn app.main:app --reload --host 0.0.0.0 --port 8000
.venv/bin/python -m pytest -q          # 29 tests

--host 0.0.0.0 matters: a phone on the same Wi-Fi reaches the API at your machine's LAN IP, never localhost.

Interactive docs at /docs, health at /healthz.

The contract is fixed

The Android app is already written against these three endpoints, so the shapes here are not ours to change — janmitra-app/src/api/client.ts and types.ts are the specification, and tests/test_contract.py is that specification executed.

POST /api/complaints 202 → {"complaintId", "status": "processing"}
GET /api/complaints/{id} the bare Complaint object
GET /api/complaints?userId= {"complaints": [...summaries]} — enveloped

Four constraints are load-bearing and easy to break by accident:

  1. camelCase on the wire. Python is snake_case internally; models serialise through to_camel.
  2. Exactly five agent steps, keyed perceive, classify, route, draft, file, in that order. The Processing screen indexes them positionally and stops polling at length five — four steps means it polls forever, six means it advances before the complaint is filed.
  3. Steps persist one at a time. The screen is a live view of a mutating record. Writing all five at the end shows an empty list and then a full one.
  4. The record must be durable before POST returns. The app replaces Capture with Processing and polls immediately, with only one retry configured. A 404 on that first poll is a permanent spinner.

Layout

app/
  main.py                    application assembly only — CORS, router mount, /healthz
  core/                      cross-cutting concerns, zero internal dependencies
    config.py                  every adapter chosen by name, from JANMITRA_* env vars
    errors.py                  domain errors — no HTTP knowledge, no status codes
    ids.py                     opaque complaint ids
    logging.py                 one formatter, one `janmitra.*` logger namespace
    time.py                    now_iso() — the app parses timestamps with new Date()
  models/                    the domain vocabulary, mirroring src/types.ts
    base.py                    CamelModel — the camelCase wire contract
    enums.py                   IssueCategory, Severity, Status, AgentStepKind
    complaint.py               Complaint, AgentStep, StatusEvent, ComplaintSummary
  schemas/                   HTTP bodies that are not the domain record
    complaints.py              SubmitComplaintRequest/Response, ComplaintListResponse
    errors.py                  the error envelope every non-2xx response uses
  api/                       the HTTP boundary — the only public surface
    deps.py                    the one place an adapter name becomes an object
    error_handlers.py          the only place that knows a NotFound is a 404
    router.py                  aggregates route modules for main.py to mount
    routes/complaints.py       the three endpoints the app calls
  services/                  backing services: one package per kind
    store/
      base.py                  ComplaintStore — the interface
      memory.py                in-process implementation (the default)
tests/                       mirrors app/
  conftest.py                store reset, client and submission fixtures
  api/test_complaints.py     the wire, asserted key by key
  api/test_error_handling.py the envelope, and that nothing leaks through it
  services/test_memory_store.py   the three mutators the agent writes through

Dependencies point one way. core imports nothing internal; models imports core; schemas imports models; services imports core and models; api imports everything below it; main imports api. Nothing points back up, so there are no cycles by construction.

api/ never imports a concrete implementation — it imports api/deps.py and type-annotates against the interfaces in services/. That single seam is how the mandated Google services arrive later without the endpoints or the agent changing.

Each service kind is a package with base.py for the interface and one module per implementation, so the milestones ahead slot in predictably:

Milestone Package Modules
now services/store/ base.py, memory.py, later firestore.py
2 — photos services/storage/ base.py, local.py, later gcs.py
3 — dispatch services/bus/ base.py, inprocess.py, later pubsub.py
6 — Gemini services/classifier/ base.py, stub.py, later gemini.py

The agent itself gets its own app/agent/ package: it consumes these services rather than being one of them.

Two conventions worth knowing. models/ and schemas/ re-export a flat facade (from app.models import Complaint) because they are a shared vocabulary used everywhere. services/ deliberately does not — an import there should name the implementation it chose (from app.services.store.memory import ...). And there is no api/v1/: the app calls /api/complaints, so a version folder would imply a URL that does not exist.

Errors

Every non-2xx response has one shape:

{"error": {"code": "complaint_not_found",
           "message": "No complaint with id 'c_x'.",
           "details": {"complaintId": "c_x"}}}

code is stable and safe to branch on; message is developer-facing; details is omitted when there is nothing to add. Four handlers cover every exit from the application — deliberate domain errors, Starlette's own (unknown route, bad method), request validation, and a catch-all.

The split matters: core/errors.py says what went wrong and carries no status codes, while api/error_handlers.py decides what that means over HTTP. So the agent worker — which has no request to respond to — raises exactly the same errors.

Two rules the tests enforce:

  1. Nothing internal leaks. An unhandled exception is logged with its traceback and answered with a generic 500. A message naming a bucket or a prompt never reaches the caller.
  2. The rejected payload is never echoed. Pydantic's errors() embeds the offending input, and for a missing field that input is the whole request body — so a missing userId would mirror the entire multi-megabyte base64 photo back to the phone and into the logs. Only loc, msg and type survive.

Note who this is for: the Android app never reads these bodies. It sees a non-2xx, axios throws, React Query surfaces an error. The envelope is for whoever is debugging — which is why the app still needs its own error states (milestone 5).

Milestones

  • 1 — API skeleton. The three endpoints against an in-memory store, returning the exact contract shape. No agent.
  • 2 — Photo storage. Decode the base64 data URL, persist the bytes, serve a real photoUrl. (The base64 is 1.5–4 MB — it cannot live in a Firestore document, whose limit is 1 MiB.)
  • 3 — The agent loop. Five steps, deterministic classifier, written incrementally, dispatched off the request path.
  • 4 — Simulated grievance system. Mints ticketId, then walks the status Filed → Acknowledged → Assigned → Resolved.
  • 5 — Point the app at it. USE_MOCK = false, and an error state on the Processing and Detail screens, which currently spin forever on failure.
  • 6 — Real Gemini. Vision classification and complaint drafting behind the interface built in milestone 3.
  • 7 — Google Cloud. Firestore, GCS, Pub/Sub, Cloud Run — as adapters.

About

No description, website, or topics provided.

Resources

Stars

0 stars

Watchers

0 watching

Forks

Releases

Packages

Contributors

Languages