gemini-3.5-flash

最后更新:2026-11-14

POSThttps://www.sagelib.com/gemini/v1beta/models/{model}:streamGenerateContent

gemini-3.5-flash 模型的聊天生成接口,Gemini直连,支持多轮上下文、流式输出、工具调用、结构化输出等。

接口鉴权方式请参考:API接入与鉴权

请求参数

请求头

参数名称 描述
*Content-Type string 可选值:application/json
application/json
*x-goog-api-key string 鉴权令牌,格式为 ${AIGATEWAY_TOKEN}

Body 参数

参数名称 描述
*contents array 可选值:List of Content objects
对话内容,每项含 role(user/model)和 parts[{text}]。多轮对话需将历史拼接在数组中
systemInstruction object 系统指令对象,子字段 parts[{text}]
safetySettings array 安全过滤设置,每项含 category 和 threshold
toolConfig object 工具配置,子字段 functionCallingConfig: {mode, allowedFunctionNames} 和 retrievalConfig
tools array 工具定义列表,支持 functionDeclarations(函数声明)和 codeExecution(代码执行)
generationConfig object 生成配置对象,包含以下子参数
generationConfig.maxOutputTokens integer 可选值:1 ~ 65536
最大输出 token 数,上限 65536
generationConfig.stopSequences array 停止序列列表
generationConfig.seed integer 随机种子,用于确定性输出
generationConfig.responseMimeType string 默认值:text/plain
可选值:application
输出 MIME 类型
generationConfig.responseSchema object 结构化输出的 JSON Schema(需配合 responseMimeType: application/json)
generationConfig.responseJsonSchema object 响应 JSON Schema(与 responseSchema 二选一)
generationConfig.presencePenalty float 可选值:-2 ~ 2
存在惩罚
generationConfig.frequencyPenalty float 可选值:-2 ~ 2
频率惩罚
generationConfig.thinkingConfig object 思考配置;子字段 thinkingLevel(minimal/low/medium/high)和 includeThoughts(bool)
generationConfig.responseModalities array 可选值:["TEXT"]
响应模态列表,仅支持 TEXT
generationConfig.cachedContent string 缓存内容引用,格式 cachedContents/${id}
generationConfig.labels object 请求标签(key-value 对象),用于计费/监控/权限
generationConfig.automaticFunctionCalling object 自动函数调用;子字段 disable(bool)、maximumRemoteCallCount(int)
generationConfig.enableEnhancedCivicAnswers boolean 可选值:true、false
增强公民问题回答
generationConfig.serviceTier string 服务等级
generationConfig.modelArmorConfig object 模型安全防护配置
generationConfig.mediaResolution object 媒体分辨率控制
generationConfig.routingConfig object 路由配置;子字段 modelRoutingPreference

请求示例

