Call the OpenAI Responses API with an environment-loaded key, a timeout and visible diagnostics. Use the returned usage to evaluate the request and the deliberate error path to check recovery.

What you’ll build

The official developer quickstart uses the Responses API with the OpenAI SDK. This script follows that interface for a small text task. Official documentation.

This program deliberately keeps the first Responses request small. It loads an authorized credential, selects a documented model, sends a short input and prints text plus usage. It does not connect external tools or maintain a conversation store. The narrow scope gives you a baseline for diagnosing later additions.

Define success before executing the script. A returned response establishes the basic API path, while an understandable answer shows that the program read the expected content. Neither proves that your intended application is reliable. Preserve this distinction when presenting the result to a teammate or turning the example into a larger evaluation.

Prerequisites

Complete the OpenAI API-key guide in the intended project and verify the model is available to that account.

Create a dedicated working directory and confirm the Python interpreter your terminal uses. Keep the script, dependency record and safe input fixtures together. Avoid mixing fragments from different examples in a session where hidden variables can change the result.

Configure the project credential through protected environment settings. Check that the expected variable is present without printing its value. Confirm the selected model is available to the project and that inference spending is authorized. Keep the application’s owner and stop procedure documented before connecting any scheduled execution.

Install SDK

python -m pip install --upgrade openai

Install the official openai package in the environment that will run the example. If importing it fails, inspect the interpreter and package location before repeatedly reinstalling. Do not name the local script openai.py, because that can shadow the package and create an error unrelated to the API.

After the first successful execution, record the installed version. A maintained project should make dependency changes reviewable and rerun its important request examples after an update. The fresh-install command is convenient for this exercise, while reproducible application deployment needs the dependency policy appropriate to the project.

Full script

import os
import sys
from openai import OpenAI, APIStatusError

model = os.environ.get("OPENAI_MODEL", "gpt-5.6-luna")
if "--bad-model" in sys.argv:
    model = "ai-api-hub-invalid-model"
client = OpenAI(api_key=os.environ["OPENAI_API_KEY"], timeout=30.0, max_retries=0)
try:
    result = client.responses.create(
        model=model,
        input="Explain the purpose of a model evaluation in a short sentence.",
        max_output_tokens=256,
        store=False,
    )
    print(result.output_text)
    print(result.usage.model_dump_json())
except APIStatusError as exc:
    print(f"HTTP {exc.status_code}")
    print(exc.response.text)
    raise SystemExit(1)

The model selection and credential are separate configuration values. The secret must be present explicitly; the model has a documented default that can be changed for an evaluation. The bad-model switch changes only that identifier. This makes the failure exercise easier to interpret than a script that simultaneously changes access, input shape and model choice.

The client timeout prevents the first diagnostic request from waiting indefinitely, and automatic retries are disabled so the initial result remains visible. The response text is printed separately from usage. Preserve that separation when saving an evaluation record: accepted content and resource usage answer different questions and should not be collapsed into a single success flag.

Expected output

Illustrative output only; this was not observed from an inference request. Model wording and usage will differ.

A brief explanation of evaluating a model.
{"input_tokens": 15, "output_tokens": 20, "total_tokens": 35}

The illustrated answer is schematic. Your actual response may phrase the explanation differently and will contain service-generated metadata. Do not write a test that requires the example’s exact wording. Check the output property relevant to the task instead, such as a valid category or a fact supported by the supplied material.

Save the model identifier, prompt revision, client version and returned usage with the outcome. Redact sensitive input before sharing the result. If the program prints an exception, inspect it as diagnostic evidence; do not count the existence of terminal output as a successful model response.

One deliberate error and its fix

python first_openai.py --bad-model

The branch sends ai-api-hub-invalid-model instead of the normal model identifier. Keep the credential configured so the request reaches model validation. The script exposes the returned rejection and stops; restore the ordinary command to use the supported model again.

The following error-field excerpt was captured on 2026-09-12 15:53 UTC from an authorized HTTP request to the same provider interface. It used harmless connection-validation input and small output settings. This records the provider’s rejection; it does not claim that the Python SDK example itself was executed.

These are normalized captured fields with the message preserved verbatim. They are not a reconstructed full provider response envelope. Empty fields and request identifiers are omitted.

{
  "http_status": 404,
  "code": "model_not_found",
  "type": "invalid_request_error",
  "message": "The model `ai-api-hub-invalid-model` does not exist or you do not have access to it."
}

Fix the deliberate error by restoring a current accessible model identifier. Do not resend the invalid identifier in a retry loop. If the ordinary request also fails, inspect that response independently because permission, funding and request validation can fail at different stages. Official error reference.

Keep the missing-key startup check as an additional local configuration guard. It tests whether the process can read its environment; it does not establish that the provider accepted the key or evaluated the requested model.

What this request costs

Interactive tool

Estimate your API costs

Your text and estimates stay in this browser. No API requests are sent to model providers.

Loading verified model records…

Transfer the returned usage into the cost calculator and compare it with your workload assumptions.

Use returned usage together with the exact model and applicable live price row. Keep the estimate tied to the request shown here. If you extend the program with media or hosted tools, review the additional charge categories before reusing the original calculation.

A single short prompt is not a representative production forecast. Collect examples from the real application, judge whether their outputs are accepted and record the work needed to repair failures. Use conservative assumptions for cases not yet measured. The calculator makes these assumptions visible; it does not turn an untested average into observed billing evidence.

Next steps

Keep the Responses API request and output handling together when extending the script. Read OpenAI error handling and add a saved evaluation set before introducing tools.

Add a fixture-based evaluation before adding more API features. Keep the original text-only request as a diagnostic baseline. Introduce structured output, conversation handling or tools one at a time and verify the application’s result parser after each change.

Before unattended operation, define protected logging, retry ownership and a clear stop condition. Document project access and credential rotation. If the workflow can trigger an external action, keep action authorization and duplicate prevention in the application rather than assuming a successful model response establishes permission. The example is ready to grow when another maintainer can reproduce its success, explain its deliberate failure and identify the remaining evaluation work.

Last verified · Source ↗

Frequently asked questions

Which interface does this starter use?
It uses the Responses API through the official Python client. Official documentation.
Can I substitute a model display name?
Copy an actual API identifier from the model catalog; display names and aliases are documented separately. Official documentation.
Where should a production key live?
Load it through environment configuration or a secret-management service. Official documentation.
Does every capacity error mean I should retry?
No. The error code distinguishes throttling from credit, spend and usage limits. Official documentation.
How do I compare a model change?
Keep representative inputs and acceptance criteria fixed; measure quality, elapsed time and returned usage for each candidate.

Sources

Last verified · Source ↗