Skip to main content
Toolkit/Framework

Compatível com OpenAI - Responses

O Alibaba Cloud Model Studio oferece suporte à API Responses compatível com OpenAI. Baseada na API Chat Completions, a API Responses simplifica a funcionalidade nativa de agentes.

Vantagens em relação à API Chat Completions da OpenAI:
  • Ferramentas integradas: Melhore os resultados em tarefas complexas com busca na web, extração de conteúdo web, interpretador de código, conversão de texto em imagem e transformação de imagens. Para mais detalhes, consulte Call built-in tools.
  • Entrada mais flexível: A API aceita tanto strings diretas quanto arrays de mensagens no formato padrão de chat.
  • Gerenciamento de contexto simplificado: Ao passar o parâmetro previous_response_id, você elimina a necessidade de construir manualmente um array completo com o histórico de mensagens.
Consulte OpenAI Responses API reference para obter detalhes sobre os parâmetros.

Pré-requisitos

Primeiramente, get an API key e set it as an environment variable. Caso utilize o SDK da OpenAI, install the SDK.
O caminho legado /api/v2/apps/protocols/compatible-mode/v1/responses da API Responses compatível com OpenAI será descontinuado em breve. Migre para o novo caminho /compatible-mode/v1/responses o mais rápido possível.
O Alibaba Cloud Model Studio lançou domínios específicos por workspace para as regiões China (Beijing), Singapore e China (Hong Kong). Os novos domínios dedicados oferecem desempenho superior e maior estabilidade para requisições de inferência. Recomendamos a migração para os novos domínios:
  • China (Beijing): de https://dashscope.aliyuncs.com para https://{WorkspaceId}.cn-beijing.maas.aliyuncs.com
  • Singapore: de https://dashscope-intl.aliyuncs.com para https://{WorkspaceId}.ap-southeast-1.maas.aliyuncs.com
  • China (Hong Kong): de https://cn-hongkong.dashscope.aliyuncs.com para https://{WorkspaceId}.cn-hongkong.maas.aliyuncs.com
O valor {WorkspaceId} corresponde ao ID do seu workspace, disponível na página Workspace Details no console do Alibaba Cloud Model Studio. O domínio existente permanece totalmente funcional.

Modelos suportados

qwen3.8-max, qwen3.8-flash, qwen3.7-max, qwen3.7-max-2026-05-20, qwen3.7-max-2026-06-08, qwen3.7-max-2026-05-17, qwen3.7-max-preview, qwen3-max, qwen3-max-2026-01-23, qwen3.7-plus, qwen3.7-plus-2026-05-26, qwen3.6-plus, qwen3.6-plus-2026-04-02, qwen3.5-plus, qwen3.5-plus-2026-04-20, qwen3.5-plus-2026-02-15, qwen3.7-flash, qwen3.7-flash-2026-07-15, qwen3.6-flash, qwen3.6-flash-2026-04-16, qwen3.5-flash, qwen3.5-flash-2026-02-23, qwen3.8-2.4t-a95b, qwen3.8-27b, qwen3.6-35b-a3b, qwen3.5-397b-a17b, qwen3.5-122b-a10b, qwen3.5-27b, qwen3.5-35b-a3b, deepseek-v4-pro, deepseek-v4-pro-0813, deepseek-v4-flash, deepseek-v4-flash-0731, glm-5.2, kimi-k3
Os modelos de geração de texto que não constam na lista acima, mas disponíveis através do Alibaba Cloud Model Studio, suportam apenas funcionalidades básicas de compatibilidade. As capacidades de Agent (ferramentas integradas, etc.) são limitadas.

Endpoints

  • Singapore
  • China (Beijing)
  • US (Virginia)
  • China (Hong Kong)
  • Germany (Frankfurt)
  • Japan (Tokyo)
Configuração de chamada via SDK base_url: https://{WorkspaceId}.ap-southeast-1.maas.aliyuncs.com/compatible-mode/v1URL para requisição HTTP: POST https://{WorkspaceId}.ap-southeast-1.maas.aliyuncs.com/compatible-mode/v1/responsesSubstitua WorkspaceId pelo seu Workspace ID real.

Exemplos de código

Chamada básica

Envie uma mensagem e obtenha uma resposta.
Python
import os
from openai import OpenAI

client = OpenAI(
    # If an environment variable is not set, replace with your API key: api_key="sk-xxx"
    api_key=os.getenv("DASHSCOPE_API_KEY"),
    base_url="https://{WorkspaceId}.ap-southeast-1.maas.aliyuncs.com/compatible-mode/v1",
)

