Manual Instrumentation for Azure Functions (JavaScript)

Learn how to manually instrument your agents to capture spans, token usage, and tool execution.

If your AI library does not have automatic instrumentation, create spans manually with well-defined names and data attributes. This gives Sentry a complete trace of how long the agent and each model or tool call took, where failures happened, and how the agent produced its final response.

This page describes the minimum span structure and attributes Sentry needs, then covers richer data such as messages, streaming metrics, and custom costs.

For conversations and privacy (setConversationId, setUser, dataCollection), see the Agent Tracing guide.

When instrumenting an agent loop, spans nest like this:

Copied
── invoke_agent My Agent          (gen_ai.invoke_agent)
   ├── chat gpt-4o                (gen_ai.chat)         ← 1st LLM call
   ├── execute_tool get_weather   (gen_ai.execute_tool)  ← tool run
   ├── chat gpt-4o                (gen_ai.chat)         ← 2nd LLM call
   └── ...

gen_ai.invoke_agent covers the complete agent run. Create one gen_ai.chat child for every model request and one gen_ai.execute_tool child for every tool execution. Model and tool spans are siblings: end the model span before running a requested tool so model latency does not include tool execution time.

A gen_ai.chat span can also appear without an agent parent for standalone LLM calls.

Set these attributes when the span starts, before the model or tool call, so head-based sampling can use them:

  • gen_ai.operation.name — required; classifies the span (chat, invoke_agent, execute_tool, …)
  • gen_ai.provider.name — e.g. openai, anthropic
  • gen_ai.request.model — requested model (pass the raw provider string)
  • gen_ai.agent.name / gen_ai.tool.name — when applicable

Use the span names shown in the examples: invoke_agent {agent name}, chat {requested model}, and execute_tool {tool name}. Record accurate start and end times. If an operation fails, set the span status to ERROR and set error.type to a low-cardinality error code or exception class.

Run the agent span in the caller's active trace context. For calls between services, follow the Distributed Tracing guide so the agent run stays connected to the rest of the trace.

To group turns into a Conversation, call setConversationId() with the application's existing chat or session ID. Reuse that ID across turns and traces. If there is no conversation ID, omit it instead of deriving one from a trace or request ID.

Complex values (messages, tool definitions, arrays) must be JSON strings — span attributes only accept primitives.

For manual spans, prompt, response, and tool content is whatever you set on the span. Omit those attributes, or gate them yourself, when you do not want to capture content.

This span represents a request to an LLM model or service that generates a response based on the input prompt.

Copied
const messages = [
  { role: "user", parts: [{ type: "text", content: "Tell me a joke" }] },
];
const tools = [
  { name: "get_weather", description: "Get weather for a city" },
];

await Sentry.startSpan(
  {
    op: "gen_ai.chat",
    name: "chat o3-mini",
    attributes: {
      "gen_ai.operation.name": "chat",
      "gen_ai.request.model": "o3-mini",
      "gen_ai.provider.name": "openai",
      "gen_ai.agent.name": "Weather Agent", // when this call is under an agent
      "gen_ai.system_instructions": "You are a helpful assistant.",
      "gen_ai.tool.definitions": JSON.stringify(tools),
      "gen_ai.input.messages": JSON.stringify(messages),
    },
  },
  async (span) => {
    // Call your model provider; map its response into span attributes below
    const result = await yourLLMClient.chat({
      model: "o3-mini",
      messages,
    });

    span.setAttributes({
      "gen_ai.response.model": result.model,
      "gen_ai.response.id": result.id,
      "gen_ai.output.messages": JSON.stringify([
        {
          role: "assistant",
          parts: [{ type: "text", content: result.text }],
        },
      ]),
      "gen_ai.response.finish_reasons": JSON.stringify([
        result.finishReason,
      ]),
      "gen_ai.usage.input_tokens": result.usage.inputTokens,
      "gen_ai.usage.output_tokens": result.usage.outputTokens,
    });
    // If the provider reports cached tokens, record them as a subset of input tokens
    if (result.usage.cachedInputTokens != null) {
      span.setAttribute(
        "gen_ai.usage.cache_read.input_tokens",
        result.usage.cachedInputTokens,
      );
    }
    return result;
  },
);

