Skip to content
SPURT.

Engineering

Adding AI to your web app: three patterns that work (with code)

A catalogue chat assistant, invoice extraction and smarter search for your web app, with working code, real API prices and India's privacy rules.

By , Engineering

Published · 8 min read

In this article · 8
  1. Which AI features are worth building first?
  2. How do you build a chat assistant grounded in your catalogue?
  3. How do you extract data from invoices and forms?
  4. How do you make search understand what customers mean?
  5. How do you know it’s working after launch?
  6. What does it cost to run?
  7. What about privacy and India’s DPDP Act?
  8. Sources

Short answer Start with narrow jobs where a wrong answer is cheap to catch: a chat assistant that answers only from your catalogue, extracting document fields into a form a person confirms, and search that understands what customers mean. Keep API keys on the server, send the model only the data it needs, and log the cost of every request.

Most of the software we build doesn't need AI. When it does, these are the three patterns worth building, and the guardrails we'd put on each.

Which AI features are worth building first?

The ones where a person or a rule can catch mistakes before they matter.

PatternGood forMain riskThe check that catches it
Chat assistant grounded in your catalogueAnswering "do you have…", "what's the price of…", "which one suits…"Inventing a product, price or policyAnswer only from retrieved records; hand off to a person otherwise
Document extractionSupplier invoices, application forms, purchase ordersMisreading a numberSchema-validated output, arithmetic checks, human confirmation
Meaning-based searchCatalogues where customers and your data use different wordsIrrelevant resultsKeyword search first, meaning-based search as a fallback

Features where the model acts on its own, such as sending messages, issuing refunds or editing records, come later, if at all. Our MVP guide explains why they rarely belong in a first version.

How do you build a chat assistant grounded in your catalogue?

Don't ask the model what it knows about your products. It doesn't know them. Search your own database first, pass the matches in, and tell it to answer only from those.

Here's a Next.js route handler using the Anthropic TypeScript SDK. The same shape works with any provider.

ts
// app/api/ask/route.ts
import Anthropic from '@anthropic-ai/sdk'
import { searchProducts } from '@/lib/catalogue' // your own database query

const client = new Anthropic() // reads ANTHROPIC_API_KEY, on the server only

const SYSTEM = `You answer customer questions for a shop, using ONLY the products given.
If the answer isn't in the products, say you don't know and suggest WhatsApp.
Quote prices exactly as given. Never invent stock, discounts or delivery dates.`

export async function POST(req: Request) {
  const { question } = await req.json()
  if (typeof question !== 'string' || question.length > 500) {
    return Response.json({ error: 'Ask a question under 500 characters.' }, { status: 400 })
  }

  const products = await searchProducts(question, 8) // top matches only

  const res = await client.messages.create({
    model: 'claude-opus-5-5',
    max_tokens: 16000, // a ceiling: you pay only for tokens actually generated
    output_config: { effort: 'low' },
    system: SYSTEM,
    messages: [
      { role: 'user', content: `Products:\n${JSON.stringify(products)}\n\nQuestion: ${question}` },
    ],
  })

  if (res.stop_reason === 'refusal') {
    return Response.json({ answer: "I can't help with that here. Please message us on WhatsApp." })
  }
  const answer = res.content.flatMap((b) => (b.type === 'text' ? [b.text] : [])).join('')
  console.log('ai_usage', res.usage.input_tokens, res.usage.output_tokens)
  return Response.json({ answer })
}

What matters more than the code:

  • Retrieval decides quality. If searchProducts returns the wrong eight products, the answer will be wrong. Spend your time here.
  • Hand off gracefully. "I don't know, message us on WhatsApp" is a good answer. On B.S. Desai's site, enquiries already go to the artist as a pre-filled WhatsApp message, and an assistant would hand off the same way.
  • Cap the input and rate-limit the route. A public endpoint that calls a paid API is an invitation to run up your bill.
  • Test with real questions. Collect 30 questions your staff actually get, including the awkward ones, and check the answers before launch and after every prompt change.

