Skip to content

fix(aiguard): evaluate LiteLLM proxy /v1/responses and /v1/messages answers - #22038

Merged
gh-worker-dd-mergequeue-cf854d[bot] merged 6 commits into
mainfrom
alberto.vara/fix-litellm-responses-messages-evaluation
Nov 25, 2026
Merged

gh-worker-dd-mergequeue-cf854d[bot] merged 6 commits into
mainfrom
alberto.vara/fix-litellm-responses-messages-evaluation

Conversation

@avara1986

@avara1986 avara1986 commented Nov 23, 2026 •

Copy link
Copy Markdown
Member

Description

Jira: APPSEC-71907

A LiteLLM proxy can run the Datadog AI Guard guardrail in pre_call and post_call mode. #21845 made the guardrail own the AI Guard evaluation of chat and text completion requests in the proxy, and left /v1/responses and /v1/messages requests to the provider listeners. But litellm sends these requests with its own HTTP client (its Responses API and Anthropic Messages handlers). For /v1/messages to an OpenAI model it can also go through chat.completions.with_raw_response, whose answer the OpenAI integration cannot read. As a result:

  • The answers of these routes, including hosted MCP mcp_call and mcp_approval_request items, were never evaluated, and the post_call mode could not block them.
  • On /v1/messages, the guardrail's prompt conversion dropped the system prompt and the tool_use and tool_result blocks, so a prompt injection inside a tool result never reached AI Guard. The OpenAI integration also evaluated the prompt a second time.

Changes in ddtrace/aiguard/integrations/litellm.py

  • Claim. In the proxy with the post_call mode, the guardrail claims a request only when its post-call hooks evaluate the answer: chat and text completions as before, and now non-streamed responses, aresponses and anthropic_messages requests on a create route (/responses or /v1/messages). The provider listeners skip a claimed request. Streamed Responses and Messages requests and /cursor/chat/completions are not claimed, so the provider listeners keep their checks there.
  • Responses prompts. The pre-call check uses the Responses input converter, so instructions, input and the prompt variables of a saved prompt are evaluated. litellm's own conversion drops the variables. If the converter fails, litellm's conversion still runs.
  • Answers. The post-call hook finds the route from the proxy URL and evaluates the non-streamed answer one time:
    • /v1/responses: the Responses converter, with the hosted MCP servers of the request tools (mcp_servers and mcp.server_id, gated by DD_AI_GUARD_MCP_ENABLED, as in the OpenAI integration);
    • /v1/messages: the Anthropic converter.
    • Only the create route of the Responses API is evaluated. Retrieve, cancel, input_items and compact answers are not.
  • Prompt of the answer evaluation. It is rebuilt from the request body (Responses instructions, input and prompt; Anthropic system and messages), never from the request metadata, which the client controls.
  • /v1/messages prompts. The Anthropic converter now converts them, so the system prompt, tool_use and tool_result are evaluated. Before the conversion, the guardrail reads each string item of the content lists as a text block, in a copy, because litellm forwards these items to the model as text.
  • Fallback. When the Anthropic converter cannot read a body, the guardrail evaluates the chat conversion of the messages and does not claim the request. Thus a provider listener that sees the model call still evaluates it.
  • Errors. A body or an answer that the converters cannot convert never fails the proxy request. The guardrail logs at debug level and skips the evaluation that it cannot build. A tools declaration that cannot be read only drops the MCP metadata.

.cursor/rules/ai-guard.mdc describes the new claim conditions, the route rule, the fallback and the known limit below.

Request (pre_call and post_call modes) Before After
/v1/responses, not streamed guardrail: prompt guardrail: prompt and answer
/v1/messages, not streamed guardrail: prompt without the system prompt and tool blocks; OpenAI integration: prompt (OpenAI models on the chat path) guardrail: prompt and answer
/v1/messages that the Anthropic converter cannot read same as the row above guardrail: text of the prompt and answer; provider listeners: as before
/v1/responses and /v1/messages, streamed guardrail: prompt; OpenAI integration: prompt (/v1/messages to OpenAI models on the chat path) unchanged: not claimed, and the stream passes through live

Customer impact

With the guardrail in post_call mode, a LiteLLM proxy now evaluates the non-streamed answers of /v1/responses and /v1/messages requests and can block them. /v1/messages prompts are evaluated with their system prompt, tool calls and tool results. The release note describes the fix.

