Adding AI to a Web App: RAG, Extraction, and Safe Automation

Start an AI integration with a bounded task and an evaluation method. Drafting a reply, extracting invoice fields, finding a policy paragraph, and updating a customer account have different failure costs. They should not share the same architecture simply because all can call a language model.
For a first release, choose a workflow where the output can be checked, a person can correct mistakes, and the benefit can be measured against the existing process. This guide outlines four implementation patterns, a document-processing example, and the checks needed before giving AI access to business data or actions.
Choose the simplest pattern that fits the task
| Pattern | Useful for | ★ Main failure to handle |
|---|---|---|
| Direct generation | Drafts, summaries, suggested replies | Unsupported or incomplete statements |
| Structured extraction | Turning documents into typed fields | Plausible but incorrect field values |
| Retrieval-augmented generation | Answering questions from an approved knowledge base | Missing, stale, or unauthorized evidence |
| Tool-assisted workflow | Preparing or performing actions across systems | Incorrect, repeated, or unauthorized actions |
Use deterministic code for exact calculations, permission decisions, and known business rules. An LLM can help interpret messy text; it should not decide whether a user is allowed to view a customer's invoice.
Example: invoice extraction with human review
Consider an illustrative workflow that receives an invoice, proposes structured fields, and asks an operator to approve the result before it reaches an accounting system. This is an architecture example, not a claim about a client deployment or a measured productivity improvement.
- Authenticate the uploader, check file type and size, and store the file with an access policy.
- Create a background job with a stable document identifier and processing status.
- Extract text or use a suitable document model; preserve page references where possible.
- Ask for structured fields such as supplier, invoice number, currency, date, and totals.
- Validate the schema, then separately check business rules and arithmetic.
- Show the proposed values alongside the source document for operator approval.
- Write approved data using an idempotency key and record the external system's response.
A response matching a JSON schema can still contain the wrong supplier or amount. Schema validation checks structure; it does not establish truth. Missing values should be represented as missing rather than filled with a plausible guess.
Handle duplicate uploads, encrypted or unreadable files, multi-invoice PDFs, credit notes, and vendor outages explicitly. A retry must not create a second accounting entry. The useful product is the complete review and recovery workflow, not just the successful model call.
When RAG is the right next step
Retrieval-augmented generation retrieves relevant material and includes it in the model's context before generating an answer. It is useful when answers need private or changing reference information, such as customer-specific documentation or internal policies.
A typical pipeline ingests documents, splits them into passages, stores searchable representations and metadata, retrieves candidate passages, and generates a response with references. Keyword search, semantic search, or a combination may be appropriate. Test retrieval quality before deciding that a vector database solves the problem.
RAG does not guarantee correct answers or instant freshness. Ingestion can lag, retrieval can miss a passage, and the model can misinterpret what it receives. Include document versions, deletion handling, and an answer that clearly states when evidence is insufficient.
Authorize retrieval before data reaches the model
Apply user and tenant permissions within the retrieval system. Do not retrieve a broad set of private records and ask the model to hide unauthorized content. The model should only receive material the requester is allowed to see.
Include the tenant and authorization scope in cache keys. When a document's access changes, invalidate or re-evaluate cached answers and searchable copies. Protect source-document links too; a citation must not bypass the permission system.
Treat retrieved documents as untrusted input. A file can contain instructions designed to redirect the model. Keep tool permissions separate from document content, restrict available actions, and test attempts to reveal other tenants' data or override the task. Prompt wording alone is not a security boundary.
Retrieval and fine-tuning solve different problems
RAG is a useful starting point when the problem is finding current reference material. Fine-tuning may help adapt behavior or output patterns when examples and an evaluation set support that choice. It is not a replacement for retrieval permissions or a dependable store of changing facts.
Start with a baseline prompt and representative tests. Add retrieval when missing knowledge is the limiting factor. Consider fine-tuning only when you can identify a behavior problem and measure whether training improves it. Combining methods can make sense; neither should be a default purchase.
For implementation background, see the OpenAI retrieval guide and the OWASP prompt injection prevention guidance. These describe mechanisms and safeguards, not a guarantee that a particular application is safe.
Build an evaluation set before a pilot
Collect representative examples that you have permission to use. Include ordinary cases, difficult layouts, missing information, ambiguous questions, and inputs that should be rejected. Keep a held-out set so repeated prompt changes do not merely fit the examples used during development.
| Workflow | Useful measures | ★ Release decision |
|---|---|---|
| Extraction | Field accuracy, critical-field errors, review time | Can operators verify values efficiently? |
| Knowledge answers | Retrieval relevance, citation support, appropriate abstention | Are answers supported by accessible evidence? |
| Suggested actions | Correct target, permissions, duplicate prevention | Can a person inspect and approve the change? |
Track latency and cost alongside quality. Compare the whole task with the manual baseline, including correction time. Set thresholds based on the consequence of a mistake rather than a generic accuracy percentage.
Estimate operating cost from usage
Token charges are only one component. A planning model should include model requests, retries, document processing, embeddings, search storage, observability, and human review. Use current provider prices and record the model and date used for the estimate.
For an illustrative workload of 10,000 requests per month, each averaging 3,000 input tokens and 500 output tokens, the base model volume is 30 million input and 5 million output tokens. Multiply those volumes by the selected provider's current rates, then add retries and other services. This is a workload example, not a price forecast.
Put limits on file size, requests per account, tool calls, and processing time. Streaming can improve perceived responsiveness, but it does not reduce the amount of work or establish that an answer is correct.
Privacy and operational ownership
Review the exact provider, endpoint, retention settings, data location requirements, and contract before sending confidential information. Do not infer API data handling from consumer chat settings or assume that every provider and feature has identical terms.
Minimize the data sent to the model and avoid logging raw sensitive inputs by default. Define who can inspect traces, how long they are retained, and what happens when a user requests deletion. Identify who owns model changes, incident handling, and rollback to a manual process.
Common questions
Does RAG eliminate hallucinations?
No. It can provide relevant evidence, but retrieval and generation can still fail. Check citation support, test missing-evidence cases, and allow the system to decline an unsupported answer.
Should the AI write directly to our database?
For consequential changes, begin with a proposal and approval step. Execute approved actions through ordinary authenticated code with validation, audit records, and duplicate prevention. Increase autonomy only after evaluating the specific risk.
Can we add AI without rebuilding the frontend?
Often, yes. An existing interface can call an authenticated backend or background job service. Choose the frontend and backend boundaries around the workflow; an AI feature alone is not a reason for a framework rewrite.
Scope a useful AI pilot
Send us one workflow, anonymized examples, and the cost of getting it wrong. We can discuss an evaluation-first pilot. If the feature belongs to a new product, our MVP cost guide and delivery guide explain the broader planning work.