Documentation
¶
Overview ¶
Package flows builds structured, multi-step conversations on top of jargo's LLM service.
A conversation is a graph of nodes. Each node sets the assistant's persona and objective, the tools it may call, and what runs on the way in and out. A tool whose handler returns the next node is an edge that moves the conversation on; one that returns no next node only gathers data. A caller outside the graph moves it with SetNode, for a transition the conversation never asked for.
A FlowManager sits beside the pipeline rather than in it. It steers the conversation by queueing frames as nodes are entered: the persona as the LLM service's system instruction, the node's objective as messages, and its toolset. Queueing rather than writing to the conversation directly is what orders each change against whatever else is in flight, and what lets a realtime service learn the toolset changed. The LLM service's tool loop then carries out each transition.
Transitions ¶
An edge function does not move the flow where it stands. It records the transition and reports its result with a context-updated callback, so the move happens once the result has reached the conversation and every other tool call of that turn has reported. A turn that called three tools therefore enters the next node once, against a finished turn.
Context strategies ¶
Entering a node appends its objective to the conversation by default, so everything said so far is kept. A node or the whole flow may instead reset the conversation, or reset it to a generated summary of what was said, which keeps the substance of a long call without its length.
Actions ¶
Actions are how a flow does something other than talk. Three are built in: "tts_say" speaks a fixed line, "end_conversation" ends the call, and "function" runs a handler at the point in the pipeline it reaches, once the speech queued ahead of it has been said. An application registers whatever else it needs with RegisterAction. A node's pre-actions run before its context is applied; its post-actions run after, or, on a node that waits for the user, once the assistant's first turn there is over.
Configured flows ¶
A flow can also be described as data. A FlowConfig, loaded from YAML or JSON, holds the nodes, what each one says, which tools it offers and where each tool leads, and NewFlow joins it to the application's handlers: the NodeFunctions and ActionHandlers the config refers to by name. The resulting Flow hands ready-made nodes to the FlowManager. A tool of a configured flow returns TransitionInYAML in its next-node slot and the config decides where the conversation goes, by a fixed target or by a field of the tool's result. A set of nodes used more than once is written once as a subflow and run from each node that needs it.
Experimental: this package may still change in a minor release.
Index ¶
- Constants
- Variables
- type ActionConfig
- type ActionFinishedFrame
- type ActionHandler
- type Config
- type ContextStrategy
- type ContextStrategyConfig
- type Enqueuer
- type Flow
- type FlowConfig
- type FlowConfigAction
- type FlowConfigBranch
- type FlowConfigError
- type FlowConfigErrorDetail
- type FlowConfigFunction
- type FlowConfigMessage
- type FlowConfigNode
- type FlowConfigSubflow
- type FlowConfigTransition
- type FlowManager
- func (fm *FlowManager) CurrentContext() ([]frames.Message, error)
- func (fm *FlowManager) CurrentNode() string
- func (fm *FlowManager) Events() *event.Registry
- func (fm *FlowManager) Initialize(ctx context.Context, node *NodeConfig) error
- func (fm *FlowManager) RegisterAction(actionType string, h ActionHandler) error
- func (fm *FlowManager) SetNode(ctx context.Context, node *NodeConfig) error
- func (fm *FlowManager) State() *State
- type FlowProblem
- type FlowReferenceError
- type FunctionActionFrame
- type Handler
- type Handlers
- type Inferencer
- type NodeConfig
- type NodeEntered
- type NodeFunction
- type State
- type Watcher
Constants ¶
const ( // ProblemMissingTool is a tool the config names that is not in the handlers. ProblemMissingTool = "missing_tool" // ProblemAmbiguousTool is a tool that more than one of the handlers defines. ProblemAmbiguousTool = "ambiguous_tool" // ProblemInvalidTool is a tool whose entry in the handlers cannot be offered. ProblemInvalidTool = "invalid_tool" // ProblemMissingHandler is an action handler the config names that is not in // the handlers. ProblemMissingHandler = "missing_handler" // ProblemAmbiguousHandler is an action handler that more than one of the // handlers defines. ProblemAmbiguousHandler = "ambiguous_handler" )
The codes of a FlowProblem.
const EventNodeEntered = "on_node_entered"
EventNodeEntered fires each time the flow enters a node, including the first node and a node it re-enters, with a NodeEntered. Handlers run in order before the node's LLM response starts, so they must be fast; start a goroutine for slow work.
event.On(fm.Events(), flows.EventNodeEntered,
func(ctx context.Context, entered flows.NodeEntered) { … })
Variables ¶
var ( // ErrFlow is the error every flow failure wraps. Match it to catch them all. ErrFlow = errors.New("flows: flow error") // ErrFlowInitialization reports that the flow could not be entered: // its opening node failed to be set up. ErrFlowInitialization = errors.New("flows: initialization failed") // ErrFlowTransition reports that a transition could not be made, which is // almost always a manager that was asked to move before it was initialized. ErrFlowTransition = errors.New("flows: transition failed") // ErrInvalidFunction reports a function a node cannot offer: one with no // name, no handler, or a shape the manager cannot call. ErrInvalidFunction = errors.New("flows: invalid function") // ErrAction reports that an action failed to run. ErrAction = errors.New("flows: action failed") )
The errors a flow reports. They form a hierarchy: every one of them wraps ErrFlow, so a caller that only wants to know the flow failed matches on that, and one that wants to know how matches on the specific error. A flow config that does not load is the exception: it is a FlowConfigError, which is about the document rather than about a flow.
var NoResponse = &NodeConfig{Name: "no-response"}
NoResponse is the sentinel a Handler returns in its next-node slot to finish the call without transitioning and without generation re-running.
It is for a tool that has already said its piece: one that plays audio of its own, or that ends the conversation. A result ordinarily goes back to the model for it to answer from, and that answer would be spoken over whatever the tool started. The result still reaches the conversation, so the model knows what happened when the user speaks next.
var TransitionInYAML = &NodeConfig{Name: "transition-in-yaml"}
TransitionInYAML is the sentinel a Handler returns in its next-node slot to defer the transition to a flow config.
Return it from a tool that a FlowConfig names: the config's transition_to for that entry decides the next node. Only a flow built from a config accepts it; a node built in code rejects it, since nothing there can decide.
Functions ¶
This section is empty.
Types ¶
type ActionConfig ¶ added in v0.1.0
type ActionConfig struct {
// Type identifies the action. It is required.
Type string
// Handler runs the action. It is required for the "function" action, which is
// nothing but a handler to run in pipeline order, and optional otherwise: for
// any other type it registers the handler under Type when the action is first
// seen.
Handler ActionHandler
// Text is what "tts_say" speaks, or the optional goodbye "end_conversation"
// speaks before ending.
Text string
// AppendTextToContext controls whether the text the built-in speaking actions
// say is written to the conversation. Nil defaults to true.
AppendTextToContext *bool
// Params carries whatever else the action needs, for a custom handler to
// read. The built-in actions do not look at it.
Params map[string]any
}
ActionConfig configures one action to run on entering or leaving a node.
Type names the action, and is what decides which handler runs: one of the built-ins ("tts_say", "end_conversation", "function") or a type registered with FlowManager.RegisterAction. A config carrying a Handler registers it under Type the first time the action is seen, so an action can bring its own implementation rather than being registered up front.
type ActionFinishedFrame ¶ added in v0.1.0
type ActionFinishedFrame struct {
frames.BaseControlFrame
}
ActionFinishedFrame marks an action as complete. An action that queues frames queues one of these behind them, so the action counts as finished when its frames have been processed rather than when it returned.
func NewActionFinishedFrame ¶ added in v0.1.0
func NewActionFinishedFrame() *ActionFinishedFrame
NewActionFinishedFrame builds an ActionFinishedFrame.
type ActionHandler ¶ added in v0.1.0
type ActionHandler func(ctx context.Context, action ActionConfig, fm *FlowManager) error
ActionHandler runs one action. It is given the action that named it and the manager driving the flow, so an action can read the flow's state or move it.
type Config ¶
type Config struct {
// Enqueuer queues the frames a flow produces; usually the *pipeline.Worker.
Enqueuer Enqueuer
// Watcher reports frames reaching the end of the pipeline, which is how an
// action learns it has finished; usually the same *pipeline.Worker. Leaving it
// nil gives up the actions that wait on the pipeline.
Watcher Watcher
// Aggregators are the conversation aggregators the pipeline shares. The flow
// reads the conversation through them, and asks the assistant side whether a
// turn's tool calls have all reported before it transitions.
Aggregators *aggregators.Pair
// LLM answers the one-shot inference the reset-with-summary strategy needs. It
// is only required by that strategy; the concrete LLM services satisfy it.
LLM Inferencer
// ContextStrategy is what happens to the conversation when a node is entered.
// Nil appends, keeping everything said so far.
ContextStrategy *ContextStrategyConfig
// GlobalFunctions are offered at every node, ahead of the node's own.
GlobalFunctions []NodeFunction
}
Config configures a FlowManager. The references are the same instances wired into the pipeline.
type ContextStrategy ¶ added in v0.1.0
type ContextStrategy string
ContextStrategy says what happens to the conversation when a node is entered.
const ( // ContextStrategyAppend adds the node's task messages to the conversation, // keeping everything said so far. It is the default. ContextStrategyAppend ContextStrategy = "append" // ContextStrategyReset replaces the conversation with the node's task // messages, so the node starts from a clean slate. ContextStrategyReset ContextStrategy = "reset" // ContextStrategyResetWithSummary replaces the conversation with a summary of // what was said, followed by the node's task messages. It keeps the substance // of a long conversation without its length. ContextStrategyResetWithSummary ContextStrategy = "reset_with_summary" )
type ContextStrategyConfig ¶ added in v0.1.0
type ContextStrategyConfig struct {
// Strategy is what happens to the conversation.
Strategy ContextStrategy
// SummaryPrompt guides the summary, and is required by
// ContextStrategyResetWithSummary.
SummaryPrompt string
}
ContextStrategyConfig configures how the conversation is updated when a node is entered. Set it on the manager for every node, or on a node to override it for that one.
func (ContextStrategyConfig) Validate ¶ added in v0.1.0
func (c ContextStrategyConfig) Validate() error
Validate reports whether the configuration is usable.
type Enqueuer ¶
type Enqueuer interface {
QueueFrame(f frames.Frame, dir ...processor.Direction)
QueueFrames(fs []frames.Frame, dir ...processor.Direction)
}
Enqueuer injects frames into the running pipeline; *pipeline.Worker satisfies it. Everything a flow does to the conversation it does by queueing a frame, so the change is ordered against whatever else is in flight.
type Flow ¶ added in v1.0.0
type Flow struct {
// contains filtered or unexported fields
}
Flow is a FlowConfig joined to the code it names: the config's nodes turned into runnable NodeConfigs, with every tool reference resolved to a NodeFunction, every transition_only function built from the config alone, and every transition wired to the node the config names.
The flow hands ready-made nodes to a FlowManager:
config, err := flows.FlowConfigFromFile("flow.yaml")
flow, err := flows.NewFlow(config, handlers)
fm, err := flows.New(flows.Config{…, GlobalFunctions: flow.GlobalFunctions()})
err = fm.Initialize(ctx, flow.InitialNode())
Building a flow validates the references the config could not: each tool exists and can be offered, each action handler the config names is one. Tool return values are checked at call time against the configured-flow contract: a tool returns TransitionInYAML in its next-node slot and the config decides the next node. {{ key }} placeholders in prompts are left in place; the FlowManager fills them from its state when it enters the node.
A config's subflows are flattened before anything is built: a subflow's nodes are copied in once for each node that runs it, under the name <node>.<subflow node>, with every transition pointing at the node it leads to.
func NewFlow ¶ added in v1.0.0
func NewFlow(config *FlowConfig, handlers ...Handlers) (*Flow, error)
NewFlow joins a config to the handlers it refers to.
handlers is the code behind the config: the NodeFunctions that implement its tools and the ActionHandlers that implement its actions. Several may be given, which lets tools and action handlers live apart; a name found in more than one of them is an error rather than a silent choice. The config's name for a tool is the tool's identity: it is what the LLM sees whatever the NodeFunction's own Name says, so several entries may share one NodeFunction.
It returns a *FlowReferenceError if a referenced tool or handler is missing or ambiguous, or a tool cannot be offered. Every such problem is collected and reported together.
func (*Flow) Config ¶ added in v1.0.0
func (f *Flow) Config() *FlowConfig
Config returns the config this flow was built from.
func (*Flow) GlobalFunctions ¶ added in v1.0.0
func (f *Flow) GlobalFunctions() []NodeFunction
GlobalFunctions returns the tools available at every node, for Config.GlobalFunctions. It is a fresh slice each time, so the caller may extend it.
func (*Flow) InitialNode ¶ added in v1.0.0
func (f *Flow) InitialNode() *NodeConfig
InitialNode returns the node the flow starts in.
func (*Flow) Node ¶ added in v1.0.0
func (f *Flow) Node(name string) (*NodeConfig, error)
Node returns the node for name: a node name from the config, or <node>.<subflow node> for a node of a subflow. For a node that runs a subflow, this is the subflow's first node. It returns an ErrFlow if the config has no such node.
type FlowConfig ¶ added in v1.0.0
type FlowConfig struct {
// InitialNode is the name of the node the flow starts in.
InitialNode string `json:"initial_node"`
// Nodes are the flow's nodes, keyed by name.
Nodes map[string]*FlowConfigNode `json:"nodes"`
// GlobalFunctions are the tools offered at every node.
GlobalFunctions []FlowConfigFunction `json:"global_functions,omitempty"`
// Flows are the subflows the flow's nodes can run, keyed by flow id.
Flows map[string]*FlowConfigSubflow `json:"flows,omitempty"`
// contains filtered or unexported fields
}
FlowConfig is a conversation flow described as data: the nodes, what each one says, which tools each node offers, and where each tool leads. It contains no code. Every tool a node references is a NodeFunction that lives in the application's code and is resolved by name when the config is joined to the application's handlers with NewFlow. The exception is a transition_only function, which does nothing but move the conversation to another node: the config supplies its description and it needs no code.
Load one with FlowConfigFromFile for a YAML or JSON file, FlowConfigFromYAML for YAML text, FlowConfigFromJSON for JSON text, or FlowConfigFromMap for a document that is already parsed. A config is validated structurally on load: the initial node exists, every transition names a node, tool names are unique within a node, and every action is well-formed. NewFlow validates the references to code. A config built in code is checked with Validate.
initial_node: greet
nodes:
greet:
role_message: You are a friendly order-taking assistant.
task_messages:
- role: developer
content: Greet the caller and ask whether they want pizza or sushi.
functions:
- name: choose_pizza
transition_only: true
description: The caller wants to order pizza.
transition_to: pizza
- name: choose_sushi
transition_only: true
description: The caller wants to order sushi.
transition_to: sushi
pizza:
task_messages:
- role: developer
content: Take a pizza order.
functions:
- name: select_pizza_order
transition_to:
field: status
cases:
ok: confirm
unavailable: pizza
default: confirm
global_functions:
- name: get_delivery_estimate
`!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 FlowConfigFromYAML and no base directory, which rejects `!include`, or with FlowConfigFromJSON.
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. The FlowManager fills them from its 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 map. A key that is not in state is an ErrFlow when the node is entered. To show the LLM a literal {{ key }}, escape it as \{{ key }}.
Metadata: a node and a function each take an optional metadata mapping of JSON values, for whatever the application wants to keep with them, such as the id of the element a node stands for in an editor. The flow carries it and never acts on it, and it is never sent to the LLM. A Flow copies it onto the nodes and functions it builds, and the FlowManager passes it to EventNodeEntered handlers and to an RTVI client as the flow moves. Metadata is sent to the client, so keep anything the end user should not see out of it.
Subflows: a set of nodes used by several flows, or several times in one, is written once as a subflow under flows. A node runs it by naming it as its flow, in place of prompts and functions of its own, and says where the subflow's return leads:
initial_node: verify_caller
flows:
verification: !include verification.yaml
nodes:
verify_caller:
flow: verification
return_to: book
book:
...
Entering such a node enters the subflow at its first node. Inside a subflow a transition target names one of its own nodes, or is return, which leads to the return_to of the node running it; to return to two places, run the subflow from two nodes. return_to may be omitted for a subflow that never returns. A Flow builds a subflow's nodes once for each node that runs it, named <node>.<subflow node>, so everything before the dot is the node that runs the subflow; that is the name FlowManager.CurrentNode reports, and EventNodeEntered gives the running node separately as Parent. A config that has subflows therefore cannot have a dot in a node name. A subflow's nodes cannot run subflows, and global_functions are offered at them too.
A config remembers the order its nodes and subflows were written in, which is the order problems are reported in; those added in code afterwards follow, by name.
func FlowConfigFromFile ¶ added in v1.0.0
func FlowConfigFromFile(path string) (*FlowConfig, error)
FlowConfigFromFile loads a config from a .yaml, .yml, or .json file.
YAML files may use `!include` with paths relative to the directory of the file that names them. 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 FlowConfigFromYAML without a base directory or FlowConfigFromJSON.
func FlowConfigFromJSON ¶ added in v1.0.0
func FlowConfigFromJSON(text string) (*FlowConfig, error)
FlowConfigFromJSON loads a config from JSON text.
func FlowConfigFromMap ¶ added in v1.0.0
func FlowConfigFromMap(data map[string]any) (*FlowConfig, error)
FlowConfigFromMap loads a config from a document that is already parsed: maps with string keys, slices, strings, booleans and numbers. The cases of a branch may be a map[any]any whose keys are booleans or numbers.
func FlowConfigFromYAML ¶ added in v1.0.0
func FlowConfigFromYAML(text, baseDir string) (*FlowConfig, error)
FlowConfigFromYAML loads a config from YAML text.
baseDir is the directory that the document's `!include` paths resolve against; an included file's own includes resolve against its directory. When it is empty, `!include` is unavailable. An include can read any file the process can read, so leave baseDir empty for text from an untrusted source.
func (*FlowConfig) MarshalJSON ¶ added in v1.0.0
func (c *FlowConfig) MarshalJSON() ([]byte, error)
MarshalJSON writes the config as a document, its nodes and subflows in the order they were written in.
func (*FlowConfig) UnmarshalJSON ¶ added in v1.0.0
func (c *FlowConfig) UnmarshalJSON(data []byte) error
UnmarshalJSON loads the config from JSON text, as FlowConfigFromJSON does.
func (*FlowConfig) Validate ¶ added in v1.0.0
func (c *FlowConfig) Validate() error
Validate checks a config built or changed in code the way a loaded one is checked: every function and action is well-formed, a node prompts the LLM or runs a subflow, and the nodes, subflows and transitions fit together. It returns a *FlowConfigError holding everything found wrong, or nil.
type FlowConfigAction ¶ added in v1.0.0
type FlowConfigAction struct {
// Type is the action type identifier.
Type string
// Handler is the name of the handler in the handlers a Flow is built with.
// It is required for function, optional for custom types, and not allowed
// on tts_say or end_conversation.
Handler string
// Extras are the pass-through keys beyond type and handler.
Extras map[string]any
}
FlowConfigAction is 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.RegisterAction. Any additional keys pass through to the handler. The text of a tts_say action may contain {{ key }} placeholders; see FlowConfig.
func (FlowConfigAction) MarshalJSON ¶ added in v1.0.0
func (a FlowConfigAction) MarshalJSON() ([]byte, error)
MarshalJSON writes the action as a document has it: its type, its handler and the pass-through keys side by side.
func (*FlowConfigAction) RegisteredInCode ¶ added in v1.0.0
func (a *FlowConfigAction) RegisteredInCode() bool
RegisteredInCode reports whether this is a custom type whose handler the config does not name.
type FlowConfigBranch ¶ added in v1.0.0
type FlowConfigBranch struct {
// Field is the key of the tool's result whose value selects the case.
Field string `json:"field"`
// Cases maps a result value to a node name. In a document the keys may be
// written as strings, booleans, or numbers; they match the result value by
// its canonical string, so `true:` matches a result of true.
Cases map[string]string `json:"cases"`
// Default is the node to transition to when the value matches no case.
// When empty, an unmatched value stays on the current node.
Default string `json:"default,omitempty"`
}
FlowConfigBranch is a transition chosen by a field of the tool's result.
func (*FlowConfigBranch) Targets ¶ added in v1.0.0
func (b *FlowConfigBranch) Targets() []string
Targets returns every node name this branch can transition to.
type FlowConfigError ¶ added in v1.0.0
type FlowConfigError struct {
// Details is everything found wrong, in the order found.
Details []FlowConfigErrorDetail
}
FlowConfigError reports a flow config that is not valid: a document of the wrong shape, or one whose nodes do not fit together.
func (*FlowConfigError) Error ¶ added in v1.0.0
func (e *FlowConfigError) Error() string
Error implements error.
type FlowConfigErrorDetail ¶ added in v1.0.0
type FlowConfigErrorDetail struct {
// Loc is where in the document the error is, as a dotted path such as
// "nodes.greet.functions.0", or "" for the document as a whole.
Loc string
// Msg says what is wrong.
Msg string
}
FlowConfigErrorDetail is one thing wrong with a flow config.
type FlowConfigFunction ¶ added in v1.0.0
type FlowConfigFunction struct {
// Name is the tool's name, as the LLM sees it. For an ordinary entry, it is
// also the name of the NodeFunction in the handlers.
Name string `json:"name"`
// TransitionOnly says the tool is defined here rather than in code. It
// requires a Description and a TransitionTo that names a node.
TransitionOnly bool `json:"transition_only,omitempty"`
// Description is what the tool is for, for the LLM. Only a transition_only
// entry has one; a NodeFunction carries its own.
Description string `json:"description,omitempty"`
// TransitionTo is the node to transition to after the tool completes, or a
// branch. It is left zero for tools that stay on the current node.
TransitionTo FlowConfigTransition `json:"transition_to,omitzero"`
// Metadata is JSON data the application attaches to the tool. See
// "Metadata" in FlowConfig.
Metadata map[string]any `json:"metadata,omitempty"`
}
FlowConfigFunction is a tool offered at a node.
Ordinarily the entry names a NodeFunction in the handlers a Flow is built 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 TransitionTo when the LLM calls it.
func (*FlowConfigFunction) Targets ¶ added in v1.0.0
func (f *FlowConfigFunction) Targets() []string
Targets returns every node name this function can transition to.
type FlowConfigMessage ¶ added in v1.0.0
type FlowConfigMessage struct {
// Role is the message role, for example "developer" or "system".
Role string `json:"role"`
// Content is the message text. It may contain {{ key }} placeholders; see
// FlowConfig.
Content string `json:"content"`
}
FlowConfigMessage is one message in a node's task_messages.
type FlowConfigNode ¶ added in v1.0.0
type FlowConfigNode struct {
// TaskMessages are what the LLM should do at this node. They are required
// unless the node runs a subflow: a nil slice is a node that never said
// what it is for, an empty non-nil one a node that deliberately adds
// nothing.
TaskMessages []FlowConfigMessage `json:"task_messages,omitzero"`
// RoleMessage is 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. It may contain {{ key }} placeholders; see
// FlowConfig.
RoleMessage string `json:"role_message,omitempty"`
// Functions are the tools offered at this node, in addition to the config's
// GlobalFunctions.
Functions []FlowConfigFunction `json:"functions,omitempty"`
// PreActions are the actions run before the LLM responds at this node.
PreActions []FlowConfigAction `json:"pre_actions,omitempty"`
// PostActions are the actions run after the LLM responds at this node.
PostActions []FlowConfigAction `json:"post_actions,omitempty"`
// ContextStrategy is how the LLM context is updated on entering this node:
// ContextStrategyAppend or ContextStrategyReset. Empty uses the
// FlowManager's strategy.
ContextStrategy ContextStrategy `json:"context_strategy,omitempty"`
// RespondImmediately says whether the LLM responds as soon as the node is
// entered. Nil defaults to true.
RespondImmediately *bool `json:"respond_immediately,omitempty"`
// Metadata is JSON data the application attaches to the node. See
// "Metadata" in FlowConfig.
Metadata map[string]any `json:"metadata,omitempty"`
// Flow is the id of the subflow this node runs, a key of the config's
// Flows. A node that runs a subflow takes only ReturnTo and Metadata
// besides.
Flow string `json:"flow,omitempty"`
// ReturnTo is the node that return in the subflow leads to. It may be
// omitted when the subflow never returns.
ReturnTo string `json:"return_to,omitempty"`
}
FlowConfigNode is one node of the flow.
A node either prompts the LLM, with TaskMessages and the fields that go with them, or runs a subflow, with Flow and ReturnTo in their place. See "Subflows" in FlowConfig.
type FlowConfigSubflow ¶ added in v1.0.0
type FlowConfigSubflow struct {
// InitialNode is the name of the node the subflow starts in.
InitialNode string `json:"initial_node"`
// Nodes are the subflow's nodes, keyed by name.
Nodes map[string]*FlowConfigNode `json:"nodes"`
// contains filtered or unexported fields
}
FlowConfigSubflow is a set of nodes that a flow's nodes can run.
Inside a subflow a function transitions to one of the subflow's own nodes, or to return. See "Subflows" in FlowConfig.
func (*FlowConfigSubflow) MarshalJSON ¶ added in v1.0.0
func (s *FlowConfigSubflow) MarshalJSON() ([]byte, error)
MarshalJSON writes the subflow as a document, its nodes in the order they were written in.
func (*FlowConfigSubflow) Returns ¶ added in v1.0.0
func (s *FlowConfigSubflow) Returns() bool
Returns reports whether any function in the subflow transitions to return.
type FlowConfigTransition ¶ added in v1.0.0
type FlowConfigTransition struct {
// Node is the node to transition to. Inside a subflow it may also be
// "return"; see "Subflows" in FlowConfig.
Node string
// Branch chooses the node from the tool's result. It replaces Node when it
// is set.
Branch *FlowConfigBranch
}
FlowConfigTransition is where a function leads: nowhere (the zero value), a node, or a branch on the tool's result. In a document it is a node name or a branch mapping.
func (FlowConfigTransition) IsZero ¶ added in v1.0.0
func (t FlowConfigTransition) IsZero() bool
IsZero reports whether the transition leads nowhere.
func (FlowConfigTransition) MarshalJSON ¶ added in v1.0.0
func (t FlowConfigTransition) MarshalJSON() ([]byte, error)
MarshalJSON writes the transition as a document has it: a node name, a branch mapping, or null.
type FlowManager ¶
type FlowManager struct {
// contains filtered or unexported fields
}
FlowManager drives a conversation through a graph of nodes.
It is not a pipeline processor. It holds the conversation and the task and steers the conversation by queueing frames as nodes are entered: the persona, the node's objective and its toolset. The LLM service's tool loop then carries out each transition. Build one with New and enter the graph with Initialize.
A node's prompts may refer to the flow's state with {{ key }} placeholders, in RoleMessage, the text of TaskMessages, 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 map, a key that is missing fails the entry with ErrFlow, and \{{ key }} is left as the literal {{ key }}.
An RTVI client is told about each node too, so it can follow the conversation through the flow. On entering a node the manager queues an rtvi.FlowNodeEnteredFrame, which reaches the client as a flow-node-entered message carrying the fields of NodeEntered; a field with no value is left out. The message is sent to RTVI clients of protocol 2.4.0 or later, and to any client before it sends client-ready, so keep anything the end user should not see out of node names, function names and metadata. Metadata that cannot be written as a JSON object is left out of the message, with a warning; the handlers of EventNodeEntered still receive it.
func (*FlowManager) CurrentContext ¶ added in v0.1.0
func (fm *FlowManager) CurrentContext() ([]frames.Message, error)
CurrentContext returns the conversation as it stands.
func (*FlowManager) CurrentNode ¶
func (fm *FlowManager) CurrentNode() string
CurrentNode returns the name of the node the flow is on, or "" before Initialize.
func (*FlowManager) Events ¶ added in v1.0.0
func (fm *FlowManager) Events() *event.Registry
Events is the registry the manager raises its events on: see EventNodeEntered.
func (*FlowManager) Initialize ¶
func (fm *FlowManager) Initialize(ctx context.Context, node *NodeConfig) error
Initialize enters the flow.
Passing a node starts the conversation there. Passing nil initializes the manager without entering a node, for a flow whose opening node is decided later and set with SetNode. Initializing twice is reported and otherwise ignored.
func (*FlowManager) RegisterAction ¶ added in v0.1.0
func (fm *FlowManager) RegisterAction(actionType string, h ActionHandler) error
RegisterAction records a handler for an action type, so a node may use it in its pre- or post-actions. The built-in types ("tts_say", "end_conversation" and "function") are registered already.
func (*FlowManager) SetNode ¶ added in v0.1.0
func (fm *FlowManager) SetNode(ctx context.Context, node *NodeConfig) error
SetNode transitions the flow to node. Enter the flow with Initialize first.
It is the manual transition, for a caller that is not part of the graph: a processor moving the conversation on something the model was never asked about. A node function transitions by returning the next node instead, which keeps the move on the tool loop that made it.
func (*FlowManager) State ¶ added in v0.1.0
func (fm *FlowManager) State() *State
State is the data a flow keeps across nodes: what the assistant has gathered so far, and anything else the handlers need to share. It is safe for concurrent use.
type FlowProblem ¶ added in v1.0.0
type FlowProblem struct {
// Code is a stable identifier for the kind of problem: ProblemMissingTool,
// ProblemAmbiguousTool, ProblemInvalidTool, ProblemMissingHandler or
// ProblemAmbiguousHandler.
Code string
// Message is a human-readable description naming the node or function
// involved.
Message string
// Node is the node the problem is about, or "" when there is none.
Node string
// Function is the function entry the problem is about, or "" when there is
// none.
Function string
}
FlowProblem is one reference a flow config makes that its handlers do not satisfy.
type FlowReferenceError ¶ added in v1.0.0
type FlowReferenceError struct {
// Problems is every unresolved reference, in the order found.
Problems []FlowProblem
}
FlowReferenceError reports that a flow config's references cannot all be resolved.
NewFlow checks every tool and action handler the config names and returns this once, with every unresolved reference, rather than stopping at the first. It matches ErrFlow.
func (*FlowReferenceError) Error ¶ added in v1.0.0
func (e *FlowReferenceError) Error() string
Error implements error.
func (*FlowReferenceError) Is ¶ added in v1.0.0
func (e *FlowReferenceError) Is(target error) bool
Is reports the error as a flow error.
type FunctionActionFrame ¶ added in v0.1.0
type FunctionActionFrame struct {
frames.BaseControlFrame
// Action is the action that named the handler.
Action ActionConfig
// Function is the handler to run.
Function ActionHandler
}
FunctionActionFrame carries a function action to run once it reaches the end of the pipeline. Queueing it rather than running the handler on the spot is what makes the handler happen at the right moment: after the speech queued ahead of it has been said, rather than while it is still being synthesized.
func NewFunctionActionFrame ¶ added in v0.1.0
func NewFunctionActionFrame(action ActionConfig, fn ActionHandler) *FunctionActionFrame
NewFunctionActionFrame builds a FunctionActionFrame.
type Handler ¶
type Handler func(ctx context.Context, args json.RawMessage, fm *FlowManager) (string, *NodeConfig, error)
Handler runs when the model calls a node function.
args carries the raw JSON arguments the model produced, and fm is the manager driving the flow. It returns the result to feed back to the model as the tool result and, optionally, the next node to move to: a non-nil next transitions the flow, a nil next leaves it on the current node and answers from the result, and NoResponse leaves it there without the assistant being asked to say anything.
Returning an empty result marks the function as transition-only: the manager substitutes an acknowledgement, since the model called the function and is owed an answer whether or not the function had one of its own.
type Handlers ¶ added in v1.0.0
Handlers is the code behind a flow config, by the name the config refers to it with: a NodeFunction for a tool, an ActionHandler for an action handler. Only the names the config references are looked up.
type Inferencer ¶ added in v0.1.0
type Inferencer interface {
RunInference(ctx context.Context, convo *frames.LLMContext, opts llm.InferenceOptions) (string, error)
}
Inferencer answers a conversation once, off to the side of the pipeline. It is what the reset-with-summary strategy summarizes through; the concrete LLM services satisfy it.
type NodeConfig ¶
type NodeConfig struct {
// Name labels the node in logs. It is optional; an unnamed node is given a
// generated name so two of them are told apart.
Name string
// RoleMessage is the assistant's persona. It is sent as the LLM service's
// system instruction on entry and, being sticky, persists across later
// transitions until another node sets its own. Leave it empty to keep the
// current persona.
RoleMessage string
// TaskMessages state the assistant's objective at this node. They are added to
// the conversation on entry, as the node's context strategy says.
//
// It is required: a nil slice is a node that never said what it is for, and is
// rejected. An empty non-nil slice is a node that deliberately adds nothing,
// which is allowed.
TaskMessages []frames.Message
// Functions are the tools available at this node. A function whose handler
// returns a next node is an edge that transitions the flow; one that returns
// no next node only gathers data.
Functions []NodeFunction
// PreActions run before the node's context is applied, so what they say is
// spoken ahead of anything the node generates.
PreActions []ActionConfig
// PostActions run after the node's context is applied. On a node that speaks
// on entry they run immediately; on one that waits for the user they are held
// back until the assistant's first turn at this node is over.
PostActions []ActionConfig
// ContextStrategy overrides the manager's strategy for this node. Nil uses the
// manager's.
ContextStrategy *ContextStrategyConfig
// RespondImmediately controls whether the assistant generates a response as
// soon as the node is entered. It defaults to true; point it at false for a
// node that should wait for the user to speak first, such as the opening node
// of a call the user initiates.
RespondImmediately *bool
// Metadata is JSON-serializable data the application attaches to the node.
// The flow never acts on it and never sends it to the LLM. An RTVI client
// receives it when the node is entered, so keep anything the end user
// should not see out of it.
Metadata map[string]any
// Parent is, for a node of a subflow, the name of the node that runs the
// subflow. A Flow sets it.
Parent string
}
NodeConfig defines one state of a conversation: the assistant's task at this point, the tools it may call, what runs on the way in and out, and whether it speaks on entry.
type NodeEntered ¶ added in v1.0.0
type NodeEntered struct {
// Node is the node entered, by name.
Node string
// PreviousNode is the node the flow left, or "" when this is the first
// node.
PreviousNode string
// Function is the function whose call caused the move, or "" when the node
// was set directly (Initialize, SetNode).
Function string
// Metadata is the entered node's Metadata, or nil.
Metadata map[string]any
// FunctionMetadata is the Metadata of Function, or nil.
FunctionMetadata map[string]any
// Parent is, when the entered node is a node of a subflow, the name of the
// node that runs the subflow; "" otherwise.
Parent string
}
NodeEntered is where a flow has just arrived, as passed to the handlers of EventNodeEntered.
type NodeFunction ¶
type NodeFunction struct {
// Name is the tool name the model calls. It must be unique within a node and
// is required.
Name string
// Description tells the model when to call the tool.
Description string
// Properties describes the tool's arguments, as the properties of a JSON
// Schema object: a map of argument name to its schema.
Properties map[string]any
// Required names the arguments the model must supply.
Required []string
// Handler runs the call and may return the next node. It is required.
Handler Handler
// CancelOnInterruption sets whether a call to this tool is canceled when the
// user interrupts. Nil leaves the flow default, which does not cancel: a flow
// function is usually doing work the conversation still needs whether or not
// the user spoke over it.
CancelOnInterruption *bool
// TimeoutSecs bounds how long a call to this tool may take, overriding the
// service-wide bound. Nil leaves the service-wide one.
TimeoutSecs *float64
// Metadata is JSON-serializable data the application attaches to the
// function. The flow never acts on it and never sends it to the LLM. An
// RTVI client receives it when the function's call enters a node, so keep
// anything the end user should not see out of it.
Metadata map[string]any
}
NodeFunction is a tool offered to the model at a node. It pairs the schema the model sees with the handler that runs when the model calls it, and with the options the call runs under.
type State ¶ added in v0.1.0
type State struct {
// contains filtered or unexported fields
}
State reads and writes a flow's shared data.
type Watcher ¶ added in v0.1.0
type Watcher interface {
// Events is where the handler for the frames reaching the end of the
// pipeline is attached.
Events() *event.Registry
SetReachedDownstreamFilter(f func(frames.Frame) bool)
}
Watcher reports frames that reach the end of the pipeline. *pipeline.Worker satisfies it. The action manager uses it to learn when its actions have finished and when the assistant's turn is over, and says which frames it wants to hear about.