Testing

  • scripts/run-tests: ai_guard_litellm_guardrail passes on all 10 environments (litellm 1.78.5 and 1.82.6, Python 3.10 to 3.14), 249 tests in each.
  • New unit tests in test_litellm_guardrail.py:
    • the claimed call types and the route rule (create route only);
    • the conversion of Responses and Messages answers, with hosted MCP mcp_servers and mcp.server_id, and without them when DD_AI_GUARD_MCP_ENABLED=false;
    • the prompt from the request body, also with only the post_call mode;
    • string items of content lists;
    • the converter fallback, which does not claim;
    • conversion errors, which skip the evaluation and do not fail the request.
  • New proxy tests in test_litellm_proxy.py send requests through the LiteLLM proxy app in process, with offline stubs:
    • /v1/responses, and /v1/messages on the chat path, on the litellm 1.82.6 Responses adapter and on the native Anthropic path, get one prompt and one answer evaluation from the guardrail and none from the provider listeners;
    • a DENY answer returns HTTP 403;
    • a prompt injection inside a tool_result is blocked;
    • a body that the Anthropic converter cannot read is not claimed, and it can still be blocked through the OpenAI integration;
    • streamed answers pass through.
  • The /v1/messages assertion that codified the gap ([("litellm", "prompt"), ("openai", "prompt")]) now expects one guardrail prompt and one guardrail answer.
  • With the litellm.py of main, 64 of the 249 tests fail.
  • scripts/lint checks, the type comment check and reno lint pass.

Risks

  • In post_call mode, a non-streamed /v1/responses or /v1/messages request now waits for one more AI Guard evaluation (the answer), as chat completions already do.
  • A /v1/messages body that the Anthropic converter cannot read gets two prompt evaluations when litellm sends it through the OpenAI SDK: one from the guardrail and one from the OpenAI integration.
  • Known limit, described in .cursor/rules/ai-guard.mdc: litellm's chat completions adapter for /v1/messages can send an image block inside a tool_result to the model as tool text (for example litellm 1.78.5 for OpenAI and Azure OpenAI models). The guardrail evaluates that block as an image, not as text.
  • Streamed /v1/responses and /v1/messages answers are still not evaluated.

Additional Notes

🤖 Generated with Claude Code

…nswers

In the LiteLLM proxy, the AI Guard guardrail evaluated the prompt of
/v1/responses and /v1/messages requests but never their answers. It did
not claim these requests, and litellm sends them with its own HTTP
client, so no provider listener evaluated the answers either. The
/v1/messages prompt check also dropped the system prompt and the
tool_use and tool_result blocks.

In post_call mode the guardrail now claims these requests and evaluates
their non-streamed answers once, with the prompt rebuilt from the
request body. Responses answers carry the hosted MCP servers of the
request tools. /v1/messages prompts go through the Anthropic converter;
when it cannot read a body, the guardrail evaluates the chat conversion
of the messages and does not claim the request.

Jira: APPSEC-71907

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
@cit-pr-commenter-54b7da

cit-pr-commenter-54b7da Bot commented Nov 23, 2026 •

Copy link
Copy Markdown

Codeowners resolved as

Resolved from the full PR diff against main using the target branch CODEOWNERS file.
CODEOWNERS team requests not listed below are not required by the current file set.

.cursor/rules/ai-guard.mdc                                              @DataDog/asm-python
ddtrace/aiguard/integrations/_anthropic.py                              @DataDog/asm-python
ddtrace/aiguard/integrations/litellm.py                                 @DataDog/asm-python
releasenotes/notes/fix-aiguard-litellm-proxy-responses-messages-65f8e6a35c745a54.yaml  @DataDog/apm-python
tests/aiguard/anthropic/test_anthropic.py                               @DataDog/asm-python
tests/aiguard/litellm_guardrail/test_litellm_guardrail.py               @DataDog/asm-python
tests/aiguard/litellm_guardrail/test_litellm_proxy.py                   @DataDog/asm-python

@cit-pr-commenter-54b7da

cit-pr-commenter-54b7da Bot commented Nov 23, 2026 •

Copy link
Copy Markdown

Dependency direction analysis

⚠️ Existing dependency direction violations

There are 22 dependency direction violations that already exist on the base branch and have not been changed by this PR.

