• About Us
  • Disclaimer
  • Contact Us
  • Privacy Policy
Tuesday, April 14, 2026
mGrowTech
No Result
View All Result
  • Technology And Software
    • Account Based Marketing
    • Channel Marketing
    • Marketing Automation
      • Al, Analytics and Automation
      • Ad Management
  • Digital Marketing
    • Social Media Management
    • Google Marketing
  • Direct Marketing
    • Brand Management
    • Marketing Attribution and Consulting
  • Mobile Marketing
  • Event Management
  • PR Solutions
  • Technology And Software
    • Account Based Marketing
    • Channel Marketing
    • Marketing Automation
      • Al, Analytics and Automation
      • Ad Management
  • Digital Marketing
    • Social Media Management
    • Google Marketing
  • Direct Marketing
    • Brand Management
    • Marketing Attribution and Consulting
  • Mobile Marketing
  • Event Management
  • PR Solutions
No Result
View All Result
mGrowTech
No Result
View All Result
Home Al, Analytics and Automation

A Coding Implementation to Build a Hierarchical Planner AI Agent Using Open-Source LLMs with Tool Execution and Structured Multi-Agent Reasoning

Josh by Josh
February 28, 2026
in Al, Analytics and Automation
0
A Coding Implementation to Build a Hierarchical Planner AI Agent Using Open-Source LLMs with Tool Execution and Structured Multi-Agent Reasoning


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}")
   tool = step.get("tool", "llm")


   ctx_compact = {
       "goal": context.get("goal"),
       "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("results", [])
       ],
   }


   if tool == "python":
       code = llm_chat(
           EXECUTOR_SYSTEM,
           user=(
               f"Step:\n{json.dumps(step, indent=2)}\n\n"
               f"Context:\n{json.dumps(ctx_compact, indent=2)}\n\n"
               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, tool=tool, output="\n".join(out))


   result_text = llm_chat(
       EXECUTOR_SYSTEM,
       user=(
           f"Step:\n{json.dumps(step, indent=2)}\n\n"
           f"Context:\n{json.dumps(ctx_compact, indent=2)}\n\n"
           f"Return the step result."
       ),
       max_new_tokens=700,
       temperature=0.3,
   )
   return StepResult(step_id=step_id, title=title, tool=tool, output=result_text)




def aggregator_agent(task: str, plan: Dict[str, Any], results: List[StepResult]) -> str:
   payload = {
       "task": task,
       "plan": plan,
       "results": [{"step_id": r.step_id, "title": r.title, "tool": r.tool, "output": r.output[:2500]} for r in results],
   }
   return llm_chat(
       AGGREGATOR_SYSTEM,
       user=f"Combine everything into the final answer.\n\nINPUT:\n{json.dumps(payload, indent=2)}",
       max_new_tokens=900,
       temperature=0.2,
   )




def run_hierarchical_agent(task: str, verbose: bool = True) -> Dict[str, Any]:
   plan = planner_agent(task)


   if verbose:
       print("\n====================")
       print("PLAN (from Planner)")
       print("====================")
       print(json.dumps(plan, indent=2))


   context = {
       "goal": plan.get("goal", task),
       "assumptions": plan.get("assumptions", []),
       "results": [],
   }


   results: List[StepResult] = []
   for step in plan.get("steps", []):
       res = executor_agent(step, context)
       results.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)


   final = aggregator_agent(task, plan, results)
   if verbose:
       print("\n====================")
       print("FINAL (from Aggregator)")
       print("====================")
       print(final)


   return {"task": task, "plan": plan, "results": results, "final": final}




demo_task = """
Create a practical checklist to launch a small multi-agent system in Python for coordinating logistics:
- One planner agent that decomposes tasks
- Two executor agents (routing + inventory)
- A simple memory store for past decisions
Keep it lightweight and runnable in Colab.
"""


_ = run_hierarchical_agent(demo_task, verbose=True)


print("\n\nType your own task (or press Enter to skip):")
user_task = input().strip()
if user_task:
   _ = run_hierarchical_agent(user_task, verbose=True)



Source_link

READ ALSO

TinyFish Launches Full Web Infrastructure Platform for AI Agents — Search, Fetch, Browser, and Agent Under One API Key

How to Implement Tool Calling with Gemma 4 and Python

Related Posts

