Skip to content
FunCoding

Search

Search docs, Skills and MCP

Python 会话与权限

组织预先确定的多轮输入,恢复 UUID 会话并处理异步审批。

This page has not been translated into English yet. The original Chinese version is shown below.

Python Query 同时是异步消息流和 CLI 控制句柄。多轮、恢复、取消和进程关闭是不同操作,应按应用需要分别使用。

多轮输入的限制

query 的 prompt 支持字符串或 AsyncIterable。多轮消息含 type: user、session_id、message 中的 role/content,以及 parent_tool_use_id: None。

from qwen_code_sdk import SDKUserMessage

SESSION_ID = "123e4567-e89b-12d3-a456-426614174000"

async def prompts():
    for text in ["Explain the project structure.", "List the test files."]:
        message: SDKUserMessage = {
            "type": "user",
            "session_id": SESSION_ID,
            "message": {"role": "user", "content": text},
            "parent_tool_use_id": None,
        }
        yield message

将 prompts() 传给 query,并在 options.session_id 使用同一个 ID。官方 v1 要求这些输入事先已知:SDK 按顺序发送,但不能把前一个响应反馈到 generator 再决定后一句。需要根据回答交互时,每轮使用单独 query 调用,并按需恢复已保存会话。

三种会话选择

字段含义
resume使用已知 UUID 恢复历史
continue_session由 CLI 选择最近会话继续
session_id为新会话指定/关联 UUID

一条请求只能用其中一个;组合会触发 ValidationError。用 get_session_id() 保存实际会话 ID,不把最近会话选择当成总能命中业务目标的稳定引用。

审批 callback

can_use_tool 必须是接收三个位置参数的 async callback:tool_name、tool_input、context。context 含 cancel_event、suggestions、blocked_path。未提供 callback、超时或 callback 抛异常都会转成拒绝,默认权限等待 60 秒。

async def can_use_tool(tool_name, tool_input, context):
    return {
        "behavior": "deny",
        "message": f"Application approval is required for {tool_name}",
    }

示例让进入 callback 的请求明确拒绝;应用可接自己的用户审批。允许时返回 behavior: allow 与 updatedInput,拒绝时返回 deny 与 message。审批 callback 不是完整文件沙箱,自动允许的工具与普通只读调用不一定进入 callback。

allowed_tools 用于无需 callback 的预先批准;core_tools 控制可用工具集合,不能拿 allowed_tools 当注册白名单。permission_mode 支持 default、plan、auto-edit、auto、yolo,其实际策略仍受 CLI 的更高优先级规则约束。

超时和进程控制

options = {
    "timeout": {
        "control_request": 60,
        "can_use_tool": 60,
        "stream_close": 60,
    }
}

单位为秒,与 TypeScript 的毫秒不同。stderr hook 必须接收一个位置字符串参数。

Query 提供 supported_commands()、mcp_server_status()、set_model()、set_permission_mode()、interrupt()、close()、get_session_id() 和 is_closed()。interrupt 取消当前操作,close 清理底层进程;不要在仅想停一轮时顺手终止整个进程。

SDK 仓库验证命令包括 npm run test:sdk:python、lint:sdk:python、typecheck:sdk:python;真实 smoke 另需兼容 CLI、认证和模型调用。文档中的配置并不代表这些外部条件已经具备。