Agentic Architectures

Catalogue / Multi-agent Coordination

STORM

Interview the topic from many angles, then outline and write

Shape
pipeline
Model calls
1 + perspectives × turns × 2 + 1 + sections (e.g. 1 + 4×4×2 + 1 + 6 = 40)
Latency
high
Complexity
high

Also known as Perspective-guided research writing

1

Why do long research reports written by AI feel shallow?

Asked for a report in one go, a model writes what it already knows, from one angle. STORM first asks who would care about the topic and why, lets each of those perspectives interview a source-backed expert, and only then outlines and writes.

You may need it if

  • Reports cover the obvious points and miss what a specialist would ask first.
  • You need sources behind every claim, not a confident summary.
  • The document runs to several pages, such as a market brief or a technical backgrounder.
2

When is a full research pipeline overkill?

Use it when

  • The output is a long, structured document that must cover a topic broadly.
  • Good sources exist to search, on the web or in your own document collection.
  • The reader will act on the document, so missing angles cost more than extra calls.

Avoid it when

What it costs

Model calls
1 + perspectives × turns × 2 + 1 + sections (e.g. 1 + 4×4×2 + 1 + 6 = 40)
Latency
high
Complexity
high
3

How does a topic become a sourced article?

Perspectives are named first. Each one interviews a grounded expert for a few turns, and every answer is filed with its sources. An outliner turns the notes into sections, and writers draft each section from the notes that belong to it.

citedanswer,turns leftturns spent ornothing newTopic: The subject of the document, its intended reader and any scope limits.TopicPerspective finder: Names three to five people who would look at the topic differently, and what each one cares about.PerspectivefinderInterviewers: One per perspective. Asks the expert one question at a time, following up on each answer.InterviewersGrounded expert: Searches the sources and answers each question with cited passages only.GroundedexpertResearch notes: Every question and answer, with its sources and the perspective that asked.ResearchnotesOutliner: Reads all notes and writes the section outline, assigning notes to each section.OutlinerSection writers: Each drafts one section from its assigned notes, citing every claim.SectionwritersArticle: The assembled document with its outline and source list.Article
  1. Step 1 of 5

    Who would care, and why?

    The perspective finder lists a few distinct readers, for a new product launch perhaps a buyer, a competitor, a regulator and an engineer. Each one gets a short brief of what it worries about.

  2. Step 2 of 5

    Interviews, one question at a time

    Each interviewer asks the expert a question from its perspective, reads the answer and asks a follow-up. Follow-ups are where the non-obvious points come out.

  3. Step 3 of 5

    Answers are filed with sources

    The expert answers only from what it finds and cites the passages. Every exchange goes into the notes, tagged with the perspective that asked.

  4. Step 4 of 5

    The notes become an outline

    When the interviews end, the outliner reads all notes and proposes sections. It assigns each note to a section, which also shows which sections are thin.

  5. Step 5 of 5

    Section by section

    Each writer drafts one section from its outline entry and its notes, citing every claim. The sections are joined into the article with a single source list.

What each part does
Topic
The subject of the document, its intended reader and any scope limits.
Perspective finder
Names three to five people who would look at the topic differently, and what each one cares about.
Interviewers
One per perspective. Asks the expert one question at a time, following up on each answer.
Grounded expert
Searches the sources and answers each question with cited passages only.
Research notes
Every question and answer, with its sources and the perspective that asked.
Outliner
Reads all notes and writes the section outline, assigning notes to each section.
Section writers
Each drafts one section from its assigned notes, citing every claim.
Article
The assembled document with its outline and source list.
  • Perspective finder → Interviewers: one brief per perspective
  • Interviewers → Grounded expert: question
  • Grounded expert → Interviewers: cited answer, turns left
  • Grounded expert → Research notes: answer and sources
  • Interviewers → Outliner: turns spent or nothing new
  • Outliner → Section writers: section and its notes

Where it connects

Entry
topic
TaskQuestion

