Messages (Deprecated)

更新时间:
复制 MD 格式

This topic describes how to use the Message class in the assistant API to create, list, retrieve, and modify messages.

Important

The Assistant API is being deprecated. Migrate to the Responses API as an alternative. The Responses API includes multiple built-in tools and supports multi-turn context management.

Related guide: For information about how to get started with the assistant API, see Quick Start.

Function name

Type

create

Create a message class

retrieve

Retrieve a message class

modify

Modify a message class

list

List message classes

Create a message

HTTP

Code example

curl --location 'https://dashscope.aliyuncs.com/api/v1/threads/thread_e99a9fe7-0433-426f-98ad-a5139c36579c/messages' \
--header 'Content-Type: application/json' \
--header "Authorization: Bearer $DASHSCOPE_API_KEY" \
--data '{
    "role": "user",
    "content": "Who are you",
    "metadata": {}
}'

Request parameters

Parameter name

Input Parameters

Parameter type

Required

thread id

The thread ID to which the message is passed.

string

Yes

content

The content of the message.

string

Yes

role

The role of the entity that provides the message. Only `user` is supported.

string

No

metadata

Other related information.

object

No

Response

{
    "id": "message_f1933671-19e1-4162-ad25-7326165123e1",
    "object": "thread.message",
    "created_at": 1711508433283,
    "thread_id": "thread_e99a9fe7-0433-426f-98ad-a5139c36579c",
    "incomplete_details": {},
    "completed_at": null,
    "incomplete_at": null,
    "assistant_id": "",
    "run_id": "",
    "file_ids": [],
    "role": "user",
    "content": [
        {
            "type": "text",
            "text": {
                "value": "Who are you",
                "annotations": []
            }
        }
    ],
    "metadata": {},
    "name": "",
    "plugin_call": {},
    "tool_calls": [],
    "status": "",
    "request_id": "b3ad40b9-f052-9665-a064-dab11c34625f"
}

Response parameters

The message class is returned. In addition to the request parameters, the response contains the following fields:

  • id: the message ID.

  • request_id: the request ID.

SDK

Code example

from dashscope import Messages
import os

msg = Messages.create(
    'the_thread_id',
    # Set the API key using an environment variable. If an environment variable is not set, replace the following line with api_key="sk-xxx" and your Model Studio API key.
    api_key=os.getenv("DASHSCOPE_API_KEY"),
    content='The message content.',
    role='user',
    metadata={'key': 'value'}
)
import com.alibaba.dashscope.exception.ApiException;
import com.alibaba.dashscope.exception.InputRequiredException;
import com.alibaba.dashscope.exception.InvalidateParameter;
import com.alibaba.dashscope.exception.NoApiKeyException;
import com.alibaba.dashscope.threads.messages.Messages;
import com.alibaba.dashscope.threads.messages.TextMessageParam;
import com.alibaba.dashscope.threads.messages.ThreadMessage;

public class Main {
    public static void main(String[] args) throws ApiException, NoApiKeyException, InputRequiredException, InvalidateParameter, InterruptedException {
        // create a message to thread
        Messages messages = new Messages();
        TextMessageParam param = TextMessageParam.builder()
                // Set the API key using an environment variable. If an environment variable is not set, replace the following line with .apiKey("sk-xxx") and your Model Studio API key.
                .apiKey(System.getenv("DASHSCOPE_API_KEY"))
                .role("user")
                .content("How to make delicious beef and potato stew?")
                .build();
        ThreadMessage message = messages.create("threadId", param);
    }
}

Request parameters

Parameter

Type

Default

Description

thread_id

string

-

The thread ID.

content

string

-

The message content.

role

str

'user'

The role of the message. Default value: user.

metadata

Dict

None

The key-value information associated with the message.

workspace

string

None

The Workspace ID of Alibaba Cloud Model Studio. This parameter is required only when the `api_key` is an API key for a sub-workspace.

api_key

string

None

The API key for Alibaba Cloud Model Studio. We recommend that you configure the API key as an environment variable.

Response

The result is a Message object. The following code shows an example of the JSON-formatted content:

