Skip to content

Incremental engine for long horizon agents 🌟 Star if you like it!

feat(examples): research recipe reads named starting pages; seeded drive (#2835)

Jiangzhouced603791f00
diff --git a/examples/cocoindex_agents/DESIGN.md b/examples/cocoindex_agents/DESIGN.md
index 8a578566..d24a684c 100644
--- a/examples/cocoindex_agents/DESIGN.md
+++ b/examples/cocoindex_agents/DESIGN.md
@@ -138,7 +138,12 @@ the page's content, and an orchestrator that never reads a page or a search
result. The recipe also says what to do with nothing to read: a search card
showing `items: 0` means no page could be found or fetched and the report
says so; a leads reduce that names no URL gives a `web_pages` source with no
-items, an empty second collection, and a report reduced from the first.
+items, an empty second collection, and a report reduced from the first. A
+task that names pages to start from gets a `web_pages` source over them in
+the first turn, beside the search (same turn, so neither excludes the
+other), read by its own fan-out and reduced with the rest; the
+`research_seeded` flow uses this to measure a changed source against a page
+the user controls.
Directions kept in view, not in v1:
diff --git a/examples/cocoindex_agents/cocoindex_agents/roles.py b/examples/cocoindex_agents/cocoindex_agents/roles.py
index 4dbefe72..c42715fe 100644
--- a/examples/cocoindex_agents/cocoindex_agents/roles.py
+++ b/examples/cocoindex_agents/cocoindex_agents/roles.py
@@ -108,7 +108,11 @@ keys, so that the same task decomposes the same way every run:
value="res:report"). If the web_search card shows items 0, nothing could
be found or fetched: declare a report that says so and answer with that
status. If src:leads shows items 0, skip its for_each and reduce the
- report from coll:pages alone.
+ report from coll:pages alone. If the task names pages to start from, open
+ them in the first turn too, as open_source(kind="web_pages", name="given",
+ urls=[those URLs]), read them with for_each(src:given, key="given",
+ collect=true, task=READ), and reduce the leads over
+ ["coll:pages", "coll:given"] and the report over all three collections.
Rules:
diff --git a/examples/cocoindex_agents/flows/README.md b/examples/cocoindex_agents/flows/README.md
index 18785c9d..af718f30 100644
--- a/examples/cocoindex_agents/flows/README.md
+++ b/examples/cocoindex_agents/flows/README.md
@@ -1,8 +1,9 @@
# Sample flows
-Six small flows: one per shape of DESIGN.md Β§2, one over PDFs, one over a
-Google Drive folder and one over the web, each a directory with a
-`prompt.md` and (except `drive` and `research`) a few short input files. The prompts are written as a user
+Seven small flows: one per shape of DESIGN.md Β§2, one over PDFs, one over a
+Google Drive folder and two over the web, each a directory with a
+`prompt.md` and (except `drive` and the two `research` flows) a few short
+input files. The prompts are written as a user
would write them: the outcome, where the data is, where the output goes, the
file naming when it matters, and what to answer. They do not mention workers,
planners or reducers; the orchestrator decomposes the task itself, following
@@ -18,6 +19,7 @@ many model calls the run made, per role.
| `orders` | A. map β†’ targets, over PDFs | one JSON object per purchase order under `orders/`, with the fields the prompt names, including which box of the Approval section is ticked |
| `drive` | A. map β†’ targets, over a Google Drive folder | one summary file per file in the Drive folder `$DRIVE_FOLDER`, `Meeting notes` β†’ `Meeting notes.summary.md` |
| `research` | E. search β†’ read β†’ follow β†’ report, over the web | what incremental computation is and where it is used; search the web, read what is found, follow the leads worth following, write `out/report.md` with citations |
+| `research_seeded` | E, starting from a page the prompt names | the same topic, starting from the page `$RESEARCH_SEED` (a page the user controls, so that a changed source can be staged) |
The purchase orders are PDFs the model reads natively (DESIGN.md Β§3,
*Documents*): one page each, a ruled line-item table, totals, and three
@@ -83,7 +85,10 @@ costs one conditional request and no model call; a page that changed only in
a timestamp, an ad or a comment count costs nothing either, because a
worker is memoized on the page's normalized content; only a real change
reaches the model, and only that page's worker and the reducers on its path
-run again. The `--plan` tree lists each source's pages with their digest and
+run again. To see that with a page you can change, run `research_seeded`
+with `$RESEARCH_SEED` set to a page you control (the raw URL of a gist, for
+example); the prompt names it as the page to start from, and the recipe
+reads it beside the search results. The `--plan` tree lists each source's pages with their digest and
when the current content was first fetched, and its unavailable pages with
the reason; citations in the report carry the URL only (DESIGN.md Β§3: no
time in a tool result).
@@ -234,7 +239,39 @@ from both collections and declared it.
|---|---|---|
| fresh | 46 (orchestrator 8, workers 34, reducers 4) | `model calls 46, sessions 20, tool calls 27, spent tokens 193265 in (provider-cached 23209 / 12%), 8068 out, files 1, 63.1s` |
| unchanged | 0 | `model calls 46 (reused 46 / 100%), sessions 20 (skipped 20 / 100%), tool calls 27 (reused 27 / 100%), files 1 (unchanged 1 / 100%), 1.1s` |
-| one source changed | not yet measured: it needs a page under the user's control (a gist, or a page they name); the scripted drive of the same case is `test_research.py::test_a_research_run_reuses_unchanged_pages_and_reruns_only_a_changed_one` (one worker's answer turn and the two reducers: 3 calls) | |
+
+The `research_seeded` flow adds a page the user controls as the starting
+page (`$RESEARCH_SEED`: the raw URL of a secret gist, a Markdown page of
+notes on the topic with two links), so that a changed source can be staged.
+Same model and engine, same day:
+
+| Run | Model calls | `stats:` |
+|---|---|---|
+| fresh | 52 (orchestrator 8, workers 36, reducers 8) | `model calls 52, sessions 23, tool calls 32, spent tokens 207238 in (provider-cached 27352 / 13%), 12828 out, files 1, 92.7s` |
+| unchanged | 0 | `model calls 52 (reused 52 / 100%), sessions 23 (skipped 23 / 100%), tool calls 32 (reused 32 / 100%), files 1 (unchanged 1 / 100%), 1.1s` |
+| the seed page changed (a paragraph added) | 4 (the gist's worker 1, the leads reducer 1, the report reducer 2) | `model calls 52 (reused 48 / 92%), sessions 23 (skipped 18 / 78%), tool calls 32 (reused 18 / 56%), spent tokens 37343 in, 3568 out, files 1, 49.2s` |
+
+What the changed-source run shows:
+
+- The validator saw the gist's digest move (`--plan`: `walk of src:given
+ changed`), the orchestrator's body re-ran with every turn a hit (0 calls),
+ the twelve search pages' workers and the five lead pages' workers were
+ skipped, and only the gist's worker re-ran its answer turn (its
+ `read_input` turn hit).
+- The leads reducer re-ran because its members changed and **picked its
+ previous answer** from the replay block (1 call, a byte-identical list of
+ URLs), so the `web_pages` source over the leads kept its identity and its
+ workers hit. The report reduce had three groups; the leaf holding the gist
+ and the root re-ran (2 calls), the other leaf was skipped. The report now
+ carries the added paragraph's claim with the gist's URL as its citation.
+- A caveat the drive surfaced: the gist's CDN answers with `max-age=300`
+ and caches per request variant. For about five minutes after the edit, a
+ conditional request from the flow's client was still answered `304` with
+ the old validator while a differently shaped request already saw the new
+ text, so the first two reruns after the edit were skipped whole, correctly
+ from what the origin told them. A page behind a caching CDN can lag its
+ own edit by the CDN's `max-age`; the flow cannot see what the server does
+ not tell it.
What the runs show:
@@ -251,8 +288,12 @@ What the runs show:
re-run the orchestrator's body with no inference because a page's ETag had
rotated while its content had not; validity now rests on the normalized
content, and the record refreshes its validators.
-- Changing a source the flow actually reads needs a page under the user's
- control; see the note in the row above.
+- The orchestrator followed the recipe's starting-page clause in the seeded
+ drive: it opened the `web_pages` source over the gist in the first turn
+ beside the search, read it with its own fan-out, and reduced the leads
+ over both collections; the gist's link to the "Build systems Γ  la carte"
+ page became one of the five leads. With 18 answers the report reduce had
+ three groups (two leaves and the root: six calls cold).
## Measured: the `drive` flow against a real account
diff --git a/examples/cocoindex_agents/flows/research_seeded/prompt.md b/examples/cocoindex_agents/flows/research_seeded/prompt.md
new file mode 100644
index 00000000..164d1f8b
--- /dev/null
+++ b/examples/cocoindex_agents/flows/research_seeded/prompt.md
@@ -0,0 +1,6 @@
+Research what incremental computation is and where it is used in build
+systems and databases. Start from the page $RESEARCH_SEED, then search the
+web, read what you find, follow the leads worth following, and write
+./out/report.md: an overview, the main approaches with their trade-offs, and
+notable systems, each claim with its source. End with a Sources section
+listing every page used, with its URL. Answer with a one-line status.
diff --git a/examples/cocoindex_agents/tests/test_research.py b/examples/cocoindex_agents/tests/test_research.py
index 8ea5987b..a446fd0c 100644
--- a/examples/cocoindex_agents/tests/test_research.py
+++ b/examples/cocoindex_agents/tests/test_research.py
@@ -213,6 +213,7 @@ class Script:
leads_task: str = LEADS
report_task: str = REPORT
reword_leads: bool = False # the leads reducer phrases its answer differently
+ seed: str | None = None # a page the task names to start from (recipe 5)
def __call__(
self, spec: SessionSpec, prefix: Transcript, hints: RunHints
@@ -230,22 +231,19 @@ class Script:
n = len(prefix.steps)
results = [s.results for s in prefix.steps]
if n == 0:
- return ModelOutput(
- calls=(
- call(
- "open_source",
- kind="web_search",
- name="web",
- queries=self.queries,
- ),
+ opens = [
+ call(
+ "open_source", kind="web_search", name="web", queries=self.queries
+ ),
+ call("open_target", kind="localfs_dir", name="out", path=str(self.out)),
+ ]
+ if self.seed is not None:
+ opens.append(
call(
- "open_target",
- kind="localfs_dir",
- name="out",
- path=str(self.out),
- ),
+ "open_source", kind="web_pages", name="given", urls=[self.seed]
+ )
)
- )
+ return ModelOutput(calls=tuple(opens))
card = results[0][0]
if not card.ok:
return ModelOutput(answer=f"could not open the web: {card.value}")
@@ -263,18 +261,17 @@ class Script:
)
return ModelOutput(answer="no evidence")
if n == 1:
- return ModelOutput(
- calls=(call("for_each", source="src:web", key="pages", task=READ),)
- )
+ fan_outs = [call("for_each", source="src:web", key="pages", task=READ)]
+ if self.seed is not None:
+ fan_outs.append(
+ call("for_each", source="src:given", key="given", task=READ)
+ )
+ return ModelOutput(calls=tuple(fan_outs))
+ first = ["coll:pages", "coll:given"] if self.seed is not None else "coll:pages"
if n == 2:
return ModelOutput(
calls=(
- call(
- "reduce",
- collection="coll:pages",
- key="leads",
- task=self.leads_task,
- ),
+ call("reduce", collection=first, key="leads", task=self.leads_task),
)
)
if n == 3:
@@ -296,7 +293,11 @@ class Script:
)
step_report = 5 if has_leads else 4
if n == step_report:
- collections = ["coll:pages", "coll:pages2"] if has_leads else ["coll:pages"]
+ collections = ["coll:pages"] + (
+ ["coll:given"] if self.seed is not None else []
+ )
+ if has_leads:
+ collections.append("coll:pages2")
return ModelOutput(
calls=(
call(
@@ -815,6 +816,47 @@ def test_empty_outcomes_are_reported_honestly_and_recover(
assert f.model.calls == 0
+def test_a_page_the_task_names_is_read_first_and_its_change_reruns_only_its_path(
+ coco_env: coco.Environment, tmp_path: pathlib.Path, monkeypatch: pytest.MonkeyPatch
+) -> None:
+ """Recipe 5's starting page: a ``web_pages`` source opened in the first turn
+ beside the search (same turn: not excluded from each other), read by its
+ own fan-out, both collections reduced for leads and for the report. A
+ change to that page re-runs its worker's answer and the two reducers; the
+ search pages' workers hit."""
+ fake = FakeWeb()
+ site(
+ fake,
+ a=Page(article("a"), etag='"a"'),
+ seed=Page(article("seed", links=(url("l1"),)), etag='"s1"'),
+ l1=Page(article("l1"), etag='"l1"'),
+ )
+ engine = FakeEngine({"q": [url("a")]})
+ f = setup(coco_env, tmp_path, monkeypatch, fake, engine, ["q"])
+ f.script.seed = url("seed")
+
+ f.run()
+ assert f.calls("orchestrator") == 8 and f.calls("worker") == 6
+ report = f.report()
+ assert all(f"({url(n)})" in report for n in ("a", "seed", "l1"))
+
+ f.run()
+ assert f.model.calls == 0 and f.executed() == {}
+
+ fake.pages[url("seed")] = Page(
+ html_page(
+ "Page seed",
+ ["Seed, revised. " + PARAGRAPHS[0], *PARAGRAPHS[1:]],
+ links=(url("l1"),),
+ ),
+ etag='"s2"',
+ )
+ f.run()
+ assert f.calls("worker") == 1 and f.calls("reducer") == 2
+ assert f.calls("orchestrator") == 0
+ assert "Seed, revised" in f.report()
+
+
def test_a_planner_reading_a_page_is_skipped_while_the_page_is_unchanged(
coco_env: coco.Environment, tmp_path: pathlib.Path, monkeypatch: pytest.MonkeyPatch
) -> None: