File size: 15,239 Bytes
1b7e88c
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
import json
from pathlib import Path
from typing import Any, Dict, List, Optional, Union

import yaml
from omagent_core.base import BotBase
from omagent_core.models.llms.base import BaseLLM, BaseLLMBackend
from omagent_core.models.llms.prompt.prompt import PromptTemplate
from omagent_core.models.llms.schemas import Message
from omagent_core.utils.logger import logging
from omagent_core.utils.registry import registry
from pydantic import Field, field_validator

from .base import BaseTool

CURRENT_PATH = Path(__file__).parents[0]


class ToolManager(BaseLLMBackend):
    tools: Dict[str, BaseTool] = Field(
        default=registry.mapping["tool"], validate_default=True
    )
    llm: Optional[BaseLLM] = Field(default=None, validate_default=True)
    prompts: List[PromptTemplate] = Field(
        default=[
            PromptTemplate.from_file(
                CURRENT_PATH.joinpath("sys_prompt.prompt"), role="system"
            ),
            PromptTemplate.from_file(
                CURRENT_PATH.joinpath("user_prompt.prompt"), role="user"
            ),
        ]
    )

    @field_validator("tools", mode="before")
    @classmethod
    def init_tools(cls, tools: Union[List, Dict]) -> Dict[str, BaseTool]:
        if isinstance(tools, dict):
            for key, value in tools.items():
                if isinstance(value, type) and issubclass(value, BaseTool):
                    tools[key] = value = value()
                elif isinstance(value, dict):
                    tools[key] = value = registry.get_tool(key)(**value)
                elif not isinstance(value, BaseTool):
                    raise ValueError(
                        "The tool must be an instance of a sub class of BaseTool, not {}".format(
                            type(value)
                        )
                    )
                if key != value.name:
                    raise ValueError(
                        "The tool name {} not match with the tool {}.".format(
                            key, value.name
                        )
                    )
            return tools
        elif isinstance(tools, list):
            init_tools = {}
            for tool in tools:
                if isinstance(tool, str):
                    t = registry.get_tool(tool)
                    if isinstance(t, BaseTool):
                        init_tools[tool] = t
                    elif isinstance(t, type) and issubclass(t, BaseTool):
                        init_tools[tool] = t()
                    else:
                        raise ValueError("Invalid tool type {}".format(type(t)))
                elif isinstance(tool, dict):
                    t = registry.get_tool(tool["name"])
                    if isinstance(t, type) and issubclass(t, BaseTool):
                        init_tools[tool["name"]] = t(**tool)
                    else:
                        raise ValueError("Invalid tool type {}".format(type(t)))
                elif isinstance(tool, BaseTool):
                    init_tools[tool.name] = tool
                else:
                    raise ValueError("Invalid tool type {}".format(type(tool)))
            return init_tools
        else:
            raise ValueError(
                "Wrong tools type {}, should be list or dict in ToolManager".format(
                    type(tools)
                )
            )

    def model_post_init(self, __context: Any) -> None:
        for _, attr_value in self.__dict__.items():
            if isinstance(attr_value, BotBase):
                attr_value._parent = self
        for tool in self.tools.values():
            tool._parent = self

    @property
    def workflow_instance_id(self) -> str:
        if hasattr(self, "_parent"):
            return self._parent.workflow_instance_id
        return None

    @workflow_instance_id.setter
    def workflow_instance_id(self, value: str):
        if hasattr(self, "_parent"):
            self._parent.workflow_instance_id = value

    def add_tool(self, tool: BaseTool):
        self.tools[tool.name] = tool

    def tool_names(self) -> List:
        return list(self.tools.keys())

    def generate_prompt(self):
        prompt = ""
        for index, (name, tool) in enumerate(self.tools.items()):
            prompt += f"{index + 1}. {name}: {tool.description}\n"
        return prompt

    def generate_schema(self, style: str = "gpt"):
        if style == "gpt":
            return [tool.generate_schema() for tool in self.tools.values()]
        else:
            raise ValueError("Only support gpt style tool selection schema")

    def execute(self, tool_name: str, args: Union[str, dict]):
        if tool_name not in self.tools:
            raise KeyError(f"The tool {tool_name} is invalid, not in the tool list.")
        tool = self.tools.get(tool_name)
        if type(args) is str:
            try:
                args = json.loads(args)
            except Exception as error:
                if self.llm is not None:
                    try:
                        args = self.dynamic_json_fixs(
                            args, tool.generate_schema(), [], str(error)
                        )
                        args = json.loads(args)
                    except:
                        raise ValueError(
                            "The args for tool execution is not a valid json string and can not be fixed. [{}]".format(
                                args
                            )
                        )

                else:
                    raise ValueError(
                        "The args for tool execution is not a valid json string. [{}]".format(
                            args
                        )
                    )
        if tool.args_schema != None:
            args = tool.args_schema.validate_args(args)
        return tool.run(args)

    async def aexecute(self, tool_name: str, args: Union[str, dict]):
        if tool_name not in self.tools:
            raise KeyError(f"The tool {tool_name} is invalid, not in the tool list.")
        tool = self.tools.get(tool_name)
        if type(args) is str:
            try:
                args = json.loads(args)
            except Exception as error:
                if self.llm is not None:
                    try:
                        args = self.dynamic_json_fixs(
                            args, tool.generate_schema(), [], str(error)
                        )
                        args = json.loads(args)
                    except:
                        raise ValueError(
                            "The args for tool execution is not a valid json string and can not be fixed. [{}]".format(
                                args
                            )
                        )

                else:
                    raise ValueError(
                        "The args for tool execution is not a valid json string. [{}]".format(
                            args
                        )
                    )
        if tool.args_schema != None:
            args = tool.args_schema.validate_args(args)
        return await tool.arun(args)

    def dynamic_json_fixs(
        self,
        broken_json,
        function_schema,
        messages: list = [],
        error_message: str = None,
    ):
        logging.warning(
            "Schema Validation for Function call {} failed, trying to fix it...".format(
                function_schema["name"]
            )
        )
        messages = [
            *messages,
            {
                "role": "system",
                "content": "\n".join(
                    [
                        "Your last function call result in error",
                        "--- Error ---",
                        error_message,
                        "Your task is to fix all errors exist in the Broken Json String to make the json validate for the schema in the given function, and use new string to call the function again.",
                        "--- Notice ---",
                        "- You need to carefully check the json string and fix the errors or adding missing value in it.",
                        "- Do not give your own opinion or imaging new info or delete exisiting info!",
                        "- Make sure the new function call does not contains information about this fix task!",
                        "--- Broken Json String ---",
                        broken_json,
                        "Start!",
                    ]
                ),
            },
        ]
        fix_res = self.llm.generate(
            records=[Message(**item) for item in messages], tool_choice=function_schema
        )
        return fix_res["choices"][0]["message"]["tool_calls"][0]["function"][
            "arguments"
        ]

    @classmethod
    def from_file(cls, file: Union[str, Path]):
        if type(file) is str:
            file = Path(file)
        elif type(file) is not Path:
            raise ValueError("Only support str or pathlib.Path")
        if not file.exists():
            raise FileNotFoundError("The file {} is not exists.".format(file))
        if file.suffix == ".json":
            config = json.load(open(file, "r"))
        elif file.suffix in (".yaml", ".yml"):
            config = yaml.load(open(file, "r"), Loader=yaml.FullLoader)
        else:
            raise ValueError("Only support json or yaml file.")

        return cls(**config)

    def execute_task(self, task, related_info="", function=None):
        if self.llm == None:
            raise ValueError(
                "The execute_task method requires the llm field to be initialized."
            )
        chat_complete_res = self.infer(
            [{"task": task, "related_info": related_info}],
            tools=self.generate_schema(),
        )[0]
        logging.info(f"ToolManager execute_task chat_complete_res: {chat_complete_res}")
        content = chat_complete_res["choices"][0]["message"].get("content")
        tool_calls = chat_complete_res["choices"][0]["message"].get("tool_calls")
        if not tool_calls:
            toolcall_failed_structure = {
                "status": "failed",
                "content": content,
            }
            return "failed", content
        else:
            tool_calls = [tool_calls[0]]
            toolcall_structure = {
                "name": tool_calls[0]["function"]["name"],
                "arguments": json.loads(tool_calls[0]["function"]["arguments"]),
            }
            self.callback.info(
                agent_id=self.workflow_instance_id,
                progress=f"Conqueror",
                message=f'Tool {toolcall_structure["name"]} executing. Arguments: {toolcall_structure["arguments"]}',
            )
            tool_execution_res = []
            try:
                for each_tool_call in tool_calls:
                    result = self.execute(
                        each_tool_call["function"]["name"],
                        each_tool_call["function"]["arguments"],
                    )
                    tool_execution_res.append(result)
                toolcall_structure = {
                    "status": "success",
                    "tool_use": list(
                        set(
                            [
                                each_tool_call["function"]["name"]
                                for each_tool_call in tool_calls
                            ]
                        )
                    ),
                    "argument": [
                        each_tool_call["function"]["arguments"]
                        for each_tool_call in tool_calls
                    ],
                }
                return "success", tool_execution_res
            except ValueError as error:
                toolcall_failed_structure = {
                    "status": "failed",
                    "tool_use": list(
                        set(
                            [
                                each_tool_call["function"]["name"]
                                for each_tool_call in tool_calls
                            ]
                        )
                    ),
                    "argument": [
                        each_tool_call["function"]["arguments"]
                        for each_tool_call in tool_calls
                    ],
                    "error": str(error),
                }
                return "failed", str(error)

    async def aexecute_task(self, task, related_info=None, function=None):
        if self.llm == None:
            raise ValueError(
                "The execute_task method requires the llm field to be initialized."
            )
        chat_complete_res = await self.ainfer(
            [{"task": task, "related_info": list(related_info.keys())}],
            tools=self.generate_schema(),
        )[0]
        logging.info(f"ToolManager aexecute_task chat_complete_res: {chat_complete_res}")
        content = chat_complete_res["choices"][0]["message"].get("content")
        tool_calls = chat_complete_res["choices"][0]["message"].get("tool_calls")
        if not tool_calls:
            toolcall_failed_structure = {
                "status": "failed",
                "content": content,
            }
            return "failed", content
        else:
            toolcall_structure = {
                "name": tool_calls[0]["function"]["name"],
                "arguments": json.loads(tool_calls[0]["function"]["arguments"]),
            }
            tool_execution_res = []
            try:
                for each_tool_call in tool_calls:
                    tool_execution_res.append(
                        await self.aexecute(
                            each_tool_call["function"]["name"],
                            each_tool_call["function"]["arguments"],
                        )
                    )

                toolcall_structure = {
                    "status": "success",
                    "tool_use": list(
                        set(
                            [
                                each_tool_call["function"]["name"]
                                for each_tool_call in tool_calls
                            ]
                        )
                    ),
                    "argument": [
                        eval(each_tool_call["function"]["arguments"])
                        for each_tool_call in tool_calls
                    ],
                }
                return "success", tool_execution_res
            except ValueError as error:
                toolcall_failed_structure = {
                    "status": "failed",
                    "tool_use": list(
                        set(
                            [
                                each_tool_call["function"]["name"]
                                for each_tool_call in tool_calls
                            ]
                        )
                    ),
                    "argument": [
                        each_tool_call["function"]["arguments"]
                        for each_tool_call in tool_calls
                    ],
                    "error": str(error),
                }
                return "failed", str(error)