0Pricing
AI Agents · Lesson

Implementing ReAct from Scratch

Write a 100-line Python implementation without LangChain: parse Action lines, run tools, loop until Final Answer.

Implementing ReAct from Scratch is a free AI Agents lesson on CoddyKit — lesson 2 of 4. You can read the complete lesson below for free — then practise it hands-on in the browser with a built-in code editor and a 24/7 AI tutor. It is part of the AI Agents learning path, one of 4 lessons in the course, and your progress syncs across the web and the CoddyKit app.

Build the Loop Yourself

You can write ReAct in ~100 lines of Python — no framework needed. Doing so once builds intuition for what frameworks abstract away.

Step 1: Define Tools

import json, math

def calculator(expression: str) -> str:
    try:
        return str(eval(expression, {'__builtins__': {}}, vars(math)))
    except Exception as e:
        return f'Error: {e}'

def search_wikipedia(query: str) -> str:
    # placeholder — call a real search API
    return f'Wikipedia summary for: {query}'

TOOLS = {
    'calculator': calculator,
    'search_wikipedia': search_wikipedia,
}

print(calculator('2 + 2 * sqrt(16)'))
print(search_wikipedia('agents'))

Step 2: Tool Schemas

schemas = [
    {'type': 'function', 'function': {
        'name': 'calculator',
        'description': 'Evaluate a math expression like 2 + 2 * sqrt(16)',
        'parameters': {'type': 'object', 'properties': {'expression': {'type': 'string'}}, 'required': ['expression']}
    }},
    {'type': 'function', 'function': {
        'name': 'search_wikipedia',
        'description': 'Search Wikipedia and return a summary',
        'parameters': {'type': 'object', 'properties': {'query': {'type': 'string'}}, 'required': ['query']}
    }}
]
import json
print(json.dumps(schemas, indent=2))

Step 3: System Prompt

system = '''
You are a research assistant. Use the available tools when needed.
Think step by step. If you have enough information, give a final answer.
'''
print(system.strip())

Step 4: The Loop

from openai import OpenAI
client = OpenAI()

def react(question, max_steps=10):
    messages = [
        {'role': 'system', 'content': system},
        {'role': 'user', 'content': question}
    ]
    for step in range(max_steps):
        r = client.chat.completions.create(
            model='gpt-4o-mini',
            messages=messages,
            tools=schemas,
        )
        msg = r.choices[0].message
        messages.append(msg)
        if not msg.tool_calls:
            return msg.content
        for tc in msg.tool_calls:
            args = json.loads(tc.function.arguments)
            try:
                result = TOOLS[tc.function.name](**args)
            except Exception as e:
                result = f'Tool error: {e}'
            messages.append({'role': 'tool', 'tool_call_id': tc.id, 'content': str(result)})
    return 'Step limit reached.'

Step 5: Run It

answer = react('What is the population of Tokyo times the square root of pi?')
print(answer)

Step 6: Add Logging

Capture every step for debugging:

def react_verbose(question, max_steps=10):
    messages = [...]
    for step in range(max_steps):
        r = client.chat.completions.create(model='gpt-4o-mini', messages=messages, tools=schemas)
        msg = r.choices[0].message
        print(f'[step {step}] thought: {msg.content}')
        if msg.tool_calls:
            for tc in msg.tool_calls:
                print(f'[step {step}] action: {tc.function.name}({tc.function.arguments})')
        ...

Step 7: Step Counter as a Tool

Some agents include the step count in the system prompt so the model knows when to converge:

system = f'You have at most {MAX_STEPS} steps. Step {current_step}/{MAX_STEPS}. ...'

Step 8: Final Answer Format

If you want structured output, force a final tool call:

tools.append({'type': 'function', 'function': {
    'name': 'final_answer',
    'description': 'Submit the final answer to the user.',
    'parameters': {'type': 'object', 'properties': {'answer': {'type': 'string'}}, 'required': ['answer']}
}})
# Loop terminates when final_answer is called.

Step 9: Tool Errors

Always return errors as tool results so the agent can recover:

try:
    result = TOOLS[name](**args)
except Exception as e:
    result = f'TOOL ERROR: {type(e).__name__}: {e}'
# Model sees the error and can try a different approach.

Step 10: Parallel Tool Calls

If msg.tool_calls has multiple entries, run them in parallel:

import asyncio

async def run_tools(tool_calls):
    async def run_one(tc):
        args = json.loads(tc.function.arguments)
        return tc.id, TOOLS[tc.function.name](**args)
    return await asyncio.gather(*[run_one(tc) for tc in tool_calls])

Step 11: Bounding the Conversation

Even within MAX_STEPS, message lists can balloon. Trim by token count between turns:

if total_tokens(messages) > 6000:
    messages = trim_messages(messages)

Step 12: Production Hardening

For prod, add: timeouts on tool calls, per-tool quotas, retry-with-backoff on API failures, full trace logging. But the loop above is your skeleton.

Tool Error Handling

What should you do when a tool raises an exception?

Recap

ReAct in ~80 lines: messages list + while loop + dispatch table. Frameworks add polish but the core is this.

Frequently asked questions

Is the “Implementing ReAct from Scratch” lesson free?

Yes — the full text of “Implementing ReAct from Scratch” is free to read here on the web, and the AI Agents course includes 4 lessons in total. To practise it interactively (a built-in code editor and a 24/7 AI tutor) and unlock the rest of the AI Agents course, upgrade to CoddyKit PRO.

What will I learn in “Implementing ReAct from Scratch”?

Write a 100-line Python implementation without LangChain: parse Action lines, run tools, loop until Final Answer. You practise AI Agents with hands-on code you run directly in the browser, and a 24/7 AI tutor answers your questions as you work through the lesson.

Do I need any experience to start AI Agents?

No prior experience is required. AI Agents on CoddyKit is structured for beginners through advanced learners; this is — lesson 2 of 4, so you can start here or from the beginning and move at your own pace.

How long does the “Implementing ReAct from Scratch” lesson take?

Most CoddyKit lessons take about 5–10 minutes. Each one is bite-sized and interactive, so you make steady progress and pick up exactly where you left off across the web and the app.

Can I write and run code in this AI Agents lesson?

Yes. Every AI Agents lesson includes a built-in code editor, so you write and run real code right in your browser and get instant AI feedback — no local setup required.

All lessons in this course

  1. ReAct: Reason + Act Pattern
  2. Implementing ReAct from Scratch
  3. Common Tool Sets (Web, Calculator, RAG)
  4. Detecting and Recovering from Tool Errors
← Back to AI Agents