Skip to content

Commit 3beba77

Browse files
mohankumar27Mohan Kumar Sagadevanmdrxy
authored
feat(ollama): support response_format (#34612)
Fixes #34610 --- This PR resolves an issue where `ChatOllama` would raise an `unexpected keyword argument 'response_format'` error when used with `create_agent` or when passed an OpenAI-style `response_format`. When using `create_agent` (especially with models like `gpt-oss`), LangChain creates a `response_format` argument (e.g., `{"type": "json_schema", ...}`). `ChatOllama` previously passed this argument directly to the underlying Ollama client, which does not support `response_format` and instead expects a `format` parameter. ## The Fix I updated `_chat_params` in `libs/partners/ollama/langchain_ollama/chat_models.py` to: 1. Intercept the `response_format` argument. 2. Map it to the native Ollama `format` parameter: * `{"type": "json_schema", "json_schema": {"schema": ...}}` -> `format=schema` * `{"type": "json_object"}` -> `format="json"` 3. Remove `response_format` from the kwargs passed to the client. ## Validation * **Reproduction Script**: Verified the fix with a script covering `json_schema`, `json_object`, and explicit `format` priority scenarios. * **New Tests**: Added 3 new unit tests to `libs/partners/ollama/tests/unit_tests/test_chat_models.py` covering these scenarios. * **Regression**: Ran the full test suite (`make -C libs/partners/ollama test`), passing 29 tests (previously 26). * **Lint/Format**: Verified with `make lint_package` and `make format`. --------- Co-authored-by: Mohan Kumar Sagadevan <mohankumarsagadevan@Mohans-MacBook-Air.local> Co-authored-by: Mason Daugherty <mason@langchain.dev> Co-authored-by: Mason Daugherty <github@mdrxy.com>
1 parent 2bc982b commit 3beba77

3 files changed

Lines changed: 369 additions & 2 deletions

File tree

libs/partners/ollama/langchain_ollama/chat_models.py

Lines changed: 107 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -792,12 +792,17 @@ def _chat_params(
792792
if v is not None
793793
}
794794

795+
format_param = self._resolve_format_param(
796+
kwargs.pop("format", self.format),
797+
kwargs.pop("response_format", None),
798+
)
799+
795800
params = {
796801
"messages": ollama_messages,
797802
"stream": kwargs.pop("stream", True),
798803
"model": kwargs.pop("model", self.model),
799804
"think": kwargs.pop("reasoning", self.reasoning),
800-
"format": kwargs.pop("format", self.format),
805+
"format": format_param,
801806
"logprobs": kwargs.pop("logprobs", self.logprobs),
802807
"top_logprobs": kwargs.pop("top_logprobs", self.top_logprobs),
803808
"options": options_dict,
@@ -815,6 +820,107 @@ def _chat_params(
815820

816821
return params
817822

823+
def _resolve_format_param(
824+
self,
825+
format_param: str | dict[str, Any] | None,
826+
response_format: Any | None,
827+
) -> str | dict[str, Any] | None:
828+
"""Resolve the format parameter.
829+
830+
Converts an OpenAI-style `response_format` dict to the `format`
831+
parameter expected by Ollama.
832+
833+
Args:
834+
format_param: The explicit `format` value (takes priority).
835+
response_format: An OpenAI-style `response_format` dict.
836+
837+
Returns:
838+
The resolved format value to pass to the Ollama client.
839+
"""
840+
if format_param is not None:
841+
if response_format is not None:
842+
warnings.warn(
843+
"Both 'format' and 'response_format' were provided. "
844+
"'response_format' will be ignored in favor of 'format'.",
845+
UserWarning,
846+
stacklevel=2,
847+
)
848+
return format_param
849+
850+
if response_format is None:
851+
return None
852+
853+
return self._convert_response_format(response_format)
854+
855+
def _convert_response_format(
856+
self,
857+
response_format: Any,
858+
) -> str | dict[str, Any] | None:
859+
"""Convert an OpenAI-style `response_format` to an Ollama `format` value.
860+
861+
Args:
862+
response_format: The `response_format` value to convert.
863+
864+
Returns:
865+
The Ollama-compatible `format` value, or `None` if conversion fails.
866+
"""
867+
if not isinstance(response_format, dict):
868+
warnings.warn(
869+
f"Ignored invalid 'response_format' type: {type(response_format)}. "
870+
"Expected a dictionary.",
871+
UserWarning,
872+
stacklevel=2,
873+
)
874+
return None
875+
876+
fmt_type = response_format.get("type")
877+
if fmt_type == "json_object":
878+
return "json"
879+
if fmt_type == "json_schema":
880+
return self._extract_json_schema(response_format)
881+
882+
warnings.warn(
883+
f"Ignored unrecognized 'response_format' type: {fmt_type}. "
884+
"Expected 'json_object' or 'json_schema'.",
885+
UserWarning,
886+
stacklevel=2,
887+
)
888+
return None
889+
890+
def _extract_json_schema(
891+
self,
892+
response_format: dict[str, Any],
893+
) -> dict[str, Any] | None:
894+
"""Extract the raw JSON schema from an OpenAI ``json_schema`` envelope.
895+
896+
Args:
897+
response_format: A dict with ``type: "json_schema"``.
898+
899+
Returns:
900+
The raw JSON schema dict, or ``None`` if extraction fails.
901+
"""
902+
json_schema_block = response_format.get("json_schema")
903+
if not isinstance(json_schema_block, dict):
904+
warnings.warn(
905+
"response_format has type 'json_schema' but 'json_schema' "
906+
f"value is {type(json_schema_block)}, expected a dict "
907+
"containing a 'schema' key. "
908+
"The format parameter will not be set.",
909+
UserWarning,
910+
stacklevel=2,
911+
)
912+
return None
913+
schema = json_schema_block.get("schema")
914+
if schema is None:
915+
warnings.warn(
916+
"response_format has type 'json_schema' but no 'schema' "
917+
"key was found in 'json_schema'. "
918+
"The format parameter will not be set.",
919+
UserWarning,
920+
stacklevel=2,
921+
)
922+
return schema
923+
818924
@model_validator(mode="after")
819925
def _set_clients(self) -> Self:
820926
"""Set clients to use for ollama."""

libs/partners/ollama/tests/integration_tests/chat_models/test_chat_models.py

Lines changed: 38 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -2,6 +2,7 @@
22

33
from __future__ import annotations
44

5+
import json
56
from typing import Annotated
67
from unittest.mock import MagicMock, patch
78

@@ -68,7 +69,7 @@ class Joke(BaseModel):
6869
setup: str = Field(description="question to set up a joke")
6970
punchline: str = Field(description="answer to resolve the joke")
7071

71-
llm = ChatOllama(model=DEFAULT_MODEL_NAME, temperature=0)
72+
llm = ChatOllama(model=DEFAULT_MODEL_NAME, temperature=0.3)
7273
query = "Tell me a joke about cats."
7374

7475
# Pydantic
@@ -112,6 +113,42 @@ class JokeSchema(TypedDict):
112113
assert set(chunk.keys()) == {"setup", "punchline"}
113114

114115

116+
@pytest.mark.parametrize(
117+
"response_format",
118+
[
119+
{"type": "json_object"},
120+
{
121+
"type": "json_schema",
122+
"json_schema": {
123+
"name": "joke",
124+
"schema": {
125+
"type": "object",
126+
"properties": {
127+
"setup": {"type": "string"},
128+
"punchline": {"type": "string"},
129+
},
130+
"required": ["setup", "punchline"],
131+
},
132+
},
133+
},
134+
],
135+
ids=["json_object", "json_schema"],
136+
)
137+
def test_response_format(response_format: dict) -> None:
138+
"""Test that OpenAI-style response_format is translated and honored."""
139+
llm = ChatOllama(model=DEFAULT_MODEL_NAME, temperature=0)
140+
result = llm.invoke(
141+
[HumanMessage("Tell me a joke about cats. Return JSON with setup/punchline.")],
142+
response_format=response_format,
143+
)
144+
assert isinstance(result, AIMessage)
145+
parsed = json.loads(str(result.content))
146+
assert isinstance(parsed, dict)
147+
if response_format["type"] == "json_schema":
148+
assert "setup" in parsed
149+
assert "punchline" in parsed
150+
151+
115152
@pytest.mark.parametrize(("model"), [(DEFAULT_MODEL_NAME)])
116153
def test_structured_output_deeply_nested(model: str) -> None:
117154
"""Test to verify structured output with a nested objects."""

0 commit comments

Comments
 (0)