Merged
docs: 收敛应用接入与对外接口参考 #735
docs: 收敛应用接入与对外接口参考 #735
Merged
jaxAdd on 5 days ago
Total: 47 files changed+1476-1261
@@ -7,7 +7,7 @@ This directory in the [DataAgent repository on GitCode](https://gitcode.com/data
7- Developer guides in [English](en/development/1.1-developer-guide.md) and [Chinese](zh/development/1.1-developer-guide.md)7- Developer guides in [English](en/development/1.1-developer-guide.md) and [Chinese](zh/development/1.1-developer-guide.md)
8- [Community](en/development/community-index.md) and [社区](zh/development/community-index.md)8- [Community](en/development/community-index.md) and [社区](zh/development/community-index.md)
9 9 
10-Maintain routes, response envelopes, and HTTP status codes in the bilingual REST references. Keep the AG-UI request and event contract in `docs/zh/reference/3.3-ag-ui-events.md` and the A2A contract in `docs/zh/reference/3.4-a2a-reference.md`. Integration and architecture pages link to those contracts.10+Maintain public HTTP routes, responses, and AG-UI requests and events in the bilingual REST references. Keep the A2A contract in the bilingual A2A references. Integration and architecture pages link to those contracts.
11 11 
12## Documentation scope12## Documentation scope
13 13 
@@ -220,7 +220,6 @@
220 ["AG-UI integration", "AG-UI 接入"],220 ["AG-UI integration", "AG-UI 接入"],
221 ["A2A integration", "用 A2A 连接 Agent 并管理任务"],221 ["A2A integration", "用 A2A 连接 Agent 并管理任务"],
222 ["A2A protocol", "A2A 参考"],222 ["A2A protocol", "A2A 参考"],
223- ["AG-UI protocol", "AG-UI 事件与运行契约"],
224 ["Extension schema", "扩展声明"],223 ["Extension schema", "扩展声明"],
225 ["MCP configuration", "MCP 配置参考"],224 ["MCP configuration", "MCP 配置参考"],
226 ["Overview", "了解 DataAgent"],225 ["Overview", "了解 DataAgent"],
Mdocs/en/getting-started/2.2-capabilities.md+3-3File content is under review, please try again later
@@ -8,7 +8,7 @@ Public examples use placeholders such as `replace-with-your-key`. Do not commit
8 8 
9Put secrets in the process environment or Home `.env`, and reference them with `$env{...}`. Logs and error text replace secrets the runtime knows. Traces can contain system prompts, conversation history, and tool results. Review this data before sharing a local trace or enabling remote export. [Trace handling](../development/2.10-observability.md#trace)9Put secrets in the process environment or Home `.env`, and reference them with `$env{...}`. Logs and error text replace secrets the runtime knows. Traces can contain system prompts, conversation history, and tool results. Review this data before sharing a local trace or enabling remote export. [Trace handling](../development/2.10-observability.md#trace)
10 10 
11-Keep secrets out of user messages. See the [AG-UI request contract](../reference/3.3-ag-ui-events.md#request) for the accepted client fields.11+Keep secrets out of user messages. See the [AG-UI request contract](../reference/3.2-rest-api.md#request) for the accepted client fields.
12 12 
13## Identity and files13## Identity and files
14 14 
Mdocs/en/reference/1.1-integration-overview.md+17-19File content is under review, please try again later
Mdocs/en/reference/1.2-python-sdk.md+93-42File content is under review, please try again later
Mdocs/en/reference/1.3-http-ag-ui.md+19-5File content is under review, please try again later
Mdocs/en/reference/1.4-a2a-integration.md+11-3File content is under review, please try again later
Mdocs/en/reference/2.1-extension-overview.md+2-2File content is under review, please try again later
@@ -12,6 +12,13 @@ This page is for plugin authors: declare resources, dependencies, and business p
12 12 
13A plugin is a directory with `.plugin.yaml` at its root. The directory name, manifest `id`, and ID in `plugins.enabled` must match. This minimal manifest registers one Python tool:13A plugin is a directory with `.plugin.yaml` at its root. The directory name, manifest `id`, and ID in `plugins.enabled` must match. This minimal manifest registers one Python tool:
14 14 
15+```text
16+common/
17+├── .plugin.yaml
18+└── tools/
19+ └── statistics.py
20+```
21+ 
15```yaml22```yaml
16schema_version: 323schema_version: 3
17id: common24id: common
@@ -28,9 +35,16 @@ tools:
28 35 
29## Load and verify during development36## Load and verify during development
30 37 
31-Follow [Use plugins](../data-analysis/2.2-install-plugins.md) to add your development directory as a candidate and enable its ID, then start Server or create an SDK Agent with the same product configuration. `plugins.paths` names the plugin's own directory; discovery alone does not enable it. Avoid two enabled sources with the same ID, such as a Home copy and a separate development directory.38+Merge this fragment into a product YAML with a configured model and replace the placeholder with the plugin directory. Keep one candidate directory per plugin ID. A Home copy and a source directory with the same ID conflict if both are candidates. See [Use plugins](../data-analysis/2.2-install-plugins.md) for loading rules.
32 39 
33-The model sees the sample tool as `common__summarize_numbers`. Test with the default root Agent and an empty `dataagent.entry`; compiled direct entries do not load root tools. See [entry mode](2.6-develop-subagents.md#entry-mode). Invoke it and verify the actual returned values, then inspect session outputs, [logs](../operations/3.2-logs.md), and [traces](../operations/3.3-trace-evaluation.md). See [Choose an extension](2.1-extension-overview.md) for resource combinations.40+```yaml
41+plugins:
42+ enabled: [common]
43+ paths:
44+ - /absolute/path/to/common
45+```
46+ 
47+Start the Server or create an SDK Agent with this configuration and leave `dataagent.entry` unset. Ask “Call `common__summarize_numbers` on 1, 2, and 3 and return its result.” Check the [execution trace](../operations/3.3-trace-evaluation.md) for the tool call and verify `count: 3` and `sum: 6` in the result. [Compiled entries](2.6-develop-subagents.md#entry-mode) do not assemble the root Agent's tools.
34 48 
35<a name="dependencies-and-parameters"></a>49<a name="dependencies-and-parameters"></a>
36 50 
@@ -48,7 +62,7 @@ defaults_file: config.yaml
48 62 
49`params` declares defaults for the plugin's own business parameters. A `defaults_file` contains only `plugins.config` and can supply defaults for the plugin and its declared dependencies. Users override those values in their selected product YAML. See the [merge reference](../operations/1.2-configuration-fields.md#configuration-merge) and [worked example](../getting-started/4.1-configuration.md#precedence).63`params` declares defaults for the plugin's own business parameters. A `defaults_file` contains only `plugins.config` and can supply defaults for the plugin and its declared dependencies. Users override those values in their selected product YAML. See the [merge reference](../operations/1.2-configuration-fields.md#configuration-merge) and [worked example](../getting-started/4.1-configuration.md#precedence).
50 64 
51-Tools and hooks obtain a copy of effective settings through `runtime.context.get_plugin_config("de-agent")` and access session outputs through `runtime.context.session.outputs`. Use host-managed `get_model(alias)` and `semantic_client` rather than rereading `.env` or recreating shared clients for the same configuration. See [Python API](3.1-python-api.md#agent-context) for types and ownership.65+Tools and hooks obtain a copy of effective settings through `runtime.context.get_plugin_config("de-agent")` and access session outputs through `runtime.context.session.outputs`. Use host-managed `get_model(alias)` and `semantic_client` rather than rereading `.env` or recreating shared clients for the same configuration. See [Python API](3.1.1-python-extension-api.md#agent-context) for types and ownership.
52 66 
53<a name="discovery-and-refresh"></a>67<a name="discovery-and-refresh"></a>
54 68 
@@ -56,4 +70,4 @@ Tools and hooks obtain a copy of effective settings through `runtime.context.get
56 70 
57Server checks local extension fingerprints when preparing the next turn and attempts refresh; in-flight turns keep their original graphs. After changing declarations or Python code, verify with a task that actually invokes the modified tool or hook. Correct a failed refresh before retrying.71Server checks local extension fingerprints when preparing the next turn and attempts refresh; in-flight turns keep their original graphs. After changing declarations or Python code, verify with a task that actually invokes the modified tool or hook. Correct a failed refresh before retrying.
58 72 
59-SDK callers rerun `prepare_runtime` and `create_agent`; custom long-lived hosts use the [dataagent.host API](3.1-python-api.md#host-api). Model, Home, listener, and `dataagent.entry` changes require restart rather than extension refresh. See [extension lifecycle](../development/2.7-extension-lifecycle.md) for fingerprints, caches, and publication boundaries.73+SDK callers rerun `prepare_runtime` and `create_agent`; custom long-lived hosts use the [dataagent.host API](3.1.4-python-host-api.md#host-api). Model, Home, listener, and `dataagent.entry` changes require restart rather than extension refresh. See [extension lifecycle](../development/2.7-extension-lifecycle.md) for fingerprints, caches, and publication boundaries.
Mdocs/en/reference/2.3-write-skills.md+1-1File content is under review, please try again later
Mdocs/en/reference/2.4-develop-tools.md+8-1File content is under review, please try again later
@@ -21,6 +21,8 @@ dataagent:
21 21 
22Placing a file in `hooks/` does not register it. See [hook declarations](../operations/1.5-extension-schema.md#agent-hooks) for grouped and flat forms. `params` is copied for every invocation.22Placing a file in `hooks/` does not register it. See [hook declarations](../operations/1.5-extension-schema.md#agent-hooks) for grouped and flat forms. `params` is copied for every invocation.
23 23 
24+To verify input validation, copy `check_input.py` into `hooks/` beside the product YAML. Merge only the `before_model` declaration and set `max_chars` to `16`. Start the service with this configuration. In two new sessions using the default root Agent, send `Hello` and `12345678901234567`. The first message should reach the model. The second should fail before the first model call. An HTTP / AG-UI client receives `RUN_ERROR` with a message containing `Input exceeds 16 characters`.
25+ 
24<a name="hook-signatures"></a>26<a name="hook-signatures"></a>
25 27 
26## Signatures28## Signatures
@@ -52,7 +54,7 @@ Plugin manifest hooks compile before product `dataagent.hooks`, in declaration o
52| `before_tool` | Before each tool invocation |54| `before_tool` | Before each tool invocation |
53| `after_tool` | After a normal return, including error ToolMessages, but not a raised exception |55| `after_tool` | After a normal return, including error ToolMessages, but not a raised exception |
54 56 
55-Exceptions propagate without retries or per-hook timeouts. REST's whole-turn `timeout_seconds` covers the stream.57+Hook exceptions propagate to the caller. The runtime applies no per-hook timeout or retry. For HTTP / AG-UI and inbound A2A, `server.run_timeout_seconds` limits each server execution, including hooks that run during it. Time spent waiting for a human answer does not count. A new execution window starts when the run resumes.
56 58 
57## Reject execution59## Reject execution
58 60 
@@ -4,14 +4,34 @@ The manifest's `subagents` list references YAML files. The model delegates to th
4 4 
5## Minimal declaration5## Minimal declaration
6 6 
7-```yaml7+```text
8-schema_version: 18+review-demo/
9-name: general-purpose9+├── .plugin.yaml
10-description: Handle focused research and file inspection.10+├── prompts/
11-system_prompt_file: prompts/general-purpose.md11+│ └── review-check.md
12+└── subagents/
13+ └── review-check.yaml
12```14```
13 15 
14-Supply the description inline or in a file and use a plugin-relative `system_prompt_file`. See [subagent declarations](../operations/1.5-extension-schema.md#subagent-declaration).16+`.plugin.yaml`
17+ 
18+```yaml
19+schema_version: 3
20+id: review-demo
21+subagents:
22+- subagents/review-check.yaml
23+```
24+ 
25+`subagents/review-check.yaml`
26+ 
27+```yaml
28+schema_version: 1
29+name: review-check
30+description: Verify subagent delegation by returning a fixed marker.
31+system_prompt_file: prompts/review-check.md
32+```
33+ 
34+Put `Reply with REVIEW_OK and no other text.` in `prompts/review-check.md`. [Enable the `review-demo` plugin](2.2-write-plugins.md#load-and-verify) and use the default root Agent. Ask “Use `task` to delegate to `review-check` and return its result.” In the [execution trace](../operations/3.3-trace-evaluation.md), check that the `task` call targeted `review-check` and returned `REVIEW_OK`. The [AG-UI subagent events](3.3-ag-ui-events.md#stream-scope) also show when the subagent starts and finishes. You can also supply the description from a file. See [subagent declarations](../operations/1.5-extension-schema.md#subagent-declaration) for name and path rules.
15 35 
16## Inheritance36## Inheritance
17 37 
Mdocs/en/reference/2.7-human-interaction.md+10-7File content is under review, please try again later
@@ -1,6 +1,6 @@
1# Human feedback in de-agent1# Human feedback in de-agent
2 2 
3-Use de-agent's human feedback to clarify business definitions, review them before SQL generation, and confirm a delivery. This is a scenario example of [human interaction and recovery](2.7-human-interaction.md), covering built-in policies and their business configuration. Start with the general guide when implementing interaction for another plugin.3+If an analysis task is missing a key definition such as the deduplication key, de-agent can pause for clarification. When pre-SQL review is enabled and its conditions are met, de-agent presents the extracted business definitions for review. The plugin can also request final confirmation before delivery. This page demonstrates those behaviors in a SQL task. See [human interaction and recovery](2.7-human-interaction.md) for the shared handler and recovery flow.
4 4 
5<a name="enable-de-agent-hitl"></a>5<a name="enable-de-agent-hitl"></a>
6 6 
@@ -23,9 +23,9 @@ Both IR switches default to `false`. The plugin's [manifest](../../../dataagent/
23 23 
24<a name="completion-guards"></a>24<a name="completion-guards"></a>
25 25 
26-## Completion guards26+## Checks before completion
27 27 
28-Both completion policies run at `after_model`. They skip a model response containing valid or invalid tool calls.28+A guard is a policy that decides whether to pause and ask a question. Both completion checks run in `after_model` and skip responses containing valid or invalid tool calls.
29 29 
30| Policy | When it asks | Manifest parameter |30| Policy | When it asks | Manifest parameter |
31| --- | --- | --- |31| --- | --- | --- |
@@ -39,7 +39,7 @@ Registering the policy enables the guard. Remove its entry to disable it, or set
39## IR clarification and review39## IR clarification and review
40 40 
41- **`ir_question_guard`.** When DataTaskIR is enabled, it checks unresolved blocking fields that have a question. The default `after_model` policy checks plans that delegate to `nl2sql` or call a configured SQL consumer, and it also checks a text-only completion. It pauses the plan before those tools run. A custom host using serial tool calls can run this guard at `before_tool` instead.41- **`ir_question_guard`.** When DataTaskIR is enabled, it checks unresolved blocking fields that have a question. The default `after_model` policy checks plans that delegate to `nl2sql` or call a configured SQL consumer, and it also checks a text-only completion. It pauses the plan before those tools run. A custom host using serial tool calls can run this guard at `before_tool` instead.
42-- **`ir_caliber_review`.** With both IR switches enabled, it presents a review of the extracted business definitions once per IR task before `task(subagent_type="nl2sql")` or `de-agent__check_and_repair_sql`. It waits until the extracted fields have no unresolved items. The answer becomes feedback for replanning.42+- **`ir_caliber_review`.** With both IR switches enabled, it presents a review of the extracted business definitions once per IR task before `task(subagent_type="nl2sql")` or `de-agent__check_and_repair_sql`. It asks after blocking clarification is complete. When the clarification limit is reached or the task enters best-effort mode, it reviews confirmed definitions and explains the remaining gaps. The answer is recorded as task IR feedback, used for replanning, and considered at the next extraction.
43 43 
44The IR question guard stores the raw answer in task-scoped `ir_clarification`. The extractor can then reassess the field. If a field remains unresolved after a reply, the task proceeds using confirmed fields and reports the gaps in the delivery. A new IR task resets the asking state.44The IR question guard stores the raw answer in task-scoped `ir_clarification`. The extractor can then reassess the field. If a field remains unresolved after a reply, the task proceeds using confirmed fields and reports the gaps in the delivery. A new IR task resets the asking state.
45 45 
@@ -69,7 +69,7 @@ Use the final confirmation policy's `conditions` for a checklist. Put model-faci
69## Verify the scenario69## Verify the scenario
70 70 
711. Start a new session with the de-agent configuration. Ask for a SQL delivery where the source metadata permits both `user_id` and `device_id` and your request leaves the deduplication key unspecified.711. Start a new session with the de-agent configuration. Ask for a SQL delivery where the source metadata permits both `user_id` and `device_id` and your request leaves the deduplication key unspecified.
72-2. When the session pauses, answer with the intended key and the source table if requested. Confirm the task continues in the same session. When review is enabled and the IR fields are resolved, check that the review before SQL generation appears once for this task.72+2. When the session pauses, answer with the intended key and the source table if requested. Confirm the task continues in the same session. When review is enabled, check that it appears once before SQL generation after blocking clarification completes or the task enters best-effort mode.
733. Check the generated SQL and delivery notes for the selected key and any remaining gaps. Answer the final confirmation if enabled. Also verify what happens when a clarification leaves a field unresolved.733. Check the generated SQL and delivery notes for the selected key and any remaining gaps. Answer the final confirmation if enabled. Also verify what happens when a clarification leaves a field unresolved.
74 74 
75The [completion guard](../../../tests/test_de_agent_completion_guards.py), [IR question guard](../../../tests/test_de_agent_ir_question_guard.py), and [IR caliber review](../../../tests/test_de_agent_delivery_guards.py) tests use local fixtures. You can run them together from the repository root.75The [completion guard](../../../tests/test_de_agent_completion_guards.py), [IR question guard](../../../tests/test_de_agent_ir_question_guard.py), and [IR caliber review](../../../tests/test_de_agent_delivery_guards.py) tests use local fixtures. You can run them together from the repository root.
Mdocs/en/reference/3.1-python-api.md+25-334File content is under review, please try again later
@@ -0,0 +1,109 @@
1+# Python extension APIs
2+ 
3+<a name="extension-api"></a>
4+ 
5+Extensions use the runtime context for plugin settings, models, and clients. See the [tool guide](2.4-develop-tools.md) for a minimal implementation.
6+ 
7+<a name="agent-context"></a>
8+ 
9+## Tool runtime context (`AgentContext`)
10+ 
11+Access through `runtime.context`.
12+ 
13+| Member | Meaning |
14+| --- | --- |
15+| `get_model(name=None)` | Configured model, default `dataagent.model`; unknown aliases raise `ValueError` |
16+| `semantic_client` | Configured client or `None` |
17+| `session.outputs` | Current session output directory |
18+| `home` | Resolved Home for shared resources |
19+| `get_plugin_config(plugin_id)` | Copy of effective plugin config. Disabled plugins raise `ValueError` |
20+| `get_plugin_state(plugin_id)` | Private in-memory dictionary for an enabled plugin within the session graph. Not checkpointed; plugin owns concurrency |
21+ 
22+<a name="extension-models-and-services"></a>
23+ 
24+## Model streams and compiled subagent factories
25+ 
26+| Name | Purpose |
27+| --- | --- |
28+| `collect_model_stream(model, messages, **kwargs)` | Stream and collect a complete model message, retaining tool calls, reasoning, and usage |
29+| `SubagentServices` | Compiled factory services `get_model`, `semantic_client`, `outputs_dir`, and `run_hooks` |
30+ 
31+<a name="semantic-client"></a>
32+ 
33+## SemanticLayer client
34+ 
35+Import `SemanticServiceClient` from `dataagent`. It is a standalone synchronous HTTP client, separate from the host and low-level graph APIs. For connection setup, certificates, and natural-language verification, see [SemanticLayer integration](../data-analysis/1.3-semantic-service.md).
atomgit-bot
atomgit-botatomgit-bot5 days ago

🟡 Medium Priority

新增的 3.1.1–3.1.4 页把原来 3.1-python-api.md 里的锚点整体搬走了:semantic-client(3.1.1 第 31 行)、hitl-api(3.1.2 第 3 行)、host-api(3.1.4 第 5 行)。

证据:对 docs/en/reference 目录检索 <a name="…">,3.1-python-api.md 只剩 <a name="agent">(第 25 行),semantic-client / hitl-api / host-api 在该文件中已不存在。但本 PR 未同步更新的英文页面仍在指向旧锚点:

触发条件与失败表现:读者点击这些链接会落到新 3.1-python-api.md 页首而不是目标小节(锚点不存在,不会跳转);若构建启用了锚点级链接校验(本 PR 声称做了本地链接检查),严格构建会报出这些断链。相比之下 3.4-a2a-reference.md 第 212 行已同步把 3.1-python-api.md#a2a-api 改成 3.1.3-python-a2a-client.md#a2a-api,说明拆分是单向完成、引用方只改了一处,其余仍是旧锚点,属于本次拆分引入的新旧不一致。

修复方向:把上述未改动文件中的链接分别指向 ../reference/3.1.1-python-extension-api.md#semantic-client、../reference/3.1.2-python-hitl-api.md#hitl-api、../reference/3.1.4-python-host-api.md#host-api;或者在新 3.1-python-api.md 保留同名占位锚点以兼容旧链接。

建议:把仍指向 3.1-python-api.md 旧锚点的英文页面链接改到新的 3.1.1/3.1.2/3.1.4 页面对应锚点(或在新 3.1-python-api.md 保留 semantic-client/hitl-api/host-api 兼容锚点),并做一次全仓 3.1-python-api.md# 引用核对。

likedislike
Incorrect?
36+ 
37+<a name="construction-and-ownership"></a>
38+ 
39+### Construction and ownership
40+ 
41+| Usage | Creation and cleanup |
42+| --- | --- |
43+| REST Server | Creates one shared client from `semantic` for the process lifespan, injects it into each Agent's `AgentContext`, and owns cleanup |
44+| `create_agent(runtime)` | The SDK creates a client when `semantic` is configured and no `semantic_client` is supplied; `Agent.close()` / `aclose()` closes it |
45+| `create_agent(runtime, semantic_client=client)` | Borrows the caller's client; closing the Agent leaves it open. The caller owns cleanup |
46+| `runtime.context.semantic_client` in a tool | Borrows the host client, or is `None` when unconfigured. The tool does not create or close it |
47+| `SemanticServiceClient.from_settings(runtime.settings.semantic)` or direct construction | The caller owns `close()`, or uses a `with` block |
48+ 
49+`from_settings` accepts resolved `SemanticSettings` and uses its URL, Basic authentication, timeout, TLS, and scenario settings. Direct `SemanticServiceClient(base_url, ...)` construction enables server certificate verification by default (`verify=True`); `from_settings` follows the configured `tls` policy.
50+ 
51+Configuration `tls.verify_server` defaults to `false`. Without a client certificate or `ciphers`, verification stays disabled. When `true`, the default SSL context is used, or the CA from `ca_file` when supplied. Provide `client_cert` and `client_key` together. Nonempty `ciphers` is passed to `SSLContext.set_ciphers`. See [semantic configuration](../operations/1.2-configuration-fields.md#semantic) for field constraints.
52+ 
53+The client uses synchronous `httpx.Client`. Offload async tool calls with `asyncio.to_thread` to avoid blocking the event loop. The owning client's `close()` rejects new requests and waits for synchronous requests in flight before closing its pool. Diagnostics redact Basic credentials and their Base64 representation; logs should not print raw secrets.
54+ 
55+<a name="methods-and-routes"></a>
56+ 
57+### Methods and routes
58+ 
59+Paths use the `/api/semantic/v1/` prefix. Retrieval-table endpoints inspect the semantic service's own metadata tables; business-table endpoints inspect tables and columns in connected business databases.
60+ 
61+| Method | HTTP method and route suffix |
62+| --- | --- |
63+| `semantic_retrieve` | `POST semantic/retrieve` |
64+| `get_table_list` | `GET advanced-search/table-list` |
65+| `get_table_columns_info` | `GET advanced-search/table-columns-info` |
66+| `get_columns_sample_values` | `GET advanced-search/column-value-info` |
67+| `semantic_search_columns` | `GET advanced-search/semantic-search-columns` |
68+| `get_joinable_tables` | `GET advanced-search/joinable-tables` |
69+| `get_table_relations_path` | `GET advanced-search/table-relations-path` |
70+| `vector_search_table_desc` | `GET advanced-search/vector-search-table-desc` |
71+| `vector_search_column_value` | `GET advanced-search/vector-search-column-value` |
72+| `sql_few_shots` | `GET advanced-search/sql-few-shots` |
73+| `search_fulltext` | `GET search/fulltext` |
74+| `search_basic` | `POST search/basic`, with search criteria |
75+| `search_dsl` | `GET search/dsl` |
76+| `search_entities(type_name, *, limit=200, offset=0)` | `GET search/basic`, paginated enumeration by type |
77+| `get_entity_by_guid` | `GET entity/guid/{guid}` |
78+| `get_entity_by_unique_attribute` | `GET entity/uniqueAttribute/type/{type_name}` |
79+| `list_retrieval_tables` | `GET retrieval/tables`, the semantic retrieval-table list |
80+| `get_retrieval_table_schema` | `GET retrieval/tables/{table}/schema`, a retrieval-table schema |
81+| `hybrid_table_columns(tables)` | `POST hybrid/table-columns`, physical columns for business tables in bulk |
82+ 
83+<a name="parameter-conventions"></a>
84+ 
85+### Parameter conventions
86+ 
87+Positional arguments go from broad to narrow, such as database, table, and keywords or query. Counts use keyword `limit`, sent as `topK` or `limit` according to the endpoint. `max_depth` and `sample_count` are also keyword-only.
88+ 
89+Column identifiers use `db.table.column`. In `get_columns_sample_values(column_ids, *, sample_count=3)`, `sample_count` ranges from 0 to 100. `search_entities` requires `limit` from 1 to 200 and a nonnegative `offset`, and returns a list of entities.
90+ 
91+`semantic_retrieve(query, *, db_name=None, evidence=None)` accepts natural-language input. Supplying the optional arguments adds `db_name` and `evidence` to the request body; omitting them retains the service's default retrieval workflow. POST criteria through `search_basic` and GET enumeration through `search_entities` are distinct operations.
92+ 
93+<a name="scenario-views"></a>
94+ 
95+### Scenario views
96+ 
97+Configured `semantic_scenario`, or `scenario=` during direct construction, sets `X-Semantic-Scenario` on requests except health. `with_scenario(scenario)` returns a client view sharing the same connection pool with a different header value.
98+ 
99+Closing a view does not close the pool. The original owning client still owns cleanup and waits for requests made through its views. Reuse the existing client without creating a connection for each scenario.
100+ 
101+<a name="sql-apis"></a>
102+ 
103+## Data access and SQL validation
104+ 
105+| Name | Purpose |
106+| --- | --- |
107+| `MCPConfig`, `MCPInfrastructureError` | SQL-over-MCP connection type and infrastructure error. See [MCP SQL](../data-analysis/1.2-mcp.md#nl2sql-mcp) |
108+| `build_sql_service`, `check_engine_driver`, `check_read_only_sql`, `check_sql` | Data gateway services and validation |
109+| `recall_database`, `RecallOptions`, `RecallError` | Async SQLite exploration and its options and errors |
Adocs/en/reference/3.1.2-python-hitl-api.md+99-0File content is under review, please try again later
Adocs/en/reference/3.1.3-python-a2a-client.md+13-0File content is under review, please try again later
Adocs/en/reference/3.1.4-python-host-api.md+116-0File content is under review, please try again later
@@ -1,12 +1,14 @@
1# REST API reference1# REST API reference
2 2 
3-Call the control plane started by `dataagent serve`. The default base URL is `http://127.0.0.1:8790`, configured by `server.host` and `server.port` in the selected YAML. The Web workbench proxies `/api/v1/*` to this service. REST has no built-in access-token check. See the [security notes](../getting-started/2.4-security.md) before exposing the control plane beyond loopback.3+Call the control plane started by `dataagent serve`. The default base URL is `http://127.0.0.1:8790`, configured by `server.host` and `server.port` in the selected YAML. REST has no built-in access-token check. See the [security notes](../getting-started/2.4-security.md) before exposing the control plane beyond loopback.
4+ 
5+This reference covers the routes, requests, responses, and events used by integrations. See the [HTTP integration guide](1.3-http-ag-ui.md) to run your first conversation.
4 6 
5<a name="envelope"></a>7<a name="envelope"></a>
6 8 
7-## Envelope9+## Response structure
8 10 
9-JSON success responses and handled HTTP errors use these envelopes:11+JSON success responses and handled HTTP errors use the following structures:
10 12 
11```json13```json
12{"success": true, "data": {}}14{"success": true, "data": {}}
@@ -16,39 +18,20 @@ JSON success responses and handled HTTP errors use these envelopes:
16{"success": false, "error": {"code": "RESOURCE_NOT_FOUND", "message": "Route not found."}}18{"success": false, "error": {"code": "RESOURCE_NOT_FOUND", "message": "Route not found."}}
17```19```
18 20 
19-A successful `POST /api/v1/runs` returns an SSE stream with HTTP 200. A successful cancel request returns HTTP 204 with an empty body. `HEAD` on the health endpoints returns only the status and headers. The response examples below show the contents of `data`.21+A successful `POST /api/v1/runs` returns an SSE stream with HTTP 200. A successful cancel request returns HTTP 204 with an empty body. `HEAD` on the health endpoints returns only the status and headers. Examples marked as full responses include the wrapper. Other JSON examples show the contents of `data`.
22+ 
23+After starting the control plane, run `curl -i http://127.0.0.1:8790/ready`. A ready service returns HTTP 200 with `success: true` and `data.status: "ready"`. Use `curl -I` if you only need the status and headers.
20 24 
21<a name="health-and-identity"></a>25<a name="health-and-identity"></a>
22 26 
23-## Health and identity27+## Health checks
24 28 
25| Method | Path | Response |29| Method | Path | Response |
26| --- | --- | --- |30| --- | --- | --- |
27-| GET, HEAD | `/healthz` | 200 with `status: "ok"` and `conversation`. |31+| GET, HEAD | `/healthz` | HTTP 200 indicates that the process is reachable. |
28-| GET, HEAD | `/ready` | 200 with `status: "ready"` and the same `conversation` fields as `/healthz`. Returns 503 when the engine is unavailable. |32+| GET, HEAD | `/ready` | HTTP 200 indicates readiness. Returns 503 when the engine is unavailable. |
29-| GET | `/api/v1/me` | `user.id` and `user.displayName` are the server's local user (`--user`). Both default to `default` if no runtime is configured. `workspace` is always `{"id":"local","name":"Local"}`. |
30-| GET | `/api/v1/capabilities` | `interaction.resume`, `conversation.memory`, and `artifact.list` are true. `artifact.export` is false. |
31 33 
32-When the engine is unavailable, the `conversation` object on `/healthz` contains only `{"ready": false}`. A ready control plane returns a shape like this:34+A ready `GET /ready` response contains `success: true`, `data.status: "ready"`, and `data.conversation.ready: true`.
33- 
34-```json
35-{
36- "status": "ok",
37- "conversation": {
38- "ready": true,
39- "protocol": "dataagent",
40- "instanceId": "server-1",
41- "model": "example-model",
42- "plugins": ["common"],
43- "home": "/absolute/path/to/.dataagent",
44- "entry": null,
45- "user": "default",
46- "timeoutSeconds": 900
47- }
48-}
49-```
50- 
51-Use `conversation.ready` for readiness. `instanceId` identifies the process, and `timeoutSeconds` reflects `server.run_timeout_seconds`. `entry` reports the configured value without checking whether it resolves to a compiled subagent. The response omits input directories, the state directory, and configuration contents.
52 35 
53<a name="sessions-and-runs"></a>36<a name="sessions-and-runs"></a>
54 37 
@@ -81,7 +64,7 @@ Statuses are `running`, `waiting_for_input`, `completed`, `error`, and `interrup
81 64 
82### Read a session65### Read a session
83 66 
84-`GET /api/v1/sessions/{threadId}` adds `messages`, `pendingInteractions`, and `notice` to the list item fields. The messages come from the saved checkpoint or, if absent, the latest graph state on that thread. The route remains available while a run is active. `pendingInteractions` contains prompts that can be answered over REST. See [human feedback](3.3-ag-ui-events.md#hitl) for their shape and how to answer. `notice` is text or `null`. On an error or interruption, it indicates whether a checkpoint was restored.67+`GET /api/v1/sessions/{threadId}` adds `messages`, `pendingInteractions`, and `notice` to the list item fields. The messages come from the saved checkpoint or, if absent, the latest graph state on that thread. The route remains available while a run is active. `pendingInteractions` contains prompts that can be answered over REST. See [human feedback](#hitl) for their shape and how to answer. `notice` is text or `null`. On an error or interruption, it indicates whether a checkpoint was restored.
85 68 
86An unknown session or a session belonging to another user returns 404. If the current user's session binding cannot be opened, the route returns 409.69An unknown session or a session belonging to another user returns 404. If the current user's session binding cannot be opened, the route returns 409.
87 70 
@@ -93,11 +76,96 @@ Send `POST /api/v1/runs/{runId}/cancel` with the active REST run's `runId`. No r
93 76 
94<a name="conversation"></a>77<a name="conversation"></a>
95 78 
96-## Conversation79+## Conversation and AG-UI events
97 80 
98-`POST /api/v1/runs` accepts one AG-UI request. See the [request format](3.3-ag-ui-events.md#request) and [integration example](1.3-http-ag-ui.md). The successful response is `text/event-stream` with `Cache-Control: no-cache` and `X-Accel-Buffering: no`.81+Send `POST /api/v1/runs` to start a turn. Before the stream opens, validation failures return 422 and conflicts with an active run or run ID return 409. See the [HTTP integration guide](1.3-http-ag-ui.md) for the runnable sequence.
99 82 
100-Before the stream starts, invalid bodies return 422. Conflicts, including an active run on the same session or an already-active `runId`, return 409. Once the server starts a 200 stream, run failures are reported as [terminal events](3.3-ag-ui-events.md#terminal-events). If the client disconnects, the server cancels the upstream stream and marks the unfinished session as interrupted.83+<a name="request"></a>
84+ 
85+### Request fields
86+ 
87+Send JSON. A normal turn contains one new message. The server loads history for `threadId`.
88+ 
89+| Field | Constraint |
90+| --- | --- |
91+| `threadId`, `runId` | 1–128 characters, starting with an ASCII letter or digit. Later characters may include `_` and `-` |
92+| `messages` | Exactly one message with `id`, `role: "user"`, and nonblank text `content` for a normal turn. Use `[]` when answering a human feedback prompt |
93+| `state` | Omit or send `null` or `{}` |
94+| `tools`, `context`, `forwardedProps` | Required. Send `[]`, `[]`, and `{}`, respectively |
95+| `answers` | A nonempty map from `interruptId` to answer text when [resuming human feedback](#hitl) |
96+| `resume`, `parentRunId` | Omit. Use the same thread to continue or `answers` to resume an interrupt |
97+ 
98+Unknown top-level fields and client-supplied state, tools, or context are rejected. Subagent messages cannot be submitted as user messages. The Server selects the model, plugins, and workspaces.
99+ 
100+Only one turn may be active per session. Active run IDs are process-wide, including across threads. The last run ID on a session and message IDs from loaded history cannot be reused to edit or replay. Use new run and message IDs.
101+ 
102+<a id="sse-response"></a>
103+ 
104+<a name="terminal-events"></a>
105+ 
106+### Read SSE events
107+ 
108+An accepted run returns HTTP 200 and `text/event-stream` with `Cache-Control: no-cache` and `X-Accel-Buffering: no`. Read JSON from SSE `data:` frames.
109+ 
110+<a id="completed"></a>
111+ 
112+`RUN_STARTED` identifies the turn. Use text and tool events to show progress. A successful run sends the `CUSTOM` event that clears pending prompts, the final `MESSAGES_SNAPSHOT`, and `RUN_FINISHED` in that order. The terminal event can include `metadata.durationMs`.
113+ 
114+| Event or outcome | Client action |
115+| --- | --- |
116+| `RUN_FINISHED` with `metadata.status="completed"` | Update the conversation with the final `MESSAGES_SNAPSHOT`. |
117+| `RUN_FINISHED` with `metadata.status="waiting_for_input"` | Show pending prompts and submit the answer on the same session. |
118+| `RUN_ERROR` with `code="CANCELLED"` | Show the run as stopped. The next turn can reuse the same `threadId`. |
119+| Other `RUN_ERROR` | Keep visible partial output and handle the `code`. Use a new `runId` for the next turn. |
120+| The stream closes without a terminal event | Reload [session details](#session-detail) before deciding whether to submit another turn. |
121+ 
122+<a name="hitl"></a>
123+ 
124+### Wait for human feedback
125+ 
126+A pause ends the stream with `RUN_FINISHED` and `metadata.status="waiting_for_input"`. A `CUSTOM name="human_feedback"` event before the final snapshot carries the complete list of pending interactions:
127+ 
128+```json
129+{"type":"CUSTOM","name":"human_feedback","value":[
130+ {"type":"human_feedback","interruptId":"<id>","message":"Choose an identity field.","options":["user_id","device_id"]}
131+]}
132+```
133+ 
134+`options` are suggestions. Users can also type an answer. Invalid answers may carry `validationError`. Replace the client list with each event's array. Submit a nonempty `answers` map to the same endpoint with the same thread, a fresh run ID, and empty `messages`.
135+ 
136+```json
137+{
138+ "threadId": "thread-001",
139+ "runId": "run-002",
140+ "messages": [],
141+ "answers": {"<id>": "user_id"},
142+ "tools": [],
143+ "context": [],
144+ "forwardedProps": {}
145+}
146+```
147+ 
148+Replace `<id>` with the received `interruptId`. Parallel interactions can be answered in batches. Sending a new user message while waiting or using an unknown or resolved ID returns 409. Blank answers pause again with `validationError`.
149+ 
150+Reload pending items from `GET /api/v1/sessions/{threadId}` and its `pendingInteractions` after refresh or restart. No HTTP stream runs while the user decides, so this wait does not count against turn timeout. Interactions started by [A2A](3.4-a2a-reference.md#a2a-hitl) must resume via A2A.
151+ 
152+<a name="errors"></a>
153+ 
154+### SSE error codes
155+ 
156+`RUN_ERROR.code` uses these values. The human-readable `message` is redacted and limited to 1,500 characters. Integrations should branch on the code. Server logs also include the exception class as `error=`.
157+ 
158+| Code | Meaning |
159+| --- | --- |
160+| `TIMEOUT` | Turn limit `server.run_timeout_seconds` or model request timeout |
161+| `CANCELLED` | Explicit `POST /api/v1/runs/{runId}/cancel` |
162+| `LOOP_DETECTED` | Loop detection stopped the turn |
163+| `LIMIT_EXCEEDED` | `model_calls_per_agent` or `tool_calls_per_agent` exceeded |
164+| `INCOMPLETE_STREAM` | Missing or duplicate terminal event, or output after termination |
165+| `CONFIG_ERROR` | Invalid configuration |
166+| `MODEL_ERROR` | Error from the model service |
167+| `TOOL_ERROR` | Tool or remote agent failed |
168+| `INTERNAL_ERROR` | Other failure |
101 169 
102<a name="outputs"></a>170<a name="outputs"></a>
103 171 
@@ -109,8 +177,13 @@ Before the stream starts, invalid bodies return 422. Conflicts, including an act
109 177 
110`GET /api/v1/sessions/{threadId}/outputs` returns regular files sorted by descending `modifiedAt`, then descending `path`. Paths are relative to the session's output directory, and sizes are in bytes.178`GET /api/v1/sessions/{threadId}/outputs` returns regular files sorted by descending `modifiedAt`, then descending `path`. Paths are relative to the session's output directory, and sizes are in bytes.
111 179 
180+Full response example
181+ 
112```json182```json
113-{"files": [{"path": "notes.txt", "size": 12, "modifiedAt": "2026-10-15T00:00:00+00:00"}]}183+{
184+ "success": true,
185+ "data": {"files": [{"path": "notes.txt", "size": 12, "modifiedAt": "2026-10-15T00:00:00+00:00"}]}
186+}
114```187```
115 188 
116The list excludes symbolic links and the internal paths `artifacts/conversation_history` and `artifacts/large_tool_results`. An existing session with no output directory returns an empty list. An output directory that is a symbolic link or a path that is not a directory returns 409. A session that does not exist or belongs to another user returns 404.189The list excludes symbolic links and the internal paths `artifacts/conversation_history` and `artifacts/large_tool_results`. An existing session with no output directory returns an empty list. An output directory that is a symbolic link or a path that is not a directory returns 409. A session that does not exist or belongs to another user returns 404.
@@ -119,10 +192,15 @@ The list excludes symbolic links and the internal paths `artifacts/conversation_
119 192 
120### Preview UTF-8 text193### Preview UTF-8 text
121 194 
122-`GET /api/v1/sessions/{threadId}/outputs/preview?path=notes.txt` takes a non-empty, URL-encoded relative path and returns:195+`GET /api/v1/sessions/{threadId}/outputs/preview?path=notes.txt` takes a non-empty, URL-encoded relative path.
196+ 
197+Full response example
123 198 
124```json199```json
125-{"type": "file", "path": "notes.txt", "content": "Sample notes", "truncated": false}200+{
201+ "success": true,
202+ "data": {"type": "file", "path": "notes.txt", "content": "Sample notes", "truncated": false}
203+}
126```204```
127 205 
128The read limit is 64 KiB. A longer file has `truncated: true` and the returned content ends on a complete UTF-8 character. An absolute path, a `..` component, or a NUL character returns 400. Missing, linked, excluded, or non-regular files return 404. Binary or invalid UTF-8 content in the preview returns 415.206The read limit is 64 KiB. A longer file has `truncated: true` and the returned content ends on a complete UTF-8 character. An absolute path, a `..` component, or a NUL character returns 400. Missing, linked, excluded, or non-regular files return 404. Binary or invalid UTF-8 content in the preview returns 415.
Mdocs/en/reference/3.3-ag-ui-events.md+3-120File content is under review, please try again later
Mdocs/en/reference/3.4-a2a-reference.md+28-26File content is under review, please try again later
Mdocs/zh/getting-started/2.2-capabilities.md+3-3File content is under review, please try again later
Mdocs/zh/getting-started/2.4-security.md+1-1File content is under review, please try again later
@@ -8,28 +8,32 @@
8 8 
9把 DataAgent 接入已有应用:在同一 Python 进程内调用,或通过 HTTP / AG-UI、A2A 与独立服务交互。先选择调用方式,再查对应的请求、会话和结果契约。9把 DataAgent 接入已有应用:在同一 Python 进程内调用,或通过 HTTP / AG-UI、A2A 与独立服务交互。先选择调用方式,再查对应的请求、会话和结果契约。
10 10 
11-<a name="服务接入"></a>
12- 
13-<a name="configuration"></a>
14- 
15-## 准备被调用的 Agent
16- 
17-先完成[配置模型并验证首次调用](../getting-started/4.1-configuration.md)并确认模型可用。使用已有 Skill 和插件时,分别按[Skill 安装与使用](../data-analysis/2.1-install-skills.md)和[插件安装、启用与配置](../data-analysis/2.2-install-plugins.md)加载;只有任务确实依赖外部工具或语义元数据时,才需要[配置模型并验证首次调用 · 按需添加已有能力](../getting-started/4.1-configuration.md#optional-services)。通过网络调用时,先启动对应 Server 并确认 `/ready` 返回 200。
18- 
19<a name="_2"></a>11<a name="_2"></a>
20 12 
21<a name="choose-an-interface"></a>13<a name="choose-an-interface"></a>
22 14 
23## 选择调用方式15## 选择调用方式
24 16 
25-| 应用需要做什么 | 调用方式 | 操作指南 |17+| 应用需要做什么 | 操作指南 | API 与协议参考 |
26| --- | --- | --- |18| --- | --- | --- |
27-| 在自己的 Python 进程里运行,指定输入和产物目录 | `prepare_runtime`、`create_agent`,由调用方管理持久化与资源 | [用 Python SDK 调用 Agent](1.2-python-sdk.md) |19+| 在自己的 Python 进程中运行 Agent | [用 Python SDK 调用 Agent](1.2-python-sdk.md) | [Python SDK 接口](3.1-python-api.md) |
28-| 从其他进程发送对话,消费文本、工具和人工交互事件 | HTTP `POST /api/v1/runs` 与 AG-UI SSE | [用 HTTP 发起对话并接收 AG-UI 事件](1.3-http-ag-ui.md) |20+| 从其他进程发送消息并接收实时事件 | [用 HTTP 发起对话并接收 AG-UI 事件](1.3-http-ag-ui.md) | [REST API 参考](3.2-rest-api.md) |
29-| 让其他 Agent 发现并调用 DataAgent,提交、查询和取消 Task | Agent Card 与 A2A JSON-RPC | [用 A2A 连接 Agent 并管理任务](1.4-a2a-integration.md) |21+| 让其他 Agent 发现 DataAgent 并管理任务 | [用 A2A 连接 Agent 并管理任务](1.4-a2a-integration.md) | [A2A 消息和任务契约](3.4-a2a-reference.md) |
30 22 
31SDK 不要求另起 Server;两种网络入口由服务端持有配置与会话。不要把客户端配置当作修改已启动 Server 的配置接口。23SDK 不要求另起 Server;两种网络入口由服务端持有配置与会话。不要把客户端配置当作修改已启动 Server 的配置接口。
32 24 
25+<a name="服务接入"></a>
26+ 
27+<a name="configuration"></a>
28+ 
29+## 准备被调用的 Agent
30+ 
31+先[配置模型并验证首次调用](../getting-started/4.1-configuration.md)。按任务需要加载[已有 Skill](../data-analysis/2.1-install-skills.md)、[已有插件](../data-analysis/2.2-install-plugins.md)或[可选服务](../getting-started/4.1-configuration.md#optional-services)。
32+ 
33+- **Python SDK** 在调用进程中创建 Agent。运行最小脚本并确认它打印回复。
34+- **HTTP / AG-UI** 启动 `dataagent serve`,确认 `GET /ready` 返回 200,再发送一次对话请求并检查终止事件。
35+- **A2A** `dataagent serve` 同时提供 A2A。也可以启动独立的 `dataagent serve-a2a`,该命令没有 `/ready` 路由。两种方式都先获取 Agent Card,再发送一条最小消息并确认任务完成。
36+ 
33<a name="conversation-and-results"></a>37<a name="conversation-and-results"></a>
34 38 
35## 续接会话与读取结果39## 续接会话与读取结果
@@ -42,13 +46,7 @@ SDK 用同一个 `thread_id` 与 checkpointer 续接对话;HTTP 按线程读
42 46 
43## 查询接口契约47## 查询接口契约
44 48 
45-| 要查询的内容 | 参考 |49+[REST API 参考](3.2-rest-api.md)统一说明 HTTP 路由、会话查询以及[对话请求和 AG-UI 事件](3.2-rest-api.md#conversation)。启动参数另见[配置字段速查](../operations/1.2-configuration-fields.md)与[命令和环境变量](../operations/1.1-cli-and-environment.md)。
46-| --- | --- |
47-| HTTP 路由、会话和产物读取、错误响应 | [REST API 参考](3.2-rest-api.md) |
48-| AG-UI 请求字段、事件及人工交互回答 | [AG-UI 事件与运行契约](3.3-ag-ui-events.md) |
49-| A2A 消息、Task、鉴权和恢复 | [A2A 参考](3.4-a2a-reference.md) |
50-| SDK 参数、资源所有权与并发规则 | [Python API 参考](3.1-python-api.md) |
51-| 选择配置、命令和环境变量 | [配置字段速查](../operations/1.2-configuration-fields.md)、[命令与环境变量](../operations/1.1-cli-and-environment.md) |
52 50 
53<a name="_3"></a>51<a name="_3"></a>
54 52 
Mdocs/zh/reference/1.2-python-sdk.md+92-41File content is under review, please try again later
@@ -6,6 +6,8 @@
6 6 
7向 DataAgent 发送一轮对话并读取 AG-UI 事件流。先按[完成第一次提问](../getting-started/1.1-quick-start.md)启动控制面,确认 `GET /ready` 返回 200。以下示例使用默认地址 `http://127.0.0.1:8790`。7向 DataAgent 发送一轮对话并读取 AG-UI 事件流。先按[完成第一次提问](../getting-started/1.1-quick-start.md)启动控制面,确认 `GET /ready` 返回 200。以下示例使用默认地址 `http://127.0.0.1:8790`。
8 8 
9+路由和状态码见 [REST API 参考](3.2-rest-api.md),对话字段、事件和恢复规则见其[对话章节](3.2-rest-api.md#conversation)。
10+ 
9## 请求11## 请求
10 12 
11向 `POST /api/v1/runs` 提交一条新消息。服务端按 `threadId` 加载对话历史。13向 `POST /api/v1/runs` 提交一条新消息。服务端按 `threadId` 加载对话历史。
@@ -27,7 +29,21 @@ curl --no-buffer --include \
27JSON29JSON
28```30```
29 31 
30-再次运行示例时,换用新的运行 ID 和消息 ID。完整字段约束见[AG-UI 事件与运行契约 · 请求](3.3-ag-ui-events.md#request)。32+再次运行示例时,换用新的运行 ID 和消息 ID。完整字段约束见[REST API 参考 · 请求字段](3.2-rest-api.md#request)。
33+ 
34+<a name="verify-response"></a>
35+ 
36+## 验证响应
37+ 
38+终端应显示 HTTP 200 和 `Content-Type: text/event-stream`。以下只展示开始和结束两帧,中间还有文本、消息快照等事件。
39+ 
40+```text
41+data: {"type":"RUN_STARTED","threadId":"thread-001","runId":"run-001"}
42+ 
43+data: {"type":"RUN_FINISHED","threadId":"thread-001","runId":"run-001","metadata":{"status":"completed","durationMs":650}}
44+```
45+ 
46+`completed` 表示本轮完成。从最后的 `MESSAGES_SNAPSHOT` 读取完整消息。`waiting_for_input` 表示正在等待人工回答,`RUN_ERROR` 表示本轮以错误或取消结束。
31 47 
32## 取消和恢复48## 取消和恢复
33 49 
@@ -37,10 +53,8 @@ JSON
37curl --include --request POST http://127.0.0.1:8790/api/v1/runs/run-001/cancel53curl --include --request POST http://127.0.0.1:8790/api/v1/runs/run-001/cancel
38```54```
39 55 
40-发送下一题时沿用 `threadId`,使用新的运行 ID、消息 ID 和消息内容。继续前如需加载历史,调用[REST API 参考 · 读取会话](3.2-rest-api.md#session-detail)。如果 DataAgent 暂停并等待用户输入,按[AG-UI 事件与运行契约 · 等待用户回答](3.3-ag-ui-events.md#hitl)提交回答。56+发送下一题时沿用 `threadId`,使用新的运行 ID、消息 ID 和消息内容。继续前如需加载历史,调用[REST API 参考 · 读取会话](3.2-rest-api.md#session-detail)。如果 DataAgent 暂停并等待用户输入,按[REST API 参考 · 等待用户回答](3.2-rest-api.md#hitl)提交回答。
41 57 
42## 事件58## 事件
43 59 
44-请求被接受后返回 HTTP 200 和 `Content-Type: text/event-stream`。逐条读取 SSE 的 `data:` 帧并解析其中的 JSON。`RUN_STARTED` 标识本轮运行。用文本和工具事件呈现实时进度,收到最终的 `MESSAGES_SNAPSHOT` 时更新消息。60+用文本和工具事件呈现实时进度。显式取消对应 `RUN_ERROR` 的 `CANCELLED` 错误码。各类结束事件的处理方式见[客户端应如何处理](3.2-rest-api.md#terminal-events)。流建立前的拒绝响应见 [REST API 参考 · HTTP 错误](3.2-rest-api.md#http-errors)。
45- 
46-查看 `RUN_FINISHED.metadata.status` 判断本轮已完成还是在等待用户输入。`RUN_ERROR` 携带结束错误码,显式停止对应 `CANCELLED`。各类结束事件的处理方式见[AG-UI 事件与运行契约 · 客户端应如何处理](3.3-ag-ui-events.md#terminal-events)。流建立前的拒绝响应见 [REST API 参考 · HTTP 错误](3.2-rest-api.md#http-errors)。
@@ -38,7 +38,15 @@ curl --include -sS http://127.0.0.1:8790/a2a/jsonrpc \
38 }'38 }'
39```39```
40 40 
41-从响应读取 `result.task.id` 用于查询,读取 `result.task.contextId` 用于续聊,并查看 `result.task.status.state`。下一条消息沿用会话 ID,并使用新的 `messageId`。省略 `returnImmediately` 时,发送请求会等待本轮结束或暂停,随后在发送响应中返回任务。41+响应的 `result.task` 包含三个用于验证和后续调用的字段。
42+ 
43+| 字段 | 用途 |
44+| --- | --- |
45+| `id` | 交给 `GetTask` 或 `CancelTask` |
46+| `contextId` | 填进下一条消息的 `message.contextId`,同时生成新的 `messageId` |
47+| `status.state` | 判断任务是排队、执行、等待回答还是已结束 |
48+ 
49+省略 `returnImmediately` 时,`SendMessage` 等待本轮结束或暂停。成功时,`result.task.status.state` 为 `TASK_STATE_COMPLETED`,可从 `result.task.artifacts` 读取 `dataagent_result`。
42 50 
43<a name="poll-and-cancel"></a>51<a name="poll-and-cancel"></a>
44 52 
@@ -53,7 +61,7 @@ curl --include -sS http://127.0.0.1:8790/a2a/jsonrpc \
53 -d '{"jsonrpc":"2.0","id":"poll-1","method":"GetTask","params":{"id":"TASK_ID"}}'61 -d '{"jsonrpc":"2.0","id":"poll-1","method":"GetTask","params":{"id":"TASK_ID"}}'
54```62```
55 63 
56-任务完成后,从 `result.artifacts` 读取 `dataagent_result` 文本产物。若任务等待人工输入,[A2A 参考 · 原生 HITL 暂停与恢复](3.4-a2a-reference.md#a2a-hitl)。需要停止任务时,将同一请求的 `method` 改为 `CancelTask`。断开 HTTP 连接或停止轮询后,任务会继续运行。64+`GetTask` 返回 `TASK_STATE_COMPLETED` 后,从 `result.artifacts` 中读取名为 `dataagent_result` 的文本产物。若状态为 `TASK_STATE_INPUT_REQUIRED`,按[原生 HITL 暂停与恢复](3.4-a2a-reference.md#a2a-hitl)提交回答。仍在等待或执行且需要停止时,将同一请求的 `method` 改为 `CancelTask`,再查询任务确认其状态。只停止轮询不会取消任务。
57 65 
58报错时保留响应头 `X-Request-ID`、任务 ID 和会话 ID。[A2A 参考 · 请求号与诊断](3.4-a2a-reference.md#request-diagnostics)可以区分请求被拒绝和任务执行失败。66报错时保留响应头 `X-Request-ID`、任务 ID 和会话 ID。[A2A 参考 · 请求号与诊断](3.4-a2a-reference.md#request-diagnostics)可以区分请求被拒绝和任务执行失败。
59 67 
@@ -77,7 +85,7 @@ a2a:
77 85 
78### 从 Python 直接调用86### 从 Python 直接调用
79 87 
80-复用同一个客户端,可以在原远端会话中继续提问。参数与异常见 [Python API 参考 · A2A](3.1-python-api.md#a2a-api)。88+复用同一个客户端,可以在原远端会话中继续提问。参数与异常见 [Python API 参考 · A2A](3.1.3-python-a2a-client.md#a2a-api)。
81 89 
82```python90```python
83import asyncio91import asyncio
@@ -19,7 +19,7 @@
19| 具有独立提示和工具范围的子任务,或已有执行图 | [开发子代理](2.6-develop-subagents.md) | 标准子代理 YAML,或 compiled 工厂与声明 |19| 具有独立提示和工具范围的子任务,或已有执行图 | [开发子代理](2.6-develop-subagents.md) | 标准子代理 YAML,或 compiled 工厂与声明 |
20| 暂停执行、请求人工反馈并根据回答恢复 | [实现人工交互与恢复](2.7-human-interaction.md) | HITL 处理器、策略和提示词 |20| 暂停执行、请求人工反馈并根据回答恢复 | [实现人工交互与恢复](2.7-human-interaction.md) | HITL 处理器、策略和提示词 |
21 21 
22-字段与默认值统一见[插件与扩展配置参考](../operations/1.5-extension-schema.md),Python 类型与接口见 [Python API 参考](3.1-python-api.md)。应用调用已有 Agent 时,回到[选择调用方式:Python、HTTP 或 A2A](integration-index.md);修改运行时实现则从[开发者导读:从扩展到源码](../development/index.md)进入。22+字段与默认值统一见[插件与扩展配置参考](../operations/1.5-extension-schema.md),Python 类型与接口见 [Python API 参考](3.1-python-api.md)。应用调用已有 Agent 时,回到[选择调用方式:Python、HTTP 或 A2A](1.1-integration-overview.md);修改运行时实现则从[开发者导读:从扩展到源码](../development/index.md)进入。
23 23 
24<a name="_2"></a>24<a name="_2"></a>
25 25 
@@ -47,7 +47,7 @@
47| 在工具里调用另一个已配置模型 | [llm-utils](../../../examples/plugins/llm-utils/README.md) |47| 在工具里调用另一个已配置模型 | [llm-utils](../../../examples/plugins/llm-utils/README.md) |
48| 产品配置中的 Python Hook | [check_input.py](../../../examples/hooks/check_input.py)、[check_tool.py](../../../examples/hooks/check_tool.py) |48| 产品配置中的 Python Hook | [check_input.py](../../../examples/hooks/check_input.py)、[check_tool.py](../../../examples/hooks/check_tool.py) |
49 49 
50-这些示例用于理解声明与实现的对应关系。安装与启用使用[插件安装、启用与配置](../data-analysis/2.2-install-plugins.md),开发期变更验证使用[扩展生命周期](../development/2.7-extension-lifecycle.md)。50+第一次扩展可从 `common` 的统计工具开始。按[编写插件 · 开发时加载与验证](2.2-write-plugins.md#load-and-verify)启用插件,用 `[1, 2, 3]` 调用工具,确认轨迹中的工具名为 `common__summarize_numbers`、返回总和为 `6`。之后再添加 Skill、Hook 或子代理,每次验证一种行为。开发期刷新规则见[扩展生命周期](../development/2.7-extension-lifecycle.md)。
51 51 
52<a name="连接已有服务"></a>52<a name="连接已有服务"></a>
53 53 
Mdocs/zh/reference/2.2-write-plugins.md+18-4File content is under review, please try again later
Mdocs/zh/reference/2.3-write-skills.md+1-1File content is under review, please try again later
@@ -38,6 +38,13 @@ tools:
38 38 
39模型用 `common__summarize_numbers` 调用此工具。普通函数由宿主包装成工具;导出 `BaseTool` 时,宿主复用其参数 schema 并以全名注册。字段和作用域见[插件与扩展配置参考 · 插件 .plugin.yaml](../operations/1.5-extension-schema.md#plugin-manifest),完整数值校验示例见 [statistics.py](../../../examples/plugins/common/tools/statistics.py)。39模型用 `common__summarize_numbers` 调用此工具。普通函数由宿主包装成工具;导出 `BaseTool` 时,宿主复用其参数 schema 并以全名注册。字段和作用域见[插件与扩展配置参考 · 插件 .plugin.yaml](../operations/1.5-extension-schema.md#plugin-manifest),完整数值校验示例见 [statistics.py](../../../examples/plugins/common/tools/statistics.py)。
40 40 
41+把实现放在插件根的 `tools/statistics.py`,按[插件加载步骤](2.2-write-plugins.md#load-and-verify)启用 `common`。在两轮独立的验证中,让 Agent 调用 `common__summarize_numbers`,检查实际工具调用和工具结果。
42+ 
43+| 工具输入 | 预期结果 |
44+| --- | --- |
45+| `{"numbers": [1, 2, 3]}` | `count` 为 `3`,`sum` 为 `6`,`mean` 为 `2`,`min` 为 `1`,`max` 为 `3`。 |
46+| `{"numbers": []}` | 若空列表传入工具,调用返回可纠正的工具错误,提示提供非空列表。 |
47+ 
41<a id="tool-runtime-clients"></a>48<a id="tool-runtime-clients"></a>
42 49 
43## 访问模型和语义客户端50## 访问模型和语义客户端
@@ -63,7 +70,7 @@ async def summarize(text: str, runtime: ToolRuntime[AgentContext]) -> str:
63 70 
64## 运行限制71## 运行限制
65 72 
66-主 Agent 和标准子代理各自执行[配置字段速查 · dataagent](../operations/1.2-configuration-fields.md#dataagent),新的一轮重新计数。73+根 Agent 和各标准子代理分别按 `dataagent.limits.model_calls_per_agent` 与 `dataagent.limits.tool_calls_per_agent` 限制单次调用中的模型次数与工具次数。下一次调用重新计数。默认值见[配置字段速查](../operations/1.2-configuration-fields.md#dataagent)。
67 74 
68`ToolException` 会变成一条可纠正的工具消息:`Invalid tool input...`。其他异常按原生工具错误处理。75`ToolException` 会变成一条可纠正的工具消息:`Invalid tool input...`。其他异常按原生工具错误处理。
69 76 
@@ -23,6 +23,8 @@ dataagent:
23 23 
24只把文件放进 `hooks/` 不会注册。字段、分组与扁平声明格式见 [插件与扩展配置参考 · Hook](../operations/1.5-extension-schema.md#agent-hooks)。`params` 每次调用都会复制,函数可从 `runtime.context` 读取宿主配置。24只把文件放进 `hooks/` 不会注册。字段、分组与扁平声明格式见 [插件与扩展配置参考 · Hook](../operations/1.5-extension-schema.md#agent-hooks)。`params` 每次调用都会复制,函数可从 `runtime.context` 读取宿主配置。
25 25 
26+验证输入检查时,将 `check_input.py` 复制到产品 YAML 同级的 `hooks/`,只合入 `before_model` 声明并把 `max_chars` 改为 `16`。用这份配置启动服务,在默认根 Agent 的两个新会话中分别发送 `Hello` 和 `12345678901234567`。第一条应通过检查并进入模型调用,第二条应在首次调用模型前失败。HTTP / AG-UI 客户端会收到 `RUN_ERROR`,错误信息包含 `Input exceeds 16 characters`。
27+ 
26<a name="hook-signatures"></a>28<a name="hook-signatures"></a>
27 29 
28## 函数签名30## 函数签名
@@ -60,7 +62,7 @@ dataagent:
60| `before_tool` | 工具调用前 |62| `before_tool` | 工具调用前 |
61| `after_tool` | 工具正常返回后,包括返回了错误 `ToolMessage`。包装调用抛出异常时不运行 |63| `after_tool` | 工具正常返回后,包括返回了错误 `ToolMessage`。包装调用抛出异常时不运行 |
62 64 
63-Hook 抛出的异常会传播。运行时不吞掉、不重试,也没有单条超时。REST 的整轮 `timeout_seconds` 仍然包住整个流。65+Hook 异常会向调用方传播。运行时没有单个 Hook 的超时或重试。HTTP / AG-UI 和入站 A2A 由 `server.run_timeout_seconds` 限制各次服务端执行,执行期间运行的 Hook 计入这个时限。等待人工回答期间不计时,后续恢复执行时重新计时。
64 66 
65## 拒绝执行67## 拒绝执行
66 68 
@@ -6,14 +6,34 @@
6 6 
7## 最小声明7## 最小声明
8 8 
9-```yaml9+```text
10-schema_version: 110+review-demo/
11-name: general-purpose11+├── .plugin.yaml
12-description: Handle focused research and file inspection.12+├── prompts/
13-system_prompt_file: prompts/general-purpose.md13+│ └── review-check.md
14+└── subagents/
15+ └── review-check.yaml
14```16```
15 17 
16-描述可直接填写或从文件读取。提示使用相对插件根的 `system_prompt_file`。名称、路径和字段限制见[插件与扩展配置参考 · 子代理 YAML](../operations/1.5-extension-schema.md#subagent-declaration)。18+`.plugin.yaml`
19+ 
20+```yaml
21+schema_version: 3
22+id: review-demo
23+subagents:
24+- subagents/review-check.yaml
25+```
26+ 
27+`subagents/review-check.yaml`
28+ 
29+```yaml
30+schema_version: 1
31+name: review-check
32+description: Verify subagent delegation by returning a fixed marker.
33+system_prompt_file: prompts/review-check.md
34+```
35+ 
36+在 `prompts/review-check.md` 写入 `Reply with REVIEW_OK and no other text.`。按[插件加载步骤](2.2-write-plugins.md#load-and-verify)启用 `review-demo`,保留默认根 Agent。提问“请用 `task` 委派给 `review-check`,并返回它的结果”。在[执行轨迹](../operations/3.3-trace-evaluation.md)中检查 `task` 调用的目标为 `review-check`、工具返回值为 `REVIEW_OK`。也可用 [AG-UI 子代理事件](3.3-ag-ui-events.md#stream-scope)确认子代理已启动和结束。描述也可由文件提供。名称和路径规则见[子代理 YAML](../operations/1.5-extension-schema.md#subagent-declaration)。
17 37 
18## 继承38## 继承
19 39 
Mdocs/zh/reference/2.7-human-interaction.md+10-7File content is under review, please try again later
@@ -2,7 +2,7 @@
2 2 
3# 示例:为 de-agent 的 SQL 任务加入人工复核3# 示例:为 de-agent 的 SQL 任务加入人工复核
4 4 
5-de-agent 可以在澄清业务口径、生成 SQL 前复核口径以及确认交付时请求人工反馈。本页是[实现人工交互与恢复](2.7-human-interaction.md)的场景示例,介绍内置策略及其业务配置。为其他插件实现交互时,先阅读通用指南。5+分析任务缺少去重标识等关键口径时,de-agent 可以暂停并请用户澄清。启用 SQL 生成前口径复核时,系统会在满足复核条件后展示已提取的业务口径。插件也可在交付前请求最终确认。本页用 SQL 任务演示这些行为。通用处理器与恢复步骤见[实现人工交互与恢复](2.7-human-interaction.md)。
6 6 
7<a name="enable-de-agent-hitl"></a>7<a name="enable-de-agent-hitl"></a>
8 8 
@@ -25,9 +25,9 @@ plugins:
25 25 
26<a name="completion-guards"></a>26<a name="completion-guards"></a>
27 27 
28-## 结束前的两个 guard28+## 结束前的两项检查
29 29 
30-两个结束策略均在 `after_model` 运行。模型响应包含有效或无效的工具调用时,这两个策略都会跳过该响应。30+这里的 `guard` 是判断是否需要暂停并提问的检查策略。两项结束检查都在 `after_model` 运行。模型响应包含有效或无效的工具调用时,两项检查均跳过该响应。
31 31 
32| 策略 | 提问时机 | 清单参数 |32| 策略 | 提问时机 | 清单参数 |
33| --- | --- | --- |33| --- | --- | --- |
@@ -71,7 +71,7 @@ IR 提问策略将原始回答保存到任务级 `ir_clarification`,后续由
71## 验证场景71## 验证场景
72 72 
731. 使用 de-agent 配置开启新会话。提交一条生成 SQL 的任务,选用同时允许 `user_id` 和 `device_id` 的源表,暂不指定去重主键。731. 使用 de-agent 配置开启新会话。提交一条生成 SQL 的任务,选用同时允许 `user_id` 和 `device_id` 的源表,暂不指定去重主键。
74-2. 会话暂停时回答正确的主键,如果提示需要源表则一并回答。确认同一会话继续运行。启用口径复核且 IR 字段均已明确时,确认本任务生成 SQL 前只提示复核一次。74+2. 会话暂停时回答正确的主键,如果提示需要源表则一并回答。确认同一会话继续运行。启用口径复核时,确认阻塞澄清完成或任务进入 best-effort 后,生成 SQL 前只提示复核一次。
753. 核对 SQL 和交付说明是否采用所选主键,并说明剩余缺口。最终确认已启用时回答该问题。也验证一次回答后字段依然无法确认的情况。753. 核对 SQL 和交付说明是否采用所选主键,并说明剩余缺口。最终确认已启用时回答该问题。也验证一次回答后字段依然无法确认的情况。
76 76 
77[结束策略测试](../../../tests/test_de_agent_completion_guards.py)、[IR 提问测试](../../../tests/test_de_agent_ir_question_guard.py)和[口径复核测试](../../../tests/test_de_agent_delivery_guards.py)使用本地测试夹具。可从仓库根目录一起运行。77[结束策略测试](../../../tests/test_de_agent_completion_guards.py)、[IR 提问测试](../../../tests/test_de_agent_ir_question_guard.py)和[口径复核测试](../../../tests/test_de_agent_delivery_guards.py)使用本地测试夹具。可从仓库根目录一起运行。
@@ -1,364 +1,49 @@
1-# Python API 参考1+<a name="python-api"></a>
2 2 
3-安装 DataAgent 后使用 `import dataagent`。包版本可查 `dataagent.__version__`。模型和图相关的模块按需导入。调用示例见 [用 Python SDK 调用 Agent](1.2-python-sdk.md)。3+# Python SDK
4 4 
5-接口分三层。先用公开 SDK;只有在写宿主服务或需要原生 LangGraph 图时,才用后两层。5+查阅应用内调用 Agent 的常用接口。配置模型、运行第一段代码和查看预期结果,见[用 Python SDK 调用 Agent](1.2-python-sdk.md)。
6- 
7-| 层 | 模块 | 给谁 | 稳定性 |
8-| --- | --- | --- | --- |
9-| 公开 SDK | `dataagent` | 在 Python 里调用 Agent 的人、写工具的人 | 对外契约 |
10-| 宿主接口 | `dataagent.host` | 把 Agent 提供给其他客户端的服务,例如 `dataagent serve` | 对外契约,面向宿主 |
11-| 低层接口 | `dataagent.lowlevel` | 需要自己管理 LangGraph 图和上下文的人 | 跟随 LangGraph 变化,可能调整 |
12- 
13-各层的导出以 [dataagent](../../../dataagent/__init__.py)、[dataagent.host](../../../dataagent/host.py)和 [dataagent.lowlevel](../../../dataagent/lowlevel.py) 中的 `__all__` 为准。
14 6 
15<a name="public-sdk"></a>7<a name="public-sdk"></a>
16- 
17-## 公开 SDK(`dataagent`)
18- 
19-| 名称 | 作用 |
20-| --- | --- |
21-| `LaunchOptions` | 启动输入,包括配置文件、环境文件和用户。冻结数据类 |
22-| `prepare_runtime` | `LaunchOptions` → `PreparedRuntime`。读取配置并校验,不创建 Agent |
23-| `PreparedRuntime` | `prepare_runtime` 的结果:设置、路径和扩展位置。只读,不要自己构造 |
24-| `create_agent` | 由 `PreparedRuntime` 创建 `Agent`。唯一推荐的创建方式 |
25-| `Agent` | `create_agent` 的返回类型。用于类型标注,不要自己构造 |
26-| `load_mcp_tools` | 加载已配置的 MCP 服务工具。无配置时返回空列表,使用方法见 [连接 MCP 服务](../data-analysis/1.2-mcp.md) |
27-| `AgentContext` | 工具里 `ToolRuntime[AgentContext]` 的上下文类型:配置的模型、语义客户端、插件配置 |
28-| [`SemanticServiceClient`](#semantic-client) | SemanticLayer HTTP 客户端:元数据查询、语义召回与实体检索 |
29-| `collect_model_stream(model, messages, **kwargs)` | 以流式调用模型并合成一条完整消息,保留工具调用、推理和用量。插件里调用 `AgentContext.get_model()` 返回的模型时用它 |
30-| `SubagentServices` | 编译子代理工厂 `factory(params, services)` 的第二个参数:`get_model`、`semantic_client`、`outputs_dir`、`run_hooks` |
31-| `ConfigurationLoadError` | 配置文件不存在、不是合法 YAML 或校验失败。`ValueError` 的子类 |
32-| `DataAgentError` | DataAgent 诊断异常的基类,字段包括 `source`、`component`、`fact`、`trace_id`。`ConfigurationLoadError`、`LoopDetectedError`、`A2ACallError` 都继承它,并保留各自的内置基类(`ValueError`、`RuntimeError`)。语义服务客户端也抛出它 |
33-| `LoopDetectedError` | 循环检测终止本轮。`kind` 说明是文本复读还是工具循环 |
34-| `safe_error` | 把异常渲染成 `{"code", "message"}`:去掉已知密钥和终端控制符,消息截断到 1500。`code` 的取值见 [AG-UI 事件与运行契约](3.3-ag-ui-events.md) |
35-| `read_yaml` | 从指定路径读取严格 YAML 配置 |
36-| `HITLHandler`、`HITLContext`、`HITLState`、`InteractionRequest`、`TriggerDecision`、`ResumeDecision` | 人工反馈的扩展接口,见[人工交互 API](#hitl-api);使用步骤见[实现人工交互与恢复](2.7-human-interaction.md) |
37-| `MCPConfig`、`MCPInfrastructureError` | 数据网关的 MCP SQL 连接参数类型和基础设施异常,见 [连接 MCP 服务 · 区分 NL2SQL 的 MCP 数据库连接](../data-analysis/1.2-mcp.md#nl2sql-mcp) |
38-| `build_sql_service`、`check_engine_driver`、`check_read_only_sql`、`check_sql` | 构建 SQL 服务、检查引擎依赖和 SQL 的数据网关接口 |
39-| `recall_database`、`RecallOptions`、`RecallError` | SQLite 数据库探索的异步入口、选项和错误类型 |
40- 
41<a name="launch-options"></a>8<a name="launch-options"></a>
42 9 
43-### `LaunchOptions`10+<a name="prepare-runtime"></a>
44 11 
45-| 字段 | 默认 | 说明 |12+## 准备运行时
46-| --- | --- | --- |
47-| `config` | `None` | 配置文件。省略时读 Home `config.yaml` |
48-| `env_file` | `None` | 环境文件。设置后用这一份代替 Home `.env` |
49-| `user_id` | `"default"` | 本地用户 ID,决定 `runtime/users/<user>/` |
50-| `cwd` | `Path.cwd()` | 相对路径的基准 |
51-| `init_home` | `False` | `True` 时创建 Home 模板,不覆盖已有文件 |
52-| `session_id` | `None` | 验证指定会话已存在且属于当前用户。Agent 的调用仍使用 `configurable.thread_id` 选会话 |
53 13 
54-输入目录从所选 YAML 的 `dataagent.input_workspaces` 读取。宿主可在创建 Agent 时显式指定,见[宿主接口](#host-api)。环境取值见[命令与环境变量 · 环境变量](../operations/1.1-cli-and-environment.md#environment-variables)。14+| 调用 | 行为 |
15+| --- | --- |
16+| `prepare_runtime()` | 读取 DataAgent Home 中的配置,返回供 `create_agent()` 使用的运行时。 |
17+| `prepare_runtime(LaunchOptions(config=路径))` | 使用指定的产品 YAML。 |
55 18 
56<a name="create-agent"></a>19<a name="create-agent"></a>
57 20 
58-### `create_agent`21+## 创建与调用 Agent
59 22 
60-```text23+`create_agent(runtime)` 返回 `Agent`。`agent.invoke(inputs, config=...)` 同步执行一轮并返回最终图状态。普通对话在 `inputs["messages"]` 中提交本轮的新消息,从返回值的 `messages` 读取回复。用 `with` 管理 Agent 生命周期。
61-create_agent(runtime, *, model=None, checkpointer=None, session=None,
62- input_workspaces=None, mcp_tools=None, extension_revision=None,
63- semantic_client=None)
64-```
65- 
66-| 参数 | 说明 |
67-| --- | --- |
68-| `checkpointer` | LangGraph checkpointer。要跨进程保留对话历史时传持久化实现 |
69-| `mcp_tools` | 配置了 MCP 时必传,值来自 `await load_mcp_tools(runtime)`。未配置 MCP 服务时可省略 |
70-| `semantic_client` | 宿主已有语义客户端时传入,Agent 不关闭它。省略时,配置了 `semantic` 就由 Agent 创建并拥有 |
71-| `model` | 覆盖默认模型对象,主要用于测试 |
72- 
73-`create_agent` 先校验入口、插件声明、MCP、Hook 和语义客户端。在预检阶段只读取声明和说明文件,插件 Python 在构图时加载。普通 SDK 调用在首次使用会话时构图。宿主传入 `session` 时,创建 Agent 的过程中会打开该会话并构图。未知关键字会触发 `TypeError`。宿主参数详见[宿主接口](#host-api)。
74 24 
75<a name="agent"></a>25<a name="agent"></a>
76 26 
77-### `Agent`27+## 指定会话
78 28 
79-| 成员 | 行为 |29+用 `config["configurable"]["thread_id"]` 选择会话。换一个 ID 会开始新会话。要在同一会话里继续对话,沿用原 ID,并为 Agent 配置持久化的 SQLite checkpointer。见 [Python SDK 使用指南](1.2-python-sdk.md#continue-conversation)。
80-| --- | --- |
81-| `invoke` / `ainvoke` / `stream` / `astream` / `astream_events` | 参数同 LangGraph,另加调用级 `output_dir`。按 `config["configurable"]["thread_id"]` 选择会话,默认是 `sdk` 或创建 Agent 时显式指定的会话。首次使用时创建 |
82-| `close` / `aclose` | 关闭本 Agent 创建的语义客户端。传入的客户端保持打开 |
83-| 上下文管理器 | `with` 退出时调用 `close`,`async with` 退出时等待 `aclose` |
84 30 
85-- 不同 `thread_id` 可以并发。同一 `thread_id` 上的重叠调用会报错。31+<a name="async-and-streaming"></a>
86-- `stream()` 在调用时准备会话并校验路径。同步和异步流都在迭代时持续占用会话,流结束、出错或关闭时释放。提前停止见[用 Python SDK 调用 Agent · 提前结束事件流](1.2-python-sdk.md#close-stream)。
87-- `output_dir` 在首次绑定会话时生效。之后沿用原目录,路径约束见[查找会话产物与恢复会话](../operations/2.2-sessions-and-outputs.md)。
88-- 每个会话缓存独立的图和上下文,本 Agent 实例共享模型客户端。图缓存目标大小为 32,只淘汰空闲图,优先淘汰最久未用的图。若活跃会话较多,缓存可暂时超过该值。对话历史由 checkpointer 保存,Trace 由会话图按轮记录。
89 32 
90-<a name="agent-context"></a>33+## 异步与流式调用
91 34 
92-### `AgentContext`35+`ainvoke()` 等待一轮结束并返回最终结果。`astream()` 在运行过程中逐步产出更新,适合接入需要实时显示进度的客户端。见[异步与流式示例](1.2-python-sdk.md#async-and-streaming)。
93 36 
94-工具通过 `runtime.context` 拿到它,SDK 用户不需要自己构造。37+<a name="sdk-errors"></a>
95 38 
96-| 成员 | 说明 |39+配置失败时,先检查模型和 YAML,见[配置模型并验证首次调用](../getting-started/4.1-configuration.md)。
97-| --- | --- |
98-| `get_model(name=None)` | 返回配置的模型。省略别名时用 `dataagent.model`。未知别名抛出 `ValueError` |
99-| `semantic_client` | 语义客户端,没有配置 `semantic` 时为 `None` |
100-| `session.outputs` | 本轮产物目录 |
101-| `home` | 已解析的 Home 路径,用于跨会话共享的资源 |
102-| `get_plugin_config(plugin_id)` | `plugins.config.<plugin_id>` 的副本。插件未启用时抛出 `ValueError` |
103-| `get_plugin_state(plugin_id)` | 当前会话图上下文中该插件的私有内存字典。只有已启用插件可以访问,字典随进程内上下文保存。Checkpoint 不含该状态,插件自己负责并发同步 |
104 40 
105-<a name="host-api"></a>41+<details markdown="1">
42+<summary>扩展与宿主开发</summary>
106 43 
107-## 宿主接口(`dataagent.host`)44+- <a id="extension-api"></a><a id="agent-context"></a><a id="extension-models-and-services"></a><a id="semantic-client"></a><a id="sql-apis"></a><a id="_1"></a><a id="_2"></a><a id="_3"></a><a id="_4"></a>[Python 扩展接口](3.1.1-python-extension-api.md) · 工具上下文、模型、SemanticLayer 和数据访问。
45+- <a id="hitl-api"></a><a id="hitl-handler"></a><a id="hitl-middleware"></a><a id="hitl-resume-actions"></a>[Python 人工交互接口](3.1.2-python-hitl-api.md) · 处理器、中断与恢复动作。
46+- <a id="a2a-api"></a>[A2A Python 客户端](3.1.3-python-a2a-client.md) · 向远端 Agent 发送消息、续接上下文与处理异常。
47+- <a id="host-api"></a><a id="host-startup"></a><a id="host-diagnostics"></a><a id="host-sessions"></a><a id="a2a-server-api"></a><a id="lowlevel-api"></a><a id="explicit-hitl-assembly"></a>[Python 宿主与原生图接口](3.1.4-python-host-api.md) · 日志、扩展刷新、AG-UI 适配和原生图装配。
108 48 
109-宿主是把 Agent 提供给其他客户端的长驻服务,例如 `dataagent serve`。只调用 Agent 的程序不需要这一节。49+</details>
atomgit-bot
atomgit-botatomgit-bot5 days ago

🟡 Medium Priority

变更点:docs/zh/reference/3.1-python-api.md 从 364 行参考页裁剪为 49 行入口页,原 AgentContext、SemanticServiceClient 方法表、HITL 接口、宿主接口、A2A 客户端等正文分别迁到 3.1.1/3.1.2/3.1.3/3.1.4;本页仅在第 44–47 行用一个默认折叠的 <details> 块保留 <a id="agent-context">、<a id="semantic-client">、<a id="hitl-api">、<a id="host-api">、<a id="a2a-api"> 等锚点。

契约破坏:其他页面仍按旧契约链接到这些锚点且未被本 PR 修改,例如 docs/zh/data-analysis/1.3-semantic-service.md:5、:36、:115(../reference/3.1-python-api.md#semantic-client,文案为“方法、参数与生命周期见…”)、docs/zh/operations/1.5-extension-schema.md:118(#hitl-api)、docs/zh/operations/2.2-sessions-and-outputs.md:100 与 docs/zh/operations/2.3-session-storage.md:213、docs/zh/development/2.7-extension-lifecycle.md:45(#host-api)、docs/zh/reference/1.2-python-sdk.md:149(#agent)。

建议:把仍指向 3.1-python-api.md 旧锚点的跨文件链接(data-analysis/1.3-semantic-service.md、operations/1.5-extension-schema.md、operations/2.2-sessions-and-outputs.md、operations/2.3-session-storage.md、development/2.7-extension-lifecycle.md、reference/1.2-python-sdk.md)改到 3.1.1/3.1.2/3.1.4 的对应锚点,并确认已发布 URL 的旧锚点有可读的落点。

likedislike
Incorrect?
110- 
111-| 名称 | 作用 |
112-| --- | --- |
113-| `refresh_extensions(runtime)` | 重读插件、Hook 和 MCP 声明,返回新的 `PreparedRuntime`。保留模型、路径和启动策略。先编译成功再替换正在使用的 PreparedRuntime;进行中的调用继续用旧图 |
114-| `extension_revision(runtime)` | 扩展来源的 SHA-256 指纹,用来判断是否需要刷新。不含业务输入和会话状态 |
115-| `server_listen(options=None)` | 读所选配置的 `server` 段,按 `prepare_runtime` 的环境规则展开 `$env{NAME}`(含 `options.env_file`),返回 `(host, port)`。没有 Home 配置文件且未显式指定配置时使用默认 `127.0.0.1:8790`。所选配置读取、环境展开或校验失败时抛出异常。`prepare_runtime` 失败时也能用 |
116-| `error_code(error)` | 把异常映射为固定错误码 |
117-| `configure_logging(runtime=None)` | 宿主启动时配置统一的 `backend.log`。无 runtime 时也能记录早期启动错误 |
118-| `register_log_secrets(values)` | 扩展或凭据刷新后追加脱敏值,保留旧运行凭据的脱敏能力 |
119-| `diagnostic_traceback(error, secrets=())` | 返回完整的脱敏堆栈,用于诊断日志,不作为公开错误响应 |
120-| `log_context` | 宿主用 ContextVar 绑定 `requestId`、`threadId`、`runId` 等关联字段,结束后重置 token |
121-| `OPAQUE_ID_PATTERN` | 客户端给的 ID(`threadId`、`runId`、用户)的正则:`[A-Za-z0-9][A-Za-z0-9_-]{0,127}`。宿主校验请求时用它 |
122-| `ERROR_CODES` | 用于 `safe_error` 和 [AG-UI 事件与运行契约 · 失败](3.3-ag-ui-events.md#errors) 的固定错误码。异常类可通过 `error_code` 指定集合内的值 |
123-| `ServerSettings` | 监听地址和端口的校验模型 |
124-| `opaque_id(value, label)` | 校验并返回符合 `OPAQUE_ID_PATTERN` 的 ID |
125-| `log_event(...)` / `safe_interrupt_fields(...)` | 记录结构化事件,或对人工交互字段递归脱敏 |
126- 
127-宿主另外使用这些成员:
128- 
129-- `create_agent(..., session=, input_workspaces=, extension_revision=)`:
130- - `session` 指定默认会话,必须是当前 Home 和用户下的标准会话路径,否则立即报错。
131- - `input_workspaces=None` 时,新会话用配置默认值,已有会话沿用保存值;显式元组(包括 `()`)必须和已有绑定的路径及顺序一致。名称不参与比较。
132- - `extension_revision` 是上面 `extension_revision(runtime)` 的值,用来让 Skill 缓存跟随扩展刷新。
133-- `runtime.paths.open_session(thread_id, *, create, output_dir=None, input_workspaces=None)`:登记或恢复会话,返回 `(SessionPaths, workspaces)`,可传给上面两个参数。`create=False` 时会话不存在返回 `None`。目录规则见 [查找会话产物与恢复会话](../operations/2.2-sessions-and-outputs.md)。
134-- `agent.as_agui(name="dataagent", **kwargs)`:创建 AG-UI 适配器,执行 `run(input)` 时按 `input.thread_id` 选择会话。每个请求用新的适配器。
135-- `agent.graph_for(thread_id)`:取得已有会话的原生图,例如读状态 `graph_for(t).aget_state(config)`。会话不存在时抛出 `ValueError`。`agent.graph` 是默认会话的图,首次访问会创建默认会话。
136- 
137-<a name="lowlevel-api"></a>
138- 
139-## 低层接口(`dataagent.lowlevel`)
140- 
141-`build_graph` 打开一个会话并返回绑定该会话的原生 LangGraph `CompiledStateGraph`。构建时校验已有路径或按该会话登记路径。调用方在调用图时传递上下文,负责语义客户端的生命周期。需要按线程路由和复用多个会话图时,使用 `create_agent`。
142- 
143-```python
144-from dataagent import AgentContext, load_mcp_tools
145-from dataagent.lowlevel import build_graph
146- 
147-context = AgentContext(runtime, semantic_client=client)
148-graph = build_graph(
149- runtime,
150- context=context,
151- checkpointer=checkpointer,
152- mcp_tools=await load_mcp_tools(runtime),
153-)
154-result = await graph.ainvoke(inputs, config, context=context)
155-```
156- 
157-```text
158-build_graph(runtime, *, checkpointer=None, model=None, session=None,
159- input_workspaces=None, mcp_tools=None, extension_revision=None, context=None)
160-```
161- 
162-- 省略 `session` 和 `context` 时用名为 `sdk` 的会话。
163-- 配置了 MCP 却没传 `mcp_tools` 时失败。配置了语义服务、而 `context` 没有语义客户端时失败。
164-- `dataagent.entry` 有值时只挂该编译型入口。
165-- 额外的 LangChain callback 放在调用的 `config["callbacks"]`,或用 `graph.with_config(callbacks=[...])`。
166- 
167-<a name="semantic-client"></a>
168- 
169-## SemanticLayer 客户端
170- 
171-`SemanticServiceClient` 从 `dataagent` 导入,是独立的同步 HTTP 客户端,不属于宿主或低层图接口。配置连接、证书并用自然语言验证服务,见 [连接语义层服务](../data-analysis/1.3-semantic-service.md)。
172- 
173-### 构造与所有权
174- 
175-| 使用方式 | 创建与关闭 |
176-| --- | --- |
177-| REST Server | 按 `semantic` 配置在进程生命周期内创建一个共享客户端,注入每个 Agent 的 `AgentContext`,由宿主关闭 |
178-| `create_agent(runtime)` | 未传 `semantic_client` 且配置了 `semantic` 时,由 SDK 创建;`Agent.close()` / `aclose()` 关闭它 |
179-| `create_agent(runtime, semantic_client=client)` | 借用调用方客户端,Agent 关闭时不关闭该连接;调用方负责关闭 |
180-| 工具中的 `runtime.context.semantic_client` | 借用宿主提供的客户端,未配置时为 `None`;工具不自行创建或关闭它 |
181-| `SemanticServiceClient.from_settings(runtime.settings.semantic)` 或直接构造 | 调用方持有客户端,负责 `close()`,也可用 `with` 管理 |
182- 
183-`from_settings` 接收已解析的 `SemanticSettings`,使用其中的地址、Basic 认证、超时、TLS 和场景配置。直接调用 `SemanticServiceClient(base_url, ...)` 时,服务端证书校验默认开启(`verify=True`);通过 `from_settings` 构造时由配置的 `tls` 决定。
184- 
185-配置的 `tls.verify_server` 默认 `false`。此时没有客户端证书和 `ciphers` 时不校验服务端证书。设为 `true` 时使用默认 SSL 上下文,提供 `ca_file` 时用该 CA。`client_cert` 与 `client_key` 必须成对,非空 `ciphers` 传给 `SSLContext.set_ciphers`。字段约束见[配置字段速查 · semantic](../operations/1.2-configuration-fields.md#semantic)。
186- 
187-客户端使用同步 `httpx.Client`。异步工具应将调用放入 `asyncio.to_thread`,避免堵住事件循环。拥有连接的客户端在 `close()` 时拒绝新请求,并等待进行中的同步请求结束再关闭连接池。Basic 凭据及其 Base64 形式进入诊断脱敏列表,日志不应输出原始密钥。
188- 
189-### 方法与路径
190- 
191-请求路径以 `/api/semantic/v1/` 为前缀。检索表接口查询语义服务自身的元数据表;业务表接口查询已接入业务库中的表和列。
192- 
193-| 方法 | HTTP 与路径后缀 |
194-| --- | --- |
195-| `semantic_retrieve` | `POST semantic/retrieve` |
196-| `get_table_list` | `GET advanced-search/table-list` |
197-| `get_table_columns_info` | `GET advanced-search/table-columns-info` |
198-| `get_columns_sample_values` | `GET advanced-search/column-value-info` |
199-| `semantic_search_columns` | `GET advanced-search/semantic-search-columns` |
200-| `get_joinable_tables` | `GET advanced-search/joinable-tables` |
201-| `get_table_relations_path` | `GET advanced-search/table-relations-path` |
202-| `vector_search_table_desc` | `GET advanced-search/vector-search-table-desc` |
203-| `vector_search_column_value` | `GET advanced-search/vector-search-column-value` |
204-| `sql_few_shots` | `GET advanced-search/sql-few-shots` |
205-| `search_fulltext` | `GET search/fulltext` |
206-| `search_basic` | `POST search/basic`,提交检索条件 |
207-| `search_dsl` | `GET search/dsl` |
208-| `search_entities(type_name, *, limit=200, offset=0)` | `GET search/basic`,按类型分页列出实体 |
209-| `get_entity_by_guid` | `GET entity/guid/{guid}` |
210-| `get_entity_by_unique_attribute` | `GET entity/uniqueAttribute/type/{type_name}` |
211-| `list_retrieval_tables` | `GET retrieval/tables`,语义层检索表清单 |
212-| `get_retrieval_table_schema` | `GET retrieval/tables/{table}/schema`,检索表结构 |
213-| `hybrid_table_columns(tables)` | `POST hybrid/table-columns`,批量取业务表的物理列 |
214- 
215-### 参数约定
216- 
217-定位参数从大到小排列,如库、表、关键词或查询。条数使用关键字参数 `limit`,实际 HTTP 参数按接口发送为 `topK` 或 `limit`;`max_depth`、`sample_count` 也只能按关键字传。
218- 
219-列标识采用 `db.table.column`。`get_columns_sample_values(column_ids, *, sample_count=3)` 的 `sample_count` 范围为 0 到 100。`search_entities` 的 `limit` 范围为 1 到 200,`offset` 必须非负;返回实体列表。
220- 
221-`semantic_retrieve(query, *, db_name=None, evidence=None)` 接收自然语言查询。提供可选参数时将 `db_name`、`evidence` 加入请求体,省略时保留服务的默认召回流程。`search_basic` 的 POST 条件检索与 `search_entities` 的 GET 按类型枚举是两种不同调用。
222- 
223-### 场景视图
224- 
225-配置 `semantic_scenario`,或直接构造时传入 `scenario=`,会在除 health 外的请求中设置 `X-Semantic-Scenario`。`with_scenario(scenario)` 返回共享同一连接池的客户端视图,用于临时切换该请求头。
226- 
227-关闭场景视图不关闭连接池;拥有连接的原客户端仍负责关闭,并等待视图中进行的请求结束。继续使用现有客户端查询即可,无需为每个场景创建连接。
228- 
229-<a name="hitl-api"></a>
230- 
231-## 人工交互 API
232- 
233-使用步骤见[实现人工交互与恢复](2.7-human-interaction.md),插件清单的字段与默认值见[插件与扩展配置参考 · 人工交互配置](../operations/1.5-extension-schema.md#hitl-configuration)。本节定义处理器、上下文、中间件与恢复动作,不重复宿主的请求格式;协议入口见 [AG-UI 事件与运行契约 · 等待用户回答](3.3-ag-ui-events.md#hitl) 和 [A2A 参考 · 原生 HITL 暂停与恢复](3.4-a2a-reference.md#a2a-hitl)。
234- 
235-<a name="hitl-handler"></a>
236- 
237-### `HITLHandler`、上下文与决策
238- 
239-从 `dataagent` 导入 `HITLHandler`、`HITLContext`、`HITLState`、`TriggerDecision`、`InteractionRequest` 和 `ResumeDecision`。处理器可无参构造,实例跨调用共享;交互状态应存入图状态和 Checkpoint,方法应保持幂等以支持重放。
240- 
241-| 方法 | 返回类型 | 默认行为 |
242-| --- | --- | --- |
243-| `trigger_policy(context, *, params)` | `TriggerDecision` | 每次匹配阶段或工具调用都会触发 |
244-| `interaction_builder(context, *, params)` | `InteractionRequest` | 使用 `params.question` 和 `params.options`,缺少问题时用通用问题 |
245-| `resume_handler(context, *, params)` | `ResumeDecision` | 把回答作为反馈交给模型,动作是 `replan`,不修改业务状态 |
246- 
247-方法可用 `def` 或 `async def`,签名必须保留关键字参数 `params`,不支持生成器。返回值必须是对应的决策对象,不接受等价字典。
248- 
249-`HITLContext` 是冻结数据类,其字段如下:
250- 
251-| 字段 | 含义 |
252-| --- | --- |
253-| `state` | 分离的图状态预览;直接修改不会提交 |
254-| `runtime` | 原生运行时;从 `runtime.context` 借用宿主服务 |
255-| `policy_id` | 带命名空间的完整策略 ID,如 `my-plugin/clarification` |
256-| `event` | 当前六阶段之一 |
257-| `tool_call` | 工具阶段的原始调用(`id`、`name`、`args`),其他阶段为 `None` |
258-| `tool_result` | `after_tool` 的原生 `ToolMessage` 或 `Command`;状态预览含工具业务更新 |
259-| `decision` | 问题构建及恢复时可读的触发判定 |
260-| `interaction` | 恢复时可读的已保存问题 |
261-| `answer` | 恢复时的用户文本回答 |
262- 
263-| 类型 | 字段与默认值 |
264-| --- | --- |
265-| `TriggerDecision` | `triggered=True`、`reason=""`、`payload={}`;未触发时不构建问题 |
266-| `InteractionRequest` | 必填非空白 `question`;`options=[]` |
267-| `ResumeDecision` | `action="replan"`、`message=None`、`state_update={}`;动作只接受 `continue`、`replan`、`reject` |
268- 
269-回答必须是非空文本,空白或结构化值会再次暂停并返回 `validation_error`。选项不自动强制枚举校验,业务校验由 `resume_handler` 完成。`state_update` 只接受可序列化业务更新,不能写入 `messages`、`hitl_history`、`hitl_replans` 或 `jump_to`。
270- 
271-处理器可声明 `state_schema`,通常继承 `HITLState` 并增加业务字段。中间件合并兼容的状态字段;同名字段注解不一致时装配失败。提交示例:
272- 
273-```python
274-return ResumeDecision(
275- action="continue",
276- state_update={"selected_key": context.answer},
277-)
278-```
279- 
280-`selected_key` 需要预先在状态 schema 中声明。工具前的更新可被工具的 `ToolRuntime.state` 读取。实际执行工具时,更新按 before-tool、工具、after-tool 的顺序提交,并遵循字段 reducer。返回 `replan` 或 `reject` 时也提交显式更新。
281- 
282-<a name="hitl-middleware"></a>
283- 
284-### `HITLMiddleware` 与显式装配
285- 
286-中间件位于 `dataagent.extensions.hitl`,负责保存交互、调用 interrupt、接收回答及提交状态。使用异步 `ainvoke` 或 `astream`。
287- 
288-| 接口 | 行为 |
289-| --- | --- |
290-| `HITLMiddleware(policies, *, model_feedback=False)` | 接收 `HITLPolicy` 列表;完整策略 ID 必须唯一。`model_feedback=True` 时提供共享反馈工具 |
291-| `HITLMiddleware.from_config(config, *, root, namespace="main", loader=None)` | 接收 `HITLConfig` 或字典;`root` 是处理器路径基准,`namespace` 用于策略 ID。启用时创建 handler 并提供反馈工具;禁用时返回空中间件 |
292-| `HITLPolicy(spec, handler, namespace="main")` | 绑定已校验的 `HITLPolicySpec` 和 `HITLHandler`,完整 ID 为 `<namespace>/<spec.id>` |
293- 
294-标准插件装配把已启用来源的策略汇集到默认根图上的一个中间件,并读取 `instructions` 提示词。关闭某个插件的 HITL 会跳过其处理器和提示词,其他来源仍可使用。显式 `from_config` 不负责读取或传入图的提示词。
295- 
296-| 阶段 | 时机 |
297-| --- | --- |
298-| `before_agent` | 每次执行开始时,在首次模型调用前运行一次 |
299-| `before_model` | 每次模型调用前 |
300-| `after_model` | 模型响应后,执行计划中的工具前 |
301-| `before_tool` | 单个工具执行前,包括 `task` |
302-| `after_tool` | 单个工具返回后,父图提交结果前 |
303-| `after_agent` | 沿结束路径返回前;重新规划可回到模型循环,再次接受复审 |
304- 
305-`matcher` 只支持工具阶段。要匹配特定子代理,设置 `matcher: task`,再由触发器检查 `tool_call.args.subagent_type`。当前没有自动回答或交互超时。
306- 
307-`request_human_feedback(question, reason="", options=None)` 是模型可见的共享工具;`ToolRuntime` 由框架注入。它返回包含原始回答的成功 `ToolMessage`。同一次模型响应中只执行第一条反馈调用,忽略其他工具调用;回答后由模型重新规划。该响应跳过确定性的 `after_model` 策略,反馈工具本身跳过 `before_tool` 和 `after_tool` 策略。
308- 
309-自行装配图时,由调用方准备 `model`、`tools`、`subagents` 和 checkpointer:
310- 
311-```python
312-from pathlib import Path
313- 
314-from langgraph.checkpoint.memory import InMemorySaver
315- 
316-from dataagent import read_yaml
317-from dataagent.core.graph import create_deep_agent
318-from dataagent.extensions.hitl import HITLMiddleware
319- 
320-path = Path("/path/to/plugin/.plugin.yaml")
321-middleware = HITLMiddleware.from_config(read_yaml(path)["hitl"], root=path.parent, namespace="main")
322-graph = create_deep_agent(
323- model=model,
324- tools=tools,
325- subagents=subagents,
326- middleware=[middleware],
327- checkpointer=InMemorySaver(),
328-)
329-```
330- 
331-显式装配需要调用方另行传入系统提示词。跨进程恢复时改用持久化 checkpointer,以同一线程和兼容策略恢复,见[一轮任务如何执行 · 人工反馈的执行与恢复](../development/2.3-execution.md#hitl-recovery)。
332- 
333-<a name="hitl-resume-actions"></a>
334- 
335-### 六阶段恢复动作
336- 
337-| 阶段 | `continue` | `replan` | `reject` |
338-| --- | --- | --- | --- |
339-| `before_agent` | 携带反馈进入后续模型流程 | 携带反馈继续且不自循环 | 转入结束路径并给出原因 |
340-| `before_model` | 携带反馈进入后续模型流程 | 携带反馈继续且不自循环 | 转入结束路径并给出原因 |
341-| `after_model` | 保留当前计划 | 跳过计划中的工具并返回模型 | 跳过计划中的工具并转入结束路径 |
342-| `before_tool` | 所有匹配策略通过后执行 | 跳过本次调用并将反馈交给模型 | 拒绝本次调用并将原因交给模型 |
343-| `after_tool` | 保留实际结果 | 保留实际结果并将反馈交给模型 | 调用已执行,将拒绝原因交给模型 |
344-| `after_agent` | 正常结束 | 携带反馈重新进入模型循环 | 带着拒绝原因结束 |
345- 
346-拒绝单次工具调用后,会话仍可继续;持续限制应由触发器或执行检查保证。状态阶段进入结束路径后仍会经过原生 `after_agent`。跳过计划时为相应调用 ID 生成错误 `ToolMessage`。before-tool 保留原调用参数。`return_direct` 工具在 `continue` 时直接返回,在 `replan` 或 `reject` 时转回模型。默认触发器可能在重新规划后再次提问;只问一次需要自定义条件。
347- 
348-待回答交互保存策略 ID、版本、阶段、问题和参数,恢复时必须兼容。工具完成后从 after-tool 恢复会复用实际结果;处理器和中断中的工具仍可能重放,外部副作用必须幂等。
349- 
350-<a name="a2a-api"></a>
351- 
352-## A2A
353- 
354-客户端接口 `A2ACaller`、`A2AResult` 和 `A2ACallError` 从 `dataagent.extensions.a2a` 导入。协议行为见 [A2A 参考 · 调用其他 Agent](3.4-a2a-reference.md#outbound)。服务端工厂从 `dataagent.server.a2a` 导入。导入 SDK 或 A2A 客户端不会加载服务端。
355- 
356-| 名称 | 给谁 | 作用 |
357-| --- | --- | --- |
358-| `A2ACaller(base_url, *, auth_token=None, timeout=None, context_id=None, http_client=None)` | 调用方 | 调用另一个 A2A 1.0 Agent。`await send(text, *, thread_id=None)` 返回 `A2AResult`。省略 `timeout` 时 HTTP 默认超时为 900 秒 |
359-| `A2AResult` | 调用方 | 结果:`text`、`context_id`、`task_id`、`state`,以及可选的 `request_id`、`root_run_id` |
360-| `A2ACallError` | 调用方 | 远端任务失败、取消或拒绝;本地 `error_code` 为 `TOOL_ERROR`,可选的 `remote_code`、`request_id`、`task_id`、`context_id`、`root_run_id` 用于远端诊断 |
361-| `create_a2a_server(runtime, *, host, port, auth_token=None, model=None, task_store=None, executor=None)` | 宿主 | 创建独立的 Starlette 应用。可替换模型、任务存储或执行器 |
362-| `run_a2a_server(runtime, *, host, port, auth_token=None)` | 宿主 | 用 uvicorn 运行上面的应用。命令行入口是 `dataagent serve-a2a` |
363- 
364-客户端从 Message 或 Task 响应中保留远端会话。不传 `thread_id` 时沿用调用实例的默认会话,可以用 `context_id` 初始化它。显式传入的 `http_client` 仍由调用方关闭。该接口发送文本并等待响应。结构化人工反馈通过[A2A 参考 · 原生 HITL 暂停与恢复](3.4-a2a-reference.md#a2a-hitl)提交。远端没有 DataAgent 诊断 metadata 时,任务与会话 ID 仍取自协议结果。将远端注册为 Agent 工具的步骤见[用 A2A 连接 Agent 并管理任务 · 让 DataAgent 调用其他 Agent](1.4-a2a-integration.md#outbound)。
@@ -0,0 +1,109 @@
1+# Python 扩展接口
2+ 
3+<a name="extension-api"></a>
4+ 
5+扩展从运行时上下文取得插件配置、模型和客户端。工具的最小实现见[编写可供 Agent 调用的工具](2.4-develop-tools.md)。
6+ 
7+<a name="agent-context"></a>
8+ 
9+## 工具的运行时上下文(`AgentContext`)
10+ 
11+工具通过 `runtime.context` 拿到它,SDK 用户不需要自己构造。
12+ 
13+| 成员 | 说明 |
14+| --- | --- |
15+| `get_model(name=None)` | 返回配置的模型。省略别名时用 `dataagent.model`。未知别名抛出 `ValueError` |
16+| `semantic_client` | 语义客户端,没有配置 `semantic` 时为 `None` |
17+| `session.outputs` | 本轮产物目录 |
18+| `home` | 已解析的 Home 路径,用于跨会话共享的资源 |
19+| `get_plugin_config(plugin_id)` | `plugins.config.<plugin_id>` 的副本。插件未启用时抛出 `ValueError` |
20+| `get_plugin_state(plugin_id)` | 当前会话图上下文中该插件的私有内存字典。只有已启用插件可以访问,字典随进程内上下文保存。Checkpoint 不含该状态,插件自己负责并发同步 |
21+ 
22+<a name="extension-models-and-services"></a>
23+ 
24+## 模型流与编译子代理工厂
25+ 
26+| 名称 | 作用 |
27+| --- | --- |
28+| `collect_model_stream(model, messages, **kwargs)` | 以流式调用模型并合成一条完整消息,保留工具调用、推理和用量。插件里调用 `AgentContext.get_model()` 返回的模型时用它 |
29+| `SubagentServices` | 编译子代理工厂 `factory(params, services)` 的第二个参数:`get_model`、`semantic_client`、`outputs_dir`、`run_hooks` |
30+ 
31+<a name="semantic-client"></a>
32+ 
33+## SemanticLayer 客户端
34+ 
35+`SemanticServiceClient` 从 `dataagent` 导入,是独立的同步 HTTP 客户端,不属于宿主或低层图接口。配置连接、证书并用自然语言验证服务,见 [连接语义层服务](../data-analysis/1.3-semantic-service.md)。
36+ 
37+<a name="_1"></a>
38+ 
39+### 构造与所有权
40+ 
41+| 使用方式 | 创建与关闭 |
42+| --- | --- |
43+| REST Server | 按 `semantic` 配置在进程生命周期内创建一个共享客户端,注入每个 Agent 的 `AgentContext`,由宿主关闭 |
44+| `create_agent(runtime)` | 未传 `semantic_client` 且配置了 `semantic` 时,由 SDK 创建;`Agent.close()` / `aclose()` 关闭它 |
45+| `create_agent(runtime, semantic_client=client)` | 借用调用方客户端,Agent 关闭时不关闭该连接;调用方负责关闭 |
46+| 工具中的 `runtime.context.semantic_client` | 借用宿主提供的客户端,未配置时为 `None`;工具不自行创建或关闭它 |
47+| `SemanticServiceClient.from_settings(runtime.settings.semantic)` 或直接构造 | 调用方持有客户端,负责 `close()`,也可用 `with` 管理 |
48+ 
49+`from_settings` 接收已解析的 `SemanticSettings`,使用其中的地址、Basic 认证、超时、TLS 和场景配置。直接调用 `SemanticServiceClient(base_url, ...)` 时,服务端证书校验默认开启(`verify=True`);通过 `from_settings` 构造时由配置的 `tls` 决定。
50+ 
51+配置的 `tls.verify_server` 默认 `false`。此时没有客户端证书和 `ciphers` 时不校验服务端证书。设为 `true` 时使用默认 SSL 上下文,提供 `ca_file` 时用该 CA。`client_cert` 与 `client_key` 必须成对,非空 `ciphers` 传给 `SSLContext.set_ciphers`。字段约束见[配置字段速查 · semantic](../operations/1.2-configuration-fields.md#semantic)。
52+ 
53+客户端使用同步 `httpx.Client`。异步工具应将调用放入 `asyncio.to_thread`,避免堵住事件循环。拥有连接的客户端在 `close()` 时拒绝新请求,并等待进行中的同步请求结束再关闭连接池。Basic 凭据及其 Base64 形式进入诊断脱敏列表,日志不应输出原始密钥。
54+ 
55+<a name="_2"></a>
56+ 
57+### 方法与路径
58+ 
59+请求路径以 `/api/semantic/v1/` 为前缀。检索表接口查询语义服务自身的元数据表;业务表接口查询已接入业务库中的表和列。
60+ 
61+| 方法 | HTTP 与路径后缀 |
62+| --- | --- |
63+| `semantic_retrieve` | `POST semantic/retrieve` |
64+| `get_table_list` | `GET advanced-search/table-list` |
65+| `get_table_columns_info` | `GET advanced-search/table-columns-info` |
66+| `get_columns_sample_values` | `GET advanced-search/column-value-info` |
67+| `semantic_search_columns` | `GET advanced-search/semantic-search-columns` |
68+| `get_joinable_tables` | `GET advanced-search/joinable-tables` |
69+| `get_table_relations_path` | `GET advanced-search/table-relations-path` |
70+| `vector_search_table_desc` | `GET advanced-search/vector-search-table-desc` |
71+| `vector_search_column_value` | `GET advanced-search/vector-search-column-value` |
72+| `sql_few_shots` | `GET advanced-search/sql-few-shots` |
73+| `search_fulltext` | `GET search/fulltext` |
74+| `search_basic` | `POST search/basic`,提交检索条件 |
75+| `search_dsl` | `GET search/dsl` |
76+| `search_entities(type_name, *, limit=200, offset=0)` | `GET search/basic`,按类型分页列出实体 |
77+| `get_entity_by_guid` | `GET entity/guid/{guid}` |
78+| `get_entity_by_unique_attribute` | `GET entity/uniqueAttribute/type/{type_name}` |
79+| `list_retrieval_tables` | `GET retrieval/tables`,语义层检索表清单 |
80+| `get_retrieval_table_schema` | `GET retrieval/tables/{table}/schema`,检索表结构 |
81+| `hybrid_table_columns(tables)` | `POST hybrid/table-columns`,批量取业务表的物理列 |
82+ 
83+<a name="_3"></a>
84+ 
85+### 参数约定
86+ 
87+定位参数从大到小排列,如库、表、关键词或查询。条数使用关键字参数 `limit`,实际 HTTP 参数按接口发送为 `topK` 或 `limit`;`max_depth`、`sample_count` 也只能按关键字传。
88+ 
89+列标识采用 `db.table.column`。`get_columns_sample_values(column_ids, *, sample_count=3)` 的 `sample_count` 范围为 0 到 100。`search_entities` 的 `limit` 范围为 1 到 200,`offset` 必须非负;返回实体列表。
90+ 
91+`semantic_retrieve(query, *, db_name=None, evidence=None)` 接收自然语言查询。提供可选参数时将 `db_name`、`evidence` 加入请求体,省略时保留服务的默认召回流程。`search_basic` 的 POST 条件检索与 `search_entities` 的 GET 按类型枚举是两种不同调用。
92+ 
93+<a name="_4"></a>
94+ 
95+### 场景视图
96+ 
97+配置 `semantic_scenario`,或直接构造时传入 `scenario=`,会在除 health 外的请求中设置 `X-Semantic-Scenario`。`with_scenario(scenario)` 返回共享同一连接池的客户端视图,用于临时切换该请求头。
98+ 
99+关闭场景视图不关闭连接池;拥有连接的原客户端仍负责关闭,并等待视图中进行的请求结束。继续使用现有客户端查询即可,无需为每个场景创建连接。
100+ 
101+<a name="sql-apis"></a>
102+ 
103+## 数据访问与 SQL 校验
104+ 
105+| 名称 | 作用 |
106+| --- | --- |
107+| `MCPConfig`、`MCPInfrastructureError` | 数据网关的 MCP SQL 连接参数类型和基础设施异常,见 [连接 MCP 服务 · 区分 NL2SQL 的 MCP 数据库连接](../data-analysis/1.2-mcp.md#nl2sql-mcp) |
108+| `build_sql_service`、`check_engine_driver`、`check_read_only_sql`、`check_sql` | 构建 SQL 服务、检查引擎依赖和 SQL 的数据网关接口 |
109+| `recall_database`、`RecallOptions`、`RecallError` | SQLite 数据库探索的异步入口、选项和错误类型 |
Adocs/zh/reference/3.1.2-python-hitl-api.md+99-0File content is under review, please try again later
Adocs/zh/reference/3.1.3-python-a2a-client.md+13-0File content is under review, please try again later
@@ -0,0 +1,119 @@
1+# Python 宿主与原生图接口
2+ 
3+本页供维护长驻宿主或自行装配 LangGraph 图的开发者查阅。应用进程中调用 Agent,见 [Python SDK 参考](3.1-python-api.md)。
4+ 
5+<a name="host-api"></a>
6+ 
7+## 构建长驻宿主(`dataagent.host`)
8+ 
9+宿主向其他客户端提供 Agent,并把监听、会话、资源刷新与日志放在自己的生命周期里管理。
10+ 
11+<a name="host-startup"></a>
12+ 
13+### 服务启动与扩展刷新
14+ 
15+| 名称 | 作用 |
16+| --- | --- |
17+| `server_listen(options=None)` | 读所选配置的 `server` 段,按 `prepare_runtime` 的环境规则展开 `$env{NAME}`(含 `options.env_file`),返回 `(host, port)`。没有 Home 配置文件且未显式指定配置时使用默认 `127.0.0.1:8790`。所选配置读取、环境展开或校验失败时抛出异常。`prepare_runtime` 失败时也能用 |
18+| `ServerSettings` | 监听地址和端口的校验模型 |
19+| `extension_revision(runtime)` | 扩展来源的 SHA-256 指纹,用来判断是否需要刷新。不含业务输入和会话状态 |
20+| `refresh_extensions(runtime)` | 重读插件、Hook 和 MCP 声明,返回新的 `PreparedRuntime`。保留模型、路径和启动策略。先编译成功再替换正在使用的 PreparedRuntime;进行中的调用继续用旧图 |
21+ 
22+<a name="host-diagnostics"></a>
23+ 
24+### 日志、错误与请求标识
25+ 
26+| 名称 | 作用 |
27+| --- | --- |
28+| `configure_logging(runtime=None)` | 宿主启动时配置统一的 `backend.log`。无 runtime 时也能记录早期启动错误 |
29+| `log_context` | 宿主用 ContextVar 绑定 `requestId`、`threadId`、`runId` 等关联字段,结束后重置 token |
30+| `log_event(...)` / `safe_interrupt_fields(...)` | 记录结构化事件,或对人工交互字段递归脱敏 |
31+| `register_log_secrets(values)` | 扩展或凭据刷新后追加脱敏值,保留旧运行凭据的脱敏能力 |
32+| `diagnostic_traceback(error, secrets=())` | 返回完整的脱敏堆栈,用于诊断日志,不作为公开错误响应 |
33+| `error_code(error)` | 把异常映射为固定错误码 |
34+| `ERROR_CODES` | 用于 `safe_error` 和 [REST API 参考 · SSE 错误码](3.2-rest-api.md#errors) 的固定错误码。异常类可通过 `error_code` 指定集合内的值 |
35+| `opaque_id(value, label)` | 校验并返回符合 `OPAQUE_ID_PATTERN` 的 ID |
36+| `OPAQUE_ID_PATTERN` | 客户端给的 ID(`threadId`、`runId`、用户)的正则:`[A-Za-z0-9][A-Za-z0-9_-]{0,127}`。宿主校验请求时用它 |
37+ 
38+<a name="host-sessions"></a>
39+ 
40+### 会话、图和 AG-UI 适配
41+ 
42+- `create_agent(..., session=, input_workspaces=, extension_revision=)`:
43+ - `session` 指定默认会话,必须是当前 Home 和用户下的标准会话路径,否则立即报错。
44+ - `input_workspaces=None` 时,新会话用配置默认值,已有会话沿用保存值;显式元组(包括 `()`)必须和已有绑定的路径及顺序一致。名称不参与比较。
45+ - `extension_revision` 是上面 `extension_revision(runtime)` 的值,用来让 Skill 缓存跟随扩展刷新。
46+- `runtime.paths.open_session(thread_id, *, create, output_dir=None, input_workspaces=None)`:登记或恢复会话,返回 `(SessionPaths, workspaces)`,可传给上面两个参数。`create=False` 时会话不存在返回 `None`。目录规则见 [查找会话产物与恢复会话](../operations/2.2-sessions-and-outputs.md)。
47+- `agent.as_agui(*, name="dataagent", **kwargs)`:创建 AG-UI 适配器,执行 `run(input)` 时按 `input.thread_id` 选择会话。每个请求用新的适配器。
48+- `agent.graph_for(thread_id)`:取得已有会话的原生图,例如读状态 `graph_for(t).aget_state(config)`。会话不存在时抛出 `ValueError`。`agent.graph` 是默认会话的图,首次访问会创建默认会话。
49+ 
50+<a name="a2a-server-api"></a>
51+ 
52+### 独立 A2A 服务
53+ 
54+工厂从 `dataagent.server.a2a` 导入。命令行用法见 [A2A 参考](3.4-a2a-reference.md)。
55+ 
56+| 名称 | 作用 |
57+| --- | --- |
58+| `create_a2a_server(runtime, *, host, port, auth_token=None, model=None, task_store=None, executor=None)` | 创建独立的 Starlette 应用。可替换模型、任务存储或执行器 |
59+| `run_a2a_server(runtime, *, host, port, auth_token=None)` | 用 uvicorn 运行上面的应用。命令行入口是 `dataagent serve-a2a` |
60+ 
61+<a name="lowlevel-api"></a>
62+ 
63+## 装配原生 LangGraph 图(`dataagent.lowlevel`)
64+ 
65+`build_graph` 打开一个会话并返回绑定该会话的原生 LangGraph `CompiledStateGraph`。构建时校验已有路径或按该会话登记路径。调用方在调用图时传递上下文,负责语义客户端的生命周期。需要按线程路由和复用多个会话图时,使用 `create_agent`。
66+ 
67+```python
68+from dataagent import AgentContext, load_mcp_tools
69+from dataagent.lowlevel import build_graph
70+ 
71+context = AgentContext(runtime, semantic_client=client)
72+graph = build_graph(
73+ runtime,
74+ context=context,
75+ checkpointer=checkpointer,
76+ mcp_tools=await load_mcp_tools(runtime),
77+)
78+result = await graph.ainvoke(inputs, config, context=context)
79+```
80+ 
81+```text
82+build_graph(runtime, *, checkpointer=None, model=None, session=None,
83+ input_workspaces=None, mcp_tools=None, extension_revision=None, context=None)
84+```
85+ 
86+- 省略 `session` 和 `context` 时用名为 `sdk` 的会话。
87+- 配置了 MCP 却没传 `mcp_tools` 时失败。配置了语义服务、而 `context` 没有语义客户端时失败。
88+- `dataagent.entry` 有值时只挂该编译型入口。
89+- 额外的 LangChain callback 放在调用的 `config["callbacks"]`,或用 `graph.with_config(callbacks=[...])`。
90+ 
91+`dataagent.lowlevel` 随 LangGraph 演进。接口导出见 [dataagent](../../../dataagent/__init__.py)、[dataagent.host](../../../dataagent/host.py) 和 [dataagent.lowlevel](../../../dataagent/lowlevel.py) 的 `__all__`。
92+ 
93+<a name="explicit-hitl-assembly"></a>
94+ 
95+### 手动装配人工交互
96+ 
97+自行装配图时,由调用方准备 `model`、`tools`、`subagents` 和 checkpointer:
98+ 
99+```python
100+from pathlib import Path
101+ 
102+from langgraph.checkpoint.memory import InMemorySaver
103+ 
104+from dataagent import read_yaml
105+from dataagent.core.graph import create_deep_agent
106+from dataagent.extensions.hitl import HITLMiddleware
107+ 
108+path = Path("/path/to/plugin/.plugin.yaml")
109+middleware = HITLMiddleware.from_config(read_yaml(path)["hitl"], root=path.parent, namespace="main")
110+graph = create_deep_agent(
111+ model=model,
112+ tools=tools,
113+ subagents=subagents,
114+ middleware=[middleware],
115+ checkpointer=InMemorySaver(),
116+)
117+```
118+ 
119+显式装配需要调用方另行传入系统提示词。跨进程恢复时改用持久化 checkpointer,以同一线程和兼容策略恢复,见[一轮任务如何执行 · 人工反馈的执行与恢复](../development/2.3-execution.md#hitl-recovery)。
@@ -1,12 +1,14 @@
1# REST API 参考1# REST API 参考
2 2 
3-通过 `dataagent serve` 启动控制面。默认地址为 `http://127.0.0.1:8790`,由所选 YAML 的 `server.host` 和 `server.port` 配置。Web 工作台将 `/api/v1/*` 转发到这个服务。REST 没有内置的访问令牌校验。需要对回环地址之外提供服务时,请先阅读[安全说明](../getting-started/2.4-security.md)。3+通过 `dataagent serve` 启动控制面。默认地址为 `http://127.0.0.1:8790`,由所选 YAML 的 `server.host` 和 `server.port` 配置。REST 没有内置的访问令牌校验。需要对回环地址之外提供服务时,请先阅读[安全说明](../getting-started/2.4-security.md)。
4+ 
5+本页涵盖应用接入需要的路由、请求字段、响应与事件。首次发起对话见[HTTP 接入指南](1.3-http-ag-ui.md)。
4 6 
5<a name="envelope"></a>7<a name="envelope"></a>
6 8 
7-## 信封9+## 响应结构
8 10 
9-JSON 成功响应和已处理的 HTTP 错误采用以下信封:11+JSON 成功响应和已处理的 HTTP 错误采用以下结构:
10 12 
11```json13```json
12{"success": true, "data": {}}14{"success": true, "data": {}}
@@ -16,39 +18,20 @@ JSON 成功响应和已处理的 HTTP 错误采用以下信封:
16{"success": false, "error": {"code": "RESOURCE_NOT_FOUND", "message": "Route not found."}}18{"success": false, "error": {"code": "RESOURCE_NOT_FOUND", "message": "Route not found."}}
17```19```
18 20 
19-`POST /api/v1/runs` 成功时返回 HTTP 200 和 SSE 事件流。取消成功时返回空的 HTTP 204。健康接口的 `HEAD` 只返回状态和响应头。下文的示例展示的是 `data` 内容。21+`POST /api/v1/runs` 成功时返回 HTTP 200 和 SSE 事件流。取消成功时返回空的 HTTP 204。健康接口的 `HEAD` 只返回状态和响应头。下文标明为完整响应的示例包含外层字段,其余 JSON 示例展示 `data` 内容。
22+ 
23+启动控制面后运行 `curl -i http://127.0.0.1:8790/ready`。就绪时应返回 HTTP 200,JSON 中 `success` 为 `true`,`data.status` 为 `ready`。用 `curl -I` 检查时只会看到响应头。
20 24 
21<a name="health-and-identity"></a>25<a name="health-and-identity"></a>
22 26 
23-## 健康与身份27+## 健康检查
24 28 
25| 方法 | 路径 | 响应 |29| 方法 | 路径 | 响应 |
26| --- | --- | --- |30| --- | --- | --- |
27-| GET, HEAD | `/healthz` | 200,包含 `status: "ok"` 和 `conversation`。 |31+| GET, HEAD | `/healthz` | HTTP 200 表示进程可达。 |
28-| GET, HEAD | `/ready` | 200,包含 `status: "ready"` 和与 `/healthz` 相同的 `conversation` 字段。引擎不可用时返回 503。 |32+| GET, HEAD | `/ready` | HTTP 200 表示已就绪。引擎不可用时返回 503。 |
29-| GET | `/api/v1/me` | `user.id` 和 `user.displayName` 是服务端本地用户(`--user`)。没有运行时配置时两者为 `default`。`workspace` 固定为 `{"id":"local","name":"Local"}`。 |
30-| GET | `/api/v1/capabilities` | `interaction.resume`、`conversation.memory` 和 `artifact.list` 为 true。`artifact.export` 为 false。 |
31 33 
32-引擎不可用时,`/healthz` 的 `conversation` 只有 `{"ready": false}`。就绪时返回的数据形如:34+就绪时,`GET /ready` 返回 `success: true`、`data.status: "ready"` 和 `data.conversation.ready: true`。
33- 
34-```json
35-{
36- "status": "ok",
37- "conversation": {
38- "ready": true,
39- "protocol": "dataagent",
40- "instanceId": "server-1",
41- "model": "example-model",
42- "plugins": ["common"],
43- "home": "/absolute/path/to/.dataagent",
44- "entry": null,
45- "user": "default",
46- "timeoutSeconds": 900
47- }
48-}
49-```
50- 
51-用 `conversation.ready` 判断就绪状态。`instanceId` 标识进程,`timeoutSeconds` 来自 `server.run_timeout_seconds`。`entry` 返回配置值,接口不会判断该值是否能解析为编译型子代理。响应不包含输入目录、状态目录或配置正文。
52 35 
53<a name="sessions-and-runs"></a>36<a name="sessions-and-runs"></a>
54 37 
@@ -81,7 +64,7 @@ JSON 成功响应和已处理的 HTTP 错误采用以下信封:
81 64 
82### 读取会话65### 读取会话
83 66 
84-`GET /api/v1/sessions/{threadId}` 在列表字段上增加 `messages`、`pendingInteractions` 和 `notice`。消息取已保存的检查点,没有检查点时读取该线程的最新图状态。会话运行中也可读取。`pendingInteractions` 只包含能通过 REST 回答的交互,具体结构和答复方式见[AG-UI 事件与运行契约 · 等待用户回答](3.3-ag-ui-events.md#hitl)。`notice` 是提示文本或 `null`。会话失败或中断时,提示会说明是否恢复了检查点。67+`GET /api/v1/sessions/{threadId}` 在列表字段上增加 `messages`、`pendingInteractions` 和 `notice`。消息取已保存的检查点,没有检查点时读取该线程的最新图状态。会话运行中也可读取。`pendingInteractions` 只包含能通过 REST 回答的交互,具体结构和答复方式见[等待用户回答](#hitl)。`notice` 是提示文本或 `null`。会话失败或中断时,提示会说明是否恢复了检查点。
85 68 
86会话不存在或属于其他用户时返回 404。当前用户的会话绑定无法打开时返回 409。69会话不存在或属于其他用户时返回 404。当前用户的会话绑定无法打开时返回 409。
87 70 
@@ -93,11 +76,100 @@ JSON 成功响应和已处理的 HTTP 错误采用以下信封:
93 76 
94<a name="conversation"></a>77<a name="conversation"></a>
95 78 
96-## 对话79+## 对话与 AG-UI 事件
97 80 
98-`POST /api/v1/runs` 接收一条 AG-UI 请求,详见[AG-UI 事件与运行契约 · 请求](3.3-ag-ui-events.md#request)和[用 HTTP 发起对话并接收 AG-UI 事件](1.3-http-ag-ui.md)。成功时返回 `text/event-stream`,并带上 `Cache-Control: no-cache` 和 `X-Accel-Buffering: no`。81+发送 `POST /api/v1/runs` 发起一轮对话。事件流建立前,校验失败返回 422,已有运行或运行 ID 冲突返回 409。完整命令和首次运行示例见[HTTP 接入指南](1.3-http-ag-ui.md)。
99 82 
100-事件流开始前,请求体校验失败返回 422。同一会话已有运行或 `runId` 正在使用等冲突返回 409。HTTP 200 的流开始后,运行失败通过[AG-UI 事件与运行契约 · 客户端应如何处理](3.3-ag-ui-events.md#terminal-events)报告。客户端断开时,服务取消上游流,并将未完成的会话标记为中断。83+<a name="request"></a>
84+ 
85+### 请求字段
86+ 
87+请求体为 JSON。普通对话只提交本轮的新消息,服务端根据 `threadId` 加载历史。
88+ 
89+| 字段 | 约束 |
90+| --- | --- |
91+| `threadId`、`runId` | 长度 1–128,首字符为 ASCII 字母或数字,其余字符还可使用 `_` 和 `-` |
92+| `messages` | 普通对话恰好一条消息,包含 `id`、`role: "user"` 和非空白文本 `content`;提交人工回答时发送 `[]` |
93+| `state` | 可省略,或发送 `null`、`{}` |
94+| `tools`、`context`、`forwardedProps` | 必填,分别发送空的 `[]`、`[]`、`{}` |
95+| `answers` | 提交[人工回答](#hitl)时发送非空的 `interruptId` 到文本回答的映射 |
96+| `resume`、`parentRunId` | 客户端省略;恢复会话沿用 `threadId`,恢复人工交互使用 `answers` |
97+ 
98+服务端拒绝未知顶层字段、客户端注入的状态、工具和上下文,以及把子代理消息作为用户消息提交。模型、插件和工作区由服务配置决定。
99+ 
100+每个会话同时只接受一轮。活跃的 `runId` 在同一服务进程内必须唯一,即便请求的线程不同。服务拒绝重用会话最后一次记录的 `runId`,也拒绝使用已加载历史里的消息 ID 进行编辑或重放。继续对话时为运行和消息生成新 ID。
101+ 
102+<a id="sse-response"></a>
103+ 
104+<a name="terminal-events"></a>
105+ 
106+### 读取 SSE 事件
107+ 
108+成功响应为 HTTP 200 和 `text/event-stream`,响应头含 `Cache-Control: no-cache` 和 `X-Accel-Buffering: no`。从每个 SSE `data:` 帧读取 JSON。
109+ 
110+<a id="completed"></a>
111+ 
112+`RUN_STARTED` 标识本轮。可用文本事件和工具事件更新进度。正常完成后,按顺序收到清空待回答项的 `CUSTOM` 事件、最后的 `MESSAGES_SNAPSHOT` 和 `RUN_FINISHED`。终止事件可包含 `metadata.durationMs`。
113+ 
114+| 事件或结果 | 客户端应如何处理 |
115+| --- | --- |
116+| `RUN_FINISHED`,`metadata.status="completed"` | 用最后的 `MESSAGES_SNAPSHOT` 更新会话。 |
117+| `RUN_FINISHED`,`metadata.status="waiting_for_input"` | 展示待回答项,用同一会话提交回答。 |
118+| `RUN_ERROR`,`code="CANCELLED"` | 显示已停止。下一轮可以沿用 `threadId`。 |
119+| 其他 `RUN_ERROR` | 保留已显示的部分输出,按 `code` 处理。下一轮使用新 `runId`。 |
120+| 断开且未收到终止事件 | 重新读取[会话详情](#session-detail)确认状态,再决定是否提交下一轮。 |
121+ 
122+<a name="hitl"></a>
123+ 
124+### 等待用户回答
125+ 
126+HITL 暂停也用 `RUN_FINISHED` 结束本轮流,但 `metadata.status="waiting_for_input"`,
127+表示等待回答。最终消息快照前的 `CUSTOM name="human_feedback"` 携带当前全部待回答项:
128+ 
129+```json
130+{"type":"CUSTOM","name":"human_feedback","value":[
131+ {"type":"human_feedback","interruptId":"<id>","message":"请选择身份字段","options":["user_id","device_id"]}
132+]}
133+```
134+ 
135+`options` 供展示,用户也可以输入文本;回答无效时附带可选的 `validationError`。
136+客户端用数组替换当前的待回答项。通过同一个 `POST /api/v1/runs` 提交非空的 `answers`,沿用 `threadId`、使用新 `runId`,并发送空的 `messages`。
137+ 
138+```json
139+{
140+ "threadId": "thread-001",
141+ "runId": "run-002",
142+ "messages": [],
143+ "answers": {"<id>": "user_id"},
144+ "tools": [],
145+ "context": [],
146+ "forwardedProps": {}
147+}
148+```
149+ 
150+将 `<id>` 换成事件里的 `interruptId`。多个并行交互可分批回答。等待回答时发送新消息,或提交未知、已解决的交互 ID,会收到 HTTP 409。空白回答会再次暂停,待回答项带有 `validationError`。
151+ 
152+刷新客户端或重启服务后,可从 `GET /api/v1/sessions/{threadId}` 的 `pendingInteractions` 恢复待回答项。用户思考期间没有活动 HTTP 流,不计入单轮执行超时。通过 A2A 发起的人工交互须在 [A2A 参考 · 原生 HITL 暂停与恢复](3.4-a2a-reference.md#a2a-hitl) 中恢复。
153+ 
154+<a name="errors"></a>
155+ 
156+### SSE 错误码
157+ 
158+`RUN_ERROR.code` 取下表中的固定值。服务端脱敏 `message`,并限制其长度为 1500 个字符。
159+ 
160+| `code` | 含义 |
161+| --- | --- |
162+| `TIMEOUT` | 超过 `server.run_timeout_seconds`,或模型请求超时 |
163+| `CANCELLED` | 客户端调用了 `POST /api/v1/runs/{runId}/cancel` |
164+| `LOOP_DETECTED` | 循环检测终止了本轮 |
165+| `LIMIT_EXCEEDED` | 超过 `model_calls_per_agent` 或 `tool_calls_per_agent` |
166+| `INCOMPLETE_STREAM` | 上游没有终止事件、重复终止,或终止后仍有事件 |
167+| `CONFIG_ERROR` | 配置无效 |
168+| `MODEL_ERROR` | 模型服务返回错误 |
169+| `TOOL_ERROR` | 工具或远端 Agent 调用失败 |
170+| `INTERNAL_ERROR` | 其他错误 |
171+ 
172+客户端应按 `code` 分支。
101 173 
102<a name="outputs"></a>174<a name="outputs"></a>
103 175 
@@ -109,8 +181,13 @@ JSON 成功响应和已处理的 HTTP 错误采用以下信封:
109 181 
110`GET /api/v1/sessions/{threadId}/outputs` 返回普通文件,按 `modifiedAt` 降序排列,时间相同再按 `path` 降序排列。路径相对会话产物目录,`size` 以字节计。182`GET /api/v1/sessions/{threadId}/outputs` 返回普通文件,按 `modifiedAt` 降序排列,时间相同再按 `path` 降序排列。路径相对会话产物目录,`size` 以字节计。
111 183 
184+完整响应示例
185+ 
112```json186```json
113-{"files": [{"path": "notes.txt", "size": 12, "modifiedAt": "2026-10-15T00:00:00+00:00"}]}187+{
188+ "success": true,
189+ "data": {"files": [{"path": "notes.txt", "size": 12, "modifiedAt": "2026-10-15T00:00:00+00:00"}]}
190+}
114```191```
115 192 
116列表跳过符号链接和内部路径 `artifacts/conversation_history`、`artifacts/large_tool_results`。会话存在但产物目录尚不存在时返回空列表。产物路径是符号链接或不是目录时返回 409。会话不存在或属于其他用户时返回 404。193列表跳过符号链接和内部路径 `artifacts/conversation_history`、`artifacts/large_tool_results`。会话存在但产物目录尚不存在时返回空列表。产物路径是符号链接或不是目录时返回 409。会话不存在或属于其他用户时返回 404。
@@ -119,10 +196,15 @@ JSON 成功响应和已处理的 HTTP 错误采用以下信封:
119 196 
120### 预览 UTF-8 文本197### 预览 UTF-8 文本
121 198 
122-`GET /api/v1/sessions/{threadId}/outputs/preview?path=notes.txt` 接收经过 URL 编码的非空相对路径,返回:199+`GET /api/v1/sessions/{threadId}/outputs/preview?path=notes.txt` 接收经过 URL 编码的非空相对路径。
200+ 
201+完整响应示例
123 202 
124```json203```json
125-{"type": "file", "path": "notes.txt", "content": "Sample notes", "truncated": false}204+{
205+ "success": true,
206+ "data": {"type": "file", "path": "notes.txt", "content": "Sample notes", "truncated": false}
207+}
126```208```
127 209 
128读取上限为 64 KiB。更长的文件返回 `truncated: true`,内容以完整的 UTF-8 字符结尾。绝对路径、`..` 路径分量或 NUL 字符返回 400。文件不存在、经过符号链接、被排除或不是普通文件时返回 404。预览范围内有二进制数据或无效 UTF-8 时返回 415。210读取上限为 64 KiB。更长的文件返回 `truncated: true`,内容以完整的 UTF-8 字符结尾。绝对路径、`..` 路径分量或 NUL 字符返回 400。文件不存在、经过符号链接、被排除或不是普通文件时返回 404。预览范围内有二进制数据或无效 UTF-8 时返回 415。
Mdocs/zh/reference/3.3-ag-ui-events.md+3-128File content is under review, please try again later
Mdocs/zh/reference/3.4-a2a-reference.md+37-35File content is under review, please try again later
Mmkdocs.yml+13-6File content is under review, please try again later