Repository navigation
fix(datadog_llm_obs): keep tool call and result structure under redaction and emit tool output tokens - #40666
Conversation
…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 EngineerI'll be helping with this pull request! Here's what you should know: ✅ I will automatically:
Note: I can only respond to comments from users who have write access to this repository. ⚙️ Control Options:
|
Greptile SummaryThis 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.
Confidence Score: 5/5The 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.
|
| 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
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>
…nged in #40655 Co-Authored-By: Devin AI <158243242+devin-ai-integration[bot]@users.noreply.github.com>
|
bugbot run |
There was a problem hiding this comment.
Cursor Bugbot has reviewed your changes using high effort and found 1 potential issue.
❌ 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")), | ||
| ) |
There was a problem hiding this comment.
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)
Reviewed by Cursor Bugbot for commit bae72a7. Configure here.
There was a problem hiding this comment.
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
09b6948
into
litellm_internal_staging


TLDR
Problem this solves:
How it solves it:
tool_output_tokensUser Flow
Before: an operator who turned on Datadog message redaction gets no tool observability at all
datadog_llm_observability_params.turn_off_message_logging: trueand restart the proxyget_weathertool call, and atoolturn carrying that tool's JSON resultassistantmessage readingredacted-by-litellm, and the trace view shows Tool Call 0, Tool Result 0, Avg. Tool Output Tokens no dataAfter: the same request keeps its content private and still shows tool structure and tool output token counts
datadog_llm_observability_params.turn_off_message_logging: trueand restart the proxyget_weathertool call, and atoolturn carrying that tool's JSON resultuserwith redacted content,assistantwith aget_weathertool call whose arguments readredacted-by-litellm, andtoolwith aget_weathertool result readingredacted-by-litellm; the span metrics carrytool_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 proxyRelevant issues
Fixes #40580
Linear ticket
Resolves LIT-7545
Pre-Submission checklist
Please complete all items before asking a LiteLLM maintainer to review your PR
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 morenpm run gen:apioutput for those two lines. This PR touches no route or model@greptileaito 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.6and Anthropicclaude-sonnet-5deployments, 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/spansbody to disk, so the exact span Datadog would receive is what is shown. NoDD_API_KEYwas available, so the Datadog UI itself was not exercised; the span JSON below is the payload it rendersSad 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 integertool_call_idwith 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/messageswith anis_errorlist-contenttool_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 underSIGSTOP, then another afterSIGCONT. 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):Before (7419a53)
/v1/chat/completions tool round trip
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}""content": "The current weather in Paris is 18°C and overcast."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} }tool_calls, notool_results, notool_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 singleassistantplaceholder as input/v1/messages tool_use and tool_result blocks
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"]}}]}'stop_reason: end_turn[{"role": "assistant", "content": "redacted-by-litellm"}], no tool structure, notool_output_tokensSad path, edge and chaos run
bash chaos.sh 20545 21545assistantrow withcontent: redacted-by-litellm, notool_callortool_resultrows, notool_output_tokensmetric, including the 60 KB result and the 20 concurrent round tripshttp://127.0.0.1:20545/ui/?page=logsshows the same requests, 24 Success and 4 FailureAfter (bae72a7)
/v1/chat/completions tool round trip
"content": "The current weather in Paris is 18°C with overcast skies."{ "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} }grep -c 'SECRET-4711\|Paris\|overcast' sink_head.jsonlprints0: the prompt, the tool arguments and the tool result never reached the sink.tool_output_tokensis 30, which islitellm.token_counter(model="anthropic/claude-sonnet-5", text=<the tool result>)/v1/messages tool_use and tool_result blocks
stop_reason: end_turnuserturn):{ "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_tokenskey, as before), streaming round trip, and/v1/responseswithfunction_call_output. A second custom callback with its ownturn_off_message_logging: truewas 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 newtool_output_tokensmetricSad path, edge and chaos run
bash chaos.sh 20546 21546user,assistantandtoolrows survive withtool_call name=get_weather tool_id=call_paris_1 type=function arguments=redacted-by-litellmandtool_result ... result=redacted-by-litellm, and thetool_output_tokenschip 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 52KeyNotFoundErrorspans 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/v1/messagesis_errorspan keeps thetool_usecall and thetool_resultblock, both redacted, withtool_output_tokens=23http://127.0.0.1:20546/ui/?page=logsshows the same requests as base, 24 Success and 4 Failure from the script (plus the stale-token failures described above)grep -c 'SECRET-\|overcast\|Oslo'overmeta.inputandmeta.outputof every span the sink received prints0. 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 itType
🐛 Bug Fix
Caveats (if any)
Medium
datadog_llm_observability_params.turn_off_message_logging(the flag the Datadog docs describe) gets the structured redaction. The globallitellm_settings.turn_off_message_loggingcollapses messages before any callback runs, so Datadog still sees one placeholder thereuser(what the global redaction writes) instead ofassistant(the default the shared hook filled in). No structure and no content either wayLow
/v1/responsesinputs withfunction_callandfunction_call_outputitems already arrive without a role or tool shape when redaction is off, so under redaction they stay role-less placeholders andtool_output_tokensis not counted. Same as before this PRtool_output_tokenscounts withlitellm.token_counterfor the request's model, so the number matches the provider's tokenizer where LiteLLM has one and falls back to the default tokenizer otherwisestr()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 positivemeta.error.messageon failure spans is provider exception text and is not touched by this redaction path (tracked in LIT-6770); andDataDogLLMObsLogger.async_send_batchcallsself.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 haspreserve_events_added_during_flushfor exactly this; tracked in LIT-7593)redacts_messages_itself()defaults toFalseonCustomLogger,LLMMetrics.tool_output_tokensis optional, and the shared hook's signature is unchangedFinal Attestation
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.
CustomLoggeraddsredacts_messages_itself()(defaultFalse). Withturn_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 optionaltool_output_tokenson span metrics (LLMMetricstyped accordingly).Tests cover proxy-style redaction flows, Anthropic tool blocks, malformed identifiers, and self-redacting vs default callbacks.
schema.d.tsonly 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