Sandbox
@Portkey-AI/gateway

AI gateway for models and MCP servers

Portkey Gateway sits in front of model providers and MCP servers so your agent apps can use one API for routing, retries, fallbacks, and guardrails. It also logs usage, manages keys and access, and supports agent frameworks like LangChain and CrewAI.

12,958 stars1.3k forksTypeScriptUpdated 3mo ago
Who it's for

Builders who want their agent apps to call many models through one gateway and enforce guardrails along the way.

What it delivers

You can route agent requests through one API instead of wiring each model and server separately.

What it does

Model routing

Send requests to 1,600+ language, vision, audio, and image models through one OpenAI-style API.

Retries and fallbacks

Retry failed requests and fall back to another model or provider when a request fails.

Load balancing and timeouts

Spread traffic across providers and set request time limits for unstable or slow models.

Guardrails

Check inputs and outputs with prebuilt, custom, or partner guardrails to block unsafe or invalid responses.

MCP Gateway

Put MCP servers behind one control plane with shared auth, access control, identity forwarding, and tool-call logs.

Agent framework support

Works with LangChain, CrewAI, AutoGen, LlamaIndex, and other agent frameworks through the gateway.

Usage and audit logs

Track requests, latency, costs, and errors from the gateway console and observability features.

How to get it

  1. 1Run
    # Run the gateway locally (needs Node.js and npm)
    npx @portkey-ai/gateway

README

English | 中文 | 日本語

[!IMPORTANT] :rocket: Gateway 2.0 (Pre-Release) Portkey's core enterprise gateway is merging into open-source with our 2.0 release. You can try the pre-release branch here. Read more about what's next for Portkey in our Series A announcement.

🆕 Portkey Models - Open-source LLM pricing for 2,300+ models across 40+ providers. Explore →

AI Gateway

Route to 250+ LLMs with 1 fast & friendly API

Portkey AI Gateway Demo showing LLM routing capabilities

Docs | Enterprise | Hosted Gateway | Changelog | API Reference

License Discord Twitter npm version Better Stack Badge

Deploy to AWS EC2 Ask DeepWiki


The AI Gateway is designed for fast, reliable & secure routing to 1600+ language, vision, audio, and image models. It is a lightweight, open-source, and enterprise-ready solution that allows you to integrate with any language model in under 2 minutes.

  • Blazing fast (<1ms latency) with a tiny footprint (122kb)
  • Battle tested, with over 10B tokens processed everyday
  • Enterprise-ready with enhanced security, scale, and custom deployments

What can you do with the AI Gateway?



[!TIP] Starring this repo helps more developers discover the AI Gateway 🙏🏻

star-2



Quickstart (2 mins)

1. Setup your AI Gateway

# Run the gateway locally (needs Node.js and npm)
npx @portkey-ai/gateway

The Gateway is running on http://localhost:8787/v1

The Gateway Console is running on http://localhost:8787/public/

Deployment guides:   Portkey Cloud (Recommended)   Docker   Node.js   Cloudflare   Replit   Others...

2. Make your first request

# pip install -qU portkey-ai

from portkey_ai import Portkey

# OpenAI compatible client
client = Portkey(
    provider="openai", # or 'anthropic', 'bedrock', 'groq', etc
    Authorization="sk-***" # the provider API key
)

# Make a request through your AI Gateway
client.chat.completions.create(
    messages=[{"role": "user", "content": "What's the weather like?"}],
    model="gpt-4o-mini"
)

Supported Libraries:   JS   Python   REST   OpenAI SDKs   Langchain   LlamaIndex   Autogen   CrewAI   More..

