Skip to content

Module 09 · Lesson 9.1

Agent Runtime and Deployment Architecture

40 minUpdated 18 Nov 2026Part of Deployment, Observability and Optimization · AI Agent Development
On this page
  1. What you will learn
  2. From a script on your laptop to a running service
  3. The pieces of a deployed agent
  4. Where the agent loop runs: server process or worker
  5. Where state lives: memory, files or a database
  6. Secrets and settings belong in the environment
  7. Test environment and production environment
  8. Check deployment readiness with Python
  9. Conclusion and your next step
  10. Common errors and fixes
  11. Validation checklist
  12. Hands-on exercise
  13. Knowledge check
  14. Frequently asked questions
  15. References

Your agent works on your laptop. You type a question, it calls a tool, it answers. Now your manager asks: "Can the shop's website use it?" Suddenly there are new questions. Which computer runs it? What happens if that computer restarts in the middle of a task? Where does the API key go?

This lesson answers those questions in plain words. You will learn the pieces of a deployed agent, where each piece lives, and how a test setup differs from a live one. Most of it needs no coding. One short Python script at the end checks a settings file for the most common mistakes.

What you will learn

  • Name the main pieces of a deployed agent and say what each one does.
  • Choose where the agent loop runs and where its state is stored.
  • Explain why secrets and settings belong in the environment, not in the code.
  • Run a Python script that checks whether a configuration is ready to deploy.

Before you start

From a script on your laptop to a running service

So far your agent has been a script. You start it, it runs, it stops. A service is different. It is a program that keeps running and waits for requests from other programs, a bit like a shop that stays open all day.

Deployment means putting the program somewhere other people or programs can use it. The word architecture here only means: which pieces exist, and how they connect. Good choices now save you from painful surprises later.

Runtime
The place and the program where the agent loop actually runs. It calls the model, runs the tools and decides when to stop.
State
Everything the agent must remember between steps or between requests: the conversation, a case record, a pending return request.
Environment
The surroundings a program runs in, such as the settings the computer gives it. "Environment variables" are named settings outside your code, for example GEMINI_API_KEY.
Endpoint
One address on your service that a client can call, such as /ask. A set of endpoints is an API.

The pieces of a deployed agent

A deployed Quillfeather agent is not one big blob. It is a handful of small pieces. Each one has a single job, and you can change or replace one without touching the others.

How one customer question travels through the service
  1. Client

    The website or app sends POST /ask

  2. API layer

    Checks the request, gives it a run id

  3. Agent loop

    Model calls and tool calls, up to MAX_ROUNDS

  4. Tools and knowledge

    lookup_order, search_help, the help pages

  5. State store and traces

    Cases, runs, traces.jsonl

The arrows show a request going in. The answer travels back along the same path.

  • API layer. Receives the request, checks its shape, hands it to the loop and returns the reply. It does no thinking of its own.
  • Agent loop. The code you wrote in Modules 2 to 4. It talks to the model provider over the internet.
  • Tools and knowledge. Your functions and your help-centre pages. These are your own code, so you control them.
  • State store. The place where anything that must survive is saved.
  • Traces and logs. The written record of what each run did. You will build this in the next lessons.

Where the agent loop runs: server process or worker

The loop must run inside some program on some computer. There are two common choices.

ChoiceHow it worksGood forWatch out for
Inside the web server processThe request arrives, the loop runs, the reply goes back on the same connection.Short tasks that finish in a few seconds, like one order question.A slow task holds the connection open. If the server restarts, the work is lost.
A separate workerThe web server saves a job and answers at once. A worker program picks the job up and runs the loop.Long tasks, such as the research agent from Module 5.More moving parts. You need a place to store jobs and results.
Start with the simple choice. Move to a worker when tasks get long. The next lesson shows how.

Think of a coffee counter. A quick espresso is made while you wait. A cake for tomorrow is ordered, you get a receipt, and the kitchen makes it in the back. The receipt is a job id. You will meet it in API Design, Background Jobs and Session Management.

Where state lives: memory, files or a database

State can live in three places. Each place has a different answer to the question: "What happens when the program restarts?"

WhereSurvives a restart?Shared by two copies of the service?Use it for
Program memoryNoNoScratch values inside one run
Files, such as checkpoint.jsonYesOnly if they share a diskSmall tools, tests, a single machine
A databaseYesYesCases, sessions, jobs, anything real users depend on

