Skip to content

fix(responses): keep nested function tool fields on the chat bridge - #51527

Open
abenezeradane wants to merge 2 commits into
BerriAI:mainfrom
abenezeradane:litellm_responses_nested_function_tools
Open

abenezeradane wants to merge 2 commits into
BerriAI:mainfrom
abenezeradane:litellm_responses_nested_function_tools

Conversation

@abenezeradane

Copy link
Copy Markdown

Handwritten 1-3 sentence description

The proxy now keeps the name, description, and schema of a Chat Completions function tool that a client sends to the Responses API. Before this change, the provider received a tool with no name, so the model did not use it. The proxy compares this tool name with the tool list of the key and stops the request if the tool is not on the list.

Details

TLDR

Problem this solves:

  • Chat Completions shaped tools on /v1/responses lost name, description, schema and strict
  • So the model never called them, and strict providers reject the empty name
  • Fixing only that would let allowed_tools keys reach blocked nested tools

How it solves it:

  • The chat bridge fills those four fields from the nested function object
  • A top-level field that is set still wins, so strict: false stays false
  • The /v1/responses allowlist also checks function.name, like /v1/messages does

Intentional product change: a key with allowed_tools now gets 403 for a Chat Completions shaped tool whose function.name is not on its list. Before, the proxy skipped that tool, and the chat bridge sent it on without a name.

User Flow

Before: a client that sends Chat Completions shaped function tools to /v1/responses on a chat-bridged model never gets a tool call, and a restricted key's tool list never sees those tools

  1. The client sends POST http://localhost:4000/v1/responses with "tools": [{"type": "function", "function": {"name": "read_file", ...}}]
  2. The model gets a tool with an empty name, an empty description and a bare object schema
  3. The reply is plain text ("I don't have access to read files...") in 3 of 3 runs, with no function_call
  4. A key whose metadata.allowed_tools is ["get_weather"] sends the same tool and gets 200

After: the same request reaches the model with the real tool, and the restricted key is refused

  1. The client sends the same POST http://localhost:4000/v1/responses
  2. The model gets read_file with its description, its path schema and strict: true
  3. The reply carries function_call read_file({"path":"notes/todo.txt"}) in 3 of 3 runs
  4. The restricted key gets 403 tool_access_denied naming read_file, also when a flat get_weather name wraps it

Relevant issues

Fixes #27276. Its custom tool half already shipped in 1.97.0, so this closes the remaining nested function tool half.

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/unit/<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.)
  • My PR's scope is as isolated as possible; it only solves 1 specific problem
  • Every automated review on my PR's latest commit has finished, and I have addressed or replied to each of its findings before requesting a maintainer review

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

Both runs used the same 2-worker proxy setup, one dedicated Redis for router state and coordination, Postgres for virtual keys, and local Ollama 0.40.15 serving hf.co/JetBrains/Mellum2.1-12B-A2.5B-Thinking-GGUF:Q4_K_M through the OpenAI-compatible chat endpoint. The curl requests replay the tool layout from the issue's reproduction. No coding tool is installed on this machine, so none was driven.

Shared setup: containers, env vars, config, proxy command
docker run -d --rm --name litellm-qa-redis -p 127.0.0.1:6391:6379 redis:7.4.2
docker run -d --rm --name litellm-qa-pg -e POSTGRES_USER=litellm -e POSTGRES_PASSWORD="$QA_PG_PASSWORD" \
  -e POSTGRES_DB=litellm -p 127.0.0.1:5491:5432 postgres:18-alpine

Env vars, values not shown: LITELLM_MASTER_KEY (a random sk- key), QA_PG_PASSWORD, and DATABASE_URL=postgresql://litellm:$QA_PG_PASSWORD@127.0.0.1:5491/litellm.

proxy_config.yaml is litellm/proxy/dev_config.yaml with this diff:

@@ -197,8 +197,19 @@
       model: openai/gpt-4o-mini
       api_key: os.environ/OPENAI_API_KEY
 
