Skip to content

1.4 Chain of Thought

Why a Model Reasons Better Step by Step

Figure 4. Direct answer vs Chain of Thought.

Figure 4. Direct answer vs Chain of Thought.

When we ask a model to solve a complex problem (whether logical inference, analysis of a situation, or planning), we often get a pale, superficial answer. And often a wrong one. But if we explicitly ask the model to show its reasoning, to work through the task step by step, the quality of the answer improves dramatically (Fig. 4). This phenomenon is the basis of the Chain of Thought (CoT) technique. The idea is simple: instead of asking the model for a direct answer, we ask it to think out loud, show intermediate steps, and explain the logic. In a way, the model forces itself to work through the task more carefully, instead of simply spitting out the first value that comes to mind.

Why does this work? Partly because generative models work token by token. If a model gives a direct answer, it can make a mistake at the very first step, and there is no way to go back. But if the model unfolds its reasoning, it builds a chain of logic in which each step relies on the previous one. An error at an early step is still possible, but overall reliability is higher.

Explicit reasoning also helps us as developers. If something goes wrong, we can see exactly where the model made a mistake. We can debug the system, understand its weak spots, and add additional checks.

The Basic Chain of Thought Architecture

Figure 5. Chain of Thought architecture.

Figure 5. Chain of Thought architecture.

Implementing CoT is fairly simple. You add an instruction to the prompt asking the model to reason step by step, and then build logic (Fig. 5) that either accumulates these reasoning steps in the context or parses them as separate steps:

class ChainOfThoughtReasoner:
    def __init__(self, client):
        self.client = client

    def solve_multi_step_problem(self, case_description):
        steps = [
            ("analyze", "Analyze the described situation. Identify the key facts and constraints."),
            ("identify_options", "What solution options are possible? List all the ones you see."),
            ("evaluate_options", "Evaluate each option by criteria: cost, time, risks. Use a table format."),
            ("recommend", "Based on the evaluation, formulate a recommendation with justification.")
        ]

        context = f"Situation description:\n{case_description}\n\n"
        results = {}

        for step_name, step_instruction in steps:
            prompt = f"{context}Task: {step_instruction}"
            response = self.call_model(prompt)
            results[step_name] = response
            context += f"\n{step_name.upper()}:\n{response}\n"

        return results

    def call_model(self, prompt):
        response = self.client.responses.create(
            model="gpt-5-mini",
            input=[{"role": "user", "content": prompt}],
            temperature=0
        )
        return response.output_text

Here we define the sequence of steps the model must go through. At each step the model gives an answer, and this answer is embedded in the context for the next step. This creates a chain in which each step builds on the previous one.

This approach has several advantages. First, each step can be checked and debugged independently of the others. If the model chose the wrong option at step 2, we will see it and can add validation or clarification. Second, intermediate results can be cached and reused: if the same analysis is needed for several options, there is no need to recompute it. And finally, when something fails, it is easy to tell at which stage of the reasoning the failure occurred.

Handling Structured Responses

When we ask the model to produce answers in a specific format (JSON, a table, a list), we need to make sure the model actually follows the format. Otherwise, downstream processing will break.

A combination of regular expressions for simple cases and JSON schemas for complex structures is a reliable approach. Here is an example with a schema:

import json
from jsonschema import validate, ValidationError

DECISION_SCHEMA = {
    "type": "object",
    "properties": {
        "decision": {"type": "string", "enum": ["APPROVE", "REJECT", "ESCALATE"]},
        "confidence": {"type": "number", "minimum": 0, "maximum": 1},
        "reasoning": {"type": "string", "minLength": 10},
        "conditions_checked": {
            "type": "array",
            "items": {"type": "string"}
        }
    },
    "required": ["decision", "confidence", "reasoning"]
}

def extract_and_validate_decision(model_response):
    json_match = re.search(r'\{.*\}', model_response, re.DOTALL)
    if not json_match:
        return None, "JSON not found in the response"

    try:
        decision = json.loads(json_match.group())
    except json.JSONDecodeError as e:
        return None, f"JSON parsing error: {e}"

    try:
        validate(decision, DECISION_SCHEMA)
    except ValidationError as e:
        return None, f"Schema validation error: {e.message}"

    return decision, None

The function searches the response for JSON, parses it, and checks it against the schema. If something does not match, it returns a description of the error. This description can later be used for retry logic.

Here is how to organize retries with clarification:

def get_validated_decision(prompt, max_retries=3):
    for attempt in range(max_retries):
        response = call_model(prompt)
        decision, error = extract_and_validate_decision(response)

        if decision:
            return decision

        if attempt < max_retries - 1:
            prompt = f"""{prompt}

WARNING: The previous response did not pass validation.
Error: {error}
Please return the answer strictly in the specified JSON format."""

    return None

