-
Notifications
You must be signed in to change notification settings - Fork 896
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
fix: Async callback for langchain #353
Merged
Merged
Changes from 2 commits
Commits
Show all changes
4 commits
Select commit
Hold shift + click to select a range
File filter
Filter by extension
Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
There are no files selected for viewing
Large diffs are not rendered by default.
Oops, something went wrong.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,87 @@ | ||
from __future__ import annotations | ||
|
||
import asyncio | ||
from typing import Any, AsyncIterator | ||
from uuid import UUID | ||
|
||
from langchain.callbacks.base import AsyncCallbackHandler | ||
|
||
|
||
class AsyncIteratorCallbackHandler(AsyncCallbackHandler): | ||
"""Callback handler that returns an async iterator.""" | ||
|
||
@property | ||
def always_verbose(self) -> bool: | ||
return True | ||
|
||
def __init__(self) -> None: | ||
self.queue = asyncio.Queue() | ||
self.done = asyncio.Event() | ||
|
||
async def on_chain_start( | ||
self, | ||
serialized: dict[str, Any], | ||
inputs: dict[str, Any], | ||
*, | ||
run_id: UUID, | ||
parent_run_id: UUID | None = None, | ||
tags: list[str] | None = None, | ||
metadata: dict[str, Any] | None = None, | ||
**kwargs: Any, | ||
) -> None: | ||
self.done.clear() | ||
|
||
async def on_llm_new_token(self, token: str, **kwargs: Any) -> None: | ||
if token is not None and token != "": | ||
print(token, end="") | ||
self.queue.put_nowait(token) | ||
|
||
async def on_chain_end( | ||
self, | ||
outputs: dict[str, Any], | ||
*, | ||
run_id: UUID, | ||
parent_run_id: UUID | None = None, | ||
tags: list[str] | None = None, | ||
**kwargs: Any, | ||
) -> None: | ||
self.done.set() | ||
|
||
async def on_chain_error( | ||
self, | ||
error: BaseException, | ||
*, | ||
run_id: UUID, | ||
parent_run_id: UUID | None = None, | ||
tags: list[str] | None = None, | ||
**kwargs: Any, | ||
) -> None: | ||
self.done.set() | ||
|
||
async def aiter(self) -> AsyncIterator[str]: | ||
while not self.queue.empty() or not self.done.is_set(): | ||
# Wait for the next token in the queue, | ||
# but stop waiting if the done event is set | ||
done, other = await asyncio.wait( | ||
[ | ||
# NOTE: If you add other tasks here, update the code below, | ||
# which assumes each set has exactly one task each | ||
asyncio.ensure_future(self.queue.get()), | ||
asyncio.ensure_future(self.done.wait()), | ||
], | ||
return_when=asyncio.FIRST_COMPLETED, | ||
) | ||
|
||
# Cancel the other task | ||
if other: | ||
other.pop().cancel() | ||
|
||
# Extract the value of the first completed task | ||
token_or_done = done.pop().result() | ||
|
||
# If the extracted value is the boolean True, the done event was set | ||
if token_or_done is True: | ||
break | ||
|
||
# Otherwise, the extracted value is a token, which we yield | ||
yield token_or_done |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file was deleted.
Oops, something went wrong.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Add this suggestion to a batch that can be applied as a single commit.
This suggestion is invalid because no changes were made to the code.
Suggestions cannot be applied while the pull request is closed.
Suggestions cannot be applied while viewing a subset of changes.
Only one suggestion per line can be applied in a batch.
Add this suggestion to a batch that can be applied as a single commit.
Applying suggestions on deleted lines is not supported.
You must change the existing code in this line in order to create a valid suggestion.
Outdated suggestions cannot be applied.
This suggestion has been applied or marked resolved.
Suggestions cannot be applied from pending reviews.
Suggestions cannot be applied on multi-line comments.
Suggestions cannot be applied while the pull request is queued to merge.
Suggestion cannot be applied right now. Please check back later.
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
seems we need drop this print
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
Haha, that is to display the text to console in stream mode. Intended.
All other bots have such prints, too
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
copy that!