Skip to content

Commit 7ce348f

Browse files
authored
πŸ› The intelligent generation agent cannot recognize the selected tool
2 parents b279ecd + 7147083 commit 7ce348f

File tree

7 files changed

+125
-187
lines changed

7 files changed

+125
-187
lines changed

β€Žbackend/apps/prompt_app.pyβ€Ž

Lines changed: 3 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -27,7 +27,9 @@ async def generate_and_save_system_prompt_api(
2727
task_description=prompt_request.task_description,
2828
user_id=user_id,
2929
tenant_id=tenant_id,
30-
language=language
30+
language=language,
31+
tool_ids=prompt_request.tool_ids,
32+
sub_agent_ids=prompt_request.sub_agent_ids
3133
), media_type="text/event-stream")
3234
except Exception as e:
3335
logger.exception(f"Error occurred while generating system prompt: {e}")

β€Žbackend/consts/model.pyβ€Ž

Lines changed: 2 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -193,6 +193,8 @@ class GeneratePromptRequest(BaseModel):
193193
task_description: str
194194
agent_id: int
195195
model_id: int
196+
tool_ids: Optional[List[int]] = None # Optional: tool IDs from frontend (takes precedence over database query)
197+
sub_agent_ids: Optional[List[int]] = None # Optional: sub-agent IDs from frontend (takes precedence over database query)
196198

197199

198200
class GenerateTitleRequest(BaseModel):

β€Žbackend/services/prompt_service.pyβ€Ž

Lines changed: 35 additions & 39 deletions
Original file line numberDiff line numberDiff line change
@@ -2,17 +2,17 @@
22
import logging
33
import queue
44
import threading
5+
from typing import Optional, List
56

67
from jinja2 import StrictUndefined, Template
78
from smolagents import OpenAIServerModel
89

9-
from consts.const import LANGUAGE, MODEL_CONFIG_MAPPING, MESSAGE_ROLE, THINK_END_PATTERN, THINK_START_PATTERN
10+
from consts.const import LANGUAGE, MESSAGE_ROLE, THINK_END_PATTERN, THINK_START_PATTERN
1011
from consts.model import AgentInfoRequest
11-
from database.agent_db import update_agent, query_sub_agents_id_list, search_agent_info_by_agent_id
12+
from database.agent_db import update_agent, search_agent_info_by_agent_id
1213
from database.model_management_db import get_model_by_model_id
1314
from database.tool_db import query_tools_by_ids
14-
from services.agent_service import get_enable_tool_id_by_agent_id
15-
from utils.config_utils import tenant_config_manager, get_model_name_from_config
15+
from utils.config_utils import get_model_name_from_config
1616
from utils.prompt_template_utils import get_prompt_generate_prompt_template
1717