A topic or research question, the intended reader, and optionally the sources to search and a target length.

Exit
article
Document

When: Every section in the outline has been written.

The full article with headings, inline citations, a source list, and a note of sections the research left thin.

Working memory for one run
notes
Evidence

Question-and-answer pairs, each with its cited passages and the perspective that asked. Discarded when the run ends.

4

What do I ask my assistant to set up?

The agents to launch

Perspective finder

Name three to five people who would read about this topic for different reasons. For each, write one line on who they are and two lines on what they most need to know. Avoid overlapping perspectives.

Sees: The topic, the intended reader and the scope limits.

Interviewer, one per perspective, at most five

You hold one perspective. Ask the expert one question at a time about what matters to you. Read each answer and follow up on whatever is vague or surprising. Say "done" when you learn nothing new.

Sees: Its own perspective brief, the topic and its own conversation with the expert. Not the other interviews.

Grounded expert

Answer each question using only passages you find in the sources. Cite every passage. If the sources do not answer the question, say so plainly instead of filling the gap.

Sees: One question at a time, plus search access to the sources. Not the interviewer's perspective brief.

Outliner

Read all the notes and write an outline of four to eight sections for the intended reader. Assign each note to one section. Flag any section with fewer than three supporting notes.

Sees: The topic, the intended reader and all the notes.

Section writer, one per section in the outline

Write your one section from the notes assigned to it. Cite a source for every claim. Do not add facts that are not in your notes, and do not repeat what other sections cover.

Sees: The full outline, its own section entry and the notes assigned to it. Not the other sections' notes.

A prompt you can paste

Works with any assistant that can launch sub-agents. It contains the agents, the procedure and the stop rule above.

Framework-agnostic prompt
You are the orchestrator of a multi-agent workflow that follows the "STORM" architecture.
Launch every agent listed below as a separate sub-agent with its own context. Give each agent only the context stated for it. Do not do an agent's work yourself. If you cannot launch sub-agents, play each agent in a clearly separated turn and never let it use what is withheld from it.

# Task
[Describe your task here]

# STORM
Interview the topic from many angles, then outline and write.
Input: the task above. It must provide: A topic or research question, the intended reader, and optionally the sources to search and a target length. If something essential is missing, ask for it before starting.

Agents to launch:
- Perspective finder: Name three to five people who would read about this topic for different reasons. For each, write one line on who they are and two lines on what they most need to know. Avoid overlapping perspectives.
  Context for this agent: The topic, the intended reader and the scope limits.
- Interviewer (one per perspective, at most five): You hold one perspective. Ask the expert one question at a time about what matters to you. Read each answer and follow up on whatever is vague or surprising. Say "done" when you learn nothing new.
  Context for this agent: Its own perspective brief, the topic and its own conversation with the expert. Not the other interviews.
- Grounded expert: Answer each question using only passages you find in the sources. Cite every passage. If the sources do not answer the question, say so plainly instead of filling the gap.
  Context for this agent: One question at a time, plus search access to the sources. Not the interviewer's perspective brief.
- Outliner: Read all the notes and write an outline of four to eight sections for the intended reader. Assign each note to one section. Flag any section with fewer than three supporting notes.
  Context for this agent: The topic, the intended reader and all the notes.
- Section writer (one per section in the outline): Write your one section from the notes assigned to it. Cite a source for every claim. Do not add facts that are not in your notes, and do not repeat what other sections cover.
  Context for this agent: The full outline, its own section entry and the notes assigned to it. Not the other sections' notes.

Procedure:
1. Restate the topic, the intended reader and the sources to search. Launch the perspective finder.
2. Launch one interviewer per perspective and one expert, as separate agents. Run the interviews in parallel.
3. Relay each question to the expert in a fresh call and each answer back to its interviewer. Store every pair, with sources and perspective, in the notes.
4. End each interview after 4 questions, or earlier when the interviewer says "done".
5. Launch the outliner on all the notes. If a flagged section matters to the reader, run one extra interview on it.
6. Launch one section writer per section, in parallel, then join the sections in outline order with one source list.

