Skip to content

Commit 12c6fd7

Browse files
committed
refactor:重构流程来简化状态更新和工具调用逻辑
1 parent 3207ce4 commit 12c6fd7

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
@@ -84,14 +84,17 @@
8484
from agents.matmaster_agent.flow_agents.scene_agent.constant import SCENE_AGENT
8585
from agents.matmaster_agent.flow_agents.scene_agent.prompt import SCENE_INSTRUCTION
8686
from agents.matmaster_agent.flow_agents.scene_agent.schema import SceneSchema
87-
from agents.matmaster_agent.flow_agents.schema import FlowStatusEnum
8887
from agents.matmaster_agent.flow_agents.step_title_agent.callback import (
8988
filter_llm_contents,
9089
)
9190
from agents.matmaster_agent.flow_agents.step_title_agent.prompt import (
9291
STEP_TITLE_INSTRUCTION,
9392
)
9493
from agents.matmaster_agent.flow_agents.step_title_agent.schema import StepTitleSchema
94+
from agents.matmaster_agent.flow_agents.step_utils import (
95+
get_current_step,
96+
is_job_submitted_step,
97+
)
9598
from agents.matmaster_agent.flow_agents.step_validation_agent.prompt import (
9699
STEP_VALIDATION_INSTRUCTION,
97100
)
@@ -101,9 +104,7 @@
101104
from agents.matmaster_agent.flow_agents.thinking_agent.agent import ThinkingAgent
102105
from agents.matmaster_agent.flow_agents.thinking_agent.constant import THINKING_AGENT
103106
from agents.matmaster_agent.flow_agents.utils import (
104-
check_plan,
105107
get_tools_list,
106-
is_plan_confirmed,
107108
scenes_contain_query_job_status,
108109
should_bypass_confirmation,
109110
)
@@ -343,28 +344,20 @@ def _build_execution_agent_for_plan(
343344
before_model_callback=filter_llm_contents,
344345
after_model_callback=MatMasterLlmConfig.opik_tracer.after_model_callback,
345346
)
346-
plan_steps = ctx.session.state.get('plan', {}).get('steps', [])
347-
agent_names = []
348-
for step in plan_steps:
349-
tool_name = step.get('tool_name')
350-
if not tool_name:
351-
continue
352-
belonging_agent = ALL_TOOLS.get(tool_name, {}).get('belonging_agent')
353-
if belonging_agent and belonging_agent not in agent_names:
354-
agent_names.append(belonging_agent)
355-
356-
sub_agents = [
357-
AGENT_CLASS_MAPPING[agent_name](MatMasterLlmConfig)
358-
for agent_name in agent_names
359-
if agent_name in AGENT_CLASS_MAPPING
360-
]
347+
current_step = get_current_step(ctx)
348+
tool_name = current_step.get('tool_name')
349+
belonging_agent = ALL_TOOLS.get(tool_name, {}).get('belonging_agent')
361350

