Python for GenAI and Agentic AI Handbook · PRACTICAL GUIDE

Build Tool-Using AI Agents with Python

Build a bounded Python watchlist agent with clear tools, state, memory, stopping rules, execution evidence and human approval.

HANDBOOK JOURNEYByte 4 of 5View all Bytes
HANDBOOK JOURNEYByte 4 of 5

Python for GenAI and Agentic AI Handbook

36 min focused reading
  1. BYTE 01Python Foundations for AI Apps
  2. BYTE 02APIs, JSON and LLM Responses
  3. BYTE 03Build a GenAI App with Python
  4. 05BYTE 05Test, Secure and Deploy Python AI
FAMILIAR SCENARIO

An assistant with a written checklist

An assistant watches a task, uses an approved tool, records progress and asks before an important action.

01Goal
02Tool
03State
04Approval

Connect the idea: A useful Python agent has boundaries and stopping rules.

Quick Start

A chatbot answers once: “Here are three weekend movies.” An agent can go further: search the current catalogue, compare family preferences, calculate total runtime and prepare a shared-watchlist update. But preparing an update is still not the same as completing it.

This Byte slows the agent loop down into five visible moments—goal, tool call, observation, approval proposal and confirmed result. Stepping through them will show exactly when state changes and why the agent must pause before a consequential action.

BOUNDED AUTONOMY

Byte project

Build a Watchlist Agent that searches verified titles, explains its plan, prepares a shared-profile update and pauses for approval before any write action.

PYTHON LEARNING LAB 04

Step through an agent loop and watch state change

An agent does not jump from goal to success. Move one step at a time and notice where evidence, approval and confirmation enter the loop.

CODE → BEHAVIOUR → OUTPUT
CURRENT STEP 1 OF 5GoalPrepare a weekend watchlist

No external action

Agent stategoal: weekend watchlistevidence: waitingapproval: not requestedexternal change: not completed
Interactive learning model — it does not execute code or change an external system.

Start from Basics

PatternWhat it doesExample
Chatbotresponds to one messageexplains an age rating
Copilotassists a person doing workdrafts a weekend watchlist
Agentchooses and performs bounded stepssearches titles and prepares an update
Toolperforms one external operationsearch_titles()
Statefacts needed during this rungoal, steps, tool results
Memoryselected context retained across runspermitted genre preference
Approvalhuman authorisation before consequenceconfirm shared-profile update

An agent loop is goal → choose step → call tool → observe result → stop or continue.

Core Explanation

Create narrow tools with precise contracts:

PYTHON
01def search_titles(language: str, rating: str) -> list[dict]:02    """Return currently available titles matching allowed filters."""03    ...0405def add_to_watchlist(profile_id: str, title_id: str) -> dict:06    """Add one verified title after an approval token is present."""07    ...
CODE RESULTTOOL CONTRACTS CREATED
TRACE THE EXECUTION
EXPECTED OUTPUT
search_titles → read-only catalogue access
add_to_watchlist → approval token required
VISUAL EXECUTIONFollow the value through the program
Python functionBounded operation
Typed contractInputs + result
PermissionRead or write scope

Avoid a general run_anything tool. Narrow tools are easier to authorise, validate, test and audit.

PYTHON
01if proposed_action.type == "update_shared_watchlist":02    return {03        "status": "approval_required",04        "proposal": proposed_action.model_dump(),05    }
CODE RESULTAGENT STATE
TRACE THE EXECUTION
EXPECTED OUTPUT
status: approval_required
external_change: not_completed
next_step: wait_for_human
VISUAL EXECUTIONFollow the value through the program
Agent proposalPlanned change
Human reviewApprove or reject
Write toolRun only after approval

After approval, the agent must inspect the write tool’s result. Preparing an action, asking for approval and completing an action are three different states.

Keep the loop small and make every stopping condition visible:

PYTHON
01for step in range(1, 5):02    decision = choose_next_step(state)0304    if decision.requires_approval:05        return request_approval(decision)0607    result = run_allowed_tool(decision.tool, decision.arguments)08    state.record(result)0910    if result.goal_completed:11        return {"status": "completed", "evidence": result}1213return {"status": "stopped", "reason": "Step limit reached"}
CODE RESULTCONFIRMED TOOL RESULT
TRACE THE EXECUTION
EXPECTED OUTPUT
step 1 → 3 titles found
step 2 → mv-101 selected
step 3 → approval received
step 4 → watchlist_updated: true
VISUAL EXECUTIONFollow the value through the program
Read toolCollect evidence
Approval gateAuthorise exact change
Write resultCompletion confirmed

Architecture / Flow Diagram

BOUNDED AGENT LOOPChoose one tool, observe evidence and decide whether to continue
FOLLOW THE FLOW
01
GoalOutcome + limits
02
Choose stepCurrent state
03
Call toolBounded action
04
Check + approveStop safely
Remember: Preparing an action is not completing it; consequential actions require tool confirmation and human approval.

The observation step prevents blind execution. Every tool result changes what the agent knows and therefore what it should do next.

Types / Components

