# Adding AI inside your app

> Add reliable AI assistants, summarizers, and structured extractors to your app with server-side provider keys, streaming UX, strict rate limits, and cost guards.

- Canonical: https://exaspark.ai/docs/ai-features-in-your-app/

## Building with ExaSpark vs adding AI inside your app

Start by separating two distinct layers. Building and editing your app inside ExaSpark uses your **ExaSpark build credits** across Free, Starter, or Pro plans.

Adding an AI assistant, summarizer, or extractor *inside* your published app for your own end users calls an external AI API — such as OpenAI, Anthropic, or Gemini — through your own server-side provider API key. Your backend handles authentication, context retrieval, and rate limits while your chosen provider bills token usage directly.

## Practical customer-facing AI patterns

The highest-value AI features solve one narrow workflow cleanly instead of dropping an ungrounded blank chat box onto every screen.

| AI feature pattern | Best UX surface | Response format | Primary safety & cost control |
| --- | --- | --- | --- |
| **Account-grounded assistant** | Help drawer or workspace panel | Streamed text (SSE) | Load only rows owned by the signed-in user |
| **Document or note summarizer** | Single-click button on saved notes | Streamed text or bullets | Cap input characters and cache result in **Cloud** |
| **Structured form extractor** | Paste receipt or email to pre-fill fields | Strict JSON schema | Validate server-side and let user confirm before saving |
| **Copy rewriting helper** | Inline "Improve listing" action | Short completion | Fast lightweight model with strict `max_tokens` |
| **Support ticket triage** | Background tagging on form submit | Enum JSON object | Constrain output strictly to allowed enum tags |

> **Note:** Ship structured extraction or single-click summarization before building open-ended chat. Narrow tasks run faster, cost far less per user, and stay easier to evaluate.

## Server-side security and tenant data isolation

Never invoke an AI API directly from frontend JavaScript. Routing every call through a dedicated server endpoint protects both your provider balance and customer privacy.

