Skip to content

Commit 331a6a6

Browse files
committed
refactor: streamline job handling by removing URLs and adding validation functions
1 parent c4971d8 commit 331a6a6

7 files changed

Lines changed: 63 additions & 20 deletions

File tree

agents/matmaster_agent/base_agents/callback.py

Lines changed: 41 additions & 8 deletions
Original file line numberDiff line numberDiff line change
@@ -14,7 +14,7 @@
1414
from google.adk.agents.llm_agent import AfterToolCallback, BeforeToolCallback
1515
from google.adk.models import LlmResponse
1616
from google.adk.tools import BaseTool, ToolContext
17-
from mcp.types import CallToolResult
17+
from mcp.types import CallToolResult, TextContent
1818

1919
from agents.matmaster_agent.constant import (
2020
CURRENT_ENV,
@@ -32,10 +32,10 @@
3232
function_calls_to_str,
3333
get_session_state,
3434
get_unique_function_call,
35-
is_json,
3635
update_llm_response,
3736
)
3837
from agents.matmaster_agent.utils.io_oss import update_tgz_dict
38+
from agents.matmaster_agent.utils.tool_response_utils import check_valid_tool_response
3939

4040
logger = logging.getLogger(__name__)
4141

@@ -457,12 +457,7 @@ async def wrapper(
457457
raise TypeError('Not CalculationMCPTool type')
458458

459459
# 检查是否为有效的 json 字典
460-
if not (
461-
tool_response
462-
and tool_response.content
463-
and tool_response.content[0].text
464-
and is_json(tool_response.content[0].text)
465-
):
460+
if not check_valid_tool_response(tool_response):
466461
return None
467462

468463
tool_result = json.loads(tool_response.content[0].text)
@@ -473,6 +468,44 @@ async def wrapper(
473468
return wrapper
474469

475470

471+
def remove_job_link(func: AfterToolCallback) -> AfterToolCallback:
472+
@wraps(func)
473+
async def wrapper(
474+
tool: BaseTool,
475+
args: dict,
476+
tool_context: ToolContext,
477+
tool_response: Union[dict, CallToolResult],
478+
) -> Optional[dict]:
479+
# 两步操作:
480+
# 1. 调用被装饰的 after_tool_callback;
481+
# 2. 如果调用的 after_tool_callback 有返回值,以这个为准
482+
# 如果 tool 为 Transfer2Agent,直接 return
483+
if tool.name == Transfer2Agent:
484+
return None
485+
486+
if (
487+
after_tool_result := await func(tool, args, tool_context, tool_response)
488+
) is not None:
489+
return after_tool_result
490+
491+
# 检查是否为有效的 json 字典
492+
if not check_valid_tool_response(tool_response):
493+
return None
494+
495+
# 移除 job_link
496+
tool_result: dict = json.loads(tool_response.content[0].text)
497+
if tool_result.get('extra_info', None) is not None:
498+
del tool_result['extra_info']['job_link']
499+
tool_response.content[0] = TextContent(
500+
type='text', text=json.dumps(tool_result)
501+
)
502+
503+
logger.info(f"[remove_job_link] final_tool_result = {tool_response}")
504+
return tool_response
505+
506+
return wrapper
507+
508+
476509
def catch_after_tool_callback_error(func: AfterToolCallback) -> AfterToolCallback:
477510
@wraps(func)
478511
async def wrapper(

agents/matmaster_agent/base_agents/job_agent.py

Lines changed: 4 additions & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -23,6 +23,7 @@
2323
inject_current_env,
2424
inject_username_ticket,
2525
remove_function_call,
26+
remove_job_link,
2627
tgz_oss_to_oss_list,
2728
)
2829
from agents.matmaster_agent.base_agents.io_agent import HandleFileUploadLlmAgent
@@ -39,7 +40,6 @@
3940
MATERIALS_PROJECT_ID,
4041
TMP_FRONTEND_STATE_KEY,
4142
ModelRole,
42-
OpenAPIJobAPI,
4343
get_BohriumExecutor,
4444
get_BohriumStorage,
4545
get_DFlowExecutor,
@@ -166,7 +166,9 @@ def __init__(
166166
)
167167
after_tool_callback = check_before_tool_callback_effect(
168168
catch_after_tool_callback_error(
169-
tgz_oss_to_oss_list(after_tool_callback, enable_tgz_unpack)
169+
remove_job_link(
170+
tgz_oss_to_oss_list(after_tool_callback, enable_tgz_unpack)
171+
)
170172
)
171173
)
172174

@@ -412,12 +414,10 @@ async def _run_async_impl(
412414
job_status = results['status']
413415
if not ctx.session.state['dflow']:
414416
bohr_job_id = results['extra_info']['bohr_job_id']
415-
job_query_url = f'{OpenAPIJobAPI}/{bohr_job_id}'
416417
frontend_result = BohrJobInfo(
417418
origin_job_id=origin_job_id,
418419
job_name=job_name,
419420
job_status=job_status,
420-
job_query_url=job_query_url,
421421
job_id=bohr_job_id,
422422
agent_name=ctx.agent.parent_agent.parent_agent.name,
423423
).model_dump(mode='json')

agents/matmaster_agent/callback.py

Lines changed: 2 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -124,13 +124,13 @@ async def matmaster_check_job_status(
124124
i18n.language = 'en'
125125

126126
reset = False
127-
for origin_job_id, job_id, job_query_url, agent_name in running_job_ids:
127+
for origin_job_id, job_id, agent_name in running_job_ids:
128128
if not callback_context.state['last_llm_response_partial']:
129129
logger.info(
130130
'[matmaster_check_job_status] new LlmResponse, prepare call API'
131131
)
132132
job_status = await get_job_status(
133-
job_query_url, access_key=MATERIALS_ACCESS_KEY
133+
job_id, access_key=MATERIALS_ACCESS_KEY
134134
) # 查询任务的最新状态
135135
callback_context.state['new_query_job_status'][
136136
'origin_job_id'

agents/matmaster_agent/main.py

Lines changed: 2 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -60,11 +60,11 @@ async def agent_main() -> None:
6060
# user_input = "高熵合金AlCoCr0.5FeNi2的可能结构是什么"
6161
# user_input = "调用 thermoelectric_agent 帮我生成10个具有Sn和Te元素的热电结构"
6262
# user_input = "plot perovstite 2021 to 2025"
63-
user_input = '帮我创建一个 FCC Bulk Cu 的结构'
63+
# user_input = '帮我创建一个 FCC Bulk Cu 的结构'
6464
# user_input = "帮我用DPA优化这个结构:https://dp-storage-test2.oss-cn-zhangjiakou.aliyuncs.com/bohrium-test/110663/12791/store/7ba41529-5af4-4e38-a6fb-c569cd769dd9/outputs/structure_paths/structure_bulk.cif"
6565
# user_input = "帮我检索TiO2"
6666
# user_input = "请你为我搭建一个氯化钠的结构"
67-
# user_input = '我想要一个bandgap 小于0.5ev的结构,空间群225,生成数量1'
67+
user_input = '我想要一个bandgap 小于0.5ev的结构,空间群225,生成数量1'
6868
# user_input = '用openlam查找一个TiO2'
6969
print(f"🧑 用户:{user_input}")
7070

agents/matmaster_agent/model.py

Lines changed: 0 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -52,7 +52,6 @@ class JobResult(BaseModel):
5252
class BohrJobInfo(BaseModel):
5353
origin_job_id: str
5454
job_id: Union[int, str]
55-
job_query_url: str
5655
job_status: JobStatus
5756
job_name: str
5857
job_result: Optional[List[JobResult]] = None

agents/matmaster_agent/utils/job_utils.py

Lines changed: 4 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -1,5 +1,6 @@
11
import aiohttp
22

3+
from agents.matmaster_agent.constant import OpenAPIJobAPI
34
from agents.matmaster_agent.model import BohrJobInfo, JobStatus
45

56

@@ -19,10 +20,10 @@ def mapping_status(status):
1920
}.get(status, 'Unknown')
2021

2122

22-
async def get_job_status(job_query_url, access_key):
23+
async def get_job_status(job_id, access_key):
2324
async with aiohttp.ClientSession() as session:
2425
async with session.get(
25-
job_query_url, headers={'accessKey': access_key}
26+
f'{OpenAPIJobAPI}/{job_id}', headers={'accessKey': access_key}
2627
) as response:
2728
data = await response.json()
2829
return mapping_status(data['data']['status'])
@@ -35,7 +36,7 @@ def has_job_running(jobs_dict: BohrJobInfo) -> bool:
3536

3637
def get_running_jobs_detail(jobs_dict: BohrJobInfo):
3738
return [
38-
(job['origin_job_id'], job['job_id'], job['job_query_url'], job['agent_name'])
39+
(job['origin_job_id'], job['job_id'], job['agent_name'])
3940
for job in jobs_dict.values()
4041
if job['job_status'] == JobStatus.Running
4142
]
Lines changed: 10 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,10 @@
1+
from agents.matmaster_agent.utils.helper_func import is_json
2+
3+
4+
def check_valid_tool_response(tool_response):
5+
return (
6+
tool_response
7+
and tool_response.content
8+
and tool_response.content[0].text
9+
and is_json(tool_response.content[0].text)
10+
)

0 commit comments

Comments
 (0)