DSPy: The framework for programming—not prompting—language models
Python
Refactor: Move model capability checks to BaseLM to remove litellm from adapters (#9516)
Maxime Rivestd0b893209a3c
diff --git a/docs/docs/learn/programming/tools.md b/docs/docs/learn/programming/tools.mdindex 0beded062..2b3d46807 100644--- a/docs/docs/learn/programming/tools.md+++ b/docs/docs/learn/programming/tools.md@@ -211,7 +211,7 @@ the screenshot below:### Model Compatibility-Native function calling automatically detects model support using `litellm.supports_function_calling()`. If the model doesn't support native function calling, DSPy will fall back to manual text-based parsing even when `use_native_function_calling=True` is set.+Native function calling automatically checks whether the LM supports it. DSPy's built-in [`dspy.LM`][dspy.LM] uses LiteLLM for this, and custom [`dspy.BaseLM`][dspy.BaseLM] implementations can override `supports_function_calling` to opt in. If the model does not support native function calling, DSPy falls back to manual text-based parsing even when `use_native_function_calling=True` is set.## Async Toolsdiff --git a/dspy/adapters/base.py b/dspy/adapters/base.pyindex 751b018f2..d57fe1314 100644--- a/dspy/adapters/base.py+++ b/dspy/adapters/base.py@@ -2,7 +2,6 @@ import loggingfrom typing import TYPE_CHECKING, Any, get_originimport json_repair-import litellmfrom dspy.adapters.types import History, Typefrom dspy.adapters.types.base_type import split_message_content_for_custom_types@@ -84,15 +83,13 @@ class Adapter:"input field with type `list[dspy.Tool]`.")- if tool_call_output_field_name and litellm.supports_function_calling(model=lm.model):+ if tool_call_output_field_name and lm.supports_function_calling:tools = inputs[tool_call_input_field_name]tools = tools if isinstance(tools, list) else [tools]- litellm_tools = []- for tool in tools:- litellm_tools.append(tool.format_as_litellm_function_call())+ lm_tools = [tool.format_as_litellm_function_call() for tool in tools]- lm_kwargs["tools"] = litellm_tools+ lm_kwargs["tools"] = lm_toolssignature_for_native_function_calling = signature.delete(tool_call_output_field_name)signature_for_native_function_calling = signature_for_native_function_calling.delete(diff --git a/dspy/adapters/json_adapter.py b/dspy/adapters/json_adapter.pyindex 897e73fc9..d45158f90 100644--- a/dspy/adapters/json_adapter.py+++ b/dspy/adapters/json_adapter.py@@ -3,7 +3,6 @@ import loggingfrom typing import Any, get_originimport json_repair-import litellmimport pydanticimport regexfrom pydantic.fields import FieldInfo@@ -45,18 +44,12 @@ class JSONAdapter(ChatAdapter):def _json_adapter_call_common(self, lm, lm_kwargs, signature, demos, inputs, call_fn):"""Common call logic to be used for both sync and async calls."""- provider = lm.model.split("/", 1)[0] or "openai"- params = litellm.get_supported_openai_params(model=lm.model, custom_llm_provider=provider)-- if not params or "response_format" not in params:+ if "response_format" not in lm.supported_params:return call_fn(lm, lm_kwargs, signature, demos, inputs)has_tool_calls = any(field.annotation == ToolCalls for field in signature.output_fields.values())- # Some models support json mode but not structured outputs- # Follows guidance from: https://docs.litellm.ai/docs/completion/json_mode#check-model-support- supports_structured_outputs = litellm.supports_response_schema(model=lm.model, custom_llm_provider=provider)- if _has_open_ended_mapping(signature) or (not self.use_native_function_calling and has_tool_calls) or not supports_structured_outputs:+ if _has_open_ended_mapping(signature) or (not self.use_native_function_calling and has_tool_calls) or not lm.supports_response_schema:# We found that structured output mode doesn't work well with dspy.ToolCalls as output field.# So we fall back to json mode if native function calling is disabled and ToolCalls is present.lm_kwargs["response_format"] = {"type": "json_object"}diff --git a/dspy/adapters/types/base_type.py b/dspy/adapters/types/base_type.pyindex 4783cee03..255686cea 100644--- a/dspy/adapters/types/base_type.py+++ b/dspy/adapters/types/base_type.py@@ -4,9 +4,10 @@ from typing import TYPE_CHECKING, Any, Optional, get_args, get_originimport json_repairimport pydantic-from litellm import ModelResponseStreamif TYPE_CHECKING:+ from litellm import ModelResponseStream+from dspy.clients.lm import LMfrom dspy.signatures.signature import Signature@@ -105,7 +106,7 @@ class Type(pydantic.BaseModel):return False@classmethod- def parse_stream_chunk(cls, chunk: ModelResponseStream) -> Optional["Type"]:+ def parse_stream_chunk(cls, chunk: "ModelResponseStream") -> Optional["Type"]:"""Parse a stream chunk into the custom type.diff --git a/dspy/adapters/types/reasoning.py b/dspy/adapters/types/reasoning.pyindex f0c3d963b..3a036c344 100644--- a/dspy/adapters/types/reasoning.py+++ b/dspy/adapters/types/reasoning.py@@ -1,6 +1,5 @@from typing import TYPE_CHECKING, Any, Optional-import litellmimport pydanticfrom dspy.adapters.types.base_type import Type@@ -61,7 +60,7 @@ class Reasoning(Type):# reasoning effort is set in `lm_kwargs` or `lm.kwargs`.reasoning_effort = "low"- if reasoning_effort is None or not litellm.supports_reasoning(lm.model):+ if reasoning_effort is None or not lm.supports_reasoning:# If users explicitly set `reasoning_effort` to None or the LM doesn't support reasoning, we don't enable# native reasoning.return signaturediff --git a/dspy/clients/base_lm.py b/dspy/clients/base_lm.pyindex c5b271259..3770c4c2b 100644--- a/dspy/clients/base_lm.py+++ b/dspy/clients/base_lm.py@@ -27,6 +27,24 @@ class BaseLM:class MyLM(dspy.BaseLM):+ @property+ def supports_function_calling(self) -> bool:+ return self.model.startswith("openai/gpt-4o")++ @property+ def supports_reasoning(self) -> bool:+ return self.model.startswith("anthropic/claude-3-7")++ @property+ def supports_response_schema(self) -> bool:+ return self.model.startswith("openai/gpt-4o")++ @property+ def supported_params(self) -> set[str]:+ if self.model.startswith("openai/gpt-4o"):+ return {"response_format"} # accepts response_format=...+ return set()+def forward(self, prompt, messages=None, **kwargs):client = OpenAI()return client.chat.completions.create(@@ -49,6 +67,26 @@ class BaseLM:self.kwargs = dict(temperature=temperature, max_tokens=max_tokens, **kwargs)self.history = []+ @property+ def supports_function_calling(self) -> bool:+ """Whether the model supports function calling (tool use)."""+ return False++ @property+ def supports_reasoning(self) -> bool:+ """Whether the model supports native reasoning (extended thinking)."""+ return False++ @property+ def supports_response_schema(self) -> bool:+ """Whether the model supports structured output via response schema."""+ return False++ @property+ def supported_params(self) -> set[str]:+ """Set of supported OpenAI-style parameter names for the model."""+ return set()+def _process_lm_response(self, response, prompt, messages, **kwargs):merged_kwargs = {**self.kwargs, **kwargs}diff --git a/dspy/clients/lm.py b/dspy/clients/lm.pyindex 4ed9e2bfc..3921cc889 100644--- a/dspy/clients/lm.py+++ b/dspy/clients/lm.py@@ -112,6 +112,30 @@ class LM(BaseLM):self._warn_zero_temp_rollout(self.kwargs.get("temperature"), self.kwargs.get("rollout_id"))+ @property+ def _provider_name(self) -> str:+ """Extract the provider name from the model string (e.g., 'openai' from 'openai/gpt-4o')."""+ if "/" in self.model:+ return self.model.split("/", 1)[0]+ return "openai"++ @property+ def supports_function_calling(self) -> bool:+ return litellm.supports_function_calling(model=self.model)++ @property+ def supports_reasoning(self) -> bool:+ return litellm.supports_reasoning(self.model)++ @property+ def supports_response_schema(self) -> bool:+ return litellm.supports_response_schema(model=self.model, custom_llm_provider=self._provider_name)++ @property+ def supported_params(self) -> set[str]:+ params = litellm.get_supported_openai_params(model=self.model, custom_llm_provider=self._provider_name)+ return set(params) if params else set()+def _warn_zero_temp_rollout(self, temperature: float | None, rollout_id):if not self._warned_zero_temp_rollout and rollout_id is not None and temperature == 0:warnings.warn(