Package-level declarations

Types

Link copied to clipboard

A GraphObserver that is also told about the calls to models and tools inside the nodes of a run and in the conditions of its edges: those of toolLoop and toolAgent, of chatWithProgress, of ask (each time it asks), of a ChatDecisionModel, also in a decisionEdge, and of execute. Each call says which caller made it: an ObservedNode, or an ObservedEdge for the condition of an edge. Use it to count the tokens of a run, log which tools ran, or show them in a debugger. Give it to a run in GraphConfig.observers, like any observer:

Link copied to clipboard
@Serializable
data class AgentState(val messages: List<ChatMessage> = emptyList(), val tokens: TokenUsage = TokenUsage())

The state of a toolAgent: the conversation so far, oldest message first, and what it cost.

Link copied to clipboard
sealed interface Answer

What a DecisionModel answered to one Question.

Link copied to clipboard
@Serializable
data class Assignment(val index: Int, val agent: String, val toolCallId: String, val toolName: String, val conversation: AgentState, val tokenBudget: Int? = null, val finished: Boolean = false)

A task that a supervisor gave to one of its agents, and the work the agent did on it.

Link copied to clipboard
@Serializable
sealed interface Attachment

A file that goes to a model with a message, such as the photo of a receipt or a contract as a PDF.

Link copied to clipboard

A DecisionModel that asks a ChatModel, so that choose, isYes, score and decisionEdge work with the model an app already has: Claude, OpenAI, Gemini, Ollama, or any other.

Link copied to clipboard
sealed interface ChatEvent

What a ChatModel emits while it writes an answer. See ChatModel.stream.

Link copied to clipboard
@Serializable
sealed interface ChatMessage

One message of a conversation with a ChatModel.

Link copied to clipboard
fun interface ChatModel

A language model that continues a conversation. It is the only thing the rest of this module needs from a model provider, so a graph written against it runs on every Kotlin target and with any provider.

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

A call to a ChatModel failed: the provider could not be reached, it returned an error, or the model declined to answer.

Link copied to clipboard
data class ChatRequest(val messages: List<ChatMessage>, val system: String? = null, val tools: List<ToolSpec> = emptyList(), val shortened: Boolean = false)

What a ChatModel is asked.

Link copied to clipboard
data class ChatResponse(val message: ChatMessage.Assistant, val usage: TokenUsage? = null, val model: String? = null)

What a ChatModel answered.

Link copied to clipboard

An AgentObserver that is also told what the calls send and get back: the request a model is sent, its answer, the input of a tool and its result. Use it to record the conversation in a trace, as OtlpObserver and OpenTelemetryObserver of telar-otel do with recordContent = true:

Link copied to clipboard
fun interface DecisionModel

A model that decides instead of writing: it picks one of the options you give it, answers yes or no, or rates something on a scale, and says how sure it is. Such a model is fast and cheap, and its answer has a fixed type, which makes it a good fit for the places where a graph has to decide: which node comes next, whether an answer is good enough, whether a person has to look.

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

A call to a DecisionModel failed: the provider could not be reached, it returned an error, or its answer does not fit the question.

Link copied to clipboard
data class DecisionRequest(val state: JsonElement, val questions: Map<String, Question>)

What a DecisionModel is asked.

Link copied to clipboard
data class DecisionResponse(val answers: Map<String, Answer>, val usage: TokenUsage? = null)

What a DecisionModel answered.

Link copied to clipboard
@SerialInfo
@Target(allowedTargets = [AnnotationTarget.PROPERTY])
annotation class Description(val value: String)

Describes a property to the model: of the input class of a Tool, or of the class a model is asked for with ask.

Link copied to clipboard
interface EmbeddingModel

A model that turns texts into vectors, so that texts that mean the same have vectors that point the same way. SemanticStore uses one to find what a query is about. It is the interface for every provider, as ChatModel is for chat: OpenAiEmbeddingModel of telar-openai reaches OpenAI, Ollama, Gemini and every server with the embeddings API of OpenAI.

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

A call to an EmbeddingModel failed: the provider could not be reached, or it returned an error.

Link copied to clipboard

A call to a model that an AgentObserver is told about. It is the same object from the start of the call to its end.

Link copied to clipboard

A call to a tool that an AgentObserver is told about. It is the same object from the start of the call to its end.

Link copied to clipboard
sealed interface Question

A question to a DecisionModel. Its kind decides the kind of Answer.

Link copied to clipboard
class SemanticStore(store: Store, embeddings: EmbeddingModel, minScore: Double = -1.0, scope: Int = Store.SEARCH_SCOPE) : Store

A Store whose search finds the items that a query means, with the vectors of an EmbeddingModel: "what does she eat?" finds "Piscivegetarian: fish, but no meat", which has none of its words. Everything else goes to store as it is.

Link copied to clipboard
class StateTool<State>(val spec: ToolSpec, val execute: suspend (State, JsonObject) -> ToolOutcome<State>)

A function a model may call that reads the state of the run and changes it: add a line to an order, book a seat, move a piece. What it did is in the state, so a checkpoint holds it and the next node sees it.

