gemini-3.8-flash
最后更新:2026-11-14
POSThttps://www.sagelib.com/chat/completions
gemini-3.8-flash 模型的聊天生成接口,OpenAI兼容,支持多轮上下文、流式输出、工具调用、结构化输出等。
接口鉴权方式请参考:API接入与鉴权
请求参数
请求头
| 参数名称 | 描述 |
|---|---|
*Authorization string |
鉴权令牌,格式为 Bearer ${AIGATEWAY_TOKEN} |
*Content-Type string |
默认值:application/json 可选值:application/json 内容类型,固定为 application/json |
Body 参数
| 参数名称 | 描述 |
|---|---|
*model string |
可选值:"gemini-3.8-flash" 指定调用的模型名称 |
*messages array |
可选值:content 会话消息,content 支持 text / image_url / input_audio 多模态块 |
max_tokens integer |
可选值:1 ~ 65536 输出 token 上限 |
stream boolean |
可选值:true、false 是否流式返回(SSE) |
reasoning_effort string |
默认值:medium 可选值:low、medium、high 思考强度 |
tools array |
可选值:Array of tool definitions 工具定义列表,模型可据此发起工具调用 |
tool_choice object |
可选值:none、auto、required 工具调用控制 |
response_format object |
可选值:json_schema 结构化输出 |
stop array |
可选值:String array (up to 5 items) 停止序列,命中即截断输出 |
请求示例
curl -v 'https://www.sagelib.com/chat/completions' \
-H "Authorization: Bearer ***" \
-H "Content-Type: application/json" \
-d '{
"model": "gemini-3.8-flash",
"messages": [
{
"role": "user",
"content": "What model are you? Which company made you? When were you launched? Briefly describe your capability boundaries."
}
]
}'
import json
import requests
# Configure base variables
base_url = "https://www.sagelib.com" # 把 base_url 换成你的网关地址 https://www.sagelib.com
api_key = "***" # Replace with your Bearer token
url = f"https://www.sagelib.com/chat/completions"
headers = {
"Authorization": f"Bearer {api_key}",
"Content-Type": "application/json",
}
data = {
"model": "gemini-3.8-flash",
"messages": [
{
"role": "user",
"content": "What model are you? Which company made you? When were you launched? Briefly describe your capability boundaries."
}
]
}
# Send the POST request
response = requests.post(url, headers=headers, json=data)
# Print the status code and the returned JSON data
print(f"Status Code: {response.status_code}")
try:
print(json.dumps(response.json(), indent=2, ensure_ascii=False))
except Exception:
print(response.text)
import java.io.BufferedReader;
import java.io.InputStreamReader;
import java.net.URI;
import java.net.http.HttpClient;
import java.net.http.HttpRequest;
import java.net.http.HttpResponse;
public class LlmStreamClient {
public static void main(String[] args) {
String baseUrl = "https://www.sagelib.com";
String apiKey = "***";
String url = "https://www.sagelib.com/chat/completions";
String jsonRequestBody = """
{
"model": "gemini-3.8-flash",
"messages": [
{
"role": "user",
"content": "What model are you? Which company made you? When were you launched? Briefly describe your capability boundaries."
}
]
}
""";
HttpClient client = HttpClient.newHttpClient();
HttpRequest request = HttpRequest.newBuilder()
.uri(URI.create(url))
.header("Authorization", "Bearer " + apiKey)
.header("Content-Type", "application/json")
.POST(HttpRequest.BodyPublishers.ofString(jsonRequestBody))
.build();
try {
// Use ofInputStream to handle the streaming response
HttpResponse<java.io.InputStream> response = client.send(request, HttpResponse.BodyHandlers.ofInputStream());
try (BufferedReader reader = new BufferedReader(new InputStreamReader(response.body()))) {
String line;
while ((line = reader.readLine()) != null) {
line = line.trim();
if (line.startsWith("data:")) {
String data = line.substring(5).trim();
if ("[DONE]".equals(data)) {
break;
}
// Tip: you can bring in Gson or Jackson here to parse the JSON in data and extract delta.content
System.out.println("Received stream chunk: " + data);
}
}
}
} catch (Exception e) {
e.printStackTrace();
}
}
}
package main
import (
"bytes"
"encoding/json"
"fmt"
"io"
"net/http"
)
func main() {
baseUrl := "https://www.sagelib.com"
apiKey := "***"
url := "https://www.sagelib.com/chat/completions"
jsonRequestBody := `
{
"model": "gemini-3.8-flash",
"messages": [
{
"role": "user",
"content": "What model are you? Which company made you? When were you launched? Briefly describe your capability boundaries."
}
]
}
`
req, err := http.NewRequest("POST", url, bytes.NewBufferString(jsonRequestBody))
if err != nil {
fmt.Println("Failed to create request:", err)
return
}
req.Header.Set("Authorization", "Bearer "+apiKey)
req.Header.Set("Content-Type", "application/json")
client := &http.Client{}
resp, err := client.Do(req)
if err != nil {
fmt.Println("Request failed:", err)
return
}
defer resp.Body.Close()
body, _ := io.ReadAll(resp.Body)
// Pretty-print the returned JSON data
var prettyBody map[string]interface{}
if err := json.Unmarshal(body, &prettyBody); err == nil {
pretty, _ := json.MarshalIndent(prettyBody, "", " ")
fmt.Println("Status Code:", resp.StatusCode)
fmt.Println(string(pretty))
} else {
fmt.Println("Status Code:", resp.StatusCode)
fmt.Println(string(body))
}
}
curl -v 'https://www.sagelib.com/chat/completions' \
-H "Authorization: Bearer ***" \
-H "Content-Type: application/json" \
-d '{
"model": "gemini-3.8-flash",
"messages": [
{
"role": "user",
"content": "What model are you? Which company made you? When were you launched? Briefly describe your capability boundaries."
}
],
"tools": [
{
"type": "function",
"function": {
"name": "get_weather",
"description": "Get weather",
"parameters": {
"type": "object",
"properties": {
"city": {
"type": "string"
}
},
"required": [
"city"
]
}
}
}
]
}'
import json
import requests
# Configure base variables
base_url = "https://www.sagelib.com" # 把 base_url 换成你的网关地址 https://www.sagelib.com
api_key = "***" # Replace with your Bearer token
url = f"https://www.sagelib.com/chat/completions"
headers = {
"Authorization": f"Bearer {api_key}",
"Content-Type": "application/json",
}
data = {
"model": "gemini-3.8-flash",
"messages": [
{
"role": "user",
"content": "What model are you? Which company made you? When were you launched? Briefly describe your capability boundaries."
}
],
"tools": [
{
"type": "function",
"function": {
"name": "get_weather",
"description": "Get weather",
"parameters": {
"type": "object",
"properties": {
"city": {
"type": "string"
}
},
"required": [
"city"
]
}
}
}
]
}
# Send the POST request
response = requests.post(url, headers=headers, json=data)
# Print the status code and the returned JSON data
print(f"Status Code: {response.status_code}")
try:
print(json.dumps(response.json(), indent=2, ensure_ascii=False))
except Exception:
print(response.text)
import java.io.BufferedReader;
import java.io.InputStreamReader;
import java.net.URI;
import java.net.http.HttpClient;
import java.net.http.HttpRequest;
import java.net.http.HttpResponse;
public class LlmStreamClient {
public static void main(String[] args) {
String baseUrl = "https://www.sagelib.com";
String apiKey = "***";
String url = "https://www.sagelib.com/chat/completions";
String jsonRequestBody = """
{
"model": "gemini-3.8-flash",
"messages": [
{
"role": "user",
"content": "What model are you? Which company made you? When were you launched? Briefly describe your capability boundaries."
}
],
"tools": [
{
"type": "function",
"function": {
"name": "get_weather",
"description": "Get weather",
"parameters": {
"type": "object",
"properties": {
"city": {
"type": "string"
}
},
"required": [
"city"
]
}
}
}
]
}
""";
HttpClient client = HttpClient.newHttpClient();
HttpRequest request = HttpRequest.newBuilder()
.uri(URI.create(url))
.header("Authorization", "Bearer " + apiKey)
.header("Content-Type", "application/json")
.POST(HttpRequest.BodyPublishers.ofString(jsonRequestBody))
.build();
try {
// Use ofInputStream to handle the streaming response
HttpResponse<java.io.InputStream> response = client.send(request, HttpResponse.BodyHandlers.ofInputStream());
try (BufferedReader reader = new BufferedReader(new InputStreamReader(response.body()))) {
String line;
while ((line = reader.readLine()) != null) {
line = line.trim();
if (line.startsWith("data:")) {
String data = line.substring(5).trim();
if ("[DONE]".equals(data)) {
break;
}
// Tip: you can bring in Gson or Jackson here to parse the JSON in data and extract delta.content
System.out.println("Received stream chunk: " + data);
}
}
}
} catch (Exception e) {
e.printStackTrace();
}
}
}
package main
import (
"bytes"
"encoding/json"
"fmt"
"io"
"net/http"
)
func main() {
baseUrl := "https://www.sagelib.com"
apiKey := "***"
url := "https://www.sagelib.com/chat/completions"
jsonRequestBody := `
{
"model": "gemini-3.8-flash",
"messages": [
{
"role": "user",
"content": "What model are you? Which company made you? When were you launched? Briefly describe your capability boundaries."
}
],
"tools": [
{
"type": "function",
"function": {
"name": "get_weather",
"description": "Get weather",
"parameters": {
"type": "object",
"properties": {
"city": {
"type": "string"
}
},
"required": [
"city"
]
}
}
}
]
}
`
req, err := http.NewRequest("POST", url, bytes.NewBufferString(jsonRequestBody))
if err != nil {
fmt.Println("Failed to create request:", err)
return
}
req.Header.Set("Authorization", "Bearer "+apiKey)
req.Header.Set("Content-Type", "application/json")
client := &http.Client{}
resp, err := client.Do(req)
if err != nil {
fmt.Println("Request failed:", err)
return
}
defer resp.Body.Close()
body, _ := io.ReadAll(resp.Body)
// Pretty-print the returned JSON data
var prettyBody map[string]interface{}
if err := json.Unmarshal(body, &prettyBody); err == nil {
pretty, _ := json.MarshalIndent(prettyBody, "", " ")
fmt.Println("Status Code:", resp.StatusCode)
fmt.Println(string(pretty))
} else {
fmt.Println("Status Code:", resp.StatusCode)
fmt.Println(string(body))
}
}
curl -v 'https://www.sagelib.com/chat/completions' \
-H "Authorization: Bearer ***" \
-H "Content-Type: application/json" \
-d '{
"model": "gemini-3.8-flash",
"messages": [
{
"role": "user",
"content": [
{
"type": "image_url",
"image_url": {
"url": "${image_url}"
}
},
{
"type": "text",
"text": "Carefully observe this image and describe the subject, scene, and style details."
}
]
}
]
}'
import json
import requests
# Configure base variables
base_url = "https://www.sagelib.com" # 把 base_url 换成你的网关地址 https://www.sagelib.com
api_key = "***" # Replace with your Bearer token
url = f"https://www.sagelib.com/chat/completions"
headers = {
"Authorization": f"Bearer {api_key}",
"Content-Type": "application/json",
}
data = {
"model": "gemini-3.8-flash",
"messages": [
{
"role": "user",
"content": [
{
"type": "image_url",
"image_url": {
"url": "${image_url}"
}
},
{
"type": "text",
"text": "Carefully observe this image and describe the subject, scene, and style details."
}
]
}
]
}
# Send the POST request
response = requests.post(url, headers=headers, json=data)
# Print the status code and the returned JSON data
print(f"Status Code: {response.status_code}")
try:
print(json.dumps(response.json(), indent=2, ensure_ascii=False))
except Exception:
print(response.text)
import java.io.BufferedReader;
import java.io.InputStreamReader;
import java.net.URI;
import java.net.http.HttpClient;
import java.net.http.HttpRequest;
import java.net.http.HttpResponse;
public class LlmStreamClient {
public static void main(String[] args) {
String baseUrl = "https://www.sagelib.com";
String apiKey = "***";
String url = "https://www.sagelib.com/chat/completions";
String jsonRequestBody = """
{
"model": "gemini-3.8-flash",
"messages": [
{
"role": "user",
"content": [
{
"type": "image_url",
"image_url": {
"url": "${image_url}"
}
},
{
"type": "text",
"text": "Carefully observe this image and describe the subject, scene, and style details."
}
]
}
]
}
""";
HttpClient client = HttpClient.newHttpClient();
HttpRequest request = HttpRequest.newBuilder()
.uri(URI.create(url))
.header("Authorization", "Bearer " + apiKey)
.header("Content-Type", "application/json")
.POST(HttpRequest.BodyPublishers.ofString(jsonRequestBody))
.build();
try {
// Use ofInputStream to handle the streaming response
HttpResponse<java.io.InputStream> response = client.send(request, HttpResponse.BodyHandlers.ofInputStream());
try (BufferedReader reader = new BufferedReader(new InputStreamReader(response.body()))) {
String line;
while ((line = reader.readLine()) != null) {
line = line.trim();
if (line.startsWith("data:")) {
String data = line.substring(5).trim();
if ("[DONE]".equals(data)) {
break;
}
// Tip: you can bring in Gson or Jackson here to parse the JSON in data and extract delta.content
System.out.println("Received stream chunk: " + data);
}
}
}
} catch (Exception e) {
e.printStackTrace();
}
}
}
package main
import (
"bytes"
"encoding/json"
"fmt"
"io"
"net/http"
)
func main() {
baseUrl := "https://www.sagelib.com"
apiKey := "***"
url := "https://www.sagelib.com/chat/completions"
jsonRequestBody := `
{
"model": "gemini-3.8-flash",
"messages": [
{
"role": "user",
"content": [
{
"type": "image_url",
"image_url": {
"url": "${image_url}"
}
},
{
"type": "text",
"text": "Carefully observe this image and describe the subject, scene, and style details."
}
]
}
]
}
`
req, err := http.NewRequest("POST", url, bytes.NewBufferString(jsonRequestBody))
if err != nil {
fmt.Println("Failed to create request:", err)
return
}
req.Header.Set("Authorization", "Bearer "+apiKey)
req.Header.Set("Content-Type", "application/json")
client := &http.Client{}
resp, err := client.Do(req)
if err != nil {
fmt.Println("Request failed:", err)
return
}
defer resp.Body.Close()
body, _ := io.ReadAll(resp.Body)
// Pretty-print the returned JSON data
var prettyBody map[string]interface{}
if err := json.Unmarshal(body, &prettyBody); err == nil {
pretty, _ := json.MarshalIndent(prettyBody, "", " ")
fmt.Println("Status Code:", resp.StatusCode)
fmt.Println(string(pretty))
} else {
fmt.Println("Status Code:", resp.StatusCode)
fmt.Println(string(body))
}
}
响应参数
Body 参数
| 参数名称 | 描述 |
|---|---|
id string |
补全请求 ID |
object string |
固定为 chat.completion |
model string |
实际使用的模型名称 |
created integer |
响应时间戳 |
choices array |
|
service_tier string |
响应回带 ON_DEMAND |
usage object |
|
prompt_tokens integer |
输入 token 数 |
completion_tokens integer |
输出 token 数(含推理) |
completion_tokens_details object |
|
reasoning_tokens integer |
推理消耗 token 数 |
POSThttps://www.sagelib.com/gemini/v1beta/models/{model}:streamGenerateContent
gemini-3.8-flash 模型的聊天生成接口,Gemini直连,支持多轮上下文、流式输出、工具调用、结构化输出等。
接口鉴权方式请参考:API接入与鉴权
请求参数
请求头
| 参数名称 | 描述 |
|---|---|
*Content-Type string |
可选值:application/json application/json |
*x-goog-api-key string |
鉴权令牌,格式为 ${AIGATEWAY_TOKEN} |
Body 参数
| 参数名称 | 描述 |
|---|---|
*model string |
可选值:"gemini-3.8-flash" 模型名称(URL models/${model_id}:generateContent 路径段) |
*contents array |
可选值:parts 对话内容(parts 数组,可含文本/图像/视频/音频/PDF 输入) |
system_instruction object |
可选值:Content or string 系统指令 |
safety_settings array |
可选值:Array of HARM category thresholds 安全设置 |
tools array |
可选值:functionDeclarations etc. 工具声明(function calling 等) |
tool_config object |
可选值:function_calling_config 工具调用控制(mode / allowed_function_names) |
config.max_output_tokens integer |
可选值:1 ~ 65536 输出 token 上限 |
config.stop_sequences array |
可选值:String array (up to 5 items) 停止序列,命中即截断输出 |
config.seed integer |
可选值:Integer 随机种子 |
config.response_mime_type string |
默认值:text/plain 可选值:text、plain、application、json 响应 mime 类型(配合结构化输出) |
config.response_schema object |
可选值:OpenAPI 3.0 subset Schema object 结构化输出 schema(须配 response_mime_type=application/json) |
config.response_json_schema object |
可选值:Standard JSON Schema 结构化输出 JSON Schema(response_schema 的替代) |
config.thinking_config object |
默认值:thinking_level:medium 可选值:medium、high 思考配置(include_thoughts 可选) |
config.cached_content string |
可选值:Cached content resource name 内容缓存引用 |
config.routing_config object |
可选值:model_router configuration 路由配置 |
config.labels object |
可选值:Key-value pairs 用户元数据标签 |
config.response_modalities array |
可选值:TEXT 响应模态(本模型输出仅文本) |
config.media_resolution string |
可选值:MEDIA_RESOLUTION_LOW、MEDIUM、HIGH 媒体输入分辨率(多模态输入用) |
请求示例
curl -v 'https://www.sagelib.com/gemini/v1beta/models/gemini-3.8-flash:streamGenerateContent' \
-H "x-goog-api-key: ***" \
-H "Content-Type: application/json" \
-d '{
"contents": [
{
"parts": [
{
"text": "What model are you? Which company made you? When were you launched? Briefly describe your capability boundaries."
}
],
"role": "user"
}
]
}'
import json
import requests
# Configure base variables
base_url = "https://www.sagelib.com" # 把 base_url 换成你的网关地址 https://www.sagelib.com
api_key = "***" # Replace with your API key
url = f"https://www.sagelib.com/gemini/v1beta/models/gemini-3.8-flash:streamGenerateContent"
headers = {
"x-goog-api-key": api_key,
"Content-Type": "application/json",
}
data = {
"contents": [
{
"parts": [
{
"text": "What model are you? Which company made you? When were you launched? Briefly describe your capability boundaries."
}
],
"role": "user"
}
]
}
# Send the POST request
response = requests.post(url, headers=headers, json=data)
# Print the status code and the returned JSON data
print(f"Status Code: {response.status_code}")
try:
print(json.dumps(response.json(), indent=2, ensure_ascii=False))
except Exception:
print(response.text)
import java.io.BufferedReader;
import java.io.InputStreamReader;
import java.net.URI;
import java.net.http.HttpClient;
import java.net.http.HttpRequest;
import java.net.http.HttpResponse;
public class LlmStreamClient {
public static void main(String[] args) {
String baseUrl = "https://www.sagelib.com";
String apiKey = "***";
String url = "https://www.sagelib.com/gemini/v1beta/models/gemini-3.8-flash:streamGenerateContent";
String jsonRequestBody = """
{
"contents": [
{
"parts": [
{
"text": "What model are you? Which company made you? When were you launched? Briefly describe your capability boundaries."
}
],
"role": "user"
}
]
}
""";
HttpClient client = HttpClient.newHttpClient();
HttpRequest request = HttpRequest.newBuilder()
.uri(URI.create(url))
.header("x-goog-api-key", apiKey)
.header("Content-Type", "application/json")
.POST(HttpRequest.BodyPublishers.ofString(jsonRequestBody))
.build();
try {
// Use ofInputStream to handle the streaming response
HttpResponse<java.io.InputStream> response = client.send(request, HttpResponse.BodyHandlers.ofInputStream());
try (BufferedReader reader = new BufferedReader(new InputStreamReader(response.body()))) {
String line;
while ((line = reader.readLine()) != null) {
line = line.trim();
if (line.startsWith("data:")) {
String data = line.substring(5).trim();
if ("[DONE]".equals(data)) {
break;
}
// Tip: you can bring in Gson or Jackson here to parse the JSON in data and extract delta.content
System.out.println("Received stream chunk: " + data);
}
}
}
} catch (Exception e) {
e.printStackTrace();
}
}
}
package main
import (
"bytes"
"encoding/json"
"fmt"
"io"
"net/http"
)
func main() {
baseUrl := "https://www.sagelib.com"
apiKey := "***"
url := "https://www.sagelib.com/gemini/v1beta/models/gemini-3.8-flash:streamGenerateContent"
jsonRequestBody := `
{
"contents": [
{
"parts": [
{
"text": "What model are you? Which company made you? When were you launched? Briefly describe your capability boundaries."
}
],
"role": "user"
}
]
}
`
req, err := http.NewRequest("POST", url, bytes.NewBufferString(jsonRequestBody))
if err != nil {
fmt.Println("Failed to create request:", err)
return
}
req.Header.Set("x-goog-api-key", apiKey)
req.Header.Set("Content-Type", "application/json")
client := &http.Client{}
resp, err := client.Do(req)
if err != nil {
fmt.Println("Request failed:", err)
return
}
defer resp.Body.Close()
body, _ := io.ReadAll(resp.Body)
// Pretty-print the returned JSON data
var prettyBody map[string]interface{}
if err := json.Unmarshal(body, &prettyBody); err == nil {
pretty, _ := json.MarshalIndent(prettyBody, "", " ")
fmt.Println("Status Code:", resp.StatusCode)
fmt.Println(string(pretty))
} else {
fmt.Println("Status Code:", resp.StatusCode)
fmt.Println(string(body))
}
}
curl -v 'https://www.sagelib.com/gemini/v1beta/models/gemini-3.8-flash:streamGenerateContent' \
-H "x-goog-api-key: ***" \
-H "Content-Type: application/json" \
-d '{
"contents": [
{
"parts": [
{
"text": "How is the weather in Beijing today? Please use a tool to query the weather."
}
],
"role": "user"
}
],
"tools": [
{
"functionDeclarations": [
{
"name": "get_weather",
"description": "Query the real-time weather conditions of a specified city",
"parameters": {
"type": "object",
"properties": {
"city": {
"type": "string"
}
},
"required": [
"city"
]
}
}
]
}
]
}'
import json
import requests
# Configure base variables
base_url = "https://www.sagelib.com" # 把 base_url 换成你的网关地址 https://www.sagelib.com
api_key = "***" # Replace with your API key
url = f"https://www.sagelib.com/gemini/v1beta/models/gemini-3.8-flash:streamGenerateContent"
headers = {
"x-goog-api-key": api_key,
"Content-Type": "application/json",
}
data = {
"contents": [
{
"parts": [
{
"text": "How is the weather in Beijing today? Please use a tool to query the weather."
}
],
"role": "user"
}
],
"tools": [
{
"functionDeclarations": [
{
"name": "get_weather",
"description": "Query the real-time weather conditions of a specified city",
"parameters": {
"type": "object",
"properties": {
"city": {
"type": "string"
}
},
"required": [
"city"
]
}
}
]
}
]
}
# Send the POST request
response = requests.post(url, headers=headers, json=data)
# Print the status code and the returned JSON data
print(f"Status Code: {response.status_code}")
try:
print(json.dumps(response.json(), indent=2, ensure_ascii=False))
except Exception:
print(response.text)
import java.io.BufferedReader;
import java.io.InputStreamReader;
import java.net.URI;
import java.net.http.HttpClient;
import java.net.http.HttpRequest;
import java.net.http.HttpResponse;
public class LlmStreamClient {
public static void main(String[] args) {
String baseUrl = "https://www.sagelib.com";
String apiKey = "***";
String url = "https://www.sagelib.com/gemini/v1beta/models/gemini-3.8-flash:streamGenerateContent";
String jsonRequestBody = """
{
"contents": [
{
"parts": [
{
"text": "How is the weather in Beijing today? Please use a tool to query the weather."
}
],
"role": "user"
}
],
"tools": [
{
"functionDeclarations": [
{
"name": "get_weather",
"description": "Query the real-time weather conditions of a specified city",
"parameters": {
"type": "object",
"properties": {
"city": {
"type": "string"
}
},
"required": [
"city"
]
}
}
]
}
]
}
""";
HttpClient client = HttpClient.newHttpClient();
HttpRequest request = HttpRequest.newBuilder()
.uri(URI.create(url))
.header("x-goog-api-key", apiKey)
.header("Content-Type", "application/json")
.POST(HttpRequest.BodyPublishers.ofString(jsonRequestBody))
.build();
try {
// Use ofInputStream to handle the streaming response
HttpResponse<java.io.InputStream> response = client.send(request, HttpResponse.BodyHandlers.ofInputStream());
try (BufferedReader reader = new BufferedReader(new InputStreamReader(response.body()))) {
String line;
while ((line = reader.readLine()) != null) {
line = line.trim();
if (line.startsWith("data:")) {
String data = line.substring(5).trim();
if ("[DONE]".equals(data)) {
break;
}
// Tip: you can bring in Gson or Jackson here to parse the JSON in data and extract delta.content
System.out.println("Received stream chunk: " + data);
}
}
}
} catch (Exception e) {
e.printStackTrace();
}
}
}
package main
import (
"bytes"
"encoding/json"
"fmt"
"io"
"net/http"
)
func main() {
baseUrl := "https://www.sagelib.com"
apiKey := "***"
url := "https://www.sagelib.com/gemini/v1beta/models/gemini-3.8-flash:streamGenerateContent"
jsonRequestBody := `
{
"contents": [
{
"parts": [
{
"text": "How is the weather in Beijing today? Please use a tool to query the weather."
}
],
"role": "user"
}
],
"tools": [
{
"functionDeclarations": [
{
"name": "get_weather",
"description": "Query the real-time weather conditions of a specified city",
"parameters": {
"type": "object",
"properties": {
"city": {
"type": "string"
}
},
"required": [
"city"
]
}
}
]
}
]
}
`
req, err := http.NewRequest("POST", url, bytes.NewBufferString(jsonRequestBody))
if err != nil {
fmt.Println("Failed to create request:", err)
return
}
req.Header.Set("x-goog-api-key", apiKey)
req.Header.Set("Content-Type", "application/json")
client := &http.Client{}
resp, err := client.Do(req)
if err != nil {
fmt.Println("Request failed:", err)
return
}
defer resp.Body.Close()
body, _ := io.ReadAll(resp.Body)
// Pretty-print the returned JSON data
var prettyBody map[string]interface{}
if err := json.Unmarshal(body, &prettyBody); err == nil {
pretty, _ := json.MarshalIndent(prettyBody, "", " ")
fmt.Println("Status Code:", resp.StatusCode)
fmt.Println(string(pretty))
} else {
fmt.Println("Status Code:", resp.StatusCode)
fmt.Println(string(body))
}
}
curl -v 'https://www.sagelib.com/gemini/v1beta/models/gemini-3.8-flash:streamGenerateContent' \
-H "x-goog-api-key: ***" \
-H "Content-Type: application/json" \
-d '{
"contents": [
{
"parts": [
{
"fileData": {
"mimeType": "video/mp4",
"fileUri": "${video_url}"
}
},
{
"text": "Carefully watch this video and describe the main actions and scene changes in chronological order."
}
],
"role": "user"
}
]
}'
import json
import requests
# Configure base variables
base_url = "https://www.sagelib.com" # 把 base_url 换成你的网关地址 https://www.sagelib.com
api_key = "***" # Replace with your API key
url = f"https://www.sagelib.com/gemini/v1beta/models/gemini-3.8-flash:streamGenerateContent"
headers = {
"x-goog-api-key": api_key,
"Content-Type": "application/json",
}
data = {
"contents": [
{
"parts": [
{
"fileData": {
"mimeType": "video/mp4",
"fileUri": "${video_url}"
}
},
{
"text": "Carefully watch this video and describe the main actions and scene changes in chronological order."
}
],
"role": "user"
}
]
}
# Send the POST request
response = requests.post(url, headers=headers, json=data)
# Print the status code and the returned JSON data
print(f"Status Code: {response.status_code}")
try:
print(json.dumps(response.json(), indent=2, ensure_ascii=False))
except Exception:
print(response.text)
import java.io.BufferedReader;
import java.io.InputStreamReader;
import java.net.URI;
import java.net.http.HttpClient;
import java.net.http.HttpRequest;
import java.net.http.HttpResponse;
public class LlmStreamClient {
public static void main(String[] args) {
String baseUrl = "https://www.sagelib.com";
String apiKey = "***";
String url = "https://www.sagelib.com/gemini/v1beta/models/gemini-3.8-flash:streamGenerateContent";
String jsonRequestBody = """
{
"contents": [
{
"parts": [
{
"fileData": {
"mimeType": "video/mp4",
"fileUri": "${video_url}"
}
},
{
"text": "Carefully watch this video and describe the main actions and scene changes in chronological order."
}
],
"role": "user"
}
]
}
""";
HttpClient client = HttpClient.newHttpClient();
HttpRequest request = HttpRequest.newBuilder()
.uri(URI.create(url))
.header("x-goog-api-key", apiKey)
.header("Content-Type", "application/json")
.POST(HttpRequest.BodyPublishers.ofString(jsonRequestBody))
.build();
try {
// Use ofInputStream to handle the streaming response
HttpResponse<java.io.InputStream> response = client.send(request, HttpResponse.BodyHandlers.ofInputStream());
try (BufferedReader reader = new BufferedReader(new InputStreamReader(response.body()))) {
String line;
while ((line = reader.readLine()) != null) {
line = line.trim();
if (line.startsWith("data:")) {
String data = line.substring(5).trim();
if ("[DONE]".equals(data)) {
break;
}
// Tip: you can bring in Gson or Jackson here to parse the JSON in data and extract delta.content
System.out.println("Received stream chunk: " + data);
}
}
}
} catch (Exception e) {
e.printStackTrace();
}
}
}
package main
import (
"bytes"
"encoding/json"
"fmt"
"io"
"net/http"
)
func main() {
baseUrl := "https://www.sagelib.com"
apiKey := "***"
url := "https://www.sagelib.com/gemini/v1beta/models/gemini-3.8-flash:streamGenerateContent"
jsonRequestBody := `
{
"contents": [
{
"parts": [
{
"fileData": {
"mimeType": "video/mp4",
"fileUri": "${video_url}"
}
},
{
"text": "Carefully watch this video and describe the main actions and scene changes in chronological order."
}
],
"role": "user"
}
]
}
`
req, err := http.NewRequest("POST", url, bytes.NewBufferString(jsonRequestBody))
if err != nil {
fmt.Println("Failed to create request:", err)
return
}
req.Header.Set("x-goog-api-key", apiKey)
req.Header.Set("Content-Type", "application/json")
client := &http.Client{}
resp, err := client.Do(req)
if err != nil {
fmt.Println("Request failed:", err)
return
}
defer resp.Body.Close()
body, _ := io.ReadAll(resp.Body)
// Pretty-print the returned JSON data
var prettyBody map[string]interface{}
if err := json.Unmarshal(body, &prettyBody); err == nil {
pretty, _ := json.MarshalIndent(prettyBody, "", " ")
fmt.Println("Status Code:", resp.StatusCode)
fmt.Println(string(pretty))
} else {
fmt.Println("Status Code:", resp.StatusCode)
fmt.Println(string(body))
}
}
响应参数
Body 参数
| 参数名称 | 描述 |
|---|---|
candidates array |
|
createTime string |
响应创建时间 |
modelVersion string |
模型版本 |
responseId string |
响应 ID |
usageMetadata object |
|
promptTokenCount integer |
输入 token 数 |
candidatesTokenCount integer |
输出 token 数 |
thoughtsTokenCount integer |
思考消耗 token 数 |
totalTokenCount integer |
总 token 数 |