()
| 441 | |
| 442 | |
| 443 | def main(): |
| 444 | print("=" * 60) |
| 445 | print("Tutorial 05: 完整的 ConversationRuntime 演示") |
| 446 | print("=" * 60) |
| 447 | |
| 448 | # --- 组装引擎 --- |
| 449 | session = Session() |
| 450 | |
| 451 | api_client = DemoApiClient() |
| 452 | |
| 453 | tool_executor = ( |
| 454 | ToolExecutor() |
| 455 | .register("bash", lambda input_str: "file1.py\nfile2.py\nREADME.md") |
| 456 | .register("read_file", lambda input_str: "file content here") |
| 457 | ) |
| 458 | |
| 459 | permission_policy = ( |
| 460 | PermissionPolicy(PermissionMode.WORKSPACE_WRITE) |
| 461 | .with_tool_requirement("bash", PermissionMode.DANGER_FULL_ACCESS) |
| 462 | .with_tool_requirement("read_file", PermissionMode.READ_ONLY) |
| 463 | ) |
| 464 | |
| 465 | runtime = ConversationRuntime( |
| 466 | session=session, |
| 467 | api_client=api_client, |
| 468 | tool_executor=tool_executor, |
| 469 | permission_policy=permission_policy, |
| 470 | system_prompt=["You are a helpful coding assistant."], |
| 471 | ) |
| 472 | |
| 473 | # --- 场景 A: 有 Prompter,bash 会被询问并通过 --- |
| 474 | print("\n--- 场景 A: 使用 AutoAllowPrompter ---") |
| 475 | summary = runtime.run_turn( |
| 476 | "当前目录有什么文件?", |
| 477 | prompter=AutoAllowPrompter(), |
| 478 | ) |
| 479 | |
| 480 | print(f"\n 循环轮次: {summary.iterations}") |
| 481 | print(f" 助手消息数: {len(summary.assistant_messages)}") |
| 482 | print(f" 工具结果数: {len(summary.tool_results)}") |
| 483 | print(f" Token 使用: {runtime.usage_tracker.summary()}") |
| 484 | |
| 485 | # 打印完整对话 |
| 486 | print("\n --- 完整对话记录 ---") |
| 487 | for i, msg in enumerate(session.messages): |
| 488 | role = msg.role.upper() |
| 489 | for block in msg.blocks: |
| 490 | if isinstance(block, TextBlock): |
| 491 | preview = block.text[:60].replace('\n', ' ') |
| 492 | print(f" [{i}] {role}: {preview}") |
| 493 | elif isinstance(block, ToolUseBlock): |
| 494 | print(f" [{i}] {role}: [调用工具 {block.name}({block.input})]") |
| 495 | elif isinstance(block, ToolResultBlock): |
| 496 | status = "ERROR" if block.is_error else "OK" |
| 497 | print(f" [{i}] {role}: [工具结果 {block.tool_name}: {status}] {block.output[:40]}") |
| 498 | |
| 499 | # --- 场景 B: 没有 Prompter,bash 会被拒绝 --- |
| 500 | print("\n\n--- 场景 B: 不提供 Prompter,bash 将被拒绝 ---") |
no test coverage detected