A good rule: if losing it would annoy a customer or cost money, it goes in a database or a file, not in memory. Follow your organisation's rules for how long personal data may be kept. See Memory Retention, Privacy and Data Lifecycle.

Secrets and settings belong in the environment

A secret is a value that gives access, such as the model API key. A setting is a value that changes how the service behaves, such as a timeout. Neither belongs inside your code. Code is copied, shared and stored in the repository. Secrets that end up there are very hard to take back.

  • Read the key from an environment variable such as GEMINI_API_KEY. The code names the variable. The value never appears in code.
  • Keep a local .env file for development, and make sure it is in .gitignore.
  • On a server, set the variable in the hosting tool's secret settings, not in a file inside the project.
  • Use a different key for testing and for live use, so a mistake in testing cannot spend live money or touch live data.
  • Put settings such as timeouts, MAX_ROUNDS and the active version in configuration too, so you can change them without editing code.

The idea of keeping configuration apart from code is described in the Twelve-Factor App guide, linked below. For more on keys and permissions, see Authentication, Secrets and Least-Privilege Access.

Test environment and production environment

An environment can also mean a whole copy of the setup. A test environment is a safe copy where mistakes cost nothing. Production is the live one that real customers use. They should be built the same way but share nothing important.

PartTest environmentProduction
Model keyA separate test key with a small limitA live key, stored as a secret
DataMade-up orders such as QF-1042Real customer data, handled by policy
Tools that writeFake or sandboxed. request_return only makes a PENDING request.Connected to real systems, still behind approval
Model repliesOften a fake model for repeatable testsThe real model
Who can reach itOnly the teamCustomers, so it needs proper access control

Check deployment readiness with Python

Many outages come from a missing setting, not from a clever bug. A tiny checker can catch the common ones before you deploy. The script below checks two sample configurations: a test one and a live one.

Pythonreadiness.py
def check_config(config):
    problems = []
    key = config.get("api_key", "")
    if not key.startswith("env:"):
        problems.append("api_key must point to an environment variable, such as env:GEMINI_API_KEY")
    if config.get("state_store") not in ("sqlite", "database", "files"):
        problems.append("state_store must be sqlite, database or files, not memory only")
    for name in ("model_timeout_s", "tool_timeout_s"):
        if not isinstance(config.get(name), (int, float)) or config[name] <= 0:
            problems.append(name + " must be a number above zero")
    if not config.get("version"):
        problems.append("version must be set, such as v1")
    if config.get("max_rounds", 0) < 1:
        problems.append("max_rounds must be at least 1")
    return problems

Part 1: the checker. Standard library only. The sample configurations follow in part 2.

Pythonreadiness.py
test_config = {
    "api_key": "env:GEMINI_API_KEY",
    "state_store": "memory",
    "model_timeout_s": 30,
    "tool_timeout_s": 0,
    "version": "v1",
    "max_rounds": 5,
}
live_config = dict(test_config, state_store="sqlite", tool_timeout_s=10)

for name, config in (("test", test_config), ("live", live_config)):
    problems = check_config(config)
    print(name, "->", "READY" if not problems else "NOT READY")
    for p in problems:
        print("  -", p)

Part 2: add this below part 1 in the same file.

What each part does

  • check_config(config) takes a dictionary of settings and returns a list of problems. An empty list means no problem was found.
  • key.startswith("env:") checks that the key setting is only a pointer to an environment variable. A real key written here would fail the check.
  • config.get("state_store") not in (...) rejects memory-only state, because a restart would lose it.
  • The for name in (...) loop checks both timeouts. A timeout of zero or a missing timeout is a problem, because a slow model call could then hang forever.
  • dict(test_config, state_store="sqlite", tool_timeout_s=10) makes a copy of the test settings with two values fixed. That is our "live" sample.
  • The final loop prints READY or NOT READY for each configuration, followed by its problems.
OutputCaptured from a real run
test -> NOT READY
  - state_store must be sqlite, database or files, not memory only
  - tool_timeout_s must be a number above zero
live -> READY

A passing check does not prove the service is safe. It only proves that four common settings are not forgotten. Treat it as a first gate, then add your own checks, such as a health endpoint that confirms the version.

Conclusion and your next step

