AI & Agent Dev Bug Sandbox logo
AI & Agent Dev Bug Sandbox
Back to Radar

Convert_to_openai_function Mishandles Optional TypedDict Fields (Total=False And NotRequired)

The langchain-core function convert_to_openai_function incorrectly marks all fields as required for TypedDict subclasses defined with total=False, and raises TypeError when encountering NotRequired annotations. This results in invalid OpenAI function schemas that impose incorrect required constraints.

highConfidence 85%LangchainVector StoresEmbeddingsAffected V<=1.2.25

Origin Analysis

The TypedDict-to-OpenAI schema conversion logic fails to properly account for __required_keys__ and __optional_keys__ (or fails to strip Required/NotRequired wrappers before type resolution). For total=False TypedDicts, fields are erroneously treated as required; for NotRequired-wrapped fields, the wrapper itself is passed to downstream type handling, leading to TypeError.
```python from typing_extensions import NotRequired, Required, TypedDict from langchain_core.utils.function_calling import convert_to_openai_function class PartialPayload(TypedDict, total=False): required_value: Required[int] optional_value: str explicit_optional_value: NotRequired[bool] print(convert_to_openai_function(PartialPayload)) # Current behavior: all three fields are marked required. class PayloadWithNotRequired(TypedDict): required_value: int optional_value: NotRequired[str] convert_to_openai_function(PayloadWithNotRequired) # Current behavior: raises TypeError instead of generating a schema. ```

Fixing Code Block

Edge Case Audit

The provided code assumes an existing function _convert_type_to_openai_schema that handles arbitrary Python types; if not available, replace that call with the original conversion logic for each field type. The patch modifies only TypedDict handling and should not affect other input types, but thorough testing is advised when upgrading or using custom type converters. Rollback: revert to the previous version or remove this patch, but note that the bug will reappear.

Ecosystem Topology

Agent Frameworks

LangChain, LlamaIndex, and Pydantic

  1. highProperty graph relation keys collide when entity IDs or labels contain underscores
  2. highCodeActAgent drops assistant tool-call metadata during handoff, leaving an orphan tool response
  3. high[Bug]: HierarchicalNodeParser async methods return the documents unsplit
  4. highLLM.predict_and_call fails with ValidationError for non-function-calling models when react_chat_formatter is omitted
  5. highAnthropic streaming server-tool input_json_delta overwrites completed client tool_use arguments due to stale cur_tool_call state