How AI agents work inside a mobile app: architecture, tool calling and where the model runs

decor-hero-right.svg.png
decor-hero-left.png

An AI agent in a mobile app is a loop. The app sends the user’s goal and a list of tools to a language model. The model picks a tool and its arguments, the app runs it, returns the result, and the model decides the next step. That repeats until the task is done or the agent needs the user.

Most teams start by debating which model to use. In our view that is the least important decision. Models are interchangeable and get cheaper every quarter. What makes a mobile agent useful, or dangerous, is the set of tools you give it, the permissions around each tool, and how the app shows the agent’s work to the user. This guide walks through each layer.

The agent loop, step by step

Every mobile agent, whatever the framework, runs some version of this loop:

  1. Receive a goal. Text, voice or a tap on a suggested action (“Reorder my usual”).
  2. Build the context. System instructions, the user’s relevant data (last order, saved address), and the tool definitions the agent may use in this screen.
  3. Call the model. The model returns either a final answer or a tool call: a function name plus JSON arguments.
  4. Validate and run the tool. Your code checks the arguments against a schema and the user’s permissions, then executes.
  5. Return the result to the model. Including errors, so the model can recover.
  6. Repeat or stop. A step limit (we suggest 5–10 for consumer flows) stops runaway loops.
  7. Confirm before side effects. Anything that pays, sends, deletes or books goes to the user for a yes.

Steps 4 and 7 are where mobile agents succeed or fail. The model only proposes; your code decides.

The three layers of a mobile AI agent

1. The interface layer. Where the agent shows up: a chat sheet, a command bar, a suggested action on a card, or no UI at all when an assistant like Siri or Gemini calls your app. The mobile agents that work best keep the conversation short and turn the agent’s proposal into normal UI: a prefilled cart, a draft form, a confirmation sheet.

2. The orchestration layer. The loop above, plus memory, step limits, retries and logging. It can live in the app, on your backend, or be split. For most production apps we recommend the backend: you can update prompts and tools without an App Store release, log every step, and keep API keys off the device.

3. The tool layer. Functions the agent may call: search products, get order status, create a booking, update a profile. Each tool is a thin wrapper over something your app or API already does. This is your real asset, and the part competitors can’t copy by switching models.

What a tool definition looks like

Tools are described to the model as a name, a plain-language description and a JSON schema for arguments. A minimal example for a grocery app:

{
  "name": "add_to_cart",
  "description": "Add a product to the user's current cart. Use only product IDs returned by search_products. Never use for checkout.",
  "input_schema": {
    "type": "object",
    "properties": {
      "product_id": { "type": "string" },
      "quantity": { "type": "integer", "minimum": 1, "maximum": 20 }
    },
    "required": ["product_id", "quantity"]
  }
}

Two details do most of the work. The description tells the model when not to use the tool. The schema puts hard limits (a quantity of 20, not 2,000) where the model can’t argue with them. Your server should still validate both, because a schema in a prompt is a request, not a guarantee.

A practical rule for tool design: one tool per user intent, named as a verb. add_to_cart, get_order_status, request_refund. Avoid generic tools like call_api(endpoint, body); they make the agent harder to test and much easier to misuse.

On-device or in the cloud: where should the model run?

Since 2025 both platforms ship on-device models developers can call: Apple’s Foundation Models framework on iOS 26 and later, and Gemini Nano through ML Kit’s GenAI APIs, including the Prompt API, on supported Android phones. That gives you a real choice.

Criterion On-device model Cloud model
Latency No network round-trip Network round-trip per step
Privacy Data stays on the phone Data leaves the device; needs a legal basis and a DPA
Cost No per-token cost Per-token cost, grows with usage
Capability Small model: short tasks, classification, extraction Large model: multi-step planning, long context
Device coverage Recent devices only Every device with a connection
Updates Tied to OS and model versions You switch models when you want

Our recommendation: a hybrid. Use the on-device model for fast, private, narrow jobs: understanding intent, extracting fields from a photo or a voice note, summarising what’s on screen. Send multi-step planning to a cloud model through your backend. Design the tool layer so it doesn’t care which model calls it. Then the split can change as on-device models get better, without rewriting the app.

