OpenAPI usage guide and examples
This guide is for integration developers and describes how to call ADA APIs for agents, skills, sessions, models, and file transit. The quick start demonstrates session creation and multi-turn conversations. Seven examples cover request parameters, key responses, and call sequences for resource management, interactions, model configuration, connection recovery, and file uploads.
API types and combinations
Agents store responsibilities and configurations and can reference skills. Skills store reusable rules or capabilities. Sessions support multi-turn interactions between users and agents. Server-Sent Events (SSE) let you continuously receive text, interaction notifications, and turn results. Start with the quick start to learn text conversations and multi-turn continuation, then use resource management, interaction, model configuration, or file transit APIs as needed.
API names link to parameter descriptions and debugging pages in the OpenAPI portal. For information about credentials and authentication, see API overview and authentication.
Type and purpose | API name | How to combine APIs |
Agent management | Create or reuse an agent and pass its | |
Skill management | Save reusable rules or capabilities as a skill and reference it through the agent's | |
Session management | Create a session and save its | |
Messages and recovery | Prompt submits new text requests. Load reopens history or recovers interrupted output. Both use SSE. | |
Execution and interactions | After you receive an interaction notification, reply with the user's answers or approval decision. Cancel execution when you need to stop the current task. | |
Model configuration | Query available models, then set and verify the session model for subsequent calls in that session. | |
File transit | Request upload authorization, upload the file using the returned information, and then check its status. This process is independent of session text input. |
The examples use SQL development tasks and resource names such as ecommerce-sales-sql for illustration. For other business scenarios, replace the resource configuration and the content in Params.prompt[].text. The call relationships remain the same.
Quick start: Create a session and have a multi-turn conversation
The following example develops SQL for a daily e-commerce report. The project ecommerce_analytics needs to use the order detail table dwd_trade_order_detail to aggregate, by shop, the amounts paid on 2026-10-20 and prepare query SQL for the target table ads_shop_sales_1d. The caller provides table schemas, sample data, and aggregation rules. The API returns SQL text and explanations. SQL execution and writes to the target table take place in the data development environment.
First, complete a text conversation. Then add the order count in the same session. Finally, load history and ask another question after closing the page. If you already have an agent, start at step 2. For your first integration, create an agent in step 1.
Prepare API calls
Streaming calls require an Alibaba Cloud OpenAPI (POP) client that supports SSE and V3 signatures (ACS3-HMAC-SHA256). An earlier signature version may return UnsupportedSignatureVersion. Setting only Accept: text/event-stream does not replace a signature upgrade. For the signature specification, see Request syntax and signature method V3. Place business parameters in query or formData as specified by each API. Serialize structured objects only once to avoid repeated encoding.
Use a POP signing client with the identity, region, and endpoint configured. Set the product to Ada and the version to 2026-07-01. In each step, set the specified API name as Action. The request JSON shows only business parameters. Send them in query or formData as specified by the API, and serialize structured parameters only once as required by the SDK. RegionId is not added to these business JSON objects.
This guide uses consistent example values: the agent is ecommerce-sales-sql, the skill is ecommerce-sales-rules, and the first session created is 20261020a1b24c3d8e5f012345678901. Requests, responses, and subsequent calls use the same values to demonstrate the data flow. In actual calls, use the names of currently accessible resources and the actual service-generated IDs from the corresponding responses. Id is generated by the caller for each new call to correlate the response.
The client reads credentials securely, for example, from the environment variables ALIBABA_CLOUD_ACCESS_KEY_ID=<YOUR_ACCESS_KEY_ID>, ALIBABA_CLOUD_ACCESS_KEY_SECRET=<YOUR_ACCESS_KEY_SECRET>. When using temporary credentials, also configure ALIBABA_CLOUD_SECURITY_TOKEN=<YOUR_SECURITY_TOKEN>. These values are placeholders. Do not write actual credentials to code or logs.
1. Create or reuse an agent
Name is required. SystemPrompt defines the output scope. DisplayName helps identify the agent. The example name must be unique within the current tenant. If a resource with the same name already exists, first use GetAgent to verify and reuse it.
Call CreateAgent to create an agent that generates SQL for daily reports.
{
"Name": "ecommerce-sales-sql",
"DisplayName": "E-commerce daily sales SQL development agent",
"SystemPrompt": "Generate reviewable e-commerce daily sales SQL from the schemas, sample data, and aggregation rules provided by the user. Return only SQL text, explanations of the rules, and validation suggestions. Do not execute SQL."
}Example key response fields (excerpt):
{
"Success": true,
"Name": "ecommerce-sales-sql"
}Check that Success=true and save the returned Name, which is ecommerce-sales-sql in this example. In the next step, use the name, not AgentId.
2. Create a session
Pass ecommerce-sales-sql from the previous step to Params._meta.agent.agentName. This example uses the default approval mode, default, so you do not need to explicitly pass the configuration.
Call CreateAgentSession:
{
"Jsonrpc": "2.0",
"Id": "sales-session-create-01",
"Params": {
"_meta": {
"agent": {
"agentName": "ecommerce-sales-sql"
}
}
}
}Example key response fields (excerpt; service-generated IDs are for illustration only):
{
"Success": true,
"JsonRpcResponse": {
"jsonrpc": "2.0",
"id": "sales-session-create-01",
"result": {
"sessionId": "20261020a1b24c3d8e5f012345678901"
}
}
}Check that Success=true and save JsonRpcResponse.result.sessionId, which is 20261020a1b24c3d8e5f012345678901 in this example. Reuse this value when submitting subsequent requests, revising SQL, and loading history.
3. Send text and read the streaming response
Place the table schemas, sample data, and aggregation definitions in Params.prompt[].text. This request asks for SQL to aggregate sales amounts.
In this example, each row is a deduplicated order detail. pay_amount is the actual amount paid for that detail, in yuan. All fields are non-null. Refunds are not deducted, and the total order amount is not counted repeatedly. Put the project, table names, date, and aggregation rules in Params.prompt[].text. No additional business parameter fields are needed.
Call PromptAgentSession:
{
"Jsonrpc": "2.0",
"Id": "sales-sql-generate-01",
"Params": {
"sessionId": "20261020a1b24c3d8e5f012345678901",
"prompt": [
{
"type": "text",
"text": "Write a shop daily sales aggregation query for project ecommerce_analytics. The query result will be used for target table ads_shop_sales_1d. The business date is 2026-10-20. Each row in source table dwd_trade_order_detail is a deduplicated order detail record. The fields are detail_id STRING, order_id STRING, shop_id STRING, pay_amount DECIMAL(18,2), order_status STRING, and ds STRING. pay_amount is the actual amount paid for each detail in yuan, not an order-level total repeated across records. All fields are non-null. ds is the business date in YYYY-MM-DD format. Include only details with ds=2026-10-20 and order_status=PAID, and sum pay_amount by shop_id without deducting refunds. The output fields are business_date, shop_id, and sales_amount. The sample details are (D001,O001,SHOP001,100.00,PAID,2026-10-20), (D002,O001,SHOP001,40.00,PAID,2026-10-20), (D003,O002,SHOP002,200.00,PAID,2026-10-20), (D004,O003,SHOP001,90.00,UNPAID,2026-10-20), and (D005,O004,SHOP002,999.00,PAID,2026-10-19). Return an aggregation SELECT query, the aggregation rules, and the expected results for the sample data. Do not execute the query or create or write the target table."
}
]
}
}The response uses SSE. The following examples show the JSON content of data for two event types, formatted for readability. Text is typically returned in multiple chunks.
Example text chunk:
{
"Jsonrpc": "2.0",
"Method": "session/update",
"Params": {
"sessionId": "20261020a1b24c3d8e5f012345678901",
"update": {
"sessionUpdate": "agent_message_chunk",
"content": {
"type": "text",
"text": "SELECT '2026-10-20' AS business_date,\n"
}
}
}
}Concatenate Params.update.content.text in order to obtain the complete answer. Use only content from agent_message_chunk with type=text as the answer text for this turn.
Example normal completion of the current Prompt:
{
"Jsonrpc": "2.0",
"Id": "sales-sql-generate-01",
"Result": {
"stopReason": "end_turn"
}
}When you receive Result.stopReason=end_turn for this request and the target turn, confirm that generation for this turn is complete. HTTP 200, a closed connection, or a single text chunk does not replace the completion result. If an interaction occurs during execution, follow example 3. If the connection closes unexpectedly, recover as described in example 5.
The expected business output is shown below. The SQL is illustrative. The model may return an equivalent query, which you should check against the aggregation definitions.
SELECT
'2026-10-20' AS business_date,
shop_id,
SUM(pay_amount) AS sales_amount
FROM ecommerce_analytics.dwd_trade_order_detail
WHERE ds = '2026-10-20'
AND order_status = 'PAID'
GROUP BY shop_id;
|
|
|
2026-10-20 | SHOP001 | 140.00 |
2026-10-20 | SHOP002 | 200.00 |
Check the generated result: the SQL filters by the business date and the PAID status and sums detail amounts by shop. Unpaid details and details for other dates in the sample are excluded. Save the SQL from the complete answer as development input for ads_shop_sales_1d. The table above contains expected values for the sample. The API did not query the source table or write to the target table.
4. Reuse the session for a multi-turn conversation
Continue to call PromptAgentSession for new user input. For example, after SQL generation completes in the first turn, ask to add the paid order count. Reuse 20261020a1b24c3d8e5f012345678901, set a new Id for the new call, and submit only the additional request. You do not need to recreate the session, call Load, or include the entire history in prompt again.
Call PromptAgentSession:
{
"Jsonrpc": "2.0",
"Id": "sales-sql-add-order-count-01",
"Params": {
"sessionId": "20261020a1b24c3d8e5f012345678901",
"prompt": [
{
"type": "text",
"text": "Add paid_order_count to the previous shop daily sales SQL. Use COUNT(DISTINCT order_id) to count paid orders. Keep project ecommerce_analytics, date 2026-10-20, status PAID, and the sales amount rules unchanged. Return the complete SQL and list the field to add to ads_shop_sales_1d. Do not modify the actual table schema."
}
]
}
}This response also uses SSE. Concatenate the text as described in step 3. After you receive the normal completion result for the current turn corresponding to sales-sql-add-order-count-01, check the revised SQL. It should add COUNT(DISTINCT order_id) AS paid_order_count while keeping the original date, payment status, and sales amount definitions unchanged.
Expected results:
|
|
|
|
2026-10-20 | SHOP001 | 140.00 | 1 |
2026-10-20 | SHOP002 | 200.00 | 1 |
The two details for SHOP001 belong to the same order, so the order count is 1. Do not count it as 2 based on the number of details. Save the complete SQL returned in this turn as the current revision. For additional requests, continue to use the same session ID, 20261020a1b24c3d8e5f012345678901, when calling PromptAgentSession. Wait for each turn to finish before submitting new text.
5. Load history and continue the session
Assume that you confirmed completion in step 4 and then closed the page. When you reopen it, first retrieve the saved session ID, 20261020a1b24c3d8e5f012345678901, and use LoadAgentSession to read history and restore the display of the previous requests and SQL.
Call LoadAgentSession:
{
"Jsonrpc": "2.0",
"Id": "sales-history-reopen-01",
"Params": {
"sessionId": "20261020a1b24c3d8e5f012345678901"
}
}LoadAgentSession returns SSE. Rebuild the history view by event type. Do not append replayed content again as a new answer. Loading history does not resubmit the SQL generation task.
After viewing history, ask for an explanation of the output fields in the current SQL. Call PromptAgentSession again using the original session ID, 20261020a1b24c3d8e5f012345678901:
{
"Jsonrpc": "2.0",
"Id": "sales-sql-explain-01",
"Params": {
"sessionId": "20261020a1b24c3d8e5f012345678901",
"prompt": [
{
"type": "text",
"text": "Based on the current shop daily sales SQL, explain the meanings, aggregation rules, and sample values for the four output fields business_date, shop_id, sales_amount, and paid_order_count. The explanations will be used as field descriptions for ads_shop_sales_1d in project ecommerce_analytics. Use business date 2026-10-20 and the existing sample data. Do not modify or execute SQL."
}
]
}
}Read the text for this turn and its corresponding normal completion result. The expected answer should explain business_date, shop_id, sales_amount, and paid_order_count using the preceding sample values. Continue to use the same session ID for subsequent questions.
If you have saved 20261020a1b24c3d8e5f012345678901 and do not need to display history, you can submit a new Prompt directly. Load is not a prerequisite for every turn. If the previous connection closed unexpectedly during generation and you have not confirmed the turn result, first follow example 5 to recover and verify the original turn. Do not use only the Load end_turn to conclude that the original generation succeeded, and do not resend the original request.
Current situation | API to use | Key actions |
The previous turn has finished and you have a new request |
| Use the same |
Reopen a completed session to view history |
| Load restores the display. Continue to use the original |
Output from the previous turn was interrupted and the result is unknown |
| First recover and verify the target turn. Do not resend Prompt to determine whether it executed. |
API combinations and complete examples
Choose a process for your business needs. Submit each request, read its response, and pass the returned values to the next step. Each example can be used independently except for explicitly stated dependencies.
The following examples retain business-related response fields and omit diagnostic fields such as RequestId. In actual integrations, retain RequestId for troubleshooting. Read each response type as follows:
Response type | Where to read values | How to pass values to subsequent calls |
JSON responses for agents, skills, file transit, and model lists | Top-level fields such as | Map values to the next request as shown in each example. Preserve field capitalization. |
JSON responses from other non-streaming session APIs |
| For example, pass |
|
| Array elements retain original keys such as |
SSE responses from Prompt and Load | First parse each event's | Use text for display. Pass interaction IDs, turn IDs, and recovery positions separately as described below. |
In session requests, set Jsonrpc to 2.0 and use a new Id for each new call. Id corresponds to JsonRpcResponse.id in a non-streaming response (for ListAgentSessions, use JsonRpcResponse.Id) or to the SSE result frame's Id. It is used only to correlate calls. Do not use it as a session ID, interaction ID, or turn ID.
Example 1: Query and create a skill and bind it to an agent
When a team develops multiple sales reports, reusable metric definitions can be saved as a skill and bound to an agent. New sessions can reuse these rules.
Skills store reusable rules or capabilities. Agents reference skills through Skills[].name. The two resource types are managed independently, so you do not need to recreate them for each session. This example uses ecommerce-sales-sql from the quick start. You can also query and select an existing resource first.
1. Query resources: ListAgents and ListSkills
Call ListAgents to query agents:
{
"Q": "ecommerce-sales-sql",
"Scope": "CUSTOM",
"MaxResults": 20
}Q is the search term for the name, display name, or description. Scope=CUSTOM queries custom resources. MaxResults=20 sets the number of results per page. Example response:
{
"Agents": [
{
"name": "ecommerce-sales-sql",
"displayName": "E-commerce daily sales SQL development agent"
}
],
"NextToken": ""
}Select Agents[0].name=ecommerce-sales-sql. In subsequent GetAgent and UpdateAgent requests, the top-level Name uses this value.
Call ListSkills to query skills:
{
"Q": "ecommerce-sales-rules",
"Scope": "CUSTOM",
"MaxResults": 20
}This request queries skills by name or description. The following example has no matching results, so proceed to create a skill. If you find the required skill, skip CreateSkill:
{
"Skills": [],
"NextToken": ""
}In this example, use Agents[].name to select the agent ecommerce-sales-sql. The skill query returns an empty array, so create ecommerce-sales-rules in the next step. If you find the required skill, read the record's Skills[].name and skip creation. Q is a search criterion and cannot replace the actual resource name returned. If the response contains NextToken, keep the filter criteria and pass the returned value in the top-level NextToken to continue querying.
If you do not have an agent, create one using the CreateAgent request in the quick start. The following steps create a skill and bind it to an existing agent.
2. Create and retrieve a skill: CreateSkill and GetSkill
Name, Description, and Metadata are required. This example uses Metadata.skillMd to submit the rules directly in Markdown.
Call CreateSkill:
{
"Name": "ecommerce-sales-rules",
"Description": "Standardize aggregation rules and SQL output requirements for e-commerce shop daily sales reports",
"Metadata": {
"skillMd": "# Shop daily sales report\nApplicable project: ecommerce_analytics. Source table: dwd_trade_order_detail. Target table: ads_shop_sales_1d.\nEach row is a deduplicated order detail. pay_amount is the actual detail-level amount paid in yuan. Fields are non-null. Filter by the ds specified by the caller and include only details with order_status=PAID. Sum by shop_id without deducting refunds. When an order count is required, use COUNT(DISTINCT order_id). Do not substitute the number of detail records.\nReturn aggregation SQL, rule explanations, and validation suggestions. Do not execute SQL. Ask the caller to confirm missing schemas or business rules first."
}
}Example key response fields (excerpt):
{
"Success": true,
"Name": "ecommerce-sales-rules"
}Check that Success=true and save the returned top-level Name. Use the same name for GetSkill, the agent's Skills[].name, and subsequent update requests. Retrieve the skill details and verify the content of Name, Description, and Metadata.
Call GetSkill:
{
"Name": "ecommerce-sales-rules"
}GetSkill example response:
{
"Name": "ecommerce-sales-rules",
"Description": "Standardize aggregation rules and SQL output requirements for e-commerce shop daily sales reports",
"Metadata": {
"skillMd": "# Shop daily sales report\nApplicable project: ecommerce_analytics. Source table: dwd_trade_order_detail. Target table: ads_shop_sales_1d.\nEach row is a deduplicated order detail. pay_amount is the actual detail-level amount paid in yuan. Fields are non-null. Filter by the ds specified by the caller and include only details with order_status=PAID. Sum by shop_id without deducting refunds. When an order count is required, use COUNT(DISTINCT order_id). Do not substitute the number of detail records.\nReturn aggregation SQL, rule explanations, and validation suggestions. Do not execute SQL. Ask the caller to confirm missing schemas or business rules first."
}
}Verify that Name matches the request and Metadata.skillMd matches the submitted rules. When binding the skill, pass only its name. Do not put the entire GetSkill response in Skills.
3. Bind the skill: GetAgent and UpdateAgent
First call GetAgent to read the agent's actual version and skill list:
{
"Name": "ecommerce-sales-sql"
}GetAgent example key response fields (excerpt):
{
"Name": "ecommerce-sales-sql",
"AgentVersion": 2,
"Skills": []
}Pass the returned AgentVersion=2 to ExpectedVersion in the next step, and use the current Skills to construct the complete updated reference list. In actual calls, use the latest integer version retrieved.
Call UpdateAgent:
{
"Name": "ecommerce-sales-sql",
"ExpectedVersion": 2,
"Skills": [
{
"name": "ecommerce-sales-rules"
}
]
}UpdateAgent example response:
{
"Success": true,
"Name": "ecommerce-sales-sql"
}Check that Success=true, then use Name=ecommerce-sales-sql to call GetAgent again. Example configuration retrieved:
{
"Name": "ecommerce-sales-sql",
"AgentVersion": 3,
"Skills": [
{
"name": "ecommerce-sales-rules"
}
]
}AgentVersion is read from this GetAgent response. The UpdateAgent response does not contain the new version number. Use the actual returned value in place of 3 in this example.
Skills is replaced in full. If other skills are already bound, retain their references and add ecommerce-sales-rules. Do not overwrite the list with the example array. After the update, use the GetAgent response field Skills to confirm the bindings.
4. Create a new session and send a message
Pass the agent name you just verified to Params._meta.agent.agentName and call CreateAgentSession:
{
"Jsonrpc": "2.0",
"Id": "sales-rules-session-create-01",
"Params": {
"_meta": {
"agent": {
"agentName": "ecommerce-sales-sql"
}
}
}
}Use the session ID from the creation response for subsequent messages:
{
"Success": true,
"JsonRpcResponse": {
"jsonrpc": "2.0",
"id": "sales-rules-session-create-01",
"result": {
"sessionId": "20261020a1b24c3d8e5f012345678902"
}
}
}Pass JsonRpcResponse.result.sessionId unchanged to Params.sessionId and call PromptAgentSession to send the first message in this session:
{
"Jsonrpc": "2.0",
"Id": "sales-rules-verify-01",
"Params": {
"sessionId": "20261020a1b24c3d8e5f012345678902",
"prompt": [
{
"type": "text",
"text": "Use skill ecommerce-sales-rules to generate shop sales amount aggregation SQL for 2026-10-20 for ads_shop_sales_1d in project ecommerce_analytics. Source table dwd_trade_order_detail contains detail_id, order_id, shop_id, pay_amount, order_status, and ds. The amount field is DECIMAL(18,2), and the other fields are STRING. All fields are non-null. Return only SQL, aggregation rule explanations, and validation suggestions. Do not execute the query."
}
]
}
}Concatenate the SSE Params.update.content.text values to obtain the answer. After receiving Result.stopReason=end_turn for the current turn, check the generated result. The field mappings are as follows:
Source field or input | Example value | Destination field or reading method |
|
|
|
|
|
|
|
|
|
|
| Add the new skill to the existing references, then submit the complete |
|
|
|
Prompt SSE field | Returned SQL text | Concatenate and display the text. You do not need to resend this history in the next turn's request. |
Check the SQL date, PAID condition, and detail amount aggregation rules. After creating a new session, check whether the answer follows the skill's rules. For subsequent configuration maintenance, see example 2.
Example 2: Update agent and skill configurations
As an agent's scope of use expands, you can adjust its display name and responsibility description. You may also need to supplement the skill description. The update APIs retain the original resource names and references, so you do not need to recreate the resources.
First confirm the name of the agent or skill to update. This example uses ecommerce-sales-sql and ecommerce-sales-rules, respectively. You can obtain the names from the quick start, example 1, or resource queries. This example changes only descriptive information. Both call sequences are: query the current configuration → submit changes → query again to verify.
1. Update the agent: GetAgent → UpdateAgent → GetAgent
Call GetAgent with Name=ecommerce-sales-sql to read the current configuration and AgentVersion. The following example assumes that the actual version is 2. Use the actual integer version when executing the call.
Call UpdateAgent:
{
"Name": "ecommerce-sales-sql",
"ExpectedVersion": 2,
"DisplayName": "E-commerce data development agent",
"Description": "Generate and review SQL based on the provided schemas and business rules"
}Example update response:
{
"Success": true,
"Name": "ecommerce-sales-sql"
}Use the returned Name to call GetAgent again:
{
"Name": "ecommerce-sales-sql"
}Read the updated configuration:
{
"Name": "ecommerce-sales-sql",
"AgentVersion": 3,
"DisplayName": "E-commerce data development agent",
"Description": "Generate and review SQL based on the provided schemas and business rules"
}This example passes only Name, ExpectedVersion, DisplayName, and Description. Omitted configurations, such as Skills, remain unchanged.
ExpectedVersion provides concurrency protection. If a version conflict occurs, reread the current configuration and merge your changes. Do not repeatedly overwrite it. Name only identifies the resource and cannot rename it.
Skills and KnowledgeBases are retained when omitted. Passing a non-empty array replaces the corresponding list in full; passing an empty array removes the corresponding bindings. When updating skill references, retain entries that you still need. When creating an agent, you can also call CreateAgent with Skills=[{"name":"ecommerce-sales-rules"}] to establish the reference.
2. Update the skill: GetSkill → UpdateSkill → GetSkill
First call GetSkill to verify the original configuration. If you change only the description, omit Metadata.
Call UpdateSkill:
{
"Name": "ecommerce-sales-rules",
"Description": "Provide aggregation rules and SQL validation rules for daily report metrics such as sales amount and paid order count"
}Example update response:
{
"Success": true,
"Name": "ecommerce-sales-rules"
}Use the returned Name to call GetSkill again:
{
"Name": "ecommerce-sales-rules"
}Check whether Description is the new value you submitted and whether Metadata.skillMd still contains the original rule content. The field mappings for both update processes are as follows:
Source field or input | Example value | Destination field or reading method |
|
|
|
|
|
|
New display name provided by the caller | E-commerce data development agent |
|
New description provided by the caller | Generate and review SQL based on the provided table schemas and business rules |
|
|
|
|
New skill description provided by the caller | Provide definitions and SQL validation rules for daily report metrics such as sales amounts and paid order counts |
|
| Original name of each resource | Pass the name to the corresponding Get API. The write acknowledgment does not replace reading back the configuration. |
When changing the content, Metadata is replaced in full, so submit the complete content. The three sources skillMd, transitId, and bundleUrl cannot be combined. Do not use UpdatedAt or SkillVersion to infer the skill's concurrency revision number.
Resource updates do not guarantee that existing sessions immediately adopt the new configuration. To verify a new configuration, create a new session and check its actual output. For the deletion process, see example 6.
Example 3: Handle approvals and questions
When generating SQL for a daily report, the agent may need to confirm "whether refunds should be deducted from sales amounts" or request approval before executing a tool operation. The client should display the received question or operation, obtain the user's decision, and reply so that the original task can continue.
Follow this process only when PromptAgentSession or LoadAgentSession actually returns _qwen/notify with Params.kind=permission_request. Do not assume that the prompt text will necessarily produce this notification.
1. Read the current interaction notification
The following example shows the data content of an SSE event. First check Method and Params.kind, then read Params.data:
{
"Jsonrpc": "2.0",
"Method": "_qwen/notify",
"Params": {
"kind": "permission_request",
"data": {
"sessionId": "20261020a1b24c3d8e5f012345678901",
"requestId": "permission_sales_refund_01",
"toolCall": {
"title": "Confirm the sales amount aggregation rules",
"rawInput": {
"questions": [
{
"question": "Should refund amounts be deducted from sales amounts?",
"header": "Refund rules",
"answerKey": "refund_scope",
"options": [
{
"label": "Do not deduct refunds",
"description": "Aggregate the actual amounts paid for paid order details."
},
{
"label": "Deduct refunds",
"description": "A refund amount field and the date to which each refund is attributed are required."
}
],
"multiSelect": false
}
]
},
"_meta": {
"qwenInteractionKind": "user_question",
"qwenAnswerKeys": [
"refund_scope"
]
}
},
"options": [
{
"optionId": "allow_once",
"name": "Submit answer",
"kind": "allow_once"
}
]
}
}
}Provide the question answers and the outer approval option separately: answers stores the business answers, and outcome.optionId stores the submission action selected by the user. The field mappings are as follows:
Notification field | Example returned value | Subsequent use |
|
| Pass it to Reply as |
|
| Pass it as |
|
| In this example, the user selects this submission action. Pass it as |
|
| Use |
2. Submit answers: ReplyAgentSession
Pass the session ID, interaction ID, and option from the notification in the request. After the user confirms "do not deduct refunds," call ReplyAgentSession:
{
"Jsonrpc": "2.0",
"Id": "sales-rule-reply-01",
"Params": {
"sessionId": "20261020a1b24c3d8e5f012345678901",
"permissionRequestId": "permission_sales_refund_01",
"outcome": {
"outcome": "selected",
"optionId": "allow_once"
},
"answers": {
"refund_scope": "Do not deduct refunds. Aggregate the actual amounts paid for paid order details."
}
}
}Example response:
{
"Success": true,
"JsonRpcResponse": {
"jsonrpc": "2.0",
"id": "sales-rule-reply-01",
"result": {
"accepted": true
}
}
}Id=sales-rule-reply-01 corresponds to JsonRpcResponse.id for this reply. permission_sales_refund_01 identifies the current interaction. The two values serve different purposes. The Reply response does not contain the SQL generated afterward. Continue reading the original Prompt or Load stream.
answers keys must come from the current questions. Prefer qwenAnswerKeys from the notification or the question's answerKey. If neither is provided, use the zero-based question index as a string, such as "0". In the preceding example, permission_sales_refund_01, allow_once, and refund_scope come from the example notification. For other interactions, use their actual request IDs, user-selected options, and answer keys. Do not always reuse these example values. Answer values are strings.
Check that JsonRpcResponse.result.accepted=true, then continue reading the original response stream. Verify that the SQL still sums the actual amounts paid for order details without deducting refunds. An accepted reply does not mean that SQL generation is complete. You must still wait for the target turn to reach a terminal state.
3. Handle standard approvals and cancel interactions
The following requests are alternative branches. Do not execute them sequentially. For a standard approval, submit the user's selection. To cancel an interaction, submit cancelled. Both branches must use the currently valid notification and the user's decision.
For a standard operation approval, do not pass answers. Assume that the notification contains requestId=permission_sales_tool_01 and the user selects allow_once from the current notification. Call ReplyAgentSession:
{
"Jsonrpc": "2.0",
"Id": "sales-tool-approve-01",
"Params": {
"sessionId": "20261020a1b24c3d8e5f012345678901",
"permissionRequestId": "permission_sales_tool_01",
"outcome": {
"outcome": "selected",
"optionId": "allow_once"
}
}
}If the user decides to cancel the preceding refund question, use the original question's interaction ID, set outcome.outcome to cancelled, and omit optionId and answers. Call ReplyAgentSession:
{
"Jsonrpc": "2.0",
"Id": "sales-rule-dismiss-01",
"Params": {
"sessionId": "20261020a1b24c3d8e5f012345678901",
"permissionRequestId": "permission_sales_refund_01",
"outcome": {
"outcome": "cancelled"
}
}
}For all three requests, read JsonRpcResponse.result.accepted. If it is true, continue reading the original stream. If it is false, retrieve the currently valid interaction again without automatically changing the user's decision. Cancelling an interaction does not cancel the entire turn. To stop execution, see Example 6.
If the agent asks a question only in plain text, wait for the turn to end, then use PromptAgentSession to submit the user's answer. You do not need to call ReplyAgentSession.
Example 4: Query and set the session model
To use a specific model to review generated SQL, first query the available models and the current session configuration, then set the model as needed. Use the original session for subsequent prompts.
Use 20261020a1b24c3d8e5f012345678901 to query the current model, then select and set another model as needed. Configure the model only after the current turn and interaction have both ended. This process does not depend on the skill creation or resource update examples.
1. Query candidate models and the current configuration
Call ListModels:
{
"ModelType": "text",
"MaxResults": 20
}Available models are determined by the actual response from ListModels. The following is an example catalog entry:
{
"Models": [
{
"Id": "qwen3-coder-plus",
"DisplayName": "Qwen3-Coder-Plus",
"Capabilities": {
"InputModalities": [
"text"
]
}
}
],
"NextToken": ""
}This example selects Models[].Id=qwen3-coder-plus. The subsequent call to SetAgentSessionModel uses this value unchanged. For actual integration, select a model based on the current catalog and session support. If the response includes NextToken, keep ModelType and MaxResults unchanged and pass the top-level NextToken to query subsequent pages. Do not use DisplayName in place of the model ID.
Call GetAgentSessionModel:
{
"Jsonrpc": "2.0",
"Id": "sales-model-read-01",
"Params": {
"sessionId": "20261020a1b24c3d8e5f012345678901"
}
}Save JsonRpcResponse.result.modelId and the thinking level information actually returned to compare configuration changes. A model visible in the catalog may not be available for the current session.
2. Set and read the effective configuration
Call SetAgentSessionModel:
{
"Jsonrpc": "2.0",
"Id": "sales-model-set-01",
"Params": {
"sessionId": "20261020a1b24c3d8e5f012345678901",
"modelId": "qwen3-coder-plus"
}
}The configuration API returns the configuration that actually takes effect. For example:
{
"Success": true,
"JsonRpcResponse": {
"jsonrpc": "2.0",
"id": "sales-model-set-01",
"result": {
"modelId": "qwen3-coder-plus"
}
}
}Call GetAgentSessionModel again to verify the configuration:
{
"Jsonrpc": "2.0",
"Id": "sales-model-read-02",
"Params": {
"sessionId": "20261020a1b24c3d8e5f012345678901"
}
}Example response:
{
"JsonRpcResponse": {
"jsonrpc": "2.0",
"id": "sales-model-read-02",
"result": {
"modelId": "qwen3-coder-plus"
}
}
}In the model catalog, Models[].Id is used to submit your selection. In the session response, modelId indicates the effective configuration. These values may differ. Save the configuration result and compare it with the value returned by a subsequent call to GetAgentSessionModel at modelId. Do not determine that the operation failed solely because the catalog ID and the ID returned by the session differ as strings. Do not append or remove provider suffixes yourself.
When configuring Params.thinkingLevel, use only supported values actually provided by the target model and session. You must pass modelId even when changing only the level. If configuration fails, query the actual configuration as well. Do not assume that all changes have been rolled back.
The field mappings are as follows:
Source field or input | Value in this example | Input field or read path |
Session creation response: |
|
|
|
|
|
|
| An empty value indicates the end of the query. Otherwise, pass the value to the next call to |
Set response: |
| Save the effective value and compare it with the value returned by |
Catalog field: | Use only supported values in the current response | Select a value as needed and pass it in |
3. Continue the conversation with the current model
Setting the model does not create a new session. Use the original session ID for a new Prompt, such as a request to review generated SQL.
Call PromptAgentSession:
{
"Jsonrpc": "2.0",
"Id": "sales-sql-model-review-01",
"Params": {
"sessionId": "20261020a1b24c3d8e5f012345678901",
"prompt": [
{
"type": "text",
"text": "Review the shop daily sales SQL for 2026-10-20 in project ecommerce_analytics in the current session. Check that the ds and PAID filters are complete, pay_amount is accumulated at the detail level, and grouping is correct. If the SQL includes paid_order_count, check that orders are deduplicated by order_id. Return the issues, their causes, and the complete corrected SQL. Do not execute the query."
}
]
}
}Verify that the actual model configuration matches the selected model, and review the results after this turn ends. Switching models does not itself guarantee SQL correctness.
Example 5: Query sessions, load history, and recover from disconnections
To retrieve a previous conversation after closing the page, or to receive the full result after a network interruption during generation, load the session to view its history and continue receiving output. This avoids resubmitting the same task.
The query and recovery process applies to existing sessions. If you know 20261020a1b24c3d8e5f012345678901, you can load the session directly. To find the session again, first call ListAgentSessions. To recover interrupted output, continue using the original session without resubmitting the original text.
1. Query sessions and read a summary
If you have saved 20261020a1b24c3d8e5f012345678901, load the session directly. Otherwise, first call ListAgentSessions to query the sessions for the agent:
{
"Jsonrpc": "2.0",
"Id": "sales-session-list-01",
"Params": {
"AgentName": "ecommerce-sales-sql",
"MaxResults": 20
}
}ListAgentSessions example response with key fields (excerpt):
{
"JsonRpcResponse": {
"Jsonrpc": "2.0",
"Id": "sales-session-list-01",
"Result": {
"MaxResults": 20,
"SessionList": [
{
"sessionId": "20261020a1b24c3d8e5f012345678901",
"title": "2026-10-20 shop daily sales SQL",
"agentName": "ecommerce-sales-sql"
}
],
"NextToken": ""
}
}
}From JsonRpcResponse.Result.SessionList, select the target record and obtain sessionId. Verify it against the actual title and time. Do not infer the session from the date alone. If the response includes NextToken, keep the filters unchanged and pass Params.NextToken to continue pagination.
To view a summary, call GetAgentSession:
{
"Jsonrpc": "2.0",
"Id": "session-summary-read-01",
"Params": {
"sessionId": "20261020a1b24c3d8e5f012345678901"
}
}Example summary response:
{
"JsonRpcResponse": {
"jsonrpc": "2.0",
"id": "session-summary-read-01",
"result": {
"sessionId": "20261020a1b24c3d8e5f012345678901",
"title": "2026-10-20 shop daily sales SQL",
"agentName": "ecommerce-sales-sql"
}
}
}In the list entry, sessionId corresponds to Params.sessionId in this request. Read JsonRpcResponse.result for the session summary. The returned title is for display, and agentName identifies the associated agent. Do not use the title or time fields to determine the turn status.
GetAgentSession does not replace history retrieval and does not provide queries for execution status or pending interactions.
2. Load history: LoadAgentSession
Pass the session ID verified in the previous step in Params.sessionId and call LoadAgentSession:
{
"Jsonrpc": "2.0",
"Id": "sales-history-load-01",
"Params": {
"sessionId": "20261020a1b24c3d8e5f012345678901"
}
}The load response is SSE, not a JSON message list. The following is the data content of a historical answer event:
{
"Jsonrpc": "2.0",
"Method": "session/update",
"Params": {
"sessionId": "20261020a1b24c3d8e5f012345678901",
"update": {
"sessionUpdate": "agent_message_chunk",
"content": {
"type": "text",
"text": "SELECT '2026-10-20' AS business_date, shop_id, SUM(pay_amount) AS sales_amount FROM ecommerce_analytics.dwd_trade_order_detail WHERE ds = '2026-10-20' AND order_status = 'PAID' GROUP BY shop_id;"
}
}
}
}Read Params.update.sessionUpdate to distinguish text sources: user_message_chunk indicates user text, and agent_message_chunk indicates agent text. Read the body from Params.update.content.text. Loading may also return configuration, interactions, and subsequent output. Do not handle only text events.
Rebuild the history view of the original session from stream events to view previous user inputs and agent answers. Do not append all replayed history as new answers.
3. Recover interrupted output by event position
Read recovery markers from the notification field Params._meta. offset, eventEpoch, and promptId should be saved as a group. Retain the last complete set of markers. If later frames omit markers, do not overwrite existing values. Result or error frames are not guaranteed to carry recovery markers. Do not require a top-level _meta to be present.
Use a new Id for each call. Results or errors in the original Prompt stream are associated with that Prompt request through the returned Id. A recovery stream that specifies Params._meta.promptId is associated through the Id of the current Load request. The recovery request determines the target turn. For an ordinary Load, Result.stopReason=end_turn indicates only that loading has ended. It does not prove that a previous turn succeeded.
For example, if the following event is received before a disconnection, save its _meta. Do not generate a cursor from character counts or the number of messages received:
{
"Jsonrpc": "2.0",
"Method": "session/update",
"Params": {
"sessionId": "20261020a1b24c3d8e5f012345678901",
"update": {
"sessionUpdate": "agent_message_chunk",
"content": {
"type": "text",
"text": "GROUP BY shop_id;"
}
},
"_meta": {
"offset": 12,
"eventEpoch": "20261020e1f24a3b9c4d012345678901",
"promptId": "prompt_sales_20261020_03"
}
}
}Field received in the stream | Value in this example |
|
|
|
|
|
|
|
|
|
|
If all three markers above were actually received in the same turn of session 20261020a1b24c3d8e5f012345678901, call LoadAgentSession to recover:
{
"Jsonrpc": "2.0",
"Id": "sales-stream-resume-01",
"Params": {
"sessionId": "20261020a1b24c3d8e5f012345678901",
"_meta": {
"isReload": true,
"beginLogOffset": 12,
"eventEpoch": "20261020e1f24a3b9c4d012345678901",
"promptId": "prompt_sales_20261020_03"
}
}
}For an actual call, replace all three values together with the markers returned for the target turn, and keep the cursor as an integer. If no complete, valid set of markers is available, use the preceding ordinary Load request to rebuild history. After recovery, verify the actual terminal status of the target turn and handle any duplicate historical content.
For an idle Load, end_turn may indicate only that loading has ended. It does not prove that the previously interrupted SQL generation succeeded. If a matching terminal status is still unavailable, retain the "result pending verification" status. Recovery from a disconnection does not depend on resending the Prompt.
Example 6: Cancel execution and delete resources
If a user submits incorrect development requirements, you can stop the current generation. After the task ends, you may also need to delete sessions or dedicated resources that are no longer needed. Use the respective APIs to cancel execution, delete a session, delete an agent, and delete a skill.
Before execution, verify the target identity and resource ownership. Check the result of each operation separately.
Before deletion, obtain user authorization and confirm that the target resource is no longer in use. Deleting a session does not undo external operations that have already occurred.
1. Request cancellation: CancelAgentSession
If the stream for the current turn to be cancelled returns Params._meta.promptId=prompt_sales_20261020_03, use the following request. This value matches the turn ID in the recovery example. Actual calls must still use the value for the target turn.
Call CancelAgentSession:
{
"Jsonrpc": "2.0",
"Id": "sales-sql-cancel-01",
"Params": {
"sessionId": "20261020a1b24c3d8e5f012345678901",
"_meta": {
"promptId": "prompt_sales_20261020_03"
}
}
}Example cancellation response:
{
"Success": true,
"JsonRpcResponse": {
"jsonrpc": "2.0",
"id": "sales-sql-cancel-01",
"result": {
"sessionId": "20261020a1b24c3d8e5f012345678901",
"removed": true
}
}
}Here, JsonRpcResponse.id corresponds to the cancellation request. You must still read the original Prompt or Load stream afterward. If the original Prompt has Id=sales-sql-explain-01, the cancellation terminal status for the target turn may be:
{
"Jsonrpc": "2.0",
"Id": "sales-sql-explain-01",
"Result": {
"stopReason": "cancelled"
}
}Before cancellation, save Params._meta.promptId from the target notification. The original Prompt stream uses Id to match the original Prompt request. A recovery stream that specifies the target turn uses Id to match the current Load request. The final frame does not have to contain _meta and should not use the Id of the Cancel request.
Params._meta.promptId specifies the target turn. If omitted, cancellation applies at the session level. A cancellation acknowledgment is not an execution terminal status. Continue reading the original stream, or recover through LoadAgentSession, until you confirm that the target execution has ended. Do not mark an incomplete answer after cancellation as a normally completed output.
2. Delete the session after confirming execution has ended
After the user confirms that the session is no longer needed and both execution and interactions have ended, call DeleteAgentSession:
{
"Jsonrpc": "2.0",
"Id": "sales-session-delete-01",
"Params": {
"sessionId": "20261020a1b24c3d8e5f012345678901"
}
}Example deletion response:
{
"Success": true,
"JsonRpcResponse": {
"jsonrpc": "2.0",
"id": "sales-session-delete-01",
"result": {
"sessionId": "20261020a1b24c3d8e5f012345678901"
}
}
}JsonRpcResponse.result.sessionId should match the value in this request. The top-level Success=true indicates that deletion succeeded.
Check Success and error responses. If execution or an interaction is still in progress, handle the current task first. Do not repeatedly request deletion. Deleting a session does not undo external operations that have already occurred.
3. Delete agents and skills as needed
Deleting a session does not automatically delete the agent or skill. Call the respective APIs only when the resources will no longer be reused and the user authorizes deletion.
Call DeleteAgent:
{
"Name": "ecommerce-sales-sql"
}This API requires only the agent name. Retrieve it from CreateAgent or GetAgent in the top-level Name field. Read the top-level Success in the success response.
Call DeleteSkill:
{
"Name": "ecommerce-sales-rules"
}This API requires only the skill name. Retrieve it from CreateSkill or GetSkill in the top-level Name field. DeleteAgent and DeleteSkill can both return the following success response:
{
"Success": true
}The following identifiers locate turns, sessions, and resources, respectively:
Source field or input | Value in this example | Input field or read path |
Notification in the original response stream: |
|
|
Session creation or query response: |
|
|
|
|
|
|
|
|
Check Success and error responses for each operation separately. Before deleting a skill, check whether other agents still reference it. Successfully deleting one resource does not mean that other resources have also been deleted. Retain resources that still need to be reused.
Example 7: File transit, upload, and status queries
To upload a local skill ZIP package containing SQL validation rules and reference files for subsequent skill creation, first request upload authorization, then upload the file and query its status. File upload and session text input are independent processes.
File transit is independent of session messages and is used to request upload authorization and query file status. The call sequence is CreateTransitUploadPolicy → OSS upload → upload confirmation (out-of-scope dependency) → GetTransitMeta. OSS upload is a separate HTTP operation, not a session Prompt.
Upload confirmation must be completed before using a ZIP file to create a skill. The confirmation API is outside the scope of the 23 APIs in this guide. Use the confirmation process provided by the target environment. The upload authorization and status query APIs listed in this example alone cannot complete the entire process from ZIP file upload to skill creation.
1. Request upload authorization: CreateTransitUploadPolicy
Consider the locally prepared skill package ecommerce-sales-rules.zip as an example. FileShowName is required. Specify other fields as needed. ExpireMs=3600000 indicates a validity period of one hour, not an expiration timestamp.
Call CreateTransitUploadPolicy:
{
"FileShowName": "ecommerce-sales-rules.zip",
"PathPrefix": "skill-bundle",
"Network": "public",
"ExpireMs": 3600000
}FileShowName is the display name of the local file. PathPrefix isolates object paths. Network=public selects a public endpoint. ExpireMs=3600000 is the validity period of the upload policy and transit record. Submitting these fields only requests authorization. It does not send file content.
Example response with key fields (excerpt; the domain and paths are illustrative, and authorization fields retain credential placeholders):
{
"Success": true,
"TransitId": "transit_20261020a1b24c3d8e5f012345678903",
"FilePath": "skill-bundle/ecommerce_analytics/20261020/ecommerce-sales-rules.zip",
"PolicyInfo": {
"Host": "https://ecommerce-skill-upload.example.invalid",
"Dir": "skill-bundle/ecommerce_analytics/20261020/ecommerce-sales-rules.zip",
"AccessId": "<UPLOAD_ACCESS_KEY_ID>",
"Policy": "<UPLOAD_POLICY_BASE64>",
"Signature": "<UPLOAD_SIGNATURE>",
"SecurityToken": "<UPLOAD_SECURITY_TOKEN>"
}
}Check Success=true and save the returned values unchanged for TransitId, FilePath, and PolicyInfo. At this point, authorization has only been obtained. This does not mean that the file upload is complete. FilePath is an opaque object path. Use it unchanged. Do not construct it from the file name.
2. Upload the file using the returned fields
Use the returned PolicyInfo.Host for a multipart/form-data POST. Populate the form according to the following mappings. Place the file field last:
Upload destination or field | Value in this example | Source |
POST destination URL |
| |
|
| Top-level |
|
|
|
|
|
|
|
|
|
|
|
|
| Local file | Place the file content last in the form. |
Read the OSS upload result. After the OSS upload succeeds, you must still complete the upload confirmation process supported by the target environment to make the transit file available. GetTransitMeta only queries status and does not perform confirmation. For the scope of the confirmation API, see the note at the end of this example.
If upload fails, investigate the cause first. If authorization expires, request it again. Do not treat a successful call to CreateTransitUploadPolicy as a successful upload. Use authorization fields unchanged. Do not print or retain the complete PolicyInfo for an extended period.
3. Query transit status: GetTransitMeta
For subsequent queries, continue using transit_20261020a1b24c3d8e5f012345678903 obtained when requesting authorization, not the OSS response body or a session ID.
Call GetTransitMeta:
{
"TransitId": "transit_20261020a1b24c3d8e5f012345678903"
}GetTransitMeta example response with key fields (excerpt, assuming the required file confirmation is complete):
{
"TransitId": "transit_20261020a1b24c3d8e5f012345678903",
"FilePath": "skill-bundle/ecommerce_analytics/20261020/ecommerce-sales-rules.zip",
"Status": "SUCCESS",
"Size": 4096
}Read Status, Size, FilePath, and ExpireAt: PENDING indicates that the file is not yet available, and SUCCESS indicates that the file is available. ExpireAt is the expiration time as a UTC Unix timestamp in milliseconds. You can compare it directly with the current timestamp in milliseconds.
4. Obtain a temporary download URL as needed
Continue using the same TransitId, add Network and a download URL validity period, and call GetTransitMeta:
{
"TransitId": "transit_20261020a1b24c3d8e5f012345678903",
"Network": "public",
"ExpireMs": 900000
}For example, the response is:
{
"TransitId": "transit_20261020a1b24c3d8e5f012345678903",
"Status": "SUCCESS",
"DownloadUrl": "https://ecommerce-skill-download.example.invalid/ecommerce-sales-rules.zip?signature=<DOWNLOAD_SIGNATURE>"
}Read DownloadUrl and download within its validity period. In this request, ExpireMs=900000 is the download URL validity period (15 minutes), which differs from the upload policy validity period in step 1. If Network is omitted, no download URL is generated. Creating a download URL does not extend the validity of the Transit record. Receiving a URL does not replace checking Status=SUCCESS.
The mappings for upload, queries, and subsequent skill creation are as follows:
Source field or input | Value in this example | Input field or read path |
|
|
|
|
| OSS form field: |
| The destination URL for the OSS upload, not the POP API endpoint. | |
|
| File availability status. If it is |
| Returned temporary download URL | Used for HTTP downloads. Request a new URL after it expires. |
Confirmed |
| Follow the |
To create a skill from an uploaded ZIP file, first complete ConfirmTransitUpload confirmation, then follow the CreateSkill source rules to pass TransitId to Metadata.transitId. ConfirmTransitUpload is an out-of-scope dependency. This guide does not provide its request structure. Integrators must verify the confirmation process in the target environment. GetTransitMeta queries do not replace upload confirmation. If no file package is needed, follow Example 1 and use Metadata.skillMd directly to create a skill.
TransitId is not an attachment input for the current text session and cannot replace sessionId. The ZIP file in this example is prepared by the caller in advance. It does not indicate that a session can directly produce files.
Handle streaming responses
PromptAgentSession and LoadAgentSession return text/event-stream on success. The client should first assemble complete SSE events, then parse the JSON protocol messages in data. Do not treat TCP fragments directly as messages. The outer protocol layer within the stream uses keys such as Jsonrpc, Params, and Result. Keys inside any retain their original case. The stream does not have the JsonRpcResponse wrapper used in ordinary responses.
Event or result | Client handling |
| Concatenate |
| Save the current interaction, options, and questions. After obtaining the user's decision, follow Example 3 to reply. |
| Associate the request and target turn, and distinguish normal completion, cancellation, and other outcomes. The end of an ordinary Load does not replace checking whether the original Prompt completed. |
| Read the actual values of |
Historical messages, | Rebuild history or update configuration, respectively. Do not append them directly as new answers for the current turn. |
| Handle according to message type. Do not treat them as SQL body text or evidence of successful execution. |
At a minimum, the receiver should separately record received text, pending interactions, the target turn result, and the recovery position. Retain necessary diagnostic information for unknown messages. Do not treat the entire turn as successful merely because a new event type appears. Disconnecting the client does not automatically cancel generation.
Save recovery information in sync with received content to avoid displaying text while losing its cursor. Read recovery markers from the notification field Params._meta. offset, eventEpoch, and promptId must remain associated. Retain the last complete set of markers. If later frames omit markers, do not overwrite existing values. Result or error frames are not guaranteed to carry recovery markers. Do not require a top-level _meta to be present.
After a disconnection, follow Example 5 to recover. An event epoch mismatch may return InvalidParameter before the stream is established, or report CLI_RELOAD_REQUIRED within the stream. In either case, reload history and rebuild the view.
Use a new Id for each new call. Results or errors in the original Prompt stream are associated with that Prompt request through the returned Id. A recovery stream that specifies Params._meta.promptId is associated through the Id of the current Load request. The recovery request determines the target turn. For an ordinary Load, Result.stopReason=end_turn indicates only that loading has ended. It does not prove that a previous turn succeeded.
Error handling and retries
Handle failures of ordinary requests and failures before stream establishment as POP errors. Retain Code, Message, and RequestId. For failures after stream establishment, parse JSON messages within the stream. If the business result is unclear, verify the status before deciding whether to retry.
Situation | Handling |
| Use a client that supports SSE and V3 signatures. Changing the Accept request header does not fix a signature version issue. |
Parameter error | Check field case, types, required conditions, and enumerated values. Within |
Permission error or resource not visible | Check the identity, region, signature, authorization, and actual resource name. |
Agent or skill creation timeout, or name conflict | First, use the original |
| If the original request included |
| Wait for the current turn to end, or complete the current interaction before submitting a new Prompt. |
Reply returns | Retrieve the currently valid interaction again and retain the user's decision. Do not automatically change options or approve operations. |
SSE interruption, or | Use |
Cancel returns | Continue reading or recover output to verify whether the target turn has ended. |
|
|
Transit status is | Verify the actual upload and required confirmation steps. The query itself does not complete upload confirmation. |
Model configuration fails |
|
Throttling or temporarily unavailable dependency | Use backoff with limits on attempts and elapsed time for retryable reads. If a write result is unknown, query or recover first. |
To safely retry session creation, use CreateAgentSession with Params containing clientToken. For example, generate and persist ecommerce-sales-20261020-create-01 for a single daily report session creation operation. When retrying the same operation, keep the token and business parameters unchanged. Use a new token for a new creation operation. The token must be 1 to 128 characters long and does not provide Prompt deduplication.
The quick start omits clientToken. If the creation result is unknown, do not add a token after the fact and assume it can deduplicate the original request. Id is used only to associate calls. Resubmitting a Prompt after a timeout may execute it again. Do not assume that reply, cancellation, and deletion operations can be repeatedly retried with the same parameters. When updating skill content, note that Metadata is replaced in its entirety.
When troubleshooting, retain Action, the call time, region, RequestId, and, where necessary, sessionId and promptId. Do not log credentials, signatures, or unrelated business content. Refer to the API documentation for limits such as field length and pagination ranges. Do not infer uniform limits for text length, QPS, connection duration, or history retention.
Automated agent API call guide
Automation should establish dependencies using actual returned values and separately determine whether API calls, model generation, and business validation succeed.
Stage | Input and action | Condition for proceeding |
Prepare development resources | Create or reuse an agent. Bind skills when rules or capabilities need to be reused. | Obtain the actual |
Create a session | Pass the agent name in | Creation succeeds, and the actual value is obtained from |
Submit requirements | Confirm that no turn remains unfinished and no interaction is pending, then write the task requirements and necessary inputs in | No stream establishment error occurs, and SSE reception and processing begin. |
Receive output and handle interactions | Concatenate text and save the recovery position. If an interaction occurs, obtain the user's decision before replying. | The target turn of the current Prompt ends normally. An accepted reply does not replace this condition. |
Validate business output | Review the answer against business requirements. For SQL, for example, check filters, aggregation granularity, and expected values. | The answer meets the task requirements. If issues remain, submit new revision requirements. |
Save or recover | Save the text result and its session association. Use Load to recover after a disconnection. | The result is traceable. Do not replace recovery with a repeated Prompt. |
The specific resources, IDs, models, and addresses in this document illustrate the complete data flow. Actual call values must come from user input, accessible resources, or the corresponding responses. Preserve the JSON types of string, integer, boolean, and structured parameters. If actual IDs, models, interaction options, or recovery markers have not been obtained, stop dependent steps. Do not continue calling APIs with illustrative values from the document.
Top-level POP parameters and fields inside any use different case conventions. For example, Params.sessionId, Params._meta, and JsonRpcResponse.result must all be used unchanged. Business dates and table names belong in the prompt body and are not new fields of the session APIs. Do not automatically change the case of arbitrary answer keys.
At creation, use Params._meta.initialConfigOptions.approvalMode to specify default or yolo. If omitted, default is used. Verify the detailed nesting structure and field conditions against the supplementary instructions for CreateAgentSession. Do not infer additional fields from this guide.
Consider yolo only when the user explicitly authorizes automatic approval. It cannot replace answers to business questions. Do not automatically change the approval mode. When handling a specific interaction, you must still use the actual ID and options in the current notification and the user's decision.
For file transit, separately save TransitId, the file status, and the validity period. Resource creation, upload authorization, successful upload, interaction acceptance, turn completion, and resource deletion are distinct outcomes. Do not combine them into a single success status.