-
Notifications
You must be signed in to change notification settings - Fork 2.8k
Expand file tree
/
Copy pathtool_task.py
More file actions
193 lines (163 loc) · 6.63 KB
/
tool_task.py
File metadata and controls
193 lines (163 loc) · 6.63 KB
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
# coding=utf-8
"""
@project: MaxKB
@Author:虎虎
@file: application_task.py
@date:2026/1/14 19:14
@desc:
"""
import json
import time
import traceback
import uuid_utils.compat as uuid
from django.db.models import QuerySet
from common.utils.logger import maxkb_logger
from common.utils.rsa_util import rsa_long_decrypt
from common.utils.tool_code import ToolExecutor
from knowledge.models.knowledge_action import State
from tools.models import Tool, ToolRecord, ToolTaskTypeChoices
from trigger.handler.base_task import BaseTriggerTask
from trigger.models import TaskRecord
executor = ToolExecutor()
def get_reference(fields, obj):
for field in fields:
value = obj.get(field)
if value is None:
return None
else:
obj = value
return obj
def get_field_value(value, kwargs):
source = value.get('source')
if source == 'custom':
return value.get('value')
else:
return get_reference(value.get('value'), kwargs)
def _coerce_by_type(field_type, raw):
if raw is None:
return None
t = (field_type or "").lower()
if t in ("string", "str", "text"):
return str(raw)
if t in ("int", "integer"):
return int(raw)
if t in ("float", "number", "double"):
return float(raw)
if t in ("bool", "boolean"):
if isinstance(raw, bool):
return raw
if isinstance(raw, (int, float)):
return bool(raw)
if isinstance(raw, str):
v = raw.strip().lower()
if v in ("true", "1", "yes", "y", "on"):
return True
if v in ("false", "0", "no", "n", "off"):
return False
raise ValueError(f"Cannot coerce {raw!r} to bool")
if t in ("list", "array"):
if isinstance(raw, list):
return raw
if isinstance(raw, tuple):
return list(raw)
raise ValueError(f"Cannot coerce {raw!r} to list")
if t in ("dict", "object", "json"):
if isinstance(raw, dict):
return raw
raise ValueError(f"Cannot coerce {raw!r} to dict")
return raw
def get_tool_execute_parameters(input_field_list, parameter_setting, kwargs):
type_map = {f.get("name"): f.get("type") for f in (input_field_list or []) if f.get("name")}
parameters = {}
for key, value in parameter_setting.items():
raw = get_field_value(value, kwargs)
parameters[key] = _coerce_by_type(type_map.get(key), raw)
return parameters
def get_loop_workflow_node(node_list):
result = []
for item in node_list:
if item.get('type') == 'loop-node':
for loop_item in item.get('loop_node_data') or []:
for inner_item in loop_item.values():
result.append(inner_item)
return result
def get_workflow_state(details):
node_list = details.values()
all_node = [*node_list, *get_loop_workflow_node(node_list)]
err = any([True for value in all_node if value.get('status') == 500 and not value.get('enableException')])
if err:
return State.FAILURE
return State.SUCCESS
def _get_result_detail(result):
if isinstance(result, dict):
result_dict = {k: (str(v)[:500] if len(str(v)) > 500 else v) for k, v in result.items()}
elif isinstance(result, list):
result_dict = [str(item)[:500] if len(str(item)) > 500 else item for item in result]
elif isinstance(result, str):
result_dict = result[:500] if len(result) > 500 else result
else:
result_dict = result
return result_dict
class ToolTask(BaseTriggerTask):
def support(self, trigger_task, **kwargs):
return trigger_task.get('source_type') == 'TOOL'
def execute(self, trigger_task, **kwargs):
parameter_setting = trigger_task.get('parameter')
tool_id = trigger_task.get('source_id')
task_record_id = uuid.uuid7()
start_time = time.time()
try:
tool = QuerySet(Tool).filter(id=tool_id, is_active=True).first()
if not tool:
maxkb_logger.info(f"Tool with id {tool_id} not found or inactive.")
return
TaskRecord(
id=task_record_id,
trigger_id=trigger_task.get('trigger'),
trigger_task_id=trigger_task.get('id'),
source_type="TOOL",
source_id=tool_id,
task_record_id=task_record_id,
meta={'input': parameter_setting, 'output': {}},
state=State.STARTED
).save()
ToolRecord(
id=task_record_id,
workspace_id=tool.workspace_id,
tool_id=tool.id,
source_type=ToolTaskTypeChoices.TRIGGER,
source_id=trigger_task.get('trigger'),
meta={'input': parameter_setting, 'output': {}},
state=State.STARTED
).save()
parameters = get_tool_execute_parameters(tool.input_field_list, parameter_setting, kwargs)
init_params_default_value = {i["field"]: i.get('default_value') for i in tool.init_field_list}
if tool.init_params is not None:
all_params = init_params_default_value | json.loads(rsa_long_decrypt(tool.init_params)) | parameters
else:
all_params = init_params_default_value | parameters
result = executor.exec_code(tool.code, all_params)
result_dict = _get_result_detail(result)
maxkb_logger.debug(f"Tool execution result: {result}")
QuerySet(TaskRecord).filter(id=task_record_id).update(
state=State.SUCCESS,
run_time=time.time() - start_time,
meta={'input': parameter_setting, 'output': result_dict}
)
QuerySet(ToolRecord).filter(id=task_record_id).update(
state=State.SUCCESS,
run_time=time.time() - start_time,
meta={'input': all_params, 'output': result_dict}
)
except Exception as e:
maxkb_logger.error(f"Tool execution error: {traceback.format_exc()}")
QuerySet(TaskRecord).filter(id=task_record_id).update(
state=State.FAILURE,
run_time=time.time() - start_time,
meta={'input': parameter_setting, 'output': 'Error: ' + str(e), 'err_message': 'Error: ' + str(e)}
)
QuerySet(ToolRecord).filter(id=task_record_id).update(
state=State.FAILURE,
run_time=time.time() - start_time,
meta={'input': parameter_setting, 'output': 'Error: ' + str(e), 'err_message': 'Error: ' + str(e)}
)