Stop rule: Each interview stops at 4 questions or when the interviewer says "done". Allow at most one extra interview for thin sections. Writing happens once per section.

Exit:
- `article`, when: Every section in the outline has been written. Deliver: The full article with headings, inline citations, a source list, and a note of sections the research left thin.

# Final deliverable
The article with headings and citations, the source list, the perspectives used, and a note of any section the research left thin.

The same thing in code

LangGraph, python, package langgraph
import operator
from typing import Annotated, Literal, TypedDict

from langchain.chat_models import init_chat_model
from langgraph.graph import END, START, StateGraph
from langgraph.types import Send
from pydantic import BaseModel

llm = init_chat_model("anthropic:claude-sonnet-5-5")
MAX_QUESTIONS = 4


def search_sources(query: str) -> list[str]:
    return []  # plug in your source search (web search, document index)


class Perspectives(BaseModel):
    briefs: list[str]


class Turn(BaseModel):
    question: str
    done: bool


class Answer(BaseModel):
    answer: str
    sources: list[str]


class Section(BaseModel):
    title: str
    note_ids: list[int]
    thin: bool


class Outline(BaseModel):
    sections: list[Section]


class Note(TypedDict):
    perspective: str
    question: str
    answer: str
    sources: list[str]


class State(TypedDict):
    topic: str
    briefs: list[str]
    notes: Annotated[list[Note], operator.add]
    outline: Outline | None
    extra_done: bool
    drafts: Annotated[list[tuple[int, str]], operator.add]


class InterviewIn(TypedDict):
    topic: str
    brief: str


class WriterIn(TypedDict):
    titles: list[str]
    i: int
    section: Section
    own_notes: list[Note]


async def ask[T: BaseModel](schema: type[T], prompt: str) -> T:
    out = await llm.with_structured_output(schema).ainvoke(prompt)
    assert isinstance(out, schema)
    return out


async def interview(topic: str, brief: str) -> list[Note]:
    notes: list[Note] = []
    for _ in range(MAX_QUESTIONS):  # stop at 4 questions or "done"
        convo = "\n".join(f"Q: {n['question']}\nA: {n['answer']}" for n in notes)
        t = await ask(Turn, f"You hold this perspective: {brief}\nTopic: {topic}\nAsk the expert one question, "
                      f"following up on anything vague. Set done when you learn nothing new.\n\n{convo}")
        if t.done:
            break
        # the expert sees one question and the passages found, never the perspective
        passages = search_sources(t.question)
        a = await ask(Answer, "Answer using only these passages and cite each one. If they do not answer, say "
                      f"so.\n\nQuestion: {t.question}\n\nPassages:\n" + "\n\n".join(passages))
        notes.append({"perspective": brief, "question": t.question, "answer": a.answer, "sources": a.sources})
    return notes


async def find_perspectives(state: State) -> dict:
    p = await ask(Perspectives, "Name three to five people who would read about this topic for different "
                  "reasons: who they are and what they most need to know. No overlaps.\n\n" + state["topic"])
    return {"briefs": p.briefs[:5]}


def fan_out(state: State) -> list[Send]:
    return [Send("interviewer", {"topic": state["topic"], "brief": b}) for b in state["briefs"]]


async def interviewer(state: InterviewIn) -> dict:
    return {"notes": await interview(state["topic"], state["brief"])}


def numbered(notes: list[Note]) -> str:
    return "\n".join(f"[{i}] ({n['perspective']}) {n['question']} -> {n['answer']} {n['sources']}"
                     for i, n in enumerate(notes))


async def outliner(state: State) -> dict:
    o = await ask(Outline, "Write an outline of four to eight sections for the intended reader. Assign each note "
                  "to one section. Flag as thin any section with fewer than three notes.\n\n"
                  f"Topic: {state['topic']}\n\nNotes:\n{numbered(state['notes'])}")
    return {"outline": o}


