Skip to main content
Modelos especializados

Deep research (Qwen-Deep-Research)

Automatiza pesquisas complexas por meio de planejamento, múltiplas rodadas de buscas na web e geração de relatórios estruturados. Coleta e sintetiza informações sem intervenção manual.

Este documento aplica-se apenas à região da China continental (Pequim). Para usar o modelo, utilize uma API key da região da China continental (Pequim).

Primeiros passos

Obtenha uma API key e exporte a API key como variável de ambiente. Se você utilizar um SDK para fazer chamadas, instale o DashScope SDK. O modelo opera em um fluxo de trabalho de duas etapas: perguntas de esclarecimento (o modelo define o escopo da pesquisa) e pesquisa profunda (o modelo busca, analisa e gera um relatório). A etapa de esclarecimento permite que o modelo compreenda exatamente o que investigar antes de iniciar um longo processo de pesquisa.
Atualmente, o modelo não oferece suporte ao DashScope SDK para Java nem a chamadas de API compatíveis com OpenAI.
import os
import dashscope

# The following is the base_url for the Beijing region.
dashscope.base_http_api_url = 'https://{WorkspaceId}.cn-beijing.maas.aliyuncs.com/api/v1'

# Configure the API key
# If not set, replace the following line with your Model Studio API key (format: sk-xxx)
API_KEY = os.getenv('DASHSCOPE_API_KEY')

def call_deep_research_model(messages, step_name):
    print(f"\n=== {step_name} ===")

    try:
        responses = dashscope.Generation.call(
            api_key=API_KEY,
            model="qwen-deep-research",
            messages=messages,
            # The qwen-deep-research model currently only supports streaming output
            stream=True
            # incremental_output=True Add this parameter for incremental output
        )

        return process_responses(responses, step_name)

    except Exception as e:
        print(f"An error occurred when calling the API: {e}")
        return ""

# Display phase content
def display_phase_content(phase, content, status):
    if content:
        print(f"\n[{phase}] {status}: {content}")
    else:
        print(f"\n[{phase}] {status}")

