Skip to main content

GLM

Este tema describe cómo utilizar las API para invocar modelos de la serie GLM en la plataforma Alibaba Cloud Model Studio.

Endpoints de servicio

Los endpoints de servicio varían según la región. Configure la URL base correspondiente a la región seleccionada.
  • Compatible con OpenAI
  • Compatible con OpenAI - Responses API
  • DashScope
  • China (Beijing)
  • EE. UU. (Virginia)
  • Germany (Frankfurt)
  • Hong Kong (China)
  • Singapore
El base_url para llamadas SDK es: https://{WorkspaceId}.cn-beijing.maas.aliyuncs.com/compatible-mode/v1Endpoint de solicitud HTTP: POST https://{WorkspaceId}.cn-beijing.maas.aliyuncs.com/compatible-mode/v1/chat/completions
Reemplace {WorkspaceId} con su ID de espacio de trabajo real.

Introducción

glm-5.3, glm-5.2 y glm-5.2-fast-preview son los modelos de la serie GLM. Tienen una longitud de contexto de 1M. glm-5.2 y glm-5.2-fast-preview le permiten configurar el modo de pensamiento y el modo sin pensamiento mediante el parámetro enable_thinking. glm-5.3 admite únicamente el modo de pensamiento, el cual no se puede desactivar. Puede ejecutar el siguiente código para invocar rápidamente el modelo glm-5.2 en modo de pensamiento. Antes de comenzar, obtenga una clave API y configúrela como variable de entorno. Si utiliza un SDK, también debe instalar el SDK de OpenAI o DashScope.
  • Compatible con OpenAI
  • DashScope
  • Compatible con Anthropic
El parámetro enable_thinking no es un parámetro estándar de OpenAI. En el SDK de Python de OpenAI, se pasa a través de extra_body. En el SDK de Node.js, se pasa como un parámetro de nivel superior.
  • Python
  • Node.js
  • HTTP

Código de ejemplo

from openai import OpenAI
import os

# Initialize the OpenAI client
client = OpenAI(
    # If the environment variable is not configured, replace the value with your Model Studio API key: api_key="sk-xxx"
    api_key=os.getenv("DASHSCOPE_API_KEY"),
    # When you make a call, replace {WorkspaceId} with your actual Workspace ID.
    base_url="https://{WorkspaceId}.ap-southeast-1.maas.aliyuncs.com/compatible-mode/v1",
)

messages = [{"role": "user", "content": "Who are you?"}]
completion = client.chat.completions.create(
    model="glm-5.2",
    messages=messages,
    # Set enable_thinking in extra_body to enable the thinking mode
    extra_body={"enable_thinking": True},
    stream=True,
    stream_options={
        "include_usage": True
    },
)

reasoning_content = ""  # Complete thinking process
answer_content = ""  # Complete response
is_answering = False  # Indicates whether the response phase has started
print("\n" + "=" * 20 + "Thinking process" + "=" * 20 + "\n")

for chunk in completion:
    if not chunk.choices:
        print("\n" + "=" * 20 + "Token usage" + "=" * 20 + "\n")
        print(chunk.usage)
        continue

    delta = chunk.choices[0].delta

    # Collect only the thinking content
    if hasattr(delta, "reasoning_content") and delta.reasoning_content is not None:
        if not is_answering:
            print(delta.reasoning_content, end="", flush=True)
        reasoning_content += delta.reasoning_content

    # After content is received, start the response
    if hasattr(delta, "content") and delta.content:
        if not is_answering:
            print("\n" + "=" * 20 + "Complete response" + "=" * 20 + "\n")
            is_answering = True
        print(delta.content, end="", flush=True)
        answer_content += delta.content

Respuesta

====================Thinking process====================

Let me carefully consider the user's question. It seems simple, but it actually has depth.

From a linguistic perspective, the user is using Chinese, which means I should respond in Chinese. This is a basic self-introduction question, but it may have multiple layers of meaning.

First, I need to be clear that as a language model, I should honestly state my identity and nature. I am not a human, nor do I have real emotional awareness. I am an AI assistant trained with deep learning technology. This is the most basic fact.

Second, considering the user's potential scenarios, they might want to know:
1. What services can I provide?
2. What are my areas of expertise?
3. What are my limitations?
4. How can they interact with me better?

In my answer, I should express a friendly and open attitude while remaining professional and accurate. I should state my main areas of expertise, such as knowledge Q&A, writing assistance, and creative support, but also frankly point out my limitations, such as the lack of real emotional experience.

In addition, to make the answer more complete, I should also express a positive attitude of being willing to help users solve problems. I can appropriately guide users to ask more specific questions to better demonstrate my abilities.

