core[patch]: ensure iterator_ in scope for _atransform_stream_with_config except (#24454)

Before, if an exception was raised in the outer `try` block in
`Runnable._atransform_stream_with_config` before `iterator_` is
assigned, the corresponding `finally` block would blow up with an
`UnboundLocalError`:

```txt
UnboundLocalError: cannot access local variable 'iterator_' where it is not associated with a value
```

By assigning an initial value to `iterator_` before entering the `try`
block, this commit ensures that the `finally` can run, and not bury the
"true" exception under a "During handling of the above exception [...]"
traceback.

Thanks for your consideration!
This commit is contained in:
Will Badart 2024-07-19 20:24:04 -07:00 committed by GitHub
parent 7b28359719
commit 74e3d796f1
No known key found for this signature in database
GPG Key ID: B5690EEEBB952194

View File

@ -2127,6 +2127,7 @@ class Runnable(Generic[Input, Output], ABC):
name=config.get("run_name") or self.get_name(),
run_id=config.pop("run_id", None),
)
iterator_ = None
try:
child_config = patch_config(config, callbacks=run_manager.get_child())
if accepts_config(transformer):
@ -2193,7 +2194,7 @@ class Runnable(Generic[Input, Output], ABC):
else:
await run_manager.on_chain_end(final_output, inputs=final_input)
finally:
if hasattr(iterator_, "aclose"):
if iterator_ is not None and hasattr(iterator_, "aclose"):
await iterator_.aclose()
@beta_decorator.beta(message="This API is in beta and may change in the future.")