Skip to content

Commit

Permalink
Allow callback handlers to opt into being run inline (#6424)
Browse files Browse the repository at this point in the history
This is useful eg for callback handlers that use context vars (like open
telemetry)

See #6095
  • Loading branch information
nfcampos committed Jun 22, 2023
1 parent a9108c1 commit 74ac6fb
Show file tree
Hide file tree
Showing 2 changed files with 13 additions and 3 deletions.
2 changes: 2 additions & 0 deletions langchain/callbacks/base.py
Original file line number Diff line number Diff line change
Expand Up @@ -194,6 +194,8 @@ class BaseCallbackHandler(

raise_error: bool = False

run_inline: bool = False

@property
def ignore_llm(self) -> bool:
"""Whether to ignore LLM callbacks."""
Expand Down
14 changes: 11 additions & 3 deletions langchain/callbacks/manager.py
Original file line number Diff line number Diff line change
Expand Up @@ -224,9 +224,12 @@ async def _ahandle_event_for_handler(
if asyncio.iscoroutinefunction(event):
await event(*args, **kwargs)
else:
await asyncio.get_event_loop().run_in_executor(
None, functools.partial(event, *args, **kwargs)
)
if handler.run_inline:
event(*args, **kwargs)
else:
await asyncio.get_event_loop().run_in_executor(
None, functools.partial(event, *args, **kwargs)
)
except NotImplementedError as e:
if event_name == "on_chat_model_start":
message_strings = [get_buffer_string(m) for m in args[1]]
Expand Down Expand Up @@ -259,12 +262,17 @@ async def _ahandle_event(
**kwargs: Any,
) -> None:
"""Generic event handler for AsyncCallbackManager."""
for handler in [h for h in handlers if h.run_inline]:
await _ahandle_event_for_handler(
handler, event_name, ignore_condition_name, *args, **kwargs
)
await asyncio.gather(
*(
_ahandle_event_for_handler(
handler, event_name, ignore_condition_name, *args, **kwargs
)
for handler in handlers
if not handler.run_inline
)
)

Expand Down

1 comment on commit 74ac6fb

@vercel
Copy link

@vercel vercel bot commented on 74ac6fb Jun 22, 2023

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Successfully deployed to the following URLs:

langchain – ./

langchain-git-master-langchain.vercel.app
langchain-langchain.vercel.app
python.langchain.com

Please sign in to comment.