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
← Learning paths> Agentic Engineering with Promptise Foundry
Lesson 94 / 100
94%

Run Multiple AI Agents: One Runtime, Many Processes

Run multiple AI agents in one runtime: add and remove processes, load manifests, share notifications, contain failures and shut down cleanly on SIGTERM.

Intermediate18 minAgent RuntimeMulti-Agent SystemsDeployment
All 100 lessons↓
  1. ✓What Is an AI Agent? Definition, How It Works, Examples
  2. ✓How to Build an AI Agent in Python (2026 Guide)
  3. ✓Build a Personal AI Agent: Memory, Reminders, Chat
  4. ✓What Is an Agent Harness? Parts and How to Build One
  5. ✓System Prompt Best Practices for AI Agents in Python
  6. ✓Best LLM for AI Agents (2026): Picks, Prices, How to Test
  7. ✓AI Agent YAML: Define and Run an Agent From a Config File
  8. ✓Streaming LLM Responses with FastAPI: Tokens and Tool Calls
  9. ✓Best Local LLM for AI Agents: Ollama Models by GPU (2026)
  10. ✓Claude AI Agent with MCP: Use Anthropic Models in Promptise
  11. ✓Gemini AI Agent with MCP: Use Google Models in Promptise
  12. ✓Azure OpenAI Agent with MCP: Use Deployments in Promptise
  13. ✓OpenRouter AI Agent with MCP: Many Models in Promptise
  14. ✓Ollama AI Agent with MCP: Run Local Models in Promptise
  15. ✓LLM Semantic Cache and Model Fallback in Python
  16. ✓What Is MCP (Model Context Protocol)? A Developer's Guide
  17. ✓What Is Tool Calling? LLM Function Calling Explained
  18. ✓MCP Tools vs Resources vs Prompts (With Python Examples)
  19. ✓How to Connect MCP Servers to Your AI Agent in Python
  20. ✓Build a Production MCP Server in Python (Step by Step)
  21. ✓MCP Transports: stdio vs Streamable HTTP vs SSE (Python)
  22. ✓MCP 2026-07-28 Migration: Make Your MCP Server Stateless
  23. ✓OpenAPI to MCP: Turn Any REST API into an MCP Server
  24. ✓MCP Authentication in Python: API Keys, JWT and OAuth
  25. ✓Build an Authenticated MCP Server for Your AI Agent (Python)
  26. ✓MCP Security Best Practices: A Checklist for MCP Servers
  27. ✓Testing MCP Servers in Python: pytest Without a Live Server
  28. ✓Too Many MCP Tools? How to Fix LLM Tool Selection in Python
  29. ✓Idempotent Tool Calls: Make AI Agent Retries Safe
  30. ✓AI Agent Tool Failures: Stop Unsafe Workarounds
  31. ✓MCP Server Caching, Timeouts and Circuit Breakers in Python
  32. ✓MCP Middleware for Servers: Auth, Logging, Rate Limits
  33. ✓MCP vs CLI for AI Agents: Tokens, Security, When to Use Each
  34. ✓LangChain vs MCP: Differences and How They Work Together
  35. ✓FastMCP Alternatives for Production MCP Servers (2026)
  36. ✓AI Agent Audit Logging: Tamper-Evident Logs in Python
  37. ✓AI Agent Human in the Loop: Approve Tool Calls in Python
  38. ✓AI Agent Prompt Injection: How to Defend Against It
  39. ✓Hidden Text Prompt Injection: Sanitize Pages for AI Agents
  40. ✓Build a Multi-Agent System in Python (and When Not To)
  41. ✓Context Engineering for AI Agents: Context Window Management
  42. ✓Context Compaction for AI Agents: Trim vs Summarize
  43. ✓How to Deploy an AI Agent with Docker (2026 Guide)
  44. ✓LLM Tool Rate Limiting: Per-Client Limits for MCP Servers
  45. ✓MCP Long-Running Tasks: Background Jobs in Python
  46. ✓MCP Server Monitoring: Prometheus, OpenTelemetry and Logs
  47. ✓Best AI Agent Frameworks (2026): Python Options Compared
  48. ✓Self-Improving AI Agent: Learn From Tool Failures in Python
  49. ✓AI Agent Identity: Authenticate Agents to MCP Servers
  50. ✓Code-Action Agents in Python: One Program vs 37 Tool Calls
  51. ✓Multi-Tenant AI Agents: Keep Each Customer's Data Apart
  52. ✓What Is Agentic RAG? How It Differs from Classic RAG
  53. ✓AI Agent Memory in Python: Short-Term and Long-Term
  54. ✓Per-User Agent Memory Isolation: Stop Leaks Between Users
  55. ✓Agentic RAG in Python: Give Your AI Agent a Search Tool
  56. ✓AI Agent Reasoning Patterns in Python: From ReAct to Debate
  57. ✓Plan-and-Execute Agents in Python: Beyond the ReAct Loop
  58. ✓Self-Modifying AI Agent in Python: Open Mode & Limits
  59. ✓CrewAI Alternatives: 7 Options and How to Migrate (2026)
  60. ✓Migrate from AutoGen: Agent Framework, AG2 and More
  61. ✓What Is an LLM Guardrail? Types, Examples and Limits
  62. ✓Best LLM Guardrails Tools (2026): 9 Platforms Compared
  63. ✓AI Agent Guardrails in Python: Block Injection, Redact PII
  64. ✓NeMo Guardrails vs Guardrails AI: Which to Choose (2026)
  65. ✓AI-Based PII Detection and Redaction Tools for LLM Apps
  66. ✓Stop Secrets Leaking Into LLM Logs and Traces
  67. ✓AI Agent Code Execution Sandbox: Run LLM Code Safely
  68. ✓AI Agent Network Egress: Limit Where Agents Can Connect
  69. ✓AutoGen Docker Task Isolation: Secure the Code Executor
  70. ✓SPIFFE for AI Agents: Workload Identity Without API Keys
  71. ✓On-Behalf-Of Auth for AI Agents: Act as Each User
  72. ✓AI Agent Production Checklist: What to Check Before Launch
  73. ✓Approval Fatigue: Auto-Approve Safe AI Agent Actions
  74. ✓What Is Human in the Loop AI? Approvals for AI Agents
  75. ✓AI Agent Notifications: Webhook and Slack Alerts in Python
  76. ✓AI Agent Observability: Trace Tool Calls, Tokens and Cost
  77. ✓Best AI Agent Observability Tools (2026), Compared
  78. ✓AI Agent Stuck in a Loop? How to Detect and Stop It
  79. ✓How to Run, Debug and Deploy an AI Agent in Python
  80. ✓AI Agent Cost Tracking: Tokens and Cost per Run and User
  81. ✓How to Evaluate AI Agents: Evals, LLM Judges and pass^k
  82. ✓AI Agent Cost Control: Budgets That Stop Runaway Spend
  83. ✓How to Test LLM Prompts and AI Agents in Python
  84. ✓AI Agent Evals in CI: Run Them on Every Pull Request
  85. ✓What Is an Agentic Runtime? AI Agent Runtimes Explained
  86. ✓Autonomous AI Agent Runtime: Budgets, Crash Recovery, API
  87. ✓Event-Driven AI Agents: Webhook, Cron and File Triggers
  88. ✓AI Agent Cron Jobs: Run an Agent on a Schedule
  89. ✓AI Agent Webhook Trigger: Run an Agent on HTTP Events
  90. ✓AI Agent File Watcher: Process New Files Automatically
  91. ✓Custom AI Agent Triggers: Wake an Agent From Any Source
  92. ✓AI Agent Event Filters: Skip Runs Before the LLM
  93. ✓AI Agent Retries and a Dead Letter Queue for Failed Runs
  94. 94Run Multiple AI Agents: One Runtime, Many Processes
  95. 95AI Agent Manifest: Declare a Long-Running Agent in YAML
  96. 96AI Agent CLI: Start, Stop and Inspect Running Agents
  97. 97AI Agent Monitoring Dashboard in the Terminal
  98. 98Multi-Agent Event Bus: Chain Agents With Events
  99. 99Distributed AI Agents: Run Agents Across Many Machines
  100. 100Pause and Resume an AI Agent: Lifecycle States Explained

