PromptisePromptise
PlatformSoonEnterprise
DocsGitHub
Talk to usGet started
Promptise - AI Framework LogoPromptise

The full-stack framework for agentic systems. Build with the framework. Run it on the platform. Launch it with our engineers.

pip install promptise

[01] Product

  • Framework
  • Platform (coming soon)
  • Enterprise
  • How it works
  • Contact

[02] Framework

  • The Agent
  • The Interface
  • The Harness

[03] Resources

  • Documentation
  • GitHub
  • Why Promptise
  • Use cases
  • Roadmap
  • Guides
  • Learning Paths
  • Questions

[04] Company

  • About
  • Terms of Service
  • Privacy Policy
  • Cookie Policy
  • Subprocessors

© 2026 Promptise by Manser Ventures. All rights reserved.

hello@promptise.com
← Guides> Runtime, triggers and deployment

Deploy AI Agents in Production: Long-Running Python Agents

Run an AI agent as a long-lived Python process: cron and webhook triggers, state between runs, a journal, budgets that pause it, and honest limits.

Level
Intermediate
Reading time
15 min
Published
Oct 10, 2026
Last updated
Oct 24, 2026
Tested with
Promptise 1.9.0
By
Promptise Team
  • Agent Runtime
  • Deployment
Contents · 10 sections↓
  1. 01How do you deploy AI agents in production?
  2. 02How a long-running agent works
  3. 03What you need
  4. 04Build a ticket triage agent, step by step
  5. 05Wake on a webhook instead of a clock
  6. 06Declare it in a manifest and run it from the CLI
  7. 07Other guardrails: health, mission and secrets
  8. 08Before you go to production
  9. 09Frequently asked questions
  10. 10Where to go next

Most agents are written as a request and a reply: you call them, they answer, they're gone. The agents that do real work in production look different. They wake up on a schedule or when something happens, do one bounded job, remember what matters for next time, and stop themselves before they do too much. This guide shows how to deploy AI agents in production by building one in Python with the Promptise Agent Runtime: a support-ticket triage agent that runs every few minutes, keeps state between runs, writes a journal you can read back, and pauses itself when it goes over its budget. Every snippet ran with gpt-5-mini, and the output you see is what it printed, including the parts that didn't go to plan.

[01]

How do you deploy AI agents in production?

Run the agent as a long-lived process, not a function call. Give it a trigger that wakes it (a cron schedule, a webhook, a file landing in a folder), tools that reach your systems, limits on what one run may do, and a record of what it did. With Promptise Foundry, that process is an AgentProcess:

Pythonquickstart.py
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
import asyncio
import sys

from promptise.config import StdioServerSpec
from promptise.runtime import AgentProcess, ProcessConfig, TriggerConfig


async def main() -> None:
    process = AgentProcess(
        name="triage",
        config=ProcessConfig(
            model="openai:gpt-5-mini",
            instructions="Triage new support tickets, then post one short summary.",
            servers={"tickets": StdioServerSpec(command=sys.executable, args=["tickets_server.py"])},
            triggers=[TriggerConfig(type="cron", cron_expression="*/15 * * * *")],
        ),
    )
    await process.start()  # builds the agent, connects its tools, starts the trigger
    print(process.status()["state"], "with", process.status()["trigger_count"], "trigger")
    try:
        await asyncio.Event().wait()  # from here on, the agent wakes every 15 minutes
    finally:
        await process.stop()
        print(process.status()["state"])


if __name__ == "__main__":
    try:
        asyncio.run(main())
    except KeyboardInterrupt:
        pass
Output
running with 1 trigger
stopped

That's a working AI agent cron job. start() builds the agent, connects to its MCP tools and starts the trigger. From then on the cron trigger wakes it every 15 minutes, with no ainvoke() call from you, until you stop it. Everything else in this guide is what you add before you trust it to run unattended.


[02]

How a long-running agent works

An AgentProcess wraps an ordinary Promptise agent. Triggers put events on a queue. A worker takes each event, adds what the agent should know (its context state, recent conversation, remaining budget) and runs the agent once. The budget is checked before every tool call, and after the run the runtime decides whether the process keeps going.

Rendering diagram…

Each process moves through a small state machine, and every transition is validated:

State

How the process gets there

running

start(), or resume() after a pause

suspended

suspend(), a budget with on_exceeded="pause", or a health anomaly with on_anomaly="pause"

stopped

stop(), or a budget with on_exceeded="stop"

failed

A startup error, or max_consecutive_failures failed runs in a row (default 3)

A suspended process keeps its triggers. Events that fire while it's paused wait in the queue until someone calls resume().


[03]

What you need

  • Python 3.10 or newer.

  • Promptise Foundry: pip install "promptise>=1.9.0". Cron, webhook and file-watch triggers work out of the box; their dependencies ship with the base install.

  • An API key for a model provider. This guide uses OpenAI with openai:gpt-5-mini; set OPENAI_API_KEY in your environment or a .env file.


[04]

Build a ticket triage agent, step by step

The agent's job: every time it wakes, find new support tickets, give each a priority, and post one summary to the team channel, naming the on-call engineer for anything urgent.

Step 01

Give the agent its tools

