このコンテンツは選択した言語では利用できません。

Chapter 2. Use models-as-a-service


Use Models-as-a-Service (MaaS) to access large language models with subscription-based governance and self-service API key management. You can discover available models, create API keys, and integrate models into your applications using OpenAI-compatible APIs.

2.1. Find Models-as-a-Service models in the dashboard

In Red Hat OpenShift AI, models published to Models-as-a-Service (MaaS) are available through the AI asset endpoints page in the OpenShift AI dashboard.

To view available models, log in to the OpenShift AI dashboard and click Gen AI studio AI asset endpoints.

The Models tab displays a table with all available model deployments. Each row shows:

Model
The model deployment name and model ID.
Use case
The model type, such as LLM for large language models.
Status
The current operational state of the model: Ready, Not ready, or Unknown.
Endpoints
A View button that opens the endpoint details.
Playground
An Add to playground link for testing the model interactively. For more information, see Test models in the playground.

To identify whether a model is published to Models-as-a-Service (MaaS), click the View button under Endpoints. Models published to MaaS display a Model as a Service badge at the top of the Endpoints dialog. The dialog shows:

  • The API endpoint URL for accessing the model through the MaaS gateway from outside the cluster
  • A subscription selector for choosing which subscription to use
  • A Generate API key button for creating 1-hour temporary API keys
  • A link to the API Keys page for managing API keys

To manage your API keys for programmatic access to MaaS models, click Gen AI studio API keys.

2.2. Access models through Models-as-a-Service

In Red Hat OpenShift AI, you can use Models-as-a-Service (MaaS) to access large language models with subscription-based governance and self-service API key management.

2.2.1. Your token limits and access levels

Before you begin working with models, it’s helpful to understand how Models-as-a-Service (MaaS) uses subscriptions and authorization policies to control your quota and access.

Note

In OpenShift AI 3.4, MaaS uses subscriptions instead of tiers and API keys instead of service account tokens for authentication.

  • Subscription assignment: You are automatically assigned to subscriptions based on your group membership in OpenShift. If you belong to multiple groups with different subscriptions, you can access all those subscriptions. When creating an API key without specifying a subscription, the system selects the subscription with the highest priority level.
  • Token limits: Your subscription determines how many tokens you can consume per time period for each model.
  • Model access: Authorization policies determine which models you can access through the API gateway. Your administrator creates authorization policies that grant your groups access to specific model endpoints. Both a subscription with quota and an authorization policy are required to access models through MaaS.
  • Authentication: You must use an API key to access models. You can create and manage your own API keys through the dashboard.

2.2.2. View your subscriptions

In Red Hat OpenShift AI, you can see which Models-as-a-Service (MaaS) subscriptions you can use for a specific model from the AI asset endpoints page.

Prerequisites

  • You have access to the OpenShift AI dashboard.
  • At least one model has been published to Models-as-a-Service in your environment.
  • You belong to a group that is assigned to at least one subscription.

Procedure

  1. In the OpenShift AI dashboard, click Gen AI studio AI asset endpoints.
  2. On the Models tab, locate a model published to Models-as-a-Service (MaaS) and click View in the Endpoints column.
  3. In the Endpoints dialog, view your subscription assignment from the Subscription dropdown.

    If you belong to multiple subscriptions that include this model, you can select which subscription to use for the model. The selected subscription’s token limits apply to your inference requests.

    Tip

    If you frequently exceed token limits or need access to additional models, contact your administrator to request a subscription update.

Verification

  • The Subscription dropdown lists at least one subscription for which you have access to this model.

2.2.3. Generate a temporary API key

In Red Hat OpenShift AI, you can generate a temporary 1-hour API key directly from the Endpoints dialog for quick testing and prototyping of Models-as-a-Service (MaaS) endpoints.

Prerequisites

  • You have access to the OpenShift AI dashboard.
  • Your administrator has enabled Models-as-a-Service and assigned you to a subscription.

