Skip to main content
Assistant API (Deprecated)

Introdução à Assistant API (Descontinuada)

A Assistant API oferece um conjunto de ferramentas de desenvolvimento para facilitar o gerenciamento de mensagens de conversa e a chamada de ferramentas. Este tópico usa o exemplo de criação de um assistente de pintura do zero para ajudar você a aprender rapidamente os métodos básicos de codificação da Assistant API.

A Assistant API está sendo descontinuada. Migre para a Responses API como alternativa. A Responses API inclui várias ferramentas integradas e suporta gerenciamento de contexto em múltiplos turnos.

Processo típico

O processo a seguir é típico para criar uma aplicação de agente (Assistant):
  1. Crie um Assistant: Ao criar um assistente, selecione um modelo, forneça instruções e adicione ferramentas, como um interpretador de código e chamada de função.
  2. Crie um Thread: Quando um usuário iniciar uma conversa, crie um thread de sessão para rastrear o histórico da conversa.
  3. Envie uma mensagem para o Thread: Adicione a mensagem do usuário à conversa.
  4. Inicie um Run: Execute o assistente no thread de sessão. O assistente analisa a mensagem, chama as ferramentas ou serviços apropriados, gera uma resposta e a retorna para você.

Cenário de exemplo

Modelos de geração de texto não conseguem gerar imagens por conta própria. Geralmente, é necessário um modelo específico de texto para imagem para converter texto em imagens. Uma aplicação de agente criada com a Assistant API pode otimizar automaticamente as palavras descritivas fornecidas pelo usuário, chamar uma ferramenta de texto para imagem para gerar imagens de alta qualidade. Por exemplo, para gerar uma imagem realista de um gato de estimação, basta fornecer uma descrição básica. O assistente de desenho refina automaticamente o prompt e o passa diretamente para a ferramenta de texto para imagem, concluindo eficientemente a tarefa de criação da imagem.

Procedimento

As etapas a seguir orientam você pelo processo em Python para o modo de saída sem streaming. Para obter o código completo dos SDKs Python e Java para saída com e sem streaming, consulte Código completo no final deste tópico.
image

Etapa 1: Preparar o ambiente de desenvolvimento

  • Solicite permissão para usar plugins: Primeiro, solicite permissão para usar o plugin Image Generation. Acesse a página Plug-ins no console Model Studio e clique em Apply for Plug-in no cartão correspondente.
  • Interpretador Python: A Assistant API requer Python 3.9 ou posterior. Verifique sua versão do Python. Para instalar uma versão específica do Python, consulte Download Python.
  • DashScope SDK: Recomendamos o uso da versão mais recente do DashScope SDK. Use o comando à direita para verificar sua versão. Para instalar uma versão específica do DashScope SDK, utilize o pip.
  • Chave de API: A Assistant API requer uma chave de API do Alibaba Cloud Model Studio. Você pode obter uma chave de API aqui. Ao usar o DashScope SDK pela primeira vez, recomendamos configurar a chave de API como uma variável de ambiente para evitar a exposição de informações sensíveis.
# Check the Python interpreter version
python --version
# Check the DashScope SDK
    pip list | grep dashscope
# Install DashScope SDK version 1.17.0
    pip install dashscope==1.17.0

Etapa 2: Criar um Assistant

Após importar o Dashscope SDK, use o método create da classe Assistant para criar um agente Assistant. Esse processo envolve a definição dos seguintes parâmetros principais:
  • model: o nome do modelo de linguagem grande, usado para configurar o LLM do agente
  • name: o nome do agente, usado para distingui-lo
  • description: uma descrição da função do agente
  • instructions: instruções em linguagem natural que definem o papel e a tarefa do agente
  • tools: uma lista de ferramentas configuradas para o agente
