Tracing
A run in production should leave a trace: which nodes ran and how long each took, which nodes the edges chose, which models and tools were called and what they cost, which tries failed, and where the run stopped. A GraphObserver is told all of that, and telar-otel sends it to OpenTelemetry, on every platform, so it shows up in the tools a team already uses, such as Jaeger, Grafana Tempo or Honeycomb.
OpenTelemetry
dependencies {
implementation("dev.deeptelar:telar-otel:0.1.0-alpha19")
}telar-otel works on every platform Telar runs on: Android, iOS, the desktop, servers and the browser, with Kotlin/JS and Kotlin/Wasm. It has two observers that record the same spans:
| Observer | Platforms | Sends the spans |
|---|---|---|
OtlpObserver | Every platform | Itself, as OTLP over HTTP, with a Ktor HttpClient of the app |
OpenTelemetryObserver | JVM and Android | Through the OpenTelemetry SDK or Java agent the app already has |
A multiplatform app uses OtlpObserver in its common code. A server on the JVM that already has OpenTelemetry uses OpenTelemetryObserver, so that a run is part of the traces of its requests.
On every platform
Give an OtlpObserver to the runs you want to trace:
val tracing =
OtlpObserver(
client = httpClient,
scope = appScope,
endpoint = "https://collector.example.com/v1/traces",
serviceName = "help-desk",
)
val config = GraphConfig(threadId = "ticket-42", checkpointer = checkpointer, observers = listOf(tracing))
graph.invoke(ticket, config)clientis a KtorHttpClientthat the app creates, with the engine of its platform (Jsin the browser,Darwinon iOS,OkHttpon Android,CIOorJavaon the JVM), and closes.scopeis where the spans are sent from, such as the scope of the app or aviewModelScope.endpointis the/v1/tracesaddress of an OpenTelemetry Collector, or of any backend that receives OTLP over HTTP. The default is a collector on the same machine,http://localhost:4318/v1/traces. A backend that wants a key gets it inheaders.resourceadds attributes of the app, such asservice.version.
A span is sent when it ends, together with the others that end within exportDelay (one second). A run never fails because of tracing: a request that fails goes to onExportFailed, and its spans are dropped. Before the app ends, call tracing.flush(), which sends what is left and returns when the collector has answered.
In a browser, the collector is on another origin than the page, so it has to allow it. In the configuration of the OpenTelemetry Collector:
receivers:
otlp:
protocols:
http:
cors:
allowed_origins: ["https://app.example.com"]A key in headers can be read by everyone who opens the page, so a page sends its spans to a collector of your own, not straight to a backend that wants a secret. A page can be closed at any time: call flush() when it is hidden (the visibilitychange event).
What a node calls. While a node runs, its coroutine context holds a TraceContext with the ids of its span. The Ktor plugin Traceparent sends them as the traceparent header, so that a server of the app records its spans inside the node:
val api = HttpClient(Js) { install(Traceparent) }Inside a trace of the app. A run is a trace of its own, unless its coroutine context holds a TraceContext: then the run is recorded inside that span. A server continues the trace of the request that started the run, from its traceparent header:
post("/tickets") {
// null when the request has no traceparent, or one that is not valid
val trace = TraceContext.parse(call.request.headers["traceparent"])
val result = withContext(trace ?: EmptyCoroutineContext) { graph.invoke(ticket, config) }
call.respond(result.state)
}A browser page that sends its requests with Traceparent and a server that reads the header this way make one trace: the node in the page, the request, and the run on the server inside it. A run that a node starts itself, such as a graph that a tool runs, is inside the span of that node without anything more.
With the OpenTelemetry SDK of Java
Give an OpenTelemetryObserver to the runs you want to trace:
val tracing = OpenTelemetryObserver(openTelemetry)
val config = GraphConfig(threadId = "ticket-42", checkpointer = checkpointer, observers = listOf(tracing))
graph.invoke(ticket, config)openTelemetry is the OpenTelemetry of your app, the one that knows where the spans go. Without an argument, the observer takes the one the OpenTelemetry Java agent or GlobalOpenTelemetry.set registered. One observer can be shared by every run of the app.
The span of a node is current while the node runs. What the node calls opens its spans inside it: an HTTP client with OpenTelemetry instrumentation, a database driver, another traced library. And a run that starts inside a span, such as the span of a request to your server, is a child of that span. OtlpObserver does not know the spans of the SDK: it needs a TraceContext around the run (see On every platform).
The spans
A run looks the same with both observers:
telar.run telar.thread_id=ticket-42 telar.outcome=completed
├─ telar.node classify telar.step=1
├─ telar.edge classify telar.step=1 telar.next_nodes=[research]
├─ telar.node research telar.step=2
│ └─ telar.run (the subgraph that "research" runs)
│ ├─ telar.node search telar.step=1
│ └─ telar.node sum telar.step=2
└─ telar.node reply telar.step=3
└─ POST api.anthropic.com (with OpenTelemetryObserver, the span of an instrumented HTTP client)- The run is a span named
telar.run, withtelar.thread_idandtelar.outcome:completed,interrupted,failedorcancelled. A run that paused also hastelar.next_nodes. An eventtelar.stepfor each step names the nodes that ran and the nodes the edges chose next, and an eventtelar.checkpointmarks each saved checkpoint. - A node is a span named
telar.node <name>inside its run, withtelar.node,telar.stepandtelar.outcome. Each try that failed and was followed by another is an eventtelar.retry, with the attempt, the pause and the exception. - An edge with a condition is a span named
telar.edge <from>inside its run, withtelar.edge.from,telar.stepandtelar.outcome, andtelar.next_nodes: what the condition chose. Its step is the one whose results it routes, 0 for an edge fromSTART. A plainedgecalls nothing and has no span; the eventtelar.stepnames where it went. - A subgraph is a
telar.runinside the span of the node that runs it. - A failure is recorded on the node or the edge and on the run, with the status
ERROR. A cancelled node, for example the other node of a step in which one node failed, is not an error.
Both observers are also an AgentObserver, so the calls to models and tools inside a node are spans of the node, and the call that the condition of a decisionEdge makes is a span of its edge. They have the names and attributes of the semantic conventions for generative AI, so a backend that knows them shows them as calls to a model. A tool agent looks like this:
telar.run telar.thread_id=ticket-42
├─ telar.node model telar.step=1
│ └─ chat gpt-5 gen_ai.request.model=gpt-5 gen_ai.usage.input_tokens=812 gen_ai.usage.output_tokens=64
├─ telar.node tools telar.step=2
│ └─ execute_tool order_status gen_ai.tool.name=order_status gen_ai.tool.call.id=toolu_01...
└─ telar.node model telar.step=3
└─ chat gpt-5 gen_ai.request.model=gpt-5 gen_ai.usage.input_tokens=901 gen_ai.usage.output_tokens=38A call to a model is a span named
chat <model>, of kindCLIENT, withgen_ai.operation.name, the model and the tokens its provider reported.gen_ai.request.modelis thenameof theChatModel, the model it was built with, andgen_ai.response.modelis the model that answered, as the provider names it in its answer (for examplegpt-4o-mini-2024-07-18forgpt-4o-mini). With the model and the tokens, a backend such as Langfuse shows what each call cost.gen_ai.usage.input_tokenscounts the tokens read from a cache too, andgen_ai.usage.output_tokensthe tokens the model wrote.gen_ai.usage.cache_read.input_tokensandgen_ai.usage.cache_write.input_tokensare there when they are not 0. A call that failed has the statusERRORand anerror.type, the name of the exception's class.The model classes of Telar know their model. A
ChatModelof your own has nonameunless it overrides it, and its span is then namedchat, withoutgen_ai.request.model:kotlinclass MyModel : ChatModel { override val name: String = "my-model-v2" override suspend fun chat(request: ChatRequest): ChatResponse = ... }A tool call is a span named
execute_tool <name>, withgen_ai.tool.nameandgen_ai.tool.call.id. A tool that returned an error to the model has the statusERRORand theerror.typetool_error, although the run goes on, because the model is told about the error. A call that ended without a result, because the run was cancelled or paused, has no status: the span of the node says what happened.
The span of a call is not the current span while the call runs, because the functions of an observer are not suspend. So the span of a model's HTTP request, from an instrumented client or the Traceparent plugin, is inside the span of the node, next to chat.
exception.type is the name of the class with its package, except on Kotlin/JS, which only knows the name of the class.
Recording the conversation
The spans of the calls say which model and which tool ran, but not what was said. To see that, the messages the model was sent, its answer, and the input and result of each tool, turn on recordContent:
val tracing = OtlpObserver(httpClient, appScope, endpoint = collector, recordContent = true)
// or, on the JVM
val tracing = OpenTelemetryObserver(openTelemetry, recordContent = true)The spans then get the attributes of the conventions for generative AI, each one JSON in a string:
| Span | Attribute | What it holds |
|---|---|---|
chat <model> | gen_ai.system_instructions | The system prompt |
gen_ai.input.messages | The messages the model was sent: user, assistant with its tool calls, and tool with the results | |
gen_ai.output.messages | The answer, with its tool calls and a finish_reason: stop, tool_call, or length when it was cut off | |
execute_tool <name> | gen_ai.tool.call.arguments | The input the model wrote for the tool |
gen_ai.tool.call.result | What the tool returned to the model |
Langfuse shows them as the input and output of each generation and each tool, with the system prompt as the first message of the input. The messages are the ones the model was really sent: the part of the conversation that shorten keeps, the prompt that ask adds when it asks again, and the prompt that a ChatDecisionModel builds. A call that failed keeps what it sent, which is often why you open the trace.
To keep the spans a sensible size:
- Each text is cut at
maxContentLengthcharacters, 8,192 unless you give another, with a note of how long it was:Where is m… [cut, 18 characters in all]. Eachchatspan repeats the whole conversation the model was sent, so a long one adds up. - An image or a PDF is a note of its type and size, such as
[image/png, 47 KB]. Its bytes are never recorded. A file sent by its address keeps the address. - What a provider adds to a message, such as the thinking of Claude, and the tools the model was offered are left out.
Personal data
The conversation holds what the users of your app wrote and what your tools found, which can be personal data. That is why recordContent is off by default. Turn it on only when you know who can read the traces and how long they are kept, for example in development, or with the consent of the people whose conversations they are.
What is never recorded
The state of a run is not recorded, and neither is what a node reports with reportProgress, such as the text a model writes. The messages of a call to a model, the input of a tool and its result are recorded only with recordContent. They can hold personal data. An observer is not even given the state. To see what a step wrote, read the history of the thread or stream the run.
An observer of your own
GraphObserver is in telar-core, so it works on every platform. Override what you need; every other function does nothing:
val slowNodes =
object : GraphObserver {
private val started = ConcurrentHashMap<ObservedNode, TimeMark>()
override fun onNodeStarted(node: ObservedNode) {
started[node] = TimeSource.Monotonic.markNow()
}
override fun onNodeCompleted(node: ObservedNode) {
val took = started.remove(node)?.elapsedNow() ?: return
if (took > 5.seconds) log.warn("${node.name} took $took in step ${node.step}")
}
override fun onNodeFailed(node: ObservedNode, cause: Throwable) {
started.remove(node)
}
}An observer is told:
| Function | When |
|---|---|
onRunStarted | A run starts: invoke, stream, resume, fork or a subgraph |
onRunCompleted, onRunInterrupted, onRunFailed | The run ended. Exactly one of them, also when the run is cancelled |
onNodeStarted | A node starts. Once, however often it is tried |
onNodeRetry | A try failed, and the node runs again after a pause |
onNodeProgress | A node called reportProgress. Only in a run that is streamed |
onNodeCompleted, onNodeInterrupted, onNodeFailed | The node ended. Exactly one of them |
onEdgeStarted | The condition of an edge starts: conditionalEdge, conditionalFanOut, decisionEdge. A plain edge is not told |
onEdgeCompleted, onEdgeFailed | The condition chose its targets, or failed. Exactly one of them |
onStepCompleted | A step ended, with the nodes the edges chose next |
onCheckpointSaved | The checkpointer saved a checkpoint |
nodeContext, edgeContext | Returns what to add to the coroutine context of a node or of the condition of an edge, such as a trace span |
A run is the same ObservedRun from its start to its end, a node the same ObservedNode, and an edge the same ObservedEdge, so an observer can keep what it needs in a map with them as keys. The conditions of a step run one after the other, after every node of the step ended. The parent of the run of a subgraph is the node that runs it.
What to keep in mind:
- Return quickly. The functions are not
suspend, and the engine waits for them. Hand slow work, such as sending data over the network, to a queue. - Be safe for threads. The nodes of a step run in parallel and call the observer at the same time, maybe on different threads.
- Do not throw. What an observer throws fails the run.
Calls to models and tools
An AgentObserver, from telar-agent, is a GraphObserver that is also told about every call to a model and every tool call inside the nodes of a run and in the conditions of its edges. That is enough to count what a run costs, to log which tools the model used, or to show the calls in a debugger:
val cost =
object : AgentObserver {
private val tokens = ConcurrentHashMap<String, Int>()
override fun onModelCallCompleted(call: ObservedModelCall, usage: TokenUsage?) {
tokens.merge(call.caller.run.threadId, usage?.total ?: 0, Int::plus)
}
override fun onToolCallCompleted(call: ObservedToolCall, isError: Boolean) {
if (isError) log.warn("${call.name} returned an error in ${call.caller}")
}
}
agent.invoke(AgentState("Where is my pizza?"), GraphConfig(observers = listOf(cost)))| Function | When |
|---|---|
onModelCallStarted | A node asks a model. A node with a retry asks again as a new call |
onModelCallCompleted, onModelCallFailed | The model answered, with the tokens its provider reported, or failed. Exactly one of them |
onToolCallStarted | A node runs a tool the model called |
onToolCallCompleted, onToolCallFailed | The tool returned a result, or an error for the model (isError); or the call ended without one: cancelled, or paused by interrupt. Exactly one of them |
The calls of toolLoop and toolAgent are reported, and those of chatWithProgress, ask, a ChatDecisionModel and List<Tool>.execute in a node or a condition of your own. ask reports each time it asks, so an answer that could not be read and was asked again is two calls. A call straight to ChatModel.chat, or outside a run, is not.
Each call has its caller: the ObservedNode that made it, or the ObservedEdge whose condition made it, as with a decisionEdge:
when (val caller = call.caller) {
is ObservedNode -> println("${caller.name} asked a model")
is ObservedEdge -> println("the edge from ${caller.from} asked a model")
}An AgentObserver is not given the conversation: not the messages, the input of a tool or its result. An observer that needs them implements ConversationObserver, an AgentObserver that is also told what each call sends and gets back:
val transcript =
object : ConversationObserver {
override fun onModelCallResponse(call: ObservedModelCall, response: ChatResponse) {
log.debug("${call.caller}: ${response.message.text}")
}
override fun onToolCallResult(call: ObservedToolCall, result: ChatMessage.ToolResult) {
log.debug("${call.name} returned ${result.text}")
}
}| Function | When |
|---|---|
onModelCallRequest | Right after onModelCallStarted, with the ChatRequest the model is sent |
onModelCallResponse | Right before onModelCallCompleted, with the ChatResponse. A streamed answer arrives whole |
onToolCallInput | Right after onToolCallStarted, with the model's ToolCall. An input that is not JSON is in invalidInput |
onToolCallResult | Right before onToolCallCompleted, with the ToolResult the model gets |
A call that fails has its request but no response, and a tool call that ends without a result has its input but no result.
The observers of telar-otel are agent observers: they record each call as a span inside its node or edge (see The spans).
A library can tell observers of its own kind about what happens in a node or a condition the same way, with forEachObserver from telar-core.