LLM API in Practice: Building a Complete AI Chat Application

    This article explains how to build a complete AI chat application using LLM APIs. It compares chat completion, message-based conversation, and task-based response APIs; covers session storage, context trimming, SSE streaming, tool calls, and structured JSON output; and outlines rate limiting, key management, moderation, log redaction, observability, and an acceptance checklist for production launch.

    1. Before You Start: What You Need

    Before you begin, confirm three things. First, you can read HTTP requests and responses and understand the basic format of SSE (Server-Sent Events). Second, you have a storage option for conversation data, such as a relational database or Redis. Third, you can inspect logs and monitoring metrics, because most production issues are diagnosed from this information.

    The examples in this article use an OpenAI-style API as a reference. Field names and details may differ between providers. Before integration, verify request fields, message roles, and streaming formats against the relevant API documentation.

    2. Choosing Among Three API Types

    Mainstream LLM APIs generally provide three calling patterns.

    1. Chat completion API. The client sends the system prompt, message history, and latest input to the server as a whole, and the model returns one complete result. The server does not store conversation state; the client maintains the full context.

    2. Message-based conversation API. The server stores the message list as a conversation object. The client appends messages and retrieves history by conversation ID. The client does not need to store the full history, which makes this pattern suitable for sharing the same conversation between web and mobile clients.

    3. Task-based response API. This type uses tasks as the unit of work and supports asynchronous execution, event callbacks, and multi-step orchestration. It fits multi-turn tool calling or Agent tasks that take longer to run.

    When selecting an API, do not rely only on scenario names. Consider the following three conditions.

    Decision condition Preferred choice
    The team already has mature conversation storage and wants full control over context Chat completion
    Multi-client synchronization is required, and you do not want to build message persistence yourself Message-based conversation
    A single task takes more than tens of seconds or includes multi-step tool calls Task-based response

    In practice, many teams first get the main path working with chat completions because it is the easiest to debug. When more complex features appear, they migrate the relevant modules to the task-based API. Both API types can coexist in the same application.

    3. Session Management and Context Trimming

    The client needs to maintain a session_id, a messages list, and token usage statistics for each session. The model has a limited context window, so you need to estimate length before sending a request.

    A simple budget formula is:

    1. available history budget = model context limit - system prompt tokens - reserved output tokens - safety margin

    A safety margin of 5% to 10% of the limit is recommended to offset token estimation errors. When history tokens exceed 80% of the budget, trigger trimming.

    There are three common trimming strategies.

    • Sliding window: keep only the most recent N turns. This is the simplest approach, but it can lose important information from earlier turns.
    • Summary compression: ask the model to summarize earlier conversation and replace the original text with the summary. The summary should preserve the user’s goals, constraints, and confirmed facts.
    • Hybrid strategy: keep the system prompt intact, summarize the middle history, and retain the most recent turns as original text. Most chat applications use this approach.

    Completion criteria: in a long conversation that exceeds the context limit, requests do not fail, and the model can still correctly answer questions related to earlier agreements.

    4. Streaming Output

    Streaming APIs return incremental content over SSE. Each event starts with data:, events are separated by blank lines, and the stream ends with data: [DONE]. Because network fragmentation can split an event, the frontend must buffer data first and then parse complete events.

    The following example shows the correct parsing flow. Note that it runs behind a backend proxy; the API key must not appear in browser code.

    1. async function* streamChat(messages) {
    2. const resp = await fetch("/api/chat", { // Forwarded by a backend proxy; the key stays on the server
    3. method: "POST",
    4. headers: { "Content-Type": "application/json" },
    5. body: JSON.stringify({ messages, stream: true }),
    6. });
    7. if (!resp.ok) throw new Error(`HTTP ${resp.status}`);
    8. const reader = resp.body.getReader();
    9. const decoder = new TextDecoder();
    10. let buffer = "";
    11. while (true) {
    12. const { done, value } = await reader.read();
    13. if (done) break;
    14. buffer += decoder.decode(value, { stream: true }).replace(/\r\n/g, "\n");
    15. let idx;
    16. while ((idx = buffer.indexOf("\n\n")) !== -1) {
    17. const frame = buffer.slice(0, idx);
    18. buffer = buffer.slice(idx + 2);
    19. for (const line of frame.split("\n")) {
    20. if (!line.startsWith("data:")) continue;
    21. const payload = line.slice(5).trim();
    22. if (payload === "[DONE]") return;
    23. let chunk;
    24. try {
    25. chunk = JSON.parse(payload);
    26. } catch {
    27. continue; // Skip non-JSON lines and log them
    28. }
    29. const delta = chunk.choices?.[0]?.delta?.content;
    30. if (delta) yield delta;
    31. }
    32. }
    33. }
    34. }
    35. // Caller
    36. for await (const text of streamChat(messages)) {
    37. appendToUI(text);
    38. }

    This code has three important points. First, { stream: true } lets the decoder correctly handle truncated multi-byte characters, such as Chinese. Second, an event is parsed only when the blank-line separator is found. Third, use only delta.content; do not render raw chunks directly to the page.

    Completion criteria: send multiple messages continuously under weak network conditions. The text shown on the page exactly matches the content returned by the server, with no garbled characters, duplication, or missing characters.

    5. Tool Calling

    Tool calling lets the model request external capabilities, such as checking the weather or reading an order. The complete flow has five steps.

    1. Declare the tool name, description, and JSON Schema parameters in the request.
    2. The model returns an assistant message with tool_calls, and each call has a unique id.
    3. The client executes the corresponding local function and sends the result back in a message with role set to tool, including the matching tool_call_id.
    4. The client appends the result to the message list and sends another request to the model.
    5. The model generates the final answer based on the tool result.

    The structure of the returned messages is as follows:

    1. [
    2. {"role": "user", "content": "What is the weather in Beijing today?"},
    3. {
    4. "role": "assistant",
    5. "content": null,
    6. "tool_calls": [{
    7. "id": "call_8f2a",
    8. "type": "function",
    9. "function": {"name": "query_weather", "arguments": "{\"city\": \"Beijing\"}"}
    10. }]
    11. },
    12. {"role": "tool", "tool_call_id": "call_8f2a", "content": "{\"city\": \"Beijing\", \"temp_c\": 22, \"weather\": \"cloudy\"}"}
    13. ]

    Below is a Python example of executing a tool on the server. It handles both argument parsing failures and function exceptions, and ensures that every tool_call_id has a corresponding returned message. Otherwise, the next request will usually fail.

    1. import json
    2. def query_weather(city: str) -> dict:
    3. # In a real project, call a weather service here
    4. return {"city": city, "temp_c": 22, "weather": "cloudy"}
    5. TOOL_HANDLERS = {"query_weather": query_weather}
    6. def handle_tool_calls(messages: list, assistant_msg: dict) -> list:
    7. messages.append(assistant_msg)
    8. for call in assistant_msg.get("tool_calls", []):
    9. name = call["function"]["name"]
    10. try:
    11. args = json.loads(call["function"]["arguments"])
    12. handler = TOOL_HANDLERS[name] # An unregistered tool raises KeyError
    13. result = handler(**args)
    14. except Exception as e:
    15. result = {"error": f"{type(e).__name__}: {e}"} # Errors must also be returned to the model
    16. messages.append({
    17. "role": "tool",
    18. "tool_call_id": call["id"],
    19. "content": json.dumps(result, ensure_ascii=False),
    20. })
    21. return messages

    Tool descriptions directly affect whether the model calls a tool correctly. A description should state when to use the tool and when not to use it, and should specify the allowed parameter values. For example, “Use only when the user asks about real-time weather in a specific city; do not use for historical weather or climate questions” is more effective than “Query weather.”

    Completion criteria: the model calls the tool once for a question such as “weather in Beijing” and does not call the tool for a question such as “why does it rain?” The answer is correct in both cases.

    6. Structured Output

    For information extraction, the model often needs to output JSON in a fixed format. Some providers offer JSON mode or schema constraints, but support varies by model and version. Even when constraints are enabled, the client must validate the output itself.

    The following example feeds validation errors back to the model for retry and falls back after the maximum number of attempts.

    1. import json
    2. def extract_with_retry(call_model, messages, validate, max_retries=2):
    3. """call_model receives a message list and returns the model output string."""
    4. current = list(messages)
    5. for attempt in range(max_retries + 1):
    6. raw = call_model(current)
    7. try:
    8. data = json.loads(raw)
    9. validate(data) # Raise ValueError if validation fails
    10. return {"ok": True, "data": data}
    11. except (json.JSONDecodeError, ValueError) as e:
    12. if attempt == max_retries:
    13. break
    14. current.append({
    15. "role": "user",
    16. "content": f"The previous output did not meet the requirements: {e}. Output only valid JSON that meets the requirements, with no explanation.",
    17. })
    18. # Fallback: return a recognizable failure result; the business decides whether to escalate or use a default
    19. return {"ok": False, "data": None, "reason": "schema_validation_failed"}

    Completion criteria: with constructed invalid inputs, the function returns a valid result within the maximum number of retries, or returns ok: false, without throwing an uncaught exception that interrupts the main flow.

    7. Production Safeguards

    A production environment needs the following items, and each should be implemented with a concrete approach.

    1. Rate limiting and retries. Use exponential backoff with jitter for 429 and 5xx errors. A set of reference parameters is: base delay 0.5 seconds, multiplier 2, per-attempt delay cap 8 seconds, and up to 4 retries. If the response header includes Retry-After, wait according to it first. Retry only idempotent or safely replayable requests to avoid duplicate charges or duplicate writes.

    1. import random, time
    2. def call_with_backoff(send, max_retries=4, base=0.5, cap=8.0):
    3. for attempt in range(max_retries + 1):
    4. resp = send()
    5. if resp.status_code not in (429, 500, 502, 503, 504):
    6. return resp
    7. if attempt == max_retries:
    8. return resp
    9. retry_after = resp.headers.get("Retry-After")
    10. if retry_after and retry_after.isdigit():
    11. delay = float(retry_after)
    12. else:
    13. delay = min(cap, base * (2 ** attempt)) * random.uniform(0.5, 1.0)
    14. time.sleep(delay)

    2. API key management. Store keys only in environment variables or a secrets management service. Do not put them in code, configuration files, or frontend bundles. Grant keys the minimum required permissions and usage limits, and rotate them regularly. If leakage is suspected, revoke and reissue immediately.

    3. Input and output moderation. Check user input before sending requests and check model output before returning it. For sensitive scenarios such as medical, financial, or minors-related use cases, set up a human review queue. Record moderation results to support appeals and postmortems.

    4. Log redaction. Log request IDs, latency, token usage, and error codes. Do not log full user messages, phone numbers, ID numbers, or keys. Before writing logs, filter sensitive content with regular expressions or a field allowlist.

    5. Observability and cost control. Track token consumption by session and by user, and set daily quotas and alert thresholds. Monitoring metrics should include at least first-token latency, total latency, error rate, and retry count.

    8. Launch Acceptance Checklist

    Proceed in the following order, and move to the next step only after the current step passes acceptance.

    1. Minimum closed loop: a single-turn question-and-answer flow runs completely from input to display. Completion criteria: the same question sent three times in a row receives a valid answer each time.
    2. Multi-turn and streaming: multi-turn context is passed correctly, and streaming output has no garbled or missing characters. Completion criteria: a question in the third turn can reference information from the first turn.
    3. Tool calling: the tool call and result-return flow is complete. Completion criteria: when a tool returns an error, the model gives a reasonable explanation instead of crashing or fabricating a result.
    4. Structured output: extraction results pass schema validation. Completion criteria: constructed invalid inputs do not interrupt the service.
    5. Production readiness: rate limiting, key management, moderation, redaction, and monitoring are all online. Completion criteria: after simulated 429 responses and timeouts, the system recovers automatically, and no sensitive information appears in logs.

    The overall timeline depends on requirement scope, team experience, testing investment, and the progress of compliance review. If the team is familiar with HTTP and backend development and the requirement scope is clear, you can first estimate the schedule against the checklist above and then adjust the plan based on actual conditions.