response = client.responses.create(
    model="qwen3.8-max",
    input="What can you do?"
)

# Get model response
# print(response.model_dump_json())
print(response.output_text)
Exemplo de resposta
Esta é uma resposta completa da API.
{
    "created_at": 1771226624,
    "id": "bf0d5c2e-f14b-9ad7-bc0d-ee0c8c9ee2d8",
    "model": "qwen3-max-2026-01-23",
    "object": "response",
    "output": [
        {
            "content": [
                {
                    "annotations": [],
                    "text": "Hi there!  I'm actually quite ......",
                    "type": "output_text"
                }
            ],
            "id": "msg_1e17fdb2-5fc3-4c78-a9e9-cbd78eb043f0",
            "role": "assistant",
            "status": "completed",
            "type": "message"
        }
    ],
    "parallel_tool_calls": false,
    "status": "completed",
    "tool_choice": "auto",
    "tools": [],
    "usage": {
        "input_tokens": 37,
        "input_tokens_details": {
            "cached_tokens": 0
        },
        "output_tokens": 220,
        "output_tokens_details": {
            "reasoning_tokens": 0
        },
        "total_tokens": 257,
        "x_details": [
            {
                "input_tokens": 37,
                "output_tokens": 220,
                "total_tokens": 257,
                "x_billing_type": "response_api"
            }
        ]
    }
}

Conversa com múltiplas turnos

O parâmetro previous_response_id mantém automaticamente o contexto da conversa, eliminando a necessidade de montar manualmente o histórico de mensagens. Cada id de resposta tem validade de 7 dias.
O previous_response_id deve ser o id de nível superior da resposta anterior (por exemplo, resp_xxx , no formato UUID), e não o id da mensagem dentro do array output (por exemplo, msg_56c860c4-3ad8-4a96-8553-d2f94c259xxx ).
Python
import os
from openai import OpenAI

client = OpenAI(
    api_key=os.getenv("DASHSCOPE_API_KEY"),
    base_url="https://{WorkspaceId}.ap-southeast-1.maas.aliyuncs.com/compatible-mode/v1",
)

# First round
response1 = client.responses.create(
    model="qwen3.8-max",
    input="My name is John, please remember it."
)
print(f"First response: {response1.output_text}")

# Second round - use previous_response_id to link context
# The response id expires in 7 days
response2 = client.responses.create(
    model="qwen3.8-max",
    input="Do you remember my name?",
    previous_response_id=response1.id
)
print(f"Second response: {response2.output_text}")
Exemplo de resposta do segundo turno
{
  "id": "f0dbb153-117f-9bbf-8176-5284b47f3xxx",
  "created_at": 1769173209.0,
  "model": "qwen3.8-max",
  "object": "response",
  "status": "completed",
  "output": [
    {
      "id": "msg_56c860c4-3ad8-4a96-8553-d2f94c259xxx",
      "type": "message",
      "role": "assistant",
      "status": "completed",
      "content": [
        {
          "type": "output_text",
          "text": "Yes, John! I remember your name. How can I assist you today?",
          "annotations": []
        }
      ]
    }
  ],
  "usage": {
    "input_tokens": 78,
    "output_tokens": 16,
    "total_tokens": 94,
    "input_tokens_details": {
      "cached_tokens": 0
    },
    "output_tokens_details": {
      "reasoning_tokens": 0
    }
  }
}
Nota: No segundo turno, a contagem de input_tokens é 78. Esse número inclui o contexto do primeiro turno, demonstrando que o modelo memorizou com sucesso o nome "John".

Raciocínio profundo

Utilize o parâmetro reasoning para controlar a intensidade do raciocínio do modelo. Ao definir reasoning.effort, o modelo pensa antes de responder e retorna o processo de raciocínio em um item de saída reasoning. O parâmetro effort aceita os seguintes valores:
  • none: Desativa o raciocínio e fornece uma resposta direta.
  • minimal: Minimiza o raciocínio para obter a resposta mais rápida.
  • low: Executa um raciocínio leve, priorizando uma resposta rápida.
  • medium (padrão): Realiza um raciocínio moderado, equilibrando velocidade e profundidade.
  • high: Efetua um raciocínio profundo, focado em problemas complexos e especializados.
Não é possível usar o parâmetro thinking_budget para controlar o tamanho máximo do raciocínio. reasoning.effort tem precedência sobre enable_thinking . Utilize reasoning.effort , pois enable_thinking será descontinuado.
Python
import os
from openai import OpenAI