Em nosso exemplo, o objetivo é criar um Assistant focado em pintura. Como a ferramenta de texto para imagem exige alta capacidade de compreensão linguística, selecionamos o Qwen-Max como modelo de raciocínio para aprimorar a compreensão semântica e as capacidades de geração de texto do Assistant.Os detalhes de configuração do agente, incluindo nome, descrição da função e instruções, aparecem claramente no trecho de código anexo.Para enriquecer a funcionalidade e a praticidade do agente, integramos o plugin oficial pré-construído Image Generation. Isso garante que o agente possa gerar automaticamente conteúdo de imagem correspondente com base nas descrições de texto recebidas.É possível criar um número ilimitado de Assistants. No entanto, chamadas frequentes para um único modelo podem acionar o limite de taxa. Recomendamos configurar modelos diferentes para seus Assistants com base nos casos de uso.Para obter mais informações sobre como usar a API, consulte Assistants API.
import dashscope
dashscope.base_http_api_url = 'https://dashscope-intl.aliyuncs.com/api/v1'

# Create a new painting assistant using Qwen-Max
painting_assistant = dashscope.Assistants.create(
    model='qwen-max',  # Use the Qwen-Max model for enhanced understanding. Model list: https://www.alibabacloud.com/help/en/model-studio/getting-started/models
    name='Art Maestro',  # The assistant's name is "Art Maestro"
    description='An AI assistant specializing in painting and art knowledge.',
    instructions='''You are an expert painting assistant. Provide detailed information about painting techniques, art history, and creative guidance.''',
    tools=[
        {
            'type': 'text_to_image',  # A tool for generating images based on descriptions
            'description': 'Use this tool to create visual examples of a painting style, technique, or art concept.'
        }
    ]
)

# Print the assistant's ID to confirm successful creation
print(f"Painting assistant 'Art Maestro' created successfully, ID: {painting_assistant.id}")

Etapa 3: Criar um Thread

Um Thread é um conceito fundamental na Assistant API que representa um contexto de conversa contínua.O Thread permite criar um encadeamento de gerenciamento de sessão quando um usuário inicia uma nova conversa. O Assistant pode usar o Thread para compreender todo o contexto da conversa e fornecer respostas mais coerentes e relevantes.Recomendamos que você:
  • Crie um novo Thread para cada novo usuário ou novo tópico de conversa.
  • Continue usando o mesmo Thread quando precisar manter o contexto.
  • Considere criar um novo Thread quando o tópico da conversa mudar significativamente para evitar confusão de contexto.
No cenário do assistente de pintura, o Thread pode rastrear a solicitação inicial do usuário, as sugestões preliminares do Assistant, o feedback do usuário e o resultado final da pintura, formando um processo de criação completo. Isso garante a coerência e a rastreabilidade de todo o processo de criação.Para obter mais informações sobre como usar a API, consulte Threads API.
from http import HTTPStatus
import dashscope
dashscope.base_http_api_url = 'https://dashscope-intl.aliyuncs.com/api/v1'

# Create a new empty thread
thread = dashscope.Threads.create()

# Check if the thread was created successfully
if thread.status_code == HTTPStatus.OK:
    print(f"Thread created successfully. Thread ID: {thread.id}")
    print("You can now start a painting conversation with the AI assistant.")
else:
    print(f"Thread creation failed. Status code: {thread.status_code}")
    print(f"Error code: {thread.code}")
    print(f"Error message: {thread.message}")

# Note: This empty thread can now be used to maintain the context of your painting project discussion,
# including any future messages about ragdoll cats or other painting subjects.

Etapa 4: Adicionar uma mensagem a um Thread

Sua entrada é transmitida por meio de um objeto Message. A Assistant API suporta o envio de uma ou mais mensagens para um único Thread. Ao criar uma Message, considere os seguintes parâmetros:
  • O ID exclusivo do Thread: thread_id
  • O conteúdo da mensagem: content
