How to Integrate an LLM into Your App: A Step-by-Step Build

Nov 13, 2026 | AI Integration

How to Integrate an LLM into Your App: A Step-by-Step Build

To integrate an LLM into your app, pick one narrow task and put a small server-side service between your application and the model provider’s API. Give that service a strict input and output contract, validate every response, and log, measure and evaluate it like any other dependency. Then ship it behind a feature flag. The API call itself takes an afternoon to write. What takes the time is everything around it: retries, schemas, evals, cost caps and data handling. That surrounding work decides whether the feature survives contact with real users.

This walkthrough uses one running example, adding automatic triage to the support-ticket screen of an existing web app. The steps apply just as well to summarising documents, extracting fields from emails or drafting replies. For the wider picture of what LLM integration means in production, see our LLM integration production guide. This article is the hands-on build.

Step 1: Choose the task before you choose the model

The most common mistake is to start from “we should add AI” and work backwards. Start instead from a single decision or piece of text work that a person in your organisation does many times a week, where the input is text and the output can be checked. Ticket triage is a good example. The input is the customer’s message. The output is a category, a priority and a one-line summary, and an agent can see straight away whether the model got it right.

Write the task down as a function signature before you write any prompt. In our example it is something like triage(ticket_text, customer_tier) returns {category, priority, summary, confidence}. If you can’t write that signature, the task isn’t ready for an LLM. A vague goal produces vague output, and nothing downstream can validate vague output.

Then decide what happens when the model is wrong. If a wrong category just means a human re-files the ticket, you can automate fully. If a wrong output sends money, emails a customer or changes a record, you need a human approval step, which we cover below. Settle this now, because it shapes the architecture.

Step 2: Build a thin LLM gateway on the server

Never call the model provider directly from the browser or a mobile client. The API key would ship to every user, and you would have no central place to enforce limits, redact data or log calls. Every request should go through your own backend, ideally through one small module or service that owns all model access. Call it the LLM gateway, even if at first it is only a single file.

The gateway has four jobs. It holds the provider credentials, loaded from a secrets manager or environment variables and never committed to source control. It exposes task-level functions such as triage() and summarise() rather than a generic “send prompt” endpoint, so the rest of your codebase never builds prompts ad hoc. It translates those tasks into provider-specific calls behind an adapter interface. And it records what went in, what came out, how long the call took and how many tokens it used.

Keep the provider swappable

The OpenAI and Anthropic APIs are close enough in shape that a thin adapter covers both. Each takes a system instruction, a list of messages and parameters such as maximum output tokens, and returns text plus usage counts. They differ in the details: how system prompts are passed, how structured output and tool calling are declared, and the error codes they return. Their official documentation (OpenAI, Anthropic) is the reference for those specifics. Write your adapter against your own task interface, not against either SDK, so that changing providers or adding a fallback becomes a config change rather than a refactor.

Open-source routing libraries can do this job for you. They save time, but they become part of your attack surface, so pin versions and track their security advisories. Our note on patching LiteLLM and PHP2Shell is a reminder that the gateway layer needs the same patch discipline as the rest of your stack. If data residency rules out hosted APIs entirely, the trade-offs are covered in self-hosted LLM vs API. The gateway pattern is the same either way.

Step 3: Write the contract: prompt plus structured output

Treat the prompt as code. Keep it in version control next to the gateway function, give it an identifier, and log that identifier with every call so you know which prompt produced which output. The system prompt should state the role, the exact categories allowed, how to set priority, and what to do when the ticket is ambiguous. A good rule for ambiguity is to return a low confidence rather than guess.

Ask for structured output, not prose. Both major providers support constraining responses to a JSON schema, either directly or through tool definitions. Use that support, and validate the result on your side anyway with a schema library such as Pydantic or Zod. Check that the category is one of your enum values, that priority is in range and that the summary is under your length limit. Anything that fails validation gets one retry with the validation error fed back. If it fails again, it falls through to a safe default: “uncategorised, needs human review”.

