Base class for tools. A tool should support the following methods: - `to_openai_function_tool_schema`: return the tool schema in OpenAI format. - `create`: create a tool instance for a trajectory. - `execute`: execute the tool. - `calc_reward`: calculate the reward respect to t
| 22 | |
| 23 | |
| 24 | class BaseTool: |
| 25 | """Base class for tools. |
| 26 | |
| 27 | A tool should support the following methods: |
| 28 | |
| 29 | - `to_openai_function_tool_schema`: return the tool schema in OpenAI format. |
| 30 | - `create`: create a tool instance for a trajectory. |
| 31 | - `execute`: execute the tool. |
| 32 | - `calc_reward`: calculate the reward respect to tool state. |
| 33 | - `release`: release the tool instance. |
| 34 | """ |
| 35 | |
| 36 | def __init__(self, config: dict, tool_schema: OpenAIFunctionToolSchema): |
| 37 | self.config = config |
| 38 | self._instance_dict = {} |
| 39 | self.tool_schema = tool_schema or self.get_openai_tool_schema() |
| 40 | assert self.tool_schema is not None, "Tool schema is not set!" |
| 41 | self.name = self.tool_schema.function.name |
| 42 | # print(json.dumps(self.tool_schema.model_dump(exclude_unset=True, exclude_none=True), indent=2)) |
| 43 | |
| 44 | def get_openai_tool_schema(self) -> OpenAIFunctionToolSchema: |
| 45 | return self.tool_schema |
| 46 | |
| 47 | |
| 48 | async def create(self, instance_id: Optional[str] = None, identity: dict = None, **kwargs) -> str: |
| 49 | """创建工具实例""" |
| 50 | if instance_id is None: |
| 51 | instance_id = str(uuid4()) |
| 52 | self._instance_dict[instance_id] = identity |
| 53 | return instance_id |
| 54 | |
| 55 | @rollout_trace_op |
| 56 | async def execute(self, instance_id: str, parameters: dict[str, Any], **kwargs) -> tuple[str, float, dict]: |
| 57 | """Execute the tool. |
| 58 | |
| 59 | Args: |
| 60 | instance_id: The instance id of the tool. |
| 61 | parameters: The json string of the parameters of the tool. |
| 62 | |
| 63 | Returns: tool_response, tool_reward_score, tool_metrics |
| 64 | tool_response: The response str of the tool. |
| 65 | tool_reward_score: The step reward score of the tool. |
| 66 | tool_metrics: The metrics of the tool. |
| 67 | """ |
| 68 | return "Updated the tool state.", 0.0, {} |
| 69 | |
| 70 | async def calc_reward(self, instance_id: str, **kwargs) -> float: |
| 71 | """Calculate the reward of the tool. |
| 72 | |
| 73 | Args: |
| 74 | instance_id: The instance id of the tool. |
| 75 | |
| 76 | Returns: |
| 77 | The reward of the tool. |
| 78 | """ |
| 79 | # 这个函数计算的是tool reward, 结果是能传到reward manager中的. 具体使用则取决于reward manager |
| 80 | return 0.0 |
| 81 |
nothing calls this directly
no outgoing calls
no test coverage detected