AI Agents and Coding Assistants

How Developers Add AI Features to an App Through an API

Follow a request from your app to a hosted AI model and back, including keys, prompts, errors, safety checks and testing.

Key takeaways

  • An AI feature is usually your app sending instructions and user content to a hosted model, then handling the text or data that comes back.
  • The secret key belongs on a server you control, never in code that reaches a user's browser or phone.
  • Replies are unpredictable enough that your code should validate them before showing, saving or acting on them.
  • Limits, timeouts, fallbacks and a set of test examples turn a demonstration into a dependable feature.

Most apps with AI features do not contain the model. They send a request over the internet to a company that runs one, receive a reply and decide what to do with it. The connection point is an API, short for application programming interface: a documented set of rules for how one program asks another to do something.

The call itself can take only a few lines of code. Most of the real work surrounds it: keeping the access key safe, writing good instructions, checking the reply, coping with failures and watching the bill.

What an API call looks like

Think of ordering at a service window with a strict form. You fill in the required fields, hand it over and get back a response in a known layout. For a language model, the form typically includes these items.

  • Which model you want to use.
  • Instructions describing the model's job, often called a system prompt.
  • The content to work on, such as a customer's question.
  • Settings, such as a cap on the length of the reply.
  • Your key, which identifies the account to be billed.

The response usually contains the generated text, a note about why generation stopped and a count of the tokens used. Tokens are the small chunks of text a model reads and writes, explained in what tokens are.

Many providers also offer an SDK, a software development kit: a library for a particular programming language that handles the formatting and network details. Field names differ between providers and change over time, so follow the current documentation of the service you pick.

The route a request takes

A typical feature, say a button that summarizes a long support message, passes through several stops.

The route of one AI request through an app
1 User action Someone presses Summarize in the app 2 Your server Checks identity and limits, builds the prompt 3 Model service Generates a reply and reports usage 4 Validation Server checks length, format and content 5 Display App shows the draft, labeled as AI-made User action Someone presses Summarize in the app 1 Your server Checks identity and limits, builds the prompt 2 Model service Generates a reply and reports usage 3 Validation Server checks length, format and content 4 Display App shows the draft, labeled as AI-made 5

Your server sits in the middle on purpose. It confirms that the user is allowed to do this, trims the input, adds your instructions and holds the key. The user's device never talks to the model service with your credentials.

Here is the shape of the server logic in simplified pseudocode, which is not tied to any real library.

receive message from signed-in user
if user is over today's limit: refuse politely
if message is too long: ask for a shorter one
reply = call_model(instructions, message, max_length, timeout)
if call failed or reply is empty: show fallback
save usage count
return reply marked as a draft

Protect the key

An API key works like a password that can spend your money. Anyone who obtains it can make requests billed to you, and may be able to reach other things your account holds.

Code that runs in a browser or ships inside a phone app can be inspected, so a key placed there should be considered public. Store it in the server's protected settings or a secrets manager. Keep it out of the source code repository, where history preserves deleted lines.

Create separate keys for development and for the live app, so a leak in one place does not expose both. Where the provider allows it, set a spending limit and restrict what each key can do. If a key leaks, revoke it and issue a new one. This is a common stumble in apps built mostly by description, and one item in the pre-publication checks.

Write the instructions like a specification

The system prompt is part of your program. State the task, the audience, the output format, what to do when information is missing and what is out of bounds. "Summarize this" leaves too much open. "Summarize the customer's message in three bullet points for a support agent. Do not add facts that are not in the message. If there is no clear request, say so" gives the model a target.

Each call is generally independent. A chat that seems to remember earlier turns usually works because the app sends the earlier messages again, or a stored summary of them. That affects cost and the amount of text that fits, since every model has a limit called the context window.

If the feature must answer from your own material, such as a product manual, a common design searches your documents first and includes the relevant passages in the request. This is retrieval, and it reduces guessing without removing it.

Treat the reply as untrusted input

A model can produce a wrong fact, ignore a format or return something odd. Your code should expect this.

If you need structured data, ask for a defined format such as JSON (a common text layout of named fields). Some services can enforce a structure you describe. Even then, check that required fields exist, numbers fall in sensible ranges and categories are ones you recognize. A well-formed answer can still be false.

Never paste a reply straight into a database command, a system shell or a web page as code. Escape it for display. If the model can trigger actions, such as issuing a refund, require your own code to enforce limits and ask a person to approve anything consequential.

User content can also contain text written to redirect the model, an attack called prompt injection. Instructions in your prompt help but cannot be relied on alone, so limit what the model is able to do.

Plan for failure and delay

Network services fail. A request may time out, be rejected because you sent too many too quickly (a rate limit), or return an error on the provider's side.

Situation Sensible response
Rate limit reached Wait, retry with increasing pauses and cap the attempts
Timeout or server error Retry a few times, then show a fallback
Invalid request or bad key Do not retry; log it and alert a developer
Reply cut off at the length cap Detect the stop reason; ask for less or allow more
Unusable or refused answer Offer the manual route and keep the user's input

Replies can take several seconds or longer. Many services can stream the answer, sending it piece by piece so the user sees progress. Decide what the app does if the person closes the screen midway, especially if an action was underway.

Mind privacy and cost

Whatever you put in the request leaves your system. Send only what the task needs, and remove names or account numbers when they add nothing. Read the provider's terms on retention, training use and where data is processed, and tell your users what happens to their content. Health, financial, legal and children's data can carry specific legal duties, so get qualified advice before sending them anywhere.

Services commonly charge by tokens, with different rates for input and output. Long instructions, long histories and long replies all add up. Work through a rough figure before launch using a usage cost estimate, and set per-user limits so one person or script cannot run up the total.

Test with examples before and after launch

Collect a few dozen realistic inputs, including awkward ones: an empty message, a very long one, another language, an angry customer, text that tries to change the instructions. For each, write down what a good answer must contain and must not contain.

Run the whole set whenever you change the prompt, the model or a setting. Some checks can be automated, such as length and required fields. Judging accuracy usually needs a person reading a sample.

Providers update and retire models, so keep the model name in a setting you can change, and keep your test set ready for that day. After launch, give users a way to report bad answers, and log enough to investigate without hoarding private content.

Common questions

Do I need to train my own model?

Usually not for a first feature. Clear instructions, examples and retrieval of your own documents cover many needs. Further customization is worth considering once testing shows a specific gap.

Can a model run inside the app instead?

Sometimes. Smaller models can run on a device or on your own server, which changes the privacy and cost picture. They need more setup and may be less capable on demanding tasks.

How do I switch providers later?

Put all model calls behind one small module in your code, so the rest of the app does not depend on one company's format. Expect to adjust prompts and rerun tests, because models behave differently even when the interface looks similar.

Written for 4ArtificialIntelligence with AI writing tools and not reviewed line by line by a person. Check anything you rely on against a textbook or primary source. Report an error.

Keep reading

All 46 articles in AI Agents and Coding Assistants →

Latest news on this topic