home
diamond Go Premium
Data Engineering Path  ·  Data & AI

Module 5 Hands-On Coding Lab & Practical Scenarios

Master the practical mechanics of stateful agent systems: implementing function calling dispatchers, cyclic LangGraph state machines, and autonomous self-correction loops.


🛠️ Challenge 1: The Function Calling Dispatcher

Scenario

An LLM emits tool call requests in JSON format. Build a safe dispatcher that validates argument types against a schema and executes the corresponding Python function.

🔍 Click to view Solution & Architecture Explanation
import json
from typing import Dict, Any, Callable

class SafeToolDispatcher:
    def __init__(self):
        self.registry: Dict[str, Callable] = {}

    def register(self, name: str, func: Callable):
        self.registry[name] = func

    def execute_tool_call(self, tool_name: str, arguments: Dict[str, Any]) -> Dict[str, Any]:
        if tool_name not in self.registry:
            return {"status": "ERROR", "error": f"Tool '{tool_name}' is not registered."}
        try:
            result = self.registry[tool_name](**arguments)
            return {"status": "SUCCESS", "output": result}
        except TypeError as e:
            return {"status": "ERROR", "error": f"Invalid arguments: {e}"}

# Test functions
dispatcher = SafeToolDispatcher()
dispatcher.register("inspect_s3_bucket", lambda bucket, prefix="": f"Objects in s3://{bucket}/{prefix}: ['data_01.parquet']")

res = dispatcher.execute_tool_call("inspect_s3_bucket", {"bucket": "analytics-prod", "prefix": "raw/"})
print("Tool Execution Result:", res)

🛠️ Challenge 2: A Cyclic LangGraph-Style State Machine

Scenario

Model an iterative loop where an agent attempts a task, evaluates if the result meets a quality threshold, and loops back if needed (up to 3 iterations).

🔍 Click to view Solution & Architecture Explanation
from typing import Dict, Any

class StateMachineAgent:
    def __init__(self, max_iterations: int = 3):
        self.max_iterations = max_iterations

    def run(self, initial_query: str) -> Dict[str, Any]:
        state = {
            "query": initial_query,
            "iteration": 0,
            "quality_score": 0.0,
            "status": "IN_PROGRESS"
        }

        while state["status"] == "IN_PROGRESS":
            state["iteration"] += 1
            print(f"[Iteration {state['iteration']}] Generating & evaluating response...")

            # Simulated quality improvement over iterations
            state["quality_score"] += 0.35

            if state["quality_score"] >= 0.8:
                state["status"] = "COMPLETED"
                state["final_answer"] = f"High-confidence verified answer (Score: {state['quality_score']:.2f})"
            elif state["iteration"] >= self.max_iterations:
                state["status"] = "MAX_RETRIES_REACHED"
                state["final_answer"] = "Best-effort answer returned."

        return state

agent = StateMachineAgent(max_iterations=3)
result = agent.run("Optimize multi-table join")
print("
Final State Machine Result:", result)
Find this content helpful? ☕ Buy me a coffee

Entity Details

Create New Item

help

Submit Technical Query

Have a question or run into an issue? Describe it below, upload an optional screenshot, and our engineering team will answer it!

image Attach image (optional)

Submit Feedback

build Free Developer Utility Free Tool
gavel

Privacy & Legal Disclaimer

1. Client-Side Browser Processing

All utility tools on DeepEngineerHub (including Image to PDF, Text Formatters, JSON Converters, and Encryptors) execute 100% locally within your client browser using WebAssembly and JavaScript. No uploaded images, text, or documents are transmitted, collected, or stored on remote servers.

2. Limitation of Liability ("As-Is" Provision)

Tools and services are provided free of charge for convenience and educational purposes "as-is" without warranties of any kind. DeepEngineerHub shall not be held liable for any data loss, formatting inconsistencies, or indirect damages resulting from tool usage.

3. Open Source & Third-Party Software

Certain utilities utilize open-source client libraries (such as jsPDF, Mermaid.js, Pyodide) licensed under MIT, Apache, or BSD open licenses. All intellectual property remains with their respective copyright holders.