Skip to content

Latest commit

 

History

2 Commits

Folders and files

NameName
Last commit message
Last commit date
 
 
 
 
 
 
 
 
 
 
 
 

Repository files navigation

Sentiment Agent – Complaint Management System

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.

🌟 Key Enhancements in this Fork

  • 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, preventing JSONDecodeError runtime crashes.

Architecture Overview

  • 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 ADK Agent implementation 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.

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

Mode Explanations:

  • 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.

Setup & Installation

# 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

Running Locally

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


API Specifications & Formats

1. Single Analysis – POST /analyze

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."
}

2. Batch Analysis – POST /batch-analyze

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]
  }'

Multi-Agent Integration Flow

  1. Upstream Triage / Ingestion: Captures raw user input and aggregates repetition metrics (duplicate_count), then invokes /batch-analyze.
  2. 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.
  3. 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).

Testing & Deployment

Run Test Suite

pytest

Docker Build

docker build -t sentiment-agent:latest .
docker run --rm -p 8080:8080 --env-file .env sentiment-agent:latest

About

For part of google cloud hackthon contribution with team

Resources

Stars

0 stars

Watchers

0 watching

Forks

Releases

Packages

Contributors

Languages