()
| 514 | # ============================================================ |
| 515 | |
| 516 | def main(): |
| 517 | print("=" * 60) |
| 518 | print("Tutorial 12: 会话持久化(JSONL)") |
| 519 | print("=" * 60) |
| 520 | |
| 521 | # 创建临时目录 |
| 522 | tmpdir = tempfile.mkdtemp(prefix="session_demo_") |
| 523 | |
| 524 | # --- 1. 方案 A:JSON 整文件 --- |
| 525 | print("\n--- 方案 A: JSON 整文件(源码中的实现)---") |
| 526 | |
| 527 | session = Session() |
| 528 | session.add_message(ConversationMessage.user_text("帮我写个排序函数")) |
| 529 | session.add_message(ConversationMessage.assistant_text( |
| 530 | "好的,我来帮你写一个快速排序。" |
| 531 | )) |
| 532 | |
| 533 | json_path = os.path.join(tmpdir, "session.json") |
| 534 | save_session_json(session, json_path) |
| 535 | print(f" 保存到: {json_path}") |
| 536 | |
| 537 | restored = load_session_json(json_path) |
| 538 | print(f" 恢复成功!消息数: {len(restored.messages)}") |
| 539 | for msg in restored.messages: |
| 540 | text = msg.blocks[0].text if msg.blocks else "" |
| 541 | print(f" [{msg.role}] {text[:40]}") |
| 542 | |
| 543 | # --- 2. 方案 B:JSONL 仅追加 --- |
| 544 | print("\n--- 方案 B: JSONL 仅追加(生产级方案)---") |
| 545 | |
| 546 | storage = JsonlSessionStorage(tmpdir) |
| 547 | sid = "demo-session-001" |
| 548 | |
| 549 | # 模拟对话 |
| 550 | msgs = [ |
| 551 | ConversationMessage.user_text("帮我分析一下这个 bug"), |
| 552 | ConversationMessage.assistant_text( |
| 553 | "好的,让我看看代码。" |
| 554 | ), |
| 555 | ConversationMessage.user_text("bug 在 auth.py 第 42 行"), |
| 556 | ConversationMessage.assistant_text( |
| 557 | "我看到了,这是一个空指针问题。已修复。" |
| 558 | ), |
| 559 | ] |
| 560 | |
| 561 | # 逐条追加(模拟实时对话) |
| 562 | prev_uuid = "" |
| 563 | for msg in msgs: |
| 564 | msg.parent_uuid = prev_uuid |
| 565 | storage.append_message(sid, msg) |
| 566 | prev_uuid = msg.uuid |
| 567 | print(f" 追加: [{msg.role}] {msg.blocks[0].text[:30]}...") |
| 568 | |
| 569 | # 追加元数据 |
| 570 | storage.append_metadata(sid, "custom-title", |
| 571 | {"title": "修复 auth.py 空指针 bug"}) |
| 572 | storage.append_metadata(sid, "last-prompt", |
| 573 | {"text": "bug 在 auth.py 第 42 行"}) |
no test coverage detected