# Process the response
def process_responses(responses, step_name):
    current_phase = None
    phase_content = ""
    research_goal = ""
    web_sites = []
    references = []
    keepalive_shown = False  # Flag to check if the KeepAlive prompt has been shown

    for response in responses:
        # Check the response status code
        if hasattr(response, 'status_code') and response.status_code != 200:
            print(f"HTTP return code: {response.status_code}")
            if hasattr(response, 'code'):
                print(f"Error code: {response.code}")
            if hasattr(response, 'message'):
                print(f"Error message: {response.message}")
            print("For more information, see: https://www.alibabacloud.com/help/en/model-studio/developer-reference/error-code")
            continue

        if hasattr(response, 'output') and response.output:
            message = response.output.get('message', {})
            phase = message.get('phase')
            content = message.get('content', '')
            status = message.get('status')
            extra = message.get('extra', {})

            # Phase change detection
            if phase != current_phase:
                if current_phase and phase_content:
                    # Display different completion descriptions based on phase and step names
                    if step_name == "Step 1: Model query confirmation" and current_phase == "answer":
                        print(f"\n Query confirmation phase completed")
                    else:
                        print(f"\n {current_phase} phase completed")
                current_phase = phase
                phase_content = ""
                keepalive_shown = False  # Reset KeepAlive prompt flag

                # Display different descriptions based on phase and step names
                if step_name == "Step 1: Model query confirmation" and phase == "answer":
                    print(f"\n Entering query confirmation phase")
                else:
                    print(f"\n Entering {phase} phase")

            # Process reference information in the Answer phase
            if phase == "answer":
                if extra.get('deep_research', {}).get('references'):
                    new_references = extra['deep_research']['references']
                    if new_references and new_references != references:  # Avoid duplicate display
                        references = new_references
                        print(f"\n   References ({len(references)}):")
                        for i, ref in enumerate(references, 1):
                            print(f"     {i}. {ref.get('title', 'No title')}")
                            if ref.get('url'):
                                print(f"        URL: {ref['url']}")
                            if ref.get('description'):
                                print(f"        Description: {ref['description'][:100]}...")
                            print()

            # Process special information in the WebResearch phase
            # Note: The qwen-deep-research-2025-12-15 model uses the streamingThinking status
            # instead of streamingQueries and streamingWebResult
            if phase == "WebResearch":
                if extra.get('deep_research', {}).get('research'):
                    research_info = extra['deep_research']['research']

                    # Process streamingThinking (snapshot model) or streamingQueries (mainline model) status
                    if status in ("streamingThinking", "streamingQueries"):
                        if 'researchGoal' in research_info:
                            goal = research_info['researchGoal']
                            if goal:
                                research_goal += goal
                                print(f"\n   Research goal: {goal}", end='', flush=True)

                    # Process streamingWebResult status (mainline model)
                    # The snapshot model merges this status using streamingThinking
                    elif status == "streamingWebResult":
                        if 'webSites' in research_info:
                            sites = research_info['webSites']
                            if sites and sites != web_sites:  # Avoid duplicate display
                                web_sites = sites
                                print(f"\n   Found {len(sites)} relevant websites:")
                                for i, site in enumerate(sites, 1):
                                    print(f"     {i}. {site.get('title', 'No title')}")
                                    print(f"        Description: {site.get('description', 'No description')[:100]}...")
                                    print(f"        URL: {site.get('url', 'No link')}")
                                    if site.get('favicon'):
                                        print(f"        Icon: {site['favicon']}")
                                    print()

                    # Process WebResultFinished status
                    elif status == "WebResultFinished":
                        print(f"\n   Web search completed. Found {len(web_sites)} reference sources.")
                        if research_goal:
                            print(f"   Research goal: {research_goal}")

            # Accumulate and display content
            if content:
                phase_content += content
                # Display content in real-time
                print(content, end='', flush=True)

            # Display phase status changes
            if status and status != "typing":
                print(f"\n   Status: {status}")

                # Display status description
                if status == "streamingThinking":
                    print("   → Decomposing research tasks and summarizing web content (WebResearch phase)")
                elif status == "streamingQueries":
                    print("   → Generating research goals and search queries (WebResearch phase)")
                elif status == "streamingWebResult":
                    print("   → Performing searches, web page reading, and code execution (WebResearch phase)")
                elif status == "WebResultFinished":
                    print("   → Web search phase completed (WebResearch phase)")

            # When status is finished, display token consumption
            if status == "finished":
                if hasattr(response, 'usage') and response.usage:
                    usage = response.usage
                    print(f"\n    Token consumption statistics:")
                    print(f"      Input tokens: {usage.get('input_tokens', 0)}")
                    print(f"      Output tokens: {usage.get('output_tokens', 0)}")
                    print(f"      Request ID: {response.get('request_id', 'Unknown')}")

            if phase == "KeepAlive":
                # Only display the prompt the first time entering the KeepAlive phase
                if not keepalive_shown:
                    print("Current step completed. Preparing for the next step.")
                    keepalive_shown = True
                continue

    if current_phase and phase_content:
        if step_name == "Step 1: Model query confirmation" and current_phase == "answer":
            print(f"\n Query confirmation phase completed")
        else:
            print(f"\n {current_phase} phase completed")

    return phase_content

def main():
    # Check API key
    if not API_KEY:
        print("Error: DASHSCOPE_API_KEY environment variable not set")
        print("Set the environment variable or modify the API_KEY variable directly in the code")
        return

    print("User initiates conversation: Research the application of artificial intelligence in education")

    # Step 1: Model query confirmation
    # The model analyzes the user's question and asks clarifying questions to define the research direction
    messages = [{'role': 'user', 'content': 'Research the application of artificial intelligence in education'}]
    step1_content = call_deep_research_model(messages, "Step 1: Model query confirmation")

    # Step 2: Deep research
    # Based on the query confirmation from Step 1, the model performs the full research process
    messages = [
        {'role': 'user', 'content': 'Research the application of artificial intelligence in education'},
        {'role': 'assistant', 'content': step1_content},  # Includes the model's query confirmation content
        {'role': 'user', 'content': 'I mainly focus on personalized learning and intelligent assessment'}
    ]

    call_deep_research_model(messages, "Step 2: Deep research")
    print("\n Research completed!")