client = OpenAI(
    api_key=os.getenv("DASHSCOPE_API_KEY"),
    base_url="https://{WorkspaceId}.ap-southeast-1.maas.aliyuncs.com/compatible-mode/v1",
)

response = client.responses.create(
    model="qwen3.8-max",
    input="Which is larger, 9.9 or 9.11?",
    reasoning={"effort": "medium"}
)

# Process the output
for item in response.output:
    if item.type == "reasoning":
        print("=== Thinking Process ===")
        for summary in item.summary:
            print(summary.text)
    elif item.type == "message":
        print("\n=== Final Answer ===")
        print(item.content[0].text)

# Check the thinking token count
print(f"\nThinking token count: {response.usage.output_tokens_details.reasoning_tokens}")
Exemplo de resposta
{
    "created_at": 1774498317,
    "id": "resp_xxx",
    "model": "qwen3.8-max",
    "object": "response",
    "output": [
        {
            "id": "msg_xxx",
            "summary": [
                {
                    "text": "Thinking Process:\n\n1.  Analyze the Request:\n    *   Question: \"Which is larger, 9.9 or 9.11?\"\n    *   Context: The user is asking a simple mathematical comparison question.\n    *   Current Date: Thursday, March 26, 2026 (provided in the system prompt).\n    *   Knowledge Cutoff: 2026 (provided in the system prompt).\n\n2.  Evaluate the Numbers:\n    *   Number A: 9.9\n    *   Number B: 9.11\n    *   These are decimal numbers.\n    *   Compare the integer part: Both are 9.\n    *   Compare the tenths place (first decimal digit):\n        *   9.9 has 9 in the tenths place.\n        *   9.11 has 1 in the tenths place.\n    *   Since 9 > 1, 9.9 is greater than 9.11.\n\n3.  Consider Potential Ambiguities:\n    *   Could this be version numbering? (e.g., software versions). In versioning, 9.11 is often \"newer\" or \"higher\" than 9.9. However, mathematically, 9.9 > 9.11.\n    *   Could this be dates? (September 9th vs September 11th). 11th is later.\n    *   Standard interpretation: Without context, decimal numbers are assumed to be mathematical values.\n    *   Common pitfall: Some people mistakenly treat decimals like whole numbers (where 11 > 9), leading them to think 9.11 > 9.9. This is a known cognitive bias or misconception in elementary math.\n    *   Decision: Provide the mathematical answer clearly, but perhaps acknowledge the versioning context if relevant (though usually, for this specific question, it's a math test). Given the simplicity, stick to the mathematical truth first.\n\n4.  Formulate the Answer:\n    *   Direct answer: 9.9 is larger.\n    *   Explanation: Compare place values. 9.9 = 9.90, 9.11 = 9.11. 90 hundredths > 11 hundredths.\n    *   Tone: Helpful, clear.\n\n5.  Drafting the Response (Internal Monologue/Draft):\n    *   Okay, mathematically 9.9 is bigger. 9.9 is 9 and 9 tenths. 9.11 is 9 and 11 hundredths (or 1 tenth and 1 hundredth). 9 tenths is more than 1 tenth.\n    *   So, 9.9 > 9.11.\n    *   I should answer in English since the question is in English.\n    *   \"9.9 is larger.\"\n    *   Add a brief explanation to avoid confusion. \"Because 9.9 equals 9.90, and 9.90 is greater than 9.11.\"\n\n6.  Refining based on \"Version Number\" possibility:\n    *   Sometimes this is a trick question about software versions. In semver, 9.11 > 9.9.\n    *   However, usually, when asked plainly \"which is larger\", it refers to numerical value.\n    *   I will provide the numerical answer as primary, maybe add a note about versions if it feels necessary. But keeping it simple is better. Most likely, this is testing the decimal comparison logic.\n    *   Let's stick to the mathematical value as the default.\n\n7.  Final Polish:\n    *   Answer: 9.9 is larger.\n    *   Reasoning: When comparing decimals, first look at the integer part, then the tenths place. The tenths digit of 9.9 is 9, and the tenths digit of 9.11 is 1. Since 9 > 1, 9.9 > 9.11.\n\n8.  Output Generation: (Matching the thought process)\n    *   State clearly which is larger.\n    *   Explain why.\n\n    *Self-Correction on Date/Time:* The system prompt mentions the current date is 2026. This doesn't affect the math question, but I should ensure I don't reference anything post-2026 if I were adding context (not needed here).\n\n    *Final Decision:* Just answer the math question directly.\n\n    \"Numerically, 9.9 is larger.\"\n    Explain: 9.9 = 9.90, 9.11 = 9.11. 90 > 11.\n\n    Wait, is there any other interpretation?\n    - Dates? 9/9 vs 9/11. 11th is later.\n    - Versions? 9.11 is newer.\n    - But \"who is big/larger\" usually implies magnitude.\n    - I will answer based on numerical magnitude but briefly mention the version context if it adds value without confusing. Actually, better to be decisive. Numerical value is the standard interpretation for \"who is larger\" with numbers.\n\n    Let's go with the numerical answer.\n\n    Plan:\n    1. State 9.9 is larger numerically.\n    2. Explain the decimal comparison.\n    3. (Optional but helpful) Mention that if it's version numbers, 9.11 might be considered \"higher\". But prioritize the math.\n    Actually, for a simple query like this, over-explaining versions might be confusing. I'll stick to the math but acknowledge the common confusion.\n\n    *Revised Plan:*\n    1. Direct answer: 9.9 is larger (mathematically).\n    2. Explanation: Place value.\n    3. Note: Unless it's a version number.\n\n    Let's keep it concise.\n\n    \"In terms of mathematical value, 9.9 is larger.\"\n    \"Because 9.9 equals 9.90, which is greater than 9.11.\"\n    \"If it's a version number, version 9.11 is usually higher than version 9.9.\"\n    This covers both bases.\n\n    Wait, looking at common AI training, this is often a \"trap\" question to see if the AI treats decimals like integers. The correct mathematical answer is crucial.\n\n    Okay, final output structure:\n    1. Mathematical answer.\n    2. Brief explanation.\n    3. Contextual note (versions).\n\n    Let's write it.\n    \"In terms of mathematical value, 9.9 is larger.\"\n    \"When comparing decimals, first compare the integer part (both are 9), then the tenths place: The tenths digit of 9.9 is 9, while the tenths digit of 9.11 is 1. Because 9 > 1, 9.9 > 9.11.\"\n    \"However, if these are software version numbers, version 9.11 is typically newer than version 9.9.\"\n\n    This is balanced.\n\n    Wait, I need to check the instruction again. \"Please remember the current actual time...\". This is just system context. I don't need to mention the date in the answer unless relevant. It's not relevant here.\n\n    Okay, ready to generate.\n\n    Wait, one more check. Is there any cultural context? In some contexts, people might say 9.11 is bigger because 11 > 9. This is the misconception I need to correct.\n    So, emphasizing the mathematical rule is key.\n\n    Final check:\n    9.9 = 9 + 9/10 = 9.90\n    9.11 = 9 + 1/10 + 1/100 = 9.11\n    9.90 > 9.11. Correct.\n\n    Response will be in English.\n    \"In terms of numerical value, 9.9 is larger.\"\n    Explain why.\n    Mention version exception.\n    Done.\n",
                    "type": "summary_text"
                }
            ],
            "type": "reasoning"
        },
        {
            "content": [
                {
                    "annotations": [],
                    "text": "In terms of mathematical value, 9.9 is larger.\n\nHere's why:\nWhen comparing decimals, you first look at the integer part, which is 9 for both. Then you look at the tenths place (the first digit after the decimal point):\n*   The tenths digit of 9.9 is 9\n*   The tenths digit of 9.11 is 1\n\nSince 9 is greater than 1, 9.9 > 9.11 (you can think of 9.9 as 9.90 for comparison).\n\nNote: If these were software version numbers, version 9.11 would typically be considered newer (or higher) than version 9.9. However, in a direct numerical comparison, 9.9 is larger.",
                    "type": "output_text"
                }
            ],
            "id": "msg_xxx",
            "role": "assistant",
            "status": "completed",
            "type": "message"
        }
    ],
    "parallel_tool_calls": false,
    "status": "completed",
    "tool_choice": "auto",
    "tools": [],
    "usage": {
        "input_tokens": 57,
        "input_tokens_details": {
            "cached_tokens": 0
        },
        "output_tokens": 2018,
        "output_tokens_details": {
            "reasoning_tokens": 1861
        },
        "total_tokens": 2075,
        "x_details": [
            {
                "input_tokens": 57,
                "output_tokens": 2018,
                "output_tokens_details": {
                    "reasoning_tokens": 1861
                },
                "total_tokens": 2075,
                "x_billing_type": "response_api"
            }
        ]
    }
}