Lessons in this path

  1. ✓What Is an AI Agent? Definition, How It Works, Examples
  2. ✓How to Build an AI Agent in Python (2026 Guide)
  3. ✓Build a Personal AI Agent: Memory, Reminders, Chat
  4. ✓What Is an Agent Harness? Parts and How to Build One
  5. ✓System Prompt Best Practices for AI Agents in Python
  6. ✓Best LLM for AI Agents (2026): Picks, Prices, How to Test
  7. ✓AI Agent YAML: Define and Run an Agent From a Config File
  8. ✓Streaming LLM Responses with FastAPI: Tokens and Tool Calls
  9. ✓Best Local LLM for AI Agents: Ollama Models by GPU (2026)
  10. ✓Claude AI Agent with MCP: Use Anthropic Models in Promptise
  11. ✓Gemini AI Agent with MCP: Use Google Models in Promptise
  12. ✓Azure OpenAI Agent with MCP: Use Deployments in Promptise
  13. ✓OpenRouter AI Agent with MCP: Many Models in Promptise
  14. ✓Ollama AI Agent with MCP: Run Local Models in Promptise
  15. ✓LLM Semantic Cache and Model Fallback in Python
  16. ✓What Is MCP (Model Context Protocol)? A Developer's Guide
  17. ✓What Is Tool Calling? LLM Function Calling Explained
  18. ✓MCP Tools vs Resources vs Prompts (With Python Examples)
  19. ✓How to Connect MCP Servers to Your AI Agent in Python
  20. ✓Build a Production MCP Server in Python (Step by Step)
  21. ✓MCP Transports: stdio vs Streamable HTTP vs SSE (Python)
  22. ✓MCP 2026-07-28 Migration: Make Your MCP Server Stateless
  23. ✓OpenAPI to MCP: Turn Any REST API into an MCP Server
  24. ✓MCP Authentication in Python: API Keys, JWT and OAuth
  25. ✓Build an Authenticated MCP Server for Your AI Agent (Python)
  26. ✓MCP Security Best Practices: A Checklist for MCP Servers
  27. ✓Testing MCP Servers in Python: pytest Without a Live Server
  28. ✓Too Many MCP Tools? How to Fix LLM Tool Selection in Python
  29. ✓Idempotent Tool Calls: Make AI Agent Retries Safe
  30. ✓AI Agent Tool Failures: Stop Unsafe Workarounds
  31. ✓MCP Server Caching, Timeouts and Circuit Breakers in Python
  32. ✓MCP Middleware for Servers: Auth, Logging, Rate Limits
  33. ✓MCP vs CLI for AI Agents: Tokens, Security, When to Use Each
  34. ✓LangChain vs MCP: Differences and How They Work Together
  35. ✓FastMCP Alternatives for Production MCP Servers (2026)
  36. ✓AI Agent Audit Logging: Tamper-Evident Logs in Python
  37. ✓AI Agent Human in the Loop: Approve Tool Calls in Python
  38. ✓AI Agent Prompt Injection: How to Defend Against It
  39. ✓Hidden Text Prompt Injection: Sanitize Pages for AI Agents
  40. ✓Build a Multi-Agent System in Python (and When Not To)
  41. ✓Context Engineering for AI Agents: Context Window Management
  42. ✓Context Compaction for AI Agents: Trim vs Summarize
  43. ✓How to Deploy an AI Agent with Docker (2026 Guide)
  44. ✓LLM Tool Rate Limiting: Per-Client Limits for MCP Servers
  45. ✓MCP Long-Running Tasks: Background Jobs in Python
  46. ✓MCP Server Monitoring: Prometheus, OpenTelemetry and Logs
  47. ✓Best AI Agent Frameworks (2026): Python Options Compared
  48. ✓Self-Improving AI Agent: Learn From Tool Failures in Python
  49. ✓AI Agent Identity: Authenticate Agents to MCP Servers
  50. ✓Code-Action Agents in Python: One Program vs 37 Tool Calls
  51. ✓Multi-Tenant AI Agents: Keep Each Customer's Data Apart
  52. ✓What Is Agentic RAG? How It Differs from Classic RAG
  53. ✓AI Agent Memory in Python: Short-Term and Long-Term
  54. ✓Per-User Agent Memory Isolation: Stop Leaks Between Users
  55. ✓Agentic RAG in Python: Give Your AI Agent a Search Tool
  56. ✓AI Agent Reasoning Patterns in Python: From ReAct to Debate
  57. ✓Plan-and-Execute Agents in Python: Beyond the ReAct Loop
  58. ✓Self-Modifying AI Agent in Python: Open Mode & Limits
  59. ✓CrewAI Alternatives: 7 Options and How to Migrate (2026)
  60. ✓Migrate from AutoGen: Agent Framework, AG2 and More
  61. ✓What Is an LLM Guardrail? Types, Examples and Limits
  62. ✓Best LLM Guardrails Tools (2026): 9 Platforms Compared
  63. ✓AI Agent Guardrails in Python: Block Injection, Redact PII
  64. ✓NeMo Guardrails vs Guardrails AI: Which to Choose (2026)
  65. ✓AI-Based PII Detection and Redaction Tools for LLM Apps
  66. ✓Stop Secrets Leaking Into LLM Logs and Traces
  67. ✓AI Agent Code Execution Sandbox: Run LLM Code Safely
  68. ✓AI Agent Network Egress: Limit Where Agents Can Connect
  69. ✓AutoGen Docker Task Isolation: Secure the Code Executor
  70. ✓SPIFFE for AI Agents: Workload Identity Without API Keys
  71. ✓On-Behalf-Of Auth for AI Agents: Act as Each User
  72. ✓AI Agent Production Checklist: What to Check Before Launch
  73. ✓Approval Fatigue: Auto-Approve Safe AI Agent Actions
  74. ✓What Is Human in the Loop AI? Approvals for AI Agents
  75. ✓AI Agent Notifications: Webhook and Slack Alerts in Python
  76. ✓AI Agent Observability: Trace Tool Calls, Tokens and Cost
  77. ✓Best AI Agent Observability Tools (2026), Compared
  78. ✓AI Agent Stuck in a Loop? How to Detect and Stop It
  79. ✓How to Run, Debug and Deploy an AI Agent in Python
  80. ✓AI Agent Cost Tracking: Tokens and Cost per Run and User
  81. ✓How to Evaluate AI Agents: Evals, LLM Judges and pass^k
  82. ✓AI Agent Cost Control: Budgets That Stop Runaway Spend
  83. ✓How to Test LLM Prompts and AI Agents in Python
  84. ✓AI Agent Evals in CI: Run Them on Every Pull Request
  85. ✓What Is an Agentic Runtime? AI Agent Runtimes Explained
  86. ✓Autonomous AI Agent Runtime: Budgets, Crash Recovery, API
  87. ✓Event-Driven AI Agents: Webhook, Cron and File Triggers
  88. ✓AI Agent Cron Jobs: Run an Agent on a Schedule
  89. ✓AI Agent Webhook Trigger: Run an Agent on HTTP Events
  90. ✓AI Agent File Watcher: Process New Files Automatically
  91. ✓Custom AI Agent Triggers: Wake an Agent From Any Source
  92. ✓AI Agent Event Filters: Skip Runs Before the LLM
  93. ✓AI Agent Retries and a Dead Letter Queue for Failed Runs
  94. 94Run Multiple AI Agents: One Runtime, Many Processes
  95. 95AI Agent Manifest: Declare a Long-Running Agent in YAML
  96. 96AI Agent CLI: Start, Stop and Inspect Running Agents
  97. 97AI Agent Monitoring Dashboard in the Terminal
  98. 98Multi-Agent Event Bus: Chain Agents With Events
  99. 99Distributed AI Agents: Run Agents Across Many Machines
  100. 100Pause and Resume an AI Agent: Lifecycle States Explained
