Digital Solutions Independent Digital Engineering Studio

Automation

Adding AI to an Existing Business Application: An Engineering Checklist

How to add a language-model step to a system that already works: where it belongs, a strict output contract, validation, queued jobs, human review, logging, data protection, cost limits and testing, with Laravel examples.

Diagram: a queued job sends minimal input to a model whose output is untrusted; validated, confident results become draft suggestions, unsure ones go to a review queue, and only approved actions reach the application.
On this page
  1. Where the AI step belongs
  2. Design the contract before the prompt
  3. Validate the output like any untrusted input
  4. Run it in the background
  5. Keep a person in the loop where it matters
  6. Log enough to explain every result
  7. Protect data and limit what the model can do
  8. Control cost and latency
  9. Test it before you trust it
  10. Plan for the model changing
  11. The checklist
  12. Where this fits in a wider system

Once a business has decided that one step of a process would benefit from a language model (classifying incoming requests, summarising long messages, extracting details from documents, drafting replies), the next question is engineering: how do you add that step to an application that already works, without making it less reliable, less secure or more expensive than it needs to be?

The guiding principle of this article is simple. Treat the model as an external service that is sometimes slow, sometimes unavailable, and returns untrusted text. Most of what follows is ordinary integration discipline applied to that kind of service. The examples use Laravel, but the design applies to any stack. Whether a task should use AI at all is a separate question, covered in practical AI automation for small businesses.

Where the AI step belongs

Three rules keep an AI step from weakening the system around it.

  1. Your system remains the source of truth. Records, prices, balances, permissions and decisions live in your database and your business logic. The model reads the minimum it needs and returns a suggestion.
  2. The AI suggests; the application decides. Whatever the model returns is validated, and anything with consequences goes through rules or a person before it takes effect.
  3. It runs outside the critical path. Saving an order, submitting a form or signing in must never wait for, or depend on, a model's response.

In practice that means the AI step sits behind an interface in your code, is called from a queued job, and writes its result to its own table, linked to the record it describes. If the model is unavailable, the rest of the application carries on and the item is handled the way it was before.

Design the contract before the prompt

Start with the output you need, not the wording of the prompt. For a step that triages incoming enquiries, for example:

{
  "type": "object",
  "properties": {
    "category": {
      "type": "string",
      "enum": ["new_project", "support", "billing", "spam", "other"]
    },
    "summary": { "type": "string" },
    "confidence": { "type": "string", "enum": ["high", "low"] }
  },
  "required": ["category", "summary", "confidence"],
  "additionalProperties": false
}

A few design choices make this contract work:

  • Closed lists instead of free text wherever the application will act on the value. A category the code does not know about is an error, not a new category.
  • An explicit way to say "unsure". Give the model a low-confidence or "other" option and route those items to a person, instead of forcing a guess.
  • Only the fields you will use. Every extra field is something else to validate, store and explain.
  • Minimal input. Send the subject and message of the enquiry, not the customer's whole history.

Major model APIs can now constrain their output to a JSON Schema, or to a subset of it (JSON Schema, OpenAI: structured outputs, Anthropic: structured outputs). Use that where it is available. It reduces malformed responses considerably, but it does not make the content correct, so validation is still needed.

Validate the output like any untrusted input

A response that matches the schema can still be wrong, and text produced by a model can contain anything its input contained. Validate it at two levels:

  • Shape: required fields present, values from the allowed lists, lengths within limits.
  • Business sense: extracted totals match the sum of the line items, dates fall in a plausible range, a referenced customer number actually exists.

And handle it as untrusted when you use it: escape it when it is displayed, never execute it, and never paste it into a database query, a shell command or an email header. The OWASP Top 10 for LLM applications (2025 edition) lists this as improper output handling (OWASP: LLM Top 10).

In Laravel, the validator you already use for requests works well here:

$data = json_decode($responseText, true, flags: JSON_THROW_ON_ERROR);

$valid = Validator::make($data, [
    'category' => ['required', Rule::enum(EnquiryCategory::class)],
    'summary' => ['required', 'string', 'max:300'],
    'confidence' => ['required', Rule::in(['high', 'low'])],
])->validate();

Run it in the background

The call to the model belongs in a queued job with a timeout, a small number of retries with increasing delays, and a defined outcome when it gives up:

final class ClassifyEnquiry implements ShouldQueue
{
    use Queueable;

    public int $tries = 3;
    public array $backoff = [30, 120, 600];
    public int $timeout = 60;

    public function __construct(public Enquiry $enquiry) {}

    public function handle(EnquiryClassifier $classifier): void
    {
        if ($this->enquiry->classification()->exists()) {
            // Already classified: a retry or a second dispatch does nothing.
            return;
        }

        $result = $classifier->classify(
            $this->enquiry->only(['subject', 'message'])
        );

        $this->enquiry->classification()->create([
            'category' => $result->category,
            'summary' => $result->summary,
            'needs_review' => $result->confidence === 'low',
            'model' => $result->model,
            'prompt_version' => $result->promptVersion,
        ]);
    }