Keep system prompts in gen_ai.system_instructions, not inside gen_ai.input.messages. Conversation titles are derived from the first user message in the input messages.

gen_ai.usage.input_tokens is the total input token count, including cache-read and cache-write tokens. gen_ai.usage.output_tokens includes reasoning tokens. Cache and reasoning attributes are subsets of those totals, so don't add them to the totals again. Sentry uses the model identifiers and token totals to calculate model costs.

AI Request span attributes
  • The span op (transaction mode) or the span's sentry.op attribute (stream mode) MUST be "gen_ai.{gen_ai.operation.name}". (e.g. "gen_ai.chat")
  • The span name SHOULD be "{gen_ai.operation.name} {gen_ai.request.model}". (e.g. "chat o3-mini")
  • The gen_ai.operation.name attribute MUST be "chat", "embeddings", "generate_content" or "text_completion".
  • The gen_ai.provider.name attribute MUST be the Generative AI product as identified by the client or server instrumentation. (e.g. "openai")
  • The gen_ai.request.model attribute MUST be the requested model. (e.g. "o3-mini")
  • The gen_ai.response.model attribute MUST be the concrete model that responded. (e.g. "gpt-4o-2024-08-06")
  • If the request originates from an agent, gen_ai.agent.name SHOULD be set to the agent's name. (e.g. "Weather Agent")
  • If relevant, gen_ai.pipeline.name SHOULD be set to the name of the AI workflow or pipeline. (e.g. "weather-pipeline")

Data AttributeTypeRequirement LevelDescriptionExample
gen_ai.input.messagesstringoptionalList of message objects sent to the LLM. [0], [1]'[{"role": "user", "parts": [{"type": "text", "content": "..."}]}]'
gen_ai.tool.definitionsstringoptionalList of objects describing the available tools. [0]'[{"name": "random_number", "description": "..."}]'
gen_ai.system_instructionsstringoptionalThe system instructions passed to the model."You are a helpful assistant."
gen_ai.request.frequency_penaltyfloatoptionalModel configuration parameter.0.5
gen_ai.request.max_tokensintoptionalModel configuration parameter.500
gen_ai.request.seedstringoptionalSeed for reproducible outputs."12345"
gen_ai.request.temperaturefloatoptionalModel configuration parameter.0.1
gen_ai.request.top_kintoptionalLimits model to K most likely next tokens.40
gen_ai.request.top_pfloatoptionalModel configuration parameter.0.7
gen_ai.request.presence_penaltyfloatoptionalModel configuration parameter.0.5
gen_ai.request.reasoning.levelstringoptionalThe reasoning or thinking effort level requested for a GenAI model. Supported values vary by provider."medium"
gen_ai.request.messagesstringoptionalDeprecated. Use gen_ai.input.messages instead. List of message objects sent to the LLM. [0]'[{"role": "system", "content": "..."}]'
gen_ai.request.available_toolsstringoptionalDeprecated. Use gen_ai.tool.definitions instead. List of objects describing the available tools. [0]'[{"name": "random_number", "description": "..."}]'

Data AttributeTypeRequirement LevelDescriptionExample
gen_ai.response.modelstringrequiredThe concrete model that responded (may differ from gen_ai.request.model)."gpt-4o-2024-08-06"
gen_ai.output.messagesstringoptionalStringified array of message objects representing the model's output. [0], [1]'[{"role": "assistant", "parts": [{"type": "text", "content": "..."}]}]'
gen_ai.response.finish_reasonsstringoptionalStringified array of reasons the model stopped generating. [0]'["stop"]'
gen_ai.response.idstringoptionalUnique identifier for the completion."chatcmpl-abc123"
gen_ai.response.streamingbooleanoptionalWhether the response was streamed.true
gen_ai.response.time_to_first_chunkdoubleoptionalSeconds until first response chunk in streaming.0.5
gen_ai.response.textstringoptionalDeprecated. Use gen_ai.output.messages instead. The text representation of the model's responses."The weather in Paris is rainy"
gen_ai.response.tool_callsstringoptionalDeprecated. Use gen_ai.output.messages instead. The tool calls in the model's response. [0]'[{"name": "random_number", "type": "function_call", "arguments": "..."}]'
gen_ai.response.time_to_first_tokendoubleoptionalDeprecated. Use gen_ai.response.time_to_first_chunk instead. Seconds until first response chunk in streaming.0.5

