My Python for AI 101 · Chapter 10
Network, time and concurrency
Five cards on waiting: the network checked before the call, the time limit bounded by a ThreadA parallel thread of execution; join(timeout) lets you wait for an answer for N seconds at most.See in the glossary →, the asynchronous entrypoint, the parallel fan-out and the lock.
Card 48 — Careful networking: urlsplit, ipaddress, urllib
Project. Dev3Pack AI Engineering Bootcamp
In one sentence. Before calling a URL, you split it, check the scheme, the host and the IP address; only then do you call it, with a maximum wait.
Why it matters for an AgentA program that uses a language model to decide what to do (search, call a tool, answer, refuse), in a loop, with stopping rules.See in the glossary →. A tool that fetches whatever URL it is given can be pointed inward (169.254.169.254, the local machine): that is SSRFServer-Side Request Forgery: getting a tool that fetches URLs to call an internal or private address on the attacker's behalf.See in the glossary →.
Analogy. Checking the beneficiary’s IBAN before the transfer, not after.
The mechanism.
parts = urlsplit(url)
if parts.scheme != "https" or not parts.hostname:
return False
ip = ipaddress.ip_address(address)
public = ip.is_global and not (ip.is_private or ip.is_loopback or ip.is_link_local)
resolved = {info[4][0] for info in socket.getaddrinfo(host, parts.port or 443)}
return bool(resolved) and all(_is_public(a) for a in resolved) # ALL public
Input → output. http://169.254.169.254/latest/meta-data/ → host 169.254.169.254, is_global → False. ip_address(int("2130706433")) → 127.0.0.1: a number hiding the local machine. is_public_url("http://example.com") → False (not https); is_public_url("https://10.0.0.5") → False.
Where to read it again. ch04 · cell 14 (allowed_url, fetch_rates with User-Agent and timeout=5) · ch13 · cells 7 and 11 (fetch_guard, every redirect checked again) · my-gecko-buyer/server/guard.py · is_public_url · buyer/mcp_client.py · _post (urllib.request.Request with the MCPModel Context Protocol: a standard for exposing tools and data sources to any agent. An MCP tool is discovered by its name, description and schema.See in the glossary → headers, course) · ch14 · cell 15 (http_request: HTTPError = the server answered; OSError = nobody is listening).
To reuse. The host allowlist lives in configuration, never in an argument. Refuse a name that cannot be resolved. A timeout on every call. Tell “the server said no” apart from “the server cannot be reached”.
Card 49 — Time, timeouts and thread
Project. Dev3Pack AI Engineering Bootcamp
In one sentence. time.perf_counter() measures a duration; a threading.Thread waited on with join(timeout) bounds a call that has no time limit of its own.
Why it matters for an agent. A local model may never answer. The agent must refuse after N seconds, not leave the user waiting.
Analogy. A limit order that expires at the close.
The mechanism.
worker = threading.Thread(target=call, daemon=True)
worker.start()
worker.join(self.timeout_s) # waits timeout_s seconds at most
if worker.is_alive():
raise ProviderTimeout(f"no answer within {self.timeout_s} s")
started = time.perf_counter()
elapsed_ms = round((time.perf_counter() - started) * 1000)
Input → output. A 2 s task waited on for 0.2 s → is_alive() is True, and the function hands back control in under 400 ms.
Where to read it again. grounded-research-agent/agent.py · _complete (timeout_s = 90) · ch14 · cells 5 and 9 (elapsed_ms, the Cold startThe slowness of the first call to a service that just started. You measure it: it's a number, not a failure verdict.See in the glossary →) · ch02 · cell 35 (time.monotonic) · ch10 · cell 11 (the ADRArchitecture Decision Record: a page that records a technical decision, the option set aside, and the numeric measurement that would change it.See in the glossary →: a 3 s TimeoutA maximum waiting time. Past it, you abandon the call and return a readable refusal, instead of waiting forever.See in the glossary →, chosen from a measurement).
To reuse. perf_counter to measure, not time.time. daemon=True so a stuck thread does not stop the program from ending. A timeout becomes a RefusalAn explicit "I can't answer": no citation, zero confidence, human review. A state, not a crash.See in the glossary → flagged for review, not a crash.
Card 50 — The asynchronous @app.entrypoint
Project. AI Support Agent (AWS Scholars, chapter 2)
In one sentence. invoke() is declared async def and decorated with @app.entrypointThe decorator that makes a function the request handler of the AgentCore Runtime.See in the glossary →: the AgentCore runtime calls it as a coroutine for every incoming request.
Why it matters for an agent. A deployed agent must be able to handle several requests without one blocking the others; the asynchronous form of the entrypoint is what makes that possible, even if the body of today’s function is mostly sequential.
Analogy. A switchboard that can put one call on hold and take another, rather than a single line that must be free before it rings again.
The mechanism.
@app.entrypoint
async def invoke(payload, context=None):
user_input = payload.get("prompt", "")
actor_id = payload.get("customer_id", "anonymous")
session_id = payload.get("session_id") or str(uuid.uuid4())
...
Input → output. {"prompt": "Can you track order ORD-001?", "customer_id": "CUST-123", "session_id": "t1"} → a text answer (the delivery status, the tracking number).
Where to read it again. main.py L337–351
To reuse. Declare a deployed agent’s entrypoint async def (AgentCore, FastAPI, Lambda) from the start, even if nothing inside is concurrent yet: it costs nothing and avoids a rewrite later.
Card 51 — Parallel fan-out: ThreadPoolExecutor and as_completed
Project. NovaMart Multi-Agent Support (AWS Scholars, chapter 3)
In one sentence. submit starts a function in a thread and returns a FutureThe promise of the result of a task started in a thread.See in the glossary → (a promise of a result) straight away; as_completedWalks through futures in the order in which they finish.See in the glossary → hands back the futures in the order in which they finish; future.result() gives the value or raises the thread’s error again.
Why it matters for an agent. The three Knowledge baseA set of documents, split and indexed, that the agent queries before answering. An unsynced base returns nothing, with no error.See in the glossary → are independent: querying them in parallel costs the time of the slowest one, not the sum. That is the core of the RAGRetrieval-Augmented Generation: search for passages in a base, then answer from them, citing them.See in the glossary → rubric (ThreadPoolExecutor(max_workers=3) + as_completed()). Inventory then Refund, on the other hand, depend on each other: there, the OrchestratorIn a multi-agent system, the agent that never answers itself: it routes the work to specialist agents.See in the glossary → forces sequential order.
Analogy. Three analysts asked at the same time, each about their own asset class; you read the notes as they come in.
The mechanism.
with ThreadPoolExecutor(max_workers=3) as executor:
futures = {executor.submit(_run_retriever, domain, agent, query): domain
for domain, agent in retrievers.items()}
for future in as_completed(futures):
domain = futures[future]
try:
_, text = future.result()
results[domain] = text
except Exception as exc: # one KB down does not sink the others
results[domain] = f"[{domain} retriever error: {exc}]"
orchestrator = Agent(..., tool_executor=SequentialToolExecutor()) # dependent steps
Input → output. Replayed with three tasks of 0.3 s, 0.1 s and 0.2 s: arrival order ['Shipping', 'Warranty', 'Returns'], total time 0.3 s instead of 0.6 s. In the project, Strands’ default parallel execution started the RefundAgent before the InventoryAgent had written its facts: hence SequentialToolExecutorThe Strands executor that runs a turn's tools one after the other.See in the glossary →.
Where to read it again. agent_orchestrator.py · search_all_policies · agent_orchestrator.py · ThreadPoolExecutor · agent_orchestrator.py · SequentialToolExecutor.
To reuse. Run in parallel the independent tasks that wait on the network; one try per future; the result assembled in a fixed order, not in the order of arrival. Sequential as soon as a step reads what the previous one writes.
Card 52 — Lock, per-thread context, lazy singleton
Project. NovaMart Multi-Agent Support (AWS Scholars, chapter 3)
In one sentence. threading.LockA lock: only one thread at a time runs the protected block.See in the glossary → guarantees that only one thread runs a block at a time; a ContextVarA variable whose value depends on the current execution context.See in the glossary → carries a value specific to the current execution context; a Lazy singletonAn object created only once, the first time it is needed, then reused.See in the glossary → creates a costly object only once, the first time it is needed.
Why it matters for an agent. The Runtime serves several requests in parallel: the graph of the 5 agents must be built only once, and the metrics log stream created only once.
Analogy. The single key to the archive room: one employee at a time, and the first one in turns on the light for everyone.
The mechanism.
_metrics_lock = threading.Lock()
with _metrics_lock:
if _metrics_stream['name'] is None: # created once, whatever the thread
_metrics_logs.create_log_stream(...)
_metrics_stream['name'] = name
lock, graph = threading.Lock(), {}
def _orchestrator():
with lock:
if 'agent' not in graph:
graph['agent'] = build_agent_graph() # built on the first request only
return graph['agent']
Input → output. First call to the Runtime: the graph is built (several seconds); following calls: immediate reuse. The X-Ray tracer uses a ContextVar to know which node to attach a subsegment to; the ThreadPoolExecutorA pool of threads that runs tasks in parallel, suited to waiting on the network.See in the glossary → threads don’t inherit that context, hence a FallbackA back-up code path run when the main call fails, to return a partial result rather than an error.See in the glossary → mechanism that keeps the Service Map connected.
Where to read it again. agent_orchestrator.py · _metrics_lock · agent_orchestrator.py · _orchestrator · agent_observability.py · ContextVar.
To reuse. Every “create if missing” shared between threads goes under a lock. Costly objects (agent graph, clients) built on the first call, then reused.
Card 65 — The semaphore and the bounded wait
Project. DRILLS.ai (Builds, OpenAI DevDay hackathon)
In one sentence. asyncio.Semaphore(2) lets two operations through at a time; locked() says whether it is full; asyncio.wait_for(…, timeout=95) stops waiting after 95 seconds.
Why it matters for an agent. A model call costs money and can take a while. Rather than piling up requests, the server answers “busy” (429) straight away, and an operation that runs too long ends in 504 instead of hanging.
Analogy. Two open counters and a “come back later” ticket when both are taken, rather than an endless queue.
The mechanism.
application_slots = asyncio.Semaphore(2)
async def run_application_operation(operation, stage="application"):
if not os.getenv("OPENAI_API_KEY"):
raise HTTPException(status_code=503, detail="Application service is not configured.")
if application_slots.locked():
raise HTTPException(status_code=429, detail="Application service is busy. Please try again shortly.")
async with application_slots:
result = await asyncio.wait_for(operation(), timeout=95)
...
Input → output. Replayed: both slots taken, a third call → 429 Application service is busy. Please try again shortly. A free slot → the operation goes through. No key → 503 before anything else.
Where to read it. api/main.py · application_slots, run_application_operation.
To reuse. Refuse fast rather than wait forever. The SemaphoreA counter that limits how many operations run at the same time. When it is full, the next request is refused or waits.See in the glossary → holds for one process: it is neither a quota shared across servers nor a spending cap.
Card 66 — Async fan-out: asyncio.gather
Project. DRILLS.ai (Builds, OpenAI DevDay hackathon)
In one sentence. asyncio.gatherStarts several coroutines at the same time and returns their results in the order they were given.See in the glossary → starts several coroutines at the same time and returns their results in order; here, each read returns a pair (postings, source down or None).
Why it matters for an agent. Five sources read one after the other add up their delays. And a source that is down must not make the others fail, nor pass for “no postings”.
Analogy. Asking five brokers for a price at the same time, and noting the ones that did not answer instead of concluding the market is empty.
The mechanism.
async def read(board):
try:
response = await client.get(f'https://boards-api.greenhouse.io/v1/boards/{board}/jobs', params={'content': 'true'})
response.raise_for_status()
payload = response.json()
jobs = [result for job in payload['jobs'] if (result := qualify(job, board))]
return jobs, None
except (httpx.HTTPError, ValueError, KeyError, TypeError):
return [], BOARDS[board]
batches = await asyncio.gather(*(read(board) for board in BOARDS), *(read_ashby(board) for board in ASHBY_BOARDS))
Input → output. Replayed with the network cut: 0 postings, unavailable_sources → ['Anthropic', 'Databricks', 'Scale AI', 'Mistral AI', 'Dust'], and the result is not cached. A complete answer stays cached for 300 seconds.
Where to read it. jobs.py · load_jobs.
To reuse. Each task catches its own errors and says who failed. Never cache an incomplete result. Compare with card 51, the same idea with threads.
In the field
The chapters of my courses and my projects where these mechanisms run for real.
- Dev3Pack, Session 2: card 49.
- Dev3Pack, Session 4: card 48.
- Dev3Pack, Session 10: card 49.
- Dev3Pack, Session 13: card 48.
- Dev3Pack, Session 14: cards 48 and 49.
- Dev3Pack, Final assignment: card 49.
- Dev3Pack, Gecko capstone: card 48.
- AWS Scholars, chapter 2 · AI Support Agent: card 50.
- AWS Scholars, chapter 3 · NovaMart Multi-Agent Support: cards 51 and 52.
- DRILLS.ai, chapter 5 · Phase 2: the pivot to job applications: cards 48 and 66.
- DRILLS.ai, chapter 10 · Deploying and operating: cards 49 and 65.