async def extra(state: State) -> dict:
    assert state["outline"]
    thin = next(s for s in state["outline"].sections if s.thin)
    return {"notes": await interview(state["topic"], f"A reader who needs: {thin.title}"), "extra_done": True}


def after_outline(state: State) -> list[Send] | Literal["extra"]:
    assert state["outline"]
    if any(s.thin for s in state["outline"].sections) and not state["extra_done"]:
        return "extra"  # at most one extra interview
    titles = [s.title for s in state["outline"].sections]
    return [Send("writer", {"titles": titles, "i": i, "section": s,
                            "own_notes": [state["notes"][k] for k in s.note_ids if k < len(state["notes"])]})
            for i, s in enumerate(state["outline"].sections)]


async def writer(state: WriterIn) -> dict:
    # one writer per section: the outline, its own entry and its own notes
    msg = await llm.ainvoke(f"Outline: {state['titles']}\nWrite only the section '{state['section'].title}' from "
                            "these notes. Cite a source for every claim; add nothing that is not in them.\n\n"
                            + numbered(state["own_notes"]))
    return {"drafts": [(state["i"], msg.text)]}


g = StateGraph(State)
g.add_node("find_perspectives", find_perspectives)
g.add_node("interviewer", interviewer)
g.add_node("outliner", outliner)
g.add_node("extra", extra)
g.add_node("writer", writer)
g.add_edge(START, "find_perspectives")
g.add_conditional_edges("find_perspectives", fan_out, ["interviewer"])
g.add_edge("interviewer", "outliner")
g.add_conditional_edges("outliner", after_outline, ["extra", "writer"])
g.add_edge("extra", "outliner")
g.add_edge("writer", END)
app = g.compile()


async def run(task: str):
    state = await app.ainvoke({"topic": task, "briefs": [], "notes": [], "outline": None, "extra_done": False, "drafts": []})
    article = "\n\n".join(text for _, text in sorted(state["drafts"]))
    sources = sorted({s for n in state["notes"] for s in n["sources"]})
    return {"article": article, "sources": sources, "outline": state["outline"]}

Replace search_sources with real retrieval; the expert here searches once with the question, so let it run its own queries if answers come back thin.

Claude Agent SDK, python, package claude-agent-sdk
import asyncio
import json
from typing import Any

from claude_agent_sdk import (AgentDefinition, ClaudeAgentOptions, ResultMessage,
                              create_sdk_mcp_server, query, tool)

MAX_QUESTIONS = 4


def search_sources(q: str) -> list[str]:
    return []  # plug in your source search (web search, document index)


@tool("search", "Search the sources and return matching passages with their ids", {"query": str})
async def search(args: dict[str, Any]) -> dict[str, Any]:
    return {"content": [{"type": "text", "text": "\n\n".join(search_sources(args["query"])) or "No passages."}]}


SOURCES = create_sdk_mcp_server("sources", tools=[search])
AGENTS = {
    "perspective-finder": AgentDefinition(
        description="Names distinct reader perspectives on a topic.",
        prompt="Name three to five people who would read about this topic for different reasons: one line on "
               "who they are, two on what they most need to know. Avoid overlaps.", tools=[]),
    "interviewer": AgentDefinition(
        description="Asks the expert one question at a time from one perspective.",
        prompt="You hold one perspective. Ask one question about what matters to you, following up on whatever "
               "is vague or surprising. Say done when you learn nothing new.", tools=[]),
    "expert": AgentDefinition(
        description="Answers one question from the sources, with citations.",
        prompt="Answer using only passages you find with search. Cite every passage. If the sources do not "
               "answer, say so plainly.", tools=["mcp__sources__search"]),
    "outliner": AgentDefinition(
        description="Turns research notes into a section outline.",
        prompt="Write an outline of four to eight sections for the intended reader. Assign each note to one "
               "section. Flag as thin any section with fewer than three notes.", tools=[]),
    "section-writer": AgentDefinition(
        description="Drafts one section from its own notes.",
        prompt="Write your one section from its notes. Cite a source for every claim. Add no facts that are not "
               "in your notes and do not repeat other sections.", tools=[]),
}


