Base callback handler
| 1 | from typing import Any, Dict, List, Union |
| 2 | import queue |
| 3 | class ServerEventCallback(): |
| 4 | """Base callback handler""" |
| 5 | |
| 6 | def __init__(self, queue: queue.Queue, *args, **kwargs): |
| 7 | super().__init__(*args, **kwargs) |
| 8 | self.queue = queue |
| 9 | self.llm_block_id = 0 |
| 10 | self.tool_block_id = 0 |
| 11 | self.tool_descriptions = {} |
| 12 | |
| 13 | def add_to_queue(self, method_name: str, block_id, **kwargs: Any): |
| 14 | data = { |
| 15 | "method_name": method_name, |
| 16 | "block_id": block_id, |
| 17 | } |
| 18 | data.update(kwargs) |
| 19 | self.queue.put(data) |
| 20 | |
| 21 | def on_tool_retrieval_start(self): |
| 22 | # tools should be of the form |
| 23 | # {tool_name, tool_desc} |
| 24 | self.add_to_queue( |
| 25 | "on_tool_retrieval_start", |
| 26 | "recommendation-1", |
| 27 | ) |
| 28 | print("on_tool_retrieval_start method called") |
| 29 | |
| 30 | def on_tool_retrieval_end(self, tools): |
| 31 | # tool should be of the form |
| 32 | # {tool_name, tool_desc} |
| 33 | self.add_to_queue( |
| 34 | "on_tool_retrieval_end", |
| 35 | "recommendation-1", |
| 36 | recommendations=tools |
| 37 | ) |
| 38 | self.tool_descriptions = { |
| 39 | tool["name"]: tool for tool in tools |
| 40 | } |
| 41 | print("on_tool_retrieval_end method called") |
| 42 | def on_request_start(self, user_input: str, method: str) -> Any: |
| 43 | self.tool_block_id = 0 |
| 44 | self.llm_block_id = 0 |
| 45 | self.add_to_queue( |
| 46 | "on_request_start", |
| 47 | block_id="start", |
| 48 | user_input=user_input, |
| 49 | method=method |
| 50 | ) |
| 51 | def on_request_end(self, outputs: str, chain: List[Any]): |
| 52 | self.add_to_queue( |
| 53 | "on_request_end", |
| 54 | block_id="end", |
| 55 | output=outputs, |
| 56 | chain=chain |
| 57 | ) |
| 58 | def on_request_error(self, error: str): |
| 59 | self.add_to_queue( |
| 60 | "on_request_error", |