Show existing violations (showing 5 of 22 highest severity)
ddtrace.internal.tracemethods -×-> ddtrace.trace  (internal-core -> product:tracing, score=103)
ddtrace.llmobs._integrations.base -×-> ddtrace.trace  (product:llmobs -> product:tracing, score=101)
ddtrace.llmobs._integrations.bedrock_agents -×-> ddtrace.trace  (product:llmobs -> product:tracing, score=101)
ddtrace.internal.span_bus -×-> ddtrace._trace.span  (internal-core -> product:tracing, score=35)
ddtrace.llmobs._llmobs -×-> ddtrace._trace.span  (product:llmobs -> product:tracing, score=33)

To see all violations, download the layers-base.json and layers-pr.json artifacts from this CI job and run:

uv run --script scripts/import-analysis/layers.py compare layers-base.json layers-pr.json

@pr-commenter

pr-commenter Bot commented Nov 23, 2026 •

Copy link
Copy Markdown

Benchmarks

Benchmark execution time: 2026-11-25 13:41:05

Comparing candidate commit 43973c4 in PR branch alberto.vara/fix-litellm-responses-messages-evaluation with baseline commit b9d1844 in branch main.

📊 Benchmarking dashboard

Found 0 performance improvements and 0 performance regressions! Performance is the same for 404 metrics, 9 unstable metrics.

Explanation

This is an A/B test comparing a candidate commit's performance against that of a baseline commit. Performance changes are noted in the tables below as:

  • 🟩 = significantly better candidate vs. baseline
  • 🟥 = significantly worse candidate vs. baseline

We compute a confidence interval (CI) over the relative difference of means between metrics from the candidate and baseline commits, considering the baseline as the reference.

If the CI is entirely outside the configured SIGNIFICANT_IMPACT_THRESHOLD (or the deprecated UNCONFIDENCE_THRESHOLD), the change is considered significant.

Feel free to reach out to #apm-benchmarking-platform on Slack if you have any questions.

More details about the CI and significant changes

You can imagine this CI as a range of values that is likely to contain the true difference of means between the candidate and baseline commits.

CIs of the difference of means are often centered around 0%, because often changes are not that big:

---------------------------------(------|---^--------)-------------------------------->
                              -0.6%    0%  0.3%     +1.2%
                                 |          |        |
         lower bound of the CI --'          |        |
sample mean (center of the CI) -------------'        |
         upper bound of the CI ----------------------'

As described above, a change is considered significant if the CI is entirely outside the configured SIGNIFICANT_IMPACT_THRESHOLD (or the deprecated UNCONFIDENCE_THRESHOLD).

For instance, for an execution time metric, this confidence interval indicates a significantly worse performance:

----------------------------------------|---------|---(---------^---------)---------->
                                       0%        1%  1.3%      2.2%      3.1%
                                                  |   |         |         |
       significant impact threshold --------------'   |         |         |
                      lower bound of CI --------------'         |         |
       sample mean (center of the CI) --------------------------'         |
                      upper bound of CI ----------------------------------'

Unstable benchmarks

These benchmarks have a confidence interval too wide to call a change; treat them as noise rather than signal.

scenario:coreapiscenario-context_with_data_listeners

  • unstable execution_time [-719.733ns; +686.494ns] or [-6.636%; +6.329%]

scenario:coreapiscenario-core_dispatch_1_listener

  • unstable execution_time [-33.399ns; +40.849ns] or [-5.207%; +6.369%]

scenario:coreapiscenario-core_dispatch_50_listeners

  • unstable execution_time [-1740.663ns; +2001.143ns] or [-8.646%; +9.940%]

scenario:coreapiscenario-core_dispatch_exception_listeners

  • unstable execution_time [-1857.510ns; +1677.204ns] or [-9.575%; +8.646%]

scenario:coreapiscenario-core_dispatch_listeners

  • unstable execution_time [-397.526ns; +344.098ns] or [-9.084%; +7.863%]

scenario:coreapiscenario-core_dispatch_no_args_listeners

  • unstable execution_time [-215.563ns; +230.613ns] or [-7.812%; +8.357%]

scenario:coreapiscenario-core_dispatch_with_results_1_listener

  • unstable execution_time [-98.564ns; +74.519ns] or [-7.127%; +5.388%]

scenario:coreapiscenario-core_dispatch_with_results_50_listeners

  • unstable execution_time [-4614.974ns; +4510.604ns] or [-9.473%; +9.259%]

scenario:coreapiscenario-core_dispatch_with_results_listeners

  • unstable execution_time [-913.792ns; +910.516ns] or [-8.859%; +8.827%]