def obj(**props: Any) -> dict[str, Any]:
    return {"type": "object", "required": list(props), "properties": props}


S, L = {"type": "string"}, {"type": "array", "items": {"type": "string"}}
BRIEFS = obj(briefs=L)
TURN = obj(question=S, done={"type": "boolean"})
ANSWER = obj(answer=S, sources=L)
OUTLINE = obj(sections={"type": "array", "items": obj(
    title=S, note_ids={"type": "array", "items": {"type": "integer"}}, thin={"type": "boolean"})})


async def delegate(agent: str, payload: str, schema: dict[str, Any] | None = None) -> Any:
    # one query per call, so every sub-agent starts from a fresh context
    options = ClaudeAgentOptions(
        agents=AGENTS, mcp_servers={"sources": SOURCES}, allowed_tools=["Agent", "mcp__sources__search"],
        output_format={"type": "json_schema", "schema": schema} if schema else None)
    prompt = f"Use the {agent} agent on the input below and return its reply unchanged.\n\n{payload}"
    async for msg in query(prompt=prompt, options=options):
        if isinstance(msg, ResultMessage):
            return msg.structured_output if schema else msg.result


async def interview(topic: str, brief: str) -> list[dict[str, Any]]:
    notes: list[dict[str, Any]] = []
    for _ in range(MAX_QUESTIONS):  # stop at 4 questions or "done"
        convo = "\n".join(f"Q: {n['question']}\nA: {n['answer']}" for n in notes)
        turn = await delegate("interviewer", f"Perspective: {brief}\nTopic: {topic}\n\n{convo}", TURN)
        if turn["done"]:
            break
        # the expert gets the question only, not the perspective
        a = await delegate("expert", turn["question"], ANSWER)
        notes.append({"perspective": brief, "question": turn["question"], **a})
    return notes


async def run(task: str):
    briefs = (await delegate("perspective-finder", task, BRIEFS))["briefs"][:5]
    notes = [n for batch in await asyncio.gather(*(interview(task, b) for b in briefs)) for n in batch]
    outline = await delegate("outliner", f"Topic: {task}\n\nNotes:\n{json.dumps(dict(enumerate(notes)))}", OUTLINE)
    thin = [s["title"] for s in outline["sections"] if s["thin"]]
    if thin:  # at most one extra interview for a thin section
        notes += await interview(task, f"A reader who needs: {thin[0]}")
        outline = await delegate("outliner", f"Topic: {task}\n\nNotes:\n{json.dumps(dict(enumerate(notes)))}", OUTLINE)
    titles = [s["title"] for s in outline["sections"]]
    drafts = await asyncio.gather(*(
        delegate("section-writer", f"Outline: {titles}\nYour section: {s['title']}\nNotes: "
                 + json.dumps([notes[i] for i in s["note_ids"] if i < len(notes)]))
        for s in outline["sections"]))
    sources = sorted({src for n in notes for src in n["sources"]})
    return {"article": "\n\n".join(drafts), "sources": sources, "perspectives": briefs, "thin": thin}

Replace search_sources with real retrieval, and check that every expert answer carries a citation before it is filed in the notes.

OpenAI Agents SDK, python, package openai-agents
import asyncio

from agents import Agent, Runner, function_tool
from pydantic import BaseModel

MAX_QUESTIONS = 4


@function_tool
def search_sources(query: str) -> list[str]:
    """Search the sources and return matching passages with their ids."""
    return []  # plug in your source search (web search, document index)


class Perspectives(BaseModel):
    briefs: list[str]


class Turn(BaseModel):
    question: str
    done: bool


class Answer(BaseModel):
    answer: str
    sources: list[str]


class Section(BaseModel):
    title: str
    note_ids: list[int]
    thin: bool


class Outline(BaseModel):
    sections: list[Section]