Embora não haja um limite rígido para o número de tokens que um Thread pode receber, o número real de tokens passados para o LLM deve respeitar o limite máximo de comprimento de entrada do modelo. Para mais informações, consulte a documentação oficial de cada modelo da série Qwen sobre o comprimento do contexto.Em nosso cenário, você enviará a primeira mensagem no Thread por meio de uma Message: "Please help me draw a picture of a ragdoll cat." É necessário criar uma classe Message. As configurações detalhadas dos parâmetros estão disponíveis no trecho de código anexo.Para obter mais informações sobre como usar a API, consulte Messages.
Após a execução do método Messages.create(), a mensagem é adicionada automaticamente ao thread e o spooling é acionado. Isso equivale a concluir as operações de criação e envio da mensagem simultaneamente, que é o comportamento padrão da API.
from http import HTTPStatus
import dashscope
dashscope.base_http_api_url = 'https://dashscope-intl.aliyuncs.com/api/v1'

# Create a message to tell the assistant what to do.
message = dashscope.Messages.create(thread.id, content='Please help me draw a picture of a ragdoll cat.')

# Check if the message was created successfully
if message.status_code == HTTPStatus.OK:
    print('Message created successfully! Message ID: %s' % message.id)
else:
    print('Message creation failed. Status code: %s, Error code: %s, Error message: %s' % (message.status_code, message.code, message.message))

Etapa 5: Criar e executar um Run

Depois que um usuário atribui uma mensagem a um Thread específico, inicie um Run para ativar o Assistant pré-configurado. O assistente usa todas as mensagens no thread como contexto, utiliza o modelo especificado e os plugins disponíveis para responder inteligentemente às perguntas do usuário e insere as respostas geradas na sequência de mensagens do thread.Neste cenário, execute as seguintes etapas:
  1. Inicialize um objeto run para conduzir o assistente de pintura, passando o ID do thread (thread.id) e o ID do assistente (assistant.id).
  2. Use o método wait do objeto run (Run.wait) até que a execução seja concluída.
  3. Utilize o método de lista de mensagens (Messages.list) para recuperar a imagem do gato de estimação desenhada pelo assistente.
Essa série de operações garante um fluxo de processamento automatizado para o assistente, desde o recebimento de uma pergunta até a saída de um resultado.Para obter mais informações sobre como usar a API, consulte Runs API.
Muitos usuários podem estar usando o modelo simultaneamente, o que pode prolongar o tempo de processamento. Recomendamos aguardar até que o status mostre "complete" antes de realizar a próxima operação para garantir um processo tranquilo.
from http import HTTPStatus
import json
import dashscope
dashscope.base_http_api_url = 'https://dashscope-intl.aliyuncs.com/api/v1'

# Create a new run to execute the message
run = dashscope.Runs.create(thread.id, assistant_id=painting_assistant.id)
if run.status_code != HTTPStatus.OK:
    print('Failed to create assistant, Status code: %s, Error code: %s, Error message: %s' % (run.status_code, run.code, run.message))
else:
    print('Assistant created successfully, ID: %s' % run.id)

# Wait for the run to complete or require action
run = dashscope.Runs.wait(run.id, thread_id=thread.id)
if run.status_code != HTTPStatus.OK:
    print('Failed to get run status, Status code: %s, Error code: %s, Error message: %s' % (run.status_code, run.code, run.message))
else:
    print(run)

# Get the thread messages to get the run output
msgs = dashscope.Messages.list(thread.id)
if msgs.status_code != HTTPStatus.OK:
    print('Failed to get messages, Status code: %s, Error code: %s, Error message: %s' % (msgs.status_code, msgs.code, msgs.message))
else:
    print(json.dumps(msgs, default=lambda o: o.__dict__, sort_keys=True, indent=4))

Código completo

  • Non-streaming output
  • Streaming output
import dashscope
from http import HTTPStatus
import json

def check_status(component, operation):
    if component.status_code == HTTPStatus.OK:
        print(f"{operation} successful.")
        return True
    else:
        print(f"{operation} failed. Status code: {component.status_code}, Error code: {component.code}, Error message: {component.message}")
        return False

