Skip to content

armgit / dspy

Public Imported from GitHub
0

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

Python

Use json mode for serialization (#8605)

TomuHirataaca8ebd4d7f0
diff --git a/dspy/clients/cache.py b/dspy/clients/cache.py
index 7ba9b0e57..7a9885f1b 100644
--- a/dspy/clients/cache.py
+++ b/dspy/clients/cache.py
@@ -75,7 +75,7 @@ class Cache:
if isinstance(value, type) and issubclass(value, pydantic.BaseModel):
return value.model_json_schema()
elif isinstance(value, pydantic.BaseModel):
- return value.model_dump()
+ return value.model_dump(mode="json")
elif callable(value):
# Try to get the source code of the callable if available
import inspect
diff --git a/dspy/predict/predict.py b/dspy/predict/predict.py
index a87523715..59939b1ef 100644
--- a/dspy/predict/predict.py
+++ b/dspy/predict/predict.py
@@ -203,8 +203,9 @@ def serialize_object(obj):
Supports Pydantic models, lists, dicts, and primitive types.
"""
if isinstance(obj, BaseModel):
- # Use model_dump to convert the model into a JSON-serializable dict
- return obj.model_dump()
+ # Use model_dump with mode="json" to ensure all fields (including HttpUrl, datetime, etc.)
+ # are converted to JSON-serializable types (strings)
+ return obj.model_dump(mode="json")
elif isinstance(obj, list):
return [serialize_object(item) for item in obj]
elif isinstance(obj, tuple):
diff --git a/tests/predict/test_predict.py b/tests/predict/test_predict.py
index e60cd14e9..37b9c87fc 100644
--- a/tests/predict/test_predict.py
+++ b/tests/predict/test_predict.py
@@ -10,9 +10,11 @@ import pydantic
import pytest
import ujson
from litellm import ModelResponse
+from pydantic import BaseModel, HttpUrl
import dspy
from dspy import Predict, Signature
+from dspy.predict.predict import serialize_object
from dspy.utils.dummies import DummyLM
@@ -684,3 +686,46 @@ def test_predicted_outputs_piped_from_predict_to_lm_call():
program(question="Why did a chicken cross the kitchen?", prediction="To get to the other side!")
assert "prediction" not in mock_completion.call_args[1]
+
+
+def test_dump_state_pydantic_non_primitive_types():
+ class WebsiteInfo(BaseModel):
+ name: str
+ url: HttpUrl
+ description: str | None = None
+ created_at: datetime
+
+ class TestSignature(dspy.Signature):
+ website_info: WebsiteInfo = dspy.InputField()
+ summary: str = dspy.OutputField()
+
+ website_info = WebsiteInfo(
+ name="Example",
+ url="https://www.example.com",
+ description="Test website",
+ created_at=datetime(2021, 1, 1, 12, 0, 0),
+ )
+
+ serialized = serialize_object(website_info)
+
+ assert serialized["url"] == "https://www.example.com/"
+ assert serialized["created_at"] == "2021-01-01T12:00:00"
+
+ json_str = ujson.dumps(serialized)
+ reloaded = ujson.loads(json_str)
+ assert reloaded == serialized
+
+ predictor = Predict(TestSignature)
+ demo = {
+ "website_info": website_info,
+ "summary": "This is a test website."
+ }
+ predictor.demos = [demo]
+
+ state = predictor.dump_state()
+ json_str = ujson.dumps(state)
+ reloaded_state = ujson.loads(json_str)
+
+ demo_data = reloaded_state["demos"][0]
+ assert demo_data["website_info"]["url"] == "https://www.example.com/"
+ assert demo_data["website_info"]["created_at"] == "2021-01-01T12:00:00"