dspy.BaseLM¶
dspy.BaseLM(model, model_type='chat', temperature=0.0, max_tokens=1000, cache=True, num_retries=0, **kwargs)
¶
Base class for handling LLM calls.
Most users can directly use the dspy.LM class, which is a subclass of BaseLM. Users can also implement their
own subclasses of BaseLM to support custom LLM providers and inject custom logic. To do so, simply override the
forward method and make sure the return format is identical to the
OpenAI response format.
Subclasses whose state is captured by BaseLM.__init__ can use the default dump_state and load_state
methods. Subclasses with extra persistent state should override both methods.
Examples:
from openai import OpenAI
import dspy
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(
model=self.model,
messages=messages or [{"role": "user", "content": prompt}],
**self.kwargs,
)
lm = MyLM(model="gpt-4o-mini")
dspy.configure(lm=lm)
print(dspy.Predict("q->a")(q="Why did the chicken cross the kitchen?"))
Source code in .venv/lib/python3.14/site-packages/dspy/clients/base_lm.py
Functions¶
__call__(prompt: str | None = None, messages: list[dict[str, Any]] | None = None, **kwargs) -> list[dict[str, Any] | str]
¶
Source code in .venv/lib/python3.14/site-packages/dspy/clients/base_lm.py
acall(prompt: str | None = None, messages: list[dict[str, Any]] | None = None, **kwargs) -> list[dict[str, Any] | str]
async
¶
Source code in .venv/lib/python3.14/site-packages/dspy/clients/base_lm.py
aforward(prompt: str | None = None, messages: list[dict[str, Any]] | None = None, **kwargs)
async
¶
Async forward pass for the language model.
Subclasses must implement this method, and the response should be identical to either of the following formats:
Raises:
| Type | Description |
|---|---|
ContextWindowExceededError
|
When the request fails because the
input exceeds the model's context window. DSPy adapters and
modules rely on this error to trigger fallback behavior (e.g.
truncating the prompt and retrying). Each subclass is
responsible for catching its provider's native error and
re-raising it as |
Source code in .venv/lib/python3.14/site-packages/dspy/clients/base_lm.py
copy(**kwargs)
¶
Returns a copy of the language model with possibly updated parameters.
Any provided keyword arguments update the corresponding attributes or LM kwargs of
the copy. For example, lm.copy(rollout_id=1, temperature=1.0) returns an LM whose
requests use a different rollout ID at non-zero temperature to bypass cache collisions.
Source code in .venv/lib/python3.14/site-packages/dspy/clients/base_lm.py
dump_state() -> dict[str, Any]
¶
Return a sanitized reconstruction state for this LM.
Subclasses whose state is captured by BaseLM.__init__ can use this
default. Subclasses with extra persistent state should override both
dump_state and load_state.
Returns:
| Type | Description |
|---|---|
dict[str, Any]
|
A dictionary that can be passed to |
dict[str, Any]
|
excludes API keys. |
Source code in .venv/lib/python3.14/site-packages/dspy/clients/base_lm.py
forward(prompt: str | None = None, messages: list[dict[str, Any]] | None = None, **kwargs)
¶
Forward pass for the language model.
Subclasses must implement this method, and the response should be identical to either of the following formats:
Raises:
| Type | Description |
|---|---|
ContextWindowExceededError
|
When the request fails because the
input exceeds the model's context window. DSPy adapters and
modules rely on this error to trigger fallback behavior (e.g.
truncating the prompt and retrying). Each subclass is
responsible for catching its provider's native error and
re-raising it as |
Source code in .venv/lib/python3.14/site-packages/dspy/clients/base_lm.py
inspect_history(n: int = 1, file: TextIO | None = None) -> None
¶
load_state(state: dict[str, Any], *, allow_custom_lm_class: bool = False) -> BaseLM
classmethod
¶
Reconstruct an LM from dump_state output.
Legacy states without a class marker load as dspy.LM. Custom LM
classes must be importable by their module-qualified class path and are
only loaded when allow_custom_lm_class=True.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
state
|
dict[str, Any]
|
Serialized LM state produced by |
required |
allow_custom_lm_class
|
bool
|
If True, allow importing and loading custom
|
False
|
Returns:
| Type | Description |
|---|---|
BaseLM
|
The reconstructed LM instance. |
Raises:
| Type | Description |
|---|---|
ValueError
|
If |
ImportError
|
If the serialized LM class cannot be imported. |
TypeError
|
If the serialized class is not a |