DEV Community

shashank ms
shashank ms

Posted on

Deep Reasoning Tutorial for Beginners

We are going to build a command-line research agent that uses deep reasoning to break down complex questions into explicit chains of thought. This helps developers and analysts get transparent, auditable answers instead of black-box responses. Because we are running on Oxlo.ai, long reasoning traces do not inflate costs, since pricing is flat per request rather than per token.

What you'll need

Oxlo.ai offers request-based pricing, which means you can use deep reasoning models like DeepSeek R1 without worrying about the length of the model's internal monologue. See https://oxlo.ai/pricing for details.

Step 1: Set up the client and test raw reasoning

First, we point the OpenAI client at Oxlo.ai and ask DeepSeek R1 a complex question. The model will emit a long reasoning trace before giving its final answer.

from openai import OpenAI

client = OpenAI(base_url="https://api.oxlo.ai/v1", api_key="YOUR_OXLO_API_KEY")

question = (
    "Analyze the potential impact of autonomous software engineering agents on "
    "entry-level programming jobs over the next decade. Consider economic, educational, "
    "and technical factors, and identify who is most at risk and who might benefit."
)

response = client.chat.completions.create(
    model="deepseek-r1-671b",
    messages=[{"role": "user", "content": question}],
)

raw_output = response.choices[0].message.content
print(raw_output)

Step 2: Extract the reasoning chain

DeepSeek R1 wraps its internal monologue in <think> tags. We will write a small parser to separate the chain of thought from the final answer so we can display them independently.

import re

def parse_reasoning(text: str):
    """Split DeepSeek R1 output into reasoning and final answer."""
    match = re.search(r"<think>(.*?)</think>(.*?)$", text, re.DOTALL)
    if match:
        reasoning = match.group(1).strip()
        answer = match.group(2).strip()
        return reasoning, answer
    return "No explicit reasoning found.", text.strip()

reasoning, answer = parse_reasoning(raw_output)
print("=== REASONING ===")
print(reasoning[:500] + "...")
print("\n=== ANSWER ===")
print(answer[:500] + "...")

Step 3: Build a reusable agent with a system prompt

To get consistent results, we define a system prompt that forces structured reasoning. Then we wrap everything in a small agent class.

SYSTEM_PROMPT = """You are a deep research analyst. When given a complex question, think step by step inside <think> tags. Consider multiple angles, identify your own assumptions, and evaluate evidence explicitly. After you finish reasoning, close the </think> tag and provide a clear, concise final answer."""
class DeepReasoner:
    def __init__(self, api_key: str, model: str = "deepseek-r1-671b"):
        self.client = OpenAI(base_url="https://api.oxlo.ai/v1", api_key=api_key)
        self.model = model

    def ask(self, question: str):
        response = self.client.chat.completions.create(
            model=self.model,
            messages=[
                {"role": "system", "content": SYSTEM_PROMPT},
                {"role": "user", "content": question},
            ],
        )
        return parse_reasoning(response.choices[0].message.content)

Step 4: Add a self-verification loop

Deep reasoning improves when the model critiques its own work. After the first pass, we feed the reasoning and answer back into the model and ask it to look for logical gaps or unsupported claims.

# Add this method to the DeepReasoner class

def verify(self, reasoning: str, answer: str, original_question: str):
    critique_prompt = (
        f"Original question: {original_question}\n\n"
        f"Reasoning: {reasoning}\n\n"
        f"Answer: {answer}\n\n"
        "Identify any logical flaws, unsupported assumptions, or missing considerations. "
        "Be specific."
    )
    response = self.client.chat.completions.create(
        model=self.model,
        messages=[{"role": "user", "content": critique_prompt}],
    )
    return response.choices[0].message.content

# Usage
agent = DeepReasoner(api_key="YOUR_OXLO_API_KEY")
reasoning, answer = agent.ask(question)
critique = agent.verify(reasoning, answer, question)
print("=== CRITIQUE ===")
print(critique)

Step 5: Package it as a CLI tool

Finally, we add a small runner that formats everything into a clean report you can run from the terminal.

if __name__ == "__main__":
    import sys

    if len(sys.argv) < 2:
        print("Usage: python reasoner.py 'Your complex question here'")
        sys.exit(1)

    user_question = sys.argv[1]
    agent = DeepReasoner(api_key="YOUR_OXLO_API_KEY")

    print("Generating reasoning...")
    reasoning, answer = agent.ask(user_question)

    print("\n========== REASONING TRACE ==========\n")
    print(reasoning)
    print("\n========== FINAL ANSWER ==========\n")
    print(answer)

    print("\n========== SELF-VERIFICATION ==========\n")
    critique = agent.verify(reasoning, answer, user_question)
    print(critique)

Run it

Save the complete script as reasoner.py and run:

python reasoner.py "How might climate change affect global coffee supply chains by 2040, and which regions are most vulnerable?"

You should see output similar to this:

========== REASONING TRACE ==========

1. Coffee is primarily grown in the "Bean Belt" between the Tropics of Cancer and Capricorn...
2. Rising temperatures and unpredictable rainfall threaten Arabica production, which requires stable cool climates...
3. Brazil and Vietnam dominate global production, so shocks there have outsized effects...
4. Resilience strategies include shifting to Robusta, agroforestry, and genetic research...

========== FINAL ANSWER ==========

By 2040, climate change is likely to reduce suitable Arabica land by up to 50%, concentrating risk in Brazil, Vietnam, and Colombia. Supply chain vulnerability will increase due to extreme weather and water scarcity. Adaptation will require diversification, investment in heat-resistant strains, and localized irrigation infrastructure.

========== SELF-VERIFICATION ==========

The reasoning correctly identifies temperature and rainfall but underemphasizes the role of pests and diseases, which are expected to expand into higher altitudes...

Wrap-up and next steps

You now have a working deep reasoning agent that separates thinking from answers and self-critiques. Two concrete ways to extend it:

  • Ground it in live data: Add a web search tool using Oxlo.ai's function calling support, then feed search results into the reasoning step so the model works with current facts rather than training data alone.
  • Stream the thought process: Oxlo.ai supports streaming responses. Update the ask method with stream=True and print reasoning tokens as they arrive, which is useful for long-running analyses.

Because Oxlo.ai uses flat per-request pricing, you can let the model reason at length without the cost spikes you would see on token-based platforms. This makes it a strong fit for agentic workflows that require multiple reasoning passes or long context windows.

Top comments (0)