ComponentResponsibilitySafety question
Goaldesired outcome and constraintsIs “done” clear?
Plannerselects the next useful stepCan it choose only allowed actions?
Tool registryexposes bounded capabilitiesAre read and write tools separate?
Staterecords current-run evidenceCan each result be traced?
Memoryretains selected permitted contextIs there a retention rule?
Policychecks identity, scope and limitsWho is allowed to do this?
Approval gatepauses consequential actionIs the proposal specific?
Stop ruleends success, uncertainty or failureCan repeated loops terminate?

Stop when the goal is complete, information is missing, permission is absent, a risk boundary is reached, a tool repeatedly fails or the maximum step count is reached.

Tool / Technology Comparison

ApproachBest forTrade-off
Explicit Python loopnarrow workflow and transparent controlyou implement state and branching
Agent frameworkdurable state, tracing and complex branchesadditional abstraction and dependency
Workflow enginepredictable long-running business processless flexible open-ended reasoning
MCP-connected toolsinteroperable tool/context exposuretrust and authorisation still remain yours
No-code agent builderrapid prototype with known connectorsfine-grained testing may be limited

MCP standardises how tools and context are exposed. It does not make a tool safe; authentication, authorisation, validation and approval remain application responsibilities.

Real-World Examples

BEFORE → ENGINEERING ACTION → VISIBLE RESULTFollow the problem until the team can prove the result.
Title search
Before
The model invents availability from memory.
Engineering action
Call a read-only catalogue tool.
Evidence after
The next step uses current tool evidence.
RESULT VERIFIED
Shared watchlist
Before
The agent is ready to change a family profile.
Engineering action
Pause with a precise approval proposal.
Evidence after
Nothing changes until a person approves.
RESULT VERIFIED
Repeated failure
Before
The same tool times out repeatedly.
Engineering action
Stop at the retry and step limit.
Evidence after
The user receives an honest failure state.
RESULT VERIFIED
These scenarios describe observable application behaviour—not private claims about any company’s internal systems.

In a support workflow, an agent may read an approved knowledge base and draft a response. Sending the response or issuing a refund needs a stronger permission boundary and verified tool result.

Imagine Pannunga

SEE IT IN PRACTICE

A junior coordinator works within a manager boundary

A junior coordinator can collect facts, compare options and prepare a plan. They should not send an official message, make a payment or change access without the correct authority and confirmation.

Simple Tanglish: Agent research panni plan prepare pannalaam. Aana shared profile change, email send, payment madhiri action-ku clear permission and tool confirmation venum.

Use Cases

WHO USES THIS — AND WHAT DO THEY OWN?Connect each concept to an engineering responsibility.
Agent engineer

Design the decision loop and tool contracts

Clear ownership
Tool developer

Implement narrow authorised operations

Clear ownership
Security engineer

Separate read, write and approval permissions

Clear ownership
Platform engineer

Trace steps, failures and execution evidence

Clear ownership
One Python AI application is a team system: code, quality, security and operations work together.

Practical project

Implement search_titles, check_profile_preferences, calculate_total_runtime and prepare_watchlist_update. Give the loop a maximum of four steps. Keep the update as a proposal until the user approves; then verify the tool response before reporting completion.

Log tool name, safe parameters, result status, latency and correlation ID. Never log secrets or unnecessary viewer content.

Key Takeaways

REMEMBER THIS

Key takeaways

  • Agents choose steps; tools perform bounded operations.
  • Every tool needs a clear name, description, parameters and result contract.
  • State tracks the current run; memory carries selected context across runs.
  • Read and write capabilities should have different permissions.
  • Consequential actions need a specific, visible approval proposal.
  • Tool evidence—not model wording—proves external completion.
  • Retry, step and time limits prevent uncontrolled loops.
  • Frameworks and MCP do not remove application safety responsibilities.

Final Thought + Next Path

Useful autonomy comes from clear boundaries, not unlimited capability. Your agent can now choose a tool, observe real evidence and pause before a consequential change. In the final Byte, you will test this behaviour, secure every boundary, package the application and operate it with measurable release evidence.

FAQ + Knowledge Check

LESSON CHECKPOINTConfirm the concept before moving forward

Choose an answer, inspect the explanation and explain the idea in your own words.

RETENTION

Is an agent simply a chatbot with a longer prompt? No. An agent can select tools, change state and repeat steps toward a goal.

Is memory the same as state? No. State supports the current run; memory retains selected information across interactions.

Does approval mean the action already happened? No. Approval authorises a tool call; the returned result proves success or failure.

Does MCP guarantee a safe integration? No. It improves interoperability, while your system still owns trust and permissions.

  1. What proves an external update completed? A) Draft text B) Tool success result C) Model confidence
  2. Which tool is safer? A) run_anything B) narrow typed tool C) hidden shell
  3. What ends repeated failure? A) More prompts B) Stop and retry limits C) Memory
  4. When should write access occur? A) Always B) With authority and approval C) Before validation
  5. What belongs in logs? A) Secrets B) Safe parameters and status C) Full private conversation

Answers: 1-B, 2-B, 3-B, 4-B, 5-B. Score 4/5 or better before continuing.

Learning rule: explain the answer in your own words before checking the next Byte.

Primary sources

OPTIONAL LEARNING CONNECTIONS

Continue by concept

Choose only what supports your next goal. This Byte does not require either link.