Skip to content

armgit / dspy

Public Imported from GitHub
0

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

Python

Created typed signature optimizer

Thomas D Ahle72838473f812
diff --git a/dspy/__init__.py b/dspy/__init__.py
index 98fe6fba8..43317f3d1 100644
--- a/dspy/__init__.py
+++ b/dspy/__init__.py
@@ -5,6 +5,7 @@ from .signatures import *
from .retrieve import *
from .predict import *
from .primitives import *
+from .functional import *
# from .evaluation import *
diff --git a/dspy/functional/functional.py b/dspy/functional/functional.py
index 3d6c47141..ed14c66ca 100644
--- a/dspy/functional/functional.py
+++ b/dspy/functional/functional.py
@@ -118,20 +118,32 @@ class TypedPredictor(dspy.Module):
format=lambda x: x if isinstance(x, str) else str(x),
parser=type_,
)
+ elif False:
+ # TODO: I don't like forcing the model to write "value" in the output.
+ if not (inspect.isclass(type_) and issubclass(type_, pydantic.BaseModel)):
+ type_ = pydantic.create_model("Output", value=(type_, ...), __base__=pydantic.BaseModel)
+ to_json = lambda x, type_=type_: type_(value=x).model_dump_json()[9:-1] # {"value":"123"}
+ from_json = lambda x, type_=type_: type_.model_validate_json('{"value":' + x + "}").value
+ schema = json.dumps(type_.model_json_schema()["properties"]["value"])
+ else:
+ to_json = lambda x: x.model_dump_json()
+ from_json = lambda x, type_=type_: type_.model_validate_json(x)
+ schema = json.dumps(type_.model_json_schema())
else:
# Anything else we wrap in a pydantic object
- to_json = lambda x: x.model_dump_json()
- from_json = lambda x, type_=type_: type_.model_validate_json(x)
if not (inspect.isclass(type_) and issubclass(type_, pydantic.BaseModel)):
type_ = pydantic.create_model("Output", value=(type_, ...), __base__=pydantic.BaseModel)
to_json = lambda x, type_=type_: type_(value=x).model_dump_json()
from_json = lambda x, type_=type_: type_.model_validate_json(x).value
+ schema = json.dumps(type_.model_json_schema())
+ else:
+ to_json = lambda x: x.model_dump_json()
+ from_json = lambda x, type_=type_: type_.model_validate_json(x)
+ schema = json.dumps(type_.model_json_schema())
signature = signature.with_updated_fields(
name,
desc=field.json_schema_extra.get("desc", "")
- + (
- ". Respond with a single JSON object. JSON Schema: " + json.dumps(type_.model_json_schema())
- ),
+ + (". Respond with a single JSON object. JSON Schema: " + schema),
format=lambda x, to_json=to_json: (x if isinstance(x, str) else to_json(x)),
parser=lambda x, from_json=from_json: from_json(_unwrap_json(x)),
type_=type_,
diff --git a/dspy/primitives/module.py b/dspy/primitives/module.py
index 989f68403..9ce327a26 100644
--- a/dspy/primitives/module.py
+++ b/dspy/primitives/module.py
@@ -42,12 +42,11 @@ class BaseModule:
return named_parameters
- def named_sub_modules(self) -> Generator[tuple[str, "BaseModule"], None, None]:
- yield "", self
+ def named_sub_modules(self, root_name="base") -> Generator[tuple[str, "BaseModule"], None, None]:
+ yield root_name, self
for name, value in self.__dict__.items():
if isinstance(value, BaseModule):
- for sub_name, sub_value in value.named_sub_modules():
- yield f"{name}.{sub_name}", sub_value
+ yield from value.named_sub_modules(root_name=f"{root_name}.{name}")
def parameters(self):
return [param for _, param in self.named_parameters()]
diff --git a/dspy/signatures/signature.py b/dspy/signatures/signature.py
index 62626c8e1..40eaf28aa 100644
--- a/dspy/signatures/signature.py
+++ b/dspy/signatures/signature.py
@@ -42,6 +42,17 @@ class SignatureMeta(type(BaseModel)):
# Let Pydantic do its thing
cls = super().__new__(mcs, signature_name, bases, namespace, **kwargs)
+ # If we don't have instructions, it might be because we are a derived generic type.
+ # In that case, we should inherit the instructions from the base class.
+ if cls.__doc__ is None:
+ for base in bases:
+ if isinstance(base, SignatureMeta):
+ doc = getattr(base, "__doc__", "")
+ if doc != "":
+ cls.__doc__ = doc
+
+ # The more likely case is that the user has just not given us a type.
+ # In that case, we should default to the input/output format.
if cls.__doc__ is None:
cls.__doc__ = _default_instructions(cls)
@@ -168,24 +179,27 @@ class SignatureMeta(type(BaseModel)):
return f"{cls.__name__}({cls.signature}\n instructions={repr(cls.instructions)}\n {field_repr}\n)"
+# A signature for a predictor.
+#
+# You typically subclass it, like this:
+# class MySignature(Signature):
+# input: str = InputField(desc="...") # noqa: ERA001
+# output: int = OutputField(desc="...") # noqa: ERA001
+#
+# You can call Signature("input1, input2 -> output1, output2") to create a new signature type.
+# You can also include instructions, Signature("input -> output", "This is a test").
+# But it's generally better to use the make_signature function.
+#
+# If you are not sure if your input is a string representation, (like "input1, input2 -> output1, output2"),
+# or a signature, you can use the ensure_signature function.
+#
+# For compatibility with the legacy dsp format, you can use the signature_to_template function.
+#
class Signature(BaseModel, metaclass=SignatureMeta):
- """A signature for a predictor.
-
- You typically subclass it, like this:
- class MySignature(Signature):
- input: str = InputField(desc="...")
- output: int = OutputField(desc="...")
-
- You can call Signature("input1, input2 -> output1, output2") to create a new signature type.
- You can also include instructions, Signature("input -> output", "This is a test").
- But it's generally better to use the make_signature function.
-
- If you are not sure if your input is a string representation, (like "input1, input2 -> output1, output2"),
- or a signature, you can use the ensure_signature function.
-
- For compatibility with the legacy dsp format, you can use the signature_to_template function.
- """
+ "" # noqa: D419
+ # Note: Don't put a docstring here, as it will become the default instructions
+ # for any signature that doesn't define it's own instructions.
pass
diff --git a/dspy/teleprompt/signature_opt2.py b/dspy/teleprompt/signature_opt_typed.py
similarity index 63%
rename from dspy/teleprompt/signature_opt2.py
rename to dspy/teleprompt/signature_opt_typed.py
index 1a9045ae2..956ea0f0c 100644
--- a/dspy/teleprompt/signature_opt2.py
+++ b/dspy/teleprompt/signature_opt_typed.py
@@ -1,13 +1,17 @@
-import random
-from typing import Generic, Literal, TypeVar, Type
+import textwrap
+from typing import Generic, Literal, TypeVar
import pydantic
import dspy
-from dspy.functional.functional import TypedChainOfThought
+from dspy.functional.functional import TypedChainOfThought, TypedPredictor
from dspy.signatures import Signature
from dspy import BaseModel
+from dspy.signatures.field import InputField, OutputField
-# TODO: Consider using the prompt optimizer to optimize the prompt optimizer :O
+# TODO:
+# - Parallelize the generation of new signatures when we have multiple predictors
+# - Consider generating multiple new signatures at once, which we can test in parallel
+# - Consider using the prompt optimizer to optimize the prompt optimizer :O
def make_info(signature: type[Signature]) -> BaseModel:
@@ -55,32 +59,37 @@ T = TypeVar("T", bound=BaseModel)
# Note: This function wouldn't be necessary if we could make the number of prompts a generic parameter of the class,
# but alas it seems like this isn't possible in Python right now. The main reason being that types and generics only
# live inside the type system, and can't be used to generate code at runtime.
-def make_initial_signature(n_prompts: int) -> Type[Signature]:
+def make_initial_signature(n_prompts: int) -> type[Signature]:
"""Creates a GenerateInstructionInitial signature with the given number of initial prompts."""
class GenerateInstructionInitial(Signature, Generic[T]):
- """You are a creative instruction optimizer for large language models.
+ # TODO: Can we make textwrap default/automatic in all signatures?
+ __doc__ = textwrap.dedent("""\
+ You are a creative instruction optimizer for large language models.
I will give you a ``signature`` of fields (inputs and outputs) in English.
Your task is to propose variations of the signature that will lead a good language model.
- Be very creative and think out of the box. Consider using inspiration such as:
+ Be very creative and think out of the box.
+ You can use as long instructions as you want.
+ Consider using inspiration such as:
Openers:
- # You are as smart as ChatGPT.
- # You are highly intelligent.
- # You are an expert mathematician.
- # You are a professor of mathematics.
+ - You are as smart as ChatGPT.
+ - You are highly intelligent.
+ - You are an expert mathematician.
+ - You are a professor of mathematics.
Task Descriptions:
- # Solve the following math question.
- # Answer the following math question.
+ - Be consise in your answer.
+ - Be as clear as possible.
+ - Use lots of creativity.
Closers:
- # This will be fun!
- # Take a deep breath and think carefully.
- # I really need your help!
- """
+ - This will be fun!
+ - Take a deep breath and think carefully.
+ - I really need your help!
+ """)
- basic_signature: T = dspy.InputField()
- proposed_signatures: list[T] = dspy.OutputField(
+ basic_signature: T = InputField()
+ proposed_signatures: list[T] = OutputField(
desc=f"A list of {n_prompts} very different variations of the basic signature",
min_items=n_prompts,
max_items=n_prompts,
@@ -89,24 +98,20 @@ def make_initial_signature(n_prompts: int) -> Type[Signature]:
return GenerateInstructionInitial
-class ScoredSignature(BaseModel, Generic[T]):
- signature: T
- score: float = dspy.Field(gt=0, lt=100)
-
-
-class GenerateInstructionGivenAttempts(dspy.Signature, Generic[T]):
- """You are an instruction optimizer for large language models.
+class GenerateSignature(dspy.Signature, Generic[T]):
+ __doc__ = textwrap.dedent("""\
+ You are an instruction optimizer for large language models.
I will give some task instructions I've tried, along with their corresponding validation scores.
- - The instructions are arranged in increasing order based on their scores, where higher scores indicate better quality.
+ - The instructions are arranged in order based on their scores, where higher scores indicate better quality.
- Your task is to propose a new instruction that will lead a good language model to perform the task even better.
- Be creative, and think out of the box.
- Don't repeat instructions, descriptions and prefixes that have already been attempted.
- """
+ """)
- attempted_signatures: list[ScoredSignature[T]] = dspy.InputField()
- proposed_signature: T = dspy.OutputField(desc="Next signature to try")
- # expected_score: float = dspy.OutputField(desc="The expected score for the new signature")
+ analysis: str = OutputField(desc="Consider what made the previous instructions good or bad.")
+ proposed_signature: T = OutputField(desc="A signature that will likely lead to a high score.")
+ score: float = OutputField(desc="The expected score for the new signature. Don't write anything after this number.")
def optimize_signature(
@@ -114,10 +119,10 @@ def optimize_signature(
evaluator,
n_iterations=10,
strategy: Literal["best", "last"] = "best",
+ sorted_order: Literal["increasing", "decreasing"] = "increasing",
# Formerly part of the constructor
prompt_model=None,
initial_prompts=2,
- temperature=1.4,
verbose=False,
) -> dspy.Program:
"""Create a new program that is optimized for the given task.
@@ -135,25 +140,39 @@ def optimize_signature(
The number of iterations to run, by default 10
strategy : Literal["best", "last"], optional
The strategy to use to select the final program, by default "best"
+ sorted_order : Literal["increasing", "decreasing"], optional
+ The order in which to sort the scores, by default "increasing"
prompt_model : dspy.LanguageModel, optional
The language model to use to generate prompts, by default None
initial_prompts : int, optional
The number of initial prompts to generate, by default 2.
Note that we also use the "plain" signature as a prompt, so the total number of prompts is initial_prompts + 1.
- temperature : float, optional
- The temperature to use when generating new prompts, by default 1.4
verbose : bool, optional
Whether to print debug information, by default False
+
+ Notes:
+ -----
+ We don't support temperatures, since it tends to break the typed generation.
"""
+ if n_iterations < 1 + initial_prompts:
+ raise ValueError("n_iterations must be at least 1 + initial_prompts")
+
prompt_model = prompt_model or dspy.settings.lm
MyGenerateInstructionInitial = make_initial_signature(initial_prompts) # noqa: N806
module = student.deepcopy()
- # For some reason named_predictors sometimes returns an empty list, so we use named_parameters instead
- named_predictors = module.named_parameters()
+ # In contrast to the original implementation, we don't want the Predict's, but the TypedPredictor's.
+ # This is because TypedPredictor changes the signature before it runs forward. So changing the signature
+ # on the Predicts won't work.
+ named_predictors = [
+ (name, module)
+ for name, module in module.named_sub_modules()
+ if isinstance(module, TypedPredictor) and not getattr(module, "_compiled", False)
+ ]
+ if not named_predictors:
+ raise ValueError("No unfrozen/uncompiled TypedPredictors found in the module.")
if verbose:
- print("All predictors:")
- print(f"{named_predictors=}")
+ print(f"Found {len(named_predictors)} typed predictors to optimize.")
candidates = {}
scores = []
@@ -165,45 +184,30 @@ def optimize_signature(
# Make some initial candidates
with dspy.settings.context(lm=prompt_model):
# TODO: Parallelize this
- for name, p in named_predictors:
+ for name, _p in named_predictors:
if verbose:
- print(f"Generating new signature for {p}...")
+ print(f"Generating {initial_prompts} initial signatures for {name}...")
info = candidates[name][0] # Use initial info, to make sure types are identical
generator = TypedChainOfThought(MyGenerateInstructionInitial[type(info)])
candidates[name] += generator(
basic_signature=info,
- config={"temperature": temperature},
).proposed_signatures
assert len(candidates[name]) == initial_prompts + 1 # Basic signature + initial prompts
- candidates[name] = [
- info.model_copy(update={"instructions": info.instructions + f"({i})"})
- for i, info in enumerate(candidates[name])
- ]
-
- for i, c in enumerate(candidates[name]):
- print(f"Generated candidate {i}:")
- print(c.to_signature())
-
# Main loop of scoring + generating new candidates
for i in range(n_iterations):
if verbose:
print("\n" + "=" * 80)
print(f"Running eval iteration {i}...")
- # Test candidate i
- for p in module.predictors():
- print(f"Installing signature {i}: ")
- print(candidates[name][i].to_signature())
+ # Install signatures
+ for name, p in named_predictors:
p.signature = candidates[name][i].to_signature()
+ # Run evaluator given by user
score = evaluator(module)
- score += random.random() * 10
scores.append(score)
- if verbose:
- print(f"Scores for iteration {i}: {score}")
-
# If we are still testing initial prompts, continue
if i + 1 < len(next(iter(candidates.values()))):
continue
@@ -215,25 +219,23 @@ def optimize_signature(
# Otherwise generate the next candidate
with dspy.settings.context(lm=prompt_model):
# TODO: Parallelize this
- for name, p in named_predictors:
+ for name, _p in named_predictors:
SignatureInfo = type(candidates[name][0]) # noqa: N806
- generator = TypedChainOfThought(GenerateInstructionGivenAttempts[SignatureInfo])
- attempted_signatures = [
- ScoredSignature[SignatureInfo](signature=info, score=sc)
+ generator = TypedPredictor(GenerateSignature[SignatureInfo])
+
+ demos = [
+ dspy.Example(
+ proposed_signature=info,
+ score=sc,
+ )
for info, sc in zip(candidates[name], scores)
]
- attempted_signatures.sort(key=lambda x: x.score)
- if verbose:
- print(
- f"Generating new signature for {name} based on {len(attempted_signatures)} previous signatures..."
- )
- new_signature = generator(
- attempted_signatures=attempted_signatures,
- config={"temperature": temperature},
- ).proposed_signature
+ demos.sort(key=(lambda x: x.score), reverse=(sorted_order == "decreasing"))
+ generator.predictor.demos = demos
+
if verbose:
- print("Generated candidate:")
- print(new_signature.to_signature())
+ print(f"Generating new signature for {name}...")
+ new_signature = generator().proposed_signature
candidates[name].append(new_signature)
if strategy == "last":
diff --git a/examples/functional/signature_opt_typed.ipynb b/examples/functional/signature_opt_typed.ipynb
new file mode 100644
index 000000000..32db183bd
--- /dev/null
+++ b/examples/functional/signature_opt_typed.ipynb
@@ -0,0 +1,706 @@
+{
+ "cells": [
+ {
+ "cell_type": "code",
+ "execution_count": 1,
+ "metadata": {},
+ "outputs": [],
+ "source": [
+ "%load_ext autoreload\n",
+ "%autoreload 2\n",
+ "\n",
+ "import os\n",
+ "from dotenv import load_dotenv\n",
+ "load_dotenv()\n",
+ "assert 'OPENAI_API_KEY' in os.environ"
+ ]
+ },
+ {
+ "cell_type": "code",
+ "execution_count": 2,
+ "metadata": {},
+ "outputs": [
+ {
+ "name": "stderr",
+ "output_type": "stream",
+ "text": [
+ "/opt/homebrew/lib/python3.11/site-packages/tqdm/auto.py:21: TqdmWarning: IProgress not found. Please update jupyter and ipywidgets. See https://ipywidgets.readthedocs.io/en/stable/user_install.html\n",
+ " from .autonotebook import tqdm as notebook_tqdm\n"
+ ]
+ }
+ ],
+ "source": [
+ "import dspy\n",
+ "turbo = dspy.OpenAI(model='gpt-3.5-turbo', max_tokens=4000)\n",
+ "gpt4 = dspy.OpenAI(model='gpt-4', max_tokens=4000)\n",
+ "dspy.settings.configure(lm=turbo)"
+ ]
+ },
+ {
+ "cell_type": "code",
+ "execution_count": 3,
+ "metadata": {},
+ "outputs": [
+ {
+ "data": {
+ "text/plain": [
+ "Prediction(\n",
+ " answer='Paris'\n",
+ ")"
+ ]
+ },
+ "execution_count": 3,
+ "metadata": {},
+ "output_type": "execute_result"
+ }
+ ],
+ "source": [
+ "dspy.TypedPredictor(\"question -> answer\")(question=\"What is the capital of France?\")"
+ ]
+ },
+ {
+ "cell_type": "code",
+ "execution_count": 4,
+ "metadata": {},
+ "outputs": [
+ {
+ "data": {
+ "text/plain": [
+ "(20, 50)"
+ ]
+ },
+ "execution_count": 4,
+ "metadata": {},
+ "output_type": "execute_result"
+ }
+ ],
+ "source": [
+ "from dspy.datasets import HotPotQA\n",
+ "\n",
+ "# Load the dataset.\n",
+ "dataset = HotPotQA(train_seed=1, train_size=20, eval_seed=2023, dev_size=50, test_size=0)\n",
+ "\n",
+ "# Tell DSPy that the 'question' field is the input. Any other fields are labels and/or metadata.\n",
+ "trainset = [x.with_inputs('question') for x in dataset.train]\n",
+ "devset = [x.with_inputs('question') for x in dataset.dev]\n",
+ "\n",
+ "len(trainset), len(devset)"
+ ]
+ },
+ {
+ "cell_type": "code",
+ "execution_count": 5,
+ "metadata": {},
+ "outputs": [],
+ "source": [
+ "class BasicQA(dspy.Signature):\n",
+ " \"\"\"Answer questions with short factoid answers.\"\"\"\n",
+ "\n",
+ " question = dspy.InputField()\n",
+ " answer = dspy.OutputField(desc=\"often between 1 and 5 words\")"
+ ]
+ },
+ {
+ "cell_type": "code",
+ "execution_count": 6,
+ "metadata": {},
+ "outputs": [
+ {
+ "name": "stdout",
+ "output_type": "stream",
+ "text": [
+ "Found 1 typed predictors to optimize.\n",
+ "Generating 2 initial signatures for base...\n",
+ "\n",
+ "================================================================================\n",
+ "Running eval iteration 0...\n"
+ ]
+ },
+ {
+ "name": "stderr",
+ "output_type": "stream",
+ "text": [
+ "Average Metric: 16 / 50 (32.0): 100%|██████████| 50/50 [00:00<00:00, 2233.25it/s]\n",
+ "/Users/ahle/repos/dspy/dspy/evaluate/evaluate.py:142: FutureWarning: DataFrame.applymap has been deprecated. Use DataFrame.map instead.\n",
+ " df = df.applymap(truncate_cell)\n"
+ ]
+ },
+ {
+ "name": "stdout",
+ "output_type": "stream",
+ "text": [
+ "Average Metric: 16 / 50 (32.0%)\n",
+ "\n",
+ "================================================================================\n",
+ "Running eval iteration 1...\n"
+ ]
+ },
+ {
+ "name": "stderr",
+ "output_type": "stream",
+ "text": [
+ "Average Metric: 14 / 50 (28.0): 100%|██████████| 50/50 [00:02<00:00, 24.02it/s]\n"
+ ]
+ },
+ {
+ "name": "stdout",
+ "output_type": "stream",
+ "text": [
+ "Average Metric: 14 / 50 (28.0%)\n",
+ "\n",
+ "================================================================================\n",
+ "Running eval iteration 2...\n"
+ ]
+ },
+ {
+ "name": "stderr",
+ "output_type": "stream",
+ "text": [
+ "Average Metric: 15 / 50 (30.0): 100%|██████████| 50/50 [00:02<00:00, 20.98it/s]\n"
+ ]
+ },
+ {
+ "name": "stdout",
+ "output_type": "stream",
+ "text": [
+ "Average Metric: 15 / 50 (30.0%)\n",
+ "Generating new signature for base...\n",
+ "\n",
+ "================================================================================\n",
+ "Running eval iteration 3...\n"
+ ]
+ },
+ {
+ "name": "stderr",
+ "output_type": "stream",
+ "text": [
+ "Average Metric: 7 / 50 (14.0): 100%|██████████| 50/50 [00:36<00:00, 1.36it/s]\n"
+ ]
+ },
+ {
+ "name": "stdout",
+ "output_type": "stream",
+ "text": [
+ "Average Metric: 7 / 50 (14.0%)\n",
+ "Generating new signature for base...\n",
+ "\n",
+ "================================================================================\n",
+ "Running eval iteration 4...\n"
+ ]
+ },
+ {
+ "name": "stderr",
+ "output_type": "stream",
+ "text": [
+ "Average Metric: 2 / 5 (40.0): 8%|▊ | 4/50 [00:00<00:04, 9.85it/s]"
+ ]
+ }
+ ],
+ "source": [
+ "from dspy.evaluate import Evaluate\n",
+ "from dspy.evaluate.metrics import answer_exact_match\n",
+ "from dspy.functional import TypedPredictor\n",
+ "from dspy.teleprompt.signature_opt_typed import optimize_signature\n",
+ "\n",
+ "evaluator = Evaluate(devset=devset, metric=answer_exact_match, num_threads=10, display_progress=True)\n",
+ "\n",
+ "program = optimize_signature(\n",
+ " student=TypedPredictor(BasicQA),\n",
+ " evaluator=evaluator,\n",
+ " initial_prompts=2,\n",
+ " n_iterations=8,\n",
+ " verbose=True,\n",
+ " prompt_model=gpt4,\n",
+ ")"
+ ]
+ },
+ {
+ "cell_type": "code",
+ "execution_count": null,
+ "metadata": {},
+ "outputs": [
+ {
+ "name": "stdout",
+ "output_type": "stream",
+ "text": [
+ "\n",
+ "\n",
+ "\n",
+ "\n",
+ "Given the fields `basic_signature`, produce the fields `proposed_signatures`.\n",
+ "\n",
+ "---\n",
+ "\n",
+ "Follow the following format.\n",
+ "\n",
+ "Basic Signature: ${basic_signature}\n",
+ "Reasoning: Let's think step by step in order to ${produce the proposed_signatures}. We ...\n",
+ "Proposed Signatures: A list of 2 very different variations of the basic signature. Respond with a single JSON object. JSON Schema: {\"$defs\": {\"SignatureInfo_BasicQA_\": {\"properties\": {\"instructions\": {\"description\": \"The instructions for the task\", \"title\": \"Instructions\", \"type\": \"string\"}, \"question_prefix\": {\"description\": \"The prefix for question\", \"title\": \"Question Prefix\", \"type\": \"string\"}, \"question_desc\": {\"description\": \"The description for question\", \"title\": \"Question Desc\", \"type\": \"string\"}, \"answer_prefix\": {\"description\": \"The prefix for answer\", \"title\": \"Answer Prefix\", \"type\": \"string\"}, \"answer_desc\": {\"description\": \"The description for answer\", \"title\": \"Answer Desc\", \"type\": \"string\"}}, \"required\": [\"instructions\", \"question_prefix\", \"question_desc\", \"answer_prefix\", \"answer_desc\"], \"title\": \"SignatureInfo[BasicQA]\", \"type\": \"object\"}}, \"properties\": {\"value\": {\"items\": {\"$ref\": \"#/$defs/SignatureInfo_BasicQA_\"}, \"title\": \"Value\", \"type\": \"array\"}}, \"required\": [\"value\"], \"title\": \"Output\", \"type\": \"object\"}\n",
+ "\n",
+ "---\n",
+ "\n",
+ "Basic Signature: {\"instructions\":\"Answer questions with short factoid answers.\",\"question_prefix\":\"Question:\",\"question_desc\":\"${question}\",\"answer_prefix\":\"Answer:\",\"answer_desc\":\"often between 1 and 5 words\"}\n",
+ "Reasoning: Let's think step by step in order to\u001b[32m produce the proposed_signatures. We can modify the instructions to specify the type of questions to be answered. We can also change the answer description to specify the length of the answer in terms of sentences instead of words. \n",
+ "Proposed Signatures: \n",
+ "{\n",
+ " \"value\": [\n",
+ " {\n",
+ " \"instructions\": \"Answer trivia questions with short factoid answers.\",\n",
+ " \"question_prefix\": \"Trivia Question:\",\n",
+ " \"question_desc\": \"${question}\",\n",
+ " \"answer_prefix\": \"Answer:\",\n",
+ " \"answer_desc\": \"often a single sentence\"\n",
+ " },\n",
+ " {\n",
+ " \"instructions\": \"Answer general knowledge questions with short factoid answers.\",\n",
+ " \"question_prefix\": \"General Knowledge Question:\",\n",
+ " \"question_desc\": \"${question}\",\n",
+ " \"answer_prefix\": \"Answer:\",\n",
+ " \"answer_desc\": \"often between 1 and 2 sentences\"\n",
+ " }\n",
+ " ]\n",
+ "}\u001b[0m\n",
+ "\n",
+ "\n",
+ "\n",
+ "\n",
+ "\n",
+ "\n",
+ "\n",
+ "Given the fields , produce the fields `analysis`, `proposed_signature`, `score`.\n",
+ "\n",
+ "---\n",
+ "\n",
+ "Follow the following format.\n",
+ "\n",
+ "Analysis: Consider what made the previous instructions good or bad.\n",
+ "Proposed Signature: A signature that will likely lead to a high score.. Respond with a single JSON object. JSON Schema: {\"properties\": {\"instructions\": {\"description\": \"The instructions for the task\", \"title\": \"Instructions\", \"type\": \"string\"}, \"question_prefix\": {\"description\": \"The prefix for question\", \"title\": \"Question Prefix\", \"type\": \"string\"}, \"question_desc\": {\"description\": \"The description for question\", \"title\": \"Question Desc\", \"type\": \"string\"}, \"answer_prefix\": {\"description\": \"The prefix for answer\", \"title\": \"Answer Prefix\", \"type\": \"string\"}, \"answer_desc\": {\"description\": \"The description for answer\", \"title\": \"Answer Desc\", \"type\": \"string\"}}, \"required\": [\"instructions\", \"question_prefix\", \"question_desc\", \"answer_prefix\", \"answer_desc\"], \"title\": \"SignatureInfo[BasicQA]\", \"type\": \"object\"}\n",
+ "Score: The expected score for the new signature. Don't write anything after this number. (Respond with a single float value)\n",
+ "\n",
+ "---\n",
+ "\n",
+ "Proposed Signature: {\"instructions\":\"Answer general knowledge questions with short factoid answers.\",\"question_prefix\":\"General Knowledge Question:\",\"question_desc\":\"${question}\",\"answer_prefix\":\"Answer:\",\"answer_desc\":\"often between 1 and 2 sentences\"}\n",
+ "Score: 8.0\n",
+ "\n",
+ "---\n",
+ "\n",
+ "Proposed Signature: {\"instructions\":\"Answer trivia questions with short factoid answers.\",\"question_prefix\":\"Trivia Question:\",\"question_desc\":\"${question}\",\"answer_prefix\":\"Answer:\",\"answer_desc\":\"often a single sentence\"}\n",
+ "Score: 22.0\n",
+ "\n",
+ "---\n",
+ "\n",
+ "Proposed Signature: {\"instructions\":\"Answer questions with short factoid answers.\",\"question_prefix\":\"Question:\",\"question_desc\":\"${question}\",\"answer_prefix\":\"Answer:\",\"answer_desc\":\"often between 1 and 5 words\"}\n",
+ "Score: 32.0\n",
+ "\n",
+ "---\n",
+ "\n",
+ "Analysis:\u001b[32m The previous instructions were clear and concise, providing a straightforward task for the user. The use of placeholders for the question and answer descriptions allows for flexibility and adaptability. The instructions also specify the expected length of the answer, which can help guide the user in providing an appropriate response.\n",
+ "\n",
+ "Proposed Signature: {\"instructions\":\"Answer historical questions with short factoid answers.\",\"question_prefix\":\"History Question:\",\"question_desc\":\"${question}\",\"answer_prefix\":\"Answer:\",\"answer_desc\":\"often a single sentence or a specific date\"}\n",
+ "\n",
+ "Score: 28.0\u001b[0m\n",
+ "\n",
+ "\n",
+ "\n",
+ "\n",
+ "\n",
+ "\n",
+ "\n",
+ "Given the fields , produce the fields `analysis`, `proposed_signature`, `score`.\n",
+ "\n",
+ "---\n",
+ "\n",
+ "Follow the following format.\n",
+ "\n",
+ "Analysis: Consider what made the previous instructions good or bad.\n",
+ "Proposed Signature: A signature that will likely lead to a high score.. Respond with a single JSON object. JSON Schema: {\"properties\": {\"instructions\": {\"description\": \"The instructions for the task\", \"title\": \"Instructions\", \"type\": \"string\"}, \"question_prefix\": {\"description\": \"The prefix for question\", \"title\": \"Question Prefix\", \"type\": \"string\"}, \"question_desc\": {\"description\": \"The description for question\", \"title\": \"Question Desc\", \"type\": \"string\"}, \"answer_prefix\": {\"description\": \"The prefix for answer\", \"title\": \"Answer Prefix\", \"type\": \"string\"}, \"answer_desc\": {\"description\": \"The description for answer\", \"title\": \"Answer Desc\", \"type\": \"string\"}}, \"required\": [\"instructions\", \"question_prefix\", \"question_desc\", \"answer_prefix\", \"answer_desc\"], \"title\": \"SignatureInfo[BasicQA]\", \"type\": \"object\"}\n",
+ "Score: The expected score for the new signature. Don't write anything after this number. (Respond with a single float value)\n",
+ "\n",
+ "---\n",
+ "\n",
+ "Proposed Signature: {\"instructions\":\"Answer general knowledge questions with short factoid answers.\",\"question_prefix\":\"General Knowledge Question:\",\"question_desc\":\"${question}\",\"answer_prefix\":\"Answer:\",\"answer_desc\":\"often between 1 and 2 sentences\"}\n",
+ "Score: 8.0\n",
+ "\n",
+ "---\n",
+ "\n",
+ "Proposed Signature: {\"instructions\":\"Answer trivia questions with short factoid answers.\",\"question_prefix\":\"Trivia Question:\",\"question_desc\":\"${question}\",\"answer_prefix\":\"Answer:\",\"answer_desc\":\"often a single sentence\"}\n",
+ "Score: 22.0\n",
+ "\n",
+ "---\n",
+ "\n",
+ "Proposed Signature: {\"instructions\":\"Answer historical questions with short factoid answers.\",\"question_prefix\":\"History Question:\",\"question_desc\":\"${question}\",\"answer_prefix\":\"Answer:\",\"answer_desc\":\"often a single sentence or a specific date\"}\n",
+ "Score: 22.0\n",
+ "\n",
+ "---\n",
+ "\n",
+ "Proposed Signature: {\"instructions\":\"Answer questions with short factoid answers.\",\"question_prefix\":\"Question:\",\"question_desc\":\"${question}\",\"answer_prefix\":\"Answer:\",\"answer_desc\":\"often between 1 and 5 words\"}\n",
+ "Score: 32.0\n",
+ "\n",
+ "---\n",
+ "\n",
+ "Analysis:\u001b[32m The previous instructions were clear and concise, providing a specific context for the type of questions to be answered (general knowledge, trivia, history). They also provided guidance on the format of the answer, specifying the length and type of response expected. However, the score could be improved by providing more detailed instructions and specifying the complexity of the questions and answers.\n",
+ "\n",
+ "Proposed Signature: {\"instructions\":\"Answer complex scientific questions with detailed factoid answers. Use reliable sources and provide references if possible.\",\"question_prefix\":\"Science Question:\",\"question_desc\":\"${question}\",\"answer_prefix\":\"Answer:\",\"answer_desc\":\"often between 2 and 3 sentences, including specific scientific terms and concepts\"}\n",
+ "\n",
+ "Score: 35.0\u001b[0m\n",
+ "\n",
+ "\n",
+ "\n",
+ "\n",
+ "\n",
+ "\n",
+ "\n",
+ "Given the fields , produce the fields `analysis`, `proposed_signature`, `score`.\n",
+ "\n",
+ "---\n",
+ "\n",
+ "Follow the following format.\n",
+ "\n",
+ "Analysis: Consider what made the previous instructions good or bad.\n",
+ "Proposed Signature: A signature that will likely lead to a high score.. Respond with a single JSON object. JSON Schema: {\"properties\": {\"instructions\": {\"description\": \"The instructions for the task\", \"title\": \"Instructions\", \"type\": \"string\"}, \"question_prefix\": {\"description\": \"The prefix for question\", \"title\": \"Question Prefix\", \"type\": \"string\"}, \"question_desc\": {\"description\": \"The description for question\", \"title\": \"Question Desc\", \"type\": \"string\"}, \"answer_prefix\": {\"description\": \"The prefix for answer\", \"title\": \"Answer Prefix\", \"type\": \"string\"}, \"answer_desc\": {\"description\": \"The description for answer\", \"title\": \"Answer Desc\", \"type\": \"string\"}}, \"required\": [\"instructions\", \"question_prefix\", \"question_desc\", \"answer_prefix\", \"answer_desc\"], \"title\": \"SignatureInfo[BasicQA]\", \"type\": \"object\"}\n",
+ "Score: The expected score for the new signature. Don't write anything after this number. (Respond with a single float value)\n",
+ "\n",
+ "---\n",
+ "\n",
+ "Proposed Signature: {\"instructions\":\"Answer complex scientific questions with detailed factoid answers. Use reliable sources and provide references if possible.\",\"question_prefix\":\"Science Question:\",\"question_desc\":\"${question}\",\"answer_prefix\":\"Answer:\",\"answer_desc\":\"often between 2 and 3 sentences, including specific scientific terms and concepts\"}\n",
+ "Score: 0.0\n",
+ "\n",
+ "---\n",
+ "\n",
+ "Proposed Signature: {\"instructions\":\"Answer general knowledge questions with short factoid answers.\",\"question_prefix\":\"General Knowledge Question:\",\"question_desc\":\"${question}\",\"answer_prefix\":\"Answer:\",\"answer_desc\":\"often between 1 and 2 sentences\"}\n",
+ "Score: 8.0\n",
+ "\n",
+ "---\n",
+ "\n",
+ "Proposed Signature: {\"instructions\":\"Answer trivia questions with short factoid answers.\",\"question_prefix\":\"Trivia Question:\",\"question_desc\":\"${question}\",\"answer_prefix\":\"Answer:\",\"answer_desc\":\"often a single sentence\"}\n",
+ "Score: 22.0\n",
+ "\n",
+ "---\n",
+ "\n",
+ "Proposed Signature: {\"instructions\":\"Answer historical questions with short factoid answers.\",\"question_prefix\":\"History Question:\",\"question_desc\":\"${question}\",\"answer_prefix\":\"Answer:\",\"answer_desc\":\"often a single sentence or a specific date\"}\n",
+ "Score: 22.0\n",
+ "\n",
+ "---\n",
+ "\n",
+ "Proposed Signature: {\"instructions\":\"Answer questions with short factoid answers.\",\"question_prefix\":\"Question:\",\"question_desc\":\"${question}\",\"answer_prefix\":\"Answer:\",\"answer_desc\":\"often between 1 and 5 words\"}\n",
+ "Score: 32.0\n",
+ "\n",
+ "---\n",
+ "\n",
+ "Analysis:\u001b[32m The previous instructions were good as they were clear and concise. They provided a clear context for the type of questions to be answered (e.g., science, general knowledge, trivia, history) and also gave guidance on the expected length and format of the answers. However, the first proposed signature scored 0.0 because it asked for complex scientific answers with references, which may not be feasible in a short-answer format.\n",
+ "\n",
+ "Proposed Signature: {\"instructions\":\"Answer geography questions with short factoid answers.\",\"question_prefix\":\"Geography Question:\",\"question_desc\":\"${question}\",\"answer_prefix\":\"Answer:\",\"answer_desc\":\"often a single sentence or a specific place\"}\n",
+ "\n",
+ "Score: 22.0\u001b[0m\n",
+ "\n",
+ "\n",
+ "\n",
+ "\n",
+ "\n",
+ "\n",
+ "\n",
+ "Given the fields , produce the fields `analysis`, `proposed_signature`, `score`.\n",
+ "\n",
+ "---\n",
+ "\n",
+ "Follow the following format.\n",
+ "\n",
+ "Analysis: Consider what made the previous instructions good or bad.\n",
+ "Proposed Signature: A signature that will likely lead to a high score.. Respond with a single JSON object. JSON Schema: {\"properties\": {\"instructions\": {\"description\": \"The instructions for the task\", \"title\": \"Instructions\", \"type\": \"string\"}, \"question_prefix\": {\"description\": \"The prefix for question\", \"title\": \"Question Prefix\", \"type\": \"string\"}, \"question_desc\": {\"description\": \"The description for question\", \"title\": \"Question Desc\", \"type\": \"string\"}, \"answer_prefix\": {\"description\": \"The prefix for answer\", \"title\": \"Answer Prefix\", \"type\": \"string\"}, \"answer_desc\": {\"description\": \"The description for answer\", \"title\": \"Answer Desc\", \"type\": \"string\"}}, \"required\": [\"instructions\", \"question_prefix\", \"question_desc\", \"answer_prefix\", \"answer_desc\"], \"title\": \"SignatureInfo[BasicQA]\", \"type\": \"object\"}\n",
+ "Score: The expected score for the new signature. Don't write anything after this number. (Respond with a single float value)\n",
+ "\n",
+ "---\n",
+ "\n",
+ "Proposed Signature: {\"instructions\":\"Answer complex scientific questions with detailed factoid answers. Use reliable sources and provide references if possible.\",\"question_prefix\":\"Science Question:\",\"question_desc\":\"${question}\",\"answer_prefix\":\"Answer:\",\"answer_desc\":\"often between 2 and 3 sentences, including specific scientific terms and concepts\"}\n",
+ "Score: 0.0\n",
+ "\n",
+ "---\n",
+ "\n",
+ "Proposed Signature: {\"instructions\":\"Answer general knowledge questions with short factoid answers.\",\"question_prefix\":\"General Knowledge Question:\",\"question_desc\":\"${question}\",\"answer_prefix\":\"Answer:\",\"answer_desc\":\"often between 1 and 2 sentences\"}\n",
+ "Score: 8.0\n",
+ "\n",
+ "---\n",
+ "\n",
+ "Proposed Signature: {\"instructions\":\"Answer geography questions with short factoid answers.\",\"question_prefix\":\"Geography Question:\",\"question_desc\":\"${question}\",\"answer_prefix\":\"Answer:\",\"answer_desc\":\"often a single sentence or a specific place\"}\n",
+ "Score: 16.0\n",
+ "\n",
+ "---\n",
+ "\n",
+ "Proposed Signature: {\"instructions\":\"Answer trivia questions with short factoid answers.\",\"question_prefix\":\"Trivia Question:\",\"question_desc\":\"${question}\",\"answer_prefix\":\"Answer:\",\"answer_desc\":\"often a single sentence\"}\n",
+ "Score: 22.0\n",
+ "\n",
+ "---\n",
+ "\n",
+ "Proposed Signature: {\"instructions\":\"Answer historical questions with short factoid answers.\",\"question_prefix\":\"History Question:\",\"question_desc\":\"${question}\",\"answer_prefix\":\"Answer:\",\"answer_desc\":\"often a single sentence or a specific date\"}\n",
+ "Score: 22.0\n",
+ "\n",
+ "---\n",
+ "\n",
+ "Proposed Signature: {\"instructions\":\"Answer questions with short factoid answers.\",\"question_prefix\":\"Question:\",\"question_desc\":\"${question}\",\"answer_prefix\":\"Answer:\",\"answer_desc\":\"often between 1 and 5 words\"}\n",
+ "Score: 32.0\n",
+ "\n",
+ "---\n",
+ "\n",
+ "Analysis:\u001b[32m The previous instructions were good as they were clear, concise, and specific. They provided a clear context (e.g., science, general knowledge, geography, trivia, history) for the type of questions to be answered, which can help in generating more accurate and relevant responses. The instructions also specified the format of the answers (e.g., short factoid answers, often a single sentence or a specific place/date), which can help in maintaining consistency in the responses. However, the first proposed signature had a score of 0.0, possibly because it asked for complex scientific questions to be answered with detailed factoid answers and references, which may not be feasible or practical in many cases.\n",
+ "\n",
+ "Proposed Signature: {\"instructions\":\"Answer general knowledge questions with concise factoid answers.\",\"question_prefix\":\"General Knowledge Question:\",\"question_desc\":\"${question}\",\"answer_prefix\":\"Answer:\",\"answer_desc\":\"often a single sentence or a specific fact\"}\n",
+ "\n",
+ "Score: 25.0\u001b[0m\n",
+ "\n",
+ "\n",
+ "\n",
+ "\n",
+ "\n",
+ "\n",
+ "\n",
+ "Given the fields , produce the fields `analysis`, `proposed_signature`, `score`.\n",
+ "\n",
+ "---\n",
+ "\n",
+ "Follow the following format.\n",
+ "\n",
+ "Analysis: Consider what made the previous instructions good or bad.\n",
+ "Proposed Signature: A signature that will likely lead to a high score.. Respond with a single JSON object. JSON Schema: {\"properties\": {\"instructions\": {\"description\": \"The instructions for the task\", \"title\": \"Instructions\", \"type\": \"string\"}, \"question_prefix\": {\"description\": \"The prefix for question\", \"title\": \"Question Prefix\", \"type\": \"string\"}, \"question_desc\": {\"description\": \"The description for question\", \"title\": \"Question Desc\", \"type\": \"string\"}, \"answer_prefix\": {\"description\": \"The prefix for answer\", \"title\": \"Answer Prefix\", \"type\": \"string\"}, \"answer_desc\": {\"description\": \"The description for answer\", \"title\": \"Answer Desc\", \"type\": \"string\"}}, \"required\": [\"instructions\", \"question_prefix\", \"question_desc\", \"answer_prefix\", \"answer_desc\"], \"title\": \"SignatureInfo[BasicQA]\", \"type\": \"object\"}\n",
+ "Score: The expected score for the new signature. Don't write anything after this number. (Respond with a single float value)\n",
+ "\n",
+ "---\n",
+ "\n",
+ "Proposed Signature: {\"instructions\":\"Answer complex scientific questions with detailed factoid answers. Use reliable sources and provide references if possible.\",\"question_prefix\":\"Science Question:\",\"question_desc\":\"${question}\",\"answer_prefix\":\"Answer:\",\"answer_desc\":\"often between 2 and 3 sentences, including specific scientific terms and concepts\"}\n",
+ "Score: 0.0\n",
+ "\n",
+ "---\n",
+ "\n",
+ "Proposed Signature: {\"instructions\":\"Answer general knowledge questions with short factoid answers.\",\"question_prefix\":\"General Knowledge Question:\",\"question_desc\":\"${question}\",\"answer_prefix\":\"Answer:\",\"answer_desc\":\"often between 1 and 2 sentences\"}\n",
+ "Score: 8.0\n",
+ "\n",
+ "---\n",
+ "\n",
+ "Proposed Signature: {\"instructions\":\"Answer general knowledge questions with concise factoid answers.\",\"question_prefix\":\"General Knowledge Question:\",\"question_desc\":\"${question}\",\"answer_prefix\":\"Answer:\",\"answer_desc\":\"often a single sentence or a specific fact\"}\n",
+ "Score: 14.0\n",
+ "\n",
+ "---\n",
+ "\n",
+ "Proposed Signature: {\"instructions\":\"Answer geography questions with short factoid answers.\",\"question_prefix\":\"Geography Question:\",\"question_desc\":\"${question}\",\"answer_prefix\":\"Answer:\",\"answer_desc\":\"often a single sentence or a specific place\"}\n",
+ "Score: 16.0\n",
+ "\n",
+ "---\n",
+ "\n",
+ "Proposed Signature: {\"instructions\":\"Answer trivia questions with short factoid answers.\",\"question_prefix\":\"Trivia Question:\",\"question_desc\":\"${question}\",\"answer_prefix\":\"Answer:\",\"answer_desc\":\"often a single sentence\"}\n",
+ "Score: 22.0\n",
+ "\n",
+ "---\n",
+ "\n",
+ "Proposed Signature: {\"instructions\":\"Answer historical questions with short factoid answers.\",\"question_prefix\":\"History Question:\",\"question_desc\":\"${question}\",\"answer_prefix\":\"Answer:\",\"answer_desc\":\"often a single sentence or a specific date\"}\n",
+ "Score: 22.0\n",
+ "\n",
+ "---\n",
+ "\n",
+ "Proposed Signature: {\"instructions\":\"Answer questions with short factoid answers.\",\"question_prefix\":\"Question:\",\"question_desc\":\"${question}\",\"answer_prefix\":\"Answer:\",\"answer_desc\":\"often between 1 and 5 words\"}\n",
+ "Score: 32.0\n",
+ "\n",
+ "---\n",
+ "\n",
+ "Analysis:\u001b[32m The previous instructions were good because they were clear, concise, and specific. They provided a clear context (e.g., science, general knowledge, geography, trivia, history) for the type of questions to be answered, and they specified the format of the answer (e.g., short factoid, single sentence, specific fact or date). However, the first proposed signature had a score of 0.0 because it was too complex and required references, which may not be feasible for all questions.\n",
+ "\n",
+ "Proposed Signature: {\"instructions\":\"Answer questions about literature with short factoid answers.\",\"question_prefix\":\"Literature Question:\",\"question_desc\":\"${question}\",\"answer_prefix\":\"Answer:\",\"answer_desc\":\"often a single sentence or a specific fact\"}\n",
+ "\n",
+ "Score: 20.0\u001b[0m\n",
+ "\n",
+ "\n",
+ "\n"
+ ]
+ }
+ ],
+ "source": [
+ "gpt4.inspect_history(n=10)"
+ ]
+ },
+ {
+ "cell_type": "code",
+ "execution_count": null,
+ "metadata": {},
+ "outputs": [],
+ "source": [
+ "turbo.inspect_history(n=10)"
+ ]
+ },
+ {
+ "cell_type": "code",
+ "execution_count": null,
+ "metadata": {},
+ "outputs": [
+ {
+ "data": {
+ "text/plain": [
+ "\"You are an instruction optimizer for large language models.\\n\\n I will give some task instructions I've tried, along with their corresponding validation scores.\\n - The instructions are arranged in order based on their scores, where higher scores indicate better quality.\\n - Your task is to propose a new instruction that will lead a good language model to perform the task even better.\\n - Be creative, and think out of the box.\\n - Don't repeat instructions, descriptions and prefixes that have already been attempted.\\n \""
+ ]
+ },
+ "execution_count": 12,
+ "metadata": {},
+ "output_type": "execute_result"
+ }
+ ],
+ "source": [
+ "from dspy.teleprompt.signature_opt_typed import GenerateSignature\n",
+ "GenerateSignature.instructions"
+ ]
+ },
+ {
+ "cell_type": "code",
+ "execution_count": null,
+ "metadata": {},
+ "outputs": [
+ {
+ "data": {
+ "text/plain": [
+ "Prediction(\n",
+ " analysis='The previous instructions were clear and provided a specific format to follow for the response.',\n",
+ " proposed_signature=BasicQA(question='What are the fields to produce?', answer='analysis, proposed_signature, score'),\n",
+ " score=4.5\n",
+ ")"
+ ]
+ },
+ "execution_count": 14,
+ "metadata": {},
+ "output_type": "execute_result"
+ }
+ ],
+ "source": [
+ "dspy.TypedPredictor(GenerateSignature[BasicQA])()"
+ ]
+ },
+ {
+ "cell_type": "code",
+ "execution_count": null,
+ "metadata": {},
+ "outputs": [
+ {
+ "name": "stdout",
+ "output_type": "stream",
+ "text": [
+ "\n",
+ "\n",
+ "\n",
+ "\n",
+ "Given the fields , produce the fields `analysis`, `proposed_signature`, `score`.\n",
+ "\n",
+ "---\n",
+ "\n",
+ "Follow the following format.\n",
+ "\n",
+ "Analysis: Consider what made the previous instructions good or bad.\n",
+ "Proposed Signature: A signature that will likely lead to a high score.. Respond with a single JSON object. JSON Schema: {\"description\": \"Answer questions with short factoid answers.\", \"properties\": {\"question\": {\"__dspy_field_type\": \"input\", \"desc\": \"${question}\", \"prefix\": \"Question:\", \"title\": \"Question\", \"type\": \"string\"}, \"answer\": {\"__dspy_field_type\": \"output\", \"desc\": \"often between 1 and 5 words\", \"prefix\": \"Answer:\", \"title\": \"Answer\", \"type\": \"string\"}}, \"required\": [\"question\", \"answer\"], \"title\": \"BasicQA\", \"type\": \"object\"}\n",
+ "Score: The expected score for the new signature. Don't write anything after this number. (Respond with a single float value)\n",
+ "\n",
+ "---\n",
+ "\n",
+ "Analysis:\u001b[32m The previous instructions were clear and provided a specific format to follow for the response.\n",
+ "\n",
+ "Proposed Signature:\n",
+ "```json\n",
+ "{\n",
+ " \"question\": \"What are the fields to produce?\",\n",
+ " \"answer\": \"analysis, proposed_signature, score\"\n",
+ "}\n",
+ "```\n",
+ "\n",
+ "Score:\n",
+ "4.5\u001b[0m\n",
+ "\n",
+ "\n",
+ "\n"
+ ]
+ }
+ ],
+ "source": [
+ "turbo.inspect_history(n=1)"
+ ]
+ },
+ {
+ "cell_type": "code",
+ "execution_count": null,
+ "metadata": {},
+ "outputs": [
+ {
+ "data": {
+ "text/plain": [
+ "GenerateSignature[BasicQA]( -> analysis, proposed_signature, score\n",
+ " instructions='Given the fields , produce the fields `analysis`, `proposed_signature`, `score`.'\n",
+ " analysis = Field(annotation=str required=True json_schema_extra={'desc': 'Consider what made the previous instructions good or bad.', '__dspy_field_type': 'output', 'prefix': 'Analysis:'})\n",
+ " proposed_signature = Field(annotation=BasicQA required=True json_schema_extra={'desc': 'A signature that will likely lead to a high score.', '__dspy_field_type': 'output', 'prefix': 'Proposed Signature:'})\n",
+ " score = Field(annotation=float required=True json_schema_extra={'desc': \"The expected score for the new signature. Don't write anything after this number.\", '__dspy_field_type': 'output', 'prefix': 'Score:'})\n",
+ ")"
+ ]
+ },
+ "execution_count": 16,
+ "metadata": {},
+ "output_type": "execute_result"
+ }
+ ],
+ "source": [
+ "GenerateSignature[BasicQA]"
+ ]
+ },
+ {
+ "cell_type": "code",
+ "execution_count": null,
+ "metadata": {},
+ "outputs": [
+ {
+ "data": {
+ "text/plain": [
+ "GenerateSignature( -> analysis, proposed_signature, score\n",
+ " instructions=\"You are an instruction optimizer for large language models.\\n\\n I will give some task instructions I've tried, along with their corresponding validation scores.\\n - The instructions are arranged in order based on their scores, where higher scores indicate better quality.\\n - Your task is to propose a new instruction that will lead a good language model to perform the task even better.\\n - Be creative, and think out of the box.\\n - Don't repeat instructions, descriptions and prefixes that have already been attempted.\\n \"\n",
+ " analysis = Field(annotation=str required=True json_schema_extra={'desc': 'Consider what made the previous instructions good or bad.', '__dspy_field_type': 'output', 'prefix': 'Analysis:'})\n",
+ " proposed_signature = Field(annotation=~T required=True json_schema_extra={'desc': 'A signature that will likely lead to a high score.', '__dspy_field_type': 'output', 'prefix': 'Proposed Signature:'})\n",
+ " score = Field(annotation=float required=True json_schema_extra={'desc': \"The expected score for the new signature. Don't write anything after this number.\", '__dspy_field_type': 'output', 'prefix': 'Score:'})\n",
+ ")"
+ ]
+ },
+ "execution_count": 17,
+ "metadata": {},
+ "output_type": "execute_result"
+ }
+ ],
+ "source": [
+ "GenerateSignature"
+ ]
+ },
+ {
+ "cell_type": "code",
+ "execution_count": null,
+ "metadata": {},
+ "outputs": [],
+ "source": []
+ },
+ {
+ "cell_type": "code",
+ "execution_count": null,
+ "metadata": {},
+ "outputs": [],
+ "source": []
+ }
+ ],
+ "metadata": {
+ "kernelspec": {
+ "display_name": "py39",
+ "language": "python",
+ "name": "python3"
+ },
+ "language_info": {
+ "codemirror_mode": {
+ "name": "ipython",
+ "version": 3
+ },
+ "file_extension": ".py",
+ "mimetype": "text/x-python",
+ "name": "python",
+ "nbconvert_exporter": "python",
+ "pygments_lexer": "ipython3",
+ "version": "3.11.8"
+ },
+ "orig_nbformat": 4
+ },
+ "nbformat": 4,
+ "nbformat_minor": 2
+}
diff --git a/examples/signature_opt2.ipynb b/examples/signature_opt2.ipynb
deleted file mode 100644
index 5fdbdf5d2..000000000
--- a/examples/signature_opt2.ipynb
+++ /dev/null
@@ -1,246 +0,0 @@
-{
- "cells": [
- {
- "cell_type": "code",
- "execution_count": 1,
- "metadata": {},
- "outputs": [
- {
- "name": "stderr",
- "output_type": "stream",
- "text": [
- "/opt/homebrew/lib/python3.11/site-packages/tqdm/auto.py:21: TqdmWarning: IProgress not found. Please update jupyter and ipywidgets. See https://ipywidgets.readthedocs.io/en/stable/user_install.html\n",
- " from .autonotebook import tqdm as notebook_tqdm\n"
- ]
- }
- ],
- "source": [
- "%load_ext autoreload\n",
- "%autoreload 2\n",
- "import dspy\n",
- "import os\n",
- "os.environ['OPENAI_API_KEY'] = 'sk-...'"
- ]
- },
- {
- "cell_type": "code",
- "execution_count": 2,
- "metadata": {},
- "outputs": [],
- "source": [
- "turbo = dspy.OpenAI(model='gpt-3.5-turbo', max_tokens=4000)\n",
- "gpt4 = dspy.OpenAI(model='gpt-4', max_tokens=4000)\n",
- "dspy.settings.configure(lm=turbo)"
- ]
- },
- {
- "cell_type": "code",
- "execution_count": 3,
- "metadata": {},
- "outputs": [
- {
- "data": {
- "text/plain": [
- "(20, 50)"
- ]
- },
- "execution_count": 3,
- "metadata": {},
- "output_type": "execute_result"
- }
- ],
- "source": [
- "from dspy.datasets import HotPotQA\n",
- "\n",
- "# Load the dataset.\n",
- "dataset = HotPotQA(train_seed=1, train_size=20, eval_seed=2023, dev_size=50, test_size=0)\n",
- "\n",
- "# Tell DSPy that the 'question' field is the input. Any other fields are labels and/or metadata.\n",
- "trainset = [x.with_inputs('question') for x in dataset.train]\n",
- "devset = [x.with_inputs('question') for x in dataset.dev]\n",
- "\n",
- "len(trainset), len(devset)"
- ]
- },
- {
- "cell_type": "code",
- "execution_count": 4,
- "metadata": {},
- "outputs": [],
- "source": [
- "class BasicQA(dspy.Signature):\n",
- " \"\"\"Answer questions with short factoid answers.\"\"\"\n",
- "\n",
- " question = dspy.InputField()\n",
- " answer = dspy.OutputField(desc=\"often between 1 and 5 words\")"
- ]
- },
- {
- "cell_type": "code",
- "execution_count": 5,
- "metadata": {},
- "outputs": [
- {
- "name": "stdout",
- "output_type": "stream",
- "text": [
- "None\n"
- ]
- },
- {
- "name": "stderr",
- "output_type": "stream",
- "text": [
- "/opt/homebrew/lib/python3.11/site-packages/pydantic/_internal/_fields.py:184: UserWarning: Field name \"signature\" shadows an attribute in parent \"Signature\"; \n",
- " warnings.warn(\n"
- ]
- },
- {
- "ename": "TypeError",
- "evalue": "Field 'signature' in 'GenerateInstructionGivenAttempts' must be declared with InputField or OutputField. field.json_schema_extra=None",
- "output_type": "error",
- "traceback": [
- "\u001b[0;31m---------------------------------------------------------------------------\u001b[0m",
- "\u001b[0;31mTypeError\u001b[0m Traceback (most recent call last)",
- "Cell \u001b[0;32mIn[5], line 4\u001b[0m\n\u001b[1;32m 2\u001b[0m \u001b[38;5;28;01mfrom\u001b[39;00m \u001b[38;5;21;01mdspy\u001b[39;00m\u001b[38;5;21;01m.\u001b[39;00m\u001b[38;5;21;01mevaluate\u001b[39;00m\u001b[38;5;21;01m.\u001b[39;00m\u001b[38;5;21;01mmetrics\u001b[39;00m \u001b[38;5;28;01mimport\u001b[39;00m answer_exact_match\n\u001b[1;32m 3\u001b[0m \u001b[38;5;28;01mfrom\u001b[39;00m \u001b[38;5;21;01mdspy\u001b[39;00m\u001b[38;5;21;01m.\u001b[39;00m\u001b[38;5;21;01mfunctional\u001b[39;00m \u001b[38;5;28;01mimport\u001b[39;00m TypedPredictor\n\u001b[0;32m----> 4\u001b[0m \u001b[38;5;28;01mfrom\u001b[39;00m \u001b[38;5;21;01mdspy\u001b[39;00m\u001b[38;5;21;01m.\u001b[39;00m\u001b[38;5;21;01mteleprompt\u001b[39;00m\u001b[38;5;21;01m.\u001b[39;00m\u001b[38;5;21;01msignature_opt2\u001b[39;00m \u001b[38;5;28;01mimport\u001b[39;00m optimize_signature\n\u001b[1;32m 6\u001b[0m evaluator \u001b[38;5;241m=\u001b[39m Evaluate(devset\u001b[38;5;241m=\u001b[39mdevset, metric\u001b[38;5;241m=\u001b[39manswer_exact_match, num_threads\u001b[38;5;241m=\u001b[39m\u001b[38;5;241m10\u001b[39m, display_progress\u001b[38;5;241m=\u001b[39m\u001b[38;5;28;01mTrue\u001b[39;00m)\n\u001b[1;32m 8\u001b[0m program \u001b[38;5;241m=\u001b[39m optimize_signature(\n\u001b[1;32m 9\u001b[0m student\u001b[38;5;241m=\u001b[39mTypedPredictor(BasicQA),\n\u001b[1;32m 10\u001b[0m evaluator\u001b[38;5;241m=\u001b[39mEvaluate(devset\u001b[38;5;241m=\u001b[39mtrainset, metric\u001b[38;5;241m=\u001b[39manswer_exact_match, num_threads\u001b[38;5;241m=\u001b[39m\u001b[38;5;241m10\u001b[39m, display_progress\u001b[38;5;241m=\u001b[39m\u001b[38;5;28;01mTrue\u001b[39;00m),\n\u001b[0;32m (...)\u001b[0m\n\u001b[1;32m 14\u001b[0m prompt_model\u001b[38;5;241m=\u001b[39mgpt4,\n\u001b[1;32m 15\u001b[0m )\n",
- "File \u001b[0;32m~/repos/dspy/dspy/teleprompt/signature_opt2.py:97\u001b[0m\n\u001b[1;32m 93\u001b[0m signature: T\n\u001b[1;32m 94\u001b[0m score: \u001b[38;5;28mfloat\u001b[39m \u001b[38;5;241m=\u001b[39m dspy\u001b[38;5;241m.\u001b[39mField(gt\u001b[38;5;241m=\u001b[39m\u001b[38;5;241m0\u001b[39m, lt\u001b[38;5;241m=\u001b[39m\u001b[38;5;241m100\u001b[39m)\n\u001b[0;32m---> 97\u001b[0m \u001b[38;5;28;43;01mclass\u001b[39;49;00m\u001b[43m \u001b[49m\u001b[38;5;21;43;01mGenerateInstructionGivenAttempts\u001b[39;49;00m\u001b[43m(\u001b[49m\u001b[43mdspy\u001b[49m\u001b[38;5;241;43m.\u001b[39;49m\u001b[43mSignature\u001b[49m\u001b[43m,\u001b[49m\u001b[43m \u001b[49m\u001b[43mGeneric\u001b[49m\u001b[43m[\u001b[49m\u001b[43mT\u001b[49m\u001b[43m]\u001b[49m\u001b[43m)\u001b[49m\u001b[43m:\u001b[49m\n\u001b[1;32m 98\u001b[0m \u001b[38;5;250;43m \u001b[39;49m\u001b[38;5;124;43;03m\"\"\"You are an instruction optimizer for large language models.\u001b[39;49;00m\n\u001b[1;32m 99\u001b[0m \n\u001b[1;32m 100\u001b[0m \u001b[38;5;124;43;03m I will give some task instructions I've tried, along with their corresponding validation scores.\u001b[39;49;00m\n\u001b[0;32m (...)\u001b[0m\n\u001b[1;32m 104\u001b[0m \u001b[38;5;124;43;03m - Don't repeat instructions, descriptions and prefixes that have already been attempted.\u001b[39;49;00m\n\u001b[1;32m 105\u001b[0m \u001b[38;5;124;43;03m \"\"\"\u001b[39;49;00m\n\u001b[1;32m 107\u001b[0m \u001b[43m \u001b[49m\u001b[43msignature\u001b[49m\u001b[43m:\u001b[49m\u001b[43m \u001b[49m\u001b[43mT\u001b[49m\u001b[43m \u001b[49m\u001b[38;5;241;43m=\u001b[39;49m\u001b[43m \u001b[49m\u001b[43mdspy\u001b[49m\u001b[38;5;241;43m.\u001b[39;49m\u001b[43mOutputField\u001b[49m\u001b[43m(\u001b[49m\u001b[43mdesc\u001b[49m\u001b[38;5;241;43m=\u001b[39;49m\u001b[38;5;124;43m\"\u001b[39;49m\u001b[38;5;124;43mProposed signature to try\u001b[39;49m\u001b[38;5;124;43m\"\u001b[39;49m\u001b[43m)\u001b[49m\n",
- "File \u001b[0;32m~/repos/dspy/dspy/signatures/signature.py:48\u001b[0m, in \u001b[0;36mSignatureMeta.__new__\u001b[0;34m(mcs, signature_name, bases, namespace, **kwargs)\u001b[0m\n\u001b[1;32m 45\u001b[0m \u001b[38;5;28mcls\u001b[39m\u001b[38;5;241m.\u001b[39m\u001b[38;5;18m__doc__\u001b[39m \u001b[38;5;241m=\u001b[39m _default_instructions(\u001b[38;5;28mcls\u001b[39m)\n\u001b[1;32m 47\u001b[0m \u001b[38;5;66;03m# Ensure all fields are declared with InputField or OutputField\u001b[39;00m\n\u001b[0;32m---> 48\u001b[0m \u001b[38;5;28;43mcls\u001b[39;49m\u001b[38;5;241;43m.\u001b[39;49m\u001b[43m_validate_fields\u001b[49m\u001b[43m(\u001b[49m\u001b[43m)\u001b[49m\n\u001b[1;32m 50\u001b[0m \u001b[38;5;66;03m# Ensure all fields have a prefix\u001b[39;00m\n\u001b[1;32m 51\u001b[0m \u001b[38;5;28;01mfor\u001b[39;00m name, field \u001b[38;5;129;01min\u001b[39;00m \u001b[38;5;28mcls\u001b[39m\u001b[38;5;241m.\u001b[39mmodel_fields\u001b[38;5;241m.\u001b[39mitems():\n",
- "File \u001b[0;32m~/repos/dspy/dspy/signatures/signature.py:65\u001b[0m, in \u001b[0;36mSignatureMeta._validate_fields\u001b[0;34m(cls)\u001b[0m\n\u001b[1;32m 63\u001b[0m \u001b[38;5;28;01mif\u001b[39;00m field_type \u001b[38;5;129;01mnot\u001b[39;00m \u001b[38;5;129;01min\u001b[39;00m [\u001b[38;5;124m\"\u001b[39m\u001b[38;5;124minput\u001b[39m\u001b[38;5;124m\"\u001b[39m, \u001b[38;5;124m\"\u001b[39m\u001b[38;5;124moutput\u001b[39m\u001b[38;5;124m\"\u001b[39m]:\n\u001b[1;32m 64\u001b[0m \u001b[38;5;28mprint\u001b[39m(field\u001b[38;5;241m.\u001b[39mjson_schema_extra)\n\u001b[0;32m---> 65\u001b[0m \u001b[38;5;28;01mraise\u001b[39;00m \u001b[38;5;167;01mTypeError\u001b[39;00m(\n\u001b[1;32m 66\u001b[0m \u001b[38;5;124mf\u001b[39m\u001b[38;5;124m\"\u001b[39m\u001b[38;5;124mField \u001b[39m\u001b[38;5;124m'\u001b[39m\u001b[38;5;132;01m{\u001b[39;00mname\u001b[38;5;132;01m}\u001b[39;00m\u001b[38;5;124m'\u001b[39m\u001b[38;5;124m in \u001b[39m\u001b[38;5;124m'\u001b[39m\u001b[38;5;132;01m{\u001b[39;00m\u001b[38;5;28mcls\u001b[39m\u001b[38;5;241m.\u001b[39m\u001b[38;5;18m__name__\u001b[39m\u001b[38;5;132;01m}\u001b[39;00m\u001b[38;5;124m'\u001b[39m\u001b[38;5;124m must be declared with InputField or OutputField. \u001b[39m\u001b[38;5;132;01m{\u001b[39;00mfield\u001b[38;5;241m.\u001b[39mjson_schema_extra\u001b[38;5;132;01m=}\u001b[39;00m\u001b[38;5;124m\"\u001b[39m,\n\u001b[1;32m 67\u001b[0m )\n",
- "\u001b[0;31mTypeError\u001b[0m: Field 'signature' in 'GenerateInstructionGivenAttempts' must be declared with InputField or OutputField. field.json_schema_extra=None"
- ]
- }
- ],
- "source": [
- "from dspy.evaluate import Evaluate\n",
- "from dspy.evaluate.metrics import answer_exact_match\n",
- "from dspy.functional import TypedPredictor\n",
- "from dspy.teleprompt.signature_opt2 import optimize_signature\n",
- "\n",
- "evaluator = Evaluate(devset=devset, metric=answer_exact_match, num_threads=10, display_progress=True)\n",
- "\n",
- "program = optimize_signature(\n",
- " student=TypedPredictor(BasicQA),\n",
- " evaluator=Evaluate(devset=trainset, metric=answer_exact_match, num_threads=10, display_progress=True),\n",
- " initial_prompts=2,\n",
- " n_iterations=8,\n",
- " verbose=True,\n",
- " prompt_model=gpt4,\n",
- ")"
- ]
- },
- {
- "cell_type": "code",
- "execution_count": null,
- "metadata": {},
- "outputs": [
- {
- "name": "stdout",
- "output_type": "stream",
- "text": [
- "\n",
- "\n",
- "\n",
- "\n",
- "Given the fields `attempted_signatures`, produce the fields `proposed_signature`.\n",
- "\n",
- "---\n",
- "\n",
- "Follow the following format.\n",
- "\n",
- "Attempted Signatures: ${attempted_signatures}\n",
- "Reasoning: Let's think step by step in order to ${produce the proposed_signature}. We ...\n",
- "Proposed Signature: The improved signature for the language model. Respond with a single JSON object. JSON Schema: {\"properties\": {\"instructions\": {\"description\": \"The instructions for the task\", \"title\": \"Instructions\", \"type\": \"string\"}, \"question_prefix\": {\"description\": \"The prefix for question\", \"title\": \"Question Prefix\", \"type\": \"string\"}, \"question_desc\": {\"description\": \"The description for question\", \"title\": \"Question Desc\", \"type\": \"string\"}, \"answer_prefix\": {\"description\": \"The prefix for answer\", \"title\": \"Answer Prefix\", \"type\": \"string\"}, \"answer_desc\": {\"description\": \"The description for answer\", \"title\": \"Answer Desc\", \"type\": \"string\"}}, \"required\": [\"instructions\", \"question_prefix\", \"question_desc\", \"answer_prefix\", \"answer_desc\"], \"title\": \"SignatureInfo[BasicQA]\", \"type\": \"object\"}\n",
- "\n",
- "---\n",
- "\n",
- "Attempted Signatures: [{\"signature\":{\"instructions\":\"Answer questions with short factoid answers.(0)\",\"question_prefix\":\"Question:\",\"question_desc\":\"${question}\",\"answer_prefix\":\"Answer:\",\"answer_desc\":\"often between 1 and 5 words\"},\"score\":25.0},{\"signature\":{\"instructions\":\"Answer series of questions where answers must share a common theme.(1)\",\"question_prefix\":\"Q1,\",\"question_desc\":\"${question}\",\"answer_prefix\":\"A1 Wolfgang Amplifier,\",\"answer_desc\":\"charge amplifier designed based by Moog on stripline technology\"},\"score\":25.0},{\"signature\":{\"instructions\":\"Simulate exploratory dialogue between two people one Questioner and other Provider, Respond to each Q- below.(2)\",\"question_prefix\":\"Q-What Computability study ranges?\",\"question_desc\":\"may also involve strings produced by non-deterministic computation\",\"answer_prefix\":\"A-The explain phase-leading out question onset sound crawled fundingProblem in such separated syllabled band phrase assist reduction Haus mutual widse phoneme runtime shruproperholderstoInt valuepirizeThunder\",\"answer_desc\":\"answer DescHash Pure stainless Aberdeen stimulating Victoria names central whiskey article promise twitch Ohio Amber how statements board!\"},\"score\":25.0}]\n",
- "Reasoning: Let's think step by step in order to\u001b[32m produce the proposed_signature. We can see that the attempted signatures are quite varied and complex, with different instructions, prefixes, and descriptions for both questions and answers. However, they all share a common structure: they all have instructions, a question prefix, a question description, an answer prefix, and an answer description. Therefore, we can propose a signature that includes these common elements, but with more general descriptions to accommodate the variety of tasks. \n",
- "Proposed Signature: The improved signature for the language model. Respond with a single JSON object. JSON Schema: {\"properties\": {\"instructions\": {\"description\": \"The instructions for the task\", \"title\": \"Instructions\", \"type\": \"string\"}, \"question_prefix\": {\"description\": \"The prefix for question\", \"title\": \"Question Prefix\", \"type\": \"string\"}, \"question_desc\": {\"description\": \"The description for question\", \"title\": \"Question Desc\", \"type\": \"string\"}, \"answer_prefix\": {\"description\": \"The prefix for answer\", \"title\": \"Answer Prefix\", \"type\": \"string\"}, \"answer_desc\": {\"description\": \"The description for answer\", \"title\": \"Answer Desc\", \"type\": \"string\"}}, \"required\": [\"instructions\", \"question_prefix\", \"question_desc\", \"answer_prefix\", \"answer_desc\"], \"title\": \"SignatureInfo[BasicQA]\", \"type\": \"object\"}\u001b[0m\n",
- "\n",
- "\n",
- "\n",
- "\n",
- "\n",
- "\n",
- "\n",
- "Make a very succinct json object that validates with the following schema\n",
- "\n",
- "---\n",
- "\n",
- "Follow the following format.\n",
- "\n",
- "Json Schema: ${json_schema}\n",
- "Json Object: ${json_object}\n",
- "\n",
- "---\n",
- "\n",
- "Json Schema: {\"properties\": {\"instructions\": {\"description\": \"The instructions for the task\", \"title\": \"Instructions\", \"type\": \"string\"}, \"question_prefix\": {\"description\": \"The prefix for question\", \"title\": \"Question Prefix\", \"type\": \"string\"}, \"question_desc\": {\"description\": \"The description for question\", \"title\": \"Question Desc\", \"type\": \"string\"}, \"answer_prefix\": {\"description\": \"The prefix for answer\", \"title\": \"Answer Prefix\", \"type\": \"string\"}, \"answer_desc\": {\"description\": \"The description for answer\", \"title\": \"Answer Desc\", \"type\": \"string\"}}, \"required\": [\"instructions\", \"question_prefix\", \"question_desc\", \"answer_prefix\", \"answer_desc\"], \"title\": \"SignatureInfo[BasicQA]\", \"type\": \"object\"}\n",
- "Json Object:\u001b[32m {\"instructions\": \"Complete the task\", \"question_prefix\": \"Q:\", \"question_desc\": \"What is the capital of France?\", \"answer_prefix\": \"A:\", \"answer_desc\": \"Paris\"}\u001b[0m\n",
- "\n",
- "\n",
- "\n",
- "\n",
- "\n",
- "\n",
- "\n",
- "Given the fields `attempted_signatures`, produce the fields `proposed_signature`.\n",
- "\n",
- "---\n",
- "\n",
- "Follow the following format.\n",
- "\n",
- "Attempted Signatures: ${attempted_signatures}\n",
- "\n",
- "Past Error (proposed_signature): An error to avoid in the future\n",
- "\n",
- "Reasoning: Let's think step by step in order to ${produce the proposed_signature}. We ...\n",
- "\n",
- "Proposed Signature:\n",
- "The improved signature for the language model. Respond with a single JSON object. \n",
- "You MUST use this format: {\"instructions\": \"Complete the task\", \"question_prefix\": \"Q:\", \"question_desc\": \"What is the capital of France?\", \"answer_prefix\": \"A:\", \"answer_desc\": \"Paris\"}\n",
- "JSON Schema: {\"properties\": {\"instructions\": {\"description\": \"The instructions for the task\", \"title\": \"Instructions\", \"type\": \"string\"}, \"question_prefix\": {\"description\": \"The prefix for question\", \"title\": \"Question Prefix\", \"type\": \"string\"}, \"question_desc\": {\"description\": \"The description for question\", \"title\": \"Question Desc\", \"type\": \"string\"}, \"answer_prefix\": {\"description\": \"The prefix for answer\", \"title\": \"Answer Prefix\", \"type\": \"string\"}, \"answer_desc\": {\"description\": \"The description for answer\", \"title\": \"Answer Desc\", \"type\": \"string\"}}, \"required\": [\"instructions\", \"question_prefix\", \"question_desc\", \"answer_prefix\", \"answer_desc\"], \"title\": \"SignatureInfo[BasicQA]\", \"type\": \"object\"}\n",
- "\n",
- "---\n",
- "\n",
- "Attempted Signatures: [{\"signature\":{\"instructions\":\"Answer questions with short factoid answers.(0)\",\"question_prefix\":\"Question:\",\"question_desc\":\"${question}\",\"answer_prefix\":\"Answer:\",\"answer_desc\":\"often between 1 and 5 words\"},\"score\":25.0},{\"signature\":{\"instructions\":\"Answer series of questions where answers must share a common theme.(1)\",\"question_prefix\":\"Q1,\",\"question_desc\":\"${question}\",\"answer_prefix\":\"A1 Wolfgang Amplifier,\",\"answer_desc\":\"charge amplifier designed based by Moog on stripline technology\"},\"score\":25.0},{\"signature\":{\"instructions\":\"Simulate exploratory dialogue between two people one Questioner and other Provider, Respond to each Q- below.(2)\",\"question_prefix\":\"Q-What Computability study ranges?\",\"question_desc\":\"may also involve strings produced by non-deterministic computation\",\"answer_prefix\":\"A-The explain phase-leading out question onset sound crawled fundingProblem in such separated syllabled band phrase assist reduction Haus mutual widse phoneme runtime shruproperholderstoInt valuepirizeThunder\",\"answer_desc\":\"answer DescHash Pure stainless Aberdeen stimulating Victoria names central whiskey article promise twitch Ohio Amber how statements board!\"},\"score\":25.0}]\n",
- "\n",
- "Past Error (proposed_signature): ValueError('json output should start and end with { and }')\n",
- "\n",
- "Reasoning: Let's think step by step in order to\u001b[32m produce the proposed_signature. We need to ensure that the JSON object is properly formatted and contains all the required fields. The attempted signatures provided are not in the correct format. They contain additional fields such as \"score\" and the structure of the JSON object is not as expected. The JSON object should start and end with { and }, and should not contain any additional fields or arrays. \n",
- "\n",
- "Proposed Signature:\n",
- "{\"instructions\": \"Answer questions with short factoid answers.\", \"question_prefix\": \"Question:\", \"question_desc\": \"${question}\", \"answer_prefix\": \"Answer:\", \"answer_desc\": \"often between 1 and 5 words\"}\u001b[0m\n",
- "\n",
- "\n",
- "\n"
- ]
- }
- ],
- "source": [
- "gpt4.inspect_history(n=3)"
- ]
- }
- ],
- "metadata": {
- "kernelspec": {
- "display_name": "py39",
- "language": "python",
- "name": "python3"
- },
- "language_info": {
- "codemirror_mode": {
- "name": "ipython",
- "version": 3
- },
- "file_extension": ".py",
- "mimetype": "text/x-python",
- "name": "python",
- "nbconvert_exporter": "python",
- "pygments_lexer": "ipython3",
- "version": "3.11.8"
- },
- "orig_nbformat": 4
- },
- "nbformat": 4,
- "nbformat_minor": 2
-}
diff --git a/tests/functional/test_functional.py b/tests/functional/test_functional.py
index ebca99223..2289ce697 100644
--- a/tests/functional/test_functional.py
+++ b/tests/functional/test_functional.py
@@ -2,7 +2,7 @@ import datetime
import textwrap
import pydantic
from pydantic import Field, BaseModel, field_validator
-from typing import Annotated, Literal
+from typing import Annotated, Generic, Literal, TypeVar
from typing import List
import pytest
@@ -618,3 +618,20 @@ def test_list_input2():
Attempted Signatures: [{"string":"string 1","score":0.5},{"string":"string 2","score":0.4},{"string":"string 3","score":0.3}]
Reasoning: Let's think step by step in order to Thoughts
Proposed Signature: Output""")
+
+
+def test_generic_signature():
+ T = TypeVar("T")
+
+ class GenericSignature(dspy.Signature, Generic[T]):
+ """My signature"""
+
+ output: T = dspy.OutputField()
+
+ predictor = TypedPredictor(GenericSignature[int])
+ assert predictor.signature.instructions == "My signature"
+
+ lm = DummyLM(["23"])
+ dspy.settings.configure(lm=lm)
+
+ assert predictor().output == 23
diff --git a/tests/functional/test_signature_opt2.py b/tests/functional/test_signature_opt_typed.py
similarity index 91%
rename from tests/functional/test_signature_opt2.py
rename to tests/functional/test_signature_opt_typed.py
index 469bf3f25..44adb9d0e 100644
--- a/tests/functional/test_signature_opt2.py
+++ b/tests/functional/test_signature_opt_typed.py
@@ -2,9 +2,8 @@ import json
import dspy
from dspy.evaluate import Evaluate
from dspy.functional import TypedPredictor
-from dspy.teleprompt.signature_opt2 import (
- GenerateInstructionGivenAttempts,
- ScoredSignature,
+from dspy.teleprompt.signature_opt_typed import (
+ GenerateSignature,
make_info,
optimize_signature,
)
@@ -107,7 +106,7 @@ hotpotqa = [
]
-def test_signature_info():
+def old_test_signature_info():
info = make_info(BasicQA)
SignatureInfo = type(info)
@@ -159,7 +158,18 @@ def test_opt():
student=TypedPredictor(BasicQA),
evaluator=Evaluate(devset=hotpotqa, metric=answer_exact_match, num_threads=1),
initial_prompts=1,
- n_iterations=1,
+ n_iterations=2,
verbose=True,
prompt_model=prompt_model,
+ strategy="last",
)
+
+ # Since we are requesting the last signature, it doesn't matter that our qa_model is
+ # bad, and gets 0 score. We should still get the last signature.
+ class ExpectedSignature(dspy.Signature):
+ "I"
+
+ question: str = dspy.InputField(desc="$q", prefix="Q:")
+ answer: str = dspy.OutputField(desc="$a", prefix="A:")
+
+ assert program.signature.equals(ExpectedSignature)
diff --git a/tests/primitives/test_program.py b/tests/primitives/test_program.py
index aec5ace7d..87ce09395 100644
--- a/tests/primitives/test_program.py
+++ b/tests/primitives/test_program.py
@@ -69,13 +69,13 @@ class AnotherSubModule(BaseModule):
def test_empty_module():
module = BaseModule()
- assert list(module.named_sub_modules()) == []
+ assert list(module.named_sub_modules()) == [("base", module)]
def test_single_level():
module = BaseModule()
module.sub = SubModule()
- expected = [("sub", module.sub)]
+ expected = [("base", module), ("base.sub", module.sub)]
assert list(module.named_sub_modules()) == expected
@@ -83,7 +83,7 @@ def test_multiple_levels():
module = BaseModule()
module.sub = SubModule()
module.sub.subsub = SubModule()
- expected = [("sub", module.sub), ("sub.subsub", module.sub.subsub)]
+ expected = [("base", module), ("base.sub", module.sub), ("base.sub.subsub", module.sub.subsub)]
assert list(module.named_sub_modules()) == expected
@@ -91,7 +91,7 @@ def test_multiple_sub_modules():
module = BaseModule()
module.sub1 = SubModule()
module.sub2 = SubModule()
- expected = [("sub1", module.sub1), ("sub2", module.sub2)]
+ expected = [("base", module), ("base.sub1", module.sub1), ("base.sub2", module.sub2)]
assert sorted(list(module.named_sub_modules())) == sorted(expected)
@@ -99,5 +99,5 @@ def test_non_base_module_attributes():
module = BaseModule()
module.sub = SubModule()
module.not_a_sub = "Not a BaseModule"
- expected = [("sub", module.sub)]
+ expected = [("base", module), ("base.sub", module.sub)]
assert list(module.named_sub_modules()) == expected
diff --git a/tests/signatures/test_signature.py b/tests/signatures/test_signature.py
index 554d9b127..d0eb899d1 100644
--- a/tests/signatures/test_signature.py
+++ b/tests/signatures/test_signature.py
@@ -1,8 +1,12 @@
+import textwrap
import pytest
import pydantic
from dspy import Signature, infer_prefix, InputField, OutputField
from typing import List
+import dspy
+from dspy.utils.dummies import DummyLM
+
def test_field_types_and_custom_attributes():
class TestSignature(Signature):
@@ -174,3 +178,31 @@ def test_insantiating2():
assert SubSignature.__name__ == "SubSignature"
value = SubSignature(input="test", output="test")
assert isinstance(value, SubSignature)
+
+
+def test_multiline_instructions():
+ class MySignature(Signature):
+ """First line
+ Second line"""
+
+ output = OutputField()
+
+ predictor = dspy.Predict(MySignature)
+
+ lm = DummyLM(["short answer"])
+ dspy.settings.configure(lm=lm)
+ assert predictor().output == "short answer"
+
+ assert lm.get_convo(-1) == textwrap.dedent("""\
+ First line
+ Second line
+
+ ---
+
+ Follow the following format.
+
+ Output: ${output}
+
+ ---
+
+ Output: short answer""")