AI

An Implementation Guide to Design Intelligent Parallel Workflows in Parsl for Multi-Tool AI Agent Execution

In this tutorial, we implement the AI’s agent pipeline using ParssTake advantage of the parallel implementation capabilities to run multiple mathematical tasks such as independent Python applications. We create a local Threadpoixecutor for synchronization, identify specialized tools such as Fibonacci account, main count, keyword extraction, simulator API calls, and coordinate them through a lightweight scheme that planns the user’s goal for the task of invitations. Outputs are assembled from all tasks and passed through a model to generate embracing text to produce a coherent reading summary from man. verify Full codes here.

!pip install -q parsl transformers accelerate


import math, json, time, random
from typing import List, Dict, Any
import parsl
from parsl.config import Config
from parsl.executors import ThreadPoolExecutor
from parsl import python_app


parsl.load(Config(executors=[ThreadPoolExecutor(label="local", max_threads=8)]))

We start installing the required libraries and importing all the units needed for our workflow. Then we form Parss with local Threadpoixecutor to operate the tasks simultaneously and download this configuration so that we can carry out our Python applications in parallel. verify Full codes here.

@python_app
def calc_fibonacci(n: int) -> Dict[str, Any]:
   def fib(k):
       a, b = 0, 1
       for _ in range(k): a, b = b, a + b
       return a
   t0 = time.time(); val = fib(n); dt = time.time() - t0
   return {"task": "fibonacci", "n": n, "value": val, "secs": round(dt, 4)}


@python_app
def extract_keywords(text: str, k: int = 8) -> Dict[str, Any]:
   import re, collections
   words = [w.lower() for w in re.findall(r"[a-zA-Z][a-zA-Z0-9\-]+", text)]
   stop = set("the a an and or to of is are was were be been in on for with as by from at this that it its if then else not no".split())
   cand = [w for w in words if w not in stop and len(w) > 3]
   freq = collections.Counter(cand)
   scored = sorted(freq.items(), key=lambda x: (x[1], len(x[0])), reverse=True)[:k]
   return {"task":"keywords","keywords":[w for w,_ in scored]}


@python_app
def simulate_tool(name: str, payload: Dict[str, Any]) -> Dict[str, Any]:
   time.sleep(0.3 + random.random()*0.5)
   return {"task": name, "payload": payload, "status": "ok", "timestamp": time.time()}

We define four functions Parslphethon_App that operate asynchronically as part of our agent’s work. We create a Fibonacci calculator, a specific routine, a keyword extract for text processing, and a simulator that simulates external API calls with random delay. These standard applications allow us to make various accounts in parallel, and to form building blocks for our multi -tool artificial intelligence agent. verify Full codes here.

def tiny_llm_summary(bullets: List[str]) -> str:
   from transformers import pipeline
   gen = pipeline("text-generation", model="sshleifer/tiny-gpt2")
   prompt = "Summarize these agent results clearly:\n- " + "\n- ".join(bullets) + "\nConclusion:"
   out = gen(prompt, max_length=160, do_sample=False)[0]["generated_text"]
   return out.split("Conclusion:", 1)[-1].strip()

We perform the Tiny_lm_summary function that uses the face-to-embedded pipeline with a lightweight SSHLEIFer/Tiny-GPT2 model to generate brief summaries of the results of our agent. It establishes the outputs of the task collected as a bullet, and leads to a “conclusion:” a braid, and only extracts the final conclusion that was established for a clean, readable summary. verify Full codes here.

def plan(user_goal: str) -> List[Dict[str, Any]]:
   intents = []
   if "fibonacci" in user_goal.lower():
       intents.append({"tool":"calc_fibonacci", "args":{"n":35}})
   if "primes" in user_goal.lower():
       intents.append({"tool":"count_primes", "args":{"limit":100_000}})
   intents += [
       {"tool":"simulate_tool", "args":{"name":"vector_db_search","payload":{"q":user_goal}}},
       {"tool":"simulate_tool", "args":{"name":"metrics_fetch","payload":{"kpi":"latency_ms"}}},
       {"tool":"extract_keywords", "args":{"text":user_goal}}
   ]
   return intents

