DSPy: The framework for programming—not prompting—language models
Python
Fix example rendering (#7990)
Chen Qian215959799a15
diff --git a/dspy/adapters/types/history.py b/dspy/adapters/types/history.pyindex bfae0df9e..f91925aef 100644--- a/dspy/adapters/types/history.py+++ b/dspy/adapters/types/history.py@@ -19,45 +19,43 @@ class History(pydantic.BaseModel):Then the history should be a list of dictionaries with keys "question" and "answer".Example:+ ```+ import dspy- ```- import dspy+ dspy.settings.configure(lm=dspy.LM("openai/gpt-4o-mini"))- dspy.settings.configure(lm=dspy.LM("openai/gpt-4o-mini"))+ class MySignature(dspy.Signature):+ question: str = dspy.InputField()+ history: dspy.History = dspy.InputField()+ answer: str = dspy.OutputField()- class MySignature(dspy.Signature):- question: str = dspy.InputField()- history: dspy.History = dspy.InputField()- answer: str = dspy.OutputField()-- history = dspy.History(- messages=[- {"question": "What is the capital of France?", "answer": "Paris"},- {"question": "What is the capital of Germany?", "answer": "Berlin"},- ]- )+ history = dspy.History(+ messages=[+ {"question": "What is the capital of France?", "answer": "Paris"},+ {"question": "What is the capital of Germany?", "answer": "Berlin"},+ ]+ )- predict = dspy.Predict(MySignature)- outputs = predict(question="What is the capital of France?", history=history)- ```+ predict = dspy.Predict(MySignature)+ outputs = predict(question="What is the capital of France?", history=history)+ ```Example of capturing the conversation history:+ ```+ import dspy- ```- import dspy+ dspy.settings.configure(lm=dspy.LM("openai/gpt-4o-mini"))- dspy.settings.configure(lm=dspy.LM("openai/gpt-4o-mini"))+ class MySignature(dspy.Signature):+ question: str = dspy.InputField()+ history: dspy.History = dspy.InputField()+ answer: str = dspy.OutputField()- class MySignature(dspy.Signature):- question: str = dspy.InputField()- history: dspy.History = dspy.InputField()- answer: str = dspy.OutputField()-- predict = dspy.Predict(MySignature)- outputs = predict(question="What is the capital of France?")- history = dspy.History(messages=[{"question": "What is the capital of France?", **outputs}])- outputs_with_history = predict(question="Are you sure?", history=history)- ```+ predict = dspy.Predict(MySignature)+ outputs = predict(question="What is the capital of France?")+ history = dspy.History(messages=[{"question": "What is the capital of France?", **outputs}])+ outputs_with_history = predict(question="Are you sure?", history=history)+ ```"""messages: list[dict[str, Any]]diff --git a/dspy/predict/best_of_n.py b/dspy/predict/best_of_n.pyindex 932842363..3b478c04a 100644--- a/dspy/predict/best_of_n.py+++ b/dspy/predict/best_of_n.py@@ -3,17 +3,18 @@ from typing import Callable, Optionalimport dspyfrom dspy.predict.predict import Prediction-from .predict import Module+from dspy.predict.predict import Moduleclass BestOfN(Module):-- def __init__(self,- module: Module,- N: int,- reward_fn: Callable[[dict, Prediction], float],- threshold: float,- fail_count: Optional[int] = None):+ def __init__(+ self,+ module: Module,+ N: int,+ reward_fn: Callable[[dict, Prediction], float],+ threshold: float,+ fail_count: Optional[int] = None,+ ):"""Runs a module up to `N` times with different temperatures and returns the best predictionout of `N` attempts or the first prediction that passes the `threshold`.@@ -26,26 +27,36 @@ class BestOfN(Module):fail_count (Optional[int], optional): The number of times the module can fail before raising an error. Defaults to N if not provided.Example:- >>> import dspy- >>> qa = dspy.ChainOfThought("question -> answer")- >>> def one_word_answer(args, pred):- >>> return 1.0 if len(pred.answer) == 1 else 0.0- >>> best_of_3 = dspy.BestOfN(module=qa, N=3, reward_fn=one_word_answer, threshold=1.0)- >>> best_of_3(question="What is the capital of Belgium?").answer- >>> # Brussels+ ```python+ import dspy++ dspy.settings.configure(lm=dspy.LM("openai/gpt-4o-mini"))++ # Define a QA module with chain of thought+ qa = dspy.ChainOfThought("question -> answer")++ # Define a reward function that checks for one-word answers+ def one_word_answer(args, pred):+ return 1.0 if len(pred.answer.split()) == 1 else 0.0++ # Create a refined module that tries up to 3 times+ best_of_3 = dspy.BestOfN(module=qa, N=3, reward_fn=one_word_answer, threshold=1.0)++ # Use the refined module+ result = best_of_3(question="What is the capital of Belgium?").answer+ # Returns: Brussels+ ```"""self.module = module- self.reward_fn = lambda *args: reward_fn(- *args) # to prevent this from becoming a parameter+ self.reward_fn = lambda *args: reward_fn(*args) # to prevent this from becoming a parameterself.threshold = thresholdself.N = Nself.fail_count = fail_count or N # default to N if fail_count is not provideddef forward(self, **kwargs):lm = self.module.get_lm() or dspy.settings.lm- temps = [lm.kwargs['temperature']- ] + [0.5 + i * (0.5 / self.N) for i in range(self.N)]- temps = list(dict.fromkeys(temps))[:self.N]+ temps = [lm.kwargs["temperature"]] + [0.5 + i * (0.5 / self.N) for i in range(self.N)]+ temps = list(dict.fromkeys(temps))[: self.N]best_pred, best_trace, best_reward = None, None, -float("inf")for idx, t in enumerate(temps):@@ -68,9 +79,7 @@ class BestOfN(Module):breakexcept Exception as e:- print(- f"BestOfN: Attempt {idx + 1} failed with temperature {t}: {e}"- )+ print(f"BestOfN: Attempt {idx + 1} failed with temperature {t}: {e}")if idx > self.fail_count:raise eself.fail_count -= 1diff --git a/dspy/predict/knn.py b/dspy/predict/knn.pyindex 85b80bca4..142c53468 100644--- a/dspy/predict/knn.py+++ b/dspy/predict/knn.py@@ -15,12 +15,26 @@ class KNN:vectorizer: The `Embedder` to use for vectorizationExample:- >>> import dspy- >>> from sentence_transformers import SentenceTransformer- >>>- >>> trainset = [dspy.Example(input="hello", output="world"), ...]- >>> knn = KNN(k=3, trainset=trainset, vectorizer=dspy.Embedder(SentenceTransformer("all-MiniLM-L6-v2").encode))- >>> similar_examples = knn(input="hello")+ ```python+ import dspy+ from sentence_transformers import SentenceTransformer++ # Create a training dataset with examples+ trainset = [+ dspy.Example(input="hello", output="world"),+ # ... more examples ...+ ]++ # Initialize KNN with a sentence transformer model+ knn = KNN(+ k=3,+ trainset=trainset,+ vectorizer=dspy.Embedder(SentenceTransformer("all-MiniLM-L6-v2").encode)+ )++ # Find similar examples+ similar_examples = knn(input="hello")+ ```"""self.k = kself.trainset = trainsetdiff --git a/dspy/teleprompt/knn_fewshot.py b/dspy/teleprompt/knn_fewshot.pyindex 56e70440a..ab08fd2fc 100644--- a/dspy/teleprompt/knn_fewshot.py+++ b/dspy/teleprompt/knn_fewshot.py@@ -22,14 +22,32 @@ class KNNFewShot(Teleprompter):**few_shot_bootstrap_args: Additional arguments for the `BootstrapFewShot` optimizer.Example:- >>> import dspy- >>> from sentence_transformers import SentenceTransformer- >>>- >>> qa = dspy.ChainOfThought("question -> answer")- >>> trainset = [dspy.Example(question="What is the capital of France?", answer="Paris").with_inputs("question"), ...]- >>> knn_few_shot = KNNFewShot(k=3, trainset=trainset, vectorizer=dspy.Embedder(SentenceTransformer("all-MiniLM-L6-v2").encode))- >>> compiled_qa = knn_few_shot.compile(qa)- >>> compiled_qa("What is the capital of Belgium?")+ ```python+ import dspy+ from sentence_transformers import SentenceTransformer++ # Define a QA module with chain of thought+ qa = dspy.ChainOfThought("question -> answer")++ # Create a training dataset with examples+ trainset = [+ dspy.Example(question="What is the capital of France?", answer="Paris").with_inputs("question"),+ # ... more examples ...+ ]++ # Initialize KNNFewShot with a sentence transformer model+ knn_few_shot = KNNFewShot(+ k=3,+ trainset=trainset,+ vectorizer=dspy.Embedder(SentenceTransformer("all-MiniLM-L6-v2").encode)+ )++ # Compile the QA module with few-shot learning+ compiled_qa = knn_few_shot.compile(qa)++ # Use the compiled module+ result = compiled_qa("What is the capital of Belgium?")+ ```"""self.KNN = KNN(k, trainset, vectorizer=vectorizer)self.few_shot_bootstrap_args = few_shot_bootstrap_args