Skip to content

Commit

Permalink
ToolAssistant-优化ToolAssistant
Browse files Browse the repository at this point in the history
  • Loading branch information
cinjospeh committed Jan 6, 2025
1 parent 84ebf34 commit 6363145
Show file tree
Hide file tree
Showing 2 changed files with 76 additions and 7 deletions.
48 changes: 42 additions & 6 deletions dbgpt/agent/expand/actions/tool_action.py
Original file line number Diff line number Diff line change
Expand Up @@ -21,12 +21,14 @@ class ToolInput(BaseModel):
tool_name: str = Field(
...,
description="The name of a tool that can be used to answer the current question"
" or solve the current task.",
" or solve the current task. "
"If no suitable tool is selected, leave this blank.",
)
args: dict = Field(
default={"arg name1": "", "arg name2": ""},
description="The tool selected for the current target, the parameter "
"information required for execution",
"information required for execution, "
"If no suitable tool is selected, leave this blank.",
)
thought: str = Field(..., description="Summary of thoughts to the user")

Expand Down Expand Up @@ -68,9 +70,9 @@ def ai_out_schema(self) -> Optional[str]:
}

return f"""Please response in the following json format:
{json.dumps(out_put_schema, indent=2, ensure_ascii=False)}
Make sure the response is correct json and can be parsed by Python json.loads.
"""
{json.dumps(out_put_schema, indent=2, ensure_ascii=False)}
Make sure the response is correct json and can be parsed by Python json.loads.
and do not write the comment in json,only write the json content."""

async def run(
self,
Expand All @@ -91,6 +93,15 @@ async def run(
need_vis_render (bool, optional): Whether need visualization rendering.
Defaults to True.
"""
success, error = parse_json_safe(ai_message)
if not success:
return ActionOutput(
is_exe_success=False,
content=f"Tool Action execute failed! llm reply {ai_message} "
f"is not a valid json format, json error: {error}. "
f"You need to strictly return the raw JSON format. ",
)

try:
param: ToolInput = self._input_convert(ai_message, ToolInput)
except Exception as e:
Expand All @@ -100,6 +111,16 @@ async def run(
content="The requested correctly structured answer could not be found.",
)

if param.tool_name is None or param.tool_name == "":
# can not choice tools, it must be some reason
return ActionOutput(
is_exe_success=False,
# content= param.thought,
content=f"There are no suitable tools available "
f"to achieve the user's goal: '{param.thought}'",
have_retry=False,
)

try:
tool_packs = ToolPack.from_resource(self.resource)
if not tool_packs:
Expand Down Expand Up @@ -137,10 +158,25 @@ async def run(
is_exe_success=response_success,
content=str(tool_result),
view=view,
thoughts=param.thought,
action=str({"tool_name": param.tool_name, "args": param.args}),
observations=str(tool_result),
)
except Exception as e:
logger.exception("Tool Action Run Failed!")
return ActionOutput(
is_exe_success=False, content=f"Tool action run failed!{str(e)}"
is_exe_success=False,
content=f"Tool action run failed!{str(e)}",
action=str({"tool_name": param.tool_name, "args": param.args}),
)


def parse_json_safe(json_str):
"""Try to parse json."""
try:
# try to parse json
data = json.loads(json_str)
return True, data
except json.JSONDecodeError as e:
# 捕捉JSON解析错误并返回详细信息
return False, e.msg
35 changes: 34 additions & 1 deletion dbgpt/agent/expand/tool_assistant_agent.py
Original file line number Diff line number Diff line change
@@ -1,9 +1,12 @@
"""Plugin Assistant Agent."""

import logging
from typing import List, Optional

from .. import Resource, ResourceType
from ..core.base_agent import ConversableAgent
from ..core.profile import DynConfig, ProfileConfig
from ..resource import BaseTool
from .actions.tool_action import ToolAction

logger = logging.getLogger(__name__)
Expand Down Expand Up @@ -37,7 +40,10 @@ class ToolAssistantAgent(ConversableAgent):
"goal.",
"Please output the selected tool name and specific parameter "
"information in json format according to the following required format."
" If there is an example, please refer to the sample format output.",
"If there is an example, please refer to the sample format output.",
"It is not necessarily required to select a tool for execution. "
"If the tool to be used or its parameters cannot be clearly "
"determined based on the user's input, you can choose not to execute.",
],
category="agent",
key="dbgpt_agent_expand_plugin_assistant_agent_constraints",
Expand All @@ -54,3 +60,30 @@ def __init__(self, **kwargs):
"""Create a new instance of ToolAssistantAgent."""
super().__init__(**kwargs)
self._init_actions([ToolAction])

@property
def desc(self) -> Optional[str]:
tools = _get_tools_by_resource(self.resource)

if tools is None or len(tools) == 0:
return "Has no tools to use"

return (
"Can use the following tools to complete the task objectives, tool information: "
f"{' '.join([f'{i+1}. tool {tools[i].name}, can {tools[i].description}.' for i in range(len(tools))])}"
)


def _get_tools_by_resource(resource: Resource) -> List[BaseTool]:
tools: List[BaseTool] = []

if resource is None:
return tools

if resource.type() == ResourceType.Tool and isinstance(resource, BaseTool):
tools.append(resource)
elif resource.type() == ResourceType.Pack:
for sub_res in resource.sub_resources:
tools.extend(_get_tools_by_resource(sub_res))

return tools

0 comments on commit 6363145

Please sign in to comment.