# trendzaphq/trendzap-intelligence architecture

> Architecture diagram of the GitHub repository trendzaphq/trendzap-intelligence, generated by GitDiagram from its file tree, README and a sample of source files (last updated 2026-07-18). It is an AI-made overview: check details against the source.

- Interactive diagram: https://gitdiagram.com/trendzaphq/trendzap-intelligence
- Repository: https://github.com/trendzaphq/trendzap-intelligence

## Overview

#### Purpose and Entry Point
TrendZap Intelligence is a stateless Python 3.11+ signal service for TrendZap’s social-virality prediction markets. It exposes prediction, forecasting, anomaly-detection, trend-discovery, and LLM explanation APIs used to price and help resolve markets.

The runtime entry point is the FastAPI application in `src/api/main.py`, launched as `uvicorn src.api.main:app`. The core package is `src/trendzap_intelligence/`.

#### API Boundary and Request Flow
`src/api/main.py` owns HTTP schemas, `/health`, and `/api/v1/*` routes. Requests enter through one of two paths:
- Deterministic/model paths: virality, engagement, anomaly, and trends invoke local model classes.
- AI paths: post/trend/anomaly requests invoke asynchronous Groq-backed analysis.

This is the boundary consumed by the TrendZap app, oracle, and risk systems; the service does not settle on-chain markets itself.

#### Predictive Signal Models
The model layer in `src/trendzap_intelligence/models/` supplies the market-facing signals:
- `virality_predictor.py`: probability and threshold-relative OVER/UNDER decision. It has an LSTM/attention architecture using text embeddings and engineered social features, with a heuristic fallback pending production training.
- `engagement_forecaster.py`: final engagement estimate and confidence bounds. It currently uses heuristic growth-curve behavior, with an XGBoost path designed for later trained inference.
- `anomaly_detector.py`: artificial-engagement detection. Rule filters are active; Isolation Forest is available for trained use.
- `trend_detector.py`: TF-IDF plus DBSCAN clustering, ranked by growth velocity; operates without supervised training.

#### AI Explanation Layer
`src/trendzap_intelligence/ai_analyzer.py` translates raw post, trend, and anomaly inputs into human-readable analysis: drivers, audience or opportunity assessment, optimization guidance, longevity, risks, and anomaly explanations.

It uses an async OpenAI-compatible client configured for Groq/Llama 3.3 70B. This isolates slow external inference from FastAPI’s event loop while keeping deterministic model outputs separate from generative interpretation.

#### Configuration and External Dependencies
`src/trendzap_intelligence/config.py` centralizes settings and sync/async AI-client creation. Environment configuration includes the required Groq API key and optional Redis URL, represented by `.env.example`.

Material dependencies/services:
- FastAPI/Uvicorn API runtime.
- Groq LLM API for AI endpoints.
- Optional Redis for LLM response caching.
- ML/NLP stack supporting LSTM embeddings, XGBoost, Isolation Forest, TF-IDF, and DBSCAN.

#### Cache and Failure Boundary
AI endpoint payloads are hashed into Redis keys and cached for five minutes in `src/api/main.py`. Redis is deliberately non-critical: cache connection or retrieval failures bypass caching rather than fail client requests. This keeps the service available when optional infrastructure is absent; Groq availability remains the primary dependency for AI analysis.

#### Deployment and Platform Integration
`Dockerfile` packages the service; `railway.toml` defines Railway deployment behavior, including health checks and restart policy. Production binds to Railway’s injected port, with local fallback to port 8000.

Upstream social engagement metrics from `trendzap-oracle` feed anomaly assessment before resolution. Resulting bot-risk signals inform `trendzap-risk`; the frontend consumes analysis APIs. Final market settlement occurs externally through TrendZap’s Avalanche contracts, using validated oracle data rather than this repository directly.