# 1. Create a painting assistant
painting_assistant = dashscope.Assistants.create(
    model='qwen-max',   # Model list: https://www.alibabacloud.com/help/en/model-studio/getting-started/models
    name='Art Maestro',
    description='AI assistant for painting and art knowledge',
    instructions='''Provide information on painting techniques, art history, and creative guidance.
    Use tools for research and image generation.''',
    tools=[
        {'type': 'quark_search', 'description': 'For researching art topics'},
        {'type': 'text_to_image', 'description': 'For creating visual examples'}
    ]
)

if not check_status(painting_assistant, "Assistant creation"):
    exit()

# 2. Create a new thread
thread = dashscope.Threads.create()

if not check_status(thread, "Thread creation"):
    exit()

# 3. Send a message to the thread
message = dashscope.Messages.create(thread.id, content='Please help me draw a picture of a ragdoll cat.')

if not check_status(message, "Message creation"):
    exit()

# 4. Run the assistant on the thread
run = dashscope.Runs.create(thread.id, assistant_id=painting_assistant.id)

if not check_status(run, "Run creation"):
    exit()

# 5. Wait for the run to complete
print("Waiting for the assistant to process the request...")
run = dashscope.Runs.wait(run.id, thread_id=thread.id)

if check_status(run, "Run completion"):
    print(f"Run completed, status: {run.status}")
else:
    print("Run not completed.")
    exit()

# 6. Retrieve and display the assistant's response
messages = dashscope.Messages.list(thread.id)

if check_status(messages, "Message retrieval"):
    if messages.data:
        # Display the content of the last message (the assistant's response)
        last_message = messages.data[0]
        print("\nAssistant's response:")
        print(json.dumps(last_message, ensure_ascii=False, default=lambda o: o.__dict__, sort_keys=True, indent=4))
    else:
        print("No messages found in the thread.")
else:
    print("Failed to retrieve the assistant's response.")

# Tip: This code creates a painting assistant, starts a conversation about how to draw a ragdoll cat,
# and displays the assistant's answer.
package com.example;
import java.util.Arrays;

import com.alibaba.dashscope.assistants.Assistant;
import com.alibaba.dashscope.assistants.AssistantParam;
import com.alibaba.dashscope.assistants.Assistants;
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.AssistantThread;
import com.alibaba.dashscope.threads.ThreadParam;
import com.alibaba.dashscope.threads.Threads;
import com.alibaba.dashscope.threads.messages.Messages;
import com.alibaba.dashscope.threads.messages.TextMessageParam;
import com.alibaba.dashscope.threads.messages.ThreadMessage;
import com.alibaba.dashscope.threads.runs.Run;
import com.alibaba.dashscope.threads.runs.RunParam;
import com.alibaba.dashscope.threads.runs.Runs;
import com.alibaba.dashscope.tools.T2Image.Text2Image;
import com.alibaba.dashscope.tools.search.ToolQuarkSearch;

public class PaintingAssistant {
    private static boolean checkStatus(Object response, String operation) {
        if (response != null) {
            System.out.println(operation + " successful.");
            return true;
        } else {
            System.out.println(operation + " failed.");
            return false;
        }
    }

