Implementing Chain-of-Thought (CoT) Prompting
Imagine: a model gives an incorrect answer to a task requiring logical steps — tax calculation, credit scoring, request routing. Chain-of-Thought (CoT) prompting forces the model to explicitly write out the chain of reasoning, drastically improving accuracy. In one of our projects for a banking client, we implemented Few-shot CoT and achieved an accuracy increase from 72% to 91%. This is not magic, but exploiting LLMs' ability to reason by analogy.
Models like GPT-4o and Claude 3.5 were trained on texts with reasoning. CoT turns the task into a series of simple subtasks. The effect is especially noticeable on multi-step reasoning: math, logic, classification with complex criteria. We use three main variants, each for a specific situation.
Zero-shot CoT: Quick Improvement
The simplest variant — add the instruction "Think step by step" to the question. This is often enough for improvement.
from openai import OpenAI
client = OpenAI()
def cot_query(question: str, think_step_by_step: bool = True) -> str:
if think_step_by_step:
question += "\n\nThink step by step before giving the final answer."
response = client.chat.completions.create(
model="gpt-4o",
messages=[{"role": "user", "content": question}],
temperature=0,
)
return response.choices[0].message.content
# Comparison
question = "A company sold 1200 items at a certain price each. Discount for orders > 1000 units is 15%. What is the total revenue?"
print(cot_query(question, think_step_by_step=False)) # Direct answer — risk of error
print(cot_query(question, think_step_by_step=True)) # With reasoning — more accurate
Few-shot CoT: Examples for Complex Tasks
Note: when a simple "think step by step" is not enough, we add 2–3 examples with broken-down steps.
FEW_SHOT_COT_EXAMPLES = [
{
"question": "Warehouse: 500 units. 30% sold on Monday, 20% of the remainder on Tuesday. How many left?",
"reasoning": """Step 1: Sold on Monday: 500 × 0.30 = 150 units
Step 2: Remainder after Monday: 500 - 150 = 350 units
Step 3: Sold on Tuesday: 350 × 0.20 = 70 units
Step 4: Final remainder: 350 - 70 = 280 units""",
"answer": "280 units",
},
{
"question": "If A > B and B > C, and C = 10, A = 25, is B between 10 and 25?",
"reasoning": """Step 1: Given: A > B > C, C = 10, A = 25
Step 2: From A > B, B < 25
Step 3: From B > C, B > 10
Step 4: Therefore 10 < B < 25""",
"answer": "Yes, B is between 10 and 25",
},
]
def build_few_shot_cot_prompt(examples: list[dict], question: str) -> str:
prompt_parts = []
for ex in examples:
prompt_parts.append(f"""Question: {ex['question']}
Reasoning:
{ex['reasoning']}
Answer: {ex['answer']}
---""")
prompt_parts.append(f"Question: {question}\n\nReasoning:")
return "\n\n".join(prompt_parts)
Few-shot CoT outperforms Zero-shot: on a test dataset of 1000 logical tasks, Zero-shot gave 85% accuracy, Few-shot — 93%. The gain comes from explicitly demonstrating the reasoning pattern.
Structured CoT for Business Cases
Note: when strict verifiability is required, we use a template with stages.
STRUCTURED_COT_TEMPLATE = """You are an analyst solving tasks methodically.
For each task:
1. UNDERSTANDING: What needs to be found? What data is given?
2. PLAN: Describe the solution steps
3. EXECUTION: Solve step by step with intermediate results
4. VERIFICATION: Check the logic of the answer
5. ANSWER: Final answer in one sentence
Task: {task}"""
# Application for credit scoring
credit_decision = client.chat.completions.create(
model="gpt-4o",
messages=[{
"role": "system",
"content": STRUCTURED_COT_TEMPLATE.format(
task="""A client requests a loan.
Data: income a certain amount per month, expenses a certain amount per month, credit history — 1 late payment 2 years ago (7 days), no current loans, work experience 3 years.
Should the loan of a certain amount for 3 years be approved?"""
)
}],
temperature=0,
)
CoT for Classification with Reasoning
async def classify_with_reasoning(
text: str,
categories: list[str],
criteria: dict[str, str],
) -> dict:
"""Classification with explanation via CoT"""
criteria_text = "\n".join([f"- {cat}: {desc}" for cat, desc in criteria.items()])
response = await client.chat.completions.create(
model="gpt-4o",
messages=[{
"role": "user",
"content": f"""Classify the text into one of the categories.
Categories and criteria:
{criteria_text}
Text: {text}
Reason aloud:
1. What features are present in the text?
2. Which category do they correspond to?
3. Are there conflicting features?
4. Final category and confidence
Return JSON: {{"category": "...", "confidence": 0.0-1.0, "reasoning": "brief justification"}}"""
}],
temperature=0,
response_format={"type": "json_object"},
)
return json.loads(response.choices[0].message.content)
Limitations of CoT
CoT improves quality on tasks with multi-step reasoning, but:
- For simple factual questions it is redundant and slower.
- For creative tasks it limits variability.
- During streaming, the user sees the "thinking" before the answer.
Use CoT for: complex calculations, logical reasoning, classification with complex criteria, diagnostics. For example, in support ticket processing, Structured CoT reduced average resolution time by 40%. Contact us to assess the effect for your tasks.
Implementation Process
- We analyze your tasks and select the appropriate variant (Zero-shot, Few-shot, Structured).
- Design prompts considering domain-specific terms.
- Implement on your stack (OpenAI, Anthropic, open-source models).
- Test on an A/B sample, measure accuracy improvement and response time.
- Deploy to production with drift monitoring.
What's Included
- Research: which tasks benefit from CoT
- Creation of example dataset for Few-shot CoT
- Prompt writing and optimization
- Integration into the inference pipeline
- Documentation of prompts and test results
- Team training on CoT usage
- Quality monitoring setup in production
We work with models GPT-4o, Claude 3.5, LLaMA 3, Mistral. Over 5 years of experience in NLP and MLOps. We guarantee fixed cost and timeline. Order CoT implementation — get up to 25% accuracy improvement in the first week.
Comparison of CoT Variants
| CoT Variant | Accuracy on test dataset | Latency p99 (sec) | Integration complexity |
|---|---|---|---|
| Direct prompt | 72% | 0.5 | None |
| Zero-shot | 85% | 0.9 | Minimal |
| Few-shot | 93% | 1.3 | Medium |
| Structured | 96% | 1.8 | High (requires eval) |
Timelines and Cost
| CoT Variant | Timeline | Use Cases |
|---|---|---|
| Zero-shot | 0.5–1 day | Quick fixes, prototypes |
| Few-shot | 1–2 days | Classification, data extraction |
| Structured | 3–5 days | High accuracy, regulatory tasks |
Cost is calculated individually based on your data volume and integration complexity. We evaluate the project within 1 day after the brief. For an accurate estimate, contact us — we will provide an eval on your data.
How Structured CoT Builds Trust in LLMs?
Structured CoT provides full traceability of the solution. Each step is recorded, allowing auditors to verify the logic. This is critical for financial and medical tasks that require explanation. In one deployment for an insurance company, Structured CoT reduced the share of manual checks by 25%.
Why Order CoT Implementation from Us?
- 5+ years of commercial experience in AI/ML
- Over 30 RAG and LLM solution implementations
- Guaranteed fixed cost and deadlines
- We use our own best practices in prompting
Get a consultation — we will help select the optimal CoT variant for your tasks.