← Path overview

Most teams that run one autonomous agent soon run several: a triage agent on a webhook, a digest agent on a morning schedule, a reporter every hour. Running each as its own script means separate startup code, separate logs and separate shutdown handling. This guide shows how to run multiple AI agents together in one Promptise Foundry AgentRuntime: add and remove processes, load them from manifests, share one event notifier, keep a failure in one agent from touching the others, and shut everything down cleanly on SIGTERM.

[01]

How do you run multiple AI agents together?

Register each agent as a named process in one runtime, start them all, and let the runtime stop them all on exit. Each process keeps its own triggers, queue, workers, model client, tools and failure counters, so one agent failing doesn't stop the rest. The runtime adds shared pieces: one place to look up status, one notifier for events, and one shutdown path. In Promptise:

Python
1
2
3
4
5
6
7
async with AgentRuntime(event_notifier=notifier) as runtime:
    await runtime.load_directory("agents")           # one .agent file per agent
    await runtime.add_process("reporter", ProcessConfig(...))
    await runtime.start_all()                        # a failed start is logged, not raised
    print(runtime.status())
    await stop_signal.wait()
# leaving the block calls stop_all()

Key takeaways:

  • Processes are isolated in state, not in resources. Each has its own counters and lifecycle, but all share one Python program and one event loop.

  • start_all() never raises for a single process. Check status() afterwards.

  • restart_process() restarts one process in any state. A FAILED process is torn down first, so its old trigger doesn't keep firing.

  • run_forever() handles SIGTERM. It serves until SIGTERM or Ctrl+C, gives runs in flight up to 5 seconds to finish, then stops every process.

  • AgentRuntime(config) registers every process in a RuntimeConfig. AgentRuntime.from_config(config) does the same.