Considering this is an open-ended opening, the answer should be both concise and informative, giving the user a clear understanding of my basic situation and laying a good foundation for subsequent conversations.

Finally, the tone should be humble and professional, neither too technical nor too casual, to make the user feel comfortable and natural.
====================Complete response====================

I am a GLM large language model trained by Zhipu AI, designed to provide users with information and help solve problems. I am designed to understand and generate human language, and I can answer questions, provide explanations, or participate in discussions on various topics.

I do not store your personal data, and our conversations are anonymous. Is there any topic I can help you understand or discuss?
====================Token usage====================

CompletionUsage(completion_tokens=344, prompt_tokens=7, total_tokens=351, completion_tokens_details=None, prompt_tokens_details=None)

Llamada a herramientas en streaming

glm-5.3, glm-5.2, glm-5.2-fast-preview, glm-5.1 y glm-5 admiten el parámetro tool_stream. Este parámetro booleano tiene como valor predeterminado true para glm-5.3 y false para los demás modelos, y solo surte efecto cuando stream se establece en true. Cuando está habilitado, los argumentos del parámetro tool_call de Function Calling se devuelven de forma incremental en un flujo, en lugar de todos a la vez al finalizar la generación completa. El comportamiento combinado de stream y tool_stream es el siguiente:

stream

tool_stream

Método de retorno de tool_call

true

true

Los argumentos se devuelven incrementalmente en múltiples fragmentos.

true

false (predeterminado)

Los argumentos se devuelven completamente en un solo fragmento.

false

true/false

tool_stream no tiene efecto. Los argumentos se devuelven de una vez en la respuesta completa.

  • Compatible con OpenAI
  • DashScope
  • Python
  • Node.js
  • HTTP

Código de ejemplo

from openai import OpenAI
import os

client = OpenAI(
    api_key=os.getenv("DASHSCOPE_API_KEY"),
    # Singapore region. Replace {WorkspaceId} with your Bailian workspace ID. URLs vary by region.
    base_url="https://{WorkspaceId}.ap-southeast-1.maas.aliyuncs.com/compatible-mode/v1",
)

tools = [
    {
        "type": "function",
        "function": {
            "name": "get_weather",
            "description": "Get the weather information for a specified city",
            "parameters": {
                "type": "object",
                "properties": {
                    "city": {"type": "string", "description": "The name of the city"}
                },
                "required": ["city"]
            }
        }
    }
]

messages = [{"role": "user", "content": "What's the weather like in Beijing?"}]

completion = client.chat.completions.create(
    model="glm-5.2",
    tools=tools,
    messages=messages,
    extra_body={
        "tool_stream": True,
    },
    stream=True,
    stream_options={"include_usage": True},
)

for chunk in completion:
    if chunk.choices:
        delta = chunk.choices[0].delta
        if hasattr(delta, 'content') and delta.content:
            print(f"[content] {delta.content}")
        if hasattr(delta, 'tool_calls') and delta.tool_calls:
            for tc in delta.tool_calls:
                print(f"[tool_call] id={tc.id}, name={tc.function.name}, args={tc.function.arguments}")
        if chunk.choices[0].finish_reason:
            print(f"[finish_reason] {chunk.choices[0].finish_reason}")
    if not chunk.choices and chunk.usage:
        print(f"[usage] {chunk.usage}")

Esfuerzo de razonamiento (reasoning_effort)

glm-5.3, glm-5.2, glm-5.2-fast-preview y glm-5.1 tienen el modo de pensamiento habilitado de forma predeterminada. El modelo primero genera el proceso de pensamiento (reasoning_content) y luego proporciona la respuesta final. Puede utilizar el parámetro reasoning_effort para ajustar el esfuerzo de razonamiento. Un valor más alto indica un pensamiento más exhaustivo. Los valores admitidos varían según el modelo. Si pasa un valor no admitido, se devolverá un error invalid_parameter_error. Seleccione un valor de la siguiente tabla.

Modelo

Valores disponibles para reasoning_effort

glm-5.3

low, high, max (máximo)

glm-5.2

none (sin razonamiento, reasoning_tokens=0), minimal, low, medium, high, xhigh, max (máximo)

glm-5.2-fast-preview

none (sin razonamiento, reasoning_tokens=0), minimal, low, medium, high, xhigh, max (máximo)

glm-5.1

none, minimal, low, medium, high, xhigh (máximo, max no es compatible)

