Skip to content

Commit 6363145

Browse files
author
cinjospeh
committed
ToolAssistant-优化ToolAssistant
1 parent 84ebf34 commit 6363145

File tree

2 files changed

+76
-7
lines changed

2 files changed

+76
-7
lines changed

dbgpt/agent/expand/actions/tool_action.py

Lines changed: 42 additions & 6 deletions
Original file line numberDiff line numberDiff line change
@@ -21,12 +21,14 @@ class ToolInput(BaseModel):
2121
tool_name: str = Field(
2222
...,
2323
description="The name of a tool that can be used to answer the current question"
24-
" or solve the current task.",
24+
" or solve the current task. "
25+
"If no suitable tool is selected, leave this blank.",
2526
)
2627
args: dict = Field(
2728
default={"arg name1": "", "arg name2": ""},
2829
description="The tool selected for the current target, the parameter "
29-
"information required for execution",
30+
"information required for execution, "
31+
"If no suitable tool is selected, leave this blank.",
3032
)
3133
thought: str = Field(..., description="Summary of thoughts to the user")
3234

@@ -68,9 +70,9 @@ def ai_out_schema(self) -> Optional[str]:
6870
}
6971

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

7577
async def run(
7678
self,
@@ -91,6 +93,15 @@ async def run(
9193
need_vis_render (bool, optional): Whether need visualization rendering.
9294
Defaults to True.
9395
"""
96+
success, error = parse_json_safe(ai_message)
97+
if not success:
98+
return ActionOutput(
99+
is_exe_success=False,
100+
content=f"Tool Action execute failed! llm reply {ai_message} "
101+
f"is not a valid json format, json error: {error}. "
102+
f"You need to strictly return the raw JSON format. ",
103+
)
104+
94105
try:
95106
param: ToolInput = self._input_convert(ai_message, ToolInput)
96107
except Exception as e:
@@ -100,6 +111,16 @@ async def run(
100111
content="The requested correctly structured answer could not be found.",
101112
)
102113

114+
if param.tool_name is None or param.tool_name == "":
115+
# can not choice tools, it must be some reason
116+
return ActionOutput(
117+
is_exe_success=False,
118+
# content= param.thought,
119+
content=f"There are no suitable tools available "
120+
f"to achieve the user's goal: '{param.thought}'",
121+
have_retry=False,
122+
)
123+
103124
try:
104125
tool_packs = ToolPack.from_resource(self.resource)
105126
if not tool_packs:
@@ -137,10 +158,25 @@ async def run(
137158
is_exe_success=response_success,
138159
content=str(tool_result),
139160
view=view,
161+
thoughts=param.thought,
162+
action=str({"tool_name": param.tool_name, "args": param.args}),
140163
observations=str(tool_result),
141164
)
142165
except Exception as e:
143166
logger.exception("Tool Action Run Failed!")
144167
return ActionOutput(
145-
is_exe_success=False, content=f"Tool action run failed!{str(e)}"
168+
is_exe_success=False,
169+
content=f"Tool action run failed!{str(e)}",
170+
action=str({"tool_name": param.tool_name, "args": param.args}),
146171
)
172+
173+
174+
def parse_json_safe(json_str):
175+
"""Try to parse json."""
176+
try:
177+
# try to parse json
178+
data = json.loads(json_str)
179+
return True, data
180+
except json.JSONDecodeError as e:
181+
# 捕捉JSON解析错误并返回详细信息
182+
return False, e.msg

dbgpt/agent/expand/tool_assistant_agent.py

Lines changed: 34 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -1,9 +1,12 @@
11
"""Plugin Assistant Agent."""
22

33
import logging
4+
from typing import List, Optional
45

6+
from .. import Resource, ResourceType
57
from ..core.base_agent import ConversableAgent
68
from ..core.profile import DynConfig, ProfileConfig
9+
from ..resource import BaseTool
710
from .actions.tool_action import ToolAction
811

912
logger = logging.getLogger(__name__)
@@ -37,7 +40,10 @@ class ToolAssistantAgent(ConversableAgent):
3740
"goal.",
3841
"Please output the selected tool name and specific parameter "
3942
"information in json format according to the following required format."
40-
" If there is an example, please refer to the sample format output.",
43+
"If there is an example, please refer to the sample format output.",
44+
"It is not necessarily required to select a tool for execution. "
45+
"If the tool to be used or its parameters cannot be clearly "
46+
"determined based on the user's input, you can choose not to execute.",
4147
],
4248
category="agent",
4349
key="dbgpt_agent_expand_plugin_assistant_agent_constraints",
@@ -54,3 +60,30 @@ def __init__(self, **kwargs):
5460
"""Create a new instance of ToolAssistantAgent."""
5561
super().__init__(**kwargs)
5662
self._init_actions([ToolAction])
63+
64+
@property
65+
def desc(self) -> Optional[str]:
66+
tools = _get_tools_by_resource(self.resource)
67+
68+
if tools is None or len(tools) == 0:
69+
return "Has no tools to use"
70+
71+
return (
72+
"Can use the following tools to complete the task objectives, tool information: "
73+
f"{' '.join([f'{i+1}. tool {tools[i].name}, can {tools[i].description}.' for i in range(len(tools))])}"
74+
)
75+
76+
77+
def _get_tools_by_resource(resource: Resource) -> List[BaseTool]:
78+
tools: List[BaseTool] = []
79+
80+
if resource is None:
81+
return tools
82+
83+
if resource.type() == ResourceType.Tool and isinstance(resource, BaseTool):
84+
tools.append(resource)
85+
elif resource.type() == ResourceType.Pack:
86+
for sub_res in resource.sub_resources:
87+
tools.extend(_get_tools_by_resource(sub_res))
88+
89+
return tools

0 commit comments

Comments
 (0)