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.

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 patternBest UX surfaceResponse formatPrimary safety & cost control
Account-grounded assistantHelp drawer or workspace panelStreamed text (SSE)Load only rows owned by the signed-in user
Document or note summarizerSingle-click button on saved notesStreamed text or bulletsCap input characters and cache result in Cloud
Structured form extractorPaste receipt or email to pre-fill fieldsStrict JSON schemaValidate server-side and let user confirm before saving
Copy rewriting helperInline "Improve listing" actionShort completionFast lightweight model with strict max_tokens
Support ticket triageBackground tagging on form submitEnum JSON objectConstrain output strictly to allowed enum tags

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.
  • 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.

Starter 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.

Starter 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

SymptomRoot causeExact fix
Provider key flagged or visible in browserAI SDK ran inside frontend code instead of a server routeRevoke the key immediately, move calls server-side, and rotate to a fresh secret
Extractor UI breaks on occasional inputsModel returned prose around JSON without schema checksEnable structured JSON output, validate server-side, and show a clean retry state
Surprise spike in AI provider billRoute lacked authentication, paste caps, or per-user limitsRequire sign-in, enforce ai_usage_logs caps, and set a hard monthly provider cap
Assistant exposes another user's recordsContext query missed user_id ownership filteringFilter every context query strictly by the authenticated user's session ID and role
Double charges from impatient clicksButton stays active during a multi-second waitDisable submit while pending, stream replies, and cache saved summaries in Cloud

Next steps

Still have a question?Ask our team and other builders on Discord.

From the blog