if __name__ == "__main__":
    main()
echo "Step 1: Model query confirmation"
# The following is the base_url for the Beijing region.
curl --location 'https://{WorkspaceId}.cn-beijing.maas.aliyuncs.com/api/v1/services/aigc/text-generation/generation' \
--header 'X-DashScope-SSE: enable' \
--header "Authorization: Bearer $DASHSCOPE_API_KEY" \
--header 'Content-Type: application/json' \
--data '{
    "input": {
        "messages": [
            {
                "content": "Research the application of artificial intelligence in education",
                "role": "user"
            }
        ]
    },
    "model": "qwen-deep-research"
}'

echo -e "\n\n"
echo "Step 2: Deep research"
# The following is the base_url for the Beijing region.
curl --location 'https://{WorkspaceId}.cn-beijing.maas.aliyuncs.com/api/v1/services/aigc/text-generation/generation' \
--header 'X-DashScope-SSE: enable' \
--header "Authorization: Bearer $DASHSCOPE_API_KEY" \
--header 'Content-Type: application/json' \
--data '{
    "input": {
        "messages": [
            {
                "content": "Research the application of artificial intelligence in education",
                "role": "user"
            },
            {
                "content": "Tell me which specific application scenarios of artificial intelligence in education you want to focus on?",
                "role": "assistant"
            },
            {
                "content": "I mainly focus on personalized learning",
                "role": "user"
            }
        ]
    },
    "model": "qwen-deep-research"
}'
import os
import dashscope

# The following is the base_url for the Beijing region.
dashscope.base_http_api_url = 'https://{WorkspaceId}.cn-beijing.maas.aliyuncs.com/api/v1'

# Configure the API key
# If not set, replace the following line with your Model Studio API key (format: sk-xxx)
API_KEY = os.getenv('DASHSCOPE_API_KEY')

def call_deep_research_model(messages, step_name):
    print(f"\n=== {step_name} ===")

    try:
        responses = dashscope.Generation.call(
            api_key=API_KEY,
            model="qwen-deep-research",
            messages=messages,
            # The qwen-deep-research model currently only supports streaming output
            stream=True
            # incremental_output=True Add this parameter for incremental output
        )

        return process_responses(responses, step_name)

    except Exception as e:
        print(f"An error occurred when calling the API: {e}")
        return ""

# Display phase content
def display_phase_content(phase, content, status):
    if content:
        print(f"\n[{phase}] {status}: {content}")
    else:
        print(f"\n[{phase}] {status}")

