Aligns Coder Agents traces with the [OpenTelemetry GenAI semantic conventions](https://opentelemetry.io/docs/specs/semconv/gen-ai/) so customers can ingest per-user model usage, spend, and tool activity without custom mapping. Scope follows the requesting team's Slack ask: agent spans, inference spans with token usage, GenAI attributes, per-user attribution, and visibility into tools that cannot be reached. Closes CODAGT-1523. ## Changes - Span names follow the conventions: `chat_turn` becomes `invoke_agent coder`, `stream` becomes `chat {model}`, and `tool_call` becomes `execute_tool {tool}`. Every stage span now carries a `stage` attribute with the old stage name, which matches the Prometheus `stage` label. Metrics are unchanged. - GenAI spans carry `gen_ai.operation.name`, `gen_ai.conversation.id` (the chat ID), `user.id` (the chat owner), and `coder.organization.id`, `coder.workspace.id`, `coder.chat.parent_id`, `coder.chat.root_id`. - `chat` spans are `CLIENT` spans with the provider, request model, and `gen_ai.request.stream` set at creation (so samplers can see them), plus requested max tokens and temperature, response ID (including OpenAI Responses metadata on non-streaming calls), the finish reason the provider reported (omitted when none, kept when Coder rejects the response), `gen_ai.output.type=json` for native OpenAI structured output, and token usage with cache read/write (only when nonzero) and reasoning breakdown. `gen_ai.usage.input_tokens` includes cached tokens, as the spec requires. Fantasy reports them separately (Google providers use the OpenAI-compatible client, which does the same). - `execute_tool` spans carry the tool name, call ID, and type (`function` for built-in tools, `extension` for MCP and caller tools), all set at creation. - Every model call records a `chat` span: assistant streams (`stage=stream`), and, as `stage=model_call`, the advisor, compaction summaries plus titles, status labels, and chat summaries (via `StageTracer.TraceModelCalls` in `resolveModelCall`). `model_call` has no histogram, so the `stream` metric is unchanged. - Failed spans get `error.type`. A tool that returns an error result, as MCP clients do for an unreachable server, ends its span with `error.type=tool_error` without recording the result text. - GenAI attributes carry metadata only; prompts, responses, and tool payloads are not recorded. The docs note that other spans and events in the trace, such as AI Gateway spans and server log events, can contain content. - Docs state known limits: Anthropic server-tool responses undercount input tokens in both spans and AI Gateway cost control (the client keeps first-iteration occupancy), the OpenAI-compatible client drops reported cache writes, request attributes are what Coder requested, and the exporter is OTLP/gRPC, plaintext unless a certificate is configured. - New docs page: `docs/coder-agents/platform-controls/opentelemetry-tracing.md`. - `coderd/x/chatd/ARCHITECTURE.md` gains a GenAI semantic conventions subsection under Lifecycle tracing. Existing attributes (`provider`, `model`, `chat_id`, `tool_name`, ...) are kept so current queries on attributes keep working. Queries on span names need to switch to the `stage` attribute or the new names. <details> <summary>Decision log</summary> - **Convention version:** semconv v1.41.0, the last core release that ships the GenAI attributes. Later releases moved them to `semantic-conventions-genai`. The PR uses the Go constants from `go.opentelemetry.io/otel/semconv/v1.41.0`, which is already in the module graph. No experiment gate: chatd is already under `x/`, and the docs page notes that the conventions may change. - **Rename vs. attributes only:** spans are renamed because the conventions define the span names. The `stage` attribute keeps lifecycle identity stable for dashboards and tests. - **Agent name:** `gen_ai.agent.name=coder` for root chats and subagents alike. `chat_kind` and `coder.chat.parent_id` tell them apart. - **Provider name mapping:** configured provider type to well-known values (`openai`, `anthropic`, `azure.ai.openai`, `aws.bedrock`, `gcp.gemini`). Anthropic providers with Bedrock settings report `aws.bedrock`. The `invoke_agent` span gets the provider after `prepare` resolves the turn's model, since the turn span starts first. Other types (`openrouter`, `openai-compat`, `vercel`, `copilot`) are passed through as-is. - **No content capture:** `gen_ai.input.messages`, `gen_ai.output.messages`, and tool arguments/results are opt-in in the conventions and not needed for usage and spend attribution, so they are left for a follow-up behind an explicit deployment flag. - **Out of scope:** GenAI metrics (`gen_ai.client.token.usage`, `gen_ai.client.operation.duration`), an aggregated token total on the `invoke_agent` span, a cost attribute, span links between subagent and parent traces, and correlation IDs with AI Gateway interceptions (an open question in the issue). Subagent turns join the parent only through `coder.chat.root_id`; a span link needs the spawning span context persisted across chats and runners. Spans carry tokens, not cost; cost stays in the existing cost API. - **Identity snapshot:** chat identity is taken when the turn opens. A workspace created mid-turn appears on spans from the next turn. </details> --- Generated by Coder Agents on behalf of @f0ssel.
292 lines
10 KiB
Go
292 lines
10 KiB
Go
package chatd
|
|
|
|
import (
|
|
"context"
|
|
"sync/atomic"
|
|
|
|
"charm.land/fantasy"
|
|
fantasyopenai "charm.land/fantasy/providers/openai"
|
|
"golang.org/x/xerrors"
|
|
|
|
"cdr.dev/slog/v3"
|
|
"github.com/coder/coder/v2/coderd/database"
|
|
"github.com/coder/coder/v2/coderd/database/db2sdk"
|
|
"github.com/coder/coder/v2/coderd/database/dbauthz"
|
|
"github.com/coder/coder/v2/coderd/util/ptr"
|
|
"github.com/coder/coder/v2/coderd/x/chatd/chatdebug"
|
|
"github.com/coder/coder/v2/coderd/x/chatd/chaterror"
|
|
"github.com/coder/coder/v2/coderd/x/chatd/chatloop"
|
|
"github.com/coder/coder/v2/coderd/x/chatd/chatprovider"
|
|
"github.com/coder/coder/v2/codersdk"
|
|
)
|
|
|
|
const defaultChatMaxOutputTokens = int64(32_000)
|
|
|
|
type modelCallSpec struct {
|
|
// purpose labels resolver logs only; it does not affect call behavior.
|
|
purpose string
|
|
chat database.Chat
|
|
explicitConfig *database.ChatModelConfig
|
|
// requestedEffort overrides the config's default reasoning effort,
|
|
// clamped to the config's max.
|
|
requestedEffort *string
|
|
// maxOutputTokens overrides the config's output-token cap and the
|
|
// package default.
|
|
maxOutputTokens *int64
|
|
// chatdScopedRoute resolves the route with chatd scope. Deployment-wide
|
|
// override models must route for user-owned chats regardless of the
|
|
// caller's actor.
|
|
chatdScopedRoute bool
|
|
// requireOpenAIResponses forces the Responses API when the route uses an
|
|
// OpenAI client, and fails if the config explicitly disables it.
|
|
requireOpenAIResponses bool
|
|
buildOptions modelBuildOptions
|
|
}
|
|
|
|
func chatRequestedEffort(chat database.Chat) *string {
|
|
if !chat.LastReasoningEffort.Valid {
|
|
return nil
|
|
}
|
|
return new(string(chat.LastReasoningEffort.ChatReasoningEffort))
|
|
}
|
|
|
|
// modelCallConfigParseError lets the advisor distinguish malformed options
|
|
// from route and client failures when deciding whether to fall back.
|
|
type modelCallConfigParseError struct{ err error }
|
|
|
|
func (e modelCallConfigParseError) Error() string {
|
|
return "parse model call config: " + e.err.Error()
|
|
}
|
|
|
|
func (e modelCallConfigParseError) Unwrap() error { return e.err }
|
|
|
|
type resolvedModelCall struct {
|
|
model chatprovider.Model
|
|
dbConfig database.ChatModelConfig
|
|
callConfig codersdk.ChatModelCallConfig
|
|
providerOptions fantasy.ProviderOptions
|
|
resolvedProvider string
|
|
resolvedModel string
|
|
resolvedEffort string
|
|
route aiGatewayModelRoute
|
|
debugEnabled bool
|
|
// reasoningRejected reports whether the provider rejected encrypted
|
|
// reasoning replayed into a call to model.
|
|
reasoningRejected *atomic.Bool
|
|
}
|
|
|
|
// stageModel uses the configured provider type rather than
|
|
// resolvedProvider, which is inferred from the model name for types such
|
|
// as copilot.
|
|
func (r resolvedModelCall) stageModel() chatloop.StageModel {
|
|
stageModel := chatloop.StageModel{
|
|
ProviderType: string(r.route.Provider.Type),
|
|
Model: r.resolvedModel,
|
|
Effort: r.resolvedEffort,
|
|
}
|
|
if r.model.Valid() {
|
|
stageModel.Provider = r.model.Provider()
|
|
}
|
|
// Settings were validated when the provider was configured.
|
|
if settings, err := db2sdk.AIProviderSettings(r.route.Provider.Settings); err == nil {
|
|
stageModel.Bedrock = settings.Bedrock != nil
|
|
}
|
|
return stageModel
|
|
}
|
|
|
|
// resolveModelCall is the single pipeline from a spec to a ready model
|
|
// client plus the call metadata flows need.
|
|
func (p *Server) resolveModelCall(ctx context.Context, spec modelCallSpec) (resolvedModelCall, error) {
|
|
out := resolvedModelCall{}
|
|
|
|
var modelName string
|
|
var configOptions []byte
|
|
switch {
|
|
case spec.explicitConfig != nil:
|
|
out.dbConfig = *spec.explicitConfig
|
|
modelName = out.dbConfig.Model
|
|
configOptions = out.dbConfig.Options
|
|
default:
|
|
dbConfig, err := p.resolveModelConfig(ctx, spec.chat)
|
|
if err != nil {
|
|
return resolvedModelCall{}, xerrors.Errorf("resolve model config: %w", err)
|
|
}
|
|
if !dbConfig.Enabled {
|
|
return resolvedModelCall{}, xerrors.Errorf("chat model config %s is disabled", dbConfig.ID)
|
|
}
|
|
out.dbConfig = dbConfig
|
|
modelName = dbConfig.Model
|
|
configOptions = dbConfig.Options
|
|
}
|
|
|
|
// clientCallConfig drives client construction; out.callConfig drives
|
|
// per-call option derivation.
|
|
clientCallConfig, err := parseModelConfigOptions(configOptions)
|
|
if err != nil {
|
|
return resolvedModelCall{}, modelCallConfigParseError{err: err}
|
|
}
|
|
out.callConfig = clientCallConfig
|
|
switch {
|
|
case spec.maxOutputTokens != nil:
|
|
out.callConfig.MaxOutputTokens = spec.maxOutputTokens
|
|
case out.callConfig.MaxOutputTokens == nil:
|
|
out.callConfig.MaxOutputTokens = ptr.Ref(defaultChatMaxOutputTokens)
|
|
}
|
|
|
|
routeCtx := ctx
|
|
if spec.chatdScopedRoute {
|
|
//nolint:gocritic // Deployment-wide override models need chatd-scoped provider reads for user-owned chats.
|
|
routeCtx = dbauthz.AsChatd(ctx)
|
|
}
|
|
out.route, err = p.resolveModelRouteForConfig(routeCtx, spec.chat.OwnerID, out.dbConfig)
|
|
if err != nil {
|
|
return resolvedModelCall{}, err
|
|
}
|
|
if spec.requireOpenAIResponses &&
|
|
chatprovider.NormalizeProvider(string(out.route.Provider.Type)) == fantasyopenai.Name {
|
|
clientCallConfig.OpenAIConfig, err = requireResponsesAPI(clientCallConfig.OpenAIConfig, modelName)
|
|
if err != nil {
|
|
return resolvedModelCall{}, err
|
|
}
|
|
out.callConfig.OpenAIConfig = clientCallConfig.OpenAIConfig
|
|
}
|
|
|
|
// The resolved identity feeds metadata, logs, and debug labels. The
|
|
// client is constructed with the configured model string so gateway
|
|
// validation sees the name exactly as configured.
|
|
out.resolvedProvider, out.resolvedModel, err = chatprovider.ResolveModelWithProviderHint(
|
|
modelName,
|
|
out.route.ModelProviderHint,
|
|
)
|
|
if err != nil {
|
|
return resolvedModelCall{}, xerrors.Errorf("resolve model metadata: %w", err)
|
|
}
|
|
|
|
debugSvc := p.debugService()
|
|
out.debugEnabled = debugSvc != nil && debugSvc.IsEnabled(ctx, spec.chat.ID, spec.chat.OwnerID)
|
|
|
|
// Coder-scale effort, before provider mapping can change or drop it.
|
|
if effectiveEffort := chatprovider.ResolveReasoningEffort(spec.requestedEffort, out.callConfig.ReasoningEffort); effectiveEffort != nil {
|
|
out.resolvedEffort = *effectiveEffort
|
|
}
|
|
|
|
buildOpts := spec.buildOptions
|
|
buildOpts.RecordHTTP = out.debugEnabled
|
|
buildOpts.StageModel = out.stageModel()
|
|
model, err := p.newModel(ctx, modelClientRequest{
|
|
Chat: spec.chat,
|
|
ModelName: modelName,
|
|
UserAgent: chatprovider.UserAgent(),
|
|
ExtraHeaders: chatprovider.CoderHeaders(spec.chat),
|
|
CallConfig: clientCallConfig,
|
|
}, out.route, buildOpts)
|
|
if err != nil {
|
|
return resolvedModelCall{}, xerrors.Errorf("create model: %w", err)
|
|
}
|
|
// Innermost, so each provider attempt of a fallback records its own span.
|
|
tracedModel := buildOpts.StageModel
|
|
tracedModel.Provider = model.Provider()
|
|
model = model.WithLanguageModel(p.stages.TraceModelCalls(model.LanguageModel(), chatloop.TracedModelOptions{
|
|
StageModel: tracedModel,
|
|
Identity: chatIdentity(spec.chat),
|
|
// chatd builds every client with its default object mode, and only
|
|
// the native OpenAI client's default sends a JSON schema; the
|
|
// others force a tool call.
|
|
JSONObjects: model.Provider() == fantasyopenai.Name,
|
|
}))
|
|
model = p.withThinkingDropBlock(model, out.route.Provider.ID, clientCallConfig, spec.chat.ID)
|
|
model = p.withQuickgenParamFallback(model, out.route.Provider.ID)
|
|
out.reasoningRejected = &atomic.Bool{}
|
|
model = p.withEncryptedReasoningFallback(model, spec.chat.ID, out.reasoningRejected)
|
|
|
|
if out.debugEnabled {
|
|
model = model.WithLanguageModel(chatdebug.WrapModel(model.LanguageModel(), debugSvc, chatdebug.RecorderOptions{
|
|
ChatID: spec.chat.ID,
|
|
OwnerID: spec.chat.OwnerID,
|
|
}))
|
|
}
|
|
out.model = model
|
|
|
|
// Only the derived provider options see the coerced config; callConfig
|
|
// stays as configured.
|
|
out.providerOptions = chatprovider.ProviderOptionsForCall(
|
|
out.model,
|
|
coerceBedrockReasoningSummary(out.route.Provider.Type, modelName, out.callConfig),
|
|
spec.requestedEffort,
|
|
)
|
|
|
|
p.logger.Debug(ctx, "resolved model call",
|
|
slog.F("purpose", spec.purpose),
|
|
slog.F("chat_id", spec.chat.ID),
|
|
slog.F("provider", out.resolvedProvider),
|
|
slog.F("model", out.resolvedModel),
|
|
slog.F("reasoning_effort", out.resolvedEffort),
|
|
slog.F("debug_enabled", out.debugEnabled),
|
|
)
|
|
return out, nil
|
|
}
|
|
|
|
// requireResponsesAPI returns an OpenAI config that selects the Responses API.
|
|
// It never mutates config.
|
|
func requireResponsesAPI(
|
|
config *codersdk.ChatModelOpenAIConfig,
|
|
modelName string,
|
|
) (*codersdk.ChatModelOpenAIConfig, error) {
|
|
var out codersdk.ChatModelOpenAIConfig
|
|
if config != nil {
|
|
if config.UseResponsesAPI != nil && !*config.UseResponsesAPI {
|
|
return nil, chaterror.WithClassification(
|
|
xerrors.Errorf("model %q disables the OpenAI Responses API, which computer use requires", modelName),
|
|
chaterror.ClassifiedError{
|
|
Kind: codersdk.ChatErrorKindConfig,
|
|
Retryable: false,
|
|
Detail: "Ask an administrator to enable the Responses API for this model or choose another computer use model.",
|
|
},
|
|
)
|
|
}
|
|
out = *config
|
|
}
|
|
out.UseResponsesAPI = ptr.Ref(true)
|
|
return &out, nil
|
|
}
|
|
|
|
func (r resolvedModelCall) newCall() fantasy.Call {
|
|
return fantasy.Call{
|
|
ProviderOptions: r.providerOptions,
|
|
MaxOutputTokens: r.callConfig.MaxOutputTokens,
|
|
Temperature: r.callConfig.Temperature,
|
|
TopP: r.callConfig.TopP,
|
|
TopK: r.callConfig.TopK,
|
|
PresencePenalty: r.callConfig.PresencePenalty,
|
|
FrequencyPenalty: r.callConfig.FrequencyPenalty,
|
|
}
|
|
}
|
|
|
|
// compactionSummaryCall follows the resolved call template, except summaries
|
|
// must not call tools. Streaming avoids the Anthropic SDK's non-streaming
|
|
// duration limit, while the explicit cap prevents adaptive thinking from
|
|
// exhausting fantasy's smaller provider default before producing summary text.
|
|
// The cap is not raised: the configured cap is the provider ceiling chatd
|
|
// knows, and providers reject a larger one. GenerateCompaction can only
|
|
// lower it, to the remaining context window.
|
|
func compactionSummaryCall(resolved resolvedModelCall) fantasy.Call {
|
|
call := resolved.newCall()
|
|
toolChoiceNone := fantasy.ToolChoiceNone
|
|
call.ToolChoice = &toolChoiceNone
|
|
return call
|
|
}
|
|
|
|
func (r resolvedModelCall) newObjectCall(schemaName, schemaDescription string, maxOutputTokens int64) fantasy.ObjectCall {
|
|
return fantasy.ObjectCall{
|
|
SchemaName: schemaName,
|
|
SchemaDescription: schemaDescription,
|
|
MaxOutputTokens: ptr.Ref(maxOutputTokens),
|
|
Temperature: r.callConfig.Temperature,
|
|
TopP: r.callConfig.TopP,
|
|
TopK: r.callConfig.TopK,
|
|
PresencePenalty: r.callConfig.PresencePenalty,
|
|
FrequencyPenalty: r.callConfig.FrequencyPenalty,
|
|
ProviderOptions: r.providerOptions,
|
|
}
|
|
}
|