DSPyDSPy 3.3 · Python 3.10+
0%
1
Curious builder0 XP earned · 300 to level 2
0 daysFinish a lesson to begin
Badge collection0 of 6 unlocked
24 small wins to finish your pathNext lesson

Real models: providers, keys and switching

dspy.LM takes a LiteLLM model string, so one line picks OpenAI, Anthropic or a local model. dspy.context switches the model for part of a program.

ModelKey
dspy.LM("openai/gpt-4o-mini")OPENAI_API_KEY
dspy.LM("anthropic/claude-sonnet-4-5")ANTHROPIC_API_KEY
dspy.LM("gemini/gemini-2.5-flash")GEMINI_API_KEY
dspy.LM("ollama_chat/llama3.2", api_base="http://localhost:11434")none; Ollama runs on your machine

The part before the slash is LiteLLM's provider name, and the key is read from that provider's environment variable. dspy.LM also takes temperature, max_tokens and cache, used on every call.

Example
export OPENAI_API_KEY="sk-..."

Switching models for one block

Example
mock = dspy.LM("openai/gpt-4o-mini", mock_response="[[ ## category ## ]]\nshipping\n\n[[ ## completed ## ]]")
sort = dspy.Predict(Triage)

print(sort(ticket="I was charged twice").category)
with dspy.context(lm=mock):
    print(sort(ticket="I was charged twice").category)
print(sort(ticket="I was charged twice").category)

dspy.configure sets the model for the whole program. dspy.context(lm=...) overrides it only inside the with block, and every module called there uses it. The mock answered shipping inside the block, and the stand-in answered outside it.

Example
sort = dspy.Predict(Triage)
sort.set_lm(dspy.LM("openai/gpt-4o-mini", mock_response="[[ ## category ## ]]\naccount\n\n[[ ## completed ## ]]"))
print(sort(ticket="I was charged twice").category)
print(sort.get_lm().model)

set_lm pins a model to one module, whatever is configured globally. A pipeline can use a cheap model for sorting and a stronger one for writing replies.

Why the course does not use a key
A hosted model gives different, better answers, costs money per call, and its outputs change between runs, so they could not be checked here. The DSPy code around the model is identical: put dspy.LM("openai/gpt-4o-mini") in dspy.configure instead of ShopLM(...), and the programs in these lessons run against it unchanged, with different answers and scores.
Try it yourself
  • Nest two dspy.context blocks with different mocks.
  • Print dspy.settings.lm.model inside and outside a context block.
  • Create dspy.LM("openai/gpt-4o-mini", temperature=0.7) and print its kwargs.

Little by little, you're building something great.