flows

Pipecat Flows - Structured conversation framework for Pipecat.

This package provides a framework for building structured conversations in Pipecat. The FlowManager handles conversation flows with support for state management, function calling, and cross-provider compatibility.

Pipecat Flows determines conversation structure at runtime, supporting function calling, action execution, and seamless transitions between conversation states.

class pipecat.flows.FlowManager(*, llm: LLMService | LLMSwitcher, context_aggregator: Any, worker: PipelineWorker | None = None, task: PipelineWorker | None = None, context_strategy: ContextStrategyConfig | None = None, transport: BaseTransport | None = None, global_functions: list[FlowsFunctionSchema | Callable[[...], Awaitable[tuple[Any, NodeConfig | None | _NoResponse]]]] | None = None)[source]

Bases: object

Manages conversation flows.

The FlowManager orchestrates conversation flows by managing state transitions, function registration, and message handling across different LLM providers, with comprehensive action handling and error management.

The manager coordinates all aspects of a conversation including LLM context management, function registration, state transitions, and action execution.

A node’s prompts may refer to state with {{ key }} placeholders, in role_message, task_messages content, and tts_say text. They are filled in each time the node is entered, so a value a handler stored earlier in the conversation can appear in a later prompt, including after a context reset. {{ order.size }} walks into a stored mapping, a key that is missing raises FlowError on entry, and \{{ key }} is left as the literal {{ key }}.

__init__(*, llm: LLMService | LLMSwitcher, context_aggregator: Any, worker: PipelineWorker | None = None, task: PipelineWorker | None = None, context_strategy: ContextStrategyConfig | None = None, transport: BaseTransport | None = None, global_functions: list[FlowsFunctionSchema | Callable[[...], Awaitable[tuple[Any, NodeConfig | None | _NoResponse]]]] | None = None)[source]

Initialize the flow manager.

Parameters:
  • llm – LLM service or LLMSwitcher.

  • context_aggregator – Context aggregator for updating user context.

  • worker – PipelineWorker instance for queueing frames.

  • task –

    PipelineWorker instance for queueing frames.

    Deprecated since version 1.5.0: Use worker instead. Will be removed in 2.0.0.

  • context_strategy – Context strategy configuration for managing conversation context during transitions.

  • transport – Transport instance for communication.

  • global_functions – Optional list of FlowsFunctionSchemas or FlowsDirectFunctions that will be available at every node. These functions are registered once during initialization and automatically included alongside node-specific functions.

property state: dict[str, Any]

Access the shared state dictionary across nodes.

This property provides access to a persistent dictionary that maintains data across node transitions. It can be used to store and retrieve conversation state, user preferences, or any other data that needs to persist throughout the flow.

Returns:

The shared state dictionary that can be used for

reading and writing state data.

Return type:

Dict[str, Any]

Examples

Setting state:

flow_manager.state["user_name"] = "Alice"
flow_manager.state["age"] = 25

Getting state:

name = flow_manager.state.get("user_name", "Unknown")
age = flow_manager.state["age"]

Checking for state:

if "user_preferences" in flow_manager.state:
    preferences = flow_manager.state["user_preferences"]
property transport: BaseTransport | None

Access the transport instance used for communication.

This property provides access to the transport instance that handles communication with the client (e.g., DailyTransport for Daily rooms). The transport can be used to interact with participants, manage audio/video settings, or access platform-specific features.

Returns:

The transport instance if provided during

initialization, None otherwise.

Return type:

Optional[BaseTransport]

Examples

Accessing transport in action handlers:

async def mute_participant(action: dict, flow_manager: FlowManager):
    transport = flow_manager.transport
    if transport and hasattr(transport, 'update_participant'):
        await transport.update_participant(participant_id, {"canSnd": False})

Working with Daily transport features:

async def get_room_info(action: dict, flow_manager: FlowManager):
    transport = flow_manager.transport
    if isinstance(transport, DailyTransport):
        participants = transport.participants()
        return {"participant_count": len(participants)}
property current_node: str | None

Access the identifier of the currently active conversation node.

This property provides access to the current node name/identifier in the conversation flow. It can be used to make decisions based on the current state of the conversation, implement conditional logic, or for debugging and logging purposes.

Returns:

The identifier of the current node if a node is active,

None if no node has been set or before initialization.

Return type:

Optional[str]

Examples

Conditional logic based on current node:

async def participant_joined(action: dict, flow_manager: FlowManager):
    current = flow_manager.current_node
    if current == "transferring_to_human_agent":
        await start_human_agent_interaction(flow_manager)
    elif current == "collecting_payment":
        await setup_secure_session(flow_manager)