The agent reaches your systems through MCP tools. Here a small MCP server stands in for a ticketing system and a team chat: a JSON file of tickets, and a log file as the channel. If you haven't built one before, How to Connect MCP Servers to Your AI Agent in Python covers the basics.

Pythontickets_server.py
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
import json
from datetime import datetime
from pathlib import Path
from typing import Literal

from promptise.mcp.server import MCPServer, ToolError

server = MCPServer("tickets")

# A stand-in for your ticketing system: a JSON file the agent reads and updates.
TICKETS = Path(__file__).with_name("tickets.json")
CHANNEL = Path(__file__).with_name("support-channel.log")


def load() -> dict:
    return json.loads(TICKETS.read_text()) if TICKETS.exists() else {}


@server.tool(read_only_hint=True)
async def list_untriaged() -> list[dict]:
    """List new support tickets that don't have a priority yet."""
    return [{"ticket_id": tid, **t} for tid, t in load().items() if t.get("priority") is None]


@server.tool()
async def set_priority(ticket_id: str, priority: Literal["P1", "P2", "P3"], reason: str) -> dict:
    """Give a ticket a priority. P1 = outage or data loss, P2 = a customer is blocked, P3 = everything else.

    Args:
        reason: One short sentence explaining the priority.
    """
    tickets = load()
    if ticket_id not in tickets:
        raise ToolError(f"There is no ticket {ticket_id}.")
    tickets[ticket_id].update(priority=priority, reason=reason)
    TICKETS.write_text(json.dumps(tickets, indent=2))
    return {"ticket_id": ticket_id, "priority": priority}


@server.tool()
async def post_summary(text: str) -> str:
    """Post a short triage summary to the support team's channel."""
    stamp = datetime.now().strftime("%H:%M:%S")
    with CHANNEL.open("a") as f:
        f.write(f"[{stamp}] {text}\n")
    return "posted"


if __name__ == "__main__":
    server.run()

Notice where the durable state lives: in the ticket system. A ticket with a priority is done, so the next run won't touch it again. That's the most reliable memory an agent can have, and it's yours, not the runtime's.

Step 02

Describe the process

ProcessConfig holds everything about the process: model, instructions, tools, triggers, starting state and limits. The file also writes a journal, which Step 6 explains.

Pythontriage_agent.py
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
import asyncio
import sys

from promptise import CallbackSink, EventNotifier
from promptise.config import StdioServerSpec
from promptise.runtime import (
    AgentProcess,
    BudgetConfig,
    ContextConfig,
    FileJournal,
    JournalEntry,
    ProcessConfig,
    ToolCostAnnotation,
    TriggerConfig,
)

INSTRUCTIONS = """\
You triage the support queue. Each time you wake up:
1. Call list_untriaged.
2. Give every ticket a priority with set_priority.
3. If you set any priorities, post ONE short summary with post_summary.
   For every P1, name the on-call engineer: use the exact on_call value
   from [Context State]. Never invent a name.
If there are no new tickets, don't post anything and reply "Nothing to triage."
"""

CONFIG = ProcessConfig(
    model="openai:gpt-5-mini",
    instructions=INSTRUCTIONS,
    servers={
        "tickets": StdioServerSpec(command=sys.executable, args=["tickets_server.py"]),
    },
    # Every minute, for the demo. In production: "*/15 * * * *" or "0 8 * * 1-5".
    triggers=[TriggerConfig(type="cron", cron_expression="* * * * *")],
    # State the agent sees at the start of every run.
    context={"initial_state": {"on_call": "Sam"}},
    # The autonomy budget: what one run, and one day, may do.
    budget=BudgetConfig(
        enabled=True,
        max_tool_calls_per_run=6,
        max_runs_per_day=200,
        tool_costs={"post_summary": ToolCostAnnotation(cost_weight=1.0, irreversible=True)},
        max_irreversible_per_run=1,
        on_exceeded="pause",
    ),
)

journal = FileJournal(".promptise/journal")


def build_process(name: str = "triage", initial_state: dict | None = None) -> AgentProcess:
    config = CONFIG
    if initial_state is not None:
        config = CONFIG.model_copy(update={"context": ContextConfig(initial_state=initial_state)})

    async def record(event) -> None:
        """Write every runtime event to the journal, plus a checkpoint after each run."""
        await journal.append(JournalEntry(process_id=name, entry_type=event.event_type, data=event.data))
        if event.event_type == "invocation.complete":
            await journal.checkpoint(
                name,
                {
                    "context_state": process.context.state_snapshot(),
                    "lifecycle_state": process.state.value,
                    "budget_remaining": process.status().get("budget"),
                },
            )

    process = AgentProcess(
        name=name,
        process_id=name,
        config=config,
        event_notifier=EventNotifier(sinks=[CallbackSink(record)]),
    )
    return process


async def main() -> None:
    process = build_process()
    await process.start()
    print(f"{process.name} is {process.state.value}. Press Ctrl+C to stop.")
    try:
        while True:
            await asyncio.sleep(3600)
    finally:
        await process.stop()
        print(f"{process.name} is {process.state.value}.")


if __name__ == "__main__":
    try:
        asyncio.run(main())
    except KeyboardInterrupt:
        pass

