Acme Engineering — Agent Cost Governance
01 / 19

Navigation

→ / SpaceNext slide
←Previous slide
HomeFirst slide
EndLast slide
SwipeTouch navigation
Click anywhere or press Esc to close

Agent Cost Governance
on Unity AI Gateway

Cost and risk controls for autonomous coding, completion, and data agents — enforced at the gateway rather than in agent code.

Six governance layers: model routing, rate limits, spend caps, guardrails, approval gates, and sandbox isolation

Builds on the Unity AI Gateway deck and the Agent Orchestration & Tool Governance deck. This deck: governing agent cost and risk specifically.

Agenda

What this deck covers.

1
The issue

Agent traffic — LLM calls, tool calls, and execution actions — creates cost and risk that's invisible without governance configured at the gateway.

2
What the governance layers are

Model routing and allowlisting, rate limits, spend caps, guardrails, approval gates, and sandbox isolation — six independently configurable controls on one gateway.

3
Why each layer matters

Cost control, risk reduction, compliance, and engineering velocity — with concrete rate-limit, spend-cap, and cost-reduction figures.

4
How to configure it

The actual gateway and Omnigent YAML — model allowlists, rate-limit hierarchy, spend caps, service policies, sandbox policy.

5
Observability

system.ai_gateway.usage — the queries that answer a cost question before finance has to ask it.

The issue

Agent spend and risk are invisible without governance at the gateway.

An engineer left a coding agent running overnight to refactor a legacy module. The agent looped. Three hours and $400 later, finance flagged the invoice — nobody had visibility while it was happening.
$400
one agent, one night, no cap in place
0
governance layers configured at the time

Why this happens

Unity AI Gateway is the chokepoint all agent traffic already passes through. Without governance configured on top of it, it is a pass-through — the gap is configuration, not a limitation of the gateway itself.

Where the spend and risk originate

Autonomous coding agents

Multi-step agentic loops. Can run for hours without a human checkpoint.

IDE completion tools at scale

Many engineers hitting completions constantly adds up faster than it is usually modeled.

Notebook and data-profiling agents

Token-heavy prompts, long context windows. One template can run 200k tokens per call.

All three route through Unity AI Gateway. The chokepoint exists. Until governance is configured, the controls do not.

The issue

Agents are not just LLM calls.

Every hop in an agent loop is a separate cost event and a separate risk surface. The governance problem is wider than token pricing.

LLM calls

The obvious part

  • Input tokens: context, system prompt, tool schemas, conversation history
  • Output tokens: reasoning, code, tool-call arguments
  • Long context loops multiply cost non-linearly
  • Model-tier selection per task is uncontrolled
Tool & API calls

The hidden part

  • Agents call search APIs, GitHub, Jira, internal services
  • Each tool result feeds back into context — more input tokens
  • Unbounded tool loops: retries on error amplify spend
  • No visibility into which tools are called, how often, by whom
Execution actions

The risky part

  • Shell commands, file writes, git push, terraform apply
  • Agents act on infrastructure — not just generate text
  • No approval gate means an agent can act on production autonomously
  • Without a gate, there is no record of who approved it
Design principle: Govern the entire agent surface — not just the LLM endpoint. Cost, capability, and safety controls belong at the same layer.
What it is

All agent traffic through one gateway chokepoint.

Coding Agentautonomous, multi-step
Completion ToolIDE, high volume
Notebook Agentdata profiling
↓
↓
↓
Unity AI Gateway Model routing · Rate limits · Spend caps · Guardrails · Service policies · Audit
↓
↓
Foundation Models
Claude · Codex-tier · Gemini
↔
External Tools
GitHub · Jira · Internal services
system.ai_gateway.usage captures every call. Custom request tags (request-tags header) enable cost attribution by project, team, or priority.
What it is

Six layers, independently configurable.

Defense in depth. Some controls are account-wide, some per-team, some per-agent type. Each layer can change without touching the others.

Control layerConfigured byScopeWhat it stops
1. Model routingPlatform teamPer route / per teamModel-tier creep, unnecessary premium-model usage
2. Rate limitsPlatform teamAccount → team → user (QPM, TPM)Runaway loops, burst overconsumption
3. Spend capsFinance + platformAccount, team, user (daily) — two actionsBilling surprises, budget overruns
4. GuardrailsSecurity teamAccount-level default, all routesSecret exfiltration, prompt injection, PII leakage
5. Service policiesEngineering leadershipPer tool-call type, contextualUnauthorized deploys, destructive actions
6. Sandbox isolationPlatform teamPer agent sessionFilesystem escape, credential theft, scope creep
Configuration surface: All six layers configure through Unity AI Gateway settings plus agent framework and Omnigent policy YAML. One control plane, no per-agent code changes required.
What it is

