CreateChat

Updated at:

Initiates a session with a specified DataAgent and receives the replies, execution processes, and artifacts of the agent in real time through an event stream. Multiple rounds of Q&A within the same session thread share the context, which can be used to append questions in an existing conversation, reconnect to an unfinished streaming output, or terminate an ongoing reply generation.

Operation description

Prerequisites

  • You must first create a DataAgent and obtain the session thread ID by calling CreateThread.

Streaming response

  • This operation is a streaming operation. The Content-Type of the response is text/event-stream. After the HTTP status code 200 is returned, events are continuously pushed until an event with the type stream_done is received.

  • The data field of each event is an independent JSON document rather than a replacement for the entire reply. Process the events in the order of arrival: text replies are provided as incremental fragments, and the execution processes of tools and sub-agents are provided as separate message events.

Two forms of faults

  • If a fault occurs before the first event arrives, a standard JSON fault response is returned with the corresponding HTTP status code.

  • If a fault occurs during the streaming output procedure, an event named error is received. The data field of the event contains an error field, and the HTTP status code remains 200. The client must perform simultaneous processing for both cases.

Three usages of action

  • create (default): Initiates a new round of conversation with messages.

  • reconnect: Reconnects to an unfinished conversation in the current thread without messages to continue receiving the output.

  • stop: Terminates the ongoing reply generation.

Scenarios requiring additional input

  • When the agent requires you to confirm or supplement information, an event with the type interactive is pushed. After completing the interaction on the client side, continue the session by sending a request with the action set to create and including the interaction results.

Try it now

Try this API in OpenAPI Explorer, no manual signing needed. Successful calls auto-generate SDK code matching your parameters. Download it with built-in credential security for local usage.

Test

RAM authorization

The table below describes the authorization required to call this API. You can define it in a Resource Access Management (RAM) policy. The table's columns are detailed below:

  • Action: The actions can be used in the Action element of RAM permission policy statements to grant permissions to perform the operation.

  • API: The API that you can call to perform the action.

  • Access level: The predefined level of access granted for each API. Valid values: create, list, get, update, and delete.

  • Resource type: The type of the resource that supports authorization to perform the action. It indicates if the action supports resource-level permission. The specified resource must be compatible with the action. Otherwise, the policy will be ineffective.

    • For APIs with resource-level permissions, required resource types are marked with an asterisk (*). Specify the corresponding Alibaba Cloud Resource Name (ARN) in the Resource element of the policy.

    • For APIs without resource-level permissions, it is shown as All Resources. Use an asterisk (*) in the Resource element of the policy.

  • Condition key: The condition keys defined by the service. The key allows for granular control, applying to either actions alone or actions associated with specific resources. In addition to service-specific condition keys, Alibaba Cloud provides a set of common condition keys applicable across all RAM-supported services.

  • Dependent action: The dependent actions required to run the action. To complete the action, the RAM user or the RAM role must have the permissions to perform all dependent actions.

Action

Access level

Resource type

Condition key

Dependent action

log:CreateChat

create

*DataAgent

