-
Notifications
You must be signed in to change notification settings - Fork 15.8k
New issue
Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.
By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.
Already on GitHub? Sign in to your account
Using langchain input types #11204
Merged
Merged
Using langchain input types #11204
Changes from all commits
Commits
Show all changes
10 commits
Select commit
Hold shift + click to select a range
4039307
x
eyurtsev 7fca5c5
x
eyurtsev dcd458b
x
eyurtsev 416d41f
x
eyurtsev 8f84efc
x
eyurtsev b90ef3b
x
eyurtsev d42d234
lint more
eyurtsev 9df8848
x
eyurtsev 2d2ad5d
x
eyurtsev 16d3d29
Merge branch 'master' into eugene/add_auto_type
eyurtsev File filter
Filter by extension
Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
There are no files selected for viewing
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,94 @@ | ||
"""Serialization module for Well Known LangChain objects. | ||
|
||
Specialized JSON serialization for well known LangChain objects that | ||
can be expected to be frequently transmitted between chains. | ||
""" | ||
import json | ||
from typing import Any, Union | ||
|
||
from langchain.prompts.base import StringPromptValue | ||
from langchain.prompts.chat import ChatPromptValueConcrete | ||
from langchain.schema.document import Document | ||
from langchain.schema.messages import ( | ||
AIMessage, | ||
AIMessageChunk, | ||
ChatMessage, | ||
ChatMessageChunk, | ||
FunctionMessage, | ||
FunctionMessageChunk, | ||
HumanMessage, | ||
HumanMessageChunk, | ||
SystemMessage, | ||
SystemMessageChunk, | ||
) | ||
from pydantic import BaseModel, ValidationError | ||
|
||
|
||
class WellKnownLCObject(BaseModel): | ||
"""A well known LangChain object.""" | ||
|
||
__root__: Union[ | ||
Document, | ||
HumanMessage, | ||
SystemMessage, | ||
ChatMessage, | ||
FunctionMessage, | ||
AIMessage, | ||
HumanMessageChunk, | ||
SystemMessageChunk, | ||
ChatMessageChunk, | ||
FunctionMessageChunk, | ||
AIMessageChunk, | ||
StringPromptValue, | ||
ChatPromptValueConcrete, | ||
] | ||
|
||
|
||
# Custom JSON Encoder | ||
class _LangChainEncoder(json.JSONEncoder): | ||
"""Custom JSON Encoder that can encode pydantic objects as well.""" | ||
|
||
def default(self, obj) -> Any: | ||
if isinstance(obj, BaseModel): | ||
return obj.dict() | ||
return super().default(obj) | ||
|
||
|
||
# Custom JSON Decoder | ||
class _LangChainDecoder(json.JSONDecoder): | ||
"""Custom JSON Decoder that handles well known LangChain objects.""" | ||
|
||
def __init__(self, *args: Any, **kwargs: Any) -> None: | ||
"""Initialize the LangChainDecoder.""" | ||
super().__init__(object_hook=self.decoder, *args, **kwargs) | ||
|
||
def decoder(self, value) -> Any: | ||
"""Decode the value.""" | ||
if isinstance(value, dict): | ||
try: | ||
obj = WellKnownLCObject.parse_obj(value) | ||
return obj.__root__ | ||
except ValidationError: | ||
return {key: self.decoder(v) for key, v in value.items()} | ||
elif isinstance(value, list): | ||
return [self.decoder(item) for item in value] | ||
else: | ||
return value | ||
|
||
|
||
# PUBLIC API | ||
|
||
|
||
def simple_dumpd(obj: Any) -> Any: | ||
"""Convert the given object to a JSON serializable object.""" | ||
return json.loads(json.dumps(obj, cls=_LangChainEncoder)) | ||
|
||
|
||
def simple_dumps(obj: Any) -> str: | ||
"""Dump the given object as a JSON string.""" | ||
return json.dumps(obj, cls=_LangChainEncoder) | ||
|
||
|
||
def simple_loads(s: str) -> Any: | ||
"""Load the given JSON string.""" | ||
return json.loads(s, cls=_LangChainDecoder) |
Oops, something went wrong.
Oops, something went wrong.
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.
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
nice