Guardrails — what agents can say and do.

Guardrails run on every request and response, before the model sees the input and before the agent sees the output. First match wins.

Input guardrails

Block before LLM

  • Prompts attempting to extract training data
  • System-prompt override attempts (Ignore all previous instructions)
  • Direct requests for internal system paths or service credentials
  • Prompt injection via tool results
Fires before token cost is incurred.
Output guardrails

Redact before agent

  • AWS access-key patterns (AKIA*)
  • Databricks personal access tokens (dapi*)
  • Private IP ranges in generated code
  • Internal hostnames and hardcoded connection strings
Pattern-matched before the agent consumes output.
PII detection

Redact before model

PII in agent context (emails, employee IDs, SSNs, card numbers) is redacted before the LLM processes it.

Redaction is deterministic: the same entity gets the same placeholder across a session.

john.doe@acme.com → [EMAIL_1]
Requirement: All three guardrail types on every agent route. pii_detection: true required to enable built-in PII redaction — guardrails are account-level defaults, not per-team opt-in.
What it is

Approval gates, and policies that remember the session.

Service policies — the approval matrix
Agent actionAutonomous?Requires
read_file✓ Yes—
run_tests✓ Yes—
create_pr✓ Yes—
git push main✗ NoHuman approval
terraform apply✗ NoHuman approval
delete_resource✗ NoHuman approval

Enforced at the gateway, not in agent code

Service policies live in gateway configuration. An agent cannot bypass them — the gateway intercepts the tool call and issues a hold before forwarding.

Contextual policies — four verdicts, not three
ALLOWProceed as requested
DENYBlock the action outright
ASKPause for human approval
TRANSFORMModify the action, then proceed

Why four verdicts: policies accumulate session state

Contextual policies evaluate every tool call and model response during a session and track cumulative state. For cost budgets: a soft threshold triggers ASK for confirmation; a hard cap triggers TRANSFORM, which can swap the agent to a more efficient model rather than blocking outright. The same state tracking backs intent-based policies, which scope an agent’s tools to what it declared it would do for the current session.

Sandbox isolation (Omnigent)

Each coding-agent session gets its own isolated Databricks Sandbox — filesystem and network scoped to that session, credentials injected at session start. A session is shareable by URL for full review.

Why it matters

Rate limits and model routing bound the velocity and the price of every call.

Rate-limit hierarchy
Account level
5,000 RPM
all teams combined, any model
Team
800 RPM
per team
Per engineer
500 req/day
any model family
Coding-agent burst
60 RPM
per engineer
Notebook agent
2k tok/min
per seat

Rate limits catch loops in real time

A 60 RPM per-engineer coding-agent limit stops a runaway loop within the first minute, well before an unattended loop could run up hundreds of dollars in overnight spend. Engineer sees a 429, investigates, fixes the loop.

Model allowlisting is the cheapest, highest-impact control

An engineer using a premium-tier model for a task a lower tier could handle can cost roughly 15× more for the same output. Allowlisting removes the choice rather than relying on attention.

34% cost reduction from routing alone

Model allowlisting drove a 34% reduction in model spend with no feature changes — the expected range going in was 20–40%.

Why it matters

Spend caps are the kill switch. Here is what changed once all six layers were live.

Spend caps (two actions)
ScopeCapPeriodOn breach
Account $15,000 monthly Alert or Block
Team $2,000 monthly Alert or Block
Engineer $50 daily Alert or Block

Rate limits and caps compound

Rate limits stop loops in real time. Caps stop cumulative overruns across the billing period. Both are needed — neither alone is sufficient.

Budget enforcement uses near-real-time cost estimates, so actual spend can overshoot the threshold before blocking engages. For a firm ceiling, pair budgets with rate limits. Use Alert for monitoring; use Block to prevent further usage.

Outcome after six layers were live
✓Per-engineer, per-team, per-day spend visible in real time via system.ai_gateway.usage. Chargebacks automated.
✓Zero runaway-loop cost events since rate limits were configured, unbounded overnight spend from a stuck loop is no longer possible.
✓Zero unauthorized deploys — every git push main and terraform apply now requires team-lead approval.
✓Budget forecast accuracy rose from roughly 40% to over 90%.
34%
cost reduction, routing alone
$0
runaway incidents, post-rollout
>90%
budget forecast accuracy
How — Layer 1

