会话管理

txcode-sdk 自动将对话历史持久化为 JSON 文件,存储在 {work_dir}/.txcode/session/ 目录下。

会话存储结构

.txcode/session/
└── session_{session_id}.json

每个会话文件的结构:

{
  "id": "a3ced874e170...",
  "title": "用户第一条消息的前50字符",
  "created_at": "2026-06-15T10:00:00+00:00",
  "updated_at": "2026-06-15T10:05:00+00:00",
  "prompt_tokens": 1500,
  "completion_tokens": 800,
  "summary_message_index": null,
  "messages": [
    { "index": 0, "role": "user", "content": "帮我创建 hello.py", "keep_context": true, "is_original": true },
    { "index": 1, "role": "assistant", "content": "{\"type\":\"assistant_with_tools\", ...}", "keep_context": true },
    { "index": 2, "role": "tool", "content": "文件已创建", "tool_call_id": "call_xxx", "keep_context": false }
  ]
}

API 参考

list_sessions()

sessions = client.list_sessions()
for s in sessions:
    print(s["print_summary"])
    # 输出: [2026-06-15] 帮我创建 hello.py (12 messages)

扫描 .txcode/session/session_*.json,提取第一条 user 消息作为标题。

get_session()

session = client.get_session("a3ced874e170")
if session:
    for msg in session["messages"]:
        print(f"  [{msg['role']}] {msg['content'][:80]}...")

get_session_messages()

获取带 printMsg 字段的消息,用于友好展示。

data = client.get_session_messages(session_id)
for msg in data["messages"]:
    pm = msg.get("printMsg")
    if pm:
        print(pm)

printMsg 生成逻辑

delete_session()

client.delete_session(session_id)

chat() 中的会话续接

result1 = await client.chat("我叫小明")
sid = result1.session_id
result2 = await client.chat("我叫什么?", session_id=sid)
print(result2.answer)  # "你叫小明"

相关类型

StepInfo

@dataclass
class StepInfo:
    reasoning: str | None          # AI 推理内容
    tool_calls: list[ToolCallInfo] # 工具调用列表
    results: list[ToolResultInfo]  # 工具执行结果
    iteration: int                 # 当前迭代编号
    usage: TokenUsage | None       # Token 用量
    printMsg: str | None           # 可打印消息

@dataclass
class ToolCallInfo:
    id: str; name: str; arguments: dict

@dataclass
class ToolResultInfo:
    name: str; success: bool; output: str | None; error: str | None