Skip to content

Commit

Permalink
langchain(patch): Fix output type for pydantic output parser (#15714)
Browse files Browse the repository at this point in the history
This PR fixes the output type for the pydantic output parser.

Fix for: langchain-ai/langserve#301
  • Loading branch information
eyurtsev authored Jan 8, 2024
1 parent 95a2c92 commit 3a8ad90
Show file tree
Hide file tree
Showing 2 changed files with 35 additions and 1 deletion.
11 changes: 10 additions & 1 deletion libs/langchain/langchain/output_parsers/pydantic.py
Original file line number Diff line number Diff line change
Expand Up @@ -15,7 +15,11 @@ class PydanticOutputParser(BaseOutputParser[T]):
"""Parse an output using a pydantic model."""

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:
try:
Expand Down Expand Up @@ -51,3 +55,8 @@ def get_format_instructions(self) -> str:
@property
def _type(self) -> str:
return "pydantic"

@property
def OutputType(self) -> Type[T]:
"""Return the pydantic model."""
return self.pydantic_object
Original file line number Diff line number Diff line change
Expand Up @@ -76,3 +76,28 @@ def test_pydantic_output_parser_fail() -> None:
assert "Failed to parse TestModel from completion" in str(e)
else:
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",
}

0 comments on commit 3a8ad90

Please sign in to comment.