[02]

How a multi-agent runtime works

An agent runtime does for AI agents what a process supervisor does for programs. It keeps a registry of named workers, starts and stops them, reports their state, and contains failures. The difference is that an agent "process" here is not an operating system process. It is a set of asyncio tasks inside one Python program: trigger listeners, a queue, workers that call the model, and a heartbeat.

Diagram of an AgentRuntime: one Python program with a shared event_notifier and an optional event_bus and broker, running three processes, triage, digest and reporter. Each process has its own triggers, queue, workers, agent and MCP clients, lifecycle, failure counters, restart policy and journal.
FigureOne AgentRuntime runs several agent processes inside one Python program

What each process owns:

  • Its configuration and agent. Model, instructions, tools, triggers, budget and health settings come from its own ProcessConfig. Two processes can use different models and different MCP servers.

  • Its queue and workers. Events for one agent never wait behind another agent's events.

  • Its lifecycle and failure handling. max_consecutive_failures, the restart policy and the state machine apply per process. One agent in FAILED is just one entry in the status table.

What they share:

  • The event notifier, if you pass one to the runtime. Every process emits into it, and the runtime drains it once all processes have stopped.

  • The event bus and message broker, if you pass them. These let one agent's output trigger another agent. Event-based chaining gets its own guide; here it is enough to know the runtime hands the same objects to every process.

  • The Python program itself: CPU, memory, the event loop, and the program's lifetime.


[03]

When to run several agents in one runtime (and when not to)

One runtime suits you when:

  • The agents belong to one product or team and are deployed together.

  • You want one status view, one alert channel and one shutdown path.

  • Most of the work is waiting on model and tool calls, which asyncio handles well.

Split them into separate programs or containers when:

  • One agent needs a different Python environment, secrets boundary or network access.

  • One agent does heavy CPU work in-process, which would slow every other agent.

  • Agents need to be deployed, scaled or rolled back independently.

  • A crash of one must not take down the others. Isolation inside a runtime covers failed runs, not a crashed program.


[04]

