2. 聊天完成 POST /api/v1/chat/completions
① 请求体(非流式)
{
"model": "NectarAI/Nectar-7B",
"messages": [
{"role": "user", "content": "什么是人工智能?"}
],
"temperature": 0.7,
"stream": false
}
② PHP 调用示例
<?php
$host = 'https://open.ai.zjb522.cn';
$apiKey = 'YOUR_API_KEY';
$payload = [
'model' => 'NectarAI/Nectar-7B',
'messages' => [
['role' => 'user', 'content' => '什么是人工智能?']
],
'temperature' => 0.7,
'stream' => false
];
$ch = curl_init($host.'/api/v1/chat/completions');
curl_setopt_array($ch, [
CURLOPT_POST => true,
CURLOPT_HTTPHEADER => [
'Content-Type: application/json',
'Authorization: Bearer '.$apiKey
],
CURLOPT_POSTFIELDS => json_encode($payload, JSON_UNESCAPED_UNICODE),
CURLOPT_RETURNTRANSFER => true,
CURLOPT_SSL_VERIFYPEER => true,
CURLOPT_TIMEOUT => 30
]);
$response = curl_exec($ch);
$httpCode = curl_getinfo($ch, CURLINFO_HTTP_CODE);
curl_close($ch);
$data = json_decode($response, true);
if (isset($data['error'])) {
echo '调用失败:' . $data['error']['message'];
} else {
echo $data['choices'][0]['message']['content'] ?? '';
}
?>
③ Python 调用示例
import requests
import json
url = 'https://open.ai.zjb522.cn/api/v1/chat/completions'
headers = {
'Content-Type': 'application/json',
'Authorization': 'Bearer YOUR_API_KEY'
}
payload = {
'model': 'NectarAI/Nectar-7B',
'messages': [{'role': 'user', 'content': '什么是人工智能?'}],
'temperature': 0.7,
'stream': False
}
resp = requests.post(url, headers=headers, json=payload, timeout=30)
resp.raise_for_status()
data = resp.json()
print(data['choices'][0]['message']['content'])
④ cURL 一键命令
curl -sS 'https://open.ai.zjb522.cn/api/v1/chat/completions' \
-H 'Content-Type: application/json' \
-H 'Authorization: Bearer YOUR_API_KEY' \
-d '{
"model": "NectarAI/Nectar-7B",
"messages": [{"role": "user", "content": "什么是人工智能?"}],
"temperature": 0.7,
"stream": false
}'
⑤ 返回体示例(200)
{
"id": "chatcmpl-6942875402500",
"object": "chat.completion",
"created": 1704067200,
"model": "NectarAI/Nectar-7B",
"choices": [{
"index": 0,
"message": {
"role": "assistant",
"content": "北京今天晴,气温 22~30 ℃,南风 2 级……"
},
"finish_reason": "stop"
}],
"usage": {
"prompt_tokens": 22,
"completion_tokens": 38,
"total_tokens": 60
}
}