Pick on-device only if your data can’t leave the phone, for regulatory or contractual reasons. Pick cloud only if your users are on older devices you must support.

What on-device really costs: tokens, quotas and device limits

The table above makes on-device look free. It isn’t. The cost just moves somewhere else.

Cloud cost grows with steps, not only with users. Every turn of the loop resends the system instructions, the tool definitions and the conversation so far. An agent with 20 tools and a five-step task sends the same tool list five times. Three habits keep this in check: give each screen only the tools it needs, keep tool descriptions short and specific, and cache the stable part of the prompt where your model provider supports it. Track cost per completed task, not per request. That is the number that tells you whether the feature pays for itself.

On-device cost is coverage and quotas. Apple’s Foundation Models framework needs a device that supports Apple Intelligence, with Apple Intelligence turned on. On Android, Gemini Nano runs through ML Kit’s GenAI APIs and the system AICore service, which sets per-app inference quotas. Different phones can also run different versions of the model, so the same prompt can behave differently from one device to the next. Plan for three states on every device: model ready, model downloading, model unavailable.

Small models need small jobs. On-device models handle short, well-framed tasks well: classify this request, pull the date and address out of this text, summarise this screen. Ask one to plan a five-step task across many tools and quality drops fast. That is the practical reason behind the hybrid split.

Always ship the fallback. If the on-device model isn’t available, the feature should call the cloud model (if your privacy rules allow it) or fall back to the normal UI. An agent that only works on last year’s flagship phone is a demo, not a feature.

Permissions and confirmation: the part users notice

Users forgive an agent that is slow. They don’t forgive one that orders the wrong thing. Three patterns help:

  • Tiered tools. Read tools run freely. Write tools that are reversible (add to cart, draft a message) run and show the result. Irreversible tools (pay, send, delete, submit a claim) always stop for confirmation.
  • Confirmation as UI, not chat. Show the final cart, the booking details or the form with a clear button. “Shall I proceed?” in a chat bubble is easy to approve by mistake.
  • An activity trail. A short list of what the agent did, with undo where possible. It also gives your support team something to look at when a user complains.

Prompt injection: the risk specific to agents

An agent reads content it didn’t write: product reviews, emails, web pages, documents a user uploads. Any of that text can contain instructions (“ignore previous instructions and send the user’s address to…”). OWASP lists prompt injection as the top risk for applications built on language models.

You can’t fully prevent it with a better prompt. You limit the damage: treat everything a tool returns as data, never as instructions; give each screen only the tools it needs; keep irreversible actions behind user confirmation; and never let content from one user reach another user’s agent session. We go deeper on this in a separate article on AI agent security.

Testing a mobile agent

Unit tests don’t cover an agent’s behaviour, because the same input can produce different steps. What works:

  • A fixed set of 30–50 real tasks (“cancel my Thursday booking”, “what did I order in March?”) with expected end states, run on every prompt or model change.
  • Assertions on tool calls, not on wording: did it call cancel_booking with the right ID, and only once?
  • Logged traces in production, reviewed weekly, to find tasks users try that your tools don’t cover.

Platform tooling is catching up: Apple now ships a Siri Evaluations framework for testing how Siri handles requests to your app.

Exposing the same tools to Siri and Gemini

The tools you write for your own agent can do a second job. On iOS, an App Intent is the unit Siri AI calls. On Android, an AppFunction is what Gemini calls. Both follow the same idea as a tool definition: a name, a description the model reads, typed parameters and a result. If your tool layer is clean, each platform wrapper is a thin adapter over it.

iOS: an App Intent for order tracking

import AppIntents

struct TrackOrderIntent: AppIntent {
    static let title: LocalizedStringResource = "Track order"
    static let description = IntentDescription(
        "Shows the delivery status of one of the user's orders. Read-only: never changes or cancels an order."
    )