The parts that matter:

  • The trigger. A standard five-field cron expression. This guide uses every minute so you can watch several cycles; a real triage agent might run every 15 minutes, or at 8:00 on weekdays.

  • The context. initial_state is the process's key-value state. The runtime shows it to the agent at the start of every run, and your code can change it while the process runs.

  • The budget. At most six tool calls per run, 200 runs a day, and one irreversible action per run. post_summary is marked irreversible because a message, once posted, can't be unposted. Cost weights are abstract units you choose, not money.

python triage_agent.py runs the process until you press Ctrl+C:

Output
triage is running. Press Ctrl+C to stop.
triage is stopped.
Step 03

Run it for a few cycles

To see the whole lifecycle in a few minutes, this script starts the process, adds tickets between runs and prints what happens. A small helper, seed_tickets.py, adds the tickets: two at first, one between runs, then a burst of five.

Pythondemo.py
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
"""Drive the triage process through three cron cycles and print what happens."""

import asyncio
import subprocess
import sys
import time
from pathlib import Path

from triage_agent import build_process

CHANNEL = Path("support-channel.log")


def seed(batch: str) -> None:
    out = subprocess.run([sys.executable, "seed_tickets.py", batch], capture_output=True, text=True)
    print(f"{time.strftime('%H:%M:%S')}  queue: {out.stdout.strip()}")


async def wait_for_run(process, n: int) -> None:
    while process.status()["invocation_count"] < n:
        await asyncio.sleep(1)
    await asyncio.sleep(1)  # let post-run bookkeeping finish
    s = process.status()
    print(
        f"{time.strftime('%H:%M:%S')}  run {n} done: state={s['state']} "
        f"conversation_messages={s['conversation_messages']} "
        f"tool_calls_left_this_run={s['budget']['tool_calls_run']}"
    )


async def main() -> None:
    CHANNEL.unlink(missing_ok=True)
    seed("1")
    process = build_process()
    await process.start()
    print(f"{time.strftime('%H:%M:%S')}  {process.name} is {process.state.value}")

    await wait_for_run(process, 1)

    # Shift change: tell the running agent who is on call now.
    process.context.put("on_call", "Dana", source="operator")
    seed("2")
    await wait_for_run(process, 2)

    # A burst of tickets: more work than one run's budget allows.
    seed("burst")
    await wait_for_run(process, 3)

    # Wait for the next cron tick while paused.
    await asyncio.sleep(65)
    s = process.status()
    print(f"{time.strftime('%H:%M:%S')}  after next tick: state={s['state']} queue_size={s['queue_size']}")

    print("\nsupport-channel.log:")
    print(CHANNEL.read_text())
    print("on_call history:", [(e.value, e.source) for e in process.context.state_history("on_call")])

    await process.stop()
    print(f"{time.strftime('%H:%M:%S')}  {process.name} is {process.state.value}")


asyncio.run(main())
Output
01:21:23  queue: 2 new ticket(s) in the queue
01:21:24  triage is running
01:22:22  run 1 done: state=running conversation_messages=2 tool_calls_left_this_run=2
01:22:22  queue: 1 new ticket(s) in the queue
01:23:11  run 2 done: state=running conversation_messages=4 tool_calls_left_this_run=3
01:23:11  queue: 5 new ticket(s) in the queue
Budget violation: max_tool_calls_per_run (limit=6, current=7), action=pause
01:24:25  run 3 done: state=suspended conversation_messages=6 tool_calls_left_this_run=0
01:25:30  after next tick: state=suspended queue_size=1

support-channel.log:
[01:22:20] T-201 set to P1 (site-wide checkout 500 errors). On-call: Sam. T-202 set to P2 (customer blocked from downloading invoice PDF).
[01:23:09] T-203 → P1: Nobody in the EU region can log in. On-call: Dana.

on_call history: [('Sam', 'system'), ('Dana', 'operator')]
AgentProcess triage: event 5c8e8eb7-675f-47c0-9be6-1a6f4ff9f3f8 (cron) dead-lettered: process stopped
01:25:31  triage is stopped

Three runs, each at the top of a minute, with no call from the script. Starting the process took about a second here; start() builds the agent and connects its tools once, and every run reuses them. The next three steps read this output from top to bottom.

Step 04

Change what the agent knows while it runs

Between runs 1 and 2, the on-call engineer changed. The script told the running process with one line:

Pythondemo.py
process.context.put("on_call", "Dana", source="operator")

Run 1 named Sam for its P1. Run 2 named Dana. Nothing restarted. The context keeps an audit trail too: state_history("on_call") shows who set each value, the initial system value and the operator change.

The process carries two kinds of memory between runs:

  • Context state, the key-value store you just used. The runtime adds it to the start of every run as a [Context State] message.

  • Recent conversation, a rolling buffer of each run's trigger message and the agent's final reply. That's why conversation_messages grows by two per run. The default keeps the last 100 messages; change it with conversation_max_messages in ContextConfig.

Note

Long runs keep their context state. Once a run has several tool results, the agent compacts its working context: earlier turns shrink to a short summary and the gathered facts to a list. System messages such as [Context State] and [Budget Remaining] are kept on every model call, compacted or not.

Here's what the model received in run 3, on its first call and on its last call, after the five priorities were set and post_summary was refused, captured with a LangChain callback:

