Skip to content

armgit / dspy

Public Imported from GitHub
0

DSPy: The framework for programming—not prompting—language models

Python

Clean up ChainOfThoughtWithHint in DSPy 3.0 (#8395)

Hangzhi18c106726a88
diff --git a/docs/docs/api/modules/ChainOfThoughtWithHint.md b/docs/docs/api/modules/ChainOfThoughtWithHint.md
deleted file mode 100644
index 8ced3770d..000000000
--- a/docs/docs/api/modules/ChainOfThoughtWithHint.md
+++ /dev/null
@@ -1,35 +0,0 @@
-# dspy.ChainOfThoughtWithHint
-
-<!-- START_API_REF -->
-::: dspy.ChainOfThoughtWithHint
- handler: python
- options:
- members:
- - __call__
- - acall
- - batch
- - deepcopy
- - dump_state
- - forward
- - get_lm
- - inspect_history
- - load
- - load_state
- - map_named_predictors
- - named_parameters
- - named_predictors
- - named_sub_modules
- - parameters
- - predictors
- - reset_copy
- - save
- - set_lm
- show_source: true
- show_root_heading: true
- heading_level: 2
- docstring_style: google
- show_root_full_path: true
- show_object_full_path: false
- separate_signature: false
- inherited_members: true
-<!-- END_API_REF -->
diff --git a/docs/docs/cheatsheet.md b/docs/docs/cheatsheet.md
index 995911738..1ea4b9695 100644
--- a/docs/docs/cheatsheet.md
+++ b/docs/docs/cheatsheet.md
@@ -145,17 +145,6 @@ question='What is the color of the sky?'
pred = generate_answer(question=question)
```
-### dspy.ChainOfThoughtwithHint
-
-```python
-generate_answer = dspy.ChainOfThoughtWithHint(BasicQA)
-
-# Call the predictor on a particular input alongside a hint.
-question='What is the color of the sky?'
-hint = "It's what you often see during a sunny day."
-pred = generate_answer(question=question, hint=hint)
-```
-
### dspy.ProgramOfThought
```python
diff --git a/docs/docs/index.md b/docs/docs/index.md
index e4f7de598..e157bd568 100644
--- a/docs/docs/index.md
+++ b/docs/docs/index.md
@@ -358,23 +358,20 @@ Given a few tens or hundreds of representative _inputs_ of your task and a _metr
For a complete RAG example that you can run, start this [tutorial](/tutorials/rag/). It improves the quality of a RAG system over a subset of StackExchange communities by 10% relative gain.
=== "Optimizing weights for Classification"
- This is a minimal but fully runnable example of setting up a `dspy.ChainOfThought` module that classifies
- short texts into one of 77 banking labels and then using `dspy.BootstrapFinetune` with 2000 text-label pairs
- from the `Banking77` to finetune the weights of GPT-4o-mini for this task. We use the variant
- `dspy.ChainOfThoughtWithHint`, which takes an optional `hint` at bootstrapping time, to maximize the utility of
- the training data. Naturally, hints are not available at test time.
-
<details><summary>Click to show dataset setup code.</summary>
```python linenums="1"
import random
from typing import Literal
- from dspy.datasets import DataLoader
+
from datasets import load_dataset
+ import dspy
+ from dspy.datasets import DataLoader
+
# Load the Banking77 dataset.
- CLASSES = load_dataset("PolyAI/banking77", split="train", trust_remote_code=True).features['label'].names
- kwargs = dict(fields=("text", "label"), input_keys=("text",), split="train", trust_remote_code=True)
+ CLASSES = load_dataset("PolyAI/banking77", split="train", trust_remote_code=True).features["label"].names
+ kwargs = {"fields": ("text", "label"), "input_keys": ("text",), "split": "train", "trust_remote_code": True}
# Load the first 2000 examples from the dataset, and assign a hint to each *training* example.
trainset = [
@@ -388,10 +385,10 @@ Given a few tens or hundreds of representative _inputs_ of your task and a _metr
```python linenums="1"
import dspy
dspy.configure(lm=dspy.LM('openai/gpt-4o-mini-2024-07-18'))
-
+
# Define the DSPy module for classification. It will use the hint at training time, if available.
- signature = dspy.Signature("text -> label").with_updated_fields('label', type_=Literal[tuple(CLASSES)])
- classify = dspy.ChainOfThoughtWithHint(signature)
+ signature = dspy.Signature("text, hint -> label").with_updated_fields('label', type_=Literal[tuple(CLASSES)])
+ classify = dspy.ChainOfThought(signature)
# Optimize via BootstrapFinetune.
optimizer = dspy.BootstrapFinetune(metric=(lambda x, y, trace=None: x.label == y.label), num_threads=24)
diff --git a/docs/docs/learn/optimization/optimizers.md b/docs/docs/learn/optimization/optimizers.md
index d56b6174a..cb428c815 100644
--- a/docs/docs/learn/optimization/optimizers.md
+++ b/docs/docs/learn/optimization/optimizers.md
@@ -150,23 +150,20 @@ optimized_program = teleprompter.compile(YOUR_PROGRAM_HERE, trainset=YOUR_TRAINS
For a complete RAG example that you can run, start this [tutorial](/tutorials/rag/). It improves the quality of a RAG system over a subset of StackExchange communities from 53% to 61%.
=== "Optimizing weights for Classification"
- This is a minimal but fully runnable example of setting up a `dspy.ChainOfThought` module that classifies
- short texts into one of 77 banking labels and then using `dspy.BootstrapFinetune` with 2000 text-label pairs
- from the `Banking77` to finetune the weights of GPT-4o-mini for this task. We use the variant
- `dspy.ChainOfThoughtWithHint`, which takes an optional `hint` at bootstrapping time, to maximize the utility of
- the training data. Naturally, hints are not available at test time. More can be found in this [tutorial](/tutorials/classification_finetuning/).
-
<details><summary>Click to show dataset setup code.</summary>
```python linenums="1"
import random
from typing import Literal
- from dspy.datasets import DataLoader
+
from datasets import load_dataset
+ import dspy
+ from dspy.datasets import DataLoader
+
# Load the Banking77 dataset.
- CLASSES = load_dataset("PolyAI/banking77", split="train", trust_remote_code=True).features['label'].names
- kwargs = dict(fields=("text", "label"), input_keys=("text",), split="train", trust_remote_code=True)
+ CLASSES = load_dataset("PolyAI/banking77", split="train", trust_remote_code=True).features["label"].names
+ kwargs = {"fields": ("text", "label"), "input_keys": ("text",), "split": "train", "trust_remote_code": True}
# Load the first 2000 examples from the dataset, and assign a hint to each *training* example.
trainset = [
@@ -179,11 +176,11 @@ optimized_program = teleprompter.compile(YOUR_PROGRAM_HERE, trainset=YOUR_TRAINS
```python linenums="1"
import dspy
- dspy.configure(lm=dspy.LM('gpt-4o-mini-2024-07-18'))
-
+ dspy.configure(lm=dspy.LM('openai/gpt-4o-mini-2024-07-18'))
+
# Define the DSPy module for classification. It will use the hint at training time, if available.
- signature = dspy.Signature("text -> label").with_updated_fields('label', type_=Literal[tuple(CLASSES)])
- classify = dspy.ChainOfThoughtWithHint(signature)
+ signature = dspy.Signature("text, hint -> label").with_updated_fields('label', type_=Literal[tuple(CLASSES)])
+ classify = dspy.ChainOfThought(signature)
# Optimize via BootstrapFinetune.
optimizer = dspy.BootstrapFinetune(metric=(lambda x, y, trace=None: x.label == y.label), num_threads=24)
diff --git a/docs/mkdocs.yml b/docs/mkdocs.yml
index 602a123c1..8ab5dfae9 100644
--- a/docs/mkdocs.yml
+++ b/docs/mkdocs.yml
@@ -88,7 +88,6 @@ nav:
- Modules:
- BestOfN: api/modules/BestOfN.md
- ChainOfThought: api/modules/ChainOfThought.md
- - ChainOfThoughtWithHint: api/modules/ChainOfThoughtWithHint.md
- CodeAct: api/modules/CodeAct.md
- Module: api/modules/Module.md
- MultiChainComparison: api/modules/MultiChainComparison.md
diff --git a/docs/scripts/generate_api_docs.py b/docs/scripts/generate_api_docs.py
index 62317fa85..10c33fe51 100644
--- a/docs/scripts/generate_api_docs.py
+++ b/docs/scripts/generate_api_docs.py
@@ -36,7 +36,6 @@ API_MAPPING = {
dspy.ReAct,
dspy.ProgramOfThought,
dspy.MultiChainComparison,
- dspy.ChainOfThoughtWithHint,
dspy.Parallel,
dspy.BestOfN,
dspy.Refine,
diff --git a/dspy/predict/__init__.py b/dspy/predict/__init__.py
index 24926ef1b..1d4ddffce 100644
--- a/dspy/predict/__init__.py
+++ b/dspy/predict/__init__.py
@@ -1,7 +1,6 @@
from dspy.predict.aggregation import majority
from dspy.predict.best_of_n import BestOfN
from dspy.predict.chain_of_thought import ChainOfThought
-from dspy.predict.chain_of_thought_with_hint import ChainOfThoughtWithHint
from dspy.predict.code_act import CodeAct
from dspy.predict.knn import KNN
from dspy.predict.multi_chain_comparison import MultiChainComparison
@@ -15,7 +14,6 @@ __all__ = [
"majority",
"BestOfN",
"ChainOfThought",
- "ChainOfThoughtWithHint",
"CodeAct",
"KNN",
"MultiChainComparison",
diff --git a/dspy/predict/chain_of_thought_with_hint.py b/dspy/predict/chain_of_thought_with_hint.py
deleted file mode 100644
index dd6ca3604..000000000
--- a/dspy/predict/chain_of_thought_with_hint.py
+++ /dev/null
@@ -1,28 +0,0 @@
-import dspy
-
-from .predict import Module
-
-
-class ChainOfThoughtWithHint(Module):
- def __init__(self, signature, rationale_type=None, **config):
- self.signature = dspy.ensure_signature(signature)
- self.module = dspy.ChainOfThought(signature, rationale_type=rationale_type, **config)
-
- def forward(self, **kwargs):
- if kwargs.get("hint"):
- hint = f"\n\t\t(secret hint: {kwargs.pop('hint')})"
- original_kwargs = kwargs.copy()
-
- # Convert the first field's value to string and append the hint
- last_key = list(self.signature.input_fields.keys())[-1]
- kwargs[last_key] = str(kwargs[last_key]) + hint
-
- # Run CoT then update the trace with original kwargs, i.e. without the hint.
- with dspy.context(trace=[]):
- pred = self.module(**kwargs)
- this_trace = dspy.settings.trace[-1]
-
- dspy.settings.trace.append((this_trace[0], original_kwargs, this_trace[2]))
- return pred
-
- return self.module(**kwargs)
diff --git a/tests/predict/test_chain_of_thought_with_hint.py b/tests/predict/test_chain_of_thought_with_hint.py
deleted file mode 100644
index 68ede17dc..000000000
--- a/tests/predict/test_chain_of_thought_with_hint.py
+++ /dev/null
@@ -1,30 +0,0 @@
-# import textwrap
-
-# import dspy
-# from dspy import ChainOfThoughtWithHint
-# from dspy.utils import DummyLM
-
-
-# def test_cot_with_no_hint():
-# lm = DummyLM([{"rationale": "find the number after 1", "answer": "2"}])
-# dspy.settings.configure(lm=lm)
-# predict = ChainOfThoughtWithHint("question -> answer")
-# # Check output fields have the right order
-# assert list(predict.extended_signature2.output_fields.keys()) == [
-# "rationale",
-# "hint",
-# "answer",
-# ]
-# assert predict(question="What is 1+1?").answer == "2"
-
-
-# def test_cot_with_hint():
-# lm = DummyLM([{"rationale": "find the number after 1", "hint": "Is it helicopter?", "answer": "2"}])
-# dspy.settings.configure(lm=lm)
-# predict = ChainOfThoughtWithHint("question -> answer")
-# assert list(predict.extended_signature2.output_fields.keys()) == [
-# "rationale",
-# "hint",
-# "answer",
-# ]
-# assert predict(question="What is 1+1?", hint="think small").answer == "2"