From 0f32b8335e3a1e0c308f4281be99669405259218 Mon Sep 17 00:00:00 2001 From: ThearchyHelios Date: Wed, 14 Oct 2026 20:05:23 +0800 Subject: [PATCH] =?UTF-8?q?=E5=BA=94=E7=94=A8=E5=B9=B3=E5=8F=B0=20BE-4=20?= =?UTF-8?q?=E5=8A=A9=E6=89=8B=EF=BC=9A=E6=8C=89=E9=9C=80=E6=9F=A5=E7=9C=8B?= =?UTF-8?q?=EF=BC=88=E9=BB=98=E8=AE=A4=E5=8F=AA=E7=BB=99=E6=95=B0=E6=8D=AE?= =?UTF-8?q?=E6=BA=90=E6=A6=82=E8=A7=88=E3=80=81look=20=E8=A1=8C=E5=81=9C?= =?UTF-8?q?=E4=B8=8B=E6=89=A7=E8=A1=8C=E6=8E=A5=E7=9D=80=E5=86=99=E3=80=81?= =?UTF-8?q?=E4=B8=80=E6=AC=A1=E6=8B=BF=E9=BD=90=E3=80=81=E6=AF=8F=E8=BD=AE?= =?UTF-8?q?=203+1=20=E6=AC=A1=E3=80=81=E7=B3=BB=E7=BB=9F=E4=BB=A3=E4=B8=BA?= =?UTF-8?q?=E6=9F=A5=E7=9C=8B=E3=80=81=E6=9F=A5=E7=9C=8B=E8=AE=B0=E5=BD=95?= =?UTF-8?q?=E8=BF=9B=E5=8E=86=E5=8F=B2=EF=BC=89=EF=BC=8C=E7=94=9F=E6=88=90?= =?UTF-8?q?=E8=BF=87=E7=A8=8B=E5=8F=AF=E6=8F=92=E6=8B=94=EF=BC=88Applier?= =?UTF-8?q?=20/=20Checker=20=E6=B3=A8=E5=85=A5=E3=80=81ask=20=E7=BB=93?= =?UTF-8?q?=E6=9D=9F=E6=9C=AC=E8=BD=AE=EF=BC=89=EF=BC=8C=E6=9F=A5=E7=9C=8B?= =?UTF-8?q?=E5=AF=B9=E8=B1=A1=E6=8C=89=E7=B1=BB=E5=9E=8B=E6=A0=87=E8=AE=B0?= =?UTF-8?q?=E5=B9=B6=E5=AE=9E=E7=8E=B0=E8=A1=A8=20/=20=E8=83=BD=E5=8A=9B?= =?UTF-8?q?=20/=20=E5=B7=A5=E4=BD=9C=E6=B5=81=E7=89=88=E6=9C=AC=E4=B8=89?= =?UTF-8?q?=E7=A7=8D=EF=BC=88=E8=A1=A8=E8=AF=A6=E6=83=85=E4=B8=8E=20db=5Fs?= =?UTF-8?q?chema=5F=5F=E3=80=81/schema=20=E5=85=B1=E7=94=A8=E5=B9=B6?= =?UTF-8?q?=E6=8C=89=E9=81=AE=E7=BD=A9=E8=A7=84=E7=9F=A9=EF=BC=89=EF=BC=8C?= =?UTF-8?q?=E5=BA=94=E7=94=A8=E6=B6=A6=E8=89=B2=E6=8E=A5=E5=8F=A3=20/copil?= =?UTF-8?q?ot/app-stream=EF=BC=8C=E4=BB=8E=E8=BF=90=E8=A1=8C=E6=8F=90?= =?UTF-8?q?=E5=8F=96=E6=A8=A1=E6=9D=BF=E8=AE=B0=E6=9D=A5=E6=BA=90=EF=BC=8C?= =?UTF-8?q?=E6=BC=94=E7=A4=BA=E6=A8=A1=E5=9E=8B=E8=B5=B0=E4=B8=80=E6=AC=A1?= =?UTF-8?q?=E6=9F=A5=E7=9C=8B=EF=BC=88=E5=90=AB=E7=BB=9F=E4=B8=80=E5=A4=8D?= =?UTF-8?q?=E6=A0=B8=E5=90=8E=E7=9A=84=E4=BF=AE=E5=A4=8D=EF=BC=89?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- backend/app/api/copilot.py | 1074 ++++++++--------- backend/app/api/copilot_context.py | 790 +----------- backend/app/api/copilot_gen.py | 639 ++++++++++ backend/app/api/datasources.py | 10 +- backend/app/data/schema_view.py | 258 ++++ backend/app/look/__init__.py | 3 + backend/app/look/base.py | 28 +- backend/app/look/capabilities.py | 263 ++++ backend/app/look/pick.py | 166 +++ backend/app/look/service.py | 221 ++++ backend/app/look/tables.py | 384 ++++++ backend/app/look/versions.py | 181 +++ backend/app/providers/mock_model.py | 66 + backend/app/tools/datasource.py | 18 +- backend/tests/test_autofix_assist.py | 3 +- backend/tests/test_catalog_impact.py | 5 +- .../tests/test_catalog_schema_truncated.py | 43 +- backend/tests/test_conversations.py | 8 +- backend/tests/test_copilot_context.py | 36 +- backend/tests/test_copilot_look.py | 617 ++++++++++ backend/tests/test_copilot_merge.py | 20 +- backend/tests/test_copilot_patch_layout.py | 14 +- backend/tests/test_copilot_scope.py | 15 +- backend/tests/test_copilot_sql_alias.py | 8 +- backend/tests/test_copilot_table_pick.py | 722 +++++------ 25 files changed, 3759 insertions(+), 1833 deletions(-) create mode 100644 backend/app/api/copilot_gen.py create mode 100644 backend/app/data/schema_view.py create mode 100644 backend/app/look/capabilities.py create mode 100644 backend/app/look/pick.py create mode 100644 backend/app/look/service.py create mode 100644 backend/app/look/tables.py create mode 100644 backend/app/look/versions.py create mode 100644 backend/tests/test_copilot_look.py diff --git a/backend/app/api/copilot.py b/backend/app/api/copilot.py index 8f75dd9f..67c13126 100644 --- a/backend/app/api/copilot.py +++ b/backend/app/api/copilot.py @@ -16,9 +16,11 @@ from sqlalchemy.ext.asyncio import AsyncSession from app.api import copilot_context from app.api.coded import DATASOURCE_SCOPE_EMPTY, CodedHTTPException -# 摘要的预算和截断阈值随数据源上下文搬到了 copilot_context,这里留着老名字 -from app.api.copilot_context import DATASOURCE_BUDGET_CHARS as _DATASOURCE_BUDGET_CHARS # noqa: F401 -from app.api.copilot_context import DETAIL_TABLE_LIMIT as _DETAIL_TABLE_LIMIT # noqa: F401 +# 读流、解析、落地搬到了生成过程(copilot_gen),这里留着老名字:测试和别处照旧从这里取 +from app.api.copilot_gen import ( # noqa: F401 + AppApplier, AppChecker, CopilotIncomplete, Generation, GraphApplier, GraphChecker, _apply_op, _iter_ops, + _member_key, _NODE_TYPES, _parse_op_line, merge_node_config, +) # 起别名:本文件底下有个叫 explain 的接口,generate 里又有个局部变量叫 raw,同名会互相盖掉 from app.core.errors import explain as explain_error, graph_error, raw as raw_error from app.data.sqlcheck import CHECK_CODES @@ -72,15 +74,14 @@ def _scope_note(rows: list[Any], scoped: bool) -> str: "db_schema__ 工具;前几轮用过别的库,这一轮也不要沿用") -def _tool_catalog(rows: list[Any], context: copilot_context.DatasourceContext | None = None) -> str: - """给 Copilot 看的工具清单。 +def _tool_catalog(rows: list[Any]) -> str: + """给助手看的工具清单。 all_specs() 只有静态注册的内置工具,数据源工具是运行时按库动态生成的 - (db_query__<源>),不补进来 Copilot 就不知道它们存在,只会退回让用户 + (db_query__<源>),不补进来助手就不知道它们存在,只会退回让用户 自己写 SQL 的代码节点——接了数据库等于白接。 - 「可查」后面列前 12 个对象。给了这一轮的数据源上下文时按它排:大库里按需求挑中的表排在前面 - (DatasourceContext.listed),不然列出来的是表结构里排在最前的那几张,和需求未必相干。 + 不列表名(look 文档 D3):以前每个库列前 12 个表名,和这一轮要做什么无关,闲聊也带着;表数写一句,字段要用时 look。 """ lines = [ f"- {name}({spec.category}):{spec.description}" @@ -91,12 +92,11 @@ def _tool_catalog(rows: list[Any], context: copilot_context.DatasourceContext | from app.tools.datasource import QUERY_PREFIX, SCHEMA_PREFIX for row in rows: - tables = context.listed(row) if context is not None else _introspect.table_names(row) - listed = "、".join(tables[:12]) + (f" 等 {len(tables)} 个对象" if len(tables) > 12 else "") + tables = _introspect.table_names(row) lines.append( f"- {QUERY_PREFIX}{row.name}(数据库):在「{row.name}」上执行 SQL。" f"{row.description or ''}" - + (f" 可查:{listed}" if tables else " ⚠ 结构未探查") + + (f" 共 {len(tables)} 张表,字段要用时 look" if tables else " ⚠ 结构未探查") ) lines.append( f"- {SCHEMA_PREFIX}{row.name}(数据库):查看「{row.name}」的表结构" @@ -104,45 +104,13 @@ def _tool_catalog(rows: list[Any], context: copilot_context.DatasourceContext | return "\n".join(lines) -#: 带进挑表需求里的前几轮问题:追问常常只说「那上上个月呢」,光看这一句挑不出表 -_PICK_HISTORY_TURNS = 3 - - -async def _pick_need(session: AsyncSession, payload: GenerateIn) -> str: - """挑表用的需求:这一轮的原话,问数据追问时再带上这次对话前几轮的问题。""" - from app.api.conversations import recent_turns - - if not payload.conversation_id: - return payload.instruction - turns = await recent_turns(session, payload.conversation_id) - asked = [t.question for t in turns if t.question][-_PICK_HISTORY_TURNS:] - return payload.instruction + (PICK_HISTORY_PROMPT.format(questions=";".join(asked)) if asked else "") - - -PICK_HISTORY_PROMPT = "\n(这次对话之前问过:{questions})" - - -async def _picker(session: AsyncSession, payload: GenerateIn, - plan: copilot_context.ContextPlan) -> tuple[Any | None, str | None]: - """挑表用的模型:同一个助手模型(copilot_model_spec),思考、额度在 pick_model 里调。不用挑表时不拿。""" - if not plan.needs_pick: - return None, None +async def _look_service(session: AsyncSession, payload: GenerateIn, sources: list[Any], *, + graph: dict[str, Any] | None, kinds: tuple[str, ...] = ("table", "capability"), + ) -> Any: + """这一轮的查看服务(copilot_context.look_service)。挑选模型用同一个助手模型,第一次要挑时才拿。""" spec = await copilot_model_spec(session, payload, max_tokens=copilot_context.PICK_MAX_TOKENS) - return await copilot_context.pick_model(session, spec) - - -async def _datasource_context( - session: AsyncSession, sources: list[Any], payload: GenerateIn, *, need: str, - graph: dict[str, Any] | None, -) -> copilot_context.DatasourceContext: - """这一轮的数据源上下文:读目录、大库按需求挑表、组装(copilot_context)。挑表失败退回只列表名,不抛异常。 - - 非流式生成、发布前修复、升级都走这里;流式生成把三步拆开,挑表放进流里(期间发心跳、挑完发 context 操作)。 - graph 是现有工作流:它的 SQL 查过的表一律给全字段。 - """ - plan = await copilot_context.plan_context(sources, graph=graph) - picker, unavailable = await _picker(session, payload, plan) - return await plan.resolve(picker, need=need, unavailable=unavailable) + return await copilot_context.look_service(sources, spec=spec, graph=graph, kinds=kinds, + answer=payload.intent == "answer") NODE_REFERENCE = """\ @@ -174,6 +142,11 @@ NODE_REFERENCE = """\ - supervisor:多 agent 协作。config: {goal, agents:[{name, description, system, tools, model}], max_rounds} 成员停不下来等人:需要审批的 MCP / 自定义工具在成员手里不会执行。要用这类工具,交给团队外的 agent 节点 - tool:直接调一个工具。config: {tool: 工具名, args: {...}, assign_to} + **写外部系统的能力**(能力登记里读写是「写入」的,look 能力时看得到)只能放在 tool 节点里,不能绑给 agent、协作团队 + (发布检查会拦,运行时也会拒)。写入一律先确认再发送:运行停在这个节点开头等人确认,确认卡上是按 args 渲染出来的 + 参数(遮罩后)和它的哈希,确认后按同一份参数发出,参数变了就拒绝发送。args 按引用写上游的值({{ input.x }}、 + {{ vars.x.字段 }}),不要让 agent 拼好整段参数再传过来;要改参数就改上游的表单,确认时不能改。结果未知时系统去核实, + 不会自动重发。探索运行里端点没有测试环境的只演练、不真发 - merge:合并查询,把几次查询的结果在库外按键合并成一张表。config: {inputs: {别名: 上游查询节点id}, sql, assign_to} **只在数据分在不同的库、要按行对齐时用**:先在各自的库里用 SQL 聚合到相同的键和粒度(比如「日期 + 门店」), 再由 merge 按键合并。同一个库里的数据写成一条 SQL(JOIN / WITH),不要拆成两次查询再合并;只组合几个单值时 @@ -201,7 +174,19 @@ NODE_REFERENCE = """\ **不要写 scope**。记忆域由平台给(当前统一是 default)。自己起一个域的后果是 写进去再也读不回来——真发生过:一轮写进 scope"user",下一轮没写 scope 落回 default,于是「我叫张三」存下来了,问「我是谁」却答不上来 -- human:人工审批。config: {mode: approve|input|edit, title, message} +- human:人工审批。config: {mode: approve|input|edit, title, message, assignee, policy, due, on_timeout, form, form_from, + correlation}。后面几项是流程应用用的(写在图里,属于流程语义);画布试运行、定时任务里没有应用绑定,一律派给任何人, + 和不写一样: + · assignee 谁来处理:{kind:"slot", slot:"finance"}(岗位:图里只写岗位名,岗位绑到哪些人或组由人在应用里做,不要写 + 具体的人)/ {kind:"initiator"}(发起人)/ {kind:"expression", expr:"input.manager"}(只能取输入和变量,结果是用户名 + 或组名)/ {kind:"hook", correlation:"…"}(等外部系统回调) + · policy 怎么汇总:any(默认,第一个人处理就算)/ all(全体同意才通过,任何一人驳回即否决)/ {quorum: m}(m 人同意 + 即通过)。all 和 quorum 只用于 approve 模式 + · due 时限,ISO 8601 时长(PT4H、P2D),从待办打开时算起;on_timeout 超时怎么办:{action:"remind", every:"PT1H"} / + {action:"escalate", to_slot:"director"}(写明升级给哪个岗位)/ {action:"reject"},没有自动批准 + · form 静态表单(agentlab.form/1:{type:"object", properties:{字段:{type, title, enum…}}, required:[…]},只有一层, + 不支持 pattern);form_from 引用上游 agent 拟的表单("nodes.agent1.form"),不合规时退回 form + · correlation 只用于 assignee 是 hook 的:模板如 "{{ input.order_id }}",外部系统按它找到这条待办 title、message 说批了会怎样时写「批准后输出」「批准后继续」,**不要写「正式出具」「批准后才会出具」**:出具只发生在 成果节点配了出具契约、并且从已发布版本发起的正式运行里;画布上试运行、问数据都是探索运行,批准后只是输出。 这次是探索运行还是正式运行,审批卡会自己标明。审的是报告时把 human 接在 report 后面(message 里可以引用 @@ -464,6 +449,8 @@ async def _history_section(session: AsyncSession, conversation_id: str | None) - 实测这种重建经常接到另一张表上,答案对不上前一轮,用户完全无从判断。 图走 _slim 去掉坐标噪音,和 base_graph 那条路径用的是同一份。 + + 上一轮查看过的对象(前端存在这一轮的 meta.looks 里)写一行:追问时模型直接点名看,不用再按需求挑(look 文档 D7)。 """ from app.api.conversations import _answer_of, recent_turns @@ -489,9 +476,36 @@ async def _history_section(session: AsyncSession, conversation_id: str | None) - "\n\n上一轮用的工作流(数据源和表都已经对好了):\n" f"{json.dumps(_slim(last_graph), ensure_ascii=False, indent=2)}" ) + if looked := _looked_line(turns[-1]): + block += "\n\n" + looked return block +LOOKED_PROMPT = "上一轮查看过:{items}(要再看时直接点名)" +LOOKED_KIND_PROMPT = {"capability": "能力 {names}", "workflow_version": "工作流版本 {names}"} + + +def _looked_line(turn: Any) -> str: + """上一轮 meta.looks 里查看过的对象,一行:「上一轮查看过:库 B 的 refunds、orders;能力 x」。没查看过是空串。""" + from app.api.conversations import turn_meta + + looks = (turn_meta(turn) or {}).get("looks") + parts: list[str] = [] + for look in looks if isinstance(looks, list) else []: + for obj in (look.get("objects") or []) if isinstance(look, dict) else []: + if not isinstance(obj, dict): + continue + names = [n for key in ("named", "picked", "joined") for n in obj.get(key) or [] if isinstance(n, str)] + if not names: + continue + kind = obj.get("kind") + text = (f"{obj.get('source')} 的 " + "、".join(names) if kind == "table" and obj.get("source") + else LOOKED_KIND_PROMPT.get(str(kind), "{names}").format(names="、".join(names))) + if text not in parts: + parts.append(text) + return LOOKED_PROMPT.format(items=";".join(parts)) if parts else "" + + def _with_history(user: str, history: str) -> str: """历史垫在请求前面。空历史时原样返回,不留一个空标题。""" return f"{history}\n\n---\n\n{user}" if history else user @@ -727,90 +741,96 @@ GRAPH_SCHEMA: dict[str, Any] = { } +def _graph_system(sources: list[Any], scope: set[str] | None, datasources: str, looks: Any) -> str: + """画布、问数据(流式和非流式)共用的 system:节点手册、工具清单、数据源概览、结构要求、输出协议、查看的用法。 + 这一份一直用到自查修正结束(接着写、修正轮都不换),模型前后看到的是同一套说法。""" + return ( + "你是一个 agent 工作流编排专家。根据用户需求,以操作流的方式逐步搭出一张可执行的工作流图。\n\n" + f"{NODE_REFERENCE}\n\n可用工具:\n{_tool_catalog(sources)}" + f"{datasources}{_scope_note(sources, scope is not None)}\n\n" + "结构要求:\n" + "1. 必须有且只有一个 input 节点和至少一个 output 节点\n" + "2. 节点 id 用简短英文小写下划线;label 用中文,一眼看懂\n" + "3. 用 assign_to 传结果,下游 {{ vars.变量名 }} 引用\n" + "4. 只能用上面列出的工具名\n" + "5. 能用 3 个节点解决就别堆 8 个\n\n" + f"{_STREAM_PROTOCOL}" + + (f"\n\n{looks.guide()}\n{copilot_context.LOOK_WHEN_PROMPT}" if looks.kinds else "") + ) + + +def _graph_request(payload: GenerateIn) -> str: + """这一轮的请求:改现有图时附上原图、只要改动操作;新建时按入口包好(_user_message)。""" + if payload.base_graph and payload.base_graph.get("nodes"): + return ( + "这是当前的工作流:\n" + f"{json.dumps(_slim(payload.base_graph), ensure_ascii=False, indent=2)}\n\n" + f"请按下面的要求修改它(只输出改动操作):\n{payload.instruction}" + ) + return _user_message(payload, patch=False) + + +def _start_graph(payload: GenerateIn) -> tuple[dict[str, dict[str, Any]], list[dict[str, Any]]]: + """服务端维护的图状态:修改场景从 base_graph 起步(拷一份再改:改之前的样子还要留着比对工具绑定),新建从空图起步。""" + if not (payload.base_graph and payload.base_graph.get("nodes")): + return {}, [] + nodes = {n["id"]: copy.deepcopy(n) for n in payload.base_graph["nodes"]} + edges = [{k: v for k, v in e.items() if k in ("source", "target", "sourceHandle")} + for e in payload.base_graph.get("edges") or []] + return nodes, edges + + @router.post("/generate", response_model=GenerateOut) async def generate( payload: GenerateIn, session: AsyncSession = Depends(get_session) ) -> GenerateOut: - """用自然语言生成或改写一张工作流图。 + """用自然语言生成或改写一张工作流图,一次返回整张图。 - 产物会经过和手工编排完全相同的校验与排版,所以生成完就是可运行、可读的, - 而不是一段还要人去修的 JSON。 + 和流式生成走同一个生成过程(copilot_gen:起草、按需查看、自查修正),只是不推送过程,收完再排版、校验后返回。 + 产物会经过和手工编排完全相同的校验与排版,所以生成完就是可运行、可读的。 """ + from app.data.sqlcheck import load_checkers + sources = await _sources(session, payload.datasource_ids) scope = {r.name for r in sources} if payload.datasource_ids else None - # 先拿模型:没配好就直接 400,不白花一次挑表 + # 先拿模型:没配好就直接 400,不白读一遍目录 try: - model, _ = await get_chat_model(session, await copilot_model_spec(session, payload)) + model, _ = await _op_model(session, payload) except ProviderNotConfigured as e: raise HTTPException(400, _unconfigured(e)) from e - # 和流式生成同一套数据源上下文,只是不发 context 操作(这条接口一次返回整张图) - context = await _datasource_context( - session, sources, payload, need=await _pick_need(session, payload), - graph=payload.base_graph if (payload.base_graph or {}).get("nodes") - else await _previous_graph(session, payload.conversation_id)) - tool_list = _tool_catalog(sources, context) - datasources = context.section() + _scope_note(sources, scope is not None) - - system = ( - "你是一个 agent 工作流编排专家。根据用户需求产出一张可执行的工作流图。\n\n" - f"{NODE_REFERENCE}\n\n可用工具:\n{tool_list}{datasources}\n\n" - "要求:\n" - "1. 必须有且只有一个 input 节点和至少一个 output 节点\n" - "2. 节点 id 用简短英文小写下划线,例如 fetch_data、summarize\n" - "3. 每个节点写清楚 label(中文),让人在画布上一眼看懂它干什么\n" - "4. 需要把结果传给下游时,用 assign_to 命名变量,下游用 {{ vars.变量名 }} 引用\n" - "5. 不要凭空发明工具名,只能用上面列出的\n" - "6. 结构尽量简单:能用 3 个节点解决就别堆 8 个" - ) - - if payload.base_graph and payload.base_graph.get("nodes"): - user = ( - "这是当前的工作流:\n" - f"{json.dumps(_slim(payload.base_graph), ensure_ascii=False, indent=2)}\n\n" - f"请按下面的要求修改它,返回完整的新图(不是补丁):\n{payload.instruction}" - ) - else: - user = _user_message(payload, patch=False) - - messages = [("system", system), - ("human", _with_history(user, await _history_section(session, payload.conversation_id)))] + checkers = await load_checkers(session, sources) + prev_graph = await _previous_graph(session, payload.conversation_id) + looks = await _look_service(session, payload, sources, graph=payload.base_graph if ( + payload.base_graph or {}).get("nodes") else prev_graph) + system = _graph_system(sources, scope, await copilot_context.section(looks), looks) + nodes, edges = _start_graph(payload) + baseline = copy.deepcopy((payload.base_graph or {}).get("nodes") or (prev_graph or {}).get("nodes") or []) + applier = GraphApplier(nodes, edges, patches=False) + gen = Generation(model, system=system, applier=applier, looks=looks, + checker=GraphChecker(applier, scope=scope, sources=sources, baseline=baseline, checkers=checkers)) + human = _with_history(_graph_request(payload), await _history_section(session, payload.conversation_id)) try: - raw = await model.with_structured_output(GRAPH_SCHEMA).ainvoke(messages) - if not isinstance(raw, dict): - raw = json.loads(message_text(raw)) - except Exception: # noqa: BLE001 - 不支持结构化输出的模型退回文本解析 - try: - text = message_text(await model.ainvoke(messages)) - raw = _extract_json(text) - except Exception as e: # noqa: BLE001 - reason, _ = explain_error(e) - raise HTTPException( - 502, f"模型未返回可用的工作流({reason})。请换一种描述重试;如反复出现," - "请在输入框的「助手使用的模型」中换用指令遵循能力更强的模型", - ) from e - - graph = { - "nodes": [ - { - "id": n.get("id") or f"node{i}", - "type": n.get("type") or "llm", - "position": {"x": 0, "y": 0}, - "data": {"label": n.get("label") or "", "config": n.get("config") or {}}, - } - for i, n in enumerate(raw.get("nodes") or []) - ], - "edges": [ - { - "source": e.get("source", ""), - "target": e.get("target", ""), - "sourceHandle": e.get("sourceHandle"), - } - for e in (raw.get("edges") or []) - ], - } + async for _op in gen.draft(human): + pass + if applier.replied is None and gen.asked is None and all(o.get("op") == "plan" for o in applier.seen): + raise CopilotIncomplete("模型没有给出任何修改,也没有说明原因") + except Exception as e: # noqa: BLE001 + reason, _ = explain_error(e) + raise HTTPException( + 502, f"模型未返回可用的工作流({reason})。请换一种描述重试;如反复出现," + "请在输入框的「助手使用的模型」中换用指令遵循能力更强的模型", + ) from e + if applier.replied is not None: + # 这句话不需要工作流:原图照旧,回答放在说明里 + return GenerateOut(graph=payload.base_graph or {"nodes": [], "edges": []}, + explanation=str(applier.replied.get("text") or "")) + if not nodes and prev_graph: + applier.replay_onto(prev_graph) + async for _op in gen.repair(): + pass try: - spec = GraphSpec.model_validate(graph) + spec = GraphSpec.model_validate({"nodes": list(nodes.values()), "edges": edges}) except Exception as e: # noqa: BLE001 raise HTTPException( 502, f"模型返回的工作流结构有误:{graph_error(e)}。请重试,或把需求描述得更具体", @@ -819,10 +839,11 @@ async def generate( spec, layout = _layout_keeping(spec, _pinned_positions(payload.base_graph)) report = validate_graph(spec) out = spec.model_dump(mode="json") - changes = tool_changes((payload.base_graph or {}).get("nodes") or [], out["nodes"]) + changes = tool_changes(baseline, out["nodes"]) return GenerateOut( graph=out, - explanation=str(raw.get("explanation", "")), + # 模型问了用户(ask):这一轮到此为止,问题放在说明里 + explanation=applier.explanation or str((gen.asked or {}).get("question") or ""), issues=[i.model_dump() for i in report.issues if i.level != "info"] + _issue_dicts(scope_issues(out["nodes"], scope), "datasource_out_of_scope") + dropped_tool_warnings(changes, payload.instruction), @@ -858,6 +879,10 @@ _STREAM_PROTOCOL = """\ - 如果这句话根本不需要工作流(见下面的路径约定),**第一行也是最后一行**就输出: {"op":"reply","text":"直接回答的内容"} 这时除了下面的 catalog_patch,不要输出任何别的操作 +- 要看表结构、能力的参数这类详情时输出一行 look(用法见后面的「按需查看」),输出之后就停下等查看结果, + 拿到结果再接着写;已经输出的操作不要重复 +- 必须先问清用户才能动手时,输出一行 {"op":"ask","question":"要问的话,把候选列出来"},这一轮就此结束:已经输出的改动 + 照常交付,用户的回答是下一轮。能按常理定的不要问 - 数据目录修改提案(可选):用户在这句话里**明确陈述了一条数据事实**时,另输出一行 {"op":"catalog_patch","source":"数据源名","table":"表名","changes":[{"path":"…","value":…,"reason":"一句话依据"}]} 它只是提案,用户确认后才写进数据目录。可以和图操作一起出现(写在 done 之前),也可以只配一行 reply(写在 reply 之前) @@ -871,25 +896,11 @@ _STREAM_PROTOCOL = """\ · 例:「在园人数是存量,不能跨天相加」→ columns.<那一列>.measure 写 stock;「status=9 表示作废,统计时要排除」→ columns.status.codes 写 {"9":"作废"},再把 valid_filter 补上排除条件;「channel_visits 是渠道和入园记录的关联表」→ description 和两条 relations.new - · 只有用户明确说出了数据事实才提,不要从自己的推测、查询结果或提问里提;表名、列名必须是上面数据源里真实存在的 + · 只有用户明确说出了数据事实才提,不要从自己的推测、查询结果或提问里提;表名、列名必须是数据源里真实存在的 + (先 look 那张表,看清现有目录再提) · 计算公式不进数据目录:「转化率=下单数/访问数」这类指标怎么算的说法属于口径卡,不要提""" -def _parse_op_line(line: str) -> dict[str, Any] | None: - """解析一行操作。围栏行、空行、解析失败、缺 op 的一律返回 None—— - 模型偶尔犯规不该毁掉整条流,跳过就是。""" - text = line.strip() - if not text or text.startswith("```"): - return None - try: - obj = json.loads(text) - except json.JSONDecodeError: - return None - if not isinstance(obj, dict) or "op" not in obj: - return None - return obj - - #: 模型只发了目录修改提案、既没回答也没改图时,补的那句回答 PATCH_ONLY_REPLY = "已按你的说明整理出数据目录的修改建议,确认无误后可保存到数据目录。" @@ -940,137 +951,6 @@ async def catalog_patch_op(op: dict[str, Any], sources: list[Any]) -> dict[str, } -_NODE_TYPES = frozenset(t.value for t in NodeType) - -#: 协作成员条目里写 "remove": true 就把这个成员拿掉。不复用 null:null 在合并里 -#: 的意思是「删这个字段」,成员本身不是一个字段 -_REMOVE_MEMBER = "remove" - - -def _member_key(member: dict[str, Any], index: int) -> str: - # 和 engine/nodes/multi.py 的叫法一致:没起名字的成员按位置叫 agentN - return str(member.get("name") or f"agent{index}") - - -def _merge_fields(old: dict[str, Any], patch: dict[str, Any]) -> dict[str, Any]: - """按字段合并:写了的覆盖,写 null 的删掉,没写的原样保留。返回新 dict。""" - out = dict(old) - for key, value in patch.items(): - if value is None: - out.pop(key, None) - else: - out[key] = value - return out - - -def _merge_members(old: list[Any], patch: list[Any]) -> list[Any]: - """协作成员按 name 合并。原有成员保持原来的次序,新名字接在后面。""" - merged: list[Any] = list(old) - where = {_member_key(m, i): i for i, m in enumerate(merged) if isinstance(m, dict)} - dropped: set[int] = set() - for i, entry in enumerate(patch): - if not isinstance(entry, dict): - continue - key = _member_key(entry, i) - if entry.get(_REMOVE_MEMBER) is True: - if key in where: - dropped.add(where[key]) - continue - fields = {k: v for k, v in entry.items() if k != _REMOVE_MEMBER} - if key in where: - merged[where[key]] = _merge_fields(merged[where[key]], fields) - else: - where[key] = len(merged) - merged.append({k: v for k, v in fields.items() if v is not None}) - return [m for i, m in enumerate(merged) if i not in dropped] - - -def merge_node_config( - node_type: str, old: dict[str, Any], patch: dict[str, Any] -) -> dict[str, Any]: - """update_node 的 config 怎么落到节点上。前端 store/studio.ts 必须是同一套规则。 - - 以前是整体替换:模型只想改一句提示词,照协议也得把整份 config 抄一遍, - 漏抄的字段就没了。真出过事——改写提示词时漏了 tools,三个要查库的 agent - 全丢了工具,一次库都没查,最后把一堆工具调用的原始标记当答案交了出去。 - 改成按字段合并之后,漏写等于不改;真要删一个字段得显式写 null。 - """ - if node_type == NodeType.SUPERVISOR.value and isinstance(patch.get("agents"), list): - members = old.get("agents") if isinstance(old.get("agents"), list) else [] - patch = {**patch, "agents": _merge_members(members, patch["agents"])} - return _merge_fields(old, patch) - - -def _apply_op(nodes: dict[str, dict[str, Any]], edges: list[dict[str, Any]], op: dict[str, Any]) -> bool: - """把一个操作应用到服务端维护的图状态。返回是否真的改了图。""" - kind = op.get("op") - if kind == "add_node": - node = op.get("node") or {} - # 类型不认识的节点不进图、也不转给前端:前端按类型查节点定义,查不到 - # 以前是整站白屏,连带没保存的编辑一起丢 - if not node.get("id") or node.get("type") not in _NODE_TYPES: - return False - nodes[node["id"]] = { - "id": node["id"], - "type": node["type"], - "position": {"x": 0, "y": 0}, - "data": {"label": node.get("label") or "", "config": node.get("config") or {}}, - } - return True - if kind == "update_node": - node = nodes.get(op.get("id") or "") - if not node: - return False - data = node.setdefault("data", {}) - if op.get("label") is not None: - data["label"] = op["label"] - if isinstance(op.get("config"), dict): - data["config"] = merge_node_config( - str(node.get("type") or ""), data.get("config") or {}, op["config"]) - return True - if kind == "remove_node": - node_id = op.get("id") - if node_id not in nodes: - return False - nodes.pop(node_id) - edges[:] = [e for e in edges if e["source"] != node_id and e["target"] != node_id] - return True - if kind == "add_edge": - edge = op.get("edge") or {} - if not edge.get("source") or not edge.get("target"): - return False - edges.append( - { - "source": edge["source"], - "target": edge["target"], - "sourceHandle": edge.get("sourceHandle"), - } - ) - return True - if kind == "remove_edge": - before = len(edges) - edges[:] = [ - e - for e in edges - if not ( - e["source"] == op.get("source") - and e["target"] == op.get("target") - and (op.get("sourceHandle") is None or e.get("sourceHandle") == op.get("sourceHandle")) - ) - ] - return len(edges) != before - return False - - -class CopilotIncomplete(Exception): - """模型这一轮没说完:输出被截断,或者一个操作都没给。画布不能按「无需修改」交付。""" - - def __init__(self, reason: str, *, hint: str = "", detail: str = "") -> None: - super().__init__(reason) - self.hint = hint or "画布未修改。可以重试,或把需求拆成几步分别提出" - self.detail = detail - - #: 流式改图的输出额度。会思考的模型(DeepSeek、Claude 的 adaptive thinking)思考也算在里面: #: 8192 时复杂的改图常常想完就没额度了,正文一个字没写(2026-09 部署实例上同类请求 5 轮坏了 4 轮) COPILOT_MAX_TOKENS = 32768 @@ -1087,53 +967,6 @@ async def _op_model(session: AsyncSession, payload: GenerateIn) -> tuple[Any, st return _BudgetFallback(big, small), model_id -async def _iter_ops(model: Any, messages: list[Any]): - """流式读模型输出,按行切出操作。done 之后即停——后面就算有闲话也不要了。 - - 除了操作,还把模型的思考原样转出去。原先这里只取正文、丢掉其余一切, - 于是从请求发出到第一个操作到达之间(实测 5~30 秒)前端一个字都收不到, - 只能干挂着"正在起草…"——用户没法判断是在想、还是已经卡死了。 - - 思考走 thinking_text()(Claude 4.6+ 的 thinking 块),不是"把非 JSON 行 - 当成思考":后者会把模型的 markdown 注释、协议跑偏时的乱输出一并当作思考 - 展示出来,反而误导。不支持 thinking 的模型就只有心跳,不硬凑。 - - 没等到 done 就因为额度用完停下的,抛 CopilotIncomplete:截断之前的操作照常转出去, - 由调用方决定整轮作废。 - """ - from app.engine.state import message_text as _text - from app.engine.state import thinking_text - - buffer = "" - cut = "" - async for chunk in model.astream(messages): - reasoning = thinking_text(chunk) - if reasoning: - yield {"op": "thinking", "delta": reasoning} - - buffer += _text(chunk) - while "\n" in buffer: - line, buffer = buffer.split("\n", 1) - op = _parse_op_line(line) - if op: - yield op - if op.get("op") == "done": - return - cut = _cut_off(chunk) or cut - op = _parse_op_line(buffer) - if op: - yield op - if op.get("op") == "done": - return - if cut: - # 截断的流和说完了的流读起来一模一样:不在这里拦下,上面就会拿原图(或半张图) - # 去自查、交付,界面上写「无需修改」 - limit = getattr(model, "max_tokens", None) - raise CopilotIncomplete( - "模型的输出超出了长度上限,修改没有写完", - detail=f"finish_reason={cut}" + (f",本轮输出上限 {limit} token" if limit else "")) - - # 多久没动静就补一拍心跳。3 秒是"用户开始怀疑是不是卡了"的量级。 _HEARTBEAT_SECONDS = 3.0 @@ -1144,8 +977,8 @@ async def _with_heartbeat(source: Any, phase: str = "planning", *, started: floa 必须在这一层做而不是在 _iter_ops 里判断时间差:模型不吐 chunk 时那个 async for 的循环体根本不执行,压根轮不到检查。 - started 给了就从那一刻算已用时长:流式生成先挑表、再起草,两段的心跳要接着算, - 不能起草一开始就跳回 0 秒。 + started 给了就从那一刻算已用时长:起草、查看、接着写、自查修正几段的心跳要接着算, + 不能每一段一开始就跳回 0 秒。 """ started = time.monotonic() if started is None else started iterator = source.__aiter__() @@ -1159,13 +992,17 @@ async def _with_heartbeat(source: Any, phase: str = "planning", *, started: floa except StopAsyncIteration: return kind = op.get("op") - # 阶段跟着实际操作走,前端据此换文案 - if kind == "add_node": + # 阶段跟着实际操作走,前端据此换文案。查看时生成过程自己发一拍 looking,查看完回到 planning + if kind == "add_node" or kind in APP_OPS: phase = "building" elif kind in ("add_edge", "connect"): phase = "wiring" elif kind == "done": phase = "finalizing" + elif kind == "heartbeat": + phase = op.get("phase") or phase + elif kind == "look": + phase = "planning" yield op break yield { @@ -1175,23 +1012,6 @@ async def _with_heartbeat(source: Any, phase: str = "planning", *, started: floa } -async def _heartbeat_until(task: asyncio.Future, *, started: float, phase: str = "planning"): - """等 task 做完,期间按拍出心跳(同 _with_heartbeat)。结果由调用方取 task.result()。 - - 流式生成在流里挑表时用:挑表最长要等 copilot_context.PICK_TIMEOUT_S,这段时间不出声, - 前端就只能干挂着「正在连接模型」。阶段算「理解需求」:挑表正是在读需求。 - """ - while not task.done(): - done, _ = await asyncio.wait({task}, timeout=_HEARTBEAT_SECONDS) - if not done: - yield {"op": "heartbeat", "phase": phase, "elapsed_ms": int((time.monotonic() - started) * 1000)} - - -#: 自查最多交回去改几轮。一轮只花一次"只输出改动"的调用;两轮还改不好,多半是 -#: 需求本身有歧义,该让人看了,而不是继续替他烧钱 -_SELF_CHECK_ROUNDS = 2 - - def _sse(obj: dict[str, Any]) -> str: return f"data: {json.dumps(obj, ensure_ascii=False)}\n\n" @@ -1777,13 +1597,13 @@ def dropped_tool_warnings(changes: list[dict[str, Any]], instruction: str) -> li def _repair_request( - nodes: dict[str, dict[str, Any]], edges: list[dict[str, Any]], errors: list[dict[str, Any]], + nodes: dict[str, dict[str, Any]], edges: list[dict[str, Any]], errors: list[dict[str, Any]], *, looks: str = "", ) -> str: - """自查交回修正的请求:只写图和问题。 + """自查交回修正的请求:图、问题,和这一轮查看过的结果(look 文档 D8:和起草时看到的是同一份文字)。 - 数据源上下文(挑中的表、字段、目录、连接条件)在 system 里,修正轮和起草用同一条 system, - 不重新挑表:两次挑出来的表不一样,模型前后看到的结构就对不上,改着改着换了一张表。 - 猜错的列名由 sql_unknown_column 的 for_model 带回那几张表的真实列。 + 修正轮和起草用同一条 system;查看结果在起草那段对话里,修正是另起的一段,所以原样带上,模型不用再看一遍。 + 修正时还可以再看 1 次(比如 sql_unknown_column 指向了一张没看过的表)。猜错的列名由 sql_unknown_column 的 + for_model 带回那几张表的真实列。 """ graph = {"nodes": list(nodes.values()), "edges": edges} return ( @@ -1794,6 +1614,7 @@ def _repair_request( + "\n\n只修这些问题,别的不要动。用操作流输出修正:改节点用 update_node" "(config 只写要改的字段,没写的保持原样;要删掉一个字段写 null);" "缺节点、缺边就补上。最后一行输出 done。" + + (f"\n\n这一轮查看过的结构(和起草时看到的是同一份):\n{looks}" if looks else "") ) @@ -1801,8 +1622,9 @@ def _repair_request( async def generate_stream(payload: GenerateIn, session: AsyncSession = Depends(get_session)): """流式版生成:SSE 逐操作推送,前端边收边把节点摆上画布。 - 结束时(done 或流断)发一条 final:服务端把累积的图排版、校验后整体给出—— - 过程可见性来自操作流,最终质量仍由和手工编排相同的 layout + validate 保证。 + 生成过程(copilot_gen)读到 look 就停下、查看、接着写,查看记录作为 look 事件发给前端(前端存进这一轮的 + meta.looks)。结束时(done 或流断)发一条 final:服务端把累积的图排版、校验后整体给出——过程可见性来自操作流, + 最终质量仍由和手工编排相同的 layout + validate 保证。模型问了用户(ask)的,这一轮到此为止,不自查修正、不自动运行。 """ from fastapi.responses import StreamingResponse @@ -1812,134 +1634,59 @@ async def generate_stream(payload: GenerateIn, session: AsyncSession = Depends(g scope = {r.name for r in sources} if payload.datasource_ids else None # 基于数据目录的 SQL 检查器:在开流之前读好目录(流里不再碰这个会话),自查和收尾共用 checkers = await load_checkers(session, sources) - - def system_for(context: copilot_context.DatasourceContext) -> str: - return ( - "你是一个 agent 工作流编排专家。根据用户需求,以操作流的方式逐步搭出一张可执行的工作流图。\n\n" - f"{NODE_REFERENCE}\n\n可用工具:\n{_tool_catalog(sources, context)}" - f"{context.section()}{_scope_note(sources, scope is not None)}\n\n" - "结构要求:\n" - "1. 必须有且只有一个 input 节点和至少一个 output 节点\n" - "2. 节点 id 用简短英文小写下划线;label 用中文,一眼看懂\n" - "3. 用 assign_to 传结果,下游 {{ vars.变量名 }} 引用\n" - "4. 只能用上面列出的工具名\n" - "5. 能用 3 个节点解决就别堆 8 个\n\n" - f"{_STREAM_PROTOCOL}" - ) - - # 现有图状态:修改场景从 base_graph 起步,新建场景从空图起步 - nodes: dict[str, dict[str, Any]] = {} - edges: list[dict[str, Any]] = [] + nodes, edges = _start_graph(payload) # 用户摆好的坐标,收尾排版时原样留着 pinned = _pinned_positions(payload.base_graph) - if payload.base_graph and payload.base_graph.get("nodes"): - # 拷一份再改:改之前的样子还要留着比对工具绑定有没有被改掉 - for n in payload.base_graph["nodes"]: - nodes[n["id"]] = copy.deepcopy(n) - edges = [ - {k: v for k, v in e.items() if k in ("source", "target", "sourceHandle")} - for e in payload.base_graph.get("edges") or [] - ] - user = ( - "这是当前的工作流:\n" - f"{json.dumps(_slim(payload.base_graph), ensure_ascii=False, indent=2)}\n\n" - f"请按下面的要求修改它(只输出改动操作):\n{payload.instruction}" - ) - else: - user = _user_message(payload, patch=False) try: model, model_id = await _op_model(session, payload) except ProviderNotConfigured as e: raise HTTPException(400, _unconfigured(e)) from e - human = _with_history(user, await _history_section(session, payload.conversation_id)) + human = _with_history(_graph_request(payload), await _history_section(session, payload.conversation_id)) # 兜底用:模型只发了改动操作时,把它们重放到这张图上 prev_graph = await _previous_graph(session, payload.conversation_id) # 比对工具绑定的基准:画布上是改之前的图;问数据页是上一轮的图(沿用它的节点 id) baseline = copy.deepcopy( (payload.base_graph or {}).get("nodes") or (prev_graph or {}).get("nodes") or []) - # 数据源上下文:读目录、拿挑表模型都要用请求的会话,开流之前做完;挑表本身放进流里,期间照常发心跳。 - # 现有工作流(画布上的原图、问数据追问时上一轮的图)查过的表一律给全字段 - plan = await copilot_context.plan_context( - sources, graph=payload.base_graph if (payload.base_graph or {}).get("nodes") else prev_graph) - picker, unavailable = await _picker(session, payload, plan) - need = await _pick_need(session, payload) + # 查看服务:读目录、读能力登记在开流之前做完。现有工作流(画布上的原图、问数据追问时上一轮的图)查过的表列在概览里 + looks = await _look_service(session, payload, sources, graph=payload.base_graph if ( + payload.base_graph or {}).get("nodes") else prev_graph) + # 这一份 system 一直用到最后:接着写、自查修正都沿用,不换 + system = _graph_system(sources, scope, await copilot_context.section(looks), looks) + applier = GraphApplier(nodes, edges) + started = time.monotonic() + gen = Generation(model, system=system, applier=applier, looks=looks, started=started, + checker=GraphChecker(applier, scope=scope, sources=sources, baseline=baseline, checkers=checkers)) async def event_stream(): - explanation = "" - seen_ops: list[dict[str, Any]] = [] - skipped_types: list[str] = [] - # 建完要不要跑,由模型在 done.run 里表态 - autorun = True - yield f"data: {json.dumps({'op': 'model', 'model': model_id}, ensure_ascii=False)}\n\n" - # 大库先按需求挑表。resolve 自己兜住了挑表的所有失败(退回只列表名),这里的 except 只防组装出意外: - # 挑表是让模型少猜,不能因为它让这一轮生成失败 - started = time.monotonic() - pending = asyncio.ensure_future(plan.resolve(picker, need=need, unavailable=unavailable)) - try: - async for beat in _heartbeat_until(pending, started=started): - yield _sse(beat) - context = pending.result() - except Exception as e: # noqa: BLE001 - context = plan.fallback(f"组装数据源上下文时出错:{explain_error(e)[0]}") - finally: - # 用户中途断开时流在上面的 yield 处被关掉,挑表的调用不能留在后台接着等 - if not pending.done(): - pending.cancel() - # 这一份 system 一直用到最后:自查交回修正时沿用同一份上下文,不重新挑表 - system = system_for(context) - messages = [("system", system), ("human", human)] - if (shown := context.op()) is not None: - yield _sse(shown) - # reply 先压着:模型可能把目录修改提案写在 reply 后面,而前端收到 reply 就收尾(画布那边之后的操作一律不收), - # 提案得排在它前面转出。reply 之后只再认 catalog_patch,其余一概不理 - replied: dict[str, Any] | None = None + yield _sse({"op": "model", "model": model_id}) patches = 0 try: - async for op in _with_heartbeat(_iter_ops(model, messages), started=started): - kind = op.get("op") - # 思考和心跳不是图操作,不进 _apply_op,直接转给前端 - if kind in ("thinking", "heartbeat"): - yield f"data: {json.dumps(op, ensure_ascii=False)}\n\n" - continue - if kind == "catalog_patch": - # 目录修改提案:核对后转给前端做成卡片,人点「保存」才写。不进图,也不算这一轮的图操作 + async for op in _with_heartbeat(gen.draft(human), started=started): + if op.get("op") == "catalog_patch": + # 目录修改提案:核对后转给前端做成卡片,人点「保存」才写。不进图,也不算这一轮的图操作。 + # reply 先压着(applier.replied):前端收到 reply 就收尾,提案得排在它前面转出 if (checked := await catalog_patch_op(op, sources)) is not None: patches += 1 yield _sse(checked) continue - if replied is not None: - continue - if kind == "reply": - # 这句话不需要工作流:等模型说完(只收它后面的提案)再转给前端、收流——后面那套 - # 排版校验对着一张空图跑,只会得到"图是空的,先拖一个节点进来" - replied = op - continue - if kind == "done": - explanation = str(op.get("explanation", "")) - # 用户要的是流程本身时("设计一个每天跑的工作流"), - # 建完就跑等于替他多花一次钱,而他要的是那张图 - autorun = op.get("run") is not False - seen_ops.append(op) - changed = _apply_op(nodes, edges, op) - if kind == "add_node" and not changed: - bad_type = (op.get("node") or {}).get("type") - if bad_type and bad_type not in _NODE_TYPES: - skipped_types.append(str(bad_type)) - if changed or kind in ("plan", "done"): - yield f"data: {json.dumps(op, ensure_ascii=False)}\n\n" - if replied is not None: - yield _sse(replied) + yield _sse(op) + if applier.replied is not None: + # 这句话不需要工作流:后面那套排版校验对着一张空图跑,只会得到"图是空的,先拖一个节点进来" + yield _sse(applier.replied) + return + if gen.asked is not None and not applier.effective: + # 先问清楚才能动手,什么都还没改:问题已经转出去了,这一轮到此为止 return # 只发了目录修改提案,既没回答也没改图(用户只是在说一条数据事实):补一句回答收尾, # 不能按下面的「模型没有给出任何修改」报错——提案已经摆在用户面前了 - if patches and all(o.get("op") == "plan" for o in seen_ops): + if patches and all(o.get("op") == "plan" for o in applier.seen): yield _sse({"op": "reply", "text": PATCH_ONLY_REPLY}) return # 流正常结束,却没有 done、也没有一个操作能认(格式跑偏,每一行都被跳过): # 往下走就是拿原图去自查、交付,界面上写「无需修改」——而模型什么都没说 - if all(o.get("op") == "plan" for o in seen_ops): + if gen.asked is None and all(o.get("op") == "plan" for o in applier.seen): raise CopilotIncomplete("模型没有给出任何修改,也没有说明原因", hint="画布未修改。可以重试,或把需求描述得更具体") except CopilotIncomplete as e: @@ -1957,49 +1704,21 @@ async def generate_stream(payload: GenerateIn, session: AsyncSession = Depends(g # 而累加器是从空图起步的,那些操作全落在不存在的节点上。上面的 prompt # 已经要求它完整重发,但那是约定,不是保证——约定落空的代价是用户收到 # 一句"图是空的,先拖一个节点进来",而他只是问了句追问。 - # - # 与其报错,不如按它本来的意思做:把这些操作重放到上一轮那张图上。 - if not nodes and prev_graph and seen_ops: - for n in prev_graph.get("nodes") or []: - if n.get("id"): - nodes[n["id"]] = copy.deepcopy(n) - # 原地改,不能重新绑定:给 edges 赋值会让它变成 event_stream 的局部 - # 变量,而它在上面 _apply_op 那一路已经被读过了 —— UnboundLocalError - edges[:] = [ - {k: v for k, v in e.items() if k in ("source", "target", "sourceHandle") and v} - for e in prev_graph.get("edges") or [] - ] - for op in seen_ops: - _apply_op(nodes, edges, op) + if not nodes and prev_graph and applier.seen: + applier.replay_onto(prev_graph) # 自查:按运行时同一套规则把图过一遍,挡住运行的问题交回模型改,改完再查。 # 以前这些问题照样交付、照样自动开跑——跑到那一步才炸(开发库里四次运行死在 # 循环 / 分支条件里套了 {{ }}),前面的步骤白跑,报错还停在半路 - repaired = 0 - for round_no in range(1, _SELF_CHECK_ROUNDS + 1): - errors = _blocking_issues(nodes, edges, scope, sources=sources, baseline=baseline, checkers=checkers) - if not errors: - break - yield _sse({"op": "check", "status": "repairing", "round": round_no, "issues": errors}) - fix = [("system", system), ("human", _repair_request(nodes, edges, errors))] - try: - async for op in _with_heartbeat(_iter_ops(model, fix), phase="repairing"): - kind = op.get("op") - if kind in ("thinking", "heartbeat"): - yield _sse(op) - # plan / done 是修补轮自己的开场和收尾,不是新方案,不覆盖原来的说明 - elif kind not in ("plan", "done", "reply") and _apply_op(nodes, edges, op): - yield _sse(op) - except Exception as e: # noqa: BLE001 - 修不成就照实交付,下面列出剩下的问题 - yield _sse({"op": "check", "status": "error", - "message": f"自查修正失败:{explain_error(e)[0]}", "detail": raw_error(e)}) - break - repaired = round_no + async for op in _with_heartbeat(gen.repair(), phase="repairing"): + yield _sse(op) remaining = _blocking_issues(nodes, edges, scope, sources=sources, baseline=baseline, checkers=checkers) # 工具绑定变化不挡运行,但要在自查这一步就说出来:工具被改没了的图照样 # 能跑,只是跑出来的是模型「假设」查过库的答案 changes = tool_changes(baseline, list(nodes.values())) warnings = dropped_tool_warnings(changes, payload.instruction) + # 建完要不要跑,由模型在 done.run 里表态;问了用户的不跑:要等他回答 + autorun = applier.autorun and gen.asked is None if remaining: # 改不好也照实交付、列出问题,但不自动运行:明知跑不起来的图,开跑只会 # 在半路报一个用户看不懂的错 @@ -2007,7 +1726,7 @@ async def generate_stream(payload: GenerateIn, session: AsyncSession = Depends(g yield _sse({"op": "check", "status": "failed", "issues": remaining, "warnings": warnings}) elif remaining is not None: - yield _sse({"op": "check", "status": "passed", "repaired": repaired, + yield _sse({"op": "check", "status": "passed", "repaired": gen.repaired, "warnings": warnings}) # 收尾:排版 + 校验,把最终图整体交付。改图时旧节点留在原处,只排新节点 @@ -2030,13 +1749,13 @@ async def generate_stream(payload: GenerateIn, session: AsyncSession = Depends(g {"level": "warning", "node_id": None, "edge_id": None, "code": "unknown_node_type", "type": t, "message": f"模型使用了不存在的节点类型「{t}」,已跳过这一步"} - for t in dict.fromkeys(skipped_types) + for t in dict.fromkeys(applier.skipped_types) ] final = { "op": "final", "graph": spec.model_dump(mode="json"), "issues": issues + warnings, - "explanation": explanation, + "explanation": applier.explanation, "autorun": autorun, "layout": layout, # 改图回执:哪些节点、成员的工具变了。画布上看不出来,得明说 @@ -2045,7 +1764,7 @@ async def generate_stream(payload: GenerateIn, session: AsyncSession = Depends(g except Exception as e: # noqa: BLE001 final = {"op": "error", "message": f"模型返回的工作流结构有误:{graph_error(e)}", "hint": "请重试,或把需求描述得更具体", "detail": raw_error(e)} - yield f"data: {json.dumps(final, ensure_ascii=False)}\n\n" + yield _sse(final) return StreamingResponse( event_stream(), @@ -2105,24 +1824,51 @@ def _publish_fix_request(graph: dict[str, Any], errors: list[dict[str, Any]], le ) -def _publish_fix_need(errors: list[dict[str, Any]], level: str) -> str: - """发布前修复挑表用的需求:要过哪一级的发布前检查、挡着的是哪些问题。""" - return (f"让这张工作流通过「{_LEVEL_WORD.get(level, level)}」级别的发布前检查,挡住发布的问题:\n" - + "\n".join(f"- {_issue_line(i)}" for i in errors)) +def _assist_system(task: str, sources: list[Any], datasources: str, looks: Any) -> str: + """发布前修复、升级证据的 system:模型、工具目录、操作流协议都和画布上改图是同一套,另可以输出 question。""" + return ( + f"你是一个 agent 工作流编排专家。现在要做的是:{task},以操作流的方式输出修改。\n\n" + f"{NODE_REFERENCE}\n\n可用工具:\n{_tool_catalog(sources)}{datasources}\n\n" + f"{_STREAM_PROTOCOL}\n\n另外可以输出 question 操作:{{\"op\":\"question\",\"node_id\":\"…\",\"text\":\"…\"}}" + + (f"\n\n{looks.guide()}" if looks.kinds else "") + ) + + +async def _with_system_look(looks: Any, request: str, graph: dict[str, Any], sources: list[Any], *, + need: str) -> str: + """不需要人参与的路径由系统代为查看要修的 SQL 用到的表(look 文档 D5),结果接在请求后面:要查哪些表是确定的, + 系统直接查能省掉一轮。记录和模型自己查看的一样,留在 looks.records 里。""" + looked = await copilot_context.system_look(looks, graph, sources, need=need) + return f"{request}\n\n{looked.text}" if looked is not None else request + + +def _questions(applier: GraphApplier, before_nodes: dict[str, dict[str, Any]], + asked: dict[str, Any] | None = None) -> list[str]: + """模型要人拿主意的话,原样交给人看,前面标上是哪个节点的事(界面上认节点标题,不认 id)。模型用 ask 问的(这一轮 + 就此结束)也算一条。""" + out: list[str] = [] + ops = [*applier.questions, *([{"text": asked.get("question")}] if asked else [])] + for op in ops: + text = str(op.get("text") or "").strip() + where = before_nodes.get(str(op.get("node_id") or "")) + title = str((where.get("data") or {}).get("label") or where.get("id")) if where else "" + if text: + out.append(f"「{title}」:{text}" if title and title not in text else text) + return out async def assist_publish_fix( session: AsyncSession, graph: dict[str, Any], *, level: str, provider: str | None = None, model: str | None = None, ) -> dict[str, Any]: - """把挡住发布的 error 交给 Copilot 修。模型、工具目录、操作流协议都和画布上改图是同一套。 + """把挡住发布的 error 交给助手修。模型、工具目录、操作流协议都和画布上改图是同一套(生成过程 copilot_gen)。 - 拿回的操作在副本上应用,再按同一套规则复核(_blocking_issues 带上发布级别:validate、门禁, - 以及这一轮改过的节点里有没有凭空猜的列名):error 变少、没有新 error、没有降低要求的改动 - (autofix.forbidden_changes)才采纳,否则整个作废并写明原因。模型认为要人拿主意的,放进 + 要修的 SQL 用到的表由系统代为查看(look 文档 D5),模型仍然可以再看。拿回的操作在副本上应用,再按同一套规则复核 + (_blocking_issues 带上发布级别:validate、门禁,以及这一轮改过的节点里有没有凭空猜的列名):error 变少、没有新 + error、没有降低要求的改动(autofix.forbidden_changes)才采纳,否则整个作废并写明原因。模型认为要人拿主意的,放进 questions 原样交给人,不硬改。 - 返回 {accepted, reason, summary, questions(一句一条的文字), graph, ops}。不落库。 + 返回 {accepted, reason, summary, questions(一句一条的文字), graph, ops, looks}。不落库。 """ from app.engine.autofix import forbidden_changes, judge @@ -2138,7 +1884,7 @@ async def assist_publish_fix( errors = _blocking_issues(before_nodes, before_edges, sources=sources, baseline=baseline, level=level, defaults=base.get("defaults"), checkers=checkers) or [] out: dict[str, Any] = {"accepted": False, "reason": None, "summary": "", "questions": [], "graph": graph, - "ops": []} + "ops": [], "looks": []} if not errors: out["summary"] = "没有阻止发布的错误,无需交给助手" return out @@ -2148,52 +1894,33 @@ async def assist_publish_fix( except ProviderNotConfigured as e: out["summary"] = _unconfigured(e) return out - # 和画布上改图同一套数据源上下文:挑表的需求是挡住发布的这些问题,图里查过的表一律给全字段 - context = await _datasource_context(session, sources, request, need=_publish_fix_need(errors, level), graph=base) - - system = ( - "你是一个 agent 工作流编排专家。现在要做的是:让一张工作流过发布前检查,以操作流的方式输出修改。\n\n" - f"{NODE_REFERENCE}\n\n可用工具:\n{_tool_catalog(sources, context)}{context.section()}\n\n" - f"{_STREAM_PROTOCOL}\n\n另外可以输出 question 操作:{{\"op\":\"question\",\"node_id\":\"…\",\"text\":\"…\"}}" - ) + looks = await _look_service(session, request, sources, graph=base, kinds=("table",)) + system = _assist_system("让一张工作流过发布前检查", sources, await copilot_context.section(looks), looks) + human = await _with_system_look(looks, _publish_fix_request(base, errors, level), base, sources, + need=copilot_context.SYSTEM_LOOK_FIX_NEED) nodes = copy.deepcopy(before_nodes) edges = copy.deepcopy(before_edges) - tried: list[dict[str, Any]] = [] - effective: list[dict[str, Any]] = [] - plan = "" + # 目录修改提案只在用户亲口陈述数据事实时才有;这里的「用户消息」是系统拼的修复请求,提了也不转 + applier = GraphApplier(nodes, edges, patches=False, questions=True) + gen = Generation(chat, system=system, applier=applier, looks=looks) try: - async for op in _iter_ops(chat, [("system", system), ("human", _publish_fix_request(base, errors, level))]): - kind = op.get("op") - # 目录修改提案只在用户亲口陈述数据事实时才有;这里的「用户消息」是系统拼的修复请求,提了也不转 - if kind in ("thinking", "heartbeat", "catalog_patch"): - continue - if kind == "plan": - plan = str(op.get("summary") or "") - elif kind == "done": - out["summary"] = str(op.get("explanation") or "") - elif kind in ("question", "reply"): - text = str(op.get("text") or "").strip() - # 原样交给人看,前面标上是哪个节点的事(界面上认节点标题,不认 id) - where = before_nodes.get(str(op.get("node_id") or "")) - title = str((where.get("data") or {}).get("label") or where.get("id")) if where else "" - if text: - out["questions"].append(f"「{title}」:{text}" if title and title not in text else text) - else: - tried.append(op) - if _apply_op(nodes, edges, op): - effective.append(op) + async for _op in gen.draft(human): + pass except Exception as e: # noqa: BLE001 - 修不成就照实说,确定性修复的结果照样交给人 out["summary"] = f"助手本轮未完成:{explain_error(e)[0]}" return out - out["summary"] = out["summary"] or plan - if not effective: + finally: + out["looks"] = list(looks.records) + out["questions"] = _questions(applier, before_nodes, gen.asked) + out["summary"] = applier.explanation or str((applier.plan or {}).get("summary") or "") + if not applier.effective: # 没动图:要么全是要人拿主意的问题,要么它没给出能用的修改。都不算「拒绝」 out["summary"] = out["summary"] or ("助手认为这些问题需要由你决定" if out["questions"] else "助手本轮没有给出修改") return out proposed = _proposed_graph(base, nodes, edges) - reasons = forbidden_changes(base, proposed, tried) + reasons = forbidden_changes(base, proposed, applier.tried) after = _blocking_issues(_nodes_by_id(proposed), proposed.get("edges") or [], sources=sources, baseline=baseline, level=level, defaults=proposed.get("defaults"), checkers=checkers) if reasons: @@ -2203,7 +1930,7 @@ async def assist_publish_fix( elif why := judge(errors, after): out["reason"] = f"助手的修改未能改善工作流,已作废:{why}" else: - out.update(accepted=True, graph=proposed, ops=effective) + out.update(accepted=True, graph=proposed, ops=applier.effective) return out @@ -2277,12 +2004,6 @@ def _upgrade_assist_request(graph: dict[str, Any], spec: GraphSpec, feeders: lis ) -def _upgrade_need(feeders: list[Any]) -> str: - """升级挑表用的需求:哪几段沙箱代码要改写成口径卡表达式(改写要用到上游查库节点查出的列)。""" - return ("把喂给口径卡的纯算术沙箱代码改写成口径卡表达式,表达式直接读上游查库节点查出的列。涉及的代码节点:" - + "、".join(f"「{code.title}」" for code, _cards in feeders)) - - def _kept_code(spec: GraphSpec) -> list[str]: """assist 之后仍然喂着口径卡的计算角色沙箱代码:不是纯算术、或者 Copilot 拿不准的,保留原样并警告。""" from app.engine.upgrade import compute_feeders @@ -2297,13 +2018,14 @@ async def assist_upgrade( session: AsyncSession, graph: dict[str, Any], *, level: str, provider: str | None = None, model: str | None = None, ) -> dict[str, Any]: - """升级的语义层:请 Copilot 把喂口径卡的纯算术沙箱代码改写成口径卡表达式,不是纯算术的保留并警告。 + """升级的语义层:请助手把喂口径卡的纯算术沙箱代码改写成口径卡表达式,不是纯算术的保留并警告。 - 模型、工具目录、操作流协议都和画布上改图是同一套;改完按搭图时同一套自查循环修正(只把这一轮冒出来的 - error 交回去,图上原来就有的不算),最后复核:没有降低要求的改动(autofix.forbidden_changes,这里没有例外: - Copilot 不换类型、不删连线)、没有比确定性改写的结果更糟(autofix.worse)才采纳,否则整个作废并写明原因。 + 模型、工具目录、操作流协议都和画布上改图是同一套(生成过程 copilot_gen);取数节点用到的表由系统代为查看(look + 文档 D5)。改完按搭图时同一套自查循环修正(只把这一轮冒出来的 error 交回去,图上原来就有的不算),最后复核:没有 + 降低要求的改动(autofix.forbidden_changes,这里没有例外:助手不换类型、不删连线)、没有比确定性改写的结果更糟 + (autofix.worse)才采纳,否则整个作废并写明原因。 - 返回 {ok, accepted, reason, summary, questions, warnings, graph, ops}。不落库。 + 返回 {ok, accepted, reason, summary, questions, warnings, graph, ops, looks}。不落库。 """ from app.engine.autofix import _sig, forbidden_changes, worse from app.engine.upgrade import compute_feeders @@ -2311,7 +2033,7 @@ async def assist_upgrade( base = copy.deepcopy(graph) spec = GraphSpec.model_validate(base) out: dict[str, Any] = {"ok": True, "accepted": False, "reason": None, "summary": "", "questions": [], - "warnings": [], "graph": graph, "ops": []} + "warnings": [], "graph": graph, "ops": [], "looks": []} feeders = compute_feeders(spec) if not feeders: out["summary"] = "口径卡的输入均不来自负责计算的沙箱代码,无需交给助手改写" @@ -2328,7 +2050,6 @@ async def assist_upgrade( defaults = base.get("defaults") base_errors = _blocking_issues(before_nodes, before_edges, sources=sources, baseline=baseline, level=level, defaults=defaults, checkers=checkers) or [] - known = {_sig(e) for e in base_errors} out["warnings"] = _kept_code(spec) request = GenerateIn(instruction="升级为可追溯结构", provider=provider, model=model) try: @@ -2336,66 +2057,39 @@ async def assist_upgrade( except ProviderNotConfigured as e: out.update(ok=False, summary=_unconfigured(e)) return out - # 同一套数据源上下文:改写时要用到查库节点查出的列,图里查过的表一律给全字段 - context = await _datasource_context(session, sources, request, need=_upgrade_need(feeders), graph=base) - - system = ( - "你是一个 agent 工作流编排专家。现在要做的是:把一张工作流里喂给口径卡的纯算术沙箱代码改写成口径卡表达式," - "以操作流的方式输出修改。\n\n" - f"{NODE_REFERENCE}\n\n可用工具:\n{_tool_catalog(sources, context)}{context.section()}\n\n" - f"{_STREAM_PROTOCOL}\n\n另外可以输出 question 操作:{{\"op\":\"question\",\"node_id\":\"…\",\"text\":\"…\"}}" - ) + looks = await _look_service(session, request, sources, graph=base, kinds=("table",)) + system = _assist_system("把一张工作流里喂给口径卡的纯算术沙箱代码改写成口径卡表达式", sources, + await copilot_context.section(looks), looks) + human = await _with_system_look(looks, _upgrade_assist_request(base, spec, feeders), base, sources, + need=copilot_context.SYSTEM_LOOK_UPGRADE_NEED) nodes = copy.deepcopy(before_nodes) edges = copy.deepcopy(before_edges) - tried: list[dict[str, Any]] = [] - effective: list[dict[str, Any]] = [] - plan = "" - - async def collect(request: str, *, first: bool) -> None: - nonlocal plan - async for op in _iter_ops(chat, [("system", system), ("human", request)]): - kind = op.get("op") - # 同发布修复:这里没有用户陈述的数据事实,目录修改提案不收 - if kind in ("thinking", "heartbeat", "catalog_patch"): - continue - if kind in ("plan", "done"): - # 修补轮的开场和收尾不是新方案,不覆盖第一轮的说明 - if first and kind == "plan": - plan = str(op.get("summary") or "") - elif first: - out["summary"] = str(op.get("explanation") or "") - elif kind in ("question", "reply"): - text = str(op.get("text") or "").strip() - where = before_nodes.get(str(op.get("node_id") or "")) - title = str((where.get("data") or {}).get("label") or where.get("id")) if where else "" - if text: - out["questions"].append(f"「{title}」:{text}" if title and title not in text else text) - else: - tried.append(op) - if _apply_op(nodes, edges, op): - effective.append(op) - + # 同发布修复:这里没有用户陈述的数据事实,目录修改提案不收 + applier = GraphApplier(nodes, edges, patches=False, questions=True) + # 自查:和搭图同一套规则,只把这一轮冒出来的 error 交回去改(原来就有的不归这一轮管) + checker = GraphChecker(applier, sources=sources, baseline=baseline, level=level, defaults=defaults, + checkers=checkers, known={_sig(e) for e in base_errors}) + gen = Generation(chat, system=system, applier=applier, checker=checker, looks=looks) try: - await collect(_upgrade_assist_request(base, spec, feeders), first=True) - # 自查:和搭图同一套规则,只把这一轮冒出来的 error 交回去改(原来就有的不归这一轮管) - for _ in range(_SELF_CHECK_ROUNDS): - now = _blocking_issues(nodes, edges, sources=sources, baseline=baseline, level=level, defaults=defaults, - checkers=checkers) - fresh = [e for e in now or [] if _sig(e) not in known] - if not effective or not fresh: - break - await collect(_repair_request(nodes, edges, fresh), first=False) + async for _op in gen.draft(human): + pass + async for _op in gen.repair(): + pass + if gen.repair_error is not None: + raise gen.repair_error except Exception as e: # noqa: BLE001 - 改不成就照实说,确定性改写的结果照样交给人 - out.update(ok=False, summary=f"助手本轮未完成:{explain_error(e)[0]}") + out.update(ok=False, summary=f"助手本轮未完成:{explain_error(e)[0]}", looks=list(looks.records)) return out - out["summary"] = out["summary"] or plan - if not effective: + out["looks"] = list(looks.records) + out["questions"] = _questions(applier, before_nodes, gen.asked) + out["summary"] = applier.explanation or str((applier.plan or {}).get("summary") or "") + if not applier.effective: out["summary"] = out["summary"] or ("助手认为这些代码不是纯算术,均保留原样" if out["questions"] else "助手本轮没有给出修改") return out proposed = _proposed_graph(base, nodes, edges) - reasons = forbidden_changes(base, proposed, tried) + reasons = forbidden_changes(base, proposed, applier.tried) after = _blocking_issues(_nodes_by_id(proposed), proposed.get("edges") or [], sources=sources, baseline=baseline, level=level, defaults=proposed.get("defaults"), checkers=checkers) if reasons: @@ -2405,7 +2099,8 @@ async def assist_upgrade( elif why := worse(base_errors, after): out["reason"] = f"助手的修改未能改善工作流,已作废:{why}" else: - out.update(accepted=True, graph=proposed, ops=effective, warnings=_kept_code(GraphSpec.model_validate(proposed))) + out.update(accepted=True, graph=proposed, ops=applier.effective, + warnings=_kept_code(GraphSpec.model_validate(proposed))) out["ok"] = out["reason"] is None return out @@ -2444,7 +2139,8 @@ async def upgrade_evidence(payload: UpgradeIn, session: AsyncSession = Depends(g 返回 {graph, changes, ops, notes, issues, applied, rejected, assist, ok}:changes / notes / rejected 的形状见 engine/upgrade.upgrade_for_evidence;issues 是升级后的图按 level 重跑 validate 和门禁的结果(和发布同一套口径); - assist 只在请求带 assist: true 时有:{ok, summary, questions, warnings},warnings 是保留没改的沙箱代码。 + assist 只在请求带 assist: true 时有:{ok, summary, questions, warnings, looks},warnings 是保留没改的沙箱代码, + looks 是这一次的查看记录(系统按取数节点的 SQL 代为查看的那一条在前)。 """ from app.engine.autofix import diff_changes from app.engine.governance import publish_issues @@ -2464,7 +2160,7 @@ async def upgrade_evidence(payload: UpgradeIn, session: AsyncSession = Depends(g helped = await assist_upgrade(session, out["graph"], level=payload.level, provider=payload.provider, model=payload.model) out["assist"] = {"ok": helped["ok"], "summary": helped["summary"], "questions": helped["questions"], - "warnings": helped["warnings"]} + "warnings": helped["warnings"], "looks": helped["looks"]} if helped["accepted"]: from app.engine.upgrade import compute_feeders @@ -2488,9 +2184,195 @@ async def upgrade_evidence(payload: UpgradeIn, session: AsyncSession = Depends(g return out +# -------------------------------------------------------------------------- +# 应用润色(总方案 A8):应用草稿由工作流版本确定性派生(app/apps/derive.py),助手只改布局、文案、控件选择。 +# 走同一个生成过程:系统先代为查看钉住的版本,模型可以再看别的版本和能力;落地调 app/apps/ops.apply_app_op, +# 自查调 app/apps/lint.lint_app。岗位绑定只能由人来做:助手只留空并在说明里提醒 +# -------------------------------------------------------------------------- + +APP_SYSTEM_PROMPT = """\ +你是应用润色助手。应用是已发布工作流版本的使用面:入口(发起用的表单)、视图(看运行产物)、实例、待办。 +应用草稿已经按钉住的工作流版本确定性派生好了,你只负责润色:布局(页面、分区、分栏、页签、组件顺序)、文案(标题、 +说明、按钮文字)、控件选择(表单字段的 x-widget、x-order,或者换成目录里更合适的组件)。 + +硬性约定: +- 只能用下面组件目录里的组件,props 按目录里写的字段和类型写,不要编造组件和属性 +- 绑定(bind)只取钉住的版本里已有的值:绑定的节点、指标、报告都要在钉住的版本里存在,拿不准就先 look 那一版; + 文字组件里不要写数字,也不要拼算式——数字只来自绑定,界面层不做任何计算 +- 可见性表达式(visible)只能用 run、input、metric、instance、task、user、view 这几个根名字,只能比较、取值、in 和 + and / or / not,不能写算术 +- 不改钉住的版本(pins),不改入口表单的数据约束(类型、必填、枚举、取值范围),只改外观 +- 岗位(slots)绑定到哪些人或组只能由人来做:岗位留着,不要替人绑定;done 的说明里提醒还有哪些岗位等着绑定 +- 能按常理定的直接改,必须由用户拿主意的才 ask""" + +APP_PROTOCOL_PROMPT = """\ +输出格式(严格遵守): +- 每行一个完整的 JSON 对象,除此之外不输出任何东西——不要 markdown 围栏、不要解释文字 +- 可用操作: + {"op":"plan","summary":"一句话说明打算怎么改"} ← 第一行 + {"op":"app_add","parent":"组件 id 或页面 id","index":0,"component":{"id":"…","type":"组件名","props":{},"bind":{}}} + {"op":"app_update","id":"组件 id","props":{},"bind":{},"visible":"…"} ← 只写要改的那几项 + {"op":"app_remove","id":"组件 id"} + {"op":"app_move","id":"组件 id","parent":"组件 id 或页面 id","index":0} + {"op":"app_page","page":{"id":"…","title":"…"}} ← 新增页面,或改已有页面的标题 + {"op":"app_set","path":"entries|views|forms|slots|task_ui","key":"…","value":{}} + {"op":"done","explanation":"两三句话说明改了什么,还有哪些岗位等着绑定"} ← 最后一行 +- 组件 id 用简短英文小写下划线,同一个应用里不重复;已有的组件用 app_update 改,不要删了重建 +- 这句话不需要改应用(只是问个问题)时,第一行也是最后一行输出 {"op":"reply","text":"直接回答的内容"} +- 要看工作流版本、能力的详情时输出一行 look(用法见下),输出之后就停下等查看结果,拿到结果再接着写 +- 必须先问清用户才能动手时,输出一行 {"op":"ask","question":"要问的话"},这一轮就此结束:已经输出的改动照常交付""" + +APP_CATALOG_PROMPT = "组件目录(只能用这些):\n{components}" +APP_COMPONENT_PROMPT = "- {name}({label},{category}){children}:绑定 {bindings};props {props}" +APP_DERIVED_PROMPT = "按钉住的版本确定性派生出的草稿(参考:组件该绑哪些节点、指标、报告,以它为准):\n{drafts}" +APP_REQUEST_PROMPT = "这是应用现在的草稿:\n{spec}\n\n请按下面的要求润色它(只输出改动操作):\n{instruction}" +APP_LOOK_WHEN_PROMPT = """\ +什么时候看:要绑定的节点、指标、报告在钉住的版本里有没有、叫什么,以系统代为查看的那一版为准,不够再看;要放动作状态、 +写入相关的组件时看能力。只改文案、顺序的不看""" +#: 系统代为查看钉住的版本时写进记录的需求(界面上显示) +APP_SYSTEM_LOOK_NEED = "应用引用的工作流版本" +APP_OPS = ("app_add", "app_update", "app_remove", "app_move", "app_page", "app_set") + + +class AppStreamIn(BaseModel): + instruction: str = Field(min_length=1, description="用自然语言说想怎么改这个应用") + #: 哪个应用。spec / bindings 不给时读它的草稿 + app_id: str | None = None + #: 编辑器里当前的草稿(agentlab.app/1):编辑器里还没保存的改动以它为准 + spec: dict[str, Any] | None = None + #: 草稿里的岗位绑定(不进 spec):应用检查按它判断岗位绑没绑 + bindings: dict[str, Any] | None = None + conversation_id: str | None = None + provider: str | None = None + model: str | None = None + + +def _app_catalog() -> str: + """组件目录:名字、中文名、类别、能不能有子组件、允许的绑定、props(只给字段和类型,app/apps/catalog.py)。""" + from app.apps.catalog import CATEGORY_LABEL, catalog_payload + + lines = [] + for c in catalog_payload()["components"]: + props = {k: v.get("type") or v.get("enum") or "string" for k, v in + ((c.get("props") or {}).get("properties") or {}).items()} + lines.append(APP_COMPONENT_PROMPT.format( + name=c["name"], label=c["label"], category=CATEGORY_LABEL.get(c["category"], c["category"]), + children=",可放子组件" if c.get("children") else "", + bindings=" / ".join(c.get("bindings") or []) or "无", props=json.dumps(props, ensure_ascii=False))) + return APP_CATALOG_PROMPT.format(components="\n".join(lines)) + + +async def _derived_drafts(session: AsyncSession, pins: list[dict[str, Any]]) -> str: + """每个钉住的版本确定性派生出的草稿,给模型对照着润色。派生是参考:哪一个派生不出来(版本没了、派生出错)就不给 + 那一份,不挡润色(P3),应用检查照样把问题列出来。""" + from app.apps import derive + + drafts = [] + for pin in pins: + try: + spec = await derive.derive_app(session, str(pin.get("workflow_id")), int(pin.get("version") or 0)) + except Exception: # noqa: BLE001 - 派生只是参考 + logger.exception("应用润色:钉住的版本 %s v%s 派生不出草稿", pin.get("workflow_id"), pin.get("version")) + continue + drafts.append(f"「{pin.get('alias')}」:{json.dumps(spec, ensure_ascii=False)}") + return APP_DERIVED_PROMPT.format(drafts="\n".join(drafts)) if drafts else "" + + +@router.post("/app-stream") +async def app_stream(payload: AppStreamIn, session: AsyncSession = Depends(get_session)): + """应用润色:SSE 推送,形状同 /generate-stream。 + + 事件:model;系统代为查看钉住版本的 look(by=system);模型的 plan、应用操作(app_add / app_update / app_remove / + app_move / app_page / app_set,已经落到服务端维护的草稿上)、look、ask、thinking、heartbeat;自查的 check;最后 + final {spec, issues, explanation}——spec 是润色后的整份草稿,issues 是应用检查的全部问题(只有人能处理的,比如 + 岗位没绑,也在里面)。只回答了一句的发 reply 收尾;问了用户、什么都还没改的发完 ask 收尾。不落库:编辑器收到 + final 后照常保存草稿。 + """ + from fastapi.responses import StreamingResponse + + from app.db.models import App + from app.look.capabilities import CapabilityKind + from app.look.pick import Picker + from app.look.service import LookService + from app.look.versions import VersionKind + + row = await session.get(App, payload.app_id) if payload.app_id else None + if payload.app_id and row is None: + raise HTTPException(404, "应用不存在,可能已被删除") + spec = copy.deepcopy(payload.spec if payload.spec is not None else (row.draft if row is not None else None)) + if not spec: + raise HTTPException(400, "没有可润色的应用草稿。请先从工作流版本生成草稿,再请助手润色") + bindings = payload.bindings if payload.bindings is not None else (row.draft_bindings if row is not None else {}) + request = GenerateIn(instruction=payload.instruction, provider=payload.provider, model=payload.model, + conversation_id=payload.conversation_id) + try: + model, model_id = await _op_model(session, request) + except ProviderNotConfigured as e: + raise HTTPException(400, _unconfigured(e)) from e + picker = Picker(await copilot_model_spec(session, request, max_tokens=copilot_context.PICK_MAX_TOKENS)) + looks = LookService([await VersionKind.load(session, picker=picker), await CapabilityKind.load(picker=picker)]) + pins = [p for p in spec.get("pins") or [] if isinstance(p, dict)] + overview = await looks.overview() + system = "\n\n".join(part for part in ( + APP_SYSTEM_PROMPT, _app_catalog(), await _derived_drafts(session, pins), overview, APP_PROTOCOL_PROMPT, + looks.guide(), APP_LOOK_WHEN_PROMPT) if part) + human = _with_history( + APP_REQUEST_PROMPT.format(spec=json.dumps(spec, ensure_ascii=False, indent=2), instruction=payload.instruction), + await _history_section(session, payload.conversation_id)) + applier = AppApplier(spec) + checker = AppChecker(applier, bindings=bindings) + started = time.monotonic() + gen = Generation(model, system=system, applier=applier, checker=checker, looks=looks, started=started) + + async def event_stream(): + yield _sse({"op": "model", "model": model_id}) + try: + # 系统先代为查看钉住的版本(look 文档 D5 的做法):润色绕不开它们,直接查省掉一轮 + first = human + targets = [{"kind": "workflow_version", "source": str(p.get("workflow_id")), "name": f"v{p.get('version')}"} + for p in pins] + if targets: + looked = await looks.look({"op": "look", "need": APP_SYSTEM_LOOK_NEED, "targets": targets}, by="system") + if looked.record is not None: + yield _sse(looked.record) + first = f"{human}\n\n{looked.text}" + async for op in _with_heartbeat(gen.draft(first), started=started): + yield _sse(op) + if applier.replied is not None: + yield _sse(applier.replied) + return + if gen.asked is not None and not applier.effective: + return + if gen.asked is None and gen.done is None and not applier.effective: + # 流正常结束,却没有 done、也没有一个操作落地:不能按「无需修改」交付 + raise CopilotIncomplete("模型没有给出任何修改,也没有说明原因", + hint="应用草稿未修改。可以重试,或把要求描述得更具体") + async for op in _with_heartbeat(gen.repair(), phase="repairing"): + yield _sse(op) + remaining = await checker.issues() + yield _sse({"op": "check", "status": "failed" if remaining else "passed", "repaired": gen.repaired, + **({"issues": remaining} if remaining else {})}) + yield _sse({"op": "final", "spec": applier.spec, "issues": await checker.lint(), + "explanation": applier.explanation}) + except CopilotIncomplete as e: + yield _sse({"op": "error", "message": f"助手本轮未完成:{e}", "hint": e.hint, "detail": e.detail}) + except Exception as e: # noqa: BLE001 + reason, hint = explain_error(e) + yield _sse({"op": "error", "message": f"助手本轮未完成:{reason}", "hint": hint, "detail": raw_error(e)}) + + return StreamingResponse( + event_stream(), + media_type="text/event-stream", + headers={"Cache-Control": "no-cache", "X-Accel-Buffering": "no"}, + ) + + class FromRunIn(BaseModel): run_id: str name: str = "" + #: 问数据回答上点「做成应用」时带上:这次运行出自哪段对话的哪一轮,记进新工作流的来源(workflows.origin) + conversation_id: str | None = None + turn_id: str | None = None @router.post("/from-run") @@ -2503,6 +2385,9 @@ async def extract_template( 提取是确定性的:只保留真正执行过的节点和它们之间的边,分支上 没走的岔路剪掉;输入值参数化成 input 字段默认值。产物落成 draft, 人审、改名、发布之后才成为正式模板——提取器是模板的作者,不是发布者。 + + 新工作流记下来源(workflows.origin = {run_id, conversation_id?, turn_id?}):从这里发布、再做成应用的那条路 + (总方案 A8)事后查得到它出自哪次运行、哪段对话。 """ from sqlalchemy import select as _sel @@ -2570,6 +2455,9 @@ async def extract_template( graph=graph, tags=["extracted"], status="draft", + origin={"run_id": run.id, + **({"conversation_id": payload.conversation_id} if payload.conversation_id else {}), + **({"turn_id": payload.turn_id} if payload.turn_id else {})}, ) session.add(workflow) await session.flush() diff --git a/backend/app/api/copilot_context.py b/backend/app/api/copilot_context.py index 3e963b5d..15b7103e 100644 --- a/backend/app/api/copilot_context.py +++ b/backend/app/api/copilot_context.py @@ -1,102 +1,46 @@ -"""助手建图时给模型看的数据源上下文:小库给详细摘要,大库先按需求挑表,再把挑中的表讲透(数据目录阶段 1B)。 +"""助手的数据上下文:system 里只给概览,要看什么由模型自己 look(look 文档第二部分,总方案第五部分)。 -**为什么要挑表。** 接进来的业务库常有上百张表。以前超过详细摘要的阈值(一个库超过 40 张表,或者几个库的摘要 -加起来超过 6000 字)就整体退成「只列表名」,工具清单里也只列前 12 个表名:助手一个字段都看不到,只能照着表名 -编字段、猜怎么连表,跑到查库那一步才「no such column」。现在大库先用一次轻量的模型调用,按这一轮的需求从 -紧凑的表目录(每张表一行:表名|中文名|粒度)里挑出相关的表,再沿关系图补上连接要经过的中间表;挑中的表给 -全部字段、数据目录和可以照抄进 SQL 的连接条件,其余表只列名字,让模型知道还有别的表可查。 +**以前。** 每一轮开始前服务端按库的大小定怎么给:小库塞详细摘要,大库先用模型挑表、挑不出就退回全部表名。这一步 +完全不看这一轮要做什么——用户说一句「你好」,助手也先花几秒挑表,再带着上万字的表结构去生成;挑表模型照提示说 +「不需要」,反而被记成失败、退回列出全部表名(look 文档 §1.3、§1.4)。 -**按数据源分三种(selected_by)。** +**现在。** system 里每个库一行概览(app/look/tables.py),工具清单不再列表名。模型要看表时输出一行 look,生成过程 +(api/copilot_gen.py)读到就停下,由查看服务(app/look/service.py)一次给齐:点名直取;只给需求时候选不超过 12 张 +全给,否则挑选模型按需求挑;补两跳以内的中间表;全部字段、数据目录、连接条件;遮罩列只给列名和类型。闲聊只调一次 +模型,数据类请求一次查看到位。 -- all:放得下详细摘要的库,照旧每张表一行带字段,额外带上数据目录和表之间的连接条件; -- model:大库,挑表成功:挑中的表讲透,其余只列名字; -- fallback:大库,挑表失败(模型不可用、报错、超时、回复无法识别、返回为空或返回的表都不存在),退回以前的 - 「只列表名」。挑表只是让模型少猜,**绝不能挡住生成**:没有它,模型照旧可以先用 db_schema 查字段。 +**各入口看什么**(总方案 §5.3):画布、问数据看表和能力(问数据只列只读能力);发布前修复、升级证据看表,由系统按要修 +的 SQL 代为查看(look 文档 D5);应用润色看工作流版本和能力(在 copilot.py 里组装)。 -现有工作流(画布上改图时的原图、问数据追问时上一轮的图)的 SQL 里查过哪些表是确定的事实:大库里这些表一律 -给全字段,挑表失败时也一样。 - -**一轮只挑一次。** 流式生成的自查修正、升级的修正轮都沿用同一份上下文(同一段 system 提示词),不重新挑表: -两次挑出来的表不一样,模型前后看到的结构就对不上。 - -**用法。** plan_context 读目录、按大小定每个源怎么给(不调模型,接口函数在开流之前调,因为请求的会话只在 -那时可用);pick_model 拿挑表用的模型(同一个助手模型,关掉思考、额度取小);ContextPlan.resolve 挑表并组装 -(流式生成在流里调,期间照常发心跳);DatasourceContext 给出提示词片段(section)、工具清单里列出的可查对象 -(listed)和告诉前端这一轮参考了哪些表的 context 操作(op)。 +这里提供:look_service(按入口组装查看服务,开流之前调:读目录、读能力登记要用会话)、section(system 里数据源那一节)、 +system_look(系统代为查看)、写 SQL 的硬性要求和「什么时候该看」的判断标准。 """ from __future__ import annotations -import asyncio -import json -import logging -import math -import time -from collections.abc import Iterable, Mapping -from dataclasses import dataclass, field -from typing import Any, Literal +from collections.abc import Mapping +from typing import Any -from app.data import catalog -from app.data import introspect -from app.data.catalog import CARDINALITY_LABEL, INFERRED_MARK, JoinEdge -from app.providers.factory import ModelSpec, get_chat_model - -logger = logging.getLogger(__name__) - -# ========================================================================== -# 参数 -# ========================================================================== - -#: 详细摘要的字符预算。超了的库改为按需求挑表,字段让挑中的表带、其余的让模型用 db_schema 工具按需查。 -#: 实测一个 53 对象的库带字段约 4000 字符,接三五个库就会把真正的需求淹掉——system prompt 里塞满 schema -#: 而挤掉用户想要什么,是本末倒置 -DATASOURCE_BUDGET_CHARS = 6000 -#: 详细摘要每个库最多列这么多对象(与 introspect.summary 的默认值一致)。超过就说明会截断:多出来的表模型 -#: 根本看不见,那还不如挑表 -DETAIL_TABLE_LIMIT = 40 -#: 挑表最多挑几张(所有数据源合计,含现有工作流用到的表) -PICK_LIMIT = 12 -#: 补上连接用的中间表之后,给全字段的表最多几张(所有数据源合计) -CONTEXT_TABLE_LIMIT = 16 -#: 挑表调用的时限(秒)。挑表在生成之前、用户在等,宁可放弃挑表也不能让生成干等 -PICK_TIMEOUT_S = 20.0 -#: 挑表调用的输出额度:十几个表名的 JSON 用不了几百 token -PICK_MAX_TOKENS = 1024 -#: 详细模式下附带的连接条件和数据目录的字符预算(所有数据源合计)。超了的不附,模型用 db_schema 查时照样看得到 -CATALOG_BUDGET_CHARS = 6000 -#: 一个源最多列多少条连接条件、多少条连接路径 -JOIN_LINES_LIMIT = 40 -PATH_LINES_LIMIT = 12 - -SelectedBy = Literal["all", "model", "fallback"] +from app.look.base import LookResult +from app.look.capabilities import CapabilityKind +from app.look.pick import PICK_MAX_TOKENS, Picker # noqa: F401 - copilot.py 按这个额度取挑选模型的规格 +from app.look.service import LookService +from app.look.tables import TableKind, graph_tables +from app.providers.factory import ModelSpec # ========================================================================== # 写给模型的文字(不上界面) # ========================================================================== -SECTION_HEAD_PROMPT = "\n\n已接入的数据源(涉及取数时优先用它们,而不是让用户自己写 SQL 的代码节点):\n" -#: 有源只列了名字时补的一句(以前紧凑模式的原话) -NAMES_ONLY_PROMPT = " (对象较多,上面只列了名字。写 SQL 前用 db_schema 工具确认字段,别猜)" -INFERRED_PROMPT = (" 标「推断,未确认」的说明和连接条件是按列名、数据库注释或模型推断出来的,没有人确认过:" - "照抄前对照字段核实,拿不准就先用 db_schema 工具查") -#: 探查结构截断了的源(每个源最多取 200 张表,introspect._MAX_TABLES):没探查到的表不在表结构缓存里,上面列不出、 -#: db_schema 也查不到。不说的话模型会以为库里就这么多表,用户说的表名对不上时就近找一张名字像的顶上 -UNEXPLORED_PROMPT = (" (这个库共 {total} 张表,只探查了 {explored} 张,还有 {rest} 张没有探查到、不在上面。用户提到的表名" - "在上面找不到时,先用 db_schema__{source} 查;也查不到就查数据字典(information_schema.columns," - "SQLite 用 sqlite_master)确认它的字段,别猜,也别拿名字相近的表顶替)") -#: 挑表请求里一个源的标题:截断了的写明只列了探查到的 -PICK_SOURCE_PROMPT = "数据源「{source}」(共 {total} 张表)" -PICK_SOURCE_PARTIAL_PROMPT = "数据源「{source}」(共 {total} 张表,只探查了 {explored} 张,下面只列探查到的)" SQL_RULES_PROMPT = ( "\n\n写 SQL 的硬性要求:\n" # 这三条都是真实踩过的:Oracle 上漏 schema 前缀直接 ORA-00942, # 写惯 MySQL 的模型会顺手写 LIMIT,而一条没有行数限制的查询能拖垮生产库 - "- 表名照抄上面的全名(含 schema 前缀),漏掉前缀在 Oracle 上会直接报 ORA-00942\n" + "- 表名照抄查看结果里的全名(含 schema 前缀),漏掉前缀在 Oracle 上会直接报 ORA-00942\n" "- 认准方言:Oracle 用 FETCH FIRST n ROWS ONLY,不是 LIMIT\n" "- 一次只写一条语句;分号拼接会被拒\n" - "- 字段拿不准就在图里先放一个 db_schema 工具节点,别猜字段名\n" # 真实踩过:列名是照着业务说法猜的,跑到查库那一步才「no such column」 - "- 列名只照上面结构里列出来的写;结构里只列了表名时先用 db_schema 查字段。搭完自查会拿 SQL 里的列名" - "去对结构,对不上会打回来让你改\n" + "- 列名只照查看结果里列出来的写;没看过的表,动笔前先 look,别猜字段名。搭完自查会拿 SQL 里的列名去对结构," + "对不上会打回来让你改\n" "- 比率、增幅、占比这类派生计算进口径卡(metrics 节点);查询结果里原样的数,报告撰写节点(report)" "可以直接用 [[v:Q1.r0.列名]] 引用。别让 llm 节点直接对数字做算术\n" # 真实运行里报告表格的表头全是英文缩写的原始列名:[[table:]] 原样用查询结果的列名 @@ -105,664 +49,60 @@ SQL_RULES_PROMPT = ( "(那是字符串);只给最外层 SELECT 的结果列起别名,WHERE、JOIN、GROUP BY 里照旧写原列名\n" ) -PICK_SYSTEM = ( - "你在帮工作流助手挑选数据表。用户这一轮提了一个需求,助手接下来要据此搭工作流、写 SQL;数据库的表太多," - "没法把每张表的字段都给它看,它只会看到你挑出的表的全部字段。请从表目录里挑出完成这个需求要用到的表。\n\n" - "挑选规则:\n" - f"- 最多挑 {PICK_LIMIT} 张,按和需求的相关程度从高到低排\n" - "- 事实表和维度表都要:要按渠道、门店、日期之类分组或筛选时,把对应的维度表也挑上\n" - "- 两张表要靠一张关联表才能连起来时,关联表也挑上\n" - "- 「当前工作流已用到」的表,需求还用得着就挑上\n" - "- 拿不准要不要的,宁可挑上\n" - "- table 照抄目录里的表名(含 schema 前缀),不要改写、不要编造;source 写表所在的数据源名\n" - "- 需求和数据库无关(闲聊、只改提示词或流程结构)时返回空列表\n\n" - '只输出 JSON:{"tables": [{"source": "数据源名", "table": "表名"}]}' -) -PICK_PROMPT = "需求:{need}\n\n{used}表目录(每行一张表:表名|中文名|粒度;行尾标「推断,未确认」的是推断出来的):\n\n{tables}" -PICK_USED_PROMPT = "当前工作流已用到:{tables}\n\n" -PICK_PROMPT_SCHEMA = { - "title": "picked_tables", - "description": "完成需求要用到的表,按相关程度从高到低排", - "type": "object", - "properties": { - "tables": { - "type": "array", - "items": { - "type": "object", - "properties": { - "source": {"type": "string", "description": "表所在的数据源名"}, - "table": {"type": "string", "description": "照抄表目录里的表名"}, - }, - "required": ["table"], - }, - }, - }, - "required": ["tables"], -} +#: 什么时候该看(look 文档 D4):画布、问数据共用 +LOOK_WHEN_PROMPT = """\ +什么时候该看: + · 闲聊、解释、改提示词、改流程结构、改不碰 SQL 的节点:不看 + · 问数据:查库交给 agent 节点,它运行时会自己查表结构。只有从概览看不出该用哪个库、用户点了表名、用户说了口径时 + 才看一次,把看到的表名写进 agent 的提示词,运行时少走弯路 + · 直接写 SQL 的取数节点、修改已有的 SQL:动笔前看,一次把要用的表都点上 + · 用户说了一条数据事实:先看那张表的现有目录,再提目录修改 + · 要看就先看,看完再规划,不要先搭节点再回头看;这次对话里已经看过的表直接点名看,不要只给需求""" + +#: 系统代为查看时写进记录的需求(界面上显示) +SYSTEM_LOOK_FIX_NEED = "要修的工作流里,查库节点的 SQL 用到的表" +SYSTEM_LOOK_UPGRADE_NEED = "要升级的工作流里,查库节点的 SQL 用到的表" -# ========================================================================== -# 拿模型 -# ========================================================================== +async def look_service(sources: list[Any], *, spec: ModelSpec | None, graph: Mapping[str, Any] | None = None, + kinds: tuple[str, ...] = ("table", "capability"), answer: bool = False) -> LookService: + """按入口组装这一轮的查看服务。读目录、读能力登记都用各自的短会话,开流前后都能调。 - -async def pick_model(session: Any, spec: ModelSpec) -> tuple[Any | None, str | None]: - """挑表用的模型:(模型, None),拿不到时 (None, 原因)。 - - spec 是助手的模型规格(copilot_model_spec),这里关掉思考、额度取小、温度 0、请求时限对齐 PICK_TIMEOUT_S: - 挑表是一次分类,不需要思考,思考只会拖慢生成开始的时间。没配接入时 get_chat_model 会静默退回演示模型, - 演示模型挑不了表,直接按挑表失败处理。 - - get_chat_model 用本模块的名字:建图模型和挑表模型分得开(测试里各换各的假模型,互不串)。 + spec 是助手的模型规格:挑选模型第一次要用时才按它拿(关思考、额度小)。graph 是现有工作流,概览里列出它查过的表。 + answer:问数据(意图为回答),能力只列只读的。 """ - from app.core.errors import explain - from app.providers.mock_model import MockChatModel - - spec = spec.model_copy(update={"thinking": "off", "max_tokens": PICK_MAX_TOKENS, "temperature": 0, - "timeout": math.ceil(PICK_TIMEOUT_S)}) - try: - model, _ = await get_chat_model(session, spec) - except Exception as e: # noqa: BLE001 - 拿不到模型只是不挑表,生成照常 - return None, f"助手使用的模型不可用:{explain(e)[0]}" - if isinstance(model, MockChatModel): - return None, "演示模型不能按需求挑选数据表" - return model, None + picker = Picker(spec) + made: list[Any] = [] + if "table" in kinds: + made.append(await TableKind.load(sources, graph=graph, picker=picker)) + if "capability" in kinds: + made.append(await CapabilityKind.load(picker=picker, read_only=answer)) + return LookService(made) -# ========================================================================== -# 规划:读目录、定模式 -# ========================================================================== +async def section(looks: LookService) -> str: + """system 里数据源那一节:各类对象的概览,有数据源时再加写 SQL 的硬性要求。什么都没有时是空串,不占提示词。""" + overview = await looks.overview() + if not overview: + return "" + tables = looks.kinds.get("table") + return "\n\n" + overview + (SQL_RULES_PROMPT if tables is not None and tables.plans else "") -@dataclass -class SourcePlan: - """一个数据源怎么给:all 给详细摘要,pick 先挑表。""" +async def system_look(looks: LookService, graph: Mapping[str, Any] | None, sources: list[Any], *, + need: str) -> LookResult | None: + """系统代为查看(look 文档 D5):图里调用工具节点的 SQL 用到的表,点名查看,不调挑选模型。没有就是 None。 - source: Any - mode: Literal["all", "pick"] - #: 目录原样(含驳回项):关系图要靠驳回项压住同一条关系的现推结果 - raw_notes: dict[str, dict[str, Any]] - #: 现有工作流 SQL 里查过的表(schema_cache 的键) - seeds: list[str] - - @property - def tables(self) -> dict[str, Any]: - return (getattr(self.source, "schema_cache", None) or {}).get("tables") or {} - - @property - def explored(self) -> int: - """探查到、在表结构缓存里的表数。""" - return len(self.tables) - - @property - def total(self) -> int: - """这个源一共几张表(含视图):探查时数据库报的总数。老缓存没记总数时按探查到的算。""" - raw = (getattr(self.source, "schema_cache", None) or {}).get("total") - return max(raw if isinstance(raw, int) and not isinstance(raw, bool) else 0, self.explored) - - @property - def unexplored(self) -> int: - """探查截断了的话还有几张没探查到;没截断为 0。 - - 只看 truncated:反射失败跳过的表(skipped)也算在 total 里,但那是「探查了、读不到」,不是没探查到。 - """ - truncated = (getattr(self.source, "schema_cache", None) or {}).get("truncated") - return max(self.total - self.explored, 0) if truncated else 0 - - @property - def notes(self) -> dict[str, dict[str, Any]]: - """给模型看的目录:去掉驳回项。""" - return {t: catalog.visible_notes(n) for t, n in self.raw_notes.items()} - - @property - def catalog_tables(self) -> int: - """有数据目录的表数:去掉驳回项之后还有内容的。整份被驳回的不算——挑表、SQL 检查都用不上它。""" - return sum(1 for n in self.raw_notes.values() if catalog.visible_notes(n)) - - -def _modes(sources: list[Any]) -> list[Literal["all", "pick"]]: - """每个源给详细摘要还是先挑表。 - - 沿用以前的判断:表超过 DETAIL_TABLE_LIMIT 的库一定挑表;其余的按详细摘要从短到长放进 DATASOURCE_BUDGET_CHARS, - 放得下的给详细摘要,放不下的挑表。全都放得下时和以前一样全是详细模式;以前超预算是所有库一起退成只列表名, - 现在是放不下的那几个库去挑表。没探查过结构的库没有表可挑,照旧给一行说明。 + 记录、文字和模型主动查看的完全一样,只是 by=system、不占模型的次数;模型仍然可以再看。 """ - modes: list[Literal["all", "pick"]] = [] - sized: list[tuple[int, int]] = [] - for i, src in enumerate(sources): - names = introspect.table_names(src) - if names and len(names) > DETAIL_TABLE_LIMIT: - modes.append("pick") - continue - modes.append("all") - if names: - sized.append((len(introspect.summary(src, detail=True)), i)) - used = 0 - for size, i in sorted(sized): - if used + size <= DATASOURCE_BUDGET_CHARS: - used += size - else: - modes[i] = "pick" - return modes - - -def graph_tables(graph: Mapping[str, Any] | None, sources: Iterable[Any]) -> dict[str, list[str]]: - """现有工作流里查库节点的 SQL 用到的表:{源名: [schema_cache 的键]},按出现顺序。 - - 只认调用工具节点上写死的 SQL(db_query__<源>);Agent 运行时自己写的 SQL 图里看不到。哪些节点算写死的查询 - 以 sqlcheck.tool_query 为准(catalog_impact.tool_queries,和发布记录、SQL 检查同一份):换成别的类型的节点 - 配置里残留的 tool、args 不算。节点认两种写法:画布的 {data: {config}} 和 GraphSpec 的 {config}。SQL 解析 - 不了的跳过。 - """ - from app.data.catalog_impact import tool_queries - from app.engine.evidence import sql_tables - - by_name = {getattr(s, "name", None): s for s in sources} - out: dict[str, list[str]] = {} - nodes = (graph or {}).get("nodes") or [] - for _, source_name, sql in tool_queries(n for n in nodes if isinstance(n, dict)): - source = by_name.get(source_name) - if source is None: - continue - try: - names = sql_tables(sql) - except Exception: # noqa: BLE001 - 认不出表就当没用到,只少一个提示 - continue - found = out.setdefault(source.name, []) - for table in names: - key = catalog.resolve_table_name(source.schema_cache, table) - if key and key not in found: - found.append(key) - return {k: v for k, v in out.items() if v} - - -async def plan_context(sources: list[Any], *, graph: Mapping[str, Any] | None = None) -> ContextPlan: - """读各源的数据目录、定每个源怎么给。不调模型。 - - graph 是现有工作流(改图时的原图、追问时上一轮的图),它的 SQL 里查过的表在大库里一律给全字段。目录读不到 - 就当没有(tools.datasource._catalog_of:用单独的会话读,出错不连累请求的会话)。 - """ - from app.tools.datasource import _catalog_of - - seeds = graph_tables(graph, sources) - plans = [] - for src, mode in zip(sources, _modes(sources)): - entries = await _catalog_of(src) if introspect.table_names(src) else {} - plans.append(SourcePlan(source=src, mode=mode, raw_notes={t: e.notes for t, e in entries.items()}, - seeds=seeds.get(src.name, []))) - return ContextPlan(plans) - - -# ========================================================================== -# 挑表 -# ========================================================================== - - -class _Unreadable(ValueError): - """模型的回复里识别不出表名。""" - - -def _picked(raw: Any) -> list[tuple[str | None, str]] | None: - """模型的回复 → [(源名或 None, 表名)]。结构化输出的对象、正文里的 JSON、字符串列表都认;对不上格式返回 None。""" - if hasattr(raw, "model_dump"): - raw = raw.model_dump() - if isinstance(raw, str): - text = raw.strip() - start = min((i for i in (text.find("{"), text.find("[")) if i >= 0), default=-1) - if start < 0: - return None - end = text.rfind("}" if text[start] == "{" else "]") - try: - raw = json.loads(text[start:end + 1]) - except ValueError: - return None - if isinstance(raw, dict): - raw = raw.get("tables") - if not isinstance(raw, list): + targets = [{"kind": "table", "source": source, "name": table} + for source, tables in graph_tables(graph, sources).items() for table in tables] + if not targets or "table" not in looks.kinds: return None - out: list[tuple[str | None, str]] = [] - for item in raw: - if isinstance(item, str) and item.strip(): - out.append((None, item.strip())) - elif isinstance(item, dict) and isinstance(item.get("table"), str) and item["table"].strip(): - src = item.get("source") - out.append((src.strip() if isinstance(src, str) and src.strip() else None, item["table"].strip())) - return out - - -async def _ask(model: Any, messages: list[tuple[str, str]]) -> list[tuple[str | None, str]]: - """问一次。先走结构化输出;不支持、报错、或给回来的不是约定的结构,再退回纯文本、从正文里取 JSON。 - - 结构化输出报错也退回(同 catalog._ask_model):有的网关不支持工具调用,一调就报错,纯文本却能用。两次加起来 - 仍受 PICK_TIMEOUT_S 约束。 - """ - from app.engine.state import message_text - - try: - parsed = _picked(await model.with_structured_output(PICK_PROMPT_SCHEMA).ainvoke(messages)) - except Exception: # noqa: BLE001 - 退回纯文本 - parsed = None - if parsed is not None: - return parsed - parsed = _picked(message_text(await model.ainvoke(messages))) - if parsed is None: - raise _Unreadable("模型的回复不是约定的格式,无法识别要用的表") - return parsed - - -@dataclass -class ContextPlan: - """plan_context 的结果:各源怎么给,等着挑表、组装。""" - - plans: list[SourcePlan] - - @property - def needs_pick(self) -> bool: - return any(p.mode == "pick" for p in self.plans) - - def _pick_messages(self, need: str) -> list[tuple[str, str]]: - blocks, used = [], [] - for p in self.plans: - if p.mode != "pick": - continue - qualified = _qualifier(p.tables) - index = catalog.render_table_index(p.source.schema_cache, p.notes) - head = (PICK_SOURCE_PARTIAL_PROMPT if p.unexplored else PICK_SOURCE_PROMPT).format( - source=p.source.name, total=p.total, explored=p.explored) - blocks.append(f"{head}:\n{index}") - if p.seeds: - used.append(f"数据源「{p.source.name}」的 " + "、".join(qualified(t) for t in p.seeds)) - human = PICK_PROMPT.format(need=need.strip(), used=PICK_USED_PROMPT.format(tables=";".join(used)) if used - else "", tables="\n\n".join(blocks)) - return [("system", PICK_SYSTEM), ("human", human)] - - def _resolve(self, picks: list[tuple[str | None, str]]) -> list[tuple[int, str]]: - """模型挑的表对到表结构上:[(第几个源, schema_cache 的键)]。对不上的丢掉。 - - 只有一个源要挑时不看模型写的源名(写错了也不要紧);有几个时按源名认,表名前面带着源名(「源名.表名」) - 也认,写了一个不存在的源名的丢掉;没写源名的按顺序在各源里找。 - """ - pick = [i for i, p in enumerate(self.plans) if p.mode == "pick"] - by_name = {self.plans[i].source.name: i for i in pick} - out: list[tuple[int, str]] = [] - for source, table in picks: - name = table - if len(pick) == 1: - candidates = pick - elif source in by_name: - candidates = [by_name[source]] - else: - prefixed = next(((by_name[n], table[len(n) + 1:]) for n in by_name - if table.startswith(n) and table[len(n):len(n) + 1] in (".", ":", ":")), None) - if prefixed is not None: - candidates, name = [prefixed[0]], prefixed[1] - elif source is not None: - continue - else: - candidates = pick - for i in candidates: - key = catalog.resolve_table_name(self.plans[i].source.schema_cache, name) - if key: - out.append((i, key)) - break - return out - - async def resolve(self, model: Any | None, *, need: str, unavailable: str | None = None) -> DatasourceContext: - """挑表并组装。不抛异常:挑表的任何失败都退回只列表名(fallback),原因写进 context 操作和日志。 - - model 是 pick_model 拿到的模型;拿不到时为 None,unavailable 是原因。没有要挑表的源时不调模型。 - """ - if not self.needs_pick: - return self._assemble([], reason=None, elapsed_ms=None) - started = time.monotonic() - reason: str | None = None - chosen: list[tuple[int, str]] = [] - if model is None: - reason = unavailable or "未配置可用的模型" - else: - try: - picks = await asyncio.wait_for(_ask(model, self._pick_messages(need)), timeout=PICK_TIMEOUT_S) - chosen = self._resolve(picks) - if not picks: - reason = "模型未挑出任何表" - elif not chosen: - reason = "模型挑出的表在表结构中都不存在" - except asyncio.TimeoutError: - reason = f"挑选数据表超过 {PICK_TIMEOUT_S:g} 秒未完成" - except _Unreadable as e: - reason = str(e) - except Exception as e: # noqa: BLE001 - 挑表失败不挡生成 - from app.core.errors import explain - - reason = f"挑选数据表的模型调用失败:{explain(e)[0]}" - elapsed = int((time.monotonic() - started) * 1000) - ctx = self._assemble(chosen if reason is None else [], reason=reason, elapsed_ms=elapsed) - if reason is None: - logger.info("助手挑表用时 %d ms:%s", elapsed, ";".join( - f"{s.source.name} {len(s.tables)} 张" for s in ctx.sources if s.selected_by == "model")) - else: - logger.warning("助手挑表未成功(%s),用时 %d ms,退回只列表名", reason, elapsed) - return ctx - - def fallback(self, reason: str) -> DatasourceContext: - """不挑表、直接按挑表失败组装:resolve 本身出了意外时用。""" - return self._assemble([], reason=reason, elapsed_ms=None) - - def _assemble(self, chosen: list[tuple[int, str]], *, reason: str | None, - elapsed_ms: int | None) -> DatasourceContext: - """定下每个源给全字段的表。 - - 先放现有工作流用到的表,再按模型给的顺序放挑中的表,合计不超过 PICK_LIMIT;然后每个源在挑中的表两两之间 - 找不超过 2 跳的连接路径,把中间表补进来,所有源合计不超过 CONTEXT_TABLE_LIMIT。已经直接相连的一对不补; - 有一条路径的中间表已经在里面的也不补。 - """ - picked: dict[int, list[str]] = {} - room = PICK_LIMIT - for i, key in [(i, t) for i, p in enumerate(self.plans) if p.mode == "pick" for t in p.seeds] + chosen: - have = picked.setdefault(i, []) - if room > 0 and key not in have: - have.append(key) - room -= 1 - extra = CONTEXT_TABLE_LIMIT - sum(len(v) for v in picked.values()) - out: list[SourceContext] = [] - for i, p in enumerate(self.plans): - if p.mode == "all": - out.append(SourceContext(p, "all", list(p.tables))) - continue - first = picked.get(i, []) - graph: dict[str, list[JoinEdge]] = {} - tables, routes = list(first), [] - if len(first) > 1: - graph = _relation_graph(p) - tables, routes = _complete(first, graph, extra) - extra -= len(tables) - len(first) - out.append(SourceContext(p, "fallback" if reason is not None else "model", tables, picked=first, - routes=routes, graph=graph)) - return DatasourceContext(out, reason=reason, elapsed_ms=elapsed_ms) - - -def _relation_graph(plan: SourcePlan) -> dict[str, list[JoinEdge]]: - """这个源的关系图:目录里的关系(驳回的不进)加上按结构现推的(外键约束、命名推断)。推不出来就当没有。""" - try: - return catalog.relation_graph(plan.raw_notes, schema_cache=plan.source.schema_cache) - except Exception: # noqa: BLE001 - 少了连接条件只是少一个提示 - logger.exception("数据源 %s 的关系图推不出来,本轮不给连接条件", plan.source.name) - return {} - - -def _complete(picked: list[str], graph: Mapping[str, list[JoinEdge]], - room: int) -> tuple[list[str], list[tuple[str, str, tuple[JoinEdge, ...]]]]: - """补连接用的中间表:(给全字段的表, [(a, b, 经中间表的两跳路径)])。room 是还能补几张。""" - tables = list(picked) - routes: list[tuple[str, str, tuple[JoinEdge, ...]]] = [] - for i, a in enumerate(picked): - for b in picked[i + 1:]: - if any(e.to_table == b for e in graph.get(a, ())): - continue - paths = [p for p in catalog.join_paths(graph, a, b, max_hops=2) if len(p) == 2] - via = next((p for p in paths if p[0].to_table in tables), None) - if via is None and paths and len(tables) - len(picked) < room: - via = paths[0] - tables.append(via[0].to_table) - if via is not None: - routes.append((a, b, via)) - return tables, routes - - -# ========================================================================== -# 组装好的上下文 -# ========================================================================== - - -def _qualifier(tables: Mapping[str, Any]): - """表名(schema_cache 的键)→ 全名:模型照着全名写 SQL,漏了 schema 前缀在 Oracle 上直接报错。""" - return lambda key: str((tables.get(key) or {}).get("qualified") or key) - - -@dataclass -class SourceContext: - """一个源这一轮怎么给的:selected_by、给全字段的表(all 时是全部表)。""" - - plan: SourcePlan - selected_by: SelectedBy - #: 给全字段的表(schema_cache 的键):挑中的表在前,补进来的中间表在后 - tables: list[str] - #: 挑中的表(含现有工作流用到的),不含补进来的中间表 - picked: list[str] = field(default_factory=list) - routes: list[tuple[str, str, tuple[JoinEdge, ...]]] = field(default_factory=list) - graph: dict[str, list[JoinEdge]] = field(default_factory=dict) - - @property - def source(self) -> Any: - return self.plan.source - - @property - def total(self) -> int: - """这个源一共几张表:表结构缓存里记的真实总数(探查截断时比探查到的多),见 SourcePlan.total。""" - return self.plan.total - - @property - def explored(self) -> int: - """探查到的表数:没有表结构时为 0。""" - return self.plan.explored - - def qualified(self, key: str) -> str: - return _qualifier(self.plan.tables)(key) - - -@dataclass -class DatasourceContext: - sources: list[SourceContext] - #: 挑表失败的原因(没有失败时为 None) - reason: str | None = None - #: 挑表用了多久(毫秒);没有挑表时为 None - elapsed_ms: int | None = None - - def listed(self, source: Any) -> list[str]: - """工具清单里「可查」后面列的对象:挑中的表在前,其余按表结构的顺序。""" - names = introspect.table_names(source) - ctx = next((s for s in self.sources if s.source is source), None) - if ctx is None or ctx.selected_by == "all" or not ctx.tables: - return names - first = [ctx.qualified(t) for t in ctx.tables] - return first + [n for n in names if n not in first] - - def op(self) -> dict[str, Any] | None: - """告诉前端这一轮参考了哪些表:{"op": "context", "sources": [...], "elapsed_ms"?}。没有可查的表时为 None。 - - 每个源一项:source 源名,source_id 源的 id(界面据此给去数据目录页的入口),tables 给了全字段的表(全名), - selected_by,total 这个源一共几张表(表结构缓存里记的真实总数),catalog_tables 有数据目录的表数(没有目录的 - 大库,界面提示先去起草目录:挑表和 SQL 检查都靠它);探查截断了的再带 explored(探查到几张),界面写「共 N 张, - 只探查了 200 张」;挑表失败的带上 reason。只列了名字的表不进 tables:界面上说的「参考了 N 张表」是模型看得到 - 字段的那些。 - """ - rows = [] - for s in self.sources: - if not s.explored: - continue - row: dict[str, Any] = {"source": s.source.name, "source_id": getattr(s.source, "id", None), - "tables": [s.qualified(t) for t in s.tables], - "selected_by": s.selected_by, "total": s.total, - "catalog_tables": s.plan.catalog_tables} - if s.plan.unexplored: - row["explored"] = s.explored - if s.selected_by == "fallback" and self.reason: - row["reason"] = self.reason - rows.append(row) - if not rows: - return None - out: dict[str, Any] = {"op": "context", "sources": rows} - if self.elapsed_ms is not None: - out["elapsed_ms"] = self.elapsed_ms - return out - - def section(self) -> str: - """system 提示词里的数据源一节。没有数据源时返回空串,不占提示词。""" - if not self.sources: - return "" - budget = [CATALOG_BUDGET_CHARS] - blocks: list[str] = [] - names_only = False - for s in self.sources: - try: - if s.selected_by == "all": - blocks.append(_detail_block(s, budget)) - elif s.tables: - blocks.append(_selected_block(s)) - else: - blocks.append(introspect.summary(s.source, detail=False)) - names_only = True - except Exception: # noqa: BLE001 - 结构缓存里有意外的写法:这个源退回只列表名,不挡生成 - logger.exception("数据源 %s 的上下文组装失败,本轮只列表名", s.source.name) - blocks.append(introspect.summary(s.source, detail=False)) - names_only = True - if s.plan.unexplored: - # 探查截断了:上面列的只是探查到的那部分,说清还有多少张没探查到、遇到不认识的表名怎么办 - blocks.append(UNEXPLORED_PROMPT.format(total=s.total, explored=s.explored, rest=s.plan.unexplored, - source=s.source.name)) - text = "\n".join(blocks) - tail = [] - if names_only: - tail.append(NAMES_ONLY_PROMPT) - if INFERRED_MARK in text: - tail.append(INFERRED_PROMPT) - return SECTION_HEAD_PROMPT + "\n".join([text, *tail]) + SQL_RULES_PROMPT - - -# ========================================================================== -# 渲染 -# ========================================================================== - - -def _notes_body(s: SourceContext, key: str) -> list[str]: - """一张表的目录正文(render_table_notes 去掉标题行:「推断,未确认」的说明在整节末尾说一次)。""" - block = catalog.render_table_notes(s.plan.notes.get(key), meta=s.plan.tables.get(key), - system_notes=catalog.system_notes_source(s.source)) - return block.split("\n")[1:] if block else [] - - -def _condition(edge: JoinEdge, qualified) -> str: - """连接条件,表名用全名:channel_visits.visit_id = visits.id(多列用 AND 连接)。""" - left, right = qualified(edge.from_table), qualified(edge.to_table) - return " AND ".join(f"{left}.{a} = {right}.{b}" for a, b in zip(edge.from_columns, edge.to_columns)) - - -def _edge_line(edge: JoinEdge, qualified) -> str: - card = f"({CARDINALITY_LABEL[edge.cardinality]})" if edge.cardinality in CARDINALITY_LABEL else "" - return _condition(edge, qualified) + card + (INFERRED_MARK if edge.status == "proposed" else "") - - -def _edges_within(graph: Mapping[str, list[JoinEdge]], tables: list[str]) -> list[JoinEdge]: - """两端都在 tables 里的关系,每条一次;一对多的翻过来,从「多」的一端写起(外键所在的表在左)。 - - 「每条一次」按 relation_id 去重,去掉的是同一条关系在关系图里的正反两条边。注意 catalog.relation_id 区分方向: - A 表目录里记的 A→B 和 B 表目录里记的 B→A 是两个编号,两边都记了的话这里会各出一行(内容相同、写法相反)。 - 这是有意不改的:编号存在每条关系上,也是审阅路径 relations.<编号> 的一部分,改成不分方向会让已有目录里的 - 编号全部对不上。 - """ - wanted = set(tables) - seen: set[str] = set() - out = [] - for table in tables: - for edge in graph.get(table, ()): - if edge.to_table not in wanted or edge.relation_id in seen: - continue - seen.add(edge.relation_id) - out.append(edge.reversed() if edge.cardinality == "one_to_many" else edge) - return out - - -def _join_lines(s: SourceContext, graph: Mapping[str, list[JoinEdge]], tables: list[str]) -> list[str]: - edges = _edges_within(graph, tables) - if not edges: - return [] - lines = [" 表之间的连接条件(写 JOIN … ON … 时照抄):"] - lines += [f" {_edge_line(e, s.qualified)}" for e in edges[:JOIN_LINES_LIMIT]] - if len(edges) > JOIN_LINES_LIMIT: - lines.append(f" …另有 {len(edges) - JOIN_LINES_LIMIT} 条,用 db_schema 工具查看各表的关联关系") - return lines - - -def _detail_block(s: SourceContext, budget: list[int]) -> str: - """放得下详细摘要的源:照旧每张表一行带字段,后面附表之间的连接条件和数据目录。 - - 连接条件和目录共用一份预算(budget,所有详细模式的源合计 CATALOG_BUDGET_CHARS):详细摘要本身已经按 - DATASOURCE_BUDGET_CHARS 放进来了,附带的东西不能再把提示词撑大一倍。连接条件先放(最短、最能防止猜着连表), - 目录按表放,放不下的表让模型用 db_schema 查(db_schema 的输出里带目录)。 - """ - lines = [introspect.summary(s.source, detail=True)] - if not s.explored: - return lines[0] - joins = _join_lines(s, _relation_graph(s.plan), list(s.plan.tables)) - size = sum(len(line) + 1 for line in joins) - if joins and size <= budget[0]: - budget[0] -= size - lines += joins - elif joins: - lines.append(" (表之间的连接条件用 db_schema 工具查看各表的关联关系)") - notes: list[str] = [] - skipped = False - for key in s.plan.tables: - body = _notes_body(s, key) - if not body: - continue - piece = [f" · {s.qualified(key)}:", *(f" {line}" for line in body)] - size = sum(len(line) + 1 for line in piece) - if size > budget[0]: - skipped = True - continue - budget[0] -= size - notes += piece - if notes: - lines.append(" 数据目录:") - lines += notes - if skipped: - lines.append(" (其余表的数据目录用 db_schema 工具查看)") - return "\n".join(lines) - - -def _source_head(source: Any) -> str: - """一个源的标题行,和 introspect 的详细摘要同一个写法。""" - schema = (getattr(source, "schema_cache", None) or {}).get("schema") - return (f"- {source.name}({source.kind},{'只读' if source.readonly else '可写'}):" - f"{source.description or '未填说明'}" + (f"|schema:{schema}" if schema else "")) - - -def _route_line(a: str, b: str, path: tuple[JoinEdge, ...], qualified) -> str: - first, second = path - qa, mid, qb = qualified(a), qualified(first.to_table), qualified(b) - return (f" {qa} 与 {qb} 没有直接关联,经 {mid} 连接:FROM {qa} JOIN {mid} ON {_condition(first, qualified)} " - f"JOIN {qb} ON {_condition(second, qualified)}" + (INFERRED_MARK if any(e.status == "proposed" for e in path) - else "")) - - -def _selected_block(s: SourceContext) -> str: - """挑了表的源:挑中的表给全部字段和目录,然后是连接条件、连接路径,其余表只列名字。""" - lead = "按这一轮的需求挑出" if s.selected_by == "model" else "现有工作流用到" - blocks, noted = [], False - for key in s.tables: - blocks += [f" {line}" for line in introspect.describe_table(s.source, key).split("\n")] - body = _notes_body(s, key) - if body: - noted = True - blocks.append(" 数据目录:") - blocks += [f" {line}" for line in body] - lines = [_source_head(s.source), - f" {lead}的 {len(s.tables)} 张表(全部字段{',有数据目录的附在表后' if noted else ''}):", *blocks] - lines += _join_lines(s, s.graph, s.tables) - if s.routes: - lines.append(" 连接路径:") - lines += [_route_line(a, b, path, s.qualified) for a, b, path in s.routes[:PATH_LINES_LIMIT]] - shown = set(s.tables) - rest = [s.qualified(t) for t in s.plan.tables if t not in shown] - if rest: - lines.append(f" 其余 {len(rest)} 个对象只列名字(要用时先用 db_schema__{s.source.name} 查字段,别猜):" - + "、".join(rest)) - return "\n".join(lines) + return await looks.look({"op": "look", "need": need, "targets": targets}, by="system") __all__ = [ - "CATALOG_BUDGET_CHARS", "CONTEXT_TABLE_LIMIT", "ContextPlan", "DATASOURCE_BUDGET_CHARS", "DETAIL_TABLE_LIMIT", - "DatasourceContext", "PICK_LIMIT", "PICK_MAX_TOKENS", "PICK_TIMEOUT_S", "SourceContext", "SourcePlan", - "graph_tables", "pick_model", "plan_context", + "LOOK_WHEN_PROMPT", "SQL_RULES_PROMPT", "SYSTEM_LOOK_FIX_NEED", "SYSTEM_LOOK_UPGRADE_NEED", "graph_tables", + "look_service", "section", "system_look", ] diff --git a/backend/app/api/copilot_gen.py b/backend/app/api/copilot_gen.py new file mode 100644 index 00000000..0670ceab --- /dev/null +++ b/backend/app/api/copilot_gen.py @@ -0,0 +1,639 @@ +"""助手的生成过程(总方案 L1,look 文档 D9):画布改图、问数据、发布前修复、升级证据、应用润色共用一个循环。 + +循环只管四件事:读到 look 就停下、执行查看、接着写、计次数和上限。怎么落地(Applier)、怎么自查(Checker)由调用方 +注入(app/look/base.py 的协议):图用 GraphApplier / GraphChecker,应用用 AppApplier / AppChecker。 + +**接着写时的消息结构**(look 文档 §2.5.5): + [system] 和起草时相同,不变 + [human] 这一轮的请求(含历史) + [assistant] 模型到 look 那一行为止的输出(look 之后的内容已丢弃) + [human] 查看结果 + 「接着输出操作,已经落地的不要重复」+ 已落地的对象 id +看几次就重复几组 assistant / human。已落地的操作由 Applier 去重:完全相同的 add_edge 忽略、和已落地节点完全相同的 +add_node 不转发、plan 只留第一次。 + +**ask。** 模型输出 {"op":"ask","question":…} 时这一轮就结束:循环里不等用户回答,不再自查修正;已经落地的改动照常 +交付(附上自查问题),用户的回答就是下一轮。 + +**自查修正。** 起草完由 Checker 找出挡路的问题,交回模型改(最多 SELF_CHECK_ROUNDS 轮);修正请求里带上这一轮的查看 +结果(和起草时看到的是同一份文字),修正阶段另给 REPAIR_LOOK_LIMIT 次查看。 + +copilot.py 原来的读流(_iter_ops)、解析(_parse_op_line)、落地(_apply_op、merge_node_config)搬到这里,copilot.py +照原名再导出。 +""" +from __future__ import annotations + +import copy +import json +import time +from collections.abc import AsyncIterator +from contextlib import aclosing +from typing import Any + +from app.engine.schema import NodeType +from app.look.base import LOOK_LIMIT, REPAIR_LOOK_LIMIT, Applied, Applier, Checker, LookBudget +from app.look.service import LookService +from app.providers.budget import cut_off as _cut_off + +#: 自查最多交回去改几轮。一轮只花一次"只输出改动"的调用;两轮还改不好,多半是需求本身有歧义,该让人看了 +SELF_CHECK_ROUNDS = 2 +#: 读到这几种操作就停下:done 说完了,look 要查看,ask 要等用户回答 +_STOP_OPS = ("done", "look", "ask") +#: 不占次数的查看回话(need 没写、次数用完)连着来几次就不再接着写:模型在原地打转,再要下去只是花钱 +_IDLE_LOOKS = 2 + + +# ========================================================================== +# 读流 +# ========================================================================== + + +def _parse_op_line(line: str) -> dict[str, Any] | None: + """解析一行操作。围栏行、空行、解析失败、缺 op 的一律返回 None—— + 模型偶尔犯规不该毁掉整条流,跳过就是。""" + text = line.strip() + if not text or text.startswith("```"): + return None + try: + obj = json.loads(text) + except json.JSONDecodeError: + return None + if not isinstance(obj, dict) or "op" not in obj: + return None + return obj + + +class CopilotIncomplete(Exception): + """模型这一轮没说完:输出被截断,或者一个操作都没给。画布不能按「无需修改」交付。""" + + def __init__(self, reason: str, *, hint: str = "", detail: str = "") -> None: + super().__init__(reason) + self.hint = hint or "画布未修改。可以重试,或把需求拆成几步分别提出" + self.detail = detail + + +async def _iter_ops(model: Any, messages: list[Any], *, lines: list[str] | None = None): + """流式读模型输出,按行切出操作。done、look、ask 之后即停——后面就算有闲话也不要了;look 之后停下也就是 + 「读到这一行就停止本次输出」,模型那条流随之关掉。 + + 除了操作,还把模型的思考原样转出去(thinking_text:Claude 的 thinking 块、OpenAI 兼容系的 reasoning_content), + 不把非 JSON 行当成思考。lines 给了的话,认出来的操作行原样记进去:接着写时作为 assistant 消息交回模型。 + + 没等到 done 就因为额度用完停下的,抛 CopilotIncomplete:截断之前的操作照常转出去,由调用方决定整轮作废。 + """ + from app.engine.state import message_text as _text + from app.engine.state import thinking_text + + buffer = "" + cut = "" + async with aclosing(model.astream(messages)) as stream: + async for chunk in stream: + reasoning = thinking_text(chunk) + if reasoning: + yield {"op": "thinking", "delta": reasoning} + + buffer += _text(chunk) + while "\n" in buffer: + line, buffer = buffer.split("\n", 1) + op = _parse_op_line(line) + if op: + if lines is not None: + lines.append(line.strip()) + yield op + if op.get("op") in _STOP_OPS: + return + cut = _cut_off(chunk) or cut + op = _parse_op_line(buffer) + if op: + if lines is not None: + lines.append(buffer.strip()) + yield op + if op.get("op") in _STOP_OPS: + return + if cut: + # 截断的流和说完了的流读起来一模一样:不在这里拦下,上面就会拿原图(或半张图) + # 去自查、交付,界面上写「无需修改」 + limit = getattr(model, "max_tokens", None) + raise CopilotIncomplete( + "模型的输出超出了长度上限,修改没有写完", + detail=f"finish_reason={cut}" + (f",本轮输出上限 {limit} token" if limit else "")) + + +# ========================================================================== +# 图的落地 +# ========================================================================== + +_NODE_TYPES = frozenset(t.value for t in NodeType) + +#: 协作成员条目里写 "remove": true 就把这个成员拿掉。不复用 null:null 在合并里 +#: 的意思是「删这个字段」,成员本身不是一个字段 +_REMOVE_MEMBER = "remove" + + +def _member_key(member: dict[str, Any], index: int) -> str: + # 和 engine/nodes/multi.py 的叫法一致:没起名字的成员按位置叫 agentN + return str(member.get("name") or f"agent{index}") + + +def _merge_fields(old: dict[str, Any], patch: dict[str, Any]) -> dict[str, Any]: + """按字段合并:写了的覆盖,写 null 的删掉,没写的原样保留。返回新 dict。""" + out = dict(old) + for key, value in patch.items(): + if value is None: + out.pop(key, None) + else: + out[key] = value + return out + + +def _merge_members(old: list[Any], patch: list[Any]) -> list[Any]: + """协作成员按 name 合并。原有成员保持原来的次序,新名字接在后面。""" + merged: list[Any] = list(old) + where = {_member_key(m, i): i for i, m in enumerate(merged) if isinstance(m, dict)} + dropped: set[int] = set() + for i, entry in enumerate(patch): + if not isinstance(entry, dict): + continue + key = _member_key(entry, i) + if entry.get(_REMOVE_MEMBER) is True: + if key in where: + dropped.add(where[key]) + continue + fields = {k: v for k, v in entry.items() if k != _REMOVE_MEMBER} + if key in where: + merged[where[key]] = _merge_fields(merged[where[key]], fields) + else: + where[key] = len(merged) + merged.append({k: v for k, v in fields.items() if v is not None}) + return [m for i, m in enumerate(merged) if i not in dropped] + + +def merge_node_config( + node_type: str, old: dict[str, Any], patch: dict[str, Any] +) -> dict[str, Any]: + """update_node 的 config 怎么落到节点上。前端 store/studio.ts 必须是同一套规则。 + + 以前是整体替换:模型只想改一句提示词,照协议也得把整份 config 抄一遍, + 漏抄的字段就没了。真出过事——改写提示词时漏了 tools,三个要查库的 agent + 全丢了工具,一次库都没查,最后把一堆工具调用的原始标记当答案交了出去。 + 改成按字段合并之后,漏写等于不改;真要删一个字段得显式写 null。 + """ + if node_type == NodeType.SUPERVISOR.value and isinstance(patch.get("agents"), list): + members = old.get("agents") if isinstance(old.get("agents"), list) else [] + patch = {**patch, "agents": _merge_members(members, patch["agents"])} + return _merge_fields(old, patch) + + +def _apply_op(nodes: dict[str, dict[str, Any]], edges: list[dict[str, Any]], op: dict[str, Any]) -> bool: + """把一个操作应用到服务端维护的图状态。返回是否真的改了图。""" + kind = op.get("op") + if kind == "add_node": + node = op.get("node") or {} + # 类型不认识的节点不进图、也不转给前端:前端按类型查节点定义,查不到 + # 以前是整站白屏,连带没保存的编辑一起丢 + if not node.get("id") or node.get("type") not in _NODE_TYPES: + return False + nodes[node["id"]] = { + "id": node["id"], + "type": node["type"], + "position": {"x": 0, "y": 0}, + "data": {"label": node.get("label") or "", "config": node.get("config") or {}}, + } + return True + if kind == "update_node": + node = nodes.get(op.get("id") or "") + if not node: + return False + data = node.setdefault("data", {}) + if op.get("label") is not None: + data["label"] = op["label"] + if isinstance(op.get("config"), dict): + data["config"] = merge_node_config( + str(node.get("type") or ""), data.get("config") or {}, op["config"]) + return True + if kind == "remove_node": + node_id = op.get("id") + if node_id not in nodes: + return False + nodes.pop(node_id) + edges[:] = [e for e in edges if e["source"] != node_id and e["target"] != node_id] + return True + if kind == "add_edge": + edge = op.get("edge") or {} + if not edge.get("source") or not edge.get("target"): + return False + edges.append( + { + "source": edge["source"], + "target": edge["target"], + "sourceHandle": edge.get("sourceHandle"), + } + ) + return True + if kind == "remove_edge": + before = len(edges) + edges[:] = [ + e + for e in edges + if not ( + e["source"] == op.get("source") + and e["target"] == op.get("target") + and (op.get("sourceHandle") is None or e.get("sourceHandle") == op.get("sourceHandle")) + ) + ] + return len(edges) != before + return False + + +class GraphApplier: + """图的落地:_apply_op 改服务端维护的图(nodes、edges 原地改,调用方手里的同一份),外加这一轮要记下的东西。 + + - seen:起草时收到的图操作(含 plan、done),兜底重放到上一轮的图上时用(replay_onto) + - tried / effective:试过的、真改了图的操作(发布前修复、升级按它们复核) + - replied:模型说这句话不需要工作流时的 reply;之后只再收目录修改提案 + - questions:发布前修复、升级里模型要人拿主意的 question(questions=True 时 reply 也算在里面) + - skipped_types:模型编出来的节点类型,收尾时说出来 + + patches:目录修改提案转不转(只有用户亲口说了数据事实的画布、问数据才转)。 + """ + + def __init__(self, nodes: dict[str, dict[str, Any]], edges: list[dict[str, Any]], *, patches: bool = True, + questions: bool = False) -> None: + self.nodes = nodes + self.edges = edges + self.patches = patches + self.questions_mode = questions + self.seen: list[dict[str, Any]] = [] + self.tried: list[dict[str, Any]] = [] + self.effective: list[dict[str, Any]] = [] + self.skipped_types: list[str] = [] + self.questions: list[dict[str, Any]] = [] + self.replied: dict[str, Any] | None = None + self.plan: dict[str, Any] | None = None + self.explanation = "" + # 建完要不要跑,由模型在 done.run 里表态 + self.autorun = True + self._landed: list[str] = [] + self._continuing = False + self._repairing = False + + def apply(self, op: dict[str, Any]) -> Applied: + kind = op.get("op") + if kind == "catalog_patch": + # 目录修改提案不进图:转给调用方核对后做成卡片(人点「保存」才写) + return Applied(False, self.patches and not self._repairing) + if kind in ("question", "reply") and self.questions_mode: + self.questions.append(op) + return Applied(False, False) + if self._repairing and kind == "reply": + return Applied(False, False) + if self.replied is not None: + return Applied(False, False) + if kind == "reply": + # 这句话不需要工作流:先压着,等模型说完(只再收它后面的提案)由调用方转出、收尾 + self.replied = op + return Applied(False, False) + if kind == "plan": + if self.plan is not None and self._continuing: + return Applied(False, False) + self.plan = self.plan or op + self.seen.append(op) + return Applied(False, True) + if kind == "done": + self.explanation = str(op.get("explanation", "")) + # 用户要的是流程本身时("设计一个每天跑的工作流"),建完就跑等于替他多花一次钱 + self.autorun = op.get("run") is not False + self.seen.append(op) + return Applied(False, True) + if self._continuing and self._repeats(op): + return Applied(False, False) + self.seen.append(op) + self.tried.append(op) + changed = _apply_op(self.nodes, self.edges, op) + if changed: + self.effective.append(op) + nid = (op.get("node") or {}).get("id") if kind == "add_node" else op.get("id") + if isinstance(nid, str) and nid not in self._landed and kind in ("add_node", "update_node"): + self._landed.append(nid) + elif kind == "add_node": + bad = (op.get("node") or {}).get("type") + if bad and bad not in _NODE_TYPES: + self.skipped_types.append(str(bad)) + return Applied(changed, changed) + + def _repeats(self, op: dict[str, Any]) -> bool: + """接着写时和已落地完全相同的操作(look §2.5.5):已有的同一条连线、和已落地节点一模一样的节点、重发的同一个操作。""" + kind = op.get("op") + if kind == "add_edge": + edge = op.get("edge") or {} + return any(e["source"] == edge.get("source") and e["target"] == edge.get("target") + and e.get("sourceHandle") == edge.get("sourceHandle") for e in self.edges) + if kind == "add_node": + node = op.get("node") or {} + have = self.nodes.get(str(node.get("id") or "")) + return have is not None and have.get("type") == node.get("type") \ + and (have.get("data") or {}).get("label") == (node.get("label") or "") \ + and (have.get("data") or {}).get("config") == (node.get("config") or {}) + return op in self.effective + + def landed(self) -> list[str]: + return list(self._landed) + + def continuing(self) -> None: + self._continuing = True + + def repairing(self) -> None: + self._repairing = True + + def replay_onto(self, graph: dict[str, Any]) -> None: + """一个操作都没落地、而上一轮有图时:模型把这一轮当成「改上一张图」,只发了改动操作,而累加器是从空图起步的。 + 与其报一句「图是空的」,不如按它本来的意思做——把这些操作重放到上一轮那张图上。""" + self.nodes.clear() + self.nodes.update({n["id"]: copy.deepcopy(n) for n in graph.get("nodes") or [] if n.get("id")}) + # 原地改,不能重新绑定:调用方手里拿的是同一份 + self.edges[:] = [{k: v for k, v in e.items() if k in ("source", "target", "sourceHandle") and v} + for e in graph.get("edges") or []] + for op in self.seen: + _apply_op(self.nodes, self.edges, op) + + +class GraphChecker: + """图的自查:按运行时同一套规则(copilot._blocking_issues)挑出挡路的问题,交回模型改。 + + known 给了(升级证据):只把这一轮冒出来的问题交回去(图上原来就有的不归这一轮管),一个修改都没落地时不修。 + """ + + def __init__(self, applier: GraphApplier, *, scope: set[str] | None = None, sources: list[Any] | None = None, + baseline: list[dict[str, Any]] | None = None, level: str | None = None, + defaults: dict[str, Any] | None = None, checkers: dict[str, Any] | None = None, + known: set[Any] | None = None) -> None: + self.applier = applier + self.scope = scope + self.sources = sources + self.baseline = baseline + self.level = level + self.defaults = defaults + self.checkers = checkers + self.known = known + + def blocking(self) -> list[dict[str, Any]] | None: + from app.api.copilot import _blocking_issues + + return _blocking_issues(self.applier.nodes, self.applier.edges, self.scope, sources=self.sources, + baseline=self.baseline, level=self.level, defaults=self.defaults, + checkers=self.checkers) + + async def issues(self) -> list[dict[str, Any]]: + errors = self.blocking() + if self.known is None: + return errors or [] + from app.engine.autofix import _sig + + if not self.applier.effective: + return [] + return [e for e in errors or [] if _sig(e) not in self.known] + + def repair_request(self, issues: list[dict[str, Any]], looks_text: str) -> str: + from app.api.copilot import _repair_request + + return _repair_request(self.applier.nodes, self.applier.edges, issues, looks=looks_text) + + +# ========================================================================== +# 应用的落地 +# ========================================================================== + +APP_REPAIR_PROMPT = ( + "这是你刚改好的应用草稿:\n{spec}\n\n" + "应用检查(和发布同一套规则)发现下面这些问题:\n{issues}\n\n" + "只修这些问题,别的不要动。用应用操作输出修正;岗位绑定要人来做,不要替人绑。最后一行输出 done。{looks}" +) +REPAIR_LOOKS_PROMPT = "\n\n这一轮查看过的内容(和起草时看到的是同一份):\n{text}" + +#: 应用检查里只有人能处理的问题:钉住哪个版本、升版怎么处置、岗位和核实人绑给谁、授权、通知渠道。不交回模型改, +#: 照常列在交付的问题里 +APP_HUMAN_ONLY = frozenset({ + "app.pin_unpublished", "app.pin_retired", "app.pin_hash", "app.upgrade_policy", "app.slot_unbound", + "app.reconciler_unbound", "app.acl_empty", "app.notify_channel_missing", "app.process_unsafe", + "app.view_source_empty", +}) + + +def _components(items: list[Any]) -> list[dict[str, Any]]: + out: list[dict[str, Any]] = [] + for item in items or []: + if isinstance(item, dict): + out.append(item) + out += _components(item.get("children") or []) + return out + + +def app_component(spec: dict[str, Any], component_id: str) -> dict[str, Any] | None: + """spec 里按 id 找组件(各页的组件树,含子组件)。""" + for page in spec.get("pages") or []: + for item in _components(page.get("body") or [] if isinstance(page, dict) else []): + if item.get("id") == component_id: + return item + return None + + +class AppApplier: + """应用的落地:app/apps/ops.apply_app_op 改 spec(原地改),外加接着写时的去重。 + + plan、done 记下说明;reply 记下(这句话不需要改应用);图操作、目录修改提案在这里一概不收。 + """ + + def __init__(self, spec: dict[str, Any]) -> None: + self.spec = spec + self.effective: list[dict[str, Any]] = [] + self.plan: dict[str, Any] | None = None + self.replied: dict[str, Any] | None = None + self.explanation = "" + self._landed: list[str] = [] + self._continuing = False + self._repairing = False + + def apply(self, op: dict[str, Any]) -> Applied: + from app.apps import ops as app_ops + + kind = str(op.get("op") or "") + if kind == "plan": + if self.plan is not None and self._continuing: + return Applied(False, False) + self.plan = self.plan or op + return Applied(False, True) + if kind == "done": + self.explanation = str(op.get("explanation", "")) + return Applied(False, True) + if kind == "reply": + if self.replied is None and not self._repairing: + self.replied = op + return Applied(False, False) + if not kind.startswith("app_"): + return Applied(False, False) + if self._continuing and self._repeats(op): + return Applied(False, False) + applied = app_ops.apply_app_op(self.spec, op) + if applied.changed: + self.effective.append(op) + target = op.get("id") or (op.get("component") or {}).get("id") or (op.get("page") or {}).get("id") \ + or op.get("key") + if isinstance(target, str) and target not in self._landed: + self._landed.append(target) + return applied + + def _repeats(self, op: dict[str, Any]) -> bool: + """接着写时:重发的同一个操作;加一个 spec 里已经一模一样存在的组件。""" + if op in self.effective: + return True + if op.get("op") == "app_add": + component = op.get("component") or {} + have = app_component(self.spec, str(component.get("id") or "")) + return have is not None and have == component + return False + + def landed(self) -> list[str]: + return list(self._landed) + + def continuing(self) -> None: + self._continuing = True + + def repairing(self) -> None: + self._repairing = True + + +class AppChecker: + """应用的自查:app/apps/lint.lint_app 的 error,去掉只有人能处理的(APP_HUMAN_ONLY),交回模型改。""" + + def __init__(self, applier: AppApplier, *, bindings: dict[str, Any] | None = None) -> None: + self.applier = applier + self.bindings = bindings or {} + + async def lint(self) -> list[dict[str, Any]]: + """全部问题(各级都在),交付时列出来。另开短会话:流里请求的会话已经不能用了。""" + from app.apps import lint as app_lint + from app.db.base import SessionLocal + + async with SessionLocal() as session: + return list(await app_lint.lint_app(session, self.applier.spec, self.bindings)) + + async def issues(self) -> list[dict[str, Any]]: + return [i for i in await self.lint() if i.get("level") == "error" and i.get("code") not in APP_HUMAN_ONLY] + + def repair_request(self, issues: list[dict[str, Any]], looks_text: str) -> str: + lines = "\n".join(f"- {i.get('path') or ''} {i.get('message') or ''}".strip() for i in issues) + return APP_REPAIR_PROMPT.format(spec=json.dumps(self.applier.spec, ensure_ascii=False, indent=2), + issues=lines, + looks=REPAIR_LOOKS_PROMPT.format(text=looks_text) if looks_text else "") + + +# ========================================================================== +# 生成过程 +# ========================================================================== + + +class Generation: + """一轮生成:起草(draft)→ 自查修正(repair)。两段之间调用方可以插自己的判断(只回答了一句、兜底重放……)。 + + model 是按操作流写的模型(copilot._op_model);looks 是这一轮的查看服务(app/look/service.py),起草和修正共用, + 看过的对象、交回过的文字都在里面。asked:模型问了用户一个问题(这一轮结束)。 + """ + + def __init__(self, model: Any, *, system: str, applier: Applier, checker: Checker | None = None, + looks: LookService | None = None, started: float | None = None) -> None: + self.model = model + self.system = system + self.applier = applier + self.checker = checker + self.looks = looks if looks is not None else LookService([]) + self.started = time.monotonic() if started is None else started + self.asked: dict[str, Any] | None = None + self.done: dict[str, Any] | None = None + self.repaired = 0 + self.repair_error: Exception | None = None + #: 这一轮调了几次主模型(含接着写、修正),验收时统计 + self.calls = 0 + + async def draft(self, request: str) -> AsyncIterator[dict[str, Any]]: + async for op in self._converse(request, LookBudget(LOOK_LIMIT), repair=False): + yield op + + async def repair(self, rounds: int = SELF_CHECK_ROUNDS) -> AsyncIterator[dict[str, Any]]: + """按 Checker 自查,挡路的问题交回模型改,改完再查。修不成(报错、截断)就停,照实发一条 check error,原因记在 + repair_error;改到第几轮记在 repaired。模型问了用户(asked)的这一轮不修。""" + if self.checker is None or self.asked is not None: + return + budget = LookBudget(REPAIR_LOOK_LIMIT) + self.applier.repairing() + for round_no in range(1, rounds + 1): + errors = await self.checker.issues() + if not errors: + break + yield {"op": "check", "status": "repairing", "round": round_no, "issues": errors} + request = self.checker.repair_request(errors, self.looks.looked()) + try: + async for op in self._converse(request, budget, repair=True): + yield op + except Exception as e: # noqa: BLE001 - 修不成就照实交付,调用方列出剩下的问题 + from app.core.errors import explain, raw + + self.repair_error = e + yield {"op": "check", "status": "error", "message": f"自查修正失败:{explain(e)[0]}", + "detail": raw(e)} + break + self.repaired = round_no + if self.asked is not None: + break + + def _elapsed(self) -> int: + return int((time.monotonic() - self.started) * 1000) + + async def _converse(self, request: str, budget: LookBudget, *, repair: bool) -> AsyncIterator[dict[str, Any]]: + """一段对话:请模型写,读到 look 就停下、查看、把结果作为下一条消息交回,再请它接着写,直到 done / ask / 流结束。""" + messages: list[tuple[str, str]] = [("system", self.system), ("human", request)] + idle = 0 + while True: + lines: list[str] = [] + look: dict[str, Any] | None = None + self.calls += 1 + async with aclosing(_iter_ops(self.model, messages, lines=lines)) as ops: + async for op in ops: + kind = op.get("op") + if kind == "thinking": + yield op + elif kind == "look": + look = op + elif kind == "ask": + self.asked = op + yield op + elif repair and kind in ("plan", "done"): + # 修补轮自己的开场和收尾,不是新方案,不覆盖原来的说明 + continue + else: + if kind == "done": + self.done = op + if self.applier.apply(op).forward: + yield op + if look is None: + return + # 查看可能要等挑选模型:心跳的阶段换成「正在查看」 + yield {"op": "heartbeat", "phase": "looking", "elapsed_ms": self._elapsed()} + result = await self.looks.look(look, budget) + if result.record is not None: + yield result.record + if not result.counted: + idle += 1 + if idle >= _IDLE_LOOKS: + return + messages = [*messages, ("ai", "\n".join(lines)), + ("human", result.text + self.looks.continue_prompt(self.applier.landed()))] + self.applier.continuing() + + +async def generate(model: Any, system: str, request: str, applier: Applier, checker: Checker | None = None, + looks: LookService | None = None, *, rounds: int = SELF_CHECK_ROUNDS) -> AsyncIterator[dict[str, Any]]: + """附录 C 的生成过程协议:起草(含查看)→ 自查修正,产出一串操作和事件。中间不需要插判断的调用方直接用它。""" + gen = Generation(model, system=system, applier=applier, checker=checker, looks=looks) + async for op in gen.draft(request): + yield op + async for op in gen.repair(rounds): + yield op diff --git a/backend/app/api/datasources.py b/backend/app/api/datasources.py index f2a9e008..8724c925 100644 --- a/backend/app/api/datasources.py +++ b/backend/app/api/datasources.py @@ -828,14 +828,16 @@ async def get_schema(source_id: str, table: str | None = None, except table_versions.SnapshotMissing as e: raise HTTPException(409, str(e)) from e if table: + from app.data import schema_view + meta = introspect_mod.find_table(row, table) - # 和 db_schema 工具同一个说法:有数据目录的表,字段清单后面附上目录 + # 和 db_schema 工具、助手查看同一个说法(schema_view.table_detail):有数据目录的表,字段清单后面附上目录; + # 遮罩列只给列名和类型 entries = await data_catalog.read_catalog(session, found.id) return { "table": table, - # 给模型看的那段文本照旧;界面画表格用下面的结构化字段 - "detail": introspect_mod.describe_table(row, table, - catalog={n: e.notes for n, e in entries.items()}), + # 给模型看的那段文本;界面画表格用下面的结构化字段 + "detail": schema_view.table_detail(row, table, catalog_notes={n: e.notes for n, e in entries.items()}), "found": meta is not None, "qualified": meta.get("qualified", table) if meta else None, "kind": ("view" if meta.get("is_view") else "table") if meta else None, diff --git a/backend/app/data/schema_view.py b/backend/app/data/schema_view.py new file mode 100644 index 00000000..80b3cb12 --- /dev/null +++ b/backend/app/data/schema_view.py @@ -0,0 +1,258 @@ +"""数据源的只读表结构视图:库概览、表目录、表详情(字段、数据目录、连接条件、两跳的连接路径)。 + +助手查看(app/look/tables.py)、运行时 agent 的 db_schema__(tools/datasource.py)、/api/datasources/{id}/schema?table= +三处共用这一份(look 文档 D6:同一张表只有一种说法,同一套遮罩规矩)。以前三处各拼各的:助手的小库摘要每张表只列 +前 6 列,db_schema 和助手又都把遮罩列的目录原样交给模型。 + +**遮罩规矩。** 遮罩列(data/engine.py 的 masked_columns,按列名设在整个数据源上)只给列名和类型:它的注释、目录里 +这一列的各项(含码值、带具体取值的说明)都不给。和表助手(data/catalog_assistant.py)是同一条规矩。代价是运行时 +agent 看到的目录少了遮罩列那部分(README 写明)。 + +只读:只看表结构缓存(schema_cache)和调用方读好的数据目录,不碰业务库。这里的文字都是写给模型看的,不上界面。 +""" +from __future__ import annotations + +import copy +from collections.abc import Iterable, Mapping +from typing import Any + +from app.data import catalog, introspect +from app.data.catalog import CARDINALITY_LABEL, INFERRED_MARK, JoinEdge +from app.data.engine import masked_columns + +#: 一个源最多列多少条连接条件、多少条连接路径 +JOIN_LINES_LIMIT = 40 +PATH_LINES_LIMIT = 12 + +# ========================================================================== +# 写给模型的文字 +# ========================================================================== + +OVERVIEW_LINE_PROMPT = "- {name}({kind},{access}):{description}|{state}" +OVERVIEW_TABLES_PROMPT = "共 {total} 张表" +OVERVIEW_PARTIAL_PROMPT = "共 {total} 张表,只探查了 {explored} 张" +OVERVIEW_CATALOG_ALL_PROMPT = "都有数据目录" +OVERVIEW_CATALOG_SOME_PROMPT = "{n} 张有数据目录" +OVERVIEW_CATALOG_NONE_PROMPT = "还没有数据目录" +OVERVIEW_MASKED_PROMPT = "设了遮罩" +OVERVIEW_SCHEMAS_PROMPT = "该账号名下没有对象,数据可能在这些 schema:{names}" +MASKED_COLUMN_PROMPT = "已遮罩,只给列名和类型" +BRIEF_PROMPT = "{name}[{kind}]:{columns}(全部 {n} 列,字数超了只给字段名,要看字段说明和目录时点名再 look)" +JOIN_HEAD_PROMPT = "表之间的连接条件(写 JOIN … ON … 时照抄):" +JOIN_MORE_PROMPT = "…另有 {n} 条,点名查看相关的表看各表的关联关系" +PATH_HEAD_PROMPT = "连接路径:" +ROUTE_PROMPT = "{a} 与 {b} 没有直接关联,经 {mid} 连接:FROM {a} JOIN {mid} ON {first} JOIN {b} ON {second}" + + +# ========================================================================== +# 遮罩 +# ========================================================================== + + +def masked_set(source: Any) -> set[str]: + """这个源的遮罩列(小写)。""" + return {c.lower() for c in masked_columns(getattr(source, "options", None))} + + +def _masked_meta(meta: Mapping[str, Any], masked: set[str]) -> dict[str, Any]: + """表结构里遮罩列的注释抹掉:注释里常有取值说明(「1=男 2=女」),遮罩列只给列名和类型。""" + out = dict(meta) + out["columns"] = [{**col, "comment": None} if str(col.get("name") or "").lower() in masked else col + for col in meta.get("columns") or [] if isinstance(col, Mapping)] + return out + + +def masked_notes(notes: Mapping[str, Any] | None, masked: set[str]) -> dict[str, Any]: + """目录里遮罩列的各项整列去掉(含码值和说明)。表级的项、关联关系只是列名,照给。""" + out = copy.deepcopy(dict(notes or {})) + columns = out.get("columns") + if masked and isinstance(columns, dict): + out["columns"] = {name: items for name, items in columns.items() if str(name).lower() not in masked} + return out + + +# ========================================================================== +# 库概览、表目录 +# ========================================================================== + + +def overview_line(source: Any, *, catalog_tables: int) -> str: + """system 里一个库一行:名称、类型、是否只读、说明、表数(没探查全时写明)、有数据目录的表数、有没有设遮罩; + 没探查或探查失败的写原因(introspect.why_empty)。""" + cache = getattr(source, "schema_cache", None) or {} + tables = cache.get("tables") or {} + if not tables: + state = introspect.why_empty(cache) + if candidates := cache.get("available_schemas"): + state += "," + OVERVIEW_SCHEMAS_PROMPT.format(names="、".join(candidates[:8])) + else: + total = cache.get("total") + total = max(total if isinstance(total, int) and not isinstance(total, bool) else 0, len(tables)) + parts = [OVERVIEW_PARTIAL_PROMPT.format(total=total, explored=len(tables)) if cache.get("truncated") + and total > len(tables) else OVERVIEW_TABLES_PROMPT.format(total=total)] + if catalog_tables >= len(tables): + parts.append(OVERVIEW_CATALOG_ALL_PROMPT) + elif catalog_tables: + parts.append(OVERVIEW_CATALOG_SOME_PROMPT.format(n=catalog_tables)) + else: + parts.append(OVERVIEW_CATALOG_NONE_PROMPT) + if masked_set(source): + parts.append(OVERVIEW_MASKED_PROMPT) + state = ",".join(parts) + return OVERVIEW_LINE_PROMPT.format( + name=source.name, kind=source.kind, access="只读" if source.readonly else "可写", + description=source.description or "未填说明", state=state) + + +def table_index(source: Any, notes_by_table: Mapping[str, Mapping[str, Any]], *, + tables: Iterable[str] | None = None) -> str: + """紧凑的表目录,每张表一行:表名|中文名|粒度(catalog.render_table_index)。挑选失败时交回给模型点名。""" + return catalog.render_table_index(getattr(source, "schema_cache", None), notes_by_table, tables=tables) + + +# ========================================================================== +# 表详情 +# ========================================================================== + + +def table_detail(source: Any, table: str, *, catalog_notes: Mapping[str, Mapping[str, Any]] | None = None) -> str: + """单表的完整字段说明,有可给模型看的目录时附在后面;遮罩列只给列名和类型。 + + catalog_notes 是这个源的数据目录 {表名: notes}(原样,含驳回项:render_table_notes 自己去掉)。找不到这张表时 + 交回的几种说法(结构没探查、只探查了一部分、确实没有)和 introspect.describe_table 一样。 + """ + meta = introspect.find_table(source, table) + if not meta: + return introspect.describe_table(source, table) + masked = masked_set(source) + shown = _masked_meta(meta, masked) + head = f"{'视图' if meta.get('is_view') else '表'} {meta.get('qualified', table)}" + if meta.get("comment"): + head += f"({meta['comment']})" + lines = [head] + pk = set(meta.get("primary_key") or []) + for col in shown["columns"]: + marks = [] + if str(col.get("name") or "").lower() in masked: + marks.append(MASKED_COLUMN_PROMPT) + else: + if col["name"] in pk: + marks.append("主键") + if not col.get("nullable", True): + marks.append("非空") + if col.get("comment"): + marks.append(col["comment"]) + suffix = f" {'、'.join(marks)}" if marks else "" + lines.append(f" {col['name']} {col.get('type') or ''}{suffix}") + if catalog_notes: + key = catalog.resolve_table_name(getattr(source, "schema_cache", None), table) + block = catalog.render_table_notes(masked_notes(catalog_notes.get(key) if key else None, masked), + meta=shown, system_notes=catalog.system_notes_source(source)) + if block: + lines.append(block) + return "\n".join(lines) + + +def table_brief(source: Any, table: str) -> str: + """字数超了时的一行:表名和全部字段名(遮罩列的名字照给,名字本身不是值)。""" + meta = introspect.find_table(source, table) or {} + columns = [str(c.get("name")) for c in meta.get("columns") or [] if isinstance(c, Mapping) and c.get("name")] + return BRIEF_PROMPT.format(name=meta.get("qualified", table), kind="视图" if meta.get("is_view") else "表", + columns="、".join(columns), n=len(columns)) + + +# ========================================================================== +# 连接条件与连接路径 +# ========================================================================== + + +def relation_graph(source: Any, raw_notes: Mapping[str, Mapping[str, Any]]) -> dict[str, list[JoinEdge]]: + """这个源的关系图:目录里的关系(驳回的不进,驳回项还要压住同一条关系的现推结果,所以给原样的目录)加上按表结构 + 现推的(外键约束、命名推断)。""" + return catalog.relation_graph(raw_notes, schema_cache=getattr(source, "schema_cache", None)) + + +def complete(picked: list[str], graph: Mapping[str, list[JoinEdge]], + room: int) -> tuple[list[str], list[tuple[str, str, tuple[JoinEdge, ...]]]]: + """补连接用的中间表:(给详情的表, [(a, b, 经中间表的两跳路径)])。room 是还能补几张。 + + 挑中的表两两之间已经直接相连的不补;有一条路径的中间表已经在里面的也不补。 + """ + tables = list(picked) + routes: list[tuple[str, str, tuple[JoinEdge, ...]]] = [] + for i, a in enumerate(picked): + for b in picked[i + 1:]: + if any(e.to_table == b for e in graph.get(a, ())): + continue + paths = [p for p in catalog.join_paths(graph, a, b, max_hops=2) if len(p) == 2] + via = next((p for p in paths if p[0].to_table in tables), None) + if via is None and paths and len(tables) - len(picked) < room: + via = paths[0] + tables.append(via[0].to_table) + if via is not None: + routes.append((a, b, via)) + return tables, routes + + +def qualifier(source: Any): + """表名(schema_cache 的键)→ 全名:模型照着全名写 SQL,漏了 schema 前缀在 Oracle 上直接报错。""" + tables = (getattr(source, "schema_cache", None) or {}).get("tables") or {} + return lambda key: str((tables.get(key) or {}).get("qualified") or key) + + +def _condition(edge: JoinEdge, qualified) -> str: + """连接条件,表名用全名:channel_visits.visit_id = visits.id(多列用 AND 连接)。""" + left, right = qualified(edge.from_table), qualified(edge.to_table) + return " AND ".join(f"{left}.{a} = {right}.{b}" for a, b in zip(edge.from_columns, edge.to_columns)) + + +def _edge_line(edge: JoinEdge, qualified) -> str: + card = f"({CARDINALITY_LABEL[edge.cardinality]})" if edge.cardinality in CARDINALITY_LABEL else "" + return _condition(edge, qualified) + card + (INFERRED_MARK if edge.status == "proposed" else "") + + +def _edges_within(graph: Mapping[str, list[JoinEdge]], tables: list[str]) -> list[JoinEdge]: + """两端都在 tables 里的关系,每条一次(按 relation_id);一对多的翻过来,从「多」的一端写起(外键所在的表在左)。""" + wanted = set(tables) + seen: set[str] = set() + out = [] + for table in tables: + for edge in graph.get(table, ()): + if edge.to_table not in wanted or edge.relation_id in seen: + continue + seen.add(edge.relation_id) + out.append(edge.reversed() if edge.cardinality == "one_to_many" else edge) + return out + + +def join_lines(source: Any, graph: Mapping[str, list[JoinEdge]], tables: list[str], *, indent: str = " ") -> list[str]: + """给出的几张表之间的连接条件,可以照抄进 SQL。没有就是空列表。""" + edges = _edges_within(graph, tables) + if not edges: + return [] + qualified = qualifier(source) + lines = [indent + JOIN_HEAD_PROMPT] + lines += [f"{indent} {_edge_line(e, qualified)}" for e in edges[:JOIN_LINES_LIMIT]] + if len(edges) > JOIN_LINES_LIMIT: + lines.append(indent + " " + JOIN_MORE_PROMPT.format(n=len(edges) - JOIN_LINES_LIMIT)) + return lines + + +def route_lines(source: Any, routes: list[tuple[str, str, tuple[JoinEdge, ...]]], *, indent: str = " ") -> list[str]: + """两张表没有直接关联、要经一张中间表连接的写法。""" + if not routes: + return [] + qualified = qualifier(source) + lines = [indent + PATH_HEAD_PROMPT] + for a, b, (first, second) in routes[:PATH_LINES_LIMIT]: + line = ROUTE_PROMPT.format(a=qualified(a), b=qualified(b), mid=qualified(first.to_table), + first=_condition(first, qualified), second=_condition(second, qualified)) + inferred = first.status == "proposed" or second.status == "proposed" + lines.append(f"{indent} {line}" + (INFERRED_MARK if inferred else "")) + return lines + + +__all__ = [ + "JOIN_LINES_LIMIT", "PATH_LINES_LIMIT", "complete", "join_lines", "masked_notes", "masked_set", "overview_line", + "qualifier", "relation_graph", "route_lines", "table_brief", "table_detail", "table_index", +] diff --git a/backend/app/look/__init__.py b/backend/app/look/__init__.py index de6b99ad..d8c3a94c 100644 --- a/backend/app/look/__init__.py +++ b/backend/app/look/__init__.py @@ -4,5 +4,8 @@ - tables.py 表(库概览、表目录、表详情,含遮罩;与 db_schema__、/schema 共用 data/schema_view.py) - capabilities.py 能力(只给操作名、参数、返回字段、读写、要不要确认;不给地址和凭据) - versions.py 工作流版本(应用润色时看钉住的版本;app/apps/describe.py) +- pick.py 按需求挑选:几种对象共用一份挑选提示词,挑选模型第一次要用时才拿 - service.py 解析 targets、按类型挑选、交回目录、字数上限、重复查看短路、产出记录 + +生成过程(读到 look 停下、执行、接着写)在 api/copilot_gen.py;各入口怎么组装在 api/copilot_context.py 和 api/copilot.py。 """ diff --git a/backend/app/look/base.py b/backend/app/look/base.py index 62b7e134..bb5d8c8a 100644 --- a/backend/app/look/base.py +++ b/backend/app/look/base.py @@ -35,14 +35,26 @@ class LookTarget(TypedDict, total=False): @dataclass class LookResult: + """一次查看交回给模型的文字,和发给前端、存进 meta.looks 的记录。 + + 记录为 None 的是没真正查看的那几种回话(need 没写、次数用完、重复查看),不发事件。counted:占不占这一轮的次数。 + """ + text: str - record: dict[str, Any] + record: dict[str, Any] | None + counted: bool = True class LookKind(Protocol): - """每种可查看的对象都实现同一组方法(L3)。遮罩按类型各自处理。""" + """每种可查看的对象都实现同一组方法(L3)。遮罩按类型各自处理。 + + detail 交回的记录块是 objects[] 里的若干项(表按库各一项,能力、工作流版本各一项);missing 是 resolve 认不出的 + 点名,由 detail 写进文字和记录。key 是一个对象在这一轮里的身份,重复查看靠它短路。 + """ kind: str + #: 写给模型的类别名:表、能力、工作流版本 + label: str async def overview(self) -> list[str]: """概览:进 system,每个来源一行。""" @@ -60,8 +72,12 @@ class LookKind(Protocol): """按需求挑选:(挑出的对象, 失败原因)。返回空列表且原因为 None 表示「按这个需求没有相关的」。""" ... - async def detail(self, objects: list[Any], budget: int) -> tuple[str, dict[str, Any]]: - """详情文字(受字数上限约束)和这一类的记录块(objects[] 里的一项)。""" + async def detail(self, objects: list[Any], budget: int, *, + missing: list[LookTarget] = ()) -> tuple[str, list[dict[str, Any]]]: + """详情文字(受字数上限约束)和这一类的记录块(objects[] 里的项)。""" + ... + + def key(self, obj: Any) -> str: ... @@ -86,6 +102,10 @@ class Applier(Protocol): """进入「接着写」:之后和已落地完全相同的操作忽略、不转发(look §2.5.5)。""" ... + def repairing(self) -> None: + """进入自查修正:plan、done 由循环吃掉;回答、目录修改提案这类只在起草时有意义的不再收。""" + ... + class Checker(Protocol): async def issues(self) -> list[dict[str, Any]]: ... diff --git a/backend/app/look/capabilities.py b/backend/app/look/capabilities.py new file mode 100644 index 00000000..24717a8c --- /dev/null +++ b/backend/app/look/capabilities.py @@ -0,0 +1,263 @@ +"""查看的对象之一:能力(总方案 L3、§5.3)。读能力登记(capabilities 表,BE-1 同步和治理)。 + +只给模型写图要用的:名字、所属系统、说明、参数、返回字段、读写效果、要不要确认。不给端点地址、认证头、凭据模式这些 +(登记的端点在 endpoints 表里,这里根本不读);遮罩字段只给字段名,参数的示例值、默认值一律不给。 + +问数据(意图为回答)时只列只读能力:写入能力不出现在概览里,点名查看也按没找到回(§2.11:问数据只能走只读)。 +""" +from __future__ import annotations + +from dataclasses import dataclass +from typing import Any + +from app.look.base import PICK_LIMIT, LookTarget +from app.look.pick import Picker, PickFailed + +# ========================================================================== +# 写给模型的文字 +# ========================================================================== + +OVERVIEW_HEAD_PROMPT = "可查看的能力(要看参数、返回字段、读写效果时用 look,kind 写 capability):" +OVERVIEW_LINE_PROMPT = "- {system}:{n} 个({effects})" +OVERVIEW_MORE_PROMPT = "- …另有 {n} 个来源" +EFFECT_PROMPT = {"read": "只读", "write": "写入", "dynamic": "视参数而定"} +APPROVAL_PROMPT = { + "confirm": "每次都要人确认", + "none": "只读能力,正式运行里不用审批", + "inherit": "跟随工具页的信任设置", +} +SYSTEM_LABEL_PROMPT = {"builtin": "内置工具", "custom": "自定义工具"} +DETAIL_HEAD_PROMPT = "· {name}({system}):{title}" +DETAIL_DESC_PROMPT = " 说明:{text}" +DETAIL_EFFECT_PROMPT = " 读写:{effect};确认:{approval}" +DETAIL_WRITE_PROMPT = " 写入能力只能放在调用工具节点里,运行时先确认再发送,参数在节点的 args 里按引用写" +DETAIL_PARAMS_PROMPT = " 参数:{items}" +DETAIL_RETURNS_PROMPT = " 返回字段:{items}" +DETAIL_TABULAR_PROMPT = " 返回结果按表格作证,可以像查询结果一样被报告和口径卡引用" +PARAM_PROMPT = "{name}({type}{required}){desc}" +FIELD_MASKED_PROMPT = "{name}(遮罩,只给字段名)" +BRIEF_PROMPT = "· {name}({system}):字数超过上限,只列名字,要看参数时点名再 look" +MISSING_PROMPT = "没找到能力:{items}(能力登记里没有它{answer};别拿名字相近的顶替)" +MISSING_ANSWER_PROMPT = ";问数据时只能查看只读能力" +INDEX_LINE_PROMPT = "{name}|{title}|{effect}" +INDEX_HEAD_PROMPT = "「{system}」:" +PICK_WHAT_PROMPT = "能力" +PICK_LINE_PROMPT = "每行一个能力:名字|标题|读写" + +#: 概览最多列几个来源 +OVERVIEW_SYSTEMS = 30 + + +@dataclass(frozen=True) +class CapabilityView: + """能力登记的一行,开流之前读好(流里不再碰请求的会话)。只留查看要用的字段。""" + + name: str + system: str + title: str + description: str + params_schema: dict[str, Any] + returns_schema: dict[str, Any] | None + tabular: dict[str, Any] | None + effect: str + approval: str + fields: dict[str, Any] + masked: tuple[str, ...] + version: int + + +def _system_label(system: str) -> str: + return SYSTEM_LABEL_PROMPT.get(system, system or "未归类") + + +class CapabilityKind: + kind = "capability" + label = "能力" + + def __init__(self, rows: list[CapabilityView], *, picker: Picker | None = None, read_only: bool = False) -> None: + self.read_only = read_only + self.rows = [r for r in rows if not read_only or r.effect == "read"] + self.by_name = {r.name: r for r in self.rows} + self.picker = picker + + @classmethod + async def load(cls, *, picker: Picker | None = None, read_only: bool = False) -> CapabilityKind: + """读能力登记里还在的那些(来源删掉了的 missing 行不列)。效果按治理后的值(effective_effect)。""" + from sqlalchemy import select + + from app.capabilities.registry import effective_effect, masked_paths + from app.db.base import SessionLocal + from app.db.models import Capability + + async with SessionLocal() as session: + found = (await session.execute( + select(Capability).where(Capability.missing.is_(False)).order_by(Capability.system, Capability.name) + )).scalars().all() + rows = [CapabilityView( + name=c.name, system=c.system or "", title=c.title or "", description=c.description or "", + params_schema=dict(c.params_schema or {}), returns_schema=c.returns_schema, tabular=c.tabular, + effect=effective_effect(c), approval=c.approval or "inherit", fields=dict(c.fields or {}), + masked=tuple(str(p) for p in masked_paths(c)), version=int(c.version or 1)) for c in found] + return cls(rows, picker=picker, read_only=read_only) + + # ---------------------------------------------------------------- 概览、目录 + + def _systems(self) -> dict[str, list[CapabilityView]]: + out: dict[str, list[CapabilityView]] = {} + for r in self.rows: + out.setdefault(r.system, []).append(r) + return out + + async def overview(self) -> list[str]: + systems = self._systems() + if not systems: + return [] + lines = [OVERVIEW_HEAD_PROMPT] + for system, rows in list(systems.items())[:OVERVIEW_SYSTEMS]: + counts = {e: sum(1 for r in rows if r.effect == e) for e in EFFECT_PROMPT} + effects = "、".join(f"{EFFECT_PROMPT[e]} {n} 个" for e, n in counts.items() if n) + lines.append(OVERVIEW_LINE_PROMPT.format(system=_system_label(system), n=len(rows), effects=effects)) + if len(systems) > OVERVIEW_SYSTEMS: + lines.append(OVERVIEW_MORE_PROMPT.format(n=len(systems) - OVERVIEW_SYSTEMS)) + return lines + + def _pool(self, sources: list[str] | None) -> list[CapabilityView]: + if not sources: + return list(self.rows) + wanted = set(sources) + return [r for r in self.rows if r.system in wanted or _system_label(r.system) in wanted] + + async def index(self, sources: list[str] | None) -> str: + blocks: dict[str, list[str]] = {} + for r in self._pool(sources): + blocks.setdefault(r.system, []).append(INDEX_LINE_PROMPT.format( + name=r.name, title=r.title or r.description[:40], effect=EFFECT_PROMPT.get(r.effect, r.effect))) + return "\n\n".join(INDEX_HEAD_PROMPT.format(system=_system_label(s)) + "\n" + "\n".join(lines) + for s, lines in blocks.items()) + + # ---------------------------------------------------------------- 点名、挑选 + + async def resolve(self, targets: list[LookTarget]) -> tuple[list[tuple[CapabilityView, str]], list[LookTarget]]: + found: list[tuple[CapabilityView, str]] = [] + missing: list[LookTarget] = [] + lowered = {r.name.lower(): r for r in self.rows} + for t in targets: + name = str(t.get("name") or "") + row = self.by_name.get(name) or lowered.get(name.lower()) + if row is None: + missing.append(t) + elif all(r.name != row.name for r, _ in found): + found.append((row, "named")) + return found, missing + + async def pick(self, need: str, sources: list[str] | None) -> tuple[list[tuple[CapabilityView, str]], str | None]: + pool = self._pool(sources) + if len(pool) <= PICK_LIMIT: + return [(r, "picked") for r in pool], None + if self.picker is None: + return [], "没有可用的挑选模型" + try: + picks = await self.picker.pick(need=need, what=PICK_WHAT_PROMPT, line=PICK_LINE_PROMPT, + index=await self.index(sources)) + except PickFailed as e: + return [], str(e) + names = {r.name: r for r in pool} + out = [(names[name], "picked") for _source, name in picks if name in names] + out = list({r.name: (r, how) for r, how in out}.values()) + if picks and not out: + return [], "挑出的能力在登记里都不存在" + return out[:PICK_LIMIT], None + + def key(self, obj: tuple[CapabilityView, str]) -> str: + return f"capability:{obj[0].name}" + + # ---------------------------------------------------------------- 详情 + + async def detail(self, objects: list[tuple[CapabilityView, str]], budget: int, *, + missing: list[LookTarget] = ()) -> tuple[str, list[dict[str, Any]]]: + lines: list[str] = [] + used = 0 + for row, _how in objects: + block = _detail(row) + if used + len(block) > budget: + block = BRIEF_PROMPT.format(name=row.name, system=_system_label(row.system)) + used += len(block) + 1 + lines.append(block) + if missing: + lines.append(MISSING_PROMPT.format(items="、".join(str(t.get("name") or "") for t in missing), + answer=MISSING_ANSWER_PROMPT if self.read_only else "")) + record = {"kind": "capability", "named": [r.name for r, how in objects if how == "named"], + "picked": [r.name for r, how in objects if how == "picked"], + "missing": [str(t.get("name") or "") for t in missing], + "versions": {r.name: r.version for r, _ in objects}} + return "\n".join(lines), [record] + + +def _schema_type(schema: Any) -> str: + if not isinstance(schema, dict): + return "any" + kind = schema.get("type") + if isinstance(kind, list): + return "|".join(str(k) for k in kind) + if kind: + return str(kind) + if "enum" in schema: + return "enum" + return "any" + + +def _params(row: CapabilityView) -> list[str]: + """参数:名字、类型、是否必填、说明。示例值和默认值不给(遮罩字段的样例会把值带出去)。""" + props = row.params_schema.get("properties") if isinstance(row.params_schema, dict) else None + required = set(row.params_schema.get("required") or []) if isinstance(row.params_schema, dict) else set() + out = [] + for name, schema in (props or {}).items(): + desc = str((schema or {}).get("description") or "").strip() if isinstance(schema, dict) else "" + out.append(PARAM_PROMPT.format(name=name, type=_schema_type(schema), required=",必填" if name in required + else "", desc=f":{desc}" if desc else "")) + return out + + +def _label(row: CapabilityView, pointer: str) -> str: + """返回字段的中文名:fields 里按 JSON 指针记的 label 项(形状同数据目录的「项」),驳回的不用。""" + item = (row.fields.get(pointer) or {}).get("label") if isinstance(row.fields.get(pointer), dict) else None + if isinstance(item, dict) and item.get("status") != "rejected" and item.get("value"): + return str(item["value"]) + return "" + + +def _returns(row: CapabilityView) -> list[str]: + """返回字段:声明了 tabular 的按列(列名 ← JSON 指针),否则按 returns_schema 的顶层字段。遮罩字段只给名字。""" + masked = set(row.masked) + pairs: list[tuple[str, str]] = [] + columns = (row.tabular or {}).get("columns") if isinstance(row.tabular, dict) else None + if isinstance(columns, dict) and columns: + pairs = [(str(label), str(pointer)) for label, pointer in columns.items()] + elif isinstance(row.returns_schema, dict): + pairs = [(name, f"/{name}") for name in (row.returns_schema.get("properties") or {})] + out = [] + for name, pointer in pairs: + if pointer in masked: + out.append(FIELD_MASKED_PROMPT.format(name=name)) + continue + label = _label(row, pointer) + out.append(f"{name}({label})" if label and label != name else name) + return out + + +def _detail(row: CapabilityView) -> str: + lines = [DETAIL_HEAD_PROMPT.format(name=row.name, system=_system_label(row.system), + title=row.title or row.description or row.name)] + if row.title and row.description and row.description != row.title: + lines.append(DETAIL_DESC_PROMPT.format(text=row.description)) + lines.append(DETAIL_EFFECT_PROMPT.format(effect=EFFECT_PROMPT.get(row.effect, row.effect), + approval=APPROVAL_PROMPT.get(row.approval, row.approval))) + if row.effect == "write": + lines.append(DETAIL_WRITE_PROMPT) + if params := _params(row): + lines.append(DETAIL_PARAMS_PROMPT.format(items=";".join(params))) + if returns := _returns(row): + lines.append(DETAIL_RETURNS_PROMPT.format(items="、".join(returns))) + if row.tabular: + lines.append(DETAIL_TABULAR_PROMPT) + return "\n".join(lines) diff --git a/backend/app/look/pick.py b/backend/app/look/pick.py new file mode 100644 index 00000000..05c561b3 --- /dev/null +++ b/backend/app/look/pick.py @@ -0,0 +1,166 @@ +"""按需求挑选:表、能力、工作流版本共用同一份挑选提示词(L3),每种对象只给自己的目录。 + +挑选是一次分类:同一个助手模型,关掉思考、额度取小、温度 0,PICK_TIMEOUT_S 时限。只在主模型写了 look、只给了需求、 +候选又超过 PICK_LIMIT 时才调;失败(拿不到模型、超时、报错、回复认不出)不挡生成,由查看服务交回目录、让主模型点名。 + +演示模型挑不了:pick_model 照实交回原因,不拿它乱挑。 +""" +from __future__ import annotations + +import asyncio +import json +import math +from typing import Any + +from app.look.base import PICK_LIMIT, PICK_TIMEOUT_S +from app.providers.factory import ModelSpec, get_chat_model + +#: 挑选调用的输出额度:十几个名字的 JSON 用不了几百 token +PICK_MAX_TOKENS = 1024 + +PICK_SYSTEM_PROMPT = ( + "你在帮工作流助手挑选它要查看的对象。用户这一轮提了一个需求,助手接下来要据此搭工作流;对象太多,没法每个都把" + "详情给它看,它只会看到你挑出的那些。请从目录里挑出完成这个需求要用到的。\n\n" + "挑选规则:\n" + f"- 最多挑 {PICK_LIMIT} 个,按和需求的相关程度从高到低排\n" + "- 完成需求要一起用的也挑上:要按渠道、门店、日期之类分组或筛选时,把对应的维度表挑上;两张表要靠一张关联表" + "才能连起来时,关联表也挑上\n" + "- 标「当前工作流已用到」的,需求还用得着就挑上\n" + "- 拿不准要不要的,宁可挑上\n" + "- name 照抄目录里的名字(含 schema 前缀),不要改写、不要编造;source 写它在目录里所属的那一组的名字\n" + "- 需求和这份目录无关时返回空列表\n\n" + '只输出 JSON:{"items": [{"source": "所属的组", "name": "名字"}]}' +) +PICK_HUMAN_PROMPT = "需求:{need}\n\n{used}{what}目录({line};行尾标「推断,未确认」的是推断出来的):\n\n{index}" +PICK_USED_PROMPT = "当前工作流已用到:{items}\n\n" +PICK_SCHEMA = { + "title": "picked_items", + "description": "完成需求要用到的对象,按相关程度从高到低排", + "type": "object", + "properties": { + "items": { + "type": "array", + "items": { + "type": "object", + "properties": { + "source": {"type": "string", "description": "它在目录里所属的那一组的名字"}, + "name": {"type": "string", "description": "照抄目录里的名字"}, + }, + "required": ["name"], + }, + }, + }, + "required": ["items"], +} + + +class PickFailed(Exception): + """挑选没成:原因写给人看(look 事件的 reason),也交回给模型。""" + + +async def pick_model(spec: ModelSpec) -> tuple[Any | None, str | None]: + """挑选用的模型:(模型, None),拿不到时 (None, 原因)。spec 是助手的模型规格(copilot_model_spec)。 + + 在流里拿:请求的会话那时已经不能用了,这里另开一个短会话读接入设置。没配接入时 get_chat_model 静默退回演示模型, + 演示模型挑不了,直接按挑选失败处理。 + """ + from app.core.errors import explain + from app.db.base import SessionLocal + from app.providers.mock_model import MockChatModel + + spec = spec.model_copy(update={"thinking": "off", "max_tokens": PICK_MAX_TOKENS, "temperature": 0, + "timeout": math.ceil(PICK_TIMEOUT_S)}) + try: + async with SessionLocal() as session: + model, _ = await get_chat_model(session, spec) + except Exception as e: # noqa: BLE001 - 拿不到模型只是挑不了,生成照常 + return None, f"助手使用的模型不可用:{explain(e)[0]}" + if isinstance(model, MockChatModel): + return None, "演示模型不能按需求挑选" + return model, None + + +def picked(raw: Any) -> list[tuple[str | None, str]] | None: + """模型的回复 → [(组名或 None, 名字)]。结构化输出的对象、正文里的 JSON、字符串列表都认;键名认 items / tables、 + name / table(以前挑表时的写法)。对不上格式返回 None。""" + if hasattr(raw, "model_dump"): + raw = raw.model_dump() + if isinstance(raw, str): + text = raw.strip() + start = min((i for i in (text.find("{"), text.find("[")) if i >= 0), default=-1) + if start < 0: + return None + end = text.rfind("}" if text[start] == "{" else "]") + try: + raw = json.loads(text[start:end + 1]) + except ValueError: + return None + if isinstance(raw, dict): + raw = raw.get("items", raw.get("tables")) + if not isinstance(raw, list): + return None + out: list[tuple[str | None, str]] = [] + for item in raw: + if isinstance(item, str) and item.strip(): + out.append((None, item.strip())) + elif isinstance(item, dict): + name = item.get("name", item.get("table")) + if isinstance(name, str) and name.strip(): + src = item.get("source") + out.append((src.strip() if isinstance(src, str) and src.strip() else None, name.strip())) + return out + + +async def _ask(model: Any, messages: list[tuple[str, str]]) -> list[tuple[str | None, str]]: + """问一次。先走结构化输出;不支持、报错、或给回来的不是约定的结构,再退回纯文本、从正文里取 JSON。 + + 结构化输出报错也退回(同 catalog._ask_model):有的网关不支持工具调用,一调就报错,纯文本却能用。 + """ + from app.engine.state import message_text + + try: + parsed = picked(await model.with_structured_output(PICK_SCHEMA).ainvoke(messages)) + except Exception: # noqa: BLE001 - 退回纯文本 + parsed = None + if parsed is not None: + return parsed + parsed = picked(message_text(await model.ainvoke(messages))) + if parsed is None: + raise PickFailed("模型的回复不是约定的格式,无法识别挑出的对象") + return parsed + + +class Picker: + """一轮里共用的挑选:模型第一次要用时才拿(多数轮次根本不挑),拿不到的原因记住,不反复拿。""" + + def __init__(self, spec: ModelSpec | None) -> None: + self.spec = spec + self._model: Any | None = None + self._unavailable: str | None = None if spec is not None else "没有可用的模型" + self.calls = 0 + + async def _get(self) -> Any: + if self._model is None and self._unavailable is None: + self._model, self._unavailable = await pick_model(self.spec) + if self._model is None: + raise PickFailed(self._unavailable or "没有可用的模型") + return self._model + + async def pick(self, *, need: str, what: str, line: str, index: str, + used: str = "") -> list[tuple[str | None, str]]: + """按需求从目录里挑。what 是对象的类别名(数据表、能力……),line 说目录一行写的是什么。失败抛 PickFailed。""" + model = await self._get() + human = PICK_HUMAN_PROMPT.format(need=need.strip(), used=PICK_USED_PROMPT.format(items=used) if used else "", + what=what, line=line, index=index) + self.calls += 1 + try: + return await asyncio.wait_for(_ask(model, [("system", PICK_SYSTEM_PROMPT), ("human", human)]), + timeout=PICK_TIMEOUT_S) + except PickFailed: + raise + except asyncio.TimeoutError as e: + raise PickFailed(f"按需求挑选超过 {PICK_TIMEOUT_S:g} 秒未完成") from e + except Exception as e: # noqa: BLE001 - 挑选失败不挡生成 + from app.core.errors import explain + + raise PickFailed(f"按需求挑选的模型调用失败:{explain(e)[0]}") from e diff --git a/backend/app/look/service.py b/backend/app/look/service.py new file mode 100644 index 00000000..8a0229f6 --- /dev/null +++ b/backend/app/look/service.py @@ -0,0 +1,221 @@ +"""查看服务(look 文档 §2.5.3,总方案 L2、L3):一行 look → 交回给模型的文字 + 发给前端的记录。 + +处理顺序: + 1. need 没写:回「look 要写 need」,不算次数;次数用完:回「按已查看的结构完成」,不再查看。 + 2. targets 按类型分组(旧写法 tables:[{source, table}] 读进来换成 kind=table)。写了 name 的点名直取,不调挑选模型; + 只写了 kind(和 source)的、或者整个没写 targets 的,按 need 在那一类里挑(没写时挑这个入口的第一类)。 + 3. 挑选失败或挑出来是空的:交回那一类的目录(status=index),写明原因,请模型点名再看。 + 4. 这一批对象这一轮都已经看过:回「已在上面」,不重新排一遍。 + 5. 各类给详情,合计受 LOOK_RESULT_CHARS 约束;记一条记录(id、by、need、status、objects、用时)。 + +系统代为查看(look 文档 D5:发布前修复、升级证据、应用润色)也走这里,by=system,不占模型的次数,记录照样发、照样存。 +查看本身出错(status=failed)不挡生成:照实交回原因,模型按已有的信息接着写。 +""" +from __future__ import annotations + +import logging +import time +from typing import Any + +from app.look.base import LOOK_LIMIT, LOOK_RESULT_CHARS, LookBudget, LookKind, LookResult, LookTarget + +logger = logging.getLogger(__name__) + +# ========================================================================== +# 写给模型的文字 +# ========================================================================== + +NEED_MISSING_PROMPT = "look 要写 need:一句话说明要查什么。这一次没有查看,也不算次数" +LIMIT_PROMPT = "这一轮的查看次数已用完(最多 {limit} 次),按已经查看的结构完成,不要再 look" +REPEAT_PROMPT = "这些{what}已经在上面的查看结果里了,不再重复给出,直接用上面的" +HEAD_MODEL_PROMPT = "查看结果(第 {n} 次,这一轮最多 {limit} 次)" +HEAD_SYSTEM_PROMPT = "系统已代为查看(不占你的查看次数)" +NEED_PROMPT = "需求:{need}" +INDEX_PROMPT = ("没能按需求挑出{what}:{reason}。下面是候选的{what}目录,从里面点名(targets 写 name)再 look 一次:\n" + "{index}") +EMPTY_PROMPT = ("按这个需求没有挑出相关的{what}。这一步确实要用到{what}的话,从下面的目录里点名再 look;" + "不需要就接着写:\n{index}") +FAILED_PROMPT = "这一次查看出错了:{reason}。按已有的信息接着写" +#: 按需求挑出来是空的:写进 look 事件的 reason,界面上照原话显示 +EMPTY_REASON = "按这个需求没有挑出相关的{what}" +UNKNOWN_KIND_PROMPT = "这一轮不能查看这一类对象:{kinds}(能查看的:{allowed})" +GUIDE_HEAD_PROMPT = ( + "按需查看(look):要看{labels}的详情时,单独输出一行\n" + ' {{"op":"look","need":"一句话说要查什么","targets":[{example}]}}\n' + " 输出这一行就停下,系统把查看结果作为下一条消息交回来,你接着往下写(已经输出的不要重复)。\n" + " · need 必填。targets 里写了 name 的直接取那几个;只写 kind(可以加 source)不写 name 的,按 need 在这一类里挑;" + "整个不写 targets 时按 need 挑{default}。sources 可选:限定在哪几个来源(数据源名、工作流名……)里挑\n" + " · kind 只能是:{kinds}\n" + " · 每轮最多查看 {limit} 次,一次把要用的都点上;这一轮已经看过的不要再看,这次对话里看过的直接点名看" +) +GUIDE_EXAMPLE_PROMPT = { + "table": '{"kind":"table","source":"数据源名","name":"表名"}', + "capability": '{"kind":"capability","name":"能力名"}', + "workflow_version": '{"kind":"workflow_version","source":"工作流名","name":"v3"}', +} +CONTINUE_PROMPT = "\n\n接着输出操作。已经输出、已经落地的操作不要重复{landed}。" +LANDED_PROMPT = "(已落地:{ids})" + + +def parse_targets(line: dict[str, Any]) -> list[LookTarget]: + """look 行里的 targets(L2)。旧写法 tables:[{source, table}](look 文档 §2.5.2 的初稿)读进来换成 kind=table。""" + out: list[LookTarget] = [] + for t in line.get("targets") or []: + if isinstance(t, dict) and isinstance(t.get("kind"), str): + target: LookTarget = {"kind": t["kind"].strip()} + for key in ("source", "name"): + if isinstance(t.get(key), (str, int)) and str(t[key]).strip(): + target[key] = str(t[key]).strip() + out.append(target) + for t in line.get("tables") or []: + if isinstance(t, str) and t.strip(): + out.append({"kind": "table", "name": t.strip()}) + elif isinstance(t, dict) and isinstance(t.get("table", t.get("name")), str): + target = {"kind": "table", "name": str(t.get("table", t.get("name"))).strip()} + if isinstance(t.get("source"), str) and t["source"].strip(): + target["source"] = t["source"].strip() + out.append(target) + return out + + +def _sources(line: dict[str, Any]) -> list[str] | None: + raw = line.get("sources") + names = [str(s).strip() for s in raw if isinstance(s, str) and s.strip()] if isinstance(raw, list) else [] + return names or None + + +class LookService: + """一轮生成里的查看:各类对象(LookKind)、这一轮的记录、看过的对象。起草和自查修正共用一份。""" + + def __init__(self, kinds: list[LookKind]) -> None: + self.kinds: dict[str, LookKind] = {k.kind: k for k in kinds} + self.records: list[dict[str, Any]] = [] + self.texts: list[str] = [] + self._seen: set[str] = set() + self._n = 0 + + @property + def default_kind(self) -> str | None: + return next(iter(self.kinds), None) + + async def overview(self) -> str: + """system 里的概览:每类各自几行,没有内容的类不占地方。""" + blocks = [] + for kind in self.kinds.values(): + lines = await kind.overview() + if lines: + blocks.append("\n".join(lines)) + return "\n\n".join(blocks) + + def guide(self) -> str: + """写给模型的 look 用法(只列这个入口能看的类)。什么时候该看由调用方另写(各入口不一样)。""" + if not self.kinds: + return "" + labels = "、".join(k.label for k in self.kinds.values()) + default = self.kinds[self.default_kind].label if self.default_kind else "" + return GUIDE_HEAD_PROMPT.format(labels=labels, example=GUIDE_EXAMPLE_PROMPT.get(self.default_kind or "", ""), + default=default, kinds="、".join(self.kinds), limit=LOOK_LIMIT) + + def looked(self) -> str: + """这一轮所有查看交回过的文字,修正请求里原样带上(look 文档 D8:和起草时看到的是同一份)。""" + return "\n\n".join(self.texts) + + def continue_prompt(self, landed: list[str]) -> str: + return CONTINUE_PROMPT.format(landed=LANDED_PROMPT.format(ids="、".join(landed)) if landed else "") + + async def look(self, line: dict[str, Any], budget: LookBudget | None = None, *, by: str = "model") -> LookResult: + need = str(line.get("need") or "").strip() + if not need: + return LookResult(NEED_MISSING_PROMPT, None, counted=False) + if budget is not None and budget.used >= budget.limit: + return LookResult(LIMIT_PROMPT.format(limit=budget.limit), None, counted=False) + if budget is not None: + budget.used += 1 + self._n += 1 + started = time.monotonic() + record: dict[str, Any] = {"op": "look", "id": f"L{self._n}", "by": by, "need": need, "status": "ok"} + head = HEAD_SYSTEM_PROMPT if by == "system" else HEAD_MODEL_PROMPT.format( + n=budget.used if budget else self._n, limit=budget.limit if budget else LOOK_LIMIT) + try: + body, objects, keys = await self._run(line, need, record) + except Exception as e: # noqa: BLE001 - 查看是辅助步骤,出错不挡生成(P3) + from app.core.errors import explain + + logger.exception("查看出错:%s", need) + record.update(status="failed", reason=explain(e)[0]) + body, objects, keys = FAILED_PROMPT.format(reason=record["reason"]), [], set() + if record["status"] == "ok" and keys and keys <= self._seen and not any(o.get("missing") for o in objects): + # 这一批这一轮都看过了:不重排一遍,也不发事件(模型没看到新东西),编号留给下一次真正的查看 + self._n -= 1 + what = "、".join(dict.fromkeys(self.kinds[k.split(":", 1)[0]].label for k in keys)) + return LookResult(REPEAT_PROMPT.format(what=what), None, counted=True) + self._seen |= keys + record["elapsed_ms"] = int((time.monotonic() - started) * 1000) + record["objects"] = objects + text = "\n".join([head, NEED_PROMPT.format(need=need), "", body]) + self.records.append(record) + self.texts.append(text) + return LookResult(text, record) + + async def _run(self, line: dict[str, Any], need: str, + record: dict[str, Any]) -> tuple[str, list[dict[str, Any]], set[str]]: + """真正查看:(交回的正文, objects[], 这一次给出详情的对象的身份)。status / reason 写进 record。""" + targets = parse_targets(line) + sources = _sources(line) + unknown = [t["kind"] for t in targets if t["kind"] not in self.kinds] + named: dict[str, list[LookTarget]] = {} + picks: dict[str, list[str] | None] = {} + for t in targets: + if t["kind"] not in self.kinds: + continue + if t.get("name"): + named.setdefault(t["kind"], []).append(t) + else: + # 只写了类别:按 need 在这一类里挑;写了 source 的只在那几个来源里挑 + scope = picks.setdefault(t["kind"], []) + if scope is not None and t.get("source"): + scope.append(t["source"]) + elif not t.get("source"): + picks[t["kind"]] = None + if not targets and self.default_kind: + picks[self.default_kind] = None + parts: list[str] = [] + objects: list[dict[str, Any]] = [] + keys: set[str] = set() + indexed: list[str] = [] + empty: list[str] = [] + budget = LOOK_RESULT_CHARS + for kind_name in dict.fromkeys([*named, *picks]): + kind = self.kinds[kind_name] + found, missing = await kind.resolve(named.get(kind_name, [])) if kind_name in named else ([], []) + if kind_name in picks: + within = picks[kind_name] or sources + chosen, reason = await kind.pick(need, within) + if reason is not None or not chosen: + index = await kind.index(within) + indexed.append(INDEX_PROMPT.format(what=kind.label, reason=reason, index=index) if reason + else EMPTY_PROMPT.format(what=kind.label, index=index)) + if reason is not None: + record["reason"] = reason + else: + empty.append(kind.label) + found += [o for o in chosen if kind.key(o) not in {kind.key(f) for f in found}] + if not found and not missing: + continue + text, blocks = await kind.detail(found, budget, missing=missing) + budget = max(budget - len(text), 0) + parts.append(text) + objects += blocks + keys |= {kind.key(o) for o in found} + if unknown: + parts.append(UNKNOWN_KIND_PROMPT.format(kinds="、".join(dict.fromkeys(unknown)), + allowed="、".join(self.kinds))) + parts += indexed + if indexed and not keys: + # 一个对象都没给出详情、交回的是目录:挑选失败(有原因)或按需求没挑出来(返回空) + record["status"] = "index" + record.setdefault("reason", EMPTY_REASON.format(what="、".join(empty))) + else: + # 给出了详情:status 是 ok,reason 只在不是 ok 时带 + record.pop("reason", None) + return "\n\n".join(p for p in parts if p), objects, keys diff --git a/backend/app/look/tables.py b/backend/app/look/tables.py new file mode 100644 index 00000000..68c526c4 --- /dev/null +++ b/backend/app/look/tables.py @@ -0,0 +1,384 @@ +"""查看的对象之一:数据表(look 文档 §2.4 D2、D3、D6)。 + +- overview:每个库一行(data/schema_view.overview_line),外加「现有工作流用到的表」只列表名; +- resolve:点名直取,认全名、只写表名、大小写不同、「库名.表名」(catalog.resolve_table_name);只有一个候选库时可以不写库名; +- pick:候选库的表加起来不超过 PICK_LIMIT 张就全给,否则用挑选模型按需求从表目录(表名|中文名|粒度)里挑; +- detail:沿关系图补上两跳以内的中间表(合计不超过 CONTEXT_TABLE_LIMIT),每张表给全部字段和数据目录(遮罩列只给 + 列名和类型),再给表之间的连接条件和连接路径;超过字数上限的表只给字段名。 + +表结构和目录在开流之前读好(load):目录用单独的会话读,读不到就当没有,不挡生成。 +""" +from __future__ import annotations + +import logging +from collections.abc import Mapping +from dataclasses import dataclass, field +from typing import Any + +from app.data import catalog, introspect, schema_view +from app.data.catalog import INFERRED_MARK, JoinEdge +from app.look.base import CONTEXT_TABLE_LIMIT, PICK_LIMIT, LookTarget +from app.look.pick import Picker, PickFailed + +logger = logging.getLogger(__name__) + +# ========================================================================== +# 写给模型的文字 +# ========================================================================== + +OVERVIEW_HEAD_PROMPT = "已接入的数据源(要看表结构时用 look,kind 写 table):" +OVERVIEW_SEEDS_PROMPT = "现有工作流用到的表:{tables}(来自现有工作流,字段要用时 look)" +SOURCE_HEAD_PROMPT = "{source}({kind}):{lead}" +LEAD_NAMED_PROMPT = "点名查看 {n} 张" +LEAD_PICKED_PROMPT = "按需求从 {total} 张表中挑出 {n} 张" +LEAD_ALL_PROMPT = "候选只有 {n} 张表,全部给出" +LEAD_JOINED_PROMPT = "另为连接补上 {n} 张" +JOINED_MARK_PROMPT = "(为连接补上)" +CAPPED_PROMPT = "一次最多查看 {limit} 张表,点名的只取了前 {limit} 张" +BRIEF_NOTE_PROMPT = "(这一次查看的字数超过上限,后面的表只给了字段名)" +MISSING_PROMPT = "没找到:{items}(表结构里没有,可能没探查到;别拿名字相近的表顶替)" +MISSING_SOURCE_PROMPT = "没找到数据源「{source}」:不在这一轮可用的数据源里" +UNEXPLORED_PROMPT = ("({source} 共 {total} 张表,只探查了 {explored} 张;用户说的表在这里找不到时,先用 db_schema__{source} " + "查,也查不到就查数据字典(information_schema.columns,SQLite 用 sqlite_master),别猜)") +INFERRED_PROMPT = ("标「推断,未确认」的说明和连接条件是按列名、数据库注释或模型推断出来的,没有人确认过:照抄前对照字段" + "核实") +INDEX_HEAD_PROMPT = "数据源「{source}」(共 {total} 张表):" +INDEX_PARTIAL_PROMPT = "数据源「{source}」(共 {total} 张表,只探查了 {explored} 张,下面只列探查到的):" +PICK_WHAT_PROMPT = "数据表" +PICK_LINE_PROMPT = "每行一张表:表名|中文名|粒度" + + +@dataclass +class SourcePlan: + """一个候选库:表结构、原样的目录(含驳回项:关系图要靠驳回项压住同一条关系的现推结果)、现有工作流用到的表。""" + + source: Any + entries: dict[str, catalog.CatalogEntry] = field(default_factory=dict) + #: 现有工作流 SQL 里查过的表(schema_cache 的键) + seeds: list[str] = field(default_factory=list) + _graph: dict[str, list[JoinEdge]] | None = None + + @property + def name(self) -> str: + return self.source.name + + @property + def tables(self) -> dict[str, Any]: + return (getattr(self.source, "schema_cache", None) or {}).get("tables") or {} + + @property + def explored(self) -> int: + return len(self.tables) + + @property + def total(self) -> int: + """这个源一共几张表(含视图):探查时数据库报的总数。老缓存没记总数时按探查到的算。""" + raw = (getattr(self.source, "schema_cache", None) or {}).get("total") + return max(raw if isinstance(raw, int) and not isinstance(raw, bool) else 0, self.explored) + + @property + def unexplored(self) -> int: + """探查截断了的话还有几张没探查到;没截断为 0(反射失败跳过的表是探查了、读不到,不算)。""" + truncated = (getattr(self.source, "schema_cache", None) or {}).get("truncated") + return max(self.total - self.explored, 0) if truncated else 0 + + @property + def raw_notes(self) -> dict[str, dict[str, Any]]: + return {t: e.notes for t, e in self.entries.items()} + + @property + def notes(self) -> dict[str, dict[str, Any]]: + """给模型看的目录:去掉驳回项。""" + return {t: catalog.visible_notes(e.notes) for t, e in self.entries.items()} + + @property + def catalog_tables(self) -> int: + """有数据目录的表数:去掉驳回项之后还有内容的。""" + return sum(1 for e in self.entries.values() if catalog.visible_notes(e.notes)) + + def graph(self) -> dict[str, list[JoinEdge]]: + """关系图,第一次要用时才推。推不出来就当没有:少了连接条件只是少一个提示。""" + if self._graph is None: + try: + self._graph = schema_view.relation_graph(self.source, self.raw_notes) + except Exception: # noqa: BLE001 + logger.exception("数据源 %s 的关系图推不出来,这次查看不给连接条件", self.name) + self._graph = {} + return self._graph + + def qualified(self, key: str) -> str: + return schema_view.qualifier(self.source)(key) + + +@dataclass(frozen=True) +class TableRef: + """查看结果里的一张表:第几个候选库、schema_cache 的键、怎么来的(named 点名 / picked 按需求挑出)。""" + + plan: int + key: str + how: str = "named" + + +def graph_tables(graph: Mapping[str, Any] | None, sources: list[Any]) -> dict[str, list[str]]: + """现有工作流里查库节点的 SQL 用到的表:{源名: [schema_cache 的键]},按出现顺序。 + + 只认调用工具节点上写死的 SQL(db_query__<源>);Agent 运行时自己写的 SQL 图里看不到。哪些节点算写死的查询 + 以 sqlcheck.tool_query 为准(catalog_impact.tool_queries,和发布记录、SQL 检查同一份):换成别的类型的节点 + 配置里残留的 tool、args 不算。节点认两种写法:画布的 {data: {config}} 和 GraphSpec 的 {config}。SQL 解析 + 不了的跳过。发布前修复、升级证据由系统代为查看的就是这些表(look 文档 D5)。 + """ + from app.data.catalog_impact import tool_queries + from app.engine.evidence import sql_tables + + by_name = {getattr(s, "name", None): s for s in sources} + out: dict[str, list[str]] = {} + nodes = (graph or {}).get("nodes") or [] + for _, source_name, sql in tool_queries(n for n in nodes if isinstance(n, dict)): + source = by_name.get(source_name) + if source is None: + continue + try: + names = sql_tables(sql) + except Exception: # noqa: BLE001 - 认不出表就当没用到 + continue + found = out.setdefault(source.name, []) + for table in names: + key = catalog.resolve_table_name(source.schema_cache, table) + if key and key not in found: + found.append(key) + return {k: v for k, v in out.items() if v} + + +class TableKind: + kind = "table" + label = "表" + + def __init__(self, plans: list[SourcePlan], *, picker: Picker | None = None) -> None: + self.plans = plans + self.picker = picker + + @classmethod + async def load(cls, sources: list[Any], *, graph: Mapping[str, Any] | None = None, + picker: Picker | None = None) -> TableKind: + """读各源的数据目录。graph 是现有工作流(改图时的原图、追问时上一轮的图),概览里列出它查过的表。""" + from app.tools.datasource import _catalog_of + + seeds = graph_tables(graph, sources) + plans = [SourcePlan(source=s, entries=await _catalog_of(s) if introspect.table_names(s) else {}, + seeds=seeds.get(s.name, [])) for s in sources] + return cls(plans, picker=picker) + + # ---------------------------------------------------------------- 概览、目录 + + async def overview(self) -> list[str]: + if not self.plans: + return [] + lines = [OVERVIEW_HEAD_PROMPT] + lines += [schema_view.overview_line(p.source, catalog_tables=p.catalog_tables) for p in self.plans] + seeds = [f"{p.name} 的 " + "、".join(p.qualified(t) for t in p.seeds) for p in self.plans if p.seeds] + if seeds: + lines.append(OVERVIEW_SEEDS_PROMPT.format(tables=";".join(seeds))) + return lines + + def _candidates(self, sources: list[str] | None) -> tuple[list[int], list[str]]: + """候选库(在这一轮可用的范围里)和认不出的库名。sources 不写时为全部。""" + if not sources: + return [i for i, p in enumerate(self.plans) if p.tables], [] + by_name = {p.name: i for i, p in enumerate(self.plans)} + found = [by_name[s] for s in sources if s in by_name] + return list(dict.fromkeys(found)), [s for s in sources if s not in by_name] + + async def index(self, sources: list[str] | None) -> str: + blocks = [] + for i in self._candidates(sources)[0]: + p = self.plans[i] + head = (INDEX_PARTIAL_PROMPT if p.unexplored else INDEX_HEAD_PROMPT).format( + source=p.name, total=p.total, explored=p.explored) + blocks.append(f"{head}\n{schema_view.table_index(p.source, p.notes)}") + return "\n\n".join(blocks) + + # ---------------------------------------------------------------- 点名、挑选 + + def _prefixed(self, name: str) -> tuple[int, str] | None: + """「库名.表名」这种写法:(第几个库, 表名)。""" + return next(((i, name[len(p.name) + 1:]) for i, p in enumerate(self.plans) + if name.startswith(p.name) and name[len(p.name):len(p.name) + 1] in (".", ":", ":")), None) + + def _find(self, source: str | None, name: str) -> TableRef | None: + """一个点名 → 表。写了库名的只在那个库里找;表名前面带着库名的也认;都没写的按顺序在各库里找。""" + if source is not None: + candidates = [i for i, p in enumerate(self.plans) if p.name == source] + elif (hit := self._prefixed(name)) is not None: + candidates, name = [hit[0]], hit[1] + else: + candidates = [i for i, p in enumerate(self.plans) if p.tables] + for i in candidates: + key = catalog.resolve_table_name(self.plans[i].source.schema_cache, name) + if key: + return TableRef(i, key) + return None + + async def resolve(self, targets: list[LookTarget]) -> tuple[list[TableRef], list[LookTarget]]: + found: list[TableRef] = [] + missing: list[LookTarget] = [] + single = len([p for p in self.plans if p.tables]) == 1 + for t in targets: + source = t.get("source") or None + if source is not None and source not in {p.name for p in self.plans}: + missing.append(t) + continue + ref = self._find(None if single and source is None else source, str(t.get("name") or "")) + if ref is None: + missing.append(t) + elif ref not in found: + found.append(ref) + return found, missing + + async def pick(self, need: str, sources: list[str] | None) -> tuple[list[TableRef], str | None]: + candidates, _ = self._candidates(sources) + pool = [TableRef(i, key, "picked") for i in candidates for key in self.plans[i].tables] + if len(pool) <= PICK_LIMIT: + return pool, None + if self.picker is None: + return [], "没有可用的挑选模型" + index = "\n\n".join( + f"{(INDEX_PARTIAL_PROMPT if p.unexplored else INDEX_HEAD_PROMPT).format(source=p.name, total=p.total, explored=p.explored)}\n" + f"{schema_view.table_index(p.source, p.notes)}" for p in (self.plans[i] for i in candidates)) + used = ";".join(f"数据源「{p.name}」的 " + "、".join(p.qualified(t) for t in p.seeds) + for p in (self.plans[i] for i in candidates) if p.seeds) + try: + picks = await self.picker.pick(need=need, what=PICK_WHAT_PROMPT, line=PICK_LINE_PROMPT, index=index, + used=used) + except PickFailed as e: + return [], str(e) + names = {self.plans[i].name for i in candidates} + out: list[TableRef] = [] + for source, name in picks: + if len(candidates) == 1: + # 只有一个库要挑时不看模型写的库名(写错了也不要紧) + ref = self._find(self.plans[candidates[0]].name, name) + elif source in names or source is None: + ref = self._find(source, name) + else: + # 写了一个不在候选里的库名:表名前带着库名的照样认,否则丢掉 + ref = self._find(None, name) if self._prefixed(name) else None + if ref is not None and ref.plan in candidates and not any(r.plan == ref.plan and r.key == ref.key + for r in out): + out.append(TableRef(ref.plan, ref.key, "picked")) + if picks and not out: + return [], "挑出的表在表结构中都不存在" + return out[:PICK_LIMIT], None + + def key(self, obj: TableRef) -> str: + return f"table:{self.plans[obj.plan].name}:{obj.key}" + + # ---------------------------------------------------------------- 详情 + + async def detail(self, objects: list[TableRef], budget: int, *, + missing: list[LookTarget] = ()) -> tuple[str, list[dict[str, Any]]]: + capped = len(objects) > CONTEXT_TABLE_LIMIT + objects = objects[:CONTEXT_TABLE_LIMIT] + by_plan: dict[int, list[TableRef]] = {} + for ref in objects: + by_plan.setdefault(ref.plan, []).append(ref) + room = CONTEXT_TABLE_LIMIT - len(objects) + lines: list[str] = [] + blocks: list[dict[str, Any]] = [] + used = 0 + briefed = False + for i, refs in by_plan.items(): + p = self.plans[i] + first = [r.key for r in refs] + tables, routes = list(first), [] + if len(first) > 1 and room > 0: + tables, routes = schema_view.complete(first, p.graph(), room) + room -= len(tables) - len(first) + joined = tables[len(first):] + named = [r.key for r in refs if r.how == "named"] + picked = [r.key for r in refs if r.how == "picked"] + lead = [] + if named: + lead.append(LEAD_NAMED_PROMPT.format(n=len(named))) + if picked: + # 候选不超过 PICK_LIMIT 张时没有挑,全部给出:照实说 + every = len(picked) == len(p.tables) and len(p.tables) <= PICK_LIMIT and not p.unexplored + lead.append(LEAD_ALL_PROMPT.format(n=len(picked)) if every + else LEAD_PICKED_PROMPT.format(total=p.total, n=len(picked))) + if joined: + lead.append(LEAD_JOINED_PROMPT.format(n=len(joined))) + lines.append(SOURCE_HEAD_PROMPT.format(source=p.name, kind=p.source.kind, lead=",".join(lead))) + notes = p.raw_notes + for key in tables: + full = schema_view.table_detail(p.source, key, catalog_notes=notes) + block = full.split("\n") + if used + len(full) > budget: + block = [schema_view.table_brief(p.source, key)] + briefed = True + used += sum(len(x) + 1 for x in block) + mark = JOINED_MARK_PROMPT if key in joined else "" + lines.append(f" · {block[0]}{mark}") + lines += [f" {x}" for x in block[1:]] + lines += schema_view.join_lines(p.source, p.graph(), tables, indent=" ") + lines += schema_view.route_lines(p.source, routes, indent=" ") + if p.unexplored: + lines.append(" " + UNEXPLORED_PROMPT.format(source=p.name, total=p.total, explored=p.explored)) + blocks.append(self._record(p, named=named, picked=picked, joined=joined, + missing=[str(t.get("name") or "") for t in missing + if self._missing_in(t) == i])) + if briefed: + lines.append(BRIEF_NOTE_PROMPT) + if capped: + lines.append(CAPPED_PROMPT.format(limit=CONTEXT_TABLE_LIMIT)) + lines += self._missing_lines(missing, blocks, set(by_plan)) + text = "\n".join(lines) + if INFERRED_MARK in text: + text += "\n" + INFERRED_PROMPT + return text, blocks + + def _missing_in(self, target: LookTarget) -> int | None: + """没找到的点名落在哪个候选库(记录按库分块):写了库名就是那个库,只有一个库时就是它。""" + source = target.get("source") + names = [i for i, p in enumerate(self.plans) if p.name == source] if source else \ + [i for i, p in enumerate(self.plans) if p.tables] + return names[0] if len(names) == 1 else None + + def _missing_lines(self, missing: list[LookTarget], blocks: list[dict[str, Any]], shown: set[int]) -> list[str]: + """没找到的点名:库认不出的说库,表认不出的说表;落在没给详情的库里的,另补一块记录。""" + lines: list[str] = [] + tables: list[str] = [] + known = {p.name for p in self.plans} + for t in missing: + source = t.get("source") + if source and source not in known: + lines.append(MISSING_SOURCE_PROMPT.format(source=source)) + blocks.append({"kind": "table", "source": source, "source_id": None, "named": [], "picked": [], + "joined": [], "missing": [str(t["name"])] if t.get("name") else []}) + continue + where = self._missing_in(t) + label = f"{self.plans[where].name} 的 {t.get('name')}" if where is not None else str(t.get("name")) + tables.append(label) + if where is not None and where not in shown: + shown.add(where) + blocks.append(self._record(self.plans[where], named=[], picked=[], joined=[], + missing=[str(m.get("name") or "") for m in missing + if self._missing_in(m) == where])) + if tables: + lines.append(MISSING_PROMPT.format(items="、".join(tables))) + return lines + + def _record(self, p: SourcePlan, *, named: list[str], picked: list[str], joined: list[str], + missing: list[str]) -> dict[str, Any]: + """look 事件里一个库的那一块(look 文档 §2.5.7)。表名写全名。""" + given = [*named, *picked, *joined] + synced = getattr(p.source, "schema_synced_at", None) + out: dict[str, Any] = { + "kind": "table", "source": p.name, "source_id": getattr(p.source, "id", None), + "named": [p.qualified(t) for t in named], "picked": [p.qualified(t) for t in picked], + "joined": [p.qualified(t) for t in joined], "missing": missing, "total": p.total, + "catalog_tables": p.catalog_tables, + "schema_synced_at": synced.isoformat() if synced is not None else None, + "catalog_versions": {p.qualified(t): p.entries[t].version for t in given if t in p.entries}, + } + if p.unexplored: + out["explored"] = p.explored + return out diff --git a/backend/app/look/versions.py b/backend/app/look/versions.py new file mode 100644 index 00000000..f24d25de --- /dev/null +++ b/backend/app/look/versions.py @@ -0,0 +1,181 @@ +"""查看的对象之一:工作流版本(总方案 L3、§5.3)。应用润色时看钉住的版本,模型也可以再看别的。 + +只列「已发布且未退役」的版本(app/apps/versions.published_versions,P5 的唯一说法),详情由 app/apps/describe.py 的 +describe_version 给:入口字段、人工节点、口径卡指标、报告、取数节点、写入动作,以及版本、级别、哈希,不含任何密钥。 + +点名写法:source 写工作流名(或 id),name 写 "v3"(或 3);不写 name 取最新的已发布版本。 +""" +from __future__ import annotations + +from dataclasses import dataclass +from typing import Any + +from app.look.base import PICK_LIMIT, LookTarget +from app.look.pick import Picker, PickFailed + +# ========================================================================== +# 写给模型的文字 +# ========================================================================== + +OVERVIEW_HEAD_PROMPT = "已发布的工作流(要看某一版的入口字段、节点、口径卡时用 look,kind 写 workflow_version):" +OVERVIEW_LINE_PROMPT = "- {name}:已发布 {versions}{level}" +OVERVIEW_MORE_PROMPT = "- …另有 {n} 个工作流" +LEVEL_PROMPT = {"governed": "受管级", "published": "已发布级"} +DETAIL_HEAD_PROMPT = "· {name} v{version}({level},哈希 {hash})" +BRIEF_PROMPT = "· {name} v{version}:字数超过上限,只列名字,要看详情时点名再 look" +MISSING_PROMPT = "没找到工作流版本:{items}(只能查看已发布且未退役的版本;别拿别的版本顶替)" +INDEX_LINE_PROMPT = "{name}|v{version}|{description}" +PICK_WHAT_PROMPT = "工作流版本" +PICK_LINE_PROMPT = "每行一个工作流的最新已发布版本:工作流名|版本|说明" + +#: 概览最多列几个工作流 +OVERVIEW_WORKFLOWS = 40 + + +@dataclass(frozen=True) +class VersionView: + workflow_id: str + workflow_name: str + description: str + version: Any # WorkflowVersion:describe_version 要它 + + @property + def number(self) -> int: + return int(self.version.version) + + @property + def label(self) -> str: + return f"{self.workflow_name} v{self.number}" + + +def _number(name: Any) -> int | None: + text = str(name or "").strip().lower().lstrip("v") + return int(text) if text.isdigit() else None + + +class VersionKind: + kind = "workflow_version" + label = "工作流版本" + + def __init__(self, items: list[VersionView], *, picker: Picker | None = None) -> None: + self.items = items + self.picker = picker + + @classmethod + async def load(cls, session: Any, *, picker: Picker | None = None) -> VersionKind: + """读全部工作流的已发布且未退役的版本。用调用方的会话,开流之前读好。""" + from sqlalchemy import select + + from app.apps import versions as app_versions + from app.db.models import Workflow + + items: list[VersionView] = [] + for wf in (await session.execute(select(Workflow).order_by(Workflow.name))).scalars().all(): + for v in await app_versions.published_versions(session, wf.id): + items.append(VersionView(workflow_id=wf.id, workflow_name=wf.name, + description=wf.description or "", version=v)) + return cls(items, picker=picker) + + def _workflows(self) -> dict[str, list[VersionView]]: + out: dict[str, list[VersionView]] = {} + for item in self.items: + out.setdefault(item.workflow_id, []).append(item) + return out + + # ---------------------------------------------------------------- 概览、目录 + + async def overview(self) -> list[str]: + flows = self._workflows() + if not flows: + return [] + lines = [OVERVIEW_HEAD_PROMPT] + for items in list(flows.values())[:OVERVIEW_WORKFLOWS]: + latest = max(items, key=lambda i: i.number) + level = LEVEL_PROMPT.get(getattr(latest.version, "level", None) or "", "") + lines.append(OVERVIEW_LINE_PROMPT.format( + name=latest.workflow_name, versions="、".join(f"v{i.number}" for i in sorted(items, key=lambda i: i.number)), + level=f"(最新 v{latest.number},{level})" if level else f"(最新 v{latest.number})")) + if len(flows) > OVERVIEW_WORKFLOWS: + lines.append(OVERVIEW_MORE_PROMPT.format(n=len(flows) - OVERVIEW_WORKFLOWS)) + return lines + + def _latest(self, sources: list[str] | None) -> list[VersionView]: + """每个工作流最新的已发布版本,sources(工作流名或 id)给了就只在这几个里。""" + out = [] + for items in self._workflows().values(): + latest = max(items, key=lambda i: i.number) + if not sources or latest.workflow_name in sources or latest.workflow_id in sources: + out.append(latest) + return out + + async def index(self, sources: list[str] | None) -> str: + return "\n".join(INDEX_LINE_PROMPT.format(name=i.workflow_name, version=i.number, + description=i.description[:60] or "未填说明") + for i in self._latest(sources)) + + # ---------------------------------------------------------------- 点名、挑选 + + async def resolve(self, targets: list[LookTarget]) -> tuple[list[tuple[VersionView, str]], list[LookTarget]]: + found: list[tuple[VersionView, str]] = [] + missing: list[LookTarget] = [] + for t in targets: + source = str(t.get("source") or "") + flow = [i for i in self.items if source in (i.workflow_name, i.workflow_id)] + wanted = _number(t.get("name")) + if t.get("name") and wanted is None: + flow = [] + hit = (next((i for i in flow if i.number == wanted), None) if wanted is not None + else max(flow, key=lambda i: i.number, default=None)) + if hit is None: + missing.append(t) + elif all(i is not hit for i, _ in found): + found.append((hit, "named")) + return found, missing + + async def pick(self, need: str, sources: list[str] | None) -> tuple[list[tuple[VersionView, str]], str | None]: + pool = self._latest(sources) + if len(pool) <= PICK_LIMIT: + return [(i, "picked") for i in pool], None + if self.picker is None: + return [], "没有可用的挑选模型" + try: + picks = await self.picker.pick(need=need, what=PICK_WHAT_PROMPT, line=PICK_LINE_PROMPT, + index=await self.index(sources)) + except PickFailed as e: + return [], str(e) + by_name = {i.workflow_name: i for i in pool} + out = list({by_name[n].workflow_id: (by_name[n], "picked") for n in + (s or name for s, name in picks) if n in by_name}.values()) + if picks and not out: + return [], "挑出的工作流不存在或没有已发布的版本" + return out[:PICK_LIMIT], None + + def key(self, obj: tuple[VersionView, str]) -> str: + return f"workflow_version:{obj[0].workflow_id}:{obj[0].number}" + + # ---------------------------------------------------------------- 详情 + + async def detail(self, objects: list[tuple[VersionView, str]], budget: int, *, + missing: list[LookTarget] = ()) -> tuple[str, list[dict[str, Any]]]: + from app.apps import describe + + lines: list[str] = [] + used = 0 + for item, _how in objects: + v = item.version + head = DETAIL_HEAD_PROMPT.format(name=item.workflow_name, version=item.number, + level=LEVEL_PROMPT.get(getattr(v, "level", None) or "", "未定级"), + hash=str(getattr(v, "graph_hash", "") or "")[:8]) + body = describe.describe_version(v, workflow_name=item.workflow_name) + block = head + "\n" + "\n".join(f" {line}" for line in body.split("\n")) + if used + len(block) > budget: + block = BRIEF_PROMPT.format(name=item.workflow_name, version=item.number) + used += len(block) + 1 + lines.append(block) + if missing: + lines.append(MISSING_PROMPT.format(items="、".join( + f"{t.get('source') or ''} {t.get('name') or ''}".strip() for t in missing))) + record = {"kind": "workflow_version", "named": [i.label for i, how in objects if how == "named"], + "picked": [i.label for i, how in objects if how == "picked"], + "missing": [f"{t.get('source') or ''} {t.get('name') or ''}".strip() for t in missing]} + return "\n".join(lines), [record] diff --git a/backend/app/providers/mock_model.py b/backend/app/providers/mock_model.py index bb924911..0ad18dd2 100644 --- a/backend/app/providers/mock_model.py +++ b/backend/app/providers/mock_model.py @@ -46,6 +46,68 @@ def _fake_value(schema: dict[str, Any], key: str = "") -> Any: return f"[mock:{key or 'value'}]" +#: 助手按操作流写图时 system 里一定有这一句(api/copilot.py 的 _STREAM_PROTOCOL / APP_PROTOCOL_PROMPT) +_OPS_MARK = "输出格式(严格遵守)" +#: 看起来是在问数据的请求:演示模型据此决定要不要先 look 一次。闲聊、改提示词不看 +_DATA_WORDS = re.compile(r"查|多少|几个|统计|数据|表|库|sql|金额|数量|排名|趋势|汇总|明细|报表|周报|月报|指标|销售|" + r"订单|人数|人次|收入|占比|同比|环比|top", re.I) +_QUERY_TOOL = re.compile(r"- db_query__(\S+?)(数据库)") + + +def _question_of(human: str) -> str: + """助手请求里用户的原话:问数据是「问题:…」那一行,画布新建是「请设计一个工作流:…」,改图是最后一段。""" + for mark in ("问题:", "请设计一个工作流:"): + if mark in human: + return human.rsplit(mark, 1)[1].split("\n", 1)[0].strip() + return human.strip().rsplit("\n", 1)[-1].strip() + + +def _ops(*ops: dict[str, Any]) -> str: + return "\n".join(json.dumps(op, ensure_ascii=False) for op in ops) + "\n" + + +def _copilot_script(messages: list[BaseMessage]) -> str | None: + """助手(画布、问数据、应用润色)的演示脚本:没配模型接入时也能看到「查看 → 接着写」的完整过程。 + + - 数据类请求、有数据源:先 plan,再 look 一次(只写 kind 和数据源,按需求挑表),停下; + - 收到查看结果(对话里已经有一条自己的输出):接着写一张「输入 → 查库的 Agent → 成果」的图; + - 闲聊:一行 reply,不看; + - 自查修正、应用润色:只说明,不改。 + """ + system = next((_text_of(m) for m in messages if m.type == "system"), "") + if _OPS_MARK not in system: + return None + humans = [_text_of(m) for m in messages if m.type == "human"] + first, last = (humans[0], humans[-1]) if humans else ("", "") + if "app_add" in system: + return _ops({"op": "plan", "summary": "演示模型不改应用"}, + {"op": "done", "explanation": "(演示模型)没有修改应用。如需真实的润色,请在「设置 → 模型接入」中添加模型接入"}) + if "上线前自查" in last: + return _ops({"op": "done", "explanation": "演示模型不做修正"}) + question = _question_of(first) + sources = _QUERY_TOOL.findall(system) + if any(m.type == "ai" for m in messages): + tool = f"db_query__{sources[0]}" if sources else None + answering = "用户问了下面这个问题" in first + return _ops( + {"op": "add_node", "node": {"id": "start", "type": "input", "label": "输入", + "config": {} if answering else {"fields": [{"name": "question"}]}}}, + {"op": "add_node", "node": {"id": "ask", "type": "agent", "label": "查库回答", "config": { + "prompt": "{{ input.question }}", "tools": [tool] if tool else [], "assign_to": "answer"}}}, + {"op": "add_edge", "edge": {"source": "start", "target": "ask"}}, + {"op": "add_node", "node": {"id": "out", "type": "output", "label": "成果", "config": { + "fields": [{"name": "answer", "value": "{{ vars.answer }}"}]}}}, + {"op": "add_edge", "edge": {"source": "ask", "target": "out"}}, + {"op": "done", "explanation": "(演示模型)按查看结果搭了一张查库回答的图", "run": True}, + ) + if sources and '"op":"look"' in system and _DATA_WORDS.search(question): + return _ops({"op": "plan", "summary": "先看一下相关的表,再搭查库回答的图"}, + {"op": "look", "need": question[:80] or "这个问题要用到的表", + "targets": [{"kind": "table", "source": sources[0]}]}) + topic = re.sub(r"\s+", " ", question).strip()[:60] or "这个问题" + return _ops({"op": "reply", "text": f"(演示模型的回复)收到「{topic}」。如需真实的回答,请在「设置 → 模型接入」中添加模型接入"}) + + class MockChatModel(BaseChatModel): """不联网的假模型。 @@ -112,6 +174,10 @@ class MockChatModel(BaseChatModel): payload = _fake_value(self.response_format) return AIMessage(content=json.dumps(payload, ensure_ascii=False, indent=2)) + # 助手按操作流写图:照脚本走一遍(数据类请求先 look 一次) + if not self.tools and (script := _copilot_script(messages)) is not None: + return AIMessage(content=script) + # 绑了工具、而且这一轮还没有工具返回过 —— 那就调一次工具, # 让 agent 循环和画布上的工具节点真的被走到 already_called = any(isinstance(m, ToolMessage) for m in messages) diff --git a/backend/app/tools/datasource.py b/backend/app/tools/datasource.py index 643b028f..0cc29a80 100644 --- a/backend/app/tools/datasource.py +++ b/backend/app/tools/datasource.py @@ -32,7 +32,7 @@ from sqlalchemy.ext.asyncio import AsyncSession from app.core.events import EventType from app.data import catalog as data_catalog -from app.data import introspect, table_versions +from app.data import introspect, schema_view, table_versions from app.data.sqlcheck import SqlChecker from app.data.engine import SnapshotTampered, masked_columns, query_timeout, run_query from app.data.guard import QueryLimits, SqlRejected, check, is_write @@ -93,6 +93,17 @@ def source_of_tool(name: str) -> str | None: return None +#: Run.options 里的键:这次运行的查询结果先遮再交给模型(api/runs.py:开登录后 user 角色发起的问数据运行)。发起时定下、 +#: 随 run.started 封存,续跑、审批恢复沿用 +MASK_RESULTS_OPTION = "mask_results" + + +def run_masks_results(run_ctx: Any) -> bool: + """这次运行的查询结果要不要在工具边界就遮(见 MASK_RESULTS_OPTION)。构造 ToolContext 时传进去。""" + options = (getattr(run_ctx, "extra", None) or {}).get("run_options") or {} + return bool(options.get(MASK_RESULTS_OPTION)) + + def run_versions(run_ctx: Any) -> dict[str, Any] | Versions | None: """一次运行固定的数据版本(runner 放在 RunContext.extra 里)。构造 ToolContext 时传进去。 @@ -682,7 +693,8 @@ def _make_schema_tool(source: Any, *, fixed: bool = False, catalog: Mapping[str, data_catalog.CatalogEntry] | None = None) -> StructuredTool: """source 同 _make_query_tool:上传源的表结构取绑定快照里冻结的那份。 - catalog:建工具时读到的数据目录,查单表时附在字段清单后面(introspect.describe_table)。 + catalog:建工具时读到的数据目录,查单表时附在字段清单后面。单表的说法和助手查看、/schema 接口是同一份 + (data/schema_view.table_detail):遮罩列只给列名和类型,它的注释和目录项都不给(look 文档 D6)。 """ notes = {name: entry.notes for name, entry in (catalog or {}).items()} @@ -691,7 +703,7 @@ def _make_schema_tool(source: Any, *, fixed: bool = False, return f"{DATA_UNAVAILABLE}{gone}" wanted = _schema_tables(table) if wanted: - return "\n\n".join(introspect.describe_table(source, t, catalog=notes) for t in wanted) + return "\n\n".join(schema_view.table_detail(source, t, catalog_notes=notes) for t in wanted) tables = introspect.table_names(source) if not tables: # 把实情交出去,而不是让它去点一个它点不到的按钮 diff --git a/backend/tests/test_autofix_assist.py b/backend/tests/test_autofix_assist.py index 88668f44..96015bb5 100644 --- a/backend/tests/test_autofix_assist.py +++ b/backend/tests/test_autofix_assist.py @@ -168,7 +168,8 @@ async def test_questions_are_passed_on_without_changes(client, monkeypatch): out = await assist(client, wf) # 一句一条的文字,前面标上是哪个节点的事(句子里已经点了名的不重复标) assert out["assist"] == {"ok": False, "summary": "等你决定出具的是哪个出口", "questions": [ - "两个出口里,哪个是要出具的?「出具」还是「原始数」?", "「周报口径卡」:required 要包括哪些指标?候选:gmv"]} + "两个出口里,哪个是要出具的?「出具」还是「原始数」?", "「周报口径卡」:required 要包括哪些指标?候选:gmv"], + "looks": []} assert out["rejected"] == [] and out["graph"] == two_exits() diff --git a/backend/tests/test_catalog_impact.py b/backend/tests/test_catalog_impact.py index 128c1e20..2b3efecb 100644 --- a/backend/tests/test_catalog_impact.py +++ b/backend/tests/test_catalog_impact.py @@ -186,11 +186,12 @@ def test_graph_sql_tables_uses_the_evidence_rules(): def test_assistant_seeds_read_tool_nodes_the_same_way(): - """助手给全字段的「现有工作流用到的表」和发布记录、SQL 检查认的是同一种节点(sqlcheck.tool_query)。 + """助手概览里的「现有工作流用到的表」、发布前修复和升级证据由系统代为查看的表(look 文档 D5),和发布记录、SQL + 检查认的是同一种节点(sqlcheck.tool_query)。 画布上把调用工具节点换成别的类型,配置里的 tool、args 还留着:那已经不是一条会执行的查询,不能当成用到的表。 """ - from app.api.copilot_context import graph_tables + from app.look.tables import graph_tables shop = SimpleNamespace(name="shop", schema_cache={"tables": { "orders": {"qualified": "orders"}, "customers": {"qualified": "customers"}, "stores": {"qualified": "stores"}}}) diff --git a/backend/tests/test_catalog_schema_truncated.py b/backend/tests/test_catalog_schema_truncated.py index 4477b7f8..7a110c4b 100644 --- a/backend/tests/test_catalog_schema_truncated.py +++ b/backend/tests/test_catalog_schema_truncated.py @@ -5,8 +5,9 @@ 提示词里也不提。这组守的是: - 目录清单接口返回 schema_truncated、schema_total(数据库里一共几张),界面据此说明「只探查了前 200 张」 -- 助手上下文的 total 是表结构缓存里的真实总数;context 操作里带上 explored(探查到几张) -- 提示词里写明还有几张没探查到,遇到不认识的表名先查结构 +- 助手的概览写「共 205 张表,只探查了 200 张」;查看记录(look 事件)的 total 是表结构缓存里的真实总数,另带 + explored(探查到几张) +- 查看结果里写明还有几张没探查到,遇到不认识的表名先查结构;交回的表目录也写明只列了探查到的 - 没截断的库照旧,不多说一句 合成库:205 张空表,测试里临时建,用完连同数据源一起删掉。 @@ -89,31 +90,37 @@ async def test_catalog_list_of_a_complete_schema(client, narrow): async def test_assistant_context_counts_the_real_total(wide): - from app.api import copilot_context + from app.look.service import LookService + from app.look.tables import TableKind sid, name = wide - plan = await copilot_context.plan_context([await _row(sid)]) - ctx = plan.fallback("测试") - (row,) = ctx.op()["sources"] + kind = await TableKind.load([await _row(sid)]) + looks = LookService([kind]) + overview = await looks.overview() + assert f"共 {WIDE} 张表,只探查了 200 张" in overview + # 点名查看一张探查到的表:记录里 total 是真实总数,另带 explored;文字里说清还有多少张没探查到 + result = await looks.look({"op": "look", "need": "看一下 t000", "targets": [ + {"kind": "table", "source": name, "name": "t000"}]}) + (row,) = result.record["objects"] assert row["total"] == WIDE and row["explored"] == 200 - text = ctx.section() - assert f"共 {WIDE} 张表" in text and "只探查了 200 张" in text and f"还有 {WIDE - 200} 张没有探查到" in text + assert f"共 {WIDE} 张表,只探查了 200 张" in result.text # 遇到不认识的表名先查结构,别猜 - assert f"db_schema__{name}" in text and "information_schema" in text - # 挑表的请求里也写明只列了探查到的 - pick = plan._pick_messages("各表的金额")[1][1] - assert f"共 {WIDE} 张表,只探查了 200 张" in pick + assert f"db_schema__{name}" in result.text and "information_schema" in result.text + # 交回的表目录也写明只列了探查到的 + assert f"共 {WIDE} 张表,只探查了 200 张,下面只列探查到的" in await kind.index(None) async def test_assistant_context_of_a_complete_schema_says_nothing_extra(narrow): - from app.api import copilot_context + from app.look.service import LookService + from app.look.tables import TableKind - sid, _ = narrow - plan = await copilot_context.plan_context([await _row(sid)]) - ctx = await plan.resolve(None, need="x") - (row,) = ctx.op()["sources"] + sid, name = narrow + looks = LookService([await TableKind.load([await _row(sid)])]) + assert "只探查了" not in await looks.overview() + result = await looks.look({"op": "look", "need": "全部"}) + (row,) = result.record["objects"] assert row["total"] == 3 and "explored" not in row - assert "没有探查到" not in ctx.section() + assert "没有探查到" not in result.text and "只探查了" not in result.text async def test_schema_tool_does_not_deny_a_table_that_was_not_introspected(wide, narrow): diff --git a/backend/tests/test_conversations.py b/backend/tests/test_conversations.py index cf7b9a5a..df0d1fb9 100644 --- a/backend/tests/test_conversations.py +++ b/backend/tests/test_conversations.py @@ -162,12 +162,12 @@ async def test_no_conversation_means_no_history_header(client, monkeypatch) -> N captured: list = [] class _Recorder: - def with_structured_output(self, *_a, **_k): - return self + # 非流式的 /generate 和流式走同一个生成过程(copilot_gen):模型按操作流回答 + async def astream(self, messages): + from langchain_core.messages import AIMessageChunk - async def ainvoke(self, messages): captured.append(messages) - return {"nodes": [], "edges": []} + yield AIMessageChunk(content='{"op":"reply","text":"好"}\n') async def _model(*_a, **_k): return _Recorder(), "mock-fast" diff --git a/backend/tests/test_copilot_context.py b/backend/tests/test_copilot_context.py index 43e6ebea..6a2e4212 100644 --- a/backend/tests/test_copilot_context.py +++ b/backend/tests/test_copilot_context.py @@ -2,14 +2,15 @@ 这组守的是"Copilot 知道有哪些库、写得出能跑的 SQL"。断了的表现很隐蔽: 它不会报错,只会退回让用户自己写 SQL 的代码节点——接了数据库等于白接。 + +按库的大小定「给详细摘要还是只列表名」的那一套(预算、40 张表的阈值)已经拿掉:system 里每个库一行概览, +要看表时模型自己 look(look 文档 D3,见 test_copilot_table_pick.py)。这里留着结构化输出和摘要本身的几条。 """ from __future__ import annotations from types import SimpleNamespace -import pytest - -from app.api.copilot import GRAPH_SCHEMA, _DATASOURCE_BUDGET_CHARS +from app.api.copilot import GRAPH_SCHEMA from app.data.introspect import summary @@ -56,32 +57,3 @@ def test_summary_without_schema_uses_bare_names(): """没有 schema 概念的库不要硬拼前缀,否则生成的 SQL 反而错。""" text = summary(_source(2, schema=None)) assert "t0" in text and "None.t0" not in text - - -def test_budget_constant_is_sane(): - """预算太小会让单个库就触发降级,太大等于没有预算。""" - assert 3000 <= _DATASOURCE_BUDGET_CHARS <= 20000 - - -@pytest.mark.parametrize("n_tables,expect_detail", [(3, True), (40, True), (53, False)]) -def test_object_count_decides_detail_level(n_tables, expect_detail): - """对象超过截断阈值就切紧凑模式。 - - 关键取舍:detail 模式每库只列 40 个对象,多出来的 Copilot 根本看不见。 - 对 53 个对象的库,"40 张表带字段"不如"53 张表只给名字"——找不到那张表, - 字段写得再全也没用。截断丢信息比省 token 更糟。 - """ - from app.api.copilot import _DETAIL_TABLE_LIMIT - from app.data.introspect import table_names - - src = _source(n_tables) - assert (len(table_names(src)) <= _DETAIL_TABLE_LIMIT) is expect_detail - - -def test_many_sources_trigger_compact_mode(): - """单库不超标,几个库加起来超预算时整体降级。""" - sources = [_source(35, name=f"db{i}") for i in range(6)] - full = sum(len(summary(s)) for s in sources) - assert full > _DATASOURCE_BUDGET_CHARS - compact = sum(len(summary(s, detail=False)) for s in sources) - assert compact < _DATASOURCE_BUDGET_CHARS diff --git a/backend/tests/test_copilot_look.py b/backend/tests/test_copilot_look.py new file mode 100644 index 00000000..719535cb --- /dev/null +++ b/backend/tests/test_copilot_look.py @@ -0,0 +1,617 @@ +"""助手的生成过程(总方案 L1,look 文档 D9)和五个入口怎么用查看。 + +模型一律用剧本,不调真接口。守的是: +- 读到 look 就停(look 之后的内容丢弃),查看结果作为下一条消息交回,接着写;消息结构照 look §2.5.5 +- 接着写时已落地的操作不重复;每轮查看次数有上限;接着写那一段被截断照实报 +- 修正请求带上这一轮的查看结果;模型问了用户(ask)这一轮就结束,不修正、不自动运行 +- 画布 / 问数据:system 里只有概览;look 事件发给前端;非流式的 /generate 走同一个过程 +- 发布前修复、升级证据:系统按要修的 SQL 代为查看(by=system),不调挑选模型 +- 历史里写「上一轮查看过」;演示模型数据类请求看一次、闲聊不看 +- 三种对象(表、能力、工作流版本)同一个接口;能力只给名字、参数、返回字段、读写、要不要确认;问数据只列只读能力 +- 应用落地(AppApplier)的去重;/app-stream 先代为查看钉住的版本;/from-run 记下来源 +""" +from __future__ import annotations + +import json +import sqlite3 +import uuid +from types import SimpleNamespace + +import pytest +from httpx import ASGITransport, AsyncClient +from langchain_core.messages import AIMessageChunk + +from app.data.introspect import introspect +from app.db.base import SessionLocal +from app.db.models import DataSource +from app.look.base import LookBudget +from app.look.service import LookService +from app.main import app +from tests.fixtures.sources import drop_source + + +@pytest.fixture +async def client(): + async with AsyncClient(transport=ASGITransport(app=app), base_url="http://test") as c: + yield c + + +@pytest.fixture +async def shop(tmp_path): + """两张表的小库:orders、customers。""" + path = tmp_path / "shop.db" + db = sqlite3.connect(path) + db.executescript( + "CREATE TABLE customers (id INTEGER PRIMARY KEY, name TEXT NOT NULL);" + "CREATE TABLE orders (id INTEGER PRIMARY KEY, customer_id INTEGER NOT NULL, amount REAL NOT NULL," + " ordered_at TEXT NOT NULL);") + db.commit() + db.close() + async with SessionLocal() as session: + row = DataSource(name=f"lookshop_{uuid.uuid4().hex[:6]}", kind="sqlite", database=str(path), + description="商城库") + session.add(row) + await session.commit() + row.schema_cache = await introspect(row) + await session.commit() + await session.refresh(row) + session.expunge(row) + yield row + await drop_source(row.id) + + +def _line(op: dict) -> str: + return json.dumps(op, ensure_ascii=False) + + +class Turns: + """按次吐操作流:第 n 次调用吐 scripts[n](调用多于剧本时重复最后一份);给了 fix,收到自查请求时吐它。 + 记下每次收到的整串消息。""" + + def __init__(self, *scripts: list, fix: list | None = None) -> None: + self.scripts = [[s if isinstance(s, AIMessageChunk) else _line(s) for s in script] for script in scripts] + self.fix = [_line(o) for o in (fix or [{"op": "done"}])] + self.calls: list[list] = [] + + async def astream(self, messages): + self.calls.append(list(messages)) + if "上线前自查" in messages[1][1]: + lines = self.fix + else: + drafts = [m for m in self.calls if "上线前自查" not in m[1][1]] + lines = self.scripts[min(len(drafts), len(self.scripts)) - 1] + for line in lines: + yield line if isinstance(line, AIMessageChunk) else AIMessageChunk(content=line + "\n") + + +def _use(monkeypatch, model) -> None: + import app.api.copilot as copilot + + async def _model(*_a, **_k): + return model, "mock-fast" + + monkeypatch.setattr(copilot, "get_chat_model", _model) + + +async def _events(client, monkeypatch, model, body: dict, path: str = "/api/copilot/generate-stream") -> list[dict]: + _use(monkeypatch, model) + out: list[dict] = [] + async with client.stream("POST", path, json=body) as r: + assert r.status_code == 200, await r.aread() + async for line in r.aiter_lines(): + if line.startswith("data: "): + out.append(json.loads(line[6:])) + return out + + +def _ops(events: list[dict]) -> list[str]: + return [e["op"] for e in events if e["op"] not in ("thinking", "heartbeat", "model")] + + +def _graph_ops(source: str, sql: str = "SELECT SUM(amount) AS 金额 FROM orders") -> list[dict]: + return [ + {"op": "add_node", "node": {"id": "q", "type": "tool", "label": "查订单", "config": { + "tool": f"db_query__{source}", "args": {"sql": sql}, "assign_to": "rows"}}}, + {"op": "add_edge", "edge": {"source": "start", "target": "q"}}, + {"op": "add_node", "node": {"id": "out", "type": "output", "label": "成果", "config": { + "fields": [{"name": "rows", "value": "{{ vars.rows }}"}]}}}, + {"op": "add_edge", "edge": {"source": "q", "target": "out"}}, + {"op": "done", "explanation": "查一下", "run": True}, + ] + + +START = {"op": "add_node", "node": {"id": "start", "type": "input", "label": "输入", "config": {}}} + + +async def _tables(source) -> LookService: + from app.look.tables import TableKind + + return LookService([await TableKind.load([source])]) + + +# ---------------------------------------------------------------- 生成过程 + + +async def test_reading_a_look_stops_the_stream_and_the_result_comes_back_as_the_next_message(shop): + from app.api.copilot_gen import Generation, GraphApplier + + after_look = {"op": "add_node", "node": {"id": "ghost", "type": "llm", "label": "不该出现", "config": {}}} + model = Turns( + [{"op": "plan", "summary": "先看订单表"}, START, + {"op": "look", "need": "订单金额", "targets": [{"kind": "table", "name": "orders"}]}, after_look], + [START, {"op": "plan", "summary": "又一个开场"}, *_graph_ops(shop.name)], + ) + nodes: dict = {} + applier = GraphApplier(nodes, []) + gen = Generation(model, system="SYS", applier=applier, looks=await _tables(shop)) + events = [op async for op in gen.draft("REQ")] + + assert len(model.calls) == 2 + system, human, ai, result = model.calls[1] + assert system == ("system", "SYS") and human == ("human", "REQ") + # 模型到 look 那一行为止的输出;look 之后的内容丢掉 + assert ai[0] == "ai" and ai[1].splitlines() == [_line({"op": "plan", "summary": "先看订单表"}), _line(START), + _line({"op": "look", "need": "订单金额", + "targets": [{"kind": "table", "name": "orders"}]})] + assert "ghost" not in nodes and "ghost" not in ai[1] + assert result[0] == "human" and result[1].startswith("查看结果(第 1 次,这一轮最多 3 次)") + assert "amount REAL" in result[1] + assert "接着输出操作。已经输出、已经落地的操作不要重复(已落地:start)" in result[1] + + kinds = [e["op"] for e in events] + # 已落地的 start 不重复,第二个 plan 不要;查看前补一拍「正在查看」,查看完发 look 事件 + assert kinds == ["plan", "add_node", "heartbeat", "look", "add_node", "add_edge", "add_node", "add_edge", "done"] + assert events[2]["phase"] == "looking" + look = events[3] + assert look["by"] == "model" and look["objects"][0]["named"] == ["orders"] + assert set(nodes) == {"start", "q", "out"} + + +async def test_landed_edges_and_nodes_are_not_forwarded_twice(shop): + from app.api.copilot_gen import Generation, GraphApplier + + edge = {"op": "add_edge", "edge": {"source": "start", "target": "q"}} + q = _graph_ops(shop.name)[0] + model = Turns( + [START, q, edge, {"op": "look", "need": "订单", "targets": [{"kind": "table", "name": "orders"}]}], + [START, q, edge, {**q, "node": {**q["node"], "label": "查订单金额"}}, {"op": "done"}], + ) + nodes: dict = {} + edges: list = [] + gen = Generation(model, system="S", applier=GraphApplier(nodes, edges), looks=await _tables(shop)) + events = [e for e in [op async for op in gen.draft("R")] if e["op"] not in ("heartbeat", "look")] + # 一模一样的节点、连线不转发也不重复追加;改了标签的同 id 节点照旧覆盖、转发 + assert [e["op"] for e in events] == ["add_node", "add_node", "add_edge", "add_node", "done"] + assert events[3]["node"]["label"] == "查订单金额" and nodes["q"]["data"]["label"] == "查订单金额" + assert edges == [{"source": "start", "target": "q", "sourceHandle": None}] + + +async def test_looks_per_round_are_capped(shop): + from app.api.copilot_gen import Generation, GraphApplier + + model = Turns(*[[{"op": "look", "need": f"第 {i} 次", "targets": [{"kind": "table", "name": t}]}] + for i, t in enumerate(["orders", "customers", "orders", "customers", "orders", "customers"])]) + looks = await _tables(shop) + gen = Generation(model, system="S", applier=GraphApplier({}, []), looks=looks) + [op async for op in gen.draft("R")] + # 3 次查看(第 3 次是重复的那一批,短路但算次数),之后回「用完了」;再要一次就不再接着写 + assert len(looks.records) == 2 + assert "查看次数已用完" in model.calls[4][-1][1] + assert len(model.calls) == 5 + + +async def test_a_cut_in_the_continuation_is_still_an_error(shop): + from app.api.copilot_gen import CopilotIncomplete, Generation, GraphApplier + + cut = AIMessageChunk(content="", response_metadata={"finish_reason": "length"}) + model = Turns([{"op": "look", "need": "订单", "targets": [{"kind": "table", "name": "orders"}]}], + [START, cut]) + gen = Generation(model, system="S", applier=GraphApplier({}, []), looks=await _tables(shop)) + with pytest.raises(CopilotIncomplete): + [op async for op in gen.draft("R")] + + +async def test_the_contract_generate_runs_draft_then_repair(shop): + """附录 C 的 generate(system, request, applier, checker, looks):起草 → 自查修正,修正请求带上查看结果。""" + from app.api.copilot_gen import GraphApplier, GraphChecker, generate + + model = Turns([{"op": "look", "need": "订单", "targets": [{"kind": "table", "name": "orders"}]}], + [START, *_graph_ops(shop.name, "SELECT o.no_such_col FROM orders o")], + fix=[{"op": "update_node", "id": "q", "config": {"args": {"sql": "SELECT o.amount FROM orders o"}}}, + {"op": "done"}]) + applier = GraphApplier({}, []) + looks = await _tables(shop) + events = [op async for op in generate(model, "S", "R", applier, GraphChecker(applier, sources=[shop]), looks)] + assert [e["status"] for e in events if e["op"] == "check"] == ["repairing"] + repair = model.calls[-1][1][1] + assert "上线前自查" in repair and "这一轮查看过的结构" in repair and "amount REAL" in repair + assert applier.nodes["q"]["data"]["config"]["args"]["sql"] == "SELECT o.amount FROM orders o" + + +# ---------------------------------------------------------------- 画布、问数据 + + +async def test_the_stream_sends_look_events_and_the_system_only_has_the_overview(client, monkeypatch, shop): + model = Turns([{"op": "plan", "summary": "看表"}, {"op": "look", "need": "订单金额", + "targets": [{"kind": "table", "name": "orders"}]}], + [START, *_graph_ops(shop.name)]) + events = await _events(client, monkeypatch, model, { + "instruction": "订单总金额", "intent": "answer", "datasource_ids": [shop.id]}) + kinds = _ops(events) + assert kinds.index("look") < kinds.index("add_node") and events[-1]["op"] == "final" + look = next(e for e in events if e["op"] == "look") + assert look["status"] == "ok" and look["objects"][0]["source"] == shop.name + # system:每个库一行概览,工具清单不列表名,不带字段;查看的用法和「什么时候该看」都在 + system = model.calls[0][0][1] + assert f"- {shop.name}(sqlite,只读):商城库|共 2 张表,还没有数据目录" in system + assert "amount REAL" not in system and "可查:" not in system + assert f"db_query__{shop.name}(数据库):在「{shop.name}」上执行 SQL。商城库 共 2 张表,字段要用时 look" in system + assert '"op":"look"' in system and "什么时候该看" in system + + +async def test_saying_hello_calls_the_model_once_and_looks_at_nothing(client, monkeypatch, shop): + model = Turns([{"op": "reply", "text": "你好"}]) + events = await _events(client, monkeypatch, model, {"instruction": "你好", "intent": "answer"}) + assert _ops(events) == ["reply"] and len(model.calls) == 1 + + +async def test_ask_ends_the_round(client, monkeypatch, shop): + """模型问了用户:这一轮到此为止,不自查修正、不自动运行;已经落地的改动照常交付。""" + ask = {"op": "ask", "question": "按下单时间还是付款时间算?"} + model = Turns([START, _graph_ops(shop.name, "SELECT o.no_such_col FROM orders o")[0], ask, + {"op": "add_node", "node": {"id": "late", "type": "llm", "label": "不该出现", "config": {}}}]) + events = await _events(client, monkeypatch, model, {"instruction": "订单金额", "datasource_ids": [shop.id]}) + kinds = _ops(events) + assert "ask" in kinds and "late" not in json.dumps(events, ensure_ascii=False) + assert not any(e["op"] == "check" and e.get("status") == "repairing" for e in events) + assert len(model.calls) == 1 + final = events[-1] + assert final["op"] == "final" and final["autorun"] is False + assert {n["id"] for n in final["graph"]["nodes"]} == {"start", "q"} + + # 什么都还没改就问:问题转出去,这一轮就结束 + events = await _events(client, monkeypatch, Turns([ask]), {"instruction": "订单金额"}) + assert _ops(events) == ["ask"] + # 非流式的 /generate:问题放在说明里,原图照旧 + r = await client.post("/api/copilot/generate", json={"instruction": "订单金额"}) + assert r.status_code == 200, r.text + assert r.json()["explanation"] == ask["question"] and r.json()["graph"]["nodes"] == [] + + +async def test_the_one_shot_generate_looks_too(client, monkeypatch, shop): + model = Turns([{"op": "look", "need": "订单", "targets": [{"kind": "table", "name": "orders"}]}], + [START, *_graph_ops(shop.name)]) + _use(monkeypatch, model) + r = await client.post("/api/copilot/generate", json={"instruction": "订单总金额", "datasource_ids": [shop.id]}) + assert r.status_code == 200, r.text + assert len(model.calls) == 2 and "amount REAL" in model.calls[1][-1][1] + assert {n["id"] for n in r.json()["graph"]["nodes"]} == {"start", "q", "out"} + + +async def test_history_says_what_was_looked_at_last_time(client, monkeypatch, shop): + from app.db.models import Conversation, ConversationTurn + + async with SessionLocal() as session: + conv = Conversation(title="看过的表") + session.add(conv) + await session.flush() + session.add(ConversationTurn(conversation_id=conv.id, seq=1, question="订单总额", answer="一共 3 笔", + status="done", meta={"looks": [{"op": "look", "id": "L1", "by": "model", + "need": "订单", "status": "ok", "objects": [ + {"kind": "table", "source": shop.name, "named": ["orders"], + "picked": [], "joined": ["customers"], "missing": []}, + {"kind": "capability", "named": ["db_query__x"], "missing": []}]}]})) + await session.commit() + conv_id = conv.id + model = Turns([{"op": "reply", "text": "好"}]) + await _events(client, monkeypatch, model, {"instruction": "那上个月呢", "intent": "answer", + "conversation_id": conv_id}) + human = model.calls[0][1][1] + assert f"上一轮查看过:{shop.name} 的 orders、customers;能力 db_query__x(要再看时直接点名)" in human + + +async def test_the_demo_model_looks_once_for_a_data_question_and_not_for_hello(client, monkeypatch, shop): + from app.providers.mock_model import MockChatModel + + _use_demo = MockChatModel(model_name="mock-fast", latency=0) + events = await _events(client, monkeypatch, _use_demo, { + "instruction": "各客户的订单金额", "intent": "answer", "datasource_ids": [shop.id]}) + kinds = _ops(events) + assert kinds.count("look") == 1 and kinds[-1] == "final", kinds + look = next(e for e in events if e["op"] == "look") + assert look["status"] == "ok" and look["objects"][0]["picked"] == ["customers", "orders"] + agent = next(n for n in events[-1]["graph"]["nodes"] if n["type"] == "agent") + assert agent["data"]["config"]["tools"] == [f"db_query__{shop.name}"] + + events = await _events(client, monkeypatch, _use_demo, {"instruction": "你好", "intent": "answer"}) + assert _ops(events) == ["reply"] + + +# ---------------------------------------------------------------- 发布前修复、升级证据:系统代为查看 + + +def _node(nid, ntype, label, **config): + return {"id": nid, "type": ntype, "position": {"x": 0, "y": 0}, "data": {"label": label, "config": config}} + + +async def test_publish_fix_looks_on_behalf_of_the_model(monkeypatch, shop): + import app.api.copilot as copilot + import app.look.pick as pick + + async def _no_picker(*_a, **_k): + raise AssertionError("系统代为查看是点名,不该调挑选模型") + + monkeypatch.setattr(pick, "get_chat_model", _no_picker) + model = Turns([{"op": "plan", "summary": "看一下"}, {"op": "done", "explanation": "无法修改"}]) + _use(monkeypatch, model) + graph = {"nodes": [ + _node("start", "input", "周期"), + _node("fetch", "tool", "取数", tool=f"db_query__{shop.name}", args={"sql": "SELECT SUM(amount) AS gmv FROM orders"}), + _node("write", "report", "报告撰写", instructions="写周报", numbers="strict", on_violation="fail"), + _node("done", "output", "出具", fields=[{"name": "周报", "value": "{{ nodes.write.text }}"}]), + _node("raw", "output", "原始数", fields=[{"name": "数", "value": "{{ nodes.fetch }}"}]), + ], "edges": [{"id": f"e{i}", "source": a, "target": b} for i, (a, b) in enumerate( + [("start", "fetch"), ("fetch", "write"), ("write", "done"), ("fetch", "raw")])]} + async with SessionLocal() as session: + out = await copilot.assist_publish_fix(session, graph, level="governed") + human = model.calls[0][1][1] + assert "发布前检查" in human and "系统已代为查看(不占你的查看次数)" in human and "amount REAL" in human + (look,) = out["looks"] + assert look["by"] == "system" and look["objects"][0]["named"] == ["orders"] + + +async def test_upgrade_looks_on_behalf_of_the_model(monkeypatch, shop): + import app.api.copilot as copilot + + model = Turns([{"op": "plan", "summary": "看一下"}, {"op": "done", "explanation": "不改"}]) + _use(monkeypatch, model) + graph = {"nodes": [ + _node("start", "input", "输入"), + _node("fetch", "tool", "查库", tool=f"db_query__{shop.name}", + args={"sql": "SELECT SUM(amount) AS a, COUNT(*) AS b FROM orders"}), + _node("calc", "code", "算比率", language="python", assign_to="calc", + code="import json\nprint(json.dumps({'ratio': 3 / 4}))"), + _node("card", "metrics", "口径卡", metrics=[{"id": "ratio", "name": "客单价", "expression": "vars.calc.ratio"}]), + _node("write", "report", "报告撰写", instructions="写一句话"), + _node("out", "output", "成果", fields=[{"name": "周报", "value": "{{ nodes.write.text }}"}]), + ], "edges": [{"id": f"e{i}", "source": a, "target": b} for i, (a, b) in enumerate( + [("start", "fetch"), ("fetch", "calc"), ("calc", "card"), ("card", "write"), ("write", "out")])]} + async with SessionLocal() as session: + out = await copilot.assist_upgrade(session, graph, level="published") + human = model.calls[0][1][1] + assert "系统已代为查看" in human and "ordered_at TEXT" in human + assert out["looks"][0]["by"] == "system" and out["looks"][0]["need"].startswith("要升级的工作流") + + +# ---------------------------------------------------------------- 三种对象,同一个接口 + + +def _capability(name: str, *, effect: str = "read", **extra): + from app.look.capabilities import CapabilityView + + return CapabilityView(name=name, system=extra.pop("system", "builtin"), title=extra.pop("title", name), + description=extra.pop("description", ""), + params_schema=extra.pop("params_schema", {}), returns_schema=extra.pop("returns_schema", None), + tabular=extra.pop("tabular", None), effect=effect, approval=extra.pop("approval", "inherit"), + fields=extra.pop("fields", {}), masked=tuple(extra.pop("masked", ())), + version=extra.pop("version", 1)) + + +def _versions(monkeypatch): + from app.apps import describe + from app.look.versions import VersionKind, VersionView + + monkeypatch.setattr(describe, "describe_version", + lambda v, *, workflow_name: f"入口字段:period\n口径卡:gmv({workflow_name} v{v.version})") + v3 = SimpleNamespace(version=3, level="governed", graph_hash="3fa2c1d0aa") + v4 = SimpleNamespace(version=4, level="published", graph_hash="77aa0000bb") + return VersionKind([VersionView("wf_1", "周销售", "每周的销售", v3), VersionView("wf_1", "周销售", "每周的销售", v4)]) + + +async def test_three_kinds_share_one_interface(monkeypatch, shop): + from app.look.capabilities import CapabilityKind + from app.look.tables import TableKind + + kinds = [await TableKind.load([shop]), CapabilityKind([_capability("web_search"), _capability("send_mail")]), + _versions(monkeypatch)] + named = {"table": {"kind": "table", "name": "orders"}, "capability": {"kind": "capability", "name": "web_search"}, + "workflow_version": {"kind": "workflow_version", "source": "周销售", "name": "v3"}} + for kind in kinds: + assert isinstance(kind.kind, str) and isinstance(kind.label, str) + overview = await kind.overview() + assert isinstance(overview, list) and overview and all(isinstance(line, str) for line in overview) + assert isinstance(await kind.index(None), str) + found, missing = await kind.resolve([named[kind.kind], {"kind": kind.kind, "name": "nope"}]) + assert len(found) == 1 and missing == [{"kind": kind.kind, "name": "nope"}] + picked, reason = await kind.pick("随便", None) + assert picked and reason is None + text, blocks = await kind.detail(found, 12_000, missing=missing) + assert isinstance(text, str) and text and blocks and all(b["kind"] == kind.kind for b in blocks) + assert all(isinstance(kind.key(o), str) for o in found) + + looks = LookService(kinds) + result = await looks.look({"op": "look", "need": "都看看", "targets": list(named.values())}, LookBudget()) + assert [o["kind"] for o in result.record["objects"]] == ["table", "capability", "workflow_version"] + assert result.record["objects"][2]["named"] == ["周销售 v3"] + assert "周销售 v3(受管级,哈希 3fa2c1d0)" in result.text and "口径卡:gmv(周销售 v3)" in result.text + # 只写 kind 不写 name:按需求在这一类里挑;工作流版本按每个工作流的最新已发布版本挑 + result = await looks.look({"op": "look", "need": "周销售", "targets": [{"kind": "workflow_version"}]}, LookBudget()) + assert result.record["objects"][0]["picked"] == ["周销售 v4"] + # 这一轮不能看的类别照实说 + result = await looks.look({"op": "look", "need": "口径", "targets": [{"kind": "caliber", "name": "x"}]}, + LookBudget()) + assert "这一轮不能查看这一类对象:caliber" in result.text + + +async def test_capabilities_show_shape_not_secrets_and_answering_lists_only_reads(): + from app.db.models import Capability + from app.look.capabilities import CapabilityKind + + names = [f"look_cap_{uuid.uuid4().hex[:6]}" for _ in range(2)] + async with SessionLocal() as session: + session.add(Capability( + name=names[0], system="erp", title="查额度", description="按部门查剩余额度", effect_system="read", + params_schema={"type": "object", "required": ["dept"], "properties": { + "dept": {"type": "string", "description": "部门编码", "examples": ["D-0001"]}}}, + tabular={"rows": "/data", "columns": {"部门": "/dept", "负责人电话": "/phone"}}, + fields={"/dept": {"label": {"value": "部门编码", "source": "human", "status": "confirmed"}}}, + masked=["/phone"], endpoint_id="ep_secret_host", version=3)) + session.add(Capability(name=names[1], system="erp", title="付款", effect_system="write", approval="confirm", + endpoint_id="ep_secret_host")) + await session.commit() + try: + kind = await CapabilityKind.load() + looks = LookService([kind]) + result = await looks.look({"op": "look", "need": "额度和付款", "targets": [ + {"kind": "capability", "name": n} for n in names]}, LookBudget()) + text = result.text + assert "读写:只读;确认:跟随工具页的信任设置" in text and "dept(string,必填):部门编码" in text + assert "部门(部门编码)" in text and "负责人电话(遮罩,只给字段名)" in text + assert "读写:写入;确认:每次都要人确认" in text and "只能放在调用工具节点里" in text + # 不给地址、凭据、示例值 + assert "ep_secret_host" not in text and "D-0001" not in text + assert result.record["objects"][0]["versions"][names[0]] == 3 + + # 问数据(意图为回答)只列只读能力:写入能力不在概览里,点名也按没找到回 + answering = LookService([await CapabilityKind.load(read_only=True)]) + assert "写入" not in await answering.overview() + result = await answering.look({"op": "look", "need": "付款", "targets": [ + {"kind": "capability", "name": names[1]}]}, LookBudget()) + assert result.record["objects"][0]["missing"] == [names[1]] and "问数据时只能查看只读能力" in result.text + finally: + async with SessionLocal() as session: + for n in names: + await session.delete(await session.get(Capability, n)) + await session.commit() + + +# ---------------------------------------------------------------- 应用润色 + + +def _fake_app_ops(monkeypatch) -> list: + """应用操作的替身(BE-3 的 apply_app_op 还没接上时):app_add 加到页面末尾,app_update 合并 props。""" + from app.apps import ops + from app.api.copilot_gen import app_component + from app.look.base import Applied + + calls: list = [] + + def apply(spec, op): + calls.append(op) + if op["op"] == "app_add": + page = next(p for p in spec["pages"] if p["id"] == op["parent"]) + page["body"].append(op["component"]) + return Applied(True) + if op["op"] == "app_update": + have = app_component(spec, op["id"]) + if have is None: + return Applied(False, False, "没有这个组件") + have["props"] = {**have.get("props", {}), **op.get("props", {})} + return Applied(True) + return Applied(False, False, "认不出") + + monkeypatch.setattr(ops, "apply_app_op", apply) + return calls + + +def test_app_applier_dedupes_when_continuing(monkeypatch): + from app.api.copilot_gen import AppApplier + + calls = _fake_app_ops(monkeypatch) + spec = {"pages": [{"id": "home", "title": "首页", "body": [{"id": "gmv", "type": "metric", "props": {}}]}]} + applier = AppApplier(spec) + add = {"op": "app_add", "parent": "home", "index": 1, "component": {"id": "note", "type": "text", "props": {}}} + upd = {"op": "app_update", "id": "gmv", "props": {"label": "销售额"}} + assert applier.apply({"op": "plan", "summary": "改标题"}).forward + assert applier.apply(add).changed and applier.apply(upd).changed + assert applier.landed() == ["note", "gmv"] + applier.continuing() + # 接着写:重发的同一个操作、一模一样已经在 spec 里的组件、第二个 plan 都不再落地也不转发 + assert applier.apply(upd).forward is False + assert applier.apply({**add, "index": 0}).forward is False + assert applier.apply({"op": "plan", "summary": "又一个开场"}).forward is False + assert len(calls) == 2 + # 图操作不进应用 + assert applier.apply({"op": "add_node", "node": {"id": "x", "type": "llm"}}).forward is False + + +async def test_app_stream_looks_at_the_pinned_version_first(client, monkeypatch): + from app.apps import derive, lint, versions + from app.db.models import Workflow, WorkflowVersion + + _fake_app_ops(monkeypatch) + async with SessionLocal() as session: + wf = Workflow(name=f"周销售_{uuid.uuid4().hex[:4]}", graph={"nodes": [], "edges": []}) + session.add(wf) + await session.flush() + v1 = WorkflowVersion(workflow_id=wf.id, version=1, graph={"nodes": [], "edges": []}, graph_hash="h" * 64, + level="published") + session.add(v1) + await session.commit() + wf_id, wf_name = wf.id, wf.name + + async def _published(session, workflow_id): + from sqlalchemy import select + + return list((await session.execute(select(WorkflowVersion).where( + WorkflowVersion.workflow_id == workflow_id))).scalars()) if workflow_id == wf_id else [] + + async def _derive(session, workflow_id, version, *, name=None): + return {"format": "agentlab.app/1", "name": "派生", "pages": [{"id": "home", "title": "首页", "body": [ + {"id": "gmv", "type": "metric", "bind": {"view": "wk", "metric": "kpi.gmv"}}]}]} + + async def _lint(session, spec, bindings, **_): + return [{"level": "error", "code": "app.slot_unbound", "message": "岗位「财务」还没有绑定", "path": "slots"}] + + monkeypatch.setattr(versions, "published_versions", _published) + monkeypatch.setattr(derive, "derive_app", _derive) + monkeypatch.setattr(lint, "lint_app", _lint) + from app.apps import describe + + monkeypatch.setattr(describe, "describe_version", lambda v, *, workflow_name: "口径卡:kpi.gmv 销售额") + spec = {"format": "agentlab.app/1", "name": "看板", "slots": {"finance": {"label": "财务"}}, + "pins": [{"alias": "wk", "workflow_id": wf_id, "version": 1, "graph_hash": "h" * 64, "use": "view"}], + "pages": [{"id": "home", "title": "首页", "body": [{"id": "gmv", "type": "metric", "props": {}}]}]} + model = Turns([{"op": "plan", "summary": "改标题"}, {"op": "app_update", "id": "gmv", "props": {"label": "销售额"}}, + {"op": "done", "explanation": "改了指标的标题;岗位「财务」等着绑定"}]) + try: + events = await _events(client, monkeypatch, model, {"instruction": "指标标题写成销售额", "spec": spec}, + path="/api/copilot/app-stream") + finally: + async with SessionLocal() as session: + await session.delete(await session.get(Workflow, wf_id)) + await session.commit() + kinds = _ops(events) + assert kinds == ["look", "plan", "app_update", "done", "check", "final"], kinds + look = events[1] + assert look["by"] == "system" and look["objects"][0]["named"] == [f"{wf_name} v1"] + system, human = model.calls[0][0][1], model.calls[0][1][1] + assert "指标块" in system and "kpi.gmv" in system and "app_update" in system + assert "系统已代为查看" in human and "口径卡:kpi.gmv 销售额" in human + final = events[-1] + assert final["spec"]["pages"][0]["body"][0]["props"] == {"label": "销售额"} + # 只有人能处理的问题(岗位没绑)不交回模型改,照常列在交付的问题里 + assert final["issues"][0]["code"] == "app.slot_unbound" + assert next(e for e in events if e["op"] == "check")["status"] == "passed" + + +# ---------------------------------------------------------------- 从运行提取 + + +async def test_from_run_records_where_the_workflow_came_from(client): + from app.db.models import Run, RunEvent, Workflow + + graph = {"nodes": [{"id": "a", "type": "input", "data": {"label": "入口", "config": {}}}], "edges": []} + async with SessionLocal() as session: + run = Run(workflow_name="提取", status="succeeded", graph=graph) + session.add(run) + await session.flush() + session.add(RunEvent(run_id=run.id, seq=1, type="node.started", node_id="a", ts=0.0, data={})) + await session.commit() + run_id = run.id + r = await client.post("/api/copilot/from-run", json={"run_id": run_id, "conversation_id": "c1", "turn_id": "t1"}) + assert r.status_code == 200, r.text + async with SessionLocal() as session: + wf = await session.get(Workflow, r.json()["workflow_id"]) + assert wf.origin == {"run_id": run_id, "conversation_id": "c1", "turn_id": "t1"} + await client.delete(f"/api/workflows/{r.json()['workflow_id']}") diff --git a/backend/tests/test_copilot_merge.py b/backend/tests/test_copilot_merge.py index 71aff232..9f8c97da 100644 --- a/backend/tests/test_copilot_merge.py +++ b/backend/tests/test_copilot_merge.py @@ -363,24 +363,12 @@ async def test_the_one_shot_generate_reports_tool_changes_too(client, monkeypatc """非流式的 /generate 交回的是整张新图:照样比对、照样提醒。""" import app.api.copilot as copilot - rewritten = copy.deepcopy(ROUND_ONE) - del _config(rewritten, "query_data")["tools"] - raw = { - "explanation": "改了提示词", - "nodes": [{"id": n["id"], "type": n["type"], "label": n["data"]["label"], - "config": n["data"]["config"]} for n in rewritten["nodes"]], - "edges": rewritten["edges"], - } - - class _OneShot: - def with_structured_output(self, *_a, **_k): - return self - - async def ainvoke(self, _messages): - return raw + # 非流式的 /generate 和流式走同一个生成过程(copilot_gen):模型按操作流改图 + ops = [{"op": "update_node", "id": "query_data", "config": {"prompt": "短一点", "tools": None}}, + {"op": "done", "explanation": "改了提示词"}] async def _model(*_a, **_k): - return _OneShot(), "mock-fast" + return _Scripted(ops), "mock-fast" monkeypatch.setattr(copilot, "get_chat_model", _model) r = await client.post("/api/copilot/generate", json={ diff --git a/backend/tests/test_copilot_patch_layout.py b/backend/tests/test_copilot_patch_layout.py index a3c19835..27525fbd 100644 --- a/backend/tests/test_copilot_patch_layout.py +++ b/backend/tests/test_copilot_patch_layout.py @@ -204,18 +204,12 @@ async def test_a_text_reply_is_passed_through_on_the_canvas_too(client, monkeypa async def test_the_non_streaming_generate_keeps_positions_too(client, monkeypatch): import app.api.copilot as copilot - class _Structured: - def with_structured_output(self, _schema): - return self - - async def ainvoke(self, _messages): - return {"explanation": "改了提示词", "nodes": [ - {"id": n["id"], "type": n["type"], "label": n["id"], "config": n["data"]["config"]} - for n in BASE["nodes"] - ], "edges": BASE["edges"]} + # 非流式的 /generate 和流式走同一个生成过程(copilot_gen):模型按操作流改图 + ops = [{"op": "update_node", "id": "answer", "config": {"prompt": "简短回答:{{ input.question }}"}}, + {"op": "done", "explanation": "改了提示词"}] async def _model(*_a, **_k): - return _Structured(), "mock-fast" + return _Scripted(ops), "mock-fast" monkeypatch.setattr(copilot, "get_chat_model", _model) r = await client.post("/api/copilot/generate", json={"instruction": "改", "base_graph": BASE}) diff --git a/backend/tests/test_copilot_scope.py b/backend/tests/test_copilot_scope.py index 5eb66696..0a6f9322 100644 --- a/backend/tests/test_copilot_scope.py +++ b/backend/tests/test_copilot_scope.py @@ -188,23 +188,16 @@ async def test_the_one_shot_generate_refuses_an_empty_scope_with_the_same_code(c async def test_the_one_shot_generate_honours_the_scope(client, monkeypatch, sources): import app.api.copilot as copilot - seen: list = [] - - class _OneShot: - def with_structured_output(self, *_a, **_k): - return self - - async def ainvoke(self, messages): - seen.append(messages) - return {"nodes": [], "edges": []} + # 非流式的 /generate 和流式走同一个生成过程(copilot_gen):模型按操作流回答 + model = _Scripted([{"op": "reply", "text": "好"}]) async def _model(*_a, **_k): - return _OneShot(), "mock-fast" + return model, "mock-fast" monkeypatch.setattr(copilot, "get_chat_model", _model) r = await client.post("/api/copilot/generate", json={ "instruction": "订单多少", "datasource_ids": [sources["scope_shop"]], }) assert r.status_code == 200, r.text - system = next(t for role, t in seen[0] if role == "system") + system = model.systems[0] assert "db_query__scope_shop" in system and "db_query__scope_sales" not in system diff --git a/backend/tests/test_copilot_sql_alias.py b/backend/tests/test_copilot_sql_alias.py index 59a79893..6861fc26 100644 --- a/backend/tests/test_copilot_sql_alias.py +++ b/backend/tests/test_copilot_sql_alias.py @@ -7,7 +7,8 @@ cell() 都直接用中文名。 中文别名要按方言加标识符引号:MySQL / MariaDB 用反引号,PostgreSQL、Oracle、SQLite 用双引号;单引号是字符串。 这组守的是: -- 节点手册里 Agent 查库的说明、写 SQL 的硬性要求(搭查库节点时的规则)都有这一条,按方言给出示例 +- 节点手册里 Agent 查库的说明、写 SQL 的硬性要求(搭查库节点时的规则)都有这一条,按方言给出示例;写 SQL 的 + 硬性要求说的是「照查看结果写、没看过先 look」,不再让助手先放一个 db_schema 节点去猜(look 文档 D3) - 加了引号的中文别名不让自查放弃列名核对:以前 SQL 里只要有带引号的标识符就整条不判,照这条规矩写的 SQL 会把猜错的英文列名一起放过去 """ @@ -34,6 +35,11 @@ def test_guidance_asks_for_chinese_aliases_with_dialect_quotes(text): assert "单引号" in text # 单引号是字符串,不是别名 +def test_sql_rules_point_at_look_not_at_guessing(): + assert "look" in SQL_RULES_PROMPT and "查看结果" in SQL_RULES_PROMPT + assert "图里先放一个 db_schema 工具节点" not in SQL_RULES_PROMPT + + def _source(**tables): return SimpleNamespace(name="shop", schema_cache={"tables": { name: {"qualified": name, "columns": [{"name": c} for c in cols]} for name, cols in tables.items()}}) diff --git a/backend/tests/test_copilot_table_pick.py b/backend/tests/test_copilot_table_pick.py index 53361e70..1bdf3077 100644 --- a/backend/tests/test_copilot_table_pick.py +++ b/backend/tests/test_copilot_table_pick.py @@ -1,34 +1,37 @@ -"""助手建图时按需求挑表、组装数据源上下文(数据目录阶段 1B)。 +"""助手按需查看表结构:查看服务的表这一类(look 文档 §2.4 D2、D3、D6,§2.5.3–§2.5.7)。 -背景:大库(几十上百张表)超出详细摘要的阈值时,以前只给模型看表名,助手一个字段都看不到,只能照着 -名字编字段、猜怎么连表。现在先用一次轻量的模型调用按需求挑出相关的表,再沿关系图补上连接用的中间表, -挑中的表给全部字段、数据目录和可以照抄的连接条件,其余表只列名字。 +以前每一轮开始前服务端按库的大小挑表、塞进 system;现在 system 里每个库一行概览,模型要看表时输出一行 look, +查看服务一次给齐。这组守的是(合成景区库:入园记录和渠道之间要经关联表 channel_visits): -这组守的是: -- 挑表、补路径、组装的结果(合成景区库:入园记录和渠道之间要经关联表 channel_visits) -- 挑表失败(报错、超时、返回不存在的表、返回为空)一律退回只列表名,生成照常进行 -- 小库保持详细模式,额外带上目录 -- 流式输出里有 context 操作;自查修正沿用同一份上下文,不再重新挑表 -- 非流式生成、发布前修复、升级共用同一套组装 +- 概览:每个库一行,不列表名、不列字段;现有工作流用到的表只列名字 +- 点名直取,不调挑选模型;只给需求时候选不超过 12 张全给,否则按需求挑(关思考、额度小) +- 补两跳以内的中间表,合计不超过 16 张;连接条件、连接路径、数据目录照抄;推断的标出来,驳回的关系不用 +- 挑选失败(报错、超时、挑出的表都不存在、回复认不出)交回表目录(status=index),挑出来是空的照实说 +- 没找到的点名、认不出的库名写进结果和记录;限定的数据源之外的不看 +- 遮罩列只给列名和类型(D6),db_schema__ 和 /schema 接口是同一份说法 +- 字数上限之外的表只给字段名;同一批表这一轮看过就不再重排 """ from __future__ import annotations import asyncio -import json import sqlite3 import uuid import pytest from httpx import ASGITransport, AsyncClient -from app.data import catalog +from app.data import catalog, schema_view from app.data.catalog import INFERRED_MARK, make_item -from app.data.engine import engines from app.data.introspect import introspect from app.db.base import SessionLocal from app.db.models import DataSource +from app.look.base import CONTEXT_TABLE_LIMIT, LookBudget +from app.look.pick import Picker +from app.look.service import LookService, parse_targets +from app.look.tables import TableKind from app.main import app from tests.fixtures.catalog import scenic +from tests.fixtures.sources import drop_source @pytest.fixture @@ -37,10 +40,10 @@ async def client(): yield c -async def _add_source(database: str, *, prefix: str = "p1b") -> DataSource: +async def _add_source(database: str, *, prefix: str = "look", options: dict | None = None) -> DataSource: async with SessionLocal() as session: row = DataSource(name=f"{prefix}_{uuid.uuid4().hex[:8]}", kind="sqlite", database=database, - description="景区业务库") + description="景区业务库", options=options or {}) session.add(row) await session.commit() row.schema_cache = await introspect(row) @@ -50,21 +53,12 @@ async def _add_source(database: str, *, prefix: str = "p1b") -> DataSource: return row -async def _drop_source(row: DataSource) -> None: - await engines.invalidate(row.id) - async with SessionLocal() as session: - live = await session.get(DataSource, row.id) - if live is not None: - await session.delete(live) - await session.commit() - - @pytest.fixture async def scenic_source(scenic_db): - """接上合成景区库(50 张表 + 1 个视图),用完删掉:留着会让同一进程里别的测试也进入大库模式。""" + """接上合成景区库(50 张表 + 1 个视图),用完删掉。""" row = await _add_source(scenic_db) yield row - await _drop_source(row) + await drop_source(row.id) @pytest.fixture @@ -78,13 +72,33 @@ async def small_source(tmp_path): " ordered_at TEXT NOT NULL);") db.commit() db.close() - row = await _add_source(str(path), prefix="p1b_small") + row = await _add_source(str(path), prefix="look_small") yield row - await _drop_source(row) + await drop_source(row.id) -class Picker: - """挑表用的假模型:结构化输出返回自己,ainvoke 记下收到的提示词,按设定回复、报错或拖延。""" +@pytest.fixture +async def masked_source(tmp_path): + """设了遮罩列 phone 的库,phone 上记了中文名和码值。""" + path = tmp_path / "masked.db" + db = sqlite3.connect(path) + db.executescript("CREATE TABLE members (id INTEGER PRIMARY KEY, name TEXT NOT NULL, phone TEXT, level INTEGER);") + db.commit() + db.close() + row = await _add_source(str(path), prefix="look_mask", options={"mask_columns": "phone"}) + async with SessionLocal() as session: + await catalog.write_entry(session, row.id, "members", { + "label": make_item("会员", "human"), + "columns": {"phone": {"label": make_item("手机号", "human"), "codes": make_item({"138": "移动号段"}, "human"), + "meaning": make_item("会员登记的手机号,例如 13800000000", "human")}, + "level": {"codes": make_item({"1": "普通", "2": "金卡"}, "human")}}}, + if_version=0, actor="王敏") + yield row + await drop_source(row.id) + + +class FakePicker: + """挑选用的假模型:结构化输出返回自己,ainvoke 记下收到的提示词,按设定回复、报错或拖延。""" def __init__(self, reply=None, *, error: Exception | None = None, delay: float = 0.0) -> None: self.reply, self.error, self.delay = reply, error, delay @@ -103,454 +117,344 @@ class Picker: return self.reply -def _use_picker(monkeypatch, picker: Picker) -> list: - """挑表模型换成假的,返回每次拿模型时的规格(核对思考关、额度小)。""" - import app.api.copilot_context as copilot_context +def _use_picker(monkeypatch, fake: FakePicker) -> list: + """挑选模型换成假的,返回每次拿模型时的规格(核对思考关、额度小)。""" + import app.look.pick as pick specs: list = [] async def _model(_session, spec): specs.append(spec) - return picker, "fake-pick" + return fake, "fake-pick" - monkeypatch.setattr(copilot_context, "get_chat_model", _model) + monkeypatch.setattr(pick, "get_chat_model", _model) return specs -class Scripted: - """按剧本吐操作流的建图模型:第一轮吐 first,收到自查请求时吐 fix。记下每次的 system 和 human。""" +async def _service(sources, *, graph=None, picker: Picker | None = None) -> LookService: + from app.providers.factory import ModelSpec - def __init__(self, first: list[dict], fix: list[dict] | None = None) -> None: - self.first = [json.dumps(o, ensure_ascii=False) for o in first] - self.fix = [json.dumps(o, ensure_ascii=False) for o in (fix or [{"op": "done"}])] - self.systems: list[str] = [] - self.humans: list[str] = [] - - async def astream(self, messages): - from langchain_core.messages import AIMessageChunk - - self.systems.append(next(t for r, t in messages if r == "system")) - human = next(t for r, t in messages if r == "human") - self.humans.append(human) - for line in (self.fix if "上线前自查" in human else self.first): - yield AIMessageChunk(content=line + "\n") - - -def _graph_using(tool: str) -> list[dict]: - return [ - {"op": "add_node", "node": {"id": "start", "type": "input", "label": "输入", "config": {}}}, - {"op": "add_node", "node": {"id": "ask", "type": "agent", "label": "查库", "config": { - "prompt": "{{ input.question }}", "tools": [tool], "assign_to": "answer"}}}, - {"op": "add_edge", "edge": {"source": "start", "target": "ask"}}, - {"op": "add_node", "node": {"id": "out", "type": "output", "label": "成果", "config": { - "fields": [{"name": "answer", "value": "{{ vars.answer }}"}]}}}, - {"op": "add_edge", "edge": {"source": "ask", "target": "out"}}, - {"op": "done", "explanation": "查一下", "run": True}, - ] - - -async def _stream(client, monkeypatch, model, body: dict) -> list[dict]: - import app.api.copilot as copilot - - async def _model(*_a, **_k): - return model, "mock-fast" - - monkeypatch.setattr(copilot, "get_chat_model", _model) - events: list[dict] = [] - async with client.stream("POST", "/api/copilot/generate-stream", json=body) as r: - assert r.status_code == 200, await r.aread() - async for line in r.aiter_lines(): - if line.startswith("data: "): - events.append(json.loads(line[6:])) - return events + return LookService([await TableKind.load(sources, graph=graph, + picker=picker or Picker(ModelSpec(provider=None, model=None)))]) #: 需求和假模型挑出的表:入园记录、渠道。两者之间没有直接关联,要经关联表 channel_visits NEED = "各渠道上月的入园人次" -PICKED = {"tables": [{"table": "visits"}, {"table": "channels"}]} -#: 三张表各自独有的字段(describe_table 的写法:列名两个空格类型) +PICKED = {"items": [{"name": "visits"}, {"name": "channels"}]} +#: 三张表各自独有的字段(表详情的写法:列名两个空格类型) SELECTED_COLUMNS = ("visitor_count INTEGER", "visit_time TEXT", "ticket_no TEXT", "channel_type TEXT", "channel_code TEXT", "attributed_share REAL") -#: 没挑中的表独有的字段:不该出现在提示词里 +#: 没挑中的表独有的字段:不该出现在结果里 OTHER_COLUMNS = ("store_code", "sku", "on_hand", "refund_amount") JOINS = ("channel_visits.visit_id = visits.id", "channel_visits.channel_id = channels.id") -def _context_op(events: list[dict]) -> dict: - found = [e for e in events if e.get("op") == "context"] - assert len(found) == 1, [e.get("op") for e in events] - return found[0] +# ---------------------------------------------------------------- 概览 -# ---------------------------------------------------------------- 组装 +async def test_overview_is_one_line_per_source_without_tables(scenic_source, small_source): + graph = {"nodes": [{"id": "q", "type": "tool", "data": {"label": "查门店", "config": { + "tool": f"db_query__{scenic_source.name}", "args": {"sql": "SELECT s.name FROM stores s"}}}}], "edges": []} + looks = await _service([scenic_source, small_source], graph=graph) + text = await looks.overview() + total = scenic.TABLE_COUNT + len(scenic.VIEWS) + assert f"- {scenic_source.name}(sqlite,只读):景区业务库|共 {total} 张表,还没有数据目录" in text + assert f"- {small_source.name}(sqlite,只读):景区业务库|共 2 张表,还没有数据目录" in text + # 不列表名、不列字段;现有工作流用到的表只列名字 + assert "channel_visits" not in text and "visitor_count" not in text + assert f"现有工作流用到的表:{scenic_source.name} 的 stores" in text -async def test_pick_brings_in_the_bridge_table_and_spells_out_fields_and_joins(scenic_source): - from app.api import copilot_context +# ---------------------------------------------------------------- 点名、挑选 - picker = Picker(PICKED) - plan = await copilot_context.plan_context([scenic_source]) - assert plan.needs_pick - ctx = await plan.resolve(picker, need=NEED) - text = ctx.section() - assert len(picker.calls) == 1 - # 挑表的输入是需求加紧凑表目录(每张表一行),不是全部字段 - assert NEED in picker.calls[0] and "channel_visits" in picker.calls[0] - assert "attributed_share" not in picker.calls[0] +async def test_named_look_brings_in_the_bridge_without_the_picker(monkeypatch, scenic_source): + fake = FakePicker(error=AssertionError("点名不该调挑选模型")) + _use_picker(monkeypatch, fake) + looks = await _service([scenic_source]) + result = await looks.look({"op": "look", "need": NEED, "targets": [ + {"kind": "table", "name": "visits"}, {"kind": "table", "name": "CHANNELS"}]}, LookBudget()) - (source,) = ctx.sources - assert source.selected_by == "model" - assert source.tables == ["visits", "channels", "channel_visits"] + assert not fake.calls + assert result.text.startswith("查看结果(第 1 次,这一轮最多 3 次)\n需求:" + NEED) for col in SELECTED_COLUMNS: - assert col in text, col + assert col in result.text, col for col in OTHER_COLUMNS: - assert col not in text, col + assert col not in result.text, col for cond in JOINS: - assert cond in text, cond - # 其余表只给名字,让模型知道还有别的表 - assert "stores" in text and "parks" in text and "v_daily_visits" in text - # 写 SQL 的硬性要求保留 - assert "写 SQL 的硬性要求" in text and "FETCH FIRST n ROWS ONLY" in text + assert cond in result.text, cond + assert "表 channel_visits(为连接补上)" in result.text + record = result.record + assert record["op"] == "look" and record["id"] == "L1" and record["by"] == "model" and record["status"] == "ok" + assert isinstance(record["elapsed_ms"], int) + (block,) = record["objects"] + assert block["kind"] == "table" and block["source"] == scenic_source.name + assert block["source_id"] == scenic_source.id + assert (block["named"], block["picked"], block["joined"], block["missing"]) == ( + ["visits", "channels"], [], ["channel_visits"], []) + assert block["total"] == scenic.TABLE_COUNT + len(scenic.VIEWS) and block["catalog_tables"] == 0 + + +async def test_need_only_look_picks_with_a_small_fast_model(monkeypatch, scenic_source): + fake = FakePicker(PICKED) + specs = _use_picker(monkeypatch, fake) + looks = await _service([scenic_source]) + result = await looks.look({"op": "look", "need": NEED}, LookBudget()) + + assert len(fake.calls) == 1 + # 挑选的输入是需求加紧凑的表目录(每张表一行),不是全部字段 + assert NEED in fake.calls[0] and "channel_visits" in fake.calls[0] and "attributed_share" not in fake.calls[0] + (spec,) = specs + assert spec.thinking == "off" and spec.max_tokens <= 2048 + (block,) = result.record["objects"] + assert (block["named"], block["picked"], block["joined"]) == ([], ["visits", "channels"], ["channel_visits"]) + assert f"按需求从 {scenic.TABLE_COUNT + len(scenic.VIEWS)} 张表中挑出 2 张,另为连接补上 1 张" in result.text + + +async def test_a_small_pool_is_given_whole_without_picking(monkeypatch, small_source): + fake = FakePicker(error=AssertionError("候选不超过 12 张不该挑")) + _use_picker(monkeypatch, fake) + looks = await _service([small_source]) + result = await looks.look({"op": "look", "need": "订单总额"}, LookBudget()) + assert not fake.calls + assert "候选只有 2 张表,全部给出" in result.text + assert "表 customers" in result.text and "表 orders" in result.text + assert f"orders.customer_id = customers.id(多对一){INFERRED_MARK}" in result.text + assert result.record["objects"][0]["picked"] == ["customers", "orders"] + + +@pytest.mark.parametrize("fake", [ + FakePicker(error=RuntimeError("网关超时")), + FakePicker(PICKED, delay=5), + FakePicker({"items": [{"name": "no_such_table"}, {"name": "也没有这张"}]}), + FakePicker("我觉得都需要"), +], ids=["error", "timeout", "unknown", "garbage"]) +async def test_pick_failures_hand_back_the_index(monkeypatch, scenic_source, fake): + import app.look.pick as pick + + monkeypatch.setattr(pick, "PICK_TIMEOUT_S", 0.2) + _use_picker(monkeypatch, fake) + looks = await _service([scenic_source]) + result = await looks.look({"op": "look", "need": NEED}, LookBudget()) + + record = result.record + assert record["status"] == "index" and record["reason"] and record["objects"] == [] + # 交回的是表目录(每张表一行),请模型点名再看;不给字段 + assert "没能按需求挑出表" in result.text and record["reason"] in result.text + assert "channel_visits" in result.text and "attributed_share" not in result.text + assert "点名" in result.text + + +async def test_an_empty_pick_is_reported_as_such(monkeypatch, scenic_source): + """挑选模型照提示说「需求和这份目录无关」返回空:照实说没挑出来,不当成失败、不塞表。""" + _use_picker(monkeypatch, FakePicker({"items": []})) + looks = await _service([scenic_source]) + result = await looks.look({"op": "look", "need": "你好"}, LookBudget()) + assert result.record["status"] == "index" + assert result.record["reason"] == "按这个需求没有挑出相关的表" + assert "按这个需求没有挑出相关的表" in result.text and "attributed_share" not in result.text + + +async def test_the_demo_model_cannot_pick(monkeypatch, scenic_source): + """没配接入时挑选模型是演示模型:照实说挑不了,交回目录。""" + import app.look.pick as pick + from app.providers.mock_model import MockChatModel + + async def _demo(_session, _spec): + return MockChatModel(model_name="mock-fast"), "mock-fast" + + monkeypatch.setattr(pick, "get_chat_model", _demo) + looks = await _service([scenic_source]) + result = await looks.look({"op": "look", "need": NEED}, LookBudget()) + assert result.record["status"] == "index" and "演示模型" in result.record["reason"] + + +# ---------------------------------------------------------------- 没找到、限定范围、多个库 + + +async def test_missing_tables_and_sources_are_named(scenic_source): + looks = await _service([scenic_source]) + result = await looks.look({"op": "look", "need": "退款明细", "targets": [ + {"kind": "table", "name": "refunds"}, {"kind": "table", "name": "refund_detail"}, + {"kind": "table", "source": "没有这个库", "name": "refunds"}]}, LookBudget()) + assert "表 refunds" in result.text + assert f"没找到:{scenic_source.name} 的 refund_detail" in result.text and "别拿名字相近的表顶替" in result.text + assert "没找到数据源「没有这个库」" in result.text + blocks = {b["source"]: b for b in result.record["objects"]} + assert blocks[scenic_source.name]["named"] == ["refunds"] + assert blocks[scenic_source.name]["missing"] == ["refund_detail"] + assert blocks["没有这个库"]["source_id"] is None and blocks["没有这个库"]["missing"] == ["refunds"] + + +async def test_several_sources_and_the_sources_field(monkeypatch, scenic_db, tmp_path): + a = await _add_source(scenic_db) + b = await _add_source(str(scenic.build(tmp_path / "b.db"))) + try: + fake = FakePicker({"items": [{"source": a.name, "name": "visits"}, {"source": b.name, "name": "orders"}, + f"{b.name}.payments", {"source": "没有这个库", "name": "refunds"}]}) + _use_picker(monkeypatch, fake) + looks = await _service([a, b]) + result = await looks.look({"op": "look", "need": "订单和入园"}, LookBudget()) + assert f"数据源「{a.name}」" in fake.calls[0] and f"数据源「{b.name}」" in fake.calls[0] + blocks = {o["source"]: o for o in result.record["objects"]} + assert blocks[a.name]["picked"] == ["visits"] + assert blocks[b.name]["picked"] == ["orders", "payments"] + + # sources 限定只在 b 里挑:挑选的目录里只有 b + fake.calls.clear() + fake.reply = {"items": [{"name": "refunds"}]} + result = await looks.look({"op": "look", "need": "退款", "sources": [b.name]}, LookBudget()) + assert f"数据源「{a.name}」" not in fake.calls[0] + assert [o["source"] for o in result.record["objects"]] == [b.name] + finally: + await drop_source(a.id) + await drop_source(b.id) + + +async def test_tables_outside_the_users_scope_are_not_found(scenic_db, small_source): + """用户限定了数据源:查看服务只认这一轮的源,别的库里的表按没找到回。""" + looks = await _service([small_source]) + result = await looks.look({"op": "look", "need": "入园", "targets": [ + {"kind": "table", "name": "visits"}]}, LookBudget()) + assert "没找到" in result.text and "visitor_count" not in result.text + + +# ---------------------------------------------------------------- 连接条件、目录 async def test_inferred_relations_are_marked_and_catalog_is_attached(scenic_source): """visits.gate_id → gates 没有外键约束,是按列名推断的,连接条件要标出来;目录里推断的项同样要标。""" - from app.api import copilot_context - async with SessionLocal() as session: await catalog.write_entry(session, scenic_source.id, "visits", { "label": make_item("入园记录", "llm"), "grain": make_item("每张门票每次检票一行", "human")}, if_version=0, actor="王敏") - plan = await copilot_context.plan_context([scenic_source]) - ctx = await plan.resolve(Picker({"tables": [{"table": "visits"}, {"table": "gates"}]}), need="各入口闸机的入园人次") - text = ctx.section() - assert f"visits.gate_id = gates.id(多对一){INFERRED_MARK}" in text - assert f"中文名:入园记录{INFERRED_MARK}" in text - assert "粒度:每张门票每次检票一行" in text and f"每张门票每次检票一行{INFERRED_MARK}" not in text + looks = await _service([scenic_source]) + result = await looks.look({"op": "look", "need": "各入口闸机的入园人次", "targets": [ + {"kind": "table", "name": "visits"}, {"kind": "table", "name": "gates"}]}, LookBudget()) + assert f"visits.gate_id = gates.id(多对一){INFERRED_MARK}" in result.text + assert f"中文名:入园记录{INFERRED_MARK}" in result.text + assert "粒度:每张门票每次检票一行" in result.text and f"每张门票每次检票一行{INFERRED_MARK}" not in result.text + assert "推断,未确认」的说明和连接条件" in result.text + (block,) = result.record["objects"] + assert block["catalog_tables"] == 1 and set(block["catalog_versions"]) == {"visits"} async def test_rejected_relations_are_not_used_for_join_paths(scenic_source): """人工驳回的关系不能拿来补路径:驳回 channel_visits → visits 后,关联表不会因为补路径被带进来。""" - from app.api import copilot_context - rels = [dict(r, status="rejected") if r["to_table"] == "visits" else r for r in catalog.fk_relations(scenic_source.schema_cache, "channel_visits")] async with SessionLocal() as session: await catalog.write_entry(session, scenic_source.id, "channel_visits", {"relations": rels}, if_version=0, actor="王敏") - plan = await copilot_context.plan_context([scenic_source]) - ctx = await plan.resolve(Picker(PICKED), need=NEED) - assert ctx.sources[0].tables == ["visits", "channels"] - assert "channel_visits.visit_id = visits.id" not in ctx.section() + looks = await _service([scenic_source]) + result = await looks.look({"op": "look", "need": NEED, "targets": [ + {"kind": "table", "name": "visits"}, {"kind": "table", "name": "channels"}]}, LookBudget()) + assert result.record["objects"][0]["joined"] == [] + assert "channel_visits.visit_id = visits.id" not in result.text -async def test_picks_are_capped_and_paths_respect_the_total_limit(scenic_source): - from app.api import copilot_context - +async def test_bridges_respect_the_total_limit(scenic_source): names = list(scenic_source.schema_cache["tables"]) - plan = await copilot_context.plan_context([scenic_source]) - ctx = await plan.resolve(Picker({"tables": [{"table": n} for n in reversed(names)]}), need="全部都要") - # 挑中的按模型给的顺序截到上限;补中间表之后合计也不超过总上限 - assert ctx.sources[0].picked == list(reversed(names))[:copilot_context.PICK_LIMIT] - assert ctx.sources[0].tables[:copilot_context.PICK_LIMIT] == ctx.sources[0].picked - assert len(ctx.sources[0].tables) <= copilot_context.CONTEXT_TABLE_LIMIT + looks = await _service([scenic_source]) + result = await looks.look({"op": "look", "need": "全部都要", "targets": [ + {"kind": "table", "name": n} for n in names]}, LookBudget()) + (block,) = result.record["objects"] + assert len(block["named"]) + len(block["joined"]) <= CONTEXT_TABLE_LIMIT + assert f"一次最多查看 {CONTEXT_TABLE_LIMIT} 张表" in result.text - # 两两都要补中间表的一组:总数不超过上限 spread = ["reviews", "channels", "stores", "tour_groups", "coupons", "products"] - ctx = await plan.resolve(Picker({"tables": [{"table": n} for n in spread]}), need="x") - assert set(spread) <= set(ctx.sources[0].tables) - assert len(ctx.sources[0].tables) <= copilot_context.CONTEXT_TABLE_LIMIT + looks = await _service([scenic_source]) + result = await looks.look({"op": "look", "need": "x", "targets": [ + {"kind": "table", "name": n} for n in spread]}, LookBudget()) + (block,) = result.record["objects"] + assert set(spread) <= set(block["named"]) + assert len(block["named"]) + len(block["joined"]) <= CONTEXT_TABLE_LIMIT -async def test_tables_used_by_the_current_graph_are_always_included(scenic_source): - """改图、追问时现有工作流已经查了哪些表是确定的事实:挑表成功时并进来,挑表失败时也给它们的字段。""" - from app.api import copilot_context - - graph = {"nodes": [{"id": "q", "type": "tool", "data": {"label": "查门店", "config": { - "tool": f"db_query__{scenic_source.name}", "args": {"sql": "SELECT s.name FROM stores s"}}}}], "edges": []} - plan = await copilot_context.plan_context([scenic_source], graph=graph) - picker = Picker({"tables": [{"table": "visits"}]}) - ctx = await plan.resolve(picker, need="再按入园人次排一下") - assert ctx.sources[0].tables[:2] == ["stores", "visits"] - assert "当前工作流已用到" in picker.calls[0] and "stores" in picker.calls[0] - - failed = await plan.resolve(Picker(error=RuntimeError("网关超时")), need="再按入园人次排一下") - assert failed.sources[0].selected_by == "fallback" - assert failed.sources[0].tables == ["stores"] - assert "store_code TEXT" in failed.section() +# ---------------------------------------------------------------- 遮罩(D6) -async def test_several_sources_pick_with_source_names(scenic_db, tmp_path): - from app.api import copilot_context +async def test_masked_columns_give_only_name_and_type_everywhere(client, masked_source): + """遮罩列只给列名和类型:目录里这一列的中文名、码值、带取值的含义都不给。助手查看、db_schema__、/schema 接口 + 是同一份说法(look 文档 D6)。""" + from app.tools.datasource import _catalog_of, _make_schema_tool - a = await _add_source(scenic_db) - b = await _add_source(str(scenic.build(tmp_path / "b.db"))) - try: - plan = await copilot_context.plan_context([a, b]) - picker = Picker({"tables": [{"source": a.name, "table": "visits"}, {"source": b.name, "table": "orders"}, - f"{b.name}.payments", {"source": "没有这个库", "table": "refunds"}]}) - ctx = await plan.resolve(picker, need="订单和入园") - assert f"数据源「{a.name}」" in picker.calls[0] and f"数据源「{b.name}」" in picker.calls[0] - by_name = {s.source.name: s for s in ctx.sources} - assert by_name[a.name].tables == ["visits"] - assert by_name[b.name].tables == ["orders", "payments"] - op = ctx.op() - assert [s["source"] for s in op["sources"]] == [a.name, b.name] - assert all(s["selected_by"] == "model" for s in op["sources"]) - finally: - await _drop_source(a) - await _drop_source(b) + entries = await _catalog_of(masked_source) + detail = schema_view.table_detail(masked_source, "members", + catalog_notes={t: e.notes for t, e in entries.items()}) + assert "phone TEXT 已遮罩,只给列名和类型" in detail + assert "手机号" not in detail and "移动号段" not in detail and "13800000000" not in detail + # 别的列的目录照给 + assert "1=普通" in detail and "中文名:会员" in detail + + tool = _make_schema_tool(masked_source, catalog=entries) + assert await tool.coroutine(table="members") == detail + body = (await client.get(f"/api/datasources/{masked_source.id}/schema", params={"table": "members"})).json() + assert body["detail"] == detail + + looks = await _service([masked_source]) + result = await looks.look({"op": "look", "need": "会员", "targets": [ + {"kind": "table", "name": "members"}]}, LookBudget()) + assert "已遮罩,只给列名和类型" in result.text and "手机号" not in result.text and "移动号段" not in result.text + assert "设了遮罩" in await looks.overview() -async def test_small_source_keeps_detail_and_carries_the_catalog(small_source): - from app.api import copilot_context - - async with SessionLocal() as session: - await catalog.write_entry(session, small_source.id, "orders", { - "label": make_item("订单", "llm"), - "columns": {"amount": {"unit": make_item("元", "human")}}}, if_version=0, actor="王敏") - picker = Picker(error=AssertionError("小库不该挑表")) - plan = await copilot_context.plan_context([small_source]) - assert not plan.needs_pick - ctx = await plan.resolve(picker, need="订单总额") - text = ctx.section() - assert not picker.calls - # 详细模式的写法照旧:每张表一行带字段 - assert "· orders[表]" in text and "· customers[表]" in text - # 额外带上目录和连接条件 - assert f"中文名:订单{INFERRED_MARK}" in text and "单位:元" in text - assert f"orders.customer_id = customers.id(多对一){INFERRED_MARK}" in text - op = ctx.op() - assert op["sources"] == [{"source": small_source.name, "source_id": small_source.id, - "tables": ["customers", "orders"], "selected_by": "all", "total": 2, - "catalog_tables": 1}] +# ---------------------------------------------------------------- 字数上限、重复查看、次数 -# ---------------------------------------------------------------- 回退:绝不阻断生成 +async def test_tables_over_the_char_limit_only_get_column_names(monkeypatch, scenic_source): + import app.look.service as service + + monkeypatch.setattr(service, "LOOK_RESULT_CHARS", 400) + looks = await _service([scenic_source]) + result = await looks.look({"op": "look", "need": "订单", "targets": [ + {"kind": "table", "name": n} for n in ("orders", "order_items", "payments", "refunds")]}, LookBudget()) + assert "字数超了只给字段名" in result.text and "后面的表只给了字段名" in result.text + # 第一张表给全了,后面的只给字段名 + assert "total_amount REAL" in result.text + assert "refunds[表]:" in result.text -@pytest.mark.parametrize("picker", [ - Picker(error=RuntimeError("网关超时")), - Picker(PICKED, delay=5), - Picker({"tables": [{"table": "no_such_table"}, {"table": "也没有这张"}]}), - Picker({"tables": []}), - Picker("我觉得都需要"), -], ids=["error", "timeout", "unknown", "empty", "garbage"]) -async def test_pick_failures_fall_back_to_names_only(client, monkeypatch, scenic_source, picker): - import app.api.copilot_context as copilot_context - - monkeypatch.setattr(copilot_context, "PICK_TIMEOUT_S", 0.2) - _use_picker(monkeypatch, picker) - model = Scripted(_graph_using(f"db_query__{scenic_source.name}")) - events = await _stream(client, monkeypatch, model, { - "instruction": NEED, "intent": "answer", "datasource_ids": [scenic_source.id]}) - - op = _context_op(events) - assert op["sources"] == [{"source": scenic_source.name, "source_id": scenic_source.id, "tables": [], - "selected_by": "fallback", "total": scenic.TABLE_COUNT + len(scenic.VIEWS), - "catalog_tables": 0, "reason": op["sources"][0]["reason"]}] - assert op["sources"][0]["reason"] - system = model.systems[0] - # 和以前一样只列表名、提醒先查字段 - assert "channel_visits" in system and "attributed_share" not in system - assert "写 SQL 前用 db_schema 工具确认字段" in system - # 生成照常进行 - assert events[-1]["op"] == "final", events[-1] +async def test_looking_at_the_same_tables_again_is_short_circuited(scenic_source): + looks = await _service([scenic_source]) + budget = LookBudget() + line = {"op": "look", "need": "门店", "targets": [{"kind": "table", "name": "stores"}]} + first = await looks.look(line, budget) + again = await looks.look(line, budget) + assert first.record is not None and again.record is None and again.counted + assert "已经在上面" in again.text and "store_code" not in again.text + assert budget.used == 2 and [r["id"] for r in looks.records] == ["L1"] + # 多了一张没看过的就照常查看 + more = await looks.look({**line, "targets": [{"kind": "table", "name": "stores"}, + {"kind": "table", "name": "parks"}]}, budget) + assert more.record["id"] == "L2" - -# ---------------------------------------------------------------- 流式:context 操作、自查沿用同一份上下文 +async def test_need_is_required_and_the_limit_is_kept(scenic_source): + looks = await _service([scenic_source]) + budget = LookBudget(limit=1) + nothing = await looks.look({"op": "look", "targets": [{"kind": "table", "name": "stores"}]}, budget) + assert "look 要写 need" in nothing.text and not nothing.counted and budget.used == 0 + await looks.look({"op": "look", "need": "门店", "targets": [{"kind": "table", "name": "stores"}]}, budget) + over = await looks.look({"op": "look", "need": "园区", "targets": [{"kind": "table", "name": "parks"}]}, budget) + assert "查看次数已用完" in over.text and over.record is None and not over.counted -async def test_stream_reports_the_context_and_prompt_carries_selected_tables(client, monkeypatch, scenic_source): - from app.api import copilot_context - - picker = Picker(PICKED) - specs = _use_picker(monkeypatch, picker) - model = Scripted(_graph_using(f"db_query__{scenic_source.name}")) - events = await _stream(client, monkeypatch, model, { - "instruction": NEED, "intent": "answer", "datasource_ids": [scenic_source.id]}) - - op = _context_op(events) - assert op["sources"] == [{"source": scenic_source.name, "source_id": scenic_source.id, - "tables": ["visits", "channels", "channel_visits"], "selected_by": "model", - "total": scenic.TABLE_COUNT + len(scenic.VIEWS), "catalog_tables": 0}] - assert isinstance(op["elapsed_ms"], int) and op["elapsed_ms"] >= 0 - # context 在模型首帧之后、第一条图操作之前 - kinds = [e["op"] for e in events] - assert kinds.index("model") < kinds.index("context") < kinds.index("add_node") - - # 挑表用同一个助手模型,关掉思考、额度取小 - (spec,) = specs - assert spec.thinking == "off" and spec.max_tokens == copilot_context.PICK_MAX_TOKENS - assert spec.max_tokens <= 2048 - - system = model.systems[0] - for col in SELECTED_COLUMNS: - assert col in system, col - for col in OTHER_COLUMNS: - assert col not in system, col - for cond in JOINS: - assert cond in system, cond - # 工具清单里列出的可查对象,先列挑中的表 - tool_line = next(line for line in system.splitlines() if line.startswith(f"- db_query__{scenic_source.name}")) - assert "可查:visits、channels、channel_visits" in tool_line +# ---------------------------------------------------------------- 旧写法 -async def test_self_check_repair_reuses_the_same_context(client, monkeypatch, scenic_source): - picker = Picker(PICKED) - _use_picker(monkeypatch, picker) - tool = f"db_query__{scenic_source.name}" - first = [ - {"op": "add_node", "node": {"id": "start", "type": "input", "label": "输入", "config": {}}}, - {"op": "add_node", "node": {"id": "q", "type": "tool", "label": "查入园", "config": { - "tool": tool, "args": {"sql": "SELECT v.no_such_col FROM visits v"}, "assign_to": "rows"}}}, - {"op": "add_edge", "edge": {"source": "start", "target": "q"}}, - {"op": "add_node", "node": {"id": "out", "type": "output", "label": "成果", "config": { - "fields": [{"name": "rows", "value": "{{ vars.rows }}"}]}}}, - {"op": "add_edge", "edge": {"source": "q", "target": "out"}}, - {"op": "done", "explanation": "查一下", "run": False}, +def test_the_old_tables_field_is_read_as_table_targets(): + """look 文档初稿的写法 tables:[{source, table}](以及只写表名的字符串)读进来换成 kind=table 的 targets。""" + assert parse_targets({"op": "look", "need": "x", "tables": [{"source": "库 B", "table": "refunds"}, "orders"], + "targets": [{"kind": "capability", "name": "db_query__b"}, {"name": "没写类别"}]}) == [ + {"kind": "capability", "name": "db_query__b"}, + {"kind": "table", "name": "refunds", "source": "库 B"}, + {"kind": "table", "name": "orders"}, ] - fix = [{"op": "update_node", "id": "q", "config": {"args": {"sql": "SELECT v.visitor_count FROM visits v"}}}, - {"op": "done"}] - model = Scripted(first, fix) - events = await _stream(client, monkeypatch, model, { - "instruction": NEED, "datasource_ids": [scenic_source.id]}) - - assert any(e.get("op") == "check" and e.get("status") == "repairing" for e in events) - assert len(model.systems) == 2 and "上线前自查" in model.humans[1] - # 修正轮带的是同一份上下文,没有重新挑表 - assert model.systems[1] == model.systems[0] - assert "attributed_share REAL" in model.systems[1] - assert len(picker.calls) == 1 -async def test_context_op_says_how_much_of_each_source_has_a_catalog(scenic_source): - """context 操作里每个源带上有数据目录的表数(catalog_tables)和源的 id:没有目录的大库,界面提示先去起草目录。 - - 真实运行里数据源一张目录都没有,挑表和 SQL 检查都用不上目录,用户也不知道该先去起草。只算有可见项的表: - 整份被驳回的不算有目录。""" - from app.api import copilot_context - - async def op() -> dict: - plan = await copilot_context.plan_context([scenic_source]) - return (await plan.resolve(Picker(PICKED), need=NEED)).op()["sources"][0] - - first = await op() - assert first["catalog_tables"] == 0 and first["source_id"] == scenic_source.id - async with SessionLocal() as session: - await catalog.write_entry(session, scenic_source.id, "visits", { - "label": make_item("入园记录", "llm")}, if_version=0, actor="王敏") - rejected = make_item("门店", "llm") - rejected["status"] = "rejected" - await catalog.write_entry(session, scenic_source.id, "stores", {"label": rejected}, if_version=0, actor="王敏") - assert (await op())["catalog_tables"] == 1 - - -async def test_small_sources_do_not_call_the_picker(client, monkeypatch, small_source): - picker = Picker(error=AssertionError("小库不该挑表")) - _use_picker(monkeypatch, picker) - model = Scripted(_graph_using(f"db_query__{small_source.name}")) - events = await _stream(client, monkeypatch, model, { - "instruction": "订单总额", "intent": "answer", "datasource_ids": [small_source.id]}) - op = _context_op(events) - assert op["sources"][0]["selected_by"] == "all" and "elapsed_ms" not in op - assert not picker.calls - assert "· orders[表]" in model.systems[0] - - -# ---------------------------------------------------------------- 非流式和两个兜底入口:同一套组装,不发 context - - -async def test_one_shot_generate_uses_the_same_context(client, monkeypatch, scenic_source): - import app.api.copilot as copilot - - picker = Picker(PICKED) - _use_picker(monkeypatch, picker) - seen: list = [] - - class _OneShot: - def with_structured_output(self, *_a, **_k): - return self - - async def ainvoke(self, messages): - seen.append(messages) - return {"nodes": [], "edges": []} - - async def _model(*_a, **_k): - return _OneShot(), "mock-fast" - - monkeypatch.setattr(copilot, "get_chat_model", _model) - r = await client.post("/api/copilot/generate", json={"instruction": NEED, "datasource_ids": [scenic_source.id]}) - assert r.status_code == 200, r.text - assert len(picker.calls) == 1 and NEED in picker.calls[0] - system = next(t for role, t in seen[0] if role == "system") - for cond in JOINS: - assert cond in system - assert "attributed_share REAL" in system - - -def _node(nid, ntype, label, **config): - return {"id": nid, "type": ntype, "position": {"x": 0, "y": 0}, "data": {"label": label, "config": config}} - - -async def test_publish_fix_shares_the_context(monkeypatch, scenic_source): - """发布前修复:现有图查的表一定带上,需求写的是挡住发布的问题;不发 context 操作(返回值里没有)。""" - import app.api.copilot as copilot - - picker = Picker({"tables": [{"source": scenic_source.name, "table": "visits"}, - {"source": scenic_source.name, "table": "channels"}]}) - _use_picker(monkeypatch, picker) - model = Scripted([{"op": "plan", "summary": "看一下"}, {"op": "done", "explanation": "无法修改"}]) - - async def _model(*_a, **_k): - return model, "mock-fast" - - monkeypatch.setattr(copilot, "get_chat_model", _model) - graph = {"nodes": [ - _node("start", "input", "周期"), - _node("fetch", "tool", "取数", tool=f"db_query__{scenic_source.name}", - args={"sql": "SELECT SUM(amount) AS gmv FROM store_sales"}), - _node("write", "report", "报告撰写", instructions="写周报", numbers="strict", on_violation="fail"), - _node("done", "output", "出具", fields=[{"name": "周报", "value": "{{ nodes.write.text }}"}]), - _node("raw", "output", "原始数", fields=[{"name": "数", "value": "{{ nodes.fetch }}"}]), - ], "edges": [{"id": f"e{i}", "source": a, "target": b} for i, (a, b) in enumerate( - [("start", "fetch"), ("fetch", "write"), ("write", "done"), ("fetch", "raw")])]} - async with SessionLocal() as session: - out = await copilot.assist_publish_fix(session, graph, level="governed") - assert model.systems, out - assert len(picker.calls) == 1 and "发布前检查" in picker.calls[0] - system = model.systems[0] - assert "attributed_share REAL" in system and "sold_at TEXT" in system - assert "context" not in json.dumps(out, ensure_ascii=False) - - -async def test_upgrade_shares_the_context(monkeypatch, scenic_source): - import app.api.copilot as copilot - - picker = Picker({"tables": [{"source": scenic_source.name, "table": "no_such_table"}]}) - _use_picker(monkeypatch, picker) - model = Scripted([{"op": "plan", "summary": "看一下"}, {"op": "done", "explanation": "不改"}]) - - async def _model(*_a, **_k): - return model, "mock-fast" - - monkeypatch.setattr(copilot, "get_chat_model", _model) - graph = {"nodes": [ - _node("start", "input", "输入"), - _node("fetch", "tool", "查库", tool=f"db_query__{scenic_source.name}", - args={"sql": "SELECT SUM(amount) AS a, COUNT(*) AS b FROM store_sales"}), - _node("calc", "code", "算比率", language="python", assign_to="calc", - code="import json\nprint(json.dumps({'ratio': 3 / 4}))"), - _node("card", "metrics", "口径卡", metrics=[{"id": "ratio", "name": "客单价", "expression": "vars.calc.ratio"}]), - _node("write", "report", "报告撰写", instructions="写一句话"), - _node("out", "output", "成果", fields=[{"name": "周报", "value": "{{ nodes.write.text }}"}]), - ], "edges": [{"id": f"e{i}", "source": a, "target": b} for i, (a, b) in enumerate( - [("start", "fetch"), ("fetch", "calc"), ("calc", "card"), ("card", "write"), ("write", "out")])]} - async with SessionLocal() as session: - await copilot.assist_upgrade(session, graph, level="published") - assert model.systems and len(picker.calls) == 1 - # 挑表失败也不挡:现有图查的表照样给全字段,其余表只列名字 - system = model.systems[0] - assert "sold_at TEXT" in system and "attributed_share" not in system +async def test_the_old_tables_field_still_looks(scenic_source): + looks = await _service([scenic_source]) + result = await looks.look({"op": "look", "need": "门店", + "tables": [{"source": scenic_source.name, "table": "stores"}]}, LookBudget()) + assert result.record["objects"][0]["named"] == ["stores"] and "store_code TEXT" in result.text