Link copied to clipboard
class TeamAgent(val name: String, val description: String, val model: ChatModel, val tools: List<Tool> = emptyList(), val system: String? = null, val inOrder: Boolean = false, val retry: Retry? = null, val shorten: (List<ChatMessage>) -> List<ChatMessage>? = null)

An agent of a team: what it is good at, and the model, tools and instructions it works with.

Link copied to clipboard
@Serializable
data class TeamState(val messages: List<ChatMessage> = emptyList(), val tokens: TokenUsage = TokenUsage(), val assignments: List<Assignment> = emptyList(), val agent: String? = null)

The state of a supervisor: its conversation with the user and the work of its agents.

Link copied to clipboard
@Serializable
data class TokenUsage(val inputTokens: Int = 0, val outputTokens: Int = 0, val cacheReadTokens: Int = 0, val cacheWriteTokens: Int = 0)

The tokens a call to a ChatModel read (inputTokens) and wrote (outputTokens), or those of several calls added up. TokenUsage() is no tokens, the start of a count:

Link copied to clipboard
class Tool(val spec: ToolSpec, val reconcile: suspend (JsonObject) -> String??, val execute: suspend (JsonObject) -> String)

A function a model may call. The usual way to create one is from a @Serializable class that holds the input, which also gives the model the input's schema:

Link copied to clipboard
@Serializable
data class ToolCall(val id: String, val name: String, val input: JsonObject, val invalidInput: String? = null)

A model's request to run the tool named name with input.

Link copied to clipboard
data class ToolOutcome<out State>(val state: State, val text: String)

What a StateTool did.

Link copied to clipboard
data class ToolSpec(val name: String, val description: String, val inputSchema: JsonObject)

What a model is told about a tool.

Link copied to clipboard
data class TypedResponse<out Answer>(val value: Answer, val message: ChatMessage.Assistant, val usage: TokenUsage? = null)

What ask returns for a ChatRequest.

Properties

Link copied to clipboard

The piece of text a model wrote, when this event is a node's report of one, and null for every other event. toolLoop and chatWithProgress report these. A report from inside a subgraph is read as well.

Functions

Link copied to clipboard
inline suspend fun <reified Answer> ChatModel.ask(request: ChatRequest, attempts: Int = 2): TypedResponse<Answer>

Returns the model's next message for request as an instance of the @Serializable class Answer, with the message it was read from. Use it to ask for a value at the end of a conversation. See the overload with a prompt for how the model is asked.

suspend fun <Answer> ChatModel.ask(serializer: KSerializer<Answer>, request: ChatRequest, attempts: Int = 2): TypedResponse<Answer>

Returns the model's next message for request as a value read with serializer. See the overload with a reified type.

inline suspend fun <reified Answer> ChatModel.ask(prompt: String, system: String? = null, attempts: Int = 2, attachments: List<Attachment> = emptyList()): Answer

Sends prompt as a single user message and returns the answer as an instance of the @Serializable class Answer, for a node that needs a value from the model and not a text.

Link copied to clipboard
suspend fun attach(attachment: Attachment)

Adds attachment to the result of the tool call that runs this code, so the model gets the file with the text the tool returns: the screenshot that a browser tool took, for example.

Link copied to clipboard
suspend fun ChatModel.chat(prompt: String, system: String? = null, attachments: List<Attachment> = emptyList()): String

Sends prompt as a single user message and returns the text of the answer, for a node that only needs a piece of text from the model. Call ChatModel.chat with a ChatRequest when you need to know whether the answer was cut off.

Link copied to clipboard

Returns the model's next message for request, like ChatModel.chat, and lets a streamed run watch the model write it. Use it in a node in place of ChatModel.chat:

suspend fun ChatModel.chatWithProgress(prompt: String, system: String? = null, attachments: List<Attachment> = emptyList()): String

Sends prompt as a single user message and returns the text of the answer, like chat with a prompt, and lets a streamed run watch the model write it. See the overload with a ChatRequest.

Link copied to clipboard
inline suspend fun <reified Option : Enum<Option>> DecisionModel.choose(state: String, instructions: String, describe: (Option) -> String? = { null }): Answer.Choice

Asks which constant of the enum Option fits state. The model sees the names of the constants, and for each one the text that describe returns. Read the constant from the answer with value.

suspend fun DecisionModel.choose(state: String, instructions: String, options: Map<String, String?>): Answer.Choice

Asks which of options fits state, for a node or an edge with one decision to make.

Link copied to clipboard
fun <State> StateGraph<State>.decisionEdge(from: NodeRef, model: DecisionModel, instructions: String, routes: Map<NodeRef, String?>, minConfidence: Double = 0.0, fallback: NodeRef? = null, state: suspend (State) -> String)

Adds a conditional edge from from on which a DecisionModel picks the next node: a router that understands language, at the speed and price of a decision model.

fun <State> StateGraph<State>.decisionEdge(from: String, model: DecisionModel, instructions: String, routes: Map<NodeRef, String?>, minConfidence: Double = 0.0, fallback: NodeRef? = null, state: suspend (State) -> String)

