🤖AI/ML

Chain of Thought

Chain of Thought / CoT Prompting

A prompting technique that guides an LLM to reason step by step. Improves complex problem-solving ability.

📖 Detailed Explanation

Chain of Thought (CoT) is a prompting technique that induces large language models (LLMs) to explicitly generate intermediate reasoning steps when solving complex reasoning problems. It was first proposed in the 2022 Google Research paper "Chain-of-Thought Prompting Elicits Reasoning in Large Language Models."

The core idea of CoT is simple. If you add a phrase such as "Let's think step by step" or include worked solutions in the examples, the LLM generates the reasoning process first instead of outputting the answer right away. These intermediate steps greatly improve the accuracy of the final answer.

CoT is particularly effective for math problems, logic puzzles, and questions that require multi-step reasoning. On GSM8K (a math benchmark), the accuracy of the PaLM 540B model improved more than threefold, from 17.9% without CoT to 56.9% with CoT. The larger the model, the more pronounced the effect of CoT.

In practice, CoT is widely used for complex analysis tasks, code debugging, and explaining decisions. Advanced techniques such as Self-Consistency (majority voting) and Tree of Thoughts (branching search) are also based on CoT. Recent LLMs such as GPT-4 and Claude are trained to perform similar reasoning internally even without CoT.

💻 Code Example

# OpenAI API를 사용한 Chain of Thought 프롬프팅
from openai import OpenAI

client = OpenAI()

# 일반 프롬프트 (CoT 없음)
standard_prompt = """
Q: 농장에 닭 23마리와 소 7마리가 있습니다. 다리는 총 몇 개일까요?
A:
"""

# Chain of Thought 프롬프트
cot_prompt = """
Q: 농장에 닭 23마리와 소 7마리가 있습니다. 다리는 총 몇 개일까요?

단계별로 풀어봅시다:

1단계: 닭의 다리 수 계산
- 닭은 2개의 다리를 가지고 있습니다
- 23마리 x 2개 = 46개

2단계: 소의 다리 수 계산
- 소는 4개의 다리를 가지고 있습니다
- 7마리 x 4개 = 28개

3단계: 전체 다리 수 합산
- 46 + 28 = 74개

A: 총 74개의 다리가 있습니다.

---

Q: 가게에서 사과 15개를 샀습니다. 5개를 먹고, 친구에게 3개를 줬습니다.
남은 사과로 각각 2개씩 담은 봉지를 만들면 몇 봉지가 될까요?

단계별로 풀어봅시다:
"""

# Zero-shot CoT (가장 간단한 방법)
zero_shot_cot = """
Q: 상자에 공이 12개 있습니다. 빨간 공은 파란 공보다 4개 많습니다.
파란 공은 몇 개일까요?

Let's think step by step.
"""

def solve_with_cot(prompt):
    response = client.chat.completions.create(
        model="gpt-4",
        messages=[
            {"role": "system", "content": "수학 문제를 단계별로 풀어주세요."},
            {"role": "user", "content": prompt}
        ],
        temperature=0
    )
    return response.choices[0].message.content

# 실행
print("=== Zero-shot CoT 결과 ===")
print(solve_with_cot(zero_shot_cot))

# Self-Consistency: 여러 번 샘플링 후 다수결
def solve_with_self_consistency(question, n_samples=5):
    answers = []
    for _ in range(n_samples):
        response = client.chat.completions.create(
            model="gpt-4",
            messages=[{"role": "user", "content": question + "\nLet's think step by step."}],
            temperature=0.7  # 다양성을 위해 temperature 설정
        )
        # 최종 답변 추출 로직 (간소화)
        answers.append(response.choices[0].message.content)
    return answers  # 실제로는 답변에서 숫자를 추출해 다수결

🗣️ Examples of Practical Conversations

In a Technical Meeting

"Our customer inquiry classification accuracy is low, but if we add a CoT instruction such as 'First, identify the main issue. Then, categorize based on our taxonomy.' to the system prompt, the basis for each classification becomes clearer and accuracy improves too."

Interview Question

"Zero-shot CoT only adds 'Let's think step by step,' whereas Few-shot CoT also provides examples that include the solution process. The effect becomes clearly noticeable when the model size is 100B or more."

In a code review

"In the debugging agent, we need to parse the CoT output, so please specify a delimiter such as 'Final Answer:' in the prompt so that the reasoning process and the final answer can be easily separated."

Take a mock interview on this topic → WIA SOOM AI Interview · Start for free

⚠️ Cautions

📏
Increased Token Cost

Because CoT generates intermediate reasoning steps, output tokens increase by 2-5 times. When processing large volumes, you need to consider API costs and latency.

🔢
Ineffective in Small Models

CoT is effective in large models with roughly 100B parameters or more. In smaller models, it can instead lead them down incorrect reasoning paths.

🎯
Unnecessary for Simple Tasks

For tasks such as sentiment analysis or simple classification, CoT can actually degrade performance. Apply it only to tasks that require complex reasoning.

🔗 Related Terms

📚 Learn More