    public static void main(String[] args) {
        try {
            // 1. Create a painting assistant
            Assistants assistants = new Assistants();
            AssistantParam assistantParam = AssistantParam.builder()
                // Model list: https://www.alibabacloud.com/help/en/model-studio/getting-started/models
                .model("qwen-max")
                .name("Art Maestro")
                .description("AI assistant for painting and art knowledge")
                .instructions("Provide information on painting techniques, art history, and creative guidance. Use tools for research and image generation.")
                .tools(Arrays.asList(ToolQuarkSearch.builder().build(),Text2Image.builder().build()))
                .build();

            Assistant paintingAssistant = assistants.create(assistantParam);
            if (!checkStatus(paintingAssistant, "Assistant creation")) {
                System.exit(1);
            }

            // 2. Create a new thread
            Threads threads = new Threads();
            AssistantThread thread = threads.create(ThreadParam.builder().build());
            if (!checkStatus(thread, "Thread creation")) {
                System.exit(1);
            }

            // 3. Create and automatically send a message to the specified thread
            Messages messages = new Messages();
            ThreadMessage message = messages.create(thread.getId(),
                TextMessageParam.builder()
                    .role("user")
                    .content("Please help me draw a picture of a ragdoll cat.")
                    .build());
            if (!checkStatus(message, "Message creation")) {
                System.exit(1);
            }

            // 4. Run the assistant on the thread
            Runs runs = new Runs();
            RunParam runParam = RunParam.builder().assistantId(paintingAssistant.getId()).build();
            Run run = runs.create(thread.getId(), runParam);
            if (!checkStatus(run, "Run creation")) {
                System.exit(1);
            }

            // 5. Wait for the run to complete
            System.out.println("Waiting for the assistant to process the request...");
            while (true) {
                if (run.getStatus().equals(Run.Status.COMPLETED) ||
                    run.getStatus().equals(Run.Status.FAILED) ||
                    run.getStatus().equals(Run.Status.CANCELLED) ||
                    run.getStatus().equals(Run.Status.REQUIRES_ACTION) ||
                    run.getStatus().equals(Run.Status.EXPIRED)) {
                    break;
                }
                Thread.sleep(1000);
                run = runs.retrieve(thread.getId(), run.getId());
            }

            if (checkStatus(run, "Run completion")) {
                System.out.println("Run completed, status: " + run.getStatus());
            } else {
                System.out.println("Run not completed.");
                System.exit(1);
            }

            // 6. Retrieve and display the assistant's response
            ListResult<ThreadMessage> messagesList = messages.list(thread.getId(), GeneralListParam.builder().build());
            if (checkStatus(messagesList, "Message retrieval")) {
                if (!messagesList.getData().isEmpty()) {
                    // Display the last message (the assistant's response)
                    ThreadMessage lastMessage = messagesList.getData().get(0);
                    System.out.println("\nAssistant's response:");
                    System.out.println(lastMessage.getContent());
                } else {
                    System.out.println("No messages found in the thread.");
                }
            } else {
                System.out.println("Failed to retrieve the assistant's response.");
            }

        } catch (ApiException | NoApiKeyException | InputRequiredException | InvalidateParameter | InterruptedException e) {
            e.printStackTrace();
        }
    }
}
  • Non-streaming output
  • Streaming output
import dashscope
from http import HTTPStatus
import json
dashscope.base_http_api_url = 'https://dashscope-intl.aliyuncs.com/api/v1'

def check_status(component, operation):
    if component.status_code == HTTPStatus.OK:
        print(f"{operation} successful.")
        return True
    else:
        print(f"{operation} failed. Status code: {component.status_code}, Error code: {component.code}, Error message: {component.message}")
        return False

# 1. Create a painting assistant
painting_assistant = dashscope.Assistants.create(
    # Model list: https://www.alibabacloud.com/help/en/model-studio/getting-started/models
    model='qwen-max',
    name='Art Maestro',
    description='AI assistant for painting and art knowledge',
    instructions='''Provide information on painting techniques, art history, and creative guidance.
    Use tools for research and image generation.''',
    tools=[
        {'type': 'text_to_image', 'description': 'For creating visual examples'}
    ]
)

if not check_status(painting_assistant, "Assistant creation"):
    exit()

# 2. Create a new thread
thread = dashscope.Threads.create()

if not check_status(thread, "Thread creation"):
    exit()

# 3. Send a message to the thread
message = dashscope.Messages.create(thread.id, content='Please help me draw a picture of a ragdoll cat.')

if not check_status(message, "Message creation"):
    exit()

# 4. Run the assistant on the thread
run = dashscope.Runs.create(thread.id, assistant_id=painting_assistant.id)

if not check_status(run, "Run creation"):
    exit()

# 5. Wait for the run to complete
print("Waiting for the assistant to process the request...")
run = dashscope.Runs.wait(run.id, thread_id=thread.id)

if check_status(run, "Run completion"):
    print(f"Run completed, status: {run.status}")
else:
    print("Run not completed.")
    exit()

# 6. Retrieve and display the assistant's response
messages = dashscope.Messages.list(thread.id)