+  # ---------- Local Ollama through the Responses-to-chat bridge ----------
+  - model_name: mellum-bridge
+    litellm_params:
+      model: openai/hf.co/JetBrains/Mellum2.1-12B-A2.5B-Thinking-GGUF:Q4_K_M
+      api_base: http://127.0.0.1:11434/v1
+      api_key: ollama
+      use_chat_completions_api: true
+
 general_settings:
   master_key: os.environ/LITELLM_MASTER_KEY
+  coordination_redis:
+    host: 127.0.0.1
+    port: 6391
@@ -217,3 +228,7 @@
     sandbox_tool_name: e2b_sandbox
   callbacks:
     - code_interpreter_interception
+
+router_settings:
+  redis_host: 127.0.0.1
+  redis_port: 6391

Before ran from git archive 40debbb9c0 litellm | tar -x in a scratch directory, with the built litellm/rust_bridge/_native.abi3.so copied in and PYTHONPATH pointing at that directory. After ran from the checkout at the PR tip. Port 4127 was Before and 4128 was After.

python litellm/proxy/proxy_cli.py --config proxy_config.yaml --port 4127 --num_workers 2 --detailed_debug --reload \
  --use_v2_migration_resolver 2>&1 | tee before-proxy.log

Each log shows two Started server process lines with different PIDs (Before 19835 and 19836, After 22169 and 22170) and two Application startup complete lines. --use_v2_migration_resolver now only prints a deprecation notice because v2 is the default, and it stays to match the AGENTS.md command.

Client script proof.sh, run as bash proof.sh 4127 and bash proof.sh 4128
#!/usr/bin/env bash
# usage: LITELLM_MASTER_KEY=... proof.sh PORT
set -u
port=$1
base="http://127.0.0.1:$port"
: "${LITELLM_MASTER_KEY:?set LITELLM_MASTER_KEY}"

read_file_fields='"name":"read_file","description":"Read a text file from the workspace and return its contents.","parameters":{"type":"object","properties":{"path":{"type":"string","description":"Workspace-relative file path"}},"required":["path"]},"strict":true'
nested_read_file="{\"type\":\"function\",\"function\":{$read_file_fields}}"
flat_get_weather='{"type":"function","name":"get_weather","description":"Get the weather for a city.","parameters":{"type":"object","properties":{"city":{"type":"string"}},"required":["city"]}}'
decoy_read_file="{\"type\":\"function\",\"name\":\"get_weather\",\"function\":{$read_file_fields}}"

summarize() {  # status body_file
  python3 - "$1" "$2" <<'PY'
import json, sys
status, body = sys.argv[1], json.load(open(sys.argv[2]))
if body.get("error"):
    error = body["error"]
    print("HTTP %s error type=%s message=%s" % (status, error.get("type"), str(error.get("message"))[:110]))
    sys.exit()
items = []
for item in body.get("output", []):
    if item.get("type") == "function_call":
        items.append("function_call %s(%s)" % (item["name"], item["arguments"]))
    elif item.get("type") == "message":
        text = " ".join(part.get("text", "") for part in item.get("content", []))
        items.append("message %r" % text[:70])
    else:
        items.append(str(item.get("type")))
print("HTTP %s output: %s" % (status, "; ".join(items)))
PY
}

ask() {  # key tool
  local out status
  out=$(mktemp)
  status=$(curl -s -o "$out" -w '%{http_code}' "$base/v1/responses" \
    -H "Authorization: Bearer $1" -H "Content-Type: application/json" \
    -d "{\"model\":\"mellum-bridge\",\"input\":\"Read the file notes/todo.txt and tell me what it says.\",\"tools\":[$2],\"max_output_tokens\":2048}")
  summarize "$status" "$out"
  rm -f "$out"
}

echo "== Bridge: Chat Completions shaped read_file tool, master key, 3 runs"
for run in 1 2 3; do printf 'run %s: ' "$run"; ask "$LITELLM_MASTER_KEY" "$nested_read_file"; done

