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

# Classify Emails

> Build a lightweight Upsonic LLM agent that classifies fintech operation emails into specific categories.

This example demonstrates how to build a lightweight **Upsonic LLM agent** that classifies incoming fintech operation emails into specific categories — helping operations teams automatically sort and respond to critical messages.

<iframe src="https://www.youtube.com/embed/1aLcd0fSgfI" title="YouTube video player" frameborder="0" className="w-full aspect-video rounded-xl" allow="accelerometer; autoplay; clipboard-write; encrypted-media; gyroscope; picture-in-picture; web-share" allowfullscreen />

## Overview

In this example, the agent classifies emails into one of two categories:

1. **Information Requests** — messages requesting data such as account statements, balance history, or audit documents.
2. **Lien on Bank Account** — notifications indicating a lien, freeze, or court order on a customer account.

The agent uses a single LLM Task to perform the classification.\
There are no external integrations — just intelligent reasoning based on email content.

## Key Features

* **Autonomous Classification**: The LLM performs all reasoning — no manual logic or regex
* **Minimal Architecture**: One Task, one prompt, one result
* **Structured Output**: Uses Pydantic models for type-safe responses
* **Extendable**: Easily add new categories or integrate with real email systems

## Code Structure

### Response Model

```python theme={null}
class ClassificationResult(BaseModel):
    category: str  # "information_request" or "lien_on_bank_account"
```

### Agent Setup

```python theme={null}
classification_agent = Agent(name="email_classification_agent")
```

### Task Definition

```python theme={null}
task = Task(
    description=task_prompt.strip(),
    response_format=ClassificationResult,
)
```

### Example Emails

The script includes two sample emails:

**Email 1 - Information Request:**

```python theme={null}
email_1 = """
Dear Operations Team,

We are requesting detailed account statements for the last six months regarding the following customer.
Please include all transaction records, account balance history, and any associated documents.

This request is made in accordance with the Financial Supervision Act.
Sincerely,
Ministry of Finance - Audit Department
"""
```

**Email 2 - Lien on Bank Account:**

```python theme={null}
email_2 = """
To Whom It May Concern,

Please be advised that a lien has been placed on the following bank account pursuant to the court order No. 2025/482.
All transactions from this account should be temporarily frozen until further notice.

Best regards,
Tax Collection Office
"""
```

## Complete Implementation

```python theme={null}
from pydantic import BaseModel
from upsonic import Agent, Task

# --- Example Emails -----------------------------------------------------------

email_1 = """
Dear Operations Team,

We are requesting detailed account statements for the last six months regarding the following customer.
Please include all transaction records, account balance history, and any associated documents.

This request is made in accordance with the Financial Supervision Act.
Sincerely,
Ministry of Finance - Audit Department
"""

email_2 = """
To Whom It May Concern,

Please be advised that a lien has been placed on the following bank account pursuant to the court order No. 2025/482.
All transactions from this account should be temporarily frozen until further notice.

Best regards,
Tax Collection Office
"""

# --- Response Model -----------------------------------------------------------

class ClassificationResult(BaseModel):
    category: str  # "information_request" or "lien_on_bank_account"


# --- Agent Setup --------------------------------------------------------------

classification_agent = Agent(name="email_classification_agent")


# --- CLI + Task Definition ----------------------------------------------------

if __name__ == "__main__":
    import argparse

    parser = argparse.ArgumentParser(description="Classify incoming fintech operation emails.")
    parser.add_argument(
        "--email_id",
        type=int,
        default=1,
        help="Email number to classify (1 or 2)"
    )
    args = parser.parse_args()

    selected_email = email_1 if args.email_id == 1 else email_2

    # Prompt (LLM does all reasoning)
    task_prompt = f"""
You are an intelligent email classification agent working for a fintech company's operations department.

Your task is to classify the following email into one of two categories:
1. information_request — The sender requests account data, statements, or other informational documents.
2. lien_on_bank_account — The sender notifies about a lien, freeze, or legal restriction on a bank account.

Email content:
---
{selected_email}
---

Guidelines:
- If the email includes terms like "provide account information", "requesting data", "audit", "statements", "supervision" → classify as "information_request".
- If it mentions "lien", "freeze", "court order", "funds held", or "blocked account" → classify as "lien_on_bank_account".
- Return the result as a JSON object with field `category` and value either "information_request" or "lien_on_bank_account".
    """

    task = Task(
        description=task_prompt.strip(),
        response_format=ClassificationResult,
    )

    result = classification_agent.do(task)
    print("\n" + "=" * 60)
    print("📧 EMAIL CLASSIFICATION RESULT")
    print("=" * 60)
    print(result.model_dump_json(indent=2))
    print("=" * 60)
```

## How It Works

1. **Input**: The LLM receives the text of the email.
2. **Reasoning**: The agent analyzes the content and context — e.g., requests vs. legal notifications.
3. **Output**: Returns a structured JSON object with a single field:
   * `category`: `"information_request"` or `"lien_on_bank_account"`

## Usage

### Setup

```bash theme={null}
uv sync
```

### Run the classifier

```bash theme={null}
# Classify Email 1 (Information Request)
uv run examples/classify_emails/classify_emails.py --email_id 1

# Classify Email 2 (Lien on Bank Account)
uv run examples/classify_emails/classify_emails.py --email_id 2
```

### Example Output

**Email 1:**

```json theme={null}
{
  "category": "information_request"
}
```

**Email 2:**

```json theme={null}
{
  "category": "lien_on_bank_account"
}
```

## Use Cases

* **Fintech Operations**: Automatically sort incoming regulatory and legal emails
* **Compliance Departments**: Handle high email volume with intelligent routing
* **Customer Support**: Categorize support tickets and requests
* **Legal Teams**: Identify urgent legal notifications requiring immediate attention

## File Structure

```bash theme={null}
examples/classify_emails/
├── classify_emails.py      # Main LLM classification agent
└── README.md               # Documentation
```

## Repository

View the complete example: [Classify Emails Example](https://github.com/Upsonic/Examples/tree/master/examples/classify_emails)
