1
0

log_callback_handler.py 1.8 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748
  1. from typing import Any, Dict, Optional
  2. from langchain.callbacks.base import BaseCallbackHandler
  3. from langchain.schema import AgentAction, AgentFinish
  4. from nicegui import ui
  5. class NiceGuiLogElementCallbackHandler(BaseCallbackHandler):
  6. """Callback Handler that writes to a log element."""
  7. def __init__(self, log_element: ui.log) -> None:
  8. """Initialize callback handler."""
  9. self.log = log_element
  10. def on_chain_start(self, serialized: Dict[str, Any], inputs: Dict[str, Any], **kwargs: Any) -> None:
  11. """Print out that we are entering a chain."""
  12. self.log.push(f'\n\n> Entering new {serialized["id"][-1]} chain...')
  13. def on_chain_end(self, outputs: Dict[str, Any], **kwargs: Any) -> None:
  14. """Print out that we finished a chain."""
  15. self.log.push('\n> Finished chain.')
  16. self.log.push(f'\nOutputs: {outputs}')
  17. def on_agent_action(self, action: AgentAction, **kwargs: Any) -> Any:
  18. """Run on agent action."""
  19. self.log.push(action.log)
  20. def on_tool_end(self,
  21. output: str,
  22. observation_prefix: Optional[str] = None,
  23. llm_prefix: Optional[str] = None,
  24. **kwargs: Any,
  25. ) -> None:
  26. """If not the final action, print out observation."""
  27. if observation_prefix is not None:
  28. self.log.push(f'\n{observation_prefix}')
  29. self.log.push(output)
  30. if llm_prefix is not None:
  31. self.log.push(f'\n{llm_prefix}')
  32. def on_text(self, text: str, **kwargs: Any) -> None:
  33. """Run when agent ends."""
  34. self.log.push(text)
  35. def on_agent_finish(self, finish: AgentFinish, **kwargs: Any) -> None:
  36. """Run on agent end."""
  37. self.log.push(finish.log)