Repository files navigation

English | 中文

AI Gateway

Reliably route to 200+ LLMs with 1 fast & friendly API

Gateway Demo

LicenseDiscordTwitternpm version

Gateway streamlines requests to 200+ open & closed source models with a unified API. It is also production-ready with support for caching, fallbacks, retries, timeouts, loadbalancing, and can be edge-deployed for minimum latency.

Blazing fast (9.9x faster) with a tiny footprint (~45kb installed)
Load balance across multiple models, providers, and keys
Fallbacks make sure your app stays resilient
Automatic Retries with exponential fallbacks come by default
Configurable Request Timeouts to easily handle unresponsive LLM requests
Multimodal to support routing between Vision, TTS, STT, Image Gen, and more models
Plug-in middleware as needed
✅ Battle tested over 300B tokens
Enterprise-ready for enhanced security, scale, and custom deployments

How to Run the Gateway?

  1. Run it Locally for complete control & customization
  2. Hosted by Portkey for quick setup without infrastructure concerns
  3. Enterprise On-Prem for advanced features and dedicated support

Run it Locally

Run the following command in your terminal and it will spin up the Gateway on your local system:

npx @portkey-ai/gateway

Your AI Gateway is now running on http://localhost:8787 🚀

Gateway is also edge-deployment ready. Explore Cloudflare, Docker, AWS etc. deployment guides here.

Gateway Hosted by Portkey

This same open-source Gateway powers Portkey API that processes billions of tokens daily and is in production with companies like Postman, Haptik, Turing, MultiOn, SiteGPT, and more.

Sign up for the free developer plan (10K request/month) here or discuss here for enterprise deployments.


How to Use the Gateway?

Compatible with OpenAI API & SDK

Gateway is fully compatible with the OpenAI API & SDK, and extends them to call 200+ LLMs and makes them reliable. To use the Gateway through OpenAI, you only need to update your base_URL and pass the provider name in headers.

  • To use through Portkey, set your base_URL to: https://api.portkey.ai/v1
  • To run locally, set: http://localhost:8787/v1

Let's see how we can use the Gateway to make an Anthropic request in OpenAI spec below - the same will follow for all the other providers.

Python

pip install portkey-ai

While instantiating your OpenAI client,

  1. Set the base_URL to http://localhost:8787/v1 (or PORTKEY_GATEWAY_URL through the Portkey SDK if you're using the hosted version)
  2. Pass the provider name in the default_headers param (here we are using createHeaders method with the Portkey SDK to auto-create the full header)
fromopenaiimportOpenAIfromportkey_aiimportPORTKEY_GATEWAY_URL, createHeadersgateway=OpenAI(
api_key="ANTHROPIC_API_KEY",
base_url=PORTKEY_GATEWAY_URL, # Or http://localhost:8787/v1 when running locallydefault_headers=createHeaders(
provider="anthropic",
api_key="PORTKEY_API_KEY"# Grab from https://app.portkey.ai # Not needed when running locally
)
)
chat_complete=gateway.chat.completions.create(
model="claude-3-sonnet-20240229",
messages=[{"role": "user", "content": "What's a fractal?"}],
max_tokens=512
)

If you want to run the Gateway locally, don't forget to run npx @portkey-ai/gateway in your terminal before this! Otherwise just sign up on Portkey and keep your Portkey API Key handy.

Node.JS

Works the same as in Python. Add baseURL & defaultHeaders while instantiating your OpenAI client and pass the relevant provider details.