Output
  MODEL SEES: system | [Context State] {'on_call': 'Dana'}
  MODEL SEES: system | You triage the support queue. Each time you wake up: 1. Call list_untriaged.…
  MODEL SEES: system | [Budget Remaining] {'tool_calls_run': 6, 'llm_turns_run': None, 'cost_run': N…
  MODEL SEES: human | [Trigger: cron] trigger_id=cron-0d704cb07a event_id=44b2fd7f-d6ea-4f00-a3b5-6a…
  MODEL SEES: ai | Posted summary and priorities: - T-201 → P1: Site-wide checkout 500 errors. On-ca…
  MODEL SEES: human | [Trigger: cron] trigger_id=cron-0d704cb07a event_id=2b028a16-0e9d-4ba1-96c1-e0…
  MODEL SEES: ai | Posted summary and priorities: - T-203 → P1: Nobody in the EU region can log in.…
  MODEL SEES: human | [Trigger: cron] trigger_id=cron-0d704cb07a event_id=78361620-5b10-4658-9eda-9b…
…
  MODEL SEES: system | [Context State] {'on_call': 'Dana'}
  MODEL SEES: system | You triage the support queue. Each time you wake up: 1. Call list_untriaged.…
  MODEL SEES: system | [Budget Remaining] {'tool_calls_run': 6, 'llm_turns_run': None, 'cost_run': N…
  MODEL SEES: system | Earlier in this conversation (shortened). Answer the user's current request,…
  MODEL SEES: human | [Trigger: cron] trigger_id=cron-0d704cb07a event_id=78361620-5b10-4658-9eda-9b…
  MODEL SEES: ai |
      tool_call: set_priority {'ticket_id': 'T-300', 'priority': 'P2', 'reason': 'User cannot receiv…
      tool_call: set_priority {'ticket_id': 'T-301', 'priority': 'P3', 'reason': 'Mobile app crashes…
      tool_call: set_priority {'ticket_id': 'T-302', 'priority': 'P1', 'reason': 'Customer was charg…
      tool_call: set_priority {'ticket_id': 'T-303', 'priority': 'P3', 'reason': 'Logo invisible in…
      tool_call: set_priority {'ticket_id': 'T-304', 'priority': 'P2', 'reason': 'Enterprise custome…
      tool_call: post_summary {'text': 'T-300 → P2: Password reset email never arrives.\nT-301 → P3:…
  MODEL SEES: tool | {"ticket_id": "T-300", "priority": "P2"}
  MODEL SEES: tool | {"ticket_id": "T-301", "priority": "P3"}
  MODEL SEES: tool | {"ticket_id": "T-302", "priority": "P1"}
  MODEL SEES: tool | {"ticket_id": "T-303", "priority": "P3"}
  MODEL SEES: tool | {"ticket_id": "T-304", "priority": "P2"}
  MODEL SEES: tool | Error: BudgetExceededError: Budget limit max_tool_calls_per_run reached (limit…
  MODEL SEES: system | Facts already gathered by your earlier tool calls, each as it was when the ca…

The first call also shows the recent conversation: the two earlier runs' trigger messages and replies. A trigger's payload arrives inside an <untrusted-trigger-payload-…> block with a random tag, after a notice that its content is data from outside the system, not instructions.

Step 05

Let the budget stop a runaway run

Run 3 got five tickets at once. Listing them, prioritizing all five and posting the summary takes seven tool calls; the budget allows six. Here's what happened, from the output above:

  • The run listed the tickets, then asked for six calls in one turn: five set_priority calls and post_summary. The listing and the five priorities used up the six allowed calls.

  • The seventh, post_summary, was refused before it ran. The agent got the refusal as the tool's result: Error: BudgetExceededError: Budget limit max_tool_calls_per_run reached (limit 6); tool call 'post_summary' was not executed. Stop calling tools and give your final answer. No summary was posted: the channel log has no line from run 3.

  • After the run, the runtime logged Budget violation: max_tool_calls_per_run (limit=6, current=7), action=pause and suspended the process. The next cron tick still fired. Its event waited in the queue (queue_size=1) instead of running. When the script stopped the process, that event was dead-lettered (process stopped) instead of vanishing.

That's the most important thing to know about the autonomy budget: per-run limits are checked before every tool call, so a call that would cross one never runs. The run itself isn't cut off. The refusal tells the agent to stop calling tools and give its final answer, so it finishes with what it has done so far: here, five priorities and no summary. The daily limit, max_runs_per_day, is checked before a run starts, so the run over that limit never happens.

Three cron runs of the triage agent: run 1 names Sam as on-call, the operator changes on_call to Dana without a restart, and run 2 names Dana. In run 3, five tickets use all six allowed tool calls, so post_summary is refused before it runs, the process is suspended after the run, and the next tick waits in the queue until resume().
FigureThree cron runs of the triage agent: a context change between runs, then a budget refusal that pauses the process

So set per-run limits above what a normal run needs: here, six calls covered the burst's priorities but not its summary. Use the daily limits to cap the total. Three more things worth knowing:

  • on_exceeded can be "pause", "stop" or "escalate". "escalate" posts the violation to a webhook or an event bus, then pauses.

  • Nothing resumes a paused process automatically, not even the daily reset. A person, or your own code, calls process.resume(), and the queued events run then.

  • With inject_remaining=True (the default), the agent sees its remaining budget at the start of each run as a [Budget Remaining] message.

Note

The budget counts tool calls and LLM turns, not money. Token spend isn't tracked. If you need a dollar limit, cap max_llm_turns_per_run and max_runs_per_day, and watch your provider's usage dashboard. The Autonomy Budget docs cover cost weights in detail.

Step 06

Keep a journal you can read back

When something goes wrong at 3 a.m., you want a record of what the agent did. Promptise has a journal for exactly this: FileJournal writes append-only JSONL, one file per process, and promptise runtime logs prints it.

Note

AgentProcess can also write a journal itself. ProcessConfig(journal=JournalConfig(level="checkpoint")) records state changes, each run's result, budget violations, refused tool calls and a checkpoint after every run, and level="full" adds trigger events and every tool call and result. It's off by default. This guide journals the runtime events instead, because the same CallbackSink can forward them to your alerting.

The process emits events as it works: process.started, invocation.start, invocation.complete, budget.warning, budget.exceeded and more. Pass an EventNotifier with a CallbackSink, and you can journal every one of them. This is the record function from Step 2:

Pythontriage_agent.py
1
2
3
4
5
6
7
8
9
10
11
12
    async def record(event) -> None:
        """Write every runtime event to the journal, plus a checkpoint after each run."""
        await journal.append(JournalEntry(process_id=name, entry_type=event.event_type, data=event.data))
        if event.event_type == "invocation.complete":
            await journal.checkpoint(
                name,
                {
                    "context_state": process.context.state_snapshot(),
                    "lifecycle_state": process.state.value,
                    "budget_remaining": process.status().get("budget"),
                },
            )

After each run it also stores a checkpoint: a snapshot of the context state, the lifecycle state and the remaining budget. Read the journal back from the command line:

>_Terminal
promptise runtime logs triage --lines 40
Output
Journal: triage  (time, entry ID, type, data)
2026-10-23T23:21:24.313  23d08156-8331-465b-8308-5c27514ef693  process.started  {"process_name": "triage", "process_id": "triage"}
2026-10-23T23:22:00.017  d1d11655-e019-4ff8-8305-63f6111e756c  invocation.start  {"model": "openai:gpt-5-mini"}
2026-10-23T23:22:21.206  7daedb30-5f7b-4071-b25d-5e1d82054d3d  invocation.complete  {"duration_ms": 21195.2}
2026-10-23T23:22:21.207  8f9cdc2e-b612-4c9c-9340-c0e53ba6e5bf  checkpoint  {"state": {"context_state": {"on_call": "Sam"}, "lifecycle_state": "running",...
2026-10-23T23:22:21.207  72482b04-4838-44f9-9c51-623eb5149dff  budget.warning  {"process_name": "triage", "limit_type": "max_irreversible_per_run", "current...
2026-10-23T23:23:00.080  bcd50bd9-d478-4322-a75d-2d66fce9eb8c  invocation.start  {"model": "openai:gpt-5-mini"}
…
2026-10-23T23:24:00.021  0373db4e-942a-4b4f-9b3b-7f53b4cc63aa  invocation.start  {"model": "openai:gpt-5-mini"}
2026-10-23T23:24:24.125  3035acfd-8612-4b51-bb7a-a6c015831d18  invocation.complete  {"duration_ms": 24108.5}
2026-10-23T23:24:24.128  cda83c84-6a6a-4e64-9f1a-56bd15547ed8  checkpoint  {"state": {"context_state": {"on_call": "Dana"}, "lifecycle_state": "suspende...
2026-10-23T23:24:24.128  8cd9b1fd-be28-4498-967e-86f1db3d1da2  budget.exceeded  {"process_name": "triage", "limit_type": "max_tool_calls_per_run", "current":...
2026-10-23T23:24:24.128  91540080-b028-4ef2-9813-cdf9c1661d16  process.suspended  {"process_name": "triage", "process_id": "triage", "reason": "budget"}
2026-10-23T23:24:24.129  bc20d1ee-4b08-4375-a88c-933bb5a92b73  budget.warning  {"process_name": "triage", "limit_type": "max_tool_calls_per_run", "current":...
2026-10-23T23:25:31.075  cc3447a6-faf3-41b7-ba81-ed6ca4c79ad5  process.stopped  {"process_name": "triage", "process_id": "triage"}

Each line starts with the entry's time and ID. The budget.warning entries after runs 1 and 2 are the irreversible limit: each run used its one post_summary, more than the default warning_threshold of 80%. The full entries are in .promptise/journal/triage.jsonl, for example this line from run 3:

JSONtriage.jsonl
{"entry_id": "8cd9b1fd-be28-4498-967e-86f1db3d1da2", "process_id": "triage", "timestamp": "2026-10-23T23:24:24.128675+00:00", "entry_type": "budget.exceeded", "data": {"process_name": "triage", "limit_type": "max_tool_calls_per_run", "current": 7, "limit": 6}}

promptise runtime logs looks up the journal by the name you give it, which is why build_process uses the process name as its process_id too.

Step 07

Restart without losing state

This process keeps its context in memory and has no JournalConfig, so a restart starts from the initial state again. The checkpoint fixes that. ReplayEngine reads the journal and returns the last known state, and you start the new process with it:

Pythonrecover.py
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
import asyncio

from promptise.runtime import ReplayEngine

from triage_agent import build_process, journal


async def main() -> None:
    recovered = await ReplayEngine(journal).recover("triage")
    print("recovered:", recovered)

    process = build_process(initial_state=recovered["context_state"])
    await process.start()
    print("state after restart:", process.context.state_snapshot())
    await process.stop()


asyncio.run(main())
Output
recovered: {'context_state': {'on_call': 'Dana'}, 'lifecycle_state': 'suspended', 'last_entry_type': 'process.stopped', 'entries_replayed': 4, 'mission': None, 'checkpoint': {'context_state': {'on_call': 'Dana'}, 'lifecycle_state': 'suspended', 'budget_remaining': {'tool_calls_run': 0, 'llm_turns_run': None, 'cost_run': None, 'irreversible_run': 1, 'tool_calls_day': None, 'runs_day': 197, 'cost_day': None}}}
state after restart: {'on_call': 'Dana'}

The new process knows Dana is on call, although the config still says Sam. It also learned the old process was suspended when it stopped: here, paused by its budget. Starting it again is a decision for a person, so check lifecycle_state before you do.

Note

A process with ProcessConfig(journal=JournalConfig(...)) does this on its own. Its first start() restores the context state, the budget counters, the conversation and the invocation count from the last checkpoint (recover_on_start=True is the default).


[05]

Wake on a webhook instead of a clock

A schedule is right for sweeps. When something else already knows a ticket arrived, let it wake the agent. A webhook trigger starts a small HTTP server inside the process; this keeps a slow cron sweep as a safety net:

Pythonwebhook_agent.py
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
import asyncio

from promptise.runtime import AgentProcess, TriggerConfig

from triage_agent import CONFIG

config = CONFIG.model_copy(
    update={
        "triggers": [
            TriggerConfig(type="cron", cron_expression="*/15 * * * *"),
            TriggerConfig(type="webhook", webhook_path="/tickets", webhook_port=8180),
        ]
    }
)


async def main() -> None:
    process = AgentProcess(name="triage", config=config)
    await process.start()
    print("listening on http://127.0.0.1:8180/tickets")
    while process.status()["invocation_count"] < 1:
        await asyncio.sleep(1)
    print("runs:", process.status()["invocation_count"])
    await process.stop()


asyncio.run(main())

Post an event the way your help desk would:

>_Terminal
curl -s -X POST http://127.0.0.1:8180/tickets -H 'Content-Type: application/json' -d '{"event": "ticket.created", "ticket_id": "T-401"}'
Output
{"status": "accepted", "event_id": "a12b105a-4e4a-49d7-812e-d9715a5410dd"}

The webhook answers 202 at once and the run happens in the background. The JSON body becomes the trigger payload the agent sees. The process printed:

Output
WebhookTrigger on port 8180 has no HMAC secret: any HTTP client can trigger this webhook. Set hmac_secret for production use.
listening on http://127.0.0.1:8180/tickets
runs: 1

And the channel got:

Output
[01:29:33] T-401: set to P1 — data export deleting source rows (risk of data loss). On-call: Sam.

Take that warning seriously. A webhook created from TriggerConfig listens on 127.0.0.1 unless you set webhook_host. TriggerConfig also takes the signature settings: hmac_secret, signature_scheme (generic, github, stripe or telegram) and allowed_sources for an IP allowlist. Add a secret to the webhook trigger:

Pythonsigned_webhook.py
1
2
3
4
5
6
TriggerConfig(
    type="webhook",
    webhook_path="/tickets",
    webhook_port=8180,
    hmac_secret=os.environ["TICKETS_WEBHOOK_SECRET"],
)

In a test, an unsigned POST got 401 with {"status": "error", "message": "Missing or invalid signature"}, and a POST with a valid X-Webhook-Signature: sha256=<hex> header got 202. In a .agent manifest, write hmac_secret: ${TICKETS_WEBHOOK_SECRET} so the secret stays out of the file. AI Agent Webhook Trigger covers GitHub and Stripe signatures, replay protection and response codes.

The other built-in triggers work the same way. file_watch wakes the agent when files matching watch_patterns appear or change in watch_path. event and message listen to an event bus or message broker, which you pass to an AgentRuntime to share between its processes. Triggers lists them all, and how to register your own.


[06]

Declare it in a manifest and run it from the CLI

You don't have to write Python to run a process. A .agent manifest describes the same thing in YAML, and the promptise runtime command runs it:

YAMLtriage.agent
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
version: "1.0"
name: triage
model: openai:gpt-5-mini
instructions: |
  You triage the support queue. Each time you wake up:
  1. Call list_untriaged.
  2. Give every ticket a priority with set_priority.
  3. If you set any priorities, post ONE short summary with post_summary.
     For every P1, name the on-call engineer: use the exact on_call value
     from [Context State]. Never invent a name.
  If there are no new tickets, don't post anything and reply "Nothing to triage."

servers:
  tickets:
    type: stdio
    command: python
    args: ["tickets_server.py"]

triggers:
  - type: cron
    cron_expression: "* * * * *"   # every minute for the demo

world:
  on_call: Sam

budget:
  enabled: true
  max_tool_calls_per_run: 6
  max_runs_per_day: 200
  max_irreversible_per_run: 1
  on_exceeded: pause
  tool_costs:
    post_summary:
      cost_weight: 1.0
      irreversible: true

world is the manifest's name for the initial context state. Check the file before you run it:

>_Terminal
promptise runtime validate triage.agent
Output
Validating triage.agent...
✓ Schema validation passed
✓ No warnings
                           Manifest Summary                            
┏━━━━━━━━━━━━━━┳━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━┓
┃ Field        ┃ Value                                                ┃
┡━━━━━━━━━━━━━━╇━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━┩
│ Name         │ triage                                               │
│ Model        │ openai:gpt-5-mini                                    │
│ Version      │ 1.0                                                  │
│ Instructions │ You triage the support queue. Each time you wake up: │
│              │ 1. Call...                                           │
│ Servers      │ 1                                                    │
│ Triggers     │ 1                                                    │
└──────────────┴──────────────────────────────────────────────────────┘
✓ Validation complete!

Then start it. It runs in the foreground until you press Ctrl+C:

>_Terminal
promptise runtime start triage.agent
Output
Loaded process: triage
                        Agent Processes                         
┏━━━━━━━━┳━━━━━━━━━┳━━━━━━━━━━┳━━━━━━━━━━━━━┳━━━━━━━┳━━━━━━━━━━┓
┃ Name   ┃ State   ┃ ID       ┃ Invocations ┃ Queue ┃ Uptime   ┃
┡━━━━━━━━╇━━━━━━━━━╇━━━━━━━━━━╇━━━━━━━━━━━━━╇━━━━━━━╇━━━━━━━━━━┩
│ triage │ RUNNING │ 83367271 │           0 │     0 │ 0h 0m 0s │
└────────┴─────────┴──────────┴─────────────┴───────┴──────────┘

Runtime triage (pid 96913), control API on http://127.0.0.1:61738
Press Ctrl+C to stop all processes, or run 'promptise runtime stop triage' from 
another terminal.

Shutting down (SIGINT)...
All processes stopped.

In that run the agent woke at the next minute, triaged two tickets and posted its summary before Ctrl+C. Pass a directory instead of a file to start every .agent file in it, and promptise runtime init --template cron writes a starter manifest. The Agent Manifests and Runtime CLI docs have every field and option.

Note

promptise runtime start serves a control API on loopback with a random token, so promptise runtime status and promptise runtime stop triage work from another terminal on the same machine. --detach runs the runtime in the background and writes its output to a log file. In production, still run it under a supervisor such as systemd, Docker or Kubernetes, which restarts it after a crash or a reboot.


[07]

Other guardrails: health, mission and secrets

The budget limits how much an agent does. Three more opt-in subsystems watch what it does. All are off by default.

  • Behavioral health (HealthConfig) spots bad patterns without calling a model: the same tool with the same arguments again and again, repeating loops, empty responses and high error rates. on_anomaly can log, pause or escalate.

  • Mission (MissionConfig) gives a process an objective and success_criteria. Every eval_every runs, a model judges progress; the process can stop itself when the mission is achieved, or escalate when confidence drops below confidence_threshold.

  • Secret scoping (SecretScopeConfig) gives each process its own secrets, resolved from ${ENV_VAR} references when it starts, encrypted in memory, with optional expiry, and revoked on stop() unless you set revoke_on_stop=False. A missing variable stops the start with SecretResolutionError: Environment variable 'NOT_SET_ANYWHERE' not found (required by secret 'tickets_token'); set it before starting the process. The agent itself can only read them through the get_secret tool in open execution mode.

Tune health checks before you let them pause anything. Empty-response detection looks at the agent's final reply only, and stuck and loop detection look within one run, so an agent with nothing to do isn't flagged. With the default thresholds and on_anomaly="pause", the triage agent ran on an empty queue every five seconds:

Output
run 1: state=running anomalies=0
run 2: state=running anomalies=0
run 3: state=running anomalies=0
run 4: state=running anomalies=0

Still, start with on_anomaly="log", read what it flags for a few days, then tune empty_threshold and stuck_threshold to fit your agent before switching to "pause". See Behavioral Health, Mission Model and Secret Scoping.


[08]

Before you go to production

Know where every piece of state lives. In Promptise 1.10.0:

State

Where it lives

Survives a restart?

Context state

Process memory

With a JournalConfig, yes. Otherwise only if you checkpoint and restore it, as in Step 7

Recent conversation

Process memory; kept across stop() and start()

With a JournalConfig, yes. Otherwise no

Budget counters, daily ones too

Process memory, checkpointed by a JournalConfig

With a JournalConfig, yes. Otherwise they start from zero

Journal and checkpoints

Files you or JournalConfig write

Yes

Tickets, orders, records

Your systems, behind MCP tools

Yes

With that in mind:

  • Plan for restarts at two levels. restart_policy="on_failure" restarts a process that reached max_consecutive_failures, with backoff, up to max_restarts times. In a test with a model name that doesn't exist, every run failed: after three failures the process went to failed, restarted itself and was running again within ten seconds, twice, with restart_count going up each time. Still run the runtime itself under systemd, Docker or Kubernetes with a restart policy, restore context from your checkpoint on start, and alert on failed.

  • Run one copy of each process. Each process has its own cron trigger and nothing coordinates replicas, so two copies of the same process both fire at every tick and do the work twice. Scale by giving different processes different jobs, and make tools that change data safe to repeat.

  • Distributed means remote control, not failover. RuntimeTransport puts an HTTP API on a node's runtime (health, status, start, stop, inject an event). It refuses to bind a public address without an auth_token, and RuntimeCoordinator(auth_token=...) sends the token to its nodes. RuntimeCoordinator registers nodes, checks their health and aggregates status. There's no shared state, no leader election and no automatic move of processes off a failed node.

  • Keep runs small. Short runs stay inside the budget and are cheaper to retry.

  • Lock down triggers. Give every webhook an hmac_secret, and put a reverse proxy in front if anything outside the machine calls it.

  • Watch the journal. Alert on budget.exceeded, health.anomaly and invocation.error events; the CallbackSink from Step 6 is a good place to send them on.


[09]

Frequently asked questions

How do I run an AI agent as a cron job?

Give an AgentProcess a trigger like TriggerConfig(type="cron", cron_expression="*/15 * * * *") and start it. The process stays up and wakes the agent on schedule, so the agent and its tool connections are built once instead of on every run. A plain system cron job that runs a script also works; it just rebuilds everything each time and keeps no state in between.

How does a long-running AI agent remember things between runs?

Three ways, in order of reliability. Your own systems, through tools: a triaged ticket stays triaged. The process context, a key-value store the agent sees at the start of every run, which you can checkpoint to a journal and restore. And a rolling buffer of recent trigger messages and replies. For anything that must survive a restart, use the first two.

How do I stop an autonomous AI agent from running up costs?

Enable BudgetConfig with per-run and daily limits on tool calls, LLM turns, cost weights and irreversible actions, and choose pause, stop or escalate for when a limit is crossed. Per-run limits are checked before every tool call, so a call that would cross one never runs, and max_runs_per_day is checked before a run starts. Track real token spend with your model provider as well.

Can I run AI agents on several machines?

You can run a runtime on each machine and manage them over HTTP with RuntimeTransport and RuntimeCoordinator. In Promptise 1.10.0 that gives you remote start, stop, status and health checks, with a bearer token, not shared state or automatic failover, so assign each process to one machine.

Do I need Kubernetes to deploy an AI agent?

No. One promptise runtime start in the foreground under any supervisor that restarts it on failure is enough to begin with: systemd, Docker with a restart policy, or a Kubernetes Deployment with one replica.


[10]

Where to go next

  • Agent Runtime: the overview of processes, triggers, state and governance.

  • Agent Processes: every ProcessConfig field and lifecycle method.

  • Cron triggers and Triggers: schedules, webhooks, file watches and custom trigger types.

  • Journal and Context & State: what to record and what the agent sees.

  • Runtime Manager: several processes in one AgentRuntime.

  • How to Deploy an AI Agent with Docker: package the agent in a container with health checks and graceful shutdown.

  • AI Agent Cron Jobs: Run an Agent on a Schedule: cron expressions, time zones and missed ticks.

  • AI Agent Production Checklist: what to check before launch.

  • Build a Production MCP Server in Python: make the tools this agent calls safe for unattended use.

  • OpenAPI to MCP: Turn Any REST API into an MCP Server: give the agent tools for an API you already have.

Contents

  1. 01How do you deploy AI agents in production?
  2. 02How a long-running agent works
  3. 03What you need
  4. 04Build a ticket triage agent, step by step
  5. 05Wake on a webhook instead of a clock
  6. 06Declare it in a manifest and run it from the CLI
  7. 07Other guardrails: health, mission and secrets
  8. 08Before you go to production
  9. 09Frequently asked questions
  10. 10Where to go next

Learning paths

Want more structure? Paths put guides in order, like a short course.

See the paths →

> Runtime, triggers and deployment

Related guides

All guides in this topic →
  • // 01Intermediate · 18 minHow to Deploy an AI Agent with Docker (2026 Guide)Deploy an AI agent with Docker: a Dockerfile, env vars and secrets, health checks, graceful shutdown, and docker compose with the agent's MCP server.
  • // 02Intermediate · 17 minAI Agent Production Checklist: What to Check Before LaunchAn AI agent production checklist: security, approvals, guardrails, limits, cost, observability, evals, deployment and incident response, with code.
  • // 03Intermediate · 18 minAI Agent Code Execution Sandbox: Run LLM Code SafelyLet an AI agent write and run Python in a Docker sandbox: analyse a CSV, try real escape attempts, set limits, and learn where the sandbox stops.
  • // 04Intermediate · 20 minAutoGen Docker Task Isolation: Secure the Code ExecutorSet up AutoGen Docker task isolation: configure DockerCommandLineCodeExecutor, run one container per task, cut the network, set limits and fix errors.
  • // 05Intermediate · 18 minAI Agent Cost Control: Budgets That Stop Runaway SpendHow to control AI agent costs: per-run and daily budgets that refuse tool calls before they run, token caps, iteration limits, and what each one misses.
  • // 06Intermediate · 25 minAI Agent Notifications: Webhook and Slack Alerts in PythonGet alerted when your AI agent fails a tool call, hits a guardrail or budget, or needs approval. Webhooks, Slack and Python callbacks, with real payloads.

Keep going.

Browse every guide by topic and level, or follow a learning path that puts them in order.

All guidesLearning paths