Logging and debugging:

async def log_conversation_state(action: dict, flow_manager: FlowManager):
    node = flow_manager.current_node
    logger.info(f"Current conversation node: {node}")
    return {"current_node": node}
property worker: PipelineWorker

Access the pipeline worker instance for frame queueing.

This property provides access to the PipelineWorker instance used by the FlowManager. The worker can be used to queue custom frames directly into the pipeline, enabling advanced flow control and custom frame injection.

Returns:

The pipeline worker instance used for frame processing and queueing operations.

Examples

Queueing frames in handlers:

async def send_custom_notification(action: dict, flow_manager: FlowManager):
    from pipecat.frames.frames import TTSUpdateSettingsFrame

    # Queue a TTS settings update frame
    await flow_manager.worker.queue_frame(
        TTSUpdateSettingsFrame(settings={"voice": "your-new-voice-id"})
    )
property task: PipelineWorker

Access the pipeline worker instance for frame queueing.

Deprecated since version 1.5.0: Use worker instead. Will be removed in 2.0.0.

Returns:

The pipeline worker instance used for frame processing and queueing operations.

async initialize(initial_node: NodeConfig | None = None) → None[source]

Initialize the flow manager.

Parameters:

initial_node – Optional initial node configuration. If provided, the flow will start at this node immediately.

Raises:

FlowInitializationError – If initialization fails.

Examples

Initialize with an initial node:

flow_manager = FlowManager(
    ... # Initialization parameters
)
await flow_manager.initialize(create_initial_node())

Initialize without an initial node (set later via set_node_from_config):

flow_manager = FlowManager(
    ... # Initialization parameters
)
await flow_manager.initialize()
get_current_context() → list[dict][source]

Get the current conversation context.

Returns:

List of messages in the current context, including system messages, user messages, and assistant responses.

Raises:

FlowError – If context aggregator is not available.

register_action(action_type: str, handler: Callable) → None[source]

Register a handler for a specific action type.

Parameters:
  • action_type – String identifier for the action (e.g., “tts_say”).

  • handler – Async or sync function that handles the action.

Example:

async def custom_notification(action: dict):
    text = action.get("text", "")
    await notify_user(text)

flow_manager.register_action("notify", custom_notification)
async set_node_from_config(node_config: NodeConfig) → None[source]

Set up a new conversation node and transition to it.

Used to manually transition between nodes in a flow.

Parameters:

node_config – Configuration for the new node.

Raises:
class pipecat.flows.FlowConfig(*, initial_node: str, nodes: ~typing.Annotated[dict[str, ~pipecat.flows.config.FlowConfig.Node], ~annotated_types.MinLen(min_length=1)], global_functions: list[~pipecat.flows.config.FlowConfig.Function] = <factory>)[source]

Bases: BaseModel

A conversation flow described as data.

Load one with from_file() for a YAML or JSON file, from_yaml() for YAML text, from_json() for JSON text, or Pydantic’s model_validate for a dict that is already parsed.

!include resolves paths on the application’s file system and can read any file the process can read, so it belongs only in configs the application ships. Load a config from another source, such as a request body, with from_yaml() and no base_dir, which rejects !include, or with from_json().

Prompt text may refer to the manager’s state with {{ key }} placeholders: a node’s role_message, the content of its task_messages, and the text of a tts_say action. FlowManager fills them from flow_manager.state each time it enters the node, so a value stored by a handler earlier in the conversation can appear in a later prompt. {{ order.size }} walks into a stored mapping, and values are rendered with str(). A key that is not in state raises FlowError when the node is entered. To show the LLM a literal {{ key }}, escape it as \{{ key }}.

Parameters:
  • initial_node – Name of the node the flow starts in.

  • nodes – The flow’s nodes, keyed by name.

  • global_functions – Tools offered at every node.

class Message(*, role: str, content: str)[source]

Bases: BaseModel

One message in a node’s task_messages.

Parameters:
  • role – Message role, e.g. developer or system.

  • content – Message text. May contain {{ key }} placeholders; see FlowConfig.

role: str
content: str
class Branch(*, field: str, cases: Annotated[dict[str, str], MinLen(min_length=1)], default: str | None = None)[source]

Bases: BaseModel

A transition chosen by a field of the tool’s result.

Parameters:
  • field – Key of the tool’s result whose value selects the case.

  • cases – Result value to node name. Keys may be written as strings, booleans, or numbers; they match the result value by its canonical string (see case_key()), so true: matches a result of True.

  • default – Node to transition to when the value matches no case. When omitted, an unmatched value stays on the current node.

field: str
cases: dict[str, str]
default: str | None
targets() → list[str][source]

