AI & Data18 November 20269 min read

From AI Prototype to Production — Part 2 of 10

How an AI agent actually works

An agent is a loop of ordinary requests and responses. The model asks for a tool; your application decides whether to run it. Part 2 of From AI Prototype to Production traces one request at message level, separates the provider's stop signals from yours, and shows how to choose the least autonomous design that works.

#AI Agents#Tool Calling#AI Engineering#Agentic AI#Production AI
A workbench holding a few loose glass blocks, connected by a cyan line to a large, orderly frame of lit modules with a small yellow status light, in a dark workshop over a faint map of southern Africa.

Swartberg Health Administrators, a fictional South African medical scheme administrator, ran a two-week pilot of a member-query assistant for its contact centre. An agent typed "why was this claim short-paid?", and the assistant came back with the benefit rule, the tariff line and a draft explanation for the member. Everyone in the room called it an agent. Then the operations manager asked a plain question: when the assistant said it had checked the claim, what actually happened, which system was called, with whose identity, and what would have stopped it reading the wrong member's file?

Nobody could answer at the level of individual messages. The team knew the framework, not the mechanics. That is the gap this part closes. Part 1 set out the Production Readiness Scorecard. The Enterprise AI Control Plane series already gives the harness reference architecture and task contract in The model proposes. The harness decides what happens next., and You do not control the agent until you control the loop covers budgets, hooks and cancellation. This part goes one level lower: what travels over the wire on each step, who executes what, and where the gates sit.

A model call is a function call with a transcript attached

Strip away the framework and an agent is a sequence of HTTP requests to a model. Each request carries three things:

  • Instructions: the system prompt, which states the role, rules and output format.
  • Messages: the conversation so far, including earlier tool requests and their results.
  • Tool definitions: for each tool, a name, a plain-language description and a JSON Schema for its arguments.

The response contains text, one or more structured requests to call a tool, or both. In Anthropic's Messages API the response has stop_reason: "tool_use" and tool_use blocks, each with an id. In OpenAI's Responses API it contains function_call items, each with a call_id. Your application runs the tool and sends the result back, tied to that identifier: a tool_result block in Anthropic's case, a function_call_output item in OpenAI's (Anthropic tool use overview; OpenAI function calling guide, both checked on 18 November 2026).

Two consequences follow. First, the model keeps no working memory between calls. Each request carries the history the model needs, or a pointer to state the provider keeps for you. OpenAI's conversation state guide offers previous_response_id and a Conversations API, and states that all previous input tokens in a chained response are still billed as input tokens. Second, every pass round the loop resends a growing transcript, so cost and latency grow with each step. Part 3 deals with what belongs in that transcript.

One question, traced message by message

Here is the Swartberg short-payment query as the application sees it. The tool names and data are illustrative.

PassApplication sendsModel returnsApplication does
1Rules; tools get_claim_lines, get_member_benefits, get_tariff_rule; the agent's question with the claim numberTool request get_claim_lines with the claim number, call ID AValidates the arguments against the schema; checks that the contact-centre agent may view this member; calls the claims system with the agent's delegated identity
2Everything above plus result A: three lines, one paid at 80%Two requests in one turn: get_member_benefits (call B) and get_tariff_rule for the line's code (call C)Checks both; runs them in parallel; returns results B and C with their IDs
3Everything above plus results B and CText: the line was paid at the scheme rate, the provider charged above it, the member's option has no top-up coverStop gate: answer produced, three tool calls used of a budget of eight, no write attempted. Ends the run
4The agent clicks "draft letter"Not a model loop: a fixed template step fills the explanation into an approved letterThe agent edits and sends; the letter is logged against the claim

Notice what the model never did. It did not connect to the claims system, hold a credential or choose whose file to open. It produced three structured requests and one paragraph. Everything that touched a system of record was the application's decision, made in code that Swartberg can test.

Notice also pass 4. The first pilot let the model write and send the letter. The production design moved that step out of the loop into a template, because the wording of member communication is something the scheme wants fixed, approved and repeatable.

The application executes tools, not the model

