core[patch]: remove v1_repr (#26165)

Co-authored-by: Erick Friis <erick@langchain.dev>
This commit is contained in:
Bagatur
2024-09-06 17:00:52 -04:00
committed by GitHub
parent b664b3364c
commit 6df9360e32
8 changed files with 24 additions and 81 deletions

View File

@@ -9,7 +9,6 @@ from typing import Any, Dict, Generator, List, Literal, Optional, Union, cast
from pydantic import ConfigDict, Field, model_validator
from langchain_core.load.serializable import Serializable
from langchain_core.utils.pydantic import v1_repr
PathLike = Union[str, PurePath]
@@ -297,7 +296,3 @@ class Document(BaseMedia):
return f"page_content='{self.page_content}' metadata={self.metadata}"
else:
return f"page_content='{self.page_content}'"
def __repr__(self) -> str:
# TODO(0.3): Remove this override after confirming unit tests!
return v1_repr(self)

View File

@@ -13,8 +13,6 @@ from typing import (
from pydantic import BaseModel, ConfigDict
from typing_extensions import NotRequired
from langchain_core.utils.pydantic import v1_repr
class BaseSerialized(TypedDict):
"""Base class for serialized objects.
@@ -259,10 +257,6 @@ class Serializable(BaseModel, ABC):
def to_json_not_implemented(self) -> SerializedNotImplemented:
return to_json_not_implemented(self)
def __repr__(self) -> str:
# TODO(0.3): Remove this override after confirming unit tests!
return v1_repr(self)
def _is_field_useful(inst: Serializable, key: str, value: Any) -> bool:
"""Check if a field is useful as a constructor argument.

View File

@@ -8,7 +8,6 @@ from langchain_core.load.serializable import Serializable
from langchain_core.utils import get_bolded_text
from langchain_core.utils._merge import merge_dicts, merge_lists
from langchain_core.utils.interactive_env import is_interactive_env
from langchain_core.utils.pydantic import v1_repr
if TYPE_CHECKING:
from langchain_core.prompts.chat import ChatPromptTemplate
@@ -111,10 +110,6 @@ class BaseMessage(Serializable):
def pretty_print(self) -> None:
print(self.pretty_repr(html=is_interactive_env())) # noqa: T201
def __repr__(self) -> str:
# TODO(0.3): Remove this override after confirming unit tests!
return v1_repr(self)
def merge_content(
first_content: Union[str, List[Union[str, Dict]]],

View File

@@ -186,34 +186,6 @@ class _IgnoreUnserializable(GenerateJsonSchema):
return {}
def v1_repr(obj: BaseModel) -> str:
"""Return the schema of the object as a string.
Get a repr for the pydantic object which is consistent with pydantic.v1.
"""
if not is_basemodel_instance(obj):
raise TypeError(f"Expected a pydantic BaseModel, got {type(obj)}")
repr_ = []
for name, field in get_fields(obj).items():
value = getattr(obj, name)
if isinstance(value, BaseModel):
repr_.append(f"{name}={v1_repr(value)}")
else:
if field.exclude:
continue
if not field.is_required():
if not value:
continue
if field.default == value:
continue
repr_.append(f"{name}={repr(value)}")
args = ", ".join(repr_)
return f"{obj.__class__.__name__}({args})"
def _create_subset_model_v1(
name: str,
model: Type[BaseModel],

View File

@@ -12,7 +12,7 @@ def test_str() -> None:
def test_repr() -> None:
assert (
repr(Document(page_content="Hello, World!"))
== "Document(page_content='Hello, World!')"
== "Document(metadata={}, page_content='Hello, World!')"
)
assert (
repr(Document(page_content="Hello, World!", metadata={"a": 3}))

File diff suppressed because one or more lines are too long

View File

@@ -2942,13 +2942,15 @@ Question:
}
assert chat_spy.call_args.args[1] == ChatPromptValue(
messages=[
SystemMessage(content="You are a nice assistant."),
SystemMessage(
content="You are a nice assistant.",
additional_kwargs={},
response_metadata={},
),
HumanMessage(
content="""Context:
[Document(page_content='foo'), Document(page_content='bar')]
Question:
What is your name?"""
content="Context:\n[Document(metadata={}, page_content='foo'), Document(metadata={}, page_content='bar')]\n\nQuestion:\nWhat is your name?",
additional_kwargs={},
response_metadata={},
),
]
)

View File

@@ -12,7 +12,6 @@ from langchain_core.utils.pydantic import (
is_basemodel_instance,
is_basemodel_subclass,
pre_init,
v1_repr,
)
@@ -195,17 +194,3 @@ def test_fields_pydantic_v1_from_2() -> None:
fields = get_fields(Foo)
assert fields == {"x": Foo.__fields__["x"]}
def test_v1_repr() -> None:
from pydantic import BaseModel, Field
class Foo(BaseModel):
bar: int = Field(default=1, alias="baz", exclude=True)
x: int = Field(default=2)
def __repr__(self) -> str:
"""Custom repr."""
return v1_repr(self)
assert repr(Foo(bar=2, x=3)) == "Foo(x=3)" # type: ignore[call-arg]