Every node name this branch can transition to.

class Function(**data: Any)[source]

Bases: BaseModel

A tool offered at a node.

Ordinarily the entry names a Flows direct function in the handlers a Flow is constructed with, and the tool’s description and parameters come from that function. A transition_only entry is defined entirely here instead: it takes no parameters, runs no code, and moves the conversation to transition_to when the LLM calls it.

Parameters:
  • name – The tool’s name, as the LLM sees it. For an ordinary entry, also the name of the direct function in the handlers.

  • transition_only – Whether the tool is defined here rather than in code. Requires description and a transition_to that names a node.

  • description – What the tool is for, for the LLM. Only a transition_only entry has one; a direct function describes itself in its docstring.

  • transition_to – Node to transition to after the tool completes, or a FlowConfig.Branch. Omitted for tools that stay on the current node.

name: str
transition_only: bool
description: str | None
transition_to: str | Branch | None
targets() → list[str][source]

Every node name this function can transition to.

class Action(*, type: str, handler: str | None = None, **extra_data: Any)[source]

Bases: BaseModel

A pre- or post-action on a node.

The built-in tts_say and end_conversation types take no handler. The built-in function type requires one: the handler runs inline in the pipeline, queued behind the bot’s turn. A custom type may name a handler too, which then runs immediately when the node’s actions execute; a custom type without one must be registered in code with FlowManager.register_action. Any additional keys pass through to the handler. The text of a tts_say action may contain {{ key }} placeholders; see FlowConfig.

Parameters:
  • type – Action type identifier.

  • handler – Name of the handler in the handlers a Flow is constructed with. Required for function, optional for custom types, not allowed on tts_say or end_conversation.

type: str
handler: str | None
property registered_in_code: bool

Whether this is a custom type whose handler the config does not name.

extras() → dict[str, Any][source]

The pass-through keys beyond type and handler.

class Node(**data: Any)[source]

Bases: BaseModel

One node of the flow.

Parameters:
  • task_messages – What the LLM should do at this node.

  • role_message – The bot’s role or personality, sent as the LLM’s system instruction on entering this node. It persists across transitions until another node sets its own. May contain {{ key }} placeholders; see FlowConfig.

  • functions – Tools offered at this node, in addition to the config’s global_functions.

  • pre_actions – Actions run before the LLM responds at this node.

  • post_actions – Actions run after the LLM responds at this node.

  • context_strategy – How the LLM context is updated on entering this node. Defaults to the FlowManager’s strategy.

  • respond_immediately – Whether the LLM responds as soon as the node is entered. Defaults to True.

task_messages: list[Message]
role_message: str | None
functions: list[Function]
pre_actions: list[Action]
post_actions: list[Action]
context_strategy: Literal['append', 'reset'] | None
respond_immediately: bool
context_strategy_enum() → ContextStrategy | None[source]

The node’s context_strategy as a ContextStrategy.

classmethod from_yaml(text: str, *, base_dir: Path | None = None) → FlowConfig[source]

Load a config from YAML text.

Parameters:
  • text – The YAML document.

  • base_dir – Directory that !include paths resolve against. When omitted, !include is unavailable. An include can read any file the process can read, so omit base_dir for text from an untrusted source.

Returns:

The validated config.

classmethod from_json(text: str) → FlowConfig[source]

Load a config from JSON text.

Parameters:

text – The JSON document.

Returns:

The validated config.

classmethod from_file(path: str | Path) → FlowConfig[source]

Load a config from a .yaml, .yml, or .json file.

YAML files may use !include with paths relative to the file’s directory. Included paths are not confined to that directory, so load only files you control. For a config from another source, such as a request body, use from_yaml() without base_dir or from_json().

Parameters:

path – Path to the file.

Returns:

The validated config.

class pipecat.flows.Flow(config: FlowConfig, *, handlers: Mapping[str, Callable] | Sequence[Mapping[str, Callable] | Any] | Any)[source]

Bases: object

A FlowConfig joined to handlers.

The flow hands ready-made node configs to FlowManager:

config = FlowConfig.from_file("flow.yaml")
flow = Flow(config, handlers=handlers)
flow_manager = FlowManager(..., global_functions=flow.global_functions)
await flow_manager.initialize(flow.initial_node)
__init__(config: FlowConfig, *, handlers: Mapping[str, Callable] | Sequence[Mapping[str, Callable] | Any] | Any)[source]

Join a config to the handlers it refers to.

Parameters:
  • config – The flow config.

  • handlers – The Python behind the config: the direct functions that implement its tools and the callables that implement its actions. A mapping of names to callables, or any object whose attributes are the callables, typically a module. A list or tuple of those lets tools and action handlers live in separate modules; a name that resolves to different callables in more than one of them is an error rather than a silent choice. Only the names the config references are looked up.