What you need

  • Python 3.10 or later and Promptise Foundry 1.7.0 or later.

  • No API key. The examples use the fake OpenAI-compatible model server from the auto-restart guide, flaky_llm.py, which can make one model fail while others work.

  • About 20 minutes.

>_Terminal
pip install "promptise>=1.7.0"

This guide builds on deploy AI agents in production, which walks through a single long-running agent.


[05]

Step 1: Declare agents in manifests

Agents that change rarely are easiest to keep in .agent files, one per agent, in version control. A manifest has the same fields as ProcessConfig, plus a config: block for any field without its own section:

YAMLagents/triage.agent
1
2
3
4
5
6
7
8
version: "1.0"
name: triage
model: openai:gpt-5-mini
instructions: |
  Triage new support tickets.
triggers:
  - type: cron
    cron_expression: "* * * * * */2"   # every 2 seconds (demo only)
YAMLagents/digest.agent
1
2
3
4
5
6
7
8
9
10
11
version: "1.0"
name: digest
model: openai:gpt-5-mini
instructions: |
  Write a short digest of yesterday's tickets.
triggers:
  - type: cron
    cron_expression: "* * * * * */3"   # every 3 seconds (demo only)
config:
  restart_policy: on_failure
  max_restarts: 5

The six-field cron expressions fire every few seconds so the demo finishes quickly. Real agents use five fields, such as 0 7 * * *. AI agent YAML config files covers the format; promptise runtime validate agents/triage.agent checks a file before you deploy it. A manifest without a journal: section keeps a checkpoint journal in .promptise/journal, unlike a ProcessConfig built in code. Its counters and conversation then carry over when the program starts again; journal: {level: none} turns it off.


[06]

Step 2: Load, add and start processes

The demo loads both manifests, adds two more processes in code, and starts everything. reporter uses a model that the fake server reports as down. archiver points at an MCP server command that doesn't exist, so it can't even start.

Pythonruntime_demo.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
"""Run several agent processes in one AgentRuntime; one fails, the others keep working."""
import asyncio
import os
import time

os.environ["OPENAI_BASE_URL"] = "http://127.0.0.1:8765/v1"  # fake model server
os.environ.setdefault("OPENAI_API_KEY", "sk-fake")

from flaky_llm import FlakyLLM
from promptise.events import CallbackSink, EventNotifier
from promptise.runtime import AgentRuntime, ProcessConfig, RuntimeBaseError, TriggerConfig

T0 = time.monotonic()


def log(message: str) -> None:
    print(f"{time.monotonic() - T0:5.1f}s  {message}")


async def on_event(event) -> None:
    log(f"event {event.event_type:17} from {event.agent_id}")


def table(runtime: AgentRuntime) -> None:
    for name, s in runtime.status()["processes"].items():
        print(f"         {name:9} {s['state']:8} invocations={s['invocation_count']} "
              f"failures={s['consecutive_failures']} restarts={s['restart_count']}")


async def main() -> None:
    llm = FlakyLLM()
    llm.down_models = {"gpt-5-nano"}  # this model's provider is down
    await llm.start()

    notifier = EventNotifier(sinks=[CallbackSink(on_event, events=[
        "process.started", "process.failed", "process.stopped",
    ])])
    async with AgentRuntime(event_notifier=notifier) as runtime:
        names = await runtime.load_directory("agents")
        log(f"loaded from manifests: {names}")
        await runtime.add_process("reporter", ProcessConfig(
            model="openai:gpt-5-nano",
            instructions="Send the hourly report.",
            triggers=[TriggerConfig(type="cron", cron_expression="* * * * * *")],
            max_consecutive_failures=2,
        ))
        await runtime.add_process("archiver", ProcessConfig(
            model="openai:gpt-5-mini",
            servers={"files": {"command": "no-such-mcp-server"}},  # cannot start
        ))
        try:
            await runtime.add_process("triage", ProcessConfig())
        except RuntimeBaseError as exc:
            log(f"duplicate name: {exc}")

        await runtime.start_all()  # logs the archiver's failure, starts the rest
        await asyncio.sleep(4.5)
        log("status after 4.5 s:")
        table(runtime)

        llm.down_models.clear()  # the provider is back
        await runtime.restart_process("reporter")  # FAILED: torn down, then started
        await runtime.restart_process("digest")    # RUNNING: stopped, then started
        await runtime.remove_process("archiver")   # FAILED: stopped, then removed
        await asyncio.sleep(2.2)
        log("status after restarting reporter and digest, removing archiver:")
        table(runtime)
        log("leaving the async with block")
    log("stop_all() done")
    await llm.stop()


asyncio.run(main())

The calls that build the runtime:

  • load_directory("agents") loads every *.agent file in sorted order and returns the names. load_manifest(path, name_override=...) loads one file. Both register processes; neither starts them.

  • add_process(name, config) registers a process from code and returns the AgentProcess. Names must be unique: a second triage raises RuntimeBaseError.

  • start_all() starts every process in CREATED, STOPPED or FAILED. If one fails to start, the error is logged and the others start anyway.

  • async with AgentRuntime(...) calls stop_all() when the block ends, also when it ends with an exception.


