Turns a new SEBI circular into a cited, clause-level compliance finding and a human-approved GitHub issue, end to end on Azure.
4-minute demo: a live SEBI scan through obligation extraction, Azure AI Search retrieval and policy impact analysis to a human-approved GitHub issue.
AfterCircular reads new circulars from the Securities and Exchange Board of India (SEBI), extracts the obligations each one imposes, checks them clause by clause against a company's own policy repository, and drafts a compliance memo when it finds a conflict. The only side effect, a GitHub issue in the policy repository, happens after a person approves it.
Built for the AI-103 course (Develop AI Apps and Agents on Azure, Chitkara University). Deployed and verified on
Azure Container Apps in September 2026; DEPLOYMENT.md rebuilds it from an empty subscription.
Compliance teams at brokers and asset managers read every SEBI circular, decide whether it applies to them, and compare it against their internal policies by hand. Most circulars don't apply, and the ones that do bury the change in long PDFs. A chatbot over one PDF doesn't help: it can't watch the regulator, compare against the company's own policies, or act safely.
- Reads the live regulator. Fetches the official
www.sebi.gov.inlisting, circular pages and PDFs. A content hash per tenant means a circular is processed once; a repeated scan makes zero model calls. - Triages before spending. A typed classifier (Jev, TypeSafe System One) archives circulars not addressed to the company's kind of entity, with no generative call.
- Turns PDFs into typed obligations.
gpt-5-miniextracts obligations as strict JSON Schema, each with a verbatim excerpt; Jev then checks every obligation against its excerpt and drops unsupported ones. - Retrieves policy evidence (RAG). Hybrid vector + keyword search (Azure AI Search, RRF) over the tenant's policy
repository, filtered by
tenant_id, then a Jev rerank. - Decides with code, not prose. Jev judges alignment (satisfies / conflicts / not addressed). A deterministic Impact Gate applies thresholds to the calibrated probabilities; uncertain cases escalate to the reasoning model, then to a person.
- Requires two-sided evidence. A
CONFLICTneeds a verbatim regulatory excerpt and a retrieved policy chunk; it then gets a drafted memo and a review inAWAITING_REVIEW. - Keeps a person in charge. Approve → one GitHub issue in the policy repository → audit event. The agent never edits or merges a policy.
- Answers questions from its own records. Ask answers from the workspace's stored decisions with citations. It refuses actions: "approve it and open the issue" is declined.
Code owns control flow, hashing, thresholds, routing, approval and audit. Each model does one kind of job, and the stages form an explicit escalation cascade: typed classifier → generative model → reasoning model → person.
Browser ──HTTPS──► Web (Next.js 16, Auth.js GitHub sign-in) external ingress
│ server-side proxy: backend key + tenant headers + the user's GitHub token
▼
API (FastAPI) internal ingress, one replica
├── SQLite on an Azure Files share (/data) scans, documents, analyses, decisions, reviews, audit, telemetry
├── Microsoft Foundry (managed identity) gpt-5-mini · text-embedding-3-small
├── Azure AI Search (managed identity) policies-dev, tenant-filtered hybrid retrieval
├── Jev / TypeSafe System One typed judgments with calibrated probabilities
├── GitHub read the policy repository; open an issue after approval
└── SEBI relay (Azure Container Instance) www.sebi.gov.in drops TLS from Azure Korea Central
Application Insights + Log Analytics dependencies, traces, container logs
One scan, per circular:
SEBI (live) → fetch listing, circular pages and PDFs → content-hash detection and versioning (per tenant)
→ Jev triage: is this circular addressed to this kind of company? not applicable → archived, no model call
→ Foundry: extract obligations, each with verbatim evidence → Jev checks every obligation is supported
→ embeddings + Azure AI Search hybrid retrieval over the policy repository
→ Jev rerank and alignment (satisfies / conflicts / not addressed), citation check
→ deterministic Impact Gate on calibrated probabilities; uncertain → Foundry reasoning → still uncertain → a person
→ CONFLICT with two-sided evidence → Foundry drafts a memo → review AWAITING_REVIEW
→ a person approves → GitHub issue in the policy repository → audit event
State. Every circular moves through one state machine (DISCOVERED → … → COMPLETED, or NEEDS_INVESTIGATION until a
person acts). Each transition is an audit row. A scan interrupted by a restart is marked failed at start-up and its
unfinished documents are retried by the next scan.
Tracing. Every model judgment is a decision record (provider, model version, state digest, evidence ids,
probabilities, thresholds, routing). Every Foundry call records latency, input/output/cached tokens, attempts and an
estimated cost. The dashboard shows a per-document trace of which stage ran, why, and what it cost. Two full traces are in
docs/traces/.
Design and thresholds: docs/architecture.md · docs/ProductionArchitecture.md
| Layer | Used |
|---|---|
| Backend | Python 3.12, FastAPI, Pydantic, SQLite, uv |
| Models | Microsoft Foundry gpt-5-mini (Responses API, JSON Schema output), text-embedding-3-small; Jev (TypeSafe System One) for typed judgments |
| Retrieval | Azure AI Search: HNSW vector + BM25 keyword fused by RRF, one index partitioned by tenant_id; a local hybrid index for development |
| Context format | TOON for model context (measured below) |
| Frontend | Next.js 16, React 19, Tailwind v4, Auth.js v5 (GitHub OAuth), Vitest |
| Cloud | Azure Container Apps, Container Registry, Azure Files, Container Instances (SEBI relay), managed identities + RBAC, Application Insights + Log Analytics |
| CI | GitHub Actions: tests, type checks, lint, next build, both Docker images, API liveness probe; image publishing via GitHub OIDC (no stored Azure secret) |
Offline suite (no network). It uses a stub provider and a vendored copy of the Acme policy corpus; it never calls Azure, SEBI, Jev or GitHub. CI runs it on every push.
cd backend && uv run pytest -q && uv run mypy app scripts evals # 171 passed, 2 skipped (run 2026-11-21) cd backend && uv run pytest -q ../infra/sebi-proxy # relay's CONNECT-only contract cd web && npx tsc --noEmit && npm run lint && npm test # 15 Vitest tests
The suite covers failure paths explicitly: a model, search or judge outage fails visibly or goes to a person instead of guessing; fabricated evidence can never become a conflict; production refuses to start with missing configuration.
Recorded evaluations (committed in backend/evals/results/, run against the live Azure
resources in September 2026):
| Evaluation | Result | Conditions |
|---|---|---|
| Retrieval quality | Expected policy in top-5 for 8/8 queries | Azure AI Search hybrid, 2 tenants (48 + 46 chunks), retrieval_eval.md |
| Tenant isolation | 0 foreign rows on cross-tenant bait queries | Same index, tenant_id filter, retrieval_eval.md |
| End-to-end, Acme (stock broker) | 6/7 expected outcomes; 6 Foundry calls; $0.0519 list-price estimate; 242.9 s scan | 6 live SEBI circulars, gpt-5-mini, live_e2e_acme-securities-pvt-ltd.md |
| End-to-end, Nimbus (asset manager) | 5/7 expected outcomes; $0.0558 list-price estimate | Same 6 circulars, live_e2e_nimbus-asset-management.md |
| Idempotency | Repeated scan: 0 new documents, 0 model calls | live_e2e_acme-securities-pvt-ltd.md |
Cases the cascade is unsure about go to a person (NEEDS_INVESTIGATION) rather than to a guessed verdict.
Token benchmark (offline, reproducible). uv run python -m evals.toon_benchmark counts tokens with tiktoken
o200k_base on fixed payloads. On the full impact-analysis context (10 obligations + 8 chunks), TOON uses 752 tokens vs
865 for compact JSON (13.1% fewer), with lossless round-trip.
Model evaluations (these call models): uv run python -m evals.judges compares the judgment layer (Jev vs Foundry) on
golden scenarios; uv run python -m evals.run benchmarks the generative deployments. Results appear in the dashboard's
Models view.
- Per scan: at most
AFTERCIRCULAR_MAX_LLM_CALLS_PER_SCANgenerative calls (code default 10) and an estimated $0.50. Per day, application-wide: $5. Checked before every call; a scan that hits a limit stops with aBUDGET_EXCEEDEDaudit event. - Triage first: non-applicable circulars cost no generative call.
- Index reuse: policy chunks are re-embedded only when the repository commit changes.
- Fail closed: in production the API refuses to start without Foundry, Azure AI Search,
SEBI_MODE=live, a Jev key, a real backend key, explicit CORS and a mounted database path. No silent fallback to fixtures or a local index.
- No Azure keys in the apps: Foundry, Search and ACR use managed identities with resource-scoped roles.
- The API has no public ingress; the web app calls it server-side with a backend key. CORS allows only the web origin; interactive API docs are off in production.
- Tenants are isolated in the database, the search index (
tenant_idfilter) and the audit log. - Regulatory documents are untrusted input: extracted from, never executed as instructions.
- The SEBI relay tunnels only
CONNECT www.sebi.gov.in:443, password-protected; the API verifies SEBI's certificate end to end, so the relay never sees plaintext.
Without any cloud account (stub provider, as CI does):
cd backend uv sync uv run pytest -q ENVIRONMENT=dev AI_PROVIDER=stub BACKEND_API_KEY=local uv run uvicorn app.main:app --port 8010 curl localhost:8010/health/ready # {"ok":true,"problems":[],"environment":"dev"}
With real models you need an Azure subscription with a Foundry resource (gpt-5-mini, text-embedding-3-small) and
an Azure AI Search service, a TypeSafe API key for Jev, a GitHub OAuth App, and a policy repository with an
aftercircular.yml manifest (fork a demo tenant below). Foundry and Search authenticate through az login.
# backend cd backend && cp .env.example .env # fill in the variables documented in .env.example uv run uvicorn app.main:app --port 8010 --reload # frontend cd web && npm install && cp .env.example .env.local npm run dev # http://localhost:3000
Sign in with GitHub → Connect (company name + policy repository) → Scan now. In the recorded run, a scan of six circulars took about four minutes.
Containers: AC_UID=$(id -u) AC_GID=$(id -g) docker compose up --build (web :3000, API :8010). Azure deployment:
DEPLOYMENT.md and scripts/azure-{build,deploy,smoke-test}.sh.
Demo tenants (fictional companies): acme-securities-policies
(a stock broker) and nimbus-amc-policies (an asset manager). The
same circulars produce different results for each: 102584 (unpaid securities) conflicts with Acme's POL-001 (seven
trading days vs SEBI's five), while 102986 conflicts with Nimbus's POL-002. Demo script:
docs/DEMO_RUNBOOK.md.
backend/
app/connectors/ SEBI connector (live listing → detail page → PDF text)
app/decisions/ Jev questions, routing thresholds, triage and impact decisions
app/agents/ Foundry tasks: obligation extraction, impact analysis, memo
app/retrieval/ Azure AI Search, plus a local hybrid index for development
app/services/ scan pipeline, Impact Gate, reviews → GitHub, Ask, traces, audit, state
evals/ retrieval, end-to-end, judge, Ask and token evaluations, with results
tests/ pytest suite (stub provider, fixture policy corpus)
web/ Next.js dashboard
infra/sebi-proxy/ SEBI relay (stdlib CONNECT tunnel) and its tests
scripts/ Azure build, deploy and smoke-test scripts
docs/ architecture, traces, runbooks, SEBI connector, index schema
- SQLite on Azure Files. Keeps the deployment to one API replica and zero managed databases. All persistence goes through one state store, so moving to PostgreSQL for scale-out is a contained change.
- On-demand scans. Scans start from the dashboard so every run has an owner. Unattended monitoring is built in behind
a flag (
AFTERCIRCULAR_ENABLE_SCHEDULED_SCAN,POST /api/scheduled-scan) for a timer such as a Container Apps Job. - SEBI relay. SEBI traffic from Azure Korea Central goes through a CONNECT-only relay; TLS stays end to end between the API and SEBI.
- Roadmap: pull requests with proposed policy edits, email and Telegram notifications, and larger golden evaluation
sets (
PRD.md).
| Document | Contents |
|---|---|
DEPLOYMENT.md |
Azure deployment runbook, problems hit and fixes |
docs/architecture.md |
decision architecture, cascade, thresholds |
docs/ProductionArchitecture.md |
production design |
docs/traces/ |
two full per-document pipeline traces |
docs/sebi-connector.md |
how the live SEBI source is read |
docs/azure-setup-runbook.md |
first-time Azure setup |
docs/DEMO_RUNBOOK.md |
demo script |
docs/AI103_MAPPING.md |
mapping to the AI-103 course |
PRD.md |
product requirements |
Course project for AI-103 (Chitkara University).