Para desactivar el modo de pensamiento, establezca el parámetro enable_thinking en false en el modo compatible con OpenAI o DashScope. Este parámetro tiene mayor prioridad que reasoning_effort. glm-5.3 no admite la desactivación del modo de pensamiento. Establecer enable_thinking en false no tiene efecto.
El modo compatible con Anthropic no admite el parámetro reasoning_effort. Para obtener el contenido de pensamiento, utilice el parámetro nativo thinking de Anthropic: {"thinking":{"type":"enabled","budget_tokens":1024}}. Cuando está activado, la respuesta content incluirá un bloque de pensamiento con type establecido en thinking.
  • Compatible con OpenAI
  • DashScope
Python
from openai import OpenAI
import os
client = OpenAI(
    api_key=os.getenv("DASHSCOPE_API_KEY"),
    # Singapore region. Replace {WorkspaceId} with your Bailian workspace ID. URLs vary by region.
    base_url="https://{WorkspaceId}.ap-southeast-1.maas.aliyuncs.com/compatible-mode/v1",
)
completion = client.chat.completions.create(
    model="glm-5.2",
    messages=[{"role": "user", "content": "Which is larger, 9.9 or 9.11?"}],
    reasoning_effort="high",
)
print(completion.choices[0].message.content)

Borrar historial de pensamiento (clear_thinking)

El parámetro clear_thinking controla si el reasoning_content (proceso de pensamiento) de turnos anteriores en una conversación de múltiples turnos se pasa al modelo como contexto. Este parámetro solo es compatible con los modelos de la serie GLM.
  • true: Ignora el reasoning_content de turnos anteriores. Solo se utiliza como entrada de contexto contenido no relacionado con el razonamiento, como texto visible, llamadas a herramientas y resultados. Esto reduce la longitud del contexto y el costo.
  • false: Conserva el reasoning_content de turnos anteriores y lo proporciona al modelo junto con el contexto. Para habilitar el Pensamiento Conservado, debe pasar el reasoning_content histórico de forma completa, sin modificaciones y en el orden original dentro de los mensajes. La omisión, recorte, reescritura o reordenamiento del contenido puede degradar el rendimiento o provocar fallos en la función.
El valor predeterminado varía según el modelo: true para glm-5.3 y false para los demás modelos GLM.
Este parámetro solo afecta al contenido histórico de pensamiento entre turnos y no cambia si el modelo genera o emite contenido de pensamiento en el turno actual.
El siguiente ejemplo utiliza el mismo conjunto de mensajes de múltiples turnos, donde el mensaje assistant contiene reasoning_content. Cuando clear_thinking se establece en true, el contenido histórico de pensamiento no se incluye en el contexto. Por lo tanto, el recuento de prompt_tokens es menor que cuando se establece en false. El valor real depende de la longitud del reasoning_content histórico.
  • Compatible con OpenAI
  • DashScope
Python
from openai import OpenAI
import os

client = OpenAI(
    api_key=os.getenv("DASHSCOPE_API_KEY"),
    # When you make a call, replace {WorkspaceId} with your actual Workspace ID.
    base_url="https://{WorkspaceId}.ap-southeast-1.maas.aliyuncs.com/compatible-mode/v1",
)

# Multi-turn conversation where the assistant message carries reasoning_content (historical thinking process)
messages = [
    {"role": "user", "content": "Please calculate 15 * 23."},
    {"role": "assistant", "content": "15 multiplied by 23 equals 345.", "reasoning_content": "15 * 23 = 345"},
    {"role": "user", "content": "What if you add 55 to that?"},
    {"role": "assistant", "content": "345 plus 55 equals 400.", "reasoning_content": "345 + 55 = 400"},
    {"role": "user", "content": "What was the intermediate result?"},
]

completion = client.chat.completions.create(
    model="glm-5.2",
    messages=messages,
    extra_body={
        "enable_thinking": True,
        # true: Ignores historical reasoning_content to reduce context length and cost
        # false (default): Retains historical reasoning_content (Preserved Thinking)
        "clear_thinking": True,
    },
)
print(completion.usage.prompt_tokens)  # The value is smaller when set to true than when set to false

API Responses

glm-5.2 admite llamadas a través de la API Responses compatible con OpenAI. Solo se admiten las regiones de China (Beijing) y Singapur. Para ver los endpoints, consulte Endpoints de servicio. Al llamar a la Responses API, puede agregar las herramientas web_search (Búsqueda web), web_extractor (Extractor web) y code_interpreter (Intérprete de código) al parámetro tools.
Python
from openai import OpenAI
import os