Saída em stream

Receba o conteúdo do modelo em tempo real, recurso especialmente útil para geração de textos longos.
Python
import os
from openai import OpenAI

client = OpenAI(
    api_key=os.getenv("DASHSCOPE_API_KEY"),
    base_url="https://{WorkspaceId}.ap-southeast-1.maas.aliyuncs.com/compatible-mode/v1",
)

stream = client.responses.create(
    model="qwen3.8-max",
    input="Please briefly introduce artificial intelligence.",
    stream=True
)

print("Receiving stream output:")
for event in stream:
    # print(event.model_dump_json())  # Uncomment to see raw event response
    if event.type == 'response.output_text.delta':
        print(event.delta, end='', flush=True)
    elif event.type == 'response.completed':
        print("\nStream completed")
        print(f"Total tokens: {event.response.usage.total_tokens}")
Exemplo de resposta
{"response":{"id":"47a71e7d-868c-4204-9693-ef8ff9058xxx","created_at":1769417481.0,"error":null,"incomplete_details":null,"instructions":null,"metadata":null,"model":"","object":"response","output":[],"parallel_tool_calls":false,"temperature":null,"tool_choice":"auto","tools":[],"top_p":null,"background":null,"completed_at":null,"conversation":null,"max_output_tokens":null,"max_tool_calls":null,"previous_response_id":null,"prompt":null,"prompt_cache_key":null,"prompt_cache_retention":null,"reasoning":null,"safety_identifier":null,"service_tier":null,"status":"queued","text":null,"top_logprobs":null,"truncation":null,"usage":null,"user":null},"sequence_number":0,"type":"response.created"}
{"response":{"id":"47a71e7d-868c-4204-9693-ef8ff9058xxx","created_at":1769417481.0,"error":null,"incomplete_details":null,"instructions":null,"metadata":null,"model":"","object":"response","output":[],"parallel_tool_calls":false,"temperature":null,"tool_choice":"auto","tools":[],"top_p":null,"background":null,"completed_at":null,"conversation":null,"max_output_tokens":null,"max_tool_calls":null,"previous_response_id":null,"prompt":null,"prompt_cache_key":null,"prompt_cache_retention":null,"reasoning":null,"safety_identifier":null,"service_tier":null,"status":"in_progress","text":null,"top_logprobs":null,"truncation":null,"usage":null,"user":null},"sequence_number":1,"type":"response.in_progress"}
{"item":{"id":"msg_16db29d6-c1d3-47d7-9177-0fba81964xxx","content":[],"role":"assistant","status":"in_progress","type":"message"},"output_index":0,"sequence_number":2,"type":"response.output_item.added"}
{"content_index":0,"item_id":"msg_16db29d6-c1d3-47d7-9177-0fba81964xxx","output_index":0,"part":{"annotations":[],"text":"","type":"output_text","logprobs":null},"sequence_number":3,"type":"response.content_part.added"}
{"content_index":0,"delta":"Artificial","item_id":"msg_16db29d6-c1d3-47d7-9177-0fba81964xxx","logprobs":[],"output_index":0,"sequence_number":4,"type":"response.output_text.delta"}
{"content_index":0,"delta":" intelligence","item_id":"msg_16db29d6-c1d3-47d7-9177-0fba81964xxx","logprobs":[],"output_index":0,"sequence_number":5,"type":"response.output_text.delta"}
{"content_index":0,"delta":" (","item_id":"msg_16db29d6-c1d3-47d7-9177-0fba81964xxx","logprobs":[],"output_index":0,"sequence_number":6,"type":"response.output_text.delta"}
{"content_index":0,"delta":"AI","item_id":"msg_16db29d6-c1d3-47d7-9177-0fba81964xxx","logprobs":[],"output_index":0,"sequence_number":7,"type":"response.output_text.delta"}
... (intermediate events omitted) ...
{"content_index":0,"delta":"fields, and is profoundly changing our","item_id":"msg_16db29d6-c1d3-47d7-9177-0fba81964xxx","logprobs":[],"output_index":0,"sequence_number":38,"type":"response.output_text.delta"}
{"content_index":0,"delta":" lives and ways of working","item_id":"msg_16db29d6-c1d3-47d7-9177-0fba81964xxx","logprobs":[],"output_index":0,"sequence_number":39,"type":"response.output_text.delta"}
{"content_index":0,"delta":".","item_id":"msg_16db29d6-c1d3-47d7-9177-0fba81964xxx","logprobs":[],"output_index":0,"sequence_number":40,"type":"response.output_text.delta"}
{"content_index":0,"item_id":"msg_16db29d6-c1d3-47d7-9177-0fba81964xxx","logprobs":[],"output_index":0,"sequence_number":41,"text":"Artificial intelligence (AI) is the technology and science of simulating human intelligent behavior by using computer systems. xxxx","type":"response.output_text.done"}
{"content_index":0,"item_id":"msg_16db29d6-c1d3-47d7-9177-0fba81964xxx","output_index":0,"part":{"annotations":[],"text":"Artificial intelligence (AI) is the technology and science of simulating human intelligent behavior by using computer systems. xxx","type":"output_text","logprobs":null},"sequence_number":42,"type":"response.content_part.done"}
{"item":{"id":"msg_16db29d6-c1d3-47d7-9177-0fba81964xxx","content":[{"annotations":[],"text":"Artificial intelligence (AI) is the technology and science of simulating human intelligent behavior by using computer systems. It aims to enable machines to perform tasks that typically require human intelligence, such as:\n\n- Learning (for example, training models with data)  \n- Reasoning (for example, logical judgment and problem-solving)  \n- Perception (for example, recognizing images, speech, or text)  \n- Understanding language (for example, natural language processing)  \n- Decision-making (for example, making optimal choices in complex environments)\n\nAI can be divided into weak AI (focused on specific tasks, such as voice assistants and recommendation systems) and strong AI (possessing general, human-like intelligence, which has not yet been achieved).\n\nCurrently, AI is widely used in various fields, including healthcare, finance, transportation, education, and entertainment, and is profoundly changing the way we live and work.","type":"output_text","logprobs":null}],"role":"assistant","status":"completed","type":"message"},"output_index":0,"sequence_number":43,"type":"response.output_item.done"}
{"response":{"id":"47a71e7d-868c-4204-9693-ef8ff9058xxx","created_at":1769417481.0,"error":null,"incomplete_details":null,"instructions":null,"metadata":null,"model":"qwen3.8-max","object":"response","output":[{"id":"msg_16db29d6-c1d3-47d7-9177-0fba81964xxx","content":[{"annotations":[],"text":"Artificial intelligence (AI) is xxxxxx","type":"output_text","logprobs":null}],"role":"assistant","status":"completed","type":"message"}],"parallel_tool_calls":false,"temperature":null,"tool_choice":"auto","tools":[],"top_p":null,"background":null,"completed_at":null,"conversation":null,"max_output_tokens":null,"max_tool_calls":null,"previous_response_id":null,"prompt":null,"prompt_cache_key":null,"prompt_cache_retention":null,"reasoning":null,"safety_identifier":null,"service_tier":null,"status":"completed","text":null,"top_logprobs":null,"truncation":null,"usage":{"input_tokens":37,"input_tokens_details":{"cached_tokens":0},"output_tokens":166,"output_tokens_details":{"reasoning_tokens":0},"total_tokens":203},"user":null},"sequence_number":44,"type":"response.completed"}

