1How does an agent stop rediscovering the same steps on every task?
After each solved task, the system writes down the few steps that made it work, in general terms, as a recipe. A new task looks up the closest recipe and follows it, adapting the details, instead of starting cold. The agent gets faster on the tasks it sees most.
You may need it if
- The agent handles many variations of the same job, such as updating a customer record in your back office.
- It wastes steps exploring screens or menus it has already navigated many times.
- Success rates differ between runs of the same kind of task for no clear reason.
2When will stored recipes not help?
Use it when
- Tasks of the same family come back often, with different details each time.
- The steps are mostly the same between tasks of a family, even if the inputs change.
- You can tell whether a task was solved, from a check or a user's confirmation.
Avoid it when
- Every task is new, so there is no family of tasks for a recipe to cover.
Use ReAct instead - The reusable part can be written as code that runs on its own, without the agent stepping through it.
Use Skill Library instead - The process is fixed and known in advance. Write it down once yourself instead of learning it.
Use Planning instead
What it costs
- Model calls
- 1 judge + the usual task calls, + 1 to write a recipe after a solved task
- Latency
- medium
- Complexity
- medium
3How does one solved task make the next one easier?
A new task fetches the closest recipe from the store. The solver follows it, adapting the details. A judge decides whether the task was solved. If so, a recipe writer turns the run into a general recipe and files or updates it. The answer leaves either way.
- Step 1 of 5
Find the closest recipe
The task description is matched against the families in the store. The closest one or two recipes come back. On the very first task of a family, nothing does.
- Step 2 of 5
Follow it, adapting the details
The solver uses the recipe as a checklist, filling the blanks with this task's specifics. Where a step does not apply, it works it out as it would without a recipe.
- Step 3 of 5
Was it solved?
The judge looks at the result and the steps taken, and decides. Only a solved task may teach anything.
- Step 4 of 5
Write the recipe
The recipe writer keeps the steps that mattered, drops the detours, and replaces names and numbers with blanks. It updates the family's recipe rather than adding a near-duplicate.
- Step 5 of 5
Answer either way
The answer leaves whether or not the task was solved. An unsolved task files nothing, so failures never become recipes.
What each part does
- Task
- The task to solve, described well enough to match it to a family of past tasks.
- Recipe store
- Short step-by-step recipes, each with the family of tasks it covers and its success count.
- Recipe lookup
- Searches the store by task description and returns the one or two closest recipes.
- Solver
- Carries out the task, following the recipe's steps where they apply and filling in the specifics.
- Solved?
- Checks the result against the task and decides whether it was solved.
- Recipe writer
- Turns the solved run into a recipe of a few general steps and files it, or improves the existing one.
- Answer
- The result of the task, with the recipe used and whether a recipe was filed.
- Recipe lookup → Solver: closest recipe
- Solver → Solved?: result and steps taken
- Solved? → Recipe writer: solved
- Solved? → Answer: not solved, nothing filed
- Recipe writer → Recipe store: new or improved recipe
Where it connects
A task described clearly enough to match a family of similar tasks, with the information needed to carry it out.
When: The judge has decided, and any recipe for a solved task has been filed.
The result, whether the judge counted it as solved, the recipe followed if any, and the recipe filed or updated.
One recipe per task family, a few general steps with blanks for specifics, and a count of successful uses.
4What do I ask my assistant to set up?
The agents to launch
Solver
Carry out the task. If a recipe is given, follow its steps in order, filling each blank with this task's details. If a step does not fit, say so and work it out. Report the result and the steps you actually took.
Sees: The task, the closest recipe and the tools the task needs. Not the other recipes.
Judge
Decide whether the task was solved, from the task, the result and the steps taken. Answer solved or not solved with one reason. When in doubt, answer not solved.
Sees: The task, the result and the steps taken. Not the recipe and not the solver's reasoning.
Recipe writer
From the solved run, write a recipe of three to eight general steps. Replace names, dates and numbers with blanks such as {customer}. Drop steps that did not help. If a recipe for this family exists, improve it instead of writing a second one.
Sees: The task, the steps taken and the existing recipe for the family, if any. Not unrelated recipes.
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.
You are the orchestrator of a multi-agent workflow that follows the "Workflow Memory" 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]
# Workflow Memory
Turn each solved task into a short recipe the next task can follow.
Input: the task above. It must provide: A task described clearly enough to match a family of similar tasks, with the information needed to carry it out. If something essential is missing, ask for it before starting.
Agents to launch:
- Solver: Carry out the task. If a recipe is given, follow its steps in order, filling each blank with this task's details. If a step does not fit, say so and work it out. Report the result and the steps you actually took.
Context for this agent: The task, the closest recipe and the tools the task needs. Not the other recipes.
- Judge: Decide whether the task was solved, from the task, the result and the steps taken. Answer solved or not solved with one reason. When in doubt, answer not solved.
Context for this agent: The task, the result and the steps taken. Not the recipe and not the solver's reasoning.
- Recipe writer: From the solved run, write a recipe of three to eight general steps. Replace names, dates and numbers with blanks such as {customer}. Drop steps that did not help. If a recipe for this family exists, improve it instead of writing a second one.
Context for this agent: The task, the steps taken and the existing recipe for the family, if any. Not unrelated recipes.
Procedure:
1. Create a recipe store searchable by task description, holding one recipe per task family with a success count.
2. Search the store with the new task and keep the closest recipe, if its family matches.
3. Launch the solver with the task and that recipe.
4. Launch the judge in a fresh context on the task, the result and the steps taken.
5. If solved, launch the recipe writer and save its recipe, adding one to the family's success count. If not solved, file nothing and lower the count of the recipe followed.
6. Release the answer with the judge's decision and the recipe used and filed.
Stop rule: One attempt per task, one judgement, at most one recipe written. Drop a recipe whose last three uses all failed.
Exit:
- `answer`, when: The judge has decided, and any recipe for a solved task has been filed. Deliver: The result, whether the judge counted it as solved, the recipe followed if any, and the recipe filed or updated.
# Final deliverable
The result, the judge's decision with its reason, the recipe followed if any, and the recipe filed or updated.
The same thing in code
from typing import TypedDict
from langchain.chat_models import init_chat_model
from langgraph.graph import END, START, StateGraph
from pydantic import BaseModel
model = init_chat_model("anthropic:claude-sonnet-5-5")
class Recipe(BaseModel):
family: str # the family of tasks it covers
steps: list[str] # three to eight general steps with blanks such as {customer}
successes: int = 0
recent: list[bool] = []
RECIPES: list[Recipe] = [] # the recipe store: one recipe per task family
def lookup(task: str) -> Recipe | None:
# plug in an embedding search over recipe families; returns the closest match or None
words = set(task.lower().split())
scored = [(len(words & set(r.family.lower().split())), r) for r in RECIPES]
best = max(scored, key=lambda s: s[0], default=(0, None))
return best[1] if best[0] > 0 else None
class Run(BaseModel):
result: str
steps_taken: list[str]
class Judgement(BaseModel):
solved: bool
reason: str
class State(TypedDict):
task: str
recipe: Recipe | None
run: Run | None
judgement: Judgement | None
filed: Recipe | None
async def find_recipe(state: State) -> dict:
return {"recipe": lookup(state["task"])}
async def solver(state: State) -> dict:
# sees the task and the closest recipe only, not the other recipes
recipe = "\n".join(state["recipe"].steps) if state["recipe"] else "none"
run = Run.model_validate(await model.with_structured_output(Run).ainvoke(
"Carry out the task. If a recipe is given, follow its steps in order, filling each blank with this "
"task's details. If a step does not fit, say so and work it out. Report the result and the steps you "
f"actually took.\n\nTask: {state['task']}\n\nRecipe:\n{recipe}"))
return {"run": run}
async def judge(state: State) -> dict:
# fresh context: the task, the result and the steps, not the recipe or the solver's reasoning
run = state["run"]
assert run
j = Judgement.model_validate(await model.with_structured_output(Judgement).ainvoke(
"Decide whether the task was solved. Answer solved or not solved with one reason. When in doubt, "
f"answer not solved.\n\nTask: {state['task']}\nResult: {run.result}\nSteps: {run.steps_taken}"))
recipe = state["recipe"]
if recipe and not j.solved: # a failed use lowers the recipe's count; nothing is filed
recipe.successes = max(0, recipe.successes - 1)
recipe.recent.append(False)
if recipe.recent[-3:] == [False] * 3: # drop a recipe whose last three uses all failed
RECIPES.remove(recipe)
return {"judgement": j}
def solved(state: State) -> str:
return "inducer" if state["judgement"] and state["judgement"].solved else END
async def inducer(state: State) -> dict:
# sees the task, the steps taken and this family's recipe, not unrelated recipes
run, old = state["run"], state["recipe"]
assert run
new = Recipe.model_validate(await model.with_structured_output(Recipe).ainvoke(
"From the solved run, write a recipe of three to eight general steps. Replace names, dates and numbers "
"with blanks such as {customer}. Drop steps that did not help. If a recipe for this family exists, "
f"improve it instead.\n\nTask: {state['task']}\nSteps taken: {run.steps_taken}\n"
f"Existing recipe: {old.model_dump_json() if old else 'none'}"))
if old:
old.steps, old.successes, old.recent = new.steps, old.successes + 1, old.recent + [True]
return {"filed": old}
new.successes, new.recent = 1, [True]
RECIPES.append(new)
return {"filed": new}
graph = StateGraph(State)
graph.add_node("lookup", find_recipe)
graph.add_node("solver", solver)
graph.add_node("judge", judge)
graph.add_node("inducer", inducer)
graph.add_edge(START, "lookup")
graph.add_edge("lookup", "solver")
graph.add_edge("solver", "judge") # one attempt, one judgement
graph.add_conditional_edges("judge", solved, ["inducer", END]) # only a solved run may write
graph.add_edge("inducer", END)
app = graph.compile()
async def run(task: str):
s = await app.ainvoke({"task": task, "recipe": None, "run": None, "judgement": None, "filed": None})
return {"result": s["run"].result, "judgement": s["judgement"], "followed": s["recipe"], "filed": s["filed"]}
Persist RECIPES in a searchable store with embedding lookup, and give the solver the real tools its tasks need.
from typing import TypeVar
from claude_agent_sdk import AgentDefinition, ClaudeAgentOptions, ResultMessage, query
from pydantic import BaseModel
class Recipe(BaseModel):
family: str # the family of tasks it covers
steps: list[str] # three to eight general steps with blanks such as {customer}
successes: int = 0
recent: list[bool] = []
RECIPES: list[Recipe] = [] # the recipe store: one recipe per task family
def lookup(task: str) -> Recipe | None:
# plug in an embedding search over recipe families; returns the closest match or None
words = set(task.lower().split())
scored = [(len(words & set(r.family.lower().split())), r) for r in RECIPES]
best = max(scored, key=lambda s: s[0], default=(0, None))
return best[1] if best[0] > 0 else None
AGENTS = {
"solver": AgentDefinition(
description="Carries out a task, following a recipe where one is given.",
prompt="Carry out the task. If a recipe is given, follow its steps in order, filling each blank with "
"this task's details. If a step does not fit, say so and work it out. Report the result and "
"the steps you actually took."), # give it the tools the task needs
"judge": AgentDefinition(
description="Decides whether a task was solved.",
prompt="Decide whether the task was solved, from the task, the result and the steps taken. Answer "
"solved or not solved with one reason. When in doubt, answer not solved.", tools=[]),
"inducer": AgentDefinition(
description="Turns a solved run into a general recipe.",
prompt="From the solved run, write a recipe of three to eight general steps. Replace names, dates and "
"numbers with blanks such as {customer}. Drop steps that did not help. If a recipe for this "
"family exists, improve it instead of writing a second one.", tools=[]),
}
class Run(BaseModel):
result: str
steps_taken: list[str]
class Judgement(BaseModel):
solved: bool
reason: str
M = TypeVar("M", bound=BaseModel)
async def delegate(agent: str, payload: str, schema: type[M]) -> M:
# one fresh sub-agent run: it sees only the payload it is handed
options = ClaudeAgentOptions(
agents={agent: AGENTS[agent]}, allowed_tools=["Agent"],
output_format={"type": "json_schema", "schema": schema.model_json_schema()})
prompt = f"Hand exactly this input to the {agent} agent and return its result.\n\n{payload}"
async for msg in query(prompt=prompt, options=options):
if isinstance(msg, ResultMessage) and msg.structured_output:
return schema.model_validate(msg.structured_output)
raise RuntimeError(f"{agent} returned no result")
async def run(task: str):
recipe = lookup(task)
steps = "\n".join(recipe.steps) if recipe else "none"
done = await delegate("solver", f"Task: {task}\n\nRecipe:\n{steps}", Run) # one attempt
verdict = await delegate( # the judge never sees the recipe or the solver's reasoning
"judge", f"Task: {task}\nResult: {done.result}\nSteps taken: {done.steps_taken}", Judgement)
filed = None
if verdict.solved: # only a solved run may write, at most one recipe
existing = recipe.model_dump_json() if recipe else "none"
new = await delegate(
"inducer", f"Task: {task}\nSteps taken: {done.steps_taken}\nExisting recipe: {existing}", Recipe)
if recipe:
recipe.steps, recipe.successes, recipe.recent = new.steps, recipe.successes + 1, recipe.recent + [True]
filed = recipe
else:
filed = new.model_copy(update={"successes": 1, "recent": [True]})
RECIPES.append(filed)
elif recipe:
recipe.successes = max(0, recipe.successes - 1)
recipe.recent.append(False)
if recipe.recent[-3:] == [False] * 3: # drop a recipe whose last three uses all failed
RECIPES.remove(recipe)
return {"result": done.result, "judgement": verdict, "followed": recipe, "filed": filed}
Persist RECIPES in a searchable store with embedding lookup, and restrict the solver's tools to those its tasks need.
from agents import Agent, Runner
from pydantic import BaseModel
class Recipe(BaseModel):
family: str # the family of tasks it covers
steps: list[str] # three to eight general steps with blanks such as {customer}
successes: int = 0
recent: list[bool] = []
RECIPES: list[Recipe] = [] # the recipe store: one recipe per task family
def lookup(task: str) -> Recipe | None:
# plug in an embedding search over recipe families; returns the closest match or None
words = set(task.lower().split())
scored = [(len(words & set(r.family.lower().split())), r) for r in RECIPES]
best = max(scored, key=lambda s: s[0], default=(0, None))
return best[1] if best[0] > 0 else None
class Run(BaseModel):
result: str
steps_taken: list[str]
class Judgement(BaseModel):
solved: bool
reason: str
solver = Agent(
name="Solver",
instructions="Carry out the task. If a recipe is given, follow its steps in order, filling each blank with "
"this task's details. If a step does not fit, say so and work it out. Report the result and "
"the steps you actually took.",
output_type=Run) # add the tools the task needs
judge = Agent(
name="Judge",
instructions="Decide whether the task was solved, from the task, the result and the steps taken. Answer "
"solved or not solved with one reason. When in doubt, answer not solved.",
output_type=Judgement)
inducer = Agent(
name="Recipe writer",
instructions="From the solved run, write a recipe of three to eight general steps. Replace names, dates "
"and numbers with blanks such as {customer}. Drop steps that did not help. If a recipe for "
"this family exists, improve it instead of writing a second one.",
output_type=Recipe)
async def run(task: str):
recipe = lookup(task)
steps = "\n".join(recipe.steps) if recipe else "none"
done = (await Runner.run(solver, f"Task: {task}\n\nRecipe:\n{steps}")).final_output_as(Run) # one attempt
verdict = (await Runner.run( # the judge never sees the recipe or the solver's reasoning
judge, f"Task: {task}\nResult: {done.result}\nSteps taken: {done.steps_taken}")).final_output_as(Judgement)
filed = None
if verdict.solved: # only a solved run may write, at most one recipe
existing = recipe.model_dump_json() if recipe else "none"
new = (await Runner.run(inducer, f"Task: {task}\nSteps taken: {done.steps_taken}\n"
f"Existing recipe: {existing}")).final_output_as(Recipe)
if recipe:
recipe.steps, recipe.successes, recipe.recent = new.steps, recipe.successes + 1, recipe.recent + [True]
filed = recipe
else:
filed = new.model_copy(update={"successes": 1, "recent": [True]})
RECIPES.append(filed)
elif recipe:
recipe.successes = max(0, recipe.successes - 1)
recipe.recent.append(False)
if recipe.recent[-3:] == [False] * 3: # drop a recipe whose last three uses all failed
RECIPES.remove(recipe)
return {"result": done.result, "judgement": verdict, "followed": recipe, "filed": filed}
Persist RECIPES in a searchable store with embedding lookup, and give the solver the real tools its tasks need.
import { anthropic } from '@ai-sdk/anthropic';
import { generateText, Output } from 'ai';
import { z } from 'zod';
const model = anthropic('claude-sonnet-5-5');
type Recipe = { family: string; steps: string[]; successes: number; recent: boolean[] };
const RECIPES: Recipe[] = []; // the recipe store: one recipe per task family
// plug in an embedding search over recipe families; returns the closest match or undefined
function lookup(task: string): Recipe | undefined {
const words = new Set(task.toLowerCase().split(/\s+/));
const score = (r: Recipe) => r.family.toLowerCase().split(/\s+/).filter((w) => words.has(w)).length;
const best = [...RECIPES].sort((a, b) => score(b) - score(a))[0];
return best && score(best) > 0 ? best : undefined;
}
async function ask<T>(instructions: string, prompt: string, schema: z.ZodType<T>): Promise<T> {
const { output } = await generateText({ model, instructions, prompt, output: Output.object({ schema }) });
return output;
}
const Run = z.object({ result: z.string(), stepsTaken: z.array(z.string()) });
const Judgement = z.object({ solved: z.boolean(), reason: z.string() });
const NewRecipe = z.object({ family: z.string(), steps: z.array(z.string()) });
export async function run(task: string) {
const recipe = lookup(task);
// the solver sees the task and the closest recipe only; add the tools the task needs
const done = await ask(
'Carry out the task. If a recipe is given, follow its steps in order, filling each blank with this task\'s '
+ 'details. If a step does not fit, say so and work it out. Report the result and the steps you actually took.',
`Task: ${task}\n\nRecipe:\n${recipe?.steps.join('\n') ?? 'none'}`, Run);
// one judgement, in a fresh context: no recipe, no solver reasoning
const verdict = await ask(
'Decide whether the task was solved, from the task, the result and the steps taken. Answer solved or not '
+ 'solved with one reason. When in doubt, answer not solved.',
`Task: ${task}\nResult: ${done.result}\nSteps taken: ${done.stepsTaken.join('; ')}`, Judgement);
let filed: Recipe | undefined;
if (verdict.solved) { // only a solved run may write, at most one recipe
const next = await ask(
'From the solved run, write a recipe of three to eight general steps. Replace names, dates and numbers '
+ 'with blanks such as {customer}. Drop steps that did not help. If a recipe for this family exists, '
+ 'improve it instead of writing a second one.',
`Task: ${task}\nSteps taken: ${done.stepsTaken.join('; ')}\nExisting recipe: ${JSON.stringify(recipe ?? 'none')}`,
NewRecipe);
if (recipe) {
Object.assign(recipe, { steps: next.steps, successes: recipe.successes + 1, recent: [...recipe.recent, true] });
filed = recipe;
} else {
filed = { ...next, successes: 1, recent: [true] };
RECIPES.push(filed);
}
} else if (recipe) {
recipe.successes = Math.max(0, recipe.successes - 1);
recipe.recent.push(false);
if (recipe.recent.slice(-3).filter((ok) => !ok).length === 3) { // last three uses all failed: drop it
RECIPES.splice(RECIPES.indexOf(recipe), 1);
}
}
return { result: done.result, judgement: verdict, followed: recipe, filed };
}
Persist RECIPES in a searchable store with embedding lookup, and give the solver the real tools its tasks need.
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
- Recipes that keep specific names and numbers lead the next task to act on the wrong record. Generalise them.
- Filing recipes from unsolved tasks spreads mistakes. Only a solved run may write.
- A lenient judge is the fastest way to poison the store. Make it default to not solved.
Chain it
Its result can feed
- Reflection conditional
Condition: Only when the task asks for a written deliverable such as a report, message or document, not a short result or a record of actions carried out.
- Chain of Verification conditional
Condition: The result contains factual assertions to verify, rather than solely creative content, a hypothetical scenario, or a record of actions.
- Debate direct
Treat A's result as the existing answer to challenge on the original task, noting whether A's judge counted it as solved.
- Constitutional Critique direct
Treat A's result as the text to check rule by rule against the constitution, and revise only the rules it fails.
- Textual Backpropagation direct
Treat A's result as an existing answer to improve for the original task. Use the judge's solved flag and the recipe followed as context for the evaluator's critique, not as a certificate.
Source
- Wang et al., 2024. Agent Workflow Memory