# Process the response
def process_responses(responses, step_name):
    current_phase = None
    phase_content = ""
    research_goal = ""
    web_sites = []
    references = []
    keepalive_shown = False  # Flag to check if the KeepAlive prompt has been shown

    for response in responses:
        # Check the response status code
        if hasattr(response, 'status_code') and response.status_code != 200:
            print(f"HTTP return code: {response.status_code}")
            if hasattr(response, 'code'):
                print(f"Error code: {response.code}")
            if hasattr(response, 'message'):
                print(f"Error message: {response.message}")
            print("For more information, see: https://www.alibabacloud.com/help/en/model-studio/error-code")
            continue

        if hasattr(response, 'output') and response.output:
            message = response.output.get('message', {})
            phase = message.get('phase')
            content = message.get('content', '')
            status = message.get('status')
            extra = message.get('extra', {})

            # Phase change detection
            if phase != current_phase:
                if current_phase and phase_content:
                    # Display different completion descriptions based on phase and step names
                    if step_name == "Step 1: Model query confirmation" and current_phase == "answer":
                        print(f"\n Query confirmation phase completed")
                    else:
                        print(f"\n {current_phase} phase completed")
                current_phase = phase
                phase_content = ""
                keepalive_shown = False  # Reset KeepAlive prompt flag

                # Display different descriptions based on phase and step names
                if step_name == "Step 1: Model query confirmation" and phase == "answer":
                    print(f"\n Entering query confirmation phase")
                else:
                    print(f"\n Entering {phase} phase")

            # Process reference information in the Answer phase
            if phase == "answer":
                if extra.get('deep_research', {}).get('references'):
                    new_references = extra['deep_research']['references']
                    if new_references and new_references != references:  # Avoid duplicate display
                        references = new_references
                        print(f"\n   References ({len(references)}):")
                        for i, ref in enumerate(references, 1):
                            print(f"     {i}. {ref.get('title', 'No title')}")
                            if ref.get('url'):
                                print(f"        URL: {ref['url']}")
                            if ref.get('description'):
                                print(f"        Description: {ref['description'][:100]}...")
                            print()

            # Process special information in the WebResearch phase
            # Note: The qwen-deep-research-2025-12-15 model uses the streamingThinking status
            # instead of streamingQueries and streamingWebResult
            if phase == "WebResearch":
                if extra.get('deep_research', {}).get('research'):
                    research_info = extra['deep_research']['research']

                    # Process streamingThinking (snapshot model) or streamingQueries (mainline model) status
                    if status in ("streamingThinking", "streamingQueries"):
                        if 'researchGoal' in research_info:
                            goal = research_info['researchGoal']
                            if goal:
                                research_goal += goal
                                print(f"\n   Research goal: {goal}", end='', flush=True)

                    # Process streamingWebResult status (mainline model)
                    # The snapshot model merges this status using streamingThinking
                    elif status == "streamingWebResult":
                        if 'webSites' in research_info:
                            sites = research_info['webSites']
                            if sites and sites != web_sites:  # Avoid duplicate display
                                web_sites = sites
                                print(f"\n   Found {len(sites)} relevant websites:")
                                for i, site in enumerate(sites, 1):
                                    print(f"     {i}. {site.get('title', 'No title')}")
                                    print(f"        Description: {site.get('description', 'No description')[:100]}...")
                                    print(f"        URL: {site.get('url', 'No link')}")
                                    if site.get('favicon'):
                                        print(f"        Icon: {site['favicon']}")
                                    print()

                    # Process WebResultFinished status
                    elif status == "WebResultFinished":
                        print(f"\n   Web search completed. Found {len(web_sites)} reference sources.")
                        if research_goal:
                            print(f"   Research goal: {research_goal}")

            # Accumulate and display content
            if content:
                phase_content += content
                # Display content in real-time
                print(content, end='', flush=True)

            # Display phase status changes
            if status and status != "typing":
                print(f"\n   Status: {status}")

                # Display status description
                if status == "streamingThinking":
                    print("   → Decomposing research tasks and summarizing web content (WebResearch phase)")
                elif status == "streamingQueries":
                    print("   → Generating research goals and search queries (WebResearch phase)")
                elif status == "streamingWebResult":
                    print("   → Performing searches, web page reading, and code execution (WebResearch phase)")
                elif status == "WebResultFinished":
                    print("   → Web search phase completed (WebResearch phase)")

            # When status is finished, display token consumption
            if status == "finished":
                if hasattr(response, 'usage') and response.usage:
                    usage = response.usage
                    print(f"\n    Token consumption statistics:")
                    print(f"      Input tokens: {usage.get('input_tokens', 0)}")
                    print(f"      Output tokens: {usage.get('output_tokens', 0)}")
                    print(f"      Request ID: {response.get('request_id', 'Unknown')}")

            if phase == "KeepAlive":
                # Only display the prompt the first time entering the KeepAlive phase
                if not keepalive_shown:
                    print("Current step completed. Preparing for the next step.")
                    keepalive_shown = True
                continue

    if current_phase and phase_content:
        if step_name == "Step 1: Model query confirmation" and current_phase == "answer":
            print(f"\n Query confirmation phase completed")
        else:
            print(f"\n {current_phase} phase completed")

    return phase_content

