toolbase.py 1.9 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768
  1. from abc import ABC, abstractmethod, abstractproperty
  2. from typing import Callable
  3. from wcf_wrapper import ContentType
  4. import wcf_wrapper
  5. from config import Config
  6. # 继承类需要用到
  7. import json
  8. import common
  9. from common import ChatMsg, MSG_CALLBACK
  10. class ToolBase(ABC):
  11. """ 工具的基础接口类. 自定义工具请继承这个类并实现各抽象方法 """
  12. config:Config
  13. """ 配置对象, 来自config.yaml"""
  14. def __init__(self, config:Config) -> None:
  15. """ 初始化工具
  16. args:
  17. config (Config): 配置
  18. """
  19. super().__init__()
  20. self.config = config
  21. def validate_config(self) -> bool:
  22. """ 确认配置是否正确。配置不正确的工具将不会被启用
  23. 若config.TOOLS 不包含自己的名字, 则返回False
  24. returns:
  25. bool: True=OK, False=配置错误
  26. """
  27. if self.name in self.config.TOOLS:
  28. return True
  29. else:
  30. return False
  31. @property
  32. @abstractproperty
  33. def name(self) -> str:
  34. """ 工具名称, 与openAI function name一致 """
  35. pass
  36. @property
  37. @abstractproperty
  38. def desc(self) -> str:
  39. """ 简短帮助说明 """
  40. pass
  41. @property
  42. @abstractproperty
  43. def function_json(self) -> dict:
  44. """ OPEN AI Function 定义, json. 参见 https://platform.openai.com/docs/assistants/tools/function-calling"""
  45. pass
  46. @abstractmethod
  47. def process_toolcall(self, arguments:str, callback_msg:MSG_CALLBACK) -> str:
  48. """ 处理Run中途的toolcall
  49. 参考: https://platform.openai.com/docs/assistants/tools/function-calling
  50. Args:
  51. arguments (str): toolcall arguments json
  52. callback_msg (MSG_CALLBACK): 回调函数, 用于发送微信消息
  53. Returns:
  54. str: Toolcall 处理结果
  55. Raise:
  56. 可以raise Exception, 外层会接住
  57. """