> ## Documentation Index
> Fetch the complete documentation index at: https://docs.praison.ai/llms.txt
> Use this file to discover all available pages before exploring further.

# Customer Service

> Multi-agent support system with routing, knowledge base, and ticket persistence

```mermaid theme={"theme":{"light":"vitesse-light","dark":"vitesse-dark"}}
flowchart LR
    In[Customer Query] --> C[Classifier]
    C --> R[Resolver]
    R --> Out[Response]
    
    style In fill:#8B0000,color:#fff
    style C fill:#2E8B57,color:#fff
    style R fill:#2E8B57,color:#fff
    style Out fill:#8B0000,color:#fff
```

Automated customer support: query classification → knowledge retrieval → response generation → satisfaction tracking. Includes SQLite ticket persistence, web search for FAQs, and API deployment.

## Setup

```bash theme={"theme":{"light":"vitesse-light","dark":"vitesse-dark"}}
# Create environment
python3 -m venv venv && source venv/bin/activate

# Install packages
pip install praisonaiagents praisonai

# Set API keys
export OPENAI_API_KEY="your-key"
export TAVILY_API_KEY="your-key"  # For knowledge search
```

## Create Sample Data

```bash theme={"theme":{"light":"vitesse-light","dark":"vitesse-dark"}}
# Create FAQ knowledge base
cat > faq.json << 'EOF'
[
  {"q": "How do I reset my password?", "a": "Go to Settings > Security > Reset Password"},
  {"q": "What are your business hours?", "a": "Mon-Fri 9am-6pm EST"},
  {"q": "How do I cancel my subscription?", "a": "Go to Account > Billing > Cancel Plan"},
  {"q": "What payment methods do you accept?", "a": "Visa, Mastercard, PayPal, Apple Pay"}
]
EOF
```

## Run: Python Code

```python theme={"theme":{"light":"vitesse-light","dark":"vitesse-dark"}}
from praisonaiagents import Agent, AgentTeam, Task, tool, db
import json

# Database for ticket persistence
db_instance = db(database_url="sqlite:///tickets.db")

# Load FAQ knowledge base
@tool
def search_faq(query: str) -> str:
    """Search FAQ knowledge base for answers."""
    with open("faq.json") as f:
        faqs = json.load(f)
    for faq in faqs:
        if any(word in faq["q"].lower() for word in query.lower().split()):
            return f"FAQ Match: {faq['a']}"
    return "No FAQ match found. Escalate to human agent."

@tool
def create_ticket(customer_id: str, issue: str, priority: str) -> str:
    """Create a support ticket."""
    import uuid
    ticket_id = f"TKT-{uuid.uuid4().hex[:8].upper()}"
    return json.dumps({"ticket_id": ticket_id, "customer_id": customer_id, "issue": issue, "priority": priority, "status": "open"})

# Agents
classifier = Agent(
    name="QueryClassifier",
    instructions="""Classify customer queries into categories:
    - billing: payment, subscription, refund
    - technical: bugs, errors, how-to
    - general: hours, contact, policies
    Return: {category, priority: high/medium/low}""",
    memory={
        "db": "sqlite:///tickets.db",
        "session_id": "support-session"
    }
)

resolver = Agent(
    name="QueryResolver",
    instructions="Search FAQ and provide helpful answers. Create tickets for complex issues.",
    tools=[search_faq, create_ticket]
)

# Tasks
classify_task = Task(
    description="Classify this customer query: {query}",
    agent=classifier,
    expected_output="JSON with category and priority"
)

resolve_task = Task(
    description="Resolve the customer issue using FAQ search. Create ticket if needed.",
    agent=resolver,
    expected_output="Resolution or ticket creation confirmation"
)

# Run
agents = AgentTeam(agents=[classifier, resolver], tasks=[classify_task, resolve_task])
result = agents.start(query="How do I reset my password?")
print(result)
```

## Run: CLI

```bash theme={"theme":{"light":"vitesse-light","dark":"vitesse-dark"}}
# Single query
praisonai "Customer asks: How do I cancel my subscription?" --memory --user-id support1

# With web search for complex queries
praisonai "Customer reports: App crashes on login" --web-search --verbose

# Interactive support mode
praisonai chat --memory --user-id support_agent
```

## Run: agents.yaml

Create `agents.yaml`:

```yaml theme={"theme":{"light":"vitesse-light","dark":"vitesse-dark"}}
framework: praisonai
topic: "customer support automation"
roles:
  classifier:
    role: Query Classifier
    goal: Categorize and prioritize customer queries
    backstory: Expert at understanding customer intent
    tasks:
      classify:
        description: |
          Classify query into: billing, technical, general
          Assign priority: high, medium, low
        expected_output: JSON with category and priority
        
  resolver:
    role: Support Agent
    goal: Resolve customer issues quickly
    backstory: Experienced customer support specialist
    tools:
      - tavily_search
    tasks:
      resolve:
        description: |
          Search for solution and provide helpful response.
          If complex, recommend ticket creation.
        expected_output: Resolution or escalation recommendation
        
  satisfaction:
    role: Quality Analyst
    goal: Ensure customer satisfaction
    backstory: Expert at measuring support quality
    tasks:
      evaluate:
        description: Rate the resolution quality 1-5 and suggest improvements
        expected_output: Quality score and recommendations
```

Run:

```bash theme={"theme":{"light":"vitesse-light","dark":"vitesse-dark"}}
praisonai agents.yaml --verbose
```

## Monitor & Verify

```bash theme={"theme":{"light":"vitesse-light","dark":"vitesse-dark"}}
# View support history
praisonai --history 10 --user-id support1

# Check metrics
praisonai --metrics

# Export tickets
praisonai --save support_tickets
```

## Serve API

```python theme={"theme":{"light":"vitesse-light","dark":"vitesse-dark"}}
from praisonaiagents import Agent, tool
import json

@tool
def search_faq(query: str) -> str:
    """Search FAQ for answers."""
    faqs = [
        {"q": "reset password", "a": "Settings > Security > Reset"},
        {"q": "cancel", "a": "Account > Billing > Cancel"}
    ]
    for faq in faqs:
        if faq["q"] in query.lower():
            return faq["a"]
    return "Please contact support@example.com"

agent = Agent(
    name="SupportAPI",
    instructions="Answer customer questions using FAQ search.",
    tools=[search_faq]
)

agent.launch(path="/support", port=8000)
```

Test:

```bash theme={"theme":{"light":"vitesse-light","dark":"vitesse-dark"}}
curl -X POST http://localhost:8000/support \
  -H "Content-Type: application/json" \
  -d '{"message": "How do I reset my password?"}'
```

## Cleanup

```bash theme={"theme":{"light":"vitesse-light","dark":"vitesse-dark"}}
rm -f tickets.db faq.json
deactivate
```

## Features Demonstrated

| Feature            | Implementation                   |
| ------------------ | -------------------------------- |
| **Multi-agent**    | Classifier + Resolver workflow   |
| **Knowledge Base** | JSON FAQ with `@tool` search     |
| **Ticket System**  | `create_ticket` tool             |
| **DB Persistence** | SQLite via `db()`                |
| **CLI**            | `praisonai chat` for interactive |
| **YAML Config**    | 3-agent support pipeline         |
| **API Endpoint**   | `agent.launch()`                 |
| **Session Resume** | `session_id` parameter           |