def main():
    # Check API key
    if not API_KEY:
        print("Error: DASHSCOPE_API_KEY environment variable not set")
        print("Set the environment variable or modify the API_KEY variable directly in the code")
        return

    print("User initiates conversation: Research the application of artificial intelligence in education")

    # Step 1: Model query confirmation
    # The model analyzes the user's question and asks clarifying questions to define the research direction
    messages = [{'role': 'user', 'content': 'Research the application of artificial intelligence in education'}]
    step1_content = call_deep_research_model(messages, "Step 1: Model query confirmation")

    # Step 2: Deep research
    # Based on the query confirmation from Step 1, the model performs the full research process
    messages = [
        {'role': 'user', 'content': 'Research the application of artificial intelligence in education'},
        {'role': 'assistant', 'content': step1_content},  # Includes the model's query confirmation content
        {'role': 'user', 'content': 'I mainly focus on personalized learning and intelligent assessment'}
    ]

    call_deep_research_model(messages, "Step 2: Deep research")
    print("\n Research completed!")

if __name__ == "__main__":
    main()
echo "Step 1: Model query confirmation"
# The following is the base_url for the Beijing region.
curl --location 'https://{WorkspaceId}.cn-beijing.maas.aliyuncs.com/api/v1/services/aigc/text-generation/generation' \
--header 'X-DashScope-SSE: enable' \
--header "Authorization: Bearer $DASHSCOPE_API_KEY" \
--header 'Content-Type: application/json' \
--data '{
    "input": {
        "messages": [
            {
                "content": "Research the application of artificial intelligence in education",
                "role": "user"
            }
        ]
    },
    "model": "qwen-deep-research"
}'

echo -e "\n\n"
echo "Step 2: Deep research"
# The following is the base_url for the Beijing region.
curl --location 'https://{WorkspaceId}.cn-beijing.maas.aliyuncs.com/api/v1/services/aigc/text-generation/generation' \
--header 'X-DashScope-SSE: enable' \
--header "Authorization: Bearer $DASHSCOPE_API_KEY" \
--header 'Content-Type: application/json' \
--data '{
    "input": {
        "messages": [
            {
                "content": "Research the application of artificial intelligence in education",
                "role": "user"
            },
            {
                "content": "Tell me which specific application scenarios of artificial intelligence in education you want to focus on?",
                "role": "assistant"
            },
            {
                "content": "I mainly focus on personalized learning",
                "role": "user"
            }
        ]
    },
    "model": "qwen-deep-research"
}'

Especificações

Modelo

Janela de contexto (tokens)

Entrada máxima (tokens)

Saída máxima (tokens)

qwen-deep-research

1.000.000

997.952

32.768

qwen-deep-research-2025-12-15

qwen-deep-research: modelo principal, atualizado continuamente. qwen-deep-research-2025-12-15: versão snapshot com maior profundidade, qualidade aprimorada e suporte a chamada de ferramentas MCP. Ambos aceitam entrada de imagem e possuem faturamento separado.

Capacidades principais

Acompanhe o progresso pelos campos phase (tarefa atual) e status (andamento da tarefa). Perguntas de esclarecimento e geração de relatório (phase: "answer") Analisa sua consulta, faz perguntas para definir o escopo e gera o relatório final da pesquisa. Valores de status:
  • typing: Geração de conteúdo textual em andamento
  • finished: Geração de conteúdo textual concluída
Planejamento de pesquisa (phase: "ResearchPlanning") Cria um esboço de pesquisa com base na sua consulta. Valores de status:
  • typing: Geração do plano de pesquisa em andamento
  • finished: Plano de pesquisa concluído
