Este documento descreve como chamar o service de inferência do modelo ZHIPUZ.AI no Alibaba Cloud Model Studio.
ZHIPU
ObservaçãoOs recursos descritos neste documento estão disponíveis apenas na região Singapore. Para usar o modelo, faça a chamada a partir da região Singapore.
ImportanteO 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 solicitações de inferência. Recomendamos migrar para os novos domínios:
- China (Beijing): de
https://dashscope.aliyuncs.comparahttps://{WorkspaceId}.cn-beijing.maas.aliyuncs.com - Singapore: de
https://dashscope-intl.aliyuncs.comparahttps://{WorkspaceId}.ap-southeast-1.maas.aliyuncs.com - China (Hong Kong): de
https://cn-hongkong.dashscope.aliyuncs.comparahttps://{WorkspaceId}.cn-hongkong.maas.aliyuncs.com
{WorkspaceId} é o ID do seu workspace, que pode ser encontrado na página Workspace Details no console do Alibaba Cloud Model Studio. O domínio existente permanece totalmente funcional.
Ativação do service
- Acesse o console do Model Studio, pesquise por ZHIPU/GLM, localize o cartão do modelo de texto da série GLM Z.AI e clique em Activate Now.
- Na caixa de diálogo, confirme a ativação e a autorização.
Após concluir essas etapas, você poderá chamar o service de modelo GLM da Z.AI.
Início rápido
O ZHIPU/GLM-5.3 é o modelo da série GLM e suporta contexto de 1M. Execute o código a seguir para chamar rapidamente o modelo ZHIPU/GLM-5.3 no modo de raciocínio.
Você precisa ter obtained an API Key e configured the API Key as an environment variable. Se for chamar o modelo usando um SDK, também é necessário instale o SDK.
Compatibilidade com OpenAI
ObservaçãoO parâmetro enable_thinking não é um parâmetro padrão da OpenAI. No SDK Python da OpenAI, passe-o em extra_body. No SDK Node.js, passe-o como um parâmetro de nível superior.
Python
Código de exemplo
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
Resposta
==================== 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 exemplo
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();
Resposta
==================== 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 exemplo
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"
}'
Chamada de ferramenta em streaming
Os modelos ZHIPU/GLM-5.3, ZHIPU/GLM-5.2, suportam o parâmetro tool_stream. Esse parâmetro é booleano, tem como valor padrão false e funciona apenas quando stream é true. Quando ativado, os arguments do parâmetro tool_call do Function calling são retornados incrementalmente como um fluxo.
Os parâmetros stream e tool_stream funcionam em conjunto da seguinte forma:
stream | tool_stream | Comotool_callé retornado |
|---|---|---|
true | true | Os |
true | false (padrão) | Os |
false | true/false | O parâmetro |
Compatível com OpenAI
Python
Código de exemplo
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 exemplo
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
}'
Controle de raciocínio (thinking.type e reasoning_effort)
O ZHIPU/GLM-5.3 sempre opera no modo de raciocínio e não suporta a desativação dessa funcionalidade. Mantenha thinking.type definido como enabled (ou mantenha enable_thinking definido como true) e use reasoning_effort para controlar a profundidade do raciocínio.
Parâmetro | Descrição | Valores suportados |
|---|---|---|
| Controla se o raciocínio está ativado. O valor padrão é |
|
| Controla a profundidade do raciocínio do modelo. Se este parâmetro não for especificado, o valor padrão será |
|
Limpar raciocínio histórico (clear_thinking)
O parâmetro clear_thinking controla se o reasoning_content (processo de raciocínio) de turnos anteriores é passado ao modelo como contexto em conversas de múltiplos turnos. Apenas os modelos da série GLM suportam este parâmetro.
true: Ignora oreasoning_contentde turnos anteriores e usa apenas conteúdo sem raciocínio, como texto visível, chamadas de ferramentas e resultados de ferramentas, como contexto. Isso reduz o comprimento do contexto e o custo.false(padrão): Retém oreasoning_contentde turnos anteriores e o fornece ao modelo junto com o contexto. Para ative o Raciocínio Preservado, você deve passar oreasoning_contenthistórico nas mensagens de forma completa, sem modificações e em sua ordem original. Omitir, truncar, reescrever ou reordenar esse conteúdo degrada o efeito ou impede que ele funcione.
ObservaçãoEste parâmetro afeta apenas o conteúdo de raciocínio histórico entre turnos. Ele não altera se o modelo gera ou produz raciocínio dentro do turno atual.
Os exemplos a seguir usam o mesmo conjunto de mensagens de múltiplos turnos, onde as mensagens do assistant carregam reasoning_content. Quando clear_thinking=true, o conteúdo de raciocínio histórico não é contabilizado no contexto, então prompt_tokens é menor do que com false (o padrão). O valor real depende do comprimento do reasoning_content histórico.
Compatível com 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
}
}'
Outros recursos
| Modelo | |||||||
|---|---|---|---|---|---|---|---|
ZHIPU/GLM-5.3 | Suportado | Suportado | Suportado | Não suportado | Suportado | Suportado | Suportado
|
ZHIPU/GLM-5.2 | Suportado | Suportado | Suportado
| Não suportado | Suportado | Suportado | Suportado
|
O cache de contexto usa cache implícito e é ativado por padrão. Ele difere do service implicit caching do Alibaba Cloud Model Studio da seguinte forma:
- O número mínimo de tokens em cache é 512, comparado a 256 no Model Studio.
Valores padrão dos parâmetros
Modelo | enable_thinking | temperature | top_p | top_k | repetition_penalty |
|---|---|---|---|---|---|
ZHIPU/GLM-5.3 | true (não pode ser desativado) | 1,0 | 0,95 | - | - |
ZHIPU/GLM-5.2 | true | 1,0 | 0,95 | - | - |
Um hífen (-) indica que o parâmetro não possui valor padrão e não é suportado.
Lista de modelos e faturamento
Os modelos da série GLM são modelos de raciocínio híbrido da Z.AI. Eles foram projetados para agentes inteligentes e oferecem dois modos: com raciocínio e sem raciocínio. O ZHIPU/GLM-5.3 suporta apenas o modo com raciocínio.
Para obter informações sobre o comprimento do contexto do modelo e preços, consulte o console do Model Studioconsole do Model Studio.
O faturamento é baseado nos tokens de entrada e saída do modelo.
No modo de raciocínio, a cadeia de pensamento é faturada com base nos tokens de saída.
Códigos de erro
Se ocorrer um erro, consulte Error codes para resolver o problema.
A seguir estão os códigos de erro de service exclusivos da Z.AI. Os códigos de erro HTTP são os mesmos que os códigos de erro gerais do Model Studio. Consulte o link acima.
Categoria do erro | Código do erro | Mensagem de erro |
|---|---|---|
Erro básico | 500 | Erro interno |
Erro de autenticação | 1000 | Falha na autenticação |
1001 | O parâmetro de Autenticação não foi recebido no cabeçalho. A autenticação não pode ser realizada. | |
1002 | O Token de Autenticação é inválido. Certifique-se de que o Token de Autenticação foi passado corretamente. | |
1003 | O Token de Autenticação expirou. Regenere ou obtenha um novo. | |
1004 | Falha na verificação do Token de Autenticação. | |
1100 | Leitura/gravação de conta | |
Erro de conta | 1110 | Sua conta está inativa. Verifique as informações da sua conta. |
1111 | Sua conta não existe. | |
1112 | Sua conta está bloqueada. Entre em contato com o suporte ao cliente para desbloqueá-la. | |
1113 | Sua conta possui saldo pendente. Recarregue sua conta e tente novamente. | |
1120 | Não é possível acessar sua conta. Tente novamente mais tarde. | |
1121 | Conta bloqueada devido a violação de política. | |
Erro de chamada de API | 1200 | Erro de chamada de API |
1210 | Parâmetros de chamada de API inválidos. Verifique a documentação. | |
1211 | O modelo não existe. Verifique o código do modelo. | |
1212 | O modelo atual não suporta o método de chamada | |
1213 | O parâmetro | |
1214 | O parâmetro | |
1215 |
| |
1220 | Você não tem permissão para acessar | |
1221 | A API | |
1222 | A API | |
1230 | Erro no processo de chamada da API. | |
1231 | Você já possui uma solicitação: | |
1234 | Erro de rede. ID do erro: | |
1261 | O prompt é muito longo. | |
Erro de bloqueio por política da API | 1300 | A chamada da API foi bloqueada por uma política. |
1301 | O sistema detectou conteúdo potencialmente inseguro ou sensível na entrada ou saída. Evite usar prompts que possam gerar conteúdo sensível. Obrigado pela cooperação. | |
1302 | A concorrência para esta API está muito alta. Reduza a concorrência ou entre em contato com o suporte ao cliente para aumentar o limite. | |
1303 | A taxa de solicitação para esta API está muito alta. Reduza a taxa de solicitação ou entre em contato com o suporte ao cliente para aumentar o limite. | |
1304 | O limite diário de chamadas para esta API foi atingido. Para aumentar o limite, entre em contato com o suporte ao cliente. | |
1305 | O limite de tráfego para esta API foi atingido. | |
1308 | O limite de uso de | |
1309 | Seu GLM Coding Plan expirou e está indisponível. Para restaurar o service, renove seu plano em https://bigmodel.cn/claude-code. | |
1310 | O limite de uso semanal/mensal foi atingido. Seu limite será redefinido em | |
1311 | Seu plano de assinatura atual não inclui acesso a | |
1312 | Este modelo está enfrentando alto tráfego. Tente novamente mais tarde ou mude para outro modelo, como | |
1313 | O uso da sua conta viola a política de uso justo e sua taxa de solicitação foi limitada. Para mais informações, consulte os "Termos e Acordos - Acordo de Assinatura e Renovação Automática". Para restaurar o acesso total, acesse Personal Center > Programming Plan Overview e solicite a remoção da restrição. |