(
agent_runner: AgentRunner,
max_step: int = 30,
show_tool_use: bool = True,
show_tool_call_result: bool = False,
stream_to_general: bool = False,
show_reasoning: bool = False,
buffer_intermediate_messages: bool = False,
)
| 114 | |
| 115 | |
| 116 | async def run_agent( |
| 117 | agent_runner: AgentRunner, |
| 118 | max_step: int = 30, |
| 119 | show_tool_use: bool = True, |
| 120 | show_tool_call_result: bool = False, |
| 121 | stream_to_general: bool = False, |
| 122 | show_reasoning: bool = False, |
| 123 | buffer_intermediate_messages: bool = False, |
| 124 | ) -> AsyncGenerator[MessageChain | None, None]: |
| 125 | step_idx = 0 |
| 126 | astr_event = agent_runner.run_context.context.event |
| 127 | tool_name_by_call_id: dict[str, str] = {} |
| 128 | buffered_llm_chains: list[MessageChain] = [] |
| 129 | can_buffer_llm_result = _should_buffer_llm_result( |
| 130 | buffer_intermediate_messages, |
| 131 | stream_to_general, |
| 132 | agent_runner, |
| 133 | ) |
| 134 | while step_idx < max_step + 1: |
| 135 | step_idx += 1 |
| 136 | |
| 137 | if step_idx == max_step + 1: |
| 138 | logger.warning( |
| 139 | f"Agent reached max steps ({max_step}), forcing a final response." |
| 140 | ) |
| 141 | if not agent_runner.done(): |
| 142 | # 拔掉所有工具 |
| 143 | if agent_runner.req: |
| 144 | agent_runner.req.func_tool = None |
| 145 | # 注入提示词 |
| 146 | agent_runner.run_context.messages.append( |
| 147 | Message( |
| 148 | role="user", |
| 149 | content="工具调用次数已达到上限,请停止使用工具,并根据已经收集到的信息,对你的任务和发现进行总结,然后直接回复用户。", |
| 150 | ) |
| 151 | ) |
| 152 | |
| 153 | stop_watcher = asyncio.create_task( |
| 154 | _watch_agent_stop_signal(agent_runner, astr_event), |
| 155 | ) |
| 156 | try: |
| 157 | async for resp in agent_runner.step(): |
| 158 | if _should_stop_agent(astr_event): |
| 159 | agent_runner.request_stop() |
| 160 | |
| 161 | if resp.type == "aborted": |
| 162 | if can_buffer_llm_result: |
| 163 | merged_chain = _merge_buffered_llm_chains(buffered_llm_chains) |
| 164 | if merged_chain: |
| 165 | astr_event.set_result( |
| 166 | MessageEventResult( |
| 167 | chain=merged_chain.chain, |
| 168 | result_content_type=ResultContentType.LLM_RESULT, |
| 169 | ), |
| 170 | ) |
| 171 | yield merged_chain |
| 172 | astr_event.clear_result() |
| 173 | if not stop_watcher.done(): |
no test coverage detected