Busca na web (phase: "WebResearch") Executa múltiplas rodadas de buscas na web e análise de conteúdo. O valor WebResultFinished indica o fim de cada rodada. Já finished sinaliza o término da fase. Valores de status:
  • streamingThinking: Decomposição de tarefas de pesquisa e resumo de conteúdo web (específico do qwen-deep-research-2025-12-15, substitui streamingQueries e streamingWebResult)
  • streamingQueries: Geração de consultas de busca (apenas para qwen-deep-research)
  • streamingWebResult: Execução de buscas na web e análise de conteúdo (apenas para qwen-deep-research)
  • WebResultFinished: Rodada de busca concluída
  • finished: Fase de busca na web concluída
Manutenção de conexão (phase: "KeepAlive") Mantém a conexão ativa entre tarefas de longa duração. Ignore esta fase e continue o processamento.

Entrada de imagem

Ambos os modelos aceitam entrada de imagem. O modelo analisa a imagem e incorpora seu conteúdo à pesquisa. Utilize o formato de array no campo content, passando objetos image e text juntos.
  • Formatos suportados: JPEG, PNG, BMP, WEBP. Tamanho máximo de 10 MB por imagem.
  • Até 5 imagens por solicitação. Aceita URLs públicas e codificação Base64.
  • O formato da resposta é idêntico ao de solicitações apenas com texto. O modelo gera um relatório baseado no conteúdo da imagem.
Exemplo de solicitação
import os
import dashscope

# The following is the base_url for the Beijing region.
dashscope.base_http_api_url = 'https://{WorkspaceId}.cn-beijing.maas.aliyuncs.com/api/v1'

API_KEY = os.getenv('DASHSCOPE_API_KEY')

messages = [
    {
        "role": "user",
        "content": [
            {"image": "https://example.aliyuncs.com/example.png"},
            {"text": "Analyze the data trends in this chart and conduct in-depth research on key findings"}
        ]
    }
]

responses = dashscope.Generation.call(
    api_key=API_KEY,
    model="qwen-deep-research",
    messages=messages,
    stream=True
)

for response in responses:
    if hasattr(response, 'output') and response.output:
        message = response.output.get('message', {})
        content = message.get('content', '')
        if content:
            print(content, end='', flush=True)
curl --location 'https://{WorkspaceId}.cn-beijing.maas.aliyuncs.com/api/v1/services/aigc/text-generation/generation' \
--header 'X-DashScope-SSE: enable' \
--header "Authorization: Bearer $DASHSCOPE_API_KEY" \
--header 'Content-Type: application/json' \
--data '{
    "input": {
        "messages": [
            {
                "content": [
                    {"image": "https://example.aliyuncs.com/example.png"},
                    {"text": "Analyze the data trends in this chart and conduct in-depth research on key findings"}
                ],
                "role": "user"
            }
        ]
    },
    "model": "qwen-deep-research"
}'
import os
import dashscope

# The following is the base_url for the Beijing region.
dashscope.base_http_api_url = 'https://{WorkspaceId}.cn-beijing.maas.aliyuncs.com/api/v1'

API_KEY = os.getenv('DASHSCOPE_API_KEY')

messages = [
    {
        "role": "user",
        "content": [
            {"image": "https://example.aliyuncs.com/example.png"},
            {"text": "Analyze the data trends in this chart and conduct in-depth research on key findings"}
        ]
    }
]

responses = dashscope.Generation.call(
    api_key=API_KEY,
    model="qwen-deep-research",
    messages=messages,
    stream=True
)

for response in responses:
    if hasattr(response, 'output') and response.output:
        message = response.output.get('message', {})
        content = message.get('content', '')
        if content:
            print(content, end='', flush=True)
curl --location 'https://{WorkspaceId}.cn-beijing.maas.aliyuncs.com/api/v1/services/aigc/text-generation/generation' \
--header 'X-DashScope-SSE: enable' \
--header "Authorization: Bearer $DASHSCOPE_API_KEY" \
--header 'Content-Type: application/json' \
--data '{
    "input": {
        "messages": [
            {
                "content": [
                    {"image": "https://example.aliyuncs.com/example.png"},
                    {"text": "Analyze the data trends in this chart and conduct in-depth research on key findings"}
                ],
                "role": "user"
            }
        ]
    },
    "model": "qwen-deep-research"
}'

