Skip to content

Commit b2e9b0f

Browse files
authored
Merge pull request #195 from AnguseZhang/feat/acs-infra
refactor: update API configuration and constants for improved compatibility
2 parents 7bcd8b5 + 9e5a71d commit b2e9b0f

8 files changed

Lines changed: 67 additions & 154 deletions

File tree

agents/matmaster_agent/base_agents/callback.py

Lines changed: 9 additions & 102 deletions
Original file line numberDiff line numberDiff line change
@@ -20,6 +20,8 @@
2020
CURRENT_ENV,
2121
FRONTEND_STATE_KEY,
2222
LOCAL_EXECUTOR,
23+
MATERIALS_ACCESS_KEY,
24+
MATERIALS_PROJECT_ID,
2325
OPENAPI_HOST,
2426
Transfer2Agent,
2527
)
@@ -178,14 +180,6 @@ def _get_projectId(ctx: Union[InvocationContext, ToolContext]):
178180
)
179181

180182

181-
@check_None_wrapper
182-
def _get_machineType(ctx: Union[InvocationContext, ToolContext]):
183-
session_state = get_session_state(ctx)
184-
return session_state[FRONTEND_STATE_KEY]['biz'].get('machineType') or os.getenv(
185-
'MACHINE_TYPE', 'c32_m64_cpu'
186-
)
187-
188-
189183
def _inject_ak(ctx: Union[InvocationContext, ToolContext], executor, storage):
190184
access_key = _get_ak(ctx)
191185
if executor is not None:
@@ -219,8 +213,7 @@ def _inject_projectId(ctx: Union[InvocationContext, ToolContext], executor, stor
219213

220214

221215
def _inject_username(ctx: Union[InvocationContext, ToolContext], executor):
222-
access_key = _get_ak(ctx)
223-
username = ak_to_username(access_key=access_key)
216+
username = ak_to_username(access_key=MATERIALS_ACCESS_KEY)
224217
if username:
225218
if executor is not None:
226219
if executor['type'] == 'dispatcher': # BohriumExecutor
@@ -238,8 +231,7 @@ def _inject_username(ctx: Union[InvocationContext, ToolContext], executor):
238231

239232

240233
def _inject_ticket(ctx: Union[InvocationContext, ToolContext], executor):
241-
access_key = _get_ak(ctx)
242-
ticket = ak_to_ticket(access_key=access_key)
234+
ticket = ak_to_ticket(access_key=MATERIALS_ACCESS_KEY)
243235
if ticket:
244236
if executor is not None:
245237
if executor['type'] == 'dispatcher': # BohriumExecutor
@@ -270,65 +262,6 @@ def _inject_current_env(executor):
270262
return executor
271263

272264

273-
def _inject_machine_type(ctx: Union[InvocationContext, ToolContext], executor):
274-
machine_type = _get_machineType(ctx)
275-
session_state = get_session_state(ctx)
276-
logger.info(
277-
f"biz = {session_state[FRONTEND_STATE_KEY]['biz']}; "
278-
f"machineType = {machine_type}"
279-
)
280-
if executor is not None:
281-
if executor['type'] == 'dispatcher': # BohriumExecutor
282-
current_machine_type = executor['machine']['remote_profile']['machine_type']
283-
if not current_machine_type:
284-
executor['machine']['remote_profile']['machine_type'] = str(
285-
machine_type
286-
)
287-
logger.info(f"After inject_machine_type, executor = {executor}")
288-
289-
return executor
290-
291-
292-
def inject_ak_projectId(func: BeforeToolCallback) -> BeforeToolCallback:
293-
@wraps(func)
294-
async def wrapper(
295-
tool: BaseTool, args: dict, tool_context: ToolContext
296-
) -> Optional[dict]:
297-
# 两步操作:
298-
# 1. 调用被装饰的 before_tool_callback;
299-
# 2. 如果调用的 before_tool_callback 有返回值,以这个为准
300-
if (before_tool_result := await func(tool, args, tool_context)) is not None:
301-
return before_tool_result
302-
303-
# 如果 tool 为 Transfer2Agent,不做 ak 和 project_id 设置/校验
304-
if tool.name == Transfer2Agent:
305-
return None
306-
307-
# 如果 tool 不是 CalculationMCPTool,不应该调用这个 callback
308-
if not isinstance(tool, CalculationMCPTool):
309-
raise TypeError(
310-
'Not CalculationMCPTool type, current tool does not have <storage>'
311-
)
312-
313-
# 获取 access_key
314-
access_key, tool.executor, tool.storage = _inject_ak(
315-
tool_context, tool.executor, tool.storage
316-
)
317-
318-
# 获取 project_id
319-
try:
320-
project_id, tool.executor, tool.storage = _inject_projectId(
321-
tool_context, tool.executor, tool.storage
322-
)
323-
except ValueError as e:
324-
raise ValueError('ProjectId is invalid') from e
325-
326-
tool_context.state['ak'] = access_key
327-
tool_context.state['project_id'] = project_id
328-
329-
return wrapper
330-
331-
332265
def inject_username_ticket(func: BeforeToolCallback) -> BeforeToolCallback:
333266
@wraps(func)
334267
async def wrapper(
@@ -383,14 +316,14 @@ async def wrapper(
383316
job_create_url = f"{OPENAPI_HOST}/openapi/v1/job/create"
384317
user_project_list_url = f"{OPENAPI_HOST}/openapi/v1/open/user/project/list"
385318
payload = {
386-
'projectId': int(tool_context.state['project_id']),
319+
'projectId': MATERIALS_PROJECT_ID,
387320
'name': 'check_job_create',
388321
}
389-
params = {'accessKey': tool_context.state['ak']}
322+
params = {'accessKey': MATERIALS_ACCESS_KEY}
390323

391324
logger.info(
392-
f"[check_job_create] project_id = {tool_context.state['project_id']}, "
393-
f"ak = {tool_context.state['ak']}"
325+
f"[check_job_create] project_id = {MATERIALS_PROJECT_ID}, "
326+
f"ak = {MATERIALS_ACCESS_KEY}"
394327
)
395328

396329
async with aiohttp.ClientSession() as session:
@@ -402,7 +335,7 @@ async def wrapper(
402335
project_name = [
403336
item['project_name']
404337
for item in res['data']['items']
405-
if item['project_id'] == int(tool_context.state['project_id'])
338+
if item['project_id'] == MATERIALS_PROJECT_ID
406339
][0]
407340

408341
async with aiohttp.ClientSession() as session:
@@ -420,32 +353,6 @@ async def wrapper(
420353
return wrapper
421354

422355

423-
def inject_machineType(func: BeforeToolCallback) -> BeforeToolCallback:
424-
@wraps(func)
425-
async def wrapper(
426-
tool: BaseTool, args: dict, tool_context: ToolContext
427-
) -> Optional[dict]:
428-
# 两步操作:
429-
# 1. 调用被装饰的 before_tool_callback;
430-
# 2. 如果调用的 before_tool_callback 有返回值,以这个为准
431-
if (before_tool_result := await func(tool, args, tool_context)) is not None:
432-
return before_tool_result
433-
434-
# 如果 tool 为 Transfer2Agent,不做 ak 和 project_id 设置/校验
435-
if tool.name == Transfer2Agent:
436-
return None
437-
438-
# 如果 tool 不是 CalculationMCPTool,不应该调用这个 callback
439-
if not isinstance(tool, CalculationMCPTool):
440-
raise TypeError(
441-
'Not CalculationMCPTool type, current tool does not have <storage>'
442-
)
443-
444-
_inject_machine_type(tool_context, tool.executor)
445-
446-
return wrapper
447-
448-
449356
# 总应该在最后
450357
def catch_before_tool_callback_error(func: BeforeToolCallback) -> BeforeToolCallback:
451358
@wraps(func)

agents/matmaster_agent/base_agents/job_agent.py

Lines changed: 18 additions & 14 deletions
Original file line numberDiff line numberDiff line change
@@ -20,9 +20,7 @@
2020
default_after_model_callback,
2121
default_after_tool_callback,
2222
default_before_tool_callback,
23-
inject_ak_projectId,
2423
inject_current_env,
25-
inject_machineType,
2624
inject_username_ticket,
2725
remove_function_call,
2826
tgz_oss_to_oss_list,
@@ -37,6 +35,8 @@
3735
LOADING_START,
3836
LOADING_STATE_KEY,
3937
LOADING_TITLE,
38+
MATERIALS_ACCESS_KEY,
39+
MATERIALS_PROJECT_ID,
4040
TMP_FRONTEND_STATE_KEY,
4141
ModelRole,
4242
OpenAPIJobAPI,
@@ -160,14 +160,8 @@ def __init__(
160160

161161
# Todo: support List[before_tool_callback]
162162
before_tool_callback = catch_before_tool_callback_error(
163-
inject_machineType(
164-
check_job_create(
165-
inject_current_env(
166-
inject_username_ticket(
167-
inject_ak_projectId(before_tool_callback)
168-
)
169-
)
170-
)
163+
check_job_create(
164+
inject_current_env(inject_username_ticket(before_tool_callback))
171165
)
172166
)
173167
after_tool_callback = check_before_tool_callback_effect(
@@ -410,6 +404,9 @@ async def _run_async_impl(
410404
):
411405
raw_result = part.function_response.response['result']
412406
results = json.loads(raw_result.content[0].text)
407+
logger.info(
408+
f"[SubmitCoreCalculationMCPLlmAgent] results = {results}"
409+
)
413410
origin_job_id = results['job_id']
414411
job_name = part.function_response.name
415412
job_status = results['status']
@@ -554,11 +551,15 @@ async def _run_async_impl(
554551
try:
555552
await self.tools[0].get_tools()
556553
if not ctx.session.state['dflow']:
557-
access_key, Executor, BohriumStorge = _inject_ak(
558-
ctx, get_BohriumExecutor(), get_BohriumStorage()
554+
access_key, Executor, BohriumStorge = (
555+
MATERIALS_ACCESS_KEY,
556+
get_BohriumExecutor(),
557+
get_BohriumStorage(),
559558
)
560-
project_id, Executor, BohriumStorge = _inject_projectId(
561-
ctx, Executor, BohriumStorge
559+
project_id, Executor, BohriumStorge = (
560+
MATERIALS_PROJECT_ID,
561+
Executor,
562+
BohriumStorge,
562563
)
563564
else:
564565
access_key, Executor, BohriumStorge = _inject_ak(
@@ -850,6 +851,9 @@ async def _run_async_impl(
850851
params_check_completed_json: dict = json.loads(
851852
response.choices[0].message.content
852853
)
854+
logger.info(
855+
f"[BaseAsyncJobAgent] params_check_completed_json = {params_check_completed_json}"
856+
)
853857
params_check_completed = params_check_completed_json['flag']
854858
params_check_reason = params_check_completed_json['reason']
855859
params_check_msg = params_check_completed_json['analyzed_messages']

agents/matmaster_agent/callback.py

Lines changed: 2 additions & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -11,8 +11,7 @@
1111
from google.genai import types
1212
from google.genai.types import FunctionCall, Part
1313

14-
from agents.matmaster_agent.base_agents.callback import _get_ak
15-
from agents.matmaster_agent.constant import FRONTEND_STATE_KEY
14+
from agents.matmaster_agent.constant import FRONTEND_STATE_KEY, MATERIALS_ACCESS_KEY
1615
from agents.matmaster_agent.locales import i18n
1716
from agents.matmaster_agent.model import UserContent
1817
from agents.matmaster_agent.prompt import get_user_content_lang
@@ -114,7 +113,6 @@ async def matmaster_check_job_status(
114113
jobs_dict
115114
): # 确认当前有在运行中的任务
116115
running_job_ids = get_running_jobs_detail(jobs_dict) # 从 state 里面拿
117-
access_key = _get_ak(callback_context) # 从 state 或环境变量里面拿
118116
if callback_context.state['target_language'] in [
119117
'Chinese',
120118
'zh-CN',
@@ -132,7 +130,7 @@ async def matmaster_check_job_status(
132130
'[matmaster_check_job_status] new LlmResponse, prepare call API'
133131
)
134132
job_status = await get_job_status(
135-
job_query_url, access_key=access_key
133+
job_query_url, access_key=MATERIALS_ACCESS_KEY
136134
) # 查询任务的最新状态
137135
callback_context.state['new_query_job_status'][
138136
'origin_job_id'

agents/matmaster_agent/constant.py

Lines changed: 34 additions & 30 deletions
Original file line numberDiff line numberDiff line change
@@ -16,13 +16,38 @@
1616
# DB
1717
DBUrl = os.getenv('SESSION_API_URL')
1818

19+
OPENAPI_HOST = ''
20+
DFLOW_HOST = ''
21+
DFLOW_K8S_API_SERVER = ''
22+
BOHRIUM_API_URL = ''
23+
24+
CURRENT_ENV = os.getenv('OPIK_PROJECT_NAME', 'prod')
25+
if CURRENT_ENV == 'test':
26+
OPENAPI_HOST = 'https://openapi.test.dp.tech'
27+
DFLOW_HOST = 'https://lbg-workflow-mlops.test.dp.tech'
28+
DFLOW_K8S_API_SERVER = 'https://lbg-workflow-mlops.test.dp.tech'
29+
BOHRIUM_API_URL = 'https://bohrium-api.test.dp.tech'
30+
elif CURRENT_ENV == 'uat':
31+
OPENAPI_HOST = 'https://openapi.uat.dp.tech'
32+
BOHRIUM_API_URL = 'https://bohrium-api.uat.dp.tech'
33+
elif CURRENT_ENV == 'prod':
34+
OPENAPI_HOST = 'https://openapi.dp.tech'
35+
DFLOW_HOST = 'https://workflows.deepmodeling.com'
36+
DFLOW_K8S_API_SERVER = 'https://workflows.deepmodeling.com'
37+
BOHRIUM_API_URL = 'https://bohrium-api.dp.tech'
38+
39+
OpenAPIJobAPI = f"{OPENAPI_HOST}/openapi/v1/sandbox/job"
40+
41+
MATERIALS_ACCESS_KEY = str(os.getenv('MATERIALS_ACCESS_KEY'))
42+
MATERIALS_PROJECT_ID = int(os.getenv('MATERIALS_PROJECT_ID'))
43+
1944
# Bohrium Constant
2045
BohriumStorge = {
2146
'type': 'https',
2247
'plugin': {
2348
'type': 'bohrium',
24-
'access_key': '',
25-
'project_id': -1,
49+
'access_key': MATERIALS_ACCESS_KEY,
50+
'project_id': MATERIALS_PROJECT_ID,
2651
'app_key': 'agent',
2752
},
2853
}
@@ -34,38 +59,17 @@
3459
'batch_type': 'OpenAPI',
3560
'context_type': 'OpenAPI',
3661
'remote_profile': {
37-
'access_key': '',
38-
'project_id': -1,
62+
'access_key': MATERIALS_ACCESS_KEY,
63+
'project_id': MATERIALS_PROJECT_ID,
3964
'app_key': 'agent',
40-
'image_address': 'registry.dp.tech/dptech/dp/native/prod-19853/dpa-mcp:0.0.0',
65+
'image_address': '',
4166
'platform': 'ali',
42-
'machine_type': '',
67+
'machine_type': 'c2_m8_cpu',
4368
},
4469
},
45-
'resources': {'envs': {}},
70+
'resources': {'envs': {'BOHRIUM_PROJECT_ID': MATERIALS_PROJECT_ID}},
4671
}
4772

48-
OPENAPI_HOST = ''
49-
DFLOW_HOST = ''
50-
DFLOW_K8S_API_SERVER = ''
51-
BOHRIUM_API_URL = ''
52-
53-
CURRENT_ENV = os.getenv('OPIK_PROJECT_NAME', 'prod')
54-
if CURRENT_ENV == 'test':
55-
OPENAPI_HOST = 'https://openapi.test.dp.tech'
56-
DFLOW_HOST = 'https://lbg-workflow-mlops.test.dp.tech'
57-
DFLOW_K8S_API_SERVER = 'https://lbg-workflow-mlops.test.dp.tech'
58-
BOHRIUM_API_URL = 'https://bohrium-api.test.dp.tech'
59-
elif CURRENT_ENV == 'uat':
60-
OPENAPI_HOST = 'https://openapi.uat.dp.tech'
61-
BOHRIUM_API_URL = 'https://bohrium-api.uat.dp.tech'
62-
elif CURRENT_ENV == 'prod':
63-
OPENAPI_HOST = 'https://openapi.dp.tech'
64-
DFLOW_HOST = 'https://workflows.deepmodeling.com'
65-
DFLOW_K8S_API_SERVER = 'https://workflows.deepmodeling.com'
66-
BOHRIUM_API_URL = 'https://bohrium-api.dp.tech'
67-
OpenAPIJobAPI = f"{OPENAPI_HOST}/openapi/v1/job"
68-
6973
DFlowExecutor = {
7074
'type': 'local',
7175
'dflow': True,
@@ -74,8 +78,8 @@
7478
'DFLOW_K8S_API_SERVER': DFLOW_K8S_API_SERVER,
7579
'DFLOW_S3_REPO_KEY': 'oss-bohrium',
7680
'DFLOW_S3_STORAGE_CLIENT': 'dflow.plugins.bohrium.TiefblueClient',
77-
'BOHRIUM_ACCESS_KEY': '',
78-
'BOHRIUM_PROJECT_ID': '',
81+
'BOHRIUM_ACCESS_KEY': MATERIALS_ACCESS_KEY,
82+
'BOHRIUM_PROJECT_ID': str(MATERIALS_PROJECT_ID),
7983
'BOHRIUM_APP_KEY': 'agent',
8084
},
8185
}

agents/matmaster_agent/model.py

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -51,7 +51,7 @@ class JobResult(BaseModel):
5151

5252
class BohrJobInfo(BaseModel):
5353
origin_job_id: str
54-
job_id: int
54+
job_id: Union[int, str]
5555
job_query_url: str
5656
job_detail_url: str
5757
job_status: JobStatus

agents/matmaster_agent/prompt.py

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -684,7 +684,7 @@ def gen_params_check_completed_agent_instruction():
684684
{{
685685
"flag": <boolean>,
686686
"reason": <string>, // *A concise explanation of the reasoning behind the judgment, covering both positive and negative evidence found in the context messages. Return empty string only if there is absolutely no relevant content to analyze.*
687-
"analyzed_message": List[<string>] // *Quote the key messages that were analyzed to make this determination.*
687+
"analyzed_messages": List[<string>] // *Quote the key messages that were analyzed to make this determination.*
688688
}}
689689
690690
Return `flag: true` ONLY IF ALL of the following conditions are met:

agents/matmaster_agent/structure_generate_agent/agent.py

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -26,7 +26,7 @@
2626
] = 'registry.dp.tech/dptech/dp/native/prod-788025/structure-generate-agent:small'
2727
StructureGenerateBohriumExecutor['machine']['remote_profile'][
2828
'machine_type'
29-
] = 'c8_m31_1 * NVIDIA T4'
29+
] = 'c8_m32_1 * NVIDIA 4090'
3030

3131
sse_params = SseServerParams(url=StructureGenerateServerUrl)
3232

0 commit comments

Comments
 (0)