TinyFish Launches Full Web Infrastructure Platform for AI Agents — Search, Fetch, Browser, and Agent Under One API Key
Al, Analytics and Automation

TinyFish Launches Full Web Infrastructure Platform for AI Agents — Search, Fetch, Browser, and Agent Under One API Key

April 14, 2026
How to Implement Tool Calling with Gemma 4 and Python
Al, Analytics and Automation

How to Implement Tool Calling with Gemma 4 and Python

April 14, 2026
Multilingual Audio Datasets for Speech Recognition AI
Al, Analytics and Automation

Multilingual Audio Datasets for Speech Recognition AI

April 14, 2026
“Too Smart for Comfort?” Regulators Battle to Control a New Type of AI Threat
Al, Analytics and Automation

“Too Smart for Comfort?” Regulators Battle to Control a New Type of AI Threat

April 14, 2026
Google AI Research Proposes Vantage: An LLM-Based Protocol for Measuring Collaboration, Creativity, and Critical Thinking
Al, Analytics and Automation

Google AI Research Proposes Vantage: An LLM-Based Protocol for Measuring Collaboration, Creativity, and Critical Thinking

April 14, 2026
An Implementation Guide to Building a DuckDB-Python Analytics Pipeline with SQL, DataFrames, Parquet, UDFs, and Performance Profiling
Al, Analytics and Automation

An Implementation Guide to Building a DuckDB-Python Analytics Pipeline with SQL, DataFrames, Parquet, UDFs, and Performance Profiling

April 13, 2026
Next Post
Trump orders federal agencies to drop Anthropic services amid Pentagon feud

Trump orders federal agencies to drop Anthropic services amid Pentagon feud

POPULAR NEWS

Trump ends trade talks with Canada over a digital services tax

Trump ends trade talks with Canada over a digital services tax

June 28, 2025
Communication Effectiveness Skills For Business Leaders

Communication Effectiveness Skills For Business Leaders

June 10, 2025
15 Trending Songs on TikTok in 2025 (+ How to Use Them)

15 Trending Songs on TikTok in 2025 (+ How to Use Them)

June 18, 2025
App Development Cost in Singapore: Pricing Breakdown & Insights

App Development Cost in Singapore: Pricing Breakdown & Insights

June 22, 2025
Comparing the Top 7 Large Language Models LLMs/Systems for Coding in 2025

Comparing the Top 7 Large Language Models LLMs/Systems for Coding in 2025

November 4, 2025

EDITOR'S PICK

Stop Obsessing Over General Remarketing

Stop Obsessing Over General Remarketing

September 19, 2025
Beyond the Spool: A Social Media Plan for Industrial Sewing Products

Beyond the Spool: A Social Media Plan for Industrial Sewing Products

September 1, 2025
LayerNorm and RMS Norm in Transformer Models

LayerNorm and RMS Norm in Transformer Models

July 23, 2025
Contactless, Smart & Scalable Solutions

Contactless, Smart & Scalable Solutions

September 15, 2025

About

We bring you the best Premium WordPress Themes that perfect for news, magazine, personal blog, etc. Check our landing page for details.

Follow us

Categories

  • Account Based Marketing
  • Ad Management
  • Al, Analytics and Automation
  • Brand Management
  • Channel Marketing
  • Digital Marketing
  • Direct Marketing
  • Event Management
  • Google Marketing
  • Marketing Attribution and Consulting
  • Marketing Automation
  • Mobile Marketing
  • PR Solutions
  • Social Media Management
  • Technology And Software
  • Uncategorized

Recent Posts

  • See Which Emails Actually Make You Money
  • Creating a ‘shared understanding’ around change comms
  • Someone planted backdoors in dozens of WordPress plug-ins used in thousands of websites
  • TinyFish Launches Full Web Infrastructure Platform for AI Agents — Search, Fetch, Browser, and Agent Under One API Key
  • About Us
  • Disclaimer
  • Contact Us
  • Privacy Policy
No Result
View All Result
  • Technology And Software
    • Account Based Marketing
    • Channel Marketing
    • Marketing Automation
      • Al, Analytics and Automation
      • Ad Management
  • Digital Marketing
    • Social Media Management
    • Google Marketing
  • Direct Marketing
    • Brand Management
    • Marketing Attribution and Consulting
  • Mobile Marketing
  • Event Management
  • PR Solutions