Package-level declarations

Types

Link copied to clipboard
data class Checkpoint<State>(val state: State, val nextNodes: List<String>, val step: Int = 0, val interruptedBefore: Boolean = false, val subgraphs: Map<String, SubgraphPosition> = emptyMap(), val effects: Map<String, String> = emptyMap())

A saved point in a graph run.

Link copied to clipboard
class CheckpointCorruptedException(val threadId: String, message: String, cause: Throwable? = null) : TelarException

The stored checkpoint of threadId could not be read, for example because the file is damaged or was written in a newer format. Checkpointer implementations throw this from Checkpointer.load.

Link copied to clipboard
interface Checkpointer<State>

Persists the checkpoints of each thread so a run can pause and resume later, even in a different process.

Link copied to clipboard

CompiledGraph.resume was called for threadId, but the checkpointer has no checkpoint for it.

Link copied to clipboard

An executable graph produced by StateGraph.compile. It is immutable and can be shared and run concurrently; each run is isolated by GraphConfig.threadId.

Link copied to clipboard
typealias EdgeCondition<State> = suspend (State) -> String

A routing function for a conditional edge: it inspects the current state and returns the name of the node to run next, or END to finish.

Link copied to clipboard

The condition of the conditional edge from from threw an exception. The original exception is available as cause. Cancellation is handled as for NodeExecutionException.

Link copied to clipboard

CompiledGraph.resume was called for threadId, but its last run already completed. Start a new run with CompiledGraph.invoke.

Link copied to clipboard
data class GraphConfig<State>(val threadId: String = "default", val checkpointer: Checkpointer<State>? = null, val interruptBefore: Set<String> = emptySet(), val interruptAfter: Set<String> = emptySet(), val maxIterations: Int = DEFAULT_MAX_ITERATIONS, val observers: List<GraphObserver> = emptyList(), val store: Store? = null)

Per-run settings for a CompiledGraph.

Link copied to clipboard
data class GraphEdge(val from: String, val to: String, val isConditional: Boolean = false, val label: String? = null)

A transition from from to to. Either end can be START or END.

Link copied to clipboard
sealed interface GraphEvent<out State>

A progress event emitted by CompiledGraph.stream and CompiledGraph.streamResume.

Link copied to clipboard
interface GraphObserver

Watches the runs of a graph: when a run starts and how it ends, when each node starts and how it ends, when the condition of an edge decides where the run goes, which nodes come next after a step, and when a checkpoint is saved. Use it to send traces and metrics to the tools a team already has, such as OpenTelemetry with telar-otel. Give it to a run with GraphConfig.observers:

Link copied to clipboard
sealed interface GraphResult<out State>
Link copied to clipboard
class GraphSession<State>(graph: CompiledGraph<State>, config: GraphConfig<State>, scope: CoroutineScope)

Runs one thread of a graph for a screen: the run is a StateFlow of GraphSnapshots that a UI draws, and the screen starts, resumes and cancels it with plain function calls. It is the unidirectional data flow of an app (state down, events up) with a graph behind it.

Link copied to clipboard
sealed interface GraphSnapshot<out State>

Where the run of a GraphSession stands. A screen draws one of these with a when, and each holds what it needs to.

Link copied to clipboard
data class GraphTopology(val nodes: List<String>, val edges: List<GraphEdge>, val dynamicRoutes: Set<String>, val subgraphs: Map<String, GraphTopology> = emptyMap(), val forEachNodes: Set<String> = emptySet())

The structure of a compiled graph: its nodes and the edges between them. Read it from CompiledGraph.topology to draw the graph or to check it in a test.

Link copied to clipboard

The graph definition or its run configuration is invalid: for example an edge points at an unknown node, or a fan-out has no Reducer. Thrown while building or compiling the graph, or when a run starts. The only check that waits for a node to run is the one of interrupt, which needs a checkpointer.

Link copied to clipboard
class InvalidRouteException(val from: String, val target: String) : TelarException

A conditional edge from from returned target, which is not a node of the graph or not one of the edge's declared targets.

Link copied to clipboard

The graph ran more steps than GraphConfig.maxIterations allows, which usually means a cycle never routes to END.

Link copied to clipboard
class MemoryCheckpointer<State>(maxHistory: Int = Int.MAX_VALUE) : Checkpointer<State>

A Checkpointer that keeps checkpoints in memory. Intended for tests and short-lived processes. Safe to share between coroutines and threads.