Keep temperature low for classification and extraction. Set a hard cap on output tokens. Include three to five short worked examples in the prompt if the categories are subtle. Resist adding instructions every time you spot a bad output. Long, contradictory prompts get worse. Fix things through the eval loop in Step 6 instead.

Step 4: Give the model the right context, and only that

The model knows nothing about your product, your customers or your categories beyond what you put in the request. For triage, that might mean the customer’s plan tier, the product area they were using and the last two messages in the thread. For harder tasks, such as answering questions from your documentation, you need retrieval: search your own content, then pass the top few passages into the prompt. Whether that is enough, or whether you need fine-tuning, depends on the task. RAG vs fine-tuning works through that decision.

Equally important is what you leave out. Every field you send to a third-party API is personal data processing under GDPR if it identifies a person. Strip or pseudonymise what the task doesn’t need. Emails, phone numbers and account IDs are rarely necessary for triage. Check the provider’s data retention and training terms, and record the flow in your processing records. Mapping exactly which data crosses which boundary is the subject of dataflow security in AI pipelines. Do that mapping before launch, not after a data protection query arrives.

Step 5: Engineer for failure

An LLM API is a remote dependency with variable latency, rate limits and occasional outages. Design for this as you would for a payment provider. The table below lists the failures to plan for and a sensible default response to each.

Failure What it looks like Default handling
Rate limiting HTTP 429 responses under load Exponential backoff with jitter, two or three retries, then queue the job
Slow response Long tail latency on large prompts Hard timeout; run non-interactive tasks in a background worker
Provider outage 5xx errors or connection failures Fail over to a second provider or model via the adapter, or degrade to manual
Malformed output Invalid JSON, unknown enum values Validate, retry once with the error, then fall back to a safe default
Plausible but wrong output Valid JSON, wrong category Confidence thresholds, human review queue, eval monitoring
Runaway cost Huge inputs, loops, abuse Input truncation, per-user and per-day spend caps, alerts

Two architectural choices remove most of the pain. First, make LLM work asynchronous wherever the user doesn’t need an instant answer. Triage can run in a background job when the ticket arrives, so the agent never waits on a spinner. Second, make jobs idempotent and cache results keyed on the input and prompt version, so a retry or a page refresh doesn’t pay for the same call twice. Where users do wait, as with drafted replies, stream the response so the first words appear quickly.

Step 6: Measure quality with evals, not vibes

Before launch, build a golden set. Take somewhere between fifty and a few hundred real, anonymised tickets, labelled with the answer a competent human would give. Write a script that runs the gateway function over the set and reports accuracy per category, the rate of low-confidence outputs and the validation failure rate. Run it every time you change the prompt, the model or the context. This is the only reliable way to know whether a change helped, and it is what lets you switch models with evidence rather than optimism.

In production, log every call with the prompt version, model, latency, input and output token counts, and the validated result. Where possible, also record whether a human later changed the output. Those corrections are free labelled data, and the useful ones belong in the golden set. Track cost per task rather than cost per month. “Triage costs a fraction of a cent per ticket” is something a finance lead can reason about. A monthly API invoice is not.

Step 7: Secure it and keep humans where they matter

Any text a user can influence can carry instructions, and the model may follow them. That is prompt injection, and no current model is immune. The defence is architectural. Give the model no permissions it doesn’t need. Treat its output as untrusted input to your system. Never let it trigger irreversible actions directly. A triage model that can only return an enum is low-risk. A model that can call tools to issue refunds is not.

For anything consequential, route the model’s proposal to a person who approves or rejects it in one tap. We wrote up one way to make that practical in human-in-the-loop action tags for steering AI agents from your phone. The principle carries over to customer-facing apps: the model drafts, a human commits. Depending on what your feature does and who it affects, check your obligations under the EU AI Act as well. Transparency duties apply when people interact with an AI system, and the EU AI Act checklist for SMEs sets out the dates.

Step 8: Roll out gradually