We've prototyped this pattern in a jewellery showroom demo, where the assistant reads live gold and silver rates that the server fetches and caches. The assistant can only be as accurate as the data you hand it.

How do you extract data from invoices and forms?

Ask the model for a fixed structure, validate it in code, and show it to a person before anything is saved. The Anthropic SDK's messages.parse takes a Zod schema and returns a typed object, or null if the output didn't fit (structured outputs docs).

ts
import Anthropic from '@anthropic-ai/sdk'
import { zodOutputFormat } from '@anthropic-ai/sdk/helpers/zod'
import { z } from 'zod'

const Invoice = z.object({
  supplierName: z.string(),
  supplierGstin: z.string().nullable(),
  invoiceNumber: z.string(),
  invoiceDate: z.string().describe('YYYY-MM-DD'),
  taxableValue: z.number(),
  cgst: z.number(),
  sgst: z.number(),
  igst: z.number(),
  total: z.number(),
})

const client = new Anthropic()

export async function extractInvoice(pdf: Buffer) {
  const res = await client.messages.parse({
    model: 'claude-opus-5-5',
    max_tokens: 16000,
    messages: [{
      role: 'user',
      content: [
        { type: 'document', source: { type: 'base64', media_type: 'application/pdf', data: pdf.toString('base64') } },
        { type: 'text', text: 'Extract these invoice fields. Use null for a missing GSTIN. Amounts in rupees.' },
      ],
    }],
    output_config: { format: zodOutputFormat(Invoice) },
  })
  return res.parsed_output // null if it couldn't be parsed: fall back to manual entry
}

const GSTIN = /^[0-9]{2}[A-Z]{5}[0-9]{4}[A-Z][1-9A-Z]Z[0-9A-Z]$/

export function needsReview(inv: z.infer<typeof Invoice>) {
  const taxesAddUp = Math.abs(inv.taxableValue + inv.cgst + inv.sgst + inv.igst - inv.total) <= 1
  const gstinOk = inv.supplierGstin === null || GSTIN.test(inv.supplierGstin)
  return !taxesAddUp || !gstinOk
}

A valid structure isn't the same as correct values. The needsReview check catches the two mistakes that matter most on an Indian invoice: taxes that don't add up to the total, and a GSTIN in the wrong format. Anything flagged goes to a person, and nothing goes into your books until someone has confirmed it. Extraction that isn't urgent, such as a month of scanned bills, can go through the Batch API at half price (Anthropic pricing).

How do you make search understand what customers mean?

Start without AI. Postgres full-text search handles stemming and ranking, and it's already in your database:

sql
-- 1. Keyword search: no extra service needed
alter table products add column search tsvector
  generated always as (to_tsvector('english', name || ' ' || coalesce(description, ''))) stored;
create index products_search_idx on products using gin (search);

select id, name from products
where search @@ websearch_to_tsquery('english', $1)
order by ts_rank(search, websearch_to_tsquery('english', $1)) desc
limit 10;

-- 2. Meaning-based search, when customers use different words
create extension if not exists vector;
alter table products add column embedding vector(1024);

select id, name from products
order by embedding <=> $1 -- cosine distance to the query's embedding
limit 10;

Add embeddings when keyword search visibly fails: customers searching in their own words, a mix of English and regional terms, or descriptions rather than product names. The pgvector extension keeps vectors in the same Postgres database. Anthropic doesn't offer its own embedding model and points to Voyage AI in its embeddings guide. Whichever you use, run both searches and merge the results, so exact matches such as product codes still come first.

How do you know it's working after launch?