Data AttributeTypeRequirement LevelDescriptionExample
gen_ai.usage.input_tokensintoptionalThe number of tokens used in the AI input (prompt), including cached tokens. [2]60
gen_ai.usage.cache_read.input_tokensintoptionalThe number of cached tokens used in the AI input (prompt).50
gen_ai.usage.cache_creation.input_tokensintoptionalTokens written to cache when processing input.20
gen_ai.usage.output_tokensintoptionalThe number of tokens used in the AI output, including reasoning tokens. [3]130
gen_ai.usage.reasoning.output_tokensintoptionalThe number of tokens used for reasoning.30
gen_ai.usage.total_tokensintoptionalThe sum of gen_ai.usage.input_tokens and gen_ai.usage.output_tokens.190
gen_ai.usage.input_tokens.cachedintoptionalDeprecated. Use gen_ai.usage.cache_read.input_tokens instead. The number of cached tokens used in the AI input (prompt).50
gen_ai.usage.input_tokens.cache_writeintoptionalDeprecated. Use gen_ai.usage.cache_creation.input_tokens instead. Tokens written to cache when processing input.20
gen_ai.usage.output_tokens.reasoningintoptionalDeprecated. Use gen_ai.usage.reasoning.output_tokens instead. The number of tokens used for reasoning.30
  • [0]: Span attributes only allow primitive data types. This means you need to use a stringified version of a list of dictionaries. Do NOT set [{"foo": "bar"}] but rather the string '[{"foo": "bar"}]' (must be parsable JSON).
  • [1]: Messages use the format {role, parts} where parts is an array of typed objects: [{"role": "user", "parts": [{"type": "text", "content": "..."}]}]. The role must be "user", "assistant", "tool", or "system". Each part has a type; common types include "text" (user-visible content), "reasoning" (internal thinking/chain-of-thought), "tool_call", and "tool_call_response". Use {"type": "reasoning", "content": "..."} for the model's thinking output. Sentry displays it as collapsible reasoning in the conversation detail, separate from user-visible text, so do not represent thinking content as a "text" part. For backwards compatibility, the legacy format {role, content} is also accepted.
  • [2]: Cached tokens are a subset of input tokens; gen_ai.usage.input_tokens includes gen_ai.usage.cache_read.input_tokens.
  • [3]: Reasoning tokens are a subset of output tokens; gen_ai.usage.output_tokens includes gen_ai.usage.reasoning.output_tokens.

Messages use {role, parts} where each part has a type. Common types:

  • text — user-visible content
  • reasoning — internal thinking shown as a collapsible row in the conversation detail
  • tool_call / tool_call_response — tool invocations linked by a shared id

Unknown part types aren't shown prominently in the conversation detail. They remain available only in the raw span attribute values.

