to/fromMap serialization for ChatMessage, PromptValue & in_memory ChatHistory #652
Add this suggestion to a batch that can be applied as a single commit.
This suggestion is invalid because no changes were made to the code.
Suggestions cannot be applied while the pull request is closed.
Suggestions cannot be applied while viewing a subset of changes.
Only one suggestion per line can be applied in a batch.
Add this suggestion to a batch that can be applied as a single commit.
Applying suggestions on deleted lines is not supported.
You must change the existing code in this line in order to create a valid suggestion.
Outdated suggestions cannot be applied.
This suggestion has been applied or marked resolved.
Suggestions cannot be applied from pending reviews.
Suggestions cannot be applied on multi-line comments.
Suggestions cannot be applied while the pull request is queued to merge.
Suggestion cannot be applied right now. Please check back later.
Hey! I’ve been using LangChain for a few projects now, and whenever I need serialization—be it Firebase, local storage, or something wacky like Protobuf—I always end up basically rebuilding the changing model structure of LangChain. After searching for toJson or toMap in the issue tracker and finding nothing, I figured I’d do something about it.
It looks like the main goal is parity with the Python version of LangChain. My reasoning is that many other languages have reflection or don’t require such detailed typing, so a built-in serialization might not be as big of a deal there. But in Dart, something like this is straightforward and easy to iterate on, so it makes sense.
This PR is super simple and doesn’t interfere with any plans to expand storage features in the framework. It’s just a step toward providing some built-in serialization. From here, you can drop these maps directly into Firestore (or wherever else). I only added toMap/fromMap for what I consider the most-used models: ChatMessage, PromptValue, and ChatHistory (plus all relevant subclasses and field types).
I also tossed in a unit test (a basic encode-reencode-compare test) to confirm the toMap/fromMap flow works as expected. I tried to handle missing required fields gracefully, but generally it shouldn’t be an issue if new fields are added in the future.
The only extra thing to note is that if new fields or new serializable subclasses pop up, they’ll need their own toMap/fromMap implementations. That’s pretty normal, but just calling it out so everything stays in sync.