Python示例
import openai
# 配置客户端
client = openai.OpenAI(
api_key="your-api-key", # 对应 DEFAULT_KEY
base_url="http://localhost:9090/v1"
)
# 非流式请求 - 使用GLM-4.6
response = client.chat.completions.create(
model="GLM-4.6",
messages=[{"role": "user", "content": "你好,请介绍一下自己"}]
)
print(response.choices[0].message.content)
# 流式请求 - 使用GLM-4.6
response = client.chat.completions.create(
model="GLM-4.6",
messages=[{"role": "user", "content": "请写一首关于春天的诗"}],
stream=True
)
for chunk in response:
if chunk.choices[0].delta.content:
print(chunk.choices[0].delta.content, end="")
cURL示例
# 非流式请求
curl -X POST http://localhost:9090/v1/chat/completions -H "Content-Type: application/json" -H "Authorization: Bearer your-api-key" -d '{
"model": "GLM-4.6",
"messages": [{"role": "user", "content": "你好"}],
"stream": false
}'
# 流式请求
curl -X POST http://localhost:9090/v1/chat/completions -H "Content-Type: application/json" -H "Authorization: Bearer your-api-key" -d '{
"model": "GLM-4.6",
"messages": [{"role": "user", "content": "你好"}],
"stream": true
}'
JavaScript示例
const fetch = require('node-fetch');
async function chatWithGLM(message, stream = false) {
const response = await fetch('http://localhost:9090/v1/chat/completions', {
method: 'POST',
headers: {
'Content-Type': 'application/json',
'Authorization': 'Bearer your-api-key'
},
body: JSON.stringify({
model: 'GLM-4.6',
messages: [{ role: 'user', content: message }],
stream: stream
})
});
if (stream) {
// 处理流式响应
const reader = response.body.getReader();
const decoder = new TextDecoder();
while (true) {
const { done, value } = await reader.read();
if (done) break;
const chunk = decoder.decode(value);
const lines = chunk.split('
');
for (const line of lines) {
if (line.startsWith('data: ')) {
const data = line.slice(6);
if (data === '[DONE]') {
console.log('
流式响应完成');
return;
}
try {
const parsed = JSON.parse(data);
const content = parsed.choices[0]?.delta?.content;
if (content) {
process.stdout.write(content);
}
} catch (e) {
// 忽略解析错误
}
}
}
}
} else {
// 处理非流式响应
const data = await response.json();
console.log(data.choices[0].message.content);
}
}
// 使用示例
chatWithGLM('你好,请介绍一下JavaScript', false);