362351
execution_agent = MatMasterSupervisorAgent(
363352
name='execution_agent',
364353
model=MatMasterLlmConfig.default_litellm_model,
365354
description='根据 materials_plan 返回的计划进行总结',
366355
instruction='',
367-
sub_agents=sub_agents + [step_title_agent] + [step_validation_agent],
356+
sub_agents=[
357+
AGENT_CLASS_MAPPING[belonging_agent](MatMasterLlmConfig),
358+
step_title_agent,
359+
step_validation_agent,
360+
],
368361
)
369362
track_adk_agent_recursive(execution_agent, MatMasterLlmConfig.opik_tracer)
370363
return execution_agent
@@ -611,8 +604,6 @@ async def _run_step_make_agent(
611604
async def _run_plan_execute_agent(
612605
self, ctx: InvocationContext
613606
) -> AsyncGenerator[Event, None]:
614-
# 重置 scenes
615-
yield update_state_event(ctx, state_delta={'scenes': []})
616607
# 执行计划
617608
self._execution_agent = self._build_execution_agent_for_plan(ctx)
618609
if self._execution_agent:
@@ -741,26 +732,6 @@ async def _run_summary_agent(
741732
yield matmaster_flow_event
742733
yield update_state_event(ctx, state_delta={'matmaster_flow_active': None})
743734

744-
# 渲染追问组件
745-
follow_up_list = await get_random_questions(i18n=i18n)
746-
for generate_follow_up_event in context_function_event(
747-
ctx,
748-
self.name,
749-
'matmaster_generate_follow_up',
750-
{},
751-
ModelRole,
752-
{
753-
'follow_up_result': json.dumps(
754-
{
755-
'invocation_id': ctx.invocation_id,
756-
'title': i18n.t('MoreQuestions'),
757-
'list': follow_up_list,
758-
}
759-
)
760-
},
761-
):
762-
yield generate_follow_up_event
763-
764735
async def _run_research_flow(
765736
self, ctx: InvocationContext
766737
) -> AsyncGenerator[Event, None]:
@@ -791,14 +762,8 @@ async def _run_research_flow(
791762
yield _scene_event
792763

793764
while True:
794-
# 制定计划(1. 无计划;2. 计划已完成;3. 计划失败;4. 用户未确认计划)
795-
# 仅查询任务状态时跳过 thinking(查任务状态不 thinking)
796-
skip_thinking = scenes_contain_query_job_status(ctx)
797-
if check_plan(ctx) in [
798-
FlowStatusEnum.NO_PLAN,
799-
FlowStatusEnum.COMPLETE,
800-
FlowStatusEnum.FAILED,
801-
] or not is_plan_confirmed(ctx):
765+
if not is_job_submitted_step(ctx):
766+
skip_thinking = scenes_contain_query_job_status(ctx)
802767
async for _step_make_event in self._run_step_make_agent(
803768
ctx,
804769
UPDATE_USER_CONTENT,
@@ -807,27 +772,50 @@ async def _run_research_flow(
807772
):
808773
yield _step_make_event
809774

810-
# 计划未确认,暂停往下执行
811-
# if is_plan_confirmed(ctx):
812775
async for _plan_execute_event in self._run_plan_execute_agent(ctx):
813776
yield _plan_execute_event
814777

815-
# 回顾历史执行
816-
user_request = ctx.user_content.parts[0].text
817-
history_steps = ctx.session.state[HISTORY_STEPS]
818-
session_files = await get_session_files(ctx.session.id)
819-
self.all_finished_agent.instruction = create_all_finished_instruction(
820-
user_request, history_steps, session_files
821-
)
822-
async for _all_finished_event in self.all_finished_agent.run_async(ctx):
823-
yield _all_finished_event
778+
# 检查是否为等待异步任务执行完成的阶段
779+
if not is_job_submitted_step(ctx):
780+
# 回顾历史执行
781+
user_request = ctx.user_content.parts[0].text
782+
history_steps = ctx.session.state[HISTORY_STEPS]
783+
session_files = await get_session_files(ctx.session.id)
784+
self.all_finished_agent.instruction = create_all_finished_instruction(
785+
user_request, history_steps, session_files
786+
)
787+
async for _all_finished_event in self.all_finished_agent.run_async(ctx):
788+
yield _all_finished_event
824789

825-
if ctx.session.state[FINISHED_STATE]['finished']:
790+
if ctx.session.state[FINISHED_STATE]['finished']:
791+
break
792+
else:
826793
break
827794

828-
# 总结计划
829-
async for _plan_summary_event in self._run_summary_agent(ctx):
830-
yield _plan_summary_event
795+
if not is_job_submitted_step(ctx):
796+
# 总结计划
797+
async for _plan_summary_event in self._run_summary_agent(ctx):
798+
yield _plan_summary_event
799+
800+
# 渲染追问组件
801+
follow_up_list = await get_random_questions(i18n=i18n)
802+
for generate_follow_up_event in context_function_event(
803+
ctx,
804+
self.name,
805+
'matmaster_generate_follow_up',
806+
{},
807+
ModelRole,
808+
{
809+
'follow_up_result': json.dumps(
810+
{
811+
'invocation_id': ctx.invocation_id,
812+
'title': i18n.t('MoreQuestions'),
813+
'list': follow_up_list,
814+
}
815+
)
816+
},
817+
):
818+
yield generate_follow_up_event
831819

832820
async def _run_async_impl(
833821
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)