Sub topic 2
Hosted APIs: what you get and what you give up
This chapter assumes you have called an HTTP API or SDK before, can read basic Python, and know what a prompt, a token, and a context window are. It covers the first of the two main ways to get a model: calling one that someone else runs.
What a hosted API is
A hosted API is a model that a provider runs on its own servers. You send a request over the network containing a prompt and some settings. The provider runs the model and returns the generated text. You never see the model's weights, which are the learned numbers that define it. You also never manage the GPUs that run it.
Most providers expose a similar chat-style interface: a model name, a list of messages, and parameters such as temperature and a maximum output length. Many other servers copy this interface. That similarity matters later, when you want to switch models.
The diagram shows where the trade-offs come from. Your prompt leaves your network, and the gateway can refuse or slow your request. Both points come up below.
What you get
- Fast start. You need an API key and a few lines of code. There is no hardware to buy and no serving software to install.
- Access to the strongest models. The largest and most capable models are often available only as hosted services. If your task needs top quality, a hosted API may be the only option.
- No operations work. The provider handles scaling, GPU failures, driver updates, and model-serving optimizations.
- Pay-per-use pricing. You pay for tokens, usually with separate prices for input and output. Cost is near zero when traffic is zero, and it grows with use.
- Elastic capacity. A traffic spike is the provider's problem, up to your rate limit.
- Frequent improvements. The provider can ship faster or better models, and you can adopt them by changing a model name.
What you give up
Control over the model
You cannot inspect or modify the weights. You cannot fine-tune beyond what the provider offers, and you cannot change how the model is served. Providers can also retire models. A model name that works today may be deprecated with a notice period you do not set. Even a model that stays in service can change behavior if you use a floating alias such as a "latest" name. A prompt that passed your tests last month can then fail without any change in your code.
Data location and privacy
Every prompt and every document you include in it travels to the provider. Whether the provider stores it, for how long, and whether it may use it for training depends on the provider's terms and your account type. These terms differ between providers and between plan tiers. Read them before you send customer data. The later chapter on privacy and compliance covers this in depth.
Predictable behavior and cost
Cost per token is clear, but total cost is not fixed. It scales with traffic, prompt length, and output length. A prompt template that grows from 500 to 4,000 tokens multiplies your bill. Latency also varies with provider load, and you cannot tune it directly.
Availability and limits
Providers enforce rate limits, usually as a cap on requests per minute and on tokens per minute. When you exceed them, the API returns an error, commonly HTTP 429. Provider outages also happen. If your product depends on one provider, their outage becomes yours.
Output that is not fully repeatable
Setting temperature to 0 makes output mostly stable, but many hosted services do not guarantee identical output for identical input. Do not write tests that require exact string equality unless the provider documents that guarantee.
Common errors and how to handle them
| Symptom | Likely cause | Fix |
|---|---|---|
| HTTP 429 | Request or token rate limit exceeded | Retry with exponential backoff, lower concurrency, or request a higher limit |
| HTTP 5xx or timeouts | Provider overload or outage | Retry a few times, then fail over or return a graceful error |
| Output silently cut off | Maximum output length reached | Check the finish reason and raise the limit |
| Error about input length | Prompt plus output exceeds the context window | Shorten the prompt or choose a larger-context model |
| Behavior changes with no code change | Floating model alias updated | Pin a dated model version and re-run your evaluation set before upgrading |
| Surprise bill | Long prompts or unbounded retries | Log token usage per request and set budget alerts |
A client that handles the common failures
The code below sets an explicit timeout and retries only on errors that are worth retrying. It reads its settings from environment variables, so the same code works with any OpenAI-compatible endpoint.
import os
import time
from openai import OpenAI, RateLimitError, APITimeoutError, APIConnectionError
client = OpenAI(
base_url=os.environ["LLM_BASE_URL"],
api_key=os.environ["LLM_API_KEY"],
timeout=30, # seconds; do not wait forever
max_retries=0, # we handle retries ourselves
)
MODEL = os.environ["LLM_MODEL"]
def ask(prompt: str, attempts: int = 4) -> str:
delay = 1.0
for attempt in range(attempts):
try:
response = client.chat.completions.create(
model=MODEL,
messages=[{"role": "user", "content": prompt}],
temperature=0,
max_tokens=500,
)
choice = response.choices[0]
if choice.finish_reason == "length":
print("warning: output was cut off at max_tokens")
usage = response.usage
print(f"tokens in={usage.prompt_tokens} out={usage.completion_tokens}")
return choice.message.content
except (RateLimitError, APITimeoutError, APIConnectionError):
if attempt == attempts - 1:
raise
time.sleep(delay)
delay *= 2 # exponential backoffThree habits in this code are worth copying. It logs token usage on every call, which is the raw data for cost estimates. It checks finish_reason so truncation is not silent. It does not retry errors such as an invalid request or a bad key, because retrying cannot fix them.
Reducing the risks without leaving
You can keep a hosted API and still limit what you give up.
- Pin versions. Use a dated model identifier where the provider offers one. Treat a version change as a deliberate upgrade that you test first.
- Keep an evaluation set. A small set of your own cases, run before any model change, tells you whether a new version is safe. The evaluation chapter builds one.
- Minimize what you send. Remove names, account numbers, and unrelated text from prompts when the task does not need them.
- Isolate the provider. Keep all model calls behind one function, like
askabove. Swapping providers is then a configuration change, not a rewrite. - Plan for failure. Decide what your application does when the API is down: queue the work, show a message, or fall back to a second provider.
When a hosted API is the right default
A hosted API is usually the best starting point when you are prototyping, when your traffic is low or uneven, when your task needs a frontier-level model, or when your team has no one to run GPU servers. It becomes harder to justify when data cannot leave your environment, when very high steady volume makes per-token billing expensive, or when you need control over model behavior and versions that the provider will not give. The chapter on hosted versus self-hosted trade-offs compares these cases side by side.
Exercise
Your application sends customer support emails to a hosted API. Last week, answer quality dropped, but nobody changed the code. Name the most likely cause and two steps that prevent it.
Show answer
The most likely cause is that the model name is a floating alias, and the provider updated the model behind it. Prevent it by pinning a dated model version, and by keeping an evaluation set that you run before adopting any new version. Logging the model identifier returned with each response also helps you confirm which version produced a given answer.
Exercise
A request fails with HTTP 429 in the code above. What happens, and why is max_retries=0 set on the client?
Show answer
The ask function catches RateLimitError, waits one second, then doubles the wait on each further attempt, up to four attempts, and re-raises the error if the last attempt fails. The client's built-in retries are turned off so that all retry behavior is in one visible place, which makes the attempt limit and the delay predictable and avoids stacking two retry layers on top of each other.