restricted_key=$(curl -s "$base/key/generate" -H "Authorization: Bearer $LITELLM_MASTER_KEY" \
  -H "Content-Type: application/json" \
  -d '{"models":["mellum-bridge"],"metadata":{"allowed_tools":["get_weather"]}}' \
  | python3 -c 'import json, sys; print(json.load(sys.stdin)["key"])')

echo "== Allowlist: key with metadata.allowed_tools = [\"get_weather\"]"
printf 'nested read_file:                   '; ask "$restricted_key" "$nested_read_file"
printf 'flat get_weather decoy + nested read_file: '; ask "$restricted_key" "$decoy_read_file"
printf 'flat get_weather (control):         '; ask "$restricted_key" "$flat_get_weather"

The tool payloads that reached Ollama come from the POST Request Sent from LiteLLM lines that --detailed_debug writes, pulled with grep -o "'tools': \[.*\], 'extra_body'" <proxy log>.

Before (40debbb)

Chat Completions shaped tool, master key

  1. bash proof.sh 4127, bridge part
run 1: HTTP 200 output: reasoning; message "I don't have access to read files from the filesystem. Please provide "
run 2: HTTP 200 output: reasoning; message "I don't have access to read files from the filesystem. However, if you"
run 3: HTTP 200 output: reasoning; message "I don't have access to read files directly. However, if you can provid"
  1. All three requests reached Ollama with this tool list
'tools': [{'type': 'function', 'function': {'name': '', 'description': '', 'parameters': {'type': 'object'}, 'strict': False}}]

Key with metadata.allowed_tools: ["get_weather"]

  1. bash proof.sh 4127, allowlist part
nested read_file:                   HTTP 200 output: reasoning; message "I don't have access to read files from the filesystem. Can you please "
flat get_weather decoy + nested read_file: HTTP 200 output: reasoning; message "I don't have access to read files from the filesystem. The available t"
flat get_weather (control):         HTTP 200 output: reasoning; message "I don't have access to read files from the filesystem. My capabilities"
  1. In order, the nested tool reached Ollama nameless, the decoy reached it as get_weather with the nested schema dropped, and the control kept its own schema
'tools': [{'type': 'function', 'function': {'name': '', 'description': '', 'parameters': {'type': 'object'}, 'strict': False}}]
'tools': [{'type': 'function', 'function': {'name': 'get_weather', 'description': '', 'parameters': {'type': 'object'}, 'strict': False}}]
'tools': [{'type': 'function', 'function': {'name': 'get_weather', 'description': 'Get the weather for a city.', 'parameters': {'type': 'object', 'properties': {'city': {'type': 'string'}}, 'required': ['city']}, 'strict': False}}]

After (ec97a6e)

Chat Completions shaped tool, master key

  1. bash proof.sh 4128, bridge part
run 1: HTTP 200 output: reasoning; message ''; function_call read_file({"path":"notes/todo.txt"})
run 2: HTTP 200 output: reasoning; message ''; function_call read_file({"path":"notes/todo.txt"})
run 3: HTTP 200 output: reasoning; message ''; function_call read_file({"path":"notes/todo.txt"})
  1. All three requests reached Ollama with this tool list
'tools': [{'type': 'function', 'function': {'name': 'read_file', 'description': 'Read a text file from the workspace and return its contents.', 'parameters': {'type': 'object', 'properties': {'path': {'type': 'string', 'description': 'Workspace-relative file path'}}, 'required': ['path']}, 'strict': True}}]

Key with metadata.allowed_tools: ["get_weather"]

  1. bash proof.sh 4128, allowlist part
nested read_file:                   HTTP 403 error type=tool_access_denied message=Tool(s) ['read_file'] are not in the allowed tools list for this key/team.
flat get_weather decoy + nested read_file: HTTP 403 error type=tool_access_denied message=Tool(s) ['read_file'] are not in the allowed tools list for this key/team.
flat get_weather (control):         HTTP 200 output: reasoning; message "I don't have access to read files from the filesystem. My capabilities"
  1. Only the control request reached Ollama. The two refused requests never left the proxy
