DSPy: The framework for programming—not prompting—language models
Python
Fix mkdoc warnings (#8410)
TomuHirataea60c75bd221
diff --git a/docs/docs/cheatsheet.md b/docs/docs/cheatsheet.mdindex e4c574a36..995911738 100644--- a/docs/docs/cheatsheet.md+++ b/docs/docs/cheatsheet.md@@ -310,7 +310,7 @@ loaded_program.load(path=save_path)### BootstrapFewShotWithRandomSearch-Detailed documentation on BootstrapFewShotWithRandomSearch can be found [here](deep-dive/optimizers/bootstrap-fewshot.md).+Detailed documentation on BootstrapFewShotWithRandomSearch can be found [here](api/optimizers/BootstrapFewShot.md).```pythonfrom dspy.teleprompt import BootstrapFewShotWithRandomSearch@@ -366,7 +366,7 @@ for p in finetune_program.predictors():### COPRO-Detailed documentation on COPRO can be found [here](deep-dive/optimizers/copro.md).+Detailed documentation on COPRO can be found [here](api/optimizers/COPRO.md).```pythonfrom dspy.teleprompt import COPRO@@ -392,11 +392,11 @@ compiled_program_optimized_bayesian_signature = teleprompter.compile(your_dspy_p### MIPROv2-Note: detailed documentation can be found [here](deep-dive/optimizers/miprov2.md). `MIPROv2` is the latest extension of `MIPRO` which includes updates such as (1) improvements to instruction proposal and (2) more efficient search with minibatching.+Note: detailed documentation can be found [here](api/optimizers/MIPROv2.md). `MIPROv2` is the latest extension of `MIPRO` which includes updates such as (1) improvements to instruction proposal and (2) more efficient search with minibatching.#### Optimizing with MIPROv2-This shows how to perform an easy out-of-the box run with `auto=light`, which configures many hyperparameters for you and performs a light optimization run. You can alternatively set `auto=medium` or `auto=heavy` to perform longer optimization runs. The more detailed `MIPROv2` documentation [here](deep-dive/optimizers/miprov2.md) also provides more information about how to set hyperparameters by hand.+This shows how to perform an easy out-of-the box run with `auto=light`, which configures many hyperparameters for you and performs a light optimization run. You can alternatively set `auto=medium` or `auto=heavy` to perform longer optimization runs. The more detailed `MIPROv2` documentation [here](api/optimizers/MIPROv2.md) also provides more information about how to set hyperparameters by hand.```python# Import the optimizerdiff --git a/docs/docs/learn/optimization/optimizers.md b/docs/docs/learn/optimization/optimizers.mdindex fb6f575ec..d56b6174a 100644--- a/docs/docs/learn/optimization/optimizers.md+++ b/docs/docs/learn/optimization/optimizers.md@@ -79,13 +79,13 @@ That being said, here's the general guidance on getting started:- If you have **very few examples** (around 10), start with `BootstrapFewShot`.- If you have **more data** (50 examples or more), try `BootstrapFewShotWithRandomSearch`.-- If you prefer to do **instruction optimization only** (i.e. you want to keep your prompt 0-shot), use `MIPROv2` [configured for 0-shot optimization to optimize](/deep-dive/optimizers/miprov2#optimizing-instructions-only-with-miprov2-0-shot).+- If you prefer to do **instruction optimization only** (i.e. you want to keep your prompt 0-shot), use `MIPROv2` [configured for 0-shot optimization to optimize](/api/optimizers/MIPROv2#optimizing-instructions-only-with-miprov2-0-shot).- If you’re willing to use more inference calls to perform **longer optimization runs** (e.g. 40 trials or more), and have enough data (e.g. 200 examples or more to prevent overfitting) then try `MIPROv2`.- If you have been able to use one of these with a large LM (e.g., 7B parameters or above) and need a very **efficient program**, finetune a small LM for your task with `BootstrapFinetune`.## How do I use an optimizer?-They all share this general interface, with some differences in the keyword arguments (hyperparameters). Detailed documentation for key optimizers can be found [here](/deep-dive/optimizers/vfrs), and a full list can be found [here](https://dspy.ai/api/optimizers/BetterTogether/).+They all share this general interface, with some differences in the keyword arguments (hyperparameters). Detailed documentation for key optimizers can be found [here](/api/optimizers/vfrs), and a full list can be found [here](https://dspy.ai/api/optimizers/BetterTogether/).Let's see this with the most common one, `BootstrapFewShotWithRandomSearch`.diff --git a/dspy/clients/embedding.py b/dspy/clients/embedding.pyindex 70af16d15..b7701997a 100644--- a/dspy/clients/embedding.py+++ b/dspy/clients/embedding.py@@ -1,3 +1,5 @@+from typing import Any, Callable, Optional, Union+import litellmimport numpy as np@@ -74,7 +76,7 @@ class Embedder:```"""- def __init__(self, model, batch_size=200, caching=True, **kwargs):+ def __init__(self, model: Union[str, Callable], batch_size: int = 200, caching: bool = True, **kwargs: dict[str, Any]):self.model = modelself.batch_size = batch_sizeself.caching = caching@@ -108,7 +110,7 @@ class Embedder:else:return np.array(embeddings, dtype=np.float32)- def __call__(self, inputs, batch_size=None, caching=None, **kwargs):+ def __call__(self, inputs: Union[str, list[str]], batch_size: Optional[int] = None, caching: Optional[bool] = None, **kwargs: dict[str, Any]) -> np.ndarray:"""Compute embeddings for the given inputs.Args:@@ -117,7 +119,7 @@ class Embedder:during initialization.caching (bool, optional): Whether to cache the embedding response when using a hosted model. If None,defaults to the caching setting from initialization.- **kwargs: Additional keyword arguments to pass to the embedding model. These will override the default+ kwargs: Additional keyword arguments to pass to the embedding model. These will override the defaultkwargs provided during initialization.Returns:diff --git a/dspy/clients/lm.py b/dspy/clients/lm.pyindex 384960a11..e9dfc901a 100644--- a/dspy/clients/lm.py+++ b/dspy/clients/lm.py@@ -36,7 +36,7 @@ class LM(BaseLM):cache_in_memory: bool = True,callbacks: Optional[List[BaseCallback]] = None,num_retries: int = 3,- provider=None,+ provider: Optional[Provider] = None,finetuning_model: Optional[str] = None,launch_kwargs: Optional[dict[str, Any]] = None,train_kwargs: Optional[dict[str, Any]] = None,diff --git a/dspy/predict/chain_of_thought.py b/dspy/predict/chain_of_thought.pyindex ab2a196db..a8bff5049 100644--- a/dspy/predict/chain_of_thought.py+++ b/dspy/predict/chain_of_thought.py@@ -1,4 +1,4 @@-from typing import Optional, Type, Union+from typing import Any, Optional, Type, Unionfrom pydantic.fields import FieldInfo@@ -14,7 +14,7 @@ class ChainOfThought(Module):signature: Type[Signature],rationale_field: Optional[Union[OutputField, FieldInfo]] = None,rationale_field_type: Type = str,- **config,+ **config: dict[str, Any],):"""A module that reasons step by step in order to predict the output of a task.diff --git a/dspy/predict/predict.py b/dspy/predict/predict.pyindex 0afb067d9..3c00df06e 100644--- a/dspy/predict/predict.py+++ b/dspy/predict/predict.py@@ -47,14 +47,14 @@ class Predict(Module, Parameter):state["lm"] = self.lm.dump_state() if self.lm else Nonereturn state- def load_state(self, state):+ def load_state(self, state: dict) -> "Predict":"""Load the saved state of a `Predict` object.Args:- state (dict): The saved state of a `Predict` object.+ state: The saved state of a `Predict` object.Returns:- self: Returns self to allow method chaining+ Self to allow method chaining."""excluded_keys = ["signature", "extended_signature", "lm"]for name, value in state.items():diff --git a/dspy/predict/program_of_thought.py b/dspy/predict/program_of_thought.pyindex 4b95c5060..66de91323 100644--- a/dspy/predict/program_of_thought.py+++ b/dspy/predict/program_of_thought.py@@ -27,7 +27,7 @@ class ProgramOfThought(Module):```"""- def __init__(self, signature: Union[str, Type[Signature]], max_iters=3, interpreter: Optional[PythonInterpreter] = None):+ def __init__(self, signature: Union[str, Type[Signature]], max_iters: int = 3, interpreter: Optional[PythonInterpreter] = None):"""Args:signature: The signature of the module.diff --git a/dspy/primitives/module.py b/dspy/primitives/module.pyindex 450816706..bc3c70f66 100644--- a/dspy/primitives/module.py+++ b/dspy/primitives/module.py@@ -7,6 +7,7 @@ import magicattrfrom dspy.dsp.utils.settings import settings, thread_local_overridesfrom dspy.predict.parallel import Parallelfrom dspy.primitives.base_module import BaseModule+from dspy.primitives.example import Examplefrom dspy.utils.callback import with_callbacksfrom dspy.utils.inspect_history import pretty_print_historyfrom dspy.utils.usage_tracker import track_usage@@ -117,7 +118,7 @@ class Module(BaseModule, metaclass=ProgramMeta):def batch(self,- examples,+ examples: list[Example],num_threads: Optional[int] = None,max_errors: Optional[int] = None,return_failed_examples: bool = False,diff --git a/dspy/signatures/signature.py b/dspy/signatures/signature.pyindex b47d63f7b..061f369cd 100644--- a/dspy/signatures/signature.py+++ b/dspy/signatures/signature.py@@ -248,7 +248,7 @@ class Signature(BaseModel, metaclass=SignatureMeta):return Signature(cls.fields, instructions)@classmethod- def with_updated_fields(cls, name, type_=None, **kwargs) -> Type["Signature"]:+ def with_updated_fields(cls, name: str, type_: Optional[Type] = None, **kwargs: dict[str, Any]) -> Type["Signature"]:"""Create a new Signature class with the updated field information.Returns a new Signature class with the field, name, updated@@ -257,7 +257,7 @@ class Signature(BaseModel, metaclass=SignatureMeta):Args:name: The name of the field to update.type_: The new type of the field.- **kwargs: The new values for the field.+ kwargs: The new values for the field.Returns:A new Signature class (not an instance) with the updated field information.diff --git a/dspy/teleprompt/knn_fewshot.py b/dspy/teleprompt/knn_fewshot.pyindex 65ff27ccb..0c8557ca6 100644--- a/dspy/teleprompt/knn_fewshot.py+++ b/dspy/teleprompt/knn_fewshot.py@@ -1,4 +1,5 @@import types+from typing import Anyfrom dspy.clients import Embedderfrom dspy.predict.knn import KNN@@ -8,7 +9,7 @@ from dspy.teleprompt.teleprompt import Teleprompterclass KNNFewShot(Teleprompter):- def __init__(self, k: int, trainset: list[Example], vectorizer: Embedder, **few_shot_bootstrap_args):+ def __init__(self, k: int, trainset: list[Example], vectorizer: Embedder, **few_shot_bootstrap_args: dict[str, Any]):"""KNNFewShot is an optimizer that uses an in-memory KNN retriever to find the k nearest neighborsin a trainset at test time. For each input example in a forward call, it identifies the k mostdiff --git a/dspy/utils/saving.py b/dspy/utils/saving.pyindex 801f8f70b..c9e8ab502 100644--- a/dspy/utils/saving.py+++ b/dspy/utils/saving.py@@ -1,10 +1,14 @@import loggingimport sysfrom pathlib import Path+from typing import TYPE_CHECKINGimport cloudpickleimport ujson+if TYPE_CHECKING:+ from dspy.primitives.module import Module+logger = logging.getLogger(__name__)@@ -20,7 +24,7 @@ def get_dependency_versions():}-def load(path):+def load(path: str) -> "Module":"""Load saved DSPy model.This method is used to load a saved DSPy model with `save_program=True`, i.e., the model is saved with cloudpickle.