    public function failed(?Throwable $exception): void
    {
        // Handled by a person, as before.
        $this->enquiry->update(['triage' => 'manual']);
    }
}

EnquiryClassifier is an interface. Its implementation builds the prompt, calls the provider, validates the response as shown above and returns a small result object. The rest of the application never sees the provider's API, which matters later when models or providers change.

Note the idempotency check at the top of handle(). Queued jobs can run more than once, and a model call costs money each time.

Keep a person in the loop where it matters

For anything that reaches a customer, involves money or commits the business to something, the model's output should be a draft or a suggestion that a person approves. The technical side of that is a review screen that shows the suggestion next to the original input, lets the reviewer accept, edit or reject it, and records what they did. Those records are valuable: they show how often the model is right and become test cases for the next change.

Low-confidence results, validation failures and anything the model marked as "other" should go straight to that review queue rather than being dropped.

Log enough to explain every result

When someone asks why an enquiry was routed to the wrong team three weeks ago, you should be able to answer. For each AI result, keep:

  • which record it was about, and when it ran;
  • the model identifier and your prompt version;
  • the validated output, and whether validation failed;
  • what a reviewer did with it.

Decide what not to keep as well. Inputs often contain personal data; store a reference to the record rather than a second copy of the text, set a retention period for anything you do store, and never log API keys.

Protect data and limit what the model can do

  • Send only what the task needs. Remove fields that are not required, and check what your provider's business or API terms say about retention and training on your data before any personal information is sent.
  • Treat everything the model reads as data, not instructions. Emails, uploaded documents and web pages can contain text written to manipulate a model. The 2025 OWASP list puts prompt injection first for this reason. An automation that reads customer messages must not be able to take significant actions on the strength of what those messages say.
  • Give it the least power that works. If the model can call tools or functions, give it read-only tools where possible, and require confirmation for anything that changes data or contacts people. OWASP calls the opposite excessive agency.
  • Keep credentials out of prompts and out of anything the model can see.

The US National Institute of Standards and Technology's AI Risk Management Framework and its Generative AI Profile are useful for a more structured review of these risks.

Control cost and latency

Usage-based pricing means a bug can become a bill. OWASP lists unbounded consumption as a risk in its own right. Practical limits:

  • a maximum input size, enforced before the call (truncate or reject very long inputs);
  • a maximum output length on every request;
  • no automatic retry loops beyond the job's own retry limit;
  • a daily or monthly spending limit with an alert, at the provider and in your own monitoring;
  • caching where the same input is processed repeatedly.

Measure cost and response time per item from the first day, so you know what normal looks like.

Test it before you trust it

Language models do not suit ordinary unit tests: the same input can produce slightly different output, and a prompt that works on five examples can fail on the sixth. Two practices fill the gap.

  • An evaluation set. Collect a set of real, anonymised examples with the answer a person would give. Run every prompt change and every model change against it, and compare the agreement rate before releasing. Add the cases reviewers corrected.
  • Shadow mode. Before the AI step affects anything, run it alongside the existing process and only record its suggestions. After a few weeks you will know how often it agrees with the people doing the work today, on your real data, without any risk.

Keep ordinary automated tests for everything around the model by faking the classifier interface: the queue behaviour, validation, the review screen and the fallback to manual handling are all deterministic and testable.

Plan for the model changing

Providers release new models and retire old ones on their own schedule. Record which model produced each result, specify a model version explicitly where the provider allows it rather than relying on a default, and treat a model change like any other dependency upgrade: run the evaluation set, compare, then release. Because the provider sits behind your own interface, switching to a different model or provider is a contained change.

The checklist

Area Question to answer before release
Placement Does the main process still work if the AI step is unavailable?
Contract Is the output a closed, documented schema with an "unsure" option?
Validation Is every result checked for shape and business sense?
Output handling Is model output escaped and never executed?
Execution Does it run in a queue, with timeouts, limited retries and a manual fallback?
Review Does a person approve anything with consequences, and are their actions recorded?
Logging Can you explain any result later without storing more personal data than necessary?
Data Does the provider's agreement cover the data you send?
Agency Can the model change data or contact people without confirmation?
Cost Are input size, output size and spending limited and monitored?
Testing Is there an evaluation set, and was the step run in shadow mode first?
Change Is the model version recorded and an upgrade path defined?

Where this fits in a wider system

AI steps are most often added to systems that already move information around: enquiry forms, shared inboxes, document workflows and messaging. If yours involves email, SMS or WhatsApp, unified messaging APIs covers the integration side of those channels.

Digital Solutions builds Laravel business applications and API and third-party integrations, and uses AI as one implementation method inside them where a step genuinely needs language understanding, with validation, review and logging around it. It is not sold as a separate AI product. If you have a process where an AI step might help, describe the process and the system it runs on.

Explore Digital Solutions

/ or Ctrl / ⌘ K to open · ↑ / ↓ to navigate · Enter to follow · Esc to close