Procedure

  1. In the OpenShift AI dashboard, click Gen AI studio AI asset endpoints.
  2. On the Models tab, locate the model you want to access and click View in the Endpoints column.
  3. In the Endpoints dialog, verify that the model displays a Model as a Service badge at the top.
  4. Copy the external API endpoint URL and store it securely. This URL is required for API calls to the model.
  5. Under the Authentication section, select your subscription from the Subscription dropdown.
  6. Click Generate API key.
  7. Copy the generated API key immediately and store it securely.

    Important

    The temporary API key is displayed only once and expires after 1 hour. Temporary API keys generated from the Endpoints dialog are scoped to the selected subscription. To create API keys with custom expiration dates, navigate to Gen AI studio API keys in the OpenShift AI dashboard.

  8. Click Close.

Verification

  • The generated API key displays with the sk-oai- prefix.
  • You have securely stored both the API key and the external API endpoint URL for use in API calls.

2.2.4. Make API calls to models

In Red Hat OpenShift AI, you can use your Models-as-a-Service (MaaS) API key to list models available to you and to make inference requests through the OpenAI-compatible API.

Prerequisites

  • You have generated a temporary API key or created an API key. For more information, see Create an API key.
  • You have copied the external API endpoint URL.
  • At least one model is published to Models-as-a-Service and accessible through your subscription.

Procedure

  1. Set your API key as an environment variable:

    $ export MAAS_API_KEY="<your_api_key>"

    The command uses the following placeholder:

    <your_api_key>
    Specifies the API key you generated or created, with the sk-oai- prefix.
  2. Set the external API endpoint URL as an environment variable:

    $ export MAAS_URL="<external_api_endpoint>"

    The command uses the following placeholder:

    <external_api_endpoint>
    Specifies the external API endpoint URL you copied from the Endpoints dialog.
  3. List available models using the /v1/models endpoint:

    $ curl -X GET "${MAAS_URL}/v1/models" \
      -H "Authorization: Bearer ${MAAS_API_KEY}"

    Example response in OpenAI-compatible format:

    {
      "object": "list",
      "data": [
        {
          "id": "facebook-opt-125m",
          "object": "model",
          "created": 1234567890,
          "owned_by": "llm",
          "ready": true
        },
        {
          "id": "llama-2-7b-chat",
          "object": "model",
          "created": 1234567890,
          "owned_by": "llm",
          "ready": true
        }
      ]
    }
  4. Call a model using the chat completions endpoint:

    $ curl -X POST "${MAAS_URL}/llm/<model_name>/v1/chat/completions" \
      -H "Authorization: Bearer ${MAAS_API_KEY}" \
      -H "Content-Type: application/json" \
      -d { "model": "<model_name>", "messages": [ { "role": "user", "content": "Explain quantum computing in simple terms." } ], "max_tokens": 150, "temperature": 0.7 }

    where:

    <model_name>

    Specifies the model deployment name from the Models as a service page, such as facebook-opt-125m or llama-2-7b-chat.

    Example response:

    {
      "id": "chatcmpl-abc123",
      "object": "chat.completion",
      "created": 1234567890,
      "model": "llama-2-7b-chat",
      "choices": [
        {
          "index": 0,
          "message": {
            "role": "assistant",
            "content": "Quantum computing is a type of computing that uses quantum mechanics..."
          },
          "finish_reason": "stop"
        }
      ],
      "usage": {
        "prompt_tokens": 12,
        "completion_tokens": 45,
        "total_tokens": 57
      }
    }

Verification

  • The /v1/models response includes the models you expect to access.
  • Chat completion requests return responses in the OpenAI-compatible JSON format.

Troubleshooting

  • If you receive 401 Unauthorized, verify that your API key is valid and has not been revoked.
  • If you receive 429 Too Many Requests, your subscription’s token limit has been reached. Wait for the token limit window to reset.

2.2.5. Test models in a Jupyter notebook

In Red Hat OpenShift AI, you can test Models-as-a-Service endpoints in a Jupyter notebook using Python code. This approach is useful for iterative testing, prototyping model integrations, and validating rate limiting behavior in an interactive environment before integrating models into applications.

