Este tópico descreve a classe Thread na Assistant API, incluindo como criar, recuperar, modificar e excluir threads.
Visão geral : Para obter mais informações sobre os recursos e o uso básico da Assistant API, consulte a Visão geral da Assistant API .
Período de retenção : Todas as instâncias de Thread são armazenadas no servidor do Alibaba Cloud Model Studio e não expiram. Use o ID da thread para recuperar informações de contexto.
Nome da função | Tipo |
|---|---|
crie | Cria uma classe Thread. |
retrieve | Recupera uma classe Thread. |
atualize | Modifica uma classe Thread. |
exclua | Exclui uma classe Thread. |
Criar uma thread
- HTTP
- SDK
curl --location 'https://dashscope-intl.aliyuncs.com/api/v1/threads' \
--header 'Content-Type: application/json' \
--header "Authorization: Bearer $DASHSCOPE_API_KEY" \
--data '{
"messages": [
{
"role": "user",
"content": "hello"
}
]
}'
Nome do parâmetro de entrada | Descrições do parâmetro de entrada | Tipo | Obrigatório |
|---|---|---|---|
messages | As mensagens passadas para a thread. | Classe Message | Não |
metadata | Nome da thread | object | Não |
{
"id": "thread_e99a9fe7-0433-426f-98ad-a5139c36579c",
"object": "thread",
"created_at": 1711448377850,
"metadata": {},
"request_id": "dd9489ec-dbdb-95d4-9ff8-cfe29b61db27"
}
- id: O ID da thread.
- request_id: O ID da solicitação.
import json
import os
from dashscope import Threads
thread = Threads.create(
# We recommend that you set the API key as an environment variable. If not, replace the following line with api_key="sk-xxx" using your Model Studio API key.
api_key=os.getenv("DASHSCOPE_API_KEY"),
messages=[{"role": "user", "content": "How does AI work? Explain it in simple terms."}]
)
print(json.dumps(thread, default=lambda o: o.__dict__, sort_keys=True, indent=4))
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.AssistantThread;
import com.alibaba.dashscope.threads.ThreadParam;
import com.alibaba.dashscope.threads.Threads;
public class Main {
public static void main(String[] args) throws ApiException, NoApiKeyException, InputRequiredException, InvalidateParameter, InterruptedException {
Threads threads = new Threads();
// We recommend that you set the API key as an environment variable. If not, replace the following line with apiKey("sk-xxx") using your Model Studio API key.
AssistantThread assistantThread = threads.create(ThreadParam.builder()
.apiKey(System.getenv("DASHSCOPE_API_KEY"))
.build());
}
}
import json
from dashscope import Threads
import dashscope
import os
dashscope.base_http_api_url = 'https://dashscope-intl.aliyuncs.com/api/v1'
thread = Threads.create(
# We recommend that you set the API key as an environment variable. If not, replace the following line with api_key="sk-xxx" using your Model Studio API key.
api_key=os.getenv("DASHSCOPE_API_KEY"),
messages=[{"role": "user", "content": "How does AI work? Explain it in simple terms."}]
)
print(json.dumps(thread, default=lambda o: o.__dict__, sort_keys=True, indent=4))
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.AssistantThread;
import com.alibaba.dashscope.threads.ThreadParam;
import com.alibaba.dashscope.threads.Threads;
import com.alibaba.dashscope.utils.Constants;
public class Main {
static {
Constants.baseHttpApiUrl="https://dashscope-intl.aliyuncs.com/api/v1";
}
public static void main(String[] args) throws ApiException, NoApiKeyException, InputRequiredException, InvalidateParameter, InterruptedException {
Threads threads = new Threads();
// We recommend that you set the API key as an environment variable. If not, replace the following line with apiKey("sk-xxx") using your Model Studio API key.
AssistantThread assistantThread = threads.create(ThreadParam.builder()
.apiKey(System.getenv("DASHSCOPE_API_KEY"))
.build());
}
}
Parâmetro | Tipo | Valor padrão | Descrição |
|---|---|---|---|
messages | List[Dict] | None | As mensagens iniciais da thread. |
metadata | Dict | None | Pares chave-valor a serem associados à thread. |
workspace | str | None | O ID do workspace do Alibaba Cloud Model Studio. Este parâmetro é obrigatório apenas quando |
api_key | str | None | A chave de API do Alibaba Cloud Model Studio. Recomendamos que você configure a chave de API como uma variável de ambiente. |
{
"created_at": 1711338305031,
"id": "thread_97934051-2c15-44bf-97de-310039d873f9",
"metadata": {},
"object": "thread",
"request_id": "982d4b9a-b982-9d53-9c79-a75b32f7168a",
"status_code": 200
}
Nome do campo | Tipo | Descrição |
|---|---|---|
status_code | int | O código de status HTTP. O valor 200 indica que a chamada foi bem-sucedida. Outros valores indicam falha na chamada. |
id | str | O ID da thread, que é uma string UUID. |
metadata | Dict | Os pares chave-valor associados à thread. |
created_at | timestamp | O momento em que a thread foi criada. |
code | str | O código de erro retornado se a solicitação falhar. Este parâmetro não é retornado se a solicitação for bem-sucedida. Apenas Python |
message | str | A mensagem de erro. Este campo é retornado apenas quando a solicitação falha. Apenas Python |
Recuperar uma thread
- HTTP
- SDK
curl --location 'https://dashscope-intl.aliyuncs.com/api/v1/threads/thread_c7ebb0ca-2e4f-43e5-b223-6e1f8c6fccc7' \
--header 'Content-Type: application/json' \
--header "Authorization: Bearer $DASHSCOPE_API_KEY"
Nome do parâmetro | Descrição do parâmetro | Tipo | Obrigatório |
|---|---|---|---|
thread_id | O ID da thread a ser recuperada. | str | Sim |
{
"id": "thread_c7ebb0ca-2e4f-43e5-b223-6e1f8c6fccc7",
"object": "thread",
"created_at": 1711507920700,
"metadata": {},
"request_id": "4d4e73ad-15fb-96ac-9262-0643a0fdb5ca"
}
- ID: ID da thread
- request_id: O ID da solicitação.
from dashscope import Threads
import os
thread = Threads.retrieve(
'thread_id',
# We recommend that you set the API key as an environment variable. If not, replace the following line with api_key="sk-xxx" using your Model Studio API key.
api_key=os.getenv("DASHSCOPE_API_KEY")
)
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.AssistantThread;
import com.alibaba.dashscope.threads.Threads;
public class Main {
public static void main(String[] args) {
Threads threads = new Threads();
// Pass the thread_id and apiKey directly
// We recommend that you set the API key as an environment variable. If not, replace the following line with apiKey("sk-xxx") using your Model Studio API key.
AssistantThread assistantThread = threads.retrieve(
"thread_id",
System.getenv("DASHSCOPE_API_KEY")
);
}
}
from dashscope import Threads
import dashscope
import os
dashscope.base_http_api_url = 'https://dashscope-intl.aliyuncs.com/api/v1'
thread = Threads.retrieve(
'thread_id',
# We recommend that you set the API key as an environment variable. If not, replace the following line with api_key="sk-xxx" using your Model Studio API key.
api_key=os.getenv("DASHSCOPE_API_KEY")
)
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.AssistantThread;
import com.alibaba.dashscope.threads.Threads;
import com.alibaba.dashscope.utils.Constants;
public class Main {
static {
Constants.baseHttpApiUrl="https://dashscope-intl.aliyuncs.com/api/v1";
}
public static void main(String[] args) throws ApiException, NoApiKeyException, InputRequiredException, InvalidateParameter, InterruptedException {
Threads threads = new Threads();
// Pass the thread_id and apiKey directly
// We recommend that you set the API key as an environment variable. If not, replace the following line with apiKey("sk-xxx") using your Model Studio API key.
AssistantThread assistantThread = threads.retrieve(
"thread_id",
System.getenv("DASHSCOPE_API_KEY")
);
}
}
Parâmetro | Tipo | Valor padrão | Descrição |
|---|---|---|---|
thread_id | str | - | O ID da thread a ser consultada. |
workspace | str | None | O ID do workspace do Alibaba Cloud Model Studio. Este parâmetro é obrigatório apenas quando |
api_key | str | None | A chave de API do Alibaba Cloud Model Studio. Recomendamos que você configure a chave de API como uma variável de ambiente. |
Modificar uma thread
- HTTP
- SDK
curl --location 'https://dashscope-intl.aliyuncs.com/api/v1/threads/thread_c7ebb0ca-2e4f-43e5-b223-6e1f8c6fccc7' \
--header 'Content-Type: application/json' \
--header "Authorization: Bearer $DASHSCOPE_API_KEY" \
--data '{
"metadata": {
"modified": "true",
"user": "abc123"
}
}'
Nome do parâmetro de entrada | Descrições do parâmetro de entrada | Tipo | Obrigatório |
|---|---|---|---|
thread_id | O ID da thread a ser modificada. | str | Sim |
metadata | Nome da thread | dict | Não |
{
"id": "thread_c7ebb0ca-2e4f-43e5-b223-6e1f8c6fccc7",
"object": "thread",
"created_at": 1711507920700,
"metadata": {
"modified": "true",
"user": "abc123"
},
"request_id": "a9ad63fa-b884-94be-9ec6-5000882de3c4"
}
- id: thread_id
- request_id: O ID da solicitação.
from dashscope import Threads
import os
thread = Threads.update(
'thread_id',
# We recommend that you set the API key as an environment variable. If not, replace the following line with api_key="sk-xxx" using your Model Studio API key.
api_key=os.getenv("DASHSCOPE_API_KEY"),
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.Threads;
public class AssistantGeneral {
public static void main(String[] args) throws ApiException, NoApiKeyException, InputRequiredException, InvalidateParameter, InterruptedException {
Threads threads = new Threads();
UpdateMetadataParam updateMetadataParam = UpdateMetadataParam.builder()
.metadata(Collections.singletonMap("key", "value"))
// We recommend that you set the API key as an environment variable. If not, replace the following line with apiKey("sk-xxx") and use your Model Studio API key.
.apiKey(System.getenv("DASHSCOPE_API_KEY"))
.build();
threads.update("thread_id", updateMetadataParam);
}
}
from dashscope import Threads
import dashscope
import os
dashscope.base_http_api_url = 'https://dashscope-intl.aliyuncs.com/api/v1'
thread = Threads.update(
'thread_id',
# We recommend that you set the API key as an environment variable. If not, replace the following line with api_key="sk-xxx" using your Model Studio API key.
api_key=os.getenv("DASHSCOPE_API_KEY"),
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.Threads;
import com.alibaba.dashscope.utils.Constants;
public class Main {
static {
Constants.baseHttpApiUrl="https://dashscope-intl.aliyuncs.com/api/v1";
}
public static void main(String[] args) throws ApiException, NoApiKeyException, InputRequiredException, InvalidateParameter, InterruptedException {
Threads threads = new Threads();
UpdateMetadataParam updateMetadataParam = UpdateMetadataParam.builder()
.metadata(Collections.singletonMap("key", "value"))
// We recommend that you set the API key as an environment variable. If not, replace the following line with apiKey("sk-xxx") and use your Model Studio API key.
.apiKey(System.getenv("DASHSCOPE_API_KEY"))
.build();
threads.update("thread_id", updateMetadataParam);
}
}
Parâmetro | Tipo | Valor padrão | Descrição |
|---|---|---|---|
thread_id | str | - | O ID da thread a ser atualizada. |
metadata | Dict | None | As informações a serem associadas à thread. |
workspace | str | None | O ID do workspace do Alibaba Cloud Model Studio. Este parâmetro é obrigatório apenas quando |
api_key | str | None | A chave de API do Alibaba Cloud Model Studio. Recomendamos que você configure a chave de API como uma variável de ambiente. |
Excluir uma thread
- HTTP
- SDK
curl --location --request DELETE 'https://dashscope-intl.aliyuncs.com/api/v1/threads/thread_c7ebb0ca-2e4f-43e5-b223-6e1f8c6fccc7' \
--header 'Content-Type: application/json' \
--header "Authorization: Bearer $DASHSCOPE_API_KEY"
Nome do parâmetro de entrada | Descrição | Tipo | Obrigatório |
|---|---|---|---|
id | O ID da thread a ser excluída | str | Sim |
{
"id": "thread_c7ebb0ca-2e4f-43e5-b223-6e1f8c6fccc7",
"object": "thread.deleted",
"deleted": true,
"request_id": "b4edb7b8-5855-9787-b5c3-0374ee2b3b2c"
}
from dashscope import Threads
import os
thread = Threads.delete(
'thread_id',
# We recommend that you set the API key as an environment variable. If not, replace the following line with api_key="sk-xxx" using your Model Studio API key.
api_key=os.getenv("DASHSCOPE_API_KEY")
)
import com.alibaba.dashscope.common.DeletionStatus;
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.Threads;
public class Main {
public static void main(String[] args) throws ApiException, NoApiKeyException, InputRequiredException, InvalidateParameter, InterruptedException {
Threads threads = new Threads();
// We recommend that you set the API key as an environment variable. If not, replace the following line with apiKey("sk-xxx") using your Model Studio API key.
String apiKey = System.getenv("DASHSCOPE_API_KEY");
DeletionStatus assistantThread = threads.delete("thread_id", apiKey);
}
}
from dashscope import Threads
import dashscope
import os
dashscope.base_http_api_url = 'https://dashscope-intl.aliyuncs.com/api/v1'
thread = Threads.delete(
'thread_id',
# We recommend that you set the API key as an environment variable. If not, replace the following line with api_key="sk-xxx" using your Model Studio API key.
api_key=os.getenv("DASHSCOPE_API_KEY")
)
import com.alibaba.dashscope.common.DeletionStatus;
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.Threads;
import com.alibaba.dashscope.utils.Constants;
public class Main {
static {
Constants.baseHttpApiUrl="https://dashscope-intl.aliyuncs.com/api/v1";
}
public static void main(String[] args) throws ApiException, NoApiKeyException, InputRequiredException, InvalidateParameter, InterruptedException {
Threads threads = new Threads();
// We recommend that you set the API key as an environment variable. If not, replace the following line with apiKey("sk-xxx") using your Model Studio API key.
String apiKey = System.getenv("DASHSCOPE_API_KEY");
DeletionStatus assistantThread = threads.delete("thread_id", apiKey);
}
}
Parâmetro | Tipo | Valor padrão | Descrição |
|---|---|---|---|
thread_id | str | - | O ID da thread a ser excluída. |
workspace | str | None | O ID do workspace do Alibaba Cloud Model Studio. Este parâmetro é obrigatório apenas quando |
api_key | str | None | A chave de API do Alibaba Cloud Model Studio. Recomendamos que você configure a chave de API como uma variável de ambiente. |
Nome do campo | Tipo | Descrição |
|---|---|---|
id | str | O ID do objeto excluído. |
deleted | bool | Confirmação de exclusão |