Imported from h3man1h/GovAssist (
docs/AGENTS.md). Install upstream withnpx skills add h3man1h/GovAssist --skill docs. Copyright stays with the author.
GovAssist — Multi-Agent Architecture & Specification
This document details the responsibilities, inputs, processing logic, outputs, tools, LLM interactions, communication protocols, and failure handling mechanisms for all 8 agents implemented in GovAssist.
1. Agent Architecture Summary
┌────────────────────────┐
│ Orchestrator Agent │
│ (State Machine & Gate) │
└───────────┬────────────┘
│ Typed AgentMessage[T]
┌──────────────┬──────────────┬───────┴──────┬──────────────┬──────────────┐
▼ ▼ ▼ ▼ ▼ ▼
┌──────────────┐┌──────────────┐┌──────────────┐┌──────────────┐┌──────────────┐┌──────────────┐
│Profile Agent ││Discovery Agt ││Eligibility Ag││Document Agent││Application Ag││Verificat. Ag │
│(LLM + Regex) ││(Catalog Tool)││(Determ. Rule)││ (OCR Engine) ││(Portal Client││(Audit Engine)│
└──────────────┘└──────────────┘└──────────────┘└──────────────┘└──────────────┘└──────────────┘
│ Passes Audit
▼
[Human Approval Gate]
│ AUTH-TOKEN
▼
┌──────────────┐
│Execution Agt │
│(Portal Client│
└──────────────┘
| # | Agent Name | Class Name | Primary Tool / Engine | LLM Role | Security / Governance Role |
|---|---|---|---|---|---|
| 1 | Orchestrator Agent | OrchestratorAgent |
State machine transition validator | None (deterministic routing) | Strict stage gate; human confirmation token generator |
| 2 | Profile Agent | ProfileAgent |
Heuristic entity parser | Ollama (gemma4:e2b) structured extraction |
Sanitizes input; generates safe demo placeholders |
| 3 | Scheme Discovery Agent | SchemeDiscoveryAgent |
SchemeCatalogTool.search() |
Optional query refinement fallback | Prevents hallucinated schemes; queries DB catalog |
| 4 | Eligibility Agent | EligibilityAgent |
EligibilityEngine.evaluate() |
None (zero LLM evaluation) | Deterministic criteria evaluation source of truth |
| 5 | Document Agent | DocumentAgent |
OCREngine.analyze_document() |
None | Strict non-authenticity constraint (VERIFIED_INFO) |
| 6 | Application Agent | ApplicationAgent |
PortalAutomationClient |
None | Automates multi-step form drafting (Steps 1–5) |
| 7 | Verification Agent | VerificationAgent |
PortalAutomationClient.get_session_state() |
None | Pre-submission compliance audit; blocks discrepancies |
| 8 | Execution Agent | ExecutionAgent |
PortalAutomationClient.submit_application() |
None | Rejects submission without valid user authorization |
2. Agent Specifications
2.1 Orchestrator Agent (OrchestratorAgent)
- Module:
backend/app/agents/orchestrator.py - Purpose: Acts as the central workflow manager. It maintains session state, enforces valid workflow transitions, sequences agent execution, generates cryptographic human confirmation tokens, and coordinates agent-to-agent communication via typed
AgentMessageenvelopes. - Workflow State Sequence:
INTAKE ➔ DISCOVERY ➔ ELIGIBILITY ➔ DOCUMENTS ➔ DRAFTING ➔ AUDIT_PENDING ➔ HUMAN_CONFIRMATION ➔ EXECUTION ➔ COMPLETE - Input: Citizen HTTP requests, session IDs, scheme IDs, files, confirmation tokens.
- Processing:
- Inspects current
SessionModel.current_stage. - Validates whether the requested action is permitted under
VALID_TRANSITIONS. - Constructs strongly typed
AgentMessage[T]envelopes and dispatches them to specialized agents. - Persists state updates to SQLite and records millisecond telemetry.
- If
VerificationAgentpasses audit, transitions state toHUMAN_CONFIRMATIONand generatesAUTH-TOKEN-XXXXXXXXXXXX. - Rejects any attempt to execute final submission unless state is
HUMAN_CONFIRMATIONand the token is valid.
- Inspects current
- Output: Structured workflow dictionaries returned to API gateway.
- Tools: Internal state machine transition validator (
VALID_TRANSITIONS). - LLM Usage: None. The Orchestrator is entirely deterministic to ensure predictable workflow enforcement.
- Failure Handling: Raises
InvalidWorkflowTransitionError(HTTP 400),UnauthorizedSubmissionError(HTTP 403), or updates stage toFAILED.
2.2 Profile Agent (ProfileAgent)
- Module:
backend/app/agents/profile_agent.py - Purpose: Ingests unstructured conversational text from citizens, extracts demographic, educational, and financial attributes into a structured
CitizenProfile, and identifies missing parameters. - Input:
AgentMessage[ProfileExtractionRequest]containinguser_textand optional existingCitizenProfile. - Processing:
- Executes regex heuristic extraction for state names, degrees (B.Tech, Degree, ITI), and income figures (e.g. "1.8 Lakhs", "180000").
- If an active LLM provider (Ollama) is available, invokes
llm_provider.generate_structured(prompt, schema_cls=CitizenProfile)with system prompt instructions. - Validates and merges LLM-extracted fields with heuristic values.
- Assigns safe demo placeholders (
DEMO-ID-0000,DEMO-BANK-0000) to guarantee no real sensitive numbers are collected. - Computes completeness score and identifies missing parameters.
- Output:
AgentMessage[ProfileExtractionResponse]containing mergedCitizenProfile,completeness_score,missing_fields, and optionalfollow_up_question. - Tools: Deterministic regex heuristic extractor,
CitizenProfilePydantic validator. - LLM Usage: Invokes local Ollama (
gemma4:e2b) for contextual entity understanding with fallback to deterministic heuristics when Ollama is unreachable. - Failure Handling: Gracefully falls back to heuristic regex extraction if LLM inference times out or fails.
2.3 Scheme Discovery Agent (SchemeDiscoveryAgent)
- Module:
backend/app/agents/discovery_agent.py - Purpose: Discovers matching welfare and scholarship programs from the local scheme catalog based on the citizen's profile.
- Input:
AgentMessage[SchemeDiscoveryQuery]containingCitizenProfile. - Processing:
- Invokes
SchemeCatalogTool.search(db, profile). - Queries
SchemeModelrecords filtered by state (citizen's state +ALL_INDIA). - Evaluates income ceiling compatibility against scheme specifications.
- Assigns match scores (0.0 to 1.0) and generates concise human-readable match rationales (e.g. "Direct match for Andhra Pradesh residents; Income ₹180,000 qualifies under ₹250,000 ceiling").
- Invokes
- Output:
AgentMessage[SchemeDiscoveryResponse]containing a ranked list ofDiscoveredSchemeMatchitems. - Tools:
SchemeCatalogTool.search(), database catalog queries. - LLM Usage: None during standard search; deterministic catalog queries ensure that only genuine seeded schemes are returned.
- Failure Handling: If no schemes match, returns an empty matches list with advice to adjust income or domicile parameters.
2.4 Eligibility Agent (EligibilityAgent)
- Module:
backend/app/agents/eligibility_agent.py - Purpose: Verifies whether the citizen satisfies official scheme criteria. Crucially, eligibility is evaluated deterministically by the
EligibilityEnginerather than delegating decisions to the LLM. - Input:
AgentMessage[EligibilityCheckRequest]containingCitizenProfileandscheme_id. - Processing:
- Loads official scheme rule specification from
SchemeModel.eligibility_rules. - Executes
EligibilityEngine.evaluate(profile, scheme). - Itemizes criteria evaluations:
- Income ceiling check (
annual_family_income <= max_family_income) - Domicile state check (
state in eligible_states) - Educational level & course check (
course in eligible_courses) - Merit score threshold check (if applicable)
- Income ceiling check (
- Determines
overall_eligible(Trueif and only if all mandatory criteria pass). - Determines list of required supporting documents from scheme registry.
- Loads official scheme rule specification from
- Output:
AgentMessage[EligibilityReport]containing itemizedCriterionVerdictobjects,overall_eligibleboolean, andrequired_documents. - Tools:
EligibilityEngine.evaluate(),SchemeCatalogTool.get_by_id(). - LLM Usage: Zero LLM usage. The engine is the sole source of truth to guarantee 100% deterministic, audit-compliant outcomes.
- Failure Handling: Raises
ValueErrorif scheme ID is invalid; records audit log withERRORstatus.
2.5 Document Agent (DocumentAgent)
- Module:
backend/app/agents/document_agent.py - Purpose: Validates uploaded supporting certificates for file readability, extracts key figures (such as annual family income), and cross-checks figures against the citizen's profile.
- Strict Non-Authenticity Standard:
The agent never claims that a document is legally or officially authentic. Allowed statuses are strictly:
VERIFIED_INFORMATION(document is legible, required fields extracted, and matches profile)NEEDS_REVIEW(discrepancy detected or fields require manual check)MISSING(required certificate omitted)UNREADABLE(corrupted, unparseable, or blank file)
- Input:
AgentMessage[DocumentAnalysisRequest]containingdocument_id,document_type, andfile_path. - Processing:
- Ingests file from local storage (
backend/app/uploads/). - Dispatches
OCREngine.analyze_document(document_id, document_type, file_path, profile). - Reads text content, verifies header tokens (e.g. "INCOME CERTIFICATE", "GOVERNMENT OF ANDHRA PRADESH", "TAHSILDAR").
- Extracts numeric values (e.g.
180000.0), certificate numbers, and applicant names. - Cross-checks extracted income against
profile.annual_family_income. - Sets verification status to
VERIFIED_INFORMATIONif values match, or records discrepancies inmismatches_against_profile.
- Ingests file from local storage (
- Output:
AgentMessage[DocumentValidationReport]containing verification status, readability score, and extracted fields dictionary. - Tools:
OCREngine.analyze_document(). - LLM Usage: None. Regex and text token classification provide predictable parsing without hallucinations.
- Failure Handling: Returns
UNREADABLEstatus if file cannot be read or parsed.
2.6 Application Agent (ApplicationAgent)
- Module:
backend/app/agents/application_agent.py - Purpose: Automatically drafts the citizen's application on the standalone demonstration government portal (
http://127.0.0.1:8001) by mapping verified profile attributes and certificates to portal fields. - Input:
AgentMessage[PortalDraftRequest]containingCitizenProfile,scheme_id, and list of verified documents. - Processing:
- Calls
PortalAutomationClient.create_session(scheme_id)on the mock portal. - Populates Step 1 (Applicant Data): full name, DOB, gender, state, demo ID.
- Populates Step 2 (Academic Data): institution name, course, current year, roll number.
- Populates Step 3 (Financial Data): annual family income, category, demo bank token.
- Populates Step 4 (Documents Attachment): uploads verified certificate files to the portal session.
- Verifies draft readiness for pre-submission audit.
- Calls
- Output:
AgentMessage[PortalDraftResult]containingportal_session_id(PORTAL-XXXXXXXX),current_step, and draft data dictionary. - Tools:
PortalAutomationClient(asynchronous HTTP client). - LLM Usage: None. Field mapping is deterministic to eliminate form-filling hallucinations.
- Failure Handling: Catches HTTP communication errors with the portal and raises detailed diagnostic exceptions.
2.7 Verification Agent (VerificationAgent)
- Module:
backend/app/agents/verification_agent.py - Purpose: Executes an independent, automated pre-submission compliance audit on the drafted portal application prior to presenting it to the citizen.
- Input:
AgentMessage[AuditVerificationRequest]containingportal_session_id,CitizenProfile, and document validation reports. - Processing:
- Queries the mock portal state via
PortalAutomationClient.get_session_state(portal_session_id). - Cross-checks portal applicant name against citizen profile name.
- Cross-checks portal domicile state against scheme requirements.
- Cross-checks portal course against eligibility criteria.
- Cross-checks portal annual family income against both profile income and document OCR extraction.
- If any discrepancy exists (e.g. portal income ₹180,000 conflicts with certificate income ₹350,000), flags a blocking issue and sets
is_ready_for_human_review = False. - If all fields match, computes compliance score (1.0) and sets
is_ready_for_human_review = True.
- Queries the mock portal state via
- Output:
AgentMessage[VerificationAuditReport]containingis_ready_for_human_review,field_auditsarray,blocking_issueslist, andcompliance_score. - Tools:
PortalAutomationClient.get_session_state(). - LLM Usage: None. Pure deterministic comparison of drafted portal fields against verified sources.
- Failure Handling: Automatically populates
blocking_issuesand prevents the workflow from unlocking human confirmation.
2.8 Execution Agent (ExecutionAgent)
- Module:
backend/app/agents/execution_agent.py - Purpose: Executes the final, irreversible application submission on the mock government portal strictly upon receiving explicit user authorization.
- Backend Authorization Gate:
Under zero circumstances will the
ExecutionAgentexecute submission without:- Session workflow stage being strictly
HUMAN_CONFIRMATION. - A valid, non-empty
confirmation_tokenmatchingSchemeApplicationModel.human_confirmation_token.
- Session workflow stage being strictly
- Input:
AgentMessage[ExecutionSubmissionRequest]containingportal_session_idandconfirmation_token. - Processing:
- Validates token presence and format.
- Calls
PortalAutomationClient.submit_application(portal_session_id, declaration=True). - Receives official registration reference number from the portal (
DEMO-AP-2026-XXXXXX). - Captures receipt payload, submission timestamp, and marks status as
SUBMITTED.
- Output:
AgentMessage[ExecutionSubmissionResult]containingreference_number,status: "SUBMITTED", andreceipt_payload. - Tools:
PortalAutomationClient.submit_application(). - LLM Usage: None.
- Failure Handling: Raises
UnauthorizedSubmissionError(HTTP 403) if token is missing or forged.
3. Typed Agent Communication Protocol (AgentMessage[T])
All 8 agents communicate strictly using strongly-typed envelopes defined in backend/app/schemas/agent_protocol.py:
class AgentMessage(BaseModel, Generic[T]):
message_id: str = Field(default_factory=lambda: f"MSG-{uuid.uuid4().hex[:8].upper()}")
session_id: str
sender_agent: str
recipient_agent: str
message_type: str
timestamp: datetime = Field(default_factory=lambda: datetime.now(timezone.utc))
payload: T
Benefits of This Architecture:
- Type Safety: The payload
Tis validated at runtime using Pydantic V2 models. - Auditability: Every message envelope carries a unique
message_id,session_id, and UTCtimestamp. - Observability: Input and output envelopes are logged directly to
AgentAuditLogModelwith millisecond execution latencies. - Modularity: Individual agents can be tested, mocked, or upgraded in isolation without breaking the orchestration state machine.