Link copied to clipboard
class MemoryStore(clock: Clock = Clock.System) : Store

A Store that keeps its items in memory, for tests and for apps that remember only while they run. Safe to share between coroutines and threads.

Link copied to clipboard

A reducer built with mergeRules could not merge the states of a step: a node changed a property that has no rule, or two nodes changed a property in ways its rule cannot combine. It is the cause of the ReducerException the run fails with.

Link copied to clipboard

A Reducer built by mergeRules from one rule for each property. Give it to StateGraph.compile, as rules or as reducer, to merge every node of a step, whatever form it has.

Link copied to clipboard

The rules of a mergeRules block.

Link copied to clipboard
typealias NodeAction<State> = suspend (State) -> State

The work a node performs: a suspending function that takes the current state and returns the updated state.

Link copied to clipboard
class NodeExecutionException(val nodeName: String, cause: Throwable, val attempts: Int = 1, val item: Int? = null) : TelarException

A node's action threw an exception. The original exception is available as cause.

Link copied to clipboard
class NodeRef

A reference to a node added with StateGraph.node. Use it with StateGraph.then and StateGraph.conditionalEdge to connect nodes without repeating their names, and read name where a node name is needed (for example in GraphConfig.interruptBefore).

Link copied to clipboard

A try of a node took longer than the timeout the node was added with, and was cancelled. It is the cause of the NodeExecutionException the run fails with, and what the retryOn of a Retry gets.

Link copied to clipboard
sealed interface ObservedCaller

The part of a run whose code is running: a node, or the condition of an edge. A library that reports what happens inside, such as the calls to models of telar-agent, reports it under the caller that forEachObserver gives.

Link copied to clipboard

An edge with a condition, which a GraphObserver is told about when the condition runs. It is the same object from the start of the condition to its end.

Link copied to clipboard

A node in one step of a run, which a GraphObserver is told about. It is the same object from the start of the node to its end.

Link copied to clipboard

A run that a GraphObserver is told about. It is the same object from the start of the run to its end, so an observer can keep what belongs to a run, such as a trace span, in a map with the run as its key.

Link copied to clipboard
fun interface Reducer<State>

Merges the states of nodes that ran in the same step and each returned a whole state.

Link copied to clipboard
class ReducerException(val nodes: List<String>, cause: Throwable) : TelarException

The Reducer threw an exception while it merged the results of nodes, the nodes of the failed step that each returned a whole state. The original exception is available as cause. Cancellation is handled as for NodeExecutionException.

Link copied to clipboard
class Retry(val attempts: Int = 3, val pause: Duration = 1.seconds, val factor: Double = 2.0, val maxPause: Duration = 30.seconds, val retryOn: (Throwable) -> Boolean = { true })

Says how often a node is tried again after it failed, and how long the engine waits between two tries. Give it to a node as retry:

Link copied to clipboard

Builder for a graph of nodes and edges over an immutable State.

Link copied to clipboard

Converts a graph state to and from a string so a Checkpointer can persist it.

Link copied to clipboard
interface Store

Keeps what an agent learned between conversations: a preference of a user, a fact, an earlier decision. A Checkpointer saves the state of one thread; a store belongs to no thread, so every run that is given the same store reads what the others wrote.

Link copied to clipboard
class StoreCorruptedException(val namespace: List<String>, val key: String?, message: String, cause: Throwable? = null) : TelarException

What a Store keeps under key in namespace could not be read, for example because the type it was written with changed, or the file or entry that holds it is damaged. key is null when a whole namespace could not be read.

Link copied to clipboard
data class StoreItem(val namespace: List<String>, val key: String, val value: String, val updatedAt: Instant)

A value that a Store keeps.

Link copied to clipboard
data class SubgraphPosition(val nextNodes: List<String>, val step: Int = 0, val interruptedBefore: Boolean = false, val subgraphs: Map<String, SubgraphPosition> = emptyMap())

Where a run stands inside a subgraph that was added with StateGraph.subgraph. It is a Checkpoint without a state: the state of a subgraph is kept in the state of the graph around it.

Link copied to clipboard
abstract class TelarException(message: String, cause: Throwable? = null) : RuntimeException

Base class for every error raised by Telar itself, so callers can catch the whole family with a single catch (e: TelarException). Integration modules and custom Checkpointers may add their own subclasses.

