Skip to content

Commit 9f7cfe4

Browse files
authored
Merge pull request #651 from AnguseZhang/fix/unsupported_archive
feat: enhance logging and environment flexibility by adding session_i…
2 parents ff2e012 + 69bfcb6 commit 9f7cfe4

5 files changed

Lines changed: 35 additions & 19 deletions

File tree

agents/matmaster_agent/constant.py

Lines changed: 3 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -53,11 +53,13 @@
5353
if CURRENT_ENV == 'test':
5454
DFLOW_HOST = 'https://lbg-workflow-mlops.test.dp.tech'
5555
DFLOW_K8S_API_SERVER = 'https://lbg-workflow-mlops.test.dp.tech'
56+
TIEFBLUE_NAS_HOST = 'https://tiefblue-nas-acs-bj.test.bohrium.com'
5657
elif CURRENT_ENV == 'uat':
57-
pass
58+
TIEFBLUE_NAS_HOST = 'https://tiefblue-nas-acs-bj.test.bohrium.com'
5859
elif CURRENT_ENV == 'prod':
5960
DFLOW_HOST = 'https://workflows.deepmodeling.com'
6061
DFLOW_K8S_API_SERVER = 'https://workflows.deepmodeling.com'
62+
TIEFBLUE_NAS_HOST = 'https://tiefblue-nas-acs-bj.bohrium.com'
6163

6264
# API URL
6365
OPENAPI_SANDBOX = f'{OPENAPI_HOST}/openapi/v1/sandbox'

agents/matmaster_agent/core_agents/public_agents/job_agents/result_core_agent/agent.py

