Skip to content

armgit / dspy

Public Imported from GitHub
0

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

Python

Feat/add append instruct to signatures (#9923)

Karthik Mathur498760149b23
diff --git a/docs/docs/api/signatures/Signature.md b/docs/docs/api/signatures/Signature.md
index 14e7db8ad..b4a534232 100644
--- a/docs/docs/api/signatures/Signature.md
+++ b/docs/docs/api/signatures/Signature.md
@@ -6,6 +6,7 @@
options:
members:
- append
+ - append_instructions
- delete
- dump_state
- equals
diff --git a/docs/docs/diving-deeper/signatures-in-depth.md b/docs/docs/diving-deeper/signatures-in-depth.md
index 08fa4eb97..711ea1c10 100644
--- a/docs/docs/diving-deeper/signatures-in-depth.md
+++ b/docs/docs/diving-deeper/signatures-in-depth.md
@@ -105,6 +105,9 @@ Every method here returns a new Signature class via deep-copy.
**`Signature.with_instructions(instructions: str)`**
New class, same fields, replaced docstring.
+**`Signature.append_instructions(instructions: str)`**
+New class, same fields, docstring extended by `instructions` (joined with a blank line). Use when you want to layer extra guidance on top of an existing signature (aka docstring) without restating its instructions.
+
**`Signature.with_updated_fields(name, type_=None, **json_schema_extra)`**
Replaces the field’s metadata by merging the keyword arguments onto its existing `json_schema_extra`. Pass `desc=...` to change the description, `prefix=...` to change the label, or any custom key your adapter or optimizer reads. If you change `type_`, the new annotation replaces the old; if you also pass `IS_TYPE_UNDEFINED=False`, you clear the “treat None as empty string” behavior Predict relies on for unannotated string-form fields.
diff --git a/dspy/signatures/signature.py b/dspy/signatures/signature.py
index bc5e83cfc..90f552de4 100644
--- a/dspy/signatures/signature.py
+++ b/dspy/signatures/signature.py
@@ -303,6 +303,35 @@ class Signature(BaseModel, metaclass=SignatureMeta):
"""
return Signature(cls.fields, instructions)
+ @classmethod
+ def append_instructions(cls, instructions: str) -> type["Signature"]:
+ """Return a new Signature class with identical fields and `instructions` appended to the existing instructions.
+
+ This method does not mutate `cls`. It constructs a fresh Signature
+ using the existing instructions from `cls.instructions` followed
+ by `instructions`, joined by a blank line.
+ Unlike `with_instructions`, the existing instructions are preserved rather than replaced.
+
+ Args:
+ instructions (str): Instruction text to append to the existing instructions.
+
+ Returns:
+ A new Signature class whose fields match `cls.fields` and whose instructions
+ equal the existing instructions joined to `instructions` by a blank line.
+
+ Examples:
+ ```python
+ import dspy
+
+ MySig = dspy.Signature("input_text -> output_text", "Translate to French.")
+ NewSig = MySig.append_instructions("Pass additional context.")
+ assert NewSig is not MySig
+ assert "Translate to French." in NewSig.instructions
+ assert "Pass additional context." in NewSig.instructions
+ ```
+ """
+ return Signature(cls.fields, f"{cls.instructions}\n\n{instructions}")
+
@classmethod
def with_updated_fields(cls, name: str, type_: type | None = None, **kwargs: dict[str, Any]) -> type["Signature"]:
"""Create a new Signature class with the updated field information.
diff --git a/tests/signatures/test_signature.py b/tests/signatures/test_signature.py
index ebd3eccb9..beb594b44 100644
--- a/tests/signatures/test_signature.py
+++ b/tests/signatures/test_signature.py
@@ -69,6 +69,35 @@ def test_with_signature():
assert signature1 is not signature2, "The type should be immutable"
+def test_append_instructions():
+ class MySig(Signature):
+ """Translate to French."""
+
+ input_text: str = InputField()
+ output_text: str = OutputField()
+
+ new_sig = MySig.append_instructions("Use a formal register.")
+ assert new_sig.instructions == "Translate to French.\n\nUse a formal register."
+ assert MySig.instructions == "Translate to French.", "The original should be unchanged"
+ assert MySig is not new_sig, "The type should be immutable"
+ assert list(new_sig.input_fields.keys()) == ["input_text"]
+ assert list(new_sig.output_fields.keys()) == ["output_text"]
+
+
+def test_append_instructions_chains():
+ sig = Signature("input1 -> output1", "Base instructions.")
+ chained = sig.append_instructions("Step one.").append_instructions("Step two.")
+ assert chained.instructions == "Base instructions.\n\nStep one.\n\nStep two."
+
+
+def test_append_instructions_preserves_default_instructions():
+ sig = Signature("input1 -> output1")
+ base_instructions = sig.instructions
+ appended = sig.append_instructions("Extra detail.")
+ assert appended.instructions == f"{base_instructions}\n\nExtra detail."
+ assert sig.instructions == base_instructions, "The original should be unchanged"
+
+
def test_with_updated_field():
signature1 = Signature("input1, input2 -> output")
signature2 = signature1.with_updated_fields("input1", prefix="Modified:")