Anthropic's documentation puts it plainly: "The model never runs anything on its own. It emits a structured request, your code (or Anthropic's servers) runs the operation, and the result flows back into the conversation" (How tool use works, checked on 18 November 2026). OpenAI's guide says the same of its API: when the model calls a function, your application executes it and returns the result.

The bracket in that quotation matters. Providers also offer tools they run themselves. Anthropic lists web search, web fetch, code execution and tool search as server tools that run on its infrastructure, where your application reads results rather than producing them. OpenAI has built-in tools of its own. For an enterprise, the question for each tool is therefore where it executes, with whose identity, and inside whose boundary. A provider-run web search sends the query outside your network. A tool exposed through the Model Context Protocol (MCP) is executed by an MCP server you or a supplier operates. CloudNala's API, function calling and MCP are different layers separates those layers.

One agent loop, with its permission and stop gatesASK AND PROPOSERequest: rules, tools,history, case stateModel returns textor a tool-callrequestParse and validateagainst the schemaPermission gate:this user, this task,this argument?EXECUTE AND DECIDEApplication runsthe tool with ascoped identityAppend resultwith the samecall IDStop gate: done,budget, erroror repeat?Final answer orhandover toa personallowstopcontinue: next requestDeny, or pausefor approvaldenied: explain or escalatePerson decidesor resumesTrace every pass: request, model version, call ID, arguments,gate decision with reason, tool result, tokens, time and stop reason
Read the top row left to right, then the middle row right to left. The model only ever returns text or a structured request to call a tool. The application validates that request, checks whether this user and this task may make it, and only then executes the tool with a scoped identity. The result goes back with the same call identifier, and a stop gate decides whether to continue, finish, or hand the run to a person. A denied request never reaches the tool.

Four mechanics decide how safe the execution step is:

  1. Schema conformance is not permission. Both providers offer a strict mode that makes tool arguments follow your schema reliably rather than on a best-effort basis. That guarantees the request is well formed. It says nothing about whether this user may look up this member. That check is yours.
  2. Parallel calls arrive together. A single response can contain several tool requests. Each needs its own permission check, and you must return a result for each ID. If ordering matters, for example read before write, turn parallel calls off for that step: Anthropic exposes disable_parallel_tool_use and OpenAI parallel_tool_calls: false.
  3. tool_choice constrains the model, not the world. Forcing a specific tool or offering only an allowed subset narrows what the model can request. Narrow the tool list per step instead of offering every tool and hoping.
  4. Errors are results. A failed call goes back to the model as a result marked as an error, so it can recover or stop. Do not hide failures and do not retry writes blindly. Writes need an idempotency key so that a retried request does not pay twice.

Two kinds of stop signal

A loop needs a reason to end. There are two sources, and production systems need both.

SignalComes fromExampleWhat the application should do
Tool requestProviderAnthropic tool_use; OpenAI function_call itemsValidate, check permission, execute, continue
Finished turnProviderAnthropic end_turnRun your own completion checks before accepting
Output limitProviderAnthropic max_tokensTreat as incomplete; never act on a truncated plan
RefusalProviderAnthropic refusalStop and route to a person with the reason
Paused server loopProviderAnthropic pause_turnResend to continue, within your own budget
Budget reachedYour harnessEight tool calls, three minutes, a token ceilingStop with a typed reason; return partial work clearly marked
RepetitionYour harnessSame tool, same arguments, three timesStop; this is a loop, not progress
Gate denialYour harnessRequest outside the user's access or the task's toolsStop or escalate; do not let the model retry around the denial
Approval neededYour harnessAny write above a thresholdPause, record the pending action, resume only on decision

Anthropic's documentation describes the loop as continuing while the stop reason is tool_use and exiting on any other reason, which your application should handle. A provider's "finished" means the model has stopped generating. It does not mean the task is done. Only your checks can say that.

Workflow, bounded agent or open autonomy

The same mechanics support three very different designs. The difference is who chooses the next step.

