Skip to main content

Compatible con OpenAI - Responses

Alibaba Cloud Model Studio admite la API de Responses compatible con OpenAI. Basándose en la API de Chat Completions, la API de Responses agiliza la funcionalidad nativa de agentes.

Ventajas sobre la API de Chat Completions de OpenAI:
  • Herramientas integradas: Mejore los resultados para tareas complejas con búsqueda web, extracción web, un intérprete de código, texto a imagen e imagen a imagen. Para más detalles, consulte Llamar a herramientas integradas.
  • Entrada más flexible: La API admite tanto entradas directas de cadenas como matrices de mensajes en el formato de chat estándar.
  • Gestión simplificada del contexto: Pasar el previous_response_id elimina la necesidad de construir manualmente una matriz completa de historial de mensajes.
Consulte la referencia de la API de Responses de OpenAI para obtener detalles sobre los parámetros.

Requisitos previos

Primero, obtenga una clave de API y configúrela como una variable de entorno. Si utiliza el SDK de OpenAI, instale el SDK.
La ruta heredada /api/v2/apps/protocols/compatible-mode/v1/responses para la API de Responses compatible con OpenAI ya no se mantiene y su funcionalidad ya no está garantizada. Migre a la nueva ruta /compatible-mode/v1/responses lo antes posible.
Alibaba Cloud Model Studio ha lanzado dominios específicos de espacio de trabajo para las regiones de China (Pekín), Singapur y China (Hong Kong). Los nuevos dominios dedicados ofrecen un rendimiento superior y una mayor estabilidad para las solicitudes de inferencia. Recomendamos migrar a los nuevos dominios:
  • China (Pekín): de https://dashscope.aliyuncs.com a https://{WorkspaceId}.cn-beijing.maas.aliyuncs.com
  • Singapur: de https://dashscope-intl.aliyuncs.com a https://{WorkspaceId}.ap-southeast-1.maas.aliyuncs.com
  • China (Hong Kong): de https://cn-hongkong.dashscope.aliyuncs.com a https://{WorkspaceId}.cn-hongkong.maas.aliyuncs.com
{WorkspaceId} es su ID de espacio de trabajo, que se encuentra en la página Workspace Details de la consola de Alibaba Cloud Model Studio. El dominio existente permanece totalmente funcional.

Modelos admitidos

qwen4-max-preview (solo Token Plan), qwen3.8-max, qwen3.8-max-0902, qwen3.8-flash, qwen3.8-2.4t-a95b, qwen3.8-27b, qwen3.8-omni-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.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.6-35b-a3b, qwen3.5-397b-a17b, qwen3.5-122b-a10b, qwen3.5-27b, qwen3.5-35b-a3b, deepseek-v4.1-flash, deepseek-v4.1-flash-1017, deepseek-v4-pro, deepseek-v4-pro-0813, deepseek-v4-flash-0731, glm-5.3, glm-5.2, kimi-k3
Los modelos de generación de texto que no están en la lista anterior pero que están disponibles a través de Alibaba Cloud Model Studio solo admiten funciones básicas de compatibilidad. Las capacidades de agente (herramientas integradas, etc.) son limitadas.
Para entrada de audio/video con qwen3.8-omni-flash, consulte la guía Omni. El modelo produce salida de texto.

Endpoints

  • Singapore
  • China (Beijing)
  • EE. UU. (Virginia)
  • Hong Kong (China)
  • Germany (Frankfurt)
  • Japan (Tokyo)
Configuración de llamada del SDK base_url: https://{WorkspaceId}.ap-southeast-1.maas.aliyuncs.com/compatible-mode/v1URL de solicitud HTTP: POST https://{WorkspaceId}.ap-southeast-1.maas.aliyuncs.com/compatible-mode/v1/responsesReemplace WorkspaceId con su ID de espacio de trabajo real.

Ejemplos de código

Llamada básica

Envíe un mensaje y obtenga una respuesta.
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)
Ejemplo de respuesta
Esta es una respuesta completa de la API.
{
    "created_at": 1771226624,
    "id": "bf0d5c2e-f14b-9ad7-bc0d-ee0c8c9ee2d8",
    "model": "qwen3.8-max",
    "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"
            }
        ]
    }
}

Conversación multironda