Prerequisites

  • You have generated a temporary API key or created a permanent API key for the model that you want to access.
  • You have copied the external API endpoint URL from the Endpoints dialog. The procedure describes how to extract the base gateway URL.
  • You have access to a Jupyter notebook environment in OpenShift AI.
  • You have Python 3.9 or later available in your notebook environment.

Procedure

  1. Create a new Jupyter notebook in your OpenShift AI workbench.
  2. In the first code cell, configure the Models-as-a-Service (MaaS) gateway URL and API key:

    DEMO_MAAS_BASE = "https://maas.example.com"
    DEMO_API_KEY = "your-api-key-here"

    The code uses the following variables:

    DEMO_MAAS_BASE
    Specifies the MaaS gateway base URL. Extract this from the external API endpoint URL you copied from the Endpoints dialog. For example, if the endpoint is \https://maas.apps.cluster.example.com/llm/facebook-opt-125m, use \https://maas.apps.cluster.example.com. The specific model URLs are retrieved from the API response in the next step.
    DEMO_API_KEY
    Specifies your API key. Use the temporary or permanent key you generated earlier.
  3. In a new code cell, add the setup code to configure the HTTP client:

    import json
    import os
    import ssl
    import urllib.error
    import urllib.request
    from typing import Any, Dict, Optional
    
    _mb = globals().get("DEMO_MAAS_BASE", "")
    if isinstance(_mb, str) and _mb.strip():
        MAAS_BASE = _mb.strip().rstrip("/")
    else:
        MAAS_BASE = os.environ.get("MAAS_BASE", "https://maas.YOUR_DOMAIN_HERE").strip().rstrip("/")
    
    _ak = globals().get("DEMO_API_KEY", "")
    if isinstance(_ak, str) and _ak.strip():
        API_KEY = _ak.strip()
    else:
        API_KEY = (os.environ.get("MAAS_API_KEY") or os.environ.get("API_KEY") or "").strip()
    
    VERIFY_TLS = os.environ.get("VERIFY_TLS", "").lower() in ("1", "true", "yes")
    MODELS_URL = f"{MAAS_BASE}/maas-api/v1/models"
    
    if not API_KEY:
        raise SystemExit(
            "Set DEMO_API_KEY in the quick-swap cell or MAAS_API_KEY / API_KEY in the environment."
        )
    
    
    def http_json(
        method: str,
        url: str,
        *,
        token: Optional[str] = None,
        data: Optional[Dict[str, Any]] = None,
    ):
        """Minimal JSON HTTP helper (stdlib only)."""
        headers = {"Content-Type": "application/json", "Accept": "application/json"}
        if token:
            headers["Authorization"] = f"Bearer {token}"
        body = None
        if data is not None:
            body = json.dumps(data).encode("utf-8")
        ctx = ssl.create_default_context()
        if not VERIFY_TLS:
            ctx.check_hostname = False
            ctx.verify_mode = ssl.CERT_NONE
        req = urllib.request.Request(url, data=body, headers=headers, method=method)
        try:
            with urllib.request.urlopen(req, context=ctx, timeout=120) as resp:
                raw = resp.read().decode("utf-8")
                return resp.status, json.loads(raw) if raw else {}
        except urllib.error.HTTPError as e:
            err_body = e.read().decode("utf-8", errors="replace")
            try:
                parsed = json.loads(err_body) if err_body else {}
            except json.JSONDecodeError:
                parsed = {"_raw": err_body}
            raise RuntimeError(f"HTTP {e.code}: {parsed}") from None
    
    
    print("MAAS_BASE :", MAAS_BASE)
    print("MODELS_URL:", MODELS_URL)
    print("VERIFY_TLS:", VERIFY_TLS)
    print("API key set:", bool(API_KEY))

    This cell defines the http_json helper function and prints the configuration summary.

  4. In a new code cell, list the available models:

    _, models_body = http_json("GET", MODELS_URL, token=API_KEY)
    
    data = models_body.get("data") or []
    if not data:
        raise SystemExit("No models in response; deploy a model and check subscription binding.")
    
    first = data[0]
    MODEL_NAME = first.get("id") or first.get("name")
    MODEL_URL = (first.get("url") or "").rstrip("/")
    if not MODEL_NAME or not MODEL_URL:
        raise RuntimeError(f"Could not parse model id/url from: {first}")
    
    print(f"MODEL_NAME: {MODEL_NAME}")
    print(f"MODEL_URL: {MODEL_URL}")
    print("\nAll models:")
    print(json.dumps(models_body, indent=2))

    This cell retrieves the list of models you can access and stores the first model’s name and URL for testing.

  5. In a new code cell, make a single inference request:

    COMPLETIONS_URL = f"{MODEL_URL}/v1/completions"
    inference_payload = {
        "model": MODEL_NAME,
        "prompt": "Hello from the notebook demo.",
        "max_tokens": 50,
    }
    
    status, completion = http_json("POST", COMPLETIONS_URL, token=API_KEY, data=inference_payload)
    
    usage = completion.get("usage") or {}
    choices = completion.get("choices") or []
    choice0 = choices[0] if choices and isinstance(choices[0], dict) else {}
    completion_text = choice0.get("text") or ""
    
    print(f"HTTP status: {status}")
    print(f"\nTokens used:")
    print(f"  prompt_tokens: {usage.get('prompt_tokens', '—')}")
    print(f"  completion_tokens: {usage.get('completion_tokens', '—')}")
    print(f"  total_tokens: {usage.get('total_tokens', '—')}")
    print(f"\nCompletion text:")
    print(completion_text if completion_text else "(empty)")

    This cell sends a completion request and displays the response with token usage information.

  6. Optional: In a new code cell, test the rate limiting behavior:

    import time
    
    # Configuration
    SLEEP_BETWEEN_REQUESTS_SEC = 1.0
    CONSECUTIVE_429_TO_STOP = 3
    MAX_REQUESTS = 64
    
    inference_payload = {
        "model": MODEL_NAME,
        "prompt": "Rate limit probe.",
        "max_tokens": 50,
    }
    
    ctx = ssl.create_default_context()
    if not VERIFY_TLS:
        ctx.check_hostname = False
        ctx.verify_mode = ssl.CERT_NONE
    
    consecutive_429 = 0
    last_code = None
    for i in range(1, MAX_REQUESTS + 1):
        body = json.dumps(inference_payload).encode("utf-8")
        req = urllib.request.Request(
            COMPLETIONS_URL,
            data=body,
            headers={
                "Authorization": f"Bearer {API_KEY}",
                "Content-Type": "application/json",
            },
            method="POST",
        )
        try:
            with urllib.request.urlopen(req, context=ctx, timeout=120) as resp:
                last_code = resp.status
        except urllib.error.HTTPError as e:
            last_code = e.code
    
        print(f"{i:3d}  HTTP {last_code}", end="")
        if last_code == 429:
            consecutive_429 += 1
            print(f"  (429 streak {consecutive_429}/{CONSECUTIVE_429_TO_STOP})")
            if consecutive_429 >= CONSECUTIVE_429_TO_STOP:
                print(f"Stopping: {CONSECUTIVE_429_TO_STOP} consecutive 429 responses.")
                break
        else:
            consecutive_429 = 0
            print()
    
        if SLEEP_BETWEEN_REQUESTS_SEC > 0 and i < MAX_REQUESTS:
            time.sleep(SLEEP_BETWEEN_REQUESTS_SEC)
    else:
        if consecutive_429 < CONSECUTIVE_429_TO_STOP:
            print(f"Stopped: reached MAX_REQUESTS={MAX_REQUESTS} without {CONSECUTIVE_429_TO_STOP} consecutive 429s.")

    This cell sends repeated requests to test rate limiting. The loop stops after receiving 3 consecutive HTTP 429 responses or reaching the maximum request count.