Uso de ferramentas integradas

Ative as ferramentas integradas para tarefas complexas. O extrator web e o interpretador de código são gratuitos por tempo limitado. Consulte tool calling para ver as ferramentas suportadas.
Python
import os
from openai import OpenAI

client = OpenAI(
    api_key=os.getenv("DASHSCOPE_API_KEY"),
    base_url="https://{WorkspaceId}.ap-southeast-1.maas.aliyuncs.com/compatible-mode/v1",
)

response = client.responses.create(
    model="qwen3.8-max",
    input="Find the Alibaba Cloud website and extract key information from the homepage",
    # For best results, enable all the built-in tools.
    tools=[
        {"type": "web_search"},
        {"type": "code_interpreter"},
        {"type": "web_extractor"}
    ],
    reasoning={"effort": "medium"}
)

# Uncomment the following line to see the intermediate output.
# print(response.output)
print(response.output_text)
Exemplo de resposta
{
    "id": "69258b21-5099-9d09-92e8-8492b1955xxx",
    "object": "response",
    "status": "completed",
    "output": [
        {
            "type": "reasoning",
            "summary": [
                {
                    "type": "summary_text",
                    "text": "The user wants to find the Alibaba Cloud website and extract information..."
                }
            ]
        },
        {
            "type": "web_search_call",
            "status": "completed",
            "action": {
                "query": "Alibaba Cloud official website",
                "type": "search",
                "sources": [
                    {
                        "type": "url",
                        "url": "https://cn.aliyun.com/"
                    },
                    {
                        "type": "url",
                        "url": "https://www.alibabacloud.com/zh"
                    }
                ]
            }
        },
        {
            "type": "reasoning",
            "summary": [
                {
                    "type": "summary_text",
                    "text": "The search results show the Alibaba Cloud website URL..."
                }
            ]
        },
        {
            "type": "web_extractor_call",
            "status": "completed",
            "goal": "Extract key information from the Alibaba Cloud homepage",
            "output": "Tongyi Large Language Model, full product portfolio, AI solutions...",
            "urls": [
                "https://cn.aliyun.com/"
            ]
        },
        {
            "type": "message",
            "role": "assistant",
            "status": "completed",
            "content": [
                {
                    "type": "output_text",
                    "text": "Key information from the Alibaba Cloud website: Tongyi Large Language Model, cloud computing services..."
                }
            ]
        }
    ],
    "usage": {
        "input_tokens": 40836,
        "output_tokens": 2106,
        "total_tokens": 42942,
        "output_tokens_details": {
            "reasoning_tokens": 677
        },
        "x_tools": {
            "web_extractor": {
                "count": 1
            },
            "web_search": {
                "count": 1
            }
        }
    }
}

