Skip to content

API Reference parrot.bots.flows.core.context

github-actions[bot] edited this page Dec 2, 2026 · 4 revisions

parrot.bots.flows.core.context

View source

Flow Primitives — FlowContext.

Shared workflow execution state tracker used by both AgentCrew and AgentsFlow orchestration engines.

Extracted from parrot.bots.orchestration.crew.FlowContext with node-centric renaming and backward-compat aliases.

Backward-compat aliases (forwarded to the primary methods): agent_metadata — property alias for node_metadata. get_input_for_agent() — alias for get_input_for_node().

Alias AgentLike

Re-exported from parrot.bots.flows.core.types.AgentLike.

Class AgentNotFoundError

Raised when FlowContext.resolve_agent cannot find the requested agent.

Inherits from LookupError so callers can catch it with either except AgentNotFoundError: (specific) or except LookupError: (generic lookup failure).

Alias AgentRef

Re-exported from parrot.bots.flows.core.types.AgentRef.

Alias AgentRegistry

Re-exported from parrot.registry.registry.AgentRegistry.

Alias ContextSnapshot

Re-exported from parrot.bots.flows.core.checkpoint.model.ContextSnapshot.

Class FlowContext

Execution state tracker for a single flow/crew run.

Tracks which nodes have completed, their results and responses, and metadata for each node's execution. Provides helpers to determine whether a node's dependencies are satisfied and to build its input payload.

Primary field: node_metadata (was agent_metadata in parrot.bots.orchestration.crew.FlowContext). The old name is kept as a @property alias for backward compatibility.

Parameter Type Default Description
initial_task str The initial prompt/task string given to the flow.
results Dict[str, Any] dict()
responses Dict[str, Any] dict()
node_metadata Dict[str, NodeExecutionInfo] dict()
completion_order List[str] list()
errors Dict[str, Exception] dict()
active_tasks Set[str] set()
completed_tasks Set[str] set()
shared_data Dict[str, Any] dict()
agent_registry Optional['AgentRegistry'] None
synthesis_client Optional[Any] None
trace_context Optional['TraceContext'] None
blackboard Optional[Any] None

Fields:

Field Type Default Description
initial_task str
results Dict[str, Any] field(default_factory=dict) Mapping of node_id → extracted result value.
responses Dict[str, Any] field(default_factory=dict) Mapping of node_id → raw response object.
node_metadata Dict[str, NodeExecutionInfo] field(default_factory=dict) Mapping of node_id → execution metadata (primary field).
completion_order List[str] field(default_factory=list) Ordered list of node_ids as they completed.
errors Dict[str, Exception] field(default_factory=dict) Mapping of node_id → exception raised during execution.
active_tasks Set[str] field(default_factory=set) Set of node_ids currently executing.
completed_tasks Set[str] field(default_factory=set) Set of node_ids that have successfully completed.
shared_data Dict[str, Any] field(default_factory=dict) Arbitrary key-value data shared across all nodes (replaces AgentContext.shared_data).
agent_registry Optional['AgentRegistry'] field(default=None) Optional AgentRegistry bound to this context for agent resolution. Set by AgentsFlow.from_definition() (FEAT-163) and available to any code that needs to resolve an agent_ref string at runtime.
synthesis_client Optional[Any] field(default=None) Optional LLM client used by synthesize_results (FEAT-163 TASK-1063). Any AbstractClient-compatible instance that exposes ask(prompt=...). If None, calling synthesize_results(ctx, result) raises a RuntimeError.
trace_context Optional['TraceContext'] field(default=None) W3C TraceContext for this run (FEAT-176 Phase 1.5). Seeded by the caller, or lazily created (root span) by FlowLifecycleAdapter on the first event of the run. Nodes and the code they invoke can read it to stitch their own spans (client/tool lifecycle events) onto the flow's trace.
blackboard Optional[Any] field(default=None, repr=False) Optional Roost Blackboard binding (FEAT-747). Not part of to_snapshot(); shared_data is unchanged.

Attributes:

Attribute Type Description
agent_metadata Dict[str, NodeExecutionInfo] Alias for node_metadata (backward compat with crew.FlowContext).

Method FlowContext.resolve_agent

Resolve an agent reference to a live agent instance.

If agent_ref is already an AgentLike (not a string), return it unchanged. If it is a string, look it up in the bound agent_registry and return the result.

resolve_agent(agent_ref: AgentRef) -> AgentLike

Parameter Type Default Description
agent_ref AgentRef Either an AgentLike instance (returned as-is) or a string agent name looked up via the registry.

Returns: AgentLike — The resolved AgentLike agent.

Raises:

  • AgentNotFoundError — If agent_ref is a string and cannot be found in the registry, or if no registry is bound to this context.

Method FlowContext.can_execute

Return True if all dependencies are in completed_tasks.

can_execute(_node_id: str, dependencies: Set[str]) -> bool

Parameter Type Default Description
_node_id str The node being evaluated (unused; kept for API symmetry).
dependencies Set[str] Set of node_ids that must complete first.

