DSPy: The framework for programming—not prompting—language models
Python
Improve literal format adherence in ChatAdapter, JSONAdapter (#1955)
Corey Zumar26850ac29b92
diff --git a/dspy/adapters/chat_adapter.py b/dspy/adapters/chat_adapter.pyindex 3f58fb0e8..e51e90d68 100644--- a/dspy/adapters/chat_adapter.py+++ b/dspy/adapters/chat_adapter.py@@ -6,14 +6,14 @@ import reimport textwrapfrom collections.abc import Mappingfrom itertools import chain-from typing import Any, Dict, List, Literal, NamedTuple, Union, get_args, get_origin+from typing import Any, Dict, List, Literal, NamedTuple, Unionimport pydanticfrom pydantic import TypeAdapterfrom pydantic.fields import FieldInfofrom dspy.adapters.base import Adapter-from dspy.adapters.utils import find_enum_member, format_field_value+from dspy.adapters.utils import find_enum_member, format_field_value, get_annotation_namefrom dspy.signatures.field import OutputFieldfrom dspy.signatures.signature import Signature, SignatureMetafrom dspy.signatures.utils import get_dspy_field_type@@ -267,19 +267,6 @@ def format_turn(signature, values, role, incomplete=False):return {"role": role, "content": collapsed_messages}-def get_annotation_name(annotation):- origin = get_origin(annotation)- args = get_args(annotation)- if origin is None:- if hasattr(annotation, "__name__"):- return annotation.__name__- else:- return str(annotation)- else:- args_str = ", ".join(get_annotation_name(arg) for arg in args)- return f"{get_annotation_name(origin)}[{args_str}]"--def enumerate_fields(fields: dict) -> str:parts = []for idx, (k, v) in enumerate(fields.items()):@@ -323,7 +310,11 @@ def prepare_instructions(signature: SignatureMeta):elif inspect.isclass(field_type) and issubclass(field_type, enum.Enum):desc = f"must be one of: {'; '.join(field_type.__members__)}"elif hasattr(field_type, "__origin__") and field_type.__origin__ is Literal:- desc = f"must be one of: {'; '.join([str(x) for x in field_type.__args__])}"+ desc = (+ # Strongly encourage the LM to avoid choosing values that don't appear in the+ # literal or returning a value of the form 'Literal[<selected_value>]'+ f"must exactly match (no extra characters) one of: {'; '.join([str(x) for x in field_type.__args__])}"+ )else:desc = "must be pareseable according to the following JSON schema: "desc += json.dumps(prepare_schema(field_type), ensure_ascii=False)diff --git a/dspy/adapters/json_adapter.py b/dspy/adapters/json_adapter.pyindex 7eed644f9..a2fbcd555 100644--- a/dspy/adapters/json_adapter.py+++ b/dspy/adapters/json_adapter.py@@ -5,7 +5,7 @@ import jsonimport loggingimport textwrapfrom copy import deepcopy-from typing import Any, Dict, KeysView, Literal, NamedTuple, get_args, get_origin+from typing import Any, Dict, KeysView, Literal, NamedTupleimport json_repairimport litellm@@ -15,7 +15,7 @@ from pydantic.fields import FieldInfofrom dspy.adapters.base import Adapterfrom dspy.adapters.image_utils import Image-from dspy.adapters.utils import find_enum_member, format_field_value, serialize_for_json+from dspy.adapters.utils import find_enum_member, format_field_value, get_annotation_name, serialize_for_jsonfrom dspy.signatures.signature import SignatureMetafrom dspy.signatures.utils import get_dspy_field_type@@ -243,19 +243,6 @@ def format_turn(signature: SignatureMeta, values: Dict[str, Any], role, incomplereturn {"role": role, "content": "\n\n".join(content).strip()}-def get_annotation_name(annotation):- origin = get_origin(annotation)- args = get_args(annotation)- if origin is None:- if hasattr(annotation, "__name__"):- return annotation.__name__- else:- return str(annotation)- else:- args_str = ", ".join(get_annotation_name(arg) for arg in args)- return f"{get_annotation_name(origin)}[{args_str}]"--def enumerate_fields(fields):parts = []for idx, (k, v) in enumerate(fields.items()):diff --git a/dspy/adapters/utils.py b/dspy/adapters/utils.pyindex 9cddc1fe8..f627f0743 100644--- a/dspy/adapters/utils.py+++ b/dspy/adapters/utils.py@@ -1,5 +1,5 @@import json-from typing import Any, List, Union+from typing import Any, List, Literal, Union, get_args, get_originfrom pydantic import TypeAdapterfrom pydantic.fields import FieldInfo@@ -103,6 +103,26 @@ def find_enum_member(enum, identifier):raise ValueError(f"{identifier} is not a valid name or value for the enum {enum.__name__}")+def get_annotation_name(annotation):+ origin = get_origin(annotation)+ args = get_args(annotation)+ if origin is None:+ if hasattr(annotation, "__name__"):+ return annotation.__name__+ else:+ return str(annotation)++ if origin is Literal:+ args_str = ", ".join(+ _quoted_string_for_literal_type_annotation(a) if isinstance(a, str) else get_annotation_name(a)+ for a in args+ )+ return f"{get_annotation_name(origin)}[{args_str}]"+ else:+ args_str = ", ".join(get_annotation_name(a) for a in args)+ return f"{get_annotation_name(origin)}[{args_str}]"++def _format_input_list_field_value(value: List[Any]) -> str:"""Formats the value of an input field of type List[Any].@@ -135,3 +155,25 @@ def _format_blob(blob: str) -> str:modified_blob = blob.replace("\n", "\n ")return f"«««\n {modified_blob}\n»»»"+++def _quoted_string_for_literal_type_annotation(s: str) -> str:+ """+ Return the specified string quoted for inclusion in a literal type annotation.+ """+ has_single = "'" in s+ has_double = '"' in s++ if has_single and not has_double:+ # Only single quotes => enclose in double quotes+ return f'"{s}"'+ elif has_double and not has_single:+ # Only double quotes => enclose in single quotes+ return f"'{s}'"+ elif has_single and has_double:+ # Both => enclose in single quotes; escape each single quote with \'+ escaped = s.replace("'", "\\'")+ return f"'{escaped}'"+ else:+ # Neither => enclose in single quotes+ return f"'{s}'"diff --git a/tests/adapters/test_chat_adapter.py b/tests/adapters/test_chat_adapter.pynew file mode 100644index 000000000..4866ac013--- /dev/null+++ b/tests/adapters/test_chat_adapter.py@@ -0,0 +1,79 @@+from typing import Literal+from unittest import mock++import pytest++import dspy+++ "input_literal, output_literal, input_value, expected_input_str, expected_output_str",+ [+ # Scenario 1: double quotes escaped within strings+ (+ Literal["one", "two", 'three"'],+ Literal["four", "five", 'six"'],+ "two",+ "Literal['one', 'two', 'three\"']",+ "Literal['four', 'five', 'six\"']",+ ),+ # Scenario 2: Single quotes inside strings+ (+ Literal["she's here", "okay", "test"],+ Literal["done", "maybe'soon", "later"],+ "she's here",+ "Literal[\"she's here\", 'okay', 'test']",+ "Literal['done', \"maybe'soon\", 'later']",+ ),+ # Scenario 3: Strings containing both single and double quotes+ (+ Literal["both\"and'", "another"],+ Literal["yet\"another'", "plain"],+ "another",+ "Literal['both\"and\\'', 'another']",+ "Literal['yet\"another\\'', 'plain']",+ ),+ # Scenario 4: No quotes at all (check the default)+ (+ Literal["foo", "bar"],+ Literal["baz", "qux"],+ "foo",+ "Literal['foo', 'bar']",+ "Literal['baz', 'qux']",+ ),+ # Scenario 5: Mixed types+ (+ Literal[1, "bar"],+ Literal[True, 3, "foo"],+ "bar",+ "Literal[1, 'bar']",+ "Literal[True, 3, 'foo']",+ ),+ ],+)+def test_chat_adapter_quotes_literals_as_expected(+ input_literal, output_literal, input_value, expected_input_str, expected_output_str+):+ """+ This test verifies that when we declare Literal fields with various mixes+ of single/double quotes, the generated content string includes those+ Literals exactly as we want them to appear (like IPython does).+ """++ class TestSignature(dspy.Signature):+ input_text: input_literal = dspy.InputField()+ output_text: output_literal = dspy.OutputField()++ program = dspy.Predict(TestSignature)++ dspy.configure(lm=dspy.LM(model="openai/gpt4o"), adapter=dspy.ChatAdapter())++ with mock.patch("litellm.completion") as mock_completion:+ program(input_text=input_value)++ mock_completion.assert_called_once()+ _, call_kwargs = mock_completion.call_args+ content = call_kwargs["messages"][0]["content"]++ assert expected_input_str in content+ assert expected_output_str in contentdiff --git a/tests/test_json_adapter.py b/tests/adapters/test_json_adapter.pysimilarity index 100%rename from tests/test_json_adapter.pyrename to tests/adapters/test_json_adapter.pydiff --git a/tests/reliability/test_pydantic_models.py b/tests/reliability/test_pydantic_models.pyindex bb6991541..89ddd7478 100644--- a/tests/reliability/test_pydantic_models.py+++ b/tests/reliability/test_pydantic_models.py@@ -1,5 +1,5 @@from enum import Enum-from typing import List+from typing import Any, List, Literalimport pydanticimport pytest@@ -103,3 +103,85 @@ def test_entity_extraction_with_multiple_primitive_outputs():" The categories should be separated by the character '|'."),)++[email protected]("module", [dspy.Predict, dspy.ChainOfThought])+def test_tool_calling_with_literals(module):+ next_tool_names = [+ "get_docs",+ "finish",+ "search_policy",+ "notify_manager",+ "calculate_accrual",+ "combine_leave",+ "review_seniority_rules",+ "fetch_calendar",+ "verify_compensation",+ "check_carryover_policy",+ ]++ class ToolCalling(dspy.Signature):+ """+ Given the fields question, produce the fields response.+ You will be given question and your goal is to finish with response.+ To do this, you will interleave Thought, Tool Name, and Tool Args, and receive a resulting Observation.+ """++ question: str = dspy.InputField()+ trajectory: str = dspy.InputField()+ next_thought: str = dspy.OutputField()+ next_tool_name: Literal[+ "get_docs",+ "finish",+ "search_policy",+ "notify_manager",+ "calculate_accrual",+ "combine_leave",+ "review_seniority_rules",+ "fetch_calendar",+ "verify_compensation",+ "check_carryover_policy",+ ] = dspy.OutputField()+ next_tool_args: dict[str, Any] = dspy.OutputField()+ response_status: Literal["success", "error", "pending"] = dspy.OutputField()+ user_intent: Literal["informational", "transactional", "exploratory"] = dspy.OutputField()++ program = dspy.Predict(ToolCalling)+ prediction = program(+ question=(+ "Tell me more about the company's internal policy for paid time off (PTO), "+ "including as many details as possible. I want to know how PTO is accrued—are "+ "there fixed rates, and do they vary by employee seniority or length of service? "+ "Are there specific rules about carrying unused PTO into the next calendar year, "+ "or is it a 'use it or lose it' system? Additionally, if an employee plans to take "+ "extended leave for a vacation or personal reasons, what is the process for submitting "+ "a request, and how far in advance should they notify their manager? Is there any overlap "+ "or interaction between PTO and other forms of leave, such as sick leave or parental leave? "+ "For example, can PTO be combined with those leave types to create a longer absence, or are "+ "they strictly separate? I’d also like to know if there are any restrictions on when PTO can "+ "be used, such as during critical business periods or holidays. Finally, what is the official "+ "policy if an employee resigns or is terminated—are they compensated for unused PTO days, and if "+ "so, at what rate?"+ ),+ trajectory=(+ "["+ "{'thought': 'Start by understanding PTO accrual rules.', 'tool_name': 'search_policy', 'tool_args': {'topic': 'PTO accrual rates'}}, "+ "{'thought': 'Clarify whether PTO accrual rates vary by seniority.', 'tool_name': 'review_seniority_rules', 'tool_args': {}}, "+ "{'thought': 'Identify carryover rules for unused PTO.', 'tool_name': 'check_carryover_policy', 'tool_args': {'year': 'current year'}}, "+ "{'thought': 'Determine policies on extended leave requests.', 'tool_name': 'search_policy', 'tool_args': {'topic': 'PTO leave request process'}}, "+ "{'thought': 'Check the notification requirements for extended PTO.', 'tool_name': 'notify_manager', 'tool_args': {'type': 'extended leave'}}, "+ "{'thought': 'Investigate overlap between PTO and sick leave.', 'tool_name': 'combine_leave', 'tool_args': {'types': ['PTO', 'sick leave']}}, "+ "{'thought': 'Explore how PTO interacts with parental leave.', 'tool_name': 'combine_leave', 'tool_args': {'types': ['PTO', 'parental leave']}}, "+ "{'thought': 'Fetch the company calendar to determine critical business periods.', 'tool_name': 'fetch_calendar', 'tool_args': {'year': 'current year'}}, "+ "{'thought': 'Verify restrictions on PTO usage during holidays.', 'tool_name': 'search_policy', 'tool_args': {'topic': 'holiday restrictions on PTO'}}, "+ "{'thought': 'Confirm whether unused PTO is compensated upon termination.', 'tool_name': 'verify_compensation', 'tool_args': {'scenario': 'termination'}}, "+ "{'thought': 'Check if PTO is compensated differently upon resignation.', 'tool_name': 'verify_compensation', 'tool_args': {'scenario': 'resignation'}}, "+ "{'thought': 'Review if accrual caps limit PTO earnings.', 'tool_name': 'calculate_accrual', 'tool_args': {'cap': True}}, "+ "{'thought': 'Investigate whether senior employees receive additional PTO benefits.', 'tool_name': 'review_seniority_rules', 'tool_args': {'seniority_level': 'high'}}, "+ "{'thought': 'Assess policy transparency in PTO documentation.', 'tool_name': 'search_policy', 'tool_args': {'topic': 'PTO documentation clarity'}}, "+ "{'thought': 'Explore how leave types can be optimized together.', 'tool_name': 'combine_leave', 'tool_args': {'types': ['PTO', 'other leave']}}, "+ "{'thought': 'Check historical trends in PTO policy changes.', 'tool_name': 'get_docs', 'tool_args': {'document': 'PTO history'}}"+ "]"+ ),+ )+ assert prediction.next_tool_name in next_tool_names