@avara1986

Copy link
Copy Markdown
Member Author

@codex review

@chatgpt-codex-connector

chatgpt-codex-connector Bot commented Nov 24, 2026 •

Copy link
Copy Markdown
Codex Review Summary: ✅ Completed

This comment shows the latest Codex review activity on this pull request.

Review Status Commit Review trigger
📝 Code Review ✅ Completed 2026-11-25T13:18:56.967677Z 43973c4 New commits
ℹ️ About Codex in GitHub

Your team has set up Codex to review pull requests in this repo. Reviews are triggered when you

  • Open a pull request for review
  • Mark a draft as ready
  • Comment "@codex review" or "@codex security review".

Codex reacts with 👀 while any review is running, comments if it has suggestions, and reacts with 👍 once all reviews finish with no findings.

@chatgpt-codex-connector

Copy link
Copy Markdown

Codex Review: Didn't find any major issues. Breezy!

Reviewed commit: 20c5f61f32

ℹ️ About Codex in GitHub

Your team has set up Codex to review pull requests in this repo. Reviews are triggered when you

  • Open a pull request for review
  • Mark a draft as ready
  • Comment "@codex review".

If Codex has suggestions, it will comment; otherwise it will react with 👍.

Codex can also answer questions or update the PR. Try commenting "@codex address that feedback".

@avara1986
avara1986 marked this pull request as ready for review November 24, 2026 16:35
@avara1986
avara1986 requested review from a team as code owners November 24, 2026 16:35
@avara1986
avara1986 requested review from florentinl and removed request for a team November 24, 2026 16:35

@datadog-datadog-prod-us1-2 datadog-datadog-prod-us1-2 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.

Bits Code Review: FAIL

Mixed Messages turns can bypass user-text rules because conversion puts a tool result last and then suppresses the provider check. Saved Responses prompts also lose MCP server identity when their tools are resolved server-side.

Open Bits AI session

🤖 Bits Code Review · Commit 20c5f61

Comment thread ddtrace/aiguard/integrations/litellm.py Resolved
Comment thread ddtrace/aiguard/integrations/litellm.py Resolved
…onses tools

The Anthropic converter emitted the text of a user turn before its
tool_result messages, so new user text was not the last turn. Tool
results answer the previous assistant turn, so they now come first.

For /v1/responses answers in the LiteLLM proxy, the hosted MCP servers
fall back to the tools echoed in the response when the request has
none (saved prompts), as the OpenAI integration does.

Jira: APPSEC-71907

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>

@datadog-datadog-prod-us1-2 datadog-datadog-prod-us1-2 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.

Bits Code Review: PASS

More details

The PR adds AI Guard evaluation of non-streamed LiteLLM Responses and Messages answers.
Mixed Messages ordering now preserves user-text checks.
Saved prompts now retain MCP server identity.
Both earlier findings are resolved; no issues remain open.
Streamed answers remain unevaluated; full suites were not rerun for this update.

Was this helpful? React 👍 or 👎

Open Bits AI session

🤖 Bits Code Review · Commit cbc2bef

Comment thread ddtrace/aiguard/integrations/litellm.py Resolved
Comment thread ddtrace/aiguard/integrations/litellm.py Resolved
…wers

The pre-call check of LiteLLM proxy Responses requests now uses the
Responses input converter, because litellm drops the variables of a
saved prompt that the provider still gets.

The guardrail now claims a proxy request only when its post-call hooks
evaluate the answer: chat and text completions, and Responses and
Messages requests that are not streamed and use a create route.
Streamed Responses and Messages requests and /cursor/chat/completions
keep the provider listener checks.

Jira: APPSEC-71907

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>

@datadog-datadog-prod-us1-2 datadog-datadog-prod-us1-2 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.

Bits Code Review: FAIL

The PR adds AI Guard evaluation of non-streamed LiteLLM Responses and Messages answers.
Earlier Messages ordering and saved-prompt MCP identity defects remain fixed.
The latest commit preserves provider checks for unevaluated routes and streams.
One issue remains: LiteLLM-supported Responses text blocks can bypass prompt evaluation.
Full suites were not rerun.

Open Bits AI session

🤖 Bits Code Review · Commit 84854e7

Comment thread ddtrace/aiguard/integrations/litellm.py Resolved
florentinl
florentinl approved these changes Nov 25, 2026 •
The LiteLLM proxy accepts chat-style text parts in a Responses input
and sends them to the model, but the Responses converter reads only
input_text and output_text parts. The guardrail now reads them as
input_text parts, in a copy, for the prompt and answer checks.

