Skip to content

fix(datadog_llm_obs): keep tool call and result structure under redaction and emit tool output tokens - #40666

Merged
yucheng-berri merged 3 commits into
litellm_internal_stagingfrom
litellm_dd_llmobs_redact_tool_structure
Sep 11, 2026
Merged

yucheng-berri merged 3 commits into
litellm_internal_stagingfrom
litellm_dd_llmobs_redact_tool_structure

Conversation

@devin-ai-integration

@devin-ai-integration devin-ai-integration Bot commented Sep 11, 2026 •

Copy link
Copy Markdown
Contributor

TLDR

Problem this solves:

  • Datadog LLM Obs shows Tool Call 0, Tool Result 0 under redaction
  • Avg. Tool Output Tokens has no data under redaction
  • Redacted spans kept one role and one placeholder, nothing else

How it solves it:

  • Datadog callback redacts its own normalized messages, not the shared hook
  • Roles, tool names, ids and types survive; content, arguments, results replaced
  • Tool result tokens counted before redaction, shipped as tool_output_tokens
  • Every other callback keeps the exact behavior it has today

User Flow

Before: an operator who turned on Datadog message redaction gets no tool observability at all

  1. They set datadog_llm_observability_params.turn_off_message_logging: true and restart the proxy
  2. They send POST https://litellm-domain/v1/chat/completions with a user turn, an assistant turn carrying one get_weather tool call, and a tool turn carrying that tool's JSON result
  3. The chat completion comes back 200 with the model's answer
  4. In Datadog LLM Observability the span's input is a single assistant message reading redacted-by-litellm, and the trace view shows Tool Call 0, Tool Result 0, Avg. Tool Output Tokens no data

After: the same request keeps its content private and still shows tool structure and tool output token counts

  1. They set datadog_llm_observability_params.turn_off_message_logging: true and restart the proxy
  2. They send POST https://litellm-domain/v1/chat/completions with a user turn, an assistant turn carrying one get_weather tool call, and a tool turn carrying that tool's JSON result
  3. The chat completion comes back 200 with the model's answer
  4. In Datadog LLM Observability the span's input has three messages: user with redacted content, assistant with a get_weather tool call whose arguments read redacted-by-litellm, and tool with a get_weather tool result reading redacted-by-litellm; the span metrics carry tool_output_tokens: 30, so the trace view counts one tool call and one tool result, and the raw prompt, arguments and result never left the proxy

Relevant issues

Fixes #40580

Linear ticket

Resolves LIT-7545

Pre-Submission checklist