Log every question and every answer, and read them. For the first month, a weekly review of the log is worth more than any dashboard.

  • Questions it couldn't answer are your content gaps: products missing from the catalogue, policies nobody wrote down, or search terms your retrieval doesn't match.
  • Handoffs to WhatsApp tell you how much work the assistant is actually taking off your staff. If most questions end in a handoff, fix retrieval before touching the prompt.
  • Answers a customer disputed go straight into your test set of real questions.
  • Cost per day should be flat and boring. A spike usually means a loop, a bot, or someone probing the endpoint.

Re-run the full test set after every change to the prompt, the model or the retrieval. Changes that look harmless often aren't.

What does it cost to run?

Less than most people fear, if you measure it. Published API prices per million tokens (Anthropic pricing), as of 29 September 2026:

ModelInputOutput
Claude Opus 5.5$4$20
Claude Sonnet 5.5$2$10
Claude Haiku 4.5$1$5

A worked example, with assumed sizes: 1,000 questions a month, each with about 3,000 input tokens (instructions, eight products and the question) and 300 output tokens.

  • On Claude Opus 5.5: 3 million input tokens × $4 plus 0.3 million output tokens × $20 comes to about $18 a month. Opus 5.5 also thinks before answering, and those tokens bill as output, so real usage will be somewhat higher.
  • On Claude Haiku 4.5: about $4.50 a month.

Your token counts will differ, which is why the route above logs usage on every call. Two more levers: repeated instructions can be cached at a fraction of the input price, and the Batch API halves the price of anything that can wait. Choose the model by testing your 30 real questions on each, not by price alone.

What about privacy and India's DPDP Act?

  • Training. Anthropic says it won't use inputs or outputs from its commercial products, including the API, to train models by default (Anthropic Privacy Center). OpenAI says API data isn't used for training unless you opt in, and keeps abuse-monitoring logs for up to 30 days (OpenAI: your data). Read the current terms of whichever provider you use.
  • Send the minimum. A product question doesn't need the customer's name or phone number. Strip personal data before it leaves your server.
  • The DPDP Act applies. If you process customers' personal data, the Digital Personal Data Protection Act, 2023 applies, with Rules notified in November 2025 and phased in over 18 months (PIB). Say in your privacy notice that an AI service processes queries.
  • Treat documents as data, not instructions. Text inside an uploaded PDF or a web page can try to redirect the model. OWASP puts prompt injection, including this indirect kind, first in its list of risks for LLM applications (OWASP LLM01). That's the strongest argument for keeping a person between the model and anything that changes your records.
  • Keys stay on the server. Never call a model API from browser code.

If you're planning an AI feature for an existing product, our custom software team builds this kind of integration, and our web development team can add a catalogue assistant to a site like Siddhani Enterprises' product pages.

Sources

Frequently asked questions

How much does it cost to add an AI assistant to a website?

The API cost is usually small next to the build cost. At published prices, 1,000 questions a month with about 3,000 input and 300 output tokens each costs roughly $4.50 on Claude Haiku 4.5 or $18 on Claude Opus 5.5, before thinking tokens. Measure your own token counts from the API's usage field, and set a monthly spending limit.

Will the AI provider train its models on my business data?

Not by default with the major business APIs. Anthropic says it won't use inputs or outputs from its commercial products, including the API, to train its models by default. OpenAI says data sent to its API isn't used for training unless you opt in. Retention rules differ by provider, so read the current terms before sending customer data.

How do I stop an AI assistant from making things up about my products?

Don't let it answer from memory. Search your own catalogue first, pass only the matching products to the model, and instruct it to answer only from them and to say when it doesn't know. Hand off to a person, on WhatsApp or a form, for anything outside the list. Then test it with the awkward questions your staff get every week.

Do I need a vector database to add AI search to my site?

Usually not at first. Postgres full-text search handles most product and document searches with no extra service. Add embeddings when customers describe things in words your catalogue doesn't use. Even then, the pgvector extension keeps the vectors inside the Postgres database you already run, so there's no separate system to maintain.

Start a project

Tell us what you’re building. One of the founders — not a sales team — comes back with questions, a plan and a fixed quote.