If the response fails validation, we generate a new request that describes the error, so the model understands what went wrong and tries to correct it. This works quite well: models can usually fix format errors if the problem is explained to them clearly.

Chain of Thought is especially useful in educational applications. Imagine a system that helps students solve problems. Instead of simply giving the answer, the system can show a step-by-step solution, explaining each step the way a teacher would.

EDUCATIONAL_PROMPT = """You are a patient math teacher.

Problem: {problem}

Solve the problem, explaining each step so that the student can follow the logic.

Structure of the explanation:
1. GIVEN: list the known quantities and their notation
2. FIND: formulate what needs to be determined
3. SOLUTION IDEA: explain the general approach to the solution
4. STEP-BY-STEP SOLUTION: carry out the solution, commenting on each action
5. CHECK: show how to make sure the answer is correct
6. ANSWER: write the final answer

Begin the explanation:"""

Such a prompt ensures that the model does not just give a formula but actually works through the logic of the solution. The student sees not only what to do but also why. In addition, the step-by-step structure makes debugging easier: if the model made a mistake, you can see at which step it happened.

Typical Mistakes

Chain of Thought is a powerful technique, but it has limitations that matter when you deploy it in production.

The most obvious one: the answer becomes much longer. If a direct answer took, say, 100 tokens, detailed reasoning can take 500–1000 tokens. That means higher API costs and increased latency. For tasks where accuracy is critical and speed is secondary, this is an acceptable trade-off. But for high-load systems with strict latency requirements, apply CoT selectively: use it for complex requests, and give direct answers for simple questions.

The second problem: the model can produce perfectly logical-looking reasoning that actually contains a hidden error. If the model drew a wrong conclusion at step 1, the following steps will be built on that error, and the result will be wrong but well argued. The self-consistency technique helps reveal such cases: we generate several independent reasoning chains with different random seeds and check whether the answers converge.

def solve_with_self_consistency(problem, num_samples=5):
    responses = []
    for _ in range(num_samples):
        response = call_model_with_cot(problem, temperature=0.7)
        answer = extract_final_answer(response)
        responses.append(answer)

    answer_counts = Counter(responses)
    most_common_answer, count = answer_counts.most_common(1)[0]
    confidence = count / num_samples

    return {
        "answer": most_common_answer,
        "confidence": confidence,
        "all_answers": dict(answer_counts)
    }

Here we can check: if several independent attempts gave the same answer, it is most likely correct. If the answers diverge, that is a signal that the task is harder than we thought, or that the model is not very sure about it.

The third point: for tasks that require specialized knowledge, the model can generate convincing reasoning that contains factual errors. The model is confident but wrong. In such cases, verifying results against external sources or human review remains necessary for critical applications.

Questions for Reflection and Practice

Theoretical questions

  1. Explain why unfolding the reasoning explicitly improves the quality of the model's answers.

  2. What is the difference between a direct answer and Chain of Thought in terms of ease of debugging?

  3. How do you build a chain of reasoning so that each step is verifiable and can be debugged independently?

  4. Which types of tasks benefit the most from Chain of Thought?

  5. Explain the self-consistency technique and the problem it solves.

  6. How does the application context (educational, business, technical) affect the structure of a prompt with reasoning?

  7. What limitations does the Chain of Thought approach have, and when is its use ineffective or even harmful?

  8. How do you design a validation system for structured model responses and handle format errors?

  9. Explain the trade-off between reasoning depth, cost, and system performance.

  10. What strategies can be used to verify the correctness of intermediate reasoning steps?

Practical exercises

  1. Implement the function build_cot_prompt, which adds step-by-step reasoning instructions to an arbitrary task.

  2. Create a function extract_final_answer that extracts the final answer from a detailed reasoning by a marker or position.

  3. Implement the class StructuredReasoner with a method for multi-step analysis where each step builds on the results of the previous ones.

  4. Build a system for validating structured responses with a JSON schema and retry logic for fixing format errors.

  5. Implement the function solve_with_self_consistency, which generates several independent solutions and computes confidence based on consensus.

  6. Create the class AdaptiveQueryProcessor, which automatically chooses between a direct answer and Chain of Thought based on an estimate of the question's complexity.

  7. Build a system for an educational scenario that generates step-by-step explanations of problem solutions, adapted to the student's level.

  8. Implement monitoring of reasoning-chain quality: logging, analysis of error frequency at different steps, and automatic suggestions for improving prompts.