Main entry points: [`src/api/main.py`](https://github.com/trendzaphq/trendzap-intelligence/blob/main/src/api/main.py) (FastAPI app), [`src/trendzap_intelligence/models/anomaly_detector.py`](https://github.com/trendzaphq/trendzap-intelligence/blob/main/src/trendzap_intelligence/models/anomaly_detector.py) (Anomaly detector), [`src/trendzap_intelligence/ai_analyzer.py`](https://github.com/trendzaphq/trendzap-intelligence/blob/main/src/trendzap_intelligence/ai_analyzer.py) (AI analyzer), [`Dockerfile`](https://github.com/trendzaphq/trendzap-intelligence/blob/main/Dockerfile) (Docker image)

## Diagram (Mermaid)

```mermaid
flowchart TD

subgraph group_api["API Service"]
  node_fastapi["FastAPI app<br/>HTTP API<br/>[main.py]"]
  node_cache[("AI response cache<br/>Redis cache<br/>[main.py]")]
end

subgraph group_models["Signal Models"]
  node_virality["Virality predictor<br/>prediction model"]
  node_engagement["Engagement forecaster<br/>forecast model"]
  node_anomaly["Anomaly detector<br/>detection model"]
  node_trends["Trend detector<br/>clustering model<br/>[trend_detector.py]"]
end

subgraph group_ai["AI Analysis"]
  node_config["Settings &amp; AI clients<br/>configuration<br/>[config.py]"]
  node_ai_analyzer["AI analyzer<br/>async analysis<br/>[ai_analyzer.py]"]
end

subgraph group_external["Platform &amp; Dependencies"]
  node_groq{{"Groq LLM API<br/>external AI"}}
  node_redis[("Redis<br/>optional infrastructure")]
  node_frontend["TrendZap frontend<br/>consumer"]
  node_oracle["trendzap-oracle<br/>upstream metrics"]
  node_risk["trendzap-risk<br/>downstream consumer"]
  node_contracts{{"Avalanche contracts<br/>external settlement"}}
  node_container["Docker image<br/>packaging"]
  node_railway["Railway deployment<br/>hosting<br/>[railway.toml]"]
end

node_frontend -->|"analysis requests"| node_fastapi
node_fastapi -->|"virality requests"| node_virality
node_fastapi -->|"engagement requests"| node_engagement
node_fastapi -->|"anomaly requests"| node_anomaly
node_fastapi -->|"trend requests"| node_trends
node_fastapi -->|"read/write AI payloads"| node_cache
node_cache -.->|"optional backend"| node_redis
node_fastapi -->|"AI endpoints"| node_ai_analyzer
node_config -->|"async client configuration"| node_ai_analyzer
node_ai_analyzer -->|"async inference"| node_groq
node_oracle -->|"engagement metrics"| node_anomaly
node_anomaly -->|"bot-risk signal"| node_risk
node_oracle -->|"validated resolution data"| node_contracts
node_container -->|"packages service"| node_fastapi
node_railway -->|"deploys"| node_container

click node_fastapi "https://github.com/trendzaphq/trendzap-intelligence/blob/main/src/api/main.py"
click node_cache "https://github.com/trendzaphq/trendzap-intelligence/blob/main/src/api/main.py"
click node_config "https://github.com/trendzaphq/trendzap-intelligence/blob/main/src/trendzap_intelligence/config.py"
click node_ai_analyzer "https://github.com/trendzaphq/trendzap-intelligence/blob/main/src/trendzap_intelligence/ai_analyzer.py"
click node_virality "https://github.com/trendzaphq/trendzap-intelligence/blob/main/src/trendzap_intelligence/models/virality_predictor.py"
click node_engagement "https://github.com/trendzaphq/trendzap-intelligence/blob/main/src/trendzap_intelligence/models/engagement_forecaster.py"
click node_anomaly "https://github.com/trendzaphq/trendzap-intelligence/blob/main/src/trendzap_intelligence/models/anomaly_detector.py"
click node_trends "https://github.com/trendzaphq/trendzap-intelligence/blob/main/src/trendzap_intelligence/models/trend_detector.py"
click node_container "https://github.com/trendzaphq/trendzap-intelligence/blob/main/Dockerfile"
click node_railway "https://github.com/trendzaphq/trendzap-intelligence/blob/main/railway.toml"

classDef toneNeutral fill:#f8fafc,stroke:#334155,stroke-width:1.5px,color:#0f172a
classDef toneBlue fill:#dbeafe,stroke:#2563eb,stroke-width:1.5px,color:#172554
classDef toneAmber fill:#fef3c7,stroke:#d97706,stroke-width:1.5px,color:#78350f
classDef toneMint fill:#dcfce7,stroke:#16a34a,stroke-width:1.5px,color:#14532d
classDef toneRose fill:#ffe4e6,stroke:#e11d48,stroke-width:1.5px,color:#881337
classDef toneIndigo fill:#e0e7ff,stroke:#4f46e5,stroke-width:1.5px,color:#312e81
classDef toneTeal fill:#ccfbf1,stroke:#0f766e,stroke-width:1.5px,color:#134e4a
class node_fastapi,node_cache toneBlue
class node_virality,node_engagement,node_anomaly,node_trends toneAmber
class node_config,node_ai_analyzer toneMint
class node_groq,node_redis,node_frontend,node_oracle,node_risk,node_contracts,node_container,node_railway toneRose
```

## Components

### API Service

- [FastAPI app](https://github.com/trendzaphq/trendzap-intelligence/blob/main/src/api/main.py): HTTP API · Health and versioned market-signal endpoints. · `src/api/main.py`
- [AI response cache](https://github.com/trendzaphq/trendzap-intelligence/blob/main/src/api/main.py): Redis cache · Five-minute cache; failures bypass caching. · `src/api/main.py`

### Signal Models

- [Virality predictor](https://github.com/trendzaphq/trendzap-intelligence/blob/main/src/trendzap_intelligence/models/virality_predictor.py): prediction model · Probability and OVER/UNDER signal with heuristic fallback. · `src/trendzap_intelligence/models/virality_predictor.py`
- [Engagement forecaster](https://github.com/trendzaphq/trendzap-intelligence/blob/main/src/trendzap_intelligence/models/engagement_forecaster.py): forecast model · Engagement estimate and confidence bounds. · `src/trendzap_intelligence/models/engagement_forecaster.py`
- [Anomaly detector](https://github.com/trendzaphq/trendzap-intelligence/blob/main/src/trendzap_intelligence/models/anomaly_detector.py): detection model · Rule-based artificial-engagement detection with Isolation Forest path. · `src/trendzap_intelligence/models/anomaly_detector.py`
- [Trend detector](https://github.com/trendzaphq/trendzap-intelligence/blob/main/src/trendzap_intelligence/models/trend_detector.py): clustering model · TF-IDF and DBSCAN trends ranked by growth velocity. · `src/trendzap_intelligence/models/trend_detector.py`

### AI Analysis

- [Settings & AI clients](https://github.com/trendzaphq/trendzap-intelligence/blob/main/src/trendzap_intelligence/config.py): configuration · Builds sync and async Groq-compatible clients. · `src/trendzap_intelligence/config.py`
- [AI analyzer](https://github.com/trendzaphq/trendzap-intelligence/blob/main/src/trendzap_intelligence/ai_analyzer.py): async analysis · Produces post, trend, and anomaly explanations. · `src/trendzap_intelligence/ai_analyzer.py`

### Platform & Dependencies

- **Groq LLM API**: external AI · Llama 3.3 70B inference for generative endpoints.
- **Redis**: optional infrastructure · Non-critical remote cache backend.
- **TrendZap frontend**: consumer · Consumes analysis APIs.
- **trendzap-oracle**: upstream metrics · Supplies social engagement data for assessment.
- **trendzap-risk**: downstream consumer · Uses bot-risk signals.
- **Avalanche contracts**: external settlement · Markets settle externally using validated oracle data.
- [Docker image](https://github.com/trendzaphq/trendzap-intelligence/blob/main/Dockerfile): packaging · `Dockerfile`
- [Railway deployment](https://github.com/trendzaphq/trendzap-intelligence/blob/main/railway.toml): hosting · Provides port, health checks, and restart policy. · `railway.toml`

## Connections

- TrendZap frontend → FastAPI app: analysis requests
- FastAPI app → Virality predictor: virality requests
- FastAPI app → Engagement forecaster: engagement requests
- FastAPI app → Anomaly detector: anomaly requests
- FastAPI app → Trend detector: trend requests
- FastAPI app → AI response cache: read/write AI payloads
- AI response cache → Redis: optional backend
- FastAPI app → AI analyzer: AI endpoints
- Settings & AI clients → AI analyzer: async client configuration
- AI analyzer → Groq LLM API: async inference
- trendzap-oracle → Anomaly detector: engagement metrics
- Anomaly detector → trendzap-risk: bot-risk signal
- trendzap-oracle → Avalanche contracts: validated resolution data
- Docker image → FastAPI app: packages service
- Railway deployment → Docker image: deploys
