Skip to content

Commit 32ae740

Browse files
authored
Merge pull request #175 from AnguseZhang/dev/zhouh
refactor: replace params_check_completed_agent with dynamic prompt in…
2 parents 8607ad4 + aac138a commit 32ae740

4 files changed

Lines changed: 29 additions & 25 deletions

File tree

agents/matmaster_agent/base_agents/job_agent.py

Lines changed: 11 additions & 21 deletions
Original file line numberDiff line numberDiff line change
@@ -4,12 +4,11 @@
44
from typing import AsyncGenerator, override, Optional
55

66
import jsonpickle
7+
import litellm
78
from google.adk.agents import LlmAgent, SequentialAgent
89
from google.adk.agents.invocation_context import InvocationContext
910
from google.adk.events import Event, EventActions
10-
from mcp.types import CallToolResult
1111
from pydantic import Field, BaseModel
12-
from yaml.scanner import ScannerError
1312

1413
from agents.matmaster_agent.base_agents.callback import check_before_tool_callback_effect, default_before_tool_callback, \
1514
catch_before_tool_callback_error, check_job_create, inject_username_ticket, inject_ak_projectId, \
@@ -33,7 +32,6 @@
3332
get_BohriumStorage,
3433
get_DFlowExecutor, OpenAPIJobAPI,
3534
)
36-
from agents.matmaster_agent.llm_config import MatMasterLlmConfig
3735
from agents.matmaster_agent.model import BohrJobInfo, DFlowJobInfo
3836
from agents.matmaster_agent.prompt import (
3937
ResultCoreAgentDescription,
@@ -43,7 +41,7 @@
4341
)
4442
from agents.matmaster_agent.utils.event_utils import is_function_call, is_function_response, send_error_event, is_text, \
4543
context_function_event, all_text_event, context_text_event, frontend_text_event, is_text_and_not_bohrium, \
46-
get_function_call_indexes, context_multipart2function_event
44+
get_function_call_indexes, context_multipart2function_event, cherry_pick_events
4745
from agents.matmaster_agent.utils.frontend import get_frontend_job_result_data
4846
from agents.matmaster_agent.utils.helper_func import update_session_state, parse_result, get_session_state, \
4947
load_tool_response
@@ -528,7 +526,6 @@ async def _run_async_impl(self, ctx: InvocationContext) -> AsyncGenerator[Event,
528526
class BaseAsyncJobAgent(LlmAgent):
529527
submit_agent: SequentialAgent
530528
result_agent: SequentialAgent
531-
params_check_completed_agent: LlmAgent
532529
params_check_info_agent: LlmAgent
533530
dflow_flag: bool = Field(False, description='Whether the agent is dflow related', exclude=True)
534531
supervisor_agent: str
@@ -594,16 +591,6 @@ def __init__(
594591
sub_agents=[result_core_agent]
595592
)
596593

597-
params_check_completed_agent = ParamsCheckCompletedAgent(
598-
model=MatMasterLlmConfig.gpt_4o,
599-
# model=model,
600-
name=f"{agent_prefix}_params_check_completed_agent",
601-
instruction=gen_params_check_completed_agent_instruction(),
602-
output_schema=ParamsCheckComplete,
603-
disallow_transfer_to_parent=True,
604-
disallow_transfer_to_peers=True
605-
)
606-
607594
params_check_info_agent = ParamsCheckInfoAgent(
608595
model=model,
609596
name=f"{agent_prefix}_params_check_info_agent",
@@ -621,10 +608,9 @@ def __init__(
621608
description=agent_description,
622609
submit_agent=submit_agent,
623610
result_agent=result_agent,
624-
params_check_completed_agent=params_check_completed_agent,
625611
params_check_info_agent=params_check_info_agent,
626612
dflow_flag=dflow_flag,
627-
sub_agents=[submit_agent, result_agent, params_check_completed_agent, params_check_info_agent],
613+
sub_agents=[submit_agent, result_agent, params_check_info_agent],
628614
supervisor_agent=supervisor_agent,
629615
sync_tools=sync_tools,
630616
enable_tgz_unpack=enable_tgz_unpack
@@ -651,10 +637,14 @@ async def _run_async_impl(self, ctx: InvocationContext) -> AsyncGenerator[Event,
651637
): # Only Query Job Result
652638
pass
653639
else:
654-
last_params_check_completed_event = None
655-
async for params_check_completed_event in self.params_check_completed_agent.run_async(ctx):
656-
last_params_check_completed_event = params_check_completed_event
657-
params_check_completed_json = json.loads(last_params_check_completed_event.content.parts[0].text)
640+
cherry_pick_parts = cherry_pick_events(ctx)[:5]
641+
context_messages = '\n'.join([f'<{item[0].title()}> said: \n{item[1]}\n' for item in cherry_pick_parts])
642+
logger.info(f"[BaseAsyncJobAgent] context_messages = {context_messages}")
643+
644+
prompt = gen_params_check_completed_agent_instruction().format(context_messages=context_messages)
645+
response = litellm.completion(model='azure/gpt-4o', messages=[{'role': 'user', 'content': prompt}],
646+
response_format=ParamsCheckComplete)
647+
params_check_completed_json: dict = json.loads(response.choices[0].message.content)
658648
params_check_completed = params_check_completed_json['flag']
659649
params_check_reason = params_check_completed_json['reason']
660650
params_check_msg = params_check_completed_json['analyzed_message']

agents/matmaster_agent/main.py

Lines changed: 2 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -64,11 +64,11 @@ async def agent_main() -> None:
6464
# user_input = "高熵合金AlCoCr0.5FeNi2的可能结构是什么"
6565
# user_input = "调用 thermoelectric_agent 帮我生成10个具有Sn和Te元素的热电结构"
6666
# user_input = "plot perovstite 2021 to 2025"
67-
# user_input = "帮我创建一个 FCC Bulk Cu 的结构"
67+
user_input = '帮我创建一个 FCC Bulk Cu 的结构'
6868
# 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"
6969
# user_input = "帮我检索TiO2"
7070
# user_input = "请你为我搭建一个氯化钠的结构"
71-
user_input = '我想要一个bandgap 小于0.5ev的结构,空间群225,生成数量1'
71+
# user_input = '我想要一个bandgap 小于0.5ev的结构,空间群225,生成数量1'
7272
# user_input = '用openlam查找一个TiO2'
7373
print(f"🧑 用户:{user_input}")
7474

agents/matmaster_agent/prompt.py

Lines changed: 3 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -653,8 +653,10 @@ def gen_result_agent_description():
653653

654654
def gen_params_check_completed_agent_instruction():
655655
return """
656-
Analyze the most recent message where the 'author' field ends with '_agent' and which contains parameter information. This message may not be the immediate preceding one.
657656
Your task is to determine if the parameters requiring user confirmation have been fully presented and a confirmation is being requested in that message.
657+
Analyze the messages from `user` and `model` listed below (only listed Latest 5 messages):
658+
659+
{context_messages}
658660
659661
Your output MUST be a valid JSON object with the following structure:
660662
{{

agents/matmaster_agent/utils/event_utils.py

Lines changed: 13 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -150,7 +150,7 @@ def context_multipart2function_event(ctx: InvocationContext, author: str, event:
150150
for part in event.content.parts:
151151
if part.text:
152152
yield from context_function_event(ctx, author, function_call_name, {'msg': part.text},
153-
ModelRole)
153+
ModelRole)
154154
elif part.function_call:
155155
yield context_function_call_event(ctx, author, function_call_id=part.function_call.id,
156156
function_call_name=part.function_call.name, role=ModelRole,
@@ -163,6 +163,18 @@ def all_text_event(ctx: InvocationContext, author: str, text: str, role: str):
163163
yield context_text_event(ctx, author, text, role)
164164

165165

166+
def cherry_pick_events(ctx: InvocationContext):
167+
events = ctx.session.events
168+
cherry_pick_parts = []
169+
for event in events:
170+
if event.content:
171+
for part in event.content.parts:
172+
if part.text:
173+
cherry_pick_parts.append((event.content.role, part.text))
174+
175+
return cherry_pick_parts
176+
177+
166178
async def send_error_event(err, ctx: InvocationContext, author):
167179
ctx.session.state['error_occurred'] = True
168180
await update_session_state(ctx, author)

0 commit comments

Comments
 (0)