- **Keep provider keys server-side.** Save `OPENAI_API_KEY` or `ANTHROPIC_API_KEY` inside **Preview** and **Live** environment settings, never client bundles. See [Secrets & API keys](https://exaspark.ai/docs/secrets-and-env-vars/).
- **Require sign-in before paid inference.** Public unauthenticated AI endpoints get discovered and drained by bots quickly. Gate routes behind user sessions or active paid tiers verified in **Cloud**.
- **Scope context strictly by `user_id`.** When grounding answers with database rows (orders, projects, notes), run the exact same owner filter used by normal APIs so one customer never sees another tenant's data.
- **Treat user text as untrusted input.** Wrap pasted documents in explicit delimiters (such as `<document>...</document>`) and never let model output mutate database records or roles without server-side checks and user confirmation.

## Streaming UX, structured JSON, and fallbacks

AI responses can take `1` to `15` seconds. Choosing the right output mode keeps your app feeling snappy and dependable.

- **Stream reading experiences.** For assistants and summaries, stream tokens via Server-Sent Events (SSE) so first words appear within a second instead of staring at a frozen spinner.
- **Require strict JSON for UI fields.** For extractors or classifiers, request schema-validated JSON and verify types server-side before responding.

```json
{
  "name": "expense_extraction",
  "schema": {
    "type": "object",
    "required": ["vendor", "amount_minor", "currency", "category", "date"],
    "properties": {
      "vendor": { "type": "string" },
      "amount_minor": { "type": "integer" },
      "currency": { "type": "string", "enum": ["USD", "EUR", "GBP"] },
      "category": { "type": "string", "enum": ["travel", "meals", "software", "office", "other"] },
      "date": { "type": "string" }
    }
  }
}
```

Always enforce explicit request timeouts (`15`–`25` seconds), disable the submit button while pending to prevent double clicks, and render a calm retry banner when upstream providers return `429` or `503`.

## Rate limits, usage logs, and spend controls

An uncapped AI endpoint inside a `$9/month` membership can turn one heavy user into negative margin overnight. Combine three layers of cost defense:

- **Per-user quotas in Cloud.** Create an `ai_usage_logs` table storing `user_id`, `feature_name`, `input_tokens`, `output_tokens`, and `created_at`. Check daily or monthly counts server-side before calling the provider and return `429` with an upgrade prompt when exceeded.
- **Input size and `max_tokens` caps.** Reject oversized pastes (for example over `15,000` characters) cleanly and cap output length to match the screen.
- **Hard monthly spend limit at your provider.** Configure a strict monthly dollar cap and billing alerts inside OpenAI, Anthropic, or Google Cloud, using a separate low-cap key for **Preview**.

Cache stable results in **Cloud** whenever possible: saving a generated note summary directly onto the `notes` row lets repeat views load instantly at zero extra token cost.

## Shipping an AI feature step by step

1. **Define one narrow workflow** — Specify exact inputs, expected output shape, and which user roles or paid plans may call it.
2. **Provision separate Preview and Live keys** — Create a low-cap development key for **Preview** and a hard-capped production key for **Live**.
3. **Wire auth, validation, and `ai_usage_logs` first** — Enforce session verification, input limits, and daily per-user caps in your server route before styling the UI.
4. **Verify failure modes in Preview** — Test empty inputs, oversized pastes, hitting the daily quota (`429`), and signed-out calls (`401`).
5. **Track live usage after Publish** — Monitor `ai_usage_logs` in **Cloud (Live)** alongside provider billing dashboards during launch week and tune quotas as real usage patterns emerge.

> **Example prompt (App):** Add a "Project Assistant" drawer on /projects/:id for signed-in project members only. Create POST /api/ai/project-chat that verifies session and project membership server-side, checks ai_usage_logs in Cloud to enforce 25 requests per user per day (returning 429 when exceeded), loads only that project's tasks and notes as context, calls our AI API via process.env.AI_API_KEY with a 20-second timeout and max_tokens=800, streams the reply to the drawer, and logs token usage.

> **Example prompt (App):** Add an "Auto-fill from text" box on /expenses/new. Send pasted receipt text (max 4,000 chars) to POST /api/ai/extract-expense using process.env.AI_API_KEY. Require strict JSON matching vendor, amount_minor, currency, category, and date, validate fields server-side, populate the form for user confirmation without auto-saving, and cap signed-in users at 30 runs per day.

## Common mistakes and troubleshooting

| Symptom | Root cause | Exact fix |
| --- | --- | --- |
| **Provider key flagged or visible in browser** | AI SDK ran inside frontend code instead of a server route | Revoke the key immediately, move calls server-side, and rotate to a fresh secret |
| **Extractor UI breaks on occasional inputs** | Model returned prose around JSON without schema checks | Enable structured JSON output, validate server-side, and show a clean retry state |
| **Surprise spike in AI provider bill** | Route lacked authentication, paste caps, or per-user limits | Require sign-in, enforce `ai_usage_logs` caps, and set a hard monthly provider cap |
| **Assistant exposes another user's records** | Context query missed `user_id` ownership filtering | Filter every context query strictly by the authenticated user's session ID and role |
| **Double charges from impatient clicks** | Button stays active during a multi-second wait | Disable submit while pending, stream replies, and cache saved summaries in **Cloud** |

## Next steps

- [Secrets & API keys](https://exaspark.ai/docs/secrets-and-env-vars/) — Keep AI provider keys strictly server-side across Preview and Live.
- [Row-level data privacy](https://exaspark.ai/docs/row-level-data-privacy/) — Enforce strict per-user database boundaries before grounding AI prompts.
- [External APIs & webhooks](https://exaspark.ai/docs/external-apis-and-webhooks/) — Handle upstream timeouts, retries, and clean error states reliably.

## From the blog

- [What is an AI agent?](https://exaspark.ai/blog/what-is-an-ai-agent/) — Understand how grounded AI tools reason and stay reliable.
- [How to build a SaaS product](https://exaspark.ai/blog/how-to-build-a-saas-product/) — Package paid AI features cleanly behind tiered plans.
- [App security checklist](https://exaspark.ai/blog/app-security-checklist/) — Protect customer privacy and API keys before going live.
