abstract_tool_parser.py 2.1 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152
  1. from typing import Dict, List, Sequence, Union
  2. from aphrodite.endpoints.openai.protocol import (DeltaMessage,
  3. ExtractedToolCallInformation)
  4. from aphrodite.transformers_utils.tokenizer import AnyTokenizer
  5. class ToolParser:
  6. """
  7. Abstract ToolParser class that should not be used directly. Provided
  8. properties and methods should be used in
  9. derived classes.
  10. """
  11. def __init__(self, tokenizer: AnyTokenizer):
  12. self.prev_tool_call_arr: List[Dict] = []
  13. # the index of the tool call that is currently being parsed
  14. self.current_tool_id: int = -1
  15. self.current_tool_name_sent: bool = False
  16. self.streamed_args_for_tool: List[str] = []
  17. self.model_tokenizer = tokenizer
  18. def extract_tool_calls(self,
  19. model_output: str) -> ExtractedToolCallInformation:
  20. """
  21. Static method that should be implemented for extracting tool calls from
  22. a complete model-generated string.
  23. Used for non-streaming responses where we have the entire model response
  24. available before sending to the client.
  25. Static because it's stateless.
  26. """
  27. raise NotImplementedError(
  28. "AbstractToolParser.extract_tool_calls has not been implemented!")
  29. def extract_tool_calls_streaming(
  30. self,
  31. previous_text: str,
  32. current_text: str,
  33. delta_text: str,
  34. previous_token_ids: Sequence[int],
  35. current_token_ids: Sequence[int],
  36. delta_token_ids: Sequence[int],
  37. ) -> Union[DeltaMessage, None]:
  38. """
  39. Instance method that should be implemented for extracting tool calls
  40. from an incomplete response; for use when handling tool calls and
  41. streaming. Has to be an instance method because it requires state -
  42. the current tokens/diffs, but also the information about what has
  43. previously been parsed and extracted (see constructor)
  44. """
  45. raise NotImplementedError(
  46. "AbstractToolParser.extract_tool_calls_streaming has not been "
  47. "implemented!")