Chamada de ferramentas MCP

A chamada de ferramentas MCP tem suporte apenas no modelo qwen-deep-research-2025-12-15. O modelo qwen-deep-research não oferece suporte a este recurso.
A chamada de ferramentas Model Context Protocol (MCP) permite que o qwen-deep-research-2025-12-15 consulte fontes de dados privadas ou específicas de domínio durante a fase WebResearch — como bases de conhecimento, documentos internos ou bancos de dados proprietários — além das buscas padrão na web. Passe a configuração do servidor MCP por meio do parâmetro research_tools. O formato da resposta é idêntico ao das chamadas padrão.
Para obter detalhes sobre research_tools e especificações de ferramentas MCP, consulte Qwen-Deep-Research .

Exemplo de solicitação

import os
import dashscope

# The following is the base_url for the Beijing region.
dashscope.base_http_api_url = 'https://{WorkspaceId}.cn-beijing.maas.aliyuncs.com/api/v1'

API_KEY = os.getenv('DASHSCOPE_API_KEY')

messages = [
    {
        "role": "user",
        "content": "Use the knowledge base to search for recently published product update announcements and compile them into a research report"
    }
]

responses = dashscope.Generation.call(
    api_key=API_KEY,
    model="qwen-deep-research-2025-12-15",
    messages=messages,
    stream=True,
    enable_feedback=False,
    research_tools=[{
        "type": "mcp",
        "server_label": "my-server",
        "server_url": "https://your-mcp-server.example.com/sse",
        "allowed_tools": ["search", "fetch"],
        "authentication": {
            "bearer": "your_jwt_token_here"
        }
    }]
)

for response in responses:
    if hasattr(response, 'output') and response.output:
        message = response.output.get('message', {})
        content = message.get('content', '')
        if content:
            print(content, end='', flush=True)
curl --location 'https://{WorkspaceId}.cn-beijing.maas.aliyuncs.com/api/v1/services/aigc/text-generation/generation' \
--header 'X-DashScope-SSE: enable' \
--header "Authorization: Bearer $DASHSCOPE_API_KEY" \
--header 'Content-Type: application/json' \
--data '{
    "input": {
        "messages": [
            {
                "content": "Use the knowledge base to search for recently published product update announcements and compile them into a research report",
                "role": "user"
            }
        ]
    },
    "model": "qwen-deep-research-2025-12-15",
    "parameters": {
        "enable_feedback": false,
        "research_tools": [{
            "type": "mcp",
            "server_label": "my-server",
            "server_url": "https://your-mcp-server.example.com/sse",
            "allowed_tools": ["search", "fetch"],
            "authentication": {
                "bearer": "your_jwt_token_here"
            }
        }]
    }
}'
import os
import dashscope

# The following is the base_url for the Beijing region.
dashscope.base_http_api_url = 'https://{WorkspaceId}.cn-beijing.maas.aliyuncs.com/api/v1'

API_KEY = os.getenv('DASHSCOPE_API_KEY')

messages = [
    {
        "role": "user",
        "content": "Use the knowledge base to search for recently published product update announcements and compile them into a research report"
    }
]

responses = dashscope.Generation.call(
    api_key=API_KEY,
    model="qwen-deep-research-2025-12-15",
    messages=messages,
    stream=True,
    enable_feedback=False,
    research_tools=[{
        "type": "mcp",
        "server_label": "my-server",
        "server_url": "https://your-mcp-server.example.com/sse",
        "allowed_tools": ["search", "fetch"],
        "authentication": {
            "bearer": "your_jwt_token_here"
        }
    }]
)

for response in responses:
    if hasattr(response, 'output') and response.output:
        message = response.output.get('message', {})
        content = message.get('content', '')
        if content:
            print(content, end='', flush=True)