finder = Agent(name="Perspective finder", output_type=Perspectives,
               instructions="Name three to five people who would read about this topic for different reasons: "
                            "who they are and what they most need to know. Avoid overlaps.")
interviewer = Agent(name="Interviewer", output_type=Turn,
                    instructions="You hold one perspective. Ask the expert one question about what matters to "
                                 "you, following up on anything vague or surprising. Set done when you learn "
                                 "nothing new.")
expert = Agent(name="Grounded expert", output_type=Answer, tools=[search_sources],
               instructions="Answer using only passages you find with search_sources. Cite every passage. If "
                            "the sources do not answer, say so plainly.")
outliner = Agent(name="Outliner", output_type=Outline,
                 instructions="Write an outline of four to eight sections for the intended reader. Assign each "
                              "note to one section. Flag as thin any section with fewer than three notes.")
writer = Agent(name="Section writer",
               instructions="Write your one section from its notes. Cite a source for every claim. Add no facts "
                            "not in your notes and do not repeat other sections.")


async def interview(topic: str, brief: str) -> list[tuple[str, str, Answer]]:
    notes: list[tuple[str, str, Answer]] = []
    for _ in range(MAX_QUESTIONS):  # stop at 4 questions or "done"
        convo = "\n".join(f"Q: {q}\nA: {a.answer}" for _, q, a in notes)
        turn = (await Runner.run(interviewer, f"Perspective: {brief}\nTopic: {topic}\n\n{convo}")).final_output_as(Turn)
        if turn.done:
            break
        # the expert sees one question, never the perspective
        answer = (await Runner.run(expert, turn.question)).final_output_as(Answer)
        notes.append((brief, turn.question, answer))
    return notes


def numbered(notes: list[tuple[str, str, Answer]]) -> str:
    return "\n".join(f"[{i}] ({p}) {q} -> {a.answer} {a.sources}" for i, (p, q, a) in enumerate(notes))


async def run(task: str):
    briefs = (await Runner.run(finder, task)).final_output_as(Perspectives).briefs[:5]
    notes = [n for batch in await asyncio.gather(*(interview(task, b) for b in briefs)) for n in batch]
    outline = (await Runner.run(outliner, f"Topic: {task}\n\nNotes:\n{numbered(notes)}")).final_output_as(Outline)
    thin = [s.title for s in outline.sections if s.thin]
    if thin:  # at most one extra interview for a thin section
        notes += await interview(task, f"A reader who needs: {thin[0]}")
        outline = (await Runner.run(outliner, f"Topic: {task}\n\nNotes:\n{numbered(notes)}")).final_output_as(Outline)
    titles = [s.title for s in outline.sections]
    # one writer per section, in parallel, each with only its own notes
    drafts = await asyncio.gather(*(
        Runner.run(writer, f"Outline: {titles}\nYour section: {s.title}\n\nNotes:\n"
                   + numbered([notes[i] for i in s.note_ids if i < len(notes)]))
        for s in outline.sections))
    sources = sorted({src for _, _, a in notes for src in a.sources})
    return {"article": "\n\n".join(d.final_output for d in drafts), "sources": sources,
            "perspectives": briefs, "thin": thin}

Replace search_sources with real retrieval, and check that every expert answer carries a citation before it is filed in the notes.

Vercel AI SDK, typescript, package ai
import { anthropic } from '@ai-sdk/anthropic';
import { generateText, isStepCount, Output, tool } from 'ai';
import { z } from 'zod';

const model = anthropic('claude-sonnet-5-5');
const MAX_QUESTIONS = 4;

async function searchSources(query: string): Promise<string[]> {
  return []; // plug in your source search (web search, document index)
}

const Answer = z.object({ answer: z.string(), sources: z.array(z.string()) });
type Note = { perspective: string; question: string } & z.infer<typeof Answer>;
const Outline = z.object({
  sections: z.array(z.object({ title: z.string(), noteIds: z.array(z.number().int()), thin: z.boolean() })),
});

