Chat 流式补全
![]()
示例使用 gpt-6.1-sol。Chat 使用 reasoning_effort,仅接受 low/medium/high/xhigh/max;不要传 none 或 minimal。工具调用请改用 Responses 函数调用。
在 Header 添加参数 Authorization,其值为 Bearer 之后拼接 Token
Authorization: Bearer ********************
请求参数
请求示例代码
curl --no-buffer --fail-with-body --request POST 'https://api.apizt.com/v1/chat/completions' \
--header "Authorization: Bearer ${tokenba_API_KEY}" \
--header 'Content-Type: application/json' \
--data-raw '{
"model": "gpt-6.1-sol",
"messages": [
{
"role": "system",
"content": "You are a helpful assistant."
},
{
"role": "user",
"content": "你好"
}
],
"stream": true,
"stream_options": {
"include_usage": true
},
"max_completion_tokens": 1000,
"reasoning_effort": "low"
}'
async function main() {
const headers = { Authorization: "Bearer " + process.env.tokenba_API_KEY };
headers["Content-Type"] = "application/json";
const body = JSON.stringify({
"model": "gpt-6.1-sol",
"messages": [
{
"role": "system",
"content": "You are a helpful assistant."
},
{
"role": "user",
"content": "你好"
}
],
"stream": true,
"stream_options": {
"include_usage": true
},
"max_completion_tokens": 1000,
"reasoning_effort": "low"
});
const response = await fetch("https://api.apizt.com/v1/chat/completions", { method: "POST", headers, body });
if (!response.ok) throw new Error("HTTP " + response.status + ": " + await response.text());
const reader = response.body.getReader();
const decoder = new TextDecoder();
try {
while (true) {
const { value, done } = await reader.read();
if (done) break;
process.stdout.write(decoder.decode(value, { stream: true }));
}
process.stdout.write(decoder.decode());
} finally { reader.releaseLock(); }
}
main().catch(console.error);
import okhttp3.*;
import java.io.File;
class Example {
public static void main(String[] args) throws Exception {
OkHttpClient client = new OkHttpClient();
RequestBody body = RequestBody.create(MediaType.parse("application/json"), "{\n \"model\": \"gpt-6.1-sol\",\n \"messages\": [\n {\n \"role\": \"system\",\n \"content\": \"You are a helpful assistant.\"\n },\n {\n \"role\": \"user\",\n \"content\": \"你好\"\n }\n ],\n \"stream\": true,\n \"stream_options\": {\n \"include_usage\": true\n },\n \"max_completion_tokens\": 1000,\n \"reasoning_effort\": \"low\"\n}");
Request.Builder request = new Request.Builder().url("https://api.apizt.com/v1/chat/completions").header("Authorization", "Bearer " + System.getenv("tokenba_API_KEY"));
request.method("POST", body);
try (Response response = client.newCall(request.build()).execute()) {
if (!response.isSuccessful()) throw new Exception("HTTP " + response.code());
System.out.println(response.body().string());
}
}
}
import Foundation
var request = URLRequest(url: URL(string: "https://api.apizt.com/v1/chat/completions")!)
request.httpMethod = "POST"
request.setValue("Bearer " + ProcessInfo.processInfo.environment["tokenba_API_KEY"]!, forHTTPHeaderField: "Authorization")
request.setValue("application/json", forHTTPHeaderField: "Content-Type")
request.httpBody = "{\n \"model\": \"gpt-6.1-sol\",\n \"messages\": [\n {\n \"role\": \"system\",\n \"content\": \"You are a helpful assistant.\"\n },\n {\n \"role\": \"user\",\n \"content\": \"你好\"\n }\n ],\n \"stream\": true,\n \"stream_options\": {\n \"include_usage\": true\n },\n \"max_completion_tokens\": 1000,\n \"reasoning_effort\": \"low\"\n}".data(using: .utf8)
let (data, response) = try await URLSession.shared.data(for: request)
print((response as? HTTPURLResponse)?.statusCode ?? 0)
print(String(data: data, encoding: .utf8) ?? "")
package main
import (
"bytes"
"fmt"
"io"
"net/http"
"os"
)
func main() {
req, err := http.NewRequest("POST", "https://api.apizt.com/v1/chat/completions", bytes.NewBufferString("{\n \"model\": \"gpt-6.1-sol\",\n \"messages\": [\n {\n \"role\": \"system\",\n \"content\": \"You are a helpful assistant.\"\n },\n {\n \"role\": \"user\",\n \"content\": \"你好\"\n }\n ],\n \"stream\": true,\n \"stream_options\": {\n \"include_usage\": true\n },\n \"max_completion_tokens\": 1000,\n \"reasoning_effort\": \"low\"\n}"))
_ = bytes.MinRead
if err != nil { panic(err) }
req.Header.Set("Authorization", "Bearer " + os.Getenv("tokenba_API_KEY"))
req.Header.Set("Content-Type", "application/json")
resp, err := http.DefaultClient.Do(req)
if err != nil { panic(err) }; defer resp.Body.Close()
data, err := io.ReadAll(resp.Body)
if err != nil { panic(err) }
fmt.Println(resp.Status, string(data))
}
<?php
$headers = ["Authorization: Bearer " . getenv("tokenba_API_KEY")];
$headers[] = "Content-Type: application/json";
$body = <<<'JSON'
{
"model": "gpt-6.1-sol",
"messages": [
{
"role": "system",
"content": "You are a helpful assistant."
},
{
"role": "user",
"content": "你好"
}
],
"stream": true,
"stream_options": {
"include_usage": true
},
"max_completion_tokens": 1000,
"reasoning_effort": "low"
}
JSON;
$curl = curl_init('https://api.apizt.com/v1/chat/completions');
curl_setopt_array($curl, [CURLOPT_CUSTOMREQUEST => 'POST', CURLOPT_HTTPHEADER => $headers, CURLOPT_RETURNTRANSFER => true, CURLOPT_POSTFIELDS => $body]);
$result = curl_exec($curl);
if ($result === false) throw new Exception(curl_error($curl));
echo $result;
curl_close($curl);
import os
import requests
headers = {"Authorization": "Bearer " + os.environ["tokenba_API_KEY"]}
payload = {'model': 'gpt-6.1-sol',
'messages': [{'role': 'system', 'content': 'You are a helpful assistant.'},
{'role': 'user', 'content': '你好'}],
'stream': True,
'stream_options': {'include_usage': True},
'max_completion_tokens': 1000,
'reasoning_effort': 'low'}
response = requests.request('POST', 'https://api.apizt.com/v1/chat/completions', headers=headers, json=payload, timeout=120, stream=True)
response.raise_for_status()
response.encoding = "utf-8"
for line in response.iter_lines(decode_unicode=True):
print(line, flush=True)
POST /v1/chat/completions HTTP/1.1
Host: api.apizt.com
Authorization: Bearer YOUR_tokenba_API_KEY
Content-Type: application/json
{
"model": "gpt-6.1-sol",
"messages": [
{
"role": "system",
"content": "You are a helpful assistant."
},
{
"role": "user",
"content": "你好"
}
],
"stream": true,
"stream_options": {
"include_usage": true
},
"max_completion_tokens": 1000,
"reasoning_effort": "low"
}
#include <curl/curl.h>
#include <stdlib.h>
#include <stdio.h>
int main(void) {
curl_global_init(CURL_GLOBAL_DEFAULT);
CURL *curl = curl_easy_init();
if (!curl) return 1;
char auth[4096];
snprintf(auth, sizeof(auth), "Authorization: Bearer %s", getenv("tokenba_API_KEY"));
struct curl_slist *headers = curl_slist_append(NULL, auth);
headers = curl_slist_append(headers, "Content-Type: application/json");
curl_easy_setopt(curl, CURLOPT_POSTFIELDS, "{\n \"model\": \"gpt-6.1-sol\",\n \"messages\": [\n {\n \"role\": \"system\",\n \"content\": \"You are a helpful assistant.\"\n },\n {\n \"role\": \"user\",\n \"content\": \"你好\"\n }\n ],\n \"stream\": true,\n \"stream_options\": {\n \"include_usage\": true\n },\n \"max_completion_tokens\": 1000,\n \"reasoning_effort\": \"low\"\n}");
curl_easy_setopt(curl, CURLOPT_URL, "https://api.apizt.com/v1/chat/completions");
curl_easy_setopt(curl, CURLOPT_CUSTOMREQUEST, "POST");
curl_easy_setopt(curl, CURLOPT_HTTPHEADER, headers);
CURLcode result = curl_easy_perform(curl);
curl_slist_free_all(headers); curl_easy_cleanup(curl); curl_global_cleanup();
return result == CURLE_OK ? 0 : 1;
}
using System;
using System.IO;
using System.Net.Http;
using System.Net.Http.Headers;
using System.Text;
using var client = new HttpClient();
using var request = new HttpRequestMessage(new HttpMethod("POST"), "https://api.apizt.com/v1/chat/completions");
request.Headers.Authorization = new AuthenticationHeaderValue("Bearer", Environment.GetEnvironmentVariable("tokenba_API_KEY"));
request.Content = new StringContent("{\n \"model\": \"gpt-6.1-sol\",\n \"messages\": [\n {\n \"role\": \"system\",\n \"content\": \"You are a helpful assistant.\"\n },\n {\n \"role\": \"user\",\n \"content\": \"你好\"\n }\n ],\n \"stream\": true,\n \"stream_options\": {\n \"include_usage\": true\n },\n \"max_completion_tokens\": 1000,\n \"reasoning_effort\": \"low\"\n}", Encoding.UTF8, "application/json");
using var response = await client.SendAsync(request);
response.EnsureSuccessStatusCode();
Console.WriteLine(await response.Content.ReadAsStringAsync());
#import <Foundation/Foundation.h>
int main(void) {
@autoreleasepool {
dispatch_semaphore_t done = dispatch_semaphore_create(0);
NSMutableURLRequest *request = [NSMutableURLRequest requestWithURL:[NSURL URLWithString:@"https://api.apizt.com/v1/chat/completions"]];
request.HTTPMethod = @"POST";
NSDictionary *env = [[NSProcessInfo processInfo] environment];
[request setValue:[@"Bearer " stringByAppendingString:env[@"tokenba_API_KEY"]] forHTTPHeaderField:@"Authorization"];
[request setValue:@"application/json" forHTTPHeaderField:@"Content-Type"];
request.HTTPBody = [@"{\n \"model\": \"gpt-6.1-sol\",\n \"messages\": [\n {\n \"role\": \"system\",\n \"content\": \"You are a helpful assistant.\"\n },\n {\n \"role\": \"user\",\n \"content\": \"你好\"\n }\n ],\n \"stream\": true,\n \"stream_options\": {\n \"include_usage\": true\n },\n \"max_completion_tokens\": 1000,\n \"reasoning_effort\": \"low\"\n}" dataUsingEncoding:NSUTF8StringEncoding];
[[[NSURLSession sharedSession] dataTaskWithRequest:request completionHandler:^(NSData *data, NSURLResponse *response, NSError *error) {
if (error) { NSLog(@"%@", error); dispatch_semaphore_signal(done); return; }
NSLog(@"%@", [[NSString alloc] initWithData:data encoding:NSUTF8StringEncoding]);
dispatch_semaphore_signal(done);
}] resume];
dispatch_semaphore_wait(done, DISPATCH_TIME_FOREVER);
}
return 0;
}
require "net/http"
require "json"
uri = URI("https://api.apizt.com/v1/chat/completions")
request = Net::HTTPGenericRequest.new("POST", true, true, uri.request_uri)
request["Authorization"] = "Bearer " + ENV.fetch("tokenba_API_KEY")
request["Content-Type"] = "application/json"
request.body = "{\n \"model\": \"gpt-6.1-sol\",\n \"messages\": [\n {\n \"role\": \"system\",\n \"content\": \"You are a helpful assistant.\"\n },\n {\n \"role\": \"user\",\n \"content\": \"你好\"\n }\n ],\n \"stream\": true,\n \"stream_options\": {\n \"include_usage\": true\n },\n \"max_completion_tokens\": 1000,\n \"reasoning_effort\": \"low\"\n}"
puts Net::HTTP.start(uri.host, uri.port, use_ssl: true) { |http| http.request(request).body }
open Lwt.Infix
let () =
let headers = Cohttp.Header.init_with "Authorization" ("Bearer " ^ Sys.getenv "tokenba_API_KEY") in
let data = {|{
"model": "gpt-6.1-sol",
"messages": [
{
"role": "system",
"content": "You are a helpful assistant."
},
{
"role": "user",
"content": "你好"
}
],
"stream": true,
"stream_options": {
"include_usage": true
},
"max_completion_tokens": 1000,
"reasoning_effort": "low"
}|} in
let headers = Cohttp.Header.add headers "Content-Type" "application/json" in
Lwt_main.run (
Cohttp_lwt_unix.Client.call ~headers ~body:(Cohttp_lwt.Body.of_string data) `POST (Uri.of_string "https://api.apizt.com/v1/chat/completions") >>= fun (_, body) ->
Cohttp_lwt.Body.to_string body >|= print_endline
)
import "dart:io";
import "package:http/http.dart" as http;
Future<void> main() async {
final headers = {"Authorization": "Bearer ${Platform.environment['tokenba_API_KEY']}"};
final request = http.Request("POST", Uri.parse("https://api.apizt.com/v1/chat/completions"));
request.headers.addAll(headers);
request.headers["Content-Type"] = "application/json";
request.body = "{\n \"model\": \"gpt-6.1-sol\",\n \"messages\": [\n {\n \"role\": \"system\",\n \"content\": \"You are a helpful assistant.\"\n },\n {\n \"role\": \"user\",\n \"content\": \"你好\"\n }\n ],\n \"stream\": true,\n \"stream_options\": {\n \"include_usage\": true\n },\n \"max_completion_tokens\": 1000,\n \"reasoning_effort\": \"low\"\n}";
final response = await request.send();
print(response.statusCode);
print(await response.stream.bytesToString());
}
library(httr)
headers <- c(Authorization = paste("Bearer", Sys.getenv("tokenba_API_KEY")))
headers["Content-Type"] <- "application/json"
body <- "{\n \"model\": \"gpt-6.1-sol\",\n \"messages\": [\n {\n \"role\": \"system\",\n \"content\": \"You are a helpful assistant.\"\n },\n {\n \"role\": \"user\",\n \"content\": \"你好\"\n }\n ],\n \"stream\": true,\n \"stream_options\": {\n \"include_usage\": true\n },\n \"max_completion_tokens\": 1000,\n \"reasoning_effort\": \"low\"\n}"
response <- VERB("POST", "https://api.apizt.com/v1/chat/completions", add_headers(.headers = headers), body = body)
stop_for_status(response)
cat(content(response, "text", encoding = "UTF-8"))
返回响应
流式返回 SSE,增量位于 choices[].delta。按事件拼接文本;结束事件为 data: [DONE]。以下 JSON 为单个事件的结构示例,不代表实际调用结果。
{
"id": "chatcmpl_demo",
"object": "chat.completion.chunk",
"model": "gpt-6.1-sol",
"choices": [
{
"index": 0,
"delta": {
"role": "assistant",
"content": "你好"
},
"finish_reason": null
}
]
}
OpenAI API 中转的流式输出场景
当应用需要像 ChatGPT 一样逐字返回内容时,可以使用本页的 Chat 流式补全接口。通过 apizt API 中转站,国内服务器可以直接请求 /v1/chat/completions,并设置 stream: true 接收 SSE 数据流。
| 场景 | 建议 |
|---|---|
| 聊天机器人 | 使用 stream: true,前端按 chunk 渲染 |
| AI 写作工具 | 边生成边展示,减少用户等待感 |
| Agent 工作流 | 将模型输出、工具调用日志和最终结果分阶段展示 |
| 国内应用后端 | 服务端请求 apizt API,再转发 SSE 给前端 |
相关文档
示例先设置 tokenba_API_KEY。JavaScript 使用 Node.js 20+,Python 安装 requests。流式示例的 Python 与 JavaScript 会逐段输出事件数据。代码中的 ID、文件名与令牌须替换为自己的值。
GPT-6.1 Sol 的 Chat 请求使用 reasoning_effort,Responses 使用 reasoning.effort;等级为 low、medium、high、xhigh、max。工具调用使用 Responses。官方型号说明。
当前模型与版本
依据 apizt 价格页,同步于 。以下型号按目录声明的协议与本页用途筛选;不代表所有参数和功能通用。切换前请核对型号说明、令牌分组与参数差异。Gemini 原生接口需同时替换 URL 中的模型 ID。
| 模型 ID | 能力标签 | 支持分组 |
|---|---|---|
gpt-6.1-sol | 对话,工具,识图,思考 | 分组(9)
|
gpt-6-astra | 对话,工具,识图,思考 | 分组(10)
|
gpt-6-sol | 对话,工具,识图,思考 | 分组(10)
|
gpt-6-luna | 对话,工具,识图,思考 | 分组(10)
|
claude-sonnet-5-5 | 对话,识图,工具 | 分组(6)
|
claude-opus-5-5 | 对话,工具,识图 | 分组(6)
|
claude-sonnet-5 | 对话,识图,工具 | 分组(8)
|
claude-fable-5-1 | 对话,识图,工具 | 分组(5)
|
共列入 220 个候选型号。查看完整模型、版本与接口目录。