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

# AI Assistant (Chat)

> Conversational AI assistant for financial insights, actions, and guidance

## Overview

The AI Assistant provides a secure, conversational chat experience to query finances, get insights, and trigger actions. Conversations are persisted per user and protected by authentication.

<CardGroup cols={3}>
  <Card title="Persistent Conversations" icon="message-circle">
    Your chats are saved with full history per conversation.
  </Card>

  <Card title="Context-Aware" icon="brain">
    Answers leverage your data, preferences, and patterns.
  </Card>

  <Card title="Secure by Default" icon="shield">
    All endpoints require auth and are isolated per user.
  </Card>
</CardGroup>

## Quick Start (App UI)

<Steps>
  <Step title="Open Chat">
    Click the chat button in the app to open the assistant.
  </Step>

  <Step title="Start a Conversation">
    Ask a question or create a new conversation to keep topics organized.
  </Step>

  <Step title="Refine & Act">
    Follow up for deeper insights or ask the assistant to perform supported actions.
  </Step>
</Steps>

## What the AI Assistant Can Do

<Columns cols={2}>
  <Card title="Transaction Intelligence" icon="search">
    * Ask natural-language questions about any transaction, category, merchant, or amount range
    * Filter by GST inclusion, business use %, missing receipts, or bill pattern status on demand
    * Run spending analytics (totals, trends, comparisons) with a single prompt
  </Card>

  <Card title="Receipt Control" icon="camera">
    * Upload a photo or PDF and let the assistant extract merchant, date, total, and GST automatically
    * Match the file to existing transactions or create a new expense instantly
    * Attach receipts to recurring bill occurrences so every payment stays audit ready
  </Card>
</Columns>

<Columns cols={2}>
  <Card title="GST & Tax Guidance" icon="calculator">
    * Query "What is my GST liability this quarter?" for live breakdowns using stored `gstRateUsed` and `gstAmount` values
    * Validate deductible status, business-use percentages, and required documentation per locale
    * Generate summaries for tax exports, BAS, or VAT filings without leaving chat
  </Card>

  <Card title="Bulk Automation" icon="layers">
    * Commands like "Categorize every Uber ride as Transport" trigger bulk update tools securely
    * Run pattern maintenance (link/unlink bills, mark occurrences paid) while the assistant handles ids
    * Request budgeting insights or forecast renewals and receive structured, exportable answers
  </Card>
</Columns>

## Receipt Capture Workflow

<Steps>
  <Step title="Capture the Receipt">
    Tap the camera icon on mobile or attach a PDF/image from desktop. Supported formats include JPG, PNG, PDF, HEIC.
  </Step>

  <Step title="AI Extraction">
    The assistant invokes `analyze_receipt` to pull merchant, amount, date, GST, and line items with ±7 day/±1% matching tolerance.
  </Step>

  <Step title="Confirm Action">
    Choose to link the receipt to a suggested transaction or create a new expense. You can also request a bill pattern link in the same message.
  </Step>

  <Step title="Audit Trail">
    The assistant stores the attachment reference so tax exports, deduction reports, and missing-receipt filters stay accurate.
  </Step>
</Steps>

## Conversational Patterns & Bills

* "Show bills missing receipts" lists recurring occurrences lacking documentation.
* "Mark my electricity bill as paid" updates the occurrence and logs the action.
* "Forecast my SaaS renewals with GST" combines pattern data and tax rates for forward planning.

## GST & Tax Expertise

* Country-specific rates from the `CountryTaxRate` service answer GST/VAT queries with local terminology.
* Commands like "Is this expense deductible in Canada?" trigger intelligent tax analysis with reasoning, warnings, and documentation checklists.
* The assistant can refresh `gstIncluded`, `gstRateUsed`, and `gstAmount` fields when you provide corrected totals.

## API Endpoints

All endpoints require a valid `Authorization: Bearer <token>` header. Errors include an `X-Error-ID` header for support tracing.

### Send Message

POST `/api/chat/message`

Request body:

```json theme={null}
{ "message": "string", "conversationId": "optional" }
```

Successful response:

```json theme={null}
{
  "success": true,
  "data": {
    "conversationId": "uuid",
    "message": {
      "id": "uuid",
      "conversationId": "uuid",
      "role": "assistant",
      "content": "...",
      "createdAt": "ISO-8601"
    },
    "toolsUsed": ["optional", "list"]
  }
}
```

### List Conversations

GET `/api/chat/conversations`

Response:

```json theme={null}
{ "success": true, "data": [ { "id": "uuid", "title": "AI2Fin Assistant", "messageCount": 0, "createdAt": "ISO-8601", "updatedAt": "ISO-8601" } ] }
```

### Create Conversation

POST `/api/chat/conversations`

Response:

```json theme={null}
{ "success": true, "data": { "id": "uuid" } }
```

### Get Conversation Messages

GET `/api/chat/conversations/:id`

Response:

```json theme={null}
{ "success": true, "data": [ { "id": "uuid", "role": "user", "content": "...", "createdAt": "ISO-8601" } ] }
```

## Authentication

All endpoints are protected with the platform auth middleware. Provide a valid bearer token. Server-side requires `OPENAI_API_KEY` configured.

## Examples

```bash theme={null}
curl -X POST https://app.ai2fin.com/api/chat/message \
  -H "Authorization: Bearer $TOKEN" \
  -H "Content-Type: application/json" \
  -d '{"message":"Summarize my last 5 expenses","conversationId":"$CID"}'
```

```bash theme={null}
curl -X GET https://app.ai2fin.com/api/chat/conversations \
  -H "Authorization: Bearer $TOKEN"
```

```bash theme={null}
curl -X POST https://app.ai2fin.com/api/chat/conversations \
  -H "Authorization: Bearer $TOKEN"
```

```bash theme={null}
curl -X GET https://app.ai2fin.com/api/chat/conversations/$CID \
  -H "Authorization: Bearer $TOKEN"
```

## Notes

* Responses may include `toolsUsed` when the assistant invoked internal tools.
* On failures, the API returns `{ success: false, error }` and sets `X-Error-ID`.
* Conversation history is retained for continuity and auditability.