Verification

  • The setup cell prints your MaaS configuration without exposing the API key value.
  • The model list cell displays at least one available model with its name and URL.
  • The inference cell returns an HTTP 200 status with completion text and token usage statistics.
  • The rate limit test demonstrates throttling behavior by receiving HTTP 429 responses when limits are exceeded.

2.2.6. Token limit responses

In Red Hat OpenShift AI, when you exceed token limits for your Models-as-a-Service (MaaS) subscription, the API returns specific error responses to help you manage your usage.

Token limit exceeded

If you exceed the maximum number of tokens allowed per time period for a model in your subscription:

Example error response

{
  "error": {
    "message": "Token limit exceeded. You have consumed the maximum number of tokens allowed for this model in your subscription.",
    "type": "token_limit_error",
    "code": 429
  }
}

Response headers for retry logic

X-RateLimit-Limit: 1000
X-RateLimit-Remaining: 0
X-RateLimit-Reset: 1234567890
Retry-After: 42

Handling token limits in Python

import time
import requests

def make_request_with_retry(url, headers, data, max_retries=3):
    for attempt in range(max_retries):
        response = requests.post(url, headers=headers, json=data)

        if response.status_code == 429:
            retry_after = int(response.headers.get('Retry-After', 60))
            print(f"Token limit exceeded. Retrying after {retry_after} seconds...")
            time.sleep(retry_after)
            continue

        return response

    raise Exception("Max retries exceeded")