Returns: bool — True when all dependencies are satisfied.

Method FlowContext.mark_completed

Record that a node has completed and store its outputs.

Updates completed_tasks, completion_order, and removes node_id from active_tasks. Stores result, response, and metadata if not None.

mark_completed(node_id: str, result: Any = None, response: Any = None, metadata: Optional[NodeExecutionInfo] = None) -> None

Parameter Type Default Description
node_id str The completed node's unique identifier.
result Any None Extracted output value (stored in self.results).
response Any None Raw response object (stored in self.responses).
metadata Optional[NodeExecutionInfo] None Execution metadata (stored in self.node_metadata).

Method FlowContext.reset_completed

Remove invalidated retry-loop nodes from recoverable state.

Used by a bounded back-edge (repair/retry loop) reset: when a cyclic edge fires and re-enters the loop, every node on the cycle must leave both the scheduler's local state (handled by the scheduler itself) AND this context's recoverable state — otherwise a checkpoint taken after the reset would still show the invalidated nodes as completed, and a resumed run would restore stale completions instead of requesting the next repair attempt (spec §2 Overview, §7 "Retry-safe snapshot").

Removes node_id from completed_tasks/completion_order/ active_tasks/results/responses/node_metadata/ errors for every id in node_ids. A no-op for any id that was never completed.

reset_completed(node_ids: Set[str]) -> None

Parameter Type Default Description
node_ids Set[str] The node ids to invalidate (the back-edge's cycle members, target through source inclusive).

Method FlowContext.mark_failed

Record that a node has failed and store the error.

Removes node_id from active_tasks and writes the exception into errors. Optionally stores execution metadata in node_metadata.

mark_failed(node_id: str, error: Exception, metadata: Optional[NodeExecutionInfo] = None) -> None

Parameter Type Default Description
node_id str The failed node's unique identifier.
error Exception The exception raised during execution.
metadata Optional[NodeExecutionInfo] None Optional execution metadata (stored in self.node_metadata).

Method FlowContext.get_input_for_node

Prepare the input payload for a node.

If the node has no dependencies the payload contains only the initial_task. Otherwise it also includes a dependencies dict with each dependency's result (if available).

get_input_for_node(node_id: str, dependencies: Set[str]) -> Dict[str, Any]

Parameter Type Default Description
node_id str The target node's identifier (unused but kept for symmetry).
dependencies Set[str] Set of node_ids whose results should be included.

Returns: Dict[str, Any] — Dict with keys "task" and optionally "dependencies".

Method FlowContext.to_snapshot

Serialize this context into a ContextSnapshot for checkpointing.

Excludes agent_registry/synthesis_client/trace_context — they are not serializable and are re-bound/re-seeded by AgentsFlow.resume(). errors (live Exception instances) are encoded as structured {type, message, repr} dicts, never reconstructed as exception objects.

to_snapshot(*, serializer: 'FlowStateSerializer', include_responses: bool = False, lossy_out: Optional[list] = None) -> 'ContextSnapshot'

Parameter Type Default Description
serializer 'FlowStateSerializer' FlowStateSerializer used to make results/ responses JSON-safe (registered types round-trip via the type registry; unregistered values degrade to a lossy tagged repr instead of failing).
include_responses bool False When True, raw responses are also captured (heavy; results-only by default, spec resolved OQ2).
lossy_out Optional[list] None Optional output list — if provided, True/False is appended reporting whether results/responses degraded any value to a lossy tagged repr. Backward-compatible opt-in (added post-review, FEAT-399): callers that need the lossy signal (e.g. FlowCheckpointer._build_checkpoint(), which embeds it in FlowCheckpoint.lossy) pass a list to receive it without changing this method's return type for existing callers.

Returns: 'ContextSnapshot' — A ContextSnapshot capturing this context's serializable state.

Method FlowContext.get_input_for_agent

Alias for get_input_for_node() (backward compat with crew.FlowContext).

get_input_for_agent(agent_name: str, dependencies: Set[str]) -> Dict[str, Any]

Parameter Type Default Description
agent_name str Forwarded as node_id to the primary method.
dependencies Set[str] Forwarded unchanged.

Returns: Dict[str, Any] — Same as get_input_for_node().

Alias FlowStateSerializer

Re-exported from parrot.bots.flows.core.checkpoint.serializer.FlowStateSerializer.

Alias NodeExecutionInfo

Re-exported from parrot.bots.flows.core.result.NodeExecutionInfo.

Alias TraceContext

Re-exported from parrot.core.events.lifecycle.TraceContext.

Architecture

Clients

Bots & Agents

Memory

Knowledge

Tools & Toolkits

Flows

Experts

Skills

Stores & Loaders

MCP & A2A

Server & APIs

Integrations

Outputs & A2UI

Prompts

Security

Operations

Migration

SDD Tooling

LLM Wiki

Deployment

Decisions

API Reference

Clone this wiki locally