if check_status(messages, "Message retrieval"):
    if messages.data:
        # Display the content of the last message (the assistant's response)
        last_message = messages.data[0]
        print("\nAssistant's response:")
        print(json.dumps(last_message, ensure_ascii=False, default=lambda o: o.__dict__, sort_keys=True, indent=4))
    else:
        print("No messages found in the thread.")
else:
    print("Failed to retrieve the assistant's response.")

# Tip: This code creates a painting assistant, starts a conversation about how to draw a ragdoll cat,
# and displays the assistant's answer.
package com.example;
import java.util.Arrays;
import com.alibaba.dashscope.protocol.Protocol;

import com.alibaba.dashscope.assistants.Assistant;
import com.alibaba.dashscope.assistants.AssistantParam;
import com.alibaba.dashscope.assistants.Assistants;
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.AssistantThread;
import com.alibaba.dashscope.threads.ThreadParam;
import com.alibaba.dashscope.threads.Threads;
import com.alibaba.dashscope.threads.messages.Messages;
import com.alibaba.dashscope.threads.messages.TextMessageParam;
import com.alibaba.dashscope.threads.messages.ThreadMessage;
import com.alibaba.dashscope.threads.runs.Run;
import com.alibaba.dashscope.threads.runs.RunParam;
import com.alibaba.dashscope.threads.runs.Runs;
import com.alibaba.dashscope.tools.T2Image.Text2Image;
import com.alibaba.dashscope.tools.search.ToolQuarkSearch;
import com.alibaba.dashscope.utils.Constants;

public class PaintingAssistant {
    static {
        Constants.baseHttpApiUrl="https://dashscope-intl.aliyuncs.com/api/v1";
    }
    private static boolean checkStatus(Object response, String operation) {
        if (response != null) {
            System.out.println(operation + " successful.");
            return true;
        } else {
            System.out.println(operation + " failed.");
            return false;
        }
    }

    public static void main(String[] args) {
        try {
            // 1. Create a painting assistant
            Assistants assistants = new Assistants();
            AssistantParam assistantParam = AssistantParam.builder()
                    // Model list: https://www.alibabacloud.com/help/en/model-studio/getting-started/models
                    .model("qwen-max")
                    .name("Art Maestro")
                    .description("AI assistant for painting and art knowledge")
                    .instructions("Provide information on painting techniques, art history, and creative guidance. Use tools for research and image generation.")
                    .tools(Arrays.asList(ToolQuarkSearch.builder().build(),Text2Image.builder().build()))
                    .build();

            Assistant paintingAssistant = assistants.create(assistantParam);
            if (!checkStatus(paintingAssistant, "Assistant creation")) {
                System.exit(1);
            }

            // 2. Create a new thread
            Threads threads = new Threads();
            AssistantThread thread = threads.create(ThreadParam.builder().build());
            if (!checkStatus(thread, "Thread creation")) {
                System.exit(1);
            }

            // 3. Send a message to the thread
            Messages messages = new Messages();
            ThreadMessage message = messages.create(thread.getId(),
                    TextMessageParam.builder()
                            .role("user")
                            .content("Please help me draw a picture of a ragdoll cat.")
                            .build());
            if (!checkStatus(message, "Message creation")) {
                System.exit(1);
            }

            // 4. Run the assistant on the thread
            Runs runs = new Runs();
            RunParam runParam = RunParam.builder().assistantId(paintingAssistant.getId()).build();
            Run run = runs.create(thread.getId(), runParam);
            if (!checkStatus(run, "Run creation")) {
                System.exit(1);
            }

            // 5. Wait for the run to complete
            System.out.println("Waiting for the assistant to process the request...");
            while (true) {
                if (run.getStatus().equals(Run.Status.COMPLETED) ||
                        run.getStatus().equals(Run.Status.FAILED) ||
                        run.getStatus().equals(Run.Status.CANCELLED) ||
                        run.getStatus().equals(Run.Status.REQUIRES_ACTION) ||
                        run.getStatus().equals(Run.Status.EXPIRED)) {
                    break;
                }
                Thread.sleep(1000);
                run = runs.retrieve(thread.getId(), run.getId());
            }

            if (checkStatus(run, "Run completion")) {
                System.out.println("Run completed, status: " + run.getStatus());
            } else {
                System.out.println("Run not completed.");
                System.exit(1);
            }

            // 6. Retrieve and display the assistant's response
            ListResult<ThreadMessage> messagesList = messages.list(thread.getId(), GeneralListParam.builder().build());
            if (checkStatus(messagesList, "Message retrieval")) {
                if (!messagesList.getData().isEmpty()) {
                    // Display the last message (the assistant's response)
                    ThreadMessage lastMessage = messagesList.getData().get(0);
                    System.out.println("\nAssistant's response:");
                    System.out.println(lastMessage.getContent());
                } else {
                    System.out.println("No messages found in the thread.");
                }
            } else {
                System.out.println("Failed to retrieve the assistant's response.");
            }

        } catch (ApiException | NoApiKeyException | InputRequiredException | InvalidateParameter | InterruptedException e) {
            e.printStackTrace();
        }
    }
}
  • Non-streaming output
  • Streaming output
