steerplane
v1.2.1
Published
The safety layer for the AGI era. Runtime guardrails for autonomous AI agents. Guards, cost limits, loop detection, and telemetry.
Maintainers
Readme
SteerPlane — TypeScript SDK
The safety layer for the AGI era. Runtime guardrails for autonomous AI agents.
steerplane.com · Guides · Docs
Cost limits · Loop detection · Action rules · Approval callbacks · Gateway · Zero dependencies
Install
npm install steerplaneQuick Start
Option 1: Gateway Mode
Point your OpenAI client at the SteerPlane gateway. Model calls sent through it are checked against the key's model rules, cost limits, request rate and repeated prompts, and a streamed reply is cut when the estimated cost reaches the limit. It does not apply action rules to tool calls. See what the gateway covers.
import OpenAI from 'openai';
const client = new OpenAI({
baseURL: 'http://localhost:8000/gateway/v1',
apiKey: 'sk_sp_...', // SteerPlane API key
defaultHeaders: { 'X-LLM-API-Key': 'sk-...' }
});
// Calls sent through the gateway are checked, including stream: true
const stream = await client.chat.completions.create({
model: 'gpt-4o-mini',
messages: [{ role: 'user', content: 'Hello' }],
stream: true // SSE streaming with real-time cost tracking
});Option 2: Higher-Order Function
Wrap your agent; its code stays as it is.
import OpenAI from 'openai';
import { guard } from 'steerplane';
const client = new OpenAI();
const runAgent = guard(
async () => {
// your code, unchanged
const reply = await client.chat.completions.create({ model: 'gpt-4o-mini', messages, tools });
// ...
},
{
agentName: 'support_bot',
maxCostUsd: 10.00,
maxSteps: 50,
policy: { deniedActions: ['delete_*'] },
}
);
await runAgent();Inside guard(), every openai or @anthropic-ai/sdk client call (Chat Completions, Responses, Messages, with or without stream: true, and the parse, stream and runTools helpers built on them) is:
- checked before it is sent. Once the step or cost limit is reached, the next call throws and is never sent.
- counted as a step, with tokens and cost from the provider's usage (Claude prompt-cache tokens included).
- checked for tool calls. If the model asks for a tool your policy denies, the call throws before your code can run the tool. A
requireApprovalrule callspolicy.approvalCallbackwith the tool's arguments.
.withResponse() keeps working. Not covered: tools that run without a model asking for them, other HTTP clients or providers, .tee() / toReadableStream() on a stream, and the cost of OpenAI streams without stream_options: { include_usage: true }. Report those steps yourself:
import { getActiveRun } from 'steerplane';
async function callTool<T>(name: string, fn: () => Promise<T>) {
const run = getActiveRun()!;
await run.checkBeforeStep(name); // throws before the tool runs
const result = await fn();
await run.logStep({ action: name, checkPolicy: false });
return result;
}Set autoInstrument: false if you already log model calls yourself, so calls aren't counted twice. Rules match the action (tool) name, not its arguments. If the SDK can't find your openai package (unusual bundler or monorepo layouts), pass it in once: instrumentModule(await import('openai')).
Option 3: Class API (Full Control)
import { SteerPlane } from 'steerplane';
const sp = new SteerPlane({ agentId: 'my_bot' });
await sp.run(async (run) => {
await run.logStep({ action: 'query_db', tokens: 380, cost: 0.002 });
await run.logStep({ action: 'call_llm', tokens: 1240, cost: 0.008 });
await run.logStep({ action: 'send_email', tokens: 120, cost: 0.001 });
}, { maxCostUsd: 10 });Option 4: Manual Lifecycle
import { SteerPlane } from 'steerplane';
const sp = new SteerPlane({ agentId: 'my_bot' });
const run = sp.createRun({ maxCostUsd: 10 });
await run.start();
await run.logStep({ action: 'search', tokens: 100, cost: 0.001 });
await run.logStep({ action: 'generate', tokens: 1240, cost: 0.008 });
await run.end();Turning loop detection off
Loop detection is on by default. If your agent calls the same tool many times on purpose (for example, once per item in a list), you can stop it from ending the run. Cost, step, runtime and policy limits still apply.
const runAgent = guard(async () => { await agent.run(); }, {
maxCostUsd: 10,
maxSteps: 200,
detectLoops: false,
});detectLoops is accepted by guard(), SteerPlane.run(), createRun() and
new RunManager().
What's New in v1.2.1
- Version kept in step with the Python SDK, whose 1.2.1 adds Claude Code hooks (
steerplane claude-code install). No change to the TypeScript API.
What's New in v1.2.0
guard()now tracks model calls on its own.openaiand@anthropic-ai/sdkcalls inside it are checked against the step and cost limits before they are sent, counted with tokens and cost, and the tool calls the model asks for are checked against your policy before your code can run them. PassautoInstrument: falseif you log model calls yourself.run.checkBeforeStep(action?)refuses a step before it starts, andlogSteptakescheckPolicyandloopCheck.- Policies saved in the dashboard now apply to runs. When a run starts, the SDK loads every active saved policy from the API (
GET /sdk/policy) and checks eachlogStepagainst it, next topolicyin your code. A refused step names the policy. For a savedrequire_approvalrule, passpolicy.approvalCallback. - Claude Code through the gateway (
/gateway/v1/messages), Claude prompt-cache pricing, and tool calls for Claude on the OpenAI route. These are API changes; see the main README.
What's New in v1.1.5
- Small cost limits are shown properly. A $0.001 ceiling used to print as "Limit: $0.00". It now prints "$0.0010". Limits of $1 or more print as before.
What's New in v1.1.4
steerplane runs killnow stops a live run. The TypeScript SDK sends steps without waiting, so the run stops one step after the server sees the kill, withRunTerminatedError.
What's New in v1.1.3
- Routed names priced correctly:
openai/gpt-4o-miniuses thegpt-4o-miniprice.
What's New in v1.1.2
- Built-in pricing now covers 106 models. Adds Mistral's current models by their API ids
(for example
mistral-large-4,mistral-medium-3-5,codestral-2508), GPT-5.6 Cyber and GPT-5.5 Cyber, GPT-Rosalind, Gemini Robotics-ER 2, and the Gemini and Mistral-latestaliases. - Fixes ids that were priced as an older model with a similar name:
gemini-pro-latestwas priced as the oldgemini-prorow,gpt-5.6-cyberasgpt-5, and current Mistral ids as the older Mistral rows. - Audio, image, video, speech, realtime, transcription and embedding models are not in the table, and nor
are ids with a cloud or router prefix (such as Bedrock's
anthropic.ids). For those, pass your own cost per step withcostinlogStep.
What's New in v1.1.1
- Built-in pricing now covers 83 models, checked against the OpenAI, Anthropic and Google pricing pages on 21 Oct 2026 (current GPT, Claude and Gemini models, by their API ids).
- Dated model names such as
gpt-4o-2024-08-06are priced as their model instead of the default rate, andgpt-4.1is no longer priced asgpt-4. - For a model that is not in the table, pass your own cost per step with
costinlogStep.
What's New in v1.1.0
- New
detectLoopsoption onguard(),SteerPlane.run(),createRun()andRunManager. Set it tofalseto stop loop detection from ending a run; cost, step, runtime and policy limits still apply. See Turning loop detection off.
What's New in v0.4.0
🌊 SSE Streaming Gateway
The AI Gateway now supports Server-Sent Events (SSE) streaming. It accumulates token costs per chunk in real time and can terminate a stream mid-response by injecting a steerplane_enforcement event when the cost ceiling is breached — without corrupting the SSE protocol.
🛡️ Policy Engine
Define allow/deny rules, sliding-window rate limits, and human approval callbacks:
import { guard } from 'steerplane';
const runAgent = guard(async () => { await agent.run(); }, {
maxCostUsd: 10,
policy: {
deniedActions: ['DROP TABLE*', 'rm -rf*'],
rateLimits: [{ pattern: 'send_email', max_count: 5, window_seconds: 60 }],
requireApproval: ['execute_trade*'],
approvalCallback: async (action) => askAHuman(action), // return true to allow
},
});🐳 Docker Compose
Full 3-service stack (for one server shared by several teams, use docker-compose.hosted.yml):
docker compose up -d
# API (8000) + Dashboard (3000) + PostgreSQL (5432)🖥️ CLI Tool (Python SDK)
pip install "steerplane[cli]"
steerplane status # Check API health
steerplane runs list # List recent runs
steerplane keys create # Create gateway API key
steerplane logs --tail # Live log streamAll Features
| Feature | Description |
|---------|-------------|
| 🌉 AI Gateway Proxy | OpenAI-style chat/completions proxy: model rules, cost, request rate and repeated-prompt checks. |
| 🌊 SSE Streaming | Real-time chunk forwarding with mid-stream cost enforcement. |
| 🛡️ Policy Engine | Allow/deny rules, sliding-window rate limits, human-approval callbacks. |
| 🔄 Loop Detection | Sliding-window pattern detector catches infinite agent loops. |
| 💰 Hard Cost Ceiling | Per-run USD limits in the SDK, per-key monthly limits in the gateway. Built-in pricing for 106 models; for any other model, pass your own cost to logStep. |
| 🚫 Step Limits | Cap maximum execution steps to prevent runaway agents. |
| 📊 Deep Telemetry | Tokens, cost, latency per step — synced to the live dashboard. |
| 🛡️ Graceful Degradation | API down? Guards still enforce locally. |
| ⚡ Zero Dependencies | Uses native fetch — no bloat. |
| 🐳 Docker Compose | 3-service stack in one command. |
Error Handling
import { guard, CostLimitExceeded, LoopDetectedError, PolicyViolationError } from 'steerplane';
const runAgent = guard(async () => {
try {
await agent.run();
} catch (err) {
if (err instanceof CostLimitExceeded) {
console.log(`Budget exceeded: $${err.currentCost}`);
}
if (err instanceof LoopDetectedError) {
console.log(`Loop detected: ${err.pattern}`);
}
if (err instanceof PolicyViolationError) {
console.log(`Policy blocked: ${err.message}`);
}
}
}, { maxCostUsd: 5 });Architecture
┌─────────────┐ ┌──────────────┐ ┌────────────┐ ┌───────────────┐
│ AI Agent │────▶│ SteerPlane │────▶│ FastAPI │────▶│ PostgreSQL │
│ (Your App) │ │ SDK / GW │ │ Server │ │ Database │
└─────────────┘ └──────────────┘ └────────────┘ └───────────────┘
│
▼
┌───────────────┐
│ Next.js │
│ Dashboard │
└───────────────┘Tech Stack
| Component | Technology |
|-----------|-----------|
| TypeScript SDK | TypeScript, guard() wrapper, zero dependencies |
| Python SDK | Python 3.10+, CLI, Config files, 4 framework integrations |
| Gateway | FastAPI + httpx, SSE streaming, built-in pricing for 106 models |
| Database | PostgreSQL 16 + SQLAlchemy + Alembic |
| Infrastructure | Docker Compose (API + Dashboard + PostgreSQL) |
| CI/CD | GitHub Actions (lint, test, Docker build) |
| Dashboard | Next.js 16, React 19, Framer Motion |
Environment Variables
| Variable | Default | Description |
|----------|---------|-------------|
| STEERPLANE_API_URL | http://localhost:8000 | SteerPlane API server URL |
Requirements
- Node.js 18+
- SteerPlane API server (for dashboard integration)
Guides
- Stop an AI agent stuck in an infinite loop
- Cap what an AI agent can spend per run
- Stop an AI agent sending the same email twice
- Put a time limit on an AI agent that ran all night
- Stop an AI agent from deleting data
Links
- Website: steerplane.com
- GitHub: github.com/vijaym2k6/SteerPlane
- PyPI: pypi.org/project/steerplane
- Dashboard:
http://localhost:3000 - API Docs:
http://localhost:8000/docs