{
    "id": "message_05494921-a646-484e-85fc-76329acba842",
    "object": "thread.message",
    "created_at": 1711345341301,
    "thread_id": "thread_f1e7737e-b045-479f-99d1-510db49d535b",
    "incomplete_details": {},
    "completed_at": null,
    "incomplete_at": null,
    "assistant_id": "",
    "run_id": "",
    "file_ids": [],
    "role": "user",
    "content": [
        {
            "type": "text",
            "text": {
                "value": "sdhafjdasf",
                "annotations": []
            }
        }
    ],
    "metadata": {
        "key": "value"
    },
    "name": "",
    "plugin_call": {},
    "tool_calls": [],
    "status": "",
    "status_code": 200,
    "request_id": "631de0b3-7e50-9c9e-8444-0924d1b7e7a5"
}

Response parameters

Field name

Field type

Field description

status_code

int

The HTTP status code of the call. A value of 200 indicates that the call is successful. Other values indicate that the call failed.

id

string

The message ID, which is a UUID string.

content

List[dict]

The message content.

content.type

string

The content type, such as text.

content.text

dict

Content

content.text.value

string

text value of the content

metadata

Dict

The key-value information associated with this message.

tool_calls

Dict

The tool call information.

plugin_call

Dict

The plugin call information.

created_at

timestamp

The time when the assistant was created.

gmt_created

datetime

2024-03-22 17:12:31

gmt_modified

datetime

2024-03-22 17:12:31

code

string

Indicates that the request failed. This parameter specifies the error code. This parameter is ignored if the request is successful.

Python only.

message

string

Indicates that the request failed. This parameter provides detailed information about the failure. This parameter is ignored if the request is successful.

Python only.

List messages

HTTP

Code example

curl --location 'https://dashscope.aliyuncs.com/api/v1/threads/thread_e99a9fe7-0433-426f-98ad-a5139c36579c/messages?limit=2&order=desc' \
--header 'Content-Type: application/json' \
--header "Authorization: Bearer $DASHSCOPE_API_KEY"

Request parameters

Parameter name

Description

Parameter type

Required

thread id

The thread ID to which the message is passed.

string

Yes

limit

Number of messages

integer

No

order

The sorting order by creation time: `asc` or `desc`.

string

No (Default: `desc`)

Response

{
    "object": "list",
    "data": [
        {
            "id": "message_f1933671-19e1-4162-ad25-7326165123e1",
            "object": "thread.message",
            "created_at": 1711508433283,
            "thread_id": "thread_e99a9fe7-0433-426f-98ad-a5139c36579c",
            "assistant_id": "",
            "run_id": "",
            "role": "user",
            "content": [
                {
                    "type": "text",
                    "text": {
                        "value": "Who are you",
                        "annotations": []
                    }
                }
            ],
            "metadata": {},
            "name": "",
            "plugin_call": {},
            "tool_calls": [],
            "status": ""
        }
    ],
    "first_id": "message_f1933671-19e1-4162-ad25-7326165123e1",
    "last_id": "message_f1933671-19e1-4162-ad25-7326165123e1",
    "has_more": false,
    "request_id": "78f7d607-4a9a-90c6-8040-d3f81c84d60a"
}

Response parameters

A list of message classes is returned. The response also includes the original request parameters and the following additional fields:

  • A list of multiple messages.

SDK

Code example

from dashscope import Messages
import os

messages = Messages.list(
    'thread_id',
    # Set the API key using an environment variable. If an environment variable is not set, replace the following line with api_key="sk-xxx" and your Model Studio API key.
    api_key=os.getenv("DASHSCOPE_API_KEY"),
    limit=1,
    order='desc'
)
import com.alibaba.dashscope.common.GeneralListParam;
import com.alibaba.dashscope.common.ListResult;
import com.alibaba.dashscope.exception.ApiException;
import com.alibaba.dashscope.exception.InputRequiredException;
import com.alibaba.dashscope.exception.InvalidateParameter;
import com.alibaba.dashscope.exception.NoApiKeyException;
import com.alibaba.dashscope.threads.messages.Messages;
import com.alibaba.dashscope.threads.messages.ThreadMessage;