On the Gateway Console (http://localhost:8787/public/) you can see all of your local logs in one place.

3. Routing & Guardrails

Configs in the LLM gateway allow you to create routing rules, add reliability and setup guardrails.

config = {
  "retry": {"attempts": 5},

  "output_guardrails": [{
    "default.contains": {"operator": "none", "words": ["Apple"]},
    "deny": True
  }]
}

# Attach the config to the client
client = client.with_options(config=config)

client.chat.completions.create(
    model="gpt-4o-mini",
    messages=[{"role": "user", "content": "Reply randomly with Apple or Bat"}]
)

# This would always response with "Bat" as the guardrail denies all replies containing "Apple". The retry config would retry 5 times before giving up.
Request flow through Portkey's AI gateway with retries and guardrails

You can do a lot more stuff with configs in your AI gateway. Jump to examples →


Enterprise Version (Private deployments)

AWS   Azure   GCP   OpenShift   Kubernetes

The LLM Gateway's enterprise version offers advanced capabilities for org management, governance, security and more out of the box. View Feature Comparison →

The enterprise deployment architecture for supported platforms is available here - Enterprise Private Cloud Deployments

Book an enterprise AI gateway demo


MCP Gateway

MCP Gateway provides a centralized control plane for managing MCP (Model Context Protocol) servers across your organization.

  • Authentication — Single auth layer at the gateway. Users authenticate once; your MCP servers receive verified requests
  • Access Control — Control which teams and users can access which servers and tools. Revoke access instantly
  • Observability — Every tool call logged with full context: who called what, parameters, response, latency
  • Identity Forwarding — Forward user identity (email, team, roles) to MCP servers automatically

Works with Claude Desktop, Cursor, VS Code, and any MCP-compatible client. Get started →


Core Features

Reliable Routing

  • Fallbacks: Fallback to another provider or model on failed requests using the LLM gateway. You can specify the errors on which to trigger the fallback. Improves reliability of your application.
  • Automatic Retries: Automatically retry failed requests up to 5 times. An exponential backoff strategy spaces out retry attempts to prevent network overload.
  • Load Balancing: Distribute LLM requests across multiple API keys or AI providers with weights to ensure high availability and optimal performance.
  • Request Timeouts: Manage unruly LLMs & latencies by setting up granular request timeouts, allowing automatic termination of requests that exceed a specified duration.
  • Multi-modal LLM Gateway: Call vision, audio (text-to-speech & speech-to-text), and image generation models from multiple providers — all using the familiar OpenAI signature
  • Realtime APIs: Call realtime APIs launched by OpenAI through the integrate websockets server.

Security & Accuracy

Cost Management

  • Smart caching: Cache responses from LLMs to reduce costs and improve latency. Supports simple and semantic* caching.
  • Usage analytics: Monitor and analyze your AI and LLM usage, including request volume, latency, costs and error rates.
  • Provider optimization*: Automatically switch to the most cost-effective provider based on usage patterns and pricing models.

Collaboration & Workflows

* Available in hosted and enterprise versions

Portkey Models

Open-source LLM pricing database for 40+ providers - used by the Gateway for cost tracking.

GitHub | Model Explorer


Cookbooks

☄️ Trending

🚨 Latest

View all cookbooks →

Supported Providers

Explore Gateway integrations with 45+ providers and 8+ agent frameworks.

ProviderSupportStream
OpenAI
Azure OpenAI
Anyscale
Google Gemini
Anthropic
Cohere
Together AI
Perplexity
Mistral
Nomic
AI21
Stability AI
DeepInfra
Ollama
Novita AI

View the complete list of 200+ supported models here



Agents

Gateway seamlessly integrates with popular agent frameworks. Read the documentation here.

FrameworkCall 200+ LLMsAdvanced RoutingCachingLogging & Tracing*Observability*Prompt Management*
Autogen
CrewAI
LangChain
Phidata
Llama Index
Control Flow
Build Your Own Agents
IO Intelligence

*Available on the hosted app. For detailed documentation click here.

Gateway Enterprise Version

Make your AI app more reliable and forward compatible, while ensuring complete data security and privacy.

✅  Secure Key Management - for role-based access control and tracking
✅  Simple & Semantic Caching - to serve repeat queries faster & save costs
✅  Access Control & Inbound Rules - to control which IPs and Geos can connect to your deployments
✅  PII Redaction - to automatically remove sensitive data from your requests to prevent indavertent exposure
✅  SOC2, ISO, HIPAA, GDPR Compliances - for best security practices
✅  Professional Support - along with feature prioritization

Schedule a call to discuss enterprise deployments


Contributing

The easiest way to contribute is to pick an issue with the good first issue tag 💪. Read the contribution guidelines here.

Bug Report? File here | Feature Request? File here

Getting Started with the Community

Join our weekly AI Engineering Hours every Friday (8 AM PT) to:

  • Meet other contributors and community members
  • Learn advanced Gateway features and implementation patterns
  • Share your experiences and get help
  • Stay updated with the latest development priorities

Join the next session → | Meeting notes


Community

Join our growing community around the world, for help, ideas, and discussions on AI.

Rubeus Social Share (4)

Files in the repo

Repository payload32 top-level entries
  • .github
  • .husky
  • .vscode
  • cookbook
  • docs
  • patches
  • plugins
  • src
  • tests
  • .dockerignore
  • .git-blame-ignore-revs
  • .gitattributes
  • .gitignore
  • .prettierignore
  • .prettierrc
  • CLAUDE.md
  • conf.example.json
  • conf.json
  • deployment.yaml
  • docker-compose.yaml
  • Dockerfile
  • eslint.config.js
  • initializeSettings.ts
  • jest.config.js
  • LICENSE
  • package-lock.json
  • package.json
  • README.md
  • rollup.config.js
  • start-test.js
  • tsconfig.json
  • wrangler.toml

Discussion (0)

Ask about usage, or say what you built with it

Sign in to join the discussion.

No comments yet. Be the first to say what this is good for.

More connectors

High-performance code intelligence MCP server. Indexes codebases into a persistent knowledge graph — average repo in milliseconds. 158 languages, sub-ms queries, 99% fewer tokens. Single static binary, zero dependencies.

43k

Universal provider proxy for OpenAI Codex & Claude Code — use any LLM (Claude, Gemini, Grok, DeepSeek, Ollama…) with Codex CLI, App, SDK, and Claude Code

14k
okf-memory/
okf-agent-memory

Git-native persistent memory for AI coding agents. Implements Google OKF v0.2 with sub-300µs in-memory BM25 search, embedded MCP server, and progressive disclosure. Slashes token bloat by 80% with zero external databases or dependencies. Built in pure Go.

547
tirth8205/
code-review-graph

Local-first code intelligence graph for MCP and CLI. Builds a persistent map of your codebase so AI coding tools read only what matters, with benchmarked context reductions on reviews and large-repo workflows.

31k
2akouwu/
reverify

Stop your AI from making things up — it proposes, deterministic tools decide, every claim checked against ground truth with evidence. Grounded facts and context survive resets. Reverse engineering is the proving ground. MCP server + CLI.

1.1k
t8y2/dbxConnectors

20 MB lightweight cross-platform database client for 90+ databases, including MySQL, PostgreSQL, SQLite, Redis, MongoDB, DuckDB, SQL Server, and Dameng. Built-in AI, MCP Server, CLI, desktop and Docker. | 轻量级跨平台数据库管理工具,支持 MySQL、PostgreSQL、SQLite、Redis、MongoDB、达梦等 90+ 数据库,提供桌面端、Docker、CLI、内置 AI 助手和 MCP Server。

19k