惯性聚合 高效追踪和阅读你感兴趣的博客、新闻、科技资讯
阅读原文 在惯性聚合中打开

推荐订阅源

爱范儿
爱范儿
WordPress大学
WordPress大学
博客园 - 【当耐特】
The Cloudflare Blog
B
Blog
Last Week in AI
Last Week in AI
小众软件
小众软件
量子位
S
SegmentFault 最新的问题
V
Visual Studio Blog
博客园 - 叶小钗
美团技术团队
阮一峰的网络日志
阮一峰的网络日志
Hugging Face - Blog
Hugging Face - Blog
钛媒体:引领未来商业与生活新知
钛媒体:引领未来商业与生活新知
宝玉的分享
宝玉的分享
A
About on SuperTechFans
雷峰网
雷峰网
J
Java Code Geeks
Microsoft Azure Blog
Microsoft Azure Blog
腾讯CDC
MongoDB | Blog
MongoDB | Blog
酷 壳 – CoolShell
酷 壳 – CoolShell
Martin Fowler
Martin Fowler

DEV Community

Authentication Security Deep Dive: From Brute Force to Salted Hashing (With Java Examples) Why AI Systems Don’t Fail — They Drift Spilling beans for how i learn for exam😁"Reinforcement Learning Cheat Sheet" I Replaced Chrome with Safari for AI Browser Automation. Here's What Broke (and What Finally Worked) How Python Borrows Other People's Work The $40 Architecture: Processing 1 Billion API Requests with 99.99% Uptime Vibe Coding: A Workflow Guide (From Zero to SaaS) Most webhook security guides protect the wrong side. The scary part is delivery. Headless CMS for TanStack Start: Build a Blog with Cosmic EU Age Verification App "Hacked in 2 Minutes" — What Actually Happened Comfy Cloud’s delete function does not actually remove files Running AI Models on GPU Cloud Servers: A Beginner Guide Event-driven media intelligence with AWS Step Functions and Bedrock I scored 500 AI prompts across 8 quality dimensions — here's what broke How to Call Google Gemini API from Next.js (Free Tier, No Backend Needed) The Portal Protocol: Reclaiming Human Connection in the Age of AI How to Fix Your Team's Scattered Knowledge Problem With a Self-Hosted Forum Intro to tc Cloud Functors: A Graph-First Mental Model for the Modern Cloud Designing Multi-Tenant Backends With Both Ownership and Team Access I Built a Neumorphic CSS Library with 77+ Components — Here's What I Learned PostgreSQL Performance Optimization: Why Connection Pooling Is Critical at Scale Cómo construí un SaaS multi-rubro para gestionar expensas en Argentina con FastAPI + Vue 3 🚀 I Built an Ethical Hacking Scanner Tool – Open Source Project I Replaced /usage and /context in Claude Code With a Single Statusline A Pythonic Way to Handle Emails (IMAP/SMTP) with Auto-Discovery and AI-Ready Design I Collected 8.9 Million Polymarket Price Points — Here's What I Found About How Markets Really Move EcoTrack AI — Carbon Footprint Tracker & Dashboard Everyone's Using AI. No One Agrees How. 5 self-hosted ebook managers worth trying in 2026 Building Your First AI Agent with LangChain: From Chatbot to Autonomous Assistant
AIchain Pool: Parallel Calls Instead of Sequential
YAIT · 2026-06-14 · via DEV Community

You have 50 documents and you're running them through an LLM in a loop. The first one finishes at the 2-second mark. The fiftieth finishes at the 100-second mark — not because it's harder, but because it waited in line behind the other 49. Pool runs all 50 at the same time.

The Problem With Loops

Every developer who works with LLMs writes this code eventually:

import os
from yait_aichain.models import Model
from yait_aichain.skills import Skill

skill = Skill(
    model=Model("claude-sonnet-4-6", api_key=os.getenv("ANTHROPIC_API_KEY")),
    input={"messages": [{"role": "user", "parts": [
        "Summarise in two sentences:\n\n{text}"
    ]}]},
)

documents = [{"text": f"Document {i} content..."} for i in range(50)]

results = []
for doc in documents:
    result = skill.run(doc)
    results.append(result)

It works. It's readable. And it's painfully slow.

Each LLM call takes roughly 2 seconds. Multiply that by 50 documents and you're staring at your terminal for almost two minutes. The calls are completely independent — document 37 doesn't need the result of document 12. Yet document 37 sits idle, waiting its turn. That's a scheduling problem, not a computation problem.

I ran into this directly while building a task that pulled N files or links and produced a consolidated report. The sequential version was logically fine but just hemorrhaged time. I needed to fire everything at once without rewriting the Skill logic — no new prompt templates, no restructured code, just a different execution model. That's what Pool is.

Pool: Parallel Map for LLM Calls

Pool takes one Skill (or Chain) and a list of inputs, then launches all of them concurrently. Think of it as Array.map() where every element runs in parallel against an LLM.

import os
from yait_aichain.models import Model
from yait_aichain.skills import Skill
from yait_aichain.pool import Pool, DONE, FAILED

skill = Skill(
    model=Model("claude-sonnet-4-6", api_key=os.getenv("ANTHROPIC_API_KEY")),
    input={"messages": [{"role": "user", "parts": [
        "Summarise in two sentences:\n\n{text}"
    ]}]},
)