public class Main {
    public static void main(String[] args) throws ApiException, NoApiKeyException, InputRequiredException, InvalidateParameter, InterruptedException {
        Messages messages = new Messages();
        // Set the API key using an environment variable. If an environment variable is not set, replace the following line with .apiKey("sk-xxx") and your Model Studio API key.
        GeneralListParam listThreadMessages = GeneralListParam.builder()
                .apiKey(System.getenv("DASHSCOPE_API_KEY"))
                .build();
        ListResult<ThreadMessage> message = messages.list("threadId", listThreadMessages);
    }
}

Request parameters

Parameter

Type

Default

Description

thread_id

string

-

The ID of the thread to query.

limit

int

None

The number of messages to retrieve.

order

string

None

The sorting order by `created_at`.

workspace

string

None

The Alibaba Cloud Model Studio Workspace ID, which is required only when the `api_key` is an API key for a sub-workspace.

api_key

string

None

The API key for Alibaba Cloud Model Studio. We recommend that you set the API key as an environment variable.

Response Parameters

Field name

Field type

Field description

has_more

boolean

Indicates whether more messages can be retrieved.

last_id

string

The ID of the last message in the returned list.

first_id

string

The ID of the first message in the returned list.

data

list[Message]

A list of Message objects.

Retrieve a message

HTTP

Code example

curl --location 'https://dashscope.aliyuncs.com/api/v1/threads/thread_e99a9fe7-0433-426f-98ad-a5139c36579c/messages/message_ea26d29d-4509-490e-98e9-9f6238bd821b' \
--header 'Content-Type: application/json' \
--header "Authorization: Bearer $DASHSCOPE_API_KEY"

Request parameters

Parameter name

Description

Parameter type

Required

thread id

The thread ID of the message to retrieve.

string

Yes

message_id

The ID of the message to retrieve.

string

Yes

Response

{
    "id": "message_ea26d29d-4509-490e-98e9-9f6238bd821b",
    "object": "thread.message",
    "created_at": 1711508622598,
    "thread_id": "thread_e99a9fe7-0433-426f-98ad-a5139c36579c",
    "assistant_id": "",
    "run_id": "",
    "role": "user",
    "content": [
        {
            "type": "text",
            "text": {
                "value": "Hello",
                "annotations": []
            }
        }
    ],
    "metadata": {},
    "name": "",
    "plugin_call": {},
    "tool_calls": [],
    "status": "",
    "request_id": "4d5ce962-91c3-9edb-87f7-00bbf985135e"
}

Response parameters

The retrieved message class is returned. In addition to the request parameters, the response contains the following fields:

  • id: Message ID

  • request_id: the request ID.

SDK

Code example

from dashscope import Messages
import os

message = Messages.retrieve(
    'message_id',
    # Set the API key using an environment variable. If an environment variable is not set, replace the following line with api_key="sk-xxx" and your Model Studio API key.
    api_key=os.getenv("DASHSCOPE_API_KEY"),
    thread_id='thread_id'
)
import com.alibaba.dashscope.exception.ApiException;
import com.alibaba.dashscope.exception.InputRequiredException;
import com.alibaba.dashscope.exception.InvalidateParameter;
import com.alibaba.dashscope.exception.NoApiKeyException;
import com.alibaba.dashscope.threads.messages.Messages;
import com.alibaba.dashscope.threads.messages.ThreadMessage;

public class Main {
    public static void main(String[] args) throws ApiException, NoApiKeyException, InputRequiredException, InvalidateParameter, InterruptedException {
        Messages messages = new Messages();
        // Set the API key using an environment variable. If an environment variable is not set, replace the following line with .apiKey("sk-xxx") and your Model Studio API key.
        String apiKey = System.getenv("DASHSCOPE_API_KEY");
        ThreadMessage message = messages.retrieve("threadId", "messageId", apiKey);
    }
}

Request parameters

Parameter

Type

Default

Description

message_id

string

-

