DSPy: The framework for programming—not prompting—language models
Python
Expand exact adapter format message coverage (#9792)
Maxime Rivest6fb3f96cbbe2
diff --git a/tests/adapters/conftest.py b/tests/adapters/conftest.pynew file mode 100644index 000000000..e1d089dce--- /dev/null+++ b/tests/adapters/conftest.py@@ -0,0 +1,55 @@+import dspy+++class StopAdapterCallCapture(BaseException):+ """Stop adapter execution after capturing the LM call.++ The exact-format tests assert the adapter-to-LM boundary: the messages and+ keyword arguments passed to the LM. Raising here avoids needing to craft a+ parseable LM response for every signature under test.+ """+++class CapturingLM(dspy.BaseLM):+ def __init__(self, source_lm=None):+ source_lm = source_lm or dspy.utils.DummyLM([{}])+ super().__init__(+ model=source_lm.model,+ model_type=source_lm.model_type,+ cache=source_lm.cache,+ **source_lm.kwargs,+ )+ self.source_lm = source_lm+ self.calls = []++ @property+ def supports_function_calling(self):+ return self.source_lm.supports_function_calling++ @property+ def supports_reasoning(self):+ return self.source_lm.supports_reasoning++ @property+ def supports_response_schema(self):+ return self.source_lm.supports_response_schema++ @property+ def supported_params(self):+ return self.source_lm.supported_params++ def __call__(self, messages=None, **kwargs):+ self.calls.append({"messages": messages, "kwargs": kwargs})+ raise StopAdapterCallCapture+++def format_messages_and_lm_kwargs(adapter, signature, demos, inputs, lm_kwargs=None, lm=None):+ capturing_lm = CapturingLM(lm)+ try:+ adapter(capturing_lm, dict(lm_kwargs or {}), signature, demos, inputs)+ except StopAdapterCallCapture:+ pass++ assert len(capturing_lm.calls) == 1+ call = capturing_lm.calls[0]+ return call["messages"], call["kwargs"]diff --git a/tests/adapters/test_baml_adapter.py b/tests/adapters/test_baml_adapter.pyindex 5cc148133..e8eaa9f6e 100644--- a/tests/adapters/test_baml_adapter.py+++ b/tests/adapters/test_baml_adapter.py@@ -8,6 +8,7 @@ from litellm.files.main import ModelResponseimport dspyfrom dspy.adapters.baml_adapter import COMMENT_SYMBOL, INDENTATION, BAMLAdapter+from tests.adapters.conftest import format_messages_and_lm_kwargs# Test fixtures - Pydantic models for testing@@ -51,6 +52,84 @@ class CircularModel(pydantic.BaseModel):field: "CircularModel"+def test_baml_adapter_format_exact_messages_for_simple_signature_with_demo():+ class QA(dspy.Signature):+ question: str = dspy.InputField()+ answer: str = dspy.OutputField()++ messages, lm_kwargs = format_messages_and_lm_kwargs(BAMLAdapter(), QA, [{"question": "Q1", "answer": "A1"}], {"question": "Q2"})++ expected_messages = [{"role": "system",+ "content": "Your input fields are:\n"+ "1. `question` (str):\n"+ "Your output fields are:\n"+ "1. `answer` (str):\n"+ "All interactions will be structured in the following way, with the appropriate "+ "values filled in.\n"+ "\n"+ "[[ ## question ## ]]\n"+ "{question}\n"+ "\n"+ "[[ ## answer ## ]]\n"+ "Output field `answer` should be of type: string\n"+ "\n"+ "[[ ## completed ## ]]\n"+ "In adhering to this structure, your objective is: \n"+ " Given the fields `question`, produce the fields `answer`."},+ {"role": "user", "content": "[[ ## question ## ]]\nQ1"},+ {"role": "assistant", "content": '{\n "answer": "A1"\n}'},+ {"role": "user",+ "content": "[[ ## question ## ]]\n"+ "Q2\n"+ "\n"+ "Respond with a JSON object in the following order of fields: `answer`."}]+ assert messages == expected_messages+ expected_lm_kwargs = {}+ assert lm_kwargs == expected_lm_kwargs+++def test_baml_adapter_format_exact_messages_with_nested_output():+ class BamlNested(pydantic.BaseModel):+ value: int+ tags: list[str]++ class TypedSignature(dspy.Signature):+ question: str = dspy.InputField()+ answer: BamlNested = dspy.OutputField()++ messages, lm_kwargs = format_messages_and_lm_kwargs(BAMLAdapter(), TypedSignature, [], {"question": "Q"})++ expected_messages = [{"role": "system",+ "content": "Your input fields are:\n"+ "1. `question` (str):\n"+ "Your output fields are:\n"+ "1. `answer` (BamlNested):\n"+ "All interactions will be structured in the following way, with the appropriate "+ "values filled in.\n"+ "\n"+ "[[ ## question ## ]]\n"+ "{question}\n"+ "\n"+ "[[ ## answer ## ]]\n"+ "Output field `answer` should be of type: {\n"+ " value: int,\n"+ " tags: string[],\n"+ "}\n"+ "\n"+ "[[ ## completed ## ]]\n"+ "In adhering to this structure, your objective is: \n"+ " Given the fields `question`, produce the fields `answer`."},+ {"role": "user",+ "content": "[[ ## question ## ]]\n"+ "Q\n"+ "\n"+ "Respond with a JSON object in the following order of fields: `answer` (must be "+ "formatted as a valid Python BamlNested)."}]+ assert messages == expected_messages+ expected_lm_kwargs = {}+ assert lm_kwargs == expected_lm_kwargs++def test_baml_adapter_basic_schema_generation():"""Test that BAMLAdapter generates simplified schemas for Pydantic models."""diff --git a/tests/adapters/test_chat_adapter.py b/tests/adapters/test_chat_adapter.pyindex cfa546660..17c160376 100644--- a/tests/adapters/test_chat_adapter.py+++ b/tests/adapters/test_chat_adapter.py@@ -1,3 +1,4 @@+import refrom typing import Literalfrom unittest import mock@@ -6,7 +7,8 @@ import pytestfrom litellm.utils import ChatCompletionMessageToolCall, Choices, Function, Message, ModelResponseimport dspy-from dspy.experimental import Citations+from dspy.experimental import Citations, Document+from tests.adapters.conftest import format_messages_and_lm_kwargs@pytest.mark.parametrize(@@ -106,7 +108,10 @@ def test_chat_adapter_format_exact_messages_for_simple_signature():question: str = dspy.InputField()answer: str = dspy.OutputField()- messages = dspy.ChatAdapter().format(QA, [], {"question": "What is the capital of France?"})+ messages, lm_kwargs = format_messages_and_lm_kwargs(dspy.ChatAdapter(), QA, [], {"question": "What is the capital of France?"})++ expected_lm_kwargs = {}+ assert lm_kwargs == expected_lm_kwargsassert messages == [{@@ -145,12 +150,15 @@ def test_chat_adapter_format_exact_messages_with_demo_and_typed_outputs():answers: list[str] = dspy.OutputField()scores: list[float] = dspy.OutputField()- messages = dspy.ChatAdapter().format(+ messages, lm_kwargs = format_messages_and_lm_kwargs(dspy.ChatAdapter(),MultiAnswer,demos=[{"question": "Q1", "answers": ["A1", "A2"], "scores": [0.1, 0.9]}],inputs={"question": "Q2"},)+ expected_lm_kwargs = {}+ assert lm_kwargs == expected_lm_kwargs+assert messages == [{"role": "system",@@ -197,6 +205,1264 @@ Respond with the corresponding output fields, starting with the field `[[ ## ans]+def test_chat_adapter_format_exact_messages_with_nested_pydantic_models():+ class Address(pydantic.BaseModel):+ city: str+ country: str++ class Person(pydantic.BaseModel):+ name: str+ address: Address+ tags: list[str]++ class Summary(pydantic.BaseModel):+ headline: str+ score: float++ class PydanticSignature(dspy.Signature):+ person: Person = dspy.InputField()+ summary: Summary = dspy.OutputField()++ messages, lm_kwargs = format_messages_and_lm_kwargs(dspy.ChatAdapter(),+ PydanticSignature,+ [],+ {"person": Person(name="Ada", address=Address(city="London", country="UK"), tags=["math", "code"])},+ )++ expected_messages = [{"role": "system",+ "content": 'Your input fields are:\n'+ '1. `person` (Person):\n'+ 'Your output fields are:\n'+ '1. `summary` (Summary):\n'+ 'All interactions will be structured in the following way, with the appropriate '+ 'values filled in.\n'+ '\n'+ '[[ ## person ## ]]\n'+ '{person}\n'+ '\n'+ '[[ ## summary ## ]]\n'+ '{summary} # note: the value you produce must adhere to the JSON schema: '+ '{"type": "object", "properties": {"headline": {"type": "string", "title": '+ '"Headline"}, "score": {"type": "number", "title": "Score"}}, "required": '+ '["headline", "score"], "title": "Summary"}\n'+ '\n'+ '[[ ## completed ## ]]\n'+ 'In adhering to this structure, your objective is: \n'+ ' Given the fields `person`, produce the fields `summary`.'},+ {"role": "user",+ "content": '[[ ## person ## ]]\n'+ '{"name": "Ada", "address": {"city": "London", "country": "UK"}, "tags": ["math", '+ '"code"]}\n'+ '\n'+ 'Respond with the corresponding output fields, starting with the field `[[ ## summary '+ '## ]]` (must be formatted as a valid Python Summary), and then ending with the '+ 'marker for `[[ ## completed ## ]]`.'}]+ assert messages == expected_messages+ expected_lm_kwargs = {}+ assert lm_kwargs == expected_lm_kwargs+++def test_chat_adapter_format_exact_messages_with_incomplete_demo():+ class IncompleteDemoSignature(dspy.Signature):+ question: str = dspy.InputField()+ context: str = dspy.InputField()+ answer: str = dspy.OutputField()+ confidence: float = dspy.OutputField()++ messages, lm_kwargs = format_messages_and_lm_kwargs(dspy.ChatAdapter(),+ IncompleteDemoSignature,+ [{"question": "Q1", "answer": "A1"}],+ {"question": "Q2", "context": "C2"},+ )++ expected_messages = [{"role": "system",+ "content": "Your input fields are:\n"+ "1. `question` (str): \n"+ "2. `context` (str):\n"+ "Your output fields are:\n"+ "1. `answer` (str): \n"+ "2. `confidence` (float):\n"+ "All interactions will be structured in the following way, with the appropriate "+ "values filled in.\n"+ "\n"+ "[[ ## question ## ]]\n"+ "{question}\n"+ "\n"+ "[[ ## context ## ]]\n"+ "{context}\n"+ "\n"+ "[[ ## answer ## ]]\n"+ "{answer}\n"+ "\n"+ "[[ ## confidence ## ]]\n"+ "{confidence} # note: the value you produce must be a single float value\n"+ "\n"+ "[[ ## completed ## ]]\n"+ "In adhering to this structure, your objective is: \n"+ " Given the fields `question`, `context`, produce the fields `answer`, "+ "`confidence`."},+ {"role": "user",+ "content": "This is an example of the task, though some input or output fields are not "+ "supplied.\n"+ "\n"+ "[[ ## question ## ]]\n"+ "Q1"},+ {"role": "assistant",+ "content": "[[ ## answer ## ]]\n"+ "A1\n"+ "\n"+ "[[ ## confidence ## ]]\n"+ "Not supplied for this particular example.\n"+ "\n"+ "[[ ## completed ## ]]\n"},+ {"role": "user",+ "content": "[[ ## question ## ]]\n"+ "Q2\n"+ "\n"+ "[[ ## context ## ]]\n"+ "C2\n"+ "\n"+ "Respond with the corresponding output fields, starting with the field `[[ ## answer "+ "## ]]`, then `[[ ## confidence ## ]]` (must be formatted as a valid Python float), "+ "and then ending with the marker for `[[ ## completed ## ]]`."}]+ assert messages == expected_messages+ expected_lm_kwargs = {}+ assert lm_kwargs == expected_lm_kwargs+++def test_chat_adapter_format_exact_messages_with_history():+ class HistorySignature(dspy.Signature):+ history: dspy.History = dspy.InputField()+ question: str = dspy.InputField()+ answer: str = dspy.OutputField()++ history = dspy.History(+ messages=[+ {"question": "What is 1+1?", "answer": "2"},+ {"question": "What is 2+2?", "answer": "4"},+ ]+ )+ messages, lm_kwargs = format_messages_and_lm_kwargs(dspy.ChatAdapter(),+ HistorySignature,+ [],+ {"history": history, "question": "What is 3+3?"},+ )++ expected_messages = [{"role": "system",+ "content": "Your input fields are:\n"+ "1. `history` (History): \n"+ "2. `question` (str):\n"+ "Your output fields are:\n"+ "1. `answer` (str):\n"+ "All interactions will be structured in the following way, with the appropriate "+ "values filled in.\n"+ "\n"+ "[[ ## history ## ]]\n"+ "{history}\n"+ "\n"+ "[[ ## question ## ]]\n"+ "{question}\n"+ "\n"+ "[[ ## answer ## ]]\n"+ "{answer}\n"+ "\n"+ "[[ ## completed ## ]]\n"+ "In adhering to this structure, your objective is: \n"+ " Given the fields `history`, `question`, produce the fields `answer`."},+ {"role": "user", "content": "[[ ## question ## ]]\nWhat is 1+1?"},+ {"role": "assistant", "content": "[[ ## answer ## ]]\n2\n\n[[ ## completed ## ]]\n"},+ {"role": "user", "content": "[[ ## question ## ]]\nWhat is 2+2?"},+ {"role": "assistant", "content": "[[ ## answer ## ]]\n4\n\n[[ ## completed ## ]]\n"},+ {"role": "user",+ "content": "[[ ## question ## ]]\n"+ "What is 3+3?\n"+ "\n"+ "Respond with the corresponding output fields, starting with the field `[[ ## answer "+ "## ]]`, and then ending with the marker for `[[ ## completed ## ]]`."}]+ assert messages == expected_messages+ expected_lm_kwargs = {}+ assert lm_kwargs == expected_lm_kwargs+++def test_chat_adapter_format_exact_messages_with_list_value_for_string_input():+ class ListAsStringSignature(dspy.Signature):+ context: str = dspy.InputField()+ answer: str = dspy.OutputField()++ messages, lm_kwargs = format_messages_and_lm_kwargs(dspy.ChatAdapter(), ListAsStringSignature, [], {"context": ["alpha", "beta"]})++ expected_messages = [{"role": "system",+ "content": "Your input fields are:\n"+ "1. `context` (str):\n"+ "Your output fields are:\n"+ "1. `answer` (str):\n"+ "All interactions will be structured in the following way, with the appropriate "+ "values filled in.\n"+ "\n"+ "[[ ## context ## ]]\n"+ "{context}\n"+ "\n"+ "[[ ## answer ## ]]\n"+ "{answer}\n"+ "\n"+ "[[ ## completed ## ]]\n"+ "In adhering to this structure, your objective is: \n"+ " Given the fields `context`, produce the fields `answer`."},+ {"role": "user",+ "content": "[[ ## context ## ]]\n"+ "[1] «alpha»\n"+ "[2] «beta»\n"+ "\n"+ "Respond with the corresponding output fields, starting with the field `[[ ## answer "+ "## ]]`, and then ending with the marker for `[[ ## completed ## ]]`."}]+ assert messages == expected_messages+ expected_lm_kwargs = {}+ assert lm_kwargs == expected_lm_kwargs+++def test_chat_adapter_format_exact_messages_with_literal_output():+ class LiteralSignature(dspy.Signature):+ question: str = dspy.InputField()+ verdict: Literal["yes", "no"] = dspy.OutputField()++ messages, lm_kwargs = format_messages_and_lm_kwargs(dspy.ChatAdapter(), LiteralSignature, [], {"question": "Is the sky blue?"})++ expected_messages = [{"role": "system",+ "content": "Your input fields are:\n"+ "1. `question` (str):\n"+ "Your output fields are:\n"+ "1. `verdict` (Literal['yes', 'no']):\n"+ "All interactions will be structured in the following way, with the appropriate "+ "values filled in.\n"+ "\n"+ "[[ ## question ## ]]\n"+ "{question}\n"+ "\n"+ "[[ ## verdict ## ]]\n"+ "{verdict} # note: the value you produce must exactly match (no extra "+ "characters) one of: yes; no\n"+ "\n"+ "[[ ## completed ## ]]\n"+ "In adhering to this structure, your objective is: \n"+ " Given the fields `question`, produce the fields `verdict`."},+ {"role": "user",+ "content": "[[ ## question ## ]]\n"+ "Is the sky blue?\n"+ "\n"+ "Respond with the corresponding output fields, starting with the field `[[ ## verdict "+ "## ]]` (must be formatted as a valid Python Literal['yes', 'no']), and then ending "+ "with the marker for `[[ ## completed ## ]]`."}]+ assert messages == expected_messages+ expected_lm_kwargs = {}+ assert lm_kwargs == expected_lm_kwargs+++def test_chat_adapter_format_exact_messages_with_multimodal_custom_type_inputs():+ class CustomTypeSignature(dspy.Signature):+ image: dspy.Image = dspy.InputField()+ audio: dspy.Audio = dspy.InputField()+ file: dspy.File = dspy.InputField()+ document: Document = dspy.InputField()+ answer: str = dspy.OutputField()++ messages, lm_kwargs = format_messages_and_lm_kwargs(dspy.ChatAdapter(),+ CustomTypeSignature,+ [],+ {+ "image": dspy.Image("https://example.com/cat.png"),+ "audio": dspy.Audio(data="QUJD", audio_format="wav"),+ "file": dspy.File.from_file_id("file-123", filename="notes.txt"),+ "document": Document(data="Alpha beta", title="Doc"),+ },+ )++ expected_messages = [{"role": "system",+ "content": "Your input fields are:\n"+ "1. `image` (Image): \n"+ "2. `audio` (Audio): \n"+ "3. `file` (File): \n"+ "4. `document` (Document): \n"+ " Type description of Document: A document containing text content that can be "+ "referenced and cited. Include the full text content and optionally a title for "+ "proper referencing.\n"+ "Your output fields are:\n"+ "1. `answer` (str):\n"+ "All interactions will be structured in the following way, with the appropriate "+ "values filled in.\n"+ "\n"+ "[[ ## image ## ]]\n"+ "{image}\n"+ "\n"+ "[[ ## audio ## ]]\n"+ "{audio}\n"+ "\n"+ "[[ ## file ## ]]\n"+ "{file}\n"+ "\n"+ "[[ ## document ## ]]\n"+ "{document}\n"+ "\n"+ "[[ ## answer ## ]]\n"+ "{answer}\n"+ "\n"+ "[[ ## completed ## ]]\n"+ "In adhering to this structure, your objective is: \n"+ " Given the fields `image`, `audio`, `file`, `document`, produce the fields "+ "`answer`."},+ {"role": "user",+ "content": [{"type": "text", "text": "[[ ## image ## ]]\n"},+ {"type": "image_url", "image_url": {"url": "https://example.com/cat.png"}},+ {"type": "text", "text": "\n\n[[ ## audio ## ]]\n"},+ {"type": "input_audio", "input_audio": {"data": "QUJD", "format": "wav"}},+ {"type": "text", "text": "\n\n[[ ## file ## ]]\n"},+ {"type": "file", "file": {"file_id": "file-123", "filename": "notes.txt"}},+ {"type": "text", "text": "\n\n[[ ## document ## ]]\n"},+ {"type": "document",+ "source": {"type": "text", "media_type": "text/plain", "data": "Alpha beta"},+ "citations": {"enabled": True},+ "title": "Doc"},+ {"type": "text",+ "text": "\n"+ "\n"+ "Respond with the corresponding output fields, starting with the field `[[ "+ "## answer ## ]]`, and then ending with the marker for `[[ ## completed ## "+ "]]`."}]}]+ assert messages == expected_messages+ expected_lm_kwargs = {}+ assert lm_kwargs == expected_lm_kwargs+++def test_chat_adapter_format_exact_messages_with_history_demo_pydantic_tools_and_image():+ def search(query: str, k: int = 3) -> str:+ """Search for documents."""+ return query++ class Location(pydantic.BaseModel):+ city: str+ country: str++ class Profile(pydantic.BaseModel):+ name: str+ location: Location+ interests: list[str]++ class AnswerCard(pydantic.BaseModel):+ answer: str+ sources: list[str]++ class RichRenderingSignature(dspy.Signature):+ """Answer using all supplied context."""++ history: dspy.History = dspy.InputField()+ image: dspy.Image = dspy.InputField()+ tools: list[dspy.Tool] = dspy.InputField()+ profile: Profile = dspy.InputField()+ question: str = dspy.InputField()+ answer: AnswerCard = dspy.OutputField()++ tool = dspy.Tool(search)+ demo_profile = Profile(+ name="Ada",+ location=Location(city="London", country="UK"),+ interests=["math", "machines"],+ )+ current_profile = Profile(+ name="Grace",+ location=Location(city="Arlington", country="USA"),+ interests=["compilers", "navy"],+ )+ history = dspy.History(+ messages=[+ {+ "profile": demo_profile,+ "question": "Who is Ada?",+ "answer": AnswerCard(answer="Ada is a mathematician.", sources=["memory"]),+ }+ ]+ )+ messages, lm_kwargs = format_messages_and_lm_kwargs(dspy.ChatAdapter(),+ RichRenderingSignature,+ demos=[+ {+ "image": dspy.Image("https://example.com/demo.png"),+ "tools": [tool],+ "profile": demo_profile,+ "question": "What should we mention?",+ "answer": AnswerCard(answer="Mention analytical engines.", sources=["demo"]),+ }+ ],+ inputs={+ "history": history,+ "image": dspy.Image("https://example.com/current.png"),+ "tools": [tool],+ "profile": current_profile,+ "question": "What should the answer include?",+ },+ )++ expected_messages = [{"role": "system",+ "content": 'Your input fields are:\n'+ '1. `history` (History): \n'+ '2. `image` (Image): \n'+ '3. `tools` (list[Tool]): \n'+ '4. `profile` (Profile): \n'+ '5. `question` (str):\n'+ 'Your output fields are:\n'+ '1. `answer` (AnswerCard):\n'+ 'All interactions will be structured in the following way, with the appropriate '+ 'values filled in.\n'+ '\n'+ '[[ ## history ## ]]\n'+ '{history}\n'+ '\n'+ '[[ ## image ## ]]\n'+ '{image}\n'+ '\n'+ '[[ ## tools ## ]]\n'+ '{tools}\n'+ '\n'+ '[[ ## profile ## ]]\n'+ '{profile}\n'+ '\n'+ '[[ ## question ## ]]\n'+ '{question}\n'+ '\n'+ '[[ ## answer ## ]]\n'+ '{answer} # note: the value you produce must adhere to the JSON schema: '+ '{"type": "object", "properties": {"answer": {"type": "string", "title": "Answer"}, '+ '"sources": {"type": "array", "items": {"type": "string"}, "title": "Sources"}}, '+ '"required": ["answer", "sources"], "title": "AnswerCard"}\n'+ '\n'+ '[[ ## completed ## ]]\n'+ 'In adhering to this structure, your objective is: \n'+ ' Answer using all supplied context.'},+ {"role": "user",+ "content": [{"type": "text",+ "text": "This is an example of the task, though some input or output fields are not "+ "supplied.\n"+ "\n"+ "[[ ## image ## ]]\n"},+ {"type": "image_url", "image_url": {"url": "https://example.com/demo.png"}},+ {"type": "text",+ "text": '\n'+ '\n'+ '[[ ## tools ## ]]\n'+ '["search, whose description is <desc>Search for documents.</desc>. It '+ "takes arguments {'query': {'type': 'string'}, 'k': {'type': 'integer', "+ '\'default\': 3}}."]\n'+ '\n'+ '[[ ## profile ## ]]\n'+ '{"name": "Ada", "location": {"city": "London", "country": "UK"}, '+ '"interests": ["math", "machines"]}\n'+ '\n'+ '[[ ## question ## ]]\n'+ 'What should we mention?'}]},+ {"role": "assistant",+ "content": '[[ ## answer ## ]]\n'+ '{"answer": "Mention analytical engines.", "sources": ["demo"]}\n'+ '\n'+ '[[ ## completed ## ]]\n'},+ {"role": "user",+ "content": '[[ ## profile ## ]]\n'+ '{"name": "Ada", "location": {"city": "London", "country": "UK"}, "interests": '+ '["math", "machines"]}\n'+ '\n'+ '[[ ## question ## ]]\n'+ 'Who is Ada?'},+ {"role": "assistant",+ "content": '[[ ## answer ## ]]\n'+ '{"answer": "Ada is a mathematician.", "sources": ["memory"]}\n'+ '\n'+ '[[ ## completed ## ]]\n'},+ {"role": "user",+ "content": [{"type": "text", "text": "[[ ## image ## ]]\n"},+ {"type": "image_url", "image_url": {"url": "https://example.com/current.png"}},+ {"type": "text",+ "text": '\n'+ '\n'+ '[[ ## tools ## ]]\n'+ '["search, whose description is <desc>Search for documents.</desc>. It '+ "takes arguments {'query': {'type': 'string'}, 'k': {'type': 'integer', "+ '\'default\': 3}}."]\n'+ '\n'+ '[[ ## profile ## ]]\n'+ '{"name": "Grace", "location": {"city": "Arlington", "country": "USA"}, '+ '"interests": ["compilers", "navy"]}\n'+ '\n'+ '[[ ## question ## ]]\n'+ 'What should the answer include?\n'+ '\n'+ 'Respond with the corresponding output fields, starting with the field `[[ '+ '## answer ## ]]` (must be formatted as a valid Python AnswerCard), and '+ 'then ending with the marker for `[[ ## completed ## ]]`.'}]}]+ assert messages == expected_messages+ expected_lm_kwargs = {}+ assert lm_kwargs == expected_lm_kwargs++def test_chat_adapter_format_exact_messages_with_base_custom_type_input():+ class Event(dspy.Type):+ label: str++ def format(self):+ return [{"type": "event", "event": {"label": self.label}}]++ @classmethod+ def description(cls):+ return "An event block."++ class EventSignature(dspy.Signature):+ event: Event = dspy.InputField()+ answer: str = dspy.OutputField()++ messages, lm_kwargs = format_messages_and_lm_kwargs(dspy.ChatAdapter(), EventSignature, [], {"event": Event(label="launch")})++ expected_messages = [{"role": "system",+ "content": "Your input fields are:\n"+ "1. `event` (Event): \n"+ " Type description of Event: An event block.\n"+ "Your output fields are:\n"+ "1. `answer` (str):\n"+ "All interactions will be structured in the following way, with the appropriate "+ "values filled in.\n"+ "\n"+ "[[ ## event ## ]]\n"+ "{event}\n"+ "\n"+ "[[ ## answer ## ]]\n"+ "{answer}\n"+ "\n"+ "[[ ## completed ## ]]\n"+ "In adhering to this structure, your objective is: \n"+ " Given the fields `event`, produce the fields `answer`."},+ {"role": "user",+ "content": [{"type": "text", "text": "[[ ## event ## ]]\n"},+ {"type": "event", "event": {"label": "launch"}},+ {"type": "text",+ "text": "\n"+ "\n"+ "Respond with the corresponding output fields, starting with the field `[[ "+ "## answer ## ]]`, and then ending with the marker for `[[ ## completed ## "+ "]]`."}]}]+ assert messages == expected_messages+ expected_lm_kwargs = {}+ assert lm_kwargs == expected_lm_kwargs++def test_chat_adapter_format_exact_messages_with_citations_output_demo():+ class CitationSignature(dspy.Signature):+ question: str = dspy.InputField()+ citations: Citations = dspy.OutputField()++ messages, lm_kwargs = format_messages_and_lm_kwargs(dspy.ChatAdapter(),+ CitationSignature,+ [+ {+ "question": "Q1",+ "citations": Citations.from_dict_list(+ [+ {+ "cited_text": "alpha",+ "document_index": 0,+ "start_char_index": 0,+ "end_char_index": 5,+ }+ ]+ ),+ }+ ],+ {"question": "Q2"},+ )++ expected_messages = [{"role": "system",+ "content": 'Your input fields are:\n'+ '1. `question` (str):\n'+ 'Your output fields are:\n'+ '1. `citations` (Citations): \n'+ ' Type description of Citations: Citations with quoted text and source references. '+ 'Include the exact text being cited and information about its source.\n'+ 'All interactions will be structured in the following way, with the appropriate '+ 'values filled in.\n'+ '\n'+ '[[ ## question ## ]]\n'+ '{question}\n'+ '\n'+ '[[ ## citations ## ]]\n'+ '{citations} # note: the value you produce must adhere to the JSON schema: '+ '{"type": "object", "$defs": {"Citation": {"type": "object", "description": '+ '"Individual citation with character location information.", "properties": {"type": '+ '{"type": "string", "default": "char_location", "title": "Type"}, "cited_text": '+ '{"type": "string", "title": "Cited Text"}, "document_index": {"type": "integer", '+ '"title": "Document Index"}, "document_title": {"anyOf": [{"type": "string"}, '+ '{"type": "null"}], "default": null, "title": "Document Title"}, "end_char_index": '+ '{"type": "integer", "title": "End Char Index"}, "start_char_index": {"type": '+ '"integer", "title": "Start Char Index"}, "supported_text": {"anyOf": [{"type": '+ '"string"}, {"type": "null"}], "default": null, "title": "Supported Text"}}, '+ '"required": ["cited_text", "document_index", "start_char_index", "end_char_index"], '+ '"title": "Citation"}}, "description": "Experimental: This class may change or be '+ 'removed in a future release without warning (introduced in v3.0.4).\\n\\nCitations '+ 'extracted from an LM response with source references.\\n\\n This type represents '+ 'citations returned by language models that support\\n citation extraction, '+ "particularly Anthropic's Citations API through LiteLLM.\\n Citations include the "+ 'quoted text and source information.\\n\\n Examples:\\n ```python\\n '+ 'import os\\n import dspy\\n from dspy.signatures import '+ 'Signature\\n from dspy.experimental import Citations, Document\\n '+ 'os.environ[\\"ANTHROPIC_API_KEY\\"] = \\"YOUR_ANTHROPIC_API_KEY\\"\\n\\n '+ "class AnswerWithSources(Signature):\\n '''Answer questions using provided "+ "documents with citations.'''\\n documents: list[Document] = "+ 'dspy.InputField()\\n question: str = dspy.InputField()\\n '+ 'answer: str = dspy.OutputField()\\n citations: Citations = '+ 'dspy.OutputField()\\n\\n # Create documents to provide as sources\\n '+ 'docs = [\\n Document(\\n data=\\"The Earth orbits the Sun '+ 'in an elliptical path.\\",\\n title=\\"Basic Astronomy '+ 'Facts\\"\\n ),\\n Document(\\n data=\\"Water '+ 'boils at 100°C at standard atmospheric pressure.\\",\\n '+ 'title=\\"Physics Fundamentals\\",\\n metadata={\\"author\\": \\"Dr. '+ 'Smith\\", \\"year\\": 2023}\\n )\\n ]\\n\\n # Use with a '+ 'model that supports citations like Claude\\n lm = '+ 'dspy.LM(\\"anthropic/claude-opus-4-1-20250805\\")\\n predictor = '+ 'dspy.Predict(AnswerWithSources)\\n result = predictor(documents=docs, '+ 'question=\\"What temperature does water boil?\\", lm=lm)\\n\\n for citation '+ 'in result.citations.citations:\\n print(citation.format())\\n '+ '```\\n ", "properties": {"citations": {"type": "array", "items": {"$ref": '+ '"#/$defs/Citation"}, "title": "Citations"}}, "required": ["citations"], "title": '+ '"Citations"}\n'+ '\n'+ '[[ ## completed ## ]]\n'+ 'In adhering to this structure, your objective is: \n'+ ' Given the fields `question`, produce the fields `citations`.'},+ {"role": "user", "content": "[[ ## question ## ]]\nQ1"},+ {"role": "assistant",+ "content": '[[ ## citations ## ]]\n'+ '<<CUSTOM-TYPE-START-IDENTIFIER>>[{"type": "char_location", "cited_text": "alpha", '+ '"document_index": 0, "start_char_index": 0, "end_char_index": '+ '5}]<<CUSTOM-TYPE-END-IDENTIFIER>>\n'+ '\n'+ '[[ ## completed ## ]]\n'},+ {"role": "user",+ "content": "[[ ## question ## ]]\n"+ "Q2\n"+ "\n"+ "Respond with the corresponding output fields, starting with the field `[[ ## "+ "citations ## ]]` (must be formatted as a valid Python Citations), and then ending "+ "with the marker for `[[ ## completed ## ]]`."}]+ def normalize_citations_schema_description(content):+ return re.sub(+ r'"description": ".*?", "properties":',+ '"description": "<CITATIONS_SCHEMA_DESCRIPTION>", "properties":',+ content,+ )++ messages[0]["content"] = normalize_citations_schema_description(messages[0]["content"])+ expected_messages[0]["content"] = normalize_citations_schema_description(expected_messages[0]["content"])++ assert messages == expected_messages+ expected_lm_kwargs = {}+ assert lm_kwargs == expected_lm_kwargs++def test_chat_adapter_format_exact_messages_and_lm_kwargs_with_native_citations():+ class AnthropicLM(dspy.utils.DummyLM):+ def __init__(self):+ super().__init__([{}])+ self.model = "anthropic/claude-3-5-sonnet"++ class CitationSignature(dspy.Signature):+ question: str = dspy.InputField()+ answer: str = dspy.OutputField()+ citations: Citations = dspy.OutputField()++ messages, lm_kwargs = format_messages_and_lm_kwargs(+ dspy.ChatAdapter(),+ CitationSignature,+ [],+ {"question": "Q?"},+ lm=AnthropicLM(),+ )++ expected_messages = [{"role": "system",+ "content": "Your input fields are:\n"+ "1. `question` (str):\n"+ "Your output fields are:\n"+ "1. `answer` (str):\n"+ "All interactions will be structured in the following way, with the appropriate "+ "values filled in.\n"+ "\n"+ "[[ ## question ## ]]\n"+ "{question}\n"+ "\n"+ "[[ ## answer ## ]]\n"+ "{answer}\n"+ "\n"+ "[[ ## completed ## ]]\n"+ "In adhering to this structure, your objective is: \n"+ " Given the fields `question`, produce the fields `answer`, `citations`."},+ {"role": "user",+ "content": "[[ ## question ## ]]\n"+ "Q?\n"+ "\n"+ "Respond with the corresponding output fields, starting with the field `[[ ## answer "+ "## ]]`, and then ending with the marker for `[[ ## completed ## ]]`."}]+ assert messages == expected_messages+ expected_lm_kwargs = {}+ assert lm_kwargs == expected_lm_kwargs++def test_chat_adapter_format_exact_messages_preserves_passthrough_lm_kwargs():+ class PassthroughSignature(dspy.Signature):+ question: str = dspy.InputField()+ answer: str = dspy.OutputField()++ messages, lm_kwargs = format_messages_and_lm_kwargs(+ dspy.ChatAdapter(),+ PassthroughSignature,+ [],+ {"question": "Q?"},+ lm_kwargs={"temperature": 0.7, "max_tokens": 42, "stream": True, "cache": False},+ )++ expected_messages = [{"role": "system",+ "content": "Your input fields are:\n"+ "1. `question` (str):\n"+ "Your output fields are:\n"+ "1. `answer` (str):\n"+ "All interactions will be structured in the following way, with the appropriate "+ "values filled in.\n"+ "\n"+ "[[ ## question ## ]]\n"+ "{question}\n"+ "\n"+ "[[ ## answer ## ]]\n"+ "{answer}\n"+ "\n"+ "[[ ## completed ## ]]\n"+ "In adhering to this structure, your objective is: \n"+ " Given the fields `question`, produce the fields `answer`."},+ {"role": "user",+ "content": "[[ ## question ## ]]\n"+ "Q?\n"+ "\n"+ "Respond with the corresponding output fields, starting with the field `[[ ## answer "+ "## ]]`, and then ending with the marker for `[[ ## completed ## ]]`."}]+ assert messages == expected_messages+ expected_lm_kwargs = {"temperature": 0.7, "max_tokens": 42, "stream": True, "cache": False}+ assert lm_kwargs == expected_lm_kwargs++def test_chat_adapter_format_exact_messages_and_lm_kwargs_with_native_reasoning():+ class ReasoningLM(dspy.utils.DummyLM):+ @property+ def supports_reasoning(self):+ return True++ class NativeReasoningSignature(dspy.Signature):+ question: str = dspy.InputField()+ reasoning: dspy.Reasoning = dspy.OutputField()+ answer: str = dspy.OutputField()++ messages, lm_kwargs = format_messages_and_lm_kwargs(+ dspy.ChatAdapter(),+ NativeReasoningSignature,+ [],+ {"question": "Q?"},+ lm=ReasoningLM([{}]),+ )++ expected_messages = [{"role": "system",+ "content": "Your input fields are:\n"+ "1. `question` (str):\n"+ "Your output fields are:\n"+ "1. `answer` (str):\n"+ "All interactions will be structured in the following way, with the appropriate "+ "values filled in.\n"+ "\n"+ "[[ ## question ## ]]\n"+ "{question}\n"+ "\n"+ "[[ ## answer ## ]]\n"+ "{answer}\n"+ "\n"+ "[[ ## completed ## ]]\n"+ "In adhering to this structure, your objective is: \n"+ " Given the fields `question`, produce the fields `reasoning`, `answer`."},+ {"role": "user",+ "content": "[[ ## question ## ]]\n"+ "Q?\n"+ "\n"+ "Respond with the corresponding output fields, starting with the field `[[ ## answer "+ "## ]]`, and then ending with the marker for `[[ ## completed ## ]]`."}]+ assert messages == expected_messages+ expected_lm_kwargs = {"reasoning_effort": "low"}+ assert lm_kwargs == expected_lm_kwargs++def test_chat_adapter_format_exact_messages_with_reasoning_and_code_outputs():+ python_code = dspy.Code["python"]++ class CodeSignature(dspy.Signature):+ question: str = dspy.InputField()+ reasoning: dspy.Reasoning = dspy.OutputField()+ code: python_code = dspy.OutputField()++ messages, lm_kwargs = format_messages_and_lm_kwargs(dspy.ChatAdapter(),+ CodeSignature,+ [{"question": "Q1", "reasoning": dspy.Reasoning(content="Think"), "code": python_code(code="print('hi')")}],+ {"question": "Q2"},+ )++ expected_messages = [{"role": "system",+ "content": "Your input fields are:\n"+ "1. `question` (str):\n"+ "Your output fields are:\n"+ "1. `reasoning` (str): \n"+ "2. `code` (Code_python): \n"+ " Type description of Code_python: Code represented in a string, specified in the "+ "`code` field. If this is an output field, the code field should follow the markdown "+ "code block format, e.g. \n"+ "```python\n"+ "{code}\n"+ "```\n"+ "Programming language: python\n"+ "All interactions will be structured in the following way, with the appropriate "+ "values filled in.\n"+ "\n"+ "[[ ## question ## ]]\n"+ "{question}\n"+ "\n"+ "[[ ## reasoning ## ]]\n"+ "{reasoning}\n"+ "\n"+ "[[ ## code ## ]]\n"+ "{code}\n"+ "\n"+ "[[ ## completed ## ]]\n"+ "In adhering to this structure, your objective is: \n"+ " Given the fields `question`, produce the fields `reasoning`, `code`."},+ {"role": "user", "content": "[[ ## question ## ]]\nQ1"},+ {"role": "assistant",+ "content": "[[ ## reasoning ## ]]\n"+ "Think\n"+ "\n"+ "[[ ## code ## ]]\n"+ "print('hi')\n"+ "\n"+ "[[ ## completed ## ]]\n"},+ {"role": "user",+ "content": "[[ ## question ## ]]\n"+ "Q2\n"+ "\n"+ "Respond with the corresponding output fields, starting with the field `[[ ## "+ "reasoning ## ]]` (must be formatted as a valid Python str), then `[[ ## code ## ]]` "+ "(must be formatted as a valid Python Code_python), and then ending with the marker "+ "for `[[ ## completed ## ]]`."}]+ assert messages == expected_messages+ expected_lm_kwargs = {}+ assert lm_kwargs == expected_lm_kwargs+++def test_chat_adapter_format_exact_messages_and_lm_kwargs_with_native_tool_calling():+ class FunctionCallingLM(dspy.utils.DummyLM):+ @property+ def supports_function_calling(self):+ return True++ def search(query: str, k: int = 3) -> str:+ """Search for documents."""+ return query++ class NativeToolSignature(dspy.Signature):+ question: str = dspy.InputField()+ tools: list[dspy.Tool] = dspy.InputField()+ tool_calls: dspy.ToolCalls = dspy.OutputField()++ messages, lm_kwargs = format_messages_and_lm_kwargs(+ dspy.ChatAdapter(use_native_function_calling=True),+ NativeToolSignature,+ [],+ {"question": "Q?", "tools": [dspy.Tool(search)]},+ lm=FunctionCallingLM([{}]),+ )++ expected_messages = [{"role": "system",+ "content": "Your input fields are:\n"+ "1. `question` (str):\n"+ "Your output fields are:\n"+ "\n"+ "All interactions will be structured in the following way, with the appropriate "+ "values filled in.\n"+ "\n"+ "[[ ## question ## ]]\n"+ "{question}\n"+ "\n"+ "\n"+ "\n"+ "[[ ## completed ## ]]\n"+ "In adhering to this structure, your objective is: \n"+ " Given the fields `question`, `tools`, produce the fields `tool_calls`."},+ {"role": "user",+ "content": "[[ ## question ## ]]\n"+ "Q?\n"+ "\n"+ "Respond with the corresponding output fields, starting with the field , and then "+ "ending with the marker for `[[ ## completed ## ]]`."}]+ assert messages == expected_messages+ expected_lm_kwargs = {"tools": [{"type": "function",+ "function": {"name": "search",+ "description": "Search for documents.",+ "parameters": {"type": "object",+ "properties": {"query": {"type": "string"},+ "k": {"type": "integer", "default": 3}},+ "required": ["query", "k"]}}}]}+ assert lm_kwargs == expected_lm_kwargs++def test_chat_adapter_format_exact_messages_with_tool_input():+ def search(query: str, k: int = 3) -> str:+ """Search for documents."""+ return query++ class ToolSignature(dspy.Signature):+ question: str = dspy.InputField()+ tools: list[dspy.Tool] = dspy.InputField()+ answer: str = dspy.OutputField()++ messages, lm_kwargs = format_messages_and_lm_kwargs(dspy.ChatAdapter(),+ ToolSignature,+ [],+ {"question": "Q?", "tools": [dspy.Tool(search)]},+ )++ expected_messages = [{"role": "system",+ "content": "Your input fields are:\n"+ "1. `question` (str): \n"+ "2. `tools` (list[Tool]):\n"+ "Your output fields are:\n"+ "1. `answer` (str):\n"+ "All interactions will be structured in the following way, with the appropriate "+ "values filled in.\n"+ "\n"+ "[[ ## question ## ]]\n"+ "{question}\n"+ "\n"+ "[[ ## tools ## ]]\n"+ "{tools}\n"+ "\n"+ "[[ ## answer ## ]]\n"+ "{answer}\n"+ "\n"+ "[[ ## completed ## ]]\n"+ "In adhering to this structure, your objective is: \n"+ " Given the fields `question`, `tools`, produce the fields `answer`."},+ {"role": "user",+ "content": '[[ ## question ## ]]\n'+ 'Q?\n'+ '\n'+ '[[ ## tools ## ]]\n'+ '["search, whose description is <desc>Search for documents.</desc>. It takes '+ "arguments {'query': {'type': 'string'}, 'k': {'type': 'integer', 'default': "+ '3}}."]\n'+ '\n'+ 'Respond with the corresponding output fields, starting with the field `[[ ## answer '+ '## ]]`, and then ending with the marker for `[[ ## completed ## ]]`.'}]+ assert messages == expected_messages+ expected_lm_kwargs = {}+ assert lm_kwargs == expected_lm_kwargs+++def test_chat_adapter_format_exact_messages_kitchen_sink():+ def search(query: str, k: int = 3) -> str:+ """Search for documents."""+ return query++ class Event(dspy.Type):+ label: str++ def format(self):+ return [{"type": "event", "event": {"label": self.label}}]++ @classmethod+ def description(cls):+ return "An event block."++ class Location(pydantic.BaseModel):+ city: str+ country: str++ class Profile(pydantic.BaseModel):+ name: str+ location: Location+ interests: list[str]++ class AnswerCard(pydantic.BaseModel):+ answer: str+ sources: list[str]++ class KitchenSinkSignature(dspy.Signature):+ """Answer carefully using every available signal."""++ history: dspy.History = dspy.InputField()+ image: dspy.Image = dspy.InputField()+ audio: dspy.Audio = dspy.InputField()+ file: dspy.File = dspy.InputField()+ document: Document = dspy.InputField()+ event: Event = dspy.InputField()+ tools: list[dspy.Tool] = dspy.InputField()+ profile: Profile = dspy.InputField()+ context: str = dspy.InputField()+ question: str = dspy.InputField()+ answer: AnswerCard = dspy.OutputField()+ verdict: Literal["yes", "no"] = dspy.OutputField()+ confidence: float = dspy.OutputField()++ tool = dspy.Tool(search)+ demo_profile = Profile(+ name="Ada",+ location=Location(city="London", country="UK"),+ interests=["math", "machines"],+ )+ current_profile = Profile(+ name="Grace",+ location=Location(city="Arlington", country="USA"),+ interests=["compilers", "navy"],+ )+ history = dspy.History(+ messages=[+ {+ "profile": demo_profile,+ "context": ["old note", "older note"],+ "question": "Who is Ada?",+ "answer": AnswerCard(answer="Ada is a mathematician.", sources=["memory"]),+ "verdict": "yes",+ "confidence": 0.8,+ }+ ]+ )+ messages, lm_kwargs = format_messages_and_lm_kwargs(dspy.ChatAdapter(),+ KitchenSinkSignature,+ demos=[+ {+ "image": dspy.Image("https://example.com/demo.png"),+ "audio": dspy.Audio(data="REVNTw==", audio_format="wav"),+ "file": dspy.File.from_file_id("file-demo", filename="demo.txt"),+ "document": Document(data="Demo document", title="Demo Doc"),+ "event": Event(label="demo-event"),+ "tools": [tool],+ "profile": demo_profile,+ "context": ["demo context one", "demo context two"],+ "question": "What should we mention?",+ "answer": AnswerCard(answer="Mention analytical engines.", sources=["demo"]),+ "verdict": "yes",+ "confidence": 0.9,+ },+ {+ "question": "Incomplete example question",+ "answer": AnswerCard(answer="Partial answer.", sources=["partial"]),+ },+ ],+ inputs={+ "history": history,+ "image": dspy.Image("https://example.com/current.png"),+ "audio": dspy.Audio(data="Q1VSUkVOVA==", audio_format="wav"),+ "file": dspy.File.from_file_id("file-current", filename="current.txt"),+ "document": Document(data="Current document", title="Current Doc"),+ "event": Event(label="current-event"),+ "tools": [tool],+ "profile": current_profile,+ "context": ["current context one", "current context two"],+ "question": "What should the answer include?",+ },+ )++ expected_messages = [{"role": "system",+ "content": 'Your input fields are:\n'+ '1. `history` (History): \n'+ '2. `image` (Image): \n'+ '3. `audio` (Audio): \n'+ '4. `file` (File): \n'+ '5. `document` (Document): \n'+ ' Type description of Document: A document containing text content that can be '+ 'referenced and cited. Include the full text content and optionally a title for '+ 'proper referencing.\n'+ '6. `event` (Event): \n'+ ' Type description of Event: An event block.\n'+ '7. `tools` (list[Tool]): \n'+ '8. `profile` (Profile): \n'+ '9. `context` (str): \n'+ '10. `question` (str):\n'+ 'Your output fields are:\n'+ '1. `answer` (AnswerCard): \n'+ "2. `verdict` (Literal['yes', 'no']): \n"+ '3. `confidence` (float):\n'+ 'All interactions will be structured in the following way, with the appropriate '+ 'values filled in.\n'+ '\n'+ '[[ ## history ## ]]\n'+ '{history}\n'+ '\n'+ '[[ ## image ## ]]\n'+ '{image}\n'+ '\n'+ '[[ ## audio ## ]]\n'+ '{audio}\n'+ '\n'+ '[[ ## file ## ]]\n'+ '{file}\n'+ '\n'+ '[[ ## document ## ]]\n'+ '{document}\n'+ '\n'+ '[[ ## event ## ]]\n'+ '{event}\n'+ '\n'+ '[[ ## tools ## ]]\n'+ '{tools}\n'+ '\n'+ '[[ ## profile ## ]]\n'+ '{profile}\n'+ '\n'+ '[[ ## context ## ]]\n'+ '{context}\n'+ '\n'+ '[[ ## question ## ]]\n'+ '{question}\n'+ '\n'+ '[[ ## answer ## ]]\n'+ '{answer} # note: the value you produce must adhere to the JSON schema: '+ '{"type": "object", "properties": {"answer": {"type": "string", "title": "Answer"}, '+ '"sources": {"type": "array", "items": {"type": "string"}, "title": "Sources"}}, '+ '"required": ["answer", "sources"], "title": "AnswerCard"}\n'+ '\n'+ '[[ ## verdict ## ]]\n'+ '{verdict} # note: the value you produce must exactly match (no extra '+ 'characters) one of: yes; no\n'+ '\n'+ '[[ ## confidence ## ]]\n'+ '{confidence} # note: the value you produce must be a single float value\n'+ '\n'+ '[[ ## completed ## ]]\n'+ 'In adhering to this structure, your objective is: \n'+ ' Answer carefully using every available signal.'},+ {"role": "user",+ "content": [{"type": "text",+ "text": "This is an example of the task, though some input or output fields are not "+ "supplied.\n"+ "\n"+ "[[ ## image ## ]]\n"},+ {"type": "image_url", "image_url": {"url": "https://example.com/demo.png"}},+ {"type": "text", "text": "\n\n[[ ## audio ## ]]\n"},+ {"type": "input_audio", "input_audio": {"data": "REVNTw==", "format": "wav"}},+ {"type": "text", "text": "\n\n[[ ## file ## ]]\n"},+ {"type": "file", "file": {"file_id": "file-demo", "filename": "demo.txt"}},+ {"type": "text", "text": "\n\n[[ ## document ## ]]\n"},+ {"type": "document",+ "source": {"type": "text", "media_type": "text/plain", "data": "Demo document"},+ "citations": {"enabled": True},+ "title": "Demo Doc"},+ {"type": "text", "text": "\n\n[[ ## event ## ]]\n"},+ {"type": "event", "event": {"label": "demo-event"}},+ {"type": "text",+ "text": '\n'+ '\n'+ '[[ ## tools ## ]]\n'+ '["search, whose description is <desc>Search for documents.</desc>. It '+ "takes arguments {'query': {'type': 'string'}, 'k': {'type': 'integer', "+ '\'default\': 3}}."]\n'+ '\n'+ '[[ ## profile ## ]]\n'+ '{"name": "Ada", "location": {"city": "London", "country": "UK"}, '+ '"interests": ["math", "machines"]}\n'+ '\n'+ '[[ ## context ## ]]\n'+ '[1] «demo context one»\n'+ '[2] «demo context two»\n'+ '\n'+ '[[ ## question ## ]]\n'+ 'What should we mention?'}]},+ {"role": "assistant",+ "content": '[[ ## answer ## ]]\n'+ '{"answer": "Mention analytical engines.", "sources": ["demo"]}\n'+ '\n'+ '[[ ## verdict ## ]]\n'+ 'yes\n'+ '\n'+ '[[ ## confidence ## ]]\n'+ '0.9\n'+ '\n'+ '[[ ## completed ## ]]\n'},+ {"role": "user",+ "content": "This is an example of the task, though some input or output fields are not "+ "supplied.\n"+ "\n"+ "[[ ## question ## ]]\n"+ "Incomplete example question"},+ {"role": "assistant",+ "content": '[[ ## answer ## ]]\n'+ '{"answer": "Partial answer.", "sources": ["partial"]}\n'+ '\n'+ '[[ ## verdict ## ]]\n'+ 'Not supplied for this particular example. \n'+ '\n'+ '[[ ## confidence ## ]]\n'+ 'Not supplied for this particular example.\n'+ '\n'+ '[[ ## completed ## ]]\n'},+ {"role": "user",+ "content": '[[ ## profile ## ]]\n'+ '{"name": "Ada", "location": {"city": "London", "country": "UK"}, "interests": '+ '["math", "machines"]}\n'+ '\n'+ '[[ ## context ## ]]\n'+ '[1] «old note»\n'+ '[2] «older note»\n'+ '\n'+ '[[ ## question ## ]]\n'+ 'Who is Ada?'},+ {"role": "assistant",+ "content": '[[ ## answer ## ]]\n'+ '{"answer": "Ada is a mathematician.", "sources": ["memory"]}\n'+ '\n'+ '[[ ## verdict ## ]]\n'+ 'yes\n'+ '\n'+ '[[ ## confidence ## ]]\n'+ '0.8\n'+ '\n'+ '[[ ## completed ## ]]\n'},+ {"role": "user",+ "content": [{"type": "text", "text": "[[ ## image ## ]]\n"},+ {"type": "image_url", "image_url": {"url": "https://example.com/current.png"}},+ {"type": "text", "text": "\n\n[[ ## audio ## ]]\n"},+ {"type": "input_audio", "input_audio": {"data": "Q1VSUkVOVA==", "format": "wav"}},+ {"type": "text", "text": "\n\n[[ ## file ## ]]\n"},+ {"type": "file", "file": {"file_id": "file-current", "filename": "current.txt"}},+ {"type": "text", "text": "\n\n[[ ## document ## ]]\n"},+ {"type": "document",+ "source": {"type": "text", "media_type": "text/plain", "data": "Current document"},+ "citations": {"enabled": True},+ "title": "Current Doc"},+ {"type": "text", "text": "\n\n[[ ## event ## ]]\n"},+ {"type": "event", "event": {"label": "current-event"}},+ {"type": "text",+ "text": '\n'+ '\n'+ '[[ ## tools ## ]]\n'+ '["search, whose description is <desc>Search for documents.</desc>. It '+ "takes arguments {'query': {'type': 'string'}, 'k': {'type': 'integer', "+ '\'default\': 3}}."]\n'+ '\n'+ '[[ ## profile ## ]]\n'+ '{"name": "Grace", "location": {"city": "Arlington", "country": "USA"}, '+ '"interests": ["compilers", "navy"]}\n'+ '\n'+ '[[ ## context ## ]]\n'+ '[1] «current context one»\n'+ '[2] «current context two»\n'+ '\n'+ '[[ ## question ## ]]\n'+ 'What should the answer include?\n'+ '\n'+ 'Respond with the corresponding output fields, starting with the field `[[ '+ '## answer ## ]]` (must be formatted as a valid Python AnswerCard), then '+ "`[[ ## verdict ## ]]` (must be formatted as a valid Python Literal['yes', "+ "'no']), then `[[ ## confidence ## ]]` (must be formatted as a valid Python "+ 'float), and then ending with the marker for `[[ ## completed ## ]]`.'}]}]+ assert messages == expected_messages+ expected_lm_kwargs = {}+ assert lm_kwargs == expected_lm_kwargs+def test_chat_adapter_with_pydantic_models():"""This test verifies that ChatAdapter can handle different input and output field types, both basic and nested.@@ -293,7 +1559,7 @@ def test_chat_adapter_exception_raised_on_failure():signature = dspy.make_signature("question->answer")adapter = dspy.ChatAdapter()invalid_completion = "{'output':'mismatched value'}"- with pytest.raises(dspy.utils.exceptions.AdapterParseError, match="Adapter ChatAdapter failed to parse*"):+ with pytest.raises(dspy.utils.exceptions.AdapterParseError, match=r"Adapter ChatAdapter failed to parse.*"):adapter.parse(signature, invalid_completion)@@ -824,7 +2090,7 @@ def test_format_system_message():expected_system_message = """Your input fields are:1. `question` (str):Your output fields are:-1. `answers` (list[str]):+1. `answers` (list[str]):\x202. `scores` (list[float]):All interactions will be structured in the following way, with the appropriate values filled in.@@ -838,7 +2104,7 @@ All interactions will be structured in the following way, with the appropriate v{scores} # note: the value you produce must adhere to the JSON schema: {"type": "array", "items": {"type": "number"}}[[ ## completed ## ]]-In adhering to this structure, your objective is:+In adhering to this structure, your objective is:\x20Answer the question with multiple answers and scores"""assert system_message == expected_system_messagediff --git a/tests/adapters/test_json_adapter.py b/tests/adapters/test_json_adapter.pyindex 13ca0ea81..c6dd1f679 100644--- a/tests/adapters/test_json_adapter.py+++ b/tests/adapters/test_json_adapter.py@@ -1,3 +1,5 @@+import enum+from typing import Literalfrom unittest import mockimport pydantic@@ -7,6 +9,7 @@ from litellm.utils import ChatCompletionMessageToolCall, Choices, Function, Messfrom openai.types.responses import ResponseOutputMessageimport dspy+from tests.adapters.conftest import format_messages_and_lm_kwargsdef test_json_adapter_format_exact_messages_for_simple_signature():@@ -14,12 +17,15 @@ def test_json_adapter_format_exact_messages_for_simple_signature():question: str = dspy.InputField()answer: str = dspy.OutputField()- messages = dspy.JSONAdapter().format(+ messages, lm_kwargs = format_messages_and_lm_kwargs(dspy.JSONAdapter(),StringSignature,demos=[],inputs={"question": "What is the capital of France?"},)+ expected_lm_kwargs = {}+ assert lm_kwargs == expected_lm_kwargs+assert messages == [{"role": "system",@@ -58,12 +64,15 @@ def test_json_adapter_format_exact_messages_with_demo_and_typed_output():answer: str = dspy.OutputField()confidence: float = dspy.OutputField()- messages = dspy.JSONAdapter().format(+ messages, lm_kwargs = format_messages_and_lm_kwargs(dspy.JSONAdapter(),MultiAnswer,demos=[{"question": "Q1", "answer": "A1", "confidence": 0.9}],inputs={"question": "Q2"},)+ expected_lm_kwargs = {}+ assert lm_kwargs == expected_lm_kwargs+assert messages == [{"role": "system",@@ -113,7 +122,10 @@ def test_json_adapter_format_exact_messages_with_described_and_bool_outputs():output1: str = dspy.OutputField(desc="String output field")output2: bool = dspy.OutputField()- messages = dspy.JSONAdapter().format(TestSignature, [], {"input1": "Test input"})+ messages, lm_kwargs = format_messages_and_lm_kwargs(dspy.JSONAdapter(), TestSignature, [], {"input1": "Test input"})++ expected_lm_kwargs = {}+ assert lm_kwargs == expected_lm_kwargsassert messages == [{@@ -149,6 +161,521 @@ Respond with a JSON object in the following order of fields: `output1`, then `ou]+def test_json_adapter_format_exact_messages_with_history_demo_pydantic_tools_and_image():+ def search(query: str, k: int = 3) -> str:+ """Search for documents."""+ return query++ class Location(pydantic.BaseModel):+ city: str+ country: str++ class Profile(pydantic.BaseModel):+ name: str+ location: Location+ interests: list[str]++ class AnswerCard(pydantic.BaseModel):+ answer: str+ sources: list[str]++ class RichRenderingSignature(dspy.Signature):+ """Answer using all supplied context."""++ history: dspy.History = dspy.InputField()+ image: dspy.Image = dspy.InputField()+ tools: list[dspy.Tool] = dspy.InputField()+ profile: Profile = dspy.InputField()+ question: str = dspy.InputField()+ answer: AnswerCard = dspy.OutputField()++ tool = dspy.Tool(search)+ demo_profile = Profile(+ name="Ada",+ location=Location(city="London", country="UK"),+ interests=["math", "machines"],+ )+ current_profile = Profile(+ name="Grace",+ location=Location(city="Arlington", country="USA"),+ interests=["compilers", "navy"],+ )+ history = dspy.History(+ messages=[+ {+ "profile": demo_profile,+ "question": "Who is Ada?",+ "answer": AnswerCard(answer="Ada is a mathematician.", sources=["memory"]),+ }+ ]+ )+ messages, lm_kwargs = format_messages_and_lm_kwargs(dspy.JSONAdapter(),+ RichRenderingSignature,+ demos=[+ {+ "image": dspy.Image("https://example.com/demo.png"),+ "tools": [tool],+ "profile": demo_profile,+ "question": "What should we mention?",+ "answer": AnswerCard(answer="Mention analytical engines.", sources=["demo"]),+ }+ ],+ inputs={+ "history": history,+ "image": dspy.Image("https://example.com/current.png"),+ "tools": [tool],+ "profile": current_profile,+ "question": "What should the answer include?",+ },+ )++ expected_messages = [{"role": "system",+ "content": 'Your input fields are:\n'+ '1. `history` (History): \n'+ '2. `image` (Image): \n'+ '3. `tools` (list[Tool]): \n'+ '4. `profile` (Profile): \n'+ '5. `question` (str):\n'+ 'Your output fields are:\n'+ '1. `answer` (AnswerCard):\n'+ 'All interactions will be structured in the following way, with the appropriate '+ 'values filled in.\n'+ '\n'+ 'Inputs will have the following structure:\n'+ '\n'+ '[[ ## history ## ]]\n'+ '{history}\n'+ '\n'+ '[[ ## image ## ]]\n'+ '{image}\n'+ '\n'+ '[[ ## tools ## ]]\n'+ '{tools}\n'+ '\n'+ '[[ ## profile ## ]]\n'+ '{profile}\n'+ '\n'+ '[[ ## question ## ]]\n'+ '{question}\n'+ '\n'+ 'Outputs will be a JSON object with the following fields.\n'+ '\n'+ '{\n'+ ' "answer": "{answer} # note: the value you produce must adhere to the JSON '+ 'schema: {\\"type\\": \\"object\\", \\"properties\\": {\\"answer\\": {\\"type\\": '+ '\\"string\\", \\"title\\": \\"Answer\\"}, \\"sources\\": {\\"type\\": \\"array\\", '+ '\\"items\\": {\\"type\\": \\"string\\"}, \\"title\\": \\"Sources\\"}}, '+ '\\"required\\": [\\"answer\\", \\"sources\\"], \\"title\\": \\"AnswerCard\\"}"\n'+ '}\n'+ 'In adhering to this structure, your objective is: \n'+ ' Answer using all supplied context.'},+ {"role": "user",+ "content": [{"type": "text",+ "text": "This is an example of the task, though some input or output fields are not "+ "supplied.\n"+ "\n"+ "[[ ## image ## ]]\n"},+ {"type": "image_url", "image_url": {"url": "https://example.com/demo.png"}},+ {"type": "text",+ "text": '\n'+ '\n'+ '[[ ## tools ## ]]\n'+ '["search, whose description is <desc>Search for documents.</desc>. It '+ "takes arguments {'query': {'type': 'string'}, 'k': {'type': 'integer', "+ '\'default\': 3}}."]\n'+ '\n'+ '[[ ## profile ## ]]\n'+ '{"name": "Ada", "location": {"city": "London", "country": "UK"}, '+ '"interests": ["math", "machines"]}\n'+ '\n'+ '[[ ## question ## ]]\n'+ 'What should we mention?'}]},+ {"role": "assistant",+ "content": '{\n'+ ' "answer": {\n'+ ' "answer": "Mention analytical engines.",\n'+ ' "sources": [\n'+ ' "demo"\n'+ ' ]\n'+ ' }\n'+ '}'},+ {"role": "user",+ "content": '[[ ## profile ## ]]\n'+ '{"name": "Ada", "location": {"city": "London", "country": "UK"}, "interests": '+ '["math", "machines"]}\n'+ '\n'+ '[[ ## question ## ]]\n'+ 'Who is Ada?'},+ {"role": "assistant",+ "content": '{\n'+ ' "answer": {\n'+ ' "answer": "Ada is a mathematician.",\n'+ ' "sources": [\n'+ ' "memory"\n'+ ' ]\n'+ ' }\n'+ '}'},+ {"role": "user",+ "content": [{"type": "text", "text": "[[ ## image ## ]]\n"},+ {"type": "image_url", "image_url": {"url": "https://example.com/current.png"}},+ {"type": "text",+ "text": '\n'+ '\n'+ '[[ ## tools ## ]]\n'+ '["search, whose description is <desc>Search for documents.</desc>. It '+ "takes arguments {'query': {'type': 'string'}, 'k': {'type': 'integer', "+ '\'default\': 3}}."]\n'+ '\n'+ '[[ ## profile ## ]]\n'+ '{"name": "Grace", "location": {"city": "Arlington", "country": "USA"}, '+ '"interests": ["compilers", "navy"]}\n'+ '\n'+ '[[ ## question ## ]]\n'+ 'What should the answer include?\n'+ '\n'+ 'Respond with a JSON object in the following order of fields: `answer` '+ '(must be formatted as a valid Python AnswerCard).'}]}]+ assert messages == expected_messages+ expected_lm_kwargs = {}+ assert lm_kwargs == expected_lm_kwargs++def test_json_adapter_format_exact_messages_with_int_and_mapping_outputs():+ class IntDictSignature(dspy.Signature):+ question: str = dspy.InputField()+ count: int = dspy.OutputField()+ metadata: dict[str, int] = dspy.OutputField()++ messages, lm_kwargs = format_messages_and_lm_kwargs(dspy.JSONAdapter(), IntDictSignature, [], {"question": "Count things"})++ expected_messages = [{"role": "system",+ "content": 'Your input fields are:\n'+ '1. `question` (str):\n'+ 'Your output fields are:\n'+ '1. `count` (int): \n'+ '2. `metadata` (dict[str, int]):\n'+ 'All interactions will be structured in the following way, with the appropriate '+ 'values filled in.\n'+ '\n'+ 'Inputs will have the following structure:\n'+ '\n'+ '[[ ## question ## ]]\n'+ '{question}\n'+ '\n'+ 'Outputs will be a JSON object with the following fields.\n'+ '\n'+ '{\n'+ ' "count": "{count} # note: the value you produce must be a single int '+ 'value",\n'+ ' "metadata": "{metadata} # note: the value you produce must adhere to the '+ 'JSON schema: {\\"type\\": \\"object\\", \\"additionalProperties\\": {\\"type\\": '+ '\\"integer\\"}}"\n'+ '}\n'+ 'In adhering to this structure, your objective is: \n'+ ' Given the fields `question`, produce the fields `count`, `metadata`.'},+ {"role": "user",+ "content": "[[ ## question ## ]]\n"+ "Count things\n"+ "\n"+ "Respond with a JSON object in the following order of fields: `count` (must be "+ "formatted as a valid Python int), then `metadata` (must be formatted as a valid "+ "Python dict[str, int])."}]+ assert messages == expected_messages+ expected_lm_kwargs = {}+ assert lm_kwargs == expected_lm_kwargs+++def test_json_adapter_format_exact_messages_with_literal_and_enum_outputs():+ class Label(enum.Enum):+ POSITIVE = "positive"+ NEGATIVE = "negative"++ class LiteralEnumSignature(dspy.Signature):+ text: str = dspy.InputField()+ decision: Literal["accept", "reject"] = dspy.OutputField()+ label: Label = dspy.OutputField()++ messages, lm_kwargs = format_messages_and_lm_kwargs(dspy.JSONAdapter(), LiteralEnumSignature, [], {"text": "Looks good"})++ expected_messages = [{"role": "system",+ "content": 'Your input fields are:\n'+ '1. `text` (str):\n'+ 'Your output fields are:\n'+ "1. `decision` (Literal['accept', 'reject']): \n"+ '2. `label` (Label):\n'+ 'All interactions will be structured in the following way, with the appropriate '+ 'values filled in.\n'+ '\n'+ 'Inputs will have the following structure:\n'+ '\n'+ '[[ ## text ## ]]\n'+ '{text}\n'+ '\n'+ 'Outputs will be a JSON object with the following fields.\n'+ '\n'+ '{\n'+ ' "decision": "{decision} # note: the value you produce must exactly match '+ '(no extra characters) one of: accept; reject",\n'+ ' "label": "{label} # note: the value you produce must be one of: positive; '+ 'negative"\n'+ '}\n'+ 'In adhering to this structure, your objective is: \n'+ ' Given the fields `text`, produce the fields `decision`, `label`.'},+ {"role": "user",+ "content": "[[ ## text ## ]]\n"+ "Looks good\n"+ "\n"+ "Respond with a JSON object in the following order of fields: `decision` (must be "+ "formatted as a valid Python Literal['accept', 'reject']), then `label` (must be "+ "formatted as a valid Python Label)."}]+ assert messages == expected_messages+ expected_lm_kwargs = {}+ assert lm_kwargs == expected_lm_kwargs+++def test_json_adapter_format_exact_messages_with_nested_pydantic_output():+ class JsonNestedAddress(pydantic.BaseModel):+ city: str+ country: str++ class JsonNestedSummary(pydantic.BaseModel):+ title: str+ address: JsonNestedAddress+ scores: list[float]++ class PydanticSignature(dspy.Signature):+ question: str = dspy.InputField()+ summary: JsonNestedSummary = dspy.OutputField()++ messages, lm_kwargs = format_messages_and_lm_kwargs(dspy.JSONAdapter(), PydanticSignature, [], {"question": "Summarize"})++ expected_messages = [{"role": "system",+ "content": 'Your input fields are:\n'+ '1. `question` (str):\n'+ 'Your output fields are:\n'+ '1. `summary` (JsonNestedSummary):\n'+ 'All interactions will be structured in the following way, with the appropriate '+ 'values filled in.\n'+ '\n'+ 'Inputs will have the following structure:\n'+ '\n'+ '[[ ## question ## ]]\n'+ '{question}\n'+ '\n'+ 'Outputs will be a JSON object with the following fields.\n'+ '\n'+ '{\n'+ ' "summary": "{summary} # note: the value you produce must adhere to the JSON '+ 'schema: {\\"type\\": \\"object\\", \\"$defs\\": {\\"JsonNestedAddress\\": '+ '{\\"type\\": \\"object\\", \\"properties\\": {\\"city\\": {\\"type\\": \\"string\\", '+ '\\"title\\": \\"City\\"}, \\"country\\": {\\"type\\": \\"string\\", \\"title\\": '+ '\\"Country\\"}}, \\"required\\": [\\"city\\", \\"country\\"], \\"title\\": '+ '\\"JsonNestedAddress\\"}}, \\"properties\\": {\\"address\\": {\\"$ref\\": '+ '\\"#/$defs/JsonNestedAddress\\"}, \\"scores\\": {\\"type\\": \\"array\\", '+ '\\"items\\": {\\"type\\": \\"number\\"}, \\"title\\": \\"Scores\\"}, \\"title\\": '+ '{\\"type\\": \\"string\\", \\"title\\": \\"Title\\"}}, \\"required\\": [\\"title\\", '+ '\\"address\\", \\"scores\\"], \\"title\\": \\"JsonNestedSummary\\"}"\n'+ '}\n'+ 'In adhering to this structure, your objective is: \n'+ ' Given the fields `question`, produce the fields `summary`.'},+ {"role": "user",+ "content": "[[ ## question ## ]]\n"+ "Summarize\n"+ "\n"+ "Respond with a JSON object in the following order of fields: `summary` (must be "+ "formatted as a valid Python JsonNestedSummary)."}]+ assert messages == expected_messages+ expected_lm_kwargs = {}+ assert lm_kwargs == expected_lm_kwargs+++def test_json_adapter_format_exact_messages_with_incomplete_demo():+ class IncompleteDemoSignature(dspy.Signature):+ question: str = dspy.InputField()+ context: str = dspy.InputField()+ answer: str = dspy.OutputField()+ score: float = dspy.OutputField()++ messages, lm_kwargs = format_messages_and_lm_kwargs(dspy.JSONAdapter(),+ IncompleteDemoSignature,+ [{"question": "Q1", "answer": "A1"}],+ {"question": "Q2", "context": "C2"},+ )++ expected_messages = [{"role": "system",+ "content": 'Your input fields are:\n'+ '1. `question` (str): \n'+ '2. `context` (str):\n'+ 'Your output fields are:\n'+ '1. `answer` (str): \n'+ '2. `score` (float):\n'+ 'All interactions will be structured in the following way, with the appropriate '+ 'values filled in.\n'+ '\n'+ 'Inputs will have the following structure:\n'+ '\n'+ '[[ ## question ## ]]\n'+ '{question}\n'+ '\n'+ '[[ ## context ## ]]\n'+ '{context}\n'+ '\n'+ 'Outputs will be a JSON object with the following fields.\n'+ '\n'+ '{\n'+ ' "answer": "{answer}",\n'+ ' "score": "{score} # note: the value you produce must be a single float '+ 'value"\n'+ '}\n'+ 'In adhering to this structure, your objective is: \n'+ ' Given the fields `question`, `context`, produce the fields `answer`, '+ '`score`.'},+ {"role": "user",+ "content": "This is an example of the task, though some input or output fields are not "+ "supplied.\n"+ "\n"+ "[[ ## question ## ]]\n"+ "Q1"},+ {"role": "assistant",+ "content": '{\n "answer": "A1",\n "score": "Not supplied for this particular example. "\n}'},+ {"role": "user",+ "content": "[[ ## question ## ]]\n"+ "Q2\n"+ "\n"+ "[[ ## context ## ]]\n"+ "C2\n"+ "\n"+ "Respond with a JSON object in the following order of fields: `answer`, then `score` "+ "(must be formatted as a valid Python float)."}]+ assert messages == expected_messages+ expected_lm_kwargs = {}+ assert lm_kwargs == expected_lm_kwargs+++def test_json_adapter_format_exact_messages_and_lm_kwargs_with_native_tool_calling():+ class FunctionCallingLM(dspy.utils.DummyLM):+ @property+ def supports_function_calling(self):+ return True++ def search(query: str, k: int = 3) -> str:+ """Search for documents."""+ return query++ class NativeToolSignature(dspy.Signature):+ question: str = dspy.InputField()+ tools: list[dspy.Tool] = dspy.InputField()+ tool_calls: dspy.ToolCalls = dspy.OutputField()++ messages, lm_kwargs = format_messages_and_lm_kwargs(+ dspy.JSONAdapter(use_native_function_calling=True),+ NativeToolSignature,+ [],+ {"question": "Q?", "tools": [dspy.Tool(search)]},+ lm=FunctionCallingLM([{}]),+ )++ expected_messages = [{"role": "system",+ "content": "Your input fields are:\n"+ "1. `question` (str):\n"+ "Your output fields are:\n"+ "\n"+ "All interactions will be structured in the following way, with the appropriate "+ "values filled in.\n"+ "\n"+ "Inputs will have the following structure:\n"+ "\n"+ "[[ ## question ## ]]\n"+ "{question}\n"+ "\n"+ "Outputs will be a JSON object with the following fields.\n"+ "\n"+ "{}\n"+ "In adhering to this structure, your objective is: \n"+ " Given the fields `question`, `tools`, produce the fields `tool_calls`."},+ {"role": "user",+ "content": "[[ ## question ## ]]\n"+ "Q?\n"+ "\n"+ "Respond with a JSON object in the following order of fields: ."}]+ assert messages == expected_messages+ expected_lm_kwargs = {"tools": [{"type": "function",+ "function": {"name": "search",+ "description": "Search for documents.",+ "parameters": {"type": "object",+ "properties": {"query": {"type": "string"},+ "k": {"type": "integer", "default": 3}},+ "required": ["query", "k"]}}}]}+ assert lm_kwargs == expected_lm_kwargs++def test_json_adapter_format_exact_messages_with_tool_calls_output_demo():+ class ToolCallsSignature(dspy.Signature):+ question: str = dspy.InputField()+ tool_calls: dspy.ToolCalls = dspy.OutputField()++ messages, lm_kwargs = format_messages_and_lm_kwargs(dspy.JSONAdapter(use_native_function_calling=False),+ ToolCallsSignature,+ [{"question": "Q1", "tool_calls": dspy.ToolCalls.from_dict_list([{"name": "search", "args": {"query": "cats"}}])}],+ {"question": "Q2"},+ )++ expected_messages = [{"role": "system",+ "content": 'Your input fields are:\n'+ '1. `question` (str):\n'+ 'Your output fields are:\n'+ '1. `tool_calls` (ToolCalls): \n'+ ' Type description of ToolCalls: Tool calls information, including the name of the '+ 'tools and the arguments to be passed to it. Arguments must be provided in JSON '+ 'format.\n'+ 'All interactions will be structured in the following way, with the appropriate '+ 'values filled in.\n'+ '\n'+ 'Inputs will have the following structure:\n'+ '\n'+ '[[ ## question ## ]]\n'+ '{question}\n'+ '\n'+ 'Outputs will be a JSON object with the following fields.\n'+ '\n'+ '{\n'+ ' "tool_calls": "{tool_calls} # note: the value you produce must adhere to '+ 'the JSON schema: {\\"type\\": \\"object\\", \\"$defs\\": {\\"ToolCall\\": '+ '{\\"type\\": \\"object\\", \\"properties\\": {\\"args\\": {\\"type\\": \\"object\\", '+ '\\"additionalProperties\\": true, \\"title\\": \\"Args\\"}, \\"name\\": {\\"type\\": '+ '\\"string\\", \\"title\\": \\"Name\\"}}, \\"required\\": [\\"name\\", \\"args\\"], '+ '\\"title\\": \\"ToolCall\\"}}, \\"properties\\": {\\"tool_calls\\": {\\"type\\": '+ '\\"array\\", \\"items\\": {\\"$ref\\": \\"#/$defs/ToolCall\\"}, \\"title\\": \\"Tool '+ 'Calls\\"}}, \\"required\\": [\\"tool_calls\\"], \\"title\\": \\"ToolCalls\\"}"\n'+ '}\n'+ 'In adhering to this structure, your objective is: \n'+ ' Given the fields `question`, produce the fields `tool_calls`.'},+ {"role": "user", "content": "[[ ## question ## ]]\nQ1"},+ {"role": "assistant",+ "content": '{\n'+ ' "tool_calls": {\n'+ ' "tool_calls": [\n'+ ' {\n'+ ' "type": "function",\n'+ ' "function": {\n'+ ' "name": "search",\n'+ ' "arguments": {\n'+ ' "query": "cats"\n'+ ' }\n'+ ' }\n'+ ' }\n'+ ' ]\n'+ ' }\n'+ '}'},+ {"role": "user",+ "content": "[[ ## question ## ]]\n"+ "Q2\n"+ "\n"+ "Respond with a JSON object in the following order of fields: `tool_calls` (must be "+ "formatted as a valid Python ToolCalls)."}]+ assert messages == expected_messages+ expected_lm_kwargs = {}+ assert lm_kwargs == expected_lm_kwargs++def test_json_adapter_passes_structured_output_when_supported_by_model():class OutputField3(pydantic.BaseModel):subfield1: int = pydantic.Field(description="Int subfield 1", ge=0, le=10)@@ -1138,7 +1665,7 @@ def test_format_system_message():expected_system_message = """Your input fields are:1. `question` (str):Your output fields are:-1. `answers` (list[str]):+1. `answers` (list[str]):\x202. `scores` (list[float]):All interactions will be structured in the following way, with the appropriate values filled in.@@ -1153,6 +1680,6 @@ Outputs will be a JSON object with the following fields."answers": "{answers} # note: the value you produce must adhere to the JSON schema: {\\"type\\": \\"array\\", \\"items\\": {\\"type\\": \\"string\\"}}","scores": "{scores} # note: the value you produce must adhere to the JSON schema: {\\"type\\": \\"array\\", \\"items\\": {\\"type\\": \\"number\\"}}"}-In adhering to this structure, your objective is:+In adhering to this structure, your objective is:\x20Answer the question with multiple answers and scores"""assert system_message == expected_system_messagediff --git a/tests/adapters/test_two_step_adapter.py b/tests/adapters/test_two_step_adapter.pyindex f045188fb..15a35fd30 100644--- a/tests/adapters/test_two_step_adapter.py+++ b/tests/adapters/test_two_step_adapter.py@@ -3,6 +3,58 @@ from unittest import mockimport pytestimport dspy+from tests.adapters.conftest import format_messages_and_lm_kwargs+++def test_two_step_adapter_format_exact_messages_for_simple_signature_with_demo():+ class QA(dspy.Signature):+ question: str = dspy.InputField()+ answer: str = dspy.OutputField()++ adapter = dspy.TwoStepAdapter(dspy.utils.DummyLM([{"answer": "x"}]))+ messages, lm_kwargs = format_messages_and_lm_kwargs(adapter, QA, [{"question": "Q1", "answer": "A1"}], {"question": "Q2"})++ expected_messages = [{"role": "system",+ "content": "You are a helpful assistant that can solve tasks based on user input.\n"+ "As input, you will be provided with:\n"+ "1. `question` (str):\n"+ "Your outputs must contain:\n"+ "1. `answer` (str):\n"+ "You should lay out your outputs in detail so that your answer can be understood by "+ "another agent\n"+ "Specific instructions: Given the fields `question`, produce the fields `answer`."},+ {"role": "user", "content": "question: Q1"},+ {"role": "assistant", "content": "answer: A1"},+ {"role": "user", "content": "question: Q2"}]+ assert messages == expected_messages+ expected_lm_kwargs = {}+ assert lm_kwargs == expected_lm_kwargs+++def test_two_step_adapter_format_exact_messages_with_typed_outputs():+ class TypedSignature(dspy.Signature):+ question: str = dspy.InputField()+ count: int = dspy.OutputField()+ answer: str = dspy.OutputField()++ adapter = dspy.TwoStepAdapter(dspy.utils.DummyLM([{"count": 1, "answer": "x"}]))+ messages, lm_kwargs = format_messages_and_lm_kwargs(adapter, TypedSignature, [], {"question": "Q"})++ expected_messages = [{"role": "system",+ "content": "You are a helpful assistant that can solve tasks based on user input.\n"+ "As input, you will be provided with:\n"+ "1. `question` (str):\n"+ "Your outputs must contain:\n"+ "1. `count` (int): \n"+ "2. `answer` (str):\n"+ "You should lay out your outputs in detail so that your answer can be understood by "+ "another agent\n"+ "Specific instructions: Given the fields `question`, produce the fields `count`, "+ "`answer`."},+ {"role": "user", "content": "question: Q"}]+ assert messages == expected_messages+ expected_lm_kwargs = {}+ assert lm_kwargs == expected_lm_kwargsdef test_two_step_adapter_call():diff --git a/tests/adapters/test_xml_adapter.py b/tests/adapters/test_xml_adapter.pyindex 51857daff..ee300ba3c 100644--- a/tests/adapters/test_xml_adapter.py+++ b/tests/adapters/test_xml_adapter.py@@ -8,6 +8,7 @@ from litellm import Choices, Message, ModelResponseimport dspyfrom dspy.adapters.chat_adapter import FieldInfoWithNamefrom dspy.adapters.xml_adapter import XMLAdapter+from tests.adapters.conftest import format_messages_and_lm_kwargsdef test_xml_adapter_format_and_parse_basic():@@ -307,12 +308,15 @@ def test_xml_adapter_format_exact_messages_for_simple_signature():question: str = dspy.InputField()answer: str = dspy.OutputField()- messages = dspy.XMLAdapter().format(+ messages, lm_kwargs = format_messages_and_lm_kwargs(dspy.XMLAdapter(),StringSignature,demos=[],inputs={"question": "why did a chicken cross the kitchen?"},)+ expected_lm_kwargs = {}+ assert lm_kwargs == expected_lm_kwargs+assert messages == [{"role": "system",@@ -349,12 +353,15 @@ def test_xml_adapter_format_exact_messages_for_two_input_signature():answer: str = dspy.InputField()judgement: str = dspy.OutputField()- messages = dspy.XMLAdapter().format(+ messages, lm_kwargs = format_messages_and_lm_kwargs(dspy.XMLAdapter(),StringSignature,demos=[],inputs={"question": "why did a chicken cross the kitchen?", "answer": "To get to the other side!"},)+ expected_lm_kwargs = {}+ assert lm_kwargs == expected_lm_kwargs+assert messages == [{"role": "system",@@ -400,12 +407,15 @@ def test_xml_adapter_format_exact_messages_with_demo_and_typed_output():answer: str = dspy.OutputField()score: float = dspy.OutputField()- messages = dspy.XMLAdapter().format(+ messages, lm_kwargs = format_messages_and_lm_kwargs(dspy.XMLAdapter(),MultiAnswer,demos=[{"question": "Q1", "answer": "A1", "score": 0.9}],inputs={"question": "Q2"},)+ expected_lm_kwargs = {}+ assert lm_kwargs == expected_lm_kwargs+assert messages == [{"role": "system",@@ -454,6 +464,300 @@ Respond with the corresponding output fields wrapped in XML tags `<answer>`, the]+def test_xml_adapter_format_exact_messages_with_history_demo_pydantic_tools_and_image():+ def search(query: str, k: int = 3) -> str:+ """Search for documents."""+ return query++ class Location(pydantic.BaseModel):+ city: str+ country: str++ class Profile(pydantic.BaseModel):+ name: str+ location: Location+ interests: list[str]++ class AnswerCard(pydantic.BaseModel):+ answer: str+ sources: list[str]++ class RichRenderingSignature(dspy.Signature):+ """Answer using all supplied context."""++ history: dspy.History = dspy.InputField()+ image: dspy.Image = dspy.InputField()+ tools: list[dspy.Tool] = dspy.InputField()+ profile: Profile = dspy.InputField()+ question: str = dspy.InputField()+ answer: AnswerCard = dspy.OutputField()++ tool = dspy.Tool(search)+ demo_profile = Profile(+ name="Ada",+ location=Location(city="London", country="UK"),+ interests=["math", "machines"],+ )+ current_profile = Profile(+ name="Grace",+ location=Location(city="Arlington", country="USA"),+ interests=["compilers", "navy"],+ )+ history = dspy.History(+ messages=[+ {+ "profile": demo_profile,+ "question": "Who is Ada?",+ "answer": AnswerCard(answer="Ada is a mathematician.", sources=["memory"]),+ }+ ]+ )+ messages, lm_kwargs = format_messages_and_lm_kwargs(dspy.XMLAdapter(),+ RichRenderingSignature,+ demos=[+ {+ "image": dspy.Image("https://example.com/demo.png"),+ "tools": [tool],+ "profile": demo_profile,+ "question": "What should we mention?",+ "answer": AnswerCard(answer="Mention analytical engines.", sources=["demo"]),+ }+ ],+ inputs={+ "history": history,+ "image": dspy.Image("https://example.com/current.png"),+ "tools": [tool],+ "profile": current_profile,+ "question": "What should the answer include?",+ },+ )++ expected_messages = [{"role": "system",+ "content": 'Your input fields are:\n'+ '1. `history` (History): \n'+ '2. `image` (Image): \n'+ '3. `tools` (list[Tool]): \n'+ '4. `profile` (Profile): \n'+ '5. `question` (str):\n'+ 'Your output fields are:\n'+ '1. `answer` (AnswerCard):\n'+ 'All interactions will be structured in the following way, with the appropriate '+ 'values filled in.\n'+ '\n'+ '<history>\n'+ '{history}\n'+ '</history>\n'+ '\n'+ '<image>\n'+ '{image}\n'+ '</image>\n'+ '\n'+ '<tools>\n'+ '{tools}\n'+ '</tools>\n'+ '\n'+ '<profile>\n'+ '{profile}\n'+ '</profile>\n'+ '\n'+ '<question>\n'+ '{question}\n'+ '</question>\n'+ '\n'+ '<answer>\n'+ '{answer} # note: the value you produce must adhere to the JSON schema: '+ '{"type": "object", "properties": {"answer": {"type": "string", "title": "Answer"}, '+ '"sources": {"type": "array", "items": {"type": "string"}, "title": "Sources"}}, '+ '"required": ["answer", "sources"], "title": "AnswerCard"}\n'+ '</answer>\n'+ 'In adhering to this structure, your objective is: \n'+ ' Answer using all supplied context.'},+ {"role": "user",+ "content": [{"type": "text",+ "text": "This is an example of the task, though some input or output fields are not "+ "supplied.\n"+ "\n"+ "<image>\n"},+ {"type": "image_url", "image_url": {"url": "https://example.com/demo.png"}},+ {"type": "text",+ "text": '\n'+ '</image>\n'+ '\n'+ '<tools>\n'+ '["search, whose description is <desc>Search for documents.</desc>. It '+ "takes arguments {'query': {'type': 'string'}, 'k': {'type': 'integer', "+ '\'default\': 3}}."]\n'+ '</tools>\n'+ '\n'+ '<profile>\n'+ '{"name": "Ada", "location": {"city": "London", "country": "UK"}, '+ '"interests": ["math", "machines"]}\n'+ '</profile>\n'+ '\n'+ '<question>\n'+ 'What should we mention?\n'+ '</question>'}]},+ {"role": "assistant",+ "content": '<answer>\n{"answer": "Mention analytical engines.", "sources": ["demo"]}\n</answer>'},+ {"role": "user",+ "content": '<profile>\n'+ '{"name": "Ada", "location": {"city": "London", "country": "UK"}, "interests": '+ '["math", "machines"]}\n'+ '</profile>\n'+ '\n'+ '<question>\n'+ 'Who is Ada?\n'+ '</question>'},+ {"role": "assistant",+ "content": '<answer>\n{"answer": "Ada is a mathematician.", "sources": ["memory"]}\n</answer>'},+ {"role": "user",+ "content": [{"type": "text", "text": "<image>\n"},+ {"type": "image_url", "image_url": {"url": "https://example.com/current.png"}},+ {"type": "text",+ "text": '\n'+ '</image>\n'+ '\n'+ '<tools>\n'+ '["search, whose description is <desc>Search for documents.</desc>. It '+ "takes arguments {'query': {'type': 'string'}, 'k': {'type': 'integer', "+ '\'default\': 3}}."]\n'+ '</tools>\n'+ '\n'+ '<profile>\n'+ '{"name": "Grace", "location": {"city": "Arlington", "country": "USA"}, '+ '"interests": ["compilers", "navy"]}\n'+ '</profile>\n'+ '\n'+ '<question>\n'+ 'What should the answer include?\n'+ '</question>\n'+ '\n'+ 'Respond with the corresponding output fields wrapped in XML tags '+ '`<answer>`.'}]}]+ assert messages == expected_messages+ expected_lm_kwargs = {}+ assert lm_kwargs == expected_lm_kwargs++def test_xml_adapter_format_exact_messages_with_nested_pydantic_output():+ class XmlAddress(pydantic.BaseModel):+ city: str+ country: str++ class XmlSummary(pydantic.BaseModel):+ title: str+ address: XmlAddress++ class PydanticSignature(dspy.Signature):+ question: str = dspy.InputField()+ summary: XmlSummary = dspy.OutputField()++ messages, lm_kwargs = format_messages_and_lm_kwargs(dspy.XMLAdapter(), PydanticSignature, [], {"question": "Summarize"})++ expected_messages = [{"role": "system",+ "content": 'Your input fields are:\n'+ '1. `question` (str):\n'+ 'Your output fields are:\n'+ '1. `summary` (XmlSummary):\n'+ 'All interactions will be structured in the following way, with the appropriate '+ 'values filled in.\n'+ '\n'+ '<question>\n'+ '{question}\n'+ '</question>\n'+ '\n'+ '<summary>\n'+ '{summary} # note: the value you produce must adhere to the JSON schema: '+ '{"type": "object", "$defs": {"XmlAddress": {"type": "object", "properties": {"city": '+ '{"type": "string", "title": "City"}, "country": {"type": "string", "title": '+ '"Country"}}, "required": ["city", "country"], "title": "XmlAddress"}}, "properties": '+ '{"address": {"$ref": "#/$defs/XmlAddress"}, "title": {"type": "string", "title": '+ '"Title"}}, "required": ["title", "address"], "title": "XmlSummary"}\n'+ '</summary>\n'+ 'In adhering to this structure, your objective is: \n'+ ' Given the fields `question`, produce the fields `summary`.'},+ {"role": "user",+ "content": "<question>\n"+ "Summarize\n"+ "</question>\n"+ "\n"+ "Respond with the corresponding output fields wrapped in XML tags `<summary>`."}]+ assert messages == expected_messages+ expected_lm_kwargs = {}+ assert lm_kwargs == expected_lm_kwargs+++def test_xml_adapter_format_exact_messages_with_incomplete_demo():+ class IncompleteDemoSignature(dspy.Signature):+ question: str = dspy.InputField()+ context: str = dspy.InputField()+ answer: str = dspy.OutputField()+ score: float = dspy.OutputField()++ messages, lm_kwargs = format_messages_and_lm_kwargs(dspy.XMLAdapter(),+ IncompleteDemoSignature,+ [{"question": "Q1", "answer": "A1"}],+ {"question": "Q2", "context": "C2"},+ )++ expected_messages = [{"role": "system",+ "content": "Your input fields are:\n"+ "1. `question` (str): \n"+ "2. `context` (str):\n"+ "Your output fields are:\n"+ "1. `answer` (str): \n"+ "2. `score` (float):\n"+ "All interactions will be structured in the following way, with the appropriate "+ "values filled in.\n"+ "\n"+ "<question>\n"+ "{question}\n"+ "</question>\n"+ "\n"+ "<context>\n"+ "{context}\n"+ "</context>\n"+ "\n"+ "<answer>\n"+ "{answer}\n"+ "</answer>\n"+ "\n"+ "<score>\n"+ "{score} # note: the value you produce must be a single float value\n"+ "</score>\n"+ "In adhering to this structure, your objective is: \n"+ " Given the fields `question`, `context`, produce the fields `answer`, "+ "`score`."},+ {"role": "user",+ "content": "This is an example of the task, though some input or output fields are not "+ "supplied.\n"+ "\n"+ "<question>\n"+ "Q1\n"+ "</question>"},+ {"role": "assistant",+ "content": "<answer>\n"+ "A1\n"+ "</answer>\n"+ "\n"+ "<score>\n"+ "Not supplied for this particular example. \n"+ "</score>"},+ {"role": "user",+ "content": "<question>\n"+ "Q2\n"+ "</question>\n"+ "\n"+ "<context>\n"+ "C2\n"+ "</context>\n"+ "\n"+ "Respond with the corresponding output fields wrapped in XML tags `<answer>`, then "+ "`<score>`."}]+ assert messages == expected_messages+ expected_lm_kwargs = {}+ assert lm_kwargs == expected_lm_kwargs++def test_format_system_message():class MySignature(dspy.Signature):"""Answer the question with multiple answers and scores"""@@ -468,7 +772,7 @@ def test_format_system_message():expected_system_message = """Your input fields are:1. `question` (str):Your output fields are:-1. `answers` (list[str]):+1. `answers` (list[str]):\x202. `scores` (list[float]):All interactions will be structured in the following way, with the appropriate values filled in.@@ -483,6 +787,6 @@ All interactions will be structured in the following way, with the appropriate v<scores>{scores} # note: the value you produce must adhere to the JSON schema: {"type": "array", "items": {"type": "number"}}</scores>-In adhering to this structure, your objective is:+In adhering to this structure, your objective is:\x20Answer the question with multiple answers and scores"""assert system_message == expected_system_message