"""让 AI 弹一个选择弹窗,并把用户选的那一项拿回去。 ## 和 show_ui 的分工 `show_ui` 展示用 —— **不阻塞**,弹出来就返回,用户看完自己关 `ask_user` 问询用 —— **阻塞**,等用户选完才返回,模型拿到选择继续干活 这两个刻意分开:展示性的东西不该把对话卡住;而"让用户在几个方案里选一个" 必须拿到答案才能继续。 ## 阻塞是怎么实现的 安卓侧 `NativeBridge.device()` 是同步的 —— 它在 UI 线程上弹出界面, 然后用一个 `CountDownLatch` 等用户点,等到(或超时)才把结果回给 Python。 Python 这边就是一次普通调用,不需要轮询。 ★ 超时必须有:用户可能把手机锁屏走了,不能让内核线程永远挂着。 默认 120 秒,到点返回 `timeout: true`,模型据此知道"用户没理我"。 ## 电脑端 明确返回不可用(桌面版的界面在桌面窗口里)。 """ import os import sys sys.path.insert(0, os.path.dirname(os.path.abspath(__file__))) from _protocol import serve # noqa: E402 from _ui_bridge import call_device, conversation_id # noqa: E402 # 等用户的秒数上限。安卓侧也有自己的上限,两边都不设的话 # 用户锁屏走了会把内核的工作线程永远占住。 TIMEOUT_S = 120 TOOL = { "name": "ask_user", "description": ( "弹一个选择弹窗问用户,**等用户选完**再继续(最多等 120 秒)。" "适合:几个方案让人挑一个、要确认一个危险操作、需要用户补充一个选择。" "options 传选项数组(每项 {label, value, description}):" "label 是按钮上显示的字,value 是你要拿到的值(留空则用 label)," "description 是选项下方的小字说明。" "多选请传 multiple=true。返回里 choice/values 就是用户选的东西;" "timeout=true 表示用户没在时限内回答。" ), "parameters": { "type": "object", "properties": { "question": { "type": "string", "description": "要问的问题", }, "options": { "type": "array", "description": "选项列表", "items": { "type": "object", "properties": { "label": {"type": "string", "description": "按钮上显示的文字"}, "value": {"type": "string", "description": "返回给模型的值,留空则用 label"}, "description": {"type": "string", "description": "选项下方的小字说明"}, }, "required": ["label"], }, }, "multiple": { "type": "boolean", "description": "是否允许多选,默认 false", }, "allow_cancel": { "type": "boolean", "description": "是否显示「取消」按钮,默认 true", }, }, "required": ["question", "options"], }, } def _clean_options(raw) -> list: """ 规整选项。 ★ 模型经常把 options 写成裸字符串数组(`["A", "B"]`)而不是对象数组 —— 这在 tool calling 里非常常见,直接 `.get()` 会 AttributeError。 所以两种都收下,别让模型因为格式小错就吃一个报错。 """ out = [] for item in raw or []: if isinstance(item, dict): label = str(item.get("label") or item.get("value") or "").strip() if not label: continue out.append( { "label": label, "value": str(item.get("value") or label), "description": str(item.get("description") or ""), } ) elif isinstance(item, (str, int, float)): text = str(item).strip() if text: out.append({"label": text, "value": text, "description": ""}) return out def run(args: dict) -> dict: question = str(args.get("question") or "").strip() if not question: raise ValueError("question 不能为空") options = _clean_options(args.get("options")) if not options: raise ValueError("options 至少要给一个选项") # 选项太多按钮会挤成一屏,截断并告诉模型(而不是静默丢掉) truncated = False if len(options) > 8: options = options[:8] truncated = True res = call_device( { "action": "ui_dialog", "question": question, "options": options, "multiple": bool(args.get("multiple")), "allowCancel": bool(args.get("allow_cancel", True)), "timeoutMs": TIMEOUT_S * 1000, "conversationId": conversation_id(), } ) if res.get("unavailable"): raise RuntimeError(res.get("error") or "当前环境没有界面能力") if res.get("error"): raise RuntimeError(str(res["error"])) out = { "question": question, "multiple": bool(res.get("multiple")), "timeout": bool(res.get("timeout")), "cancelled": bool(res.get("cancelled")), "choice": res.get("choice") or "", "values": res.get("values") or [], } if truncated: out["note"] = "选项超过 8 个,只显示了前 8 个" return out if __name__ == "__main__": serve(TOOL, run)