async function ask<T>(schema: z.ZodType<T>, instructions: string, prompt: string): Promise<T> {
  const { output } = await generateText({ model, output: Output.object({ schema }), instructions, prompt });
  return output;
}

async function interview(topic: string, brief: string): Promise<Note[]> {
  const notes: Note[] = [];
  for (let i = 0; i < MAX_QUESTIONS; i++) { // stop at 4 questions or "done"
    const turn = await ask(
      z.object({ question: z.string(), done: z.boolean() }),
      'You hold one perspective. Ask the expert one question about what matters to you, following up on ' +
        'anything vague or surprising. Set done when you learn nothing new.',
      `Perspective: ${brief}\nTopic: ${topic}\n\n${notes.map((n) => `Q: ${n.question}\nA: ${n.answer}`).join('\n')}`,
    );
    if (turn.done) break;
    // the grounded expert: one question, search access, never the perspective
    const { output } = await generateText({
      model,
      output: Output.object({ schema: Answer }),
      tools: {
        search: tool({
          description: 'Search the sources and return matching passages with their ids',
          inputSchema: z.object({ query: z.string() }),
          execute: async ({ query }) => searchSources(query),
        }),
      },
      stopWhen: isStepCount(6),
      instructions: 'Answer using only passages you find with search. Cite every passage. If the sources do not answer, say so.',
      prompt: turn.question,
    });
    notes.push({ perspective: brief, question: turn.question, ...output });
  }
  return notes;
}

const OUTLINER =
  'Write an outline of four to eight sections for the intended reader. Assign each note to one section. ' +
  'Flag as thin any section with fewer than three notes.';
const numbered = (notes: Note[]) => notes.map((n, i) => `[${i}] (${n.perspective}) ${n.question} -> ${n.answer} ${n.sources}`).join('\n');

export async function run(task: string) {
  const { briefs } = await ask(
    z.object({ briefs: z.array(z.string()) }),
    'Name three to five people who would read about this topic for different reasons: who they are and what they most need to know. Avoid overlaps.',
    task,
  );
  const perspectives = briefs.slice(0, 5);
  const notes = (await Promise.all(perspectives.map((b) => interview(task, b)))).flat();
  let outline = await ask(Outline, OUTLINER, `Topic: ${task}\n\nNotes:\n${numbered(notes)}`);
  const thin = outline.sections.filter((s) => s.thin).map((s) => s.title);
  if (thin.length) { // at most one extra interview for a thin section
    notes.push(...(await interview(task, `A reader who needs: ${thin[0]}`)));
    outline = await ask(Outline, OUTLINER, `Topic: ${task}\n\nNotes:\n${numbered(notes)}`);
  }
  const titles = outline.sections.map((s) => s.title);
  // one writer per section, in parallel, each with only its own notes
  const drafts = await Promise.all(
    outline.sections.map(async (s) => {
      const { text } = await generateText({
        model,
        instructions:
          'Write your one section from its notes. Cite a source for every claim. Add no facts not in your notes and do not repeat other sections.',
        prompt: `Outline: ${titles.join(' | ')}\nYour section: ${s.title}\n\nNotes:\n${numbered(s.noteIds.filter((i) => i < notes.length).map((i) => notes[i]))}`,
      });
      return text;
    }),
  );
  const sources = [...new Set(notes.flatMap((n) => n.sources))];
  return { article: drafts.join('\n\n'), sources, perspectives, thin };
}

Replace searchSources with real retrieval, and check that every expert answer carries a citation before it is filed in the notes.

Snippets are generated when the site is built and type-checked against the SDK versions listed in the repository. Treat them as a starting skeleton.

What goes wrong

  • Perspectives that are near duplicates produce the same questions. Check that each brief names a different concern.
  • An expert allowed to answer from memory introduces uncited claims. Require a citation for every sentence of every answer.
  • Writing all sections in one call loses the benefit of the outline. Give each writer only its own notes.

Chain it

Its result can feed

Source