Please complete all items before asking a LiteLLM maintainer to review your PR

  • I have added meaningful tests
  • The handful of test files covering my change pass locally, e.g. uv run pytest tests/test_litellm/<your_test_file>.py -v. Leave the suites (make test-unit-*, make test-unit) to CI: it finishes in ~15 minutes where a laptop takes an hour or more
  • My PR passes all required CI/CD checks (e.g., lint, schema.d.ts sync check, etc.). The schema.d.ts sync check was red on the base branch tip 7419a53 itself (fix(auto-router): omit Claude Code system text from classifier #40655 changed two classifier descriptions without regenerating), so bae72a7 carries the npm run gen:api output for those two lines. This PR touches no route or model
  • My PR's scope is as isolated as possible; it only solves 1 specific problem
  • I have received a Greptile Confidence Score of at least 4/5 before requesting a maintainer review (Greptile reviews automatically once the PR is opened; only comment @greptileai to re-request a review after pushing changes)

Delays in PR merge?

If you're seeing a delay in your PR being merged, ping the LiteLLM Team on Slack (#pr-review).

Screenshots / Proof of Fix

Shared setup for both runs: a real proxy (2 workers, real Postgres) with real OpenAI gpt-5.6 and Anthropic claude-sonnet-5 deployments, Datadog LLM Obs in Agent mode (LITELLM_DD_AGENT_HOST=127.0.0.1, LITELLM_DD_LLM_OBS_PORT=<sink>) pointed at a local HTTP sink that writes every /api/intake/llm-obs/v1/trace/spans body to disk, so the exact span Datadog would receive is what is shown. No DD_API_KEY was available, so the Datadog UI itself was not exercised; the span JSON below is the payload it renders

model_list:
  - model_name: gpt-5.6
    litellm_params:
      model: openai/gpt-5.6
      api_key: os.environ/OPENAI_API_KEY
  - model_name: claude-sonnet
    litellm_params:
      model: anthropic/claude-sonnet-5
      api_key: os.environ/ANTHROPIC_API_KEY

litellm_settings:
  callbacks: ["datadog_llm_observability"]
  datadog_llm_observability_params:
    turn_off_message_logging: true

general_settings:
  master_key: sk-7545
  database_url: os.environ/DATABASE_URL
TOOLS='[{"type":"function","function":{"name":"get_weather","description":"Get current weather for a city","parameters":{"type":"object","properties":{"city":{"type":"string"}},"required":["city"]}}}]'
ROUND='[{"role":"user","content":"What is the weather in Paris right now? Use the tool."},{"role":"assistant","content":null,"tool_calls":[{"id":"call_paris_1","type":"function","function":{"name":"get_weather","arguments":"{\"city\": \"Paris\"}"}}]},{"role":"tool","tool_call_id":"call_paris_1","content":"{\"city\": \"Paris\", \"temp_c\": 18, \"sky\": \"overcast\", \"account_secret\": \"SECRET-4711\"}"}]'

Sad path, edge and chaos run, shared across both sides: one script (bash chaos.sh <proxy_port> <sink_port>) sends the same ten requests to a proxy, all against the real providers, no mocks. C1 unknown model name; C2 a tool result whose id matches no tool call (OpenAI 400); C3 a wrong virtual key; C4 an integer tool_call_id with a null tool name on Anthropic (provider 400); C5 an empty tool result next to a list-content tool result; C6 a 60 KB unicode and emoji tool result; C7 /v1/messages with an is_error list-content tool_result; C8 a streaming round trip where the client disconnects after 2 s; C9 20 concurrent round trips split across gpt-5.6 and claude-sonnet-5; C10 a round trip with the sink under SIGSTOP, then another after SIGCONT. Each sink also serves the spans it received as a page (http://127.0.0.1:<sink_port>/), so the payload Datadog gets can be read in a browser next to that proxy's Admin UI logs page (http://127.0.0.1:<proxy_port>/ui/?page=logs). Recording of the run below, base leg first, then tip, each showing the terminal, the intake page and the Admin UI logs (the full resolution mp4 is attached to the Devin session linked at the bottom):

chaos run recording, base then tip

Before (7419a53)

/v1/chat/completions tool round trip

  1. curl -s http://127.0.0.1:20545/v1/chat/completions -H "Authorization: Bearer sk-7545" -H "Content-Type: application/json" -d "{\"model\":\"claude-sonnet\",\"messages\":$ROUND,\"tools\":$TOOLS}"
  2. Client gets 200 with "content": "The current weather in Paris is 18°C and overcast."
  3. Span the sink received (meta.input, meta.output, token metrics):
{
  "input": [{"role": "assistant", "content": "redacted-by-litellm"}],
  "output": [],
  "metrics": {"input_tokens": 56.0, "output_tokens": 18.0, "total_tokens": 74.0}
}
  1. No tool_calls, no tool_results, no tool_output_tokens. Every other span in the run (gpt-5.6 and claude-sonnet, first-turn tool call, plain chat, streaming, /v1/messages) has the same single assistant placeholder as input

/v1/messages tool_use and tool_result blocks

  1. curl -s http://127.0.0.1:20545/v1/messages -H "Authorization: Bearer sk-7545" -H "Content-Type: application/json" -d '{"model":"claude-sonnet","max_tokens":200,"messages":[{"role":"user","content":"What is the weather in Paris? Use the tool."},{"role":"assistant","content":[{"type":"tool_use","id":"toolu_paris_1","name":"get_weather","input":{"city":"Paris"}}]},{"role":"user","content":[{"type":"tool_result","tool_use_id":"toolu_paris_1","content":"{\"city\": \"Paris\", \"temp_c\": 18, \"sky\": \"overcast\", \"account_secret\": \"SECRET-4711\"}"}]}],"tools":[{"name":"get_weather","description":"Get current weather for a city","input_schema":{"type":"object","properties":{"city":{"type":"string"}},"required":["city"]}}]}'
  2. Client gets 200, stop_reason: end_turn
  3. Span input is again [{"role": "assistant", "content": "redacted-by-litellm"}], no tool structure, no tool_output_tokens

Sad path, edge and chaos run

  1. bash chaos.sh 20545 21545
  2. Status codes: 400, 400, 401, 400, 200, 200, 200, disconnected, 20 x 200, 200, 200

base terminal

  1. The sink received 28 spans (24 ok, 4 error: unknown model, OpenAI 400, wrong key, Anthropic 400). Every span's input is one assistant row with content: redacted-by-litellm, no tool_call or tool_result rows, no tool_output_tokens metric, including the 60 KB result and the 20 concurrent round trips

base intake page

  1. http://127.0.0.1:20545/ui/?page=logs shows the same requests, 24 Success and 4 Failure

base logs

After (bae72a7)

/v1/chat/completions tool round trip

  1. Same curl against the fixed proxy on port 20546
  2. Client gets 200 with "content": "The current weather in Paris is 18°C with overcast skies."
  3. Span the sink received:
{
  "input": [
    {"role": "user", "content": "redacted-by-litellm"},
    {
      "role": "assistant",
      "content": "redacted-by-litellm",
      "tool_calls": [{"name": "get_weather", "arguments": "redacted-by-litellm", "tool_id": "call_paris_1", "type": "function"}]
    },
    {
      "role": "tool",
      "content": "redacted-by-litellm",
      "tool_results": [{"name": "get_weather", "result": "redacted-by-litellm", "tool_id": "call_paris_1", "type": "function"}]
    }
  ],
  "output": [{"role": "assistant", "content": "redacted-by-litellm"}],
  "metrics": {"input_tokens": 546.0, "output_tokens": 67.0, "total_tokens": 613.0, "reasoning_output_tokens": 44.0, "tool_output_tokens": 30.0}
}
  1. grep -c 'SECRET-4711\|Paris\|overcast' sink_head.jsonl prints 0: the prompt, the tool arguments and the tool result never reached the sink. tool_output_tokens is 30, which is litellm.token_counter(model="anthropic/claude-sonnet-5", text=<the tool result>)

/v1/messages tool_use and tool_result blocks

  1. Same curl against port 20546
  2. Client gets 200, stop_reason: end_turn
  3. Span input (after the redacted user turn):
{
  "input": [
    {
      "role": "assistant",
      "content": "redacted-by-litellm",
      "tool_calls": [{"name": "get_weather", "arguments": "redacted-by-litellm", "tool_id": "toolu_paris_1", "type": "tool_use"}]
    },
    {
      "role": "user",
      "content": "redacted-by-litellm",
      "tool_results": [{"name": "get_weather", "result": "redacted-by-litellm", "tool_id": "toolu_paris_1", "type": "function"}]
    }
  ],
  "output": [{"role": "assistant", "content": "redacted-by-litellm"}],
  "metrics": {"input_tokens": 544.0, "output_tokens": 67.0, "total_tokens": 611.0, "reasoning_output_tokens": 42.0, "tool_output_tokens": 30.0}
}

Also run on both sides with identical client responses: first-turn tool call (span output now shows the assistant message with its one redacted tool call), plain chat with no tools (no tool_output_tokens key, as before), streaming round trip, and /v1/responses with function_call_output. A second custom callback with its own turn_off_message_logging: true was attached to both proxies and received byte-identical redacted payloads before and after, and the same run with redaction off produced the same spans on both sides plus the new tool_output_tokens metric

Sad path, edge and chaos run

  1. bash chaos.sh 20546 21546
  2. Status codes identical to base: 400, 400, 401, 400, 200, 200, 200, disconnected, 20 x 200, 200, 200

tip terminal

  1. The sink received the same 28 spans from the script (24 ok, 4 error). On every one the user, assistant and tool rows survive with tool_call name=get_weather tool_id=call_paris_1 type=function arguments=redacted-by-litellm and tool_result ... result=redacted-by-litellm, and the tool_output_tokens chip reads 30 (one result), 43 (two results), 27051 (the 60 KB result) and 23 (/v1/messages). The failure spans carry the same redacted shape. The page header reads 80 rather than 28 because the tip's Admin UI tab kept polling with a session token from the previous proxy process during setup, which produced 52 KeyNotFoundError spans with no model and no messages before the script ran; the proxy log has the key hash and timing, and the base proxy logs the same kind of span for the wrong-key request, so this is unrelated to the change

tip intake page

  1. The C7 /v1/messages is_error span keeps the tool_use call and the tool_result block, both redacted, with tool_output_tokens=23

tip /v1/messages is_error span

  1. http://127.0.0.1:20546/ui/?page=logs shows the same requests as base, 24 Success and 4 Failure from the script (plus the stale-token failures described above)

tip logs

  1. grep -c 'SECRET-\|overcast\|Oslo' over meta.input and meta.output of every span the sink received prints 0. An earlier run of the same script without the recording gave the same result with 29 spans per side; the one extra was the C8 stream, which in the recorded run was cut before the proxy logged it

Type

🐛 Bug Fix

Caveats (if any)

Medium

  • Only datadog_llm_observability_params.turn_off_message_logging (the flag the Datadog docs describe) gets the structured redaction. The global litellm_settings.turn_off_message_logging collapses messages before any callback runs, so Datadog still sees one placeholder there
    • Under the global flag the placeholder's role is now user (what the global redaction writes) instead of assistant (the default the shared hook filled in). No structure and no content either way

Low

  • /v1/responses inputs with function_call and function_call_output items already arrive without a role or tool shape when redaction is off, so under redaction they stay role-less placeholders and tool_output_tokens is not counted. Same as before this PR
  • tool_output_tokens counts with litellm.token_counter for the request's model, so the number matches the provider's tokenizer where LiteLLM has one and falls back to the default tokenizer otherwise
  • Bugbot on bae72a7 flagged that str() coerced tool result ids survive redaction. Ids are kept by design so Datadog can link a result to its call, the same contract Greptile agreed to in its withdrawn thread, so this stands as a false positive
  • Veria and Devin Review posted nothing on this PR or on the three sibling PRs merged just before it (fix(caching): keep an open Redis circuit breaker open and quiet on the sync read and spend counter paths #40624, fix(auto-router): omit Claude Code system text from classifier #40655, feat(ui): link the entity cells on the team detail page's keys table #40647), so there is no verdict from them to report
  • Two pre-existing behaviours surfaced by the chaos run, both identical at the merge base and out of scope here: meta.error.message on failure spans is provider exception text and is not touched by this redaction path (tracked in LIT-6770); and DataDogLLMObsLogger.async_send_batch calls self.log_queue.clear() after its awaited POST, so spans appended during the send are dropped (the base run lost 2 of 29 spans this way, the base class already has preserve_events_added_during_flush for exactly this; tracked in LIT-7593)
  • Backward incompatibilities: none. redacts_messages_itself() defaults to False on CustomLogger, LLMMetrics.tool_output_tokens is optional, and the shared hook's signature is unchanged

Final Attestation

  • The tests check the right things, including the edge cases, and regressions in the respective real-world customer use-cases are not possible after this PR

ran /live-pr-risk and found no regressions/backward incompatible risks


Note

Medium Risk
Changes observability redaction and what sensitive payloads reach Datadog when logging is off; behavior is scoped to the Datadog callback via an opt-in hook, with broad test coverage but still on the logging/security boundary.

Overview
Fixes Datadog LLM Observability when message redaction is on: spans no longer collapse to a single placeholder, so tool call/result counts and Avg. Tool Output Tokens stay usable without leaking prompts or tool payloads.

CustomLogger adds redacts_messages_itself() (default False). With turn_off_message_logging, the shared hook still strips classifier audit fields and excluded keys, but skips blanket message/response redaction when a callback opts in so it can redact in its own schema.

Datadog LLM Obs opts in and redacts normalized span messages itself: roles, tool names, ids, and types remain; content, arguments, and results become redacted-by-litellm. Tool result token counts are computed before redaction and emitted as optional tool_output_tokens on span metrics (LLMMetrics typed accordingly).

Tests cover proxy-style redaction flows, Anthropic tool blocks, malformed identifiers, and self-redacting vs default callbacks. schema.d.ts only updates classifier field descriptions (regen), not API behavior from this fix.

Reviewed by Cursor Bugbot for commit bae72a7. Bugbot is set up for automated code reviews on this repo. Configure here.

Link to Devin session: https://app.devin.ai/sessions/667c249c0bb2421dbcf2cf454812e23c
Open in Devin Desktop: https://app.devin.ai/desktop/session/667c249c0bb2421dbcf2cf454812e23c?variant=devin
Requested by: @yucheng-berri


Devin Review

…tion and emit tool output tokens

Under datadog_llm_observability_params.turn_off_message_logging the span kept only one role plus "redacted-by-litellm" per message, so Datadog showed Tool Call 0, Tool Result 0 and no tool output token data. The shared CustomLogger hook collapsed the messages before the callback ran, and the Datadog redaction then dropped tool_calls and tool_results.

The Datadog callback now opts out of the shared message collapse (redacts_messages_itself) and redacts its own normalized messages, keeping roles, tool names, ids and types while replacing content, arguments and results. Tool result tokens are counted with litellm.token_counter before redaction and shipped as the tool_output_tokens metric. Other callbacks keep the inherited behavior.

Resolves LIT-7545

Co-Authored-By: Devin AI <158243242+devin-ai-integration[bot]@users.noreply.github.com>
@devin-ai-integration

Copy link
Copy Markdown
Contributor Author

🤖 Devin AI Engineer

I'll be helping with this pull request! Here's what you should know:

✅ I will automatically:

  • Address comments on this PR. Add '(aside)' to your comment to have me ignore it.
  • Look at CI failures and help fix them

Note: I can only respond to comments from users who have write access to this repository.

⚙️ Control Options:

  • Disable automatic comment, CI, and merge conflict monitoring

@codspeed

codspeed Bot commented Sep 11, 2026 •

Copy link
Copy Markdown
Contributor

Merging this PR will not alter performance

✅ 31 untouched benchmarks


Comparing litellm_dd_llmobs_redact_tool_structure (bae72a7) with litellm_internal_staging (7419a53)

Open in CodSpeed

@greptile-apps

greptile-apps Bot commented Sep 11, 2026 •

Copy link
Copy Markdown
Contributor

Greptile Summary

This PR preserves normalized tool-call and tool-result structure when Datadog-specific message logging is disabled, while redacting content, arguments, and results. It also reports tool-result token counts and keeps shared callback redaction behavior unchanged.

  • Adds callback-controlled message redaction so Datadog can redact normalized messages locally.
  • Preserves safe roles and tool identifiers needed for Datadog tool observability.
  • Emits optional tool_output_tokens metrics computed before redaction.
  • Adds coverage for structured redaction, token counting, malformed identifiers, exclusions, and callback isolation.
  • Synchronizes generated dashboard schema descriptions with the base API schema.

Confidence Score: 5/5

The PR appears safe to merge; no actionable new defects or outstanding findings remain.

The Datadog callback retains normalized messages only long enough to redact their sensitive fields locally, while tool-result token counts are emitted without result content. The identifier-redaction finding was correctly withdrawn after clarification of the required correlation contract. The comments-guidance thread was manually resolved without explanation.

Important Files Changed

Filename Overview
litellm/integrations/custom_logger.py Adds an opt-in hook allowing callbacks to retain messages for callback-local redaction while preserving other exclusions.
litellm/integrations/datadog/datadog_llm_obs.py Implements structure-preserving Datadog redaction and tool-result token metrics without exposing tool payloads.
litellm/types/integrations/datadog_llm_obs.py Extends Datadog metrics typing with the optional tool-output token count.
tests/test_litellm/integrations/datadog/test_datadog_llm_obs.py Covers structured redaction, secret removal, token accounting, malformed identifiers, and exclusion behavior.
tests/test_litellm/litellm_core_utils/test_redact_messages.py Verifies self-redacting callbacks retain messages while shared sensitive-field handling remains active.
ui/litellm-dashboard/src/lib/http/schema.d.ts Synchronizes generated classifier configuration descriptions with the existing schema source.

Reviews (3): Last reviewed commit: "chore(ui): regenerate schema.d.ts for th..." | Re-trigger Greptile

greptile-apps[bot]

This comment was marked as resolved.

@codecov

codecov Bot commented Sep 11, 2026

Copy link
Copy Markdown

Codecov Report

✅ All modified and coverable lines are covered by tests.

📢 Thoughts on this report? Let us know!

…change

Co-Authored-By: Devin AI <158243242+devin-ai-integration[bot]@users.noreply.github.com>
@devin-ai-integration

Copy link
Copy Markdown
Contributor Author

@greptileai

…nged in #40655

Co-Authored-By: Devin AI <158243242+devin-ai-integration[bot]@users.noreply.github.com>
@mateo-berri

Copy link
Copy Markdown
Contributor

bugbot run

@devin-ai-integration

Copy link
Copy Markdown
Contributor Author

@greptileai

@cursor cursor Bot left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Cursor Bugbot has reviewed your changes using high effort and found 1 potential issue.

Fix All in Cursor

❌ Bugbot Autofix is OFF. To automatically fix reported issues with cloud agents, enable autofix in the Cursor dashboard.

Reviewed by Cursor Bugbot for commit bae72a7. Configure here.

result=REDACTED_BY_LITELLM,
tool_id=_safe_identifier(tool_result.get("tool_id")),
type=_safe_identifier(tool_result.get("type")),
)

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Stringified tool IDs bypass redaction

Low Severity

_safe_identifier only blanks non-string tool names and IDs, but _to_dd_tool_results and _tool_call_names_by_id already coerce those values with str() during normalization. A non-string tool_call_id, tool_use_id, or tool name therefore becomes a string that survives redaction and can still appear on the Datadog span. The new tool-call redaction covers this for id/type/name on calls, but the same check does not hold for result IDs or linked result names.

Additional Locations (2)
Fix in Cursor Fix in Web

Reviewed by Cursor Bugbot for commit bae72a7. Configure here.

Copy link
Copy Markdown
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Tool ids are kept on purpose so Datadog can link calls to results, see the Greptile thread above. _safe_identifier guards the str type, not privacy

@devin-ai-integration devin-ai-integration Bot left a comment

Copy link
Copy Markdown
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

✅ Devin Review: No Issues Found

Devin Review analyzed this PR and found no bugs or issues to report.

Devin Review

@yucheng-berri
yucheng-berri merged commit 09b6948 into litellm_internal_staging Sep 11, 2026
93 of 94 checks passed
@yucheng-berri
yucheng-berri deleted the litellm_dd_llmobs_redact_tool_structure branch September 11, 2026 20:12
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

Datadog Observability - Cost & Auto-router - Follow-up request for PR #39320

2 participants