Anatomy of an LLM application: request, response, stop reason

Study time
≈ 2 h (estimate)
Needs
L1-M01-L02, L1-M01-L03
Updated
2026-11-06

Progress is saved in this browser only. No account, nothing is sent to a server.

Draft · reviewed by AI, not yet by a person. Content may change. English translation: AI-assisted, not human-reviewed.
On this page

Module: L1-M01 · Duration: ~120 min (estimate, including the independent exercise; L01 also includes first-time setup) · Previous: L03 · Next: L05 - LLM failure modes and a first test scenario

1. Introduction

The user only sees a chat box. Behind it is a chain of steps: the application builds the prompt, calls the model provider's API, receives a block of JSON, reads a few fields from it, and only then displays something.

Many bugs of AI features sit in this chain of steps and not in the model:

  • The application ignores the "the answer was cut off" signal.
  • The application does not handle the case where the model refuses to answer.
  • The application crashes when a field is null.

This lesson teaches you to read requests and responses like a tester. You do not call a real API yet; that starts in L1-M03. Here you work with fixtures (sample data) built according to the structure in the official documentation.

2. Learning objectives

  1. Identify the components of an LLM application and where defects can occur in each component.
  2. Read a response JSON from the Claude Messages API and from OpenAI Chat Completions, and point out the text, the stop reason and the usage.
  3. Explain the meaning of the main stop reasons, and the risk when an application ignores them.
  4. Implement and run deterministic checks for a response: truncated, refused, empty, over max_tokens.
  5. Design test cases for response handling without calling a real API.

3. Prerequisites and tools

  • L02 (tokens, max_tokens) and L03 (non-determinism).
  • JSON (JavaScript Object Notation): a text format for exchanging data, made of objects {"key": value}, arrays [...], strings, numbers, true/false and null. If you have tested REST APIs, you already know it.

4. Concepts

4.1 The components of an LLM application

Flow diagram: user → application (backend); 1. the application builds the prompt (system + history + message) into a JSON request; 2. sends it over HTTPS with an API key to the model provider's API; 3. the API returns a JSON response (content, stop reason, usage) to the application; 4. the application checks, parses and shows it to the user.
Diagram: The components of an LLM application
Component Example defects
Building the prompt Missing system prompt; user input inserted in the wrong place; history trimmed wrongly (L02)
Sending the request API key exposed on the client side; timeout; rate limit exceeded (a limit on the number of requests within a time window, L1-M03)
Response Truncated (max_tokens); refused; no text
Handling the response Ignoring the stop reason; parsing JSON wrongly; displaying an empty string

Everyday example. Ordering through a food-delivery app. You are the user, the app is the backend, the restaurant is the model provider, and the rider brings the result back. A defect can sit at each step: the app records the wrong dish (building the prompt), the order does not go through because the network drops (sending the request), the restaurant says the dish is sold out (refusal), or the app says "delivered" while the bag is empty (handling the response). A tester needs to know which step broke, not only that "the food did not arrive".

4.2 The request: basic parts

With the Claude Messages API, the three required parameters are model, max_tokens and messages. The messages have a role of user or assistant, usually alternating; the documentation states that consecutive turns with the same role are merged into one turn. There is also a top-level system parameter for setting the system prompt [R1].

A minimal request looks like this. It is an illustration and has not been sent anywhere:

{
  "model": "<tên model>",
  "max_tokens": 256,
  "system": "You are LinguaBot. Correct English grammar.",
  "messages": [
    {"role": "user", "content": "She go to school every day"}
  ]
}

(<tên model> is a placeholder for the model name.)

