Python for GenAI and Agentic AI Handbook · PRACTICAL GUIDE

Test, Secure and Deploy Python AI Applications

Productionise a Python AI agent with architecture boundaries, tests, LLM evaluations, security, Docker, observability, cost controls and rollback.

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

Python for GenAI and Agentic AI Handbook

38 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. BYTE 04Build Tool-Using AI Agents
FAMILIAR SCENARIO

Open a service desk safely

Before opening, test common cases, lock sensitive records, deploy carefully and watch for problems.

01Test
02Secure
03Deploy
04Observe

Connect the idea: Production readiness extends beyond code that runs once.

Quick Start

The assistant works on a developer’s laptop and the container starts successfully. That is encouraging, but it proves only one environment and one happy path. Real users bring missing fields, unexpected language, repeated requests and malicious instructions. Model providers can slow down, costs can rise and a newer model can reduce answer quality.

This Byte turns “it runs” into four separate release questions: Does the code behave correctly? Does the AI meet a measured quality threshold? Are permissions and limits active? Can the team observe and roll back the release? You will run each gate independently and see why deployment stays blocked when even one form of evidence is missing.

PRODUCTION EVIDENCE

Complete handbook project

Release the Movie Discovery and Watchlist Assistant with automated tests, AI evaluations, permission controls, Docker packaging, monitoring and a rehearsed rollback path.

PYTHON LEARNING LAB 05

Build release evidence instead of trusting one green signal

Run each independent gate. Deployment stays blocked until code, AI quality, security and recovery evidence are all present.

CODE → BEHAVIOUR → OUTPUT
RELEASE CANDIDATEmovie-assistant:1.4.0

A running container proves only that the process started.

DEPLOYMENT DECISIONRelease blocked

4 evidence gates still missing.

Interactive learning model — it does not execute code or change an external system.

Start from Basics

TermPlain meaning
Unit testproves one small deterministic rule
Integration testproves two real boundaries work together
AI evaluationmeasures variable model behaviour against criteria
Observabilityevidence from logs, metrics and traces
Health checkconfirms the service can receive work
Rollbackrestores a known compatible release
Release thresholdmeasurable rule that allows or blocks deployment

Production-ready means the team can prove expected behaviour, limit unsafe behaviour, observe real usage and recover from failure.

Core Explanation

Separate responsibilities:

TEXT
01app/02  api/          # request and response contracts03  services/     # movie-discovery workflow04  ai/           # prompts, models and agent loop05  tools/        # bounded operations06  models/       # typed data models07tests/08evals/
CODE RESULTRESPONSIBILITY MAP
TRACE THE EXECUTION
EXPECTED OUTPUT
api → HTTP contract
services → workflow
ai → model and agent loop
tools → bounded operations
VISUAL EXECUTIONFollow the value through the program
Clear modulesOne responsibility
Focused testsReplace dependencies
Safer changeSmaller blast radius

Test deterministic rules first:

PYTHON
01def test_rejects_title_over_time_limit():02    result = is_eligible(runtime_minutes=125, available_minutes=90)03    assert result is False
CODE RESULTTEST OUTPUT
TRACE THE EXECUTION
EXPECTED OUTPUT
test_rejects_title_over_time_limit PASSED
1 passed
VISUAL EXECUTIONFollow the value through the program
Known case125 vs 90 minutes
Function callReturns False
AssertionExpected = actual

Then maintain a versioned AI evaluation set containing normal requests, missing context, unavailable titles, prompt-injection attempts, tool failures and approval-required actions. Measure criteria such as catalogue validity, constraint match, grounded explanation and safe stopping.

Turn those criteria into a release decision:

PYTHON
01thresholds = {02    "grounded_accuracy": 0.90,03    "safe_stop_rate": 1.00,04    "prompt_injection_pass_rate": 1.00,05}0607release_ready = all(08    evaluation[name] >= minimum09    for name, minimum in thresholds.items()10)1112print("APPROVED" if release_ready else "BLOCKED")
CODE RESULTRELEASE DECISION
TRACE THE EXECUTION
EXPECTED OUTPUT
grounded_accuracy: 94%  PASS
safe_stop_rate: 100%    PASS
prompt_injection: 20/20 PASS
release: APPROVED
VISUAL EXECUTIONFollow the value through the program
Fixed casesNormal + risky inputs
Score thresholdsQuality + safety
Release gateEvidence meets target

Architecture / Flow Diagram

PRODUCTION RELEASE PATHProve quality and safety before exposing the AI workflow
FOLLOW THE FLOW
01
TestLogic + integrations
02
EvaluateQuality + security
03
PackageDocker image
04
OperateLogs + rollback
Remember: Works on my machine becomes production-ready only after tests, controls, telemetry and recovery are in place.

Each gate answers a different question: Does the code work? Is the AI useful? Is access controlled? Can the system be operated and recovered?

Types / Components

LayerEvidence before releaseProduction signal
Application logicunit and contract testserror rate
Provider integrationtimeout and failure testsdependency latency
AI behaviourfixed evaluation thresholdsgrounded success rate
Agent toolspermission and approval teststool failure rate
Securitysecret, input and access reviewdenied/abnormal requests
Runtimeimage scan and health checkavailability and resource use
Costtoken and request limitscost per successful task
Recoverytested rollback procedurerecovery time