Raises:

FlowReferenceError – If a referenced tool or handler is missing or ambiguous, or a tool is not a valid direct function. Every such problem is collected and reported together.

property config: FlowConfig

The config this flow was constructed from.

property initial_node: NodeConfig

The node config the flow starts in.

property global_functions: list[FlowsFunctionSchema | Callable[[...], Awaitable[tuple[Any, NodeConfig | None | _NoResponse]]]]

Tools available at every node, for FlowManager(global_functions=...).

A fresh list each time, so the caller may extend it.

node(name: str) → NodeConfig[source]

The node config for name.

Parameters:

name – A node name from the config.

Raises:

FlowError – If the config has no such node.

class pipecat.flows.ActionConfig[source]

Bases: TypedDict

Configuration for an action.

Parameters:
  • type – Action type identifier (e.g. “tts_say”, “notify_slack”).

  • handler – Callable to handle the action.

  • text – Text to speak for the “tts_say” action, or the optional goodbye message for the “end_conversation” action.

  • append_text_to_context – For the built-in TTS actions (“tts_say” and “end_conversation”), whether the spoken text is appended to the LLM context. Defaults to True.

Note

Additional fields are allowed and passed to the handler.

class pipecat.flows.ContextStrategy(*values)[source]

Bases: Enum

Strategy for managing context during node transitions.

Parameters:
  • APPEND – Append new messages to existing context (default).

  • RESET – Reset context with new messages only.

  • RESET_WITH_SUMMARY –

    Reset context but include an LLM-generated summary.

    Deprecated since version 1.5.0: Use LLMSummarizeContextFrame instead — push it in a pre-action to trigger on-demand summarization during a node transition. See https://docs.pipecat.ai/guides/fundamentals/context-summarization. Will be removed in 2.0.0.

APPEND = 'append'
RESET = 'reset'
RESET_WITH_SUMMARY = 'reset_with_summary'
class pipecat.flows.ContextStrategyConfig(strategy: ContextStrategy, summary_prompt: str | None = None)[source]

Bases: object

Configuration for context management.

Parameters:
  • strategy – Strategy to use for context management.

  • summary_prompt –

    Required prompt text when using RESET_WITH_SUMMARY.

    Deprecated since version 1.5.0: Use LLMContextSummaryConfig.summarization_prompt instead. Deprecated together with RESET_WITH_SUMMARY. Will be removed in 2.0.0.

summary_prompt: str | None = None
class pipecat.flows.FlowResult(**kwargs)[source]

Bases: TypedDict

Optional convention TypedDict for status/error results.

Deprecated since version 1.5.0: No replacement. FlowResult is no longer required or referenced by any handler type, and Pipecat’s upstream function-call-result contract is Any — define your own TypedDict or return any JSON-serializable value. Will be removed in 2.0.0.

Parameters:
  • status – Status of the function execution.

  • error – Optional error message if execution failed.

class pipecat.flows.FlowsFunctionSchema(name: str, description: str, properties: dict[str, Any], required: list[str], handler: Callable[[], Awaitable[Any]] | Callable[[dict[str, Any]], Awaitable[Any]] | Callable[[dict[str, Any], FlowManager], Awaitable[Any]], cancel_on_interruption: bool = False, timeout_secs: float | None = None)[source]

Bases: object

Function schema with Flows-specific properties.

This class extends a standard function schema with the Flows-specific handler that runs when the function is called, plus its call options.

Parameters:
  • name – Name of the function.

  • description – Description of the function.

  • properties – Dictionary defining parameter types and descriptions.

  • required – List of required parameter names.

  • handler – Function handler to process the function call.

  • cancel_on_interruption – Whether to cancel this function call when an interruption occurs. Defaults to False.

  • timeout_secs – Optional per-tool timeout in seconds, overriding the global function_call_timeout_secs. Defaults to None (use global timeout).

cancel_on_interruption: bool = False
timeout_secs: float | None = None
to_function_schema() → FunctionSchema[source]

Convert to a standard FunctionSchema for use with LLMs.

Returns:

FunctionSchema without flow-specific fields.

class pipecat.flows.NodeConfig[source]

Bases: TypedDict

Configuration for a single node in the flow.

