Skip to content

Commit d6b0eca

Browse files
authored
[Py] Suport yield & return from wrapped generators (#951)
Sync only (since python async generators dont' support it anyhow)
1 parent e034266 commit d6b0eca

File tree

3 files changed

+110
-81
lines changed

3 files changed

+110
-81
lines changed

python/langsmith/run_helpers.py

Lines changed: 9 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -625,6 +625,7 @@ def generator_wrapper(
625625
inspect.signature(func).parameters.get("run_tree", None) is not None
626626
)
627627
results: List[Any] = []
628+
function_return: Any = None
628629
try:
629630
if func_accepts_parent_run:
630631
kwargs["run_tree"] = run_container["new_run"]
@@ -653,8 +654,13 @@ def generator_wrapper(
653654
yield item
654655
except GeneratorExit:
655656
break
656-
except StopIteration:
657-
pass
657+
except StopIteration as e:
658+
function_return = e.value
659+
if function_return is not None:
660+
# In 99% of cases, people yield OR return; to keep
661+
# backwards compatibility, we'll only return if there's
662+
# return value is non-null.
663+
results.append(function_return)
658664

659665
except BaseException as e:
660666
_on_run_end(run_container, error=e)
@@ -671,6 +677,7 @@ def generator_wrapper(
671677
else:
672678
function_result = None
673679
_on_run_end(run_container, outputs=function_result)
680+
return function_return
674681

675682
if inspect.isasyncgenfunction(func):
676683
selected_wrapper: Callable = async_generator_wrapper

0 commit comments

Comments
 (0)