Model routing & allowlisting.

Gateway route config
# Serving endpoint config (simplified)
route_config:
  routes:
    - name: coding-agent-senior
      model_allowlist:
        - claude-sonnet-4-*
        - claude-opus-4-*
      tags_filter: {team: engineering, tier: senior}

    - name: completion-tool-mid
      model_allowlist:
        - claude-haiku-3-*
      tags_filter: {team: engineering, tier: mid}

    - name: notebook-agent-data
      model_allowlist:
        - gemini-2-flash-*
      tags_filter: {team: data}
Policy by agent type

Coding agent — senior: Sonnet default, Opus on explicit request. All other model families blocked.

Completion tool — mid-level: Haiku-equivalent tier only. Sonnet, Opus, and Gemini Pro blocked.

Notebook agent — data team: Approved Gemini family, flash by default. All Claude families and GPT-4 blocked.

How — Layers 2 & 3

Rate limits and spend caps — the two responses agents receive.

Rate-limit response (velocity)
# What the agent receives on throttle
HTTP/1.1 429 Too Many Requests
Retry-After: 60
{
  "error": "rate_limit_exceeded",
  "limit": "60 RPM per engineer",
  "reset_at": "2026-07-07T14:32:00Z"
}

First-match-wins: the gateway evaluates most-specific to least-specific. A per-engineer burst limit fires before the team or account limit ever needs to.

Spend-cap response (total)
# Spend cap response — same 429, different cause
HTTP/1.1 429 Too Many Requests
{
  "error": "spend_cap_exceeded",
  "scope": "user",
  "cap_usd": 50.00,
  "spent_usd": 50.12,
  "resets_at": "2026-07-08T00:00:00Z"
}

Finance integration: spend data in system.ai_gateway.usage feeds a nightly roll-up — a line item per team per day, no override path once a cap fires.

How — Layer 5

Service policies — approval gates for high-risk tool calls.

Gateway service policy
# Gateway service policy (simplified)
service_policies:
  - name: high-risk-tool-gate
    match:
      tool_names:
        - git_push_main
        - terraform_apply
        - delete_resource
    action: require_approval
    approval:
      timeout_seconds: 300
      approver_groups: [team-leads]
      on_timeout: deny

What the agent experiences

The gateway intercepts the matching tool call and returns a hold. Execution pauses. A notification goes to the on-call team lead. Approve → agent continues. Deny or timeout → agent receives a rejection. The entire flow is logged.

Enforced at the gateway, not in agent code

Policies live in gateway configuration, not in a prompt or tool definition — an agent cannot reason its way past one.

How — Layer 6

Omnigent sandbox policy — isolation and a per-session spend ceiling.

Omnigent sandbox policy YAML
# Per-session isolation and cost budget
guardrails:
  policies:
    cost_budget:
      type: contextual
      on: [request]
      soft_threshold: 500000  # tokens
      soft_action: ask         # pause, ask human
      hard_limit: 1000000
      hard_action: transform   # switch to cheaper model
  isolation:
    filesystem: workspace_only
    network:
      - api.github.com
      - internal.jira.example.com
    credentials: env_scoped  # rotated per session

Session-scoped cost budgets

A single coding-agent session has its own token budget separate from gateway-level caps. Soft threshold pauses for confirmation; hard cap switches the agent to a more efficient model before terminating.

Full transparency for code-at-scale scenarios

Each session has a shareable URL. Team leads can inspect what the agent sees: working directory, full tool-call history, LLM conversation, and sandbox decisions.

Defense in depth

Filesystem, network, and credentials are scoped at the OS level before the gateway is involved. An agent cannot escape its sandbox or access unlisted services.

How — Observability

The usage table, and what breaks quietly if you skip the fine print.

Queries against system.ai_gateway.usage
-- Daily spend by engineer
SELECT user_id, date_trunc('day', timestamp) AS day,
       sum(total_cost_usd) AS spend_usd,
       sum(total_tokens) AS tokens
FROM system.ai_gateway.usage
WHERE workspace_id = current_workspace_id()
  AND timestamp >= current_date - INTERVAL 30 DAYS
GROUP BY 1, 2
ORDER BY spend_usd DESC;
-- Anomaly alert: 3x daily average breach
WITH daily_avg AS (
  SELECT user_id, avg(daily_spend) AS avg_spend
  FROM (
    SELECT user_id, DATE(timestamp) AS d,
           sum(total_cost_usd) AS daily_spend
    FROM system.ai_gateway.usage
    WHERE timestamp >= current_date - 30
    GROUP BY 1, 2
  ) GROUP BY 1
)
SELECT u.user_id, today.spend, d.avg_spend,
       today.spend / d.avg_spend AS ratio