Mitigation strategies

  • Reduce max_tokens in your requests to consume fewer tokens per request
  • Implement exponential backoff retry logic to handle temporary limit violations
  • Batch requests with longer delays between them to spread token consumption over time
  • Contact your administrator to request a subscription update with higher token limits if you consistently hit limits

2.2.7. Test models in the playground

In Red Hat OpenShift AI, the Gen AI Studio playground provides a chat-style interface for sending prompts to deployed models and reviewing the responses. You can test Models-as-a-Service (MaaS) endpoints in the playground using your existing subscriptions and token quotas.

Important

Playground testing consumes tokens from your subscription’s token limit. Heavy testing can deplete your quota and block subsequent production usage. Use a subscription dedicated to development if available.

Prerequisites

  • You are logged in to the OpenShift AI dashboard.
  • You are a member of at least one group that is granted access to a Models-as-a-Service (MaaS) subscription.
  • At least one model has been published to MaaS and is included in your subscription.
  • You have deployed a Llama Stack server in your project. For more information, see Deploying a Llama Stack server.

Procedure

  1. From the OpenShift AI dashboard, click Gen AI studio AI asset endpoints.
  2. Locate the MaaS model that you want to test.
  3. In the Actions column for that model, click the action menu (⋮) and then select Try in playground.

    The playground interface opens in a new browser tab.

  4. In the Configure panel, verify your MaaS settings:

    1. From the Model dropdown, verify that the correct model is selected.

      MaaS models are displayed in the format <endpoint-name>/<model-id>. For example, maas-vllm-inference-1/facebook/opt-125m.

    2. From the Subscription dropdown, select the subscription to use for testing.

      If you belong to multiple subscriptions, select the subscription you want to use for testing.

  5. Test the model by entering a prompt in the message field and then clicking Send.

    The model response appears in the chat interface.

  6. Optional: Adjust model parameters, configure system prompts, or use additional playground features.

    For information about playground features such as temperature settings, streaming responses, system prompts, model comparison, RAG integration, and code export, see Experimenting with models in the gen AI playground.

Verification

  • The model returns a response to your prompt.

2.2.8. Manage persistent API keys

2.2.8.1. View your API keys

In Red Hat OpenShift AI, you can view a list of your Models-as-a-Service (MaaS) API keys in the OpenShift AI dashboard. The list shows the status, creation date, last-used date, and expiration date for each key.

Prerequisites

  • You are logged in to the OpenShift AI dashboard.
  • Your administrator has enabled Models-as-a-Service and assigned you to a subscription.

Procedure

  1. In the OpenShift AI dashboard, click Gen AI studio API keys.

    The API keys page displays a table with the following columns:

    • Name: The name assigned to the API key
    • Status: The current state of the key. Possible values: Active, Expired, Revoked.
    • Owner: Your username
    • Creation date: The date when the key was created
    • Last used: The date when the key was last used to access a model
    • Expiration date: The expiration date for the key
  2. Optional: Filter the list of API keys by status using the Status dropdown and selecting Active, Expired, or Revoked.
  3. Optional: Sort the table by clicking any column header.