import dashscope
from http import HTTPStatus
import json

def check_status(component, operation):
    if component.status_code == HTTPStatus.OK:
        print(f"{operation} successful.")
        return True
    else:
        print(f"{operation} failed. Status: {component.status_code}, Code: {component.code}, Message: {component.message}")
        return False

# 1. Create a painting Assistant
painting_assistant = dashscope.Assistants.create(
    model='qwen-max',  # Model list: https://www.alibabacloud.com/help/en/model-studio/getting-started/models
    name='Art Maestro',
    description='AI assistant for painting and art knowledge',
    instructions='''Provide information on painting techniques, art history, and creative guidance.
    Use tools for research and image generation.''',
    tools=[
        {'type': 'quark_search', 'description': 'For researching art topics'},
        {'type': 'text_to_image', 'description': 'For creating visual examples'}
    ]
)

if not check_status(painting_assistant, "Assistant creation"):
    exit()

# 2. Create a new thread
thread = dashscope.Threads.create()

if not check_status(thread, "Thread creation"):
    exit()

# 3. Send a message to the thread
message = dashscope.Messages.create(thread.id, content='Please help me draw a picture of a Ragdoll cat.')

if not check_status(message, "Message creation"):
    exit()

# 4. Run the Assistant on the thread
run = dashscope.Runs.create(thread.id, assistant_id=painting_assistant.id)

if not check_status(run, "Run creation"):
    exit()

# 5. Wait for the run to complete
print("Waiting for the assistant to process the request...")
run = dashscope.Runs.wait(run.id, thread_id=thread.id)

if check_status(run, "Run completion"):
    print(f"Run completed with status: {run.status}")
else:
    print("Failed to complete the run.")
    exit()

# 6. Retrieve and display the Assistant's response
messages = dashscope.Messages.list(thread.id)

if check_status(messages, "Message retrieval"):
    if messages.data:
        # Display the content of the last message (Assistant's response)
        last_message = messages.data[0]
        print("\nAssistant's response:")
        print(json.dumps(last_message, ensure_ascii=False, default=lambda o: o.__dict__, sort_keys=True, indent=4))
    else:
        print("No messages found in the thread.")
else:
    print("Failed to retrieve the assistant's response.")

# Note: This code creates a painting Assistant, starts a conversation about how to draw a Ragdoll cat,
# and displays the Assistant's response.
package com.example;
import java.util.Arrays;