1818
# Configure logging
@@ -34,7 +34,7 @@ def _process_thinking_tokens(new_token: str, is_thinking: bool, token_join: list
3434
"""
3535
# Handle thinking mode
3636
if is_thinking:
37-
return not (THINK_END_PATTERN in new_token)
37+
return THINK_END_PATTERN not in new_token
3838

3939
# Handle start of thinking
4040
if THINK_START_PATTERN in new_token:
@@ -98,14 +98,16 @@ def call_llm_for_system_prompt(model_id: int, user_prompt: str, system_prompt: s
9898
raise e
9999

100100

101-
def gen_system_prompt_streamable(agent_id: int, model_id: int, task_description: str, user_id: str, tenant_id: str, language: str):
101+
def gen_system_prompt_streamable(agent_id: int, model_id: int, task_description: str, user_id: str, tenant_id: str, language: str, tool_ids: Optional[List[int]] = None, sub_agent_ids: Optional[List[int]] = None):
102102
for system_prompt in generate_and_save_system_prompt_impl(
103103
agent_id=agent_id,
104104
model_id=model_id,
105105
task_description=task_description,
106106
user_id=user_id,
107107
tenant_id=tenant_id,
108-
language=language
108+
language=language,
109+
tool_ids=tool_ids,
110+
sub_agent_ids=sub_agent_ids
109111
):
110112
# SSE format, each message ends with \n\n
111113
yield f"data: {json.dumps({'success': True, 'data': system_prompt}, ensure_ascii=False)}\n\n"
@@ -116,17 +118,35 @@ def generate_and_save_system_prompt_impl(agent_id: int,
116118
task_description: str,
117119
user_id: str,
118120
tenant_id: str,
119-
language: str):
120-
# Get description of tool and agent
121-
# In create mode (agent_id=0), return empty lists
122-
if agent_id == 0:
121+
language: str,
122+
tool_ids: Optional[List[int]] = None,
123+
sub_agent_ids: Optional[List[int]] = None):
124+
# Get description of tool and agent from frontend-provided IDs
125+
# Frontend always provides tool_ids and sub_agent_ids (could be empty arrays)
126+
127+
# Handle tool IDs
128+
if tool_ids and len(tool_ids) > 0:
129+
tool_info_list = query_tools_by_ids(tool_ids)
130+
logger.debug(f"Using frontend-provided tool IDs: {tool_ids}")
131+
else:
123132
tool_info_list = []
133+
logger.debug("No tools selected (empty tool_ids list)")
134+
135+
# Handle sub-agent IDs
136+
if sub_agent_ids and len(sub_agent_ids) > 0:
124137
sub_agent_info_list = []
138+
for sub_agent_id in sub_agent_ids:
139+
try:
140+
sub_agent_info = search_agent_info_by_agent_id(
141+
agent_id=sub_agent_id, tenant_id=tenant_id)
142+
sub_agent_info_list.append(sub_agent_info)
143+
except Exception as e:
144+
logger.warning(
145+
f"Failed to get sub-agent info for agent_id {sub_agent_id}: {str(e)}")
146+
logger.debug(f"Using frontend-provided sub-agent IDs: {sub_agent_ids}")
125147
else:
126-
tool_info_list = get_enabled_tool_description_for_generate_prompt(
127-
tenant_id=tenant_id, agent_id=agent_id)
128-
sub_agent_info_list = get_enabled_sub_agent_description_for_generate_prompt(
129-
tenant_id=tenant_id, agent_id=agent_id)
148+
sub_agent_info_list = []
149+
logger.debug("No sub-agents selected (empty sub_agent_ids list)")
130150

131151
# 1. Real-time streaming push
132152
final_results = {"duty": "", "constraint": "", "few_shots": "", "agent_var_name": "", "agent_display_name": "",
@@ -292,27 +312,3 @@ def join_info_for_generate_system_prompt(prompt_for_generate, sub_agent_info_lis
292312
"assistant_description": assistant_description
293313
})
294314
return content
295-
296-
297-
def get_enabled_tool_description_for_generate_prompt(agent_id: int, tenant_id: str):
298-
# Get tool information
299-
logger.info("Fetching tool instances")
300-
tool_id_list = get_enable_tool_id_by_agent_id(
301-
agent_id=agent_id, tenant_id=tenant_id)
302-
tool_info_list = query_tools_by_ids(tool_id_list)
303-
return tool_info_list
304-
305-
306-
def get_enabled_sub_agent_description_for_generate_prompt(agent_id: int, tenant_id: str):
307-
logger.info("Fetching sub-agents information")
308-
309-
sub_agent_id_list = query_sub_agents_id_list(
310-
main_agent_id=agent_id, tenant_id=tenant_id)
311-
312-
sub_agent_info_list = []
313-
for sub_agent_id in sub_agent_id_list:
314-
sub_agent_info = search_agent_info_by_agent_id(
315-
agent_id=sub_agent_id, tenant_id=tenant_id)
316-
317-
sub_agent_info_list.append(sub_agent_info)
318-
return sub_agent_info_list

β€Žfrontend/app/[locale]/agents/AgentConfiguration.tsxβ€Ž

Lines changed: 13 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -161,12 +161,25 @@ export default forwardRef<AgentConfigHandle, AgentConfigProps>(function AgentCon
161161
const currentAgentName = agentName;
162162
const currentAgentDisplayName = agentDisplayName;
163163

164+
// Extract tool IDs from selected tools (convert string IDs to numbers)
165+
// Always pass tool_ids array (empty array means no tools selected, undefined means use database)
166+
// In edit mode, we want to use current selection, so pass the array even if empty
167+
const toolIds = selectedTools.map((tool) => Number(tool.id));
168+
169+
// Get sub-agent IDs from enabledAgentIds
170+
// Always pass sub_agent_ids array (empty array means no sub-agents selected, undefined means use database)
171+
// In edit mode, we want to use current selection, so pass the array even if empty
172+
const subAgentIds = [...enabledAgentIds];
173+
164174
// Call backend API to generate agent prompt
175+
// Pass tool_ids and sub_agent_ids to use frontend selection instead of database query
165176
await generatePromptStream(
166177
{
167178
agent_id: agentIdToUse,
168179
task_description: businessLogic,
169180
model_id: selectedModel?.id?.toString() || "",
181+
tool_ids: toolIds,
182+
sub_agent_ids: subAgentIds,
170183
},
171184
(data) => {
172185
// Process streaming response data

β€Žfrontend/app/[locale]/agents/components/tool/ToolConfigModal.tsxβ€Ž

Lines changed: 41 additions & 51 deletions
Original file line numberDiff line numberDiff line change
@@ -65,69 +65,59 @@ export default function ToolConfigModal({
6565

6666
// load tool config
6767
useEffect(() => {
68+
const buildDefaultParams = () =>
69+
(tool?.initParams || []).map((param) => ({
70+
...param,
71+
value: param.value,
72+
}));
73+
6874
const loadToolConfig = async () => {
69-
if (tool && mainAgentId) {
70-
setIsLoading(true);
71-
try {
72-
const result = await searchToolConfig(parseInt(tool.id), mainAgentId);
73-
if (result.success) {
74-
if (result.data?.params) {
75-
// use backend returned config content
76-
const savedParams = tool.initParams.map((param) => {
77-
// if backend returned config has this param value, use backend returned value
78-
// otherwise use param default value
79-
const savedValue = result.data.params[param.name];
80-
return {
81-
...param,
82-
value: savedValue !== undefined ? savedValue : param.value,
83-
};
84-
});
85-
setCurrentParams(savedParams);
86-
} else {
87-
// if backend returned params is null, means no saved config, use default config
88-
setCurrentParams(
89-
tool.initParams.map((param) => ({
90-
...param,
91-
value: param.value, // use default value
92-
}))
93-
);
94-
}
95-
} else {
96-
message.error(result.message || t("toolConfig.message.loadError"));
97-
// when load failed, use default config
98-
setCurrentParams(
99-
tool.initParams.map((param) => ({
75+
if (!tool) {
76+
setCurrentParams([]);
77+
return;
78+
}
79+
80+
// In creation mode we do not have an agent ID yet, so use the tool's default params.
81+
if (!mainAgentId) {
82+
setCurrentParams(buildDefaultParams());
83+
return;
84+
}
85+
86+
setIsLoading(true);
87+
try {
88+
const result = await searchToolConfig(parseInt(tool.id), mainAgentId);
89+
if (result.success) {
90+
if (result.data?.params) {
91+
const savedParams = tool.initParams.map((param) => {
92+
const savedValue = result.data.params[param.name];
93+
return {
10094
...param,
101-
value: param.value,
102-
}))
103-
);
95+
value: savedValue !== undefined ? savedValue : param.value,
96+
};
97+
});
98+
setCurrentParams(savedParams);
99+
} else {
100+
setCurrentParams(buildDefaultParams());
104101
}
105-
} catch (error) {
106-
log.error(t("toolConfig.message.loadError"), error);
107-
message.error(t("toolConfig.message.loadErrorUseDefault"));
108-
// when error occurs, use default config
109-
setCurrentParams(
110-
tool.initParams.map((param) => ({
111-
...param,
112-
value: param.value,
113-
}))
114-
);
115-
} finally {
116-
setIsLoading(false);
102+
} else {
103+
message.error(result.message || t("toolConfig.message.loadError"));
104+
setCurrentParams(buildDefaultParams());
117105
}
118-
} else {
119-
// if there is no tool or mainAgentId, clear params
120-
setCurrentParams([]);
106+
} catch (error) {
107+
log.error(t("toolConfig.message.loadError"), error);
108+
message.error(t("toolConfig.message.loadErrorUseDefault"));
109+
setCurrentParams(buildDefaultParams());
110+
} finally {
111+
setIsLoading(false);
121112
}
122113
};
123114

124115
if (isOpen && tool) {
125116
loadToolConfig();
126117
} else {
127-
// when modal is closed, clear params
128118
setCurrentParams([]);
129119
}
130-
}, [isOpen, tool, mainAgentId, t]);
120+
}, [isOpen, tool, mainAgentId, t, message]);
131121

132122
// check required fields
133123
const checkRequiredFields = () => {

β€Žfrontend/types/agentConfig.tsβ€Ž

Lines changed: 2 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -323,6 +323,8 @@ export interface GeneratePromptParams {
323323
agent_id: number;
324324
task_description: string;
325325
model_id: string;
326+
tool_ids?: number[]; // Optional: tool IDs selected in frontend (takes precedence over database query)
327+
sub_agent_ids?: number[]; // Optional: sub-agent IDs selected in frontend (takes precedence over database query)
326328
}
327329

328330
/**

0 commit comments

Comments
Β (0)