Chat Completions
OpenAI 兼容的聊天补全接口,支持流式输出、函数调用、结构化输出和视觉理解。
POST /v1/chat/completions
请求示例
- Curl
- Python
- TypeScript
- Java
- Go
- PHP
- Ruby
- C#
curl https://gw.opentoken.io/v1/chat/completions \
-H "Content-Type: application/json" \
-H "Authorization: Bearer $OPEN_TOKEN_KEY" \
-d '{
"model": "gpt-4o",
"messages": [
{"role": "system", "content": "你是资深 Python 工程师。"},
{"role": "user", "content": "解释装饰器的工作原理。"}
],
"temperature": 0.7,
"max_tokens": 500
}'
import os
import requests
response = requests.post(
"https://gw.opentoken.io/v1/chat/completions",
headers={
"Authorization": f"Bearer {os.environ['OPEN_TOKEN_KEY']}",
"Content-Type": "application/json",
},
json={
"model": "gpt-4o",
"messages": [
{"role": "system", "content": "你是资深 Python 工程师。"},
{"role": "user", "content": "解释装饰器的工作原理。"},
],
"temperature": 0.7,
"max_tokens": 500,
},
)
data = response.json()
print(data["choices"][0]["message"]["content"])
print(f"Token: {data['usage']['total_tokens']}")
const response = await fetch(
"https://gw.opentoken.io/v1/chat/completions",
{
method: "POST",
headers: {
"Authorization": `Bearer ${process.env.OPEN_TOKEN_KEY}`,
"Content-Type": "application/json",
},
body: JSON.stringify({
model: "gpt-4o",
messages: [
{ role: "system", content: "你是资深 Python 工程师。" },
{ role: "user", content: "解释装饰器的工作原理。" },
],
temperature: 0.7,
max_tokens: 500,
}),
}
);
const data = await response.json();
console.log(data.choices[0].message.content);
import java.net.http.*;
import java.net.URI;
import com.google.gson.*;
HttpClient client = HttpClient.newHttpClient();
String apiKey = System.getenv("OPEN_TOKEN_KEY");
JsonObject sys = new JsonObject();
sys.addProperty("role", "system");
sys.addProperty("content", "你是资深 Python 工程师。");
JsonObject usr = new JsonObject();
usr.addProperty("role", "user");
usr.addProperty("content", "解释装饰器的工作原理。");
JsonArray msgs = new JsonArray();
msgs.add(sys); msgs.add(usr);
JsonObject payload = new JsonObject();
payload.addProperty("model", "gpt-4o");
payload.add("messages", msgs);
payload.addProperty("temperature", 0.7);
payload.addProperty("max_tokens", 500);
HttpRequest request = HttpRequest.newBuilder()
.uri(URI.create("https://gw.opentoken.io/v1/chat/completions"))
.header("Authorization", "Bearer " + apiKey)
.header("Content-Type", "application/json")
.POST(HttpRequest.BodyPublishers.ofString(payload.toString()))
.build();
HttpResponse<String> resp = client.send(request,
HttpResponse.BodyHandlers.ofString());
System.out.println(resp.body());
package main
import (
"bytes"; "encoding/json"; "fmt"
"net/http"; "os"
)
func main() {
apiKey := os.Getenv("OPEN_TOKEN_KEY")
body, _ := json.Marshal(map[string]interface{}{
"model": "gpt-4o",
"messages": []map[string]string{
{"role": "system", "content": "你是资深 Python 工程师。"},
{"role": "user", "content": "解释装饰器的工作原理。"},
},
"temperature": 0.7,
"max_tokens": 500,
})
req, _ := http.NewRequest("POST",
"https://gw.opentoken.io/v1/chat/completions", bytes.NewBuffer(body))
req.Header.Set("Authorization", "Bearer "+apiKey)
req.Header.Set("Content-Type", "application/json")
resp, _ := http.DefaultClient.Do(req)
defer resp.Body.Close()
var result map[string]interface{}
json.NewDecoder(resp.Body).Decode(&result)
fmt.Println(result)
}
<?php
$apiKey = getenv('OPEN_TOKEN_KEY');
$ch = curl_init('https://gw.opentoken.io/v1/chat/completions');
curl_setopt_array($ch, [
CURLOPT_RETURNTRANSFER => true,
CURLOPT_POST => true,
CURLOPT_HTTPHEADER => [
'Authorization: Bearer ' . $apiKey,
'Content-Type: application/json',
],
CURLOPT_POSTFIELDS => json_encode([
'model' => 'gpt-4o',
'messages' => [
['role' => 'system', 'content' => '你是资深 Python 工程师。'],
['role' => 'user', 'content' => '解释装饰器的工作原理。'],
],
'temperature' => 0.7,
'max_tokens' => 500,
]),
]);
$data = json_decode(curl_exec($ch), true);
curl_close($ch);
echo $data['choices'][0]['message']['content'];
require 'net/http'
require 'json'
api_key = ENV['OPEN_TOKEN_KEY']
uri = URI('https://gw.opentoken.io/v1/chat/completions')
http = Net::HTTP.new(uri.host, uri.port)
http.use_ssl = true
request = Net::HTTP::Post.new(uri.path, {
'Authorization' => "Bearer #{api_key}",
'Content-Type' => 'application/json',
})
request.body = {
model: 'gpt-4o',
messages: [
{ role: 'system', content: '你是资深 Python 工程师。' },
{ role: 'user', content: '解释装饰器的工作原理。' }
],
temperature: 0.7,
max_tokens: 500,
}.to_json
response = http.request(request)
data = JSON.parse(response.body)
puts data['choices'][0]['message']['content']
using System.Net.Http.Headers;
using System.Text;
using System.Text.Json;
var apiKey = Environment.GetEnvironmentVariable("OPEN_TOKEN_KEY");
using var client = new HttpClient();
client.DefaultRequestHeaders.Authorization =
new AuthenticationHeaderValue("Bearer", apiKey);
var payload = new
{
model = "gpt-4o",
messages = new[]
{
new { role = "system", content = "你是资深 Python 工程师。" },
new { role = "user", content = "解释装饰器的工作原理。" },
},
temperature = 0.7,
max_tokens = 500,
};
var json = JsonSerializer.Serialize(payload);
var content = new StringContent(json, Encoding.UTF8, "application/json");
var response = await client.PostAsync(
"https://gw.opentoken.io/v1/chat/completions", content);
var body = await response.Content.ReadAsStringAsync();
Console.WriteLine(body);