Jira: APPSEC-71907

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>

@datadog-datadog-prod-us1-2 datadog-datadog-prod-us1-2 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.

Bits Code Review: FAIL

The PR evaluates non-streamed LiteLLM Responses and Messages answers.
Messages ordering and saved-prompt MCP identity defects remain fixed.
This commit restores chat-style text inside user messages.
The same content-loss defect remains in function-call outputs, leaving tool-result injections unchecked.
Streamed answers remain unevaluated; full suites were not rerun.

Open Bits AI session

🤖 Bits Code Review · Commit f1c25ce

Comment thread ddtrace/aiguard/integrations/litellm.py Resolved
Co-authored-by: datadog-datadog-prod-us1-2[bot] <261164178+datadog-datadog-prod-us1-2[bot]@users.noreply.github.com>

@datadog-datadog-prod-us1-2 datadog-datadog-prod-us1-2 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.

Bits Code Review: PASS

More details

AI Guard evaluates non-streamed LiteLLM Responses and Messages answers.
Messages ordering and saved-prompt MCP identity defects are fixed.
Chat-style text is preserved in user messages and function-call outputs.
All reported findings are resolved; none remain open.
Streamed answers remain unevaluated; full suites were not rerun.

Was this helpful? React 👍 or 👎

Open Bits AI session

🤖 Bits Code Review · Commit 766d123

@datadog-datadog-prod-us1-2

datadog-datadog-prod-us1-2 Bot commented Nov 25, 2026 •

Copy link
Copy Markdown
Contributor

Pipelines  Tests

🎉 All green!

🧪 All tests passed
❄️ No new flaky tests detected

This comment will be updated automatically if new data arrives.
🔗 Commit SHA: 43973c4 | Docs | View more details | Give us feedback!

Reformat the tool output branch of _responses_text_parts, which was
over the line length, and test that chat-style text parts of a
function_call_output are evaluated.

Jira: APPSEC-71907

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
@avara1986

Copy link
Copy Markdown
Member Author

/merge

@gh-worker-devflow-routing-ef8351

gh-worker-devflow-routing-ef8351 Bot commented Nov 25, 2026 •

Copy link
Copy Markdown

View all feedbacks in Devflow UI.

2026-11-25 13:53:27 UTC ℹ️ Start processing command /merge


2026-11-25 13:53:31 UTC ℹ️ MergeQueue: pull request added to the queue

The expected merge time in main is approximately 1h (p90).


2026-11-25 14:26:31 UTC ❌ MergeQueue: The build pipeline failed for this merge request

Build pipeline has failing jobs for 58bb310:

What to do next?

  • Investigate the failures and when ready, re-add your pull request to the queue!
  • If your PR checks are green, try to rebase/merge. It might be because the CI run is a bit old.
  • Any question, go check the FAQ.

This build will be kept for 3h more. During that period, you can retry the pipeline or the failing jobs and then re-run the same command!
If you want to reset everything, you can cancel your previous command by rerunning it with the -c flag.

@avara1986

Copy link
Copy Markdown
Member Author

/merge

@gh-worker-devflow-routing-ef8351

gh-worker-devflow-routing-ef8351 Bot commented Nov 25, 2026 •

Copy link
Copy Markdown

View all feedbacks in Devflow UI.

2026-11-25 14:50:07 UTC ℹ️ Start processing command /merge


2026-11-25 14:50:11 UTC ℹ️ MergeQueue: pull request added to the queue

The expected merge time in main is approximately 1h (p90).


2026-11-25 15:32:45 UTC ℹ️ MergeQueue: This merge request was merged

@gh-worker-dd-mergequeue-cf854d
gh-worker-dd-mergequeue-cf854d Bot merged commit f2a4810 into main Nov 25, 2026
558 checks passed
@gh-worker-dd-mergequeue-cf854d
gh-worker-dd-mergequeue-cf854d Bot deleted the alberto.vara/fix-litellm-responses-messages-evaluation branch November 25, 2026 15:32
avara1986 added a commit that referenced this pull request Nov 25, 2026
…thropic-evaluate-mcp-connector

Resolve the conflicts with #22038: keep the in-order content walk and apply its
rule there, so the tool results of a user turn come before that turn's text.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
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.

2 participants