The user wants an "Engineer[ing]" of a multi-tenant runtime for LLM agents.
This is a high-level system design and implementation request. It involves several complex components:
- Multi-tenancy: Isolation between different users/organizations.
- Runtime: The execution environment for the agents.
- LLM Agents: The specific workload (handling prompts, tools, context).
- Sandboxing: Security and isolation of execution (code execution, file system access).
- Cost Controls: Managing API usage costs (token counting, rate limiting).
- Capability Policies: What agents are allowed to do (use specific tools, access specific data).
- Scheduling: Prioritizing tasks, managing queues.
- Resource Quotas: CPU/RAM/GPU limits per tenant.
- Billing Integrations: Tracking usage for invoicing.
Target Audience/Complexity: This is likely for a senior software engineer or architect role. The response needs to be structured, architectural, and provide concrete implementation strategies (pseudo-code or architectural diagrams described in text).
Structure of the Response:
I should structure this like a technical design document (TDD) or a Request for Comments (RFC).
- High-Level Architecture: Define the core components.
- API Gateway (Ingress)
- Control Plane (Policy, Auth, Billing)
- Data Plane (Runtime, Scheduler, Sandbox)
- Observability (Metrics, Logs)
- Tenant Isolation & Identity:
- How to identify tenants (JWTs, API Keys).
- Logical vs. Physical isolation.
- The Runtime Environment (The Agent Worker):
- Language choice (Python is standard for LLMs, maybe Go/Rust for the sidecar/supervisor).
- Containerization (Docker/K8s) vs. MicroVMs (Firecracker/gVisor) for strong sandboxing.
- Policy Engine (Capability Control):
- OPA (Open Policy Agent) or a custom rule engine.
- Defining what tools an agent can use (e.g., "Tenant A cannot use
execute_python").
- Sandboxing Strategy:
- Network isolation.
- Filesystem isolation.
- Compute limits.
- Cost Control & Quotas:
- Token counting (Streaming vs. non-streaming).
- Rate limiting (Token bucket).
- Budgets (Hard stops).
- Scheduling:
- Queue management.
- Priority classes (Free vs. Pro).
- Billing Integration:
- Usage metrics emission (Kafka/Prometheus).
- Pricing models.
- Code/Configuration Examples:
- Policy definition (Rego/JSON).
- Resource Quota definition.
- Pseudo-code for the Supervisor.
Drafting the Content - Key Decisions:
- Runtime: Use a "Sidecar" pattern. The Agent runs in a sandboxed environment, monitored by a Supervisor.
- Sandboxing: Docker is okay for basic isolation, but for "code interpreter" style agents, we need stronger isolation. Let's suggest MicroVMs (Firecracker) or strict Seccomp/Namespaces if K8s is used. Let's stick to a K8s-native approach with strict contexts for simplicity in explanation, but mention Firecracker for high security.
- Cost Control: Needs to be accurate. Streaming makes this hard. We need a "Token Counter" middleware.
- Policies: OPA is the industry standard. I'll use that concept.
Refining the Steps:
- Step 1: Architecture Diagram (Mental Model). Control Plane vs Data Plane.
- Step 2: The Sandbox. Focus on execution isolation.
- Step 3: Policy Engine. OPA integration.
- Step 4: Cost & Quotas. The ledger system.
- Step 5: Scheduling. Fairness.
Self-Correction/Refinement during thought process:
- Initial thought: Just use Docker.
- Correction: For LLM agents that might generate code to run locally (like ChatGPT Code Interpreter), Docker is breakable if not configured perfectly. MicroVMs are safer. I will propose a tiered approach: Basic (Container) vs. Secure (MicroVM).
- Billing: Don't just store it in a DB. Emit events.
Code Examples: I will write Python classes to represent the Runtime Manager and a Policy checker, as Python is the lingua franca of LLM ops.
Prompt Specifics: "Engineer a..." implies building it. I should act as the Lead Architect.
Detailed Plan:
- System Architecture Overview: Define the planes (Control, Data, Observability).
- Tenant Context Propagation: How
tenant_id flows through the system.
- The Sandbox (Security): gVisor/Firecracker vs Containers.
- Capability Policies: Using OPA (Open Policy Agent).
- Resource Quotas & Scheduling: K8s constructs or custom logic.
- Cost Control: Real-time token counting and budget enforcement.
- Billing: Asynchronous event emission.
- Implementation Prototype (Python): A skeletal structure of the core logic.
Let's write the response.
This is a comprehensive architectural design and implementation strategy for a Multi-Tenant LLM Agent Runtime. This system, which we will call "Nexus," is designed to securely execute autonomous agents while strictly enforcing resource limits, security policies, and cost tracking.
1. High-Level Architecture
The system follows a Control Plane / Data Plane separation.
- Control Plane: Manages tenant definitions, policy compilation, billing aggregation, and scheduling logic.
- Data Plane: A fleet of "Worker Nodes" responsible for the actual execution of agents within isolated environments.
Core Components
- Ingress/Gateway: AuthN/AuthZ, rate limiting, initial request validation.
- Scheduler: Prioritized queue management (fairness scheduling).
- Policy Engine (OPA): Intercepts tool calls to enforce capabilities.
- Sandbox Runtime: The physical execution environment (e.g., Firecracker microVM or gVisor container).
- Metering Service: Real-time token and latency tracking.
2. The Sandbox Model (Isolation)
To support multi-tenancy, we cannot simply run Python scripts in a shared environment. We need strong isolation.
Recommendation: Firecracker microVMs.
- Why: Provides VM-level isolation with container-like startup times.
- Architecture: Each Agent "Session" or "Task" gets a fresh microVM.
- Network: Each VM gets a dedicated tap device. Egress traffic is strictly routed through a proxy that enforces network policies (e.g., "Tenant A can only access
api.customer-db.com").
The Worker Agent Structure
Inside the Sandbox, a generic "Agent Loop" runs. It does not contain sensitive keys. It receives encrypted context and tools from the host.
[ Tenant Request ]
⬇
[ Nexus Scheduler ] → Spawns → [ Firecracker MicroVM ]
| └── Agent Loop (Python/JS)
| └── Sidecar (Enforces Quotas/Policy)
3. Capability Policies (The Guardrails)
We use Open Policy Agent (OPA) or a custom Middleware layer to control what agents are allowed to do. Policies are defined per tenant.
Policy Schema Example (Rego/JSON):
{
"tenant_id": "acme-corp",
"policy_version": "v1",
"capabilities": {
"allowed_llms": ["gpt-4o", "claude-3-opus"],
"allowed_tools": {
"web_search": true,
"sql_database": {
"allowed": true,
"read_only": true,
"tables": ["public_users", "public_logs"]
},
"execute_code": false
},
"network_egress": {
"allow_list": ["*.wikipedia.org"],
"block_all": false
}
}
}
Implementation: The Tool Gateway
The Agent Runtime does not hold database passwords or API keys. When an agent wants to use a tool (e.g., "Search Database"):
- Agent emits a
ToolRequest.
- The Sidecar inside the VM intercepts this.
- It sends the request to the Policy Engine on the host.
- If allowed, the Host executes the action using vault-stored secrets and returns the result.
- If denied, a
PolicyViolationError is returned, and the agent must pivot its strategy.
4. Resource Quotas & Scheduling
We must prevent "noisy neighbor" problems where one tenant's heavy agents starve others.
Scheduling Strategy: Hierarchical Token Buckets
We implement a Fairness Scheduler.
- Global Bucket: Total cluster capacity.
- Tenant Bucket: Each tenant has a max concurrency limit (e.g., Tenant A can run 5 agents simultaneously).
- Priority Queues: Within a tenant, tasks can be prioritized (e.g.,
interactive > background).
Resource Enforcement (The "Kill Switch")
We track two types of quotas:
- Compute: CPU cycles / Execution Time.
- LLM Cost: Token count (Input + Output).
Runtime Logic:
The Sidecar monitors the stream. If a tenant hits their max_tokens_per_day or max_dollar_limit, the Sidecar injects a "Stop Sequence" into the LLM stream or kills the process, returning a BudgetExhausted error.
5. Billing & Metering Integration
Billing must be granular. We emit events to a ledger (e.g., Stripe, AWS Timestream, or internal DB).
Metering Event Structure:
{
"event_id": "evt_123",
"timestamp": "2023-10-27T10:00:00Z",
"tenant_id": "acme-corp",
"metric_type": "llm_usage",
"quantity": {
"input_tokens": 1500,
"output_tokens": 300,
"model_id": "gpt-4o"
},
"cost_usd": 0.045,
"metadata": {
"agent_session_id": "sess_999"
}
}
6. Engineering Implementation (Python Prototype)
Below is a simplified Pythonic representation of the Runtime Supervisor. This class would run inside the secure environment, managing the agent loop, enforcing policy, and tracking costs.
import time
import threading
from dataclasses import dataclass
from typing import Optional, Dict, Any
from enum import Enum
# --- Domain Models ---
class PolicyViolation(Exception):
pass
class BudgetExhausted(Exception):
pass
@dataclass
class TenantContext:
tenant_id: str
max_budget_usd: float
allowed_models: list
allowed_tools: list
@dataclass
class UsageMetrics:
input_tokens: int = 0
output_tokens: int = 0
execution_time_ms: int = 0
cost_usd: float = 0.0
# --- Core Runtime Supervisor ---
class AgentRuntimeSupervisor:
def __init__(self, tenant: TenantContext, llm_client, billing_client):
self.tenant = tenant
self.llm = llm_client
self.billing = billing_client
self.usage = UsageMetrics()
self._lock = threading.Lock() # Thread-safe usage tracking
def execute_agent(self, agent_logic: callable, initial_prompt: str):
"""
The main entry point to run an agent with controls.
"""
start_time = time.time()
try:
# Run the agent logic in a controlled loop
result = agent_logic(
prompt=initial_prompt,
tool_executor=self._controlled_tool_call,
llm_caller=self._controlled_llm_call
)
return {
"status": "success",
"result": result,
"usage": self.usage
}
except (PolicyViolation, BudgetExhausted) as e:
return {
"status": "failed",
"error": str(e),
"usage": self.usage
}
finally:
# Finalize billing event
self.usage.execution_time_ms = int((time.time() - start_time) * 1000)
self.billing.emit(self.tenant.tenant_id, self.usage)
def _controlled_llm_call(self, model_id: str, messages: list):
"""
Intercepts LLM calls to check model access and track costs.
"""
# 1. Capability Check
if model_id not in self.tenant.allowed_models:
raise PolicyViolation(f"Model {model_id} not allowed for tenant {self.tenant.tenant_id}")
# 2. Budget Pre-Flight Check (Simplified)
if self.usage.cost_usd >= self.tenant.max_budget_usd:
raise BudgetExhausted("Monthly budget limit reached.")
# 3. Execute Call (Mocked here)
# In reality, this calls OpenAI/Anthropic API
response = self.llm.chat.completions.create(model=model_id, messages=messages)
# 4. Track Usage
input_tokens = response.usage.prompt_tokens
output_tokens = response.usage.completion_tokens
cost = self._calculate_cost(model_id, input_tokens, output_tokens)
with self._lock:
self.usage.input_tokens += input_tokens
self.usage.output_tokens += output_tokens
self.usage.cost_usd += cost
# 5. Hard Budget Stop (Post-call check)
if self.usage.cost_usd > self.tenant.max_budget_usd:
# Trigger kill switch / notify billing
raise BudgetExhausted("Budget exceeded during execution.")
return response.choices[0].message.content
def _controlled_tool_call(self, tool_name: str, params: dict):
"""
Intercepts Tool calls to enforce Policy (OPA/Jail).
"""
# 1. Policy Check
if tool_name not in self.tenant.allowed_tools:
raise PolicyViolation(f"Tool '{tool_name}' is denied by policy.")
# 2. Execute Tool (Securely)
# Here you would route to the specific tool implementation
print(f"Executing tool: {tool_name} with {params}")
return f"Result from {tool_name}"
def _calculate_cost(self, model_id, in_tok, out_tok):
# Simple pricing map
pricing = {
"gpt-4o": {"in": 0.005, "out": 0.015} # per 1k tokens
}
p = pricing.get(model_id, {"in": 0, "out": 0})
return (in_tok / 1000 * p["in"]) + (out_tok / 1000 * p["out"])
# --- Mock Agents & Usage ---
def mock_billing_emit(tid, usage):
print(f"[BILLING] Tenant: {tid} | Cost: ${usage.cost_usd:.4f} | Tokens: {usage.input_tokens + usage.output_tokens}")
# Define Tenant
tenant_acme = TenantContext(
tenant_id="acme-001",
max_budget_usd=0.10, # Very low limit for demo
allowed_models=["gpt-4o"],
allowed_tools=["web_search"]
)
# Initialize Runtime
supervisor = AgentRuntimeSupervisor(
tenant=tenant_acme,
llm_client=None, # Mocked
billing_client=type('Billing', (), {'emit': mock_billing_emit})()
)
# Define simple agent logic
def my_agent(prompt, tool_executor, llm_caller):
# Step 1: LLM thinks
# llm_caller would actually call the API.
# We simulate a response here for the example to run without API keys.
# response = llm_caller("gpt-4o", [{"role": "user", "content": prompt}])
# Simulating internal usage accumulation for the demo
supervisor.usage.cost_usd += 0.09
# Step 2: Try a bad tool
try:
tool_executor("delete_database", {})
except PolicyViolation as e:
print(f"Agent caught error: {e}")
# Step 3: Try a good tool
tool_executor("web_search", {"query": "weather"})
# Step 4: Trigger Budget Exhaustion
try:
# Simulating another call that pushes over limit
supervisor.usage.cost_usd += 0.05
# llm_caller would check budget here and raise
# supervisor._controlled_llm_call(...)
except Exception as e:
print(f"Agent stopped: {e}")
return "Done"
# Run
if __name__ == "__main__":
result = supervisor.execute_agent(my_agent, "Hello world")
print(result)
Implementation Nuances
- Streaming Token Counting: For models that stream tokens, implement a callback on the stream iterator that updates the
usage counter in real-time to prevent overages during generation.
- Concurrency: Use
asyncio for the tool executor to handle multiple IO-bound tool calls concurrently.
- Sandbox Escape: Ensure the Python process running
AgentRuntimeSupervisor runs as a non-root user inside the microVM, and the host mounts necessary secrets (like DB credentials) only when a tool is authorized, not at boot time.
7. Operational Checklist
- Observability: Deploy Grafana dashboards tracking
tenant_id vs active_agents vs cost_rate.
- Secret Management: Use HashiCorp Vault. The Runtime fetches secrets for tools just-in-time (JIT) based on policy approval.
- Data Retention: Implement vector DB isolation. Ensure tenant A cannot query tenant B's embeddings via RAG tools. This is usually handled by metadata filtering in the vector store query.