Plan-and-execute agents and choosing an architecture
Overview
The workflow patterns introduced throughout this chapter solve different categories of AI engineering problems. Prompt chaining handles dependent transformations, routing selects specialized paths, parallelization accelerates independent operations, and evaluator–optimizer workflows improve generated artifacts through feedback.
However, some tasks require an agent to determine the necessary operations before execution begins and reconsider those operations as new information becomes available.
Consider the following request:
“Investigate why our checkout service is experiencing errors and prepare a technical incident report.”
The agent might initially decide to inspect application metrics, examine error logs, review recent deployments, and prepare a report.
During execution, the error logs might reveal database connection timeouts. The agent should then introduce a database investigation task, even though that task was absent from its original plan.
This is the plan-and-execute pattern: an architecture that separates strategic task decomposition from operational execution.
Unlike a fixed prompt chain, the exact sequence of tasks is not completely defined by the developer. Unlike a conventional tool-calling loop, the agent maintains an explicit representation of its intended future work.
Planning versus reactive execution
A conventional tool-calling agent repeatedly observes its current context and decides which tool to call next.
A plan-and-execute agent maintains a broader view of the objective by constructing an initial plan and updating that plan when necessary.
| Characteristic | Reactive tool-calling agent | Plan-and-execute agent |
|---|---|---|
| Decision horizon | Next action | Multiple future actions |
| Explicit plan | Optional | Central architectural component |
| Progress tracking | Often implicit in messages | Explicit task state |
| Adaptation | Selects another action | Revises remaining tasks |
| Planning overhead | Usually lower | Usually higher |
| Suitable problems | Short interactive tasks | Complex multi-stage objectives |
Reactive agents can also plan internally. The distinction is that plan-and-execute architectures expose the plan as application state that engineers can inspect, validate, persist, and control.
The previous lesson introduced reflection and self-correction. Replanning extends those ideas beyond improving an individual artifact: it changes the remaining work required to achieve an objective.
Environment setup
Install the dependencies used throughout this lesson.
pip install -U "langgraph>=1,<2" "langchain[openai]>=1,<2" "pydantic>=2,<3"Configure your API credentials.
export OPENAI_API_KEY="your-api-key"The examples use the course’s designated openai:gpt-5.4-mini model and current LangGraph 1.x and LangChain 1.x interfaces.
The model-backed examples require valid credentials and access to that model. The examples use illustrative local data and have not been live-tested against the model endpoint.
The building blocks
A plan-and-execute architecture normally contains four logical components.
| Component | Responsibility | Typical output |
|---|---|---|
| Planner | Decompose the objective | Initial task list |
| Executor | Perform the next task | Execution result |
| Replanner | Reassess remaining work | Updated task list or stop decision |
| Responder | Communicate the outcome | Final answer and completion status |
These components need not use separate models. They may share one model while using different prompts, schemas, tools, and operational permissions.
The following diagram illustrates the complete execution lifecycle.
Recording the execution result is commonly implemented inside the executor node rather than as a separate graph node.
Designing the state
An effective state schema separates the original objective, pending work, completed work, collected evidence, execution limits, and final response.
For example, an investigation agent might maintain:
objective: The user’s original request.pending: Tasks that have not yet been performed.results: Evidence collected from completed tasks.steps_taken: The number of executed tasks.status: Whether execution is running, completed, or incomplete.response: The final user-facing result.
Separating pending and completed tasks prevents the replanner from accidentally treating previously executed work as unfinished.
In a sequential graph, each executor invocation can return an updated task list and result collection. Ordinary state fields use replacement semantics unless a reducer is explicitly configured.
LangGraph’s graph topology remains fixed after compilation. Dynamic planning changes the data inside the graph and determines how often nodes execute; it does not require creating new graph nodes for every generated task.
See the official LangGraph Graph API documentation for state, reducers, and conditional control flow.
Planner
The planner transforms a high-level objective into smaller operations that the executor can actually perform.
An effective plan must be actionable, sufficiently complete, appropriately ordered, and compatible with the application’s available capabilities.
For the checkout incident, a reasonable initial plan might contain:
- Inspect checkout error metrics.
- Retrieve relevant application logs.
- Examine recent deployment activity.
Each task produces evidence needed to understand the incident.
Planning should not include imaginary capabilities such as accessing a database that the executor has no permission to query.
Structured planning
Free-form plans are readable by humans but inconvenient for reliable execution. Extracting numbered tasks from natural-language paragraphs introduces unnecessary parsing uncertainty.
Use structured output to represent plans as validated Python objects.
The following standalone example generates an ordered content preparation plan using a restricted set of available actions.
from typing import Literal
from pydantic import BaseModel
from langchain.chat_models import init_chat_model
from langchain.messages import SystemMessage, HumanMessage
model = init_chat_model("openai:gpt-5.4-mini")
Action = Literal["outline", "write", "review"]
class Task(BaseModel):
action: Action
instructions: str
class Plan(BaseModel):
tasks: list[Task]
planner = model.with_structured_output(Plan)
result = planner.invoke([
SystemMessage(
content=(
"Create a short ordered execution plan. "
"Use only the available actions. "
"Write content before reviewing it."
)
),
HumanMessage(
content="Prepare a beginner tutorial about Python decorators."
),
])
for index, task in enumerate(result.tasks, start=1):
print(index, task.action, task.instructions)Illustrative output:
1 outline Identify essential decorator concepts.
2 write Produce a tutorial with practical examples.
3 review Check clarity and technical correctness.The structured-output interface returns a Plan object containing individual Task objects.
The Literal type restricts action names, while application code should separately validate task ordering, maximum plan length, repeated operations, and authorization requirements.
A valid schema does not guarantee a useful plan. A model could produce an empty task list or arrange otherwise valid actions incorrectly.
Planning granularity
Tasks that are too broad are difficult to verify. Tasks that are too narrow create unnecessary scheduling and model overhead.
For example, “investigate the system” is too broad for a tightly controlled executor. Conversely, independently planning every arithmetic operation in a financial calculation is usually unnecessary.
Choose a task size that produces an observable result, has a clear purpose, and can be retried or inspected independently.
The planner should produce an operational task list, not a lengthy explanation of its internal reasoning.
Tip: Define the executor’s capabilities before designing the planner. A plan is useful only when its tasks correspond to operations the application can actually perform.
Executor
The executor performs the next pending task and records its outcome.
Its responsibilities are deliberately narrower than those of the planner. It should perform the assigned operation rather than independently redefine the overall objective.
An executor can be implemented using ordinary Python functions, REST clients, database queries, individual LLM invocations, tools, or a complete tool-calling agent.
Using a tool-calling agent as an executor
Some tasks require multiple local decisions. For example, a task instructing an executor to inspect an invoice might require retrieving the invoice, checking its payment status, and interpreting the returned data.
LangChain’s create_agent can provide this local autonomy while an outer LangGraph workflow retains control over the larger plan.
The following standalone example implements a specialized, read-only inventory executor.
from langchain.agents import create_agent
from langchain.chat_models import init_chat_model
from langchain.messages import HumanMessage
from langchain.tools import tool
model = init_chat_model("openai:gpt-5.4-mini")
@tool
def lookup_inventory(sku: str) -> str:
"""Retrieve available inventory for a product SKU."""
inventory = {
"KB-100": 25,
"MS-200": 0,
"HD-300": 12,
}
if sku not in inventory:
return f"Unknown SKU: {sku}"
return f"{sku}: {inventory[sku]} units available"
executor = create_agent(
model=model,
tools=[lookup_inventory],
system_prompt=(
"Execute the assigned inventory investigation task. "
"Use the inventory tool for factual stock information. "
"Do not invent quantities or modify inventory."
),
)
result = executor.invoke(
{
"messages": [
HumanMessage(
content="Check whether KB-100 and MS-200 are in stock."
)
]
},
config={"recursion_limit": 12},
)
print(result["messages"][-1].text)A typical response reports that KB-100 has 25 available units and MS-200 is out of stock.
The outer planning workflow can treat this agent as an executor and record its result in shared state.
For known operations, directly invoking trusted Python functions is often simpler and cheaper than introducing a nested tool-calling loop.
The LangChain agents documentation describes the current create_agent interface.
Replanner and responder
The replanner examines completed work and decides whether to continue the existing plan, change remaining tasks, or terminate execution.
Replanning may become necessary when a task produces unexpected findings, required information becomes unavailable, completed work makes another task unnecessary, or the original plan fails to satisfy the objective.
The responder is responsible for communicating the final result. It should distinguish verified findings from hypotheses and incomplete work.
Complete example: Adaptive incident investigation
This example combines an LLM-based planner and replanner with a deterministic executor.
The executor uses simulated monitoring data so the example requires no external observability platform. The application enforces mandatory evidence requirements independently of model decisions.
import json
from typing import Literal
from typing_extensions import TypedDict
from pydantic import BaseModel
from langchain.chat_models import init_chat_model
from langchain.messages import SystemMessage, HumanMessage
from langgraph.graph import StateGraph, START, END
model = init_chat_model("openai:gpt-5.4-mini")
Action = Literal["metrics", "logs", "deployments", "database"]
MAX_STEPS = 4
DATA: dict[Action, str] = {
"metrics": "Checkout error rate increased from 0.2% to 8.4%.",
"logs": "Repeated database connection pool timeout errors.",
"deployments": "No application deployments in the previous 24 hours.",
"database": "Database connection pool utilization reached 100%.",
}
class Plan(BaseModel):
pending: list[Action]
planning_model = model.with_structured_output(Plan)
class State(TypedDict):
objective: str
pending: list[Action]
results: dict[str, str]
history: list[Action]
steps_taken: int
status: str
response: str
def normalize(actions, completed):
return list(dict.fromkeys(
action for action in actions
if action in DATA and action not in completed
))
def required_actions(state: State) -> list[Action]:
required: list[Action] = ["metrics", "logs"]
if "pool timeout" in state["results"].get("logs", ""):
required.append("database")
return [
action for action in required
if action not in state["results"]
]
def planner(state: State):
plan = planning_model.invoke([
SystemMessage(
content=(
"Create an initial investigation plan. "
"Available checks: metrics, logs, deployments, database. "
"Begin with metrics and logs. Add other checks as needed."
)
),
HumanMessage(content=state["objective"]),
])
return {
"pending": normalize(
["metrics", "logs"] + plan.pending, []
),
"results": {},
"history": [],
"steps_taken": 0,
"status": "running",
"response": "",
}
def executor(state: State):
action = state["pending"][0]
return {
"results": {
**state["results"],
action: DATA[action],
},
"history": state["history"] + [action],
"pending": state["pending"][1:],
"steps_taken": state["steps_taken"] + 1,
}
def replanner(state: State):
missing = required_actions(state)
if state["steps_taken"] >= MAX_STEPS:
return {
"status": "incomplete" if missing else "completed",
"pending": missing,
}
decision = planning_model.invoke([
SystemMessage(
content=(
"Revise the remaining investigation plan using the "
"collected evidence. Do not repeat completed checks. "
"Add relevant missing checks. Return an empty pending "
"list when sufficient evidence has been collected."
)
),
HumanMessage(content=json.dumps({
"objective": state["objective"],
"remaining_plan": state["pending"],
"completed_results": state["results"],
"remaining_budget": MAX_STEPS - state["steps_taken"],
})),
])
pending = normalize(
missing + decision.pending,
state["history"],
)
return {
"pending": pending,
"status": "running" if pending else "completed",
}
def route(state: State) -> Literal["execute", "respond"]:
if (
not state["pending"]
or state["steps_taken"] >= MAX_STEPS
):
return "respond"
return "execute"
def responder(state: State):
response = model.invoke([
SystemMessage(
content=(
"Write a concise incident report based only on the "
"supplied evidence. Distinguish observations from "
"suspected causes. State investigation limitations. "
"Do not claim any remediation was performed."
)
),
HumanMessage(content=json.dumps({
"objective": state["objective"],
"status": state["status"],
"evidence": state["results"],
"missing_required_checks": required_actions(state),
})),
])
return {"response": response.text}
builder = StateGraph(State)
builder.add_node("planner", planner)
builder.add_node("executor", executor)
builder.add_node("replanner", replanner)
builder.add_node("responder", responder)
builder.add_edge(START, "planner")
builder.add_conditional_edges(
"planner",
route,
{"execute": "executor", "respond": "responder"},
)
builder.add_edge("executor", "replanner")
builder.add_conditional_edges(
"replanner",
route,
{"execute": "executor", "respond": "responder"},
)
builder.add_edge("responder", END)
graph = builder.compile()
result = graph.invoke(
{"objective": "Investigate checkout errors and prepare a report."},
config={"recursion_limit": 20},
)
print("Status:", result["status"])
print("Executed tasks:", result["history"])
print("Evidence:", result["results"])
print(result["response"])A possible execution produces:
Status: completed
Executed tasks: ['metrics', 'logs', 'database', 'deployments']
Checkout errors increased from 0.2% to 8.4%.
Database connection pool exhaustion is a likely contributing
factor, supported by timeout errors and 100% pool utilization.
No recent application deployment was identified.
Further investigation is required to establish the underlying cause.The exact execution order and report wording may vary.
Understanding the execution lifecycle
The planner initializes the task queue. The executor removes its first item, performs the corresponding lookup, and records the result.
The replanner receives both completed evidence and unfinished work. Once application logs reveal database connection timeouts, the deterministic required_actions() function ensures a database check is scheduled even if the model overlooks it.
The normalization function removes duplicate and completed tasks.
The conditional edge continues execution while pending tasks and sufficient budget remain.
Finally, the responder synthesizes available evidence without performing additional investigations.
Here, completed means the defined investigation requirements were satisfied. It does not mean the incident was resolved or its root cause conclusively established.
Note: Never allow an LLM’s declaration of completion to bypass mandatory business requirements. Application-level completion criteria must remain authoritative.
Dynamic task decomposition
Dynamic task decomposition occurs when the agent determines additional work during execution rather than exclusively during initialization.
Suppose an agent is preparing a comparison of software products. Its original plan includes collecting pricing, comparing functionality, and writing recommendations.
After discovering that one product has usage-based pricing, the agent might introduce additional tasks to estimate monthly consumption and calculate projected costs.
The original objective remains unchanged, but the operations required to achieve it evolve.
The following diagram illustrates how new evidence changes pending work.
Dependencies and task scheduling
A sequential list works when tasks must execute one at a time. More complex plans may represent each task using a unique identifier, action name, input parameters, dependencies, execution status, and result reference.
A task becomes eligible for execution only after its dependencies are satisfied.
Independent tasks may execute concurrently using LangGraph’s Send mechanism. This combines dynamic planning with the orchestrator–worker pattern introduced earlier in the chapter.
A planner should not automatically parallelize every task. Operations requiring shared mutable resources, ordered side effects, or upstream evidence may need sequential execution.
Preventing unproductive replanning
Repeated replanning can consume significant resources without advancing the objective.
Common causes include repeatedly scheduling failed tasks, generating equivalent tasks under different descriptions, losing completed-task history, and failing to define completion criteria.
Prevent these problems using stable task identifiers, duplicate detection, bounded retries, progress measurements, and explicit execution budgets.
LangGraph’s recursion_limit provides an additional safeguard against excessive graph execution. It measures graph super-steps, not completed business tasks or actual model calls.
Maintain separate application-level limits for task executions, model invocations, token consumption, elapsed time, and expensive external operations where appropriate.
When limits are reached, return an explicit incomplete result rather than presenting partial work as successful.
Selecting the appropriate architecture
Production AI engineering is not about maximizing agent autonomy. It is about achieving the required outcome with acceptable reliability, cost, latency, and operational risk.
The simplest architecture that consistently satisfies the requirements is usually the strongest starting point.
Architecture comparison
| Pattern | Best suited for | Main limitation |
|---|---|---|
| Single LLM call | Straightforward generation or extraction | Limited process control |
| Prompt chaining | Predictable dependent transformations | Sequential latency |
| Routing | Classification into specialized paths | Misclassification risk |
| Parallelization | Independent, predefined operations | Aggregation complexity |
| Orchestrator–worker | Dynamically determined subtasks | Coordination overhead |
| Evaluator–optimizer | Iterative artifact improvement | Repeated evaluation costs |
| Reactive tool-calling agent | Flexible tool selection | Unpredictable execution paths |
| Plan-and-execute | Adaptive multi-stage objectives | Planning and replanning overhead |
| Multi-agent architecture | Distinct specialist contexts or responsibilities | Communication and coordination complexity |
These patterns are composable rather than mutually exclusive.
For additional examples, consult the official LangGraph workflows and agents guide.
A practical selection framework
Evaluate five dimensions before selecting an architecture:
- Task predictability: Can developers define the required operations in advance?
- Dependencies: Must operations execute sequentially, or can they run independently?
- Quality requirements: Is one generation sufficient, or is evaluation necessary?
- Environmental uncertainty: Will new information change the required operations?
- Operational consequences: Could incorrect decisions cause financial, security, or business harm?
For example, invoice field extraction generally needs structured output and validation rather than a planning agent.
A support chatbot may need routing and specialized retrieval.
A comprehensive incident investigation may justify plan-and-execute because its next tasks depend on newly discovered evidence.
An action that modifies production infrastructure additionally needs trusted authorization and appropriate approval controls regardless of the underlying agent architecture.
Cost and latency trade-offs
Consider a plan-and-execute workflow with four executed tasks, one initial planning call, four replanning calls, and one final response call.
If every executor task also invokes a model, the workflow requires ten model calls before accounting for retries.
If the executor performs deterministic lookups instead, only six model calls are necessary.
Replan only when the additional reasoning provides meaningful value. Predictable operations can continue without invoking the replanner after every task, provided the application still checks completion and safety requirements.
Production engineering considerations
Persistence and recovery
Long-running planning workflows benefit from checkpointing. Store the pending plan, completed results, execution counters, and status so interrupted runs can resume without unnecessarily repeating completed work.
Use durable checkpointers such as PostgresSaver or AsyncPostgresSaver for production deployments.
External side effects must still be idempotent. Checkpointing alone cannot guarantee that an external payment, email, or database mutation executes exactly once.
Testing and observability
Evaluate planner validity, task execution correctness, replanning effectiveness, and final response quality independently.
Important production metrics include task completion rates, unnecessary task rates, repeated operations, budget exhaustion, final answer accuracy, and cost per successful request.
Use LangSmith tracing to inspect individual decisions and identify whether failures originate from planning, execution, or replanning.
Planning models should also be tested against unsupported objectives, contradictory evidence, unavailable tools, and attempts to manipulate task instructions.
Connecting to the chapter project
The self-evaluating content-generation agent combines several patterns from this chapter.
Routing selects an appropriate content format. Prompt chaining establishes dependent preparation and generation stages. An evaluator checks the generated artifact, while controlled replanning introduces additional work when feedback reveals missing requirements.
For straightforward content requests, a bounded evaluator–optimizer workflow may be sufficient. More complex requests involving multiple deliverables, research dependencies, and changing requirements may justify explicit plan-and-execute orchestration.
The next lesson, Multi-agent architectures, extends this approach by distributing responsibilities across specialized agents. You will examine how agents collaborate, delegate work, maintain distinct contexts, and coordinate execution while preserving clear ownership and control boundaries.
Build an Adaptive Content Generation Agent
Build a plan-and-execute content generation agent that creates an initial task plan based on a user's content brief. Execute planning and writing tasks individually, evaluate the resulting draft, and dynamically schedule revision tasks when quality requirements are not satisfied. Maintain execution history, enforce a maximum step budget, and return an explicit completion status without allowing indefinite revision cycles.
from typing import Literal
from typing_extensions import TypedDict
from pydantic import BaseModel
from langchain.chat_models import init_chat_model
from langchain.messages import SystemMessage, HumanMessage
from langgraph.graph import StateGraph, START, END
model = init_chat_model("openai:gpt-5.4-mini")
Action = Literal["outline", "draft", "evaluate", "revise"]
MAX_STEPS = 8
class Plan(BaseModel):
steps: list[Literal["outline", "draft"]]
class Review(BaseModel):
passed: bool
feedback: str
class State(TypedDict):
brief: str
pending: list[Action]
history: list[str]
outline: str
draft: str
feedback: str
approved: bool
steps_taken: int
status: str
output: str
# TODO: Create structured-output planning and evaluation models.
# TODO: Implement a planner that creates the initial task list.
# TODO: Implement an executor that handles one pending action.
# TODO: Implement a replanner that schedules evaluation and revision.
# TODO: Implement a routing function with a maximum step budget.
# TODO: Implement a responder that distinguishes approved and incomplete work.
# TODO: Compile the graph and invoke it with a content brief.from typing import Literal
from typing_extensions import TypedDict
from pydantic import BaseModel
from langchain.chat_models import init_chat_model
from langchain.messages import SystemMessage, HumanMessage
from langgraph.graph import StateGraph, START, END
model = init_chat_model("openai:gpt-5.4-mini")
Action = Literal["outline", "draft", "evaluate", "revise"]
MAX_STEPS = 8
class Plan(BaseModel):
steps: list[Literal["outline", "draft"]]
class Review(BaseModel):
passed: bool
feedback: str
planning_model = model.with_structured_output(Plan)
evaluation_model = model.with_structured_output(Review)
class State(TypedDict):
brief: str
pending: list[Action]
history: list[str]
outline: str
draft: str
feedback: str
approved: bool
steps_taken: int
status: str
output: str
def generate(instructions: str, content: str) -> str:
response = model.invoke([
SystemMessage(content=instructions),
HumanMessage(content=content),
])
return response.text
def planner(state: State):
plan = planning_model.invoke([
SystemMessage(
content=(
"Plan the requested content. Available actions are "
"outline and draft. Use outline before draft for "
"complex requests. For simple requests, draft directly."
)
),
HumanMessage(content=state["brief"]),
])
pending: list[Action] = (
["outline", "draft"] if "outline" in plan.steps else ["draft"]
)
return {
"pending": pending,
"history": [],
"outline": "",
"draft": "",
"feedback": "",
"approved": False,
"steps_taken": 0,
"status": "running",
"output": "",
}
def executor(state: State):
action = state["pending"][0]
updates = {
"pending": state["pending"][1:],
"history": state["history"] + [action],
"steps_taken": state["steps_taken"] + 1,
}
if action == "outline":
updates["outline"] = generate(
"Create a concise content outline.",
state["brief"],
)
elif action == "draft":
updates["draft"] = generate(
"Write the requested content in 80-180 words. "
"Use the supplied outline if one exists.",
f"Brief:\n{state['brief']}\nOutline:\n{state['outline']}",
)
updates["approved"] = False
elif action == "evaluate":
review = evaluation_model.invoke([
SystemMessage(
content=(
"Evaluate the draft for relevance, clarity, factual "
"caution, and compliance with the brief. Provide "
"specific feedback. Pass only acceptable drafts."
)
),
HumanMessage(
content=(
f"Brief:\n{state['brief']}\nDraft:\n{state['draft']}"
)
),
])
count = len(state["draft"].split())
length_ok = 80 <= count <= 180
updates["approved"] = review.passed and length_ok
updates["feedback"] = (
review.feedback
+ f" Word count: {count}; required range: 80-180."
)
elif action == "revise":
updates["draft"] = generate(
"Revise the draft according to the feedback. "
"Preserve the brief's requirements. Use 80-180 words.",
f"Brief:\n{state['brief']}\n"
f"Draft:\n{state['draft']}\n"
f"Feedback:\n{state['feedback']}",
)
updates["approved"] = False
return updates
def replanner(state: State):
last_action = state["history"][-1]
if state["approved"]:
return {"pending": [], "status": "approved"}
if state["steps_taken"] >= MAX_STEPS:
return {"status": "budget_exhausted"}
if last_action in ("draft", "revise"):
return {"pending": ["evaluate"]}
if last_action == "evaluate":
return {"pending": ["revise", "evaluate"]}
return {}
def route(state: State) -> Literal["execute", "respond"]:
if (
state["approved"]
or state["steps_taken"] >= MAX_STEPS
or not state["pending"]
):
return "respond"
return "execute"
def responder(state: State):
if state["approved"]:
return {
"status": "approved",
"output": state["draft"],
}
return {
"status": (
"budget_exhausted"
if state["steps_taken"] >= MAX_STEPS
else "incomplete"
),
"output": "",
}
builder = StateGraph(State)
builder.add_node("planner", planner)
builder.add_node("executor", executor)
builder.add_node("replanner", replanner)
builder.add_node("responder", responder)
builder.add_edge(START, "planner")
builder.add_conditional_edges(
"planner",
route,
{"execute": "executor", "respond": "responder"},
)
builder.add_edge("executor", "replanner")
builder.add_conditional_edges(
"replanner",
route,
{"execute": "executor", "respond": "responder"},
)
builder.add_edge("responder", END)
graph = builder.compile()
result = graph.invoke(
{
"brief": (
"Write a beginner-friendly article explaining why "
"Python developers should use automated testing."
)
},
config={"recursion_limit": 30},
)
print("Status:", result["status"])
print("Execution history:", result["history"])
print("Steps taken:", result["steps_taken"])
if result["approved"]:
print(result["output"])
else:
print("No approved content was produced.")
print("Latest feedback:", result["feedback"])Summary
- Plan-and-execute agents separate high-level task planning from individual task execution.
- A planner converts a user objective into an ordered collection of actionable and appropriately constrained tasks.
- An executor performs individual tasks and records their outcomes as evidence for subsequent decisions.
- A replanner updates unfinished work based on execution results, unexpected conditions, and remaining requirements.
- Dynamic task decomposition allows agents to introduce, remove, replace, or reorder subtasks during execution.
- Explicit completion criteria, execution budgets, and trusted authorization checks prevent uncontrolled agent behavior.
- Architecture selection should balance task uncertainty, dependencies, quality requirements, operational risk, latency, and cost.