Deterministic workflowBounded agentOpen autonomy
Who chooses the next stepCodeThe model, from a short list, inside limitsThe model, from a broad toolset
ToolsCalled by code at fixed pointsA small allowlist, mostly read-onlyMany tools, including writes
Stop ruleThe workflow endsBudget, typed stop reasons, approval for writesMostly the model's judgement
TestingUnit and integration testsScenario sets and trajectory checksHard to bound; needs heavy monitoring
Swartberg exampleClaim status lookup and the member letterShort-payment explanationNone in production

Anthropic's Building effective agents (19 December 2024) draws the same line between workflows, where code follows predefined paths, and agents, where the model directs its own process, and advises the simplest solution that works. Microsoft's open agentic AI design patterns catalogue (MIT licence, pattern marked preview, checked on 18 November 2026) describes a bounded autonomy pattern in which a governor outside the model grants one of four profiles: observe only, propose, act with approval, or act. Its summary line is worth keeping: "Autonomy is a server-side grant, not a model behavior." The sample's thresholds are labelled illustrative, so treat it as a design reference, not a standard.

The decision rule for Swartberg, and for most enterprises, is to use the least autonomous design that achieves the outcome. Most of the member-query journey is a workflow. One step, explaining an unexpected payment from several records, has genuine uncertainty about which records matter, so it became a bounded agent with read-only tools. CloudNala's series Not Every Workflow Needs an Agent gives the test for finding that step, starting with use a workflow until the unknown forces an agent.

What changes when the tool results are health information

Every tool result goes into the transcript, and the transcript goes to the model provider on the next pass. At Swartberg, a claim line can reveal a diagnosis code. Health information is special personal information under section 26 of POPIA, the Protection of Personal Information Act, and processing it is prohibited unless an authorisation or exception in the Act applies. If the model endpoint is outside South Africa, section 72 sets conditions for transferring personal information across the border. This is general information, not legal advice.

The engineering response is concrete. Return the fields the step needs, not the whole record: the claim tool returns tariff code, amount charged and amount paid, not diagnosis codes, unless the explanation requires them. Log the call IDs and field lists, so you can show what entered the context. Know where each endpoint processes data. And make sure the person who signs off the tool's output schema includes someone who understands the scheme's privacy obligations, not only the developer.

Agent mechanics checklist

Before a bounded agent leaves the pilot:

  1. List every tool, where it executes, and the identity it runs with.
  2. Define a strict schema for every tool, and a separate permission check for every call.
  3. Turn off parallel calls for any step where order matters.
  4. Give every write an idempotency key and an approval rule.
  5. Map each provider stop reason to an application action, including truncation and refusal.
  6. Set budgets for passes, tool calls, tokens and wall-clock time, with typed stop reasons.
  7. Trace every pass: model version, call IDs, arguments, gate decisions, results and cost.
  8. Trim each tool's output to the fields the step needs, and record what was sent.
  9. Write down why each step is a workflow, a bounded agent or neither.

Scorecard contribution

This part supplies evidence for four rows of the Production Readiness Scorecard in Part 1. The states for Swartberg are illustrative.

Scorecard rowEvidence from this partSwartberg state
Agent/toolsTool inventory with execution location, identity, schema, permission check, idempotency and approval ruletested
ModelStop-reason handling, including truncation and refusal; model version in every tracetested
SecurityDelegated identity per call; minimum fields per tool result; endpoint location knownhypothesis
ObservabilityPer-pass trace with call IDs, gate decisions, tokens and stop reasontested

Next: Part 3, Context is the product. Previous: Part 1, A demo is not a service. All parts are on the series page.

How CloudNala can help

CloudNala reviews agent designs at message level. We trace a representative task through your harness, list every tool with its execution location, identity and permission check, map provider stop reasons to application actions, and identify which steps should be workflows instead of agent decisions. You leave with a tool inventory, a gate design and a trace specification your engineers can build and your risk team can review.


Work with CloudNala

CloudNala helps organisations move from technology ambition to practical execution across cloud, AI, data, platform engineering and digital services.

Whether you are exploring AI, modernising your cloud environment, building a public-sector digital service, or turning an idea into a working MVP, we can help you shape the roadmap and deliver the next step.

Book an Agent Design Review or write to us at consult@cloudnala.co.za

Found this useful?

Share