Chain-of-Thought
Chain-of-Thought Prompting (CoT)
A prompting technique that guides an LLM to perform step-by-step reasoning. Improves complex problem-solving ability.
Chain-of-Thought Prompting (CoT)
A prompting technique that guides an LLM to perform step-by-step reasoning. Improves complex problem-solving ability.
Chain-of-Thought (CoT) Prompting is a prompt engineering technique that induces a large language model (LLM) to explicitly generate intermediate reasoning steps before the final answer when solving complex problems. Published by Google Research in 2022, this technique dramatically improved LLM performance in mathematical reasoning, logical thinking, commonsense reasoning, and more.
CoT's working principle mimics the human thought process. Rather than solving a complex problem all at once, it breaks the problem into several smaller steps and solves them sequentially. For example, Zero-shot CoT, which simply adds the phrase "Let's think step by step," improves arithmetic problem accuracy by more than 3 times.
Few-shot CoT is a method that provides examples including the solution process in the prompt. The model learns the reasoning pattern of the examples and generates step-by-step solutions in a similar way for new problems. Self-Consistency further improves accuracy by sampling multiple reasoning paths and selecting the most consistent answer.
In practice, CoT is applied to all LLM applications that require multi-step reasoning, such as complex analysis tasks, code generation and debugging, and legal/medical document analysis. Models specialized for reasoning, such as the OpenAI o1 series, use mechanisms similar to CoT internally.
# Chain-of-Thought ν둬νν
ν¨ν΄λ€
from openai import OpenAI
client = OpenAI()
# 1. Zero-shot CoT: κ°μ₯ κ°λ¨ν λ°©λ²
def zero_shot_cot(question: str) -> str:
prompt = f"{question}\n\nLet's think step by step."
response = client.chat.completions.create(
model="gpt-4",
messages=[{"role": "user", "content": prompt}],
temperature=0
)
return response.choices[0].message.content
# 2. Few-shot CoT: μμμ ν¨κ» μ 곡
def few_shot_cot(question: str) -> str:
prompt = """Q: Roger has 5 tennis balls. He buys 2 more cans of tennis balls.
Each can has 3 tennis balls. How many tennis balls does he have now?
A: Let me work through this step by step.
- Roger starts with 5 tennis balls
- He buys 2 cans, each containing 3 balls
- New balls: 2 cans x 3 balls = 6 balls
- Total: 5 + 6 = 11 tennis balls
The answer is 11.
Q: {question}
A: Let me work through this step by step."""
response = client.chat.completions.create(
model="gpt-4",
messages=[{"role": "user", "content": prompt.format(question=question)}],
temperature=0
)
return response.choices[0].message.content
# 3. Self-Consistency: λ€μκ²°λ‘ μ λ’°λ ν₯μ
import re
from collections import Counter
def self_consistency_cot(question: str, n_samples: int = 5) -> dict:
answers = []
reasonings = []
for _ in range(n_samples):
response = client.chat.completions.create(
model="gpt-4",
messages=[{"role": "user", "content": f"{question}\nLet's think step by step."}],
temperature=0.7 # λ€μμ±μ μν΄ temperature μν₯
)
text = response.choices[0].message.content
reasonings.append(text)
# μ«μ μ λ΅ μΆμΆ (λ§μ§λ§ μ«μλ₯Ό μ λ΅μΌλ‘ κ°μ )
numbers = re.findall(r'\d+', text.split("answer")[-1] if "answer" in text.lower() else text)
if numbers:
answers.append(numbers[-1])
# λ€μκ²°λ‘ μ΅μ’
λ΅λ³ κ²°μ
answer_counts = Counter(answers)
final_answer = answer_counts.most_common(1)[0] if answer_counts else (None, 0)
return {
"final_answer": final_answer[0],
"confidence": final_answer[1] / n_samples,
"all_answers": answers
}
# μ¬μ© μμ
question = "A store has 45 apples. If 12 are sold and 8 more are added, how many are there?"
print("Zero-shot CoT:", zero_shot_cot(question)[:200])
print("\nSelf-Consistency:", self_consistency_cot(question))
"We had many numerical calculation errors in financial report analysis, but after adding a CoT instruction to the system prompt saying 'State the source of each figure and the calculation process,' the error rate dropped by 40%."
"The difference between CoT and regular prompting is whether the intermediate reasoning process is made explicit. The effect is clear in models with 100B parameters or more, and there is a research result showing that accuracy on the GSM8K benchmark improved from 17% to 57%."
"Setting the temperature to 0.7 in Self-Consistency is fine, but sampling 5 times may be less cost-effective. 3 times is enough, so consider an adaptive approach that samples additionally only when the results disagree."
Take a mock interview on this topic β WIA SOOM AI Interview Β· Start for free
CoT increases output tokens by 3-5 times. For large-scale processing, consider cost and latency, and apply it only to tasks where it is truly necessary.
CoT is effective on large models of roughly 100B parameters or more. On smaller models, it may instead generate incorrect reasoning paths.
The reasoning process generated by the model is not always accurate, nor does it always reflect the actual internal computation. Additional verification is needed, especially for tasks that require fact-checking.