# Munshi AI API V1 Architecture

## Core rule
The AI model is never the authority for tenant identity or business data.

```text
Client / ERP / CRM
        |
        | X-API-Key
        v
+-----------------------+
| ai.munshiji.pk        |
| API Gateway           |
| Auth + Tenant Context |
| Conversation Store    |
| AI Provider Adapter   |
| Tool Registry         |
+-----------+-----------+
            |
            | authenticated tool call
            v
      Client's own backend
            |
            v
        Tenant DB
```

The API key maps to exactly one organization. Every conversation, message, tool and usage record is scoped to that organization.

## Why no direct tenant SQL
A generic AI SaaS should not receive arbitrary customer DB credentials or let a model generate SQL. The customer ERP/CRM exposes controlled tools such as:

- `get_customer_balance`
- `get_sales_summary`
- `get_invoice`
- `get_stock`

The AI can call only registered tools. The customer backend remains the source of truth.

## V1 local model
The first adapter uses Ollama. The model is local to the AI server, so there is no per-token cloud subscription. The provider adapter is isolated in `src/services/ai-provider.js` so another provider can be added without changing the API layer.

## Tenant isolation checklist
- API key -> organization on the server.
- No `tenant_id` accepted as an authority for database access.
- Conversation queries require organization ID.
- Tool queries require organization ID.
- Usage logs require organization ID.
- Remote tool hosts must be HTTPS and explicitly allowlisted.
- Tool execution has a timeout.
- One tool round per chat request in V1 to prevent loops.
