MCPcopy Create free account
hub / github.com/Louisym/MiniCC / run_turn

Function run_turn

tutorials/01_agentic_loop_basics.py:156–225  ·  view source on GitHub ↗

执行一个完整的"对话轮次"。 这个函数做的事情: 1. 把用户的输入加到对话历史里 2. 不断循环:调用 AI → 如果 AI 要用工具就执行 → 再调用 AI → ... 3. 直到 AI 给出纯文字回复(不再需要工具),循环结束 参数: ai: AI 模型(真实场景下是 Anthropic API) session: 对话历史(所有消息的列表) user_input: 用户这次说的话 返回: 更新后的对话历史

(ai: FakeAI, session: list[Message], user_input: str)

Source from the content-addressed store, hash-verified

154# 对应源码: rust/crates/runtime/src/conversation.rs 的 run_turn() 方法
155
156def run_turn(ai: FakeAI, session: list[Message], user_input: str) -> list[Message]:
157 """
158 执行一个完整的"对话轮次"
159
160 这个函数做的事情:
161 1. 把用户的输入加到对话历史里
162 2. 不断循环:调用 AI → 如果 AI 要用工具就执行 → 再调用 AI → ...
163 3. 直到 AI 给出纯文字回复(不再需要工具),循环结束
164
165 参数:
166 ai: AI 模型(真实场景下是 Anthropic API)
167 session: 对话历史(所有消息的列表)
168 user_input: 用户这次说的话
169
170 返回:
171 更新后的对话历史
172 """
173 # 步骤 1: 把用户消息加入对话历史
174 session.append(Message(role="user", content=user_input))
175 print(f"\n[用户] {user_input}")
176
177 # 步骤 2: 开始 Agentic Loop
178 iteration = 0
179 max_iterations = 10 # 安全限制,防止无限循环
180
181 while True:
182 iteration += 1
183 if iteration > max_iterations:
184 print("[错误] 超过最大循环次数,强制停止")
185 break
186
187 print(f"\n--- 循环第 {iteration} 轮 ---")
188
189 # 步骤 2a: 调用 AI(传入完整的对话历史)
190 ai_response = ai.chat(session)
191
192 # 步骤 2b: 判断 AI 的回复类型
193 if ai_response["type"] == "text":
194 # AI 给出了纯文字回复 → 循环结束!
195 assistant_msg = Message(role="assistant", content=ai_response["text"])
196 session.append(assistant_msg)
197 print(f"[助手] {ai_response['text']}")
198 break # <-- 这就是循环终止的条件
199
200 elif ai_response["type"] == "tool_use":
201 # AI 要使用工具 → 我们需要执行工具,把结果告诉 AI
202 tool_name = ai_response["name"]
203 tool_input = ai_response["input"]
204 print(f"[助手] 我要使用工具: {tool_name}({tool_input})")
205
206 # 先把 AI 的"工具请求"消息加入历史
207 session.append(Message(
208 role="assistant",
209 content=f"[tool_use: {tool_name}({tool_input})]"
210 ))
211
212 # 执行工具
213 if tool_name in TOOL_REGISTRY:

Callers 1

mainFunction · 0.85

Calls 3

appendMethod · 0.80
chatMethod · 0.80
MessageClass · 0.70

Tested by

no test coverage detected