[07]

Step 3: See one failure stay contained

The first part of the output:

Text
1
2
3
4
5
6
7
8
9
10
11
12
  0.0s  loaded from manifests: ['digest', 'triage']
  0.0s  duplicate name: Process 'triage' already exists. Use remove_process() first or choose a different name.
  0.3s  event process.started   from digest
  0.3s  event process.started   from triage
  0.3s  event process.started   from reporter
  0.3s  event process.failed    from archiver
  1.6s  event process.failed    from reporter
  4.8s  status after 4.5 s:
         digest    running  invocations=2 failures=0 restarts=0
         triage    running  invocations=2 failures=0 restarts=0
         reporter  failed   invocations=0 failures=2 restarts=0
         archiver  failed   invocations=0 failures=0 restarts=0

The archiver failed at startup. start_all() logged AgentRuntime: failed to start archiver: Failed to connect to server 'files' ... on stderr and went on. The reporter started, failed two runs in a row, and entered FAILED. Meanwhile triage and digest kept running on their schedules, unaffected. The shared notifier delivered events from all four, each tagged with its process name in agent_id.

That is the isolation a runtime gives you: failed runs, failed starts, restart loops and budgets stay within one process. It doesn't isolate resources. All four processes share one event loop, so code that blocks it, such as a synchronous HTTP call in a lifecycle listener or a CallbackSink, stalls every agent at once. Keep your callbacks async and short.


[08]

Step 4: Restart, replace and remove processes

The second part of the output, after the model provider comes back:

Text
1
2
3
4
5
6
7
8
  4.9s  event process.started   from reporter
  4.9s  event process.stopped   from digest
  4.9s  event process.started   from digest
  4.9s  event process.stopped   from archiver
  7.1s  status after restarting reporter and digest, removing archiver:
         digest    running  invocations=2 failures=0 restarts=0
         triage    running  invocations=3 failures=0 restarts=0
         reporter  running  invocations=2 failures=0 restarts=0

Three different operations happened here:

  • restart_process("reporter") brought the failed process back. On a FAILED process it first tears down the trigger and tasks the failure left behind, then builds the process again, so you see only process.started. start_all() does the same for every FAILED process.

  • restart_process("digest") on a running process stops it and starts it again. You see process.stopped and process.started. Its counters, such as invocation_count, carry over.

  • remove_process("archiver") stopped the failed process, which emitted process.stopped, and dropped it from the registry. To replace a process with a new config, remove it and add it again.

For automatic restarts after failures, use the per-process restart policy instead of doing it by hand. AI agent auto-restart covers it.

Read the runtime's status

runtime.status() returns {"process_count": n, "processes": {name: status}}, where each status is the same dict as process.status(). runtime.list_processes() is the short form, with name, state and process ID. runtime.get_process(name) returns the AgentProcess itself, for example to read its dead_letters or add a lifecycle listener. AI agent lifecycle states explains every field and state.


[09]

Step 5: Describe the whole runtime in RuntimeConfig

RuntimeConfig holds every process config in one object that serializes to JSON. Build a runtime from it with from_config():

Pythonconfig_demo.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
"""RuntimeConfig, from_config() and the two presets."""
import asyncio
import json

from promptise.runtime import (
    DEFAULT_DEVELOPMENT_CONFIG,
    DEFAULT_PRODUCTION_CONFIG,
    AgentRuntime,
    ProcessConfig,
    RuntimeConfig,
    TriggerConfig,
)

config = RuntimeConfig(processes={
    "triage": ProcessConfig(
        instructions="Triage new support tickets.",
        triggers=[TriggerConfig(type="cron", cron_expression="*/5 * * * *")],
    ),
    "digest": ProcessConfig(
        instructions="Write the daily digest.",
        triggers=[TriggerConfig(type="cron", cron_expression="0 7 * * *")],
        restart_policy="on_failure",
    ),
})


async def main() -> None:
    runtime = AgentRuntime(config)                     # registers every process
    print("AgentRuntime(config):", [p["name"] + "/" + p["state"] for p in runtime.list_processes()])

    saved = json.dumps(config.to_dict())               # e.g. store it in a file or database
    again = RuntimeConfig.from_dict(json.loads(saved))
    print("round trip:", list(again.processes), again.processes["digest"].restart_policy)

    for name, preset in [("development", DEFAULT_DEVELOPMENT_CONFIG),
                         ("production", DEFAULT_PRODUCTION_CONFIG)]:
        print(f"{name} preset: processes={preset.processes} "
              f"distributed.enabled={preset.distributed.enabled}")


asyncio.run(main())
Output
AgentRuntime(config): ['triage/created', 'digest/created']
round trip: ['triage', 'digest'] on_failure
development preset: processes={} distributed.enabled=False
production preset: processes={} distributed.enabled=False

