Skip to content

Commit 3ec6cab

Browse files
committed
refactor:重构流程来简化状态更新和工具调用逻辑
1 parent b8c264b commit 3ec6cab

6 files changed

Lines changed: 79 additions & 84 deletions

File tree

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

Lines changed: 1 addition & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -25,7 +25,6 @@
2525
SubmitRenderAgent,
2626
)
2727
from agents.matmaster_agent.flow_agents.model import PlanStepStatusEnum
28-
from agents.matmaster_agent.locales import i18n
2928
from agents.matmaster_agent.logger import PrefixFilter
3029
from agents.matmaster_agent.state import CURRENT_STEP
3130
from agents.matmaster_agent.utils.event_utils import (
@@ -143,7 +142,7 @@ async def _run_events(self, ctx: InvocationContext) -> AsyncGenerator[Event, Non
143142
# Only Query Job Result
144143
step_title = ctx.session.state.get('step_title', {}).get(
145144
'title',
146-
f"{i18n.t(ctx.session.state['separate_card_info'])} {ctx.session.state['plan_index'] + 1}: {current_step_tool_name}",
145+
current_step_tool_name,
147146
)
148147
for matmaster_flow_event in context_function_event(
149148
ctx,

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

Lines changed: 5 additions & 9 deletions
Original file line numberDiff line numberDiff line change
@@ -25,12 +25,14 @@
2525
from agents.matmaster_agent.core_agents.public_agents.job_agents.result_core_agent.prompt import (
2626
ResultCoreAgentDescription,
2727
)
28+
from agents.matmaster_agent.flow_agents.step_utils import get_current_step
2829
from agents.matmaster_agent.logger import PrefixFilter
2930
from agents.matmaster_agent.services.job import (
3031
get_job_detail,
3132
parse_and_prepare_err,
3233
parse_and_prepare_results,
3334
)
35+
from agents.matmaster_agent.state import CURRENT_STEP, CURRENT_STEP_STATUS
3436
from agents.matmaster_agent.utils.event_utils import (
3537
all_text_event,
3638
context_function_event,
@@ -115,14 +117,8 @@ async def _run_events(self, ctx: InvocationContext) -> AsyncGenerator[Event, Non
115117
if status != 'Running':
116118
# 更新状态
117119
plan_status = 'success' if status == 'Finished' else 'failed'
118-
update_plan = copy.deepcopy(ctx.session.state['plan'])
119-
logger.info(
120-
f'{ctx.session.id} plan_index = {ctx.session.state['plan_index']}'
121-
)
122-
update_plan['steps'][ctx.session.state['plan_index']][
123-
'status'
124-
] = plan_status
125-
120+
post_execution_step = copy.deepcopy(get_current_step(ctx))
121+
post_execution_step[CURRENT_STEP_STATUS] = plan_status
126122
update_long_running_jobs = copy.deepcopy(
127123
ctx.session.state['long_running_jobs']
128124
)
@@ -131,7 +127,7 @@ async def _run_events(self, ctx: InvocationContext) -> AsyncGenerator[Event, Non
131127
ctx,
132128
state_delta={
133129
'long_running_jobs': update_long_running_jobs,
134-
'plan': update_plan,
130+
CURRENT_STEP: post_execution_step,
135131
},
136132
)
137133

agents/matmaster_agent/flow_agents/agent.py

Lines changed: 52 additions & 64 deletions
Original file line numberDiff line numberDiff line change
@@ -86,14 +86,17 @@
8686
from agents.matmaster_agent.flow_agents.scene_agent.constant import SCENE_AGENT
8787
from agents.matmaster_agent.flow_agents.scene_agent.prompt import SCENE_INSTRUCTION
8888
from agents.matmaster_agent.flow_agents.scene_agent.schema import SceneSchema
89-
from agents.matmaster_agent.flow_agents.schema import FlowStatusEnum
9089
from agents.matmaster_agent.flow_agents.step_title_agent.callback import (
9190
filter_llm_contents,
9291
)
9392
from agents.matmaster_agent.flow_agents.step_title_agent.prompt import (
9493
STEP_TITLE_INSTRUCTION,
9594
)
9695
from agents.matmaster_agent.flow_agents.step_title_agent.schema import StepTitleSchema
96+
from agents.matmaster_agent.flow_agents.step_utils import (
97+
get_current_step,
98+
is_job_submitted_step,
99+
)
97100
from agents.matmaster_agent.flow_agents.step_validation_agent.prompt import (
98101
STEP_VALIDATION_INSTRUCTION,
99102
)
@@ -103,9 +106,7 @@
103106
from agents.matmaster_agent.flow_agents.thinking_agent.agent import ThinkingAgent
104107
from agents.matmaster_agent.flow_agents.thinking_agent.constant import THINKING_AGENT
105108
from agents.matmaster_agent.flow_agents.utils import (
106-
check_plan,
107109
get_tools_list,
108-
is_plan_confirmed,
109110
scenes_contain_query_job_status,
110111
should_bypass_confirmation,
111112
)
@@ -345,28 +346,20 @@ def _build_execution_agent_for_plan(
345346
before_model_callback=filter_llm_contents,
346347
after_model_callback=MatMasterLlmConfig.opik_tracer.after_model_callback,
347348
)
348-
plan_steps = ctx.session.state.get('plan', {}).get('steps', [])
349-
agent_names = []
350-
for step in plan_steps:
351-
tool_name = step.get('tool_name')
352-
if not tool_name:
353-
continue
354-
belonging_agent = ALL_TOOLS.get(tool_name, {}).get('belonging_agent')
355-
if belonging_agent and belonging_agent not in agent_names:
356-
agent_names.append(belonging_agent)
357-
358-
sub_agents = [
359-
AGENT_CLASS_MAPPING[agent_name](MatMasterLlmConfig)
360-
for agent_name in agent_names
361-
if agent_name in AGENT_CLASS_MAPPING
362-
]
349+
current_step = get_current_step(ctx)
350+
tool_name = current_step.get('tool_name')
351+
belonging_agent = ALL_TOOLS.get(tool_name, {}).get('belonging_agent')
363352

364353
execution_agent = MatMasterSupervisorAgent(
365354
name='execution_agent',
366355
model=MatMasterLlmConfig.default_litellm_model,
367356
description='根据 materials_plan 返回的计划进行总结',
368357
instruction='',
369-
sub_agents=sub_agents + [step_title_agent] + [step_validation_agent],
358+
sub_agents=[
359+
AGENT_CLASS_MAPPING[belonging_agent](MatMasterLlmConfig),
360+
step_title_agent,
361+
step_validation_agent,
362+
],
370363
)
371364
track_adk_agent_recursive(execution_agent, MatMasterLlmConfig.opik_tracer)
372365
return execution_agent
@@ -711,8 +704,6 @@ async def _run_step_make_agent(
711704
async def _run_plan_execute_agent(
712705
self, ctx: InvocationContext
713706
) -> AsyncGenerator[Event, None]:
714-
# 重置 scenes
715-
yield update_state_event(ctx, state_delta={'scenes': []})
716707
# 执行计划
717708
self._execution_agent = self._build_execution_agent_for_plan(ctx)
718709
if self._execution_agent:
@@ -841,26 +832,6 @@ async def _run_summary_agent(
841832
yield matmaster_flow_event
842833
yield update_state_event(ctx, state_delta={'matmaster_flow_active': None})
843834

844-
# 渲染追问组件
845-
follow_up_list = await get_random_questions(i18n=i18n)
846-
for generate_follow_up_event in context_function_event(
847-
ctx,
848-
self.name,
849-
'matmaster_generate_follow_up',
850-
{},
851-
ModelRole,
852-
{
853-
'follow_up_result': json.dumps(
854-
{
855-
'invocation_id': ctx.invocation_id,
856-
'title': i18n.t('MoreQuestions'),
857-
'list': follow_up_list,
858-
}
859-
)
860-
},
861-
):
862-
yield generate_follow_up_event
863-
864835
async def _run_research_flow(
865836
self, ctx: InvocationContext
866837
) -> AsyncGenerator[Event, None]:
@@ -891,14 +862,8 @@ async def _run_research_flow(
891862
yield _scene_event
892863

893864
while True:
894-
# 制定计划(1. 无计划;2. 计划已完成;3. 计划失败;4. 用户未确认计划)
895-
# 仅查询任务状态时跳过 thinking(查任务状态不 thinking)
896-
skip_thinking = scenes_contain_query_job_status(ctx)
897-
if check_plan(ctx) in [
898-
FlowStatusEnum.NO_PLAN,
899-
FlowStatusEnum.COMPLETE,
900-
FlowStatusEnum.FAILED,
901-
] or not is_plan_confirmed(ctx):
865+
if not is_job_submitted_step(ctx):
866+
skip_thinking = scenes_contain_query_job_status(ctx)
902867
async for _step_make_event in self._run_step_make_agent(
903868
ctx,
904869
UPDATE_USER_CONTENT,
@@ -907,27 +872,50 @@ async def _run_research_flow(
907872
):
908873
yield _step_make_event
909874

910-
# 计划未确认,暂停往下执行
911-
# if is_plan_confirmed(ctx):
912875
async for _plan_execute_event in self._run_plan_execute_agent(ctx):
913876
yield _plan_execute_event
914877

915-
# 回顾历史执行
916-
user_request = ctx.user_content.parts[0].text
917-
history_steps = ctx.session.state[HISTORY_STEPS]
918-
session_files = await get_session_files(ctx.session.id)
919-
self.all_finished_agent.instruction = create_all_finished_instruction(
920-
user_request, history_steps, session_files
921-
)
922-
async for _all_finished_event in self.all_finished_agent.run_async(ctx):
923-
yield _all_finished_event
878+
# 检查是否为等待异步任务执行完成的阶段
879+
if not is_job_submitted_step(ctx):
880+
# 回顾历史执行
881+
user_request = ctx.user_content.parts[0].text
882+
history_steps = ctx.session.state[HISTORY_STEPS]
883+
session_files = await get_session_files(ctx.session.id)
884+
self.all_finished_agent.instruction = create_all_finished_instruction(
885+
user_request, history_steps, session_files
886+
)
887+
async for _all_finished_event in self.all_finished_agent.run_async(ctx):
888+
yield _all_finished_event
924889

925-
if ctx.session.state[FINISHED_STATE]['finished']:
890+
if ctx.session.state[FINISHED_STATE]['finished']:
891+
break
892+
else:
926893
break
927894

928-
# 总结计划
929-
async for _plan_summary_event in self._run_summary_agent(ctx):
930-
yield _plan_summary_event
895+
if not is_job_submitted_step(ctx):
896+
# 总结计划
897+
async for _plan_summary_event in self._run_summary_agent(ctx):
898+
yield _plan_summary_event
899+
900+
# 渲染追问组件
901+
follow_up_list = await get_random_questions(i18n=i18n)
902+
for generate_follow_up_event in context_function_event(
903+
ctx,
904+
self.name,
905+
'matmaster_generate_follow_up',
906+
{},
907+
ModelRole,
908+
{
909+
'follow_up_result': json.dumps(
910+
{
911+
'invocation_id': ctx.invocation_id,
912+
'title': i18n.t('MoreQuestions'),
913+
'list': follow_up_list,
914+
}
915+
)
916+
},
917+
):
918+
yield generate_follow_up_event
931919

932920
async def _run_async_impl(
933921
self, ctx: InvocationContext

agents/matmaster_agent/flow_agents/execution_agent/agent.py

Lines changed: 6 additions & 9 deletions
Original file line numberDiff line numberDiff line change
@@ -17,6 +17,10 @@
1717
MATMASTER_SUPERVISOR_AGENT,
1818
)
1919
from agents.matmaster_agent.flow_agents.model import PlanStepStatusEnum
20+
from agents.matmaster_agent.flow_agents.step_utils import (
21+
get_current_step,
22+
is_job_submitted_step,
23+
)
2024
from agents.matmaster_agent.flow_agents.step_validation_agent.prompt import (
2125
STEP_VALIDATION_INSTRUCTION,
2226
)
@@ -303,14 +307,8 @@ async def _prepare_retry_other_tool(
303307

304308
@override
305309
async def _run_events(self, ctx: InvocationContext) -> AsyncGenerator[Event, None]:
306-
plan = ctx.session.state['plan']
307-
logger.info(f'{ctx.session.id} plan = {plan}')
308-
309-
current_step = ctx.session.state[CURRENT_STEP]
310-
current_step_status = current_step['status']
311-
312310
# 制造工具调用上下文,已提交的任务跳过该步骤
313-
if current_step_status != PlanStepStatusEnum.SUBMITTED:
311+
if not is_job_submitted_step(ctx):
314312
async for (
315313
_construct_function_call_event
316314
) in self._construct_function_call_ctx(ctx):
@@ -320,7 +318,7 @@ async def _run_events(self, ctx: InvocationContext) -> AsyncGenerator[Event, Non
320318
async for _core_execution_event in self._core_execution_agent(ctx):
321319
yield _core_execution_event
322320

323-
post_execution_step = ctx.session.state[CURRENT_STEP]
321+
post_execution_step = get_current_step(ctx)
324322
# 工具调用结果返回【成功】
325323
if post_execution_step['status'] == PlanStepStatusEnum.SUCCESS:
326324
# 对成功的工具调用结果进行校验
@@ -330,7 +328,6 @@ async def _run_events(self, ctx: InvocationContext) -> AsyncGenerator[Event, Non
330328
ctx
331329
):
332330
yield _tool_result_validation_event
333-
334331
# 异步任务,直接退出当前函数
335332
elif post_execution_step['status'] == PlanStepStatusEnum.SUBMITTED:
336333
return
Lines changed: 14 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,14 @@
1+
from google.adk.agents import InvocationContext
2+
3+
from agents.matmaster_agent.flow_agents.model import PlanStepStatusEnum
4+
from agents.matmaster_agent.state import CURRENT_STEP, CURRENT_STEP_STATUS
5+
6+
7+
def get_current_step(ctx: InvocationContext):
8+
return ctx.session.state.get(CURRENT_STEP, {})
9+
10+
11+
def is_job_submitted_step(ctx: InvocationContext) -> bool:
12+
return (
13+
get_current_step(ctx).get(CURRENT_STEP_STATUS) == PlanStepStatusEnum.SUBMITTED
14+
)

agents/matmaster_agent/state.py

Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -11,6 +11,7 @@
1111
MULTI_PLANS = 'multi_plans'
1212
PLAN_CONFIRM = 'plan_confirm'
1313
CURRENT_STEP = 'current_step'
14+
CURRENT_STEP_STATUS = 'status'
1415
HISTORY_STEPS = 'history_steps'
1516
FINISHED_STATE = 'finished_state'
1617

0 commit comments

Comments
 (0)