Verification

  • Verify that the API keys table displays your API keys with columns for name, status, owner, creation date, last-used date, and expiration date.
  • If you applied status filters, verify that the table shows only API keys matching the selected status.

2.2.8.2. Create an API key

In Red Hat OpenShift AI, you can create Models-as-a-Service (MaaS) API keys to authenticate inference requests to large language models.

Important

Your group membership is captured at API key creation time. If your group membership changes after the key is created, the key retains the original group associations. To reflect updated group membership, revoke the existing key and create a new one.

Prerequisites

  • You are logged in to the OpenShift AI dashboard.
  • You authenticate to OpenShift AI using OpenShift authentication. External OIDC users create API keys through the MaaS API using curl or other HTTP clients, not through the dashboard.
  • Your administrator has deployed Models-as-a-Service.
  • You are a member of at least one OpenShift group that is included in a MaaS subscription.

Procedure

  1. In the OpenShift AI dashboard, click Gen AI studio API keys.
  2. Click Create API key.
  3. In the Create API key dialog, configure the following settings:

    1. In the Name field, enter a descriptive name for the API key.
    2. Optional: In the Description field, enter additional details about the key’s purpose.
    3. From the Subscription dropdown, select the subscription that determines which models the key can access and the applicable token limits.

      The Models section displays the models included in the selected subscription and their configured token limits.

    4. From the Expiration dropdown, select the number of days until the key expires, or select Never to create a permanent key.

      Note

      You can select an expiration period from 1 to 365 days. The default expiration is 30 days. Your administrator can set a maximum expiration limit in the Tenant custom resource. If not set, the default maximum is 90 days.

  4. Click Create.

    The API key created dialog displays the generated key with a prefix of sk-oai-.

    Important

    The plaintext key is displayed only during creation and cannot be retrieved later. Save the key in a secrets manager before closing the API key created dialog. If you lose the key, you must revoke it and create a new one.

  5. Click the copy icon next to the API key field to copy the key, and then save it in a secure location for use in applications.
  6. Click Close.

Verification

  1. In the OpenShift AI dashboard, navigate to Gen AI studio API keys.
  2. Verify that the new API key appears in the table.
  3. Confirm that the Status column displays Active with a green checkmark.
  4. Verify that the Subscription column shows a subscription that includes the models you want to access.
  5. Check that the Expires column displays the correct expiration date based on the number of days you selected.
  6. Optional: Test the API key by listing the models available through your subscription:

    $ curl -H "Authorization: Bearer <your-api-key>" \
      https://<maas-gateway-url>/maas-api/v1/models

    The command uses the following placeholders:

    <your-api-key>
    Specifies the API key you created.
    <maas-gateway-url>

    Specifies your MaaS gateway URL.

    The response lists the models accessible through your subscription in JSON format.

2.2.8.3. Revoke your API key

In Red Hat OpenShift AI, you can revoke one of your Models-as-a-Service (MaaS) API keys if you no longer need it or suspect that it has been compromised.

Important

Revoking an API key is permanent and cannot be undone. Applications and services using the revoked key lose access and receive 401 Unauthorized responses.

Prerequisites

  • You have access to the OpenShift AI dashboard.
  • You have at least one API key.
  • The key you want to revoke has not already been revoked or expired.

Procedure

To revoke an individual API key:

  1. In the OpenShift AI dashboard, click Gen AI studio API keys.
  2. In the row for the API key you want to revoke, click the action menu (⋮) and select Revoke.
  3. In the Revoke API key? dialog, review the warning that revocation is permanent.
  4. Enter the API key name to confirm.
  5. Click Revoke.

To revoke all your API keys:

  1. In the OpenShift AI dashboard, click Gen AI studio API keys.
  2. Click the action menu (⋮) and select Revoke all my keys.
  3. In the dialog, review the warning that revocation is permanent.
  4. Click Revoke all keys.

Verification

  • The API key shows a Revoked status in the API keys table. The revoked key remains visible in the table but can no longer be used for authentication.
  • Attempting to use the revoked key in an API request returns a 401 Unauthorized response with the error code invalid_api_key.

2.2.9. Best practices for using Models-as-a-Service