El parámetro previous_response_id mantiene automáticamente el contexto de la conversación, por lo que no necesita construir manualmente el historial de mensajes. Cada id de respuesta es válido durante 7 días.
El previous_response_id debe ser el id de nivel superior de la respuesta anterior (por ejemplo, resp_xxx, en formato UUID), no el id del mensaje dentro de la matriz output (por ejemplo, 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}")
Ejemplo de respuesta de segunda ronda
{
  "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: En la segunda ronda, el recuento de input_tokens es 78. Este número incluye el contexto de la primera ronda, lo que demuestra que el modelo recordó correctamente el nombre "John".

Pensamiento profundo

Use reasoning.effort para controlar la intensidad del pensamiento. Los valores admitidos y los valores predeterminados dependen del modelo; consulte la referencia del parámetro reasoning. El pensamiento se devuelve como un elemento de salida reasoning. El ejemplo de qwen3.8-max a continuación usa reasoning.effort, que tiene prioridad sobre enable_thinking. No admite thinking_budget para limitar la longitud del pensamiento.
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}")
Ejemplo de respuesta
{
    "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"
            }
        ]
    }
}

Salida en streaming

Reciba contenido del modelo en tiempo real, especialmente útil para la generación de texto extenso.
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}")
Ejemplo de respuesta
{"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 herramientas integradas

Habilite las herramientas integradas para tareas complejas. El extractor web y el intérprete de código son gratuitos por tiempo limitado. Consulte llamada de herramientas para ver las herramientas admitidas. Para qwen3.8-omni-flash, la única herramienta integrada admitida es web_search. También se admiten herramientas personalizadas de tipo function.
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)
Ejemplo de respuesta
{
    "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
            }
        }
    }
}

Caché de sesión

En conversaciones multironda, habilite el caché de sesión para permitir que el servidor almacene en caché el contexto de la conversación automáticamente. Esto reduce la latencia y los costos sin necesidad de gestión manual del caché. El almacenamiento en caché implícito automático se describe por separado en Caché de contexto. Uso: Para habilitar el caché de sesión, agregue x-dashscope-session-cache: enable al encabezado de la solicitud. Para deshabilitarlo, establezca el valor en disable. El valor predeterminado es disable. Comportamiento de caché:
  • Caché de sesión habilitado:
    • El modelo admite caché explícito: Usa caché explícito. Para facturación y restricciones, consulte Caché explícito.
    • El modelo no admite caché explícito pero sí admite caché implícito: Usa caché implícito. Para facturación y restricciones, consulte Caché implícito.
  • Caché de sesión no habilitado: Igual que las llamadas normales a la API. El caché implícito sigue habilitándose automáticamente para los modelos que lo admiten, pero sin los beneficios del caché de sesión.
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}")

Migración de la API de Chat Completions a la API de Responses

La API de Responses simplifica la interfaz de la API de Chat Completions manteniendo la compatibilidad. Para migrar, siga estos pasos.

1. Actualice la dirección del endpoint

Actualice la dirección del endpoint de /v1/chat/completions a /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. Actualice el manejo de respuestas

La API de Responses devuelve una estructura de respuesta diferente. Use el atajo output_text para recuperar la salida de texto, o acceda a información detallada a través de la matriz output. Comparación de respuestas
# 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 las conversaciones multironda

Con la API de Chat Completions, debe gestionar manualmente la matriz de historial de mensajes. La API de Responses simplifica este proceso utilizando el parámetro previous_response_id para vincular automáticamente el contexto de la conversación. El id de la respuesta es válido durante 7 días.
  • 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. Uso de herramientas integradas

La API de Responses incluye herramientas integradas. Especifíquelas en el parámetro tools. Las herramientas de Intérprete de Código y búsqueda web son gratuitas por tiempo limitado. Consulte llamada de herramientas.
  • 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)

FAQ

P: ¿Cómo pasar el contexto de conversación multironda?

R: Pase el id de la respuesta anterior exitosa del modelo como parámetro previous_response_id en su próxima solicitud de conversación.

P: ¿Por qué no puedo imprimir 'output_text'?

R: Este atributo falta en algunas versiones del SDK de Python de OpenAI, como la 1.99.2. Para resolver este error, actualice el SDK a la última versión.

Relacionado