Close Menu
    Facebook X (Twitter) Instagram
    Articles Stock
    • Home
    • Technology
    • AI
    • Pages
      • About us
      • Contact us
      • Disclaimer For Articles Stock
      • Privacy Policy
      • Terms and Conditions
    Facebook X (Twitter) Instagram
    Articles Stock
    AI

    A Coding Implementation to Construct a Hierarchical Planner AI Agent Utilizing Open-Supply LLMs with Device Execution and Structured Multi-Agent Reasoning

    Naveed AhmadBy Naveed Ahmad28/02/2026Updated:28/02/2026No Comments2 Mins Read
    blog banner23 70


    def executor_agent(step: Dict[str, Any], context: Dict[str, Any]) -> StepResult:
       step_id = int(step.get("id", 0))
       title = step.get("title", f"Step {step_id}")
       device = step.get("device", "llm")
    
    
       ctx_compact = {
           "purpose": context.get("purpose"),
           "assumptions": context.get("assumptions", []),
           "prior_results": [
               {"step_id": r.step_id, "title": r.title, "tool": r.tool, "output": r.output[:1500]}
               for r in context.get("outcomes", [])
           ],
       }
    
    
       if device == "python":
           code = llm_chat(
               EXECUTOR_SYSTEM,
               person=(
                   f"Step:n{json.dumps(step, indent=2)}nn"
                   f"Context:n{json.dumps(ctx_compact, indent=2)}nn"
                   f"Write Python code that completes the step. Output ONLY code."
               ),
               max_new_tokens=700,
               temperature=0.2,
           )
           py = run_python(code)
           out = []
           out.append("PYTHON_CODE:n" + code)
           out.append("nEXECUTION_OK: " + str(py["ok"]))
           if py["stdout"]:
               out.append("nSTDOUT:n" + py["stdout"])
           if py["error"]:
               out.append("nERROR:n" + py["error"])
           return StepResult(step_id=step_id, title=title, device=device, output="n".be a part of(out))
    
    
       result_text = llm_chat(
           EXECUTOR_SYSTEM,
           person=(
               f"Step:n{json.dumps(step, indent=2)}nn"
               f"Context:n{json.dumps(ctx_compact, indent=2)}nn"
               f"Return the step outcome."
           ),
           max_new_tokens=700,
           temperature=0.3,
       )
       return StepResult(step_id=step_id, title=title, device=device, output=result_text)
    
    
    
    
    def aggregator_agent(activity: str, plan: Dict[str, Any], outcomes: Listing[StepResult]) -> str:
       payload = {
           "activity": activity,
           "plan": plan,
           "outcomes": [{"step_id": r.step_id, "title": r.title, "tool": r.tool, "output": r.output[:2500]} for r in outcomes],
       }
       return llm_chat(
           AGGREGATOR_SYSTEM,
           person=f"Mix every thing into the ultimate reply.nnINPUT:n{json.dumps(payload, indent=2)}",
           max_new_tokens=900,
           temperature=0.2,
       )
    
    
    
    
    def run_hierarchical_agent(activity: str, verbose: bool = True) -> Dict[str, Any]:
       plan = planner_agent(activity)
    
    
       if verbose:
           print("n====================")
           print("PLAN (from Planner)")
           print("====================")
           print(json.dumps(plan, indent=2))
    
    
       context = {
           "purpose": plan.get("purpose", activity),
           "assumptions": plan.get("assumptions", []),
           "outcomes": [],
       }
    
    
       outcomes: Listing[StepResult] = []
       for step in plan.get("steps", []):
           res = executor_agent(step, context)
           outcomes.append(res)
           context["results"].append(res)
    
    
           if verbose:
               print("n--------------------")
               print(f"STEP {res.step_id}: {res.title}  [tool={res.tool}]")
               print("--------------------")
               print(res.output)
    
    
       remaining = aggregator_agent(activity, plan, outcomes)
       if verbose:
           print("n====================")
           print("FINAL (from Aggregator)")
           print("====================")
           print(remaining)
    
    
       return {"activity": activity, "plan": plan, "outcomes": outcomes, "remaining": remaining}
    
    
    
    
    demo_task = """
    Create a sensible guidelines to launch a small multi-agent system in Python for coordinating logistics:
    - One planner agent that decomposes duties
    - Two executor brokers (routing + stock)
    - A easy reminiscence retailer for previous selections
    Hold it light-weight and runnable in Colab.
    """
    
    
    _ = run_hierarchical_agent(demo_task, verbose=True)
    
    
    print("nnType your personal activity (or press Enter to skip):")
    user_task = enter().strip()
    if user_task:
       _ = run_hierarchical_agent(user_task, verbose=True)



    Source link

    Naveed Ahmad

    Related Posts

    India disrupts entry to widespread developer platform Supabase with blocking order

    28/02/2026

    Pentagon strikes to designate Anthropic as a supply-chain danger

    28/02/2026

    The best way to Construct Interactive Geospatial Dashboards Utilizing Folium with Heatmaps, Choropleths, Time Animation, Marker Clustering, and Superior Interactive Plugins

    28/02/2026
    Leave A Reply Cancel Reply

    Categories
    • AI
    Recent Comments
      Facebook X (Twitter) Instagram Pinterest
      © 2026 ThemeSphere. Designed by ThemeSphere.

      Type above and press Enter to search. Press Esc to cancel.