Skip to content

Fix: Handle list token in LangChain callback on_llm_new_token to prevent AttributeError #2191

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

Open
wants to merge 2 commits into
base: main
Choose a base branch
from
Open
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
18 changes: 16 additions & 2 deletions backend/chainlit/langchain/callbacks.py
Original file line number Diff line number Diff line change
Expand Up @@ -447,14 +447,28 @@ async def on_llm_new_token(
if start["tt_first_token"] is None:
start["tt_first_token"] = (time.time() - start["start"]) * 1000

# Process token to ensure it's a string, as strip() will be called on it.
processed_token: str
# Handle case where token is a list (can occur with some model outputs).
# Join all elements into a single string to maintain compatibility with downstream processing.
if isinstance(token, list):
# If token is a list, join its elements (converted to strings) into a single string.
processed_token = "".join(map(str, token))
elif not isinstance(token, str):
# If token is neither a list nor a string, convert it to a string.
processed_token = str(token)
else:
# If token is already a string, use it as is.
processed_token = token

if self.stream_final_answer:
self._append_to_last_tokens(token)
self._append_to_last_tokens(processed_token)

if self.answer_reached:
if not self.final_stream:
self.final_stream = Message(content="")
await self.final_stream.send()
await self.final_stream.stream_token(token)
await self.final_stream.stream_token(processed_token)
self.has_streamed_final_answer = True
else:
self.answer_reached = self._check_if_answer_reached()
Expand Down