curl -v 'https://www.sagelib.com/gemini/v1beta/models/gemini-3.5-flash:streamGenerateContent' \
  -H "x-goog-api-key: ***" \
  -H "Content-Type: application/json" \
  -d '{
    "contents": [
      {
        "parts": [
          {
            "text": "How does AI work?"
          }
        ],
        "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.5-flash:streamGenerateContent"

headers = {
    "x-goog-api-key": api_key,
    "Content-Type": "application/json",
}

data = {
    "contents": [
        {
            "parts": [
                {
                    "text": "How does AI work?"
                }
            ],
            "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.5-flash:streamGenerateContent";

        String jsonRequestBody = """
            {
                "contents": [
                    {
                        "parts": [
                            {
                                "text": "How does AI work?"
                            }
                        ],
                        "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.5-flash:streamGenerateContent"

    jsonRequestBody := `
            {
                "contents": [
                    {
                        "parts": [
                            {
                                "text": "How does AI work?"
                            }
                        ],
                        "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.5-flash:streamGenerateContent' \
  -H "x-goog-api-key: ***" \
  -H "Content-Type: application/json" \
  -d '{
    "systemInstruction": {
      "parts": [
        {
          "text": "You are a cat. Your name is Neko."
        }
      ]
    },
    "contents": [
      {
        "role": "user",
        "parts": [
          {
            "text": "Hello there"
          }
        ]
      }
    ]
  }'
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.5-flash:streamGenerateContent"

headers = {
    "x-goog-api-key": api_key,
    "Content-Type": "application/json",
}

data = {
    "systemInstruction": {
        "parts": [
            {
                "text": "You are a cat. Your name is Neko."
            }
        ]
    },
    "contents": [
        {
            "role": "user",
            "parts": [
                {
                    "text": "Hello there"
                }
            ]
        }
    ]
}

# 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.5-flash:streamGenerateContent";

        String jsonRequestBody = """
            {
                "systemInstruction": {
                    "parts": [
                        {
                            "text": "You are a cat. Your name is Neko."
                        }
                    ]
                },
                "contents": [
                    {
                        "role": "user",
                        "parts": [
                            {
                                "text": "Hello there"
                            }
                        ]
                    }
                ]
            }
            """;

        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.5-flash:streamGenerateContent"

    jsonRequestBody := `
            {
                "systemInstruction": {
                    "parts": [
                        {
                            "text": "You are a cat. Your name is Neko."
                        }
                    ]
                },
                "contents": [
                    {
                        "role": "user",
                        "parts": [
                            {
                                "text": "Hello there"
                            }
                        ]
                    }
                ]
            }
`

    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.5-flash:streamGenerateContent' \
  -H "x-goog-api-key: ***" \
  -H "Content-Type: application/json" \
  -d '{
    "contents": [
      {
        "parts": [
          {
            "text": "List 3 popular programming languages with their main use cases"
          }
        ],
        "role": "user"
      }
    ],
    "generationConfig": {
      "responseMimeType": "application/json",
      "responseSchema": {
        "type": "object",
        "properties": {
          "languages": {
            "type": "array",
            "items": {
              "type": "object",
              "properties": {
                "name": {
                  "type": "string"
                },
                "useCase": {
                  "type": "string"
                }
              },
              "required": [
                "name",
                "useCase"
              ]
            }
          }
        },
        "required": [
          "languages"
        ]
      },
      "thinkingConfig": {
        "thinkingLevel": "low"
      }
    }
  }'
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.5-flash:streamGenerateContent"

headers = {
    "x-goog-api-key": api_key,
    "Content-Type": "application/json",
}

data = {
    "contents": [
        {
            "parts": [
                {
                    "text": "List 3 popular programming languages with their main use cases"
                }
            ],
            "role": "user"
        }
    ],
    "generationConfig": {
        "responseMimeType": "application/json",
        "responseSchema": {
            "type": "object",
            "properties": {
                "languages": {
                    "type": "array",
                    "items": {
                        "type": "object",
                        "properties": {
                            "name": {
                                "type": "string"
                            },
                            "useCase": {
                                "type": "string"
                            }
                        },
                        "required": [
                            "name",
                            "useCase"
                        ]
                    }
                }
            },
            "required": [
                "languages"
            ]
        },
        "thinkingConfig": {
            "thinkingLevel": "low"
        }
    }
}

# 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.5-flash:streamGenerateContent";

        String jsonRequestBody = """
            {
                "contents": [
                    {
                        "parts": [
                            {
                                "text": "List 3 popular programming languages with their main use cases"
                            }
                        ],
                        "role": "user"
                    }
                ],
                "generationConfig": {
                    "responseMimeType": "application/json",
                    "responseSchema": {
                        "type": "object",
                        "properties": {
                            "languages": {
                                "type": "array",
                                "items": {
                                    "type": "object",
                                    "properties": {
                                        "name": {
                                            "type": "string"
                                        },
                                        "useCase": {
                                            "type": "string"
                                        }
                                    },
                                    "required": [
                                        "name",
                                        "useCase"
                                    ]
                                }
                            }
                        },
                        "required": [
                            "languages"
                        ]
                    },
                    "thinkingConfig": {
                        "thinkingLevel": "low"
                    }
                }
            }
            """;

        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.5-flash:streamGenerateContent"

    jsonRequestBody := `
            {
                "contents": [
                    {
                        "parts": [
                            {
                                "text": "List 3 popular programming languages with their main use cases"
                            }
                        ],
                        "role": "user"
                    }
                ],
                "generationConfig": {
                    "responseMimeType": "application/json",
                    "responseSchema": {
                        "type": "object",
                        "properties": {
                            "languages": {
                                "type": "array",
                                "items": {
                                    "type": "object",
                                    "properties": {
                                        "name": {
                                            "type": "string"
                                        },
                                        "useCase": {
                                            "type": "string"
                                        }
                                    },
                                    "required": [
                                        "name",
                                        "useCase"
                                    ]
                                }
                            }
                        },
                        "required": [
                            "languages"
                        ]
                    },
                    "thinkingConfig": {
                        "thinkingLevel": "low"
                    }
                }
            }
`

    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 创建时间(ISO 8601)
modelVersion string 实际模型版本号
responseId string 响应唯一标识
usageMetadata object
    promptTokenCount integer 输入 token 数
    totalTokenCount integer 总 token 数
    promptTokensDetails array 输入 token 明细(按模态拆分)
    trafficType string 流量类型,如 ON_DEMAND