Patch forward ref bug (#12508)

Currently this gives a bug:
```
from langchain.schema.runnable import RunnableLambda

bound = RunnableLambda(lambda x: x).with_config({"callbacks": []})

# ConfigError: field "callbacks" not yet prepared so type is still a ForwardRef, you might need to call RunnableConfig.update_forward_refs().
```

Rather than deal with cyclic imports and extra load time, etc., I think
it makes sense to just have a separate Callbacks definition here that is
a relaxed typehint.
This commit is contained in:
William FH 2023-10-29 16:53:01 +09:00 committed by GitHub
parent 36204c2baf
commit a830b809f3
No known key found for this signature in database
GPG Key ID: 4AEE18F83AFDEB23
2 changed files with 17 additions and 1 deletions

View File

@ -32,6 +32,10 @@ if TYPE_CHECKING:
CallbackManager, CallbackManager,
CallbackManagerForChainRun, CallbackManagerForChainRun,
) )
else:
# Pydantic validates through typed dicts, but
# the callbacks need forward refs updated
Callbacks = Optional[Union[List, Any]]
class EmptyDict(TypedDict, total=False): class EmptyDict(TypedDict, total=False):

View File

@ -60,7 +60,11 @@ from langchain.schema.runnable import (
RunnableSequence, RunnableSequence,
RunnableWithFallbacks, RunnableWithFallbacks,
) )
from langchain.schema.runnable.base import ConfigurableField, RunnableGenerator from langchain.schema.runnable.base import (
ConfigurableField,
RunnableBinding,
RunnableGenerator,
)
from langchain.schema.runnable.utils import ( from langchain.schema.runnable.utils import (
ConfigurableFieldMultiOption, ConfigurableFieldMultiOption,
ConfigurableFieldSingleOption, ConfigurableFieldSingleOption,
@ -3999,3 +4003,11 @@ async def test_runnable_gen_transform() -> None:
assert list(chain.stream(3)) == [1, 2, 3] assert list(chain.stream(3)) == [1, 2, 3]
assert [p async for p in achain.astream(4)] == [1, 2, 3, 4] assert [p async for p in achain.astream(4)] == [1, 2, 3, 4]
def test_with_config_callbacks() -> None:
result = RunnableLambda(lambda x: x).with_config({"callbacks": []})
# Bugfix from version 0.0.325
# ConfigError: field "callbacks" not yet prepared so type is still a ForwardRef,
# you might need to call RunnableConfig.update_forward_refs().
assert isinstance(result, RunnableBinding)