A deployed agent is a few small pieces: an API layer, the agent loop, tools and knowledge, a state store and traces. Keep real state outside the model, keep secrets in the environment, and keep test and production apart.

Your next step: write down your agent's pieces on one page. For each piece, say where it runs and where its state lives. Then continue to API Design, Background Jobs and Session Management, where you design the endpoints and handle long tasks.

For related reading, see the Agent Launch Safety Checklist and Zero-Downtime Deployments: Feature Flags, Blue-Green, and AI-Generated Rollout Plans.

Common errors and how to fix them

The agent forgets a customer's case after the service restarts.

Why it happens: The case record lives only in program memory.

Fix: Save the record to a file or a database after each step, and load it when a request arrives.

The API key appears in the repository history.

Why it happens: The key was typed into a code file or a committed settings file.

Fix: Remove it, create a new key because the old one is exposed, and read the value from an environment variable.

The service hangs when the model provider is slow.

Why it happens: No timeout is set on the model call.

Fix: Set a timeout for every model and tool call, and return a clear error or hand the case to a person when it passes.

A test accidentally changes real data.

Why it happens: The test environment shares a key or a database with production.

Fix: Give each environment its own key, its own data and its own configuration.

Validation checklist

Tick each item once you have confirmed it.

Hands-on exercise

Review a deployment plan

A teammate proposes this plan for the Quillfeather agent: one script on a laptop that answers website questions, cases kept in a Python list, the API key typed at the top of agent.py, and no timeouts because "the model is fast". Rewrite the plan so it is ready for a controlled test environment.

You will need

  • The service must answer POST /ask.
  • Cases must survive a restart.
  • Tests must not need a real key.

Acceptance criteria

Your work is done when every one of these is true.

Hints (3)
  • Run your plan through the four checks in readiness.py.
  • Ask what is lost if the laptop closes at 3 pm.
  • A fake model is a stand-in object that returns fixed replies.
Show a model answer

A good rewrite reads like this. Run the agent as a small service process, not on a personal laptop. Read GEMINI_API_KEY from the environment and list .env in .gitignore. Save each case to a file such as cases.json, or to a small database, after every step. Set model_timeout_s and tool_timeout_s in a configuration file and fail with a handover when they pass. Add a version label. In tests, pass a fake model client so no key is needed, and use a separate test key for the one check that talks to the real model. This plan also passes the readiness checker.

Knowledge check

Choose an answer, then check it. Nothing is recorded — this is for you.

  1. 1.Where should the main record of a customer's case be kept?
    Show the answer and explanation

    Answer: B. Your own store survives restarts and can be read by any copy of the service. The model keeps nothing between calls, so the first option loses data. A variable is tempting because it is simple, but it disappears when the program stops.

  2. 2.What is the safest way to give the service its API key?
    Show the answer and explanation

    Answer: B. The code only names the variable, so the value never enters the repository. Typing the key in the file is convenient, but anyone who can read the code or its history can use the key.

  3. 3.Why should test and production use different keys and data?
    Show the answer and explanation

    Answer: A. Separation limits the damage a mistake can do. The other options are not true. Using one shared key can look easier, but a runaway test then costs real money.

Frequently asked questions

What does deploying an AI agent mean?

It means running the agent as a program that other programs or people can reach, usually through an API. It also means giving it a safe place to store state, its own settings and secrets, and a way for you to see what it is doing.

Do I need a database for my first agent service?

Not always. For a small test setup, saving cases in a JSON file is fine. When several copies of the service run, or real users depend on the data, move to a database.

Where does the AI model actually run?

Usually at the model provider, not on your server. Your service sends a request over the internet and waits for the reply. Some teams host open models themselves, but the architecture of your service stays much the same.

What is the difference between a test environment and production?

A test environment is a safe copy used for trying things with made-up data. Production is the live system that real customers use. They should be built the same way but use different keys, data and settings.

Written by
PromptFable Editorial
Last updated 18 Nov 2026
Review
Reviewed by Waseem Nadir, Technical Reviewer
Last reviewed 27 Nov 2026

References

Primary sources for the technical details in this lesson. Vendor platforms change — check the official page if anything here looks different from what you see.

PromptFable is independent and is not affiliated with, endorsed by or sponsored by Anthropic, Google, OpenAI or any other vendor. Claude, Gemini, Google AI Studio and other product names are trademarks of their respective owners.