Portkey AI Gateway

repository·main·Indexed 11 days ago

https://github.com/portkey-ai/gateway

A high-performance routing layer for LLMs providing reliability through retries and fallbacks, scalability via load balancing, and security through guardrails. It includes integrations for the Vercel AI SDK, Langchain, Llama Index, and various AI providers like OpenAI and Anthropic. Version 1.15.2 features a plugin system with hooks (Start, BeforeRequest, AfterRequest, End) and a Lasso Security plugin for content classification.

Tokens
70.6K
Snippets
224
Records
278
Agent score
93%

What's inside Portkey

  1. Overview of MCP Gateway

    main

    The MCP Gateway acts as a centralized control plane for managing Model Context Protocol (MCP) servers. It provides:

    • Authentication: A single auth layer at the gateway so users authenticate once.
    • Access Control: Granular control over which teams/users can access specific servers or tools.
    • Observability: Full logging of tool calls, including parameters, responses, and latency.
    • Identity Forwarding: Automatically forwards user identity (email, roles, etc.) to MCP servers.

    It is compatible with Claude Desktop, Cursor, VS Code, and other MCP-compatible clients.

  2. Explore Portkey Practitioners' Cookbooks

    main
    The Portkey Practitioners' Cookbooks repository provides strategies, notebooks, and practical examples for managing production LLM challenges using the Portkey Gateway. It covers advanced patterns such as caching, automatic retries, fallback mechanisms, and monitoring for various agent frameworks and providers.
  3. Core Features of the Portkey AI Gateway

    main

    The Portkey AI Gateway provides several categories of features to enhance LLM application development:

    Reliable Routing

    • Fallbacks: Automatically switch to a different provider or model if a request fails. You can specify which error codes trigger a fallback.
    • Automatic Retries: Retry failed requests up to 5 times using an exponential backoff strategy.
    • Load Balancing: Distribute requests across multiple API keys or providers using weights for high availability.
    • Request Timeouts: Set granular timeouts to terminate requests that exceed a specific duration.
    • Multi-modal LLM Gateway: Use a unified OpenAI-compatible signature to call vision, audio (TTS/STT), and image generation models.
    • Realtime APIs: Support for OpenAI realtime APIs via an integrated websockets server.

    Security & Accuracy

    • Guardrails: Verify inputs and outputs against 40+ pre-built checks or bring your own custom guardrails.
    • Secure Key Management: Use personal keys or generate virtual keys on the fly.
    • Role-based access control: Granular control over users, workspaces, and API keys.
    • Compliance: SOC2, HIPAA, GDPR, and CCPA compliant.

    Cost Management

    • Smart caching: Supports both simple and semantic caching to reduce latency and costs.
    • Usage analytics: Monitor request volume, latency, costs, and error rates.
    • Provider optimization: Automatically switch to the most cost-effective provider based on pricing and usage.

    Collaboration & Workflows

    • Agents Support: Integrates with frameworks like Autogen, CrewAI, LangChain, LlamaIndex, Phidata, and Control Flow.
    • Prompt Template Management: Collaborative versioning and management of prompt templates.
  4. How Portkey Caching Works: Simple vs Semantic

    main

    Portkey provides two caching strategies to reduce LLM latency and costs by serving subsequent responses from cache instead of making new model requests:

    1. Simple Caching: Serves from cache only when the input prompts are identical.
    2. Semantic Caching: Uses cosine similarity to serve from cache when a new prompt is semantically similar to a previously cached prompt (based on a similarity threshold).

    Caching is activated by passing a cache object within the config parameter of your API calls.

    // Simple Caching configuration
    { "cache": { "mode": "simple" } }
    
    // Semantic Caching configuration
    { "cache": { "mode": "semantic" } }
  5. What are Gateway Configs and how do they work?

    main

    Gateway Configs are JSON objects that instruct the Portkey AI Gateway to perform advanced orchestration tasks such as automatic retries, caching, fallbacks, load balancing, and timeouts.

    Instead of manually handling errors like rate limits (429 status codes) in your application logic, you pass a configuration to the gateway, and the gateway executes the logic on your behalf.

    {
      "retry": {
        "attempts": 3,
        "on_status_codes": [429]
      }
    }
  6. Configure Caching, Fallbacks, and Load Balancing

    main

    Portkey allows you to manage production reliability features like Semantic Caching, Fallbacks, and Load Balancing via Configs. You define these configurations in the Portkey dashboard and apply them by passing the config ID during client instantiation.

    Example Config JSON

    To enable semantic caching and a fallback strategy from mistral-medium to mistral-tiny:

    {
    	"cache": {"mode": "semantic"},
    	"strategy": {"mode": "fallback"},
    	"targets": [
    		{
    			"provider": "mistral-ai", "api_key": "...",
    			"override_params": {"model": "mistral-medium"}
    		},
    		{
    			"provider": "mistral-ai", "api_key": "...",
    			"override_params": {"model": "mistral-tiny"}
    		}
    	]
    }

    Applying a Config

    Pass the Config ID (e.g., pp-mistral-cache-xx) to the config parameter when initializing the Portkey client.

    # Python
    portkey = Portkey(
        api_key="PORTKEY_API_KEY",
        config="pp-mistral-cache-xx"
    )
    // JavaScript
    const portkey = new Portkey({
        apiKey: "PORTKEY_API_KEY",
        config: "pp-mistral-cache-xx"
    });
  7. Configure Loadbalancing and Nested Fallbacks

    main

    You can define complex routing behaviors using a config object.

    • Loadbalancing: Use strategy: { mode: 'loadbalance' } to distribute traffic across multiple targets. Use the weight property (e.g., 0.5) to specify the proportion of traffic sent to each target.
    • Fallbacks: Use strategy: { mode: 'fallback' } to define a list of targets that will be tried sequentially if the preceding target fails.
    • Nested Strategies: You can nest a fallback strategy inside a loadbalance target to ensure that if one provider in the loadbalancer fails, it immediately tries a backup provider.
    • Overrides: Use override_params within a target to change specific parameters (like model or max_tokens) for that specific provider.
    const config = {
      strategy: {
        mode: 'loadbalance'
      },
      targets: [
        {
          virtual_key: process.env['ANTHROPIC_VIRTUAL_KEY'],
          weight: 0.5,
          override_params: {
            max_tokens: 200,
            model: 'claude-3-opus-20240229'
          }
        },
        {
          strategy: {
            mode: 'fallback'
          },
          targets: [
            {
              virtual_key: process.env['OPENAI_VIRTUAL_KEY']
            },
            {
              virtual_key: process.env['AZURE_OPENAI_VIRTUAL_KEY']
            }
          ],
          weight: 0.5
        }
      ]
    };
  8. What are Guardrails and Checks in Portkey?

    main

    In the Portkey ecosystem, Guardrails and Checks are the primary use cases for plugins:

    • Checks: Individual functions that assess an input prompt or output response against predefined conditions. A check returns a boolean verdict or an error.
    • Guardrails: A collection of checks run together within the beforeRequest or afterRequest hooks. The combined result is a verdict that dictates the action taken (e.g., failing the request or returning a specific status code like 246 if the guardrail fails).

    Guardrails can be managed via the Portkey UI or defined as JSON within the Portkey config.

  9. Configure Routing and Guardrails with Configs

    main

    The AI Gateway uses Configs to define operational logic such as retries, fallbacks, load balancing, and guardrails. You can attach these configurations to your client using the .with_options(config=...) method.

    Common configuration keys include:

    • retry: Defines the number of attempts for failed requests.
    • output_guardrails: A list of rules to inspect model responses. For example, you can use default.contains with an operator (like none) and a list of words to deny responses containing specific terms.
    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"}]
    )
    
    # Note: In this example, the response will always be "Bat" because the 
    # guardrail denies any reply containing "Apple".
  10. Enterprise Version Features

    main

    The Enterprise Version of the Portkey Gateway is designed for private deployments requiring enhanced security and reliability. Key features include:

    • Secure Key Management: For role-based access control and tracking.
    • Simple & Semantic Caching: To serve repeat queries faster and save costs.
    • Access Control & Inbound Rules: Control which IPs and Geos can connect to your deployments.
    • PII Redaction: Automatically remove sensitive data from requests to prevent exposure.
    • Compliance: SOC2, ISO, HIPAA, and GDPR compliance.
    • Professional Support: Including feature prioritization.
  11. How Portkey Gateway Plugins and Hooks work

    main

    Portkey Gateway Plugins allow you to extend the Gateway's capabilities by executing custom logic at specific stages of the request lifecycle using Hooks.

    Currently, four types of hooks are supported:

    1. Start: Executed at the beginning of the request for setup and logging.
    2. BeforeRequest: Executed before the request is sent to the AI model. This is the primary hook used for implementing Guardrails.
    3. AfterRequest: Executed after the AI model processes the request but before the response is returned. Used for post-processing and validations.
    4. End: Executed at the end of the request lifecycle for final logging and cleanup.
  12. Getting Started with Portkey Gateway features

    main

    The cookbook provides several guides for implementing core Gateway capabilities: