Spaces:
Sleeping
Sleeping
Upload 7 files
Browse files- aworld/core/tool/action.py +54 -0
- aworld/core/tool/action_factory.py +110 -0
- aworld/core/tool/action_template.py +45 -0
- aworld/core/tool/base.py +539 -0
- aworld/core/tool/func_to_tool.py +270 -0
- aworld/core/tool/tool_desc.py +121 -0
- aworld/core/tool/tool_template.py +82 -0
aworld/core/tool/action.py
ADDED
|
@@ -0,0 +1,54 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
# coding: utf-8
|
| 2 |
+
# Copyright (c) 2025 inclusionAI.
|
| 3 |
+
import abc
|
| 4 |
+
from enum import Enum, EnumMeta
|
| 5 |
+
from typing import Tuple, Any
|
| 6 |
+
|
| 7 |
+
from aworld.core.common import ToolActionInfo, ActionModel, ActionResult
|
| 8 |
+
|
| 9 |
+
|
| 10 |
+
class ExecutableAction(object):
|
| 11 |
+
__metaclass__ = abc.ABCMeta
|
| 12 |
+
|
| 13 |
+
@abc.abstractmethod
|
| 14 |
+
def act(self, action: ActionModel, **kwargs) -> Tuple[ActionResult, Any]:
|
| 15 |
+
"""Execute the action."""
|
| 16 |
+
|
| 17 |
+
@abc.abstractmethod
|
| 18 |
+
async def async_act(self, action: ActionModel, **kwargs) -> Tuple[ActionResult, Any]:
|
| 19 |
+
"""Execute the action."""
|
| 20 |
+
|
| 21 |
+
|
| 22 |
+
class DynamicEnumMeta(EnumMeta):
|
| 23 |
+
def __new__(metacls, cls, bases, classdict):
|
| 24 |
+
for name, value in classdict.items():
|
| 25 |
+
if isinstance(value, tuple) and len(value) == 2:
|
| 26 |
+
classdict[name] = (value[0], value[1])
|
| 27 |
+
return super().__new__(metacls, cls, bases, classdict)
|
| 28 |
+
|
| 29 |
+
|
| 30 |
+
class ToolAction(Enum, metaclass=DynamicEnumMeta):
|
| 31 |
+
@classmethod
|
| 32 |
+
def get_value_by_name(cls, name: str) -> ToolActionInfo | None:
|
| 33 |
+
members = cls.members()
|
| 34 |
+
name = name.upper()
|
| 35 |
+
if name in members:
|
| 36 |
+
if hasattr(members[name], 'value'):
|
| 37 |
+
return members[name].value
|
| 38 |
+
else:
|
| 39 |
+
return members[name]
|
| 40 |
+
return None
|
| 41 |
+
|
| 42 |
+
@classmethod
|
| 43 |
+
def members(cls):
|
| 44 |
+
return dict(filter(lambda item: not item[0].startswith("_"), cls.__dict__.items()))
|
| 45 |
+
|
| 46 |
+
|
| 47 |
+
TOOL_ACTION = """
|
| 48 |
+
from aworld.config.tool_action import ToolAction
|
| 49 |
+
from aworld.core.common import ToolActionInfo, ParamInfo
|
| 50 |
+
|
| 51 |
+
class {name}Action(ToolAction):
|
| 52 |
+
'''{name} action enum.'''
|
| 53 |
+
# ERROR = ToolActionInfo(name="error", desc="action error")
|
| 54 |
+
"""
|
aworld/core/tool/action_factory.py
ADDED
|
@@ -0,0 +1,110 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
# coding: utf-8
|
| 2 |
+
# Copyright (c) 2025 inclusionAI.
|
| 3 |
+
|
| 4 |
+
import logging
|
| 5 |
+
import sys
|
| 6 |
+
from typing import Dict, List
|
| 7 |
+
|
| 8 |
+
from aworld.core.factory import Factory
|
| 9 |
+
from aworld.logs.util import logger
|
| 10 |
+
|
| 11 |
+
|
| 12 |
+
class ActionManager(Factory):
|
| 13 |
+
def __init__(self, type_name: str = None):
|
| 14 |
+
super(ActionManager, self).__init__(type_name)
|
| 15 |
+
self._tool_action_mapping: Dict[str, str] = {}
|
| 16 |
+
self._tool_action_cache: Dict[str, List[str]] = {}
|
| 17 |
+
|
| 18 |
+
def __call__(self, name: str, tool_name: str = None, **kwargs):
|
| 19 |
+
if name is None:
|
| 20 |
+
raise ValueError("action name is None")
|
| 21 |
+
if tool_name is None:
|
| 22 |
+
tool_name = ""
|
| 23 |
+
|
| 24 |
+
final_name = tool_name + name
|
| 25 |
+
try:
|
| 26 |
+
if final_name in self._cls:
|
| 27 |
+
act = self._cls[final_name](**kwargs)
|
| 28 |
+
else:
|
| 29 |
+
raise RuntimeError("The action was not registered.\nPlease confirm the package has been imported.")
|
| 30 |
+
except Exception:
|
| 31 |
+
err = sys.exc_info()
|
| 32 |
+
logging.warning("Failed to create action with name '%s':\n%s" % (name, err[1]), exc_info=err)
|
| 33 |
+
act = None
|
| 34 |
+
|
| 35 |
+
if act is None:
|
| 36 |
+
act = UnknownAction(name=name, **kwargs)
|
| 37 |
+
act.name = name
|
| 38 |
+
return act
|
| 39 |
+
|
| 40 |
+
def register(self, name: str, desc: str, **kwargs):
|
| 41 |
+
def func(cls):
|
| 42 |
+
tool_name = kwargs.get("tool_name")
|
| 43 |
+
if not tool_name:
|
| 44 |
+
logger.warning("tool name is empty")
|
| 45 |
+
tool_name = ""
|
| 46 |
+
if name in self._cls and self._tool_action_mapping.get(name) == tool_name:
|
| 47 |
+
logger.warning(f"{tool_name} tool {name} action already in {self._type} factory, will override it.")
|
| 48 |
+
|
| 49 |
+
self._tool_action_mapping[name] = tool_name
|
| 50 |
+
final_name = tool_name + name
|
| 51 |
+
self._cls[final_name] = cls
|
| 52 |
+
self._desc[final_name] = desc
|
| 53 |
+
self._ext_info[final_name] = kwargs
|
| 54 |
+
return cls
|
| 55 |
+
|
| 56 |
+
return func
|
| 57 |
+
|
| 58 |
+
def get_actions_by_tool(self, tool_name: str):
|
| 59 |
+
if tool_name in self._tool_action_cache:
|
| 60 |
+
return self._tool_action_cache[tool_name]
|
| 61 |
+
|
| 62 |
+
actions = []
|
| 63 |
+
for action_name, v in self._tool_action_mapping.items():
|
| 64 |
+
if tool_name == v:
|
| 65 |
+
actions.append(action_name)
|
| 66 |
+
self._tool_action_cache[tool_name] = actions
|
| 67 |
+
return actions
|
| 68 |
+
|
| 69 |
+
|
| 70 |
+
ActionFactory = ActionManager("action_type")
|
| 71 |
+
|
| 72 |
+
|
| 73 |
+
class UnknownAction(object):
|
| 74 |
+
def __init__(self, name: str, *args, **kwargs):
|
| 75 |
+
self.options = {}
|
| 76 |
+
self._args = args
|
| 77 |
+
self._kwargs = kwargs
|
| 78 |
+
|
| 79 |
+
def __enter__(self):
|
| 80 |
+
return self
|
| 81 |
+
|
| 82 |
+
def __exit__(self, t, v, traceback):
|
| 83 |
+
pass
|
| 84 |
+
|
| 85 |
+
def act(self, *args, **kwds):
|
| 86 |
+
"""Perform optimization and return an SolverResults object."""
|
| 87 |
+
self._solver_error('act')
|
| 88 |
+
|
| 89 |
+
async def async_act(self, *args, **kwds):
|
| 90 |
+
self._solver_error('async_act')
|
| 91 |
+
|
| 92 |
+
def reset(self):
|
| 93 |
+
"""Reset the state of an optimizer"""
|
| 94 |
+
self._solver_error('reset')
|
| 95 |
+
|
| 96 |
+
def set_options(self, istr):
|
| 97 |
+
"""Set the options in the optimizer from a string."""
|
| 98 |
+
self._solver_error('set_options')
|
| 99 |
+
|
| 100 |
+
def __bool__(self):
|
| 101 |
+
return self.available()
|
| 102 |
+
|
| 103 |
+
def __getattr__(self, attr):
|
| 104 |
+
self._solver_error(attr)
|
| 105 |
+
|
| 106 |
+
def _action_error(self, method_name):
|
| 107 |
+
raise RuntimeError(
|
| 108 |
+
f"""Attempting to use an unavailable action. The ActionFactory was unable to create the
|
| 109 |
+
action "{self.type}" and returned an UnknownAction object. This error is raised at the point where
|
| 110 |
+
the UnknownAction object was used as if it were valid (by calling method "{method_name}").""")
|
aworld/core/tool/action_template.py
ADDED
|
@@ -0,0 +1,45 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
# coding: utf-8
|
| 2 |
+
# Copyright (c) 2025 inclusionAI.
|
| 3 |
+
|
| 4 |
+
# need action's name, desc, tool_name and func/async_func
|
| 5 |
+
|
| 6 |
+
ACTION_TEMPLATE = """
|
| 7 |
+
import traceback
|
| 8 |
+
from typing import Tuple, Any, List, Dict
|
| 9 |
+
|
| 10 |
+
from aworld.core.envs.action_factory import ActionFactory
|
| 11 |
+
from aworld.core.common import ActionModel, ActionResult
|
| 12 |
+
from aworld.logs.util import logger
|
| 13 |
+
from aworld.utils.async_func import async_func
|
| 14 |
+
from aworld.virtual_environments.action import ExecutableAction
|
| 15 |
+
|
| 16 |
+
|
| 17 |
+
@ActionFactory.register(name="{name}",
|
| 18 |
+
desc="{desc}",
|
| 19 |
+
tool_name="{tool_name}")
|
| 20 |
+
class {name}(ExecutableAction):
|
| 21 |
+
# only for function to tool.
|
| 22 |
+
def act(self, action: ActionModel, **kwargs) -> Tuple[ActionResult, Any]:
|
| 23 |
+
{func_import}import {func}
|
| 24 |
+
try:
|
| 25 |
+
res = {func}(**action.params)
|
| 26 |
+
if not res:
|
| 27 |
+
raise ValueError(f"{func} no result return.")
|
| 28 |
+
return ActionResult(content=res, success=True), None
|
| 29 |
+
except Exception as e:
|
| 30 |
+
logger.error(traceback.format_exc())
|
| 31 |
+
return ActionResult(content=str(e), error=str(e)), None
|
| 32 |
+
|
| 33 |
+
|
| 34 |
+
async def async_act(self, action: ActionModel, **kwargs) -> Tuple[ActionResult, Any]:
|
| 35 |
+
{func_import}import {func}
|
| 36 |
+
|
| 37 |
+
try:
|
| 38 |
+
res = await {call_func}(**action.params)
|
| 39 |
+
if not res:
|
| 40 |
+
raise ValueError(f"{func} no result return.")
|
| 41 |
+
return ActionResult(content=res, success=True), None
|
| 42 |
+
except Exception as e:
|
| 43 |
+
logger.error(traceback.format_exc())
|
| 44 |
+
return ActionResult(content=str(e), error=str(e)), None
|
| 45 |
+
"""
|
aworld/core/tool/base.py
ADDED
|
@@ -0,0 +1,539 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
# coding: utf-8
|
| 2 |
+
# Copyright (c) 2025 inclusionAI.
|
| 3 |
+
|
| 4 |
+
import abc
|
| 5 |
+
import traceback
|
| 6 |
+
from typing import Dict, Tuple, Any, TypeVar, Generic, List, Union
|
| 7 |
+
|
| 8 |
+
from pydantic import BaseModel
|
| 9 |
+
|
| 10 |
+
from aworld.config.conf import ToolConfig, load_config, ConfigDict
|
| 11 |
+
from aworld.core.event import eventbus
|
| 12 |
+
from aworld.core.tool.action import ToolAction
|
| 13 |
+
from aworld.core.tool.action_factory import ActionFactory
|
| 14 |
+
from aworld.core.common import Observation, ActionModel, ActionResult
|
| 15 |
+
from aworld.core.context.base import Context
|
| 16 |
+
from aworld.core.event.base import Message, ToolMessage, AgentMessage, Constants
|
| 17 |
+
from aworld.core.factory import Factory
|
| 18 |
+
from aworld.events.util import send_message
|
| 19 |
+
from aworld.logs.util import logger
|
| 20 |
+
from aworld.models.model_response import ToolCall
|
| 21 |
+
from aworld.output import ToolResultOutput
|
| 22 |
+
from aworld.output.base import StepOutput
|
| 23 |
+
from aworld.utils.common import convert_to_snake, sync_exec
|
| 24 |
+
|
| 25 |
+
AgentInput = TypeVar("AgentInput")
|
| 26 |
+
ToolInput = TypeVar("ToolInput")
|
| 27 |
+
|
| 28 |
+
|
| 29 |
+
class BaseTool(Generic[AgentInput, ToolInput]):
|
| 30 |
+
"""The basic generic classes of tools in the environment, with two parameterized types: AgentInput and ToolInput.
|
| 31 |
+
|
| 32 |
+
We follow the gym/gymnasium protocol to be compatible with gym games, can also build special env tool in the framework.
|
| 33 |
+
"""
|
| 34 |
+
__metaclass__ = abc.ABCMeta
|
| 35 |
+
|
| 36 |
+
def __init__(self, conf: Union[Dict[str, Any], ConfigDict, ToolConfig], **kwargs) -> None:
|
| 37 |
+
self.conf = conf
|
| 38 |
+
if isinstance(conf, ConfigDict):
|
| 39 |
+
pass
|
| 40 |
+
elif isinstance(conf, Dict):
|
| 41 |
+
self.conf = ConfigDict(conf)
|
| 42 |
+
elif isinstance(conf, ToolConfig):
|
| 43 |
+
# To add flexibility
|
| 44 |
+
self.conf = ConfigDict(conf.model_dump())
|
| 45 |
+
else:
|
| 46 |
+
logger.warning(f"Unknown conf type: {type(conf)}")
|
| 47 |
+
self._finished = False
|
| 48 |
+
|
| 49 |
+
self._name = kwargs.pop('name', self.conf.get("name", convert_to_snake(self.__class__.__name__)))
|
| 50 |
+
action_executor.register(name=self.name(), tool=self)
|
| 51 |
+
self.action_executor = action_executor
|
| 52 |
+
self.event_driven = kwargs.pop('event_driven', self.conf.get('event_driven', False))
|
| 53 |
+
self.handler = kwargs.get('handler', self.conf.get('handler', None))
|
| 54 |
+
|
| 55 |
+
for k, v in kwargs.items():
|
| 56 |
+
setattr(self, k, v)
|
| 57 |
+
|
| 58 |
+
def _init_context(self, context: Context):
|
| 59 |
+
self.context = context
|
| 60 |
+
|
| 61 |
+
def name(self):
|
| 62 |
+
"""Tool unique name."""
|
| 63 |
+
return self._name
|
| 64 |
+
|
| 65 |
+
def pre_step(self, action: ToolInput, **kwargs):
|
| 66 |
+
pass
|
| 67 |
+
|
| 68 |
+
def post_step(self,
|
| 69 |
+
step_res: Tuple[AgentInput, float, bool, bool, Dict[str, Any]],
|
| 70 |
+
action: ToolInput,
|
| 71 |
+
**kwargs) -> Message:
|
| 72 |
+
pass
|
| 73 |
+
|
| 74 |
+
def step(self, message: Message, **kwargs) -> Message:
|
| 75 |
+
self._init_context(message.context)
|
| 76 |
+
action = message.payload
|
| 77 |
+
self.pre_step(action, **kwargs)
|
| 78 |
+
res = self.do_step(action, **kwargs)
|
| 79 |
+
final_res = self.post_step(res, action, **kwargs)
|
| 80 |
+
return final_res
|
| 81 |
+
|
| 82 |
+
@abc.abstractmethod
|
| 83 |
+
def reset(self, *, seed: int | None = None, options: Dict[str, str] | None = None) -> Tuple[
|
| 84 |
+
AgentInput, dict[str, Any]]:
|
| 85 |
+
"""Resets the initial internal state, returning an initial state and extended info."""
|
| 86 |
+
|
| 87 |
+
@abc.abstractmethod
|
| 88 |
+
def do_step(self, action: ToolInput, **kwargs) -> Tuple[AgentInput, float, bool, bool, Dict[str, Any]]:
|
| 89 |
+
"""Run one step of the tool's in env using the actions.
|
| 90 |
+
|
| 91 |
+
Args:
|
| 92 |
+
action(ToolInput): Actions provided by the agent to update the observation.
|
| 93 |
+
Return:
|
| 94 |
+
Quintuple,key information: AgentInput and extended info dict.
|
| 95 |
+
"""
|
| 96 |
+
|
| 97 |
+
@property
|
| 98 |
+
def finished(self) -> bool:
|
| 99 |
+
"""The final execution status of the task from agent instructions."""
|
| 100 |
+
return self._finished
|
| 101 |
+
|
| 102 |
+
@abc.abstractmethod
|
| 103 |
+
def close(self) -> None:
|
| 104 |
+
"""Close the tool resources in the environment."""
|
| 105 |
+
|
| 106 |
+
def render(self):
|
| 107 |
+
"""For interface compatibility."""
|
| 108 |
+
pass
|
| 109 |
+
|
| 110 |
+
|
| 111 |
+
class AsyncBaseTool(Generic[AgentInput, ToolInput]):
|
| 112 |
+
"""The basic generic classes of tools in the environment, with two parameterized types: AgentInput and ToolInput.
|
| 113 |
+
|
| 114 |
+
We follow the gym/gymnasium protocol to be compatible with gym games, can also build special env tool in the framework.
|
| 115 |
+
"""
|
| 116 |
+
__metaclass__ = abc.ABCMeta
|
| 117 |
+
|
| 118 |
+
def __init__(self, conf: Union[Dict[str, Any], ConfigDict, ToolConfig], **kwargs) -> None:
|
| 119 |
+
self.conf = conf
|
| 120 |
+
if isinstance(conf, ConfigDict):
|
| 121 |
+
pass
|
| 122 |
+
elif isinstance(conf, Dict):
|
| 123 |
+
self.conf = ConfigDict(conf)
|
| 124 |
+
elif isinstance(conf, ToolConfig):
|
| 125 |
+
# To add flexibility
|
| 126 |
+
self.conf = ConfigDict(conf.model_dump())
|
| 127 |
+
else:
|
| 128 |
+
logger.warning(f"Unknown conf type: {type(conf)}")
|
| 129 |
+
self._finished = False
|
| 130 |
+
|
| 131 |
+
self._name = kwargs.pop('name', self.conf.get("name", convert_to_snake(self.__class__.__name__)))
|
| 132 |
+
action_executor.register(name=self.name(), tool=self)
|
| 133 |
+
self.action_executor = action_executor
|
| 134 |
+
self.event_driven = kwargs.pop('event_driven', self.conf.get('event_driven', False))
|
| 135 |
+
self.handler = kwargs.get('handler', self.conf.get('handler', None))
|
| 136 |
+
|
| 137 |
+
for k, v in kwargs.items():
|
| 138 |
+
setattr(self, k, v)
|
| 139 |
+
|
| 140 |
+
def _init_context(self, context: Context):
|
| 141 |
+
self.context = context
|
| 142 |
+
|
| 143 |
+
def name(self):
|
| 144 |
+
"""Tool unique name."""
|
| 145 |
+
return self._name
|
| 146 |
+
|
| 147 |
+
async def pre_step(self, action: ToolInput, **kwargs):
|
| 148 |
+
pass
|
| 149 |
+
|
| 150 |
+
async def post_step(self,
|
| 151 |
+
step_res: Tuple[AgentInput, float, bool, bool, Dict[str, Any]],
|
| 152 |
+
action: ToolInput,
|
| 153 |
+
**kwargs) -> Message:
|
| 154 |
+
pass
|
| 155 |
+
|
| 156 |
+
async def step(self, message: Message, **kwargs) -> Message:
|
| 157 |
+
self._init_context(message.context)
|
| 158 |
+
action = message.payload
|
| 159 |
+
await self.pre_step(action, **kwargs)
|
| 160 |
+
res = await self.do_step(action, **kwargs)
|
| 161 |
+
final_res = await self.post_step(res, action, **kwargs)
|
| 162 |
+
return final_res
|
| 163 |
+
|
| 164 |
+
@abc.abstractmethod
|
| 165 |
+
async def reset(self, *, seed: int | None = None, options: Dict[str, str] | None = None) -> Tuple[
|
| 166 |
+
AgentInput, dict[str, Any]]:
|
| 167 |
+
"""Resets the initial internal state, returning an initial state and extended info."""
|
| 168 |
+
|
| 169 |
+
@abc.abstractmethod
|
| 170 |
+
async def do_step(self, action: ToolInput, **kwargs) -> Tuple[AgentInput, float, bool, bool, Dict[str, Any]]:
|
| 171 |
+
"""Run one step of the tool's in env using the actions.
|
| 172 |
+
|
| 173 |
+
Args:
|
| 174 |
+
action(ToolInput): Actions provided by the agent to update the observation.
|
| 175 |
+
Return:
|
| 176 |
+
Quintuple,key information: AgentInput and extended info dict.
|
| 177 |
+
"""
|
| 178 |
+
|
| 179 |
+
@property
|
| 180 |
+
def finished(self) -> bool:
|
| 181 |
+
"""The final execution status of the task from agent instructions."""
|
| 182 |
+
return self._finished
|
| 183 |
+
|
| 184 |
+
@abc.abstractmethod
|
| 185 |
+
async def close(self) -> None:
|
| 186 |
+
"""Close the tool resources in the environment."""
|
| 187 |
+
|
| 188 |
+
async def render(self):
|
| 189 |
+
"""For interface compatibility."""
|
| 190 |
+
pass
|
| 191 |
+
|
| 192 |
+
|
| 193 |
+
class Tool(BaseTool[Observation, List[ActionModel]]):
|
| 194 |
+
def _internal_process(self, step_res: Tuple[AgentInput, float, bool, bool, Dict[str, Any]],
|
| 195 |
+
action: ToolInput,
|
| 196 |
+
**kwargs):
|
| 197 |
+
if not step_res or not action:
|
| 198 |
+
return
|
| 199 |
+
for idx, act in enumerate(action):
|
| 200 |
+
if eventbus is not None:
|
| 201 |
+
tool_output = ToolResultOutput(
|
| 202 |
+
tool_type=kwargs.get("tool_id_mapping", {}).get(act.tool_id) or self.name(),
|
| 203 |
+
tool_name=act.tool_name,
|
| 204 |
+
data=step_res[0].content,
|
| 205 |
+
origin_tool_call=ToolCall.from_dict({
|
| 206 |
+
"function": {
|
| 207 |
+
"name": act.action_name,
|
| 208 |
+
"arguments": act.params,
|
| 209 |
+
}
|
| 210 |
+
}),
|
| 211 |
+
metadata=step_res[0].action_result[idx].metadata
|
| 212 |
+
)
|
| 213 |
+
tool_output_message = Message(
|
| 214 |
+
category=Constants.OUTPUT,
|
| 215 |
+
payload=tool_output,
|
| 216 |
+
sender=self.name(),
|
| 217 |
+
session_id=self.context.session_id if self.context else "",
|
| 218 |
+
headers={"context": self.context}
|
| 219 |
+
)
|
| 220 |
+
sync_exec(send_message, tool_output_message)
|
| 221 |
+
|
| 222 |
+
def step(self, message: Message, **kwargs) -> Message:
|
| 223 |
+
self._init_context(message.context)
|
| 224 |
+
action = message.payload
|
| 225 |
+
tool_id_mapping = {}
|
| 226 |
+
for act in action:
|
| 227 |
+
tool_id = act.tool_id
|
| 228 |
+
tool_name = act.tool_name
|
| 229 |
+
tool_id_mapping[tool_id] = tool_name
|
| 230 |
+
self.pre_step(action, **kwargs)
|
| 231 |
+
res = self.do_step(action, **kwargs)
|
| 232 |
+
final_res = self.post_step(res, action, **kwargs)
|
| 233 |
+
self._internal_process(res, action, tool_id_mapping=tool_id_mapping, **kwargs)
|
| 234 |
+
return final_res
|
| 235 |
+
|
| 236 |
+
def post_step(self,
|
| 237 |
+
step_res: Tuple[Observation, float, bool, bool, Dict[str, Any]],
|
| 238 |
+
action: List[ActionModel],
|
| 239 |
+
**kwargs) -> Tuple[Observation, float, bool, bool, Dict[str, Any]] | Message:
|
| 240 |
+
if not step_res:
|
| 241 |
+
raise Exception(f'{self.name()} no observation has been made.')
|
| 242 |
+
|
| 243 |
+
step_res[0].from_agent_name = action[0].agent_name
|
| 244 |
+
for idx, act in enumerate(action):
|
| 245 |
+
step_res[0].action_result[idx].tool_id = act.tool_id
|
| 246 |
+
|
| 247 |
+
agent = self.context.swarm.agents.get(action[0].agent_name)
|
| 248 |
+
feedback_tool_result = agent.feedback_tool_result if agent else False
|
| 249 |
+
if feedback_tool_result:
|
| 250 |
+
return AgentMessage(payload=step_res,
|
| 251 |
+
caller=action[0].agent_name,
|
| 252 |
+
sender=self.name(),
|
| 253 |
+
receiver=action[0].agent_name,
|
| 254 |
+
session_id=self.context.session_id,
|
| 255 |
+
headers={"context": self.context})
|
| 256 |
+
else:
|
| 257 |
+
return AgentMessage(payload=step_res,
|
| 258 |
+
sender=action[0].agent_name,
|
| 259 |
+
session_id=self.context.session_id,
|
| 260 |
+
headers={"context": self.context})
|
| 261 |
+
|
| 262 |
+
|
| 263 |
+
class AsyncTool(AsyncBaseTool[Observation, List[ActionModel]]):
|
| 264 |
+
async def _internal_process(self, step_res: Tuple[AgentInput, float, bool, bool, Dict[str, Any]],
|
| 265 |
+
action: ToolInput,
|
| 266 |
+
**kwargs):
|
| 267 |
+
for idx, act in enumerate(action):
|
| 268 |
+
# send tool results output
|
| 269 |
+
if eventbus is not None:
|
| 270 |
+
tool_output = ToolResultOutput(
|
| 271 |
+
tool_type=kwargs.get("tool_id_mapping", {}).get(act.tool_id) or self.name(),
|
| 272 |
+
tool_name=act.tool_name,
|
| 273 |
+
data=step_res[0].content,
|
| 274 |
+
origin_tool_call=ToolCall.from_dict({
|
| 275 |
+
"function": {
|
| 276 |
+
"name": act.action_name,
|
| 277 |
+
"arguments": act.params,
|
| 278 |
+
}
|
| 279 |
+
}),
|
| 280 |
+
metadata=step_res[0].action_result[idx].metadata
|
| 281 |
+
)
|
| 282 |
+
tool_output_message = Message(
|
| 283 |
+
category=Constants.OUTPUT,
|
| 284 |
+
payload=tool_output,
|
| 285 |
+
sender=self.name(),
|
| 286 |
+
session_id=self.context.session_id if self.context else "",
|
| 287 |
+
headers={"context": self.context}
|
| 288 |
+
)
|
| 289 |
+
await send_message(tool_output_message)
|
| 290 |
+
|
| 291 |
+
await send_message(Message(
|
| 292 |
+
category=Constants.OUTPUT,
|
| 293 |
+
payload=StepOutput.build_finished_output(name=f"{action[0].agent_name if action else ''}",
|
| 294 |
+
step_num=0),
|
| 295 |
+
sender=self.name(),
|
| 296 |
+
receiver=action[0].agent_name,
|
| 297 |
+
session_id=self.context.session_id if self.context else "",
|
| 298 |
+
headers={"context": self.context}
|
| 299 |
+
))
|
| 300 |
+
|
| 301 |
+
async def step(self, message: Message, **kwargs) -> Message:
|
| 302 |
+
self._init_context(message.context)
|
| 303 |
+
action = message.payload
|
| 304 |
+
tool_id_mapping = {}
|
| 305 |
+
for act in action:
|
| 306 |
+
tool_id = act.tool_id
|
| 307 |
+
tool_name = act.tool_name
|
| 308 |
+
tool_id_mapping[tool_id] = tool_name
|
| 309 |
+
await self.pre_step(action, **kwargs)
|
| 310 |
+
res = await self.do_step(action, **kwargs)
|
| 311 |
+
final_res = await self.post_step(res, action, **kwargs)
|
| 312 |
+
await self._internal_process(res, action, tool_id_mapping=tool_id_mapping, **kwargs)
|
| 313 |
+
return final_res
|
| 314 |
+
|
| 315 |
+
async def post_step(self,
|
| 316 |
+
step_res: Tuple[Observation, float, bool, bool, Dict[str, Any]],
|
| 317 |
+
action: List[ActionModel],
|
| 318 |
+
**kwargs) -> Tuple[Observation, float, bool, bool, Dict[str, Any]] | Message:
|
| 319 |
+
if not step_res:
|
| 320 |
+
raise Exception(f'{self.name()} no observation has been made.')
|
| 321 |
+
|
| 322 |
+
step_res[0].from_agent_name = action[0].agent_name
|
| 323 |
+
for idx, act in enumerate(action):
|
| 324 |
+
step_res[0].action_result[idx].tool_id = act.tool_id
|
| 325 |
+
|
| 326 |
+
agent = self.context.swarm.agents.get(action[0].agent_name)
|
| 327 |
+
feedback_tool_result = agent.feedback_tool_result if agent else False
|
| 328 |
+
if feedback_tool_result:
|
| 329 |
+
return AgentMessage(payload=step_res,
|
| 330 |
+
caller=action[0].agent_name,
|
| 331 |
+
sender=self.name(),
|
| 332 |
+
receiver=action[0].agent_name,
|
| 333 |
+
session_id=Context.instance().session_id,
|
| 334 |
+
headers={"context": self.context})
|
| 335 |
+
else:
|
| 336 |
+
return AgentMessage(payload=step_res,
|
| 337 |
+
sender=action[0].agent_name,
|
| 338 |
+
session_id=Context.instance().session_id,
|
| 339 |
+
headers={"context": self.context})
|
| 340 |
+
|
| 341 |
+
|
| 342 |
+
class ToolsManager(Factory):
|
| 343 |
+
def __init__(self, type_name: str = None):
|
| 344 |
+
super(ToolsManager, self).__init__(type_name)
|
| 345 |
+
self._tool_with_action = {}
|
| 346 |
+
self._tool_conf = {}
|
| 347 |
+
self._tool_instance = {}
|
| 348 |
+
|
| 349 |
+
def __iter__(self):
|
| 350 |
+
for name in self._cls:
|
| 351 |
+
name = "async_" + name if self._asyn.get(name, False) else name
|
| 352 |
+
yield name
|
| 353 |
+
|
| 354 |
+
def __contains__(self, name: str) -> bool:
|
| 355 |
+
"""Whether the name in the factory."""
|
| 356 |
+
name = "async_" + name if self._asyn.get(name, False) else name
|
| 357 |
+
return name in self._cls
|
| 358 |
+
|
| 359 |
+
def __call__(self, name: str = None, *args, **kwargs):
|
| 360 |
+
if name is None:
|
| 361 |
+
return self
|
| 362 |
+
|
| 363 |
+
asyn = kwargs.pop("asyn", False)
|
| 364 |
+
name = "async_" + name if asyn else name
|
| 365 |
+
|
| 366 |
+
conf = self._tool_conf.get(name)
|
| 367 |
+
if not conf:
|
| 368 |
+
logger.warning(f"{name} not find conf in tool factory")
|
| 369 |
+
conf = dict()
|
| 370 |
+
elif isinstance(conf, BaseModel):
|
| 371 |
+
conf = conf.model_dump()
|
| 372 |
+
|
| 373 |
+
user_conf = kwargs.pop('conf', None)
|
| 374 |
+
if user_conf:
|
| 375 |
+
if isinstance(user_conf, BaseModel):
|
| 376 |
+
conf.update(user_conf.model_dump())
|
| 377 |
+
elif isinstance(user_conf, dict):
|
| 378 |
+
conf.update(user_conf)
|
| 379 |
+
else:
|
| 380 |
+
logger.warning(f"Unknown conf type: {type(user_conf)}, ignored!")
|
| 381 |
+
self._tool_conf[name] = conf
|
| 382 |
+
|
| 383 |
+
# must is a dict
|
| 384 |
+
conf['name'] = name
|
| 385 |
+
conf = ConfigDict(conf)
|
| 386 |
+
|
| 387 |
+
if kwargs.get("reuse", conf.get('reuse', False)) is True and name in self._tool_instance:
|
| 388 |
+
return self._tool_instance[name]
|
| 389 |
+
|
| 390 |
+
if name in self._cls:
|
| 391 |
+
tool = self._cls[name](conf=conf, **kwargs)
|
| 392 |
+
self._tool_instance[name] = tool
|
| 393 |
+
else:
|
| 394 |
+
raise RuntimeError(f"can not find {name} tool in the ToolFactory, register it first.")
|
| 395 |
+
|
| 396 |
+
action_executor.register(name, tool)
|
| 397 |
+
return tool
|
| 398 |
+
|
| 399 |
+
def get_tool_action(self, tool: str, asyn: bool = False):
|
| 400 |
+
if asyn:
|
| 401 |
+
tool = "async_" + tool
|
| 402 |
+
return self._tool_with_action.get(tool)
|
| 403 |
+
|
| 404 |
+
def register(self, name: str, desc: str, supported_action: ToolAction = None, conf_file_name: str = None, **kwargs):
|
| 405 |
+
"""Register a tool to tool factory.
|
| 406 |
+
|
| 407 |
+
Args:
|
| 408 |
+
name: Tool name
|
| 409 |
+
desc: Tool description
|
| 410 |
+
supported_action: Tool abilities
|
| 411 |
+
conf_file_name: Default tool config
|
| 412 |
+
"""
|
| 413 |
+
res = super(ToolsManager, self).register(name, desc, **kwargs)
|
| 414 |
+
asyn = kwargs.pop("asyn", False)
|
| 415 |
+
prefix = "async_" if asyn else ""
|
| 416 |
+
conf_file_name = conf_file_name if conf_file_name else f"{name}_tool.yaml"
|
| 417 |
+
conf = load_config(conf_file_name, kwargs.get("dir"))
|
| 418 |
+
if not conf:
|
| 419 |
+
logger.debug(f"can not load conf from {conf_file_name}")
|
| 420 |
+
# use general tool config
|
| 421 |
+
conf = ToolConfig().model_dump()
|
| 422 |
+
name = prefix + name
|
| 423 |
+
self._tool_with_action[name] = supported_action
|
| 424 |
+
self._tool_conf[name] = conf
|
| 425 |
+
logger.debug(f"{name} register to the tool factory.")
|
| 426 |
+
return res
|
| 427 |
+
|
| 428 |
+
|
| 429 |
+
ToolFactory = ToolsManager("env_tool_type")
|
| 430 |
+
|
| 431 |
+
|
| 432 |
+
class ToolActionExecutor(object):
|
| 433 |
+
__metaclass__ = abc.ABCMeta
|
| 434 |
+
|
| 435 |
+
def __init__(self, tool: Tool = None):
|
| 436 |
+
self.tool = tool
|
| 437 |
+
self.tools: Dict[str, Tool] = {}
|
| 438 |
+
|
| 439 |
+
def register(
|
| 440 |
+
self,
|
| 441 |
+
name: str,
|
| 442 |
+
tool: Union[Tool, AsyncTool]):
|
| 443 |
+
self.tools[name] = tool
|
| 444 |
+
|
| 445 |
+
@abc.abstractmethod
|
| 446 |
+
def execute_action(self, actions: List[ActionModel], **kwargs) -> Tuple[List[ActionResult], Any]:
|
| 447 |
+
""""""
|
| 448 |
+
return self.execute_env_action(actions, self.tool, **kwargs)
|
| 449 |
+
|
| 450 |
+
@abc.abstractmethod
|
| 451 |
+
async def async_execute_action(self, actions: List[ActionModel], **kwargs) -> Tuple[List[ActionResult], Any]:
|
| 452 |
+
""""""
|
| 453 |
+
return await self.async_execute_env_action(actions, self.tool, **kwargs)
|
| 454 |
+
|
| 455 |
+
@abc.abstractmethod
|
| 456 |
+
def execute_env_action(self,
|
| 457 |
+
actions: List[ActionModel],
|
| 458 |
+
tool: Tool,
|
| 459 |
+
**kwargs) -> Tuple[List[ActionResult], Any]:
|
| 460 |
+
""""""
|
| 461 |
+
action_results = []
|
| 462 |
+
ctx = None
|
| 463 |
+
for action in actions:
|
| 464 |
+
if action is None:
|
| 465 |
+
logger.warning("empty action, ignore it.")
|
| 466 |
+
continue
|
| 467 |
+
|
| 468 |
+
if tool is None:
|
| 469 |
+
tool_name = action.tool_name
|
| 470 |
+
tool = self.tools.get(tool_name)
|
| 471 |
+
if tool is None:
|
| 472 |
+
tool = ToolFactory(tool_name, conf=kwargs.get("conf", ToolConfig()))
|
| 473 |
+
self.tools[tool_name] = tool
|
| 474 |
+
|
| 475 |
+
try:
|
| 476 |
+
action_result, ctx = self.do_act(action, tool, **kwargs)
|
| 477 |
+
except:
|
| 478 |
+
logger.warning(traceback.format_exc())
|
| 479 |
+
action_result = ActionResult(error=traceback.format_exc(), success=False)
|
| 480 |
+
action_result.action_name = action.action_name
|
| 481 |
+
action_result.tool_name = action.tool_name
|
| 482 |
+
action_results.append(action_result)
|
| 483 |
+
return action_results, ctx
|
| 484 |
+
|
| 485 |
+
async def async_execute_env_action(self,
|
| 486 |
+
actions: List[ActionModel],
|
| 487 |
+
tool: Tool,
|
| 488 |
+
**kwargs) -> Tuple[List[ActionResult], Any]:
|
| 489 |
+
""""""
|
| 490 |
+
action_results = []
|
| 491 |
+
ctx = None
|
| 492 |
+
for action in actions:
|
| 493 |
+
if action is None:
|
| 494 |
+
logger.warning("empty action, ignore it.")
|
| 495 |
+
continue
|
| 496 |
+
|
| 497 |
+
if tool is None:
|
| 498 |
+
tool_name = "async_" + action.tool_name
|
| 499 |
+
tool = self.tools.get(tool_name)
|
| 500 |
+
if tool is None:
|
| 501 |
+
tool = ToolFactory(tool_name, conf=kwargs.get("conf", ToolConfig()))
|
| 502 |
+
self.tools[tool_name] = tool
|
| 503 |
+
try:
|
| 504 |
+
action_result, ctx = await self.async_do_act(action, tool, **kwargs)
|
| 505 |
+
except:
|
| 506 |
+
logger.warning(traceback.format_exc())
|
| 507 |
+
action_result = ActionResult(error=traceback.format_exc(), success=False)
|
| 508 |
+
action_result.action_name = action.action_name
|
| 509 |
+
action_result.tool_name = action.tool_name
|
| 510 |
+
action_results.append(action_result)
|
| 511 |
+
return action_results, ctx
|
| 512 |
+
|
| 513 |
+
def do_act(self, action_model: ActionModel, tool: Tool, **kwargs):
|
| 514 |
+
action_name = action_model.action_name
|
| 515 |
+
if action_name not in ActionFactory:
|
| 516 |
+
action_name = action_model.tool_name + action_model.action_name
|
| 517 |
+
if action_name not in ActionFactory:
|
| 518 |
+
raise ValueError(f'Action {action_model.action_name} not found in ActionFactory')
|
| 519 |
+
|
| 520 |
+
action = ActionFactory(action_name)
|
| 521 |
+
action_result, page = action.act(action_model, tool=tool, **kwargs)
|
| 522 |
+
logger.info(f"{tool.name()}-{action_model.action_name} execute finished")
|
| 523 |
+
return action_result, page
|
| 524 |
+
|
| 525 |
+
async def async_do_act(self, action_model: ActionModel, tool: Tool,
|
| 526 |
+
**kwargs):
|
| 527 |
+
action_name = action_model.action_name
|
| 528 |
+
if action_name not in ActionFactory:
|
| 529 |
+
action_name = action_model.tool_name + action_model.action_name
|
| 530 |
+
if action_name not in ActionFactory:
|
| 531 |
+
raise ValueError(f'Action {action_model.action_name} not found in ActionFactory')
|
| 532 |
+
|
| 533 |
+
action = ActionFactory(action_name)
|
| 534 |
+
action_result, page = await action.async_act(action_model, tool=tool, **kwargs)
|
| 535 |
+
logger.info(f"{tool.name()}-{action_model.action_name} execute finished")
|
| 536 |
+
return action_result, page
|
| 537 |
+
|
| 538 |
+
|
| 539 |
+
action_executor = ToolActionExecutor()
|
aworld/core/tool/func_to_tool.py
ADDED
|
@@ -0,0 +1,270 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
# coding: utf-8
|
| 2 |
+
# Copyright (c) 2025 inclusionAI.
|
| 3 |
+
import importlib
|
| 4 |
+
import inspect
|
| 5 |
+
import os
|
| 6 |
+
import sys
|
| 7 |
+
|
| 8 |
+
from typing import Callable, Any, get_type_hints, get_origin, get_args
|
| 9 |
+
|
| 10 |
+
from pydantic import create_model, Field, BaseModel
|
| 11 |
+
from pydantic.fields import FieldInfo
|
| 12 |
+
|
| 13 |
+
from aworld.core.common import ToolActionInfo, ParamInfo
|
| 14 |
+
from aworld.core.tool.action import TOOL_ACTION
|
| 15 |
+
from aworld.core.tool.action_factory import ActionFactory
|
| 16 |
+
from aworld.core.tool.action_template import ACTION_TEMPLATE
|
| 17 |
+
from aworld.core.tool.base import ToolFactory
|
| 18 |
+
from aworld.core.tool.tool_template import TOOL_TEMPLATE
|
| 19 |
+
from aworld.logs.util import logger
|
| 20 |
+
|
| 21 |
+
|
| 22 |
+
def be_tool(
|
| 23 |
+
tool_name: str = None,
|
| 24 |
+
tool_desc: str = None,
|
| 25 |
+
name: str = None,
|
| 26 |
+
desc: str = None, **kwargs
|
| 27 |
+
) -> Callable[..., Any]:
|
| 28 |
+
"""Decorate a function to be a tool, auto register the tool and action with the parameters with the factory.
|
| 29 |
+
|
| 30 |
+
Example:
|
| 31 |
+
>>> @be_tool()
|
| 32 |
+
>>> def example():
|
| 33 |
+
>>> return "example"
|
| 34 |
+
|
| 35 |
+
# write name and description
|
| 36 |
+
>>> @be_tool(name="param", desc="example param func")
|
| 37 |
+
>>> def example_param(param: str):
|
| 38 |
+
>>> return param
|
| 39 |
+
|
| 40 |
+
>>> @be_tool(tool_name='field_param_tool')
|
| 41 |
+
>>> def example_param_field(param: str = Field(..., description="param")):
|
| 42 |
+
>>> return param
|
| 43 |
+
|
| 44 |
+
>>> @be_tool(tool_name='field_param_tool')
|
| 45 |
+
>>> def example_param_2(param: str = Field(..., description="param")):
|
| 46 |
+
>>> return param
|
| 47 |
+
|
| 48 |
+
Args:
|
| 49 |
+
tool_name: Optional name for the tool.
|
| 50 |
+
tool_desc: Optional description for the tool.
|
| 51 |
+
name: Optional name for the function.
|
| 52 |
+
desc: Optional description of function.
|
| 53 |
+
"""
|
| 54 |
+
|
| 55 |
+
def decorator(func: Callable[..., Any]) -> Callable[..., Any]:
|
| 56 |
+
# converts python function into a tool with associated actions
|
| 57 |
+
function_to_tool(
|
| 58 |
+
func,
|
| 59 |
+
tool_name=tool_name,
|
| 60 |
+
tool_desc=tool_desc,
|
| 61 |
+
name=name,
|
| 62 |
+
desc=desc,
|
| 63 |
+
**kwargs
|
| 64 |
+
)
|
| 65 |
+
return func
|
| 66 |
+
|
| 67 |
+
return decorator
|
| 68 |
+
|
| 69 |
+
|
| 70 |
+
def function_to_tool(
|
| 71 |
+
func: Callable[..., Any],
|
| 72 |
+
tool_name: str = None,
|
| 73 |
+
tool_desc: str = None,
|
| 74 |
+
name: str = None,
|
| 75 |
+
desc: str = None,
|
| 76 |
+
**kwargs
|
| 77 |
+
) -> None:
|
| 78 |
+
"""Transform a python function into a tool, and register to the factory.
|
| 79 |
+
|
| 80 |
+
Generates necessary code files dynamically and manages tool and action registration.
|
| 81 |
+
|
| 82 |
+
Args:
|
| 83 |
+
func: An executable function.
|
| 84 |
+
tool_name: The name of the tool that is transformed by the function.
|
| 85 |
+
tool_desc: The description of the tool what it can do, default the same as tool_name.
|
| 86 |
+
name: Alias name of function.
|
| 87 |
+
desc: The description of the function what it can do, default the same as name.
|
| 88 |
+
"""
|
| 89 |
+
tool_name = tool_name or name or func.__name__
|
| 90 |
+
action_name = name or func.__name__
|
| 91 |
+
|
| 92 |
+
if tool_name == "<lambda>" or action_name == "<lambda>":
|
| 93 |
+
raise ValueError("You must provide a name for lambda functions")
|
| 94 |
+
|
| 95 |
+
# async func, will use AsyncTool
|
| 96 |
+
is_async = inspect.iscoroutinefunction(func)
|
| 97 |
+
|
| 98 |
+
name = action_name
|
| 99 |
+
if not inspect.iscoroutinefunction(func):
|
| 100 |
+
name = f"async_func({action_name})"
|
| 101 |
+
|
| 102 |
+
# build action
|
| 103 |
+
if action_name not in ActionFactory:
|
| 104 |
+
func_import = func.__module__
|
| 105 |
+
if func_import == '__main__':
|
| 106 |
+
path = inspect.getsourcefile(func)
|
| 107 |
+
package = path.replace(os.getcwd(), '').replace('.py', '')
|
| 108 |
+
if package[0] == '/':
|
| 109 |
+
package = package[1:]
|
| 110 |
+
func_import = f"from {package} "
|
| 111 |
+
else:
|
| 112 |
+
func_import = f"from {func_import} "
|
| 113 |
+
con = ACTION_TEMPLATE.format(name=action_name,
|
| 114 |
+
desc=desc if desc else action_name,
|
| 115 |
+
tool_name=tool_name,
|
| 116 |
+
func_import=func_import,
|
| 117 |
+
func=func.__name__,
|
| 118 |
+
call_func=name)
|
| 119 |
+
with open(f"{action_name}.py", 'w+') as write:
|
| 120 |
+
write.writelines(con)
|
| 121 |
+
module = importlib.import_module(action_name)
|
| 122 |
+
getattr(module, action_name)
|
| 123 |
+
|
| 124 |
+
if not kwargs.get('keep_file', False):
|
| 125 |
+
os.remove(f"{action_name}.py")
|
| 126 |
+
else:
|
| 127 |
+
logger.warning(f"{action_name} already register to the tool.")
|
| 128 |
+
raise ValueError(f"{action_name} already register to a tool.")
|
| 129 |
+
|
| 130 |
+
# build params info
|
| 131 |
+
parameters = func_params(func)
|
| 132 |
+
|
| 133 |
+
module_name = f'{tool_name}_action'
|
| 134 |
+
if module_name not in sys.modules:
|
| 135 |
+
# ToolAction process
|
| 136 |
+
with open(f"{module_name}.py", 'w+') as write:
|
| 137 |
+
write.writelines(TOOL_ACTION.format(name=tool_name))
|
| 138 |
+
module = importlib.import_module(module_name)
|
| 139 |
+
if not kwargs.get('keep_file', False):
|
| 140 |
+
os.remove(f"{module_name}.py")
|
| 141 |
+
tool_action_cls = getattr(module, f"{tool_name}Action")
|
| 142 |
+
else:
|
| 143 |
+
logger.info(f"{module_name} already exists in modules, reuse the tool action.")
|
| 144 |
+
tool_action_cls = getattr(sys.modules[module_name], f"{tool_name}Action")
|
| 145 |
+
|
| 146 |
+
params = {}
|
| 147 |
+
if parameters:
|
| 148 |
+
for k, v in parameters['properties'].items():
|
| 149 |
+
params[k] = ParamInfo(name=k,
|
| 150 |
+
type=v.get('type', 'string'),
|
| 151 |
+
required=False if v.get('default') else True,
|
| 152 |
+
default_value=v.get('default'),
|
| 153 |
+
desc=v.get('description', k))
|
| 154 |
+
|
| 155 |
+
setattr(tool_action_cls,
|
| 156 |
+
action_name.upper(),
|
| 157 |
+
ToolActionInfo(
|
| 158 |
+
name=action_name,
|
| 159 |
+
desc=desc if desc else action_name,
|
| 160 |
+
input_params=params
|
| 161 |
+
))
|
| 162 |
+
|
| 163 |
+
# build tool
|
| 164 |
+
if tool_name not in ToolFactory:
|
| 165 |
+
con = TOOL_TEMPLATE.format(name=tool_name,
|
| 166 |
+
desc=tool_desc if tool_desc else tool_name,
|
| 167 |
+
action=f"{tool_name}Action",
|
| 168 |
+
action_import=f"from {tool_action_cls.__module__} import {tool_name}Action",
|
| 169 |
+
cls='AsyncTool' if is_async else 'Tool',
|
| 170 |
+
async_flag='async ' if is_async else '',
|
| 171 |
+
async_underline='async_' if is_async else '',
|
| 172 |
+
await_flag='await ' if is_async else '')
|
| 173 |
+
|
| 174 |
+
if tool_name == action_name:
|
| 175 |
+
tool_name += '_tool'
|
| 176 |
+
|
| 177 |
+
with open(f"{tool_name}.py", 'w+') as write:
|
| 178 |
+
write.writelines(con)
|
| 179 |
+
importlib.import_module(tool_name)
|
| 180 |
+
|
| 181 |
+
if not kwargs.get('keep_file', False):
|
| 182 |
+
os.remove(f"{tool_name}.py")
|
| 183 |
+
|
| 184 |
+
|
| 185 |
+
def func_params(func: Callable[..., Any]):
|
| 186 |
+
"""Extracts parameter information from the function.
|
| 187 |
+
|
| 188 |
+
Args:
|
| 189 |
+
func: An executable function.
|
| 190 |
+
|
| 191 |
+
Returns:
|
| 192 |
+
JSON schema of the function input parameters.
|
| 193 |
+
"""
|
| 194 |
+
sig = inspect.signature(func)
|
| 195 |
+
type_hints = get_type_hints(func)
|
| 196 |
+
filtered_params = []
|
| 197 |
+
|
| 198 |
+
# The function must have a return value
|
| 199 |
+
if sig.return_annotation == inspect.Parameter.empty:
|
| 200 |
+
raise RuntimeError(f"{func} no return value, preferably a string.")
|
| 201 |
+
|
| 202 |
+
for name, param in sig.parameters.items():
|
| 203 |
+
filtered_params.append((name, param))
|
| 204 |
+
|
| 205 |
+
fields: dict[str, Any] = {}
|
| 206 |
+
param_descs = {}
|
| 207 |
+
|
| 208 |
+
for name, param in filtered_params:
|
| 209 |
+
ann = type_hints.get(name, param.annotation)
|
| 210 |
+
default = param.default
|
| 211 |
+
def_desc = None
|
| 212 |
+
if hasattr(default, 'description'):
|
| 213 |
+
def_desc = default.description
|
| 214 |
+
field_description = param_descs.get(name, def_desc)
|
| 215 |
+
|
| 216 |
+
if isinstance(default, FieldInfo):
|
| 217 |
+
default = default.default
|
| 218 |
+
|
| 219 |
+
# If there's no type hint, assume `Any`
|
| 220 |
+
if ann == inspect.Parameter.empty:
|
| 221 |
+
ann = Any
|
| 222 |
+
|
| 223 |
+
# Handle different parameter kinds
|
| 224 |
+
if param.kind == param.VAR_POSITIONAL:
|
| 225 |
+
# e.g. *args: extend positional args
|
| 226 |
+
if get_origin(ann) is tuple:
|
| 227 |
+
# e.g. def foo(*args: tuple[int, ...]) -> treat as List[int]
|
| 228 |
+
args_of_tuple = get_args(ann)
|
| 229 |
+
if len(args_of_tuple) == 2 and args_of_tuple[1] is Ellipsis:
|
| 230 |
+
ann = list[args_of_tuple[0]] # type: ignore
|
| 231 |
+
else:
|
| 232 |
+
ann = list[Any]
|
| 233 |
+
else:
|
| 234 |
+
# If user wrote *args: int, treat as List[int]
|
| 235 |
+
ann = list[ann] # type: ignore
|
| 236 |
+
|
| 237 |
+
# Default factory to empty list
|
| 238 |
+
fields[name] = (
|
| 239 |
+
ann,
|
| 240 |
+
Field(default_factory=list, description=field_description), # type: ignore
|
| 241 |
+
)
|
| 242 |
+
elif param.kind == param.VAR_KEYWORD:
|
| 243 |
+
# **kwargs handling
|
| 244 |
+
if get_origin(ann) is dict:
|
| 245 |
+
# e.g. def foo(**kwargs: dict[str, int])
|
| 246 |
+
dict_args = get_args(ann)
|
| 247 |
+
if len(dict_args) == 2:
|
| 248 |
+
ann = dict[dict_args[0], dict_args[1]] # type: ignore
|
| 249 |
+
else:
|
| 250 |
+
ann = dict[str, Any]
|
| 251 |
+
else:
|
| 252 |
+
# e.g. def foo(**kwargs: int) -> Dict[str, int]
|
| 253 |
+
ann = dict[str, ann]
|
| 254 |
+
|
| 255 |
+
fields[name] = (
|
| 256 |
+
ann,
|
| 257 |
+
Field(default_factory=dict, description=field_description), # type: ignore
|
| 258 |
+
)
|
| 259 |
+
else:
|
| 260 |
+
if default == inspect.Parameter.empty:
|
| 261 |
+
# Required field
|
| 262 |
+
fields[name] = (ann, Field(..., description=field_description))
|
| 263 |
+
else:
|
| 264 |
+
# Parameter with a default value
|
| 265 |
+
fields[name] = (ann, Field(default=default, description=field_description))
|
| 266 |
+
|
| 267 |
+
dynamic_model = create_model(f"{func.__name__}".upper(), __base__=BaseModel, **fields)
|
| 268 |
+
json_schema = dynamic_model.model_json_schema()
|
| 269 |
+
logger.debug(f"{func} parameters schema: {json_schema}")
|
| 270 |
+
return json_schema
|
aworld/core/tool/tool_desc.py
ADDED
|
@@ -0,0 +1,121 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
# coding: utf-8
|
| 2 |
+
# Copyright (c) 2025 inclusionAI.
|
| 3 |
+
|
| 4 |
+
from typing import List, Dict
|
| 5 |
+
|
| 6 |
+
from aworld.core.tool.action_factory import ActionFactory
|
| 7 |
+
|
| 8 |
+
from aworld.core.tool.base import ToolFactory
|
| 9 |
+
from aworld.logs.util import logger
|
| 10 |
+
|
| 11 |
+
|
| 12 |
+
def tool_action_desc():
|
| 13 |
+
"""Utility method of generate description of tools and their actions.
|
| 14 |
+
|
| 15 |
+
The standard protocol can be transformed based on the API of different llm.
|
| 16 |
+
Define as follows:
|
| 17 |
+
```
|
| 18 |
+
{
|
| 19 |
+
"tool_name": {
|
| 20 |
+
"desc": "A toolkit description.",
|
| 21 |
+
"actions": [
|
| 22 |
+
{
|
| 23 |
+
"name": "action name",
|
| 24 |
+
"desc": "action description.",
|
| 25 |
+
"params": {
|
| 26 |
+
"param_name": {
|
| 27 |
+
"desc": "param description.",
|
| 28 |
+
"type": "param type, such as int, str, etc.",
|
| 29 |
+
"required": True | False
|
| 30 |
+
}
|
| 31 |
+
}
|
| 32 |
+
}
|
| 33 |
+
]
|
| 34 |
+
}
|
| 35 |
+
}
|
| 36 |
+
```
|
| 37 |
+
"""
|
| 38 |
+
|
| 39 |
+
def process(action_info):
|
| 40 |
+
action_dict = dict()
|
| 41 |
+
action_dict["name"] = action_info.name
|
| 42 |
+
action_dict["desc"] = action_info.desc
|
| 43 |
+
action_dict["params"] = dict()
|
| 44 |
+
|
| 45 |
+
for k, v in action_info.input_params.items():
|
| 46 |
+
params_dict = v.model_dump()
|
| 47 |
+
params_dict.pop("name")
|
| 48 |
+
action_dict["params"][k] = params_dict
|
| 49 |
+
return action_dict
|
| 50 |
+
|
| 51 |
+
descs = dict()
|
| 52 |
+
for tool in ToolFactory:
|
| 53 |
+
tool_val_dict = dict()
|
| 54 |
+
descs[tool] = tool_val_dict
|
| 55 |
+
|
| 56 |
+
tool_val_dict["desc"] = ToolFactory.desc(tool)
|
| 57 |
+
tool_action = ToolFactory.get_tool_action(tool)
|
| 58 |
+
actions = []
|
| 59 |
+
action_names = ActionFactory.get_actions_by_tool(tool_name=tool)
|
| 60 |
+
if action_names:
|
| 61 |
+
for action_name in action_names:
|
| 62 |
+
info = tool_action.get_value_by_name(action_name)
|
| 63 |
+
if not info:
|
| 64 |
+
logger.warning(f"{action_name} can not find in {tool}, please check it.")
|
| 65 |
+
continue
|
| 66 |
+
try:
|
| 67 |
+
action_dict = process(info)
|
| 68 |
+
except:
|
| 69 |
+
logger.warning(f"{action_name} process fail.")
|
| 70 |
+
action_dict = dict()
|
| 71 |
+
actions.append(action_dict)
|
| 72 |
+
elif tool_action:
|
| 73 |
+
for k, info in tool_action.__members__.items():
|
| 74 |
+
action_dict = process(info.value)
|
| 75 |
+
actions.append(action_dict)
|
| 76 |
+
else:
|
| 77 |
+
logger.debug(f"{tool} no action!")
|
| 78 |
+
tool_val_dict["actions"] = actions
|
| 79 |
+
return descs
|
| 80 |
+
|
| 81 |
+
|
| 82 |
+
def get_actions() -> List[str]:
|
| 83 |
+
res = []
|
| 84 |
+
for _, tool_info in tool_action_desc().items():
|
| 85 |
+
actions = tool_info.get("actions")
|
| 86 |
+
if not actions:
|
| 87 |
+
continue
|
| 88 |
+
|
| 89 |
+
for action in actions:
|
| 90 |
+
res.append(action['name'])
|
| 91 |
+
return res
|
| 92 |
+
|
| 93 |
+
|
| 94 |
+
def get_actions_by_tools(tool_names: Dict = None) -> List[str]:
|
| 95 |
+
if not tool_names:
|
| 96 |
+
return get_actions()
|
| 97 |
+
|
| 98 |
+
res = []
|
| 99 |
+
for tool_name, tool_info in tool_action_desc().items():
|
| 100 |
+
if tool_name not in tool_names:
|
| 101 |
+
continue
|
| 102 |
+
|
| 103 |
+
actions = tool_info.get("actions")
|
| 104 |
+
if not actions:
|
| 105 |
+
continue
|
| 106 |
+
|
| 107 |
+
for action in actions:
|
| 108 |
+
res.append(action['name'])
|
| 109 |
+
return res
|
| 110 |
+
|
| 111 |
+
|
| 112 |
+
def get_tool_desc():
|
| 113 |
+
return tool_action_desc()
|
| 114 |
+
|
| 115 |
+
|
| 116 |
+
def get_tool_desc_by_name(name: str):
|
| 117 |
+
return tool_action_desc().get(name, None)
|
| 118 |
+
|
| 119 |
+
|
| 120 |
+
def is_tool_by_name(name: str) -> bool:
|
| 121 |
+
return name in ToolFactory
|
aworld/core/tool/tool_template.py
ADDED
|
@@ -0,0 +1,82 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
# coding: utf-8
|
| 2 |
+
# Copyright (c) 2025 inclusionAI.
|
| 3 |
+
|
| 4 |
+
# need tool's name, desc and cls params
|
| 5 |
+
TOOL_TEMPLATE = """
|
| 6 |
+
import json
|
| 7 |
+
from typing import List, Tuple, Dict, Any, Union
|
| 8 |
+
|
| 9 |
+
from aworld.config.conf import ToolConfig, ConfigDict
|
| 10 |
+
from aworld.core.envs.tool import Tool, AsyncTool, ToolFactory
|
| 11 |
+
from aworld.core.common import Observation, ActionModel, ActionResult
|
| 12 |
+
from aworld.logs.util import logger
|
| 13 |
+
from aworld.virtual_environments.utils import build_observation
|
| 14 |
+
{action_import}
|
| 15 |
+
|
| 16 |
+
|
| 17 |
+
@ToolFactory.register(name="{name}", desc="{desc}", supported_action={action})
|
| 18 |
+
class {name}Tool({cls}[Observation, List[ActionModel]]):
|
| 19 |
+
def __init__(self, conf: Union[Dict[str, Any], ConfigDict, ToolConfig], **kwargs) -> None:
|
| 20 |
+
super().__init__(conf, **kwargs)
|
| 21 |
+
|
| 22 |
+
{async_flag}def reset(self, *, seed: int | None = None, options: Dict[str, str] | None = None) -> Tuple[
|
| 23 |
+
Observation, dict[str, Any]]:
|
| 24 |
+
# from options obtain user query
|
| 25 |
+
return build_observation(observer=self.name(),
|
| 26 |
+
ability=''), dict()
|
| 27 |
+
|
| 28 |
+
{async_flag}def step(self, action: List[ActionModel], **kwargs) -> Tuple[Observation, float, bool, bool, Dict[str, Any]]:
|
| 29 |
+
reward = 0
|
| 30 |
+
fail_error = ""
|
| 31 |
+
action_result = None
|
| 32 |
+
|
| 33 |
+
invalid_acts: List[int] = []
|
| 34 |
+
for i, act in enumerate(action):
|
| 35 |
+
if act.tool_name != "{name}":
|
| 36 |
+
invalid_acts.append(i)
|
| 37 |
+
|
| 38 |
+
if invalid_acts:
|
| 39 |
+
for i in invalid_acts:
|
| 40 |
+
action[i] = None
|
| 41 |
+
|
| 42 |
+
resp = ""
|
| 43 |
+
try:
|
| 44 |
+
action_result, resp = {await_flag}self.action_executor.{async_underline}execute_action(action, **kwargs)
|
| 45 |
+
reward = 1
|
| 46 |
+
except Exception as e:
|
| 47 |
+
fail_error = str(e)
|
| 48 |
+
|
| 49 |
+
terminated = kwargs.get("terminated", False)
|
| 50 |
+
if action_result:
|
| 51 |
+
for res in action_result:
|
| 52 |
+
if res.is_done:
|
| 53 |
+
terminated = res.is_done
|
| 54 |
+
|
| 55 |
+
info = dict()
|
| 56 |
+
info['exception'] = fail_error
|
| 57 |
+
info.update(kwargs)
|
| 58 |
+
if resp:
|
| 59 |
+
resp = json.dumps(resp)
|
| 60 |
+
else:
|
| 61 |
+
resp = action_result[0].content
|
| 62 |
+
|
| 63 |
+
action_result = [ActionResult(content=resp, keep=True, is_done=True)]
|
| 64 |
+
observation = build_observation(observer=self.name(),
|
| 65 |
+
ability=action[-1].action_name,
|
| 66 |
+
content=resp,
|
| 67 |
+
info=info)
|
| 68 |
+
observation.action_result = action_result
|
| 69 |
+
self._finished = True
|
| 70 |
+
return (observation,
|
| 71 |
+
reward,
|
| 72 |
+
terminated,
|
| 73 |
+
kwargs.get("truncated", False),
|
| 74 |
+
dict())
|
| 75 |
+
|
| 76 |
+
{async_flag}def close(self) -> None:
|
| 77 |
+
pass
|
| 78 |
+
|
| 79 |
+
{async_flag}def finished(self) -> bool:
|
| 80 |
+
# one time
|
| 81 |
+
return True
|
| 82 |
+
"""
|