Skip to main content

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 tofalseor omit it, the request fails.

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 user and assistant.

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 stop.

output.choices.[].message

object

Yes

The conversation message.

output.choices.[].message.role

str

Yes

The role. The enumeration values are user, assistant, and tool.

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 array[object] type.

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 (group)

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 (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_change value might not exist. Therefore, use the persistent step flag whenever possible.
  • For an empty package, the step, step_change, and group fields might not exist.
  • plan, think, and generation are each composed of an xxx_start event and an xxx_end event.
  • tool_call is composed of three events: tool_call_start, tool_calling, and tool_return.
  • tool_call_start indicates the start of the tool call. The system begins to collect tool call information in a stream. At this point, details such as name and arguments are not available for output. tool_calling indicates that the complete parameters for the tool call have been retrieved and are being output. tool_return indicates that the tool call has completed and includes the structured information from the tool's return value.

Step change event (step_change)

Value ofstepat event occurrence

Event name

Explanation

plan_start

planning

Start planning

The step status changes to planning. This marks the beginning of the corresponding state and includes the current package.

plan_end

planning

End planning

The step status is about to change to another state. When the event occurs, step is still planning. This marks the end of the corresponding state and includes the current package.

think_start

thinking

Start thinking

Same as the plan event.

think_end

thinking

End thinking

Same as the plan event.

report_start

reporting

Start summarizing

Same as the plan event.

report_end

reporting

End summarizing

Same as the plan event.

generation_start

generating

Start generating

Same as the plan event.

generation_end

generating

End generating

Same as the plan event.

tool_call_start

tool_calling

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_calling_{tool_name}

Tool call in progress

The specific parameters and name of the tool call are output. The tool_calling status changes to tool_calling_{tool_name}.

tool_return

tool_calling_{tool_name}

Tool return

Includes the tool return information. The step status is about to change to another state. When the event occurs, step is still tool_calling_{tool_name}.

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)
Agent Development
Agent Context
Agent Governance & Evolution
Store
Application Marketplace