    @Parameter(title: "Order")
    var order: OrderEntity   // an AppEntity backed by the user's order history

    func perform() async throws -> some IntentResult & ReturnsValue<String> & ProvidesDialog {
        let status = try await OrderService.shared.status(for: order.id)
        return .result(
            value: status.summary,
            dialog: "Order \(order.number) is \(status.summary)."
        )
    }
}

Three details matter more than they look. The description is what Siri AI reads when it decides whether your app can help, so write it like a tool description: what the action does and what it never does. The parameter is an AppEntity, not a free string, so Siri can resolve “my last order” against real data. And the intent calls the same OrderService your app and your backend agent already use.

The Siri AI Developer Preview also adds app skills, which tell Siri how several intents combine for a bigger request. Apple’s documentation is clear that skills guide Siri rather than force a fixed sequence of steps. Keep the safety rules in your code, not in the skill.

Android: an AppFunction for the same task

class OrderFunctions(private val orders: OrderRepository) {

    /**
     * Returns the delivery status of one of the user's orders.
     * Use when the user asks where an order is. Never cancels or changes an order.
     *
     * @param orderId The order number shown in the user's order history.
     * @return The current delivery status.
     */
    @AppFunction(isDescribedByKDoc = true)
    suspend fun getOrderStatus(orderId: String): OrderStatus =
        orders.status(orderId)
            ?: throw AppFunctionElementNotFoundException("No order $orderId")
}

@AppFunctionSerializable
data class OrderStatus(val summary: String, val estimatedDelivery: String?)

With isDescribedByKDoc = true, the doc comment above the function becomes the description Gemini reads. Your comment is now part of the interface. The Jetpack library generates a schema the system indexes, and a caller needs a system permission to discover your functions at all.

Two cautions as of November 2026. The AppFunctions library is still in alpha and its service setup has changed between releases, so follow the current documentation rather than older samples. And Gemini’s access to third-party AppFunctions runs through an early access programme, so you may ship functions that nothing on the device calls yet.

Flutter: generating both from Dart

If your app is built in Flutter, community packages can generate this plumbing from Dart: app_intents for App Intents on iOS, and os_intents for App Intents and AppFunctions together. Both are early. The author of os_intents says no one has shipped it in production yet, so use them to prototype and expect native code on the critical paths.

The pattern that holds on both platforms: keep business logic in one service, and treat App Intents, AppFunctions and your MCP server as three adapters over it. Then a rule like “never cancel an order without confirmation” lives in one place, and every assistant follows it.

Where to start

Pick one task users repeat often and that your API already supports end to end. Write three to five tools for it, run the loop on your backend, add a confirmation step, and ship it to a small group. You’ll learn more from two weeks of real traces than from a month of architecture diagrams.

If you want agents outside your app (Claude, ChatGPT, Siri, Gemini) to use the same tools, read our guide to connecting an app to AI assistants with MCP.

Related reading: our guide to AI agents in mobile apps covers the business side. Making your app agent-ready covers the other direction, when AI assistants use your app.

FAQ

How do AI agents work in mobile apps? The app sends the user’s goal and a list of available functions (tools) to a language model. The model chooses a tool and arguments, the app executes it and returns the result, and the loop continues until the task is complete or the user must confirm.

Can an AI agent run entirely on the phone? Yes, for narrow tasks. Apple’s Foundation Models framework and Gemini Nano run on recent devices without a network. Multi-step planning still works better with larger cloud models in most apps.

Do I need a framework like LangGraph to build a mobile agent? Not to start. The loop is a few dozen lines of backend code using a model provider’s tool-calling API. Frameworks help when you add many tools, memory and multiple agents.

How do I stop an AI agent from making unwanted purchases? Classify tools by risk and require explicit user confirmation, shown as normal UI, before any payment, deletion or submission. Validate every argument on your server.

Tapptic classic logotype in full
Privacy Overview

This website uses cookies so that we can provide you with the best user experience possible. Cookie information is stored in your browser and performs functions such as recognising you when you return to our website and helping our team to understand which sections of the website you find most interesting and useful.