Building LLM Applications After APIs Open: Layers, Access, Context, and Cost
After model providers expose chat, streaming, and multi-turn context through APIs, product work shifts toward engineering structure and cost control. This guide covers a five-layer chat architecture, credential handling, request retries, conversation state, streaming, context strategies, usage control, security, and how to choose between direct calls, a gateway, and a third-party framework.
Why this matters
Building a conversational product used to mean handling model capability, the user interface, session storage, and usage tracking as separate pieces of work. Once a provider exposes core capabilities—chat, streaming output, and multi-turn context—as APIs, the main barriers move to engineering organization and cost control. With one set of credentials, developers can call multiple kinds of endpoints and spend their effort on business logic and user experience instead of rebuilding the underlying stack.
This style of openness creates three immediate changes. First, capability is obtained through on-demand calls rather than an all-in-one subscription. Second, the application shape is defined by the developer and is no longer tied to one fixed client. Third, differentiation comes more from data, scenarios, and experience design; access to the underlying model is no longer a barrier by itself.
Open APIs are not the same as free or unlimited use. Quotas, concurrency limits, billing units, and the list of available models are defined by the provider’s official documentation. This article does not commit to any specific numbers. The examples are structural illustrations only.
What layers make up a chat application
A complete chat application can usually be split into five layers. Clear boundaries make ownership and replacement easier.
- Access layer: authentication, request construction, timeouts, and retries. This is the only place that calls the model API directly.
- Session layer: stores each user’s message history and decides which messages are sent with the current request.
- Business layer: system prompts, role settings, tool calls, result checks, and other business rules.
- Presentation layer: shows model output as a stream or as a complete reply, and handles interruption and regeneration.
- Observability layer: records latency, usage, error codes, and user feedback so later optimization has data.
The value of this split is that when the provider changes parameters or models, the change usually stays in the access layer. The other layers remain stable.
Key steps in the access flow
Credential management
Store credentials in environment variables or a dedicated secrets service. Do not put them in source code, configuration files, or logs. A front-end page should not hold credentials; all requests should go through your own backend. That reduces the chance of a leak and lets the server apply rate limits and auditing in one place.
Sending a request
The example below uses the Python standard library to send a JSON request with retries. In a real integration, replace the path, field names, and response shape with what the chosen service documents.
import jsonimport osimport timeimport urllib.errorimport urllib.requestAPI_BASE_URL = os.environ["LLM_API_BASE_URL"]API_KEY = os.environ["LLM_API_KEY"]MODEL_NAME = os.environ.get("LLM_MODEL_NAME", "")RETRYABLE_CODES = {429, 500, 502, 503}def post_json(path, payload, max_retries=3):url = API_BASE_URL.rstrip("/") + pathdata = json.dumps(payload).encode("utf-8")for attempt in range(max_retries):req = urllib.request.Request(url,data=data,headers={"Content-Type": "application/json","Authorization": f"Bearer {API_KEY}",},method="POST",)try:with urllib.request.urlopen(req, timeout=60) as resp:return json.loads(resp.read().decode("utf-8"))except urllib.error.HTTPError as err:is_last = attempt == max_retries - 1if err.code in RETRYABLE_CODES and not is_last:time.sleep(2 ** attempt) # exponential backoffcontinueraiseraise RuntimeError("request failed after the maximum number of retries")
This function only handles transport-level problems. A 429 means rate limiting was hit. 5xx responses are usually temporary server faults. Both are reasonable candidates for backoff and retry. Parameter errors and authentication failures among 4xx responses should be raised immediately; retrying will not fix them.
Handling multi-turn chat
Multi-turn chat means each request carries the previous messages. The application maintains the message list and appends the model reply after each turn.
def chat(history, user_input, system_prompt="You are a careful technical assistant."):history.append({"role": "user", "content": user_input})messages = [{"role": "system", "content": system_prompt}] + historypayload = {"model": MODEL_NAME, "messages": messages}result = post_json("/chat/completions", payload) # path is illustrative onlyreply = result["choices"][0]["message"]["content"]history.append({"role": "assistant", "content": reply})return reply
This snippet omits error handling and persistence. In a real project, roll back the last user message if the request fails so local session state does not diverge from what the service recorded.
Streaming output
Streaming lets users see the first text sooner, which is a clear improvement over waiting for the full reply. Servers usually return content in chunks. The client concatenates those chunks and renders them as they arrive. Three details matter: chunk boundaries can split multi-byte characters; if the user leaves the page mid-stream, cancel the upstream request so quota is not wasted; and write the session store only after the stream finishes, so incomplete content is not saved.
Context and session management
Context length is limited. Letting history grow without bound slows requests, raises cost, and eventually exceeds the model’s input limit. Three common approaches are used.
- Sliding window: keep only the most recent turns. It is simple to implement, but early agreements can be lost.
- Summary compression: periodically ask the model to compress older dialogue into a summary and place that summary in the system prompt. Long-term information can be kept, but later answers depend on summary quality.
- Retrieval augmentation: split history, store it in a vector index, and recall relevant passages for the current question. This fits knowledge-heavy scenarios, but it needs extra storage and retrieval components.
The right choice depends on the scenario. Customer-support chats often use a sliding window plus markers for key facts. Long-document collaboration is a better fit for combining summaries with retrieval.
Usage and cost control
Token-based metering is a common billing model, and input and output are often billed separately. Cost work usually starts in these places:
- Shorten the system prompt: remove repeated wording and keep fixed rules in one place so each turn sends less input.
- Cap output length: set a reasonable upper bound for the business so a single request cannot produce an extremely long reply.
- Cache stable results: when the same input always yields a result that does not change over time, cache the response in the application.
- Record usage in detail: break it down by user, feature, and model so high-cost paths can be found.
- Set budget alerts: notify an owner when daily usage nears a threshold, and optionally fall back to a lower-cost model.
Usage accounting should be done on the server and stored. Front-end estimates alone often disagree with the bill.
Security and compliance
Security risk in a chat application clusters in three places.
The first is credential safety. If credentials leak, someone else can spend the quota. Rotate keys on a schedule, use separate credentials per environment, and enable secret scanning in the code repository.
The second is input and output checks. User input may try to override system instructions. Do not splice user text directly into a privileged prompt. Before model output is used to run an action, render HTML, or write to a database, validate and escape it.
The third is data privacy. Conversations may contain personal information or business secrets. Tell users how data is handled, limit sensitive fields in logs, and follow the rules that apply in your region for cross-border transfer and retention.
Choosing and evaluating an approach
The same feature can be built in more than one way. Compare these dimensions when choosing.
| Dimension | Direct calls | Self-built gateway | Third-party framework |
|---|---|---|---|
| Time to start | Fast | Medium | Fast |
| Credential safety | Depends on isolating the front end | Centralized | Depends on framework configuration |
| Observability | Must be added yourself | Easy to instrument in one place | Depends on the framework |
| Long-term maintenance | Low | Medium | Must track framework versions |
For many teams, a sound path is to validate the requirement with direct calls, then move to a self-built gateway once the feature is stable, so authentication, rate limiting, and observability sit in one place.
Before release, set up an evaluation process. Prepare a set of representative questions and record answer quality, average response time, and cost per call after each version change. Use those measurements, not a general impression, to decide whether to ship.
Summary
Open APIs lower the cost of starting a chat application, but long-term operation depends on engineering quality. Focus on layered design, credentials and security, context management, and cost observability. A steady order of work is to build a clear access layer first, then improve session handling and observability.
