This service is a production-ready AI Sentiment Agent designed for a multi-agent complaint management system. It exposes an asynchronous FastAPI API backed by Google Gemini 2.5 Flash via the Google ADK to provide deep semantic, emotional, and structural analysis of customer complaints, paired with a local high-volume safety-boost mechanism.
- Full AI Autonomy: Urgency scoring (0–100) and Priority routing (P0–P3) are now dynamically inferred by Gemini's contextual reasoning rather than rigid local keyword heuristics.
- Robust JSON Guardrails: Built-in automatic string sanitization to strip unexpected Markdown wrappers (
json ...) frequently returned by advanced LLMs, preventingJSONDecodeErrorruntime crashes.
- FastAPI Layer (
app/main.py): Handles async HTTP endpoints, input/output validation via Pydantic, and global error handling. - Agent Wrapper (
app/agent.py): Core Google ADKAgentimplementation managing sessions, fallback routing, and LLM output parsing. - Prompting (
app/prompts.py): System persona constraints, precise evaluation rubrics, and high-quality few-shot examples for the LLM. - Domain Models (
app/models.py): Structured Pydantic schemas enforcing data integrity for upstream and downstream orchestration. - Configuration (
app/config.py): Centralized Pydantic-Settings management for environment variables.
Create a .env file in the root directory. To support both the legacy code hooks and the modern Google GenAI SDK under the hood, both API key variables must be set:
GOOGLE_API_KEY=AIzaSy... # Read by app/agent.py safety checks
GEMINI_API_KEY=AIzaSy... # Read by underlying Google GenAI Client
GEMINI_MODEL=gemini-2.5-flash
AGENT_MODE=online # auto | online | offline
ENVIRONMENT=local # local | dev | prod
LOG_LEVEL=INFO
REQUEST_TIMEOUT_SECONDS=20
online: Forces Gemini-only execution. Fails fast if keys are missing or upstream APIs timeout.offline: Completely bypasses remote calls. Uses deterministic local regex heuristics for low-cost testing.auto(Default): Uses Gemini if keys are detected; gracefully drops down to offline heuristics on failure.
# Clone and enter the repository
cd sentiment-agent
# Create and activate virtual environment
python -m venv .venv
source .venv/bin/activate # On Windows use: .venv\Scripts\activate
# Upgrade pip and install dependencies
pip install --upgrade pip
pip install -r requirements.txt
Start the Uvicorn development server with hot-reload enabled:
uvicorn app.main:app --reload
The interactive API documentation will be available immediately at: http://127.0.0.1:8000/docs
Request:
curl -X POST http://localhost:8000/analyze \
-H "Content-Type: application/json" \
-d '{
"text": "Your server is down! I am losing thousands of dollars every minute! Fix it now!",
"duplicate_count": 100
}'
Response (Code 200):
{
"sentiment": "negative",
"emotion": "anger",
"urgency_score": 98,
"priority": "P0",
"reasoning": "Customer reports a critical server outage leading to significant financial loss, demanding immediate action. Duplicate complaint volume is high (duplicate_count=100), so priority was boosted by one level."
}
Designed for upstream data pipelines to bulk-enrich triage queues efficiently.
Request:
curl -X POST http://localhost:8000/batch-analyze \
-H "Content-Type: application/json" \
-d '{
"texts": ["Great update!", "I am hacked!"],
"duplicate_counts": [0, 5]
}'
- Upstream Triage / Ingestion: Captures raw user input and aggregates repetition metrics (
duplicate_count), then invokes/batch-analyze. - Sentiment Agent (This Service): Processes text with Gemini to extract emotional states, assigns a raw risk score (0–100), maps it to a standard priority, and triggers a local escalation multiplier if
duplicate_count > 20. - Downstream Routing: Consumes the structured output (
priority,urgency_score) to automatically route tickets to real-time Slack/PagerDuty alerts (P0) or standard email backlogs (P3).
pytest
docker build -t sentiment-agent:latest .
docker run --rm -p 8080:8080 --env-file .env sentiment-agent:latest