Commit ·
7113709
0
Parent(s):
Initial commit: Week 3 workspace (notebook + multi-agent customer support)
Browse files- .gitignore +36 -0
- agent1.ipynb +0 -0
- multi_agent_customer_support/.env.example +17 -0
- multi_agent_customer_support/.gitignore +34 -0
- multi_agent_customer_support/README.md +180 -0
- multi_agent_customer_support/pyproject.toml +41 -0
- multi_agent_customer_support/scripts/load_dotenv_and_run.ps1 +50 -0
- multi_agent_customer_support/servers/returns_service/__init__.py +1 -0
- multi_agent_customer_support/servers/returns_service/main.py +273 -0
- multi_agent_customer_support/sql/fix_rls_and_verify.sql +39 -0
- multi_agent_customer_support/sql/schema_and_seed.sql +155 -0
- multi_agent_customer_support/src/__init__.py +1 -0
- multi_agent_customer_support/src/agents/__init__.py +1 -0
- multi_agent_customer_support/src/agents/adk_runtime.py +111 -0
- multi_agent_customer_support/src/agents/billing_agent.py +124 -0
- multi_agent_customer_support/src/agents/customer_context.py +31 -0
- multi_agent_customer_support/src/agents/returns_remote_agent.py +166 -0
- multi_agent_customer_support/src/agents/router_agent.py +256 -0
- multi_agent_customer_support/src/agents/support_agent.py +103 -0
- multi_agent_customer_support/src/main.py +163 -0
- multi_agent_customer_support/src/mcp/__init__.py +1 -0
- multi_agent_customer_support/src/mcp/python_mcp_server.py +54 -0
- multi_agent_customer_support/src/mcp/supabase_client.py +236 -0
- multi_agent_customer_support/src/mcp/supabase_mcp_connection.py +39 -0
- multi_agent_customer_support/src/mcp/supabase_mcp_server.py +170 -0
- multi_agent_customer_support/tests/__init__.py +1 -0
- multi_agent_customer_support/tests/test_returns_remote_agent.py +61 -0
- multi_agent_customer_support/tests/test_returns_service.py +73 -0
- multi_agent_customer_support/tests/test_router_fallback.py +35 -0
- multi_agent_customer_support/tests/test_scenarios.py +153 -0
- multi_agent_customer_support/tests/test_supabase_client.py +107 -0
.gitignore
ADDED
|
@@ -0,0 +1,36 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
# Secrets — never commit
|
| 2 |
+
.env
|
| 3 |
+
.env.*
|
| 4 |
+
!.env.example
|
| 5 |
+
|
| 6 |
+
# Local editor / MCP (machine-specific paths)
|
| 7 |
+
.cursor/
|
| 8 |
+
|
| 9 |
+
# Python (any subfolder)
|
| 10 |
+
**/.venv/
|
| 11 |
+
**/venv/
|
| 12 |
+
**/__pycache__/
|
| 13 |
+
*.py[cod]
|
| 14 |
+
*$py.class
|
| 15 |
+
*.egg-info/
|
| 16 |
+
.eggs/
|
| 17 |
+
dist/
|
| 18 |
+
build/
|
| 19 |
+
|
| 20 |
+
# Testing / coverage
|
| 21 |
+
**/.pytest_cache/
|
| 22 |
+
.coverage
|
| 23 |
+
htmlcov/
|
| 24 |
+
|
| 25 |
+
# Generated reports
|
| 26 |
+
**/reports/
|
| 27 |
+
|
| 28 |
+
# Jupyter
|
| 29 |
+
.ipynb_checkpoints/
|
| 30 |
+
|
| 31 |
+
# OS / IDE
|
| 32 |
+
.idea/
|
| 33 |
+
.vscode/
|
| 34 |
+
*.swp
|
| 35 |
+
.DS_Store
|
| 36 |
+
Thumbs.db
|
agent1.ipynb
ADDED
|
File without changes
|
multi_agent_customer_support/.env.example
ADDED
|
@@ -0,0 +1,17 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
# Copy this file to .env and fill values before running.
|
| 2 |
+
APP_ENV=development
|
| 3 |
+
APP_HOST=127.0.0.1
|
| 4 |
+
APP_PORT=8000
|
| 5 |
+
|
| 6 |
+
# Returns service endpoint used by the remote returns agent.
|
| 7 |
+
RETURNS_SERVICE_URL=http://127.0.0.1:8081
|
| 8 |
+
# Optional: full Agent Card URL for ADK RemoteA2aAgent (default: {RETURNS_SERVICE_URL}/.well-known/agent-card.json).
|
| 9 |
+
# RETURNS_A2A_AGENT_CARD_URL=http://127.0.0.1:8081/.well-known/agent-card.json
|
| 10 |
+
|
| 11 |
+
# Supabase settings for MCP server integration.
|
| 12 |
+
SUPABASE_URL=https://your-project.supabase.co
|
| 13 |
+
# App / supabase_client.py: use the anon key for client-side style access.
|
| 14 |
+
SUPABASE_ANON_KEY=your-supabase-anon-key
|
| 15 |
+
# Legacy name (optional): some files still read SUPABASE_KEY.
|
| 16 |
+
SUPABASE_KEY=your-supabase-service-role-or-anon-key
|
| 17 |
+
SUPABASE_ACCESS_TOKEN=your-supabase-personal-access-token
|
multi_agent_customer_support/.gitignore
ADDED
|
@@ -0,0 +1,34 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
# Environment and secrets
|
| 2 |
+
.env
|
| 3 |
+
.env.*
|
| 4 |
+
!.env.example
|
| 5 |
+
|
| 6 |
+
# Python
|
| 7 |
+
.venv/
|
| 8 |
+
venv/
|
| 9 |
+
__pycache__/
|
| 10 |
+
*.py[cod]
|
| 11 |
+
*$py.class
|
| 12 |
+
*.so
|
| 13 |
+
.Python
|
| 14 |
+
*.egg-info/
|
| 15 |
+
.eggs/
|
| 16 |
+
dist/
|
| 17 |
+
build/
|
| 18 |
+
*.egg
|
| 19 |
+
|
| 20 |
+
# Testing / coverage
|
| 21 |
+
.pytest_cache/
|
| 22 |
+
.coverage
|
| 23 |
+
htmlcov/
|
| 24 |
+
.tox/
|
| 25 |
+
|
| 26 |
+
# Generated reports (regenerate with pytest --html)
|
| 27 |
+
reports/
|
| 28 |
+
|
| 29 |
+
# IDE / OS
|
| 30 |
+
.idea/
|
| 31 |
+
.vscode/
|
| 32 |
+
*.swp
|
| 33 |
+
.DS_Store
|
| 34 |
+
Thumbs.db
|
multi_agent_customer_support/README.md
ADDED
|
@@ -0,0 +1,180 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
# Multi-Agent Customer Support System with MCP and A2A
|
| 2 |
+
|
| 3 |
+
**Multi-Agent Customer Support System with MCP and A2A** — a Python reference app where a **RouterAgent** classifies customer messages and delegates to specialists: **BillingAgent** and **SupportAgent** (data via Supabase, exposed through MCP-style tools), and **ReturnsRemoteAgent** (remote **Agent-to-Agent** protocol to a dedicated returns FastAPI service).
|
| 4 |
+
|
| 5 |
+
## Architecture
|
| 6 |
+
|
| 7 |
+
```text
|
| 8 |
+
+------------------+
|
| 9 |
+
| RouterAgent |
|
| 10 |
+
| (intent route) |
|
| 11 |
+
+--------+---------+
|
| 12 |
+
|
|
| 13 |
+
+-----------------------+----------------------+
|
| 14 |
+
| | |
|
| 15 |
+
v v v
|
| 16 |
+
+----------------+ +-------------------+ +----------------------+
|
| 17 |
+
| BillingAgent | | SupportAgent | | ReturnsRemoteAgent |
|
| 18 |
+
| ADK + tools | | ADK + tickets | | ADK RemoteA2aAgent |
|
| 19 |
+
+-------+--------+ +---------+---------+ +----------+-----------+
|
| 20 |
+
| | |
|
| 21 |
+
| MCP tool parity | MCP tool parity | A2A JSON-RPC
|
| 22 |
+
| (FunctionTool / | (get_support_tickets) | + agent card
|
| 23 |
+
| stdio MCP server) | |
|
| 24 |
+
v v v
|
| 25 |
+
+----------------+ +-------------------+ +----------------------+
|
| 26 |
+
| Supabase | | Supabase | | Returns Service |
|
| 27 |
+
| customers, | | support_tickets | | (FastAPI, port 8081) |
|
| 28 |
+
| orders, ... | | | | eligibility + return |
|
| 29 |
+
+----------------+ +-------------------+ +----------------------+
|
| 30 |
+
```
|
| 31 |
+
|
| 32 |
+
- **MCP → Supabase**: `src/mcp/supabase_mcp_server.py` exposes `get_billing_info` / `get_support_tickets` over stdio MCP; the same logic is called in-process from agents via `FunctionTool`.
|
| 33 |
+
- **A2A → Returns Service**: `servers/returns_service/main.py` serves an ADK agent over A2A; `ReturnsRemoteAgent` connects using the Agent Card URL.
|
| 34 |
+
|
| 35 |
+
## Tech Stack
|
| 36 |
+
|
| 37 |
+
- Google ADK (`google-adk`), A2A SDK (`a2a-sdk`), MCP (`mcp`), FastMCP, FastAPI, Uvicorn, Supabase (`supabase`), `httpx`, `python-dotenv`
|
| 38 |
+
|
| 39 |
+
## Project Structure
|
| 40 |
+
|
| 41 |
+
```text
|
| 42 |
+
multi_agent_customer_support/
|
| 43 |
+
sql/
|
| 44 |
+
schema_and_seed.sql # DDL + seed data
|
| 45 |
+
fix_rls_and_verify.sql # RLS policies + checks (run after schema if needed)
|
| 46 |
+
src/
|
| 47 |
+
main.py # FastAPI + CLI entry (`python -m src.main`)
|
| 48 |
+
agents/
|
| 49 |
+
router_agent.py
|
| 50 |
+
billing_agent.py
|
| 51 |
+
support_agent.py
|
| 52 |
+
returns_remote_agent.py
|
| 53 |
+
mcp/
|
| 54 |
+
supabase_mcp_server.py
|
| 55 |
+
supabase_mcp_connection.py
|
| 56 |
+
servers/returns_service/main.py # Returns A2A microservice
|
| 57 |
+
tests/
|
| 58 |
+
.env.example
|
| 59 |
+
README.md
|
| 60 |
+
```
|
| 61 |
+
|
| 62 |
+
## Setup
|
| 63 |
+
|
| 64 |
+
### 1. Supabase: project, schema, and seed
|
| 65 |
+
|
| 66 |
+
1. Create a project in [Supabase](https://supabase.com).
|
| 67 |
+
2. In the SQL editor (or `psql`), run:
|
| 68 |
+
- `sql/schema_and_seed.sql` — tables, seed rows, and dev-oriented RLS as provided.
|
| 69 |
+
- If you hit RLS / permission issues with the anon key, run `sql/fix_rls_and_verify.sql` and re-check policies.
|
| 70 |
+
|
| 71 |
+
### 2. Environment variables
|
| 72 |
+
|
| 73 |
+
Copy and edit:
|
| 74 |
+
|
| 75 |
+
```bash
|
| 76 |
+
cp .env.example .env
|
| 77 |
+
```
|
| 78 |
+
|
| 79 |
+
Typical variables:
|
| 80 |
+
|
| 81 |
+
| Variable | Purpose |
|
| 82 |
+
|----------|---------|
|
| 83 |
+
| `SUPABASE_URL` | Project URL |
|
| 84 |
+
| `SUPABASE_ANON_KEY` | Anon key (or `SUPABASE_KEY` legacy) |
|
| 85 |
+
| `GEMINI_API_KEY` or `GOOGLE_API_KEY` | ADK / Gemini for router and agents |
|
| 86 |
+
| `RETURNS_SERVICE_URL` | Returns service base URL (default `http://127.0.0.1:8081`) |
|
| 87 |
+
| `RETURNS_A2A_AGENT_CARD_URL` | Optional full Agent Card URL override |
|
| 88 |
+
|
| 89 |
+
### 3. Install dependencies
|
| 90 |
+
|
| 91 |
+
Python **3.12** recommended.
|
| 92 |
+
|
| 93 |
+
```powershell
|
| 94 |
+
cd multi_agent_customer_support
|
| 95 |
+
py -3.12 -m venv .venv
|
| 96 |
+
.\.venv\Scripts\Activate.ps1
|
| 97 |
+
python -m pip install --upgrade pip
|
| 98 |
+
pip install -e .
|
| 99 |
+
pip install -e ".[dev]" # optional: pytest + pytest-asyncio
|
| 100 |
+
```
|
| 101 |
+
|
| 102 |
+
### 4. Run the Supabase MCP server (separate process)
|
| 103 |
+
|
| 104 |
+
From `multi_agent_customer_support/`:
|
| 105 |
+
|
| 106 |
+
```powershell
|
| 107 |
+
python -m src.mcp.supabase_mcp_server
|
| 108 |
+
```
|
| 109 |
+
|
| 110 |
+
Uses stdio MCP; configure Cursor or other MCP hosts to launch this command with the same working directory and `.env` loaded.
|
| 111 |
+
|
| 112 |
+
### 5. Run the Returns FastAPI (A2A) service
|
| 113 |
+
|
| 114 |
+
```powershell
|
| 115 |
+
uvicorn servers.returns_service.main:app --host 127.0.0.1 --port 8081
|
| 116 |
+
```
|
| 117 |
+
|
| 118 |
+
Or: `python -m servers.returns_service.main`
|
| 119 |
+
Agent card: `GET http://127.0.0.1:8081/.well-known/agent-card.json`
|
| 120 |
+
|
| 121 |
+
### 6. Run the main CLI
|
| 122 |
+
|
| 123 |
+
```powershell
|
| 124 |
+
python -m src.main
|
| 125 |
+
```
|
| 126 |
+
|
| 127 |
+
Optional: `CLI_CUSTOMER_ID` in `.env` to skip the customer-id prompt.
|
| 128 |
+
Type `quit` or `exit` to stop.
|
| 129 |
+
|
| 130 |
+
### Run the HTTP API (optional)
|
| 131 |
+
|
| 132 |
+
```powershell
|
| 133 |
+
uvicorn src.main:app --reload --port 8000
|
| 134 |
+
```
|
| 135 |
+
|
| 136 |
+
Example:
|
| 137 |
+
|
| 138 |
+
```bash
|
| 139 |
+
curl -X POST http://127.0.0.1:8000/support/query \
|
| 140 |
+
-H "Content-Type: application/json" \
|
| 141 |
+
-d "{\"customer_id\":\"you@example.com\",\"message\":\"I was charged twice\"}"
|
| 142 |
+
```
|
| 143 |
+
|
| 144 |
+
Response includes `result`, `routed_to`, `escalated`, and `rationale`.
|
| 145 |
+
|
| 146 |
+
## Example conversations (CLI)
|
| 147 |
+
|
| 148 |
+
Use a **real seeded customer email** from Supabase when testing billing/support data.
|
| 149 |
+
|
| 150 |
+
### Billing
|
| 151 |
+
|
| 152 |
+
```text
|
| 153 |
+
> I was charged twice for my last order. Can you check my billing?
|
| 154 |
+
```
|
| 155 |
+
|
| 156 |
+
Expect routing to **billing** and a summary grounded in `get_billing_info` / orders.
|
| 157 |
+
|
| 158 |
+
### Returns
|
| 159 |
+
|
| 160 |
+
```text
|
| 161 |
+
> I want to return order ORD-123. Am I eligible for a refund?
|
| 162 |
+
```
|
| 163 |
+
|
| 164 |
+
Expect routing to **returns** and an answer from the remote **Returns** A2A agent (returns service must be running with `GEMINI_API_KEY`).
|
| 165 |
+
|
| 166 |
+
### Escalation
|
| 167 |
+
|
| 168 |
+
```text
|
| 169 |
+
> My account was hacked, all my orders are gone, and nobody is helping me.
|
| 170 |
+
```
|
| 171 |
+
|
| 172 |
+
For high-severity or ambiguous cases the router may return an **escalation** response (`[ESCALATE]`, `ESCALATE_FLAG`) so a human can take over; exact behavior may use the LLM router when API keys are set, or heuristics when not.
|
| 173 |
+
|
| 174 |
+
## Tests
|
| 175 |
+
|
| 176 |
+
```powershell
|
| 177 |
+
pytest tests/ -q
|
| 178 |
+
```
|
| 179 |
+
|
| 180 |
+
Scenario tests live in `tests/test_scenarios.py`.
|
multi_agent_customer_support/pyproject.toml
ADDED
|
@@ -0,0 +1,41 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
[project]
|
| 2 |
+
name = "multi-agent-customer-support"
|
| 3 |
+
version = "0.1.0"
|
| 4 |
+
description = "Multi-agent customer support app using Google's ADK, FastAPI, and Supabase."
|
| 5 |
+
readme = "README.md"
|
| 6 |
+
requires-python = ">=3.12,<3.13"
|
| 7 |
+
dependencies = [
|
| 8 |
+
"google-adk",
|
| 9 |
+
"a2a-sdk",
|
| 10 |
+
"mcp",
|
| 11 |
+
"a2a-mcp-server==0.1.5",
|
| 12 |
+
"fastmcp==3.2.4",
|
| 13 |
+
"fastapi",
|
| 14 |
+
"uvicorn",
|
| 15 |
+
"supabase",
|
| 16 |
+
"python-dotenv",
|
| 17 |
+
"httpx",
|
| 18 |
+
]
|
| 19 |
+
|
| 20 |
+
[build-system]
|
| 21 |
+
requires = ["setuptools>=68.0"]
|
| 22 |
+
build-backend = "setuptools.build_meta"
|
| 23 |
+
|
| 24 |
+
[tool.setuptools]
|
| 25 |
+
package-dir = {"" = "src"}
|
| 26 |
+
|
| 27 |
+
[tool.setuptools.packages.find]
|
| 28 |
+
where = ["src"]
|
| 29 |
+
|
| 30 |
+
[project.optional-dependencies]
|
| 31 |
+
dev = [
|
| 32 |
+
"pytest>=8.0",
|
| 33 |
+
"pytest-asyncio>=0.24",
|
| 34 |
+
"pytest-html>=4.0",
|
| 35 |
+
]
|
| 36 |
+
|
| 37 |
+
[tool.pytest.ini_options]
|
| 38 |
+
testpaths = ["tests"]
|
| 39 |
+
python_files = ["test_*.py"]
|
| 40 |
+
asyncio_mode = "auto"
|
| 41 |
+
asyncio_default_fixture_loop_scope = "function"
|
multi_agent_customer_support/scripts/load_dotenv_and_run.ps1
ADDED
|
@@ -0,0 +1,50 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
param(
|
| 2 |
+
[Parameter(Mandatory = $true)]
|
| 3 |
+
[string]$EnvFile,
|
| 4 |
+
|
| 5 |
+
[Parameter(Mandatory = $true)]
|
| 6 |
+
[string]$Command,
|
| 7 |
+
|
| 8 |
+
[Parameter(Mandatory = $false)]
|
| 9 |
+
[string[]]$Arguments = @()
|
| 10 |
+
)
|
| 11 |
+
|
| 12 |
+
Set-StrictMode -Version Latest
|
| 13 |
+
$ErrorActionPreference = "Stop"
|
| 14 |
+
|
| 15 |
+
function Import-DotEnvFile {
|
| 16 |
+
param([string]$Path)
|
| 17 |
+
|
| 18 |
+
if (-not (Test-Path -LiteralPath $Path)) {
|
| 19 |
+
Write-Error "Dotenv file not found: $Path"
|
| 20 |
+
}
|
| 21 |
+
|
| 22 |
+
Get-Content -LiteralPath $Path | ForEach-Object {
|
| 23 |
+
$line = $_.Trim()
|
| 24 |
+
if (-not $line -or $line.StartsWith("#")) {
|
| 25 |
+
return
|
| 26 |
+
}
|
| 27 |
+
|
| 28 |
+
$eq = $line.IndexOf("=")
|
| 29 |
+
if ($eq -lt 1) {
|
| 30 |
+
return
|
| 31 |
+
}
|
| 32 |
+
|
| 33 |
+
$key = $line.Substring(0, $eq).Trim()
|
| 34 |
+
$value = $line.Substring($eq + 1).Trim()
|
| 35 |
+
|
| 36 |
+
# Strip optional quotes
|
| 37 |
+
if (($value.StartsWith('"') -and $value.EndsWith('"')) -or ($value.StartsWith("'") -and $value.EndsWith("'"))) {
|
| 38 |
+
$value = $value.Substring(1, $value.Length - 2)
|
| 39 |
+
}
|
| 40 |
+
|
| 41 |
+
if ($key) {
|
| 42 |
+
Set-Item -Path ("Env:{0}" -f $key) -Value $value
|
| 43 |
+
}
|
| 44 |
+
}
|
| 45 |
+
}
|
| 46 |
+
|
| 47 |
+
Import-DotEnvFile -Path $EnvFile
|
| 48 |
+
|
| 49 |
+
& $Command @Arguments
|
| 50 |
+
exit $LASTEXITCODE
|
multi_agent_customer_support/servers/returns_service/__init__.py
ADDED
|
@@ -0,0 +1 @@
|
|
|
|
|
|
|
| 1 |
+
"""Returns microservice package."""
|
multi_agent_customer_support/servers/returns_service/main.py
ADDED
|
@@ -0,0 +1,273 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
"""
|
| 2 |
+
Returns microservice: FastAPI + A2A (Agent-to-Agent) JSON-RPC for an ADK ``LlmAgent``.
|
| 3 |
+
|
| 4 |
+
**Run locally** (from ``multi_agent_customer_support/``; activates the venv first)::
|
| 5 |
+
|
| 6 |
+
.venv\\Scripts\\activate
|
| 7 |
+
uvicorn servers.returns_service.main:app --host 127.0.0.1 --port 8081
|
| 8 |
+
|
| 9 |
+
Or::
|
| 10 |
+
|
| 11 |
+
python -m uvicorn servers.returns_service.main:app --host 127.0.0.1 --port 8081
|
| 12 |
+
|
| 13 |
+
Environment:
|
| 14 |
+
|
| 15 |
+
- ``RETURNS_SERVICE_PORT`` — default ``8081`` (used by ``main()`` when you ``python -m servers.returns_service.main``).
|
| 16 |
+
- ``RETURNS_A2A_PUBLIC_URL`` — base URL embedded in the Agent Card (default ``http://127.0.0.1:8081``).
|
| 17 |
+
- ``GOOGLE_API_KEY`` or ``GEMINI_API_KEY`` — required for A2A ``message/send`` so the model can call tools.
|
| 18 |
+
- ``ADK_MODEL`` — optional override (default ``gemini-2.5-flash``).
|
| 19 |
+
|
| 20 |
+
**Example curl**
|
| 21 |
+
|
| 22 |
+
Agent card (no API key required)::
|
| 23 |
+
|
| 24 |
+
curl -s http://127.0.0.1:8081/.well-known/agent-card.json | head
|
| 25 |
+
|
| 26 |
+
Direct mock tool endpoints (no LLM; same rules as the agent tools)::
|
| 27 |
+
|
| 28 |
+
curl -s -X POST http://127.0.0.1:8081/tools/check_return_eligibility \\
|
| 29 |
+
-H "Content-Type: application/json" -d "{\\"order_number\\": \\"ORD-42\\"}"
|
| 30 |
+
|
| 31 |
+
curl -s -X POST http://127.0.0.1:8081/tools/initiate_return \\
|
| 32 |
+
-H "Content-Type: application/json" \\
|
| 33 |
+
-d "{\\"order_number\\": \\"ORD-42\\", \\"reason\\": \\"changed mind\\"}"
|
| 34 |
+
|
| 35 |
+
A2A JSON-RPC (needs Gemini for the agent to reply; body is illustrative)::
|
| 36 |
+
|
| 37 |
+
curl -s -X POST http://127.0.0.1:8081/ \\
|
| 38 |
+
-H "Content-Type: application/json" \\
|
| 39 |
+
-d "{\\"jsonrpc\\":\\"2.0\\",\\"id\\":\\"1\\",\\"method\\":\\"message/send\\",\\"params\\":{\\"message\\":{\\"role\\":\\"user\\",\\"parts\\":[{\\"kind\\":\\"text\\",\\"text\\":\\"Is order ORD-42 eligible for return?\\"}],\\"message_id\\":\\"m1\\",\\"kind\\":\\"message\\"}}}"
|
| 40 |
+
"""
|
| 41 |
+
|
| 42 |
+
from __future__ import annotations
|
| 43 |
+
|
| 44 |
+
import os
|
| 45 |
+
import uuid
|
| 46 |
+
from contextlib import asynccontextmanager
|
| 47 |
+
from typing import Any
|
| 48 |
+
|
| 49 |
+
from a2a.server.apps import A2AFastAPIApplication
|
| 50 |
+
from a2a.server.request_handlers import DefaultRequestHandler
|
| 51 |
+
from a2a.server.tasks import InMemoryPushNotificationConfigStore
|
| 52 |
+
from a2a.server.tasks import InMemoryTaskStore
|
| 53 |
+
from fastapi import FastAPI
|
| 54 |
+
from google.adk.agents.llm_agent import LlmAgent
|
| 55 |
+
from google.adk.a2a.utils.agent_card_builder import AgentCardBuilder
|
| 56 |
+
from google.adk.a2a.utils.agent_to_a2a import to_a2a as adk_to_a2a
|
| 57 |
+
from google.adk.artifacts.in_memory_artifact_service import InMemoryArtifactService
|
| 58 |
+
from google.adk.auth.credential_service.in_memory_credential_service import (
|
| 59 |
+
InMemoryCredentialService,
|
| 60 |
+
)
|
| 61 |
+
from google.adk.a2a.executor.a2a_agent_executor import A2aAgentExecutor
|
| 62 |
+
from google.adk.memory.in_memory_memory_service import InMemoryMemoryService
|
| 63 |
+
from google.adk.runners import Runner
|
| 64 |
+
from google.adk.sessions.in_memory_session_service import InMemorySessionService
|
| 65 |
+
from google.adk.tools.function_tool import FunctionTool
|
| 66 |
+
from pydantic import BaseModel
|
| 67 |
+
|
| 68 |
+
# ---------------------------------------------------------------------------
|
| 69 |
+
# Mock tool implementations (also wrapped as ADK FunctionTools for the LlmAgent)
|
| 70 |
+
# ---------------------------------------------------------------------------
|
| 71 |
+
|
| 72 |
+
|
| 73 |
+
def check_return_eligibility(order_number: str) -> dict[str, Any]:
|
| 74 |
+
"""
|
| 75 |
+
Mock eligibility: last character of ``order_number`` must be a digit; even -> eligible.
|
| 76 |
+
|
| 77 |
+
Returns JSON-serializable dict: ``eligible``, ``reason``.
|
| 78 |
+
"""
|
| 79 |
+
s = (order_number or "").strip()
|
| 80 |
+
if not s:
|
| 81 |
+
return {"eligible": False, "reason": "order_number is empty"}
|
| 82 |
+
last = s[-1]
|
| 83 |
+
if not last.isdigit():
|
| 84 |
+
return {
|
| 85 |
+
"eligible": False,
|
| 86 |
+
"reason": "last character is not a digit (mock rule requires a trailing digit)",
|
| 87 |
+
}
|
| 88 |
+
eligible = int(last) % 2 == 0
|
| 89 |
+
reason = (
|
| 90 |
+
"last digit is even - eligible under mock policy"
|
| 91 |
+
if eligible
|
| 92 |
+
else "last digit is odd - not eligible under mock policy"
|
| 93 |
+
)
|
| 94 |
+
return {"eligible": eligible, "reason": reason}
|
| 95 |
+
|
| 96 |
+
|
| 97 |
+
def initiate_return(order_number: str, reason: str) -> dict[str, Any]:
|
| 98 |
+
"""Mock creating a return request."""
|
| 99 |
+
rid = f"ret-{uuid.uuid4().hex[:12]}"
|
| 100 |
+
msg = f"Return initiated for order {order_number}"
|
| 101 |
+
if (reason or "").strip():
|
| 102 |
+
msg += f" ({reason.strip()[:500]})"
|
| 103 |
+
return {
|
| 104 |
+
"return_id": rid,
|
| 105 |
+
"status": "initiated",
|
| 106 |
+
"message": msg,
|
| 107 |
+
}
|
| 108 |
+
|
| 109 |
+
|
| 110 |
+
_RETURNS_AGENT_INSTRUCTION = """You are a returns specialist for an online store.
|
| 111 |
+
|
| 112 |
+
You have two tools:
|
| 113 |
+
- check_return_eligibility(order_number) — returns whether the order is eligible (mock rule) with a reason.
|
| 114 |
+
- initiate_return(order_number, reason) — creates a mock return request.
|
| 115 |
+
|
| 116 |
+
When the user asks about eligibility, call check_return_eligibility with the order number they provide.
|
| 117 |
+
When they want to start a return, call initiate_return with order number and reason.
|
| 118 |
+
|
| 119 |
+
Reply in clear, short natural language and include key facts from the tool results.
|
| 120 |
+
"""
|
| 121 |
+
|
| 122 |
+
|
| 123 |
+
def build_returns_llm_agent() -> LlmAgent:
|
| 124 |
+
"""ADK agent exposed over A2A (tools: eligibility + initiate return)."""
|
| 125 |
+
model = os.getenv("ADK_MODEL", "gemini-2.5-flash")
|
| 126 |
+
return LlmAgent(
|
| 127 |
+
name="returns_agent",
|
| 128 |
+
model=model,
|
| 129 |
+
description="Returns eligibility and return initiation (mock rules).",
|
| 130 |
+
instruction=_RETURNS_AGENT_INSTRUCTION,
|
| 131 |
+
tools=[
|
| 132 |
+
FunctionTool(check_return_eligibility),
|
| 133 |
+
FunctionTool(initiate_return),
|
| 134 |
+
],
|
| 135 |
+
)
|
| 136 |
+
|
| 137 |
+
|
| 138 |
+
def to_a2a(
|
| 139 |
+
host: str = "127.0.0.1",
|
| 140 |
+
port: int = 8081,
|
| 141 |
+
) -> Any:
|
| 142 |
+
"""
|
| 143 |
+
ADK pattern: build a **Starlette** ASGI app that speaks A2A (JSON-RPC + agent card).
|
| 144 |
+
|
| 145 |
+
Run with::
|
| 146 |
+
|
| 147 |
+
uvicorn servers.returns_service.main:starlette_a2a_app --host 127.0.0.1 --port 8081
|
| 148 |
+
|
| 149 |
+
``starlette_a2a_app`` is created on first access (see ``__getattr__`` below).
|
| 150 |
+
|
| 151 |
+
This is the same helper as ``google.adk.a2a.utils.agent_to_a2a.to_a2a`` applied to
|
| 152 |
+
:func:`build_returns_llm_agent`.
|
| 153 |
+
"""
|
| 154 |
+
agent = build_returns_llm_agent()
|
| 155 |
+
return adk_to_a2a(agent, host=host, port=port, protocol="http")
|
| 156 |
+
|
| 157 |
+
|
| 158 |
+
_starlette_a2a_singleton: Any | None = None
|
| 159 |
+
|
| 160 |
+
|
| 161 |
+
def __getattr__(name: str) -> Any:
|
| 162 |
+
"""Lazily build the Starlette A2A app so importing :data:`app` does not spawn a second ASGI stack."""
|
| 163 |
+
global _starlette_a2a_singleton
|
| 164 |
+
if name == "starlette_a2a_app":
|
| 165 |
+
if _starlette_a2a_singleton is None:
|
| 166 |
+
_starlette_a2a_singleton = to_a2a()
|
| 167 |
+
return _starlette_a2a_singleton
|
| 168 |
+
raise AttributeError(f"module {__name__!r} has no attribute {name!r}")
|
| 169 |
+
|
| 170 |
+
|
| 171 |
+
# ---------------------------------------------------------------------------
|
| 172 |
+
# FastAPI composite app: health, legacy /returns/process, direct tool JSON, + A2A
|
| 173 |
+
# ---------------------------------------------------------------------------
|
| 174 |
+
|
| 175 |
+
|
| 176 |
+
class ReturnsProcessBody(BaseModel):
|
| 177 |
+
customer_id: str
|
| 178 |
+
message: str
|
| 179 |
+
|
| 180 |
+
|
| 181 |
+
class CheckEligibilityBody(BaseModel):
|
| 182 |
+
order_number: str
|
| 183 |
+
|
| 184 |
+
|
| 185 |
+
class InitiateReturnBody(BaseModel):
|
| 186 |
+
order_number: str
|
| 187 |
+
reason: str = ""
|
| 188 |
+
|
| 189 |
+
|
| 190 |
+
@asynccontextmanager
|
| 191 |
+
async def _lifespan(app: FastAPI):
|
| 192 |
+
agent = build_returns_llm_agent()
|
| 193 |
+
public_base = (os.getenv("RETURNS_A2A_PUBLIC_URL") or "http://127.0.0.1:8081").rstrip("/")
|
| 194 |
+
rpc_url = f"{public_base}/"
|
| 195 |
+
|
| 196 |
+
card_builder = AgentCardBuilder(agent=agent, rpc_url=rpc_url)
|
| 197 |
+
agent_card = await card_builder.build()
|
| 198 |
+
|
| 199 |
+
async def _create_runner() -> Runner:
|
| 200 |
+
return Runner(
|
| 201 |
+
app_name=agent.name or "returns_service",
|
| 202 |
+
agent=agent,
|
| 203 |
+
artifact_service=InMemoryArtifactService(),
|
| 204 |
+
session_service=InMemorySessionService(),
|
| 205 |
+
memory_service=InMemoryMemoryService(),
|
| 206 |
+
credential_service=InMemoryCredentialService(),
|
| 207 |
+
)
|
| 208 |
+
|
| 209 |
+
task_store = InMemoryTaskStore()
|
| 210 |
+
push_config_store = InMemoryPushNotificationConfigStore()
|
| 211 |
+
executor = A2aAgentExecutor(runner=_create_runner)
|
| 212 |
+
handler = DefaultRequestHandler(
|
| 213 |
+
agent_executor=executor,
|
| 214 |
+
task_store=task_store,
|
| 215 |
+
push_config_store=push_config_store,
|
| 216 |
+
)
|
| 217 |
+
a2a_http = A2AFastAPIApplication(agent_card=agent_card, http_handler=handler)
|
| 218 |
+
a2a_http.add_routes_to_app(app)
|
| 219 |
+
yield
|
| 220 |
+
|
| 221 |
+
|
| 222 |
+
app = FastAPI(
|
| 223 |
+
title="Returns Service",
|
| 224 |
+
description="Returns A2A agent + legacy HTTP helpers.",
|
| 225 |
+
lifespan=_lifespan,
|
| 226 |
+
)
|
| 227 |
+
|
| 228 |
+
|
| 229 |
+
@app.get("/health")
|
| 230 |
+
async def health() -> dict[str, str]:
|
| 231 |
+
return {"status": "ok"}
|
| 232 |
+
|
| 233 |
+
|
| 234 |
+
@app.post("/returns/process")
|
| 235 |
+
async def process_return(payload: ReturnsProcessBody) -> dict[str, str]:
|
| 236 |
+
"""Legacy endpoint used by ``ReturnsRemoteAgent`` in the main API."""
|
| 237 |
+
return {
|
| 238 |
+
"result": (
|
| 239 |
+
f"[ReturnsService] Return request noted for `{payload.customer_id}` "
|
| 240 |
+
f"with message: '{payload.message}'. "
|
| 241 |
+
"For structured eligibility/initiation use the A2A agent or /tools/* routes."
|
| 242 |
+
)
|
| 243 |
+
}
|
| 244 |
+
|
| 245 |
+
|
| 246 |
+
@app.post("/tools/check_return_eligibility")
|
| 247 |
+
async def tools_check_eligibility(body: CheckEligibilityBody) -> dict[str, Any]:
|
| 248 |
+
"""Direct HTTP binding of :func:`check_return_eligibility` (no LLM)."""
|
| 249 |
+
return check_return_eligibility(body.order_number)
|
| 250 |
+
|
| 251 |
+
|
| 252 |
+
@app.post("/tools/initiate_return")
|
| 253 |
+
async def tools_initiate_return(body: InitiateReturnBody) -> dict[str, Any]:
|
| 254 |
+
"""Direct HTTP binding of :func:`initiate_return` (no LLM)."""
|
| 255 |
+
return initiate_return(body.order_number, body.reason)
|
| 256 |
+
|
| 257 |
+
|
| 258 |
+
def main() -> None:
|
| 259 |
+
"""CLI entry: ``python -m servers.returns_service.main``."""
|
| 260 |
+
import uvicorn
|
| 261 |
+
|
| 262 |
+
host = os.getenv("RETURNS_SERVICE_HOST", "127.0.0.1")
|
| 263 |
+
port = int(os.getenv("RETURNS_SERVICE_PORT", "8081"))
|
| 264 |
+
uvicorn.run(
|
| 265 |
+
"servers.returns_service.main:app",
|
| 266 |
+
host=host,
|
| 267 |
+
port=port,
|
| 268 |
+
reload=False,
|
| 269 |
+
)
|
| 270 |
+
|
| 271 |
+
|
| 272 |
+
if __name__ == "__main__":
|
| 273 |
+
main()
|
multi_agent_customer_support/sql/fix_rls_and_verify.sql
ADDED
|
@@ -0,0 +1,39 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
-- ============================================================
|
| 2 |
+
-- One-time fix: Row Level Security for anon/API access + verify counts
|
| 3 |
+
-- Run in Supabase SQL Editor if tables already exist but the JS/Python
|
| 4 |
+
-- client sees 0 rows or insert fails with policy errors.
|
| 5 |
+
-- ============================================================
|
| 6 |
+
|
| 7 |
+
alter table customers enable row level security;
|
| 8 |
+
alter table orders enable row level security;
|
| 9 |
+
alter table support_tickets enable row level security;
|
| 10 |
+
|
| 11 |
+
drop policy if exists "dev_api_all_customers" on public.customers;
|
| 12 |
+
drop policy if exists "dev_api_all_orders" on public.orders;
|
| 13 |
+
drop policy if exists "dev_api_all_support_tickets" on public.support_tickets;
|
| 14 |
+
|
| 15 |
+
create policy "dev_api_all_customers"
|
| 16 |
+
on public.customers
|
| 17 |
+
for all
|
| 18 |
+
to anon, authenticated
|
| 19 |
+
using (true)
|
| 20 |
+
with check (true);
|
| 21 |
+
|
| 22 |
+
create policy "dev_api_all_orders"
|
| 23 |
+
on public.orders
|
| 24 |
+
for all
|
| 25 |
+
to anon, authenticated
|
| 26 |
+
using (true)
|
| 27 |
+
with check (true);
|
| 28 |
+
|
| 29 |
+
create policy "dev_api_all_support_tickets"
|
| 30 |
+
on public.support_tickets
|
| 31 |
+
for all
|
| 32 |
+
to anon, authenticated
|
| 33 |
+
using (true)
|
| 34 |
+
with check (true);
|
| 35 |
+
|
| 36 |
+
select
|
| 37 |
+
(select count(*)::bigint from customers) as customers,
|
| 38 |
+
(select count(*)::bigint from orders) as orders,
|
| 39 |
+
(select count(*)::bigint from support_tickets) as support_tickets;
|
multi_agent_customer_support/sql/schema_and_seed.sql
ADDED
|
@@ -0,0 +1,155 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
-- ============================================================
|
| 2 |
+
-- Multi-Agent Customer Support - Schema + Seed (Supabase Postgres)
|
| 3 |
+
-- Paste into: Supabase Dashboard → SQL Editor → Run
|
| 4 |
+
-- ============================================================
|
| 5 |
+
|
| 6 |
+
create extension if not exists pgcrypto;
|
| 7 |
+
|
| 8 |
+
-- Optional: clean slate (remove if you already have production data!)
|
| 9 |
+
drop table if exists support_tickets cascade;
|
| 10 |
+
drop table if exists orders cascade;
|
| 11 |
+
drop table if exists customers cascade;
|
| 12 |
+
|
| 13 |
+
-- =====================
|
| 14 |
+
-- 1) TABLE DEFINITIONS
|
| 15 |
+
-- =====================
|
| 16 |
+
|
| 17 |
+
create table customers (
|
| 18 |
+
id uuid primary key default gen_random_uuid(),
|
| 19 |
+
name text not null,
|
| 20 |
+
email text not null unique,
|
| 21 |
+
created_at timestamptz not null default now()
|
| 22 |
+
);
|
| 23 |
+
|
| 24 |
+
create table orders (
|
| 25 |
+
id uuid primary key default gen_random_uuid(),
|
| 26 |
+
customer_id uuid not null references customers(id),
|
| 27 |
+
order_number text not null unique,
|
| 28 |
+
total_amount numeric not null,
|
| 29 |
+
status text not null,
|
| 30 |
+
created_at timestamptz not null default now()
|
| 31 |
+
);
|
| 32 |
+
|
| 33 |
+
create table support_tickets (
|
| 34 |
+
id uuid primary key default gen_random_uuid(),
|
| 35 |
+
customer_id uuid not null references customers(id),
|
| 36 |
+
order_id uuid references orders(id),
|
| 37 |
+
category text not null,
|
| 38 |
+
status text not null,
|
| 39 |
+
description text not null,
|
| 40 |
+
created_at timestamptz not null default now()
|
| 41 |
+
);
|
| 42 |
+
|
| 43 |
+
create index idx_orders_customer_id on orders(customer_id);
|
| 44 |
+
create index idx_tickets_customer_id on support_tickets(customer_id);
|
| 45 |
+
create index idx_tickets_order_id on support_tickets(order_id);
|
| 46 |
+
create index idx_tickets_category_status on support_tickets(category, status);
|
| 47 |
+
|
| 48 |
+
-- =================
|
| 49 |
+
-- 2) SEEDING DATA
|
| 50 |
+
-- =================
|
| 51 |
+
|
| 52 |
+
insert into customers (id, name, email, created_at) values
|
| 53 |
+
('11111111-1111-1111-1111-111111111101', 'Ava Thompson', 'ava.thompson@example.com', now() - interval '90 days'),
|
| 54 |
+
('11111111-1111-1111-1111-111111111102', 'Liam Carter', 'liam.carter@example.com', now() - interval '88 days'),
|
| 55 |
+
('11111111-1111-1111-1111-111111111103', 'Noah Bennett', 'noah.bennett@example.com', now() - interval '76 days'),
|
| 56 |
+
('11111111-1111-1111-1111-111111111104', 'Emma Rodriguez', 'emma.rodriguez@example.com', now() - interval '73 days'),
|
| 57 |
+
('11111111-1111-1111-1111-111111111105', 'Sophia Nguyen', 'sophia.nguyen@example.com', now() - interval '69 days'),
|
| 58 |
+
('11111111-1111-1111-1111-111111111106', 'Mason Patel', 'mason.patel@example.com', now() - interval '62 days'),
|
| 59 |
+
('11111111-1111-1111-1111-111111111107', 'Isabella Kim', 'isabella.kim@example.com', now() - interval '55 days'),
|
| 60 |
+
('11111111-1111-1111-1111-111111111108', 'Ethan Brooks', 'ethan.brooks@example.com', now() - interval '49 days'),
|
| 61 |
+
('11111111-1111-1111-1111-111111111109', 'Olivia Davis', 'olivia.davis@example.com', now() - interval '35 days'),
|
| 62 |
+
('11111111-1111-1111-1111-111111111110', 'Lucas Garcia', 'lucas.garcia@example.com', now() - interval '21 days');
|
| 63 |
+
|
| 64 |
+
insert into orders (id, customer_id, order_number, total_amount, status, created_at) values
|
| 65 |
+
('22222222-2222-2222-2222-222222222201', '11111111-1111-1111-1111-111111111101', 'ORD-2026-0001', 129.99, 'paid', now() - interval '40 days'),
|
| 66 |
+
('22222222-2222-2222-2222-222222222202', '11111111-1111-1111-1111-111111111102', 'ORD-2026-0002', 79.50, 'shipped', now() - interval '38 days'),
|
| 67 |
+
('22222222-2222-2222-2222-222222222203', '11111111-1111-1111-1111-111111111103', 'ORD-2026-0003', 249.00, 'paid', now() - interval '36 days'),
|
| 68 |
+
('22222222-2222-2222-2222-222222222204', '11111111-1111-1111-1111-111111111104', 'ORD-2026-0004', 54.25, 'refunded', now() - interval '33 days'),
|
| 69 |
+
('22222222-2222-2222-2222-222222222205', '11111111-1111-1111-1111-111111111105', 'ORD-2026-0005', 310.75, 'shipped', now() - interval '30 days'),
|
| 70 |
+
('22222222-2222-2222-2222-222222222206', '11111111-1111-1111-1111-111111111106', 'ORD-2026-0006', 18.99, 'paid', now() - interval '27 days'),
|
| 71 |
+
('22222222-2222-2222-2222-222222222207', '11111111-1111-1111-1111-111111111107', 'ORD-2026-0007', 97.40, 'paid', now() - interval '24 days'),
|
| 72 |
+
('22222222-2222-2222-2222-222222222208', '11111111-1111-1111-1111-111111111108', 'ORD-2026-0008', 145.00, 'shipped', now() - interval '20 days'),
|
| 73 |
+
('22222222-2222-2222-2222-222222222209', '11111111-1111-1111-1111-111111111109', 'ORD-2026-0009', 220.15, 'paid', now() - interval '17 days'),
|
| 74 |
+
('22222222-2222-2222-2222-222222222210', '11111111-1111-1111-1111-111111111110', 'ORD-2026-0010', 65.00, 'refunded', now() - interval '14 days'),
|
| 75 |
+
('22222222-2222-2222-2222-222222222211', '11111111-1111-1111-1111-111111111101', 'ORD-2026-0011', 33.49, 'paid', now() - interval '11 days'),
|
| 76 |
+
('22222222-2222-2222-2222-222222222212', '11111111-1111-1111-1111-111111111105', 'ORD-2026-0012', 412.00, 'shipped', now() - interval '7 days');
|
| 77 |
+
|
| 78 |
+
insert into support_tickets (id, customer_id, order_id, category, status, description, created_at) values
|
| 79 |
+
('33333333-3333-3333-3333-333333333301', '11111111-1111-1111-1111-111111111101', '22222222-2222-2222-2222-222222222201', 'billing', 'open',
|
| 80 |
+
'Customer reports duplicate charge for order ORD-2026-0001.', now() - interval '10 days'),
|
| 81 |
+
|
| 82 |
+
('33333333-3333-3333-3333-333333333302', '11111111-1111-1111-1111-111111111102', '22222222-2222-2222-2222-222222222202', 'returns', 'in_progress',
|
| 83 |
+
'Wrong size delivered; customer requested exchange and return label.', now() - interval '9 days'),
|
| 84 |
+
|
| 85 |
+
('33333333-3333-3333-3333-333333333303', '11111111-1111-1111-1111-111111111103', '22222222-2222-2222-2222-222222222203', 'general', 'resolved',
|
| 86 |
+
'Asked for updated shipping ETA and tracking clarification.', now() - interval '8 days'),
|
| 87 |
+
|
| 88 |
+
('33333333-3333-3333-3333-333333333304', '11111111-1111-1111-1111-111111111104', '22222222-2222-2222-2222-222222222204', 'billing', 'resolved',
|
| 89 |
+
'Refund completed but customer did not see bank settlement yet.', now() - interval '7 days'),
|
| 90 |
+
|
| 91 |
+
('33333333-3333-3333-3333-333333333305', '11111111-1111-1111-1111-111111111105', '22222222-2222-2222-2222-222222222205', 'returns', 'escalated',
|
| 92 |
+
'Item arrived damaged; customer requested full refund with photo evidence.', now() - interval '6 days'),
|
| 93 |
+
|
| 94 |
+
('33333333-3333-3333-3333-333333333306', '11111111-1111-1111-1111-111111111106', '22222222-2222-2222-2222-222222222206', 'billing', 'in_progress',
|
| 95 |
+
'Promo code was not applied at checkout; requesting partial refund.', now() - interval '5 days'),
|
| 96 |
+
|
| 97 |
+
('33333333-3333-3333-3333-333333333307', '11111111-1111-1111-1111-111111111107', '22222222-2222-2222-2222-222222222207', 'general', 'open',
|
| 98 |
+
'Customer wants to update shipping address after placing the order.', now() - interval '4 days'),
|
| 99 |
+
|
| 100 |
+
('33333333-3333-3333-3333-333333333308', '11111111-1111-1111-1111-111111111108', '22222222-2222-2222-2222-222222222208', 'returns', 'open',
|
| 101 |
+
'Return requested for unopened item within return window.', now() - interval '3 days'),
|
| 102 |
+
|
| 103 |
+
('33333333-3333-3333-3333-333333333309', '11111111-1111-1111-1111-111111111109', '22222222-2222-2222-2222-222222222209', 'billing', 'escalated',
|
| 104 |
+
'Customer states tax amount appears incorrect for shipping destination.', now() - interval '2 days'),
|
| 105 |
+
|
| 106 |
+
('33333333-3333-3333-3333-333333333310', '11111111-1111-1111-1111-111111111110', '22222222-2222-2222-2222-222222222210', 'returns', 'resolved',
|
| 107 |
+
'Refund was issued after returned item passed warehouse inspection.', now() - interval '36 hours'),
|
| 108 |
+
|
| 109 |
+
('33333333-3333-3333-3333-333333333311', '11111111-1111-1111-1111-111111111101', '22222222-2222-2222-2222-222222222211', 'general', 'open',
|
| 110 |
+
'Asked whether order can be bundled with a recent purchase.', now() - interval '18 hours'),
|
| 111 |
+
|
| 112 |
+
('33333333-3333-3333-3333-333333333312', '11111111-1111-1111-1111-111111111105', '22222222-2222-2222-2222-222222222212', 'billing', 'open',
|
| 113 |
+
'Invoice email missing line-item breakdown; customer requested corrected invoice.', now() - interval '6 hours');
|
| 114 |
+
|
| 115 |
+
-- =================
|
| 116 |
+
-- 3) RLS (dev)
|
| 117 |
+
-- =================
|
| 118 |
+
-- PostgREST uses the `anon` / `authenticated` roles. Without policies, SELECT/INSERT
|
| 119 |
+
-- from the Supabase client (anon key) will see 0 rows or get 42501 errors.
|
| 120 |
+
-- Replace these with tighter policies before production.
|
| 121 |
+
|
| 122 |
+
alter table customers enable row level security;
|
| 123 |
+
alter table orders enable row level security;
|
| 124 |
+
alter table support_tickets enable row level security;
|
| 125 |
+
|
| 126 |
+
drop policy if exists "dev_api_all_customers" on public.customers;
|
| 127 |
+
drop policy if exists "dev_api_all_orders" on public.orders;
|
| 128 |
+
drop policy if exists "dev_api_all_support_tickets" on public.support_tickets;
|
| 129 |
+
|
| 130 |
+
create policy "dev_api_all_customers"
|
| 131 |
+
on public.customers
|
| 132 |
+
for all
|
| 133 |
+
to anon, authenticated
|
| 134 |
+
using (true)
|
| 135 |
+
with check (true);
|
| 136 |
+
|
| 137 |
+
create policy "dev_api_all_orders"
|
| 138 |
+
on public.orders
|
| 139 |
+
for all
|
| 140 |
+
to anon, authenticated
|
| 141 |
+
using (true)
|
| 142 |
+
with check (true);
|
| 143 |
+
|
| 144 |
+
create policy "dev_api_all_support_tickets"
|
| 145 |
+
on public.support_tickets
|
| 146 |
+
for all
|
| 147 |
+
to anon, authenticated
|
| 148 |
+
using (true)
|
| 149 |
+
with check (true);
|
| 150 |
+
|
| 151 |
+
-- SQL Editor will show THIS result (otherwise "Success. No rows returned" is normal):
|
| 152 |
+
select
|
| 153 |
+
(select count(*)::bigint from customers) as customers,
|
| 154 |
+
(select count(*)::bigint from orders) as orders,
|
| 155 |
+
(select count(*)::bigint from support_tickets) as support_tickets;
|
multi_agent_customer_support/src/__init__.py
ADDED
|
@@ -0,0 +1 @@
|
|
|
|
|
|
|
| 1 |
+
"""Top-level package for the multi-agent customer support app."""
|
multi_agent_customer_support/src/agents/__init__.py
ADDED
|
@@ -0,0 +1 @@
|
|
|
|
|
|
|
| 1 |
+
"""Agent modules for routing and domain-specific support."""
|
multi_agent_customer_support/src/agents/adk_runtime.py
ADDED
|
@@ -0,0 +1,111 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
"""Shared helpers for running ADK ``LlmAgent`` instances with ``Runner`` (stdio-free)."""
|
| 2 |
+
|
| 3 |
+
from __future__ import annotations
|
| 4 |
+
|
| 5 |
+
import logging
|
| 6 |
+
import uuid
|
| 7 |
+
from typing import TypeVar
|
| 8 |
+
|
| 9 |
+
from google.adk.agents.base_agent import BaseAgent
|
| 10 |
+
from google.adk.artifacts.in_memory_artifact_service import InMemoryArtifactService
|
| 11 |
+
from google.adk.auth.credential_service.in_memory_credential_service import (
|
| 12 |
+
InMemoryCredentialService,
|
| 13 |
+
)
|
| 14 |
+
from google.adk.memory.in_memory_memory_service import InMemoryMemoryService
|
| 15 |
+
from google.adk.runners import Runner
|
| 16 |
+
from google.adk.sessions.in_memory_session_service import InMemorySessionService
|
| 17 |
+
from google.genai import types
|
| 18 |
+
from pydantic import BaseModel
|
| 19 |
+
|
| 20 |
+
logger = logging.getLogger(__name__)
|
| 21 |
+
|
| 22 |
+
TModel = TypeVar("TModel", bound=BaseModel)
|
| 23 |
+
|
| 24 |
+
|
| 25 |
+
def genai_api_configured() -> bool:
|
| 26 |
+
"""True when Gemini Developer API keys are present (same convention as google-genai)."""
|
| 27 |
+
import os
|
| 28 |
+
|
| 29 |
+
return bool(os.getenv("GOOGLE_API_KEY") or os.getenv("GEMINI_API_KEY"))
|
| 30 |
+
|
| 31 |
+
|
| 32 |
+
async def run_llm_agent_once(
|
| 33 |
+
*,
|
| 34 |
+
agent: BaseAgent,
|
| 35 |
+
user_message: str,
|
| 36 |
+
app_name: str,
|
| 37 |
+
user_id: str | None = None,
|
| 38 |
+
) -> str:
|
| 39 |
+
"""
|
| 40 |
+
Run a single-turn conversation: one user message in, final model text out.
|
| 41 |
+
|
| 42 |
+
Uses an ephemeral session id so concurrent FastAPI requests do not share history.
|
| 43 |
+
"""
|
| 44 |
+
session_service = InMemorySessionService()
|
| 45 |
+
runner = Runner(
|
| 46 |
+
app_name=app_name,
|
| 47 |
+
agent=agent,
|
| 48 |
+
artifact_service=InMemoryArtifactService(),
|
| 49 |
+
session_service=session_service,
|
| 50 |
+
memory_service=InMemoryMemoryService(),
|
| 51 |
+
credential_service=InMemoryCredentialService(),
|
| 52 |
+
auto_create_session=True,
|
| 53 |
+
)
|
| 54 |
+
session_id = str(uuid.uuid4())
|
| 55 |
+
uid = user_id or "anonymous"
|
| 56 |
+
|
| 57 |
+
content = types.Content(
|
| 58 |
+
role="user",
|
| 59 |
+
parts=[types.Part(text=user_message)],
|
| 60 |
+
)
|
| 61 |
+
|
| 62 |
+
final_text = ""
|
| 63 |
+
async for event in runner.run_async(
|
| 64 |
+
user_id=uid,
|
| 65 |
+
session_id=session_id,
|
| 66 |
+
new_message=content,
|
| 67 |
+
):
|
| 68 |
+
if not event.is_final_response():
|
| 69 |
+
continue
|
| 70 |
+
if not event.content or not event.content.parts:
|
| 71 |
+
continue
|
| 72 |
+
chunk = "".join(
|
| 73 |
+
part.text
|
| 74 |
+
for part in event.content.parts
|
| 75 |
+
if part.text and not getattr(part, "thought", False)
|
| 76 |
+
)
|
| 77 |
+
if chunk.strip():
|
| 78 |
+
final_text = chunk
|
| 79 |
+
|
| 80 |
+
return final_text.strip()
|
| 81 |
+
|
| 82 |
+
|
| 83 |
+
async def run_router_structured(
|
| 84 |
+
*,
|
| 85 |
+
agent: BaseAgent,
|
| 86 |
+
user_message: str,
|
| 87 |
+
schema_type: type[TModel],
|
| 88 |
+
app_name: str = "router",
|
| 89 |
+
) -> TModel | None:
|
| 90 |
+
"""
|
| 91 |
+
Run router agent expecting structured JSON matching ``schema_type``.
|
| 92 |
+
|
| 93 |
+
Returns ``None`` if the model returns empty/unparseable output (caller should fall back).
|
| 94 |
+
"""
|
| 95 |
+
raw = await run_llm_agent_once(
|
| 96 |
+
agent=agent,
|
| 97 |
+
user_message=user_message,
|
| 98 |
+
app_name=app_name,
|
| 99 |
+
)
|
| 100 |
+
if not raw:
|
| 101 |
+
return None
|
| 102 |
+
try:
|
| 103 |
+
return schema_type.model_validate_json(raw)
|
| 104 |
+
except Exception as exc:
|
| 105 |
+
logger.warning(
|
| 106 |
+
"Failed to parse router output as %s: %s — raw: %s",
|
| 107 |
+
schema_type,
|
| 108 |
+
exc,
|
| 109 |
+
raw[:500],
|
| 110 |
+
)
|
| 111 |
+
return None
|
multi_agent_customer_support/src/agents/billing_agent.py
ADDED
|
@@ -0,0 +1,124 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
"""Billing specialist agent: ADK ``LlmAgent`` + Supabase MCP tool functions (same impl as MCP server)."""
|
| 2 |
+
|
| 3 |
+
from __future__ import annotations
|
| 4 |
+
|
| 5 |
+
import json
|
| 6 |
+
import os
|
| 7 |
+
from typing import Any
|
| 8 |
+
|
| 9 |
+
from google.adk.agents.llm_agent import LlmAgent
|
| 10 |
+
from google.adk.tools.function_tool import FunctionTool
|
| 11 |
+
|
| 12 |
+
from src.mcp.supabase_mcp_server import get_billing_info, get_support_tickets
|
| 13 |
+
|
| 14 |
+
from .adk_runtime import genai_api_configured, run_llm_agent_once
|
| 15 |
+
from .customer_context import resolve_customer_email
|
| 16 |
+
|
| 17 |
+
|
| 18 |
+
def _billing_tools() -> list[Any]:
|
| 19 |
+
"""Expose MCP-parity tools to the LLM via ADK ``FunctionTool`` wrappers."""
|
| 20 |
+
return [
|
| 21 |
+
FunctionTool(get_billing_info),
|
| 22 |
+
FunctionTool(get_support_tickets),
|
| 23 |
+
]
|
| 24 |
+
|
| 25 |
+
|
| 26 |
+
_BILLING_INSTRUCTION = """You are a billing assistant for an e-commerce company.
|
| 27 |
+
|
| 28 |
+
You have tools that mirror the Supabase MCP server:
|
| 29 |
+
- ``get_billing_info(email)`` — JSON with customer orders (order_number, total_amount, status).
|
| 30 |
+
- ``get_support_tickets(email)`` — JSON list of support tickets.
|
| 31 |
+
|
| 32 |
+
Rules:
|
| 33 |
+
1. The user message includes the **resolved customer email**. Always pass that exact email string to tools.
|
| 34 |
+
2. Call the tools when you need factual data; do not invent amounts or order numbers.
|
| 35 |
+
3. Reply in concise, friendly natural language summarizing billing status and any open billing-related tickets.
|
| 36 |
+
4. If JSON shows ``customer_not_found``, say we could not match an account and ask them to verify their email.
|
| 37 |
+
"""
|
| 38 |
+
|
| 39 |
+
|
| 40 |
+
class BillingAgent:
|
| 41 |
+
"""
|
| 42 |
+
Handles billing-related questions using Gemini + tool calls.
|
| 43 |
+
|
| 44 |
+
Tools implement the same behavior as ``src/mcp/supabase_mcp_server.py`` (stdio MCP is optional;
|
| 45 |
+
in-process calls keep tests and local dev simple).
|
| 46 |
+
"""
|
| 47 |
+
|
| 48 |
+
def __init__(self, model: str | None = None) -> None:
|
| 49 |
+
self._model = model or os.getenv("ADK_MODEL", "gemini-2.5-flash")
|
| 50 |
+
self._agent = LlmAgent(
|
| 51 |
+
name="billing_agent",
|
| 52 |
+
model=self._model,
|
| 53 |
+
instruction=_BILLING_INSTRUCTION,
|
| 54 |
+
tools=_billing_tools(),
|
| 55 |
+
)
|
| 56 |
+
|
| 57 |
+
async def handle(self, customer_id: str, message: str) -> str:
|
| 58 |
+
"""
|
| 59 |
+
Answer a billing question for ``customer_id`` (UUID or email) and user ``message``.
|
| 60 |
+
|
| 61 |
+
Uses the LLM when ``GOOGLE_API_KEY`` / ``GEMINI_API_KEY`` is set; otherwise returns a
|
| 62 |
+
deterministic summary from the same tool functions.
|
| 63 |
+
"""
|
| 64 |
+
email = resolve_customer_email(customer_id)
|
| 65 |
+
if not email:
|
| 66 |
+
return (
|
| 67 |
+
"We could not resolve an email address for this customer id. "
|
| 68 |
+
"Please provide a customer id that exists in our system or use your account email."
|
| 69 |
+
)
|
| 70 |
+
|
| 71 |
+
if not genai_api_configured():
|
| 72 |
+
billing_json = get_billing_info(email)
|
| 73 |
+
tickets_json = get_support_tickets(email)
|
| 74 |
+
return _format_billing_fallback(billing_json, tickets_json, message)
|
| 75 |
+
|
| 76 |
+
user_prompt = (
|
| 77 |
+
f"Resolved customer email (use for tool calls): {email}\n"
|
| 78 |
+
f"Customer id (reference): {customer_id}\n\n"
|
| 79 |
+
f"User question:\n{message}\n"
|
| 80 |
+
)
|
| 81 |
+
return await run_llm_agent_once(
|
| 82 |
+
agent=self._agent,
|
| 83 |
+
user_message=user_prompt,
|
| 84 |
+
app_name="billing",
|
| 85 |
+
)
|
| 86 |
+
|
| 87 |
+
|
| 88 |
+
def _format_billing_fallback(billing_json: str, tickets_json: str, message: str) -> str:
|
| 89 |
+
"""Readable summary without an LLM (offline / CI)."""
|
| 90 |
+
try:
|
| 91 |
+
billing = json.loads(billing_json)
|
| 92 |
+
tickets_payload = json.loads(tickets_json)
|
| 93 |
+
except json.JSONDecodeError:
|
| 94 |
+
return "[BillingAgent] Unable to parse billing data."
|
| 95 |
+
|
| 96 |
+
lines = [
|
| 97 |
+
"[BillingAgent — offline summary]",
|
| 98 |
+
f'Your question: "{message[:200]}"',
|
| 99 |
+
"",
|
| 100 |
+
]
|
| 101 |
+
|
| 102 |
+
if billing.get("error") == "customer_not_found":
|
| 103 |
+
lines.append("No customer record found for that email.")
|
| 104 |
+
return "\n".join(lines)
|
| 105 |
+
|
| 106 |
+
cust = billing.get("customer") or {}
|
| 107 |
+
lines.append(f"Customer: {cust.get('name', 'Unknown')} ({cust.get('email', '')})")
|
| 108 |
+
orders = billing.get("orders") or []
|
| 109 |
+
if not orders:
|
| 110 |
+
lines.append("No orders on file.")
|
| 111 |
+
else:
|
| 112 |
+
lines.append(f"Orders ({len(orders)}):")
|
| 113 |
+
for o in orders[:10]:
|
| 114 |
+
lines.append(
|
| 115 |
+
f" - {o.get('order_number')}: "
|
| 116 |
+
f"amount={o.get('total_amount')}, status={o.get('status')}"
|
| 117 |
+
)
|
| 118 |
+
if len(orders) > 10:
|
| 119 |
+
lines.append(f" … and {len(orders) - 10} more.")
|
| 120 |
+
|
| 121 |
+
tickets = tickets_payload.get("tickets") or []
|
| 122 |
+
lines.append("")
|
| 123 |
+
lines.append(f"Support tickets on file: {len(tickets)}.")
|
| 124 |
+
return "\n".join(lines)
|
multi_agent_customer_support/src/agents/customer_context.py
ADDED
|
@@ -0,0 +1,31 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
"""Resolve end-user email for MCP tools from API ``customer_id`` (UUID or email)."""
|
| 2 |
+
|
| 3 |
+
from __future__ import annotations
|
| 4 |
+
|
| 5 |
+
from src.mcp.supabase_client import SupabaseConfigurationError, get_customer_by_id
|
| 6 |
+
|
| 7 |
+
|
| 8 |
+
def resolve_customer_email(customer_id: str) -> str | None:
|
| 9 |
+
"""
|
| 10 |
+
MCP tools expect an email.
|
| 11 |
+
|
| 12 |
+
- If ``customer_id`` looks like an email (contains ``@``), use it as-is.
|
| 13 |
+
- Otherwise treat it as ``customers.id`` and look up ``email`` from Supabase.
|
| 14 |
+
|
| 15 |
+
Returns ``None`` if lookup fails or email is missing.
|
| 16 |
+
"""
|
| 17 |
+
raw = (customer_id or "").strip()
|
| 18 |
+
if not raw:
|
| 19 |
+
return None
|
| 20 |
+
if "@" in raw:
|
| 21 |
+
return raw
|
| 22 |
+
|
| 23 |
+
try:
|
| 24 |
+
row = get_customer_by_id(raw)
|
| 25 |
+
except (SupabaseConfigurationError, ValueError, RuntimeError):
|
| 26 |
+
return None
|
| 27 |
+
|
| 28 |
+
if not row:
|
| 29 |
+
return None
|
| 30 |
+
email = row.get("email")
|
| 31 |
+
return str(email).strip() if email else None
|
multi_agent_customer_support/src/agents/returns_remote_agent.py
ADDED
|
@@ -0,0 +1,166 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
"""Remote returns integration via ADK ``RemoteA2aAgent`` (A2A JSON-RPC to the returns service).
|
| 2 |
+
|
| 3 |
+
The returns microservice (``servers/returns_service/main.py``) exposes an ADK ``LlmAgent`` over A2A
|
| 4 |
+
with tools ``check_return_eligibility`` and ``initiate_return``. This module wraps that remote
|
| 5 |
+
agent so the rest of the app can call those tools without speaking JSON-RPC directly.
|
| 6 |
+
|
| 7 |
+
**RouterAgent usage**
|
| 8 |
+
|
| 9 |
+
``RouterAgent`` routes returns-related NL queries here via :meth:`handle`::
|
| 10 |
+
|
| 11 |
+
# Inside RouterAgent.route (returns branch):
|
| 12 |
+
return await self.returns.handle(customer_id, message)
|
| 13 |
+
|
| 14 |
+
For **structured** calls (tests, future tooling), use :meth:`check_return_eligibility` and
|
| 15 |
+
:meth:`initiate_return` — they send explicit instructions over the same A2A link so the *remote*
|
| 16 |
+
model invokes the matching tool and we parse JSON from the reply.
|
| 17 |
+
|
| 18 |
+
**Requirements**
|
| 19 |
+
|
| 20 |
+
- Returns service running (default ``http://127.0.0.1:8081``).
|
| 21 |
+
- Agent card reachable at ``{base_url}/.well-known/agent-card.json`` (or set ``RETURNS_A2A_AGENT_CARD_URL``).
|
| 22 |
+
- Remote service must have ``GEMINI_API_KEY`` / ``GOOGLE_API_KEY`` so its LlmAgent can run tools.
|
| 23 |
+
"""
|
| 24 |
+
|
| 25 |
+
from __future__ import annotations
|
| 26 |
+
|
| 27 |
+
import json
|
| 28 |
+
import logging
|
| 29 |
+
import os
|
| 30 |
+
import re
|
| 31 |
+
from typing import Any
|
| 32 |
+
|
| 33 |
+
from google.adk.agents.remote_a2a_agent import RemoteA2aAgent
|
| 34 |
+
|
| 35 |
+
from .adk_runtime import run_llm_agent_once
|
| 36 |
+
|
| 37 |
+
logger = logging.getLogger(__name__)
|
| 38 |
+
|
| 39 |
+
# Stable name for Runner / events (must match RemoteA2aAgent instance name for logging clarity).
|
| 40 |
+
_RETURNS_REMOTE_NAME = "returns_service_a2a"
|
| 41 |
+
|
| 42 |
+
_APP_NAME = "returns_a2a_client"
|
| 43 |
+
|
| 44 |
+
|
| 45 |
+
def _default_agent_card_url(base_url: str) -> str:
|
| 46 |
+
"""Resolve Agent Card URL; override with ``RETURNS_A2A_AGENT_CARD_URL`` for proxies."""
|
| 47 |
+
explicit = (os.getenv("RETURNS_A2A_AGENT_CARD_URL") or "").strip()
|
| 48 |
+
if explicit:
|
| 49 |
+
return explicit
|
| 50 |
+
return f"{base_url.rstrip('/')}/.well-known/agent-card.json"
|
| 51 |
+
|
| 52 |
+
|
| 53 |
+
def _parse_json_object(text: str) -> dict[str, Any]:
|
| 54 |
+
"""Best-effort parse of a single JSON object from model text (may include markdown fences)."""
|
| 55 |
+
raw = (text or "").strip()
|
| 56 |
+
if not raw:
|
| 57 |
+
raise ValueError("empty response from remote A2A agent")
|
| 58 |
+
|
| 59 |
+
if raw.startswith("```"):
|
| 60 |
+
lines = raw.splitlines()
|
| 61 |
+
if lines and lines[0].startswith("```"):
|
| 62 |
+
lines = lines[1:]
|
| 63 |
+
if lines and lines[-1].strip().startswith("```"):
|
| 64 |
+
lines = lines[:-1]
|
| 65 |
+
raw = "\n".join(lines).strip()
|
| 66 |
+
|
| 67 |
+
try:
|
| 68 |
+
out = json.loads(raw)
|
| 69 |
+
if isinstance(out, dict):
|
| 70 |
+
return out
|
| 71 |
+
except json.JSONDecodeError:
|
| 72 |
+
pass
|
| 73 |
+
|
| 74 |
+
m = re.search(r"\{[\s\S]*\}", raw)
|
| 75 |
+
if m:
|
| 76 |
+
return json.loads(m.group(0))
|
| 77 |
+
|
| 78 |
+
raise ValueError(f"no JSON object found in response: {raw[:300]}")
|
| 79 |
+
|
| 80 |
+
|
| 81 |
+
class ReturnsRemoteAgent:
|
| 82 |
+
"""
|
| 83 |
+
Client for the returns microservice using ``RemoteA2aAgent``.
|
| 84 |
+
|
| 85 |
+
``base_url`` is the HTTP origin of the service (e.g. ``http://127.0.0.1:8081``), *not* the
|
| 86 |
+
JSON-RPC path — the Agent Card URL is derived by :func:`_default_agent_card_url`.
|
| 87 |
+
"""
|
| 88 |
+
|
| 89 |
+
def __init__(self, base_url: str) -> None:
|
| 90 |
+
self.base_url = base_url.rstrip("/")
|
| 91 |
+
card_url = _default_agent_card_url(self.base_url)
|
| 92 |
+
self._remote = RemoteA2aAgent(
|
| 93 |
+
name=_RETURNS_REMOTE_NAME,
|
| 94 |
+
agent_card=card_url,
|
| 95 |
+
description="Remote returns A2A agent (eligibility + initiate return tools)",
|
| 96 |
+
)
|
| 97 |
+
|
| 98 |
+
async def check_return_eligibility(self, order_number: str) -> dict[str, Any]:
|
| 99 |
+
"""
|
| 100 |
+
Ask the remote agent to run ``check_return_eligibility`` for ``order_number``.
|
| 101 |
+
|
| 102 |
+
Returns a dict with at least ``eligible`` and ``reason`` (from the remote tool output).
|
| 103 |
+
"""
|
| 104 |
+
prompt = (
|
| 105 |
+
"You must call the tool named check_return_eligibility exactly once with the "
|
| 106 |
+
f"given order_number.\n\norder_number: {order_number!r}\n\n"
|
| 107 |
+
"After the tool returns, reply with nothing except a single JSON object copying "
|
| 108 |
+
'the tool result: {"eligible": <bool>, "reason": "<string>"}. '
|
| 109 |
+
"No markdown, no explanation."
|
| 110 |
+
)
|
| 111 |
+
text = await run_llm_agent_once(
|
| 112 |
+
agent=self._remote,
|
| 113 |
+
user_message=prompt,
|
| 114 |
+
app_name=_APP_NAME,
|
| 115 |
+
)
|
| 116 |
+
try:
|
| 117 |
+
data = _parse_json_object(text)
|
| 118 |
+
except (json.JSONDecodeError, ValueError) as exc:
|
| 119 |
+
logger.warning("Failed to parse eligibility JSON: %s — raw: %s", exc, text[:500])
|
| 120 |
+
return {"error": "parse_failed", "detail": str(exc), "raw": text[:2000]}
|
| 121 |
+
return data
|
| 122 |
+
|
| 123 |
+
async def initiate_return(self, order_number: str, reason: str) -> dict[str, Any]:
|
| 124 |
+
"""
|
| 125 |
+
Ask the remote agent to run ``initiate_return`` for ``order_number`` and ``reason``.
|
| 126 |
+
|
| 127 |
+
Returns a dict with ``return_id``, ``status``, and ``message`` when parsing succeeds.
|
| 128 |
+
"""
|
| 129 |
+
prompt = (
|
| 130 |
+
"You must call the tool named initiate_return exactly once with:\n"
|
| 131 |
+
f" order_number: {order_number!r}\n"
|
| 132 |
+
f" reason: {reason!r}\n\n"
|
| 133 |
+
"After the tool returns, reply with nothing except a single JSON object copying "
|
| 134 |
+
'the tool result: {"return_id": "<string>", "status": "initiated", "message": "<string>"}. '
|
| 135 |
+
"No markdown, no explanation."
|
| 136 |
+
)
|
| 137 |
+
text = await run_llm_agent_once(
|
| 138 |
+
agent=self._remote,
|
| 139 |
+
user_message=prompt,
|
| 140 |
+
app_name=_APP_NAME,
|
| 141 |
+
)
|
| 142 |
+
try:
|
| 143 |
+
data = _parse_json_object(text)
|
| 144 |
+
except (json.JSONDecodeError, ValueError) as exc:
|
| 145 |
+
logger.warning("Failed to parse initiate_return JSON: %s — raw: %s", exc, text[:500])
|
| 146 |
+
return {"error": "parse_failed", "detail": str(exc), "raw": text[:2000]}
|
| 147 |
+
return data
|
| 148 |
+
|
| 149 |
+
async def handle(self, customer_id: str, message: str) -> str:
|
| 150 |
+
"""
|
| 151 |
+
Natural-language entry point used by **RouterAgent** for the returns branch.
|
| 152 |
+
|
| 153 |
+
Forwards ``customer_id`` and the user ``message`` to the remote returns agent over A2A
|
| 154 |
+
(same JSON-RPC channel as structured methods, without forcing JSON-only output).
|
| 155 |
+
"""
|
| 156 |
+
prompt = (
|
| 157 |
+
f"Customer id: {customer_id}\n\n"
|
| 158 |
+
f"User message:\n{message}\n\n"
|
| 159 |
+
"Use the returns tools as needed (check_return_eligibility, initiate_return) "
|
| 160 |
+
"and answer helpfully."
|
| 161 |
+
)
|
| 162 |
+
return await run_llm_agent_once(
|
| 163 |
+
agent=self._remote,
|
| 164 |
+
user_message=prompt,
|
| 165 |
+
app_name=_APP_NAME,
|
| 166 |
+
)
|
multi_agent_customer_support/src/agents/router_agent.py
ADDED
|
@@ -0,0 +1,256 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
"""Router agent (root): classifies NL queries and delegates to domain agents."""
|
| 2 |
+
|
| 3 |
+
from __future__ import annotations
|
| 4 |
+
|
| 5 |
+
import os
|
| 6 |
+
from dataclasses import dataclass
|
| 7 |
+
from typing import Literal
|
| 8 |
+
|
| 9 |
+
from google.adk.agents.llm_agent import LlmAgent
|
| 10 |
+
from pydantic import BaseModel, Field
|
| 11 |
+
|
| 12 |
+
from .adk_runtime import genai_api_configured, run_router_structured
|
| 13 |
+
from .billing_agent import BillingAgent
|
| 14 |
+
from .returns_remote_agent import ReturnsRemoteAgent
|
| 15 |
+
from .support_agent import SupportAgent
|
| 16 |
+
|
| 17 |
+
|
| 18 |
+
@dataclass
|
| 19 |
+
class RouterOutcome:
|
| 20 |
+
"""Result of :meth:`RouterAgent.route_with_meta` (answer + routing metadata for CLI/API)."""
|
| 21 |
+
|
| 22 |
+
answer: str
|
| 23 |
+
routed_to: Literal["billing", "returns", "support", "escalate"]
|
| 24 |
+
escalated: bool
|
| 25 |
+
rationale: str | None = None
|
| 26 |
+
|
| 27 |
+
|
| 28 |
+
class RouterDecision(BaseModel):
|
| 29 |
+
"""Structured router output when Gemini is available (matches ``output_schema``)."""
|
| 30 |
+
|
| 31 |
+
route: Literal["billing", "returns", "support"] = Field(
|
| 32 |
+
...,
|
| 33 |
+
description="Exactly one downstream agent to handle this turn.",
|
| 34 |
+
)
|
| 35 |
+
escalate: bool = Field(False, description="True if a human specialist should take over.")
|
| 36 |
+
rationale: str = Field("", description="Short justification for auditing.")
|
| 37 |
+
|
| 38 |
+
|
| 39 |
+
# Prompt + few-shot exemplars teach the small model routing boundaries without extra tooling.
|
| 40 |
+
_ROUTER_FEW_SHOT = """
|
| 41 |
+
Examples (follow the same routing rules for new inputs):
|
| 42 |
+
|
| 43 |
+
User: Where can I download last month's VAT invoice?
|
| 44 |
+
Assistant JSON: {"route":"billing","escalate":false,"rationale":"invoice / billing document"}
|
| 45 |
+
|
| 46 |
+
User: My card was charged twice for order #4412.
|
| 47 |
+
Assistant JSON: {"route":"billing","escalate":false,"rationale":"duplicate charge"}
|
| 48 |
+
|
| 49 |
+
User: I want to return sneakers and print a prepaid label.
|
| 50 |
+
Assistant JSON: {"route":"returns","escalate":false,"rationale":"return + label"}
|
| 51 |
+
|
| 52 |
+
User: Am I eligible to return clearance items opened last week?
|
| 53 |
+
Assistant JSON: {"route":"returns","escalate":false,"rationale":"returns eligibility"}
|
| 54 |
+
|
| 55 |
+
User: The app freezes when I open notifications — generic bug.
|
| 56 |
+
Assistant JSON: {"route":"support","escalate":false,"rationale":"general product issue"}
|
| 57 |
+
|
| 58 |
+
User: I'm going to sue your company unless I get my money today!!!
|
| 59 |
+
Assistant JSON: {"route":"support","escalate":true,"rationale":"legal threat / high severity"}
|
| 60 |
+
|
| 61 |
+
User: ???
|
| 62 |
+
Assistant JSON: {"route":"support","escalate":true,"rationale":"unclear intent"}
|
| 63 |
+
"""
|
| 64 |
+
|
| 65 |
+
|
| 66 |
+
ROUTER_SYSTEM_INSTRUCTION = f"""You are the intent router for a commerce support system.
|
| 67 |
+
|
| 68 |
+
Choose exactly one route:
|
| 69 |
+
- billing — invoices, charges, payments, subscriptions, receipts (money on account).
|
| 70 |
+
- returns — product returns, exchanges, prepaid labels, return eligibility.
|
| 71 |
+
- support — general troubleshooting, bugs, vague questions, shipping status *unless* it is clearly billing or returns.
|
| 72 |
+
|
| 73 |
+
Set escalate=true when:
|
| 74 |
+
- The user is furious, threatens legal action, mentions lawyers/police/regulators,
|
| 75 |
+
- Self-harm or abuse is hinted,
|
| 76 |
+
- The request is too ambiguous to route safely,
|
| 77 |
+
|
| 78 |
+
Output **only JSON** matching the schema (route, escalate, rationale). No markdown fences.
|
| 79 |
+
|
| 80 |
+
{_ROUTER_FEW_SHOT}
|
| 81 |
+
"""
|
| 82 |
+
|
| 83 |
+
|
| 84 |
+
def classify_intent_fallback(message: str) -> RouterDecision:
|
| 85 |
+
"""
|
| 86 |
+
Keyword + heuristic router used when Gemini is not configured or JSON parsing fails.
|
| 87 |
+
|
| 88 |
+
Kept deterministic for CI and for environments without ``GOOGLE_API_KEY``.
|
| 89 |
+
"""
|
| 90 |
+
lower = (message or "").lower().strip()
|
| 91 |
+
|
| 92 |
+
escalate_terms = (
|
| 93 |
+
"lawsuit",
|
| 94 |
+
"lawyer",
|
| 95 |
+
"attorney",
|
| 96 |
+
"sue ",
|
| 97 |
+
" suing",
|
| 98 |
+
"police",
|
| 99 |
+
"fcc",
|
| 100 |
+
" regulator",
|
| 101 |
+
"suicide",
|
| 102 |
+
"self-harm",
|
| 103 |
+
"kill myself",
|
| 104 |
+
"discriminat",
|
| 105 |
+
)
|
| 106 |
+
if any(t in lower for t in escalate_terms):
|
| 107 |
+
return RouterDecision(
|
| 108 |
+
route="support",
|
| 109 |
+
escalate=True,
|
| 110 |
+
rationale="potential high-severity / legal / safety keywords",
|
| 111 |
+
)
|
| 112 |
+
|
| 113 |
+
if any(
|
| 114 |
+
k in lower
|
| 115 |
+
for k in (
|
| 116 |
+
"return",
|
| 117 |
+
"exchange",
|
| 118 |
+
"label",
|
| 119 |
+
"ship back",
|
| 120 |
+
"send back",
|
| 121 |
+
"wrong item",
|
| 122 |
+
"didn't fit",
|
| 123 |
+
"doesn't fit",
|
| 124 |
+
" rma",
|
| 125 |
+
)
|
| 126 |
+
):
|
| 127 |
+
return RouterDecision(route="returns", escalate=False, rationale="returns-flow keywords")
|
| 128 |
+
|
| 129 |
+
billing_terms = (
|
| 130 |
+
"invoice",
|
| 131 |
+
"bill",
|
| 132 |
+
"billing",
|
| 133 |
+
"charge",
|
| 134 |
+
"charged",
|
| 135 |
+
"payment",
|
| 136 |
+
"subscription",
|
| 137 |
+
"receipt",
|
| 138 |
+
"refund",
|
| 139 |
+
"card",
|
| 140 |
+
"paypal",
|
| 141 |
+
"vat",
|
| 142 |
+
"statement",
|
| 143 |
+
"duplicate charge",
|
| 144 |
+
"overcharge",
|
| 145 |
+
)
|
| 146 |
+
if any(k in lower for k in billing_terms):
|
| 147 |
+
return RouterDecision(route="billing", escalate=False, rationale="billing/payment keywords")
|
| 148 |
+
|
| 149 |
+
if len(lower) < 4:
|
| 150 |
+
return RouterDecision(route="support", escalate=True, rationale="message too short / unclear")
|
| 151 |
+
|
| 152 |
+
return RouterDecision(route="support", escalate=False, rationale="default general support")
|
| 153 |
+
|
| 154 |
+
|
| 155 |
+
class RouterAgent:
|
| 156 |
+
"""
|
| 157 |
+
Root agent: uses Gemini + few-shot JSON classification when keys exist; otherwise heuristics.
|
| 158 |
+
|
| 159 |
+
Construct with explicit specialist agents (wired in ``main.py``):
|
| 160 |
+
|
| 161 |
+
- ``billing`` — :class:`BillingAgent` (Supabase tool functions / MCP parity)
|
| 162 |
+
- ``returns`` — :class:`ReturnsRemoteAgent` (remote returns A2A service)
|
| 163 |
+
- ``support`` — :class:`SupportAgent`
|
| 164 |
+
"""
|
| 165 |
+
|
| 166 |
+
def __init__(
|
| 167 |
+
self,
|
| 168 |
+
*,
|
| 169 |
+
billing: BillingAgent,
|
| 170 |
+
support: SupportAgent,
|
| 171 |
+
returns: ReturnsRemoteAgent,
|
| 172 |
+
model: str | None = None,
|
| 173 |
+
) -> None:
|
| 174 |
+
self._model = model or os.getenv("ADK_MODEL", "gemini-2.5-flash")
|
| 175 |
+
self.billing = billing
|
| 176 |
+
self.support = support
|
| 177 |
+
self.returns = returns
|
| 178 |
+
|
| 179 |
+
self._router_llm = LlmAgent(
|
| 180 |
+
name="router",
|
| 181 |
+
model=self._model,
|
| 182 |
+
instruction=ROUTER_SYSTEM_INSTRUCTION,
|
| 183 |
+
output_schema=RouterDecision,
|
| 184 |
+
)
|
| 185 |
+
|
| 186 |
+
async def route_with_meta(self, customer_id: str, message: str) -> RouterOutcome:
|
| 187 |
+
"""
|
| 188 |
+
Classify ``message``, dispatch to the right specialist, return answer + metadata.
|
| 189 |
+
|
| 190 |
+
Use this from the CLI and from APIs that need ``routed_to`` / ``escalated``.
|
| 191 |
+
"""
|
| 192 |
+
router_input = (
|
| 193 |
+
"Classify this customer turn.\n\n"
|
| 194 |
+
f"customer_id: {customer_id}\n\n"
|
| 195 |
+
f"message:\n{message}\n"
|
| 196 |
+
)
|
| 197 |
+
|
| 198 |
+
decision: RouterDecision | None = None
|
| 199 |
+
if genai_api_configured():
|
| 200 |
+
decision = await run_router_structured(
|
| 201 |
+
agent=self._router_llm,
|
| 202 |
+
user_message=router_input,
|
| 203 |
+
schema_type=RouterDecision,
|
| 204 |
+
app_name="router",
|
| 205 |
+
)
|
| 206 |
+
|
| 207 |
+
if decision is None:
|
| 208 |
+
decision = classify_intent_fallback(message)
|
| 209 |
+
|
| 210 |
+
if decision.escalate:
|
| 211 |
+
text = (
|
| 212 |
+
"[ESCALATE]\n"
|
| 213 |
+
"This request was flagged for a human specialist.\n"
|
| 214 |
+
f"Routing note: {decision.rationale}\n"
|
| 215 |
+
"ESCALATE_FLAG: true"
|
| 216 |
+
)
|
| 217 |
+
return RouterOutcome(
|
| 218 |
+
answer=text,
|
| 219 |
+
routed_to="escalate",
|
| 220 |
+
escalated=True,
|
| 221 |
+
rationale=decision.rationale,
|
| 222 |
+
)
|
| 223 |
+
|
| 224 |
+
if decision.route == "billing":
|
| 225 |
+
ans = await self.billing.handle(customer_id, message)
|
| 226 |
+
return RouterOutcome(
|
| 227 |
+
answer=ans,
|
| 228 |
+
routed_to="billing",
|
| 229 |
+
escalated=False,
|
| 230 |
+
rationale=decision.rationale,
|
| 231 |
+
)
|
| 232 |
+
|
| 233 |
+
if decision.route == "returns":
|
| 234 |
+
ans = await self.returns.handle(customer_id, message)
|
| 235 |
+
return RouterOutcome(
|
| 236 |
+
answer=ans,
|
| 237 |
+
routed_to="returns",
|
| 238 |
+
escalated=False,
|
| 239 |
+
rationale=decision.rationale,
|
| 240 |
+
)
|
| 241 |
+
|
| 242 |
+
ans = await self.support.handle(customer_id, message)
|
| 243 |
+
return RouterOutcome(
|
| 244 |
+
answer=ans,
|
| 245 |
+
routed_to="support",
|
| 246 |
+
escalated=False,
|
| 247 |
+
rationale=decision.rationale,
|
| 248 |
+
)
|
| 249 |
+
|
| 250 |
+
async def route(self, customer_id: str, message: str) -> str:
|
| 251 |
+
"""
|
| 252 |
+
Classify ``message`` and invoke the appropriate agent (answer text only).
|
| 253 |
+
|
| 254 |
+
Escalations return a body containing ``[ESCALATE]`` and ``ESCALATE_FLAG: true``.
|
| 255 |
+
"""
|
| 256 |
+
return (await self.route_with_meta(customer_id, message)).answer
|
multi_agent_customer_support/src/agents/support_agent.py
ADDED
|
@@ -0,0 +1,103 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
"""General support agent: reads tickets via MCP-parity tools and guides or escalates."""
|
| 2 |
+
|
| 3 |
+
from __future__ import annotations
|
| 4 |
+
|
| 5 |
+
import json
|
| 6 |
+
import os
|
| 7 |
+
from typing import Any
|
| 8 |
+
|
| 9 |
+
from google.adk.agents.llm_agent import LlmAgent
|
| 10 |
+
from google.adk.tools.function_tool import FunctionTool
|
| 11 |
+
|
| 12 |
+
from src.mcp.supabase_mcp_server import get_support_tickets
|
| 13 |
+
|
| 14 |
+
from .adk_runtime import genai_api_configured, run_llm_agent_once
|
| 15 |
+
from .customer_context import resolve_customer_email
|
| 16 |
+
|
| 17 |
+
|
| 18 |
+
def _support_tools() -> list[Any]:
|
| 19 |
+
return [
|
| 20 |
+
FunctionTool(get_support_tickets),
|
| 21 |
+
]
|
| 22 |
+
|
| 23 |
+
|
| 24 |
+
_SUPPORT_INSTRUCTION = """You are a careful customer-support assistant.
|
| 25 |
+
|
| 26 |
+
You have one factual tool:
|
| 27 |
+
- ``get_support_tickets(email)`` — returns JSON with ``tickets`` for that customer.
|
| 28 |
+
|
| 29 |
+
Guidelines:
|
| 30 |
+
1. Use the **resolved email** provided in the user message for ``get_support_tickets``.
|
| 31 |
+
2. Summarize ticket status at a high level (subject/category if present); do not fabricate ticket IDs.
|
| 32 |
+
3. For abuse, threats, legal threats, suspected fraud, or account compromise, clearly recommend **human escalation**.
|
| 33 |
+
4. Keep answers concise and professional.
|
| 34 |
+
"""
|
| 35 |
+
|
| 36 |
+
|
| 37 |
+
class SupportAgent:
|
| 38 |
+
"""Generic support flow with optional Gemini; offline mode summarizes tickets without an LLM."""
|
| 39 |
+
|
| 40 |
+
def __init__(self, model: str | None = None) -> None:
|
| 41 |
+
self._model = model or os.getenv("ADK_MODEL", "gemini-2.5-flash")
|
| 42 |
+
self._agent = LlmAgent(
|
| 43 |
+
name="support_agent",
|
| 44 |
+
model=self._model,
|
| 45 |
+
instruction=_SUPPORT_INSTRUCTION,
|
| 46 |
+
tools=_support_tools(),
|
| 47 |
+
)
|
| 48 |
+
|
| 49 |
+
async def handle(self, customer_id: str, message: str) -> str:
|
| 50 |
+
email = resolve_customer_email(customer_id)
|
| 51 |
+
if not email:
|
| 52 |
+
return (
|
| 53 |
+
"We could not resolve an email for this customer id. "
|
| 54 |
+
"Please contact support with your registered email."
|
| 55 |
+
)
|
| 56 |
+
|
| 57 |
+
if not genai_api_configured():
|
| 58 |
+
tickets_json = get_support_tickets(email)
|
| 59 |
+
return _format_support_fallback(tickets_json, message)
|
| 60 |
+
|
| 61 |
+
user_prompt = (
|
| 62 |
+
f"Resolved customer email (use for tool calls): {email}\n"
|
| 63 |
+
f"Customer id (reference): {customer_id}\n\n"
|
| 64 |
+
f"User message:\n{message}\n"
|
| 65 |
+
)
|
| 66 |
+
return await run_llm_agent_once(
|
| 67 |
+
agent=self._agent,
|
| 68 |
+
user_message=user_prompt,
|
| 69 |
+
app_name="support",
|
| 70 |
+
)
|
| 71 |
+
|
| 72 |
+
|
| 73 |
+
def _format_support_fallback(tickets_json: str, message: str) -> str:
|
| 74 |
+
try:
|
| 75 |
+
payload = json.loads(tickets_json)
|
| 76 |
+
except json.JSONDecodeError:
|
| 77 |
+
return "[SupportAgent] Unable to parse ticket data."
|
| 78 |
+
|
| 79 |
+
lines = [
|
| 80 |
+
"[SupportAgent — offline summary]",
|
| 81 |
+
f'Your message: "{message[:200]}"',
|
| 82 |
+
"",
|
| 83 |
+
]
|
| 84 |
+
|
| 85 |
+
if payload.get("error") == "customer_not_found":
|
| 86 |
+
lines.append("No matching customer email in our records.")
|
| 87 |
+
return "\n".join(lines)
|
| 88 |
+
|
| 89 |
+
tickets = payload.get("tickets") or []
|
| 90 |
+
lines.append(f"Open/recent tickets in view: {len(tickets)}.")
|
| 91 |
+
for t in tickets[:5]:
|
| 92 |
+
subj = t.get("subject") or t.get("title") or "(no subject)"
|
| 93 |
+
cat = t.get("category", "")
|
| 94 |
+
stat = t.get("status", "")
|
| 95 |
+
lines.append(f" - [{stat}] {cat}: {subj}")
|
| 96 |
+
if len(tickets) > 5:
|
| 97 |
+
lines.append(f" … and {len(tickets) - 5} more.")
|
| 98 |
+
|
| 99 |
+
lines.append("")
|
| 100 |
+
lines.append(
|
| 101 |
+
"If this involves threats, legal action, or account security, request a human specialist."
|
| 102 |
+
)
|
| 103 |
+
return "\n".join(lines)
|
multi_agent_customer_support/src/main.py
ADDED
|
@@ -0,0 +1,163 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
"""Multi-agent customer support: FastAPI API + optional interactive CLI.
|
| 2 |
+
|
| 3 |
+
Run the HTTP API (from ``multi_agent_customer_support/``)::
|
| 4 |
+
|
| 5 |
+
uvicorn src.main:app --reload --port 8000
|
| 6 |
+
|
| 7 |
+
Run the stdin CLI (same cwd; loads ``.env`` from the workspace)::
|
| 8 |
+
|
| 9 |
+
python -m src.main
|
| 10 |
+
|
| 11 |
+
Environment:
|
| 12 |
+
|
| 13 |
+
- ``RETURNS_SERVICE_URL`` — returns microservice base URL (default ``http://127.0.0.1:8081``).
|
| 14 |
+
- ``CLI_CUSTOMER_ID`` — default customer id (email or UUID) for the CLI when set.
|
| 15 |
+
- ``GEMINI_API_KEY`` / ``GOOGLE_API_KEY`` — router + specialists.
|
| 16 |
+
- Supabase: ``SUPABASE_URL``, ``SUPABASE_ANON_KEY`` (see ``src/mcp/supabase_client.py``).
|
| 17 |
+
|
| 18 |
+
Wiring:
|
| 19 |
+
|
| 20 |
+
- ``RouterAgent`` receives ``BillingAgent``, ``SupportAgent``, and ``ReturnsRemoteAgent`` explicitly.
|
| 21 |
+
- ``ReturnsRemoteAgent`` talks to the **A2A** returns service at ``RETURNS_SERVICE_URL``.
|
| 22 |
+
- Billing/support use in-process tools matching the Supabase MCP server; ``get_supabase_mcp_toolset()`` builds an
|
| 23 |
+
ADK ``McpToolset`` for a **stdio** MCP connection to ``src.mcp.supabase_mcp_server`` when you need the real MCP client.
|
| 24 |
+
"""
|
| 25 |
+
|
| 26 |
+
from __future__ import annotations
|
| 27 |
+
|
| 28 |
+
import asyncio
|
| 29 |
+
import os
|
| 30 |
+
from typing import Any
|
| 31 |
+
|
| 32 |
+
from dotenv import load_dotenv
|
| 33 |
+
from fastapi import FastAPI
|
| 34 |
+
from pydantic import BaseModel
|
| 35 |
+
|
| 36 |
+
from google.adk.tools.mcp_tool.mcp_toolset import McpToolset
|
| 37 |
+
|
| 38 |
+
from .agents.billing_agent import BillingAgent
|
| 39 |
+
from .agents.returns_remote_agent import ReturnsRemoteAgent
|
| 40 |
+
from .agents.router_agent import RouterAgent
|
| 41 |
+
from .agents.support_agent import SupportAgent
|
| 42 |
+
from .mcp.supabase_mcp_connection import build_supabase_mcp_toolset
|
| 43 |
+
from .mcp.supabase_mcp_server import SupabaseMCPServer
|
| 44 |
+
|
| 45 |
+
load_dotenv()
|
| 46 |
+
|
| 47 |
+
RETURNS_SERVICE_URL = os.getenv("RETURNS_SERVICE_URL", "http://127.0.0.1:8081")
|
| 48 |
+
|
| 49 |
+
# --- Specialists + router (single shared graph for the API process) ---
|
| 50 |
+
billing_agent = BillingAgent()
|
| 51 |
+
support_agent = SupportAgent()
|
| 52 |
+
returns_remote_agent = ReturnsRemoteAgent(RETURNS_SERVICE_URL)
|
| 53 |
+
router_agent = RouterAgent(
|
| 54 |
+
billing=billing_agent,
|
| 55 |
+
support=support_agent,
|
| 56 |
+
returns=returns_remote_agent,
|
| 57 |
+
)
|
| 58 |
+
|
| 59 |
+
supabase_mcp = SupabaseMCPServer()
|
| 60 |
+
|
| 61 |
+
# Lazy MCP stdio client (Supabase MCP server subprocess connects when tools are first resolved).
|
| 62 |
+
_supabase_mcp_toolset: McpToolset | None = None
|
| 63 |
+
|
| 64 |
+
|
| 65 |
+
def get_supabase_mcp_toolset() -> McpToolset:
|
| 66 |
+
"""Return the shared ADK ``McpToolset`` for the Supabase MCP stdio server."""
|
| 67 |
+
global _supabase_mcp_toolset
|
| 68 |
+
if _supabase_mcp_toolset is None:
|
| 69 |
+
_supabase_mcp_toolset = build_supabase_mcp_toolset()
|
| 70 |
+
return _supabase_mcp_toolset
|
| 71 |
+
|
| 72 |
+
|
| 73 |
+
app = FastAPI(title="Multi-Agent Customer Support")
|
| 74 |
+
|
| 75 |
+
|
| 76 |
+
class SupportQuery(BaseModel):
|
| 77 |
+
customer_id: str
|
| 78 |
+
message: str
|
| 79 |
+
|
| 80 |
+
|
| 81 |
+
@app.get("/health")
|
| 82 |
+
async def health() -> dict[str, Any]:
|
| 83 |
+
return {
|
| 84 |
+
"status": "ok",
|
| 85 |
+
"returns_service_url": RETURNS_SERVICE_URL,
|
| 86 |
+
"supabase": supabase_mcp.health(),
|
| 87 |
+
"agents": {
|
| 88 |
+
"router": "RouterAgent",
|
| 89 |
+
"billing": "BillingAgent",
|
| 90 |
+
"support": "SupportAgent",
|
| 91 |
+
"returns": "ReturnsRemoteAgent (A2A)",
|
| 92 |
+
},
|
| 93 |
+
"mcp": {
|
| 94 |
+
"supabase_stdio_toolset": "lazy singleton via get_supabase_mcp_toolset()",
|
| 95 |
+
"tools": ["get_billing_info", "get_support_tickets"],
|
| 96 |
+
},
|
| 97 |
+
}
|
| 98 |
+
|
| 99 |
+
|
| 100 |
+
@app.post("/support/query")
|
| 101 |
+
async def support_query(payload: SupportQuery) -> dict[str, Any]:
|
| 102 |
+
"""
|
| 103 |
+
Route ``message`` for ``customer_id`` through :meth:`RouterAgent.route_with_meta`.
|
| 104 |
+
"""
|
| 105 |
+
out = await router_agent.route_with_meta(payload.customer_id, payload.message)
|
| 106 |
+
return {
|
| 107 |
+
"result": out.answer,
|
| 108 |
+
"routed_to": out.routed_to,
|
| 109 |
+
"escalated": out.escalated,
|
| 110 |
+
"rationale": out.rationale,
|
| 111 |
+
}
|
| 112 |
+
|
| 113 |
+
|
| 114 |
+
def _cli_customer_id() -> str:
|
| 115 |
+
cid = (os.getenv("CLI_CUSTOMER_ID") or "").strip()
|
| 116 |
+
if cid:
|
| 117 |
+
return cid
|
| 118 |
+
try:
|
| 119 |
+
return input("Customer id (email or UUID) [demo@example.com]: ").strip() or "demo@example.com"
|
| 120 |
+
except EOFError:
|
| 121 |
+
return "demo@example.com"
|
| 122 |
+
|
| 123 |
+
|
| 124 |
+
async def _cli_loop_async() -> None:
|
| 125 |
+
"""
|
| 126 |
+
Simple REPL: stdin lines -> RouterAgent -> print answer + routing metadata.
|
| 127 |
+
|
| 128 |
+
Ensures the Supabase MCP toolset object is created so the MCP client wiring is initialized
|
| 129 |
+
(actual stdio subprocess may still start only when tools are loaded by a consumer).
|
| 130 |
+
"""
|
| 131 |
+
load_dotenv()
|
| 132 |
+
_ = get_supabase_mcp_toolset()
|
| 133 |
+
|
| 134 |
+
customer_id = _cli_customer_id()
|
| 135 |
+
print("Interactive support CLI. Type quit / exit to stop.")
|
| 136 |
+
print(f"Using customer_id={customer_id!r} (set CLI_CUSTOMER_ID to skip prompt)\n")
|
| 137 |
+
|
| 138 |
+
while True:
|
| 139 |
+
try:
|
| 140 |
+
line = input("> ").strip()
|
| 141 |
+
except (EOFError, KeyboardInterrupt):
|
| 142 |
+
print()
|
| 143 |
+
break
|
| 144 |
+
if not line:
|
| 145 |
+
continue
|
| 146 |
+
if line.lower() in ("quit", "exit", "q"):
|
| 147 |
+
break
|
| 148 |
+
|
| 149 |
+
out = await router_agent.route_with_meta(customer_id, line)
|
| 150 |
+
print(out.answer)
|
| 151 |
+
print(f"[meta] routed_to={out.routed_to!r} escalated={out.escalated}")
|
| 152 |
+
if out.rationale:
|
| 153 |
+
print(f"[meta] rationale={out.rationale!r}")
|
| 154 |
+
print()
|
| 155 |
+
|
| 156 |
+
|
| 157 |
+
def run_cli() -> None:
|
| 158 |
+
"""Entry for ``python -m src.main``."""
|
| 159 |
+
asyncio.run(_cli_loop_async())
|
| 160 |
+
|
| 161 |
+
|
| 162 |
+
if __name__ == "__main__":
|
| 163 |
+
run_cli()
|
multi_agent_customer_support/src/mcp/__init__.py
ADDED
|
@@ -0,0 +1 @@
|
|
|
|
|
|
|
| 1 |
+
"""MCP-style integrations (Supabase server wrapper)."""
|
multi_agent_customer_support/src/mcp/python_mcp_server.py
ADDED
|
@@ -0,0 +1,54 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
"""Local Python MCP server for project diagnostics."""
|
| 2 |
+
|
| 3 |
+
from __future__ import annotations
|
| 4 |
+
|
| 5 |
+
import os
|
| 6 |
+
from datetime import datetime, timezone
|
| 7 |
+
from pathlib import Path
|
| 8 |
+
|
| 9 |
+
from dotenv import load_dotenv
|
| 10 |
+
from fastmcp import FastMCP
|
| 11 |
+
|
| 12 |
+
|
| 13 |
+
def _load_env_files() -> None:
|
| 14 |
+
project_root = Path(__file__).resolve().parents[3]
|
| 15 |
+
workspace_root = Path(__file__).resolve().parents[4]
|
| 16 |
+
|
| 17 |
+
# Prefer explicit env files if present
|
| 18 |
+
load_dotenv(dotenv_path=workspace_root / ".env", override=False)
|
| 19 |
+
load_dotenv(dotenv_path=project_root / ".env", override=False)
|
| 20 |
+
|
| 21 |
+
|
| 22 |
+
_load_env_files()
|
| 23 |
+
|
| 24 |
+
mcp = FastMCP("multi-agent-python-mcp")
|
| 25 |
+
|
| 26 |
+
|
| 27 |
+
@mcp.tool
|
| 28 |
+
def ping() -> str:
|
| 29 |
+
"""Return a simple heartbeat response."""
|
| 30 |
+
return "pong"
|
| 31 |
+
|
| 32 |
+
|
| 33 |
+
@mcp.tool
|
| 34 |
+
def project_info() -> dict[str, str]:
|
| 35 |
+
"""Return quick project/runtime metadata."""
|
| 36 |
+
return {
|
| 37 |
+
"project": "multi_agent_customer_support",
|
| 38 |
+
"python": os.sys.version.split()[0],
|
| 39 |
+
"timestamp_utc": datetime.now(timezone.utc).isoformat(),
|
| 40 |
+
}
|
| 41 |
+
|
| 42 |
+
|
| 43 |
+
@mcp.tool
|
| 44 |
+
def supabase_env_status() -> dict[str, bool]:
|
| 45 |
+
"""Tell whether Supabase env vars are present."""
|
| 46 |
+
return {
|
| 47 |
+
"has_supabase_url": bool(os.getenv("SUPABASE_URL")),
|
| 48 |
+
"has_supabase_key": bool(os.getenv("SUPABASE_KEY")),
|
| 49 |
+
"has_supabase_access_token": bool(os.getenv("SUPABASE_ACCESS_TOKEN")),
|
| 50 |
+
}
|
| 51 |
+
|
| 52 |
+
|
| 53 |
+
if __name__ == "__main__":
|
| 54 |
+
mcp.run()
|
multi_agent_customer_support/src/mcp/supabase_client.py
ADDED
|
@@ -0,0 +1,236 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
"""Supabase Postgres helpers for customer support data (supabase-py).
|
| 2 |
+
|
| 3 |
+
Import from the ``src`` package to avoid clashing with the PyPI ``mcp`` SDK, for example:
|
| 4 |
+
|
| 5 |
+
from src.mcp.supabase_client import get_customer_by_email
|
| 6 |
+
|
| 7 |
+
This matches running the API with ``uvicorn src.main:app`` from ``multi_agent_customer_support/``.
|
| 8 |
+
"""
|
| 9 |
+
|
| 10 |
+
from __future__ import annotations
|
| 11 |
+
|
| 12 |
+
import os
|
| 13 |
+
from typing import Any
|
| 14 |
+
|
| 15 |
+
from dotenv import load_dotenv
|
| 16 |
+
|
| 17 |
+
try:
|
| 18 |
+
from supabase import Client, create_client
|
| 19 |
+
except ImportError as exc: # pragma: no cover - env without supabase installed
|
| 20 |
+
Client = Any # type: ignore[misc, assignment]
|
| 21 |
+
create_client = None
|
| 22 |
+
_IMPORT_ERROR = exc
|
| 23 |
+
else:
|
| 24 |
+
_IMPORT_ERROR = None
|
| 25 |
+
|
| 26 |
+
|
| 27 |
+
class SupabaseConfigurationError(RuntimeError):
|
| 28 |
+
"""Raised when URL/key are missing or the Supabase SDK is unavailable."""
|
| 29 |
+
|
| 30 |
+
|
| 31 |
+
def _load_dotenv() -> None:
|
| 32 |
+
"""Load `.env` from typical locations (workspace root + package root)."""
|
| 33 |
+
try:
|
| 34 |
+
from pathlib import Path
|
| 35 |
+
|
| 36 |
+
here = Path(__file__).resolve()
|
| 37 |
+
package_root = here.parents[2]
|
| 38 |
+
workspace_root = here.parents[3]
|
| 39 |
+
load_dotenv(dotenv_path=workspace_root / ".env", override=False)
|
| 40 |
+
load_dotenv(dotenv_path=package_root / ".env", override=False)
|
| 41 |
+
except Exception:
|
| 42 |
+
load_dotenv(override=False)
|
| 43 |
+
|
| 44 |
+
|
| 45 |
+
_load_dotenv()
|
| 46 |
+
|
| 47 |
+
_client: Client | None = None
|
| 48 |
+
|
| 49 |
+
|
| 50 |
+
def _resolve_anon_key() -> str:
|
| 51 |
+
"""Prefer SUPABASE_ANON_KEY; fall back to SUPABASE_KEY for older configs."""
|
| 52 |
+
return (os.getenv("SUPABASE_ANON_KEY") or os.getenv("SUPABASE_KEY") or "").strip()
|
| 53 |
+
|
| 54 |
+
|
| 55 |
+
def _require_sdk() -> None:
|
| 56 |
+
if create_client is None:
|
| 57 |
+
raise SupabaseConfigurationError(
|
| 58 |
+
"supabase-py is not installed or failed to import."
|
| 59 |
+
) from _IMPORT_ERROR
|
| 60 |
+
|
| 61 |
+
|
| 62 |
+
def get_supabase_client() -> Client:
|
| 63 |
+
"""
|
| 64 |
+
Return a cached Supabase client using ``SUPABASE_URL`` and ``SUPABASE_ANON_KEY``.
|
| 65 |
+
|
| 66 |
+
``SUPABASE_KEY`` is accepted as a fallback when ``SUPABASE_ANON_KEY`` is unset.
|
| 67 |
+
"""
|
| 68 |
+
global _client
|
| 69 |
+
_require_sdk()
|
| 70 |
+
|
| 71 |
+
if _client is not None:
|
| 72 |
+
return _client
|
| 73 |
+
|
| 74 |
+
url = (os.getenv("SUPABASE_URL") or "").strip()
|
| 75 |
+
key = _resolve_anon_key()
|
| 76 |
+
if not url or not key:
|
| 77 |
+
raise SupabaseConfigurationError(
|
| 78 |
+
"Set SUPABASE_URL and SUPABASE_ANON_KEY (or SUPABASE_KEY) in the environment."
|
| 79 |
+
)
|
| 80 |
+
|
| 81 |
+
assert create_client is not None
|
| 82 |
+
_client = create_client(url, key)
|
| 83 |
+
return _client
|
| 84 |
+
|
| 85 |
+
|
| 86 |
+
def reset_supabase_client_cache() -> None:
|
| 87 |
+
"""Clear the cached client (mainly for tests)."""
|
| 88 |
+
global _client
|
| 89 |
+
_client = None
|
| 90 |
+
|
| 91 |
+
|
| 92 |
+
def get_customer_by_email(email: str) -> dict[str, Any] | None:
|
| 93 |
+
"""
|
| 94 |
+
Fetch a single customer row by unique email.
|
| 95 |
+
|
| 96 |
+
:param email: Customer email (trimmed); must be non-empty.
|
| 97 |
+
:returns: One row as a dict, or ``None`` if not found.
|
| 98 |
+
:raises SupabaseConfigurationError: If env or SDK is not usable.
|
| 99 |
+
:raises ValueError: If ``email`` is empty.
|
| 100 |
+
"""
|
| 101 |
+
email_clean = (email or "").strip()
|
| 102 |
+
if not email_clean:
|
| 103 |
+
raise ValueError("email must be a non-empty string")
|
| 104 |
+
|
| 105 |
+
try:
|
| 106 |
+
client = get_supabase_client()
|
| 107 |
+
response = (
|
| 108 |
+
client.table("customers")
|
| 109 |
+
.select("*")
|
| 110 |
+
.eq("email", email_clean)
|
| 111 |
+
.limit(1)
|
| 112 |
+
.execute()
|
| 113 |
+
)
|
| 114 |
+
rows = response.data or []
|
| 115 |
+
return rows[0] if rows else None
|
| 116 |
+
except SupabaseConfigurationError:
|
| 117 |
+
raise
|
| 118 |
+
except Exception as exc:
|
| 119 |
+
raise RuntimeError(f"Failed to load customer by email: {exc}") from exc
|
| 120 |
+
|
| 121 |
+
|
| 122 |
+
def get_customer_by_id(customer_id: str) -> dict[str, Any] | None:
|
| 123 |
+
"""
|
| 124 |
+
Fetch a single customer row by primary key ``id`` (UUID string).
|
| 125 |
+
|
| 126 |
+
:param customer_id: ``customers.id`` as a string.
|
| 127 |
+
:returns: One row as a dict, or ``None`` if not found.
|
| 128 |
+
:raises SupabaseConfigurationError: If env or SDK is not usable.
|
| 129 |
+
:raises ValueError: If ``customer_id`` is empty.
|
| 130 |
+
"""
|
| 131 |
+
cid = (customer_id or "").strip()
|
| 132 |
+
if not cid:
|
| 133 |
+
raise ValueError("customer_id must be a non-empty string")
|
| 134 |
+
|
| 135 |
+
try:
|
| 136 |
+
client = get_supabase_client()
|
| 137 |
+
response = (
|
| 138 |
+
client.table("customers")
|
| 139 |
+
.select("*")
|
| 140 |
+
.eq("id", cid)
|
| 141 |
+
.limit(1)
|
| 142 |
+
.execute()
|
| 143 |
+
)
|
| 144 |
+
rows = response.data or []
|
| 145 |
+
return rows[0] if rows else None
|
| 146 |
+
except SupabaseConfigurationError:
|
| 147 |
+
raise
|
| 148 |
+
except Exception as exc:
|
| 149 |
+
raise RuntimeError(f"Failed to load customer by id: {exc}") from exc
|
| 150 |
+
|
| 151 |
+
|
| 152 |
+
def get_orders_by_customer(customer_id: str) -> list[dict[str, Any]]:
|
| 153 |
+
"""
|
| 154 |
+
List orders for a customer (newest first by ``created_at``).
|
| 155 |
+
|
| 156 |
+
:param customer_id: UUID string for ``orders.customer_id``.
|
| 157 |
+
:returns: List of order rows (possibly empty).
|
| 158 |
+
:raises SupabaseConfigurationError: If env or SDK is not usable.
|
| 159 |
+
:raises ValueError: If ``customer_id`` is empty.
|
| 160 |
+
"""
|
| 161 |
+
cid = (customer_id or "").strip()
|
| 162 |
+
if not cid:
|
| 163 |
+
raise ValueError("customer_id must be a non-empty string")
|
| 164 |
+
|
| 165 |
+
try:
|
| 166 |
+
client = get_supabase_client()
|
| 167 |
+
response = (
|
| 168 |
+
client.table("orders")
|
| 169 |
+
.select("*")
|
| 170 |
+
.eq("customer_id", cid)
|
| 171 |
+
.order("created_at", desc=True)
|
| 172 |
+
.execute()
|
| 173 |
+
)
|
| 174 |
+
return list(response.data or [])
|
| 175 |
+
except SupabaseConfigurationError:
|
| 176 |
+
raise
|
| 177 |
+
except Exception as exc:
|
| 178 |
+
raise RuntimeError(f"Failed to list orders for customer: {exc}") from exc
|
| 179 |
+
|
| 180 |
+
|
| 181 |
+
def get_support_tickets_by_customer(customer_id: str) -> list[dict[str, Any]]:
|
| 182 |
+
"""
|
| 183 |
+
List support tickets for a customer (newest first by ``created_at``).
|
| 184 |
+
|
| 185 |
+
:param customer_id: UUID string for ``support_tickets.customer_id``.
|
| 186 |
+
:returns: List of ticket rows (possibly empty).
|
| 187 |
+
:raises SupabaseConfigurationError: If env or SDK is not usable.
|
| 188 |
+
:raises ValueError: If ``customer_id`` is empty.
|
| 189 |
+
"""
|
| 190 |
+
cid = (customer_id or "").strip()
|
| 191 |
+
if not cid:
|
| 192 |
+
raise ValueError("customer_id must be a non-empty string")
|
| 193 |
+
|
| 194 |
+
try:
|
| 195 |
+
client = get_supabase_client()
|
| 196 |
+
response = (
|
| 197 |
+
client.table("support_tickets")
|
| 198 |
+
.select("*")
|
| 199 |
+
.eq("customer_id", cid)
|
| 200 |
+
.order("created_at", desc=True)
|
| 201 |
+
.execute()
|
| 202 |
+
)
|
| 203 |
+
return list(response.data or [])
|
| 204 |
+
except SupabaseConfigurationError:
|
| 205 |
+
raise
|
| 206 |
+
except Exception as exc:
|
| 207 |
+
raise RuntimeError(f"Failed to list support tickets for customer: {exc}") from exc
|
| 208 |
+
|
| 209 |
+
|
| 210 |
+
def get_support_tickets_by_category(category: str) -> list[dict[str, Any]]:
|
| 211 |
+
"""
|
| 212 |
+
List support tickets matching a category (e.g. ``billing``, ``returns``, ``general``).
|
| 213 |
+
|
| 214 |
+
:param category: Ticket category string.
|
| 215 |
+
:returns: List of ticket rows (possibly empty).
|
| 216 |
+
:raises SupabaseConfigurationError: If env or SDK is not usable.
|
| 217 |
+
:raises ValueError: If ``category`` is empty.
|
| 218 |
+
"""
|
| 219 |
+
cat = (category or "").strip()
|
| 220 |
+
if not cat:
|
| 221 |
+
raise ValueError("category must be a non-empty string")
|
| 222 |
+
|
| 223 |
+
try:
|
| 224 |
+
client = get_supabase_client()
|
| 225 |
+
response = (
|
| 226 |
+
client.table("support_tickets")
|
| 227 |
+
.select("*")
|
| 228 |
+
.eq("category", cat)
|
| 229 |
+
.order("created_at", desc=True)
|
| 230 |
+
.execute()
|
| 231 |
+
)
|
| 232 |
+
return list(response.data or [])
|
| 233 |
+
except SupabaseConfigurationError:
|
| 234 |
+
raise
|
| 235 |
+
except Exception as exc:
|
| 236 |
+
raise RuntimeError(f"Failed to list support tickets: {exc}") from exc
|
multi_agent_customer_support/src/mcp/supabase_mcp_connection.py
ADDED
|
@@ -0,0 +1,39 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
"""ADK ``McpToolset`` factory for the Supabase MCP stdio server (separate process).
|
| 2 |
+
|
| 3 |
+
Billing/support agents in this repo call the same tool implementations in-process
|
| 4 |
+
(``FunctionTool`` + ``supabase_mcp_server``). This toolset is for hosts that want a **real**
|
| 5 |
+
stdio MCP connection (e.g. future refactors, diagnostics).
|
| 6 |
+
|
| 7 |
+
The server is started as::
|
| 8 |
+
|
| 9 |
+
python -m src.mcp.supabase_mcp_server
|
| 10 |
+
|
| 11 |
+
from the ``multi_agent_customer_support`` package root (``cwd`` below).
|
| 12 |
+
"""
|
| 13 |
+
|
| 14 |
+
from __future__ import annotations
|
| 15 |
+
|
| 16 |
+
import sys
|
| 17 |
+
from pathlib import Path
|
| 18 |
+
|
| 19 |
+
from google.adk.tools.mcp_tool.mcp_session_manager import StdioConnectionParams
|
| 20 |
+
from google.adk.tools.mcp_tool.mcp_toolset import McpToolset
|
| 21 |
+
from mcp import StdioServerParameters
|
| 22 |
+
|
| 23 |
+
# src/mcp/supabase_mcp_connection.py -> parents[2] = multi_agent_customer_support
|
| 24 |
+
_PACKAGE_ROOT = Path(__file__).resolve().parent.parent.parent
|
| 25 |
+
|
| 26 |
+
|
| 27 |
+
def build_supabase_mcp_toolset() -> McpToolset:
|
| 28 |
+
"""Configure MCP client for ``get_billing_info`` and ``get_support_tickets`` on the Supabase server."""
|
| 29 |
+
return McpToolset(
|
| 30 |
+
connection_params=StdioConnectionParams(
|
| 31 |
+
server_params=StdioServerParameters(
|
| 32 |
+
command=sys.executable,
|
| 33 |
+
args=["-m", "src.mcp.supabase_mcp_server"],
|
| 34 |
+
cwd=str(_PACKAGE_ROOT),
|
| 35 |
+
),
|
| 36 |
+
timeout=30.0,
|
| 37 |
+
),
|
| 38 |
+
tool_filter=["get_billing_info", "get_support_tickets"],
|
| 39 |
+
)
|
multi_agent_customer_support/src/mcp/supabase_mcp_server.py
ADDED
|
@@ -0,0 +1,170 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
"""Supabase-backed MCP server for ADK agents (Model Context Protocol tools over stdio).
|
| 2 |
+
|
| 3 |
+
This process exposes tools that query Postgres via ``supabase-py``. Run it as a **separate
|
| 4 |
+
process** and point Google ADK / MCP clients at this server (stdio transport).
|
| 5 |
+
|
| 6 |
+
How to run (from ``multi_agent_customer_support/``):
|
| 7 |
+
|
| 8 |
+
.venv\\Scripts\\activate
|
| 9 |
+
python -m src.mcp.supabase_mcp_server
|
| 10 |
+
|
| 11 |
+
Environment (same as ``supabase_client``):
|
| 12 |
+
|
| 13 |
+
- ``SUPABASE_URL``
|
| 14 |
+
- ``SUPABASE_ANON_KEY`` (or legacy ``SUPABASE_KEY``)
|
| 15 |
+
|
| 16 |
+
Ensure Row Level Security policies allow the ``anon`` role to read the relevant tables
|
| 17 |
+
(see ``sql/fix_rls_and_verify.sql``).
|
| 18 |
+
"""
|
| 19 |
+
|
| 20 |
+
from __future__ import annotations
|
| 21 |
+
|
| 22 |
+
import json
|
| 23 |
+
import os
|
| 24 |
+
from typing import Any
|
| 25 |
+
|
| 26 |
+
from dotenv import load_dotenv
|
| 27 |
+
from fastmcp import FastMCP
|
| 28 |
+
|
| 29 |
+
from .supabase_client import (
|
| 30 |
+
SupabaseConfigurationError,
|
| 31 |
+
get_customer_by_email,
|
| 32 |
+
get_orders_by_customer,
|
| 33 |
+
get_support_tickets_by_customer,
|
| 34 |
+
get_supabase_client,
|
| 35 |
+
)
|
| 36 |
+
|
| 37 |
+
# Load workspace / package .env before tools run (FastMCP subprocess may not inherit shell env).
|
| 38 |
+
try:
|
| 39 |
+
from pathlib import Path
|
| 40 |
+
|
| 41 |
+
_here = Path(__file__).resolve()
|
| 42 |
+
_pkg = _here.parents[2]
|
| 43 |
+
_ws = _here.parents[3]
|
| 44 |
+
load_dotenv(dotenv_path=_ws / ".env", override=False)
|
| 45 |
+
load_dotenv(dotenv_path=_pkg / ".env", override=False)
|
| 46 |
+
except Exception:
|
| 47 |
+
load_dotenv(override=False)
|
| 48 |
+
|
| 49 |
+
|
| 50 |
+
mcp = FastMCP("supabase-support-mcp")
|
| 51 |
+
|
| 52 |
+
|
| 53 |
+
@mcp.tool()
|
| 54 |
+
def get_billing_info(email: str) -> str:
|
| 55 |
+
"""
|
| 56 |
+
Look up a customer by email and return a concise JSON summary of their orders
|
| 57 |
+
(billing-related: ``order_number``, ``total_amount``, ``status``).
|
| 58 |
+
|
| 59 |
+
Returns a JSON string for easy consumption by agents.
|
| 60 |
+
"""
|
| 61 |
+
email_clean = (email or "").strip()
|
| 62 |
+
if not email_clean:
|
| 63 |
+
return json.dumps({"error": "invalid_email", "message": "email must be non-empty"})
|
| 64 |
+
|
| 65 |
+
customer = get_customer_by_email(email_clean)
|
| 66 |
+
if not customer:
|
| 67 |
+
return json.dumps(
|
| 68 |
+
{"error": "customer_not_found", "email": email_clean, "orders": []}
|
| 69 |
+
)
|
| 70 |
+
|
| 71 |
+
customer_id = str(customer.get("id", ""))
|
| 72 |
+
orders_raw = get_orders_by_customer(customer_id)
|
| 73 |
+
|
| 74 |
+
orders = []
|
| 75 |
+
for row in orders_raw:
|
| 76 |
+
amt = row.get("total_amount")
|
| 77 |
+
try:
|
| 78 |
+
total = float(amt) if amt is not None else None
|
| 79 |
+
except (TypeError, ValueError):
|
| 80 |
+
total = amt
|
| 81 |
+
orders.append(
|
| 82 |
+
{
|
| 83 |
+
"order_number": row.get("order_number"),
|
| 84 |
+
"total_amount": total,
|
| 85 |
+
"status": row.get("status"),
|
| 86 |
+
}
|
| 87 |
+
)
|
| 88 |
+
|
| 89 |
+
payload = {
|
| 90 |
+
"customer": {
|
| 91 |
+
"id": customer_id,
|
| 92 |
+
"name": customer.get("name"),
|
| 93 |
+
"email": customer.get("email"),
|
| 94 |
+
},
|
| 95 |
+
"orders": orders,
|
| 96 |
+
"order_count": len(orders),
|
| 97 |
+
}
|
| 98 |
+
return json.dumps(payload, default=str)
|
| 99 |
+
|
| 100 |
+
|
| 101 |
+
@mcp.tool()
|
| 102 |
+
def get_support_tickets(email: str) -> str:
|
| 103 |
+
"""
|
| 104 |
+
Look up a customer by email and return all ``support_tickets`` for that customer.
|
| 105 |
+
|
| 106 |
+
Returns a JSON string containing ``customer`` metadata and a ``tickets`` list.
|
| 107 |
+
"""
|
| 108 |
+
email_clean = (email or "").strip()
|
| 109 |
+
if not email_clean:
|
| 110 |
+
return json.dumps({"error": "invalid_email", "message": "email must be non-empty"})
|
| 111 |
+
|
| 112 |
+
customer = get_customer_by_email(email_clean)
|
| 113 |
+
if not customer:
|
| 114 |
+
return json.dumps(
|
| 115 |
+
{
|
| 116 |
+
"error": "customer_not_found",
|
| 117 |
+
"email": email_clean,
|
| 118 |
+
"tickets": [],
|
| 119 |
+
}
|
| 120 |
+
)
|
| 121 |
+
|
| 122 |
+
customer_id = str(customer.get("id", ""))
|
| 123 |
+
tickets = get_support_tickets_by_customer(customer_id)
|
| 124 |
+
|
| 125 |
+
payload = {
|
| 126 |
+
"customer": {
|
| 127 |
+
"id": customer_id,
|
| 128 |
+
"name": customer.get("name"),
|
| 129 |
+
"email": customer.get("email"),
|
| 130 |
+
},
|
| 131 |
+
"tickets": tickets,
|
| 132 |
+
"ticket_count": len(tickets),
|
| 133 |
+
}
|
| 134 |
+
return json.dumps(payload, default=str)
|
| 135 |
+
|
| 136 |
+
|
| 137 |
+
class SupabaseMCPServer:
|
| 138 |
+
"""Lightweight health helper used by ``src.main`` FastAPI (not the MCP stdio server)."""
|
| 139 |
+
|
| 140 |
+
def health(self) -> dict[str, Any]:
|
| 141 |
+
try:
|
| 142 |
+
get_supabase_client()
|
| 143 |
+
return {
|
| 144 |
+
"configured": True,
|
| 145 |
+
"sdk_available": True,
|
| 146 |
+
"supabase_url_set": bool(os.getenv("SUPABASE_URL")),
|
| 147 |
+
"anon_or_key_set": bool(
|
| 148 |
+
os.getenv("SUPABASE_ANON_KEY") or os.getenv("SUPABASE_KEY")
|
| 149 |
+
),
|
| 150 |
+
}
|
| 151 |
+
except SupabaseConfigurationError as exc:
|
| 152 |
+
return {
|
| 153 |
+
"configured": False,
|
| 154 |
+
"sdk_available": True,
|
| 155 |
+
"error": str(exc),
|
| 156 |
+
}
|
| 157 |
+
|
| 158 |
+
|
| 159 |
+
def main() -> None:
|
| 160 |
+
"""
|
| 161 |
+
Start the MCP server (default: **stdio** transport).
|
| 162 |
+
|
| 163 |
+
Run as a dedicated process; ADK / MCP hosts spawn this executable and communicate
|
| 164 |
+
over stdin/stdout per the Model Context Protocol.
|
| 165 |
+
"""
|
| 166 |
+
mcp.run()
|
| 167 |
+
|
| 168 |
+
|
| 169 |
+
if __name__ == "__main__":
|
| 170 |
+
main()
|
multi_agent_customer_support/tests/__init__.py
ADDED
|
@@ -0,0 +1 @@
|
|
|
|
|
|
|
| 1 |
+
"""Project tests package."""
|
multi_agent_customer_support/tests/test_returns_remote_agent.py
ADDED
|
@@ -0,0 +1,61 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
"""Unit tests for returns_remote_agent helpers (no live A2A server)."""
|
| 2 |
+
|
| 3 |
+
import os
|
| 4 |
+
import sys
|
| 5 |
+
import unittest
|
| 6 |
+
import unittest.mock
|
| 7 |
+
|
| 8 |
+
_ROOT = os.path.abspath(os.path.join(os.path.dirname(__file__), ".."))
|
| 9 |
+
sys.path.insert(0, _ROOT)
|
| 10 |
+
|
| 11 |
+
from src.agents.returns_remote_agent import ( # noqa: E402
|
| 12 |
+
ReturnsRemoteAgent,
|
| 13 |
+
_default_agent_card_url,
|
| 14 |
+
_parse_json_object,
|
| 15 |
+
)
|
| 16 |
+
|
| 17 |
+
|
| 18 |
+
class TestParseJsonObject(unittest.TestCase):
|
| 19 |
+
def test_plain_json(self) -> None:
|
| 20 |
+
d = _parse_json_object('{"eligible": true, "reason": "ok"}')
|
| 21 |
+
self.assertTrue(d["eligible"])
|
| 22 |
+
self.assertEqual(d["reason"], "ok")
|
| 23 |
+
|
| 24 |
+
def test_fenced_json(self) -> None:
|
| 25 |
+
d = _parse_json_object('```json\n{"a": 1}\n```')
|
| 26 |
+
self.assertEqual(d["a"], 1)
|
| 27 |
+
|
| 28 |
+
def test_embedded_braces(self) -> None:
|
| 29 |
+
d = _parse_json_object('Here you go: {"eligible": false, "reason": "x"} thanks')
|
| 30 |
+
self.assertFalse(d["eligible"])
|
| 31 |
+
|
| 32 |
+
|
| 33 |
+
class TestDefaultAgentCardUrl(unittest.TestCase):
|
| 34 |
+
def test_override_env(self) -> None:
|
| 35 |
+
with unittest.mock.patch.dict(
|
| 36 |
+
os.environ,
|
| 37 |
+
{"RETURNS_A2A_AGENT_CARD_URL": "http://example.com/card.json"},
|
| 38 |
+
):
|
| 39 |
+
self.assertEqual(
|
| 40 |
+
_default_agent_card_url("http://127.0.0.1:8081"),
|
| 41 |
+
"http://example.com/card.json",
|
| 42 |
+
)
|
| 43 |
+
|
| 44 |
+
def test_default_suffix(self) -> None:
|
| 45 |
+
with unittest.mock.patch.dict(os.environ, {"RETURNS_A2A_AGENT_CARD_URL": ""}):
|
| 46 |
+
url = _default_agent_card_url("http://127.0.0.1:8081")
|
| 47 |
+
self.assertEqual(
|
| 48 |
+
url,
|
| 49 |
+
"http://127.0.0.1:8081/.well-known/agent-card.json",
|
| 50 |
+
)
|
| 51 |
+
|
| 52 |
+
|
| 53 |
+
class TestReturnsRemoteAgentInit(unittest.TestCase):
|
| 54 |
+
def test_builds_remote_a2a(self) -> None:
|
| 55 |
+
r = ReturnsRemoteAgent("http://127.0.0.1:8081")
|
| 56 |
+
self.assertEqual(r.base_url, "http://127.0.0.1:8081")
|
| 57 |
+
self.assertEqual(r._remote.name, "returns_service_a2a")
|
| 58 |
+
|
| 59 |
+
|
| 60 |
+
if __name__ == "__main__":
|
| 61 |
+
unittest.main()
|
multi_agent_customer_support/tests/test_returns_service.py
ADDED
|
@@ -0,0 +1,73 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
"""Tests for ``servers/returns_service/main.py`` (FastAPI + mock tools)."""
|
| 2 |
+
|
| 3 |
+
import os
|
| 4 |
+
import sys
|
| 5 |
+
import unittest
|
| 6 |
+
|
| 7 |
+
_ROOT = os.path.abspath(os.path.join(os.path.dirname(__file__), ".."))
|
| 8 |
+
sys.path.insert(0, _ROOT)
|
| 9 |
+
|
| 10 |
+
from fastapi.testclient import TestClient # noqa: E402
|
| 11 |
+
|
| 12 |
+
from servers.returns_service import main as rs # noqa: E402
|
| 13 |
+
|
| 14 |
+
|
| 15 |
+
class TestReturnsTools(unittest.TestCase):
|
| 16 |
+
def test_eligibility_even_digit(self) -> None:
|
| 17 |
+
r = rs.check_return_eligibility("ORD-42")
|
| 18 |
+
self.assertTrue(r["eligible"])
|
| 19 |
+
self.assertIn("even", r["reason"].lower())
|
| 20 |
+
|
| 21 |
+
def test_eligibility_odd_digit(self) -> None:
|
| 22 |
+
r = rs.check_return_eligibility("X-41")
|
| 23 |
+
self.assertFalse(r["eligible"])
|
| 24 |
+
|
| 25 |
+
def test_eligibility_non_digit_suffix(self) -> None:
|
| 26 |
+
r = rs.check_return_eligibility("ABC")
|
| 27 |
+
self.assertFalse(r["eligible"])
|
| 28 |
+
|
| 29 |
+
def test_initiate_return_shape(self) -> None:
|
| 30 |
+
r = rs.initiate_return("ORD-1", "too big")
|
| 31 |
+
self.assertEqual(r["status"], "initiated")
|
| 32 |
+
self.assertTrue(r["return_id"].startswith("ret-"))
|
| 33 |
+
self.assertIn("ORD-1", r["message"])
|
| 34 |
+
|
| 35 |
+
|
| 36 |
+
class TestReturnsFastAPI(unittest.TestCase):
|
| 37 |
+
"""Use ``TestClient`` as a context manager so FastAPI ``lifespan`` runs (A2A route registration)."""
|
| 38 |
+
|
| 39 |
+
def test_health(self) -> None:
|
| 40 |
+
with TestClient(rs.app) as client:
|
| 41 |
+
res = client.get("/health")
|
| 42 |
+
self.assertEqual(res.status_code, 200)
|
| 43 |
+
self.assertEqual(res.json()["status"], "ok")
|
| 44 |
+
|
| 45 |
+
def test_agent_card(self) -> None:
|
| 46 |
+
with TestClient(rs.app) as client:
|
| 47 |
+
res = client.get("/.well-known/agent-card.json")
|
| 48 |
+
self.assertEqual(res.status_code, 200)
|
| 49 |
+
data = res.json()
|
| 50 |
+
self.assertIn("name", data)
|
| 51 |
+
self.assertEqual(data.get("name"), "returns_agent")
|
| 52 |
+
|
| 53 |
+
def test_tools_eligibility_endpoint(self) -> None:
|
| 54 |
+
with TestClient(rs.app) as client:
|
| 55 |
+
res = client.post(
|
| 56 |
+
"/tools/check_return_eligibility",
|
| 57 |
+
json={"order_number": "ORD-8"},
|
| 58 |
+
)
|
| 59 |
+
self.assertEqual(res.status_code, 200)
|
| 60 |
+
self.assertTrue(res.json()["eligible"])
|
| 61 |
+
|
| 62 |
+
def test_returns_process_legacy(self) -> None:
|
| 63 |
+
with TestClient(rs.app) as client:
|
| 64 |
+
res = client.post(
|
| 65 |
+
"/returns/process",
|
| 66 |
+
json={"customer_id": "c1", "message": "hello"},
|
| 67 |
+
)
|
| 68 |
+
self.assertEqual(res.status_code, 200)
|
| 69 |
+
self.assertIn("result", res.json())
|
| 70 |
+
|
| 71 |
+
|
| 72 |
+
if __name__ == "__main__":
|
| 73 |
+
unittest.main()
|
multi_agent_customer_support/tests/test_router_fallback.py
ADDED
|
@@ -0,0 +1,35 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
"""Tests for heuristic router classification (no Gemini required)."""
|
| 2 |
+
|
| 3 |
+
import os
|
| 4 |
+
import sys
|
| 5 |
+
import unittest
|
| 6 |
+
|
| 7 |
+
_ROOT = os.path.abspath(os.path.join(os.path.dirname(__file__), ".."))
|
| 8 |
+
sys.path.insert(0, _ROOT)
|
| 9 |
+
|
| 10 |
+
from src.agents.router_agent import classify_intent_fallback # noqa: E402
|
| 11 |
+
|
| 12 |
+
|
| 13 |
+
class TestRouterFallback(unittest.TestCase):
|
| 14 |
+
def test_returns_keywords(self) -> None:
|
| 15 |
+
d = classify_intent_fallback("I need a return label for order 9")
|
| 16 |
+
self.assertEqual(d.route, "returns")
|
| 17 |
+
self.assertFalse(d.escalate)
|
| 18 |
+
|
| 19 |
+
def test_billing_keywords(self) -> None:
|
| 20 |
+
d = classify_intent_fallback("Duplicate charge on my Visa")
|
| 21 |
+
self.assertEqual(d.route, "billing")
|
| 22 |
+
|
| 23 |
+
def test_escalate_legal(self) -> None:
|
| 24 |
+
d = classify_intent_fallback("I will contact my lawyer tomorrow")
|
| 25 |
+
self.assertTrue(d.escalate)
|
| 26 |
+
self.assertEqual(d.route, "support")
|
| 27 |
+
|
| 28 |
+
def test_generic_support(self) -> None:
|
| 29 |
+
d = classify_intent_fallback("The notifications tab freezes")
|
| 30 |
+
self.assertEqual(d.route, "support")
|
| 31 |
+
self.assertFalse(d.escalate)
|
| 32 |
+
|
| 33 |
+
|
| 34 |
+
if __name__ == "__main__":
|
| 35 |
+
unittest.main()
|
multi_agent_customer_support/tests/test_scenarios.py
ADDED
|
@@ -0,0 +1,153 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
"""
|
| 2 |
+
High-level scenario tests: billing (MCP tool functions), returns (A2A agent), escalation.
|
| 3 |
+
|
| 4 |
+
Uses mocks so no live Supabase, Gemini, or returns microservice is required.
|
| 5 |
+
"""
|
| 6 |
+
|
| 7 |
+
from __future__ import annotations
|
| 8 |
+
|
| 9 |
+
import json
|
| 10 |
+
import os
|
| 11 |
+
import sys
|
| 12 |
+
from unittest.mock import AsyncMock, patch
|
| 13 |
+
|
| 14 |
+
import pytest
|
| 15 |
+
|
| 16 |
+
_ROOT = os.path.abspath(os.path.join(os.path.dirname(__file__), ".."))
|
| 17 |
+
sys.path.insert(0, _ROOT)
|
| 18 |
+
|
| 19 |
+
from src.agents.billing_agent import BillingAgent # noqa: E402
|
| 20 |
+
from src.agents.router_agent import RouterAgent, RouterDecision # noqa: E402
|
| 21 |
+
from src.agents.support_agent import SupportAgent # noqa: E402
|
| 22 |
+
from src.agents.returns_remote_agent import ReturnsRemoteAgent # noqa: E402
|
| 23 |
+
|
| 24 |
+
|
| 25 |
+
def _make_router(
|
| 26 |
+
*,
|
| 27 |
+
billing: BillingAgent | None = None,
|
| 28 |
+
support: SupportAgent | None = None,
|
| 29 |
+
returns: ReturnsRemoteAgent | None = None,
|
| 30 |
+
) -> RouterAgent:
|
| 31 |
+
return RouterAgent(
|
| 32 |
+
billing=billing or BillingAgent(),
|
| 33 |
+
support=support or SupportAgent(),
|
| 34 |
+
returns=returns or ReturnsRemoteAgent("http://127.0.0.1:8081"),
|
| 35 |
+
)
|
| 36 |
+
|
| 37 |
+
|
| 38 |
+
@pytest.mark.asyncio
|
| 39 |
+
async def test_billing_scenario_mcp_tools_used() -> None:
|
| 40 |
+
"""
|
| 41 |
+
User asks about duplicate charges; router -> BillingAgent; offline path calls
|
| 42 |
+
``get_billing_info`` / ``get_support_tickets`` (same functions as the Supabase MCP server).
|
| 43 |
+
"""
|
| 44 |
+
query = "I was charged twice for my last order. Can you check my billing?"
|
| 45 |
+
customer_id = "billing-scenario@example.com"
|
| 46 |
+
|
| 47 |
+
billing_payload = {
|
| 48 |
+
"customer": {
|
| 49 |
+
"id": "c1",
|
| 50 |
+
"name": "Scenario User",
|
| 51 |
+
"email": customer_id,
|
| 52 |
+
},
|
| 53 |
+
"orders": [
|
| 54 |
+
{
|
| 55 |
+
"order_number": "ORD-1001",
|
| 56 |
+
"total_amount": 49.99,
|
| 57 |
+
"status": "paid",
|
| 58 |
+
}
|
| 59 |
+
],
|
| 60 |
+
"order_count": 1,
|
| 61 |
+
}
|
| 62 |
+
tickets_payload = {"tickets": [], "ticket_count": 0}
|
| 63 |
+
|
| 64 |
+
with (
|
| 65 |
+
patch("src.agents.billing_agent.genai_api_configured", return_value=False),
|
| 66 |
+
patch(
|
| 67 |
+
"src.agents.billing_agent.get_billing_info",
|
| 68 |
+
return_value=json.dumps(billing_payload),
|
| 69 |
+
) as mock_billing,
|
| 70 |
+
patch(
|
| 71 |
+
"src.agents.billing_agent.get_support_tickets",
|
| 72 |
+
return_value=json.dumps(tickets_payload),
|
| 73 |
+
) as mock_tickets,
|
| 74 |
+
):
|
| 75 |
+
router = _make_router()
|
| 76 |
+
out = await router.route_with_meta(customer_id, query)
|
| 77 |
+
|
| 78 |
+
assert out.routed_to == "billing"
|
| 79 |
+
assert out.escalated is False
|
| 80 |
+
mock_billing.assert_called_once()
|
| 81 |
+
mock_tickets.assert_called_once()
|
| 82 |
+
# Billing explanation from offline formatter
|
| 83 |
+
assert "billing" in out.answer.lower() or "BillingAgent" in out.answer
|
| 84 |
+
assert "ORD-1001" in out.answer or "order" in out.answer.lower()
|
| 85 |
+
|
| 86 |
+
|
| 87 |
+
@pytest.mark.asyncio
|
| 88 |
+
async def test_returns_scenario_eligibility_path() -> None:
|
| 89 |
+
"""
|
| 90 |
+
Returns query -> router picks returns; ``ReturnsRemoteAgent.check_return_eligibility``
|
| 91 |
+
is exercised with A2A stack mocked.
|
| 92 |
+
"""
|
| 93 |
+
query = "I want to return order 123456. Am I eligible?"
|
| 94 |
+
customer_id = "returns-user@example.com"
|
| 95 |
+
|
| 96 |
+
returns = ReturnsRemoteAgent("http://127.0.0.1:8081")
|
| 97 |
+
router = _make_router(returns=returns)
|
| 98 |
+
|
| 99 |
+
with patch.object(returns, "handle", new_callable=AsyncMock) as mock_handle:
|
| 100 |
+
mock_handle.return_value = (
|
| 101 |
+
"For order 123456, eligibility: yes — your order qualifies for a return."
|
| 102 |
+
)
|
| 103 |
+
routed = await router.route_with_meta(customer_id, query)
|
| 104 |
+
|
| 105 |
+
assert routed.routed_to == "returns"
|
| 106 |
+
assert routed.escalated is False
|
| 107 |
+
mock_handle.assert_called_once_with(customer_id, query)
|
| 108 |
+
assert "eligible" in routed.answer.lower() or "qualif" in routed.answer.lower()
|
| 109 |
+
|
| 110 |
+
with patch(
|
| 111 |
+
"src.agents.returns_remote_agent.run_llm_agent_once",
|
| 112 |
+
new_callable=AsyncMock,
|
| 113 |
+
) as mock_run:
|
| 114 |
+
mock_run.return_value = '{"eligible": true, "reason": "last digit even"}'
|
| 115 |
+
result = await returns.check_return_eligibility("123456")
|
| 116 |
+
mock_run.assert_awaited()
|
| 117 |
+
assert result.get("eligible") is True
|
| 118 |
+
assert "reason" in result
|
| 119 |
+
|
| 120 |
+
|
| 121 |
+
@pytest.mark.asyncio
|
| 122 |
+
async def test_escalation_scenario_flag() -> None:
|
| 123 |
+
"""
|
| 124 |
+
Security-sensitive message -> router escalates; metadata maps to ``escalated`` on
|
| 125 |
+
:class:`~src.agents.router_agent.RouterOutcome` (HTTP API uses ``escalated`` / ``routed_to``).
|
| 126 |
+
"""
|
| 127 |
+
query = (
|
| 128 |
+
"My account was hacked and all my orders disappeared "
|
| 129 |
+
"and support is ignoring me."
|
| 130 |
+
)
|
| 131 |
+
decision = RouterDecision(
|
| 132 |
+
route="support",
|
| 133 |
+
escalate=True,
|
| 134 |
+
rationale="account security / suspected compromise",
|
| 135 |
+
)
|
| 136 |
+
|
| 137 |
+
with (
|
| 138 |
+
patch("src.agents.router_agent.genai_api_configured", return_value=True),
|
| 139 |
+
patch(
|
| 140 |
+
"src.agents.router_agent.run_router_structured",
|
| 141 |
+
new_callable=AsyncMock,
|
| 142 |
+
return_value=decision,
|
| 143 |
+
),
|
| 144 |
+
):
|
| 145 |
+
router = _make_router()
|
| 146 |
+
out = await router.route_with_meta("cust-1", query)
|
| 147 |
+
|
| 148 |
+
assert out.escalated is True
|
| 149 |
+
assert out.routed_to == "escalate"
|
| 150 |
+
assert "[ESCALATE]" in out.answer
|
| 151 |
+
# Example metadata shape consumers may mirror
|
| 152 |
+
metadata = {"escalate": out.escalated, "routed_to": out.routed_to}
|
| 153 |
+
assert metadata["escalate"] is True
|
multi_agent_customer_support/tests/test_supabase_client.py
ADDED
|
@@ -0,0 +1,107 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
"""Unit tests for mcp.supabase_client (mocked Supabase)."""
|
| 2 |
+
|
| 3 |
+
import os
|
| 4 |
+
import sys
|
| 5 |
+
import unittest
|
| 6 |
+
from types import SimpleNamespace
|
| 7 |
+
from unittest.mock import MagicMock, patch
|
| 8 |
+
|
| 9 |
+
# Resolve `mcp` from src/ when tests are run without editable install.
|
| 10 |
+
_ROOT = os.path.abspath(os.path.join(os.path.dirname(__file__), ".."))
|
| 11 |
+
# Import via the `src` package (`src.mcp`) so we do not clash with PyPI `mcp` SDK.
|
| 12 |
+
sys.path.insert(0, _ROOT)
|
| 13 |
+
|
| 14 |
+
from src.mcp import supabase_client as sc # noqa: E402
|
| 15 |
+
|
| 16 |
+
|
| 17 |
+
class TestSupabaseClient(unittest.TestCase):
|
| 18 |
+
def setUp(self) -> None:
|
| 19 |
+
sc.reset_supabase_client_cache()
|
| 20 |
+
|
| 21 |
+
def tearDown(self) -> None:
|
| 22 |
+
sc.reset_supabase_client_cache()
|
| 23 |
+
|
| 24 |
+
def test_get_customer_by_email_empty_raises(self) -> None:
|
| 25 |
+
with self.assertRaises(ValueError):
|
| 26 |
+
sc.get_customer_by_email(" ")
|
| 27 |
+
|
| 28 |
+
@patch.object(sc, "get_supabase_client")
|
| 29 |
+
def test_get_customer_by_email_found(self, mock_get: MagicMock) -> None:
|
| 30 |
+
row = {"id": "1", "email": "a@b.com", "name": "A"}
|
| 31 |
+
chain = MagicMock()
|
| 32 |
+
mock_get.return_value.table.return_value = chain
|
| 33 |
+
chain.select.return_value.eq.return_value.limit.return_value.execute.return_value = (
|
| 34 |
+
SimpleNamespace(data=[row])
|
| 35 |
+
)
|
| 36 |
+
|
| 37 |
+
out = sc.get_customer_by_email("a@b.com")
|
| 38 |
+
self.assertEqual(out, row)
|
| 39 |
+
chain.select.assert_called_with("*")
|
| 40 |
+
chain.select.return_value.eq.assert_called_with("email", "a@b.com")
|
| 41 |
+
|
| 42 |
+
@patch.object(sc, "get_supabase_client")
|
| 43 |
+
def test_get_customer_by_email_not_found(self, mock_get: MagicMock) -> None:
|
| 44 |
+
chain = MagicMock()
|
| 45 |
+
mock_get.return_value.table.return_value = chain
|
| 46 |
+
chain.select.return_value.eq.return_value.limit.return_value.execute.return_value = (
|
| 47 |
+
SimpleNamespace(data=[])
|
| 48 |
+
)
|
| 49 |
+
self.assertIsNone(sc.get_customer_by_email("x@y.com"))
|
| 50 |
+
|
| 51 |
+
@patch.object(sc, "get_supabase_client")
|
| 52 |
+
def test_get_customer_by_id_found(self, mock_get: MagicMock) -> None:
|
| 53 |
+
row = {"id": "uuid-1", "email": "a@b.com", "name": "A"}
|
| 54 |
+
chain = MagicMock()
|
| 55 |
+
mock_get.return_value.table.return_value = chain
|
| 56 |
+
chain.select.return_value.eq.return_value.limit.return_value.execute.return_value = (
|
| 57 |
+
SimpleNamespace(data=[row])
|
| 58 |
+
)
|
| 59 |
+
|
| 60 |
+
out = sc.get_customer_by_id("uuid-1")
|
| 61 |
+
self.assertEqual(out, row)
|
| 62 |
+
chain.select.return_value.eq.assert_called_with("id", "uuid-1")
|
| 63 |
+
|
| 64 |
+
def test_get_customer_by_id_empty_raises(self) -> None:
|
| 65 |
+
with self.assertRaises(ValueError):
|
| 66 |
+
sc.get_customer_by_id(" ")
|
| 67 |
+
|
| 68 |
+
@patch.object(sc, "get_supabase_client")
|
| 69 |
+
def test_get_orders_by_customer(self, mock_get: MagicMock) -> None:
|
| 70 |
+
rows = [{"id": "o1", "customer_id": "c1"}]
|
| 71 |
+
chain = MagicMock()
|
| 72 |
+
mock_get.return_value.table.return_value = chain
|
| 73 |
+
chain.select.return_value.eq.return_value.order.return_value.execute.return_value = (
|
| 74 |
+
SimpleNamespace(data=rows)
|
| 75 |
+
)
|
| 76 |
+
|
| 77 |
+
out = sc.get_orders_by_customer("c1")
|
| 78 |
+
self.assertEqual(out, rows)
|
| 79 |
+
chain.select.return_value.eq.assert_called_with("customer_id", "c1")
|
| 80 |
+
chain.select.return_value.eq.return_value.order.assert_called()
|
| 81 |
+
|
| 82 |
+
@patch.object(sc, "get_supabase_client")
|
| 83 |
+
def test_get_support_tickets_by_category(self, mock_get: MagicMock) -> None:
|
| 84 |
+
rows = [{"id": "t1", "category": "billing"}]
|
| 85 |
+
chain = MagicMock()
|
| 86 |
+
mock_get.return_value.table.return_value = chain
|
| 87 |
+
chain.select.return_value.eq.return_value.order.return_value.execute.return_value = (
|
| 88 |
+
SimpleNamespace(data=rows)
|
| 89 |
+
)
|
| 90 |
+
|
| 91 |
+
out = sc.get_support_tickets_by_category("billing")
|
| 92 |
+
self.assertEqual(out, rows)
|
| 93 |
+
chain.select.return_value.eq.assert_called_with("category", "billing")
|
| 94 |
+
|
| 95 |
+
@patch.dict(
|
| 96 |
+
os.environ,
|
| 97 |
+
{"SUPABASE_URL": "", "SUPABASE_ANON_KEY": "", "SUPABASE_KEY": ""},
|
| 98 |
+
clear=False,
|
| 99 |
+
)
|
| 100 |
+
def test_configuration_error_missing_env(self) -> None:
|
| 101 |
+
sc.reset_supabase_client_cache()
|
| 102 |
+
with self.assertRaises(sc.SupabaseConfigurationError):
|
| 103 |
+
sc.get_supabase_client()
|
| 104 |
+
|
| 105 |
+
|
| 106 |
+
if __name__ == "__main__":
|
| 107 |
+
unittest.main()
|