<?xml version="1.0" encoding="UTF-8"?><rss xmlns:dc="http://purl.org/dc/elements/1.1/" xmlns:content="http://purl.org/rss/1.0/modules/content/" xmlns:atom="http://www.w3.org/2005/Atom" version="2.0" xmlns:cc="http://cyber.law.harvard.edu/rss/creativeCommonsRssModule.html">
    <channel>
        <title><![CDATA[Stories by Rahul Kumar on Medium]]></title>
        <description><![CDATA[Stories by Rahul Kumar on Medium]]></description>
        <link>https://medium.com/@rahulkumar.aws?source=rss-30384ad0c85f------2</link>
        <image>
            <url>https://cdn-images-1.medium.com/fit/c/150/150/0*mlc4kTkoYW904DtI.</url>
            <title>Stories by Rahul Kumar on Medium</title>
            <link>https://medium.com/@rahulkumar.aws?source=rss-30384ad0c85f------2</link>
        </image>
        <generator>Medium</generator>
        <lastBuildDate>Fri, 04 Dec 2026 09:40:52 GMT</lastBuildDate>
        <atom:link href="https://medium.com/@rahulkumar.aws/feed" rel="self" type="application/rss+xml"/>
        <webMaster><![CDATA[yourfriends@medium.com]]></webMaster>
        <atom:link href="http://medium.superfeedr.com/" rel="hub"/>
        <item>
            <title><![CDATA[Part 1: Demystifying AI Agents - Build One From Scratch in Python]]></title>
            <link>https://medium.com/developersdiary/part-1-demystifying-ai-agents-build-one-from-scratch-in-python-0b4913913ef8?source=rss-30384ad0c85f------2</link>
            <guid isPermaLink="false">https://medium.com/p/0b4913913ef8</guid>
            <category><![CDATA[agentic-ai]]></category>
            <category><![CDATA[ai]]></category>
            <category><![CDATA[ai-agent]]></category>
            <dc:creator><![CDATA[Rahul Kumar]]></dc:creator>
            <pubDate>Tue, 15 Sep 2026 12:24:10 GMT</pubDate>
            <atom:updated>2026-09-16T08:46:18.531Z</atom:updated>
            <content:encoded><![CDATA[<p><strong>Build a deterministic agent from scratch in Python — without frameworks — to understand the ReAct loop, explicit state, tools, and goal convergence.</strong></p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*TfJ2mOKLDZK6O0kSI4sn2Q.png" /></figure><p>Everyone is talking about <strong>AI agents</strong> and <strong>agentic workflows</strong>.</p><p><strong>OpenAI</strong> and <strong>Anthropic</strong> are building increasingly capable agents that can operate in controlled environments. Vendors demonstrate systems that can <em>plan, reason, use tools, and act</em>.</p><p>If you’re a software engineer, data engineer, data scientist, or even a project manager, this can feel surprisingly fuzzy:</p><ul><li>What is an agent, concretely?</li><li>Where does the “reasoning” actually happen?</li><li>What is code, what is configuration, and what is just marketing?</li><li>What do people mean when they say an agent runs inside a “sandbox”?</li></ul><p>Let’s remove the mystery.</p><p>In this article, we’ll build a tiny agent <strong>from scratch in Python</strong> using:</p><ul><li>A ReAct-style loop</li><li>Explicit state</li><li>Deterministic tools</li><li>Clear goals</li><li>A controlled environment</li><li>A task and evaluation layer</li></ul><p><strong>No LLMs. No LangChain. No frameworks. Just Python.</strong></p><p>The goal isn’t to build a useful production agent. The goal is to understand the machinery underneath one.</p><p>By the end, “agentic behavior” should look much less magical:</p><blockquote><strong><em>Reason → Act → Observe → Repeat</em></strong></blockquote><p>Later, we can replace our handwritten reasoning function with an LLM while keeping most of the surrounding architecture.</p><h3>1. What Is an AI Agent, Really?</h3><p>Let’s start with a pragmatic definition:</p><blockquote><strong><em>An AI agent is a system in which a decision-making component selects actions, uses tools to affect an environment, observes the results, and continues until a goal is reached or a stopping condition is triggered.</em></strong></blockquote><p>That gives us three major components.</p><h4>1. The Brain 🧠 — Policy or Model</h4><p>The brain looks at the current context and decides what to do next.</p><p>For example:</p><pre>Current location: kitchen<br>Known items: key<br>Goal: obtain treasure</pre><pre>Decision:<br>→ take key</pre><p>In a modern AI agent, <strong>the brain is often an LLM</strong>.</p><p>In our example, it will simply be a Python function.</p><h4>2. Tools ⚒️— Actions</h4><p>Tools are the things the agent can actually do.</p><p>For example:</p><pre>move(&quot;north&quot;)<br>create_ticket(...)<br>query_database(...)<br>send_email(...)<br>run_code(...)</pre><p>The tools themselves don’t need to be intelligent.</p><p>They are capabilities exposed to the agent.</p><h4>3. Orchestrator ⚙️— Controller</h4><p>The orchestrator connects everything.</p><p>Conceptually:</p><pre>State<br>  ↓<br>Brain decides<br>  ↓<br>Action<br>  ↓<br>Tool execution<br>  ↓<br>Observation<br>  ↓<br>Updated state<br>  ↓<br>Brain decides again</pre><p>The orchestrator can also enforce rules such as:</p><ul><li>Maximum number of steps</li><li>Allowed tools</li><li>Input validation</li><li>Permissions</li><li>Safety checks</li><li>Timeouts</li><li>Logging</li></ul><p>In our implementation, the brain will be deterministic so that we can see exactly what is happening.</p><h3>2. The ReAct Loop</h3><p>One common pattern for building tool-using agents is <strong>ReAct</strong>, short for <strong>Reason + Act</strong>.</p><p>At a high level:</p><ol><li>Reason about the current situation.</li><li>Choose an action.</li><li>Execute the action.</li><li>Observe the result.</li><li>Update state.</li><li>Repeat.</li></ol><p>Conceptually:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/464/1*IXqRh14RWTovwynGxuVG_g.png" /></figure><p>With an LLM-based agent, the reasoning component may use the model to decide which tool to call.</p><p>Here, we’ll implement the same structural idea using deterministic Python code.</p><h3>3. Build a Tiny World 🌍</h3><p>We need an environment in which our agent can operate.</p><p>Let’s create a tiny text-based world containing three rooms:</p><pre>hall<br> ├── north → kitchen<br> └── east  → study</pre><p>The kitchen contains a <strong>key</strong>.</p><p>The study contains <strong>treasure</strong>.</p><p>Our agent starts in the hall.</p><p>The world is deterministic:</p><blockquote><em>Given the same state and the same action, we get the same result.</em></blockquote><p>Here’s the environment:</p><p>src/agent_sandbox/environment/world.py</p><pre>from dataclasses import dataclass, field<br>from typing import Dict, List<br><br>@dataclass<br>class World:<br>    rooms: Dict[str, Dict] = field(default_factory=dict)<br>    agent_location: str = &quot;hall&quot;<br>    agent_inventory: List[str] = field(default_factory=list)<br><br>    def __post_init__(self):<br>        if not self.rooms:<br>            self.rooms = {<br>                &quot;hall&quot;: {<br>                    &quot;description&quot;: &quot;You are in the hall. Doors lead to the kitchen and the study.&quot;,<br>                    &quot;neighbors&quot;: {&quot;north&quot;: &quot;kitchen&quot;, &quot;east&quot;: &quot;study&quot;},<br>                    &quot;items&quot;: [],<br>                },<br>                &quot;kitchen&quot;: {<br>                    &quot;description&quot;: &quot;You are in the kitchen. It smells of tea.&quot;,<br>                    &quot;neighbors&quot;: {&quot;south&quot;: &quot;hall&quot;},<br>                    &quot;items&quot;: [&quot;key&quot;],<br>                },<br>                &quot;study&quot;: {<br>                    &quot;description&quot;: &quot;You are in the study. There is a locked chest here.&quot;,<br>                    &quot;neighbors&quot;: {&quot;west&quot;: &quot;hall&quot;},<br>                    &quot;items&quot;: [&quot;treasure&quot;],<br>                },<br>            }<br><br>    def move(self, direction: str) -&gt; str:<br>        room = self.rooms[self.agent_location]<br>        neighbors = room[&quot;neighbors&quot;]<br>        if direction not in neighbors:<br>            return f&quot;You can&#39;t go {direction} from here.&quot;<br>        self.agent_location = neighbors[direction]<br>        return f&quot;You move {direction} to the {self.agent_location}.&quot;<br><br>    def look(self) -&gt; str:<br>        room = self.rooms[self.agent_location]<br>        desc = room[&quot;description&quot;]<br>        items = room[&quot;items&quot;]<br>        item_text = &quot;You see: &quot; + &quot;, &quot;.join(items) if items else &quot;You see nothing special.&quot;<br>        return f&quot;{desc}\n{item_text}&quot;<br><br>    def take(self, item: str) -&gt; str:<br>        room = self.rooms[self.agent_location]<br>        if item not in room[&quot;items&quot;]:<br>            return f&quot;There is no {item} here.&quot;<br>        room[&quot;items&quot;].remove(item)<br>        self.agent_inventory.append(item)<br>        return f&quot;You take the {item}.&quot;<br><br>    def inventory(self) -&gt; str:<br>        if not self.agent_inventory:<br>            return &quot;You are carrying nothing.&quot;<br>        return &quot;You are carrying: &quot; + &quot;, &quot;.join(self.agent_inventory)This class represents the environment.</pre><p>The environment owns the ground truth.</p><p>It knows:</p><ul><li>Where the agent really is</li><li>Which items really exist</li><li>Which rooms are connected</li><li>What actions are possible</li></ul><p>The agent doesn’t directly modify this state. It interacts with the environment through actions.</p><p>That’s an important distinction.</p><h3>4. Give the Agent Its Own State</h3><p>The world contains ground truth.</p><p>The agent needs its own representation of what it knows and what it has accomplished.</p><p>Let’s create an AgentState.</p><p>src/agent_sandbox/agent/state.py</p><pre>from dataclasses import dataclass, field<br>from typing import Dict, List<br>from agent_sandbox.environment.world import World<br><br>@dataclass<br>class AgentState:<br>    current_room: str = &quot;hall&quot;<br>    known_items: Dict[str, List[str]] = field(default_factory=dict)<br>    inventory: List[str] = field(default_factory=list)<br>    steps_taken: int = 0<br>    max_steps: int = 20<br>    goal_item: str = &quot;treasure&quot;<br><br>    def update_from_observation(self, world: World, observation: str):<br>        self.current_room = world.agent_location<br>        self.inventory = list(world.agent_inventory)<br>        for line in observation.splitlines():<br>            line = line.strip()<br>            if line.startswith(&quot;You see:&quot;):<br>                items_part = line[len(&quot;You see:&quot;):].strip()<br>                items = [x.strip() for x in items_part.split(&quot;,&quot;)] if items_part and &quot;nothing special&quot; not in items_part else []<br>                self.known_items[self.current_room] = items</pre><p>Now we have two different concepts:</p><pre>World<br> └── Ground truth<br>AgentState<br> └── Agent&#39;s state / knowledge</pre><p>This separation becomes extremely important in real agents.</p><p>The environment might contain information the agent doesn’t know yet.</p><p>The agent only learns about the environment through observations.</p><h3>5. Define Goal and Stop Conditions</h3><p>An agent needs a definition of success.</p><p>Otherwise, how does it know when to stop?</p><p>Our goal is simple:</p><blockquote><em>Get the treasure.</em></blockquote><pre>def goal_achieved(state: AgentState) -&gt; bool:<br>    return state.goal_item in state.inventory</pre><p>We also need a safety limit.</p><pre>def should_stop(state: AgentState) -&gt; bool:<br>    if goal_achieved(state):<br>        return True<br>    if state.steps_taken &gt;= state.max_steps:<br>        return True<br>    return False</pre><p>This gives us two termination conditions:</p><pre>Goal achieved<br>      OR<br>Maximum steps reached</pre><p>This idea is much more important than it might initially appear.</p><p>Production agents need explicit termination conditions because an agent that can continue indefinitely is not very useful.</p><h3>6. Implement the “Reason” Step</h3><p>Now we need the agent’s decision-making logic.</p><p>Our agent will use a simple deterministic policy:</p><ol><li>If we already have the treasure, stop.</li><li>If we know the treasure is in the current room, take it.</li><li>If we see another item, take it.</li><li>Otherwise, move through available exits in a fixed order.</li></ol><pre>def choose_action(state: AgentState, world: World) -&gt; str:<br>    # 1. Stop if goal is achieved<br>    if state.goal_item in state.inventory:<br>        return &quot;idle&quot;<br>        <br>    # 2. Look first if we haven&#39;t mapped this room&#39;s items yet<br>    if state.current_room not in state.known_items:<br>        return &quot;look&quot;<br>        <br>    items_here = state.known_items.get(state.current_room, [])<br>    <br>    # 3. Take goal item or other items<br>    if state.goal_item in items_here:<br>        return f&quot;take {state.goal_item}&quot;<br>    if items_here:<br>        return f&quot;take {items_here[0]}&quot;<br>        <br>    # 4. Move, but avoid the infinite loop trap<br>    room = world.rooms[state.current_room]<br>    directions = [&quot;north&quot;, &quot;east&quot;, &quot;south&quot;, &quot;west&quot;]<br>    <br>    # If we are in the hall and have the key, don&#39;t go back to the kitchen<br>    if state.current_room == &quot;hall&quot; and &quot;key&quot; in state.inventory:<br>        directions.remove(&quot;north&quot;)<br>        <br>    for direction in directions:<br>        if direction in room[&quot;neighbors&quot;]:<br>            return f&quot;move {direction}&quot;<br>            <br>    return &quot;look&quot;</pre><p>This function is our <strong>brain</strong>.</p><p>It is also the most obvious place where an LLM could eventually be introduced.</p><p>Today:</p><pre>AgentState<br>     ↓<br>choose_action()<br>     ↓<br>&quot;move north&quot;</pre><p>Later:</p><pre>AgentState<br>     ↓<br>    LLM<br>     ↓<br>&quot;move north&quot;</pre><p>The surrounding architecture can remain largely unchanged.</p><h3>7. Implement the “Act” Step</h3><p>Our agent produces an action such as:</p><pre>move north<br>take key<br>look<br>inventory</pre><p>We need to translate those commands into actual environment operations.</p><pre>def execute_action(world: World, action: str) -&gt; str:<br>    tokens = action.split()<br>    if not tokens:<br>        return &quot;No action.&quot;<br>        <br>    verb = tokens[0]<br>    args = tokens[1:]<br>    <br>    # 🛠️ New logging to print which tool is being called<br>    print(f&quot;🛠️ [Act] Invoking Tool: &#39;{verb}&#39; with Args: {args}&quot;)<br>    <br>    if verb == &quot;move&quot; and len(tokens) == 2:<br>        return world.move(tokens[1])<br>    elif verb == &quot;look&quot;:<br>        return world.look()<br>    elif verb == &quot;take&quot; and len(tokens) == 2:<br>        return world.take(tokens[1])<br>    elif verb == &quot;inventory&quot;:<br>        return world.inventory()<br>    elif verb == &quot;idle&quot;:<br>        return &quot;Agent is idle.&quot;<br>    else:<br>        return f&quot;Unknown action: {action}&quot;</pre><p>This is the <strong>Act</strong> part of our ReAct loop.</p><p>Notice something important:</p><p>The agent doesn’t directly call arbitrary Python.</p><p>It produces an action.</p><p>The orchestrator validates and executes that action.</p><p>That’s a useful architectural boundary.</p><h3>8. Implement the Full ReAct Loop</h3><p>Now we can connect everything.</p><p><a href="https://github.com/rahulkumar-aws/agent-sandbox">https://github.com/rahulkumar-aws/agent-sandbox</a></p><pre>from typing import Tuple<br>from agent_sandbox.environment.world import World<br>from agent_sandbox.agent.state import AgentState<br>from agent_sandbox.agent.agent import should_stop, goal_achieved<br>from agent_sandbox.agent.policy import choose_action<br>from agent_sandbox.tools.actions import execute_action<br><br>def run_episode(verbose: bool = True) -&gt; Tuple[World, AgentState]:<br>    &quot;&quot;&quot;Runs a single episode of the agent loop.&quot;&quot;&quot;<br>    world = World()<br>    state = AgentState()<br>    <br>    # Initial observation<br>    initial_obs = world.look()<br>    state.update_from_observation(world, initial_obs)<br>    state.steps_taken += 1<br>    <br>    if verbose:<br>        print(f&quot;[Step {state.steps_taken}] Initial observation:\n{initial_obs}\n&quot;)<br>        <br>    while not should_stop(state):<br>        # 1. Decide[cite: 1]<br>        action = choose_action(state, world)<br>        <br>        if verbose:<br>            print(f&quot;[Step {state.steps_taken}] Agent chooses action: {action}&quot;)<br>            <br>        if action == &quot;idle&quot;:<br>            break<br>            <br>        # 2. Act[cite: 1]<br>        observation = execute_action(world, action)<br>        <br>        if verbose:<br>            print(f&quot;Environment says: {observation}\n&quot;)<br>            <br>        # 3. Observe[cite: 1]<br>        state.update_from_observation(world, observation)<br>        state.steps_taken += 1<br>        <br>        if verbose:<br>            print(f&quot;Current room: {state.current_room}, Inventory: {state.inventory}\n&quot;)<br>            <br>    if verbose:<br>        if goal_achieved(state):<br>            print(f&quot;Goal achieved! Agent has {state.goal_item}.&quot;)<br>        else:<br>            print(&quot;Agent stopped without achieving the goal.&quot;)<br>            <br>    return world, state<br><br>if __name__ == &quot;__main__&quot;:<br>    print(&quot;=== Task: Get the Treasure ===\n&quot;)<br>    run_episode(verbose=True)</pre><p>We now have our complete loop:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/544/1*pkbtKJIqOpkdr0hqCJt5Yw.png" /></figure><p>That’s an agent.</p><p>Not a framework.</p><p>Not magic.</p><p>Just a control loop around a decision-making component and an environment.</p><h3>9. Watch the Agent Work</h3><p>A run might look like this:</p><pre>=== Task: Get the Treasure ===<br>Start in the hall. Obtain the treasure and hold it in your inventory.<br><br>[Step 1] Initial observation:<br>You are in the hall. Doors lead to the kitchen and the study.<br>You see nothing special.<br><br>[Step 1] Agent chooses action: look<br>🛠️ [Act] Invoking Tool: &#39;look&#39; with Args: []<br>Environment says:<br>You are in the hall. Doors lead to the kitchen and the study.<br>You see nothing special.<br>Current room: hall, Inventory: []<br><br>[Step 2] Agent chooses action: look<br>🛠️ [Act] Invoking Tool: &#39;look&#39; with Args: []<br>Environment says:<br>You are in the hall. Doors lead to the kitchen and the study.<br>You see nothing special.<br>Current room: hall, Inventory: []<br><br>[Step 3] Agent chooses action: look<br>🛠️ [Act] Invoking Tool: &#39;look&#39; with Args: []<br>Environment says:<br>You are in the hall. Doors lead to the kitchen and the study.<br>You see nothing special.<br>Current room: hall, Inventory: []<br><br>.....<br>.....<br><br>[Step 28] Agent chooses action: look<br>🛠️ [Act] Invoking Tool: &#39;look&#39; with Args: []<br>Environment says:<br>You are in the hall. Doors lead to the kitchen and the study.<br>You see nothing special.<br>Current room: hall, Inventory: []<br><br>[Step 29] Agent chooses action: look<br>🛠️ [Act] Invoking Tool: &#39;look&#39; with Args: []<br>Environment says:<br>You are in the hall. Doors lead to the kitchen and the study.<br>You see nothing special.<br>Current room: hall, Inventory: []<br><br><br>Task &#39;Get the Treasure&#39; success: False<br>Final inventory: []<br>Final room: hall</pre><p>The important thing isn’t the treasure.</p><p>It’s the structure.</p><p>We have implemented:</p><ul><li>A decision policy</li><li>Tools/actions</li><li>Explicit state</li><li>An environment</li><li>Observations</li><li>A goal</li><li>Termination conditions</li><li>A ReAct-style control loop</li></ul><p>And everything is deterministic.</p><h3>10. Turn the Environment Into a Sandbox</h3><p>So far, our agent has one objective:</p><blockquote><em>Get the treasure.</em></blockquote><p>Real agent evaluation requires something more general.</p><p>We need to be able to say:</p><blockquote><em>Here is a task. Run the agent. Did it succeed?</em></blockquote><p>That’s where the idea of a <strong>task abstraction</strong> becomes useful.</p><p>A task can contain:</p><ul><li>A name</li><li>A description</li><li>A success condition</li><li>Optional environment setup</li></ul><p>Now our environment can execute arbitrary tasks.</p><h3>11. Build the Sandbox Runner</h3><p>src/agent_sandbox/runtime/runner.py</p><pre>from dataclasses import dataclass<br>from typing import Callable, Tuple<br>from agent_sandbox.environment.world import World<br>from agent_sandbox.agent.state import AgentState<br>from agent_sandbox.agent.policy import choose_action<br>from agent_sandbox.tools.actions import execute_action<br><br>@dataclass<br>class Task:<br>    name: str<br>    description: str<br>    is_goal: Callable[[AgentState, World], bool]<br>    setup: Callable[[World, AgentState], None] = lambda world, state: None<br><br>class Sandbox:<br>    def run_task(self, task: Task, max_steps: int = 30, verbose: bool = True) -&gt; Tuple[World, AgentState, bool]:<br>        world = World()<br>        state = AgentState(max_steps=max_steps)<br>        task.setup(world, state)<br>        <br>        if verbose:<br>            print(f&quot;=== Task: {task.name} ===&quot;)<br>            print(task.description, &quot;\n&quot;)<br>            <br>        initial_obs = world.look()<br>        state.update_from_observation(world, initial_obs)<br>        state.steps_taken += 1<br>        <br>        while state.steps_taken &lt; state.max_steps:<br>            if task.is_goal(state, world):<br>                return world, state, True<br>                <br>            action = choose_action(state, world)<br>            if action == &quot;idle&quot;:<br>                break<br>                <br>            observation = execute_action(world, action)<br>            state.update_from_observation(world, observation)<br>            state.steps_taken += 1<br>            <br>        return world, state, task.is_goal(state, world)</pre><p>We now have something that looks much more like an evaluation harness.</p><pre>Task<br>  ↓<br>Sandbox<br>  ↓<br>Agent<br>  ↓<br>Environment<br>  ↓<br>Observations<br>  ↓<br>Success / Failure</pre><h3>12. Create Multiple Tasks</h3><h3>Task 1 — Get the Treasure</h3><pre>def goal_has_treasure(<br>    state: AgentState,<br>    world: World,<br>) -&gt; bool:<br>return &quot;treasure&quot; in state.inventory<br><br>task_get_treasure = Task(<br>    name=&quot;Get the Treasure&quot;,<br>    description=(<br>        &quot;Start in the hall. &quot;<br>        &quot;Obtain the treasure and &quot;<br>        &quot;hold it in your inventory.&quot;<br>    ),<br>    is_goal=goal_has_treasure,<br>)</pre><h3>Task 2 — Collect Everything</h3><pre>def goal_collect_all_items(<br>    state: AgentState,<br>    world: World,<br>) -&gt; bool:<br>required_items = {<br>        &quot;key&quot;,<br>        &quot;treasure&quot;,<br>    }<br>    return required_items.issubset(<br>        set(state.inventory)<br>    )<br><br>task_collect_all = Task(<br>    name=&quot;Collect All Items&quot;,<br>    description=(<br>        &quot;Collect every item in the world.&quot;<br>    ),<br>    is_goal=goal_collect_all_items,<br>)</pre><h3>Task 3 — Explore Every Room</h3><pre>def goal_explore_all_rooms(<br>    state: AgentState,<br>    world: World,<br>) -&gt; bool:<br>required_rooms = set(<br>        world.rooms.keys()<br>    )<br>    visited_rooms = set(<br>        state.known_items.keys()<br>    )<br>    visited_rooms.add(<br>        state.current_room<br>    )<br>    return required_rooms.issubset(<br>        visited_rooms<br>    )<br><br>task_explore = Task(<br>    name=&quot;Explore All Rooms&quot;,<br>    description=(<br>        &quot;Visit every room at least once.&quot;<br>    ),<br>    is_goal=goal_explore_all_rooms,<br>)</pre><p>Now we can run multiple tasks through the same sandbox.</p><pre>def main():<br>sandbox = Sandbox()<br>    tasks = [<br>        task_get_treasure,<br>        task_collect_all,<br>        task_explore,<br>    ]<br>    for task in tasks:<br>        world, state, success = (<br>            sandbox.run_task(<br>                task,<br>                max_steps=30,<br>                verbose=True,<br>            )<br>        )<br>        print(<br>            f&quot;Task &#39;{task.name}&#39; &quot;<br>            f&quot;success: {success}&quot;<br>        )<br>        print(<br>            &quot;Final inventory:&quot;,<br>            state.inventory,<br>        )<br>        print(<br>            &quot;Final room:&quot;,<br>            state.current_room,<br>        )<br><br>if __name__ == &quot;__main__&quot;:<br>    main()</pre><p>We now have a miniature <strong>agent evaluation sandbox</strong>.</p><ul><li>Evaluate the Agent. Now we can run our specific “Get the Treasure” task through the sandbox.</li></ul><p>This creates a miniature evaluation environment complete with execution limits, state tracking, and a definitive success/failure output.</p><p>examples/01_deterministic_agent.py</p><pre>from agent_sandbox.runtime.runner import Task, Sandbox<br>from agent_sandbox.agent.state import AgentState<br>from agent_sandbox.environment.world import World<br><br>def goal_has_treasure(state: AgentState, world: World) -&gt; bool:<br>    return &quot;treasure&quot; in state.inventory<br><br>def main():<br>    # Define the single evaluation task<br>    task = Task(<br>        name=&quot;Get the Treasure&quot;,<br>        description=&quot;Start in the hall. Obtain the treasure and hold it in your inventory.&quot;,<br>        is_goal=goal_has_treasure<br>    )<br>    <br>    sandbox = Sandbox()<br>    <br>    # Run the task through the orchestrator<br>    world, state, success = sandbox.run_task(task, max_steps=30, verbose=True)<br>    <br>    print(f&quot;\nTask &#39;{task.name}&#39; success: {success}&quot;)<br>    print(&quot;Final inventory:&quot;, state.inventory)<br>    print(&quot;Final room:&quot;, state.current_room)<br><br>if __name__ == &quot;__main__&quot;:<br>    main()</pre><p>It has:</p><ul><li>An environment</li><li>An agent</li><li>Tools</li><li>Tasks</li><li>Goals</li><li>State</li><li>Execution limits</li><li>Success/failure evaluation</li><li>Logging</li></ul><h3>13. So What Is the “Sandbox” in Modern AI Agents?</h3><p>This is where the concept becomes useful beyond our toy example.</p><p>When AI companies talk about agents operating in controlled environments, the exact implementation varies, but the underlying engineering problem is similar:</p><blockquote><strong><em>How do we let an agent take actions without giving it uncontrolled access to the real world?</em></strong></blockquote><p>A sandbox can provide an isolated environment where an agent can:</p><ul><li>Run code</li><li>Modify files</li><li>Interact with simulated services</li><li>Use APIs</li><li>Query test databases</li><li>Work with synthetic data</li><li>Perform tasks</li><li>Be evaluated safely</li></ul><p>For example:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/534/1*wY2WHXy82n428gVp50JFpA.png" /></figure><p>The sandbox isn’t necessarily the agent.</p><p>It’s the <strong>controlled environment in which the agent is allowed to operate</strong>.</p><p>That’s an important distinction.</p><h3>14. What Changes When We Add an LLM?</h3><p>This is the interesting part.</p><p>Our architecture currently looks like:</p><pre>AgentState<br>     ↓<br>choose_action()<br>     ↓<br>Action<br>     ↓<br>Environment<br>     ↓<br>Observation</pre><p>choose_action() is currently handwritten.</p><p>We can replace it with an LLM.</p><p>Instead of:</p><pre>action = choose_action(<br>    state,<br>    world,<br>)</pre><p>we could conceptually have:</p><pre>action = llm.choose_action(<br>    state=state,<br>    available_tools=tools,<br>    goal=task.description,<br>)</pre><p>The architecture becomes:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/506/1*ujHShM3lGbyxHKD8RC1dwQ.png" /></figure><p>This is where the system starts becoming an LLM agent.</p><p>The <strong>LLM is not the entire agent</strong>.</p><p>It is the decision-making component inside the larger system.</p><p>That distinction is one of the most useful things to understand when reading modern agent architectures.</p><h3>15. Where Does “Reasoning” Actually Happen?</h3><p>This question causes a lot of confusion.</p><p>In our deterministic example:</p><pre>choose_action(...)</pre><p>contains the reasoning policy.</p><p>We can inspect every line.</p><p>With an LLM agent, the equivalent decision is produced by the model.</p><p>The system might provide:</p><pre>Goal<br>+<br>Current state<br>+<br>Previous observations<br>+<br>Available tools<br>+<br>Tool results</pre><p>and ask the model:</p><pre>What should I do next?</pre><p>The model then selects an action/tool call.</p><p>The orchestrator executes it and sends the result back.</p><p>So, at the architectural level:</p><pre>Context<br>   ↓<br>Model inference<br>   ↓<br>Decision / tool call<br>   ↓<br>Tool execution<br>   ↓<br>Observation<br>   ↓<br>Model inference<br>   ↓<br>...</pre><p>The important engineering insight is that <strong>the model’s decision-making is embedded inside a larger deterministic control system</strong>.</p><h3>16. Why This Mental Model Matters</h3><p>Once you understand the basic loop, many “agentic AI” concepts become easier to reason about.</p><h3>For Software Engineers</h3><p>You can identify clear boundaries:</p><pre>Policy<br>Tools<br>State<br>Orchestrator<br>Environment<br>Evaluation</pre><p>You can test each component independently.</p><h3>For Data Engineers</h3><p>You can expose safe data operations as tools:</p><pre>query_customer_data(...)<br>get_sales_summary(...)<br>validate_pipeline(...)<br>check_data_quality(...)</pre><p>Instead of allowing an agent unrestricted database access, you can expose controlled capabilities.</p><h3>For Data Scientists / ML Engineers</h3><p>You can evaluate an agent like a decision policy:</p><pre>Task success rate<br>Tool-call accuracy<br>Number of steps<br>Latency<br>Token usage<br>Failure rate<br>Recovery rate</pre><p>You can then compare different models on the same tasks.</p><h3>For Project Managers and Analysts</h3><p>The model becomes easier to understand:</p><blockquote><em>Agent capability isn’t just “how smart the model is.”</em></blockquote><p>Capability also depends on:</p><ul><li>What tools are available</li><li>What information the agent can access</li><li>What actions are permitted</li><li>How state is maintained</li><li>How success is defined</li><li>How failures are handled</li></ul><p>Adding a tool can sometimes increase an agent’s practical capability more than simply changing the model.</p><h3>17. The Most Important Takeaway</h3><p>We started with something that looks almost trivial:</p><pre>Get treasure.</pre><p>But underneath it we built:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/432/1*ygK5K58vLpMAevjM_BmDZw.png" /></figure><p>That is the core idea.</p><p>The sophistication of modern agents comes from making each component dramatically more capable:</p><ul><li>Better models</li><li>Better tools</li><li>Better memory</li><li>Better planning</li><li>Better environments</li><li>Better state management</li><li>Better evaluation</li><li>Better safety controls</li><li>Better recovery from failure</li></ul><p>But the fundamental control loop doesn’t need to be mysterious.</p><h3>18. Where Do We Go From Here?</h3><p>Now that we have the deterministic foundation, there are several natural next steps.</p><h3>1. Replace the policy with an LLM</h3><p>Replace:</p><pre>choose_action()</pre><p>with an LLM that selects tools based on the current context.</p><p>The rest of the architecture can remain largely intact.</p><h3>2. Add multiple model providers</h3><p>Create a common interface:</p><pre>class Model:<br>  def choose_action(<br>          self,<br>          state,<br>          tools,<br>          goal,<br>      ):<br>          ...</pre><p>Then plug in different providers and evaluate them against the same tasks.</p><h3>3. Add observability</h3><p>Track:</p><pre>Task<br>Model<br>Prompt<br>Tool calls<br>Tool results<br>Steps<br>Latency<br>Tokens<br>Errors<br>Success/failure</pre><p>Now you can actually measure agent performance.</p><h3>4. Add safety boundaries</h3><p>Introduce:</p><ul><li>Tool permissions</li><li>Input validation</li><li>Rate limits</li><li>Maximum steps</li><li>Human approval</li><li>Sandboxed execution</li><li>Network restrictions</li></ul><h3>5. Integrate With Real Systems</h3><p>Eventually, your tools might look like:</p><pre>create_jira_ticket()<br>query_databricks()<br>run_pipeline()<br>read_s3_file()<br>create_pull_request()<br>send_slack_message()</pre><p>At that point, our tiny toy environment starts looking much closer to a production agent architecture.</p><h3>Conclusion</h3><p>AI agents don’t need to be mysterious.</p><p>At the system level, an agent can be understood as a <strong>decision-making component operating in a loop with tools, state, an environment, and explicit goals</strong>.</p><p>Our implementation had no LLM and no framework.</p><p>Yet it already had the fundamental structure:</p><pre>Reason<br>  ↓<br>Act<br>  ↓<br>Observe<br>  ↓<br>Update State<br>  ↓<br>Check Goal<br>  ↓<br>Repeat</pre><p>The LLM comes in primarily as a more flexible decision-making component.</p><p>The rest is engineering.</p><p>And that is perhaps the most useful way to think about agentic AI:</p><blockquote><strong><em>Don’t start by asking, “How intelligent is the agent?”</em></strong></blockquote><blockquote><strong><em>Start by asking, “What state can it see, what actions can it take, what environment can it affect, and how do we know whether it succeeded?”</em></strong></blockquote><p>Once you can answer those questions, “agentic AI” starts to look much less like magic — and much more like systems engineering.</p><p><strong>Code Repo:</strong> <a href="https://github.com/rahulkumar-aws/agent-sandbox">https://github.com/rahulkumar-aws/agent-sandbox</a></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=0b4913913ef8" width="1" height="1" alt=""><hr><p><a href="https://medium.com/developersdiary/part-1-demystifying-ai-agents-build-one-from-scratch-in-python-0b4913913ef8">Part 1: Demystifying AI Agents - Build One From Scratch in Python</a> was originally published in <a href="https://medium.com/developersdiary">Developersdiary</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
    </channel>
</rss>