AgentObserver
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:
val cost = object : AgentObserver {
override fun onModelCallCompleted(call: ObservedModelCall, usage: TokenUsage?) {
println("${call.caller}: ${usage?.total ?: 0} tokens")
}
}
agent.invoke(AgentState("Where is my pizza?"), GraphConfig(observers = listOf(cost)))The rules of GraphObserver hold:
No conversation. An observer learns which model and which tool were called, the tokens and whether a tool returned an error, but not the messages, the input of a tool or its result. Only a ConversationObserver is told those. No observer gets the state of the graph.
Every start has one end. A model call that started ends with exactly one of onModelCallCompleted and onModelCallFailed, and a tool call with exactly one of onToolCallCompleted and onToolCallFailed, also when the run is cancelled.
Calls from several coroutines, because the tools of an answer run at the same time.
A call outside a running node or condition, or straight to ChatModel.chat, is not reported.
Inheritors
Functions
The model of call answered, with the tokens its provider reported, or null when it reported none.
call asks its model. A try of a node with a retry asks again, as a new call.
call ended without a result: it was cancelled, the tool paused the run with interrupt, or it threw an error that ends the run, such as an OutOfMemoryError.
call runs its tool.