Two results deserve attention:

  • AgentRuntime(config) registers every process in CREATED; nothing starts until start_all() or run_forever(). AgentRuntime.from_config(config) does the same and takes the same event_bus, broker and event_notifier arguments.

  • The presets have no processes. DEFAULT_DEVELOPMENT_CONFIG and DEFAULT_PRODUCTION_CONFIG are identical: both leave distributed.enabled off, because turning it on starts a network transport. Build your own RuntimeConfig instead, and treat the presets as empty starting points. They are shared module-level objects, so copy one with model_copy(deep=True) before you change it.

to_dict() writes webhook hmac_secret values as **********. A config loaded back with from_dict() then fails validation until you supply the real secret, so keep secrets in environment variables and fill them in at load time.


[10]

Step 6: Shut down cleanly on SIGTERM

Docker, Kubernetes and systemd stop a program by sending SIGTERM, then SIGKILL after a grace period. Python's default for SIGTERM is to exit at once, without running finally blocks or async with exits. So the runtime's cleanup never runs unless something turns SIGTERM into a normal shutdown. run_forever() does that: it starts every process, serves until SIGTERM or Ctrl+C, and then stops them gracefully. serve.py is the whole entry point:

Pythonserve.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
"""Run every agent in ./agents until SIGTERM or Ctrl+C, then stop them all cleanly."""
import asyncio
import logging
import time

from promptise.events import CallbackSink, EventNotifier
from promptise.runtime import AgentRuntime

T0 = time.monotonic()


def log(message: str) -> None:
    print(f"{time.monotonic() - T0:5.1f}s  {message}", flush=True)


async def on_event(event) -> None:
    log(f"event {event.event_type} from {event.agent_id}")


async def main() -> None:
    notifier = EventNotifier(sinks=[CallbackSink(on_event, events=[
        "process.started", "process.stopped",
    ])])
    runtime = AgentRuntime(event_notifier=notifier)
    await runtime.load_directory("agents")
    await runtime.run_forever()  # starts all; on SIGTERM or Ctrl+C, runs in flight get 5 s to finish
    done = {n: s["invocation_count"] for n, s in runtime.status()["processes"].items()}
    log(f"all processes stopped; completed runs: {done}")


logging.basicConfig(level=logging.WARNING)
asyncio.run(main())

sigterm_check.py starts serve.py against a model that takes 2 seconds per answer, waits five seconds, and sends SIGTERM while a run is in flight:

Output
  0.3s  event process.started from digest
  0.3s  event process.started from triage
WARNING:promptise.runtime.process:AgentProcess triage: event bdb412f9-3827-4e3d-820c-57e9b8992ceb (cron) dead-lettered: process stopped
  4.4s  event process.stopped from digest
  4.5s  event process.stopped from triage
  4.5s  all processes stopped; completed runs: {'digest': 1, 'triage': 2}
exit code: 0

After the signal, no new run started. Each process stopped once its run in flight had finished, triage a little after digest, and the event still waiting in triage's queue was dead-lettered, as the warning says. Both process.stopped events were delivered before the program exited with code 0.

Runs in flight get up to drain_timeout seconds to finish: 5 by default, set per process with ProcessConfig(drain_timeout=...) or for all of them with run_forever(drain_timeout=...). A run still going after that is cancelled and, with a journal, recorded as run_interrupted. A second SIGTERM or Ctrl+C cancels at once. A plain stop_all() or stop_process() cancels runs at once unless you pass drain_timeout=, and so does the end of an async with AgentRuntime() block. If losing in-flight work matters, keep a journal and recover from it, as durable AI agents shows, and make tool calls idempotent so a repeated run is safe.

promptise runtime start runs a directory of manifests the same way: it handles SIGTERM like Ctrl+C and drains runs in flight. Use your own entry point like serve.py when you add processes or sinks in code. The AI agent runtime CLI covers the command.


[11]

The complete example

Text
1
2
3
4
5
6
7
8
9
multi-agent-runtime/
├── agents/
│   ├── triage.agent       # manifest, cron every 2 s (step 1)
│   └── digest.agent       # manifest with config overrides (step 1)
├── flaky_llm.py           # fake OpenAI-compatible model; down_models fails one model
├── runtime_demo.py        # load, add, fail, restart, remove (steps 2-4)
├── config_demo.py         # RuntimeConfig, from_config, presets (step 5)
├── serve.py               # production entry point with SIGTERM handling (step 6)
└── sigterm_check.py       # starts serve.py and sends SIGTERM
>_Terminal
pip install "promptise>=1.7.0"
python runtime_demo.py
python config_demo.py
python sigterm_check.py

serve.py is the file to adapt. Point it at your agents directory, add your sinks, and run it as the container's command. To run against a real model, remove the fake server from the demos and set OPENAI_API_KEY.


[12]

Running it in production

Know the limits per process

A runtime has no global limits. Each process carries its own:

Limit

Default

What it bounds

concurrency

1 (1 to 100)

Runs in parallel for this process. The total load on your model provider is the sum over all processes.

Trigger queue

1,000 events, fixed

Events waiting per process. When full, webhooks answer 503.

