Skip to content

armgit / dspy

Public Imported from GitHub
0

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

Python

Support multiturn history (#7851)

Chen Qian05a9312ad18d
diff --git a/dspy/__init__.py b/dspy/__init__.py
index f5283f30d..74cad5a39 100644
--- a/dspy/__init__.py
+++ b/dspy/__init__.py
@@ -8,7 +8,7 @@ import dspy.retrievers
from dspy.evaluate import Evaluate # isort: skip
from dspy.clients import * # isort: skip
-from dspy.adapters import Adapter, ChatAdapter, JSONAdapter, Image # isort: skip
+from dspy.adapters import Adapter, ChatAdapter, JSONAdapter, Image, History # isort: skip
from dspy.utils.logging_utils import configure_dspy_loggers, disable_logging, enable_logging
from dspy.utils.asyncify import asyncify
from dspy.utils.saving import load
@@ -26,11 +26,4 @@ context = settings.context
BootstrapRS = BootstrapFewShotWithRandomSearch
-from .__metadata__ import (
- __name__,
- __version__,
- __description__,
- __url__,
- __author__,
- __author_email__
-)
+from .__metadata__ import __name__, __version__, __description__, __url__, __author__, __author_email__
diff --git a/dspy/adapters/__init__.py b/dspy/adapters/__init__.py
index e6358a27e..6cb61fcad 100644
--- a/dspy/adapters/__init__.py
+++ b/dspy/adapters/__init__.py
@@ -2,10 +2,12 @@ from dspy.adapters.base import Adapter
from dspy.adapters.chat_adapter import ChatAdapter
from dspy.adapters.json_adapter import JSONAdapter
from dspy.adapters.image_utils import Image
+from dspy.adapters.types import History
__all__ = [
"Adapter",
"ChatAdapter",
"JSONAdapter",
"Image",
+ "History",
]
diff --git a/dspy/adapters/base.py b/dspy/adapters/base.py
index e43e1f584..7964dac1c 100644
--- a/dspy/adapters/base.py
+++ b/dspy/adapters/base.py
@@ -2,6 +2,7 @@ from abc import ABC, abstractmethod
from litellm import ContextWindowExceededError
+from dspy.adapters.types import History
from dspy.utils.callback import with_callbacks
@@ -65,3 +66,38 @@ class Adapter(ABC):
def format_finetune_data(self, signature, demos, inputs, outputs):
raise NotImplementedError
+
+ def format_turn(self, signature, values, role, incomplete=False, is_conversation_history=False):
+ pass
+
+ def format_conversation_history(self, signature, inputs):
+ history_field_name = None
+ for name, field in signature.input_fields.items():
+ if field.annotation == History:
+ history_field_name = name
+ break
+
+ if history_field_name is None:
+ return []
+
+ # In order to format the conversation history, we need to remove the history field from the signature.
+ signature_without_history = signature.delete(history_field_name)
+ conversation_history = inputs[history_field_name].messages if history_field_name in inputs else None
+
+ if conversation_history is None:
+ return []
+
+ messages = []
+ for message in conversation_history:
+ messages.append(
+ self.format_turn(signature_without_history, message, role="user", is_conversation_history=True)
+ )
+ messages.append(
+ self.format_turn(signature_without_history, message, role="assistant", is_conversation_history=True)
+ )
+
+ inputs_copy = dict(inputs)
+ del inputs_copy[history_field_name]
+
+ messages.append(self.format_turn(signature_without_history, inputs_copy, role="user"))
+ return messages
diff --git a/dspy/adapters/chat_adapter.py b/dspy/adapters/chat_adapter.py
index ef38073ce..6cfc77c94 100644
--- a/dspy/adapters/chat_adapter.py
+++ b/dspy/adapters/chat_adapter.py
@@ -12,6 +12,7 @@ from pydantic.fields import FieldInfo
from dspy.adapters.base import Adapter
from dspy.adapters.image_utils import try_expand_image_tags
+from dspy.adapters.types.history import History
from dspy.adapters.utils import format_field_value, get_annotation_name, parse_value
from dspy.signatures.field import OutputField
from dspy.signatures.signature import Signature, SignatureMeta
@@ -46,14 +47,20 @@ class ChatAdapter(Adapter):
]
demos = incomplete_demos + complete_demos
-
prepared_instructions = prepare_instructions(signature)
messages.append({"role": "system", "content": prepared_instructions})
+
+ # Add the few-shot examples
for demo in demos:
- messages.append(format_turn(signature, demo, role="user", incomplete=demo in incomplete_demos))
- messages.append(format_turn(signature, demo, role="assistant", incomplete=demo in incomplete_demos))
+ messages.append(self.format_turn(signature, demo, role="user", incomplete=demo in incomplete_demos))
+ messages.append(self.format_turn(signature, demo, role="assistant", incomplete=demo in incomplete_demos))
+
+ # Add the chat history after few-shot examples
+ if any(field.annotation == History for field in signature.input_fields.values()):
+ messages.extend(self.format_conversation_history(signature, inputs))
+ else:
+ messages.append(self.format_turn(signature, inputs, role="user"))
- messages.append(format_turn(signature, inputs, role="user"))
messages = try_expand_image_tags(messages)
return messages
@@ -92,7 +99,7 @@ class ChatAdapter(Adapter):
# Add the assistant message
role = "assistant"
incomplete = False
- assistant_message = format_turn(signature, outputs, role, incomplete)
+ assistant_message = self.format_turn(signature, outputs, role, incomplete)
messages.append(assistant_message)
# Wrap the messages in a dictionary with a "messages" key
@@ -108,6 +115,9 @@ class ChatAdapter(Adapter):
}
return format_fields(fields_with_values)
+ def format_turn(self, signature, values, role, incomplete=False, is_conversation_history=False):
+ return format_turn(signature, values, role, incomplete, is_conversation_history)
+
def format_fields(fields_with_values: Dict[FieldInfoWithName, Any]) -> str:
"""
@@ -129,7 +139,7 @@ def format_fields(fields_with_values: Dict[FieldInfoWithName, Any]) -> str:
return "\n\n".join(output).strip()
-def format_turn(signature, values, role, incomplete=False):
+def format_turn(signature, values, role, incomplete=False, is_conversation_history=False):
"""
Constructs a new message ("turn") to append to a chat thread. The message is carefully formatted
so that it can instruct an LLM to generate responses conforming to the specified DSPy signature.
@@ -140,24 +150,31 @@ def format_turn(signature, values, role, incomplete=False):
that should be included in the message.
role: The role of the message, which can be either "user" or "assistant".
incomplete: If True, indicates that output field values are present in the set of specified
- ``values``. If False, indicates that ``values`` only contains input field values.
+ `values`. If False, indicates that `values` only contains input field values. Only used if
+ `is_conversation_history` is False.
+ is_conversation_history: If True, indicates that the message is part of the chat history, otherwise
+ it is a demo (few-shot example).
Returns:
A chat message that can be appended to a chat thread. The message contains two string fields:
- ``role`` ("user" or "assistant") and ``content`` (the message text).
+ `role` ("user" or "assistant") and `content` (the message text).
"""
if role == "user":
fields = signature.input_fields
- message_prefix = (
- "This is an example of the task, though some input or output fields are not supplied." if incomplete else ""
- )
+ if incomplete and not is_conversation_history:
+ message_prefix = "This is an example of the task, though some input or output fields are not supplied."
+ else:
+ message_prefix = ""
else:
- # Add the completed field for the assistant turn
- fields = {**signature.output_fields, BuiltInCompletedOutputFieldInfo.name: BuiltInCompletedOutputFieldInfo.info}
- values = {**values, BuiltInCompletedOutputFieldInfo.name: ""}
+ # Add the completed field or chat history for the assistant turn
+ fields = {**signature.output_fields}
+ values = {**values}
message_prefix = ""
+ if not is_conversation_history:
+ fields.update({BuiltInCompletedOutputFieldInfo.name: BuiltInCompletedOutputFieldInfo.info})
+ values.update({BuiltInCompletedOutputFieldInfo.name: ""})
- if not incomplete and not set(values).issuperset(fields.keys()):
+ if not incomplete and not is_conversation_history and not set(values).issuperset(fields.keys()):
raise ValueError(f"Expected {fields.keys()} but got {values.keys()}")
messages = []
@@ -166,7 +183,12 @@ def format_turn(signature, values, role, incomplete=False):
field_messages = format_fields(
{
- FieldInfoWithName(name=k, info=v): values.get(k, "Not supplied for this particular example.")
+ FieldInfoWithName(name=k, info=v): values.get(
+ k,
+ "Not supplied for this conversation history message. "
+ if is_conversation_history
+ else "Not supplied for this particular example. ",
+ )
for k, v in fields.items()
},
)
diff --git a/dspy/adapters/json_adapter.py b/dspy/adapters/json_adapter.py
index c318ab59e..a7c55ed5a 100644
--- a/dspy/adapters/json_adapter.py
+++ b/dspy/adapters/json_adapter.py
@@ -14,7 +14,8 @@ from pydantic.fields import FieldInfo
from dspy.adapters.base import Adapter
from dspy.adapters.image_utils import Image
-from dspy.adapters.utils import parse_value, format_field_value, get_annotation_name, serialize_for_json
+from dspy.adapters.types.history import History
+from dspy.adapters.utils import format_field_value, get_annotation_name, parse_value, serialize_for_json
from dspy.signatures.signature import SignatureMeta
from dspy.signatures.utils import get_dspy_field_type
@@ -82,10 +83,14 @@ class JSONAdapter(Adapter):
messages.append({"role": "system", "content": prepare_instructions(signature)})
for demo in demos:
- messages.append(format_turn(signature, demo, role="user", incomplete=demo in incomplete_demos))
- messages.append(format_turn(signature, demo, role="assistant", incomplete=demo in incomplete_demos))
+ messages.append(self.format_turn(signature, demo, role="user", incomplete=demo in incomplete_demos))
+ messages.append(self.format_turn(signature, demo, role="assistant", incomplete=demo in incomplete_demos))
- messages.append(format_turn(signature, inputs, role="user"))
+ # Add the chat history after few-shot examples
+ if any(field.annotation == History for field in signature.input_fields.values()):
+ messages.extend(self.format_conversation_history(signature, inputs))
+ else:
+ messages.append(self.format_turn(signature, inputs, role="user"))
return messages
@@ -103,8 +108,8 @@ class JSONAdapter(Adapter):
return fields
- def format_turn(self, signature, values, role, incomplete=False):
- return format_turn(signature, values, role, incomplete)
+ def format_turn(self, signature, values, role, incomplete=False, is_conversation_history=False):
+ return format_turn(signature, values, role, incomplete, is_conversation_history)
def format_fields(self, signature, values, role):
fields_with_values = {
@@ -163,7 +168,13 @@ def format_fields(role: str, fields_with_values: Dict[FieldInfoWithName, Any]) -
return "\n\n".join(output).strip()
-def format_turn(signature: SignatureMeta, values: Dict[str, Any], role, incomplete=False) -> Dict[str, str]:
+def format_turn(
+ signature: SignatureMeta,
+ values: Dict[str, Any],
+ role,
+ incomplete=False,
+ is_conversation_history=False,
+) -> Dict[str, str]:
"""
Constructs a new message ("turn") to append to a chat thread. The message is carefully formatted
so that it can instruct an LLM to generate responses conforming to the specified DSPy signature.
@@ -174,7 +185,10 @@ def format_turn(signature: SignatureMeta, values: Dict[str, Any], role, incomple
that should be included in the message.
role: The role of the message, which can be either "user" or "assistant".
incomplete: If True, indicates that output field values are present in the set of specified
- ``values``. If False, indicates that ``values`` only contains input field values.
+ `values`. If False, indicates that `values` only contains input field values. Only
+ relevant if `is_conversation_history` is False.
+ is_conversation_history: If True, indicates that the message is part of a chat history instead of a
+ few-shot example.
Returns:
A chat message that can be appended to a chat thread. The message contains two string fields:
``role`` ("user" or "assistant") and ``content`` (the message text).
@@ -183,25 +197,29 @@ def format_turn(signature: SignatureMeta, values: Dict[str, Any], role, incomple
if role == "user":
fields: Dict[str, FieldInfo] = signature.input_fields
- if incomplete:
+ if incomplete and not is_conversation_history:
content.append("This is an example of the task, though some input or output fields are not supplied.")
else:
fields: Dict[str, FieldInfo] = signature.output_fields
- if not incomplete:
+ if not incomplete and not is_conversation_history:
+ # For complete few-shot examples, ensure that the values contain all the fields.
field_names: KeysView = fields.keys()
if not set(values).issuperset(set(field_names)):
raise ValueError(f"Expected {field_names} but got {values.keys()}")
- formatted_fields = format_fields(
- role=role,
- fields_with_values={
- FieldInfoWithName(name=field_name, info=field_info): values.get(
- field_name, "Not supplied for this particular example."
+ fields_with_values = {}
+ for field_name, field_info in fields.items():
+ if is_conversation_history:
+ fields_with_values[FieldInfoWithName(name=field_name, info=field_info)] = values.get(
+ field_name, "Not supplied for this conversation history message. "
)
- for field_name, field_info in fields.items()
- },
- )
+ else:
+ fields_with_values[FieldInfoWithName(name=field_name, info=field_info)] = values.get(
+ field_name, "Not supplied for this particular example. "
+ )
+
+ formatted_fields = format_fields(role=role, fields_with_values=fields_with_values)
content.append(formatted_fields)
if role == "user":
diff --git a/dspy/adapters/types/__init__.py b/dspy/adapters/types/__init__.py
new file mode 100644
index 000000000..50b27b6e4
--- /dev/null
+++ b/dspy/adapters/types/__init__.py
@@ -0,0 +1,3 @@
+from dspy.adapters.types.history import History
+
+__all__ = ["History"]
diff --git a/dspy/adapters/types/history.py b/dspy/adapters/types/history.py
new file mode 100644
index 000000000..bfae0df9e
--- /dev/null
+++ b/dspy/adapters/types/history.py
@@ -0,0 +1,70 @@
+from typing import Any
+
+import pydantic
+
+
+class History(pydantic.BaseModel):
+ """Class representing the conversation history.
+
+ The conversation history is a list of messages, each message entity should have keys from the associated signature.
+ For example, if you have the following signature:
+
+ ```
+ class MySignature(dspy.Signature):
+ question: str = dspy.InputField()
+ history: dspy.History = dspy.InputField()
+ answer: str = dspy.OutputField()
+ ```
+
+ Then the history should be a list of dictionaries with keys "question" and "answer".
+
+ Example:
+
+ ```
+ import dspy
+
+ 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()
+
+ 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)
+ ```
+
+ Example of capturing the conversation history:
+
+ ```
+ import dspy
+
+ 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()
+
+ 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]]
+
+ model_config = {
+ "frozen": True,
+ "str_strip_whitespace": True,
+ "validate_assignment": True,
+ "extra": "forbid",
+ }
diff --git a/dspy/predict/predict.py b/dspy/predict/predict.py
index 03bc44d86..128356496 100644
--- a/dspy/predict/predict.py
+++ b/dspy/predict/predict.py
@@ -54,10 +54,10 @@ class Predict(Module, Parameter):
# `excluded_keys` are fields that go through special handling.
if name not in excluded_keys:
setattr(self, name, value)
-
+
self.signature = self.signature.load_state(state["signature"])
- if "extended_signature" in state: # legacy, up to and including 2.5, for CoT.
+ if "extended_signature" in state: # legacy, up to and including 2.5, for CoT.
raise NotImplementedError("Loading extended_signature is no longer supported in DSPy 2.6+")
return self
@@ -90,11 +90,23 @@ class Predict(Module, Parameter):
if not all(k in kwargs for k in signature.input_fields):
present = [k for k in signature.input_fields if k in kwargs]
missing = [k for k in signature.input_fields if k not in kwargs]
- print(f"WARNING: Not all input fields were provided to module. Present: {present}. Missing: {missing}.")
+
+ from dspy.adapters.types import History
+
+ if not all(signature.input_fields[k].annotation == History for k in missing):
+ # We allow missing history fields.
+ print(f"WARNING: Not all input fields were provided to module. Present: {present}. Missing: {missing}.")
import dspy
+
adapter = dspy.settings.adapter or dspy.ChatAdapter()
- completions = adapter(lm, lm_kwargs=config, signature=signature, demos=demos, inputs=kwargs)
+ completions = adapter(
+ lm,
+ lm_kwargs=config,
+ signature=signature,
+ demos=demos,
+ inputs=kwargs,
+ )
pred = Prediction.from_completions(completions, signature=signature)
@@ -113,6 +125,7 @@ class Predict(Module, Parameter):
def __repr__(self):
return f"{self.__class__.__name__}({self.signature})"
+
def serialize_object(obj):
"""
Recursively serialize a given object into a JSON-compatible format.
diff --git a/dspy/signatures/signature.py b/dspy/signatures/signature.py
index e5052c31c..0121de9ea 100644
--- a/dspy/signatures/signature.py
+++ b/dspy/signatures/signature.py
@@ -185,6 +185,17 @@ class Signature(BaseModel, metaclass=SignatureMeta):
def append(cls, name, field, type_=None) -> Type["Signature"]:
return cls.insert(-1, name, field, type_)
+ @classmethod
+ def delete(cls, name) -> Type["Signature"]:
+ fields = dict(cls.fields)
+
+ if name in fields:
+ del fields[name]
+ else:
+ raise ValueError(f"Field `{name}` not found in `{cls.__name__}`.")
+
+ return Signature(fields, cls.instructions)
+
@classmethod
def insert(cls, index: int, name: str, field, type_: Type = None) -> Type["Signature"]:
# It's possible to set the type as annotation=type in pydantic.Field(...)
diff --git a/tests/predict/test_predict.py b/tests/predict/test_predict.py
index 0ae2c000d..037a49404 100644
--- a/tests/predict/test_predict.py
+++ b/tests/predict/test_predict.py
@@ -9,6 +9,7 @@ import ujson
import dspy
from dspy import Predict, Signature
from dspy.utils.dummies import DummyLM
+from unittest.mock import patch, MagicMock, Mock
def test_initialization_with_string_signature():
@@ -87,6 +88,7 @@ def test_demos_after_dump_and_load_state():
# Demos don't need to keep the same types after saving and loading the state.
assert new_instance.demos[0]["content"] == original_instance.demos[0].content
+
def test_typed_demos_after_dump_and_load_state():
class Item(pydantic.BaseModel):
name: str
@@ -94,6 +96,7 @@ def test_typed_demos_after_dump_and_load_state():
class InventorySignature(dspy.Signature):
"""Handle inventory items and their translations."""
+
items: list[Item] = dspy.InputField()
language: str = dspy.InputField()
translated_items: list[Item] = dspy.OutputField()
@@ -102,16 +105,10 @@ def test_typed_demos_after_dump_and_load_state():
original_instance = Predict(InventorySignature)
original_instance.demos = [
dspy.Example(
- items=[
- Item(name="apple", quantity=5),
- Item(name="banana", quantity=3)
- ],
+ items=[Item(name="apple", quantity=5), Item(name="banana", quantity=3)],
language="SPANISH",
- translated_items=[
- Item(name="manzana", quantity=5),
- Item(name="plátano", quantity=3)
- ],
- total_quantity=8
+ translated_items=[Item(name="manzana", quantity=5), Item(name="plátano", quantity=3)],
+ total_quantity=8,
).with_inputs("items", "language"),
]
@@ -147,6 +144,7 @@ def test_typed_demos_after_dump_and_load_state():
assert loaded_demo["translated_items"][0]["name"] == "manzana"
assert loaded_demo["translated_items"][1]["name"] == "plátano"
+
# def test_typed_demos_after_dump_and_load_state():
# class TypedTranslateToEnglish(dspy.Signature):
# """Translate content from a language to English."""
@@ -403,3 +401,47 @@ def test_load_state_chaining():
new_instance = Predict("question -> answer").load_state(state)
assert new_instance is not None
assert new_instance.demos == original.demos
+
+
[email protected]("adapter_type", ["chat", "json"])
+def test_call_predict_with_chat_history(adapter_type):
+ class SpyLM(dspy.LM):
+ def __init__(self, *args, return_json=False, **kwargs):
+ super().__init__(*args, **kwargs)
+ self.calls = []
+ self.return_json = return_json
+
+ def __call__(self, prompt=None, messages=None, **kwargs):
+ self.calls.append({"prompt": prompt, "messages": messages, "kwargs": kwargs})
+ if self.return_json:
+ return ["{'answer':'100%'}"]
+ return ["[[ ## answer ## ]]\n100%!"]
+
+ class MySignature(dspy.Signature):
+ question: str = dspy.InputField()
+ history: dspy.History = dspy.InputField()
+ answer: str = dspy.OutputField()
+
+ program = Predict(MySignature)
+
+ if adapter_type == "chat":
+ lm = SpyLM("dummy_model")
+ dspy.settings.configure(adapter=dspy.ChatAdapter(), lm=lm)
+ else:
+ lm = SpyLM("dummy_model", return_json=True)
+ dspy.settings.configure(adapter=dspy.JSONAdapter(), lm=lm)
+
+ program(
+ question="are you sure that's correct?",
+ history=dspy.History(messages=[{"question": "what's the capital of france?", "answer": "paris"}]),
+ )
+
+ # Verify the LM was called with correct messages
+ assert len(lm.calls) == 1
+ messages = lm.calls[0]["messages"]
+
+ assert len(messages) == 4
+
+ assert "what's the capital of france?" in messages[1]["content"]
+ assert "paris" in messages[2]["content"]
+ assert "are you sure that's correct" in messages[3]["content"]