Ship behind a feature flag. Run the model first in shadow mode: it triages every incoming ticket, but the results are only stored, not shown. Compare them against what your agents actually do for a week or two. Then show the suggestions to a few agents as editable defaults, and watch the correction rate. Only once the correction rate is low and stable should you let high-confidence results apply automatically, with low-confidence ones still going to a human. Each stage is reversible with a flag flip.

Here is the pre-launch checklist we would hold any first integration to:

  • All model calls go through one server-side gateway; no keys in clients or repos.
  • Prompts are versioned, and the version is logged with every call.
  • Outputs are schema-validated, with a defined safe fallback.
  • Timeouts, retries with backoff, and a failover or manual path are in place.
  • Personal data is minimised and the data flow is documented for GDPR.
  • A golden eval set exists and runs on every prompt or model change.
  • Per-task cost and latency are tracked, with spend caps and alerts.
  • Irreversible actions require human approval.
  • The feature is behind a flag, with shadow mode run first.

If your app is an older monolith without a clean service layer, the same steps apply, but the gateway may need to sit alongside the legacy system rather than inside it. Integrating LLMs into legacy enterprise systems covers those patterns.

If this were our app, here’s where we’d start

We would not start with the model. We would spend the first day choosing one task from the support or operations queue that is high-volume, text-in and checkable, and pulling a hundred real examples of it with the correct answers. The second step would be the gateway with a single task function, schema validation and logging, running in shadow mode against live traffic. Nothing user-facing changes at that point. The eval numbers from that week tell you whether to proceed, rethink the prompt, add retrieval or drop the idea. That is a cheap answer either way, and far better than learning it from customers.

D3X Solutions LABS is an AI engineering studio in Ireland, and this is the kind of build we do. We start by scoping the task and the failure cost. Then we design the gateway, evals and data flow so that your own team can run and extend them, and we stay involved only as long as the integration needs it. If you are weighing up where an LLM fits in your product, or have a prototype that needs to become production-grade, book a free 30-minute call using the form below and we will work through your first use case with you.

Frequently Asked Questions

How do I add an LLM to an existing app?

Add a server-side module or service that owns all model calls, and expose task-specific functions from it to the rest of your app. Validate the model's output against a schema, log every call, and release the feature behind a flag. Start with one narrow, checkable task rather than a general chat feature.

Should I call the OpenAI or Anthropic API directly from the frontend?

No. Calling from the browser or a mobile app exposes your API key and removes your ability to enforce rate limits, redact personal data or log usage. Always route requests through your own backend.

How do I make LLM output reliable enough for production?

Ask for structured output against a JSON schema and validate it in your own code. Keep temperature low for classification and extraction, and define a safe fallback for invalid responses. Measure quality with a labelled eval set that you rerun on every prompt or model change.

How much does LLM API integration cost to run?

Running cost is the input and output tokens per request, multiplied by the provider's per-token prices, multiplied by request volume. Work this out per task, cap output tokens, cache repeated inputs and set spend alerts. Engineering time for validation, evals and monitoring is usually a bigger cost than the API bill for a first feature.

Can I switch between LLM providers later?

Yes, if you write your code against your own task interface and put a thin adapter in front of each provider's SDK. With an eval set in place, you can test a new model against the same examples and switch on evidence. Switching then becomes a configuration change rather than a rewrite.

Is sending customer data to an LLM API GDPR compliant?

It can be, but you need a lawful basis, a data processing agreement with the provider and a clear record of what data goes where. Minimise or pseudonymise personal data the task doesn't need, and check the provider's retention and training terms. Document the flow before launch.

Want this working in your business?

D3X Solutions LABS builds AI agents and automation that pay back fast. Not sure where to start? A free 30-minute call is enough to find the first thing worth building.

Get in touch

Blog

What We Do

Product

Consumer and enterprise software, built with taste and shipped fast.

Infrastructure

AI agents, automation, and orchestration - production systems, not demos.

Advisory

Hands-on engineering and strategy for teams shipping AI into production.