'tools': [{'type': 'function', 'function': {'name': 'get_weather', 'description': 'Get the weather for a city.', 'parameters': {'type': 'object', 'properties': {'city': {'type': 'string'}}, 'required': ['city']}, 'strict': False}}]

Tests, mutation check and gates

The regression tests live in test_litellm_completion_responses.py (TestToolTransformation), test_openai_responses_guardrail_tool_merge.py and test_tools_allowlist_enforcement.py. Each mutant below was applied to the PR tip on its own and run against the new tests, and every one turned them red.

  • M1, the bridge casts the raw tool again: 5 tests fail, including the guardrail merge test
  • M2, nested fields win over top-level ones: set_top_level_fields_win and explicit_top_level_strict_false_wins fail
  • M3, a falsy top-level field falls back: explicit_top_level_strict_false_wins fails
  • M4, a None top-level field is kept: none_top_level_fields_fall_back_to_nested fails
  • M5, the extractor reads only the flat name: the nested and flat-decoy deny tests and the name list test fail
  • M6, the extractor keeps one name with nested first: flat_name_behind_nested_decoy fails
  • M7, the nested function is not validated: the string and list cases of the non-object test fail
  • M8, the extractor adds a stray name for nested tools: test_openai_responses_chat_completions_shaped_tools_yield_every_name fails

The five lint gates (ruff_strict_gate, type_discipline_gate, test_quality_gate, openapi_docs_gate, type_check_gate) pass against origin/main at ec97a6e. Locally, tests/unit/responses, tests/unit/llms/openai/responses, tests/unit/proxy/guardrails and tests/unit/proxy/test_tools_allowlist_enforcement.py pass (8862 tests), and so do the other callers of the bridge in tests/unit/litellm_core_utils/prompt_templates, tests/unit/router_utils and tests/unit/router_strategy (5479 tests). Seven tests were left out because this machine lacks their environment. Six are in guardrail_hooks/semantic_guard and need semantic_router, and test_deep_tool_arguments_parser_limit_keeps_raw_masking_fallback never reaches its JSON recursion guard on Python 3.14.

Type

🐛 Bug Fix

Caveats (if any)

Severe

  • Keys with allowed_tools now get 403 for nested tools outside their list
    • Before, the check skipped them, and the chat bridge sent them on without a name
    • Operators should add the nested tool names their clients send to allowed_tools

Low

  • Non-string tool names no longer count for the /v1/responses allowlist, same as /v1/messages
    • Before, "name": 123 got 403. Now Ollama refuses it with 400, so no model sees it
    • A provider that turned such a name into a string would get the tool unchecked
  • Three bridge helpers still read only the top-level name of a function tool
    • The namespace collision check, the namespace name map and the deferred tool names
    • They matter only when nested tools mix with namespace tools or defer_loading
  • An empty top-level name still beats a nested one, since only None counts as unset
  • fix(responses): omit tool strict when not provided #50184 (the strict line) and fix(guardrails): check Responses tools in namespace and tool_search_output against allowed_tools #49132 (the extractor loop) touch nearby lines, so expect a small rebase

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

A function tool sent to /v1/responses in the Chat Completions layout
reached the provider with an empty name, an empty description and a bare
object schema, because the bridge read only top-level fields. The bridge
now fills name, description, parameters and strict from the nested
function object when the top level does not set them, so an explicit
top-level strict false still wins.

The Responses tool-name extractor now reads function.name too, through the
shared anthropic_tool_names helper, so allowed_tools sees every name a
tool can act under and a flat decoy name cannot carry a blocked nested one.
…llowed_tools

The deny cases alone let an extractor that adds a stray name for nested
tools pass, which would refuse a client whose tools are all allowed. Assert
the exact name list for a nested tool and a hybrid tool instead.
@veria-ai

veria-ai Bot commented Nov 13, 2026 •

Copy link
Copy Markdown
Contributor

PR overview

No security issues were found in this pull request.

Reviews

This branch has not been deployed

No deployments
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.

[Bug]: Responses API → Chat Completions bridge drops tool names and forwards unsupported tool types (custom, shell)

1 participant