Adds a decision edge from the node named from, usually START. See the overload taking a NodeRef.

Link copied to clipboard

Runs calls in parallel on these tools and returns one result for each call, in the order of the calls.

Link copied to clipboard
fun handoffTeam(agents: List<TeamAgent>, tokenBudget: Int? = null): CompiledGraph<TeamState>

Returns a graph that is a team of agents who hand the conversation to each other: the first of agents answers, and each agent can end its turn by handing the conversation to another, which goes on from there.

Link copied to clipboard
suspend fun DecisionModel.isYes(state: String, instructions: String): Answer.YesNo

Asks a yes/no question about state. Read Answer.YesNo.isYes, or compare Answer.YesNo.probability with a line of your own.

Link copied to clipboard
fun keepLast(messages: Int): (List<ChatMessage>) -> List<ChatMessage>

Returns a function for shorten of toolLoop that leaves out the oldest messages of a conversation of more than messages messages, so that a long conversation stays within what a model can read:

Link copied to clipboard
fun memoryTools(namespace: List<String> = listOf("memories"), limit: Int = Store.DEFAULT_LIMIT, searchLimit: Int = Store.DEFAULT_SEARCH_LIMIT): List<Tool>

Returns the tools with which an agent keeps what it learns for its next conversations, in namespace of the Store of the run:

Link copied to clipboard

Returns the tool calls of the last assistant message that have no ChatMessage.ToolResult yet.

Link copied to clipboard
suspend fun DecisionModel.score(state: String, instructions: String, levels: List<String>): Answer.Score

Asks for a rating of state on the scale of levels, described from the lowest to the highest.

Link copied to clipboard
inline fun <State, reified Input> StateTool(name: String, description: String, noinline execute: suspend (State, Input) -> ToolOutcome<State>): StateTool<State>

Creates a StateTool for a graph with the state State, whose input is the @Serializable type Input. The input schema is built from the type as for a Tool. Use StateTool<State, Unit> for a tool that takes no input.

fun <State, Input> StateTool(name: String, description: String, serializer: KSerializer<Input>, execute: suspend (State, Input) -> ToolOutcome<State>): StateTool<State>

Creates a StateTool whose input is read with serializer. See the overload with a reified type.

Link copied to clipboard
fun supervisor(model: ChatModel, agents: List<TeamAgent>, system: String? = null, tokenBudget: Int? = null, retry: Retry? = null, shorten: (List<ChatMessage>) -> List<ChatMessage>? = null): CompiledGraph<TeamState>

Returns a graph that is a team of agents with a supervisor: model reads the task, gives each part to the agent that fits it, reads what comes back, and answers when the task is done.

Link copied to clipboard
inline fun <reified Input> Tool(name: String, description: String, noinline execute: suspend (Input) -> String): Tool

Creates a Tool whose input is the @Serializable type Input. The input schema is built from the type, with the text of Description annotations as the description of each property.

inline fun <reified Input> Tool(name: String, description: String, noinline reconcile: suspend (Input) -> String?, noinline execute: suspend (Input) -> String): Tool

Creates a Tool whose input is the @Serializable type Input, for a tool that does something that must not happen twice, such as a payment.

fun <Input> Tool(name: String, description: String, serializer: KSerializer<Input>, execute: suspend (Input) -> String): Tool

Creates a Tool whose input is read with serializer. See the overload with a reified type.

fun <Input> Tool(name: String, description: String, serializer: KSerializer<Input>, reconcile: suspend (Input) -> String?, execute: suspend (Input) -> String): Tool

Creates a Tool with a reconcile whose input is read with serializer. See the overload with a reified type.

Link copied to clipboard
fun toolAgent(model: ChatModel, tools: List<Tool> = emptyList(), system: String? = null, inOrder: Boolean = false, tokenBudget: Int? = null, retry: Retry? = null, shorten: (List<ChatMessage>) -> List<ChatMessage>? = null): CompiledGraph<AgentState>

Returns a graph that is a tool-calling agent: model answers the conversation in the state, and runs tools as often as it needs to before it answers.

Link copied to clipboard
fun <State> StateGraph<State>.toolLoop(model: ChatModel, tools: List<Tool> = emptyList(), messages: (State) -> List<ChatMessage>, append: (State, List<ChatMessage>) -> State, firstMessage: (State) -> String? = null, system: String? = null, then: NodeRef = NodeRef.END, modelNode: String = "model", toolsNode: String = "tools", stateTools: List<StateTool<State>> = emptyList(), inOrder: Boolean = false, countTokens: (State, TokenUsage) -> State? = null, stopWhen: (State) -> Boolean? = null, retry: Retry? = null, shorten: (List<ChatMessage>) -> List<ChatMessage>? = null): NodeRef

Adds the loop of a tool-calling agent to this graph and returns its first node.

Link copied to clipboard
inline fun <reified Option : Enum<Option>> Answer.Choice.value(): Option

The constant of Option that this answer picked, after a choose with that enum.