client = OpenAI(
    # If the environment variable is not configured, replace the following line with your Model Studio API key: api_key="sk-xxx"
    api_key=os.getenv("DASHSCOPE_API_KEY"),
    # The following URL is for the Singapore region. For the other region, use https://{WorkspaceId}.cn-beijing.maas.aliyuncs.com/compatible-mode/v1
    base_url="https://{WorkspaceId}.ap-southeast-1.maas.aliyuncs.com/compatible-mode/v1",
)

response = client.responses.create(
    model="glm-5.2",
    input="Hello! Please introduce yourself in one sentence.",
    # Optional: enable the web search, web extractor, and code interpreter tools
    tools=[
        {"type": "web_search"},
        {"type": "web_extractor"},
        {"type": "code_interpreter"},
    ],
)

# Get the model response
print(response.output_text)

Otras funciones

ModeloConversación multirondaLlamada a funcionesSalida estructuradaBúsqueda webModo parcialCaché de contexto
glm-5.3CompatibleCompatibleCompatible
Solo se admite response_format configurado como json_object
No compatibleNo compatibleCompatible
Solo se admite caché implícita
glm-5.2CompatibleCompatibleCompatible
Solo en modo sin pensamiento
No compatibleNo compatibleCompatible
Solo se admite caché implícita
glm-5.2-fast-previewCompatibleCompatibleCompatible
Solo en modo sin pensamiento
No compatibleNo compatibleCompatible
Solo se admite caché implícita
glm-5.1CompatibleCompatibleCompatible
Solo en modo sin pensamiento
No compatibleNo compatibleCompatible
Se admiten tanto caché explícita como implícita
glm-5CompatibleCompatibleCompatible
Solo en modo sin pensamiento
No compatibleNo compatibleCompatible
Solo se admite caché implícita

Valores predeterminados de parámetros

Modelo

enable_thinking

temperature

top_p

top_k

repetition_penalty

glm-5.3

true (no se puede desactivar)

1.0

0.95

No compatible

No compatible

glm-5.2

true

1.0

0.95

20

1.0

glm-5.1

true

1.0

0.95

20

1.0

glm-5

true

1.0

0.95

20

1.0

Para más información sobre los parámetros, consulte Compatible con OpenAI - Chat.

Precauciones

Los modelos de código abierto de terceros implementados en la nube (como glm-5.2) manejan los hiperparámetros de manera diferente a la versión oficial del modelo: la versión oficial realiza una validación de umbrales en los hiperparámetros y recurre a los valores predeterminados cuando se superan dichos umbrales; la versión implementada en la nube transmite directamente los valores de los parámetros proporcionados por el usuario sin validación de umbrales. Por lo tanto, configuraciones inadecuadas de hiperparámetros (como establecer repetition_penalty en 0.1) pueden provocar resultados inesperados (como impresión repetida). Recomendamos utilizar los valores predeterminados de los hiperparámetros (consulte la tabla de valores de parámetros predeterminados anterior) para los modelos de código abierto de terceros y evitar el uso de parámetros personalizados.
Al invocar el modelo, respete los tipos de parámetros y los campos obligatorios de la API que utilice. En particular:
  • max_tokens debe ser un número entero, como 1024, no el valor booleano true. Al invocar glm-5.3, true puede tratarse como 1, lo que trunca la salida después de 1 token sin devolver un error de parámetro. La salida puede contener únicamente el contenido del proceso de pensamiento, sin una respuesta final.
  • Al utilizar la API compatible con Anthropic, cada herramienta del arreglo tools debe incluir name, como "name": "get_weather". Si se omite name, la solicitud falla. Incluya el nombre de la herramienta antes de enviar la solicitud.

Modelos y facturación

Los modelos de la serie GLM son modelos de razonamiento híbrido diseñados por Zhipu AI para agentes. Proporcionan modos de pensamiento y sin pensamiento.
  • glm-5.3: El modelo GLM de la serie GLM con una longitud de contexto de 1M. Admite Function Calling, salida estructurada y caché implícita. Puede llamarlo mediante interfaces compatibles con OpenAI, DashScope y Anthropic.
  • glm-5.2: Un modelo GLM con una longitud de contexto de 1M. Admite Function Calling, salida estructurada y caché implícita. Puede llamarlo mediante interfaces compatibles con OpenAI, DashScope y Anthropic.
  • glm-5.2-fast-preview: El modo rápido del modelo glm-5.2. Para más información, consulte Modo Prime.
Para obtener información sobre la longitud del contexto del modelo y los precios, consulte la consola de Model Studio. La facturación se basa en el número de tokens de entrada y salida.
En el modo de pensamiento, la cadena de pensamiento se factura como tokens de salida.

Códigos de error

Si ocurre un error, consulte Códigos de error para obtener información sobre solución de problemas.