Skip to content

1.1 Introduction

This chapter covers what a developer needs to know to start working with LLM-based applications. We will look at how to send requests, what kinds of responses you can get, and how to handle possible errors.

How We Look at the Model

For you as a developer, a language model is simply a service. Text goes in, text comes out. Inside there are billions of parameters, but in essence it is a black box. What matters is that it is an HTTP endpoint with a defined contract: you send a request, you pay for processing, and you get a result.

When working with models you need to know a few key parameters.

The context window is the maximum amount of text the model can process in a single call. It is measured in tokens. Modern models have windows ranging from 8 thousand to 128 thousand tokens and more. This is the limit for both input and output. If the context window is 4K tokens, your prompt, instructions, examples, input data, and the response all have to fit into it.

Tokens are the basic units into which the model splits text. For English, one token roughly corresponds to four characters. For Russian text the ratio is lower: usually one to two characters per token, which directly affects request cost. If you work with Russian text, you can safely divide the context window stated in the model specification by two, because it is usually given in English-language tokens.

Temperature controls how random the model's answers are. At temperature 0 the model picks the most probable next token. This is needed for tasks where predictability matters: text classification, data extraction, and specific answers to questions where you need a concrete fact. At temperatures in the range 0.7–1.0 the answers become more varied and sound livelier. But they are less reproducible: the same question can get different answers. This is good for creative tasks.

The First Request

To start working with the API you need an access key. The process is standard for almost all providers: create an account, link a payment method, and generate a key in your personal dashboard. The key looks like a long string of the form sk-... and gives full access to the API on behalf of your account.

If you spend an hour searching GitHub, you can find hundreds of repositories where keys are stored right in the code. Sometimes they are in configuration files, sometimes in commit messages, sometimes simply in a .env file that was committed by accident. Every such case is a compromise. Other people can use your key, and you will pay for their requests. The bills can grow to enormous amounts.

Store keys in environment variables or in a dedicated secrets store (a vault). For development, use one key with one limit; for production, a separate key with its own limit. Then if the development key is compromised, the damage will be contained.

An example of initializing the OpenAI client:

import os
from openai import OpenAI

# The key is read from an environment variable, not from the code
client = OpenAI(api_key=os.environ.get("OPENAI_API_KEY"))

response = client.responses.create(
    model="gpt-5-mini",
    input=[
        {
            "role": "system",
            "content": "You are an assistant that answers briefly and to the point."
        },
        {
            "role": "user",
            "content": "What is machine learning?"
        }
    ],
    temperature=0
)

print(response.output_text)

What is happening here? First, the key is read from an environment variable rather than a string in the code. Second, the model is specified explicitly, which matters for reproducibility, because providers update models from time to time and their behavior can change. Third, a chat interface is used with a separation between the system message (the instruction) and the user request. Finally, the temperature is set to 0 to make the answer deterministic. This is the basic template that repeats in most applications.

Handling Errors

The API can return an error for various reasons, and each one needs its own handling. You may hit a rate limit, run out of balance on the account, send a context that is too large for the window, or the service may be temporarily unavailable.

You can simply let the exception propagate. That works for prototypes, but in production the system will start failing at the first traffic spike. The better approach is retry logic with exponential backoff. If a request fails because of a rate limit, we wait a bit and try again. If it fails because of a server error, we also retry, but a few times.

import time
from openai import OpenAI, RateLimitError, APIError

def call_with_retry(client, messages, max_retries=3):
    """
    Calls the API with automatic retries on errors.

    Args:
        client: OpenAI client object
        messages: List of messages to send
        max_retries: Maximum number of attempts

    Returns:
        The model's response text
    """
    for attempt in range(max_retries):
        try:
            response = client.responses.create(
                model="gpt-5-mini",
                input=messages,
                temperature=0
            )
            return response.output_text
        except RateLimitError:
            # On a rate limit, wait exponentially longer
            wait_time = 2 ** attempt
            time.sleep(wait_time)
        except APIError as e:
            # Other errors are retried too, but we give up only if this was the last attempt
            if attempt == max_retries - 1:
                raise
            time.sleep(1)

    raise Exception("Maximum number of API call attempts exceeded")

The logic is as follows: we try to run the request. If it failed because of a rate limit (too many requests per second), we wait, and the waiting time grows after each attempt: 2 seconds, then 4, then 8. If it failed for another API reason, we also try again, but we give up only on the third attempt.

In practice you need more: logging of every request and error, metrics on the error rate by type, and a circuit breaker (so you do not flood a failing API with requests). But the foundation is retries with a delay.

Metadata in the Response

Every API response contains not only the text itself but also useful metadata. The usage field shows how many tokens were used: input, output, and total. Keep an eye on it so you do not waste money. The finish_reason field shows why the model stopped generating: it can be stop (normal completion), length (the maximum response size was reached), or content_filter (a safety filter was triggered).

response = client.responses.create(
    model="gpt-5-mini",
    input=messages,
    temperature=0
)

# Extract token usage information
prompt_tokens = response.usage.input_tokens
completion_tokens = response.usage.output_tokens
total_tokens = response.usage.total_tokens

print(f"Input tokens: {prompt_tokens}")
print(f"Response tokens: {completion_tokens}")
print(f"Total tokens: {total_tokens}")
print(f"Finish reason: {response.output[0].finish_reason}")

Why does this matter? Because finish_reason can tell you a lot about why a response looks strange. If finish_reason is length, the model wanted to keep going, but the response-size limit stopped it. The answer is incomplete, and you should either allow a longer answer (increase max_tokens) or rephrase the question more briefly.

If you save metadata for every request, you can spot patterns. For example, it may turn out that 15% of all requests end with finish_reason == "length". That is a signal that you need to increase max_tokens or optimize the prompts so the answers are shorter.

How to Choose a Model?

Providers usually offer several models: one very powerful (and expensive), several mid-range ones, and several fast and cheap ones. The choice is not obvious, because you need to find a balance: a more powerful model costs more, while a cheaper one may deliver worse quality.

My advice: for prototyping, use the most powerful model. The goal here is not saving money but understanding what the system can do under ideal conditions. Once the architecture works, try switching to a cheaper model and look at the quality. If it has not dropped, or the drop is not critical, stay with the cheap one. If it has dropped, look for a compromise. Compromises can take different forms. It may turn out that a mid-range model delivers 95% of the quality of the powerful one at 50% of the cost. Or a cheaper model may handle the task well if you improve the prompt or add examples. Often a good prompt on a cheap model gives better results than a poor prompt on an expensive one.

Keep in mind that costs can quickly get out of hand, especially when there are errors in the system. For example, a looping retry can generate thousands of requests per second. To reduce the risk, set spending limits and configure notifications when they are reached. Use different keys for different environments. Privacy is another important aspect. All data sent to the API is processed on the provider's side. For sensitive information, study the provider's data-processing policy carefully. In some cases you may need to deploy models locally or anonymize the data. Answer quality can be unstable: identical requests give different results, especially at non-zero temperature, and model updates can change behavior. That is why it is important to have automated tests and the ability to roll back quickly. Finally, dependence on an external service is an architectural risk. If the provider becomes unavailable, the system can stop completely. Critical systems need fallback mechanisms: caching, alternative providers, and graceful degradation.