Skip to content

Conversation

@thromel
Copy link

@thromel thromel commented Dec 15, 2025

Summary

  • Add validation in _process_selection_response to check that the LLM response contains a valid tools list before processing
  • Raise a clear ValueError with actionable guidance instead of cryptic KeyError: 'tools'
  • Add unit tests for malformed response handling (missing key and null value cases)

Root Cause

When using with_structured_output(), some models may not strictly follow the schema and could return responses without the expected tools key. The previous code directly accessed response["tools"] without validation, causing intermittent KeyError failures.

Test Plan

  • Added test_malformed_response_missing_tools_key - verifies ValueError is raised when tools key is missing
  • Added test_malformed_response_null_tools - verifies ValueError is raised when tools is None
  • All 12 existing tests pass
  • Lint checks pass

Fixes #34358

…eware

Add validation in `_process_selection_response` to check that the LLM
response contains a valid 'tools' list before processing. Previously,
if the LLM returned a malformed response (missing 'tools' key or null
value), a cryptic `KeyError: 'tools'` was raised.

Now raises a clear `ValueError` with actionable guidance suggesting the
user try a model with better structured output support.

Fixes langchain-ai#34358
@github-actions github-actions bot added langchain `langchain` package issues & PRs fix For PRs that implement a fix and removed fix For PRs that implement a fix labels Dec 15, 2025
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

fix For PRs that implement a fix langchain `langchain` package issues & PRs

Projects

None yet

Development

Successfully merging this pull request may close these issues.

🐛 KeyError: 'tools' in LLMToolSelectorMiddleware when model response misses expected key

1 participant