Link copied to clipboard

CompiledGraph.fork was asked to start the thread threadId, which already has a checkpoint. A fork starts a thread of its own, so that it cannot overwrite a run. Choose another id, or delete the thread first.

Properties

Link copied to clipboard
const val END: String

Represents the final state of the graph. Execution stops when this node is reached.

Link copied to clipboard
const val START: String

Represents the starting point of the graph.

Functions

Link copied to clipboard
suspend fun <T> effect(key: String, serializer: StateSerializer<T>, block: suspend () -> T): T

Runs block, a side effect such as a payment or an email, once for the step of the node that calls it, and returns its result. When the step runs again, the call returns the result of the first time and block does not run.

suspend fun <T> effect(key: String, serializer: StateSerializer<T>, reconcile: suspend (id: String) -> T?, block: suspend (id: String) -> T): T

Runs block, a side effect such as a payment, once for the step of the node that calls it, as the effect without reconcile does, and also closes the moment in which that one can repeat it: between the end of block and the save of its result.

Link copied to clipboard
suspend fun effectId(): String?

Returns the id of the effect with a reconcile whose block or reconcile is running, and null elsewhere. It is the same each time the step of the effect runs again, so it is the idempotency key to pass to a service from code that does not get the id itself, such as a tool of telar-agent.

Link copied to clipboard
suspend fun forEachNodeObserver(notify: (observer: GraphObserver, node: ObservedNode) -> Unit)

Calls notify with each observer of the run and the node that runs this code. Does nothing outside a running node, also in the condition of an edge.

Link copied to clipboard
suspend fun forEachObserver(notify: (observer: GraphObserver, caller: ObservedCaller) -> Unit)

Calls notify with each observer of the run and the node or edge that runs this code, so that a library can tell observers of its own kind about what happens inside a node or in the condition of an edge. telar-agent tells its AgentObservers about the calls to models and tools this way:

Link copied to clipboard
suspend fun <T> Store.get(namespace: List<String>, key: String, serializer: StateSerializer<T>): T?

Returns the value under key in namespace, read with serializer, or null when there is none.

Link copied to clipboard
suspend fun <State> interrupt(state: State): Nothing

Pauses the run from inside a node and saves state. Use it when a node finds out in the middle of its work that it needs a person, for example to ask a question it only knows at run time.

Link copied to clipboard

Returns true when this code runs in a node of a run that is collected with CompiledGraph.stream or CompiledGraph.streamResume, so that what it passes to reportProgress reaches a collector. A node can use it to skip work that only produces progress.

Link copied to clipboard

Builds MergeRules from one rule for each property that nodes of the same step may change, in place of a reducer that merges whole states by hand:

Link copied to clipboard
suspend fun <T> Store.put(namespace: List<String>, key: String, value: T, serializer: StateSerializer<T>)

Keeps value under key in namespace, written with serializer.

Link copied to clipboard
suspend fun reportProgress(value: Any)

Reports value from a running node to whoever collects the run: it arrives as a GraphEvent.NodeProgress in the flow of CompiledGraph.stream or CompiledGraph.streamResume, before the node's GraphEvent.NodeCompleted. Use it for what a node produces while it works, such as the text a model writes or how far a download is.

Link copied to clipboard

DSL entry point for building a StateGraph.

Link copied to clipboard
fun <State> Flow<GraphEvent<State>>.states(): Flow<State>

Maps a stream of events to the state after each step, which is convenient for UI code that only renders the latest state (for example collectAsState in Compose).

Link copied to clipboard
suspend fun store(): Store

Returns the Store of the running graph, which GraphConfig.store gave it. Call it from the action of a node, the work of a node, or a tool that a node runs. The nodes of a subgraph, and so the agents of a team, reach the store of the graph around them.

Link copied to clipboard
fun <State> List<Checkpoint<State>>.withCheckpoint(checkpoint: Checkpoint<State>, maxHistory: Int = Int.MAX_VALUE): List<Checkpoint<State>>

Returns this history of a thread after checkpoint is saved, for a Checkpointer that keeps a history: the checkpoints with an earlier step, then checkpoint, and of those the last maxHistory.

Link copied to clipboard
fun Store.within(vararg namespace: String): Store

Returns a view of this store whose namespaces all start with namespace. Give each user a view of their own, store.within("users", userId), so that a graph compiled once serves every user, and nothing in it can read what another user's runs wrote.