curl --location 'https://{WorkspaceId}.cn-beijing.maas.aliyuncs.com/api/v1/services/aigc/text-generation/generation' \
--header 'X-DashScope-SSE: enable' \
--header "Authorization: Bearer $DASHSCOPE_API_KEY" \
--header 'Content-Type: application/json' \
--data '{
    "input": {
        "messages": [
            {
                "content": "Use the knowledge base to search for recently published product update announcements and compile them into a research report",
                "role": "user"
            }
        ]
    },
    "model": "qwen-deep-research-2025-12-15",
    "parameters": {
        "enable_feedback": false,
        "research_tools": [{
            "type": "mcp",
            "server_label": "my-server",
            "server_url": "https://your-mcp-server.example.com/sse",
            "allowed_tools": ["search", "fetch"],
            "authentication": {
                "bearer": "your_jwt_token_here"
            }
        }]
    }
}'

Faturamento

Modelo

Custo de entrada (por 1 mil tokens)

Custo de saída (por 1 mil tokens)

Cota gratuita

qwen-deep-research

$0,007742

$0,023367

Sem cota gratuita

qwen-deep-research-2025-12-15

A determinar

A determinar

Sem cota gratuita

O faturamento baseia-se em tokens de entrada (mensagens do usuário e prompts do sistema) e tokens de saída (perguntas de esclarecimento, planos de pesquisa, objetivos, consultas de busca e o relatório final). Os dois modelos são faturados separadamente.

Colocando em produção

Utilize saída em streaming O modelo oferece suporte apenas à saída em streaming (stream=True). Uma única tarefa de pesquisa pode durar vários minutos, envolvendo dezenas de ciclos iterativos de busca e leitura, o que excede o tempo limite de uma solicitação síncrona. Use streaming para manter a conexão aberta e acompanhar o progresso pelos campos phase e status. Trate erros adequadamente Verifique o código de status da resposta em cada chunk. Para códigos diferentes de 200, leia os campos code e message e faça o tratamento apropriado. Monitore o uso de tokens Quando o status for finished, obtenha o consumo de tokens em response.usage (tokens de entrada, tokens de saída e ID da solicitação). Gerencie a manutenção de conexão A fase KeepAlive mantém a conexão ativa entre tarefas de longa duração. Ignore esta fase e continue processando o fluxo.

Perguntas frequentes

  • Por que o campo output está vazio em alguns chunks de resposta? Os primeiros chunks contêm apenas metadados. O conteúdo chega nos chunks subsequentes conforme o modelo o gera.
  • Como saber se uma fase foi concluída? Uma fase é concluída quando o status muda para finished.
  • O modelo oferece suporte a chamadas de API compatíveis com OpenAI? Não. Chamadas de API compatíveis com OpenAI não têm suporte.
  • Como são calculados os tokens de entrada e saída? Tokens de entrada: mensagens do usuário e prompts do sistema. Tokens de saída: perguntas de esclarecimento, planos de pesquisa, objetivos, consultas de busca e o relatório final.
  • Qual a diferença entre qwen-deep-research e qwen-deep-research-2025-12-15? qwen-deep-research: modelo principal, atualizado continuamente. qwen-deep-research-2025-12-15: versão snapshot com maior profundidade, qualidade aprimorada e suporte a MCP. Ambos aceitam entrada de imagem e possuem faturamento separado.
  • Como envio imagens para pesquisa? Use o formato de array no campo content: passe {"image": "URL"} e {"text": "descrição"} como objetos no array. Ambos os modelos aceitam entrada de imagem.
  • Como pular a pergunta de esclarecimento e ir direto para a pesquisa? Defina enable_feedback como false nos parameters. O modelo ignorará a pergunta de esclarecimento e iniciará a pesquisa imediatamente.

Referência da API

Para parâmetros de entrada e saída, consulte Qwen-Deep-Research.

Códigos de erro

Se a chamada do modelo falhar e retornar uma mensagem de erro, consulte Códigos de erro para resolução.

Limitação de taxa

Consulte Limitação de taxa.
Plano de Tokens
Inferência do Modelo
Avaliação
Compressão de Modelos
Estatísticas e Monitoramento
Suporte