FROM daily_avg d
JOIN (...today_spend...) today USING (user_id)
WHERE today.spend > d.avg_spend * 3;
Gotchas
IssueDetail
Model-tier creepWithout allowlisting, model choice defaults to whoever pays least attention — a premium model can cost roughly 15× a lower tier for the same output.
Budgets don't track provisioned throughputUnity AI Gateway budgets track only pay-per-token and batch inference. Do not rely on budget caps to limit provisioned-throughput spend.
Budget scale limitsMax 4 shared thresholds per budget, max 20 per-user overrides per budget, max 1,000 budgets per account.
Enforcement is approximateBudgets use near-real-time cost estimates, so actual spend can overshoot before blocking engages. Pair budgets with rate limits for firm control.
pii_detection: true is not implicitBuilt-in PII redaction requires this flag explicitly set on the route.

The billable-usage system table rolls up cost at the UC model-service level regardless of which API surface (mlflow-format, native provider API) was used. A pre-built usage dashboard visualizes spend trends by team, agent type, and model.

Which runtime · Omnigent

Omnigent governs what the agent does.

What

An open-source meta-harness that wraps a coding-agent CLI (Claude Code, Codex) behind one contract, then runs the agent loop with sessions, a sandbox, and a policy engine. Available self-hosted or Databricks-managed.

How

It inserts a governed hop in the loop. Every tool call routes back to the server, a stateful policy returns ALLOW, ASK, DENY, or TRANSFORM, then the Omnibox sandbox runs the approved action. The gate runs even under CLI bypass mode, so it is not opt-out.

Why

You get control over what the agent does, not just what the model reads and writes: approval gates, per-session spend ceilings, kernel-level filesystem and network isolation, shared and replayable sessions, and a durable transcript.

When

Choose Omnigent when the agent needs guardrails on its actions. Managed for zero-setup workspace auth and the strongest sandbox, OSS when you need custom policies, your own host, or your own model keys. If you only need auth and usage, this is more than you need, so use ug.

Which runtime · ug (formerly ucode)

ug routes an installed agent through the gateway.

Setup and config
# install once
uv tool install git+https://github.com/databricks/unity-gateway
# sign in, discover models, write each agent's config
ug configure --workspace https://YOUR-WORKSPACE-HOST --agents claude,codex
# launch, pick a governed model service
ug claude --model system.ai.claude-sonnet-4-5
ug mcp add          # register governed MCP tools
ug usage            # per-user spend and token totals

How it connects

ug handles OAuth and writes each agent's config, so there are no provider API keys and no manual endpoint wiring. Requests land on the gateway under workspace identity and record to system.ai_gateway.usage.

What

A thin launcher (formerly ucode; the old name stays as a backward-compatible alias) that configures a supported agent (Claude Code, Codex, and others) and launches it against the gateway. No harness, no sessions, no sandbox.

Why

The fastest path to per-user auth, model routing, and usage visibility on an agent your engineers already run locally. One CLI configures many agents the same way.

When

Choose ug when the agent is already installed and you just need per-user auth, model routing, and spend visibility. The moment you need sessions, sandboxing, or policy on actions, graduate to Omnigent. ug governs model traffic, not what the agent does on disk.

How — Rollout sequence

Don't boil the ocean. Start here.

Each step is independently valuable. Stop after any step if the org isn't ready. Later steps get easier once earlier ones are in place.

1
Usage monitoring first

Enable system.ai_gateway.usage and run the spend-by-engineer query. No controls yet — just visibility.

2
Model allowlists

Map teams to model tiers by actual task profile. Expect 20–40% cost reduction within the first billing cycle.

3
Rate limits

Set per-engineer RPM limits conservatively, then tune up. Runaway loops stop; normal use barely notices.

4
Spend caps

Account, team, and daily-user caps. Finance gets a committed ceiling; engineering gets autonomy within it.

5
Guardrails

PII detection and output secret scanning. Security team owns this layer independently.

6
Approval gates & sandbox isolation

Service policies and Omnigent sandboxes for agents with infrastructure access. Pilot with one team, tune, then expand.

SIX LAYERS. ONE GATEWAY. ZERO SURPRISES.
Model routing · Rate limits · Spend caps · Guardrails · Approval gates · Sandbox isolation
Acme Engineering · Databricks Applied AI Governance Series · Agent Cost Governance