AI 320 — Applied AI, Retrieval and Reliable Automation · Weeks 9–11
Tool use, state machines and idempotent workflows
Full teaching sequence and cumulative subject work
Study the complete on-site source sections below, then work the original example, changed-condition problem and transfer laboratory. Review software transactions and graph state from CS 201 and CS 220; revisit CS50 AI Search and Knowledge. Design a dry-run workflow before connecting any external service.
Durable action state and idempotency
An action workflow separates proposed, validated, approved, executing and completed states. The approval should bind a stable payload fingerprint and operation identifier. A local set can demonstrate deduplication within one process, but cannot protect concurrent workers or survive restart. Durable storage and atomic state transitions are needed at the actual action boundary.
Distributed systems can fail after an external service performs an action but before the local system records success. A retry policy must reconcile that uncertain outcome using the provider’s supported idempotency or lookup mechanism. Claiming exactly-once delivery from a local flag alone conceals this failure window.
Worked problem
A worker sends request R, the provider performs it, and the worker crashes before recording completed. Explain what the retry worker must avoid.
Trace the complete reasoning
It must not assume that absence of a local completion flag proves the action never happened.
Reuse the stable operation identifier with an external idempotency mechanism where supported, or reconcile against the provider’s recorded action before retrying.
Store the approved payload fingerprint durably and reject a changed payload under the same operation ID.
Record uncertain outcomes explicitly and route unresolved ones to review. A second worker must not independently approve the same action through a non-atomic local check.
Independent transfer problem
Two workers both read approved before either writes executing. Give the coordination property needed to prevent both from owning the action.
Compare the transfer solution
Use an atomic compare-and-set or transactional claim that lets only one worker move that operation from approved to executing. The loser must not proceed. This prevents a local race but does not by itself solve the external-success/local-crash window; the external reconciliation policy is still needed.
Learning objectives
- Explain and trace the mechanisms in tool use, state machines and idempotent workflows.
- Apply the method to the worked example and changed-condition exercise.
- Identify assumptions, failure cases and the evidence needed to justify a result.
Study the mechanism
An agentic workflow chooses actions in a changing environment. That flexibility increases the importance of explicit state, limited permissions and recovery behavior. A tool description is not an access-control system. The application must verify the caller, constrain arguments and authorize every consequential action.
Retries are unavoidable when networks fail, but repeating an action may duplicate its effect. An idempotency key identifies a logical operation so repeated delivery can reuse or recognize the same result. The key must be stable across retries and scoped to the authorized action. It cannot be regenerated on every attempt. For persistent multi-worker systems, storing the key and state transition needs appropriate transactional or atomic coordination; a local set is only a teaching demonstration.
Separate proposal, approval and execution states. Approval should attach to the exact action, target and content, with expiry or reapproval when material fields change. A model suggesting a different recipient does not inherit approval for the original recipient. Record enough state to reconcile an ambiguous timeout: the server may have executed an action even when the caller did not receive its response. Never treat a timeout as proof that nothing happened.
Worked example
def dry_run_execute(action, approved, completed):
key = action["operation_id"]
if key in completed:
return "already_recorded"
if action != approved:
return "approval_required"
completed.add(key)
return "simulated_only"
action = {"operation_id":"op-1", "recipient":"fictional@example.invalid", "body":"Draft"}
seen = set()
assert dry_run_execute(action, dict(action), seen) == "simulated_only"
assert dry_run_execute(action, dict(action), seen) == "already_recorded"The simulation performs no network action. It compares the proposed dictionary with the approved dictionary and tracks a stable operation ID. The local set is lost on restart and is not safe for concurrent workers. A production action needs durable state and permission checks; copying this toy tracker into a multi-user service would not provide reliable exactly-once behavior.
Check your understanding
What should a timeout after sending an action imply?
- The outcome may be unknown and needs reconciliation
- The action definitely did not happen
- The operation should receive a new ID immediately
Answer and reasoning for every option
Correct: The outcome may be unknown and needs reconciliation The response can be lost after the effect occurred.
Reconsider: The action definitely did not happen Network failure does not establish server state.
Reconsider: The operation should receive a new ID immediately A new ID can defeat duplicate protection and repeat the effect.
Transfer laboratory: Approval binding and a changed recipient
An approved draft names recipient A. A later model call changes only the recipient to B while retaining the same operation ID. Is the prior approval sufficient?
Work through the full solution
No. Approval must bind to the exact authorized action and material fields, including recipient and content. The changed proposal returns to approval. A stable operation ID identifies a logical operation but cannot grant permission for changed effects. Persist the approved payload or its canonical digest and verify it before execution; reconcile unknown prior outcomes before retrying.
Evidence of understanding
Reject the changed target and separate deduplication from authorization.
Complete on-site teaching readings
These are full attributed source sections, not previews. Read them alongside the original Academy explanation and code.
- sqlite3 — DB-API 2.0 interface for SQLite databases · Python Software Foundation and Python documentation contributors
- queue — A synchronized queue class · Python Software Foundation and Python documentation contributors
- concurrent.futures — Launching parallel tasks · Python Software Foundation and Python documentation contributors
- enum — Support for enumerations · Python Software Foundation and Python documentation contributors
- HTTP request methods · Mozilla Contributors
- HTTP response status codes · Mozilla Contributors
- LLM06:2025 Excessive Agency · OWASP GenAI Security Project contributors
Open the complete practice sequence and cumulative assessment →