gateway README

The project's README from github.com/Portkey-AI/gateway. As one markdown file: README.md.

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.


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.

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


Core Features

Reliable Routing

Security & Accuracy

Cost Management

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

🚨 Latest

View all cookbooks →

Supported Providers

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

Provider Support Stream
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.

Framework Call 200+ LLMs Advanced Routing Caching Logging & 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

gateway (Portkey-AI/gateway)

Searching Database…

13.2K ·GitHub
Что это такое?AI-шлюз с открытым исходным кодом, который через один быстрый и удобный API направляет ваши запросы к более чем 1 600 моделям — языковым, vision, аудио и изображений — от 45+ провайдеров, со встроенными guardrails, кешированием, повторными попытками и fallback-ами.
Это библиотека, которую я подключаю к своему коду, или отдельный сервер, который я запускаю?Это сервер, а не библиотека: он стоит между вашим приложением и провайдерами моделей и пересылает запросы в формате OpenAI к выбранной модели. Можно развернуть его самостоятельно через Docker, Node.js, Cloudflare Workers или Replit либо использовать облачную версию Portkey Cloud.
Как его запустить?Сначала разверните шлюз — рекомендуемый путь это Portkey Cloud, альтернативы — Docker, Node.js, Cloudflare и Replit — затем отправьте первый запрос через JS- или Python SDK, обычный REST или OpenAI SDK. В README утверждается, что интеграция занимает меньше 2 минут.
Мне нужны API-ключи от каждого провайдера, или шлюз сам с этим разбирается?Свои ключи провайдеров приносите вы, либо прямо на шлюзе можно сгенерировать виртуальные ключи. На стороне клиента поддерживаются обычный REST, а также JS- и Python SDK, OpenAI SDK, LangChain, LlamaIndex, Autogen и CrewAI.
Всё это бесплатно и с открытым исходным кодом?Ядро шлюза — open source под лицензией MIT, но часть возможностей закрыта: управление шаблонами промптов есть только в облачной и enterprise-версиях, а enterprise-тариф добавляет управление организациями, governance и удаление PII-данных. Gateway 2.0 пока в статусе pre-release.
Можно ли направлять на него чувствительный или регулируемый трафик?Да — он соответствует SOC2, HIPAA, GDPR и CCPA, а enterprise-тариф добавляет удаление PII-данных, входящие правила по IP/геолокации и разграничение доступа на основе ролей. При самостоятельном размещении трафик запросов не покидает вашу инфраструктуру.
Что будет, если провайдер упадёт или начнёт тормозить?Запросы автоматически повторяются до 5 раз с экспоненциальной задержкой, чтобы не перегружать сеть, можно задать детальные таймауты, которые убивают зависшие запросы, а балансировка нагрузки распределяет трафик между несколькими API-ключами или провайдерами с весами и fallback-ами на случай недоступности.
Для чего нужна часть MCP Gateway?Это централизованная панель управления MCP-серверами: пользователи авторизуются один раз на шлюзе, администраторы решают, какие команды к каким серверам и инструментам имеют доступ, а каждый вызов инструмента логируется с указанием вызвавшего, параметров и задержки. Работает с Claude Desktop, Cursor, VS Code и любым MCP-совместимым клиентом.
Он поможет сократить мой счёт за LLM?Да. Умное кеширование (простое и семантическое) быстрее и дешевле обслуживает повторяющиеся запросы, аналитика использования отслеживает объём запросов, задержки, затраты и долю ошибок, а оптимизация провайдеров может автоматически переключаться на самого выгодного провайдера на основе паттернов использования.
С какими провайдерами и агентскими фреймворками он работает?45+ провайдеров, включая OpenAI, Azure OpenAI, Google Gemini, Anthropic, Cohere, Mistral, Together AI, DeepInfra и Ollama, а также 8+ агентских фреймворков: Autogen, CrewAI, LangChain, LlamaIndex, Phidata, Control Flow, IO Intelligence и собственные агенты.
Creator
Portkey-AI
Size
66.1 MB
Stars
13.2K
Age
3y
Commits · 90 Days