Cache de sessão

Em conversas com múltiplos turnos, ative o cache de sessão para permitir que o servidor armazene automaticamente o contexto da conversa. Isso reduz a latência e os custos sem exigir gerenciamento manual de cache. Uso: Para ativar o cache de sessão, adicione x-dashscope-session-cache: enable ao cabeçalho da requisição. Para desativá-lo, defina o valor como disable. O valor padrão é disable. Comportamento do cache:
  • Cache de sessão ativado:
    • Modelo com suporte a cache explícito: Utiliza o cache explícito. Para faturamento e restrições, consulte Explicit cache.
    • Modelo sem suporte a cache explícito, mas com suporte a cache implícito: Utiliza o cache implícito. Para faturamento e restrições, consulte Implicit cache.
  • Cache de sessão não ativado: Comporta-se como chamadas normais da API. O cache implícito ainda é ativado automaticamente para modelos compatíveis, porém sem os benefícios do cache de sessão.
Python
import os
from openai import OpenAI

client = OpenAI(
    api_key=os.getenv("DASHSCOPE_API_KEY"),
    base_url="https://{WorkspaceId}.ap-southeast-1.maas.aliyuncs.com/compatible-mode/v1",
    # Enable session cache via default_headers
    default_headers={"x-dashscope-session-cache": "enable"}
)

