-
Notifications
You must be signed in to change notification settings - Fork 14.5k
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
[BUG] Logic error when nesting Chain, and no error message #25603
Comments
Since there are no errors reported and no restrictions, this bug is a fatal bug. |
This is an issue with pydantic's Smart Union. You can change class ExpandChain(Chain):
expand_type: Literal["regex", "llm"]
chain: _RegexExpandChain | _LLMExpandChain | None = None
@root_validator(pre=False) # change pre = False The following is a simple example. from pydantic.v1 import BaseModel
def test(pre: bool, n):
class Convert(BaseModel):
number: str | int
@root_validator(pre=pre)
def convert_int(cls, values: dict):
v = values.get("number")
print(f"{pre = }, source {type(v) = }")
if isinstance(v, str):
v = int(v)
values["number"] = v
return values
output = Convert(number=n).number
print(f"{pre = }, output {type(output) = }")
print("=" * 10)
test(pre=True, n="1") # always str
test(pre=True, n=1) # always str
test(pre=False, n="1") # after convert to int
test(pre=False, n=1) In short, because you used However, afterwards, Pydantic attempts to convert the chain into your specified |
But why does it return exactly what I want when I set up |
Because they are all However, if it's from pydantic.v1 import BaseModel
class Convert(BaseModel):
v: int | str
# Pydantic first attempts to convert the input to an int;
# if it fails, it tries to convert it to a str,
# and if that also fails, it raises an error.
print(type(Convert(v="1").v)) # is int, because it can convert to int
print(type(Convert(v="a").v)) # is str, because it can't convert to int
print(type(Convert(v=[1]).v)) # raise ValidationError, because it can't convert to int or str In this example, even though "1" already satisfies the condition of int | str, under the handling of Union, it will still attempt type conversion. |
Another option is to set class ExpandChain(Chain):
expand_type: Literal["regex", "llm"]
chain: _RegexExpandChain | _LLMExpandChain | None = None # will always use _RegexExpandChain
# chain: Chain | None = None # will be correct
class Config:
smart_union = True
@root_validator(pre=True) |
Checked other resources
Example Code
Error Message and Stack Trace (if applicable)
No any error message
Description
See example code and comment for details
System Info
langchain==0.2.14
langchain-community==0.2.12
langchain-core==0.2.33
langchain-openai==0.1.22
langchain-text-splitters==0.2.2
platform: ubuntu20.04
python version: python3.10
The text was updated successfully, but these errors were encountered: