Backend API
Python/FastAPI core API powering TerraGuard with 40+ endpoints, 6 AI agents, 5 MCP servers, and Inngest-driven async workflows for disaster event management.
Overview
The tg-backend-api is the central service of the TerraGuard platform. Built with Python and FastAPI, it provides the core REST API that the frontend and other services consume. It handles event management, AI-powered enrichment, reporting, knowledge base operations, notifications, and team/organization management.
The service runs on port 5601 and exposes all routes under the /api/v1 prefix.
Architecture
Key Features
40+ REST Endpoints
The API aggregates routers from over 30 modules covering events, reports, knowledge, notifications, organizations, teams, dashboards, and more. All routers are registered in app/apis/routes.py.
6 AI Agents
Built with the pydantic-ai framework, each agent handles a specific task in the enrichment pipeline:
| Agent | Purpose |
|---|---|
gdacs_response_agent | Analyzes and structures GDACS event data |
news_filter_agent | LLM-based validation of news article relevance |
news_briefing_agent | Generates concise news briefings from discovered articles |
notify_agent | Crafts notification content for email and Telegram |
gdacs_rag_agent | Retrieval-augmented generation for event Q&A |
report_generation_agent | Multi-section report generation using MCP tools (ReAct pattern) |
5 MCP Servers
Model Context Protocol servers provide tool access for the report generation agent:
| Server | Port | Purpose |
|---|---|---|
| Brave Search | 8001 | Web search tool |
| Doclink | 8002 | Document URL retrieval |
| GeoPop | 8003 | Geocoding and population data |
| DB Search | 8004 | Database query tool |
| Vector Search | 8005 | Semantic search over knowledge base |
Inngest Async Workflows
The service uses Inngest (backed by Redis) for event-driven background processing. Key workflow functions include:
execute_event_pipeline— Orchestrates the full enrichment pipeline for new eventsprocess_event_from_go— Handles webhook events from the Event Processorcentralized_scheduler— Manages scheduled tasks (news crawling, report generation)send_email— Async email deliverysqs_poller— Legacy SQS message processing
Database
PostgreSQL with two critical extensions:
- PostGIS — Geospatial queries (proximity searches, region containment)
- pgVector — Vector embeddings for semantic search over crawled knowledge
All models are defined in app/models.py (~2000+ lines of SQLModel definitions).
Configuration
Key environment variables from .env:
| Variable | Description | Default |
|---|---|---|
DATABASE_HOST | PostgreSQL host | localhost |
DATABASE_PORT | PostgreSQL port | 5432 |
DATABASE_NAME | Database name | tg_db |
OPENAI_API_KEY | OpenAI API key for AI agents | required |
GEMINI_API_KEY | Google Gemini API key | required |
SERPER_API_KEY | Serper.dev key — primary web/news search | required |
BRAVE_API_KEY | Brave Search key — search fallback | optional |
GEO_POP_API | URL of the GeoPop API service | http://localhost:8077/api/v1 |
INNGEST_BASE_URL | Inngest server URL | http://localhost:8288 |
INNGEST_EVENT_KEY | Inngest event signing key | required |
INNGEST_SIGNING_KEY | Inngest webhook signing key | required |
TELEGRAM_BOT_TOKEN | Telegram bot token for notifications | required |
SMTP_HOST | SMTP server for email notifications | localhost |
SMTP_PORT | SMTP port | 1025 |
FRONTEND_URL | Frontend URL for links in notifications | http://localhost:3000 |
API Endpoints
The API is organized into the following route groups (all prefixed with /api/v1):
| Prefix | Tag | Description |
|---|---|---|
/auth | auth | Authentication and user management |
/events | events | Disaster event CRUD and queries |
/event-news | event-news | News articles linked to events |
/event-notes | event-notes | Manual notes on events |
/event-pipeline | event-pipeline | Event processing pipeline triggers |
/evaluate | evaluate | AI evaluation endpoints |
/dashboard | dashboard | Dashboard aggregations and stats |
/knowledge | knowledge | Knowledge base management |
/documents | documents | Document upload and processing |
/reports | reports | Report generation and management |
/report-templates | report-templates | Report template CRUD |
/report-schedulers | report-schedulers | Scheduled report configuration |
/notifications | notifications | Notification history and triggers |
/message-templates | message-templates | Email/Telegram templates |
/organizations | organizations | Organization management |
/matrix | matrix | Organization alert matrices |
/matrix-regions | matrix-regions | Region-specific matrix config |
/teams | teams | Team management |
/roles | roles | Role management |
/contacts | contacts | Contact directory |
/country-configs | country-configs | Per-country settings |
/geo-location | geo-location | Geocoding utilities |
/ingest | ingest | Manual event ingestion |
/internal | internal | Internal webhooks (event processor) |
/update-scheduler | update-scheduler | Scheduled update configuration |
/news-crawler-scheduler | news-crawler-scheduler | News crawl scheduling |
Directory Structure
tg-backend-api/
├── app/
│ ├── main.py # FastAPI application entry point
│ ├── config.py # Pydantic Settings configuration
│ ├── models.py # SQLModel definitions (2000+ lines)
│ ├── apis/
│ │ ├── routes.py # Router aggregation (30+ routers)
│ │ ├── auth/ # Authentication endpoints
│ │ ├── event/ # Event CRUD
│ │ ├── event_news/ # Event news management
│ │ ├── knowledge/ # Knowledge base
│ │ ├── reports/ # Report generation
│ │ ├── notification/ # Notifications
│ │ ├── organization/ # Org, matrix, country config
│ │ ├── dashboard/ # Dashboard stats
│ │ └── internal/ # Internal webhooks
│ ├── agents/
│ │ ├── gdacs_response_agent.py
│ │ ├── news_filter_agent.py
│ │ ├── news_briefing_agent.py
│ │ ├── notify_agent.py
│ │ ├── gdacs_rag_agent.py
│ │ └── report_generation_agent/
│ ├── inngest/
│ │ ├── worker.py # Inngest worker process
│ │ ├── client.py # Inngest client configuration
│ │ ├── registry.py # Function registration
│ │ └── functions/
│ │ ├── execute_event_pipeline.py
│ │ ├── process_event_from_go.py
│ │ ├── centralized_scheduler.py
│ │ └── send_email.py
│ ├── mcp/
│ │ ├── runner.py # MCP server runner
│ │ ├── db_search/ # Database search MCP
│ │ ├── vector_search/ # Vector search MCP
│ │ ├── doclink/ # Document link MCP
│ │ └── geopop/ # GeoPop proxy MCP
│ └── common/
│ ├── search_providers.py # Serper (primary) + Brave (fallback) search
│ ├── firecrawl_client.py # Web Crawler client
│ └── document_processor_client.py
├── alembic/ # Database migrations
├── Makefile
└── pyproject.tomlRunning
# Start the API server
make server
# Start the Inngest worker (separate terminal)
make inngest
# Start all MCP servers (separate terminal)
make mcp-all
# Run integration tests
make e2e-testKnowledge Discovery Pipeline
How TerraGuard automatically discovers, crawls, validates, and indexes external knowledge sources to build a comprehensive information base for each disaster event.
Event Processor
Go-based deterministic event ingestion service with pluggable source adapters, PostGIS spatial correlation, hash-based deduplication, and atomic upserts.