gemini-3.6-flash
最后更新:2026-11-14
POSThttps://www.sagelib.com/chat/completions
gemini-3.6-flash 模型的聊天生成接口,OpenAI兼容,支持多轮上下文、流式输出、工具调用、结构化输出等。
接口鉴权方式请参考:API接入与鉴权
请求参数
请求头
| 参数名称 | 描述 |
|---|---|
*Authorization string |
鉴权令牌,格式为 Bearer ${AIGATEWAY_TOKEN} |
*Content-Type string |
默认值:application/json 可选值:application/json 内容类型,固定为 application/json |
Body 参数
| 参数名称 | 描述 |
|---|---|
*model string |
可选值:"gemini-3.6-flash" 模型名称,固定值 |
*messages array |
可选值:At least 1 message 对话消息列表,每项含 role(system/user/assistant)和 content |
temperature float |
采样温度,控制输出随机性 |
max_tokens integer |
可选值:>= 1 最大输出 token 数 |
max_completion_tokens integer |
可选值:>= 1 最大输出 token 数(别名) |
stop string |
可选值:String or array 停止序列 |
stream boolean |
默认值:false 可选值:true、false 是否流式输出,true 时返回 SSE |
top_p float |
核采样参数 |
response_format object |
可选值:text 输出格式控制 |
tools array |
可选值:type、function 工具/函数声明 |
tool_choice string |
可选值:auto、none 工具选择策略 |
reasoning_effort string |
可选值:none、low、medium、high、max 推理深度控制 |
请求示例
curl -v 'https://www.sagelib.com/chat/completions' \
-H "Authorization: Bearer ***" \
-H "Content-Type: application/json" \
-d '{
"messages": [
{
"content": "What model are you? Which company made you? Briefly describe your capability boundaries.",
"role": "user"
}
],
"model": "gemini-3.6-flash"
}'
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 = {
"messages": [
{
"content": "What model are you? Which company made you? Briefly describe your capability boundaries.",
"role": "user"
}
],
"model": "gemini-3.6-flash"
}
# 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 = """
{
"messages": [
{
"content": "What model are you? Which company made you? Briefly describe your capability boundaries.",
"role": "user"
}
],
"model": "gemini-3.6-flash"
}
""";
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 := `
{
"messages": [
{
"content": "What model are you? Which company made you? Briefly describe your capability boundaries.",
"role": "user"
}
],
"model": "gemini-3.6-flash"
}
`
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.6-flash",
"messages": [
{
"role": "user",
"content": "List the time and space complexity of 5 classic sorting algorithms; output as a JSON array with each item containing name/time_complexity/space_complexity/stable fields"
}
],
"response_format": {
"type": "json_object"
},
"max_tokens": 500
}'
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.6-flash",
"messages": [
{
"role": "user",
"content": "List the time and space complexity of 5 classic sorting algorithms; output as a JSON array with each item containing name/time_complexity/space_complexity/stable fields"
}
],
"response_format": {
"type": "json_object"
},
"max_tokens": 500
}
# 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.6-flash",
"messages": [
{
"role": "user",
"content": "List the time and space complexity of 5 classic sorting algorithms; output as a JSON array with each item containing name/time_complexity/space_complexity/stable fields"
}
],
"response_format": {
"type": "json_object"
},
"max_tokens": 500
}
""";
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.6-flash",
"messages": [
{
"role": "user",
"content": "List the time and space complexity of 5 classic sorting algorithms; output as a JSON array with each item containing name/time_complexity/space_complexity/stable fields"
}
],
"response_format": {
"type": "json_object"
},
"max_tokens": 500
}
`
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 '{
"messages": [
{
"content": "Please read the following technical document carefully and summarize the key points (3-5 conclusions):\n\nArtificial intelligence has developed rapidly over the past decade. From AlexNet\u0027s breakthrough in the ImageNet competition in 2012, to the introduction of the Transformer architecture in 2017 that reshaped NLP research, to the emergence of ChatGPT in 2022 that brought large language models to the public. Algorithms, computing power, and data — the three driving forces of deep learning — have together propelled this wave of AI...\n\nPlease summarize the key points based on the content above.",
"role": "user"
}
],
"model": "gemini-3.6-flash",
"reasoning_effort": "medium"
}'
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 = {
"messages": [
{
"content": "Please read the following technical document carefully and summarize the key points (3-5 conclusions):\n\nArtificial intelligence has developed rapidly over the past decade. From AlexNet\u0027s breakthrough in the ImageNet competition in 2012, to the introduction of the Transformer architecture in 2017 that reshaped NLP research, to the emergence of ChatGPT in 2022 that brought large language models to the public. Algorithms, computing power, and data — the three driving forces of deep learning — have together propelled this wave of AI...\n\nPlease summarize the key points based on the content above.",
"role": "user"
}
],
"model": "gemini-3.6-flash",
"reasoning_effort": "medium"
}
# 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 = """
{
"messages": [
{
"content": "Please read the following technical document carefully and summarize the key points (3-5 conclusions):\n\nArtificial intelligence has developed rapidly over the past decade. From AlexNet\u0027s breakthrough in the ImageNet competition in 2012, to the introduction of the Transformer architecture in 2017 that reshaped NLP research, to the emergence of ChatGPT in 2022 that brought large language models to the public. Algorithms, computing power, and data — the three driving forces of deep learning — have together propelled this wave of AI...\n\nPlease summarize the key points based on the content above.",
"role": "user"
}
],
"model": "gemini-3.6-flash",
"reasoning_effort": "medium"
}
""";
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 := `
{
"messages": [
{
"content": "Please read the following technical document carefully and summarize the key points (3-5 conclusions):\n\nArtificial intelligence has developed rapidly over the past decade. From AlexNet\u0027s breakthrough in the ImageNet competition in 2012, to the introduction of the Transformer architecture in 2017 that reshaped NLP research, to the emergence of ChatGPT in 2022 that brought large language models to the public. Algorithms, computing power, and data — the three driving forces of deep learning — have together propelled this wave of AI...\n\nPlease summarize the key points based on the content above.",
"role": "user"
}
],
"model": "gemini-3.6-flash",
"reasoning_effort": "medium"
}
`
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 |
请求唯一标识 |
object string |
固定为 chat.completion |
created integer |
创建时间戳(Unix 秒) |
model string |
模型名称 |
choices array |
生成结果数组 |
usage object |
|
prompt_tokens integer |
输入 token 数 |
completion_tokens integer |
输出 token 数 |
total_tokens integer |
总 token 数 |
POSThttps://www.sagelib.com/gemini/v1beta/models/{model}:streamGenerateContent
gemini-3.6-flash 模型的聊天生成接口,Gemini直连,支持多轮上下文、流式输出、工具调用、结构化输出等。
接口鉴权方式请参考:API接入与鉴权
请求参数
请求头
| 参数名称 | 描述 |
|---|---|
*Content-Type string |
可选值:application/json application/json |
*x-goog-api-key string |
鉴权令牌,格式为 ${AIGATEWAY_TOKEN} |
Body 参数
| 参数名称 | 描述 |
|---|---|
*contents array |
可选值:At least 1 Content object 对话内容,每项含 role(user/model)和 parts(text/inlineData/fileData 列表) |
systemInstruction object |
可选值:Contains parts[].text 系统指令,设定模型全局行为 |
safetySettings array |
可选值:threshold 安全设置,覆盖默认安全阈值 |
tools array |
可选值:List of functionDeclarations 工具/函数声明 |
toolConfig object |
可选值:functionCallingConfig 工具配置(需配合 tools) |
generationConfig object |
生成配置子对象 |
generationConfig.temperature float |
采样温度 |
generationConfig.topP float |
核心采样 |
generationConfig.topK integer |
Top-K 采样 |
generationConfig.maxOutputTokens integer |
可选值:1 ~ 65536 最大输出 token 数 |
generationConfig.stopSequences array |
可选值:string[] 停止序列列表 |
generationConfig.seed integer |
随机种子 |
generationConfig.responseMimeType string |
可选值:text、plain、application、json 输出 MIME 类型 |
generationConfig.responseSchema object |
可选值:properties 结构化输出 schema |
generationConfig.responseJsonSchema object |
JSON Schema(与 responseSchema 互斥) |
generationConfig.responseLogprobs boolean |
可选值:true、false 是否返回对数概率 |
generationConfig.logprobs integer |
可选值:>= 0 返回最可能 N 个 token(需 responseLogprobs) |
generationConfig.presencePenalty float |
可选值:-2 ~ 2 存在惩罚 |
generationConfig.frequencyPenalty float |
可选值:-2 ~ 2 频率惩罚 |
generationConfig.thinkingConfig object |
可选值:thinkingBudget、includeThoughts 思考配置 |
generationConfig.responseModalities array |
可选值:TEXT、AUDIO、IMAGE、VIDEO 响应模态列表 |
generationConfig.cachedContent string |
可选值:cachedContents 缓存内容引用 |
generationConfig.labels object |
可选值:key-value pairs 请求标签 |
generationConfig.automaticFunctionCalling object |
可选值:disable、maximumRemoteCallCount 自动函数调用 |
generationConfig.enableEnhancedCivicAnswers boolean |
可选值:true、false 增强公民问题回答 |
generationConfig.serviceTier string |
服务等级 |
generationConfig.modelArmorConfig object |
模型安全防护配置 |
generationConfig.mediaResolution object |
可选值:LOW、MEDIUM、HIGH 媒体分辨率控制 |
generationConfig.routingConfig object |
可选值:modelRoutingPreference 路由配置 |
generationConfig.modelSelectionConfig object |
模型选择配置 |
请求示例
curl -v 'https://www.sagelib.com/gemini/v1beta/models/gemini-3.6-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.6-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.6-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.6-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.6-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"
}
],
"generationConfig": {
"responseSchema": {
"type": "OBJECT",
"properties": {
"name": {
"type": "STRING"
}
}
}
}
}'
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.6-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"
}
],
"generationConfig": {
"responseSchema": {
"type": "OBJECT",
"properties": {
"name": {
"type": "STRING"
}
}
}
}
}
# 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.6-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"
}
],
"generationConfig": {
"responseSchema": {
"type": "OBJECT",
"properties": {
"name": {
"type": "STRING"
}
}
}
}
}
""";
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.6-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"
}
],
"generationConfig": {
"responseSchema": {
"type": "OBJECT",
"properties": {
"name": {
"type": "STRING"
}
}
}
}
}
`
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.6-flash:streamGenerateContent' \
-H "x-goog-api-key: ***" \
-H "Content-Type: application/json" \
-d '{
"contents": [
{
"parts": [
{
"text": "Analyze the correctness of the following algorithm: for an undirected graph G=(V,E), use DFS to determine whether a cycle exists; give a rigorous reasoning process."
}
],
"role": "user"
}
],
"systemInstruction": {
"parts": [
{
"text": "You are a computer science professor; please answer in a rigorous academic style using mathematical notation and precise logical reasoning."
}
]
},
"generationConfig": {
"thinkingConfig": {
"thinkingBudget": 1024,
"includeThoughts": true
}
}
}'
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.6-flash:streamGenerateContent"
headers = {
"x-goog-api-key": api_key,
"Content-Type": "application/json",
}
data = {
"contents": [
{
"parts": [
{
"text": "Analyze the correctness of the following algorithm: for an undirected graph G=(V,E), use DFS to determine whether a cycle exists; give a rigorous reasoning process."
}
],
"role": "user"
}
],
"systemInstruction": {
"parts": [
{
"text": "You are a computer science professor; please answer in a rigorous academic style using mathematical notation and precise logical reasoning."
}
]
},
"generationConfig": {
"thinkingConfig": {
"thinkingBudget": 1024,
"includeThoughts": True
}
}
}
# 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.6-flash:streamGenerateContent";
String jsonRequestBody = """
{
"contents": [
{
"parts": [
{
"text": "Analyze the correctness of the following algorithm: for an undirected graph G=(V,E), use DFS to determine whether a cycle exists; give a rigorous reasoning process."
}
],
"role": "user"
}
],
"systemInstruction": {
"parts": [
{
"text": "You are a computer science professor; please answer in a rigorous academic style using mathematical notation and precise logical reasoning."
}
]
},
"generationConfig": {
"thinkingConfig": {
"thinkingBudget": 1024,
"includeThoughts": true
}
}
}
""";
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.6-flash:streamGenerateContent"
jsonRequestBody := `
{
"contents": [
{
"parts": [
{
"text": "Analyze the correctness of the following algorithm: for an undirected graph G=(V,E), use DFS to determine whether a cycle exists; give a rigorous reasoning process."
}
],
"role": "user"
}
],
"systemInstruction": {
"parts": [
{
"text": "You are a computer science professor; please answer in a rigorous academic style using mathematical notation and precise logical reasoning."
}
]
},
"generationConfig": {
"thinkingConfig": {
"thinkingBudget": 1024,
"includeThoughts": true
}
}
}
`
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 |
|
usageMetadata object |
|
promptTokenCount integer |
输入 token 数 |
candidatesTokenCount integer |
输出 token 数 |
totalTokenCount integer |
总 token 数 |
modelVersion string |
模型版本号 |