跳转到主要内容
POST
/
v1beta
/
models
/
{model}
:streamGenerateContent
streamGenerateContent
curl --request POST \
  --url https://openp.ai/v1beta/models/{model}:streamGenerateContent
import requests

url = "https://openp.ai/v1beta/models/{model}:streamGenerateContent"

response = requests.post(url)

print(response.text)
const options = {method: 'POST'};

fetch('https://openp.ai/v1beta/models/{model}:streamGenerateContent', options)
.then(res => res.json())
.then(res => console.log(res))
.catch(err => console.error(err));
<?php

$curl = curl_init();

curl_setopt_array($curl, [
CURLOPT_URL => "https://openp.ai/v1beta/models/{model}:streamGenerateContent",
CURLOPT_RETURNTRANSFER => true,
CURLOPT_ENCODING => "",
CURLOPT_MAXREDIRS => 10,
CURLOPT_TIMEOUT => 30,
CURLOPT_HTTP_VERSION => CURL_HTTP_VERSION_1_1,
CURLOPT_CUSTOMREQUEST => "POST",
]);

$response = curl_exec($curl);
$err = curl_error($curl);

curl_close($curl);

if ($err) {
echo "cURL Error #:" . $err;
} else {
echo $response;
}
package main

import (
"fmt"
"net/http"
"io"
)

func main() {

url := "https://openp.ai/v1beta/models/{model}:streamGenerateContent"

req, _ := http.NewRequest("POST", url, nil)

res, _ := http.DefaultClient.Do(req)

defer res.Body.Close()
body, _ := io.ReadAll(res.Body)

fmt.Println(string(body))

}
HttpResponse<String> response = Unirest.post("https://openp.ai/v1beta/models/{model}:streamGenerateContent")
.asString();
require 'uri'
require 'net/http'

url = URI("https://openp.ai/v1beta/models/{model}:streamGenerateContent")

http = Net::HTTP.new(url.host, url.port)
http.use_ssl = true

request = Net::HTTP::Post.new(url)

response = http.request(request)
puts response.read_body
generateContent 完全一致,但 以流式形式返回 —— 边生成边推送 chunk,降低首字延迟。

请求

curl "https://openp.ai/v1beta/models/gemini-3.1-pro-preview:streamGenerateContent?alt=sse" \
  -H "x-goog-api-key: $OPENPAI_API_KEY" \
  -H "Content-Type: application/json" \
  -d '{
    "contents": [{"role": "user", "parts": [{"text": "讲个 100 字故事"}]}]
  }'
注意 query 参数 ?alt=sse —— 没有它时返回的是 JSON 数组(每条一个完整 candidate), 带上 alt=sse 才返回标准 SSE 流(data: {...} 形式)。

流式块

data: {"candidates":[{"content":{"role":"model","parts":[{"text":"在"}]},"index":0}]}

data: {"candidates":[{"content":{"role":"model","parts":[{"text":"一个"}]},"index":0}]}

...

data: {"candidates":[{"finishReason":"STOP","index":0}],"usageMetadata":{...}}
最后一块通常带 finishReasonusageMetadata

Python(google-genai)

from google import genai

client = genai.Client(
    api_key="sk-...",
    http_options={"base_url": "https://openp.ai"},
)

stream = client.models.generate_content_stream(
    model="gemini-3.1-pro-preview",
    contents="讲个 100 字故事",
)
for chunk in stream:
    print(chunk.text, end="", flush=True)

注意

  • 流式响应中也支持 tools / 函数调用 / 思考模式 —— 字段会出现在某个 chunk 内。
  • 客户端要处理 SSE 连接断开后的重试(不可幂等,重试会重新计费)。