The ID of the message to query.

thread_id

string

-

The ID of the thread to which the message belongs.

workspace

string

None

The Workspace ID of Alibaba Cloud Model Studio. This parameter is required only when the api_key is a sub-workspace API Key.

api_key

string

None

The API key for Alibaba Cloud Model Studio. We recommend that you configure the API key as an environment variable.

Response parameters

See the response for the create operation.

Modify a message

HTTP

Code example

curl --location 'https://dashscope.aliyuncs.com/api/v1/threads/thread_e99a9fe7-0433-426f-98ad-a5139c36579c/messages/message_ea26d29d-4509-490e-98e9-9f6238bd821b' \
--header 'Content-Type: application/json' \
--header "Authorization: Bearer $DASHSCOPE_API_KEY" \
--data '{
    "metadata": {
        "modified": "true",
        "user": "abc123"
    }
}'

Request parameters

Parameter name

Input Parameters

Parameter type

Required

thread_id

The ID of the thread to modify.

string

Yes

message_id

The ID of the message to modify.

string

Yes

metadata

The metadata.

dict

Response

{
    "id": "message_ea26d29d-4509-490e-98e9-9f6238bd821b",
    "object": "thread.message",
    "created_at": 1711508622598,
    "thread_id": "thread_e99a9fe7-0433-426f-98ad-a5139c36579c",
    "incomplete_details": {},
    "completed_at": null,
    "incomplete_at": null,
    "assistant_id": "",
    "run_id": "",
    "file_ids": [],
    "role": "user",
    "content": [
        {
            "type": "text",
            "text": {
                "value": "Hello",
                "annotations": []
            }
        }
    ],
    "metadata": {
        "modified": "true",
        "user": "abc123"
    },
    "name": "",
    "plugin_call": {},
    "tool_calls": [],
    "status": "",
    "request_id": "7877b011-cb94-9df1-9add-dc42b7d611f6"
}

Output Parameters

The modified message class is returned. In addition to the request parameters, the response contains the following fields:

  • id: Message ID

  • request_id: the request ID.

SDK

Code example

from dashscope import Messages

import os

thread = Messages.update(
    'message_id',
    # Set the API key using an environment variable. If an environment variable is not set, replace the following line with api_key="sk-xxx" and your Model Studio API key.
    api_key=os.getenv("DASHSCOPE_API_KEY"),
    thread_id='the_message_thread_id',
    metadata={'key': 'value'}
)
import java.util.Collections;
import com.alibaba.dashscope.common.UpdateMetadataParam;
import com.alibaba.dashscope.exception.ApiException;
import com.alibaba.dashscope.exception.InputRequiredException;
import com.alibaba.dashscope.exception.InvalidateParameter;
import com.alibaba.dashscope.exception.NoApiKeyException;
import com.alibaba.dashscope.threads.messages.Messages;

public class Main {
    public static void main(String[] args) throws ApiException, NoApiKeyException, InputRequiredException, InvalidateParameter, InterruptedException {
        Messages messages = new Messages();
        // Set the API key using an environment variable. If an environment variable is not set, replace the following line with .apiKey("sk-xxx") and your Model Studio API key.
        UpdateMetadataParam updateMetadataParam = UpdateMetadataParam.builder()
                .metadata(Collections.singletonMap("key", "value"))
                .apiKey(System.getenv("DASHSCOPE_API_KEY"))
                .build();
        messages.update("thread_id", "message_Id", updateMetadataParam);
    }
}

Request parameters

Parameter

Type

Default

Description

message_id

string

-

The ID of the message to update.

thread_id

string

-

The ID of the thread to which the message to be updated belongs.

metadata

Dict

None

The information associated with the thread.

workspace

string

None

The Workspace ID of Alibaba Cloud Model Studio, which is required only when the api_key is a sub-workspace API Key.

api_key

string

None

The API key for Alibaba Cloud Model Studio. We recommend that you configure the API key as an environment variable.

Response parameters

See the response for the create operation.

Error codes

If an assistant API call fails and returns an error message, see Error messages to resolve the issue.