mirror of
https://github.com/hwchase17/langchain.git
synced 2025-07-01 10:54:15 +00:00
langchain(patch): Fix output type for pydantic output parser (#15714)
This PR fixes the output type for the pydantic output parser. Fix for: https://github.com/langchain-ai/langserve/issues/301
This commit is contained in:
parent
95a2c92e26
commit
3a8ad90509
@ -15,7 +15,11 @@ class PydanticOutputParser(BaseOutputParser[T]):
|
|||||||
"""Parse an output using a pydantic model."""
|
"""Parse an output using a pydantic model."""
|
||||||
|
|
||||||
pydantic_object: Type[T]
|
pydantic_object: Type[T]
|
||||||
"""The pydantic model to parse."""
|
"""The pydantic model to parse.
|
||||||
|
|
||||||
|
Attention: To avoid potential compatibility issues, it's recommended to use
|
||||||
|
pydantic <2 or leverage the v1 namespace in pydantic >= 2.
|
||||||
|
"""
|
||||||
|
|
||||||
def parse(self, text: str) -> T:
|
def parse(self, text: str) -> T:
|
||||||
try:
|
try:
|
||||||
@ -51,3 +55,8 @@ class PydanticOutputParser(BaseOutputParser[T]):
|
|||||||
@property
|
@property
|
||||||
def _type(self) -> str:
|
def _type(self) -> str:
|
||||||
return "pydantic"
|
return "pydantic"
|
||||||
|
|
||||||
|
@property
|
||||||
|
def OutputType(self) -> Type[T]:
|
||||||
|
"""Return the pydantic model."""
|
||||||
|
return self.pydantic_object
|
||||||
|
@ -76,3 +76,28 @@ def test_pydantic_output_parser_fail() -> None:
|
|||||||
assert "Failed to parse TestModel from completion" in str(e)
|
assert "Failed to parse TestModel from completion" in str(e)
|
||||||
else:
|
else:
|
||||||
assert False, "Expected OutputParserException"
|
assert False, "Expected OutputParserException"
|
||||||
|
|
||||||
|
|
||||||
|
def test_pydantic_output_parser_type_inference() -> None:
|
||||||
|
"""Test pydantic output parser type inference."""
|
||||||
|
|
||||||
|
class SampleModel(BaseModel):
|
||||||
|
foo: int
|
||||||
|
bar: str
|
||||||
|
|
||||||
|
# Ignoring mypy error that appears in python 3.8, but not 3.11.
|
||||||
|
# This seems to be functionally correct, so we'll ignore the error.
|
||||||
|
pydantic_parser = PydanticOutputParser(
|
||||||
|
pydantic_object=SampleModel # type: ignore[var-annotated]
|
||||||
|
)
|
||||||
|
schema = pydantic_parser.get_output_schema().schema()
|
||||||
|
|
||||||
|
assert schema == {
|
||||||
|
"properties": {
|
||||||
|
"bar": {"title": "Bar", "type": "string"},
|
||||||
|
"foo": {"title": "Foo", "type": "integer"},
|
||||||
|
},
|
||||||
|
"required": ["foo", "bar"],
|
||||||
|
"title": "SampleModel",
|
||||||
|
"type": "object",
|
||||||
|
}
|
||||||
|
Loading…
Reference in New Issue
Block a user