The agent engineering platform.
Python agentsaiai-agentsanthropicchatgptdeepagentsenterpriseframeworkgeminigenerative-ailangchainlanggraphllmmultiagentopen-sourceopenaipydanticpythonragtypescript
fix(core): make `convert_to_openai_function` handle callables and non-dict mappings (#39750)
gaoanze88804ae7447d72e
diff --git a/libs/core/langchain_core/utils/function_calling.py b/libs/core/langchain_core/utils/function_calling.pyindex 94ca4038cb..0a6ebf7ca9 100644--- a/libs/core/langchain_core/utils/function_calling.py+++ b/libs/core/langchain_core/utils/function_calling.py@@ -29,7 +29,6 @@ from pydantic.v1 import Field as Field_v1from pydantic.v1 import create_model as create_model_v1from typing_extensions import TypedDict, is_typeddict-import langchain_corefrom langchain_core._api import betafrom langchain_core.messages import AIMessage, BaseMessage, HumanMessage, ToolMessagefrom langchain_core.utils.json_schema import dereference_refs@@ -225,8 +224,11 @@ def _convert_python_function_to_openai_function(Returns:The OpenAI function description."""+ # Import locally to prevent circular import+ from langchain_core.tools.base import create_schema_from_function # noqa: PLC0415+func_name = _get_python_function_name(function)- model = langchain_core.tools.base.create_schema_from_function(+ model = create_schema_from_function(func_name,function,filter_args=(),@@ -336,9 +338,10 @@ def _format_tool_to_openai_function(tool: BaseTool) -> FunctionDescription:Returns:The function description."""- is_simple_oai_tool = (- isinstance(tool, langchain_core.tools.simple.Tool) and not tool.args_schema- )+ # Import locally to prevent circular import+ from langchain_core.tools import Tool # noqa: PLC0415++ is_simple_oai_tool = isinstance(tool, Tool) and not tool.args_schemaif tool.tool_call_schema and not is_simple_oai_tool:if isinstance(tool.tool_call_schema, dict):return _convert_json_schema_to_openai_function(@@ -402,6 +405,9 @@ def convert_to_openai_function(`description` and `parameters` keys are now optional. Only `name` isrequired and guaranteed to be part of the output."""+ # Import locally to prevent circular import+ from langchain_core.tools import BaseTool # noqa: PLC0415+if strict and isinstance(function, dict):function = copy.deepcopy(function)@@ -447,7 +453,7 @@ def convert_to_openai_function("dict[str, Any]",_convert_typed_dict_to_openai_function(cast("type", function)),)- elif isinstance(function, langchain_core.tools.base.BaseTool):+ elif isinstance(function, BaseTool):oai_function = cast("dict[str, Any]", _format_tool_to_openai_function(function))elif callable(function):oai_function = cast(diff --git a/libs/core/tests/unit_tests/utils/test_function_calling.py b/libs/core/tests/unit_tests/utils/test_function_calling.pyindex 1e5a2d3e0f..d205fef2ce 100644--- a/libs/core/tests/unit_tests/utils/test_function_calling.py+++ b/libs/core/tests/unit_tests/utils/test_function_calling.py@@ -25,6 +25,7 @@ from packaging.version import parsefrom pydantic import BaseModel, ConfigDict, Fieldfrom pydantic.errors import PydanticInvalidForJsonSchema+import langchain_corefrom langchain_core.messages import AIMessage, HumanMessage, ToolMessagefrom langchain_core.runnables import RunnableLambdafrom langchain_core.tools import BaseTool, StructuredTool, Tool, tool@@ -1475,3 +1476,29 @@ def test_convert_to_openai_tool_computer_passthrough() -> None:}result = convert_to_openai_tool(computer_tool)assert result == computer_tool+++def test_convert_to_openai_function_without_tools_module_imported(+ monkeypatch: pytest.MonkeyPatch,+) -> None:+ """Test conversion works when `langchain_core.tools` is not bound on the package.++ Regression test: the `BaseTool` check reached the class through+ `langchain_core.tools.base`, which is only an attribute of `langchain_core` once+ something imports that submodule. Called from a process that had not, conversion+ raised `AttributeError: module 'langchain_core' has no attribute 'tools'` instead of+ converting the callable.+ """+ monkeypatch.delattr(langchain_core, "tools", raising=False)++ def my_func(x: int) -> int:+ """Return the input.++ Args:+ x: A number.+ """+ return x++ result = convert_to_openai_function(my_func)++ assert result["name"] == "my_func"