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)
| 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() |