# Construct a long text exceeding 1024 tokens to trigger cache creation.
# (If the initial prompt is under 1024 tokens, the server creates the cache once the total context exceeds this threshold.)
long_context = "Artificial intelligence is an important branch of computer science that focuses on the research and development of theories, methods, technologies, and application systems that can simulate, extend, and expand human intelligence." * 50

# First request
response1 = client.responses.create(
    model="qwen3.8-max",
    input=long_context + "\n\nBased on the background knowledge above, briefly introduce the random forest algorithm in machine learning.",
)
print(f"First response: {response1.output_text}")

# Second request: Link the context using previous_response_id. The server manages the cache automatically.
response2 = client.responses.create(
    model="qwen3.8-max",
    input="What are the main differences between it and GBDT?",
    previous_response_id=response1.id,
)
print(f"Second response: {response2.output_text}")

# Check the cache hit status
usage = response2.usage
print(f"Input tokens: {usage.input_tokens}")
print(f"Cached tokens: {usage.input_tokens_details.cached_tokens}")

Migrar da API Chat Completions para a API Responses

A API Responses simplifica a interface da API Chat Completions mantendo a compatibilidade. Para migrar, siga estas etapas.

1. Atualize o endereço do endpoint

Atualize o endereço do endpoint de /v1/chat/completions para /v1/responses.
Python
# Chat Completions API
completion = client.chat.completions.create(
    model="qwen3.8-max",
    messages=[
        {"role": "system", "content": "You are a helpful assistant."},
        {"role": "user", "content": "Hello!"}
    ]
)
print(completion.choices[0].message.content)

# Responses API - can use the same message format
response = client.responses.create(
    model="qwen3.8-max",
    input=[
        {"role": "system", "content": "You are a helpful assistant."},
        {"role": "user", "content": "Hello!"}
    ]
)
print(response.output_text)

# Responses API - or use a more concise format
response = client.responses.create(
    model="qwen3.8-max",
    input="Hello!"
)
print(response.output_text)

2. Atualize o tratamento da resposta