acs:log:{#regionId}:{#accountId}:dataagent/{#name}

None None

Request syntax

POST /chat HTTP/1.1

Request parameters

Parameter

Type

Required

Description

Example

body

object

Yes

The request body in JSON format.

name

string

Yes

The name of the DataAgent, which specifies the agent for the current session. The agent must be created under the current account and you must have the permissions to access it.

my-agent

threadId

string

Yes

The session thread ID, which identifies a continuous conversation context. Multiple rounds of Q&A within the same thread share the context. You must first call CreateThread to obtain this ID.

thread-tiirv9-irwdoal8t4rm

action

string

No

The action type of the current request. Valid values:

  • create (default): Initiates a new round of conversation.

  • reconnect: Reconnects to an unfinished conversation in the current thread to continue receiving the output.

  • stop: Terminates the ongoing reply generation.

create

messages

array<object>

No

The list of messages carried in the current request. When initiating a new conversation, a message with the role set to user is typically passed. This parameter is optional when the action is reconnect or stop.

array<object>

No

A message.

messageId

string

No

The message ID, which is generated by the caller to identify the message in the current request.

msg-0001

role

string

No

The sender of the message. Set this parameter to user for user questions.

user

contents

array<object>

No

The list of message contents. A single message can carry multiple content segments.

object

No

A content segment.

type

string

No

The content type. Set this parameter to text for text content.

text

value

string

No

The content value. When the type is text, this parameter specifies the question text sent to the agent.

Count the top 10 URLs with the highest request volume in the nginx-access-log over the last hour

tools

array<object>

No

The list of tool interaction results. When the agent requires you to confirm or supplement input on the client side through an interactive event, backfill the corresponding interaction results in the next request.

object

No

The interaction result of a tool calling invoke. The fields are specified by the convention of the corresponding tool.

{"type":"confirm"}

any

No

The details of the interaction result. Common fields include type (the interaction type, such as confirm or user_input), result (the interaction result), and content (the supplementary description).

confirm

variables

object

No

The session variables in key-value pairs, which are used to pass context parameters for the current session to the agent, such as workspace, region, project, language, timeZone, startTime, and endTime. Unnecessary keys can be omitted.

{"region":"cn-hangzhou"}

any

No

The variable value. The type is defined by the corresponding key and can be a string or a number.

cn-hangzhou

Initiate a new round of conversation:

{
  "name": "my-agent",
  "threadId": "thread-tiirv9-irwdoal8t4rm",
  "action": "create",
  "messages": [
    {
      "role": "user",
      "contents": [
        { "type": "text", "value": "Count the top 10 URLs with the highest request volume in the nginx-access-log over the last hour" }
      ]
    }
  ],
  "variables": {
    "region": "cn-hangzhou",
    "project": "nginx-demo",
    "language": "zh"
  }
}

Terminate the ongoing reply generation (messages are not required):

{
  "name": "my-agent",
  "threadId": "thread-tiirv9-irwdoal8t4rm",
  "action": "stop"
}

Response elements

Element

Type

Description

Example

object

The response. This operation returns a Server-Sent Events (SSE) stream with the Content-Type set to text/event-stream. The data field of each event is a JSON document of the following structure, which is pushed multiple times while the agent generates the reply.

messages

array<object>

The list of messages pushed in the current event. Typically, it contains only one newly added message.

array<object>

A message.

agents

array<object>

The list of sub-agent calls initiated in the current message. This field may appear only when the role is assistant.

object

The information about a sub-agent call.

{"status":"start"}

any

The details of the sub-agent invocation. Common fields include name (the name of the sub-agent), arguments (the input parameters for the invocation), and status (the execution status: start, progress, success, or fail).

search_data

artifacts

array<object>

The list of artifacts (files) produced by the current message. This field may appear only when the role is assistant.

object

An artifact.

{"name":"report.md"}

any

The details of the artifact. Common fields include name (the name of the artifact) and path (the path of the artifact). You can call operations such as ListArtifacts and GetArtifact to retrieve the generated files.

report.md

callId

string

The call ID of the current execution. A message with this value as the parentCallId is its subordinate message, which can be used to restore the execution hierarchy of the agent.

call_0fdabe9ba7c645a7a6cbf34f

contents

array<object>

The list of contents of the current message.

object

A content segment.

{"type ":"text"}

any

The details of the content. Common fields include type and value. If type is text, value is a text snippet of the reply. If type is spin_text, value is a prompt for the thinking and execution process of the agent. If type is thread_title_updated, value is the updated session title. If type is error, value is an error message that contains a code and a message. During streaming output, the append (whether it is an incremental snippet) and lastChunk (whether it is the last chunk) markers are also included.

text

detail

string

The supplementary description of the current message, such as the description of the action currently being executed.

Analyzing query conditions

events

array<object>

The list of events carried in the current message, which are used to express changes in the session state. Common types include: thinking (thinking in progress), interactive (requires you to supplement input or confirm), task_finished (the current node is completed, and the payload contains success and statistics information), stream_done (the current streaming output is completed), error (an execute fault occurs), and thread_title_updated (the session title is updated).

object

An event.

{"type ":"thinking"}

any

The details of the event. Common fields include type (the type of the event) and payload (the event data, whose structure varies based on the event type).

task_finished

parentCallId

string

The ID of the parent call, which is used to restore the execution hierarchy. An empty string indicates the root node of the current session.

thread-t709p8-s24hgl7ug8jw

role

string

The producer of the message. Valid values: assistant (the reply or action of the agent), tool (the tool execution result), user (the user input), and system (the system message).

assistant

seq

integer

The message sequence number, which increments within the same session and can be used to sort messages at the same level. We recommend that you also refer to the timestamp instead of strictly relying on this value.

1

timestamp

string

The message generation time, which is a UNIX timestamp in string format.

1765289000

tools

array<object>

The list of tool calling invokes initiated by the agent in the current message. This field may appear only when the role is assistant.

object

A tool calling invoke.

{"name":"test"}

any

The details of tool invocations. Common fields include name (the name of the tool), arguments (the input parameters), status (the execution stage status: start, success, or fail), state (the execution result: success or fail), and contents (the output content of the tool).

get_current_time

type

string

The message type. This field may be absent for regular reply messages. It appears when the entire message is used to express a state, such as done indicating the end of the session and error indicating an error message.

done

version

string

The message structure version number. The current version is v0.1.0.

v0.1.0

traceId

string

The Tracing Analysis ID of the current session, which is used to locate the current invoke during troubleshooting.

88b50db22437400fa9c16c5399722310

The response is pushed by events. Each event consists of event, id, and data. The data is a complete JSON document:

event: message
id: 1
data: {"messages":[{"parentCallId":"","callId":"thread-t709p8-s24hgl7ug8jw","role":"assistant","seq":4,"timestamp":"1765289004","contents":[{"type":"text","value":"Analyzing...","append":true}]}],"traceId":"88b50db22437400fa9c16c5399722310"}

Concatenate the value of the text type in the same message in the order of arrival to form the complete reply text. The content of the spin_text type is the prompt for the thinking and execution process of the agent, which does not need to be displayed as the main text. When the task ends, events of the task_finished type (with success in the payload) and the stream_done type are received in sequence.

Examples

Success response

JSON format

{
  "messages": [
    {
      "agents": [
        {
          "key": "search_data"
        }
      ],
      "artifacts": [
        {
          "key": "report.md"
        }
      ],
      "callId": "call_0fdabe9ba7c645a7a6cbf34f",
      "contents": [
        {
          "key": "text"
        }
      ],
      "detail": "Analyzing query conditions",
      "events": [
        {
          "key": "task_finished"
        }
      ],
      "parentCallId": "thread-t709p8-s24hgl7ug8jw",
      "role": "assistant",
      "seq": 1,
      "timestamp": "1765289000",
      "tools": [
        {
          "key": "get_current_time"
        }
      ],
      "type": "done",
      "version": "v0.1.0"
    }
  ],
  "traceId": "88b50db22437400fa9c16c5399722310"
}

Error codes

See Error Codes for a complete list.

Release notes

See Release Notes for a complete list.