Skip to main content

08. Programming & Technologies

Python for Agentic AI

Python is the default language for Agentic AI: type hints and Pydantic turn messy LLM JSON into safe contracts; asyncio and httpx run concurrent model/tool I/O; FastAPI serves the product edge; venv/uv keep deps reproducible. Frameworks change — these Python skills stay.

What you will learn

  • Explain why Python dominates agent stacks
  • Use typing + Pydantic at LLM and tool boundaries
  • Design async gather/Semaphore patterns for agent I/O
  • Structure tool handlers with validation and authZ
  • Answer interview questions with short, solid answers
Python pillars: typing Pydantic asyncio tools serving
Interview staple: types and async at the edges; frameworks sit on top.

Definition

Python for Agentic AI means writing the runtime glue that frameworks assume: typed functions, validated schemas, non-blocking HTTP to models and tools, secrets via env, and a thin API that owns auth, budgets, and logging.

Most Module 07 kits (LangChain, LangGraph, CrewAI, AutoGen, Agents SDK, ADK, PydanticAI, LlamaIndex, Haystack) are Python-first. Mastering the language patterns matters more than memorizing one SDK.

Introduction

This lesson (#1 in Programming & Technologies) opens Module 08 after the frameworks survey. You know orchestration kits; now ground the language they run on.

Next: JavaScript and TypeScript for Agentic AI — the other major product language for agents and UIs.

Why Python

  • Richest agent/RAG/ML ecosystem and examples
  • Fast iteration for prototypes that become services
  • Pydantic + FastAPI = natural typed HTTP edge
  • Asyncio fits wait-heavy LLM and tool calls
  • Still need discipline — scripts are not production agents

Typing essentials

  • Annotate public functions: list[str], dict[str, int], X | None (3.10+)
  • Prefer built-in generics over typing.List / Dict
  • TypedDict for structured dict shapes when models are overkill
  • Run pyright or mypy in CI — agents amplify type bugs into tool disasters
  • match/case for routing tool results and API envelopes (always case _)

Pydantic contracts

LLMs emit probabilistic strings. Databases and tools need deterministic types. Pydantic v2 is the boundary firewall: validate tool args and final outputs before side effects.

LLM JSON through Pydantic into tools
Fail closed on ValidationError — never pass raw model JSON to refunds or writes.
  • BaseModel + Field for tool argument schemas
  • model_validate / model_validate_json at parse time
  • Use dataclasses internally; Pydantic at external boundaries
  • Structured outputs (SDK output_type) still re-validate in your code
  • Same idea as Module 05: least privilege + validated args

Asyncio and httpx

Agent runs spend most time waiting on networks. Use async clients, asyncio.gather for independent calls, and asyncio.Semaphore to cap concurrency against rate limits and cost.

Agent loop awaiting LLM tools and gather with Semaphore
Bound parallel LLM/tool calls — unbounded gather can melt quotas.
  • httpx.AsyncClient (or async SDK clients) — not sync requests in async routes
  • Explicit timeouts (connect + read)
  • gather for fan-out; Semaphore for budgets
  • asyncio.to_thread / process pool for blocking CPU work
  • Never block the event loop in FastAPI handlers

Tools as Python functions

  • One tool = one typed function with a clear docstring/schema
  • Validate args with Pydantic; check authZ in the function body
  • Return structured results the model can consume
  • Idempotency and retries for write tools
  • Log tool name, latency, and outcome — not secrets

Serving and packaging

  • FastAPI + Uvicorn for the product API wrapping the agent
  • Secrets only from env / secret managers — never in prompts or repos
  • uv or venv + lockfile for reproducible installs
  • Pin framework and model-client versions
  • Structured logs: request id, tokens, latency, tool counts

Testing agent Python

  • Unit-test tool handlers with fake args — no live LLM needed
  • Contract tests for Pydantic schemas (valid + invalid fixtures)
  • Mock LLM/httpx in integration tests; keep a small live smoke suite
  • Eval sets for prompts separate from pytest unit suites
  • Fail CI on type errors and schema regressions

Map to earlier modules

  • Pydantic validation ≈ Module 05 tool-arg safety
  • Async gather ≈ Module 06 parallel workers
  • FastAPI edge ≈ CrewAI/Agents SDK “app owns auth/budgets”
  • Types enable PydanticAI and clean SDK tool schemas
  • Next language track: JS/TS for browser and Node agents

Failure modes

  • Sync requests inside async agent loops
  • Trusting raw LLM JSON into SQL or payments
  • Unbounded gather that spikes cost and rate limits
  • Hardcoded API keys in notebooks pushed to git
  • No types — “it worked in the demo” until production

Program / implementation notes

Build a tiny FastAPI service with one Pydantic tool schema, an async httpx call, and a Semaphore. Keep the agent framework optional until the Python spine is solid.

  • Prefer Python 3.11+ for typing and performance
  • Next: JavaScript and TypeScript for Agentic AI

Advantages and limitations

  • Advantage: deepest agent/ML ecosystem
  • Advantage: Pydantic + FastAPI production path is clear
  • Advantage: asyncio matches wait-heavy LLM workloads
  • Limitation: GIL — offload heavy CPU; do not pretend threads fix everything
  • Limitation: easy to ship messy scripts without contracts
  • Limitation: browser/realtime UIs often need JS/TS alongside

Key points

  • Python skills outlast any single agent framework.
  • Type hints + pyright/mypy catch tool bugs early.
  • Pydantic validates LLM/tool JSON before side effects.
  • asyncio + httpx + Semaphore for concurrent I/O with caps.
  • FastAPI edge owns auth, budgets, secrets, and logs.
  • Test tools and schemas without always calling a live model.

FAQs

Do I need asyncio for every agent?

For production APIs and concurrent tools/LLM calls, yes in practice. Small sync scripts are fine for learning — do not ship them as the service core.

Pydantic or dataclasses?

Dataclasses for internal domain objects. Pydantic for API, config, and anything from an LLM or external HTTP payload.

httpx or requests?

Prefer httpx (especially AsyncClient) for new agent code. requests is sync and blocks event loops.

Is Python enough without a framework?

You can build a ReAct loop yourself, but frameworks save agent-loop boilerplate. Still write your own validation, authZ, and budgets.

Interview questions

  1. Why is Python dominant for Agentic AI?

    Answer Richest libraries for LLMs, RAG, and agents, plus FastAPI/Pydantic for typed services and asyncio for wait-heavy I/O — most major agent SDKs ship Python first.

  2. How do you safely use LLM JSON in tools?

    Answer Parse and validate with Pydantic (or equivalent) before any side effect; reject invalid args fail-closed and log the validation error.

  3. How do you run parallel tool or LLM calls in Python?

    Answer Use asyncio.gather with async clients, wrap tasks in an asyncio.Semaphore to cap concurrency, and set explicit timeouts.

  4. What belongs in a FastAPI agent service?

    Answer Auth, input validation, budget/timeout enforcement, calling the agent/runtime, structured logging/tracing, and never embedding secrets in prompts.

  5. How do you test agent Python code?

    Answer Unit-test tool handlers and Pydantic schemas with fixtures; mock LLM/HTTP in integration tests; keep a small live smoke suite and separate eval sets.

  6. Name a common production Python agent bug.

    Answer Calling synchronous requests (or heavy CPU) inside async handlers — blocking the event loop and stalling all concurrent agent runs.

Related topics

Practice task

Complete each numbered practice step in a notebook or doc before opening the next lesson.

  1. Write a Pydantic model for a “create_ticket” tool (3–5 fields with constraints).
  2. Sketch an async function that gathers 3 httpx calls under a Semaphore(2).
  3. List 4 items your FastAPI edge must enforce before running an agent.
  4. Write 3 pytest cases: valid tool args, invalid args, and unauthorized user.
  5. Answer interview questions 1, 2, and 3 in two sentences each.