We define the plan function to determine the user’s goal in an organized list of tools. It checks the goal text for the main words such as “Fibonacci” or “Primary Numbers” to create specific mathematical tasks, then adds virtual procedures such as API simulations, retrieving standards, extracting keywords, and forming the implementation scheme for our AI. verify Full codes here.

def run_agent(user_goal: str) -> Dict[str, Any]:
   tasks = plan(user_goal)
   futures = []
   for t in tasks:
       if t["tool"]=="calc_fibonacci": futures.append(calc_fibonacci(**t["args"]))
       elif t["tool"]=="count_primes": futures.append(count_primes(**t["args"]))
       elif t["tool"]=="extract_keywords": futures.append(extract_keywords(**t["args"]))
       elif t["tool"]=="simulate_tool": futures.append(simulate_tool(**t["args"]))
   raw = [f.result() for f in futures]


   bullets = []
   for r in raw:
       if r["task"]=="fibonacci":
           bullets.append(f"Fibonacci({r['n']}) = {r['value']} computed in {r['secs']}s.")
       elif r["task"]=="count_primes":
           bullets.append(f"{r['count']} primes found ≤ {r['limit']}.")
       elif r["task"]=="keywords":
           bullets.append("Top keywords: " + ", ".join(r["keywords"]))
       else:
           bullets.append(f"Tool {r['task']} responded with status={r['status']}.")


   narrative = tiny_llm_summary(bullets)
   return {"goal": user_goal, "bullets": bullets, "summary": narrative, "raw": raw}

In the run_age_Gent function, we carry out the full agent’s workflow by creating an important plan from the user’s goal, then sending each tool as the Parss application to run it in parallel. Once all future contracts are completed, we convert their results into clear bullet points and feed them with a tiny_lm_summary for us to create a brief narration. The function returns an organized dictionary that contains the original goal, detailed lead points, a created LLM summary, and raw tool outputs. verify Full codes here.

if __name__ == "__main__":
   goal = ("Analyze fibonacci(35) performance, count primes under 100k, "
           "and prepare a concise executive summary highlighting insights for planning.")
   result = run_agent(goal)
   print("\n=== Agent Bullets ===")
   for b in result["bullets"]: print("•", b)
   print("\n=== LLM Summary ===\n", result["summary"])
   print("\n=== Raw JSON ===\n", json.dumps(result["raw"], indent=2)[:800], "...")

In the main implementation bloc, we define the target of the sample that combines digital arithmetic, the main count, and brief generation. We played the agent on this goal, printing the created bullets, displaying the made LLM summary, and previewing the raw JSON output to check the results of human reading and structural.

In conclusion, this implementation shows how the simultaneous application model for Parss can organize a variety of work burdens in a parallel way, allowing the AI factor to combine numerical analysis, text processing, and simulator external services in a unified pipeline. By merging a small LLM in the final stage, we convert structurally structured results into a natural language, and explains how parallel models and artificial intelligence models can be combined to create response and extension factors suitable for tasks in actual or widely.


verify Full codes here. Do not hesitate to check our GitHub page for lessons, symbols and notebooks. Also, do not hesitate to follow us twitter And do not forget to join 100K+ ML Subreddit And subscribe to Our newsletter.


Asif Razzaq is the CEO of Marktechpost Media Inc .. As a pioneer and vision engineer, ASIF is committed to harnessing the potential of artificial intelligence for social goodness. His last endeavor is to launch the artificial intelligence platform, Marktechpost, which highlights its in -depth coverage of machine learning and deep learning news, which is technically sound and can be easily understood by a wide audience. The platform is proud of more than 2 million monthly views, which shows its popularity among the masses.

Don’t miss more hot News like this! Click here to discover the latest in AI news!

2025-08-15 18:27:00

Related Articles

Back to top button