A API Responses retorna uma estrutura de resposta diferente. Use o atalho output_text para recuperar a saída de texto ou acesse informações detalhadas por meio do array output. Comparação de respostas
# Chat Completions Response
{
  "id": "chatcmpl-416b0ea5-e362-9fec-97c5-0a60b5d7xxx",
  "choices": [
    {
      "finish_reason": "stop",
      "index": 0,
      "logprobs": null,
      "message": {
        "content": "Hello! I'm happy to see you~  How can I help you?",
        "refusal": null,
        "role": "assistant",
        "function_call": null,
        "tool_calls": null
      }
    }
  ],
  "created": 1769416269,
  "model": "qwen3.8-max",
  "object": "chat.completion",
  "service_tier": null,
  "system_fingerprint": null,
  "usage": {
    "completion_tokens": 14,
    "prompt_tokens": 22,
    "total_tokens": 36,
    "prompt_tokens_details": {
      "cached_tokens": 0
    }
  }
}
# Responses API Response
    {
      "id": "d69c735d-0f5e-4b6c-9c2a-8cab5eb14xxx",
      "created_at": 1769416269.0,
      "model": "qwen3.8-max",
      "object": "response",
      "status": "completed",
      "output": [
        {
          "id": "msg_3426d3e5-8da7-4dd8-a6a5-7c2cd866xxx",
          "type": "message",
          "role": "assistant",
          "status": "completed",
          "content": [
            {
              "type": "output_text",
              "text": "Hello! Today is Monday, January 26, 2026. How can I help you? ",
              "annotations": []
            }
          ]
        }
      ],
      "usage": {
        "input_tokens": 34,
        "output_tokens": 25,
        "total_tokens": 59,
        "input_tokens_details": {
          "cached_tokens": 0
        },
        "output_tokens_details": {
          "reasoning_tokens": 0
        }
      }
    }

3. Simplifique conversas com múltiplos turnos

Com a API Chat Completions, é necessário gerenciar manualmente o array de histórico de mensagens. A API Responses simplifica esse processo usando o parâmetro previous_response_id para vincular automaticamente o contexto da conversa. O id da resposta tem validade de 7 dias.
  • Python
  • Node.js
# Chat Completions - manual message history management
messages = [
    {"role": "system", "content": "You are a helpful assistant."},
    {"role": "user", "content": "What is the capital of France?"}
]
res1 = client.chat.completions.create(
    model="qwen3.8-max",
    messages=messages
)

# Manually add response to history
messages.append(res1.choices[0].message)
messages.append({"role": "user", "content": "What is its population?"})

res2 = client.chat.completions.create(
    model="qwen3.8-max",
    messages=messages
)
# Responses API - automatic linking with previous_response_id
    res1 = client.responses.create(
        model="qwen3.8-max",
        input="What is the capital of France?"
    )

    # Just pass the previous response ID
    res2 = client.responses.create(
        model="qwen3.8-max",
        input="What is its population?",
        previous_response_id=res1.id
    )

4. Utilize ferramentas integradas

A API Responses inclui ferramentas integradas. Especifique-as no parâmetro tools. As ferramentas Code Interpreter e busca na web são gratuitas por tempo limitado. Consulte tool calling.
  • Python
  • Node.js
  • Curl
# Chat Completions - you need to implement tools yourself
def web_search(query):
    # Need to implement web search logic yourself
    import requests
    r = requests.get(f"https://api.example.com/search?q={query}")
    return r.json().get("results", [])

completion = client.chat.completions.create(
    model="qwen3.8-max",
    messages=[{"role": "user", "content": "Who is the current president of France?"}],
    functions=[{
        "name": "web_search",
        "description": "Search the web for information",
        "parameters": {
            "type": "object",
            "properties": {"query": {"type": "string"}},
            "required": ["query"]
        }
    }]
)
# Responses API - use built-in tools directly
    response = client.responses.create(
        model="qwen3.8-max",
        input="Who is the current president of France?",
        tools=[{"type": "web_search"}]  # Enable web search directly
    )
    print(response.output_text)

Perguntas frequentes

P: Como passar o contexto de uma conversa com múltiplos turnos?

R: Passe o id da resposta anterior bem-sucedida do modelo como o parâmetro previous_response_id na sua próxima requisição de conversa.

P: Por que não consigo imprimir 'output_text'?

R: Esse atributo está ausente em algumas versões do SDK Python da OpenAI, como a 1.99.2. Para resolver esse erro, atualize o SDK para a versão mais recente.

Relacionados

Referência da API de Geração de Texto
Geração de Imagens
  • FAQ
Geração de Vídeo
Áudio
API em tempo real
Incorporação de Texto
Produção de Modelos