Lines changed: 3 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -141,7 +141,9 @@ async def _run_events(self, ctx: InvocationContext) -> AsyncGenerator[Event, Non
141141
logger.info(f"{ctx.session.id} dict_result = {dict_result}")
142142

143143
if self.enable_tgz_unpack:
144-
tgz_flag, new_tool_result = await update_tgz_dict(dict_result)
144+
tgz_flag, new_tool_result = await update_tgz_dict(
145+
dict_result, session_id=ctx.session.id
146+
)
145147
else:
146148
new_tool_result = dict_result
147149
parsed_tool_result = await parse_result(ctx, new_tool_result)

agents/matmaster_agent/services/job.py

Lines changed: 7 additions & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -11,6 +11,7 @@
1111
MATMASTER_AGENT_NAME,
1212
OPENAPI_FILE_TOKEN_API,
1313
OPENAPI_HOST,
14+
TIEFBLUE_NAS_HOST,
1415
OpenAPIJobAPI,
1516
)
1617
from agents.matmaster_agent.logger import PrefixFilter
@@ -153,7 +154,7 @@ async def get_token_and_download_dir(dir_path, job_id, access_key):
153154
}
154155
async with aiohttp.ClientSession() as session:
155156
async with session.post(
156-
'https://tiefblue-nas-acs-bj.test.bohrium.com/api/downloadr',
157+
f'{TIEFBLUE_NAS_HOST}/api/downloadr',
157158
json=request_body,
158159
headers={
159160
'Authorization': f"Bearer {token}",
@@ -197,7 +198,9 @@ async def get_iterate_files(
197198
return prefix, iterate_json
198199

199200

200-
async def parse_and_prepare_results(job_id: str = '', access_key: str = ''):
201+
async def parse_and_prepare_results(
202+
job_id: str = '', access_key: str = '', session_id: str = ''
203+
):
201204
def norm(p: str) -> str:
202205
p = p.replace('\\', '/')
203206
if p.endswith('/') and p != '/':
@@ -294,7 +297,7 @@ async def safe_cleanup_file(file_download_path: Path):
294297
results_txt_parsed = jsonpickle.loads(
295298
f.read().replace('pathlib._local.PosixPath', 'pathlib.PosixPath')
296299
)
297-
logger.info(f"results_txt_parsed = {results_txt_parsed}")
300+
logger.info(f"{session_id} results_txt_parsed = {results_txt_parsed}")
298301
os.remove(RESULTS_TXT)
299302

300303
final_results = {}
@@ -318,7 +321,7 @@ async def safe_cleanup_file(file_download_path: Path):
318321
obj = await find_obj(rel)
319322

320323
if obj is None:
321-
logger.warning(f"`{rel}` is not exist")
324+
logger.warning(f"{session_id} `{rel}` is not exist")
322325
continue
323326

324327
is_dir = bool(obj.get('isDir'))

agents/matmaster_agent/utils/io_oss.py

Lines changed: 9 additions & 5 deletions
Original file line numberDiff line numberDiff line change
@@ -162,13 +162,14 @@ async def upload_base64_to_oss(data: str, oss_path: str) -> dict:
162162

163163

164164
async def extract_convert_and_upload(
165-
compressed_url: str, temp_dir_path: str = './tmp'
165+
compressed_url: str, temp_dir_path: str = './tmp', session_id: str = ''
166166
) -> dict:
167167
"""
168168
下载 TGZ → 解压 → JPG 转 Base64 → 上传 OSS → 自动清理
169169
"""
170170
async with temp_dir(temp_dir_path) as temp_path:
171171
# 获取所有JPG文件的Base64编码
172+
logger.info(f"{session_id} compressed_url = {compressed_url}")
172173
files = await extract_files_from_compressed_file_url(compressed_url, temp_path)
173174
conversion_tasks = [file_to_base64(file) for file in files]
174175
base64_results = await asyncio.gather(*conversion_tasks)
@@ -187,14 +188,16 @@ async def extract_convert_and_upload(
187188
}
188189

189190

190-
async def update_tgz_dict(tool_result: dict):
191+
async def update_tgz_dict(tool_result: dict, session_id: str = ''):
191192
new_tool_result = {}
192193
compressed_flag = False
193194
for k, v in tool_result.items():
194195
new_tool_result[k] = v
195196
if isinstance(v, str) and v.startswith('https') and v.endswith(('tgz', 'zip')):
196197
compressed_flag = True
197-
new_tool_result.update(**await extract_convert_and_upload(v))
198+
new_tool_result.update(
199+
**await extract_convert_and_upload(v, session_id=session_id)
200+
)
198201

199202
return compressed_flag, new_tool_result
200203

@@ -212,6 +215,7 @@ async def extract_file_content(file_url: str, temp_dir_path: str = './tmp') -> d
212215

213216

214217
if __name__ == '__main__':
215-
invalid_zip = 'https://bohrium-agent-test.oss-cn-zhangjiakou.aliyuncs.com/agent/jobs/337612/72f4337ea51448edacabf9559bc630b3/outputs.zip'
218+
invalid_zip = 'https://bohrium-agent-test.oss-cn-zhangjiakou.aliyuncs.com/agent/jobs/337612/fc6c0cc25d8847c8acb226c097557ed7/outputs.zip'
216219
valid_zip = 'https://bohrium-agent-test.oss-cn-zhangjiakou.aliyuncs.com/agent/jobs/110680/c15113bb106b46f1a49800e776a2b8fc/outputs.zip'
217-
asyncio.run(extract_convert_and_upload(invalid_zip, './tmp'))
220+
failed_zip = 'https://bohrium-agents.oss-cn-zhangjiakou.aliyuncs.com/agent/jobs/337612/263edcfa12a2460abd222f6deeb19969/outputs.zip'
221+
asyncio.run(extract_convert_and_upload(failed_zip, './tmp'))

scripts/sandbox_cli.py

Lines changed: 13 additions & 8 deletions
Original file line numberDiff line numberDiff line change
@@ -1,10 +1,12 @@
11
import argparse
2+
import asyncio
23
import json
34
import os
45
import sys
56
import time
67
from datetime import datetime
78

9+
import aiohttp
810
import jsonpickle
911
import requests
1012
from dotenv import find_dotenv, load_dotenv
@@ -100,7 +102,7 @@ def poll_job_status(job_id, interval=10):
100102
time.sleep(interval)
101103

102104

103-
def main():
105+
async def main():
104106
parser = argparse.ArgumentParser(description='Sandbox job cli')
105107
subparsers = parser.add_subparsers(
106108
dest='command', help='Available commands', required=True
@@ -138,7 +140,7 @@ def main():
138140
)
139141

140142
args = parser.parse_args()
141-
143+
access_key = os.getenv('MATERIALS_ACCESS_KEY')
142144
# 调用API获取job信息
143145
logger.info(f"Job ID: {args.job_id}")
144146

@@ -150,7 +152,7 @@ def main():
150152

151153
try:
152154
response = requests.get(
153-
f"{OpenAPIJobAPI}/{args.job_id}?accessKey={os.getenv('BOHRIUM_ACCESS_KEY')}"
155+
f"{OpenAPIJobAPI}/{args.job_id}?accessKey={access_key}"
154156
)
155157
response.raise_for_status()
156158
job_info = response.json()
@@ -181,23 +183,26 @@ def main():
181183
logger.info(f"{job_name}[{job_status}] -- {duration}")
182184

183185
# download log
184-
get_token_and_download_file('log', args.job_id)
186+
await get_token_and_download_file('log', args.job_id, access_key)
185187

186188
if job_status in ['Running']:
187189
return
188190
elif job_status == 'Finished':
189191
# download result.txt
190192
results_txt = 'results.txt'
191-
get_token_and_download_file(results_txt, args.job_id)
193+
await get_token_and_download_file(results_txt, args.job_id, access_key)
192194
with open(results_txt) as f:
193195
logger.info(jsonpickle.loads(f.read()))
194196
os.remove(results_txt)
195197

196198
if args.download_output:
197199
# 下载结果文件
198200
if result_url and result_url != 'null':
199-
result_response = requests.get(result_url, stream=True)
200-
check_status_and_download_file(result_response, args.output)
201+
async with aiohttp.ClientSession() as session:
202+
async with session.get(result_url) as result_response:
203+
await check_status_and_download_file(
204+
result_response, args.output
205+
)
201206
else:
202207
logger.error('No resultUrl found or resultUrl is empty')
203208
elif args.command == 'kill':
@@ -207,4 +212,4 @@ def main():
207212

208213

209214
if __name__ == '__main__':
210-
main()
215+
asyncio.run(main())

0 commit comments

Comments
 (0)