Handle streaming responses via Callbacks
mainTo process tokens as they are generated, set streaming=True and provide a callback handler to the generate method. You can implement custom logic by inheriting from BaseCallbackHandler and overriding on_llm_new_token.
on_llm_new_token receives the token and a kwargs dictionary. The kwargs dictionary contains llm_output (including token usage) and a final flag indicating if it is the last chunk.
from sparkai.core.callbacks import BaseCallbackHandler
from typing import Any, Optional
class ChunkPrintHandler(BaseCallbackHandler):
"""Callback Handler that prints to std out."""
def __init__(self, color: Optional[str] = None) -> None:
self.color = color
def on_llm_new_token(self, token: str, *, chunk: None = None, **kwargs: Any):
print(token)
# kwargs contains llm_output with usage info and 'final' status