The Complete Production SOP: How to Deploy and Run Portkey AI Gateway Load Balancing & Fallbacks in Autonomous AI Agents
Step-by-step SOP to install and run Portkey AI Gateway Load Balancing & Fallbacks in Codex, Claude Code, & Cursor. Includes verified configs and error fixes.
Technical Overview & Architectural Context
Autonomous coding agents frequently encounter hard stops when upstream LLM providers throttle requests, hit sudden token rate limits, or suffer transient network downtime. When an agent (such as Claude Code, Cursor, or Codex) makes raw client calls directly to a single provider API, any 429 Too Many Requests or 503 Service Unavailable halts the entire automated loop, burning context tokens on repeated failed retries or producing broken multi-file patch sets. Without an intermediary gateway, agents also lack unified observability into model latency, cost attribution, and token distribution across development iterations. The Portkey AI Gateway Load Balancing & Fallbacks skill enforces deterministic, production-grade routing boundaries. By mounting this skill, the agent routes all provider SDK calls through Portkey Gateway instances configured with weighted load balancing, exponential backoff, and automatic multi-provider fallback chains (e.g., failing over from OpenAI to Anthropic or AWS Bedrock). The agent operates within strict workspace filesystem boundaries (fs_write scoped to workspace, shell_exec set to false), ensuring resilient model consumption without risking secret leakage or unbounded retry loops.
Prerequisites & Environment Requirements
Verified Search Intents & Long-Tail Queries Solved
This operational tutorial is engineered to provide deterministic solutions for these developer search queries:
Step-by-Step Execution Playbook
Local Environment Setup & SKILL.md Mounting
Create the local skill manifest directory and inject verified procedural rules.
Agent runtimes such as Claude Code and Cursor scan defined directories (`.claude/skills/`, `.cursor/rules/`, or `~/.agents/skills/`) for standard SKILL.md manifests. By creating the skill file directly within the project's agent registry path, the agent hot-reloads the triggers ('setup portkey ai gateway', 'configure provider fallback portkey', 'load balance llm requests') and adheres to the specified declarative execution SOP.
mkdir -p .agents/skills/portkey-ai-gateway-proxy && curl -fsSL https://askills.dev/api/skills/portkey-ai-gateway-proxy/raw -o .agents/skills/portkey-ai-gateway-proxy/SKILL.md---
name: "portkey-ai-gateway-proxy"
description: "Route LLM traffic through a fast, resilient AI Gateway with load balancing and retries."
metadata:
author: "Portkey AI"
version: "1.0.0"
runtime_compatibility:
- "codex"
- "claude-code"
- "cursor"
- "windsurf"
triggers:
- "setup portkey ai gateway"
- "configure provider fallback portkey"
- "load balance llm requests"
permissions:
fs_read: true
fs_write: "workspace"
shell_exec: false
net_access: false
---
# Portkey AI Gateway Load Balancing & Fallbacks
Configures Portkey AI Gateway: unified multi-provider routing (OpenAI, Anthropic, Bedrock), automated retries with exponential backoff, fallback provider failover, and request load balancing.
## When to Invoke
Invoke this skill whenever you need to:
- setup portkey ai gateway
- configure provider fallback portkey
- load balance llm requests
## Execution SOP & Rules
1. Deploy Portkey Gateway as a lightweight Docker container or serverless edge worker.
2. Configure routing configs declaring targets, retry attempts, and fallback provider sequences.
3. Route client SDK requests through the gateway by updating the baseURL parameter.
4. Monitor provider latency, error rates, and token throughput on centralized dashboards.
## Verification Checklist
- Run local linting, syntax validation, and type-checks before reporting completion.
- Ensure all created or modified files adhere to workspace boundaries and avoid uncommitted secrets.
- Verify tests or build commands exit cleanly with return code 0.Keep the SKILL.md rules succinct. Agents ingest frontmatter metadata into their initial context; omitting verbose descriptions saves context tokens during large diff reviews.
Notice `permissions.shell_exec: false` and `permissions.fs_write: 'workspace'`. If your agent attempts to execute external shell daemons without confirmation or write to system-level directories, the sandbox policy will abort the execution.
Environment Secrets & Dependency Validation
Inject required environment variables safely without leaking secrets into conversation history.
The Portkey Gateway requires virtual keys or direct provider keys alongside the Portkey API Key (if using managed control planes) or local environment variables (if running the self-hosted open-source gateway). Store these in `.env.local` or Docker environment configurations. Never prompt the AI agent with raw API keys.
cat << 'EOF' >> .env.local
PORTKEY_GATEWAY_URL=http://localhost:8787/v1
PORTKEY_API_KEY=pk-prod-workspace-credentials
OPENAI_API_KEY=sk-proj-primary-key
ANTHROPIC_API_KEY=sk-ant-fallback-key
EOF
echo ".env.local" >> .gitignore{
"strategy": {
"mode": "fallback"
},
"targets": [
{
"provider": "openai",
"api_key": "${OPENAI_API_KEY}",
"override_params": {
"model": "gpt-4o"
},
"retry": {
"attempts": 3,
"on_status_codes": [429, 500, 503]
}
},
{
"provider": "anthropic",
"api_key": "${ANTHROPIC_API_KEY}",
"override_params": {
"model": "claude-3-5-sonnet-20241022"
}
}
]
}Export `PORTKEY_GATEWAY_URL` in your workstation shell before starting Claude Code CLI or Cursor to allow seamless interception of OpenAI-compatible client libraries.
Ensure `.env.local` is listed in `.gitignore` before asking an agent to review repository files, preventing sensitive credentials from being committed during automated Git workflows.
Intent Matching & Trigger Invocation
Verify deterministic activation using tested natural language prompts.
Instruct your autonomous agent using trigger-aligned vocabulary. When an agent detects matching trigger phrases ('setup portkey ai gateway' or 'configure provider fallback portkey'), it activates the deterministic SOP defined in SKILL.md, ensuring that client SDK initializations are routed through the proxy baseURL with custom headers containing the fallback configuration.
import OpenAI from 'openai';
import { createHeaders } from 'portkey-ai';
const portkeyConfig = require('../portkey-config.json');
export const aiClient = new OpenAI({
apiKey: process.env.PORTKEY_API_KEY || 'dummy-key',
baseURL: process.env.PORTKEY_GATEWAY_URL || 'http://localhost:8787/v1',
defaultHeaders: createHeaders({
config: portkeyConfig,
virtualKey: 'openai-default-vk'
})
});Use concise verbs matching the frontmatter triggers, such as 'configure provider fallback portkey with OpenAI primary and Anthropic secondary', to directly target the activation heuristic.
Verification, Linting & Output Quality Gate
Execute automated self-healing checks before accepting agent deliverables.
Following the SKILL.md verification checklist, the agent must run local test suites, validate JSON syntax on Portkey routing configs, and verify that mock 429 responses trigger failover without throwing unhandled exceptions.
npm run lint && npm test -- --testPathPattern=llmClientimport { aiClient } from '../src/llmClient';
describe('Portkey AI Gateway Routing', () => {
it('successfully reaches gateway endpoint', async () => {
expect(aiClient.baseURL).toContain(':8787/v1');
expect(aiClient.defaultHeaders).toHaveProperty('x-portkey-config');
});
});Review git diff with `git diff --staged` before accepting pull requests created by the agent to ensure no unwanted proxy configurations overwrite production environment flags.
Real-World Scenario: Configuring Portkey Gateway Fallback Routing from OpenAI GPT-4o to Anthropic Claude 3.5 Sonnet
“We are getting intermittent 429 rate limit errors from OpenAI in our backend extraction pipeline. Please configure provider fallback portkey routing so that failed requests automatically retry 3 times and then fall back to Anthropic Claude 3.5 Sonnet through the local Portkey AI Gateway.”
Runtime Troubleshooting & Failure Modes
Root Cause: The agent injected a fallback configuration referencing environment variables (${OPENAI_API_KEY}) that were not exported in the running Gateway container environment or the client header was malformed.
docker exec -it portkey-gateway env | grep -E 'OPENAI|ANTHROPIC' || export PORTKEY_CONFIG=$(cat portkey-config.json | envsubst)Root Cause: The Portkey local edge gateway instance is not running or is listening inside Docker without the container port mapped to the host.
docker run -d --name portkey-gateway -p 8787:8787 portkeyai/gateway:latestFrequently Asked Questions (Portkey AI Gateway Load Balancing & Fallbacks SOP)
Q:Can I use Portkey AI Gateway Load Balancing & Fallbacks across Codex, Claude Code, and Cursor simultaneously?
Yes. The skill conforms to the universal SKILL.md specification supported across all modern agent runtimes. By placing the manifest in `.agents/skills/portkey-ai-gateway-proxy/SKILL.md` or linking it inside runtime rules (`.cursor/rules` or `.claude/skills`), any compatible agent reads the identical SOP instructions and configuration triggers.
Q:How does Portkey AI Gateway Load Balancing & Fallbacks prevent context window overflow during long agent sessions?
By establishing concise procedural boundaries and deterministic validation gates rather than polluting system prompts with redundant rules. Offloading retry logic and provider failover rules to the Portkey gateway config eliminates the need for the agent to generate repetitive error-recovery boilerplate code in your application.
Q:Does this skill require escalated root or container permissions?
No. It is audited with a security score of 98/100 and runs safely within workspace-scoped sandboxes. The skill frontmatter explicitly declares `shell_exec: false` and `fs_write: workspace`, meaning agents can safely edit local config and client files without touching system processes.
Ready to equip your autonomous agent with Portkey AI Gateway Load Balancing & Fallbacks?
Copy the complete audited SKILL.md specification or download the 1-click zip bundle directly from our verified registry.