These concepts are present in almost every API: the system prompt (the developer's instructions), the messages (the conversation) and an output length limit. The field names and details differ, so a tester must read the documentation of exactly the API in use.

Good vs bad: a test case for the request-building step. Written in English because the dev team reads it:

Weak:  Send "She go to school every day". Expected: HTTP 200.

Good:  Send "She go to school every day". Capture the request JSON the app sent.
       Expected: "system" is present and equals the approved system prompt v3;
       messages[-1] is {"role": "user", "content": "She go to school every day"} (exact text);
       "max_tokens" is 256, the configured value.

HTTP 200 only proves the request went through, not that it was right. The good one catches "missing system prompt" or "user input inserted in the wrong place" from the table in section 4.1, defects that still return 200.

4.3 The response: three things a tester must always look at

  1. Content: the text the model generated.
  2. Stop reason: why the model stopped.
  3. Usage: the number of tokens used, which is also the basis for computing the cost.

An analogy: a response is like a delivered parcel. The content is the goods. The stop reason is the delivery note saying "delivered in full", "delivered short" or "delivery refused". The usage is the invoice. Opening the box without reading the delivery note is the easiest way to miss a defect.

Worked example: reading the three things in the fixture openai_refusal.json. The important part of the file: "content": null, "refusal": "I can't help with that.", "finish_reason": "stop", "usage": {"prompt_tokens": 40, "completion_tokens": 8, ...}. Let the lab's parser and checks read it (in the lab folder, with the venv active):

python -c "from lab.llm_response import load, qa_issues; r = load('fixtures/openai_refusal.json'); print(r); print(qa_issues(r, max_tokens=16))"
LLMResult(provider='openai', model='gpt-example-model', text=None, stop_reason='complete', raw_stop_reason='stop', input_tokens=40, output_tokens=8, refusal="I can't help with that.")
['model refused: "I can\'t help with that."', 'reply has no text']

Output run on 2026-11-06 on Python 3.14.6 and 3.12.3, Linux, identical on both versions. Read it by the three things:

  1. Content: text=None. There is nothing to display.
  2. Stop reason: stop, normalised to complete. If you only looked at this field, you would think everything is fine.
  3. Usage: 40 tokens in, 8 tokens out. There are 8 output tokens even though content is null: they sit in the refusal, and they may still be billed.

The tester's conclusion: only by reading all three (plus the refusal field) do you see that this is a refusal, and that the UI must show a friendly message instead of an empty box.

5. Technical deep dive

5.1 Claude Messages API: the response

According to the API reference [R1], the response has a type that is always "message", a role of "assistant", and a content that is an array of content blocks. A text block has the form {"type": "text", "text": ...}. The response also has model, stop_reason, stop_sequence and usage.

The stop_reason values listed in the documentation [R1]:

stop_reason Meaning (per the documentation) Risk if the application ignores it
end_turn The model stopped naturally -
max_tokens Reached the request's max_tokens limit or the model's maximum Displaying a truncated answer as if it were complete
stop_sequence Met a custom stop sequence - (usually intended)
tool_use The model calls one or more tools Treating it as "no answer" (L1-M05)
pause_turn A long-running turn was paused Displaying an unfinished result. The lab puts it in other and reports an issue for a human to look at (fail closed)
refusal The safety classifiers intervened because they detected a potential policy violation Displaying empty content or a confusing error
model_context_window_exceeded The model's context window was exceeded A truncated answer (L02)

usage has input_tokens and output_tokens, plus other fields for caching (temporarily storing a repeated part of the prompt to reuse it and reduce cost). The documentation also notes that the total number of input tokens is the sum of input_tokens, cache_creation_input_tokens and cache_read_input_tokens [R1]. This lab uses only the first two fields.

Good vs bad: the code that displays the reply.

# Weak: shows whatever text is there; a cut-off or refused reply looks normal
show(result.text)

# Good: decide from the stop reason, the refusal and the text together
issues = qa_issues(result, max_tokens=256)
if issues:
    show_friendly_notice(issues)
else:
    show(result.text)

The weak snippet shows the learner "For example, she" as if it were a complete sentence (fixture anthropic_max_tokens). The good one looks at stop_reason, refusal and the text together, exactly like the lab's qa_issues.

5.2 OpenAI Chat Completions: the response

According to the API reference [R2], the response has an object of "chat.completion", a choices array, and usage (prompt_tokens, completion_tokens, total_tokens). Each choice has a message (role, content) and a finish_reason, with the values stop, length, tool_calls, content_filter (and function_call, now deprecated).

Two points a tester needs to watch [R2]:

  • message.content can be null, for example when the model calls a tool.
  • message can have a refusal field holding the model's refusal message.

Everyday example. You receive a parcel with a valid tracking number, the slip says "delivered successfully", but the box only holds a note "the shop refused to sell this item". The slip says "success" (finish_reason: "stop"), the box is empty (content: null), and the reason is on the note (refusal). That is exactly the fixture openai_refusal.json in section 4.3.

5.3 Normalising into one shape

The two APIs use different names for the same idea: max_tokens versus length, input_tokens versus prompt_tokens. The lab builds a common class (a user-defined data type) LLMResult and maps the stop reasons into 5 groups: complete, truncated, tool_call, filtered, other.

Note: this mapping is a design choice of the lab, not a provider standard. For example, the lab puts pause_turn in other, because the right way to handle it depends on the application.

Everyday example. Two couriers write their statuses differently: courier A writes "Delivered", courier B writes "Đã giao". Your order-tracking app maps both to one shared status, "received", so the screen does not need to know each courier. If one day courier B adds a new status "Partly delivered" that the app does not know yet, the safe choice is to show "needs checking", not to assume "received". That is the lab's other and its fail-closed principle.

6. The QA perspective

  • What to test: how the application handles each stop reason; what the application does when the content is empty or null; whether usage is logged so that costs can be tracked; whether the application tolerates new fields it does not use.
  • Why: these are integration defects, they are deterministic, and they can be tested completely without calling a model. That is the cheapest and most stable kind of test you can write for an AI feature.
  • What can go wrong: a truncated answer is still displayed as normal; a refusal is displayed as an empty box; a crash because of None; costs are not tracked.
  • Expected behaviour (an example to agree with the team): on truncated, display it with a notice or automatically ask for the continuation; on filtered or a refusal, display an approved friendly message; on empty content, do not display an empty chat bubble.
  • How to detect: use a fixture for each kind of response, as in this lab. In L1-M03 you will learn how to record real responses to use as fixtures.
  • How to report: attach the response JSON (with sensitive data masked), the stop reason, and a screenshot of what the UI displayed.

Unit test or integration test? The tests in this lesson are unit tests: they check our code with fixed data and do not call a model. Integration tests (calling a real API) come in L1-M03.

7. Real-world scenarios

Scenario 1 - A truncated grammar explanation (fictional). An English-learning app sets max_tokens too low. The explanation stops at "For example, she". The fixture anthropic_max_tokens.json simulates exactly this situation. The application does not check stop_reason, so the learner sees an unfinished sentence. Test: with stop_reason = "max_tokens", the UI must display a notice, or the application must ask for the continuation.

Scenario 2 - A business assistant that uses several providers (fictional). The company switches from provider A to provider B. The old code checks finish_reason == "length", while the new provider returns stop_reason = "max_tokens". After the switch, no truncation warning fires any more. Test: a contract test suite that runs the same scenario on the fixtures of both providers.

8. Hands-on tutorial

8.1 The relevant structure

code-labs/l1-m01/
├── fixtures/
│   ├── anthropic_end_turn.json     # trả lời đầy đủ
│   ├── anthropic_max_tokens.json   # bị cắt
│   ├── openai_stop.json            # trả lời đầy đủ
│   └── openai_refusal.json         # content = null, có refusal
├── lab/llm_response.py
└── tests/test_llm_response.py

The comments in the tree read: complete answer; truncated; complete answer; content = null, with a refusal.

Every fixture is illustrative data. The structure follows the documentation [R1][R2], while the values (id, model, token counts) are made up. Each file has a _note field saying so. The parser ignores _note.

8.2 Reading the code

def from_anthropic(payload):
    texts = [block["text"] for block in payload["content"] if block.get("type") == "text"]
    raw = payload["stop_reason"]
    return LLMResult(
        provider="anthropic", model=payload["model"],
        text="".join(texts) if texts else None,
        stop_reason=ANTHROPIC_STOP.get(raw, "other"), raw_stop_reason=raw,
        input_tokens=payload["usage"]["input_tokens"],
        output_tokens=payload["usage"]["output_tokens"],
    )
  • content is an array of blocks. We take only the blocks with type == "text" and join them. A response can have several blocks, or no text block at all (for example only a tool call).
  • ANTHROPIC_STOP.get(raw, "other"): an unknown stop reason falls into other instead of causing a crash.
  • payload["usage"] uses [...], not .get. Missing usage is data that breaks the contract, so we want it to fail loudly (see test_missing_usage_fails_loudly).

qa_issues(result, max_tokens) returns a list of issues: refusal, truncated, filtered, an unhandled stop reason (other), no text, and output_tokens > max_tokens. An unknown stop reason is not ignored but reported: the fail closed principle.

8.3 Running the demo

python -m lab.llm_response

Actual output (2026-10-31, checked with max_tokens=16):

anthropic_end_turn     complete   in=42  out=7   issues=none
anthropic_max_tokens   truncated  in=42  out=16  issues=["reply truncated (stop reason 'max_tokens')"]
openai_stop            complete   in=40  out=6   issues=none
openai_refusal         complete   in=40  out=8   issues=['model refused: "I can\'t help with that."', 'reply has no text']

Reading the result:

  • Second line: the text looks like a normal sentence, but the stop reason says it was cut off. Only a stop-reason check can detect it.
  • Last line: finish_reason is stop (the complete group), but the model refused and content is null. If you rely only on the stop reason, you miss this defect. That is why you need several checks.

8.4 Running the tests

python -m pytest tests/test_llm_response.py -v

Expected result: 15 tests pass. Two parametrised tests check the stop-reason mapping table by changing the value in the fixture inside the test itself:

@pytest.mark.parametrize("raw, expected", [
    ("end_turn", "complete"), ("max_tokens", "truncated"), ("tool_use", "tool_call"),
    ("model_context_window_exceeded", "truncated"), ("pause_turn", "other"),
])
def test_anthropic_stop_reasons(raw, expected):
    data = payload("anthropic_end_turn")
    data["stop_reason"] = raw
    assert from_anthropic(data).stop_reason == expected

8.5 Troubleshooting

Symptom Cause Fix
FileNotFoundError: fixtures/... when running the demo Run in the wrong folder cd code-labs/l1-m01
json.decoder.JSONDecodeError A fixture you wrote yourself has invalid JSON syntax Check for trailing commas and double quotes
KeyError: 'usage' The fixture is missing usage This is the designed behaviour (fail loudly)

8.6 Safety when moving to a real API (L1-M03)

  • The API key lives only in an environment variable or a .env file. Never commit the .env file; commit only .env.example (this lab ships a sample file that contains no key).
  • Never call the API from code that runs in a browser or a mobile app, because users would see the key.
  • Set a spending limit in the provider account before running tests repeatedly.
  • Do not send real company or customer data into the lab. The model provider processes all the data you send.

9. Independent exercise

Problem: The fixture set does not yet cover the cases "OpenAI truncated" and "Claude refuses via the stop reason".

Requirements:

Copy the starter file exercises/test_l04_my_fixtures.py into tests/ and fill in the TODO places.

  1. Build payloads directly in code for two cases:
    • OpenAI: finish_reason = "length", unfinished content, completion_tokens = 16.
    • Claude: stop_reason = "refusal", content is an empty array, output_tokens = 0.
  2. Assert that qa_issues(..., max_tokens=16) reports the right issues for each case.
  3. Answer: why does the Claude refusal case produce two issues? Is that desirable or noise?

Deliverable: the test file and the answer.

Acceptance criteria: the tests pass; the payloads have all the fields the parser needs; the answer is reasoned.

Test data: the two payloads in requirement 1, max_tokens=16.

Hint: look at fixtures/*.json for the minimum fields. The parser does not need id or created. The parser for OpenAI is from_openai_chat(payload), for Claude from_anthropic(payload). Syntax note: when you write a dict in Python, JSON null becomes None, true becomes True, false becomes False. Alternatively, paste the raw JSON into a string and use json.loads(...).

9.1 Extra exercise: decide what the UI shows (20-25 minutes)

Problem: qa_issues lists the problems, but the screen needs one decision. The product team sets the rule: "show" when the stop reason is complete, there is text and no refusal; "show_with_notice" when truncated and there is text; "friendly_error" for every other case (refusal, filtered, tool_call, other, no text).

Requirements:

  1. Copy exercises/test_l04_extra_display.py into tests/ and run it once: 7 tests fail with TODO.
  2. Write display_decision(result) following that rule. It must look at refusal, the text and the stop reason.
  3. At TODO 2 (stop reason max_tokens but content is empty), write your prediction before running.

Acceptance criteria: 7 passed. You can explain why a function that only looks at the stop reason turns openai_refusal into "show".

Hint: compute has_text = bool(result.text and result.text.strip()) first, then look at the refusal and has_text before the stop reason.

9.2 Real-world scenario: a cut-off restaurant review summary (fictional)

Context. The fictional food-delivery app GiaoLe has a "summarise 200 reviews in 3 sentences" feature on each restaurant page. The QA team pulled three responses from the logs (data masked):

  • R1: stop_reason: "max_tokens", text "Món ăn ngon, giá hợp lý, nhưng nhiều khách phàn nàn về" ("Tasty food, fair prices, but many customers complain about"). The UI shows this sentence as is, with no notice.
  • R2: stop_reason: "refusal", content: []. The UI shows an empty white box.
  • R3: stop_reason: "end_turn", a complete 3-sentence text. The UI shows it normally.

Task: (a) write the expected UI behaviour for R1, R2 and R3; (b) write a bug report for R1; (c) propose 3 tests that run without calling the model.

A good answer has:

  • R1 treated as a defect: the sentence is cut exactly at the important part (the complaint) and can mislead customers
  • A concrete expected behaviour for R2 (an approved friendly message, or hiding the summary block), not just "do not show an empty box"
  • R3 treated as an integration pass, while noting that the summary's content still needs another oracle (L05)
  • A bug report with the response JSON (data masked), stop_reason, a screenshot of the UI, the configured max_tokens, and a severity with its reason
  • 3 tests that use a fixture for each kind of response, like the lab's fixtures/
  • Does not propose "raise max_tokens" as the only fix: the UI must still handle max_tokens

10. Knowledge check

0/20 done · Results are kept in this browser only.

P02 · True or false

If finish_reason is stop, you can be sure the response has text to display.

P03 · Match

Match each stop reason with its meaning:

P05 · Short answer

After a model change, costs doubled but nobody noticed for 2 weeks. Propose 2 tests or monitoring checks based on the usage field.

P06 · Fill in the blank

The three things a tester must always look at in a response: the content, ___ and ___.

P07 · Multiple choice

In the output of the demo python -m lab.llm_response, the anthropic_max_tokens line has text that looks like a normal sentence. Which check detects that it was cut off?

P08 · Spot the bug

The from_anthropic function below was copied from lab/llm_response.py but has one defect. Find it.

def from_anthropic(payload):
    texts = [block["text"] for block in payload["content"] if block.get("type") == "text"]
    raw = payload["stop_reason"]
    return LLMResult(
        provider="anthropic", model=payload["model"],
        text="".join(texts) if texts else None,
        stop_reason=ANTHROPIC_STOP[raw], raw_stop_reason=raw,
        input_tokens=payload["usage"]["input_tokens"],
        output_tokens=payload["usage"]["output_tokens"],
    )

P09 · Select all that apply

The openai_refusal line in the demo output: which issues does qa_issues report? Select all that apply.

P10 · True or false

The lab's mapping of pause_turn into the other group is a standard set by the provider.

P11 · Recall

Lesson: L1-M01-L02

Lesson L02: the max_tokens part only counts towards the context budget when the model uses all of it.

P13 · Multiple choice

In the worked example in §4.3, the fixture openai_refusal.json has content: null but usage still reports completion_tokens: 8. What does that tell a tester?

P14 · True or false

A test case that only asserts "the request returns HTTP 200" cannot detect a "missing system prompt" defect in the request.

P15 · True or false

In the output of the example in §4.3, the LLMResult for openai_refusal has stop_reason='complete' even though the model refused.

P16 · Put in order

Put the four steps of one model call in order, following the diagram in §4.1.

  1. It sends the request JSON over HTTPS with the API key
  2. The application checks, parses and displays it to the user
  3. The application builds the prompt: system, history and message
  4. The API returns a response JSON with content, stop reason and usage

P17 · Match

Under the rule of the extra exercise §9.1, match each lab fixture with the correct display decision.

P18 · Spot the bug

The function below is a wrong solution to the extra exercise §9.1. Find the defect.

def display_decision(result):
    if result.stop_reason == "complete":
        return "show"
    has_text = bool(result.text and result.text.strip())
    if result.refusal or not has_text:
        return "friendly_error"
    if result.stop_reason == "truncated":
        return "show_with_notice"
    return "friendly_error"

P19 · Recall

Lesson: L1-M01-L03

Lesson L03: from API version 2026-10-21, how does the Claude API handle a request that sends temperature?

P20 · Apply now

In code-labs/l1-m01, copy exercises/test_l04_extra_display.py into tests/, run python -m pytest tests/test_l04_extra_display.py once before changing anything, then do the extra exercise in §9.1 and run it again.

Checklist

11. Summary

  • Concepts: an LLM application has four steps: build the prompt, send the request, receive the response, handle the response. Every response has content, a stop reason and usage, with field names that differ between providers.
  • Skills: read a response JSON; normalise it; write deterministic checks; test with fixtures.
  • Traps: reading only the text and ignoring the stop reason; assuming there is always content; hard-coding one provider's field names; exposing the API key.
  • You can now: write a unit-test suite for the response-handling layer of an LLM feature.

12. References

ID Title Publisher URL Accessed Relevance
R1 Messages API reference Anthropic https://platform.claude.com/docs/en/api/messages 2026-10-31 Required parameters, response structure, the stop_reason values, the usage field
R2 Chat Completions - Create (API reference) OpenAI https://developers.openai.com/api/reference/resources/chat/subresources/completions/methods/create 2026-10-31 Structure of choices, finish_reason, usage, content can be null, refusal
R3 Context windows (overflow behavior) Anthropic https://platform.claude.com/docs/en/build-with-claude/context-windows 2026-10-31 model_context_window_exceeded

Version note: model providers' APIs change often. The list of stop reasons and the usage fields were read on 2026-10-31. Check them again before teaching.

Key terms (English ↔ Vietnamese)

English Tiếng Việt
Request / Response Yêu cầu gửi đi / Phản hồi nhận về
System prompt Chỉ dẫn của nhà phát triển, đặt trước hội thoại
Stop reason / Finish reason Lý do model dừng sinh output
Usage Số token đã dùng
Fixture Dữ liệu mẫu cố định dùng trong test. Lưu ý: trong pytest, @pytest.fixture là hàm chuẩn bị dữ liệu hoặc đối tượng cho test, khác nghĩa với file fixture JSON ở bài này
Refusal Model từ chối trả lời
Contract test Test kiểm tra hai bên tuân thủ cùng một "hợp đồng" dữ liệu
Truncated Bị cắt cụt