As a OpenShift AI user, follow these recommendations to effectively and securely use Models-as-a-Service (MaaS).

2.2.9.1. API key security

  • Never commit API keys to version control. Store API keys in environment variables, Kubernetes secrets, or secret management systems such as HashiCorp Vault.
  • Use descriptive names for API keys. Create separate keys for different applications or purposes such as production-chatbot, dev-testing, or notebook-experiments to track usage and simplify revocation.
  • Rotate API keys periodically. Generate new keys regularly and revoke old ones, especially for long-lived keys used in production applications.
  • Revoke compromised keys immediately. If an API key is exposed or no longer needed, revoke it through the dashboard to prevent unauthorized access.
  • Set appropriate expiration dates. Use shorter expiration periods for development and testing, and coordinate with your team for production key rotation schedules.

2.2.9.2. Quota management

  • Monitor your subscription limits. Check your subscription quotas in the dashboard to understand your available token limits and avoid unexpected quota exhaustion.
  • Check rate limit headers in responses. Review the X-RateLimit-Remaining header in API responses to track your usage against subscription limits in real time.
  • Plan for quota exhaustion. Implement graceful error handling when quotas are depleted, such as queuing requests or displaying user-friendly messages.
  • Choose subscriptions wisely. If you belong to multiple subscriptions with access to the same model, select the appropriate subscription for your use case when creating API keys or testing in the playground.

2.2.9.3. Token optimization

  • Set reasonable max_tokens values. Request only as many tokens as you need for your use case. Avoid setting excessively high limits that waste quota.
  • Optimize prompts for efficiency. Shorter, more focused prompts often produce better results while consuming fewer tokens than verbose or repetitive prompts.
  • Use system prompts effectively. Configure consistent model behavior through system prompts rather than repeating instructions in every user message.
  • Avoid redundant context. Send only the conversation history that the model needs to respond to the current request.
  • Test prompts before deploying. Use the playground to refine prompts and verify token consumption before implementing them in production code.

2.2.9.4. Performance and reliability

  • Implement retry logic with exponential backoff. Handle rate limit errors (HTTP 429) and temporary failures gracefully by retrying requests with increasing delays.
  • Cache responses when appropriate. If you make identical requests repeatedly, cache the results to reduce token consumption and improve response time.
  • Use streaming for interactive applications. Enable streaming responses to provide faster time-to-first-token and better user experience for chat-based applications.
  • Handle errors gracefully. Implement proper error handling for rate limits, quota exhaustion, network errors, and model timeouts.

2.2.9.5. Testing and development

  • Test in the playground first. Use the playground to validate model responses, compare models, and experiment with parameters before writing code.
  • Export playground configurations. Use the playground’s code export feature to generate starter code templates with your tested prompts and parameters.
  • Use temporary API keys for development. Generate short-lived API keys for testing and experimentation to minimize security risk if keys are accidentally exposed.
  • Validate model responses. Implement response validation in your application to ensure the model’s output meets your requirements and handles edge cases.
  • Test with multiple models. If multiple models are available in your subscription, test different models to find the best balance of response quality, speed, and token consumption for your use case.

2.2.9.6. Multi-subscription usage

  • Understand subscription priorities. If you belong to multiple subscriptions with access to the same model, the subscription with the highest priority level is used by default for API requests.
  • Select subscriptions explicitly when needed. When creating API keys or testing in the playground, explicitly choose which subscription to use rather than relying on automatic priority-based selection.
  • Separate development and production usage. If possible, use different subscriptions for development, testing, and production to isolate quota consumption and costs.
  • Track your usage per subscription. Monitor your token consumption separately for each subscription you belong to, especially if subscriptions have different usage policies or billing.

2.2.9.7. Production deployment

  • Use descriptive API key names. Create separate API keys for each production application or service to support usage tracking and selective revocation.
  • Implement monitoring and logging. Log API requests and responses (excluding sensitive data) to support debugging, usage analysis, and compliance requirements.
  • Set up alerting for quota limits. Monitor your subscription quota consumption and alert your team when approaching limits to avoid service disruptions.
  • Coordinate with administrators. If your usage patterns change or you need higher quotas, contact your administrator to request subscription adjustments.