import com.alibaba.dashscope.assistants.Assistant;
import com.alibaba.dashscope.assistants.AssistantParam;
import com.alibaba.dashscope.assistants.Assistants;
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.AssistantThread;
import com.alibaba.dashscope.threads.ThreadParam;
import com.alibaba.dashscope.threads.Threads;
import com.alibaba.dashscope.threads.messages.Messages;
import com.alibaba.dashscope.threads.messages.TextMessageParam;
import com.alibaba.dashscope.threads.messages.ThreadMessage;
import com.alibaba.dashscope.threads.runs.Run;
import com.alibaba.dashscope.threads.runs.RunParam;
import com.alibaba.dashscope.threads.runs.Runs;
import com.alibaba.dashscope.tools.T2Image.Text2Image;
import com.alibaba.dashscope.tools.search.ToolQuarkSearch;

public class PaintingAssistant {
    private static boolean checkStatus(Object response, String operation) {
        if (response != null) {
            System.out.println(operation + " successful.");
            return true;
        } else {
            System.out.println(operation + " failed.");
            return false;
        }
    }

    public static void main(String[] args) {
        try {
            // 1. Create the painting assistant
            Assistants assistants = new Assistants();
            AssistantParam assistantParam = AssistantParam.builder()
                .model("qwen-max")
                .name("Art Maestro")
                .description("AI assistant for painting and art knowledge")
                .instructions("Provide information on painting techniques, art history, and creative guidance. Use tools for research and image generation.")
                .tools(Arrays.asList(ToolQuarkSearch.builder().build(),Text2Image.builder().build()))
                .build();

            Assistant paintingAssistant = assistants.create(assistantParam);
            if (!checkStatus(paintingAssistant, "Assistant creation")) {
                System.exit(1);
            }

            // 2. Create a new thread
            Threads threads = new Threads();
            AssistantThread thread = threads.create(ThreadParam.builder().build());
            if (!checkStatus(thread, "Thread creation")) {
                System.exit(1);
            }

            // 3. Send a message to the thread
            Messages messages = new Messages();
            ThreadMessage message = messages.create(thread.getId(),
                TextMessageParam.builder()
                    .role("user")
                    .content("Please help me draw a picture of a Ragdoll cat.")
                    .build());
            if (!checkStatus(message, "Message creation")) {
                System.exit(1);
            }

            // 4. Run the assistant on the thread
            Runs runs = new Runs();
            RunParam runParam = RunParam.builder().assistantId(paintingAssistant.getId()).build();
            Run run = runs.create(thread.getId(), runParam);
            if (!checkStatus(run, "Run creation")) {
                System.exit(1);
            }

            // 5. Wait for the run to complete
            System.out.println("Waiting for the assistant to process the request...");
            while (true) {
                if (run.getStatus().equals(Run.Status.COMPLETED) ||
                    run.getStatus().equals(Run.Status.FAILED) ||
                    run.getStatus().equals(Run.Status.CANCELLED) ||
                    run.getStatus().equals(Run.Status.REQUIRES_ACTION)||
                    run.getStatus().equals(Run.Status.EXPIRED)) {
                    break;
                }
                Thread.sleep(1000);
                run = runs.retrieve(thread.getId(), run.getId());
            }

            if (checkStatus(run, "Run completion")) {
                System.out.println("Run completed with status: " + run.getStatus());
            } else {
                System.out.println("Failed to complete the run.");
                System.exit(1);
            }

            // 6. Retrieve and display the assistant's response
            ListResult<ThreadMessage> messagesList = messages.list(thread.getId(), GeneralListParam.builder().build());
            if (checkStatus(messagesList, "Message retrieval")) {
                if (!messagesList.getData().isEmpty()) {
                    // Display the last message (the assistant's response)
                    ThreadMessage lastMessage = messagesList.getData().get(0);
                    System.out.println("\nAssistant's response:");
                    System.out.println(lastMessage.getContent());
                } else {
                    System.out.println("No messages found in the thread.");
                }
            } else {
                System.out.println("Failed to retrieve the assistant's response.");
            }

        } catch (ApiException | NoApiKeyException | InputRequiredException | InvalidateParameter | InterruptedException e) {
            e.printStackTrace();
        }
    }
}

Próximos passos

Para obter explicações detalhadas sobre os parâmetros dos componentes da Assistant API, consulte Referência de desenvolvimento da Assistant API.