Parameters:
  • task_messages – List of message dicts defining the current node’s objectives.

  • name – Name of the node, useful for debug logging when returning a next node from a “consolidated” function.

  • role_message – The bot’s role/personality as a plain string, sent as the LLM’s system instruction via LLMUpdateSettingsFrame. When provided, the system instruction persists across node transitions until a new node explicitly sets role_message again.

  • role_messages –

    Deprecated list-of-dicts format for the bot’s role/personality.

    Deprecated since version 1.5.0: Use role_message (str) instead. Will be removed in 2.0.0.

  • functions – List of FlowsFunctionSchema definitions or direct functions whose definitions are automatically extracted from their signatures.

  • pre_actions – Actions to execute before LLM inference.

  • post_actions – Actions to execute after LLM inference.

  • context_strategy – Strategy for updating context during transitions.

  • respond_immediately – Whether to run LLM inference as soon as the node is set (default: True).

Example:

{
    "role_message": "You are a helpful assistant...",
    "task_messages": [
        {
            "role": "developer",
            "content": "Ask the user for their name..."
        }
    ],
    "functions": [...],
    "pre_actions": [...],
    "post_actions": [...],
    "context_strategy": ContextStrategyConfig(strategy=ContextStrategy.APPEND),
    "respond_immediately": true,
}
pipecat.flows.flows_tool_options(*, cancel_on_interruption: bool = False, timeout_secs: float | None = None) → Callable[[Callable], Callable][source]

Configure a Flows direct function’s call options.

This decorator is optional; use it to override the defaults for a Flows direct function (an async function whose first parameter is flow_manager).

Parameters:
  • cancel_on_interruption – Whether to cancel the function call when the user interrupts. Defaults to False.

  • timeout_secs – Optional per-tool timeout in seconds, overriding the global function_call_timeout_secs. Defaults to None (use global timeout).

Returns:

A decorator that attaches the metadata to the function.

Example:

@flows_tool_options(cancel_on_interruption=False, timeout_secs=30)
async def long_running_task(flow_manager: FlowManager, query: str):
    '''Perform a long-running task that should not be cancelled on interruption.'''
    # ... implementation
    return {"status": "complete"}, None
pipecat.flows.flows_direct_function(*, cancel_on_interruption: bool = False, timeout_secs: float | None = None) → Callable[[Callable], Callable][source]

Configure a Flows direct function’s call options.

Deprecated since version 1.5.0: Renamed to flows_tool_options() to align with Pipecat’s @tool_options and make clearer that it configures call options. Will be removed in 2.0.0.

Parameters:
  • cancel_on_interruption – Whether to cancel the function call when the user interrupts. Defaults to False.

  • timeout_secs – Optional per-tool timeout in seconds, overriding the global function_call_timeout_secs. Defaults to None (use global timeout).

Returns:

A decorator that attaches the metadata to the function.

exception pipecat.flows.FlowError[source]

Bases: Exception

Base exception for all flow-related errors.

This is the parent class for all flow system exceptions. Use this for generic flow errors or when a more specific exception doesn’t apply.

exception pipecat.flows.FlowInitializationError[source]

Bases: FlowError

Raised when flow initialization fails.

This exception occurs during flow manager setup, typically due to invalid configuration, missing dependencies, or initialization errors.

class pipecat.flows.FlowProblem(code: str, message: str, node: str | None = None, function: str | None = None)[source]

Bases: object

One reference a flow config makes that its handlers do not satisfy.

Parameters:
  • code – Stable identifier for the kind of problem: missing_tool, ambiguous_tool, invalid_tool, missing_handler, or ambiguous_handler.

  • message – Human-readable description naming the node, function, or variable involved.

  • node – The node the problem is about, when there is one.

  • function – The function entry the problem is about, when there is one.

node: str | None = None
function: str | None = None
exception pipecat.flows.FlowReferenceError(problems: list[FlowProblem])[source]

Bases: FlowError

Raised when a flow config’s references cannot all be resolved.

Constructing a Flow checks every tool, action handler, and template variable the config names and raises this once, with every unresolved reference, rather than stopping at the first.

__init__(problems: list[FlowProblem])[source]

Initialize with the unresolved references.

Parameters:

problems – Every unresolved reference, in the order found.

exception pipecat.flows.FlowTransitionError[source]

Bases: FlowError

Raised when a state transition fails.

This exception occurs when transitioning between nodes fails due to invalid node configurations, missing target nodes, or transition errors.

exception pipecat.flows.InvalidFunctionError[source]

Bases: FlowError

Raised when an invalid or unavailable function is called.

This exception occurs when attempting to call functions that are not properly registered, have invalid signatures, or cannot be found.

exception pipecat.flows.ActionError[source]

Bases: FlowError

Raised when an action execution fails.

This exception occurs during action execution, including built-in actions like TTS or custom actions, due to invalid configuration or execution errors.

Submodules