Swarm
LangChainOfficialPublished by LangChain
- Skill
- Tool integration
- Automation and integrations
- MIT
- Low risk
- Has scripts
AutoGineer summary
Written by AutoGineer from the skill’s own files, not by the author
Swarm provides a structured way to process large volumes of independent items in parallel. By organizing data into tables, it allows users to fan out instructions to subagents or direct model calls, aggregate results, and perform targeted retries on failed items. It is designed to handle batching automatically, making it efficient for tasks ranging from simple data classification to complex, multi-step agentic workflows.
What it does
- Creates tabular data structures from files, glob patterns, or custom record sets.
- Dispatches instructions across rows in parallel using subagents or direct model calls.
- Supports automatic and custom batching to optimize throughput and cost.
- Enables chaining of multiple passes to accumulate data on existing rows.
- Provides filtering capabilities for targeted processing and error recovery.
- Allows for local JavaScript-based aggregation of results after processing.
When to use it
- When you need to perform the same task on a large number of independent files or records.
- When you want to classify, extract, or label data using structured output.
- When a task requires complex, multi-step reasoning or tool usage across many items.
- When you need to retry only the failed portions of a large batch operation.
Advantages
- Significantly faster and cheaper for simple tasks by using direct model calls.
- Handles large datasets by managing batching and concurrency automatically.
- Maintains state across multiple passes, allowing for iterative data enrichment.
- Flexible source handling supports both file-based and custom record-based inputs.
Usage examples
- “Classify the sentiment of every JSON object in data.jsonl using the swarm skill.”
- The agent creates a table from the records, runs a classification instruction across all rows, and returns a summary of the sentiment distribution.
- “Use swarm to review all TypeScript files in src/ for security issues.”
- The agent identifies files via glob, dispatches a 'reviewer' subagent to each file, and compiles a table of findings.
Install
Download the skill as a ZIP:
https://mp-staging.autogineer.com/agent-skills/langchain-ai/swarm/downloadUnzip it into the cross-client skills folder of your project:
mkdir -p .agents/skills && unzip swarm.zip -d .agents/skills
Documentation by LangChain
Swarm
Process many independent items in parallel. create builds a table handle;
run fans work out across rows and merges results back. One row = one unit
of work — swarm handles batching automatically.
Flow
Create. Build a table from a source — files, a glob pattern, or pre-parsed records. One row per item. Returns a handle.
Run. Dispatch an
instructiontemplate across rows. Results are merged back into the table. Returns{ completed, failed, skipped, failures }.Aggregate. Use
rows()and plain JS to count, filter, or summarize. Do not spawn additional subagents for aggregation.Retry. Re-run with
filter: { column: "<col>", exists: false }to reprocess only failed rows.
Choosing a source
glob / filePaths — one file = one row. Use when each file is an
independent unit of work. Each row gets { id, file }; the subagent reads
the file itself via the {file} placeholder.
tasks — pass pre-built records directly. Use when the data lives inside
a file (JSONL, CSV, JSON array). Read and parse the file first inside
eval, then pass the records. One record = one row — do not group
multiple items into a single row.
For small files (under ~500 lines), parse and create in one block:
const { create } = await import("@/skills/swarm");
const raw = await tools.readFile({ file_path: "/data.jsonl" });
const records = raw.trim().split("\n").map(l => JSON.parse(l));
const table = await create({ tasks: records });
console.log(table);For large files, read in chunks of 500 lines to avoid truncation:
const { create } = await import("@/skills/swarm");
let records = [];
let offset = 0;
while (true) {
const chunk = await tools.readFile({ file_path: "/data.txt", offset, limit: 500 });
const lines = chunk.split("\n").filter(l => l.trim());
for (const l of lines) { records.push({ id: `r${records.length}`, text: l }); }
if (lines.length < 500) break;
offset += 500;
}
const table = await create({ tasks: records });
console.log(table);When the file is too large to parse and dispatch in one eval call, split
across two blocks. Only the block that calls swarm functions needs the import:
// eval 1: parse only — no swarm import needed
const raw = await tools.readFile({ file_path: "/data.jsonl" });
globalThis.records = raw.trim().split("\n").map(l => JSON.parse(l));
console.log(`Parsed ${globalThis.records.length} records`);// eval 2: create and dispatch
const { create, run } = await import("@/skills/swarm");
const table = await create({ tasks: globalThis.records });
const result = await run(table.id, {
instruction: "Classify {text}",
responseSchema: {
type: "object",
properties: { label: { type: "string" } },
required: ["label"],
},
});
console.log(result);Passing filePaths: ["/data.jsonl"] would produce a table with one row
pointing at the file — not one row per record inside it.
When to use subagentType
Omit subagentType for classification, extraction, labeling, and any task
where a single model call with structured output is sufficient. This is the
default and is significantly cheaper and faster — each dispatch is a direct
model call, no tools, no iteration.
Set subagentType when the task requires tools, file access, or multi-step
reasoning. Each dispatch runs a full agentic loop with the named subagent.
// Direct model call — classification, no tools needed
await run(table.id, {
instruction: "Classify {text}",
responseSchema: { type: "object", properties: { label: { type: "string" } }, required: ["label"] },
});
// Subagent — needs to read files and reason over multiple steps
await run(table.id, {
subagentType: "reviewer",
instruction: "Review {file} for security issues.",
responseSchema: { type: "object", properties: { finding: { type: "string" } }, required: ["finding"] },
});Instruction + context
instruction is a per-item template with {column} placeholders.
Placeholders are resolved by the framework — your column names appear in
prompts as references to the values listed alongside, never as raw
template syntax. Subagents do the work — do not process items yourself in
JS and write the results into rows.
context is free-form prose prepended to every subagent prompt. Use it for
shared background: domain terms, classification rules, examples, etc.
const { create, run } = await import("@/skills/swarm");
const table = await create({ glob: "src/**/*.ts" });
const r = await run(table.id, {
subagentType: "reviewer",
instruction: "Review {file} for security issues. List findings or write 'no issues'.",
context: "TypeScript Express backend using Prisma ORM. Focus on injection, auth bypass, path traversal.",
responseSchema: {
type: "object",
properties: { review: { type: "string" } },
required: ["review"],
},
});
console.log(r);
// → { completed: 45, failed: 2, skipped: 0, failures: [...] }Structured output
responseSchema is required. Schema properties become top-level columns on
each row and constrain what subagents can return.
const { run } = await import("@/skills/swarm");
await run(table.id, {
instruction: "Classify: {text}",
responseSchema: {
type: "object",
properties: {
sentiment: { type: "string", enum: ["positive", "negative", "neutral"] },
},
required: ["sentiment"],
},
});
// Row after: { id: "r1", text: "...", sentiment: "positive" }Batching
By default, swarm auto-batches to keep total dispatches under 10. For small tables (≤10 rows) each row gets its own subagent call. For larger tables, rows are grouped automatically.
Set batchSize to control grouping:
Number — uniform batch size for all rows.
batchSize: 1forces per-row dispatch;batchSize: 20groups in twenties.Function —
(row, rowCount) => number. Returns the desired batch size for each row. Rows with the same batch size are grouped together, then chunked. Allows mixed dispatch where some rows go solo and others batch.
const { create, run } = await import("@/skills/swarm");
const table = await create({ tasks: items });
// Complex items get individual attention; simple ones batch together
await run(table.id, {
instruction: "Analyze {text}",
responseSchema: {
type: "object",
properties: { analysis: { type: "string" } },
required: ["analysis"],
},
batchSize: (row) => (row.token_count > 1000 ? 1 : 10),
});Batch sizes are clamped to [1, 50] after evaluation.
Aggregation
After run(), use rows() and plain JS — no additional subagents needed.
const { rows } = await import("@/skills/swarm");
const data = await rows(table.id, { columns: ["sentiment"] });
const counts = {};
data.forEach(r => { counts[r.sentiment] = (counts[r.sentiment] || 0) + 1 });
console.log(counts);
// → { positive: 120, negative: 45, neutral: 35 }Chaining passes
run updates the table in place — chain calls to accumulate columns.
const { create, run } = await import("@/skills/swarm");
const table = await create({ tasks: interviews });
await run(table.id, {
instruction: "Classify sentiment of {text}",
responseSchema: {
type: "object",
properties: { sentiment: { type: "string", enum: ["positive", "negative", "neutral"] } },
required: ["sentiment"],
},
});
await run(table.id, {
filter: { column: "sentiment", equals: "negative" },
instruction: "Summarize why {text} had negative sentiment.",
responseSchema: {
type: "object",
properties: { summary: { type: "string" } },
required: ["summary"],
},
});Action-only tasks
When subagents perform actions (write a file, apply a fix) rather than return
data, use a simple schema with a status or marker field. The exists: false
filter still works for retries.
const { create, run } = await import("@/skills/swarm");
const fixedSchema = {
type: "object",
properties: { fixed: { type: "string" } },
required: ["fixed"],
};
const table = await create({ glob: "src/**/*.ts" });
await run(table.id, {
subagentType: "fixer",
instruction: "Add missing JSDoc to all exported functions in {file}.",
responseSchema: fixedSchema,
});
// retry any that failed
await run(table.id, {
subagentType: "fixer",
instruction: "Add missing JSDoc to all exported functions in {file}.",
responseSchema: fixedSchema,
filter: { column: "fixed", exists: false },
});Filtering
{ column: "status", equals: "done" }
{ column: "status", notEquals: "done" }
{ column: "category", in: ["A", "B"] }
{ column: "result", exists: false } // not yet processed
{ and: [filter1, filter2] }
{ or: [filter1, filter2] }Technical notes
Only import
@/skills/swarmin blocks where you call swarm functions. Data preparation (reading files, parsing, storing inglobalThis) does not need the import. Destructure only what you use:{ create },{ run },{ create, run }, etc.Console output is capped at ~5 KB. Never log raw file contents — log only counts and short samples.
readFileinsideevalreturns raw content — no line-number prefixes. Request at most 500 lines per call. For files with more than 500 lines, loop with incrementingoffset.When building a table from a file, read it inside
eval. Data read inside the sandbox stays there; it never enters the agent's context window.Never write to
.swarm/directly. Always usecreate().Everything the subagent needs must be in
instruction+context. Subagents can't see the agent's context.Row ids must be unique.
create()rejects sources that produce duplicate ids. Fortasks, that's a caller-side responsibility; forglob/filePaths, ids are auto-disambiguated by parent directory.Unknown columns fail fast. If
instructionreferences{foo}and no matched row providesfoo,run()throws before any subagent is dispatched.
API Reference
create(source)
Create a table. Returns a handle { id, count, columns }.
| Source | Description |
|---|---|
{ glob: "src/**/*.ts" } or { glob: ["src/**/*.ts", "lib/**/*.ts"] } | Match files by one or more patterns. Columns: id, file |
{ filePaths: ["a.ts", "b.ts"] } | Explicit file list. Columns: id, file |
{ tasks: [{ id: "t1", text: "..." }] } | Custom rows. Each must have id |
run(tableId, options)
Dispatch work across rows. Returns { completed, failed, skipped, failures }.
| Option | Default | Description |
|---|---|---|
instruction | (required) | Template with {column} placeholders |
responseSchema | (required) | JSON Schema (type: "object") — properties become row columns |
context | — | Prose prepended to every subagent prompt |
filter | — | Only dispatch matching rows |
subagentType | — | Name of subagent to dispatch to. When set, runs a full agentic loop. When omitted, runs a direct model call |
batchSize | auto | Number or (row, rowCount) => number. Auto caps dispatches at 10; 1 = per-row; function = per-row sizing |
concurrency | 10 | Max concurrent subagent dispatches (clamped to 1–10) |
rows(tableId, options?)
Retrieve rows. Use for inspection and JS-based aggregation.
| Option | Description |
|---|---|
filter | Only return matching rows |
columns | Project to specific columns |
limit | Max rows returned |
Files
- ATTRIBUTION.mdAdded by AutoGineer872 B
- LICENSELicence file added by AutoGineer1.0 KiB
- SKILL.md11.8 KiB
- scripts/batching.tsScript8.7 KiB
- scripts/executor.tsScript4.6 KiB
- scripts/filter.tsScript1.8 KiB
- scripts/index.tsScript10.5 KiB
- scripts/interpolate.tsScript2.3 KiB
- scripts/table.tsScript15.7 KiB
- scripts/types.tsScript7.4 KiB
- scripts/utils.tsScript892 B
scripts/batching.ts
import { extractPlaceholders } from "./interpolate.js";
import type { BatchFn } from "./types.js";
import { readColumn } from "./utils.js";
/**
* Maximum rows per batch when auto-batching.
*/
export const MAX_BATCH_SIZE = 50;
/**
* Group an array of items into batches of a given size.
*
* The last batch may be smaller than `batchSize` if the total count
* is not evenly divisible.
*
* @param items - Array of items to batch.
* @param batchSize - Maximum number of items per batch.
* @returns Array of batches (each batch is an array of items).
*/
export function createBatches<T>(items: T[], batchSize: number): T[][] {
const batches: T[][] = [];
for (let i = 0; i < items.length; i += batchSize) {
batches.push(items.slice(i, i + batchSize));
}
return batches;
}
/**
* Clamp a batch size to [1, MAX_BATCH_SIZE].
*/
function clampBatchSize(n: number): number {
return Math.max(1, Math.min(Math.round(n), MAX_BATCH_SIZE));
}
/**
* Resolve batch sizes and group rows into dispatch-ready batches.
*
* Handles all three modes:
* - **Auto** (`batchSize` undefined): computes a uniform size from row
* count and `maxSubagents` to stay within the concurrency budget.
* - **Uniform** (`batchSize` is a number): all rows use that size.
* - **Per-row** (`batchSize` is a function): evaluates per row, groups
* rows sharing the same batch size, then chunks each group.
*
* Every batch size is clamped to [1, MAX_BATCH_SIZE].
*
* @param rows - Matched rows to dispatch.
* @param batchSize - Batch strategy: undefined (auto), number, or function.
* @param maxSubagents - Concurrency cap used for auto-batch calculation.
* @returns Array of row batches, each ready for dispatch as a single task.
*/
export function resolveBatchGroups(
rows: Record<string, unknown>[],
maxSubagents: number,
batchSize?: number | BatchFn,
): Record<string, unknown>[][] {
if (rows.length === 0) {
return [];
}
if (batchSize === undefined) {
// Auto: keep total dispatches under maxSubagents
const auto =
rows.length > maxSubagents
? Math.min(Math.ceil(rows.length / maxSubagents), MAX_BATCH_SIZE)
: 1;
return createBatches(rows, auto);
}
if (typeof batchSize === "number") {
return createBatches(rows, clampBatchSize(batchSize));
}
const groups = new Map<number, Record<string, unknown>[]>();
for (const row of rows) {
const size = clampBatchSize(batchSize(row, rows.length));
let group = groups.get(size);
if (!group) {
group = [];
groups.set(size, group);
}
group.push(row);
}
const batches: Record<string, unknown>[][] = [];
for (const [size, group] of groups) {
for (const batch of createBatches(group, size)) {
batches.push(batch);
}
}
return batches;
}
/**
* Wrap a per-item JSON Schema into a batch-level response schema.
*
* Produces a schema of the form:
* ```json
* { "results": [{ "id": "...", ...itemProps }] }
* ```
*
* The item schema's properties are merged with an `id` field so each
* batch entry can be matched back to its row.
*
* @param itemSchema - Per-item JSON Schema.
* @returns Batch-level JSON Schema wrapping items in a `results` array.
*/
export function wrapSchema(
itemSchema: Record<string, unknown>,
count?: number,
): Record<string, unknown> {
const props = (itemSchema.properties as Record<string, unknown>) ?? {};
const req = (itemSchema.required as string[]) ?? [];
const itemProperties: Record<string, unknown> = {
id: { type: "string" },
...props,
};
const itemRequired: string[] = ["id", ...req];
const resultsArray: Record<string, unknown> = {
type: "array",
items: {
type: "object",
additionalProperties: false,
properties: itemProperties,
required: itemRequired,
},
};
if (count != null) {
resultsArray.minItems = count;
resultsArray.maxItems = count;
}
return {
type: "object",
additionalProperties: false,
properties: {
results: resultsArray,
},
required: ["results"],
};
}
/**
* Format a single column value for inclusion in a batch prompt.
*
* Strings are inserted verbatim; numbers/booleans are stringified;
* objects/arrays are JSON-serialized; `undefined` and `null` become
* the empty string so the row still renders with its id.
*/
function formatValue(value: unknown): string {
if (value === undefined || value === null) {
return "";
}
if (typeof value === "string") {
return value;
}
if (typeof value === "number" || typeof value === "boolean") {
return String(value);
}
return JSON.stringify(value);
}
/**
* Rewrite `{col}` placeholders in the author's instruction to
* `` `col` `` (backtick-quoted column name, no braces). The model
* sees a column name as a name, never as template syntax.
*/
function renderTaskBlock(instruction: string): string {
return instruction.replace(
/\{([^}]+)\}/g,
(_m, raw) => `\`${String(raw).trim()}\``,
);
}
/**
* Render the items section.
*
* - 0 placeholders → `[id]` per row (no values, degenerate).
* - 1 placeholder → `[id] <value>` per row (flat).
* - 2+ placeholders → labeled block:
* [id]
* col1: <value>
* col2: <value>
*/
function renderItemsBlock(
rows: Array<Record<string, unknown>>,
placeholders: string[],
): string {
const lines: string[] = [];
for (const row of rows) {
const id = String(row.id);
if (placeholders.length === 0) {
lines.push(`[${id}]`);
continue;
}
if (placeholders.length === 1) {
const value = readColumn(row, placeholders[0]);
lines.push(`[${id}] ${formatValue(value)}`);
continue;
}
lines.push(`[${id}]`);
for (const col of placeholders) {
const value = readColumn(row, col);
lines.push(` ${col}: ${formatValue(value)}`);
}
}
return lines.join("\n");
}
/**
* Build a single prompt for a batch of rows.
*
* The instruction is rewritten to drop template-syntax braces — every
* `{col}` becomes `` `col` `` so the model sees column names as names,
* not as slots it must fill in. Items are rendered as either a flat
* list (single-column case) or a labeled per-column block, so the
* binding from row id to column value is structural and explicit.
*
* @param instruction - Instruction template with `{column}` placeholders.
* @param rows - Array of row objects to include in the batch.
* @param context - Optional context prose prepended to the prompt.
* @returns A single prompt string covering all rows in the batch.
*/
export function buildBatchPrompt(
instruction: string,
rows: Array<Record<string, unknown>>,
context?: string,
): string {
const placeholders = extractPlaceholders(instruction);
const taskBlock = renderTaskBlock(instruction);
const itemsBlock = renderItemsBlock(rows, placeholders);
const parts: string[] = [];
if (context) {
parts.push(context);
parts.push("");
}
parts.push("# Task");
parts.push(taskBlock);
parts.push("");
parts.push(`# Items (${rows.length})`);
if (placeholders.length === 1) {
parts.push(`Each item below is the value of \`${placeholders[0]}\`.`);
parts.push("");
} else if (placeholders.length > 1) {
const cols = placeholders.map((p) => `\`${p}\``).join(", ");
parts.push(`Each item below provides ${cols}.`);
parts.push("");
}
parts.push(itemsBlock);
parts.push("");
parts.push(
`Return a JSON object with a 'results' array of exactly ${rows.length} ` +
"entries, each including the item's 'id' exactly as shown above.",
);
return parts.join("\n");
}
/**
* Unpack a batch response string into per-row results.
*
* Parses the JSON response expecting `{ results: [{ id, ...fields }] }`.
* Maps each item's `id` to its remaining fields. IDs present in
* `expectedIds` but absent from the response are returned in `missing`.
*
* @param response - Raw JSON string from the subagent.
* @param expectedIds - List of row IDs the batch was supposed to cover.
* @returns Map of ID → result fields, plus a list of IDs missing from
* the response.
*/
export function unpackBatchResults(
response: string,
expectedIds: string[],
): { results: Map<string, unknown>; missing: string[] } {
const resultsMap = new Map<string, unknown>();
const missing: string[] = [];
try {
const parsed = JSON.parse(response);
const items: Array<Record<string, unknown>> = parsed?.results ?? [];
for (const item of items) {
if (item && typeof item.id === "string") {
const { id, ...fields } = item;
resultsMap.set(id, fields);
}
}
} catch {
// Parse failure — all IDs are missing
}
for (const id of expectedIds) {
if (!resultsMap.has(id)) {
missing.push(id);
}
}
return { results: resultsMap, missing };
}
Requirements and compatibility
Works with: Claude Code, Claude apps, OpenAI Codex, GitHub Copilot, Cursor, Gemini CLI, Kiro, OpenCode, Goose, Amp, Roo Code, JetBrains Junie, Factory Droid, Devin (ex-Windsurf), Mistral Vibe, OpenHands, Letta
“Works with” means the tool reads the open Agent Skills format; a skill written for one tool may use features others lack.
Needs: Needs Node.js
The author says: Requires @langchain/quickjs code interpreter with swarm_task PTC tool
Security
What our scanner noticed· Low risk
- Scripts that your agent may run
This skill includes scripts that your agent may run. Read them before you use it.
A static scan is not a guarantee. Skills are third-party content: review a skill before you let an agent use it.
Attribution and licence
- Published by
- LangChain
- Publisher
- LangChain (Official)
- Source
- langchain-ai/langchain-skills · config/skills/swarm · commit 126c384
- Licence
- MIT License (redistribution allowed)
- LICENSE (added by AutoGineer from LICENSE)
- ATTRIBUTION.md (written by AutoGineer)
- Synced
AutoGineer is not affiliated with or endorsed by LangChain.
Download ZIP
The ZIP holds the skill’s files, its licence files and an ATTRIBUTION.md. Download swarm.zip