MCPcopy
hub / github.com/stanfordnlp/dspy / context

Method context

dspy/dsp/utils/settings.py:216–257  ·  view source on GitHub ↗

Override DSPy settings for one `with` block. Use `dspy.context(...)` when you need temporary settings—a different LM, adapter, or flag—without changing the process-wide defaults from `dspy.configure(...)`. The block inherits every current setting, overrides only the

(self, **kwargs)

Source from the content-addressed store, hash-verified

214
215 @contextmanager
216 def context(self, **kwargs):
217 """Override DSPy settings for one `with` block.
218
219 Use `dspy.context(...)` when you need temporary settings—a different
220 LM, adapter, or flag—without changing the process-wide defaults from
221 `dspy.configure(...)`. The block inherits every current setting,
222 overrides only the keys you pass, and restores the originals on exit.
223
224 Unlike `dspy.configure(...)`, you can call `dspy.context(...)` from
225 any thread or async task.
226
227 Args:
228 **kwargs: Settings to override, such as `lm`, `adapter`,
229 `track_usage`, or `allow_tool_async_sync_conversion`.
230
231 Examples:
232 Use a different LM for one call:
233 ```python
234 import dspy
235
236 dspy.configure(lm=dspy.LM("openai/gpt-5-mini"))
237 qa = dspy.Predict("question -> answer")
238
239 with dspy.context(lm=dspy.LM("anthropic/claude-sonnet-4-6")):
240 result = qa(question="What is the capital of France?")
241 # uses claude-sonnet-4-6 inside this block
242 # back to gpt-5-mini here
243 ```
244
245 See Also:
246 `dspy.configure`: set process-wide defaults.
247 """
248 # `dspy.context` is documented manually in docs/docs/api/utils/context.md
249 # changes here should be reflected there as well.
250 original_overrides = thread_local_overrides.get().copy()
251 new_overrides = dotdict({**main_thread_config, **original_overrides, **kwargs})
252 token = thread_local_overrides.set(new_overrides)
253
254 try:
255 yield
256 finally:
257 thread_local_overrides.reset(token)
258
259 def __repr__(self):
260 overrides = thread_local_overrides.get()

Callers 15

track_usageFunction · 0.80
compileMethod · 0.80
forwardMethod · 0.80
compileMethod · 0.80
wrapped_programFunction · 0.80
append_a_ruleFunction · 0.80
patched_forwardFunction · 0.80
propose_new_textsMethod · 0.80
forwardMethod · 0.80
aforwardMethod · 0.80
forwardMethod · 0.80

Calls 4

dotdictClass · 0.90
copyMethod · 0.45
getMethod · 0.45
resetMethod · 0.45

Tested by 15

test_dspy_contextFunction · 0.64
workerFunction · 0.64
forwardMethod · 0.64
aforwardMethod · 0.64
foo3Function · 0.64
test_async_limiterFunction · 0.64
verify_asyncifyFunction · 0.64
run_compileFunction · 0.64