Models with extended thinking (such as Anthropic's thinking blocks, Gemini's thought, or DeepSeek's reasoning_content) produce internal reasoning that isn't part of the user-visible reply. Represent this as a reasoning part alongside the user-facing text part — don't fold thinking into text.

Copied
span.setAttribute(
  "gen_ai.output.messages",
  JSON.stringify([
    {
      role: "assistant",
      parts: [
        { type: "reasoning", content: "6 times 7 is 42." },
        { type: "text", content: "The answer is 42." },
      ],
    },
  ]),
);
span.setAttribute("gen_ai.usage.output_tokens", result.usage.outputTokens);
// Reasoning tokens are a subset of output tokens
span.setAttribute(
  "gen_ai.usage.reasoning.output_tokens",
  result.usage.reasoningTokens,
);

When previous thinking is fed back into a multi-turn request, include the same reasoning parts in assistant messages within gen_ai.input.messages.

Link a tool request to its result with the same id:

Copied
// Model asked to call a tool
span.setAttribute(
  "gen_ai.output.messages",
  JSON.stringify([
    {
      role: "assistant",
      parts: [
        {
          type: "tool_call",
          id: "call_abc",
          name: "get_weather",
          arguments: { location: "Paris" },
        },
      ],
    },
  ]),
);

// Later chat span: tool result fed back to the model
const inputWithTool = [
  {
    role: "user",
    parts: [{ type: "text", content: "Weather in Paris?" }],
  },
  {
    role: "assistant",
    parts: [
      {
        type: "tool_call",
        id: "call_abc",
        name: "get_weather",
        arguments: { location: "Paris" },
      },
    ],
  },
  {
    role: "tool",
    parts: [
      {
        type: "tool_call_response",
        id: "call_abc",
        name: "get_weather",
        content: '{"temp_c": 18}',
      },
    ],
  },
];
span.setAttribute("gen_ai.input.messages", JSON.stringify(inputWithTool));

This span represents the execution of an agent, capturing the full lifecycle from receiving a task to producing a final response.

Copied
const inputMessages = [
  {
    role: "user",
    parts: [{ type: "text", content: "What's the weather in Paris?" }],
  },
];

await Sentry.startSpan(
  {
    op: "gen_ai.invoke_agent",
    name: "invoke_agent Weather Agent",
    attributes: {
      "gen_ai.operation.name": "invoke_agent",
      "gen_ai.agent.name": "Weather Agent",
      "gen_ai.input.messages": JSON.stringify(inputMessages),
    },
  },
  async (span) => {
    // Model and tool spans created here become children of the agent span.
    const result = await myAgent.run();

    span.setAttribute(
      "gen_ai.output.messages",
      JSON.stringify([
        {
          role: "assistant",
          parts: [{ type: "text", content: String(result.output) }],
        },
      ]),
    );
    return result;
  },
);

Child gen_ai.chat and gen_ai.execute_tool spans should also set gen_ai.agent.name so model and tool usage can be attributed per agent.

Invoke Agent span attributes

Describes AI agent invocation.

  • The span op (transaction mode) or the span's sentry.op attribute (stream mode) MUST be "gen_ai.invoke_agent".
  • The span name SHOULD be "invoke_agent {gen_ai.agent.name}".
  • The gen_ai.operation.name attribute MUST be "invoke_agent".
  • The gen_ai.agent.name attribute SHOULD be set to the agent's name. (e.g. "Weather Agent")
  • If relevant, gen_ai.pipeline.name SHOULD be set to the name of the AI workflow or pipeline the agent belongs to.

Additional attributes on the span:

Data AttributeTypeRequirement LevelDescriptionExample
gen_ai.input.messagesstringoptionalList of message objects given to the agent. [0], [1]'[{"role": "user", "parts": [{"type": "text", "content": "..."}]}]'
gen_ai.tool.definitionsstringoptionalList of objects describing the available tools. [0]'[{"name": "random_number", "description": "..."}]'
gen_ai.system_instructionsstringoptionalThe system instructions passed to the model."You are a helpful assistant."
gen_ai.pipeline.namestringoptionalThe name of the AI workflow or pipeline the agent belongs to."weather-pipeline"
gen_ai.request.messagesstringoptionalDeprecated. Use gen_ai.input.messages instead. List of message objects given to the agent. [0]'[{"role": "system", "content": "..."}]'
gen_ai.request.available_toolsstringoptionalDeprecated. Use gen_ai.tool.definitions instead. List of objects describing the available tools. [0]'[{"name": "random_number", "description": "..."}]'

Data AttributeTypeRequirement LevelDescriptionExample
gen_ai.output.messagesstringoptionalStringified array of message objects representing the agent's output. [0], [1]'[{"role": "assistant", "parts": [{"type": "text", "content": "..."}]}]'
gen_ai.response.textstringoptionalDeprecated. Use gen_ai.output.messages instead. The text representation of the agent's response."The weather in Paris is rainy"
gen_ai.response.tool_callsstringoptionalDeprecated. Use gen_ai.output.messages instead. The tool calls in the model's response. [0]'[{"name": "random_number", "type": "function_call", "arguments": "..."}]'

Data AttributeTypeRequirement LevelDescriptionExample
gen_ai.usage.input_tokensintoptionalThe number of tokens used in the AI input (prompt), including cached tokens. [2]60
gen_ai.usage.cache_read.input_tokensintoptionalThe number of cached tokens used in the AI input (prompt).50
gen_ai.usage.cache_creation.input_tokensintoptionalTokens written to cache when processing input.20
gen_ai.usage.output_tokensintoptionalThe number of tokens used in the AI output, including reasoning tokens. [3]130
gen_ai.usage.reasoning.output_tokensintoptionalThe number of tokens used for reasoning.30
gen_ai.usage.total_tokensintoptionalThe sum of gen_ai.usage.input_tokens and gen_ai.usage.output_tokens.190
gen_ai.usage.input_tokens.cachedintoptionalDeprecated. Use gen_ai.usage.cache_read.input_tokens instead. The number of cached tokens used in the AI input (prompt).50
gen_ai.usage.input_tokens.cache_writeintoptionalDeprecated. Use gen_ai.usage.cache_creation.input_tokens instead. Tokens written to cache when processing input.20
gen_ai.usage.output_tokens.reasoningintoptionalDeprecated. Use gen_ai.usage.reasoning.output_tokens instead. The number of tokens used for reasoning.30
  • [0]: Span attributes only allow primitive data types. This means you need to use a stringified version of a list of dictionaries. Do NOT set [{"foo": "bar"}] but rather the string '[{"foo": "bar"}]' (must be parsable JSON).
  • [1]: Messages use the format {role, parts} where parts is an array of typed objects: [{"role": "user", "parts": [{"type": "text", "content": "..."}]}]. The role must be "user", "assistant", "tool", or "system". Each part has a type; common types include "text" (user-visible content), "reasoning" (internal thinking/chain-of-thought), "tool_call", and "tool_call_response". Use {"type": "reasoning", "content": "..."} for the model's thinking output. Sentry displays it as collapsible reasoning in the conversation detail, separate from user-visible text, so do not represent thinking content as a "text" part. For backwards compatibility, the legacy format {role, content} is also accepted.
  • [2]: Cached tokens are a subset of input tokens; gen_ai.usage.input_tokens includes gen_ai.usage.cache_read.input_tokens.
  • [3]: Reasoning tokens are a subset of output tokens; gen_ai.usage.output_tokens includes gen_ai.usage.reasoning.output_tokens.

This span represents the execution of a tool or function that was requested by an AI model, including the input arguments and resulting output.

Copied
await Sentry.startSpan(
  {
    op: "gen_ai.execute_tool",
    name: "execute_tool get_weather",
    attributes: {
      "gen_ai.operation.name": "execute_tool",
      "gen_ai.agent.name": "Weather Agent",
      "gen_ai.tool.name": "get_weather",
      "gen_ai.tool.description": "Get weather for a city",
      "gen_ai.tool.call.arguments": JSON.stringify({ location: "Paris" }),
    },
  },
  async (span) => {
    try {
      const result = await getWeather({ location: "Paris" });
      span.setAttribute("gen_ai.tool.call.result", JSON.stringify(result));
      return result;
    } catch (error) {
      span.setStatus({ code: 2, message: "internal_error" });
      span.setAttribute(
        "error.type",
        error instanceof Error ? error.constructor.name : "Error",
      );
      throw error;
    }
  },
);

Marking failed tools with an error status populates the Tool Errors widget.

Execute Tool span attributes

Describes a tool execution.

  • The span op (transaction mode) or the span's sentry.op attribute (stream mode) MUST be "gen_ai.execute_tool".
  • The span name SHOULD be "execute_tool {gen_ai.tool.name}". (e.g. "execute_tool query_database")
  • The gen_ai.operation.name attribute MUST be "execute_tool".
  • The gen_ai.tool.name attribute SHOULD be set to the name of the tool. (e.g. "query_database")
  • The gen_ai.agent.name attribute SHOULD be set to the agent's name. (e.g. "Weather Agent")
  • If relevant, gen_ai.pipeline.name SHOULD be set to the name of the AI workflow or pipeline. (e.g. "weather-pipeline")

Additional attributes on the span:

Data AttributeTypeRequirement LevelDescriptionExample
gen_ai.tool.namestringoptionalName of the tool executed."random_number"
gen_ai.tool.call.argumentsstringoptionalArguments of the tool call (stringified JSON)."{\"max\":10}"
gen_ai.tool.call.resultstringoptionalResult of the tool call (stringified)."7"
gen_ai.tool.descriptionstringoptionalDescription of the tool executed."Tool returning a random number"
gen_ai.tool.typestringoptionalDeprecated. This attribute should no longer be set. The type of tool being used."function"; "extension"; "datastore"
gen_ai.tool.inputstringoptionalDeprecated. Use gen_ai.tool.call.arguments instead. Input given to the executed tool as string."{\"max\":10}"
gen_ai.tool.outputstringoptionalDeprecated. Use gen_ai.tool.call.result instead. The output from the tool."7"

This span represents a decision on generated content against a set of questions, such as grading a model's reply for accuracy or tone. Models like TypeSafe Jev produce these spans.

Sentry identifies a decision by gen_ai.operation.name: "decide". Decisions share the ai_client operation type with ordinary LLM calls, so the operation name is what sets them apart.

Copied
const questions = {
  resolves_issue: {
    type: "boolean",
    instructions: "Does the reply resolve the customer's issue?",
  },
  accuracy: {
    type: "score",
    instructions: "Does the reply correctly answer the user's question?",
    // For a score question, criteria is an ordered array; the index is the score.
    criteria: ["incorrect", "partially correct", "correct"],
  },
  tone: {
    type: "choice",
    instructions: "Classify the tone of the reply.",
    // For a choice question, criteria maps each label to its description.
    criteria: {
      friendly: "Warm and helpful",
      neutral: "Plain and factual",
      rude: "Dismissive or hostile",
    },
  },
};

const evaluationInput = [
  {
    type: "evaluation",
    state: "Your refund has been processed and will arrive in 3-5 days.",
    questions,
  },
];

await Sentry.startSpan(
  {
    op: "gen_ai.decide",
    name: "decide typesafe/jev-1.13",
    attributes: {
      "gen_ai.operation.name": "decide",
      "gen_ai.request.model": "typesafe/jev-1.13",
      "gen_ai.provider.name": "typesafe",
      "gen_ai.agent.name": "Support Agent", // when this evaluation runs under an agent
      "gen_ai.input.messages": JSON.stringify(evaluationInput),
    },
  },
  async (span) => {
    // Call your evaluator; map its response into span attributes below
    const result = await yourEvaluator.evaluate({
      state: evaluationInput[0].state,
      questions,
    });

    span.setAttributes({
      "gen_ai.response.model": result.model, // e.g. "typesafe/jev-1.13-20260917"
      "gen_ai.output.messages": JSON.stringify([
        {
          type: "evaluation",
          answers: {
            resolves_issue: { type: "boolean", probability: 0.98 },
            accuracy: { type: "score", score: 2, confidence: 0.91 },
            tone: {
              type: "choice",
              choice: "friendly",
              probabilities: { friendly: 0.87, neutral: 0.1, rude: 0.03 },
              confidence: 0.87,
            },
          },
        },
      ]),
      "gen_ai.usage.input_tokens": result.usage.inputTokens,
      "gen_ai.usage.output_tokens": result.usage.outputTokens,
    });
    return result;
  },
);

The input is a single {type: "evaluation", state, questions} object. state is the text being evaluated, and each entry in questions describes one question. The output is a single {type: "evaluation", answers} object keyed by those same question names. Answers come in a few types (boolean, noul, score, and choice), each with its own fields. See the attributes below for the full shape.

Pass the raw provider model string in gen_ai.request.model (and gen_ai.response.model) so Sentry can resolve the model icon and any model costs.

Decision span attributes

Describes a decision on generated content against a set of questions (for example a TypeSafe Jev evaluation).

  • The span op (transaction mode) or the span's sentry.op attribute (stream mode) MUST be "gen_ai.decide".
  • The span name SHOULD be "decide {gen_ai.request.model}". (e.g. "decide typesafe/jev-1.13")
  • The gen_ai.operation.name attribute MUST be "decide". Sentry uses this attribute, not the span op, to tell decisions apart from ordinary LLM calls (both share the ai_client operation type).
  • The gen_ai.request.model attribute SHOULD be the requested evaluation model. (e.g. "typesafe/jev-1.13")
  • The gen_ai.response.model attribute SHOULD be the concrete model that responded. (e.g. "typesafe/jev-1.13-20260917")
  • The gen_ai.provider.name attribute SHOULD be set to the provider. (e.g. "typesafe")
  • The gen_ai.agent.name attribute SHOULD be set to the agent's name when the evaluation runs under an agent. (e.g. "Support Agent")

Additional attributes on the span:

Data AttributeTypeRequirement LevelDescriptionExample
gen_ai.input.messagesstringoptionalA single evaluation object holding the evaluated state and the questions (stringified JSON). [0]'[{"type": "evaluation", "state": "...", "questions": {"accuracy": {"type": "score", "criteria": ["incorrect", "correct"]}}}]'
gen_ai.output.messagesstringoptionalA single evaluation object holding the answers, keyed by the same question keys (stringified JSON). [1]'[{"type": "evaluation", "answers": {"accuracy": {"type": "score", "score": 1}}}]'
gen_ai.usage.input_tokensintoptionalThe number of tokens used in the evaluation input.154
gen_ai.usage.output_tokensintoptionalThe number of tokens used in the evaluation output.28

[0] Each entry in questions has an instructions string and a type. For a score question, criteria is an ordered string array whose index is the score (["low", "medium", "high"]). For a choice question, criteria maps each label to its description ({"positive": "...", "negative": "..."}).

[1] Each answer carries a type that matches its question:

Answer typeFields
booleanprobability
noulnoul holds the probability (Jev's variant of boolean).
scorescore, plus optional legend ({"0": "low"}), probabilities, and confidence
choicechoice, plus optional probabilities and confidence

Optional fields may be omitted, but a field present with the wrong type makes that question or answer unreadable and it's shown raw in the span detail.

This span represents a read from, write to, or management operation against an agent's persistent memory store, such as retrieving relevant memories before a model call or saving new ones after it.

Sentry identifies a memory operation by the gen_ai.memory.client span op. The specific action goes in gen_ai.operation.name, and the span name matches it.

Copied
const query = "user dietary preferences";

await Sentry.startSpan(
  {
    op: "gen_ai.memory.client",
    name: "search_memory",
    attributes: {
      "gen_ai.operation.name": "search_memory",
      "gen_ai.memory.store.id": "user-preferences-store",
      "gen_ai.agent.name": "Support Agent", // when the operation runs under an agent
      "gen_ai.memory.query.text": query, // opt-in; may contain sensitive data
    },
  },
  async (span) => {
    const records = await memoryStore.search(query);

    span.setAttributes({
      "gen_ai.memory.record.count": records.length,
      // opt-in; may contain sensitive data
      "gen_ai.memory.records": JSON.stringify(
        records.map((record) => ({
          id: record.id,
          content: record.content,
          score: record.score,
        })),
      ),
    });
    return records;
  },
);

Set gen_ai.operation.name to the action: search_memory to retrieve records, create_memory / update_memory / upsert_memory to write them, delete_memory to remove them, and create_memory_store / delete_memory_store to manage the store itself.

gen_ai.memory.query.text applies only to search_memory. When an operation targets a single record, set gen_ai.memory.record.id; on delete_memory, omitting it can mean every record in the store is removed. gen_ai.memory.record.count is the number of records returned, written, or deleted.

gen_ai.memory.query.text and gen_ai.memory.records can carry user data and PII, so they are opt-in. Omit them, or gate them yourself, when you don't want that content in Sentry.

Memory span attributes

Describes a read from, write to, or management operation against an agent's persistent memory store.

  • The span op (transaction mode) or the span's sentry.op attribute (stream mode) MUST be "gen_ai.memory.client". Sentry uses this op, not the span name, to classify the span as a memory operation.
  • The gen_ai.operation.name attribute MUST be one of "create_memory_store", "delete_memory_store", "create_memory", "update_memory", "upsert_memory", "search_memory", or "delete_memory". It names the specific action.
  • The span name SHOULD be the gen_ai.operation.name value. (e.g. "search_memory")
  • The gen_ai.agent.name attribute SHOULD be set to the agent's name when the operation runs under an agent. (e.g. "Support Agent")

Additional attributes on the span:

Data AttributeTypeRequirement LevelDescriptionExample
gen_ai.memory.store.idstringoptionalThe memory store the operation targets. What this maps to is implementation-specific (a collection, namespace, or vector index)."user-preferences-store"
gen_ai.memory.record.idstringoptionalThe record the operation applies to. For delete_memory, its absence may indicate that every record in the store is deleted."mem_5j66UpCpwteGg4YSxUnt7lPY"
gen_ai.memory.record.countintoptionalThe number of records relevant to the operation: records returned for search_memory, or records the operation attempted to write or delete.3
gen_ai.memory.query.textstringoptionalThe search query used to retrieve memories. Only applicable to search_memory. Opt-in: may contain sensitive data, so capture it only on purpose."user dietary preferences"
gen_ai.memory.recordsstringoptionalThe records stored or retrieved, as a stringified JSON array. [0] Opt-in: may contain sensitive data including PII, so capture it only on purpose.'[{"content": "User prefers dark mode", "id": "mem_123", "score": 0.95}]'

[0] Each element follows the MemoryRecord schema: a required content (a string or a JSON object) plus optional id, metadata, and score.

When the model streams tokens, keep the span open until the stream finishes (including when you yield chunks to the client). Set response attributes when you have the final usage and text:

  • gen_ai.response.streaming — true
  • gen_ai.response.time_to_first_chunk — seconds until the first chunk
  • gen_ai.response.tokens_per_second — output throughput, if you can measure it
  • gen_ai.output.messages, token usage, and gen_ai.response.model — same as a non-streaming call, once the stream completes

Use Sentry.startInactiveSpan if the span outlives the function that starts the stream, and Sentry.withActiveSpan when work within the stream needs the model span as its parent. End the span when the stream completes or fails. See Streamed Spans for span lifecycle patterns.

When manually setting token attributes, be aware of how Sentry uses them to calculate model costs.

Cached and reasoning tokens are subsets, not separate counts. gen_ai.usage.input_tokens is the total input token count that already includes any cached tokens. Similarly, gen_ai.usage.output_tokens already includes reasoning tokens. Sentry subtracts the cached/reasoning counts from the totals to compute the "raw" portion, so reporting them incorrectly can produce wrong or negative costs.

For example, say your LLM call uses 100 input tokens total, 90 of which were served from cache. Using a standard rate of $0.01 per token and a cached rate of $0.001 per token:

Correct — input_tokens is the total (includes cached):

  • gen_ai.usage.input_tokens = 100
  • gen_ai.usage.cache_read.input_tokens = 90
  • Sentry calculates: (100 - 90) × $0.01 + 90 × $0.001 = $0.10 + $0.09 = $0.19 ✓

Wrong — input_tokens set to only the non-cached tokens, making cached larger than total:

  • gen_ai.usage.input_tokens = 10
  • gen_ai.usage.cache_read.input_tokens = 90
  • Sentry calculates: (10 - 90) × $0.01 + 90 × $0.001 = −$0.80 + $0.09 = −$0.71

Because gen_ai.usage.cache_read.input_tokens (90) is larger than gen_ai.usage.input_tokens (10), the subtraction goes negative, resulting in a negative total cost.

The same applies to gen_ai.usage.output_tokens and gen_ai.usage.reasoning.output_tokens.

By default, Sentry derives model cost from the model name and token counts. Pass the raw provider model string unchanged so pricing can resolve. If your provider reports costs or you use custom pricing, see Send Custom Costs.

Was this helpful?
Help improve this content
Our documentation is open source and available on GitHub. Your contributions are welcome, whether fixing a typo (drat!) or suggesting an update ("yeah, this would be better").