max_invocation_time

0 (none)

Seconds per run.

budget

off

Tool calls, model turns and cost per run and per day. See AI agent cost control.

trigger_delivery.dead_letter_size

100

Undeliverable events kept for inspection.

context.conversation_max_messages

100

Short-term memory kept between runs.

max_lifetime

0 (unlimited)

Seconds before the process is stopped or recycled.

There are no CPU, memory or open-file limits per process, because processes are not operating system processes. If you need hard limits, put agents in separate containers. Each webhook trigger opens its own HTTP server, so every webhook in the runtime needs its own port.

Share one notifier, and alert on the right events

Pass one EventNotifier to the runtime and add sinks for what each audience needs: a LogSink for everything, a WebhookSink for process.failed or your own "gave up" event to the on-call channel. Every event carries the process name in agent_id and metadata["process_name"], so one channel can serve all agents. AI agent notifications covers sinks and signing.

Control it from outside

Wrap the runtime in the control API to list, start, stop, suspend and deploy processes over HTTP while it runs. AI agent control API covers it, including authentication. The API's restart route uses restart_process(), so it brings back FAILED processes too.

Deploy it as one container

Run serve.py as the container command, mount the journal directory on a volume, and give the container a restart policy for program crashes. Set the stop grace period above the drain timeout (5 seconds by default) plus a few seconds for the final checkpoints. Deploy an AI agent with Docker has the Dockerfile.


[13]

Common problems and fixes

Symptom

Cause

Fix

RuntimeBaseError: Process 'x' already exists

Two manifests or calls use the same name

Rename one, or remove_process() first

A process is missing after start_all()

Its start failed; start_all() only logs

Check status() for failed and read the log line

docker stop kills the program with no process.stopped events

SIGTERM isn't handled, so Python exits at once

Serve with run_forever(), as serve.py does

Runs are cut off on docker stop

The grace period is shorter than drain_timeout

Raise the grace period, or lower drain_timeout

All agents slow down together

Blocking code in a listener, sink or in-process tool stalls the shared event loop

Make callbacks async; move heavy work to MCP servers or threads

load_directory() fails halfway

It raises on the first invalid manifest, after loading the ones before it

Validate manifests in CI with promptise runtime validate


[14]

Limitations

  • One program per runtime. All processes of a runtime share a Python program. DistributedConfig(enabled=True) connects runtimes on several machines through a coordinator, as distributed AI agents shows, but each process still runs inside one program.

  • No resource isolation. A memory leak or CPU-heavy code in one agent affects all of them.

  • A short drain on shutdown. run_forever() gives runs in flight up to drain_timeout seconds, then cancels them. Events still in a queue are dead-lettered, not run.

  • No dependencies between processes. start_all() starts processes in registration order and doesn't wait for one to be healthy before the next.

  • No built-in event bus or broker. The runtime passes through objects you provide; it doesn't create them.


[15]

Frequently asked questions

Can I run several AI agents in one Python program?

Yes. Register each one as a process in a Promptise AgentRuntime, with its own model, tools and triggers, and call start_all(). They run concurrently on one asyncio event loop. Each has its own queue, workers and failure handling, so one failing agent doesn't stop the others.

What happens to the other agents when one agent fails?

Nothing. A failed run, a failed start or a process that ends up FAILED affects only that process. The other agents keep running their triggers. What isn't isolated is the program itself: if it crashes, runs out of memory or blocks its event loop, every agent is affected.

How do I restart one agent without restarting the others?

Call runtime.restart_process(name). It stops and starts only that process, in any state: a FAILED process is torn down first, so its old trigger doesn't run next to the new one.

How do I shut down multiple AI agents gracefully?

Serve them with await runtime.run_forever(). On SIGTERM or Ctrl+C it starts no new runs, gives runs in flight up to drain_timeout seconds (5 by default) to finish, then stops every process and delivers pending notifications. A run still going after that is cancelled; keep a journal if you must recover it.

Should each AI agent run in its own container?

Not necessarily. Agents that are deployed together and mostly wait on model calls run well in one runtime and one container. Use separate containers when agents need different dependencies, secrets or network access, when one is CPU-heavy, or when they must be deployed and scaled independently.

What is the difference between AgentRuntime and AgentProcess?

An AgentProcess is one long-running agent with its own triggers, queue, lifecycle and restart policy. An AgentRuntime manages many of them: it registers, starts, stops and reports on processes by name, and shares an event notifier, event bus and broker between them.


[16]

Next steps

  • Your first long-running agent, end to end: deploy AI agents in production.

  • Restart policies for each process: AI agent auto-restart.

  • Manage the runtime over HTTP: AI agent control API.

  • Governance for every process: the autonomous AI agent runtime.

  • Agents that work together inside one run, rather than side by side: multi-agent systems.

  • Reference: runtime manager, configuration and manifests in the Promptise docs.

← PreviousAI Agent Retries and a Dead Letter Queue for Failed RunsNext lesson →AI Agent Manifest: Declare a Long-Running Agent in YAML