items = [
    {"text": "Artificial intelligence is transforming..."},
    {"text": "Quantum computing promises..."},
    {"text": "Climate change is accelerating..."},
    {"text": "Blockchain technology enables..."},
    {"text": "Gene editing with CRISPR..."},
]

pool = Pool(skill, items=items, max_flows=5)
results = pool.run()

for result in results:
    print(result)

s = pool.status
print(f"done={s[DONE]}  failed={s[FAILED]}")

Three things worth noticing:

  1. The Skill didn't change. Same model, same prompt template, same {text} placeholder. Pool wraps existing logic — it doesn't demand new logic.
  2. pool.run() returns a list in the same order as the input. Item 0 in, result 0 out. No need to track which response belongs to which document.
  3. Status tracking is built in. pool.status gives you a dict with DONE and FAILED counts, so you know exactly what succeeded and what didn't.

The math is straightforward. Five items averaging ~2 seconds each, running concurrently: wall-clock time drops from ~10 seconds to ~2 seconds. The overhead is network jitter and provider-side queuing, not sequential waiting. Scale to 50 items and the gap gets embarrassing. Exact numbers depend on your provider and network conditions, but the shape of the improvement is consistent — you pay for one round-trip, not N.

Controlling Concurrency With max_flows

Running everything at once sounds great until your API provider starts returning 429 errors.

LLM providers enforce rate limits, and those limits vary by model, tier, and account type. Blasting 200 concurrent requests is a reliable way to get throttled regardless of your tier. Check your provider's current documentation before tuning this number — don't just guess.

max_flows is your throttle. It sets the maximum number of calls in flight at any given moment:

pool = Pool(skill, items=documents, max_flows=10)

With max_flows=10, Pool processes 50 documents in waves of 10 concurrent calls. Still dramatically faster than sequential, but it keeps you within reasonable rate-limit bounds. Dial it up or down depending on what your provider will tolerate.

Failures Don't Sink the Ship

Batch jobs have a classic failure mode: item 23 out of 50 throws an error and the whole run aborts. You fix the issue, restart from scratch, and wait through items 1–22 again. Deeply annoying.

Pool handles this differently. Each item gets its own outcome — DONE or FAILED. One failed call doesn't stop the rest. After pool.run() completes, check pool.status for the breakdown:

s = pool.status
print(f"done={s[DONE]}  failed={s[FAILED]}")
# done=48  failed=2

You get 48 good results. You know exactly which 2 failed. Reprocess those two — not the entire batch.

Pool + Chain: Multi-Step Pipelines in Parallel

Pool isn't limited to a single Skill. It accepts a Chain as its runner, which means multi-step workflows parallelize just as easily.

Here's a real example: fetch a web page, convert it to Markdown, then summarize it — all in parallel across multiple URLs.

import os
from yait_aichain.models import Model
from yait_aichain.skills import Skill
from yait_aichain.chain import Chain
from yait_aichain.pool import Pool, DONE, FAILED
from yait_aichain.tools import convertToMD

fetch = convertToMD()

summarise = Skill(
    model=Model("claude-sonnet-4-6", api_key=os.getenv("ANTHROPIC_API_KEY")),
    input={"messages": [{"role": "user", "parts": [
        "Summarise in one sentence:\n\n{result}"
    ]}]},
)

# Each Chain step is a tuple of (runner, output_key, input_mapping).
# Here: fetch writes its output to "result", mapped from the item's "source" field.
# The summarise Skill then reads {result} from that output key.
per_item = Chain(steps=[
    (fetch, "result", {"input": "source"}),  # fetch page; store as "result"
    summarise,                                # summarise reads {result}
])

items = [
    {"source": "https://fr.lipsum.com"},
    {"source": "https://de.lipsum.com"},
    {"source": "https://es.lipsum.com"},
]

pool = Pool(per_item, items=items, max_flows=3)
results = pool.run()

for item, result in zip(items, results):
    print(f"[{item['source']}]\n{result}\n")

s = pool.status
print(f"done={s[DONE]}  failed={s[FAILED]}")

The Chain step tuple has three elements: the runner, the key under which its output is stored, and a mapping from that key to the next step's input field. So (fetch, "result", {"input": "source"}) means: run fetch using the item's source field as input, store the output under "result". The summarise Skill then receives {result} via its prompt template. Each URL goes through the full fetch-then-summarize pipeline independently, and Pool runs all three chains at once.

When Pool Changes the Math

Consider a weekly report pulling data from 200 sources — summarize each one, then combine. Sequential at ~2 seconds per call: roughly 400 seconds, nearly 7 minutes. With max_flows=20, you process those 200 items in 10 waves: roughly 20 seconds total. What used to need a scheduled overnight job now finishes while you're still looking at the screen.

The API surface is intentionally small:

  • Pool(runner, items, max_flows) — runner is a Skill or Chain; items is a list of dicts; max_flows caps concurrency
  • pool.run() — executes everything, returns results in input order
  • pool.status — returns {DONE: int, FAILED: int} after the run

No async/await boilerplate. No callbacks. Define your Skill, list your inputs, set a concurrency cap, and Pool handles the scheduling.