> ## Documentation Index
> Fetch the complete documentation index at: https://docs.uselemma.ai/llms.txt
> Use this file to discover all available pages before exploring further.

# Instrument a Go agent

> Send complete agent traces from a Go service with the Lemma Go client

Use the Go client to send one [trace](https://docs.uselemma.ai/tracing/instrumentation/concepts.md) for each agent run from a Go service. You start the trace, wrap each model call and tool call in a live handle, and end the trace once. The client measures timing, keeps spans in start order, and sends the payload defined by the [trace contract](https://docs.uselemma.ai/reference/trace-contract.md).

## Install the client

The client is a Go module with no dependencies outside the standard library. It needs Go 1.21 or later.

```bash theme={null}
go get github.com/uselemma/lemma/packages/go/tracing
```

Set `LEMMA_API_KEY` and `LEMMA_PROJECT_ID` in the environment of the process that runs your agent. [Send your first trace](https://docs.uselemma.ai/tracing/instrumentation/setup.md#set-up-manually) explains where both values come from. To record the deployed version on each trace, set `LEMMA_RELEASE`.

## Trace one agent run

One agent run is one trace. Create the client once per process, start a trace where the run starts, and end it where the run ends.

```go theme={null}
import lemma "github.com/uselemma/lemma/packages/go/tracing"

client, err := lemma.NewClient(lemma.Config{})
if err != nil {
	log.Printf("lemma disabled: %v", err)
}

func handle(ctx context.Context, threadID, question string) string {
	ctx, trace := client.StartTrace(ctx, lemma.TraceOptions{
		Name:     "support-agent",
		ThreadID: threadID,
		Input:    question,
	})
	answer := runAgent(ctx, question)
	trace.End(lemma.TraceEnd{Output: answer})
	return answer
}
```

`StartTrace` returns a context that holds the trace, so `runAgent` can add children without receiving the handle. When `NewClient` fails, the client is `nil` and every tracing call does nothing.

Trace fields map to the trace record:

* **`Name`**: the agent name Lemma groups by
* **`Input`**: the current user turn
* **`ThreadID`**: the conversation ID. Use the same value on every turn and a new trace for each turn, as [Instrumenting multi-turn agents](https://docs.uselemma.ai/guides/instrumenting-multi-turn-agents.md) describes
* **`UserID`** and **`Metadata`**: optional context for filtering. `lemma` and keys starting with `lemma.`, in metadata and attributes, are [reserved](https://docs.uselemma.ai/reference/trace-contract.md#reserved-keys) for Lemma

## Record model calls

A generation is one model call. Start it before the call and end it with the reply, so its duration is the call’s real duration.

```go theme={null}
_, generation := lemma.StartGeneration(ctx, lemma.SpanOptions{
	Name:        "chat",
	Model:       "gpt-4o",
	LLMProvider: "openai",
	Input:       messages,
})
reply, err := callModel(ctx, messages)
if err != nil {
	generation.End(lemma.SpanEnd{Error: err})
	return "", err
}
generation.End(lemma.SpanEnd{
	Output: reply.Message,
	Usage: &lemma.Usage{
		InputTokens:  lemma.Tokens(reply.Usage.PromptTokens),
		OutputTokens: lemma.Tokens(reply.Usage.CompletionTokens),
	},
})
```

Pass every message the call sends as `Input`: the system prompt, earlier turns, tool results, and the current user message. The client serializes any value `encoding/json` accepts, and also writes the list as per-message attributes.

Set only the `Usage` fields your provider returned. A nil field means the provider didn’t report it, and `lemma.Tokens(0)` records a real zero.

## Record tool calls

A tool call is one tool invocation. Start it with the arguments, then end it with the result or the error.

```go theme={null}
_, tool := lemma.StartTool(ctx, lemma.SpanOptions{
	Name:  call.Name,
	Input: call.Arguments,
})
result, err := runTool(ctx, call)
if err != nil {
	tool.End(lemma.SpanEnd{Error: err})
} else {
	tool.End(lemma.SpanEnd{Output: result})
}
```

When several tools run in goroutines, start each handle inside its own goroutine. Handles are safe for concurrent use.

## Nest work under a step

A child started from a context nests under that context’s current span. To group work, start a span and pass its context to the code that does the work.

```go theme={null}
stepCtx, step := lemma.StartSpan(ctx, lemma.SpanOptions{
	Name:  "retrieve-context",
	Input: query,
})
docs := searchDocs(stepCtx, query)
step.End(lemma.SpanEnd{Output: len(docs)})
```

A tool started inside `searchDocs` with `lemma.StartTool(stepCtx, …)` becomes a child of `retrieve-context`.

## Record failures

Record a failure on the handle where it happened. Lemma stores status `ERROR` and the error message.

* **A child failed**: pass `Error` to `End` instead of an output
* **The run failed**: call `trace.Fail(err)` before `trace.End`. The trace is still sent
* **The agent recovered**: end the failed child with its error and leave the trace successful

A child that is still open when the trace ends is sent as failed, with the error `span was still open when the trace ended`. Ending a span twice does nothing. If `trace.End` returns an error, calling it again resends the same trace; once a trace is delivered, a later `End` sends nothing.

## Understand delivery

`trace.End` sends the complete trace in one request and returns the delivery error. A failed send never panics and never changes your agent’s result. When Lemma rejects the trace, the error holds a `*lemma.IngestError` with the HTTP status; find it with `errors.As`.

* **Retries**: the client retries a network error, a timeout, a 408, a 429, or a 5xx twice, waiting at most 2 seconds between tries
* **Timeout**: each request times out after 4 seconds, and `End` returns within 10 seconds when Lemma is unreachable
* **Blocking**: `End` waits for delivery. Call it after you write the response, or in a goroutine your shutdown waits for
* **Payload size**: the client cuts any string longer than 65,536 characters and ends it with `…[truncated N chars]`, as the TypeScript and Python clients do. A `[]byte` is sent as `[binary N bytes]`. Lemma drops a whole trace when any one span is over 5 MiB, and these limits make it far less likely that one huge value pushes a span past that

## Record work that already happened

Use `RecordSpan`, `RecordGeneration`, and `RecordTool` only for work your process didn’t run, such as a tool call your provider executed. Pass the real timing so the span isn’t stamped at the time you record it.

```go theme={null}
trace.RecordTool(lemma.SpanOptions{
	Name:      "web_search",
	Input:     call.Arguments,
	Output:    call.Result,
	StartedAt: call.StartedAt,
	Duration:  call.Elapsed,
})
```

## Avoid these mistakes

Each of these produces a trace that Lemma accepts but can’t analyze correctly:

* **Creating every span when the run ends**: all spans get the same start time. Start each handle before its work
* **Recording calls in a different order**: the client sends spans in start order, so record them with their real times
* **Sending one trace per model call**: model and tool calls are children of the run’s trace
* **Trimming generation input**: a generation without its messages can’t be diagnosed
* **Leaving out `ThreadID`**: turns of one conversation appear as unrelated traces

## Related pages

> [card] [Trace contract](https://docs.uselemma.ai/reference/trace-contract.md)
>
> The payload the client sends and what each field unlocks.

> [card] [Building high-quality traces](https://docs.uselemma.ai/guides/building-high-quality-traces.md)
>
> What a complete trace contains, with examples.

> [card] [Instrumenting multi-turn agents](https://docs.uselemma.ai/guides/instrumenting-multi-turn-agents.md)
>
> Thread IDs, turns, and message history.

> [card] [Common issues](https://docs.uselemma.ai/tracing/troubleshooting/common-issues.md)
>
> Diagnose missing spans, flat trees, and blank input or output.


This documentation is built and hosted on [Mintlify](https://mintlify.com), a developer documentation platform.