Este documento describe cómo llamar al servicio de inferencia de modelos Z.AI en Alibaba Cloud Model Studio.
NotaLas funciones descritas en este documento están disponibles únicamente en la región de Singapur. Para utilizar el modelo, llámelo desde la región de Singapur.
ImportanteAlibaba 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.comahttps://{WorkspaceId}.cn-beijing.maas.aliyuncs.com - Singapur: de
https://dashscope-intl.aliyuncs.comahttps://{WorkspaceId}.ap-southeast-1.maas.aliyuncs.com - China (Hong Kong): de
https://cn-hongkong.dashscope.aliyuncs.comahttps://{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.
Activación del servicio
- Vaya a la consola de Model Studio, busque ZHIPU/GLM, encuentre la tarjeta del modelo de texto Z.AI GLM-series y haga clic en Activate Now.
- En el cuadro de diálogo, confirme la activación y la autorización.
Después de completar estos pasos, puede llamar al servicio de modelos GLM de Z.AI.
Inicio rápido
ZHIPU/GLM-5.3 es el modelo más reciente de la serie GLM y admite un contexto de 1M. Ejecute el siguiente código para llamar rápidamente al modelo ZHIPU/GLM-5.3 en modo de pensamiento.
Debe haber obtenido una clave de API y configurado la clave de API como variable de entorno. Si llama al modelo mediante un SDK, también debe instalar el SDK.
Compatibilidad con OpenAI
NotaEl parámetro enable_thinking no es un parámetro estándar de OpenAI. En el SDK de Python de OpenAI, se pasa en extra_body. En el SDK de Node.js, se pasa como un parámetro de nivel superior.
Python
Código de ejemplo
from openai import OpenAI
import os
# Initialize the OpenAI client
client = OpenAI(
# If the environment variable is not set, replace "sk-xxx" with your Alibaba Cloud Model Studio API Key.
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",
)
messages = [{"role": "user", "content": "Who are you?"}]
completion = client.chat.completions.create(
model="ZHIPU/GLM-5.3",
messages=messages,
# Enable thinking mode by setting enable_thinking in extra_body.
# reasoning_effort controls the reasoning effort. Optional values: max (default), high, low.
extra_body={"enable_thinking": True, "reasoning_effort": "max"},
stream=True,
stream_options={
"include_usage": True
},
)
reasoning_content = "" # Full reasoning process
answer_content = "" # Full response
is_answering = False # Tracks if the model is in the answering phase
print("\n" + "=" * 20 + " Reasoning 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 reasoning 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
# When content is received, start generating the response
if hasattr(delta, "content") and delta.content:
if not is_answering:
print("\n" + "=" * 20 + " Full Response " + "=" * 20 + "\n")
is_answering = True
print(delta.content, end="", flush=True)
answer_content += delta.content
Respuesta
==================== Reasoning Process ====================
Let me carefully consider the user's question. It seems simple, but it is actually quite profound.
From a linguistic perspective, the user is using English, which means I should respond in English. This is a fundamental 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 possess true emotions or consciousness. I am an AI assistant trained with deep learning technology. This is a basic fact.
Second, considering the user's potential needs, 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 more effectively?
In my answer, I should express a friendly and open attitude while maintaining professionalism and accuracy. I should state my main areas of expertise, such as knowledge Q&A, writing assistance, and creative support, while also frankly pointing out my limitations, such as the lack of real emotional experience.
Furthermore, to make the answer more complete, I should also express a positive attitude and willingness to help users solve problems. I can guide the user to ask more specific questions to better showcase my abilities.
Considering this is an open-ended opening, the answer should be concise and clear, yet contain enough information to give the user a clear understanding of my basic situation and lay a good foundation for subsequent conversations.
Finally, the tone should remain humble and professional, neither too technical nor too casual, to make the user feel comfortable and natural.
==================== Full 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 explore?
==================== Token Usage ====================
CompletionUsage(completion_tokens=344, prompt_tokens=7, total_tokens=351, completion_tokens_details=None, prompt_tokens_details=None)
Node.js
Código de ejemplo
import OpenAI from "openai";
import process from 'process';
// Initialize the OpenAI client
const openai = new OpenAI({
// If the environment variable is not set, replace "sk-xxx" with your Alibaba Cloud Model Studio API Key.
apiKey: process.env.DASHSCOPE_API_KEY,
// Singapore region. Replace {WorkspaceId} with your Bailian workspace ID. URLs vary by region.
baseURL: 'https://{WorkspaceId}.ap-southeast-1.maas.aliyuncs.com/compatible-mode/v1'
});
let reasoningContent = ''; // Full reasoning process
let answerContent = ''; // Full response
let isAnswering = false; // Tracks if the model is in the answering phase
async function main() {
try {
const messages = [{ role: 'user', content: 'Who are you?' }];
const stream = await openai.chat.completions.create({
model: 'ZHIPU/GLM-5.3',
messages,
// Note: In the Node.js SDK, non-standard parameters like enable_thinking are passed as top-level properties, not within extra_body.
enable_thinking: true,
// reasoning_effort controls the reasoning effort. Optional values: max (default), high, low.
reasoning_effort: 'max',
stream: true,
stream_options: {
include_usage: true
},
});
console.log('\n' + '='.repeat(20) + ' Reasoning Process ' + '='.repeat(20) + '\n');
for await (const chunk of stream) {
if (!chunk.choices?.length) {
console.log('\n' + '='.repeat(20) + ' Token Usage ' + '='.repeat(20) + '\n');
console.log(chunk.usage);
continue;
}
const delta = chunk.choices[0].delta;
// Collect only the reasoning content
if (delta.reasoning_content !== undefined && delta.reasoning_content !== null) {
if (!isAnswering) {
process.stdout.write(delta.reasoning_content);
}
reasoningContent += delta.reasoning_content;
}
// When content is received, start generating the response
if (delta.content !== undefined && delta.content) {
if (!isAnswering) {
console.log('\n' + '='.repeat(20) + ' Full Response ' + '='.repeat(20) + '\n');
isAnswering = true;
}
process.stdout.write(delta.content);
answerContent += delta.content;
}
}
} catch (error) {
console.error('Error:', error);
}
}
main();
Respuesta
==================== Reasoning Process ====================
Let me carefully consider the user's question, "Who are you?" This requires analysis and a response from multiple perspectives.
First, this is a basic identity question. As a GLM large language model, I need to accurately state my identity. I should clearly state that I am an AI assistant developed by ZHIPU AI.
Second, I need to consider the user's possible intentions. They might be first-time users wanting to understand basic functions, or they might want to confirm if I can provide specific help, or they might just be testing my response style. Therefore, I need to give an open and friendly answer.
I also need to consider the completeness of the answer. In addition to introducing my identity, I should briefly explain my main functions, such as Q&A, content creation, and analysis, so the user knows how to use this assistant.
Finally, I need to ensure a friendly and approachable tone, expressing a willingness to help. I can use expressions like "I'm happy to help" to make the user feel the warmth of the interaction.
Based on these considerations, I can craft a concise and clear answer that both addresses the user's question and guides future interaction.
==================== Full Response ====================
I am GLM, a large language model trained by ZHIPU AI. Trained on massive text data, I can understand and generate human language to help users answer questions, provide information, and engage in conversations.
I am continuously learning and improving to provide better services. I'm happy to answer your questions or provide assistance! What can I do for you?
==================== Token Usage ====================
{ prompt_tokens: 7, completion_tokens: 248, total_tokens: 255 }
HTTP
Código de ejemplo
curl
# Singapore region. Replace {WorkspaceId} with your Bailian workspace ID. URLs vary by region.
curl -X POST https://{WorkspaceId}.ap-southeast-1.maas.aliyuncs.com/compatible-mode/v1/chat/completions \
-H "Authorization: Bearer $DASHSCOPE_API_KEY" \
-H "Content-Type: application/json" \
-d '{
"model": "ZHIPU/GLM-5.3",
"messages": [
{
"role": "user",
"content": "Who are you?"
}
],
"stream": true,
"stream_options": {
"include_usage": true
},
"enable_thinking": true,
"reasoning_effort": "max"
}'
Llamada de herramienta en streaming
Los modelos ZHIPU/GLM-5.3 y ZHIPU/GLM-5.2 admiten el parámetro tool_stream. Este parámetro es un valor booleano cuyo valor predeterminado es false y solo funciona cuando stream es true. Cuando está habilitado, los arguments del parámetro tool_call de Function calling se devuelven incrementalmente como un flujo.
Los parámetros stream y tool_stream funcionan conjuntamente de la siguiente manera:
stream | tool_stream | Cómo |
|---|---|---|
true | true |
|
true | false (predeterminado) |
|
false | true/false |
|
Compatible con OpenAI
Python
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 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 is the weather like in Beijing"}]
completion = client.chat.completions.create(
model="ZHIPU/GLM-5.3",
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}")
Node.js
Código de ejemplo
import OpenAI from "openai";
import process from 'process';
const openai = new OpenAI({
apiKey: process.env.DASHSCOPE_API_KEY,
// Singapore region. Replace {WorkspaceId} with your Bailian workspace ID. URLs vary by region.
baseURL: 'https://{WorkspaceId}.ap-southeast-1.maas.aliyuncs.com/compatible-mode/v1'
});
const tools = [
{
type: "function",
"function": {
name: "get_weather",
description: "Get weather information for a specified city",
parameters: {
type: "object",
properties: {
city: { type: "string", description: "The name of the city" }
},
required: ["city"]
}
}
}
];
async function main() {
try {
const stream = await openai.chat.completions.create({
model: 'ZHIPU/GLM-5.3',
messages: [{ role: 'user', content: 'What is the weather like in Beijing' }],
tools: tools,
tool_stream: true,
stream: true,
stream_options: {
include_usage: true
},
});
for await (const chunk of stream) {
if (!chunk.choices?.length) {
if (chunk.usage) {
console.log(`[usage] ${JSON.stringify(chunk.usage)}`);
}
continue;
}
const delta = chunk.choices[0].delta;
if (delta.content) {
console.log(`[content] ${delta.content}`);
}
if (delta.tool_calls) {
for (const tc of delta.tool_calls) {
console.log(`[tool_call] id=${tc.id}, name=${tc.function.name}, args=${tc.function.arguments}`);
}
}
if (chunk.choices[0].finish_reason) {
console.log(`[finish_reason] ${chunk.choices[0].finish_reason}`);
}
}
} catch (error) {
console.error('Error:', error);
}
}
main();
curl
# Singapore region. Replace {WorkspaceId} with your Bailian workspace ID. URLs vary by region.
curl -X POST https://{WorkspaceId}.ap-southeast-1.maas.aliyuncs.com/compatible-mode/v1/chat/completions \
-H "Authorization: Bearer $DASHSCOPE_API_KEY" \
-H "Content-Type: application/json" \
-d '{
"model": "ZHIPU/GLM-5.3",
"messages": [
{
"role": "user",
"content": "What is the weather like in Beijing"
}
],
"tools": [
{
"type": "function",
"function": {
"name": "get_weather",
"description": "Get weather information for a specified city",
"parameters": {
"type": "object",
"properties": {
"city": {"type": "string", "description": "The name of the city"}
},
"required": ["city"]
}
}
}
],
"stream": true,
"stream_options": {"include_usage": true},
"tool_stream": true
}'
Control de pensamiento (thinking.type y reasoning_effort)
ZHIPU/GLM-5.3 siempre se ejecuta en modo de pensamiento y no admite desactivar el pensamiento. Mantenga thinking.type configurado en enabled (o mantenga enable_thinking configurado en true) y utilice reasoning_effort para controlar la profundidad de razonamiento.
Parámetro | Descripción | Valores admitidos |
|---|---|---|
| Controla si el pensamiento está habilitado. El valor predeterminado es |
|
| Controla la profundidad de razonamiento del modelo. Si no se especifica este parámetro, el valor predeterminado es |
|
Borrar razonamiento histórico (clear_thinking)
El parámetro clear_thinking controla si el reasoning_content (proceso de razonamiento) de turnos anteriores se pasa al modelo como contexto en conversaciones de múltiples turnos. Solo los modelos de la serie GLM admiten este parámetro.
true: Ignora elreasoning_contentde turnos anteriores y utiliza únicamente contenido sin razonamiento, como texto visible, llamadas a herramientas y resultados de herramientas, como contexto. Esto reduce la longitud del contexto y el costo.false(predeterminado): Conserva elreasoning_contentde turnos anteriores y lo proporciona al modelo junto con el contexto. Para habilitar el Pensamiento Conservado, debe pasar elreasoning_contenthistórico completo en los mensajes, sin modificaciones y en su orden original. Omitirlo, truncarlo, reescribirlo o reordenarlo degrada el efecto o impide que surta efecto.
NotaEste parámetro afecta únicamente al contenido de razonamiento histórico entre turnos. No cambia si el modelo genera o emite razonamiento dentro del turno actual.
Los siguientes ejemplos utilizan el mismo conjunto de mensajes de múltiples turnos, donde los mensajes de assistant llevan reasoning_content. Cuando clear_thinking=true, el contenido de razonamiento histórico no se cuenta para el contexto, por lo que prompt_tokens es menor que con false (el valor predeterminado). El valor real depende de la longitud del reasoning_content histórico.
Compatible con OpenAI
from openai import OpenAI
import os
client = OpenAI(
api_key=os.getenv("DASHSCOPE_API_KEY"),
# The following is the URL for the Singapore region. Replace {WorkspaceId} with your Model Studio workspace ID. URLs differ by region.
base_url="https://{WorkspaceId}.ap-southeast-1.maas.aliyuncs.com/compatible-mode/v1",
)
# Multi-turn conversation. The assistant messages carry reasoning_content (historical reasoning process).
messages = [
{"role": "user", "content": "What is 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="ZHIPU/GLM-5.3",
messages=messages,
extra_body={
"thinking": {
"type": "enabled",
"clear_thinking": False # False = retain reasoning content
}
}
)
print(completion.usage.prompt_tokens) # Lower with true than with false
# The following is the URL for the Singapore region. Replace {WorkspaceId} with your Model Studio workspace ID. URLs differ by region.
curl -X POST https://{WorkspaceId}.ap-southeast-1.maas.aliyuncs.com/compatible-mode/v1/chat/completions \
-H "Authorization: Bearer $DASHSCOPE_API_KEY" \
-H "Content-Type: application/json" \
-d '{
"model": "ZHIPU/GLM-5.3",
"messages": [
{"role": "user", "content": "What is 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?"}
],
"thinking": {
"type": "enabled",
"clear_thinking": false
}
}'
Otras funciones
| Modelo | |||||||
|---|---|---|---|---|---|---|---|
ZHIPU/GLM-5.3 | Compatible | Compatible | Compatible | No compatible | Compatible | Compatible | Compatible
|
ZHIPU/GLM-5.2 | Compatible | Compatible | Compatible
| No compatible | Compatible | Compatible | Compatible
|
El almacenamiento en caché de contexto utiliza caché implícita y está habilitado de forma predeterminada. Se diferencia del servicio de caché implícita de Alibaba Cloud Model Studio de la siguiente manera:
- El número mínimo de tokens en caché es 512, en comparación con 1024 para Model Studio.
Valores predeterminados de parámetros
Modelo | enable_thinking | temperature | top_p | top_k | repetition_penalty |
|---|---|---|---|---|---|
ZHIPU/GLM-5.3 | true (no se puede desactivar) | 1.0 | 0.95 | - | - |
ZHIPU/GLM-5.2 | true | 1.0 | 0.95 | - | - |
Un guion (-) indica que el parámetro no tiene valor predeterminado y no es compatible.
Lista de modelos y facturación
Los modelos de la serie GLM son modelos de razonamiento híbrido de Z.AI. Están diseñados para agentes inteligentes y ofrecen dos modos: pensamiento y no pensamiento. ZHIPU/GLM-5.3 solo admite el modo de pensamiento.
Para obtener información sobre la longitud del contexto del modelo y los precios, consulte la consola de Model Studioconsola de Model Studio.
La facturación se basa en los tokens de entrada y salida del modelo.
En el modo de pensamiento, la cadena de pensamiento se factura según los tokens de salida.
Códigos de error
Si ocurre un error, consulte Códigos de error para resolver el problema.
Los siguientes son códigos de error de servicio exclusivos de Z.AI. Los códigos de error HTTP son los mismos que los códigos de error generales de Model Studio. Consulte el enlace anterior.
Categoría de error | Código de error | Mensaje de error |
|---|---|---|
Error básico | 500 | Error interno |
Error de autenticación | 1000 | Error de autenticación |
1001 | No se recibió el parámetro de autenticación en el encabezado. No se puede realizar la autenticación. | |
1002 | El token de autenticación no es válido. Asegúrese de que el token de autenticación se pase correctamente. | |
1003 | El token de autenticación ha caducado. Regenérelo u obtenga uno nuevo. | |
1004 | La verificación del token de autenticación falló. | |
1100 | Lectura/escritura de cuenta | |
Error de cuenta | 1110 | Su cuenta está inactiva. Verifique la información de su cuenta. |
1111 | Su cuenta no existe. | |
1112 | Su cuenta está bloqueada. Póngase en contacto con el servicio de atención al cliente para desbloquearla. | |
1113 | Su cuenta tiene un saldo pendiente. Recargue su cuenta e inténtelo de nuevo. | |
1120 | No se puede acceder a su cuenta. Inténtelo de nuevo más tarde. | |
1121 | Cuenta bloqueada debido a una violación de política. | |
Error de llamada de API | 1200 | Error de llamada de API |
1210 | Parámetros de llamada de API no válidos. Consulte la documentación. | |
1211 | El modelo no existe. Verifique el código del modelo. | |
1212 | El modelo actual no admite el método de llamada | |
1213 | No se recibió el parámetro | |
1214 | El parámetro | |
1215 |
| |
1220 | No tiene permiso para acceder a | |
1221 | La API | |
1222 | La API | |
1230 | Error en el proceso de llamada de API. | |
1231 | Ya tiene una solicitud: | |
1234 | Error de red. ID de error: | |
1261 | El prompt es demasiado largo. | |
Error de bloqueo por política de API | 1300 | La llamada a la API fue bloqueada por una política. |
1301 | El sistema detectó contenido potencialmente inseguro o sensible en la entrada o salida. Evite utilizar instrucciones que puedan generar contenido sensible. Gracias por su cooperación. | |
1302 | La concurrencia para esta API es demasiado alta. Reduzca la concurrencia o póngase en contacto con el servicio de atención al cliente para aumentar el límite. | |
1303 | La tasa de solicitudes para esta API es demasiado alta. Reduzca la tasa de solicitudes o póngase en contacto con el servicio de atención al cliente para aumentar el límite. | |
1304 | Se ha alcanzado el límite diario de llamadas para esta API. Para aumentar el límite, póngase en contacto con el servicio de atención al cliente. | |
1305 | Se ha alcanzado el límite de tráfico para esta API. | |
1308 | Se ha alcanzado el límite de uso de | |
1309 | Su GLM Coding Plan ha caducado y no está disponible. Para restaurar el servicio, renueve su plan en https://bigmodel.cn/claude-code. | |
1310 | Se ha alcanzado el límite de uso semanal/mensual. Su límite se restablecerá en | |
1311 | Su plan de suscripción actual no incluye acceso a | |
1312 | Este modelo está experimentando un alto tráfico. Inténtelo de nuevo más tarde o cambie a otro modelo como | |
1313 | El uso de su cuenta infringe la política de uso justo y su tasa de solicitudes ha sido limitada. Para obtener más información, consulte "Terms and Agreements - Subscription and Auto-renewal Agreement". Para restaurar el acceso completo, vaya a Centro personal > Resumen del plan de programación y solicite levantar la restricción. |