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

Class ConversationRuntime

tutorials/18_design_patterns_for_agents.py:246–296  ·  view source on GitHub ↗

注意: __init__ 不创建任何依赖, 全部从外部接收。 这就是依赖注入——"把依赖注入进来, 而不是自己造"。

Source from the content-addressed store, hash-verified

244
245 # 对应 conversation.rs:100-110 的 ConversationRuntime<C, T>
246 class ConversationRuntime:
247 """
248 注意: __init__ 不创建任何依赖, 全部从外部接收。
249 这就是依赖注入——"把依赖注入进来, 而不是自己造"
250 """
251 def __init__(
252 self,
253 api_client: ApiClient, # 从外部传入
254 tool_executor: ToolExecutor, # 从外部传入
255 max_iterations: int = 10,
256 ):
257 self.api_client = api_client
258 self.tool_executor = tool_executor
259 self.max_iterations = max_iterations
260 self.messages: list[dict] = []
261
262 def run_turn(self, user_input: str) -> str:
263 """对应 conversation.rs:170-283 的 run_turn"""
264 self.messages.append({"role": "user", "content": user_input})
265
266 for i in range(self.max_iterations):
267 events = self.api_client.stream(self.messages)
268 text_parts = []
269 tool_calls = []
270
271 for event in events:
272 if event["type"] == "text":
273 text_parts.append(event["text"])
274 elif event["type"] == "tool_use":
275 tool_calls.append(event)
276
277 self.messages.append({
278 "role": "assistant",
279 "content": "".join(text_parts),
280 "tool_calls": tool_calls,
281 })
282
283 if not tool_calls:
284 return "".join(text_parts)
285
286 for call in tool_calls:
287 result = self.tool_executor.execute(
288 call["name"], call["input"]
289 )
290 self.messages.append({
291 "role": "tool",
292 "tool_use_id": call["id"],
293 "content": result,
294 })
295
296 return "达到最大迭代次数"
297
298 # ---- 演示: 同一个 Runtime, 不同的 "插头" ----
299

Callers 1

Calls

no outgoing calls

Tested by

no test coverage detected