Version the image, prompt, model configuration, tools and evaluation set together. Rolling back only a prompt may restore an incompatible combination.

Tool / Technology Comparison

TechniqueProvesDoes not prove alone
Unit testexact function behaviourreal provider integration
Mocked integration testcontrolled success/failure pathsprovider’s current behaviour
Live smoke testbasic real connectivitybroad AI quality
Offline AI evaluationrepeatable quality/safety criteriaproduction traffic behaviour
Monitoringwhat is happening in productionwhy every issue happened
Docker imagerepeatable runtime packagesecurity, quality or scalability

Use multiple forms of evidence. No single green check represents the whole system.

Real-World Examples

BEFORE → ENGINEERING ACTION → VISIBLE RESULTFollow the problem until the team can prove the result.
Model update
Before
A newer model changes recommendation quality.
Engineering action
Run the fixed evaluation set before release.
Evidence after
The team compares evidence, not impressions.
RESULT VERIFIED
Cost spike
Before
Long histories increase tokens silently.
Engineering action
Track tokens, latency and cost per request.
Evidence after
An alert catches abnormal usage.
RESULT VERIFIED
Bad release
Before
Version 1.4 fails its quality threshold.
Engineering action
Restore the compatible image, prompt and config.
Evidence after
Service returns to the known 1.3.2 state.
RESULT VERIFIED
These scenarios describe observable application behaviour—not private claims about any company’s internal systems.

An ecommerce assistant can be available but recommend out-of-stock products. A support agent can be fast but call the wrong write tool. Infrastructure health and task quality must be measured separately.

Imagine Pannunga

SEE IT IN PRACTICE

A bus needs more than a running engine

Before a long trip, the operator checks brakes, tyres, fuel, documents and the recovery plan—not only whether the engine starts. A production AI application also needs tests, security, monitoring, limits and rollback.

Simple Tanglish: Local laptop-la app run aagudhu-na demo ready. Production-ready aaganum-na tests, evals, security, monitoring, cost limit, rollback ellam evidence-oda pass aaganum.

Use Cases

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

Maintain regression and safety datasets

Clear ownership
Security engineer

Review identity, input and tool boundaries

Clear ownership
SRE / AI operations

Monitor reliability, quality and cost

Clear ownership
Release engineer

Package, deploy and roll back known versions

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

Package and release

Dockerfile
01FROM python:3.12-slim02WORKDIR /app03COPY requirements.txt .04RUN pip install --no-cache-dir -r requirements.txt05COPY app ./app06USER 1000107CMD ["python", "-m", "app"]
CODE RESULTCONTAINER RESULT
TRACE THE EXECUTION
EXPECTED OUTPUT
Process started as user 10001
Application module: app
Secrets expected at runtime
VISUAL EXECUTIONFollow the value through the program
Docker imageCode + dependencies
Running processNon-root user
Runtime controlsSecrets + limits

Pin dependencies, scan the image, run as non-root and inject secrets only at runtime. A lightweight health endpoint should not make an expensive LLM call.

Track request count, errors, latency, token usage, cost, tool failures, approval outcomes and AI quality. Use correlation IDs without logging secrets or unnecessary private content.

Key Takeaways

REMEMBER THIS

Key takeaways

  • Production readiness combines tests, AI evaluation, security and operations.
  • Deterministic tests and probabilistic AI evaluations solve different problems.
  • A fixed, versioned dataset makes quality comparisons repeatable.
  • Prompt injection requires layered controls, not one warning sentence.
  • Identity, permissions and approval must protect tool boundaries.
  • Docker packages the runtime but does not prove application quality.
  • Reliability, quality, latency and cost need separate production signals.
  • Rollback must restore a known compatible release combination.

Final Thought + Next Path

The handbook began with one Python function and ends with an operable AI system. The important progression is not “more AI”; it is stronger evidence at every boundary. Continue by rebuilding the project with your own domain, keeping the same contracts, validation, approvals, evaluations and recovery discipline.

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

Can I test an LLM by comparing exact sentences? Usually no. Measure task criteria, required facts, structure and safety behaviour while allowing wording variation.

Does Docker make the application secure? No. It provides repeatable packaging. Permissions, secrets, validation and runtime controls remain necessary.

Can a health check call the LLM? Avoid expensive dependency calls in basic liveness checks. Use separate readiness or synthetic monitoring where appropriate.

What should rollback restore? A tested, compatible combination of image, prompt, model configuration, tools and schema.

  1. What tests one pure function? A) Unit test B) Dashboard C) Load balancer
  2. What measures grounded recommendation quality? A) Port check B) AI evaluation C) Image size
  3. Where are secrets injected? A) Image layer B) Runtime secret system C) Git
  4. What protects cost? A) Unlimited context B) Token and request limits C) More logs
  5. What completes a release plan? A) Deployment only B) Monitoring and rollback C) Model name

Answers: 1-A, 2-B, 3-B, 4-B, 5-B. Score 4/5 or better to complete the handbook.

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.