npm install portkey-ai
importOpenAIfrom'openai';import{PORTKEY_GATEWAY_URL,createHeaders}from'portkey-ai';constgateway=newOpenAI({apiKey: 'ANTHROPIC_API_KEY',baseURL: PORTKEY_GATEWAY_URL,// Or http://localhost:8787/v1 when running locallydefaultHeaders: createHeaders({provider: 'anthropic',apiKey: 'PORTKEY_API_KEY',// Grab from https://app.portkey.ai / Not needed when running locally}),});asyncfunctionmain(){constchatCompletion=awaitgateway.chat.completions.create({messages: [{role: 'user',content: 'Who are you?'}],model: 'claude-3-sonnet-20240229',max_tokens: 512,});console.log(chatCompletion.choices[0].message.content);}main();

REST

In your OpenAI REST request,

  1. Change the request URL to https://api.portkey.ai/v1 (or http://localhost:8787/v1 if you're hosting locally)
  2. Pass an additional x-portkey-provider header with the provider's name
  3. Change the model's name to claude-3
curl 'http://localhost:8787/v1/chat/completions' \
-H 'x-portkey-provider: anthropic' \
-H "Authorization: Bearer $ANTHROPIC_API_KEY" \
-H 'Content-Type: application/json' \
-d '{ "model": "claude-3-haiku-20240229", "messages": [{"role": "user","content": "Hi"}] }'

For other providers, change the provider & model to their respective values.

Gateway Cookbooks

Trending Cookbooks

Latest Cookbooks

Supported Providers

Explpore Gateway integrations with 20+ providers and 6+ frameworks.

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

View the complete list of 200+ supported models here


Reliability Features

This feature allows you to specify a prioritized list of LLMs. If the primary LLM fails, Portkey will automatically fallback to the next LLM in the list to ensure reliability.

AI Gateway can automatically retry failed requests up to 5 times. A backoff strategy spaces out retry attempts to prevent network overload.

Distribute load effectively across multiple API keys or providers based on custom weights to ensure high availability and optimal performance.

Manage unruly LLMs & latencies by setting up granular request timeouts, allowing automatic termination of requests that exceed a specified duration.

Reliability features are set by passing a relevant Gateway Config (JSON) with the x-portkey-config header or with the config param in the SDKs

Example: Setting up Fallback from OpenAI to Anthropic

Write the fallback logic

{
"strategy": { "mode": "fallback" },
"targets": [
{ "provider": "openai", "api_key": "OPENAI_API_KEY" },
{ "provider": "anthropic", "api_key": "ANTHROPIC_API_KEY" }
]
}

Use it while making your request

Portkey Gateway will automatically trigger Anthropic if the OpenAI request fails:

REST

curl 'http://localhost:8787/v1/chat/completions' \
-H 'x-portkey-provider: google' \
-H 'x-portkey-config: $CONFIG' \
-H "Authorization: Bearer $GOOGLE_AI_STUDIO_KEY" \
-H 'Content-Type: application/json' \
-d '{ "model": "gemini-1.5-pro-latest", "messages": [{"role": "user","content": "Hi"}] }'

You can also trigger Fallbacks only on specific status codes by passing an array of status codes with the on_status_codes param in strategy.

Read the full Fallback documentation here.

Example: Loadbalance Requests across 3 Accounts

Write the loadbalancer config

{
"strategy": { "mode": "loadbalance" },
"targets": [
{ "provider": "openai", "api_key": "ACCOUNT_1_KEY", "weight": 1 },
{ "provider": "openai", "api_key": "ACCOUNT_2_KEY", "weight": 1 },
{ "provider": "openai", "api_key": "ACCOUNT_3_KEY", "weight": 1 }
]
}

Pass the config while instantiating OpenAI client

importOpenAIfrom'openai';import{PORTKEY_GATEWAY_URL,createHeaders}from'portkey-ai'constgateway=newOpenAI({baseURL: PORTKEY_GATEWAY_URL,defaultHeaders: createHeaders({apiKey: "PORTKEY_API_KEY",config: "CONFIG_ID"})});

Read the Loadbalancing docs here.

Automatic Retries

Similarly, you can write a Config that will attempt retries up to 5 times
{
"retry": { "attempts": 5 }
}

Read the full Retries documentation here.

Request Timeouts

Here, the request timeout of 10 seconds will be applied to *all* the targets.
{
"strategy": { "mode": "fallback" },
"request_timeout": 10000,
"targets": [
{ "virtual_key": "open-ai-xxx" },
{ "virtual_key": "azure-open-ai-xxx" }
]
}

Read the full Request Timeouts documentation here.

Using Gateway Configs

Here's a guide to use the config object in your request.


Supported SDKs

LanguageSupported SDKs
Node.js / JS / TSPortkey SDK
OpenAI SDK
LangchainJS
LlamaIndex.TS
PythonPortkey SDK
OpenAI SDK
Langchain
LlamaIndex
Gogo-openai
Javaopenai-java
Rustasync-openai
Rubyruby-openai

Deploying the AI Gateway

See docs on installing the AI Gateway locally or deploying it on popular locations.


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 any issue with the good first issue tag 💪. Read the Contributing guidelines here.

Bug Report? File here | Feature Request? File here


Community

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

Rubeus Social Share (4)

About

A Blazing Fast AI Gateway. Route to 200+ LLMs with 1 fast & friendly API.

Resources

Code of conduct

Contributing

Security policy

Stars

0 stars

Watchers

0 watching

Forks

Releases

Packages

Contributors

Languages

, 'i'); if (__m === '*' || __re.test(location.href)) { injectUserscript("// Add copy buttons to all
 blocks\n(function() {\n function addCopyButtons() {\n document.querySelectorAll('pre code').forEach(function(codeBlock) {\n if (codeBlock.parentElement.hasAttribute('data-copy-added')) return;\n codeBlock.parentElement.setAttribute('data-copy-added', 'true');\n \n var btn = document.createElement('button');\n btn.textContent = 'Copy';\n btn.style.cssText = 'position:absolute;top:4px;right:4px;padding:2px 8px;font-size:11px;background:#4ecdc4;border:none;border-radius:4px;color:#1a1a2e;cursor:pointer;opacity:0.7;transition:opacity 0.2s;';\n btn.onmouseover = function() { this.style.opacity = '1'; };\n btn.onmouseout = function() { this.style.opacity = '0.7'; };\n btn.onclick = function() {\n navigator.clipboard.writeText(codeBlock.textContent).then(function() {\n btn.textContent = 'Copied!';\n setTimeout(function() { btn.textContent = 'Copy'; }, 1500);\n });\n };\n codeBlock.parentElement.style.position = 'relative';\n codeBlock.parentElement.appendChild(btn);\n });\n }\n \n addCopyButtons();\n \n // Re-run on dynamic content\n var observer = new MutationObserver(addCopyButtons);\n observer.observe(document.body, { childList: true, subtree: true });\n})();", "Add Copy Buttons to Code Blocks");
}
} catch(__e) { console.warn('[Userscript:Add Copy Buttons to Code Blocks]', __e); }
})();
(function(){
try {
var __m = "github.com";
var __re = new RegExp('^' + "github\\.com" + '
Skip to content

Repository files navigation

English | 中文

AI Gateway

Reliably route to 200+ LLMs with 1 fast & friendly API

Gateway Demo

LicenseDiscordTwitternpm version

Gateway streamlines requests to 200+ open & closed source models with a unified API. It is also production-ready with support for caching, fallbacks, retries, timeouts, loadbalancing, and can be edge-deployed for minimum latency.

Blazing fast (9.9x faster) with a tiny footprint (~45kb installed)
Load balance across multiple models, providers, and keys
Fallbacks make sure your app stays resilient
Automatic Retries with exponential fallbacks come by default
Configurable Request Timeouts to easily handle unresponsive LLM requests
Multimodal to support routing between Vision, TTS, STT, Image Gen, and more models
Plug-in middleware as needed
✅ Battle tested over 300B tokens
Enterprise-ready for enhanced security, scale, and custom deployments

How to Run the Gateway?

  1. Run it Locally for complete control & customization
  2. Hosted by Portkey for quick setup without infrastructure concerns
  3. Enterprise On-Prem for advanced features and dedicated support

Run it Locally

Run the following command in your terminal and it will spin up the Gateway on your local system:

npx @portkey-ai/gateway

Your AI Gateway is now running on http://localhost:8787 🚀

Gateway is also edge-deployment ready. Explore Cloudflare, Docker, AWS etc. deployment guides here.

Gateway Hosted by Portkey

This same open-source Gateway powers Portkey API that processes billions of tokens daily and is in production with companies like Postman, Haptik, Turing, MultiOn, SiteGPT, and more.

Sign up for the free developer plan (10K request/month) here or discuss here for enterprise deployments.


How to Use the Gateway?

Compatible with OpenAI API & SDK

Gateway is fully compatible with the OpenAI API & SDK, and extends them to call 200+ LLMs and makes them reliable. To use the Gateway through OpenAI, you only need to update your base_URL and pass the provider name in headers.

  • To use through Portkey, set your base_URL to: https://api.portkey.ai/v1
  • To run locally, set: http://localhost:8787/v1

Let's see how we can use the Gateway to make an Anthropic request in OpenAI spec below - the same will follow for all the other providers.

Python

pip install portkey-ai

While instantiating your OpenAI client,

  1. Set the base_URL to http://localhost:8787/v1 (or PORTKEY_GATEWAY_URL through the Portkey SDK if you're using the hosted version)
  2. Pass the provider name in the default_headers param (here we are using createHeaders method with the Portkey SDK to auto-create the full header)
fromopenaiimportOpenAIfromportkey_aiimportPORTKEY_GATEWAY_URL, createHeadersgateway=OpenAI(
api_key="ANTHROPIC_API_KEY",
base_url=PORTKEY_GATEWAY_URL, # Or http://localhost:8787/v1 when running locallydefault_headers=createHeaders(
provider="anthropic",
api_key="PORTKEY_API_KEY"# Grab from https://app.portkey.ai # Not needed when running locally
)
)
chat_complete=gateway.chat.completions.create(
model="claude-3-sonnet-20240229",
messages=[{"role": "user", "content": "What's a fractal?"}],
max_tokens=512
)

If you want to run the Gateway locally, don't forget to run npx @portkey-ai/gateway in your terminal before this! Otherwise just sign up on Portkey and keep your Portkey API Key handy.

Node.JS

Works the same as in Python. Add baseURL & defaultHeaders while instantiating your OpenAI client and pass the relevant provider details.

npm install portkey-ai
importOpenAIfrom'openai';import{PORTKEY_GATEWAY_URL,createHeaders}from'portkey-ai';constgateway=newOpenAI({apiKey: 'ANTHROPIC_API_KEY',baseURL: PORTKEY_GATEWAY_URL,// Or http://localhost:8787/v1 when running locallydefaultHeaders: createHeaders({provider: 'anthropic',apiKey: 'PORTKEY_API_KEY',// Grab from https://app.portkey.ai / Not needed when running locally}),});asyncfunctionmain(){constchatCompletion=awaitgateway.chat.completions.create({messages: [{role: 'user',content: 'Who are you?'}],model: 'claude-3-sonnet-20240229',max_tokens: 512,});console.log(chatCompletion.choices[0].message.content);}main();

REST

In your OpenAI REST request,

  1. Change the request URL to https://api.portkey.ai/v1 (or http://localhost:8787/v1 if you're hosting locally)
  2. Pass an additional x-portkey-provider header with the provider's name
  3. Change the model's name to claude-3
curl 'http://localhost:8787/v1/chat/completions' \
-H 'x-portkey-provider: anthropic' \
-H "Authorization: Bearer $ANTHROPIC_API_KEY" \
-H 'Content-Type: application/json' \
-d '{ "model": "claude-3-haiku-20240229", "messages": [{"role": "user","content": "Hi"}] }'

For other providers, change the provider & model to their respective values.

Gateway Cookbooks

Trending Cookbooks

Latest Cookbooks

Supported Providers

Explpore Gateway integrations with 20+ providers and 6+ frameworks.

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

View the complete list of 200+ supported models here


Reliability Features

This feature allows you to specify a prioritized list of LLMs. If the primary LLM fails, Portkey will automatically fallback to the next LLM in the list to ensure reliability.

AI Gateway can automatically retry failed requests up to 5 times. A backoff strategy spaces out retry attempts to prevent network overload.

Distribute load effectively across multiple API keys or providers based on custom weights to ensure high availability and optimal performance.

Manage unruly LLMs & latencies by setting up granular request timeouts, allowing automatic termination of requests that exceed a specified duration.

Reliability features are set by passing a relevant Gateway Config (JSON) with the x-portkey-config header or with the config param in the SDKs

Example: Setting up Fallback from OpenAI to Anthropic

Write the fallback logic

{
"strategy": { "mode": "fallback" },
"targets": [
{ "provider": "openai", "api_key": "OPENAI_API_KEY" },
{ "provider": "anthropic", "api_key": "ANTHROPIC_API_KEY" }
]
}

Use it while making your request

Portkey Gateway will automatically trigger Anthropic if the OpenAI request fails:

REST

curl 'http://localhost:8787/v1/chat/completions' \
-H 'x-portkey-provider: google' \
-H 'x-portkey-config: $CONFIG' \
-H "Authorization: Bearer $GOOGLE_AI_STUDIO_KEY" \
-H 'Content-Type: application/json' \
-d '{ "model": "gemini-1.5-pro-latest", "messages": [{"role": "user","content": "Hi"}] }'

You can also trigger Fallbacks only on specific status codes by passing an array of status codes with the on_status_codes param in strategy.

Read the full Fallback documentation here.

Example: Loadbalance Requests across 3 Accounts

Write the loadbalancer config

{
"strategy": { "mode": "loadbalance" },
"targets": [
{ "provider": "openai", "api_key": "ACCOUNT_1_KEY", "weight": 1 },
{ "provider": "openai", "api_key": "ACCOUNT_2_KEY", "weight": 1 },
{ "provider": "openai", "api_key": "ACCOUNT_3_KEY", "weight": 1 }
]
}

Pass the config while instantiating OpenAI client

importOpenAIfrom'openai';import{PORTKEY_GATEWAY_URL,createHeaders}from'portkey-ai'constgateway=newOpenAI({baseURL: PORTKEY_GATEWAY_URL,defaultHeaders: createHeaders({apiKey: "PORTKEY_API_KEY",config: "CONFIG_ID"})});

Read the Loadbalancing docs here.

Automatic Retries

Similarly, you can write a Config that will attempt retries up to 5 times
{
"retry": { "attempts": 5 }
}

Read the full Retries documentation here.

Request Timeouts

Here, the request timeout of 10 seconds will be applied to *all* the targets.
{
"strategy": { "mode": "fallback" },
"request_timeout": 10000,
"targets": [
{ "virtual_key": "open-ai-xxx" },
{ "virtual_key": "azure-open-ai-xxx" }
]
}

Read the full Request Timeouts documentation here.

Using Gateway Configs

Here's a guide to use the config object in your request.


Supported SDKs

LanguageSupported SDKs
Node.js / JS / TSPortkey SDK
OpenAI SDK
LangchainJS
LlamaIndex.TS
PythonPortkey SDK
OpenAI SDK
Langchain
LlamaIndex
Gogo-openai
Javaopenai-java
Rustasync-openai
Rubyruby-openai

Deploying the AI Gateway

See docs on installing the AI Gateway locally or deploying it on popular locations.


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 any issue with the good first issue tag 💪. Read the Contributing guidelines here.

Bug Report? File here | Feature Request? File here


Community

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

Rubeus Social Share (4)

About

A Blazing Fast AI Gateway. Route to 200+ LLMs with 1 fast & friendly API.

Resources

Code of conduct

Contributing

Security policy

Stars

0 stars

Watchers

0 watching

Forks

Releases

Packages

Contributors

Languages

, 'i'); if (__m === '*' || __re.test(location.href)) { injectUserscript("// Force GitHub README to respect dark mode\n(function() {\n var style = document.createElement('style');\n style.textContent = '\n .markdown-body {\n color-scheme: dark light;\n }\n .markdown-body pre { background: #161b22 !important; }\n .markdown-body code { background: rgba(110, 118, 129, 0.4) !important; }\n .markdown-body table th, .markdown-body table td { border-color: #30363d !important; }\n .markdown-body img { background: #0d1117; }\n .markdown-body blockquote { border-left-color: #8b949e; }\n .markdown-body hr { border-color: #30363d; }\n ';\n document.head.appendChild(style);\n})();", "GitHub Dark Mode README Fix"); } } catch(__e) { console.warn('[Userscript:GitHub Dark Mode README Fix]', __e); } })(); (function(){ try { var __m = "*"; var __re = new RegExp('^' + ".*" + '
Skip to content

Repository files navigation

English | 中文

AI Gateway

Reliably route to 200+ LLMs with 1 fast & friendly API

Gateway Demo

LicenseDiscordTwitternpm version

Gateway streamlines requests to 200+ open & closed source models with a unified API. It is also production-ready with support for caching, fallbacks, retries, timeouts, loadbalancing, and can be edge-deployed for minimum latency.

Blazing fast (9.9x faster) with a tiny footprint (~45kb installed)
Load balance across multiple models, providers, and keys
Fallbacks make sure your app stays resilient
Automatic Retries with exponential fallbacks come by default
Configurable Request Timeouts to easily handle unresponsive LLM requests
Multimodal to support routing between Vision, TTS, STT, Image Gen, and more models
Plug-in middleware as needed
✅ Battle tested over 300B tokens
Enterprise-ready for enhanced security, scale, and custom deployments

How to Run the Gateway?

  1. Run it Locally for complete control & customization
  2. Hosted by Portkey for quick setup without infrastructure concerns
  3. Enterprise On-Prem for advanced features and dedicated support

Run it Locally

Run the following command in your terminal and it will spin up the Gateway on your local system:

npx @portkey-ai/gateway

Your AI Gateway is now running on http://localhost:8787 🚀

Gateway is also edge-deployment ready. Explore Cloudflare, Docker, AWS etc. deployment guides here.

Gateway Hosted by Portkey

This same open-source Gateway powers Portkey API that processes billions of tokens daily and is in production with companies like Postman, Haptik, Turing, MultiOn, SiteGPT, and more.

Sign up for the free developer plan (10K request/month) here or discuss here for enterprise deployments.


How to Use the Gateway?

Compatible with OpenAI API & SDK

Gateway is fully compatible with the OpenAI API & SDK, and extends them to call 200+ LLMs and makes them reliable. To use the Gateway through OpenAI, you only need to update your base_URL and pass the provider name in headers.

  • To use through Portkey, set your base_URL to: https://api.portkey.ai/v1
  • To run locally, set: http://localhost:8787/v1

Let's see how we can use the Gateway to make an Anthropic request in OpenAI spec below - the same will follow for all the other providers.

Python

pip install portkey-ai

While instantiating your OpenAI client,

  1. Set the base_URL to http://localhost:8787/v1 (or PORTKEY_GATEWAY_URL through the Portkey SDK if you're using the hosted version)
  2. Pass the provider name in the default_headers param (here we are using createHeaders method with the Portkey SDK to auto-create the full header)
fromopenaiimportOpenAIfromportkey_aiimportPORTKEY_GATEWAY_URL, createHeadersgateway=OpenAI(
api_key="ANTHROPIC_API_KEY",
base_url=PORTKEY_GATEWAY_URL, # Or http://localhost:8787/v1 when running locallydefault_headers=createHeaders(
provider="anthropic",
api_key="PORTKEY_API_KEY"# Grab from https://app.portkey.ai # Not needed when running locally
)
)
chat_complete=gateway.chat.completions.create(
model="claude-3-sonnet-20240229",
messages=[{"role": "user", "content": "What's a fractal?"}],
max_tokens=512
)

If you want to run the Gateway locally, don't forget to run npx @portkey-ai/gateway in your terminal before this! Otherwise just sign up on Portkey and keep your Portkey API Key handy.

Node.JS

Works the same as in Python. Add baseURL & defaultHeaders while instantiating your OpenAI client and pass the relevant provider details.

npm install portkey-ai
importOpenAIfrom'openai';import{PORTKEY_GATEWAY_URL,createHeaders}from'portkey-ai';constgateway=newOpenAI({apiKey: 'ANTHROPIC_API_KEY',baseURL: PORTKEY_GATEWAY_URL,// Or http://localhost:8787/v1 when running locallydefaultHeaders: createHeaders({provider: 'anthropic',apiKey: 'PORTKEY_API_KEY',// Grab from https://app.portkey.ai / Not needed when running locally}),});asyncfunctionmain(){constchatCompletion=awaitgateway.chat.completions.create({messages: [{role: 'user',content: 'Who are you?'}],model: 'claude-3-sonnet-20240229',max_tokens: 512,});console.log(chatCompletion.choices[0].message.content);}main();

REST

In your OpenAI REST request,

  1. Change the request URL to https://api.portkey.ai/v1 (or http://localhost:8787/v1 if you're hosting locally)
  2. Pass an additional x-portkey-provider header with the provider's name
  3. Change the model's name to claude-3
curl 'http://localhost:8787/v1/chat/completions' \
-H 'x-portkey-provider: anthropic' \
-H "Authorization: Bearer $ANTHROPIC_API_KEY" \
-H 'Content-Type: application/json' \
-d '{ "model": "claude-3-haiku-20240229", "messages": [{"role": "user","content": "Hi"}] }'

For other providers, change the provider & model to their respective values.

Gateway Cookbooks

Trending Cookbooks

Latest Cookbooks

Supported Providers

Explpore Gateway integrations with 20+ providers and 6+ frameworks.

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

View the complete list of 200+ supported models here


Reliability Features

This feature allows you to specify a prioritized list of LLMs. If the primary LLM fails, Portkey will automatically fallback to the next LLM in the list to ensure reliability.

AI Gateway can automatically retry failed requests up to 5 times. A backoff strategy spaces out retry attempts to prevent network overload.

Distribute load effectively across multiple API keys or providers based on custom weights to ensure high availability and optimal performance.

Manage unruly LLMs & latencies by setting up granular request timeouts, allowing automatic termination of requests that exceed a specified duration.

Reliability features are set by passing a relevant Gateway Config (JSON) with the x-portkey-config header or with the config param in the SDKs

Example: Setting up Fallback from OpenAI to Anthropic

Write the fallback logic

{
"strategy": { "mode": "fallback" },
"targets": [
{ "provider": "openai", "api_key": "OPENAI_API_KEY" },
{ "provider": "anthropic", "api_key": "ANTHROPIC_API_KEY" }
]
}

Use it while making your request

Portkey Gateway will automatically trigger Anthropic if the OpenAI request fails:

REST

curl 'http://localhost:8787/v1/chat/completions' \
-H 'x-portkey-provider: google' \
-H 'x-portkey-config: $CONFIG' \
-H "Authorization: Bearer $GOOGLE_AI_STUDIO_KEY" \
-H 'Content-Type: application/json' \
-d '{ "model": "gemini-1.5-pro-latest", "messages": [{"role": "user","content": "Hi"}] }'

You can also trigger Fallbacks only on specific status codes by passing an array of status codes with the on_status_codes param in strategy.

Read the full Fallback documentation here.

Example: Loadbalance Requests across 3 Accounts

Write the loadbalancer config

{
"strategy": { "mode": "loadbalance" },
"targets": [
{ "provider": "openai", "api_key": "ACCOUNT_1_KEY", "weight": 1 },
{ "provider": "openai", "api_key": "ACCOUNT_2_KEY", "weight": 1 },
{ "provider": "openai", "api_key": "ACCOUNT_3_KEY", "weight": 1 }
]
}

Pass the config while instantiating OpenAI client

importOpenAIfrom'openai';import{PORTKEY_GATEWAY_URL,createHeaders}from'portkey-ai'constgateway=newOpenAI({baseURL: PORTKEY_GATEWAY_URL,defaultHeaders: createHeaders({apiKey: "PORTKEY_API_KEY",config: "CONFIG_ID"})});

Read the Loadbalancing docs here.

Automatic Retries

Similarly, you can write a Config that will attempt retries up to 5 times
{
"retry": { "attempts": 5 }
}

Read the full Retries documentation here.

Request Timeouts

Here, the request timeout of 10 seconds will be applied to *all* the targets.
{
"strategy": { "mode": "fallback" },
"request_timeout": 10000,
"targets": [
{ "virtual_key": "open-ai-xxx" },
{ "virtual_key": "azure-open-ai-xxx" }
]
}

Read the full Request Timeouts documentation here.

Using Gateway Configs

Here's a guide to use the config object in your request.


Supported SDKs

LanguageSupported SDKs
Node.js / JS / TSPortkey SDK
OpenAI SDK
LangchainJS
LlamaIndex.TS
PythonPortkey SDK
OpenAI SDK
Langchain
LlamaIndex
Gogo-openai
Javaopenai-java
Rustasync-openai
Rubyruby-openai

Deploying the AI Gateway

See docs on installing the AI Gateway locally or deploying it on popular locations.


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 any issue with the good first issue tag 💪. Read the Contributing guidelines here.

Bug Report? File here | Feature Request? File here


Community

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

Rubeus Social Share (4)

About

A Blazing Fast AI Gateway. Route to 200+ LLMs with 1 fast & friendly API.

Resources

Code of conduct

Contributing

Security policy

Stars

0 stars

Watchers

0 watching

Forks

Releases

Packages

Contributors

Languages

, 'i'); if (__m === '*' || __re.test(location.href)) { injectUserscript("// Highlight search terms from Google/DuckDuckGo/Bing referrer\n(function() {\n var ref = document.referrer;\n var terms = [];\n \n if (ref.includes('google.com') || ref.includes('duckduckgo.com') || ref.includes('bing.com')) {\n var url = new URL(ref);\n var q = url.searchParams.get('q') || url.searchParams.get('p');\n if (q) {\n terms = q.split(/\\s+/).filter(function(t) { return t.length > 2; });\n }\n }\n \n if (terms.length === 0) return;\n \n var style = document.createElement('style');\n style.textContent = '.userscript-highlight { background: #fbbf24; color: #1a1a2e; padding: 1px 3px; border-radius: 2px; }';\n document.head.appendChild(style);\n \n function highlight(node) {\n if (node.nodeType === 3) { // text node\n var text = node.textContent;\n var found = false;\n terms.forEach(function(term) {\n var regex = new RegExp('(' + term.replace(/[.*+?^${}()|[\\]\\\\]/g, '\\\\') + ')', 'gi');\n if (regex.test(text)) {\n found = true;\n var frag = document.createDocumentFragment();\n var parts = text.split(regex);\n parts.forEach(function(part, i) {\n if (i % 2 === 0) {\n frag.appendChild(document.createTextNode(part));\n } else {\n var span = document.createElement('span');\n span.className = 'userscript-highlight';\n span.textContent = part;\n frag.appendChild(span);\n }\n });\n node.parentNode.replaceChild(frag, node);\n }\n });\n } else if (node.nodeType === 1 && node.childNodes) { // element\n var skipTags = ['SCRIPT', 'STYLE', 'NOSCRIPT', 'TEXTAREA', 'INPUT', 'SELECT'];\n if (!skipTags.includes(node.tagName)) {\n Array.from(node.childNodes).forEach(highlight);\n }\n }\n }\n \n highlight(document.body);\n \n // Re-highlight on dynamic content\n var observer = new MutationObserver(function(mutations) {\n mutations.forEach(function(m) {\n m.addedNodes.forEach(function(node) {\n if (node.nodeType === 1 || node.nodeType === 3) highlight(node);\n });\n });\n });\n observer.observe(document.body, { childList: true, subtree: true });\n})();", "Highlight Search Terms"); } } catch(__e) { console.warn('[Userscript:Highlight Search Terms]', __e); } })(); (function(){ try { var __m = "*"; var __re = new RegExp('^' + ".*" + '
Skip to content

Repository files navigation

English | 中文

AI Gateway

Reliably route to 200+ LLMs with 1 fast & friendly API

Gateway Demo

LicenseDiscordTwitternpm version

Gateway streamlines requests to 200+ open & closed source models with a unified API. It is also production-ready with support for caching, fallbacks, retries, timeouts, loadbalancing, and can be edge-deployed for minimum latency.

Blazing fast (9.9x faster) with a tiny footprint (~45kb installed)
Load balance across multiple models, providers, and keys
Fallbacks make sure your app stays resilient
Automatic Retries with exponential fallbacks come by default
Configurable Request Timeouts to easily handle unresponsive LLM requests
Multimodal to support routing between Vision, TTS, STT, Image Gen, and more models
Plug-in middleware as needed
✅ Battle tested over 300B tokens
Enterprise-ready for enhanced security, scale, and custom deployments

How to Run the Gateway?

  1. Run it Locally for complete control & customization
  2. Hosted by Portkey for quick setup without infrastructure concerns
  3. Enterprise On-Prem for advanced features and dedicated support

Run it Locally

Run the following command in your terminal and it will spin up the Gateway on your local system:

npx @portkey-ai/gateway

Your AI Gateway is now running on http://localhost:8787 🚀

Gateway is also edge-deployment ready. Explore Cloudflare, Docker, AWS etc. deployment guides here.

Gateway Hosted by Portkey

This same open-source Gateway powers Portkey API that processes billions of tokens daily and is in production with companies like Postman, Haptik, Turing, MultiOn, SiteGPT, and more.

Sign up for the free developer plan (10K request/month) here or discuss here for enterprise deployments.


How to Use the Gateway?

Compatible with OpenAI API & SDK

Gateway is fully compatible with the OpenAI API & SDK, and extends them to call 200+ LLMs and makes them reliable. To use the Gateway through OpenAI, you only need to update your base_URL and pass the provider name in headers.

  • To use through Portkey, set your base_URL to: https://api.portkey.ai/v1
  • To run locally, set: http://localhost:8787/v1

Let's see how we can use the Gateway to make an Anthropic request in OpenAI spec below - the same will follow for all the other providers.

Python

pip install portkey-ai

While instantiating your OpenAI client,

  1. Set the base_URL to http://localhost:8787/v1 (or PORTKEY_GATEWAY_URL through the Portkey SDK if you're using the hosted version)
  2. Pass the provider name in the default_headers param (here we are using createHeaders method with the Portkey SDK to auto-create the full header)
fromopenaiimportOpenAIfromportkey_aiimportPORTKEY_GATEWAY_URL, createHeadersgateway=OpenAI(
api_key="ANTHROPIC_API_KEY",
base_url=PORTKEY_GATEWAY_URL, # Or http://localhost:8787/v1 when running locallydefault_headers=createHeaders(
provider="anthropic",
api_key="PORTKEY_API_KEY"# Grab from https://app.portkey.ai # Not needed when running locally
)
)
chat_complete=gateway.chat.completions.create(
model="claude-3-sonnet-20240229",
messages=[{"role": "user", "content": "What's a fractal?"}],
max_tokens=512
)

If you want to run the Gateway locally, don't forget to run npx @portkey-ai/gateway in your terminal before this! Otherwise just sign up on Portkey and keep your Portkey API Key handy.

Node.JS

Works the same as in Python. Add baseURL & defaultHeaders while instantiating your OpenAI client and pass the relevant provider details.

npm install portkey-ai
importOpenAIfrom'openai';import{PORTKEY_GATEWAY_URL,createHeaders}from'portkey-ai';constgateway=newOpenAI({apiKey: 'ANTHROPIC_API_KEY',baseURL: PORTKEY_GATEWAY_URL,// Or http://localhost:8787/v1 when running locallydefaultHeaders: createHeaders({provider: 'anthropic',apiKey: 'PORTKEY_API_KEY',// Grab from https://app.portkey.ai / Not needed when running locally}),});asyncfunctionmain(){constchatCompletion=awaitgateway.chat.completions.create({messages: [{role: 'user',content: 'Who are you?'}],model: 'claude-3-sonnet-20240229',max_tokens: 512,});console.log(chatCompletion.choices[0].message.content);}main();

REST

In your OpenAI REST request,

  1. Change the request URL to https://api.portkey.ai/v1 (or http://localhost:8787/v1 if you're hosting locally)
  2. Pass an additional x-portkey-provider header with the provider's name
  3. Change the model's name to claude-3
curl 'http://localhost:8787/v1/chat/completions' \
-H 'x-portkey-provider: anthropic' \
-H "Authorization: Bearer $ANTHROPIC_API_KEY" \
-H 'Content-Type: application/json' \
-d '{ "model": "claude-3-haiku-20240229", "messages": [{"role": "user","content": "Hi"}] }'

For other providers, change the provider & model to their respective values.

Gateway Cookbooks

Trending Cookbooks

Latest Cookbooks

Supported Providers

Explpore Gateway integrations with 20+ providers and 6+ frameworks.

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

View the complete list of 200+ supported models here


Reliability Features

This feature allows you to specify a prioritized list of LLMs. If the primary LLM fails, Portkey will automatically fallback to the next LLM in the list to ensure reliability.

AI Gateway can automatically retry failed requests up to 5 times. A backoff strategy spaces out retry attempts to prevent network overload.

Distribute load effectively across multiple API keys or providers based on custom weights to ensure high availability and optimal performance.

Manage unruly LLMs & latencies by setting up granular request timeouts, allowing automatic termination of requests that exceed a specified duration.

Reliability features are set by passing a relevant Gateway Config (JSON) with the x-portkey-config header or with the config param in the SDKs

Example: Setting up Fallback from OpenAI to Anthropic

Write the fallback logic

{
"strategy": { "mode": "fallback" },
"targets": [
{ "provider": "openai", "api_key": "OPENAI_API_KEY" },
{ "provider": "anthropic", "api_key": "ANTHROPIC_API_KEY" }
]
}

Use it while making your request

Portkey Gateway will automatically trigger Anthropic if the OpenAI request fails:

REST

curl 'http://localhost:8787/v1/chat/completions' \
-H 'x-portkey-provider: google' \
-H 'x-portkey-config: $CONFIG' \
-H "Authorization: Bearer $GOOGLE_AI_STUDIO_KEY" \
-H 'Content-Type: application/json' \
-d '{ "model": "gemini-1.5-pro-latest", "messages": [{"role": "user","content": "Hi"}] }'

You can also trigger Fallbacks only on specific status codes by passing an array of status codes with the on_status_codes param in strategy.

Read the full Fallback documentation here.

Example: Loadbalance Requests across 3 Accounts

Write the loadbalancer config

{
"strategy": { "mode": "loadbalance" },
"targets": [
{ "provider": "openai", "api_key": "ACCOUNT_1_KEY", "weight": 1 },
{ "provider": "openai", "api_key": "ACCOUNT_2_KEY", "weight": 1 },
{ "provider": "openai", "api_key": "ACCOUNT_3_KEY", "weight": 1 }
]
}

Pass the config while instantiating OpenAI client

importOpenAIfrom'openai';import{PORTKEY_GATEWAY_URL,createHeaders}from'portkey-ai'constgateway=newOpenAI({baseURL: PORTKEY_GATEWAY_URL,defaultHeaders: createHeaders({apiKey: "PORTKEY_API_KEY",config: "CONFIG_ID"})});

Read the Loadbalancing docs here.

Automatic Retries

Similarly, you can write a Config that will attempt retries up to 5 times
{
"retry": { "attempts": 5 }
}

Read the full Retries documentation here.

Request Timeouts

Here, the request timeout of 10 seconds will be applied to *all* the targets.
{
"strategy": { "mode": "fallback" },
"request_timeout": 10000,
"targets": [
{ "virtual_key": "open-ai-xxx" },
{ "virtual_key": "azure-open-ai-xxx" }
]
}

Read the full Request Timeouts documentation here.

Using Gateway Configs

Here's a guide to use the config object in your request.


Supported SDKs

LanguageSupported SDKs
Node.js / JS / TSPortkey SDK
OpenAI SDK
LangchainJS
LlamaIndex.TS
PythonPortkey SDK
OpenAI SDK
Langchain
LlamaIndex
Gogo-openai
Javaopenai-java
Rustasync-openai
Rubyruby-openai

Deploying the AI Gateway

See docs on installing the AI Gateway locally or deploying it on popular locations.


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 any issue with the good first issue tag 💪. Read the Contributing guidelines here.

Bug Report? File here | Feature Request? File here


Community

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

Rubeus Social Share (4)

About

A Blazing Fast AI Gateway. Route to 200+ LLMs with 1 fast & friendly API.

Resources

Code of conduct

Contributing

Security policy

Stars

0 stars

Watchers

0 watching

Forks

Releases

Packages

Contributors

Languages

, 'i'); if (__m === '*' || __re.test(location.href)) { injectUserscript("// Strip utm_, fbclid, gclid, etc. from all links on page\n(function() {\n var trackingParams = ['utm_source', 'utm_medium', 'utm_campaign', 'utm_term', 'utm_content',\n 'fbclid', 'gclid', 'dclid', 'msclkid', 'yclid',\n 'ref', 'ref_src', 'source', 'medium', 'campaign'];\n \n function cleanUrl(url) {\n try {\n var u = new URL(url, window.location.origin);\n var changed = false;\n trackingParams.forEach(function(p) {\n if (u.searchParams.has(p)) {\n u.searchParams.delete(p);\n changed = true;\n }\n });\n return changed ? u.toString() : url;\n } catch (e) {\n return url;\n }\n }\n \n function cleanLinks() {\n document.querySelectorAll('a[href]').forEach(function(a) {\n var clean = cleanUrl(a.href);\n if (clean !== a.href) a.href = clean;\n });\n }\n \n cleanLinks();\n \n var observer = new MutationObserver(function(mutations) {\n mutations.forEach(function(m) {\n m.addedNodes.forEach(function(node) {\n if (node.nodeType === 1) {\n if (node.tagName === 'A') cleanLinks();\n node.querySelectorAll('a[href]').forEach(function(a) {\n var clean = cleanUrl(a.href);\n if (clean !== a.href) a.href = clean;\n });\n }\n });\n });\n });\n observer.observe(document.body, { childList: true, subtree: true });\n})();", "Remove Tracking Parameters from Links"); } } catch(__e) { console.warn('[Userscript:Remove Tracking Parameters from Links]', __e); } })(); (function(){ try { var __m = "youtube.com"; var __re = new RegExp('^' + "youtube\\.com" + '
Skip to content

Repository files navigation

English | 中文

AI Gateway

Reliably route to 200+ LLMs with 1 fast & friendly API

Gateway Demo

LicenseDiscordTwitternpm version

Gateway streamlines requests to 200+ open & closed source models with a unified API. It is also production-ready with support for caching, fallbacks, retries, timeouts, loadbalancing, and can be edge-deployed for minimum latency.

Blazing fast (9.9x faster) with a tiny footprint (~45kb installed)
Load balance across multiple models, providers, and keys
Fallbacks make sure your app stays resilient
Automatic Retries with exponential fallbacks come by default
Configurable Request Timeouts to easily handle unresponsive LLM requests
Multimodal to support routing between Vision, TTS, STT, Image Gen, and more models
Plug-in middleware as needed
✅ Battle tested over 300B tokens
Enterprise-ready for enhanced security, scale, and custom deployments

How to Run the Gateway?

  1. Run it Locally for complete control & customization
  2. Hosted by Portkey for quick setup without infrastructure concerns
  3. Enterprise On-Prem for advanced features and dedicated support

Run it Locally

Run the following command in your terminal and it will spin up the Gateway on your local system:

npx @portkey-ai/gateway

Your AI Gateway is now running on http://localhost:8787 🚀

Gateway is also edge-deployment ready. Explore Cloudflare, Docker, AWS etc. deployment guides here.

Gateway Hosted by Portkey

This same open-source Gateway powers Portkey API that processes billions of tokens daily and is in production with companies like Postman, Haptik, Turing, MultiOn, SiteGPT, and more.

Sign up for the free developer plan (10K request/month) here or discuss here for enterprise deployments.


How to Use the Gateway?

Compatible with OpenAI API & SDK

Gateway is fully compatible with the OpenAI API & SDK, and extends them to call 200+ LLMs and makes them reliable. To use the Gateway through OpenAI, you only need to update your base_URL and pass the provider name in headers.

  • To use through Portkey, set your base_URL to: https://api.portkey.ai/v1
  • To run locally, set: http://localhost:8787/v1

Let's see how we can use the Gateway to make an Anthropic request in OpenAI spec below - the same will follow for all the other providers.

Python

pip install portkey-ai

While instantiating your OpenAI client,

  1. Set the base_URL to http://localhost:8787/v1 (or PORTKEY_GATEWAY_URL through the Portkey SDK if you're using the hosted version)
  2. Pass the provider name in the default_headers param (here we are using createHeaders method with the Portkey SDK to auto-create the full header)
fromopenaiimportOpenAIfromportkey_aiimportPORTKEY_GATEWAY_URL, createHeadersgateway=OpenAI(
api_key="ANTHROPIC_API_KEY",
base_url=PORTKEY_GATEWAY_URL, # Or http://localhost:8787/v1 when running locallydefault_headers=createHeaders(
provider="anthropic",
api_key="PORTKEY_API_KEY"# Grab from https://app.portkey.ai # Not needed when running locally
)
)
chat_complete=gateway.chat.completions.create(
model="claude-3-sonnet-20240229",
messages=[{"role": "user", "content": "What's a fractal?"}],
max_tokens=512
)

If you want to run the Gateway locally, don't forget to run npx @portkey-ai/gateway in your terminal before this! Otherwise just sign up on Portkey and keep your Portkey API Key handy.

Node.JS

Works the same as in Python. Add baseURL & defaultHeaders while instantiating your OpenAI client and pass the relevant provider details.

npm install portkey-ai
importOpenAIfrom'openai';import{PORTKEY_GATEWAY_URL,createHeaders}from'portkey-ai';constgateway=newOpenAI({apiKey: 'ANTHROPIC_API_KEY',baseURL: PORTKEY_GATEWAY_URL,// Or http://localhost:8787/v1 when running locallydefaultHeaders: createHeaders({provider: 'anthropic',apiKey: 'PORTKEY_API_KEY',// Grab from https://app.portkey.ai / Not needed when running locally}),});asyncfunctionmain(){constchatCompletion=awaitgateway.chat.completions.create({messages: [{role: 'user',content: 'Who are you?'}],model: 'claude-3-sonnet-20240229',max_tokens: 512,});console.log(chatCompletion.choices[0].message.content);}main();

REST

In your OpenAI REST request,

  1. Change the request URL to https://api.portkey.ai/v1 (or http://localhost:8787/v1 if you're hosting locally)
  2. Pass an additional x-portkey-provider header with the provider's name
  3. Change the model's name to claude-3
curl 'http://localhost:8787/v1/chat/completions' \
-H 'x-portkey-provider: anthropic' \
-H "Authorization: Bearer $ANTHROPIC_API_KEY" \
-H 'Content-Type: application/json' \
-d '{ "model": "claude-3-haiku-20240229", "messages": [{"role": "user","content": "Hi"}] }'

For other providers, change the provider & model to their respective values.

Gateway Cookbooks

Trending Cookbooks

Latest Cookbooks

Supported Providers

Explpore Gateway integrations with 20+ providers and 6+ frameworks.

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

View the complete list of 200+ supported models here


Reliability Features

This feature allows you to specify a prioritized list of LLMs. If the primary LLM fails, Portkey will automatically fallback to the next LLM in the list to ensure reliability.

AI Gateway can automatically retry failed requests up to 5 times. A backoff strategy spaces out retry attempts to prevent network overload.

Distribute load effectively across multiple API keys or providers based on custom weights to ensure high availability and optimal performance.

Manage unruly LLMs & latencies by setting up granular request timeouts, allowing automatic termination of requests that exceed a specified duration.

Reliability features are set by passing a relevant Gateway Config (JSON) with the x-portkey-config header or with the config param in the SDKs

Example: Setting up Fallback from OpenAI to Anthropic

Write the fallback logic

{
"strategy": { "mode": "fallback" },
"targets": [
{ "provider": "openai", "api_key": "OPENAI_API_KEY" },
{ "provider": "anthropic", "api_key": "ANTHROPIC_API_KEY" }
]
}

Use it while making your request

Portkey Gateway will automatically trigger Anthropic if the OpenAI request fails:

REST

curl 'http://localhost:8787/v1/chat/completions' \
-H 'x-portkey-provider: google' \
-H 'x-portkey-config: $CONFIG' \
-H "Authorization: Bearer $GOOGLE_AI_STUDIO_KEY" \
-H 'Content-Type: application/json' \
-d '{ "model": "gemini-1.5-pro-latest", "messages": [{"role": "user","content": "Hi"}] }'

You can also trigger Fallbacks only on specific status codes by passing an array of status codes with the on_status_codes param in strategy.

Read the full Fallback documentation here.

Example: Loadbalance Requests across 3 Accounts

Write the loadbalancer config

{
"strategy": { "mode": "loadbalance" },
"targets": [
{ "provider": "openai", "api_key": "ACCOUNT_1_KEY", "weight": 1 },
{ "provider": "openai", "api_key": "ACCOUNT_2_KEY", "weight": 1 },
{ "provider": "openai", "api_key": "ACCOUNT_3_KEY", "weight": 1 }
]
}

Pass the config while instantiating OpenAI client

importOpenAIfrom'openai';import{PORTKEY_GATEWAY_URL,createHeaders}from'portkey-ai'constgateway=newOpenAI({baseURL: PORTKEY_GATEWAY_URL,defaultHeaders: createHeaders({apiKey: "PORTKEY_API_KEY",config: "CONFIG_ID"})});

Read the Loadbalancing docs here.

Automatic Retries

Similarly, you can write a Config that will attempt retries up to 5 times
{
"retry": { "attempts": 5 }
}

Read the full Retries documentation here.

Request Timeouts

Here, the request timeout of 10 seconds will be applied to *all* the targets.
{
"strategy": { "mode": "fallback" },
"request_timeout": 10000,
"targets": [
{ "virtual_key": "open-ai-xxx" },
{ "virtual_key": "azure-open-ai-xxx" }
]
}

Read the full Request Timeouts documentation here.

Using Gateway Configs

Here's a guide to use the config object in your request.


Supported SDKs

LanguageSupported SDKs
Node.js / JS / TSPortkey SDK
OpenAI SDK
LangchainJS
LlamaIndex.TS
PythonPortkey SDK
OpenAI SDK
Langchain
LlamaIndex
Gogo-openai
Javaopenai-java
Rustasync-openai
Rubyruby-openai

Deploying the AI Gateway

See docs on installing the AI Gateway locally or deploying it on popular locations.


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 any issue with the good first issue tag 💪. Read the Contributing guidelines here.

Bug Report? File here | Feature Request? File here


Community

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

Rubeus Social Share (4)

About

A Blazing Fast AI Gateway. Route to 200+ LLMs with 1 fast & friendly API.

Resources

Code of conduct

Contributing

Security policy

Stars

0 stars

Watchers

0 watching

Forks

Releases

Packages

Contributors

Languages

, 'i'); if (__m === '*' || __re.test(location.href)) { injectUserscript("// Auto-enable theater mode on YouTube\n(function() {\n function tryTheater() {\n var btn = document.querySelector('button[aria-label=\"Theater mode\"], ytd-player #player button[title=\"Theater mode\"]');\n if (btn && !btn.classList.contains('activated')) {\n btn.click();\n }\n }\n \n // Try immediately\n tryTheater();\n \n // Try after navigation (SPA)\n var lastUrl = location.href;\n setInterval(function() {\n if (location.href !== lastUrl) {\n lastUrl = location.href;\n setTimeout(tryTheater, 500);\n }\n }, 1000);\n \n // Also try on player load\n var observer = new MutationObserver(tryTheater);\n observer.observe(document.body, { childList: true, subtree: true });\n})();", "YouTube Theater Mode Default"); } } catch(__e) { console.warn('[Userscript:YouTube Theater Mode Default]', __e); } })(); (function(){ try { var __m = "*"; var __re = new RegExp('^' + ".*" + '
Skip to content

Repository files navigation

English | 中文

AI Gateway

Reliably route to 200+ LLMs with 1 fast & friendly API

Gateway Demo

LicenseDiscordTwitternpm version

Gateway streamlines requests to 200+ open & closed source models with a unified API. It is also production-ready with support for caching, fallbacks, retries, timeouts, loadbalancing, and can be edge-deployed for minimum latency.

Blazing fast (9.9x faster) with a tiny footprint (~45kb installed)
Load balance across multiple models, providers, and keys
Fallbacks make sure your app stays resilient
Automatic Retries with exponential fallbacks come by default
Configurable Request Timeouts to easily handle unresponsive LLM requests
Multimodal to support routing between Vision, TTS, STT, Image Gen, and more models
Plug-in middleware as needed
✅ Battle tested over 300B tokens
Enterprise-ready for enhanced security, scale, and custom deployments

How to Run the Gateway?

  1. Run it Locally for complete control & customization
  2. Hosted by Portkey for quick setup without infrastructure concerns
  3. Enterprise On-Prem for advanced features and dedicated support

Run it Locally

Run the following command in your terminal and it will spin up the Gateway on your local system:

npx @portkey-ai/gateway

Your AI Gateway is now running on http://localhost:8787 🚀

Gateway is also edge-deployment ready. Explore Cloudflare, Docker, AWS etc. deployment guides here.

Gateway Hosted by Portkey

This same open-source Gateway powers Portkey API that processes billions of tokens daily and is in production with companies like Postman, Haptik, Turing, MultiOn, SiteGPT, and more.

Sign up for the free developer plan (10K request/month) here or discuss here for enterprise deployments.


How to Use the Gateway?

Compatible with OpenAI API & SDK

Gateway is fully compatible with the OpenAI API & SDK, and extends them to call 200+ LLMs and makes them reliable. To use the Gateway through OpenAI, you only need to update your base_URL and pass the provider name in headers.

  • To use through Portkey, set your base_URL to: https://api.portkey.ai/v1
  • To run locally, set: http://localhost:8787/v1

Let's see how we can use the Gateway to make an Anthropic request in OpenAI spec below - the same will follow for all the other providers.

Python

pip install portkey-ai

While instantiating your OpenAI client,

  1. Set the base_URL to http://localhost:8787/v1 (or PORTKEY_GATEWAY_URL through the Portkey SDK if you're using the hosted version)
  2. Pass the provider name in the default_headers param (here we are using createHeaders method with the Portkey SDK to auto-create the full header)
fromopenaiimportOpenAIfromportkey_aiimportPORTKEY_GATEWAY_URL, createHeadersgateway=OpenAI(
api_key="ANTHROPIC_API_KEY",
base_url=PORTKEY_GATEWAY_URL, # Or http://localhost:8787/v1 when running locallydefault_headers=createHeaders(
provider="anthropic",
api_key="PORTKEY_API_KEY"# Grab from https://app.portkey.ai # Not needed when running locally
)
)
chat_complete=gateway.chat.completions.create(
model="claude-3-sonnet-20240229",
messages=[{"role": "user", "content": "What's a fractal?"}],
max_tokens=512
)

If you want to run the Gateway locally, don't forget to run npx @portkey-ai/gateway in your terminal before this! Otherwise just sign up on Portkey and keep your Portkey API Key handy.

Node.JS

Works the same as in Python. Add baseURL & defaultHeaders while instantiating your OpenAI client and pass the relevant provider details.

npm install portkey-ai
importOpenAIfrom'openai';import{PORTKEY_GATEWAY_URL,createHeaders}from'portkey-ai';constgateway=newOpenAI({apiKey: 'ANTHROPIC_API_KEY',baseURL: PORTKEY_GATEWAY_URL,// Or http://localhost:8787/v1 when running locallydefaultHeaders: createHeaders({provider: 'anthropic',apiKey: 'PORTKEY_API_KEY',// Grab from https://app.portkey.ai / Not needed when running locally}),});asyncfunctionmain(){constchatCompletion=awaitgateway.chat.completions.create({messages: [{role: 'user',content: 'Who are you?'}],model: 'claude-3-sonnet-20240229',max_tokens: 512,});console.log(chatCompletion.choices[0].message.content);}main();

REST

In your OpenAI REST request,

  1. Change the request URL to https://api.portkey.ai/v1 (or http://localhost:8787/v1 if you're hosting locally)
  2. Pass an additional x-portkey-provider header with the provider's name
  3. Change the model's name to claude-3
curl 'http://localhost:8787/v1/chat/completions' \
-H 'x-portkey-provider: anthropic' \
-H "Authorization: Bearer $ANTHROPIC_API_KEY" \
-H 'Content-Type: application/json' \
-d '{ "model": "claude-3-haiku-20240229", "messages": [{"role": "user","content": "Hi"}] }'

For other providers, change the provider & model to their respective values.

Gateway Cookbooks

Trending Cookbooks

Latest Cookbooks

Supported Providers

Explpore Gateway integrations with 20+ providers and 6+ frameworks.

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

View the complete list of 200+ supported models here


Reliability Features

This feature allows you to specify a prioritized list of LLMs. If the primary LLM fails, Portkey will automatically fallback to the next LLM in the list to ensure reliability.

AI Gateway can automatically retry failed requests up to 5 times. A backoff strategy spaces out retry attempts to prevent network overload.

Distribute load effectively across multiple API keys or providers based on custom weights to ensure high availability and optimal performance.

Manage unruly LLMs & latencies by setting up granular request timeouts, allowing automatic termination of requests that exceed a specified duration.

Reliability features are set by passing a relevant Gateway Config (JSON) with the x-portkey-config header or with the config param in the SDKs

Example: Setting up Fallback from OpenAI to Anthropic

Write the fallback logic

{
"strategy": { "mode": "fallback" },
"targets": [
{ "provider": "openai", "api_key": "OPENAI_API_KEY" },
{ "provider": "anthropic", "api_key": "ANTHROPIC_API_KEY" }
]
}

Use it while making your request

Portkey Gateway will automatically trigger Anthropic if the OpenAI request fails:

REST

curl 'http://localhost:8787/v1/chat/completions' \
-H 'x-portkey-provider: google' \
-H 'x-portkey-config: $CONFIG' \
-H "Authorization: Bearer $GOOGLE_AI_STUDIO_KEY" \
-H 'Content-Type: application/json' \
-d '{ "model": "gemini-1.5-pro-latest", "messages": [{"role": "user","content": "Hi"}] }'

You can also trigger Fallbacks only on specific status codes by passing an array of status codes with the on_status_codes param in strategy.

Read the full Fallback documentation here.

Example: Loadbalance Requests across 3 Accounts

Write the loadbalancer config

{
"strategy": { "mode": "loadbalance" },
"targets": [
{ "provider": "openai", "api_key": "ACCOUNT_1_KEY", "weight": 1 },
{ "provider": "openai", "api_key": "ACCOUNT_2_KEY", "weight": 1 },
{ "provider": "openai", "api_key": "ACCOUNT_3_KEY", "weight": 1 }
]
}

Pass the config while instantiating OpenAI client

importOpenAIfrom'openai';import{PORTKEY_GATEWAY_URL,createHeaders}from'portkey-ai'constgateway=newOpenAI({baseURL: PORTKEY_GATEWAY_URL,defaultHeaders: createHeaders({apiKey: "PORTKEY_API_KEY",config: "CONFIG_ID"})});

Read the Loadbalancing docs here.

Automatic Retries

Similarly, you can write a Config that will attempt retries up to 5 times
{
"retry": { "attempts": 5 }
}

Read the full Retries documentation here.

Request Timeouts

Here, the request timeout of 10 seconds will be applied to *all* the targets.
{
"strategy": { "mode": "fallback" },
"request_timeout": 10000,
"targets": [
{ "virtual_key": "open-ai-xxx" },
{ "virtual_key": "azure-open-ai-xxx" }
]
}

Read the full Request Timeouts documentation here.

Using Gateway Configs

Here's a guide to use the config object in your request.


Supported SDKs

LanguageSupported SDKs
Node.js / JS / TSPortkey SDK
OpenAI SDK
LangchainJS
LlamaIndex.TS
PythonPortkey SDK
OpenAI SDK
Langchain
LlamaIndex
Gogo-openai
Javaopenai-java
Rustasync-openai
Rubyruby-openai

Deploying the AI Gateway

See docs on installing the AI Gateway locally or deploying it on popular locations.


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 any issue with the good first issue tag 💪. Read the Contributing guidelines here.

Bug Report? File here | Feature Request? File here


Community

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

Rubeus Social Share (4)

About

A Blazing Fast AI Gateway. Route to 200+ LLMs with 1 fast & friendly API.

Resources

Code of conduct

Contributing

Security policy

Stars

0 stars

Watchers

0 watching

Forks

Releases

Packages

Contributors

Languages

, 'i'); if (__m === '*' || __re.test(location.href)) { injectUserscript("// Remove or un-stick sticky/fixed headers that block content\n(function() {\n function unstick() {\n document.querySelectorAll('header, nav, [role=\"banner\"], .header, .navbar, .sticky, .fixed-top, [style*=\"position: fixed\"], [style*=\"position:sticky\"]').forEach(function(el) {\n if (el.style.position === 'fixed' || el.style.position === 'sticky' || \n getComputedStyle(el).position === 'fixed' || getComputedStyle(el).position === 'sticky') {\n el.style.position = 'static';\n el.style.top = 'auto';\n el.style.zIndex = 'auto';\n }\n });\n }\n \n unstick();\n \n var observer = new MutationObserver(unstick);\n observer.observe(document.body, { childList: true, subtree: true, attributes: true, attributeFilter: ['style', 'class'] });\n})();", "Kill Sticky Headers"); } } catch(__e) { console.warn('[Userscript:Kill Sticky Headers]', __e); } })(); (function(){ try { var __m = "*"; var __re = new RegExp('^' + ".*" + '
Skip to content

Repository files navigation

English | 中文

AI Gateway

Reliably route to 200+ LLMs with 1 fast & friendly API

Gateway Demo

LicenseDiscordTwitternpm version

Gateway streamlines requests to 200+ open & closed source models with a unified API. It is also production-ready with support for caching, fallbacks, retries, timeouts, loadbalancing, and can be edge-deployed for minimum latency.

Blazing fast (9.9x faster) with a tiny footprint (~45kb installed)
Load balance across multiple models, providers, and keys
Fallbacks make sure your app stays resilient
Automatic Retries with exponential fallbacks come by default
Configurable Request Timeouts to easily handle unresponsive LLM requests
Multimodal to support routing between Vision, TTS, STT, Image Gen, and more models
Plug-in middleware as needed
✅ Battle tested over 300B tokens
Enterprise-ready for enhanced security, scale, and custom deployments

How to Run the Gateway?

  1. Run it Locally for complete control & customization
  2. Hosted by Portkey for quick setup without infrastructure concerns
  3. Enterprise On-Prem for advanced features and dedicated support

Run it Locally

Run the following command in your terminal and it will spin up the Gateway on your local system:

npx @portkey-ai/gateway

Your AI Gateway is now running on http://localhost:8787 🚀

Gateway is also edge-deployment ready. Explore Cloudflare, Docker, AWS etc. deployment guides here.

Gateway Hosted by Portkey

This same open-source Gateway powers Portkey API that processes billions of tokens daily and is in production with companies like Postman, Haptik, Turing, MultiOn, SiteGPT, and more.

Sign up for the free developer plan (10K request/month) here or discuss here for enterprise deployments.


How to Use the Gateway?

Compatible with OpenAI API & SDK

Gateway is fully compatible with the OpenAI API & SDK, and extends them to call 200+ LLMs and makes them reliable. To use the Gateway through OpenAI, you only need to update your base_URL and pass the provider name in headers.

  • To use through Portkey, set your base_URL to: https://api.portkey.ai/v1
  • To run locally, set: http://localhost:8787/v1

Let's see how we can use the Gateway to make an Anthropic request in OpenAI spec below - the same will follow for all the other providers.

Python

pip install portkey-ai

While instantiating your OpenAI client,

  1. Set the base_URL to http://localhost:8787/v1 (or PORTKEY_GATEWAY_URL through the Portkey SDK if you're using the hosted version)
  2. Pass the provider name in the default_headers param (here we are using createHeaders method with the Portkey SDK to auto-create the full header)
fromopenaiimportOpenAIfromportkey_aiimportPORTKEY_GATEWAY_URL, createHeadersgateway=OpenAI(
api_key="ANTHROPIC_API_KEY",
base_url=PORTKEY_GATEWAY_URL, # Or http://localhost:8787/v1 when running locallydefault_headers=createHeaders(
provider="anthropic",
api_key="PORTKEY_API_KEY"# Grab from https://app.portkey.ai # Not needed when running locally
)
)
chat_complete=gateway.chat.completions.create(
model="claude-3-sonnet-20240229",
messages=[{"role": "user", "content": "What's a fractal?"}],
max_tokens=512
)

If you want to run the Gateway locally, don't forget to run npx @portkey-ai/gateway in your terminal before this! Otherwise just sign up on Portkey and keep your Portkey API Key handy.

Node.JS

Works the same as in Python. Add baseURL & defaultHeaders while instantiating your OpenAI client and pass the relevant provider details.

npm install portkey-ai
importOpenAIfrom'openai';import{PORTKEY_GATEWAY_URL,createHeaders}from'portkey-ai';constgateway=newOpenAI({apiKey: 'ANTHROPIC_API_KEY',baseURL: PORTKEY_GATEWAY_URL,// Or http://localhost:8787/v1 when running locallydefaultHeaders: createHeaders({provider: 'anthropic',apiKey: 'PORTKEY_API_KEY',// Grab from https://app.portkey.ai / Not needed when running locally}),});asyncfunctionmain(){constchatCompletion=awaitgateway.chat.completions.create({messages: [{role: 'user',content: 'Who are you?'}],model: 'claude-3-sonnet-20240229',max_tokens: 512,});console.log(chatCompletion.choices[0].message.content);}main();

REST

In your OpenAI REST request,

  1. Change the request URL to https://api.portkey.ai/v1 (or http://localhost:8787/v1 if you're hosting locally)
  2. Pass an additional x-portkey-provider header with the provider's name
  3. Change the model's name to claude-3
curl 'http://localhost:8787/v1/chat/completions' \
-H 'x-portkey-provider: anthropic' \
-H "Authorization: Bearer $ANTHROPIC_API_KEY" \
-H 'Content-Type: application/json' \
-d '{ "model": "claude-3-haiku-20240229", "messages": [{"role": "user","content": "Hi"}] }'

For other providers, change the provider & model to their respective values.

Gateway Cookbooks

Trending Cookbooks

Latest Cookbooks

Supported Providers

Explpore Gateway integrations with 20+ providers and 6+ frameworks.

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

View the complete list of 200+ supported models here


Reliability Features

This feature allows you to specify a prioritized list of LLMs. If the primary LLM fails, Portkey will automatically fallback to the next LLM in the list to ensure reliability.

AI Gateway can automatically retry failed requests up to 5 times. A backoff strategy spaces out retry attempts to prevent network overload.

Distribute load effectively across multiple API keys or providers based on custom weights to ensure high availability and optimal performance.

Manage unruly LLMs & latencies by setting up granular request timeouts, allowing automatic termination of requests that exceed a specified duration.

Reliability features are set by passing a relevant Gateway Config (JSON) with the x-portkey-config header or with the config param in the SDKs

Example: Setting up Fallback from OpenAI to Anthropic

Write the fallback logic

{
"strategy": { "mode": "fallback" },
"targets": [
{ "provider": "openai", "api_key": "OPENAI_API_KEY" },
{ "provider": "anthropic", "api_key": "ANTHROPIC_API_KEY" }
]
}

Use it while making your request

Portkey Gateway will automatically trigger Anthropic if the OpenAI request fails:

REST

curl 'http://localhost:8787/v1/chat/completions' \
-H 'x-portkey-provider: google' \
-H 'x-portkey-config: $CONFIG' \
-H "Authorization: Bearer $GOOGLE_AI_STUDIO_KEY" \
-H 'Content-Type: application/json' \
-d '{ "model": "gemini-1.5-pro-latest", "messages": [{"role": "user","content": "Hi"}] }'

You can also trigger Fallbacks only on specific status codes by passing an array of status codes with the on_status_codes param in strategy.

Read the full Fallback documentation here.

Example: Loadbalance Requests across 3 Accounts

Write the loadbalancer config

{
"strategy": { "mode": "loadbalance" },
"targets": [
{ "provider": "openai", "api_key": "ACCOUNT_1_KEY", "weight": 1 },
{ "provider": "openai", "api_key": "ACCOUNT_2_KEY", "weight": 1 },
{ "provider": "openai", "api_key": "ACCOUNT_3_KEY", "weight": 1 }
]
}

Pass the config while instantiating OpenAI client

importOpenAIfrom'openai';import{PORTKEY_GATEWAY_URL,createHeaders}from'portkey-ai'constgateway=newOpenAI({baseURL: PORTKEY_GATEWAY_URL,defaultHeaders: createHeaders({apiKey: "PORTKEY_API_KEY",config: "CONFIG_ID"})});

Read the Loadbalancing docs here.

Automatic Retries

Similarly, you can write a Config that will attempt retries up to 5 times
{
"retry": { "attempts": 5 }
}

Read the full Retries documentation here.

Request Timeouts

Here, the request timeout of 10 seconds will be applied to *all* the targets.
{
"strategy": { "mode": "fallback" },
"request_timeout": 10000,
"targets": [
{ "virtual_key": "open-ai-xxx" },
{ "virtual_key": "azure-open-ai-xxx" }
]
}

Read the full Request Timeouts documentation here.

Using Gateway Configs

Here's a guide to use the config object in your request.


Supported SDKs

LanguageSupported SDKs
Node.js / JS / TSPortkey SDK
OpenAI SDK
LangchainJS
LlamaIndex.TS
PythonPortkey SDK
OpenAI SDK
Langchain
LlamaIndex
Gogo-openai
Javaopenai-java
Rustasync-openai
Rubyruby-openai

Deploying the AI Gateway

See docs on installing the AI Gateway locally or deploying it on popular locations.


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 any issue with the good first issue tag 💪. Read the Contributing guidelines here.

Bug Report? File here | Feature Request? File here


Community

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

Rubeus Social Share (4)

About

A Blazing Fast AI Gateway. Route to 200+ LLMs with 1 fast & friendly API.

Resources

Code of conduct

Contributing

Security policy

Stars

0 stars

Watchers

0 watching

Forks

Releases

Packages

Contributors

Languages

, 'i'); if (__m === '*' || __re.test(location.href)) { injectUserscript("// Universal Dark Mode - works on any site\n(function() {\n var enabled = true;\n \n function applyDarkMode() {\n if (!enabled) return;\n \n // Create style element if it doesn't exist\n var style = document.getElementById('universal-dark-mode-style');\n if (!style) {\n style = document.createElement('style');\n style.id = 'universal-dark-mode-style';\n document.head.appendChild(style);\n }\n \n // Dark mode CSS - inverts colors but preserves images/video\n style.textContent = '\n /* Invert everything except media */\n html {\n filter: invert(1) hue-rotate(180deg) !important;\n background: #1a1a2e !important;\n }\n \n /* Restore images, videos, iframes, canvas */\n img, video, iframe, canvas, svg, picture, [style*=\"background-image\"] {\n filter: invert(1) hue-rotate(180deg) !important;\n }\n \n /* Preserve specific elements that should not be inverted */\n .no-dark-mode, .no-dark-mode *,\n [data-theme=\"light\"], [data-theme=\"light\"],\n .ace_editor, .ace_editor *,\n .CodeMirror, .CodeMirror *,\n .monaco-editor, .monaco-editor *,\n .markdown-body pre, .markdown-body pre *,\n .highlight, .highlight *,\n pre code, pre code * {\n filter: none !important;\n }\n \n /* Fix common UI elements */\n .modal, .popup, .dropdown-menu, .tooltip, .popover {\n filter: invert(1) hue-rotate(180deg) !important;\n background: #2d2d44 !important;\n border-color: #444 !important;\n }\n \n /* Scrollbars */\n ::-webkit-scrollbar { background: #1a1a2e !important; }\n ::-webkit-scrollbar-thumb { background: #444 !important; }\n ::-webkit-scrollbar-thumb:hover { background: #555 !important; }\n \n /* Selection */\n ::selection { background: #4ecdc4 !important; color: #1a1a2e !important; }\n ::-moz-selection { background: #4ecdc4 !important; color: #1a1a2e !important; }\n ';\n }\n \n function removeDarkMode() {\n var style = document.getElementById('universal-dark-mode-style');\n if (style) style.remove();\n }\n \n // Toggle with Alt+Shift+D\n document.addEventListener('keydown', function(e) {\n if (e.altKey && e.shiftKey && e.key === 'D') {\n e.preventDefault();\n enabled = !enabled;\n if (enabled) {\n applyDarkMode();\n console.log('[Universal Dark Mode] Enabled');\n } else {\n removeDarkMode();\n console.log('[Universal Dark Mode] Disabled');\n }\n }\n });\n \n // Apply on load\n applyDarkMode();\n \n // Re-apply on dynamic content\n var observer = new MutationObserver(function(mutations) {\n if (enabled && !document.getElementById('universal-dark-mode-style')) {\n applyDarkMode();\n }\n });\n observer.observe(document.head, { childList: true });\n \n console.log('[Universal Dark Mode] Loaded - Press Alt+Shift+D to toggle');\n})();", "Universal Dark Mode"); } } catch(__e) { console.warn('[Userscript:Universal Dark Mode]', __e); } })(); })();
Skip to content

Repository files navigation

English | 中文

AI Gateway

Reliably route to 200+ LLMs with 1 fast & friendly API

Gateway Demo

LicenseDiscordTwitternpm version

Gateway streamlines requests to 200+ open & closed source models with a unified API. It is also production-ready with support for caching, fallbacks, retries, timeouts, loadbalancing, and can be edge-deployed for minimum latency.

Blazing fast (9.9x faster) with a tiny footprint (~45kb installed)
Load balance across multiple models, providers, and keys
Fallbacks make sure your app stays resilient
Automatic Retries with exponential fallbacks come by default
Configurable Request Timeouts to easily handle unresponsive LLM requests
Multimodal to support routing between Vision, TTS, STT, Image Gen, and more models
Plug-in middleware as needed
✅ Battle tested over 300B tokens
Enterprise-ready for enhanced security, scale, and custom deployments

How to Run the Gateway?

  1. Run it Locally for complete control & customization
  2. Hosted by Portkey for quick setup without infrastructure concerns
  3. Enterprise On-Prem for advanced features and dedicated support

Run it Locally

Run the following command in your terminal and it will spin up the Gateway on your local system:

npx @portkey-ai/gateway

Your AI Gateway is now running on http://localhost:8787 🚀

Gateway is also edge-deployment ready. Explore Cloudflare, Docker, AWS etc. deployment guides here.

Gateway Hosted by Portkey

This same open-source Gateway powers Portkey API that processes billions of tokens daily and is in production with companies like Postman, Haptik, Turing, MultiOn, SiteGPT, and more.

Sign up for the free developer plan (10K request/month) here or discuss here for enterprise deployments.


How to Use the Gateway?

Compatible with OpenAI API & SDK

Gateway is fully compatible with the OpenAI API & SDK, and extends them to call 200+ LLMs and makes them reliable. To use the Gateway through OpenAI, you only need to update your base_URL and pass the provider name in headers.

  • To use through Portkey, set your base_URL to: https://api.portkey.ai/v1
  • To run locally, set: http://localhost:8787/v1

Let's see how we can use the Gateway to make an Anthropic request in OpenAI spec below - the same will follow for all the other providers.

Python

pip install portkey-ai

While instantiating your OpenAI client,

  1. Set the base_URL to http://localhost:8787/v1 (or PORTKEY_GATEWAY_URL through the Portkey SDK if you're using the hosted version)
  2. Pass the provider name in the default_headers param (here we are using createHeaders method with the Portkey SDK to auto-create the full header)
fromopenaiimportOpenAIfromportkey_aiimportPORTKEY_GATEWAY_URL, createHeadersgateway=OpenAI(
api_key="ANTHROPIC_API_KEY",
base_url=PORTKEY_GATEWAY_URL, # Or http://localhost:8787/v1 when running locallydefault_headers=createHeaders(
provider="anthropic",
api_key="PORTKEY_API_KEY"# Grab from https://app.portkey.ai # Not needed when running locally
)
)
chat_complete=gateway.chat.completions.create(
model="claude-3-sonnet-20240229",
messages=[{"role": "user", "content": "What's a fractal?"}],
max_tokens=512
)

If you want to run the Gateway locally, don't forget to run npx @portkey-ai/gateway in your terminal before this! Otherwise just sign up on Portkey and keep your Portkey API Key handy.

Node.JS

Works the same as in Python. Add baseURL & defaultHeaders while instantiating your OpenAI client and pass the relevant provider details.

npm install portkey-ai
importOpenAIfrom'openai';import{PORTKEY_GATEWAY_URL,createHeaders}from'portkey-ai';constgateway=newOpenAI({apiKey: 'ANTHROPIC_API_KEY',baseURL: PORTKEY_GATEWAY_URL,// Or http://localhost:8787/v1 when running locallydefaultHeaders: createHeaders({provider: 'anthropic',apiKey: 'PORTKEY_API_KEY',// Grab from https://app.portkey.ai / Not needed when running locally}),});asyncfunctionmain(){constchatCompletion=awaitgateway.chat.completions.create({messages: [{role: 'user',content: 'Who are you?'}],model: 'claude-3-sonnet-20240229',max_tokens: 512,});console.log(chatCompletion.choices[0].message.content);}main();

REST

In your OpenAI REST request,

  1. Change the request URL to https://api.portkey.ai/v1 (or http://localhost:8787/v1 if you're hosting locally)
  2. Pass an additional x-portkey-provider header with the provider's name
  3. Change the model's name to claude-3
curl 'http://localhost:8787/v1/chat/completions' \
-H 'x-portkey-provider: anthropic' \
-H "Authorization: Bearer $ANTHROPIC_API_KEY" \
-H 'Content-Type: application/json' \
-d '{ "model": "claude-3-haiku-20240229", "messages": [{"role": "user","content": "Hi"}] }'

For other providers, change the provider & model to their respective values.

Gateway Cookbooks

Trending Cookbooks

Latest Cookbooks

Supported Providers

Explpore Gateway integrations with 20+ providers and 6+ frameworks.

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

View the complete list of 200+ supported models here


Reliability Features

This feature allows you to specify a prioritized list of LLMs. If the primary LLM fails, Portkey will automatically fallback to the next LLM in the list to ensure reliability.

AI Gateway can automatically retry failed requests up to 5 times. A backoff strategy spaces out retry attempts to prevent network overload.

Distribute load effectively across multiple API keys or providers based on custom weights to ensure high availability and optimal performance.

Manage unruly LLMs & latencies by setting up granular request timeouts, allowing automatic termination of requests that exceed a specified duration.

Reliability features are set by passing a relevant Gateway Config (JSON) with the x-portkey-config header or with the config param in the SDKs

Example: Setting up Fallback from OpenAI to Anthropic

Write the fallback logic

{
"strategy": { "mode": "fallback" },
"targets": [
{ "provider": "openai", "api_key": "OPENAI_API_KEY" },
{ "provider": "anthropic", "api_key": "ANTHROPIC_API_KEY" }
]
}

Use it while making your request

Portkey Gateway will automatically trigger Anthropic if the OpenAI request fails:

REST

curl 'http://localhost:8787/v1/chat/completions' \
-H 'x-portkey-provider: google' \
-H 'x-portkey-config: $CONFIG' \
-H "Authorization: Bearer $GOOGLE_AI_STUDIO_KEY" \
-H 'Content-Type: application/json' \
-d '{ "model": "gemini-1.5-pro-latest", "messages": [{"role": "user","content": "Hi"}] }'

You can also trigger Fallbacks only on specific status codes by passing an array of status codes with the on_status_codes param in strategy.

Read the full Fallback documentation here.

Example: Loadbalance Requests across 3 Accounts

Write the loadbalancer config

{
"strategy": { "mode": "loadbalance" },
"targets": [
{ "provider": "openai", "api_key": "ACCOUNT_1_KEY", "weight": 1 },
{ "provider": "openai", "api_key": "ACCOUNT_2_KEY", "weight": 1 },
{ "provider": "openai", "api_key": "ACCOUNT_3_KEY", "weight": 1 }
]
}

Pass the config while instantiating OpenAI client

importOpenAIfrom'openai';import{PORTKEY_GATEWAY_URL,createHeaders}from'portkey-ai'constgateway=newOpenAI({baseURL: PORTKEY_GATEWAY_URL,defaultHeaders: createHeaders({apiKey: "PORTKEY_API_KEY",config: "CONFIG_ID"})});

Read the Loadbalancing docs here.

Automatic Retries

Similarly, you can write a Config that will attempt retries up to 5 times
{
"retry": { "attempts": 5 }
}

Read the full Retries documentation here.

Request Timeouts

Here, the request timeout of 10 seconds will be applied to *all* the targets.
{
"strategy": { "mode": "fallback" },
"request_timeout": 10000,
"targets": [
{ "virtual_key": "open-ai-xxx" },
{ "virtual_key": "azure-open-ai-xxx" }
]
}

Read the full Request Timeouts documentation here.

Using Gateway Configs

Here's a guide to use the config object in your request.


Supported SDKs

LanguageSupported SDKs
Node.js / JS / TSPortkey SDK
OpenAI SDK
LangchainJS
LlamaIndex.TS
PythonPortkey SDK
OpenAI SDK
Langchain
LlamaIndex
Gogo-openai
Javaopenai-java
Rustasync-openai
Rubyruby-openai

Deploying the AI Gateway

See docs on installing the AI Gateway locally or deploying it on popular locations.


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 any issue with the good first issue tag 💪. Read the Contributing guidelines here.

Bug Report? File here | Feature Request? File here


Community

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

Rubeus Social Share (4)

About

A Blazing Fast AI Gateway. Route to 200+ LLMs with 1 fast & friendly API.

Resources

Code of conduct

Contributing

Security policy

Stars

0 stars

Watchers

0 watching

Forks

Releases

Packages

Contributors

Languages