Generate conversations
This API provides capabilities for scenario-based conversations, research, and writing. It uses the `agent_id` and `agent_version` parameters from Agent Application Management.
Request syntax
POST /deep-search-agent/chat/completions HTTP/1.1
Request parameters
Parameter name | Type | Required | Description |
|---|---|---|---|
stream | bool | Yes | Set this parameter to true. The current version only supports streaming output. If you set this parameter to |
input | object | Yes | The input field. |
input.request_id | str | No | The request ID. This is a custom ID defined by your service. |
input.messages | array[object] | Yes | The conversation messages. |
input.messages.[].role | str | Yes | The role. The enumeration values are |
input.messages.[].content | str | Yes | The content to generate. |
parameters | object | Yes | The configuration parameter field. |
parameters.agent_options | object | Yes | Parameters specific to the agent. |
parameters.agent_options.agent_id | string | Yes | The application ID. |
parameters.agent_options.agent_version | string | Yes | The application version. |
parameters.agent_options.session_files | array[string] | No | A list of dynamic file IDs. For more information about how to obtain a file ID, see the file upload document. You can pass a maximum of 10 file IDs. |
Response parameters
Parameter | Type | Required | Description |
|---|---|---|---|
request_id | str | Yes | The request ID from the DashScope platform. |
code | str | Yes | The status code. A value of 200 indicates success. |
message | str | Yes | The status message. |
output | object | Yes | The output field. |
output.request_id | str | No | User-defined Request ID |
output.choices | array[object] | Yes | The model output information. |
output.choices.[].finish_reason | str | Yes | The reason why the generation ended. Only the last package outputs |
output.choices.[].message | object | Yes | The conversation message. |
output.choices.[].message.role | str | Yes | The role. The enumeration values are |
output.choices.[].message.content | str | array[object] | Yes | The generated content or the content returned by the tool. When report generation is enabled in the configuration, the report message body is of the |
output.choices.[].message.reasoning_content | str | No | The thinking content. If the `content` field is empty, the system attempts to retrieve the `reasoning_content` from the last round of deep thinking. |
output.choices.[].message.tool_calls | array[object] | No | Information about the tool call. |
output.choices.[].message.tool_calls[0].arguments | dcit[str,object] | No | The parameters for the tool call. |
output.choices.[].message.tool_calls[0].name | str | No | The name of the tool that was called. |
output.choices.[].message.additional_kwargs.extra_json | Any | No | When a tool call returns, this field carries the structured output information. |
output.choices.[].message.extra | dict | No | The step status information. |
output.choices.[].message.extra.group | str | No | The execution phase. |
output.choices.[].message.extra.step_change | str | No | The step change event. |
output.choices.[].message.extra.step | str | No | The current step. |
output.choices.[].message.response_metadata | dict | No | Detailed information about the request model call. |
output.usage | object | No | Usage statistics. |
output.usage.input_tokens | int | No | Input tokens. |
output.usage.output_tokens | int | No | Output tokens. |
output.usage.total_tokens | int | No | Total tokens. |
Plan enumerations
Execution phase ( | Description | Notes |
|---|---|---|
planning | Planning | Corresponds to the plan model. The system is in the task planning phase. This phase includes `start` and `end` events. |
generating | Generating | Represents the writing model. The system is in the report generation phase. This phase does not distinguish detailed event changes and has no `start` or `end` events. The `step` status only includes `thinking` and `generating`, and no tools are called. |
Current step ( | Description and notes |
|---|---|
planning | Planning |
thinking | Thinking |
reporting | Summarizing (specific to legal scenarios) |
generating | Generating |
tool_calling | Calling a tool |
tool_calling_{tool_name} | Calling a tool. The tool name is included. |
- For model-related reasons, the
step_changevalue might not exist. Therefore, use the persistentstepflag whenever possible. - For an empty package, the
step,step_change, andgroupfields might not exist. plan,think, andgenerationare each composed of anxxx_startevent and anxxx_endevent.tool_callis composed of three events:tool_call_start,tool_calling, andtool_return.tool_call_startindicates the start of the tool call. The system begins to collect tool call information in a stream. At this point, details such asnameandargumentsare not available for output.tool_callingindicates that the complete parameters for the tool call have been retrieved and are being output.tool_returnindicates that the tool call has completed and includes the structured information from the tool's return value.
Step change event ( | Value of | Event name | Explanation |
|---|---|---|---|
plan_start |
| Start planning | The |
plan_end |
| End planning | The |
think_start |
| Start thinking | Same as the |
think_end |
| End thinking | Same as the |
report_start |
| Start summarizing | Same as the |
report_end |
| End summarizing | Same as the |
generation_start |
| Start generating | Same as the |
generation_end |
| End generating | Same as the |
tool_call_start |
| Start tool call | Indicates that the tool call has started. The system begins to collect tool call information in a stream. At this point, details such as `name` and `arguments` cannot be output. |
tool_calling |
| Tool call in progress | The specific parameters and name of the tool call are output. The |
tool_return |
| Tool return | Includes the tool return information. The |
Examples
Request example
{
"input": {
"messages": [
{
"role": "user",
"content": "Current date"
}
]
},
"parameters": {
"agent_options": {
"agent_id": "aid-xxx",
"agent_version": "beta"
}
}
}
Response example
data: {
"code": "200",
"message": "",
"output": {
"choices": [{
"finish_reason": "",
"message": {
"content": "",
"additional_kwargs": {},
"response_metadata": {},
"tool_calls": [],
"reasoning_content": "",
"role": "assistant",
"extra": {
"group": "planning",
"step_change": "think_start",
"step": "thinking"
}
}
}]
},
"usage": null,
"request_id": "5b853312-8d0c-42ff-9d26-08339d5ff38e"
}
If report generation is enabled in the configuration, the last package from the model provides the storage addresses and paths for the HTML and MD files. The following describes the values for the type field in content:
file_path: The file storage path. You can use this path for subsequent PDF exports and to retrieve the file download links.md_file_url: The MD file download link.html_file_url: The HTML file download link.
{
"status_code": 200,
"code": "",
"message": "",
"output": {
"choices": [
{
"finish_reason": "stop",
"message": {
"content": [
{
"type": "file_path",
"text": "msearch/agents/files/upload/536fa835-a381-4870-99c1-79dee3ab946c"
},
{
"type": "md_file_url",
"text": "https://msearch-cloud.oss-cn-hangzhou.aliyuncs.com/msearch/agents/files/upload/536fa835-a381-4870-99c1-79dee3ab946c.md?x-oss-signature-version=OSS4-HMAC-SHA256&x-oss-date=20250904T151053Z&x-oss-expires=900&x-oss-credential=YOUR_ACCESS_KEY_ID&x-oss-signature=YOUR_SIGNATURE"
},
{
"type": "html_file_url",
"text": "https://msearch-cloud.oss-cn-hangzhou.aliyuncs.com/msearch/agents/files/upload/536fa835-a381-4870-99c1-79dee3ab946c.html?x-oss-signature-version=OSS4-HMAC-SHA256&x-oss-date=20250904T151053Z&x-oss-expires=900&x-oss-credential=YOUR_ACCESS_KEY_ID&x-oss-signature=YOUR_SIGNATURE"
}
],
"additional_kwargs": {},
"response_metadata": {
"model_name": "deep-research-generation",
"agent_name": "writing_agent"
},
"tool_calls": [],
"reasoning_content": "",
"role": "assistant"
}
}
]
},
"usage": null,
"request_id": "3070fa78-c5d5-4bad-b2fc-e20787f6eb75"
}
Call examples
# coding=utf-8
import os
import json
import requests
split_line = "\\n-------------------------------------Report Generation Link---------------------------------------------------\\n"
chat_completions_url = 'https://dashscope.aliyuncs.com/api/v2/apps/deep-search-agent/chat/completions'
headers = {
'Authorization': f'Bearer {os.getenv("DASHSCOPE_API_KEY", "")}', # Configure the API KEY
'Content-Type': 'application/json'
}
if __name__ == "__main__":
params = {
"input": {
"messages": [{"role": "user", "content": "What are the main multimodal models in China, and how do they compare in terms of performance and effectiveness?"}] # Pass the request message
},
"parameters": {
"agent_options": { # Set agent options
"agent_id": "${agent_id}", # The application ID. You can obtain it from the Application Management page. Example: aid-8fd***e00
"agent_version": "${agent_version}" # The application version. Can be beta for the test version or release for the published version.
}
},
"stream": True
}
response = requests.post(chat_completions_url, headers=headers, json=params, stream=True)
resultlist = []
stage = ''
action = ''
content = ''
reasoning_content = ''
for chunk in response.iter_lines():
if chunk:
chunk_str = chunk.decode('utf-8').strip()
if chunk_str.startswith('data:'):
json_str = chunk_str[len('data:'):].strip()
try:
obj = json.loads(json_str)
# Check for abnormalities
if obj.get('code') != '200':
print("Service abnormal:", obj)
# Get the message body
msg = obj.get('output', {}).get('choices', [{}])[0].get('message', {})
extra_flags = msg.get('extra', {}) # Get the model status flag field
if stage != extra_flags.get('group', ''): # Get the current model phase
print(f"agent stage: {extra_flags.get('group', '')}")
stage = extra_flags.get('group', '')
if action != extra_flags.get('step', '') and extra_flags.get('step', ''): # Get the current model step
print(f"agent action: {extra_flags.get('step', '')}")
action = extra_flags.get('step', '')
role = msg.get('role', '') # Get the model role: assistant or tool
content = msg.get('content') # Get the generated content
toolcalls = msg.get('tool_calls', []) # Get the tool calls
if toolcalls:
print(f'{toolcalls}')
if not content: # If content is empty, try to get reasoning_content from the last round of deep thinking
content = msg.get('reasoning_content', '')
if isinstance(content, str):
if role == "tool":
print("\\n" + content + "\\n", end='') # Add a line break before and after
else:
print(content, end='') # Streaming output
else:
# Note that content may not be a string
print(split_line, content)
# Save as needed
resultlist.append(obj)
except Exception as e:
print("Parsing exception:", e)
import java.io.*;
import java.net.*;
import java.util.*;
import com.alibaba.fastjson.*;
import java.nio.charset.StandardCharsets;
public class DeepSearchStreamDemo {
// Configure the API KEY
public final static String CHAT_COMPLETIONS_URL = "https://dashscope.aliyuncs.com/api/v2/apps/deep-search-agent/chat/completions";
public final static String API_KEY = System.getenv("DASHSCOPE_API_KEY");
public static void main(String[] args) throws Exception {
// Construct the parameters
Map<String, Object> params = new HashMap<>();
// input.messages
List<Map<String, Object>> messages = new ArrayList<>();
Map<String, Object> msgObj = new HashMap<>();
msgObj.put("role", "user");
msgObj.put("content", "${prompt}");
messages.add(msgObj);
// input
Map<String, Object> input = new HashMap<>();
input.put("messages", messages);
// parameters.agent_options
Map<String, Object> agentOptions = new HashMap<>(); //
agentOptions.put("agent_id", "${agent_id}");// The application ID. You can obtain it from the Application Management page. Example: aid-8fd***e00
agentOptions.put("agent_version", "${agent_version}"); // The application version. Can be beta for the test version or release for the published version.
// parameters
Map<String, Object> parameters = new HashMap<>();
parameters.put("agent_options", agentOptions);
params.put("input", input);
params.put("parameters", parameters);
params.put("stream", true);
String body = JSON.toJSONString(params);
// HTTP request
URL apiUrl = new URL(CHAT_COMPLETIONS_URL);
HttpURLConnection conn = (HttpURLConnection) apiUrl.openConnection();
conn.setRequestMethod("POST");
conn.setDoOutput(true);
conn.setRequestProperty("Authorization", "Bearer " + API_KEY);
conn.setRequestProperty("Content-Type", "application/json");
// Send the body
try (OutputStream os = conn.getOutputStream()) {
os.write(body.getBytes(StandardCharsets.UTF_8));
}
// Process the streaming response
InputStream inputStream = conn.getInputStream();
BufferedReader reader = new BufferedReader(new InputStreamReader(inputStream, StandardCharsets.UTF_8));
String line;
String stage = "";
String action = "";
List<JSONObject> resultList = new ArrayList<>();
while ((line = reader.readLine()) != null) {
if (!line.trim().isEmpty()) {
String chunkStr = line.trim();
if (chunkStr.startsWith("data:")) {
String jsonStr = chunkStr.substring(5).trim();
try {
JSONObject obj = JSON.parseObject(jsonStr);
// Check for abnormalities
if (!"200".equals(obj.getString("code"))) {
System.out.print("Service abnormal: " + obj);
}
// Get output->choices[0]->message
JSONObject msg = null;
if (obj.containsKey("output")) {
JSONObject output = obj.getJSONObject("output");
if (output != null && output.containsKey("choices")) {
JSONArray choices = output.getJSONArray("choices");
if (choices != null && !choices.isEmpty()) {
JSONObject firstChoice = choices.getJSONObject(0);
if (firstChoice.containsKey("message")) {
msg = firstChoice.getJSONObject("message");
}
}
}
}
if (msg == null) {
continue;
}
// Get the extra_flags field
JSONObject extraFlags = msg.containsKey("extra") && msg.get("extra") != null
? msg.getJSONObject("extra") : new JSONObject();
// agent stage
String stageNew = extraFlags.containsKey("group") && extraFlags.get("group") != null
? extraFlags.getString("group") : "";
if (!stage.equals(stageNew)) {
System.out.println("agent stage: " + stageNew);
}
stage = stageNew;
// agent action
String actionNew = extraFlags.containsKey("step") && extraFlags.get("step") != null
? extraFlags.getString("step") : "";
if (!action.equals(actionNew) && !actionNew.isEmpty()) {
System.out.println("agent action: " + actionNew);
}
action = actionNew;
String role = msg.containsKey("role") && msg.get("role") != null
? msg.getString("role") : "";
Object contentObj = msg.get("content");
String content = null;
boolean isContentString = false;
// content is a string type
if (contentObj instanceof String) {
content = contentObj.toString();
isContentString = true;
}
// If the string is empty, supplement with reasoning_content
if (isContentString && content.isEmpty()) {
Object reasoningContentObj = msg.get("reasoning_content");
if (reasoningContentObj instanceof String) {
content = reasoningContentObj.toString();
}
}
// Tool call
if (msg.containsKey("tool_calls") && msg.get("tool_calls") instanceof List) {
JSONArray toolCalls = msg.getJSONArray("tool_calls");
if (!toolCalls.isEmpty()) {
System.out.println(toolCalls);
}
}
// -------Output content check--------
if (isContentString) {
// If it is a string, print it directly whether it is empty or not (consistent with Python)
if ("tool".equals(role)) {
System.out.print("\\n" + content + "\\n");
} else {
System.out.print(content);
}
} else {
// If it is not a string (such as an Object or Array), print a separator line, then print the content
System.out.println("\\n------------------------------------------------------------------Report Generation Link------------------------------------------------------------------");
System.out.println(contentObj != null ? contentObj.toString() : "null");
}
// ------end----
// Save as needed
resultList.add(obj);
} catch (Exception e) {
System.out.println("Parsing exception: " + e);
}
}
}
}
reader.close();
}
}