2.3. Models-as-a-Service user access troubleshooting

As a OpenShift AI user, you can diagnose and resolve common issues when accessing models through Models-as-a-Service (MaaS).

2.3.1. Authentication errors: 401 Unauthorized

Symptom

{
  "error": {
    "message": "Invalid or expired API key",
    "type": "authentication_error",
    "code": 401
  }
}

Possible causes and solutions

  • API key expired: If your API key has expired, create a new one from the API keys page.
  • API key revoked: Check if the API key has been revoked. Create a new API key if necessary.
  • Incorrect API key format: Ensure you’re using the Authorization: Bearer <key> header format with the full API key including the sk-oai- prefix.
  • Using wrong authentication method: Generate a MaaS API key from the dashboard. OpenShift tokens are not valid for MaaS authentication.

2.3.2. Authorization errors: 403 Forbidden

Symptom

{
  "error": {
    "message": "Access denied. Your subscription does not have permission to access this model.",
    "type": "authorization_error",
    "code": 403
  }
}

Possible causes and solutions

  • Model not included in your subscription: Contact your administrator to request that the model be added to your subscription.
  • No authorization policy exists: Ask your administrator to verify that an authorization policy exists for your groups to access the model through the API gateway.

2.3.3. Model not found: 404

Symptom

{
  "error": {
    "message": "Model not found",
    "type": "not_found_error",
    "code": 404
  }
}

Possible causes and solutions

  • Incorrect model name: Verify the model name using the /v1/models endpoint.
  • Model not deployed: Ask your administrator to check if the model is deployed and ready.
  • Typo in URL: Ensure the URL format is correct: https://maas.<domain>/llm/<model-name>/v1/chat/completions

2.3.4. Exceeded token limits

If you exceed the maximum number of tokens allowed per time period for a model in your subscription:

Example error response

{
  "error": {
    "message": "Token limit exceeded. You have consumed the maximum number of tokens allowed for this model in your subscription.",
    "type": "token_limit_error",
    "code": 429
  }
}

Response headers for retry logic

X-RateLimit-Limit: 1000
X-RateLimit-Remaining: 0
X-RateLimit-Reset: 1234567890
Retry-After: 42

Handling token limits in Python

import time
import requests

def make_request_with_retry(url, headers, data, max_retries=3):
    for attempt in range(max_retries):
        response = requests.post(url, headers=headers, json=data)

        if response.status_code == 429:
            retry_after = int(response.headers.get('Retry-After', 60))
            print(f"Token limit exceeded. Retrying after {retry_after} seconds...")
            time.sleep(retry_after)
            continue

        return response

    raise Exception("Max retries exceeded")

Mitigation strategies

  • Reduce max_tokens in requests to consume fewer tokens per request
  • Implement exponential backoff retry logic to handle temporary limit violations
  • Batch requests with longer delays between them to spread token consumption over time
  • Contact your administrator to request a subscription update with higher token limits if you consistently hit limits

2.3.5. Persistent token limit errors

Symptom

You continue to receive 429 errors even after waiting.

Possible causes and solutions

  • Subscription token limits exhausted: Check token limits for your subscription for the model you are trying to access. Wait for the time period to reset or contact your administrator for a subscription update.
  • Incorrect retry logic: Ensure you’re respecting the Retry-After header value.
  • Multiple applications using the same API key: Each application should have its own API key to better track and manage token consumption.
Red Hat logoGithubredditYoutubeTwitter

詳細情報

試用、購入および販売

コミュニティー

会社概要

Red Hat は、企業がコアとなるデータセンターからネットワークエッジに至るまで、各種プラットフォームや環境全体で作業を簡素化できるように、強化されたソリューションを提供しています。

多様性を受け入れるオープンソースの強化

Red Hat では、コード、ドキュメント、Web プロパティーにおける配慮に欠ける用語の置き換えに取り組んでいます。このような変更は、段階的に実施される予定です。詳細情報: Red Hat ブログ.

Red Hat ドキュメントについて

Legal Notice

Theme

© 2026 Red Hat
トップに戻る