DSPy: The framework for programming—not prompting—language models
Python
Add API reference pages for dspy.configure and dspy.context (#9445)
Maxime Rivest566299051d40
diff --git a/docs/docs/api/utils/configure.md b/docs/docs/api/utils/configure.mdnew file mode 100644index 000000000..73f8e5414--- /dev/null+++ b/docs/docs/api/utils/configure.md@@ -0,0 +1,95 @@+# dspy.configure++Set the default language model, adapter, and other settings for DSPy.++```python+dspy.configure(**kwargs)+```++Call `dspy.configure(...)` once near the top of your script or notebook.+Every DSPy module will use these defaults unless you override them with+[`dspy.context`](context.md). The values persist until you call+`dspy.configure(...)` again.++!!! note+ Pass a [`dspy.LM`](../models/LM.md) object as `lm`, not a bare model+ string.++## Settings++| Setting | Default | Description |+| --- | --- | --- |+| `lm` | `None` | Default language model. Pass a [`dspy.LM`](../models/LM.md) instance. |+| `adapter` | `None` | Formats prompts and parses LM responses. When `None`, modules use [`dspy.ChatAdapter`](../adapters/ChatAdapter.md). |+| `callbacks` | `[]` | Observability and logging hooks. See [Observability](../../tutorials/observability/index.md). |+| `track_usage` | `False` | Record token counts for every LM call. |+| `async_max_workers` | `8` | Maximum concurrent workers for async operations. |+| `num_threads` | `8` | Thread count for [`dspy.Parallel`](../modules/Parallel.md). |+| `max_errors` | `10` | Stop parallel execution after this many errors. |+| `disable_history` | `False` | Stop recording LM call history. |+| `max_history_size` | `10000` | Cap on stored history entries. |+| `allow_tool_async_sync_conversion` | `False` | Let async tools run in synchronous code. See [Async](../../tutorials/async/index.md). |+| `provide_traceback` | `False` | Include Python tracebacks in error logs. |+| `warn_on_type_mismatch` | `True` | Warn when a module input type does not match the signature. |++## Examples++### Set the default LM++```python+import dspy++dspy.configure(lm=dspy.LM("openai/gpt-5-mini"))++qa = dspy.Predict("question -> answer")+result = qa(question="What is the capital of France?")+print(result.answer)+```++### Set the LM and adapter++```python+import dspy++dspy.configure(+ lm=dspy.LM("anthropic/claude-sonnet-4-6"),+ adapter=dspy.JSONAdapter(),+)+```++### Enable usage tracking and tune concurrency++```python+import dspy++dspy.configure(+ lm=dspy.LM("gemini/gemini-3-flash-preview"),+ track_usage=True,+ async_max_workers=4,+)+```++## When to use `dspy.configure`++Use `dspy.configure(...)` when one set of defaults should apply to most of+your program—scripts, notebooks, test setup, or application startup.++If you need different settings for one call or one block, use+[`dspy.context`](context.md) instead.++## Thread safety++Only the thread that first calls `dspy.configure(...)` may call it again.+Other threads that try will get a `RuntimeError`. In async code, only the+task that first called `dspy.configure(...)` may continue to call it.++For temporary overrides inside worker threads, async tasks, or+[`dspy.Parallel`](../modules/Parallel.md) blocks, use+[`dspy.context`](context.md).++## See Also++- [`dspy.context`](context.md) — temporary overrides that last for one block.+- [`dspy.LM`](../models/LM.md) — create the language model you pass as `lm`.+- [Language Models](../../learn/programming/language_models.md) — overview of LM configuration.+- [Adapters](../../learn/programming/adapters.md) — how adapters format prompts and parse responses.diff --git a/docs/docs/api/utils/context.md b/docs/docs/api/utils/context.mdnew file mode 100644index 000000000..2003f7ab6--- /dev/null+++ b/docs/docs/api/utils/context.md@@ -0,0 +1,101 @@+# dspy.context++Override DSPy settings inside one `with` block.++```python+with dspy.context(**kwargs):+ ... # overrides active here+# original settings restored+```++Use `dspy.context(...)` when you need a different LM, adapter, or flag for+one part of your program without changing the process-wide defaults from+[`dspy.configure`](configure.md). The block inherits every current setting,+overrides only the keys you pass, and restores the originals when it exits.++`dspy.context(...)` accepts the same settings as+[`dspy.configure`](configure.md#settings).++## Examples++### Use a different LM for one block++```python+import dspy++dspy.configure(lm=dspy.LM("openai/gpt-5-mini"))+qa = dspy.Predict("question -> answer")++result = qa(question="What is the capital of France?")+print("default:", result.answer)++with dspy.context(lm=dspy.LM("anthropic/claude-sonnet-4-6")):+ result = qa(question="What is the capital of France?")+ print("temporary:", result.answer)++print("restored:", dspy.settings.lm.model) # openai/gpt-5-mini+```++### Use a different adapter for one block++```python+import dspy++dspy.configure(lm=dspy.LM("gemini/gemini-3-flash-preview"))+qa = dspy.Predict("question -> answer")++with dspy.context(adapter=dspy.JSONAdapter()):+ result = qa(question="What is the capital of France?")+ print(result.answer)+```++### Enable async tool conversion temporarily++```python+import asyncio+import dspy++async def async_tool(x: int) -> int:+ await asyncio.sleep(0.1)+ return x * 2++tool = dspy.Tool(async_tool)++with dspy.context(allow_tool_async_sync_conversion=True):+ print(tool(x=5))+```++### Nested blocks++Inner blocks override outer ones. Each restores cleanly on exit:++```python+import dspy++dspy.configure(lm=dspy.LM("openai/gpt-5-mini"))++with dspy.context(lm=dspy.LM("anthropic/claude-sonnet-4-6")):+ print(dspy.settings.lm.model) # anthropic/claude-sonnet-4-6+ with dspy.context(track_usage=True):+ print(dspy.settings.lm.model) # anthropic/claude-sonnet-4-6 (inherited)+ print(dspy.settings.track_usage) # True+ print(dspy.settings.track_usage) # False (restored)+print(dspy.settings.lm.model) # openai/gpt-5-mini (restored)+```++## Thread safety++Unlike [`dspy.configure`](configure.md), you can call `dspy.context(...)` from+**any** thread or async task. This makes it the right tool for overrides inside+[`dspy.Parallel`](../modules/Parallel.md), `asyncio.gather`, or any concurrent+code.++Settings inside a `dspy.context(...)` block do not leak to other threads or+tasks.++## See Also++- [`dspy.configure`](configure.md) — set process-wide defaults.+- [`dspy.LM`](../models/LM.md) — create the language model you pass as `lm`.+- [Language Models](../../learn/programming/language_models.md) — overview of LM configuration.+- [Adapters](../../learn/programming/adapters.md) — how adapters format prompts and parse responses.diff --git a/docs/mkdocs.yml b/docs/mkdocs.ymlindex 74bc64c4d..791bd4623 100644--- a/docs/mkdocs.yml+++ b/docs/mkdocs.yml@@ -155,6 +155,8 @@ nav:- Embeddings: api/tools/Embeddings.md- PythonInterpreter: api/tools/PythonInterpreter.md- Utils:+ - configure: api/utils/configure.md+ - context: api/utils/context.md- StatusMessage: api/utils/StatusMessage.md- StatusMessageProvider: api/utils/StatusMessageProvider.md- StreamListener: api/utils/StreamListener.mddiff --git a/dspy/dsp/utils/settings.py b/dspy/dsp/utils/settings.pyindex b5f0c731b..47bceba4d 100644--- a/dspy/dsp/utils/settings.py+++ b/dspy/dsp/utils/settings.py@@ -163,6 +163,48 @@ class Settings:)def configure(self, **kwargs):+ """Set the default language model, adapter, and other settings for DSPy.++ Call `dspy.configure(...)` once near the top of your script. Every+ DSPy module will use these defaults unless you override them with+ `dspy.context(...)`. The values persist until you call+ `dspy.configure(...)` again.++ Only the thread that first calls `dspy.configure(...)` may call it+ again. Use `dspy.context(...)` for temporary overrides in other+ threads or async tasks.++ Args:+ **kwargs: Settings to update. Common keys include `lm` (a+ `dspy.LM`), `adapter` (e.g. `dspy.JSONAdapter()`),+ `callbacks`, `track_usage`, `async_max_workers`, and+ `num_threads`.++ Examples:+ Set a default LM:+ ```python+ import dspy++ dspy.configure(lm=dspy.LM("openai/gpt-5-mini"))+ ```++ Set multiple defaults at once:+ ```python+ import dspy++ dspy.configure(+ lm=dspy.LM("anthropic/claude-sonnet-4-6"),+ adapter=dspy.JSONAdapter(),+ track_usage=True,+ )+ ```++ See Also:+ [`dspy.LM`][dspy.LM]: create the language model you pass as `lm`.+ `dspy.context`: temporary overrides inside one block.+ """+ # `dspy.configure` is documented manually in docs/docs/api/utils/context.md+ # changes here should be reflected there as well.# If no exception is raised, the `configure` call is allowed.self._ensure_configure_allowed()@@ -172,12 +214,39 @@ class Settings:@contextmanagerdef context(self, **kwargs):- """- Context manager for temporary configuration changes at the thread level.- Does not affect global configuration. Changes only apply to the current thread.- If threads are spawned inside this block using ParallelExecutor, they will inherit these overrides.- """+ """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 keys you pass, and restores the originals on exit.++ Unlike `dspy.configure(...)`, you can call `dspy.context(...)` from+ any thread or async task.++ Args:+ **kwargs: Settings to override, such as `lm`, `adapter`,+ `track_usage`, or `allow_tool_async_sync_conversion`.++ Examples:+ Use a different LM for one call:+ ```python+ import dspy++ dspy.configure(lm=dspy.LM("openai/gpt-5-mini"))+ qa = dspy.Predict("question -> answer")++ with dspy.context(lm=dspy.LM("anthropic/claude-sonnet-4-6")):+ result = qa(question="What is the capital of France?")+ # uses claude-sonnet-4-6 inside this block+ # back to gpt-5-mini here+ ```++ See Also:+ `dspy.configure`: set process-wide defaults.+ """+ # `dspy.context` is documented manually in docs/docs/api/utils/context.md+ # changes here should be reflected there as well.original_overrides = thread_local_overrides.get().copy()new_overrides = dotdict({**main_thread_config, **original_overrides, **kwargs})token = thread_local_overrides.set(new_overrides)