gemini-nano-banana-2.1

最后更新:2026-11-14

POSThttps://www.sagelib.com/chat/completions

gemini-nano-banana-2.1 模型的聊天生成接口,OpenAI兼容,支持多轮上下文、流式输出、文生图与多模态输入,输出为文本与内联图片组成的多模态结果。

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

请求参数

请求头

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

Body 参数

参数名称 描述
*model string 默认值:gemini-nano-banana-2.1
可选值:gemini-nano-banana-2.1
模型名,指定要调用的模型
*messages array 可选值:role:system / user / assistant;content 为纯字符串或多模态内容块数组
对话消息数组,role 支持 system / user / assistant;content 可为纯字符串或多模态块数组(text 块 / image_url 块)
stream boolean 默认值:false
可选值:true / false
是否以 SSE 流式返回响应
max_tokens integer 可选值:1 - 32768
最大输出 token 数
max_completion_tokens integer 可选值:1 - 32768
最大输出 token 数(与 max_tokens 同义,同时传入时优先于 max_tokens)
temperature float 可选值:0.0 - 2.0
采样温度,值越大输出越随机
top_p float 可选值:0.0 - 1.0
核采样阈值,控制候选词累积概率
stop array 可选值:字符串数组
停止序列,命中后停止生成
modalities array 可选值:["text", "image"]
输出模态,生成图像时须包含 image
eca_image_config object 可选值:aspect_ratio:1:1 / 1:4 / 1:8 / 2:3 / 3:2 / 3:4 / 4:1 / 4:3 / 4:5 / 5:4 / 8:1 / 9:16 / 16:9 / 21:9;image_size:1K(默认)/ 2K / 4K
图像生成配置(平台扩展字段),映射至 Gemini generationConfig.imageConfig
eca_thinking_config object 可选值:budget_tokens:0 / 128 / 1024 / 8192 / 24576(推荐档位)
思考配置(平台扩展字段),映射至 Gemini generationConfig.thinkingConfig
reasoning_effort string 默认值:medium
可选值:minimal、medium、high
推理强度,映射至 Gemini thinking 档位

请求示例

curl -v 'https://www.sagelib.com/chat/completions' \
  -H "Authorization: Bearer ***" \
  -H "Content-Type: application/json" \
  -d '{
    "model": "gemini-nano-banana-2.1",
    "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-nano-banana-2.1",
    "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-nano-banana-2.1",
              "messages": [
                {
                  "role": "user",
                  "content": "What model are you? Which company made you? When were you launched? Briefly describe your capability boundaries."
                }
              ]
            }
            """;

        HttpRequest request = HttpRequest.newBuilder()
                .uri(URI.create(url))
                .header("Authorization", "Bearer " + apiKey)
                .header("Content-Type", "application/json")
                .POST(HttpRequest.BodyPublishers.ofString(jsonRequestBody))
                .build();

        HttpClient client = HttpClient.newHttpClient();
        HttpResponse<String> response = client.send(request, HttpResponse.BodyHandlers.ofString());

        System.out.println("Status Code: " + response.statusCode());
        System.out.println(response.body());
    }
}
package main

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

func main() {
    baseUrl := "https://www.sagelib.com"
    apiKey := "***"
    url := "https://www.sagelib.com/chat/completions"

    jsonRequestBody := `
            {
              "model": "gemini-nano-banana-2.1",
              "messages": [
                {
                  "role": "user",
                  "content": "What model are you? Which company made you? When were you launched? Briefly describe your capability boundaries."
                }
              ]
            }
            `

    req, _ := http.NewRequest("POST", url, bytes.NewBufferString(jsonRequestBody))
    req.Header.Set("Authorization", "Bearer "+apiKey)
    req.Header.Set("Content-Type", "application/json")

    resp, err := http.DefaultClient.Do(req)
    if err != nil {
        panic(err)
    }
    defer resp.Body.Close()

    body, _ := io.ReadAll(resp.Body)
    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": [
      {
        "role": "user",
        "content": "What model are you? Which company made you? When were you launched? Briefly describe your capability boundaries."
      }
    ],
    "model": "gemini-nano-banana-2.1",
    "stream": 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 Bearer token

url = f"https://www.sagelib.com/chat/completions"

headers = {
    "Authorization": f"Bearer {api_key}",
    "Content-Type": "application/json",
}

data = {
    "messages": [
        {
            "role": "user",
            "content": "What model are you? Which company made you? When were you launched? Briefly describe your capability boundaries."
        }
    ],
    "model": "gemini-nano-banana-2.1",
    "stream": 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/chat/completions";

        String jsonRequestBody = """
            {
              "messages": [
                {
                  "role": "user",
                  "content": "What model are you? Which company made you? When were you launched? Briefly describe your capability boundaries."
                }
              ],
              "model": "gemini-nano-banana-2.1",
              "stream": true
            }
            """;

        HttpRequest request = HttpRequest.newBuilder()
                .uri(URI.create(url))
                .header("Authorization", "Bearer " + apiKey)
                .header("Content-Type", "application/json")
                .POST(HttpRequest.BodyPublishers.ofString(jsonRequestBody))
                .build();

        HttpClient client = HttpClient.newHttpClient();
        HttpResponse<String> response = client.send(request, HttpResponse.BodyHandlers.ofString());

        System.out.println("Status Code: " + response.statusCode());
        System.out.println(response.body());
    }
}
package main

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

func main() {
    baseUrl := "https://www.sagelib.com"
    apiKey := "***"
    url := "https://www.sagelib.com/chat/completions"

    jsonRequestBody := `
            {
              "messages": [
                {
                  "role": "user",
                  "content": "What model are you? Which company made you? When were you launched? Briefly describe your capability boundaries."
                }
              ],
              "model": "gemini-nano-banana-2.1",
              "stream": true
            }
            `

    req, _ := http.NewRequest("POST", url, bytes.NewBufferString(jsonRequestBody))
    req.Header.Set("Authorization", "Bearer "+apiKey)
    req.Header.Set("Content-Type", "application/json")

    resp, err := http.DefaultClient.Do(req)
    if err != nil {
        panic(err)
    }
    defer resp.Body.Close()

    body, _ := io.ReadAll(resp.Body)
    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-nano-banana-2.1",
    "messages": [
      {
        "role": "user",
        "content": "Generate an image: an orange tabby cat sitting on a windowsill, gazing at the city skyline in the sunset glow, watercolor style, warm tones, delicate and atmospheric."
      }
    ],
    "eca_image_config": {
      "image_size": "2K"
    }
  }'
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-nano-banana-2.1",
    "messages": [
        {
            "role": "user",
            "content": "Generate an image: an orange tabby cat sitting on a windowsill, gazing at the city skyline in the sunset glow, watercolor style, warm tones, delicate and atmospheric."
        }
    ],
    "eca_image_config": {
        "image_size": "2K"
    }
}

# 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-nano-banana-2.1",
              "messages": [
                {
                  "role": "user",
                  "content": "Generate an image: an orange tabby cat sitting on a windowsill, gazing at the city skyline in the sunset glow, watercolor style, warm tones, delicate and atmospheric."
                }
              ],
              "eca_image_config": {
                "image_size": "2K"
              }
            }
            """;

        HttpRequest request = HttpRequest.newBuilder()
                .uri(URI.create(url))
                .header("Authorization", "Bearer " + apiKey)
                .header("Content-Type", "application/json")
                .POST(HttpRequest.BodyPublishers.ofString(jsonRequestBody))
                .build();

        HttpClient client = HttpClient.newHttpClient();
        HttpResponse<String> response = client.send(request, HttpResponse.BodyHandlers.ofString());

        System.out.println("Status Code: " + response.statusCode());
        System.out.println(response.body());
    }
}
package main

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

func main() {
    baseUrl := "https://www.sagelib.com"
    apiKey := "***"
    url := "https://www.sagelib.com/chat/completions"

    jsonRequestBody := `
            {
              "model": "gemini-nano-banana-2.1",
              "messages": [
                {
                  "role": "user",
                  "content": "Generate an image: an orange tabby cat sitting on a windowsill, gazing at the city skyline in the sunset glow, watercolor style, warm tones, delicate and atmospheric."
                }
              ],
              "eca_image_config": {
                "image_size": "2K"
              }
            }
            `

    req, _ := http.NewRequest("POST", url, bytes.NewBufferString(jsonRequestBody))
    req.Header.Set("Authorization", "Bearer "+apiKey)
    req.Header.Set("Content-Type", "application/json")

    resp, err := http.DefaultClient.Do(req)
    if err != nil {
        panic(err)
    }
    defer resp.Body.Close()

    body, _ := io.ReadAll(resp.Body)
    fmt.Println("Status Code:", resp.StatusCode)
    fmt.Println(string(body))
}

响应参数

Body 参数

参数名称 描述
id string 本次响应唯一标识
model string 实际响应的模型名
object string 可选值:chat.completion
固定为 chat.completion
created integer 生成时间戳
choices array 候选结果数组
    choices[].index integer 候选序号
    choices[].message.role string 可选值:assistant
固定为 assistant
    choices[].message.content array 多模态 parts 数组,元素形如 {"type":"text","text":...} 或 {"type":"image_url","image_url":{"url":"data:image/png;base64,..."}}
    choices[].message.reasoning_content string 思考内容(本模型以「思考图」形式体现在多模态 parts 中)
    choices[].finish_reason string 可选值:stop
结束原因,正常为 stop
usage object token 用量统计
    usage.prompt_tokens integer 输入 token 数
    usage.completion_tokens integer 输出 token 数
    usage.total_tokens integer 总 token 数
    usage.completion_tokens_details.image_tokens integer 输出中图像占用的 token
    usage.completion_tokens_details.text_tokens integer 输出中文本占用的 token
service_tier string 服务层级
POSThttps://www.sagelib.com/gemini/v1beta/models/{model}:streamGenerateContent

gemini-nano-banana-2.1 模型的聊天生成接口,Gemini直连,支持多轮上下文、文生图与多模态输入,输出为文本与内联图片组成的多模态结果。

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

请求参数

请求头

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

Body 参数

参数名称 描述
*contents array 可选值:role:user / model;parts:text / inline_data / file_data
输入内容数组,承载用户消息与多模态素材。请求体字段名同为 contents,parts 支持 text / inline_data / file_data 三种内容块
model string 默认值:gemini-nano-banana-2.1
可选值:gemini-nano-banana-2.1
模型名。可省略(模型名由请求 URL 路径中的模型段承载),亦可在请求体中携带
system_instruction string 可选值:parts 数组
系统指令,约束生成风格与整体行为;请求体字段名原样保持 system_instruction(含 parts 结构)
safety_settings array 可选值:threshold:BLOCK_NONE / BLOCK_ONLY_HIGH / BLOCK_MEDIUM_AND_ABOVE / BLOCK_LOW_AND_ABOVE
安全过滤设置,按类别设定阈值;元素含 category(如 HARM_CATEGORY_HARASSMENT)与 threshold 配对
tools array 可选值:type:google_search / search_types:web_search / search_types:image_search
工具声明,本模型支持 Google 搜索接地(grounding),不支持函数调用(function calling);请求体字段名原样保持 tools
config.response_modalities array 可选值:TEXT / IMAGE
输出模态,控制模型返回的内容类型;映射到请求体 generationConfig.responseModalities(驼峰)
config.image_config object 可选值:aspect_ratio:1:1 / 1:4 / 1:8 / 2:3 / 3:2 / 3:4 / 4:1 / 4:3 / 4:5 / 5:4 / 8:1 / 9:16 / 16:9 / 21:9;image_size:1K(默认)/ 2K / 4K
图像生成配置(宽高比、分辨率档位);映射到请求体 generationConfig.imageConfig,子字段为 aspectRatio / imageSize
config.thinking_config object 可选值:thinking_level:minimal / medium(默认)/ high
思考配置;映射到请求体 generationConfig.thinkingConfig,子字段为 thinkingLevel / includeThoughts
config.temperature float 可选值:0.0 - 2.0
采样温度,值越大输出越随机;映射到请求体 generationConfig.temperature(同名)
config.top_p float 可选值:0.0 - 1.0
核采样阈值;映射到请求体 generationConfig.topP(驼峰)
config.top_k integer 可选值:≥ 1
Top-K 采样;映射到请求体 generationConfig.topK(驼峰)
config.candidate_count integer 可选值:≥ 1
返回候选数量;映射到请求体 generationConfig.candidateCount(驼峰)
config.max_output_tokens integer 可选值:1 - 32768
最大输出 token 数;映射到请求体 generationConfig.maxOutputTokens(驼峰)
config.seed integer 可选值:整数
随机种子,用于结果复现;映射到请求体 generationConfig.seed(同名)
config.stop_sequences array 可选值:字符串数组
停止序列,遇任一字符串即停止;映射到请求体 generationConfig.stopSequences(驼峰)

请求示例

curl -v 'https://www.sagelib.com/gemini/v1beta/models/gemini-nano-banana-2.1:streamGenerateContent' \
  -H "x-goog-api-key: ***" \
  -H "Content-Type: application/json" \
  -d '{
    "contents": [
      {
        "parts": [
          {
            "text": "Please read the following product requirements document, identify its core functional modules, explain the dependencies between the modules, and output a brief feature list:\n\nWe plan to build a team collaboration kanban system. Core features include task kanban, member management, milestone tracking, file attachments and message notifications. The kanban organizes task status by columns: To Do, In Progress, Done. Each task supports priority labels, due dates and assigned members. The system needs to support real-time multi-user editing and operation auditing. Please analyze based on the requirements above."
          }
        ],
        "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-nano-banana-2.1:streamGenerateContent"

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

data = {
    "contents": [
        {
            "parts": [
                {
                    "text": "Please read the following product requirements document, identify its core functional modules, explain the dependencies between the modules, and output a brief feature list:\n\nWe plan to build a team collaboration kanban system. Core features include task kanban, member management, milestone tracking, file attachments and message notifications. The kanban organizes task status by columns: To Do, In Progress, Done. Each task supports priority labels, due dates and assigned members. The system needs to support real-time multi-user editing and operation auditing. Please analyze based on the requirements above."
                }
            ],
            "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-nano-banana-2.1:streamGenerateContent";

        String jsonRequestBody = """
            {
              "contents": [
                {
                  "parts": [
                    {
                      "text": "Please read the following product requirements document, identify its core functional modules, explain the dependencies between the modules, and output a brief feature list:\n\nWe plan to build a team collaboration kanban system. Core features include task kanban, member management, milestone tracking, file attachments and message notifications. The kanban organizes task status by columns: To Do, In Progress, Done. Each task supports priority labels, due dates and assigned members. The system needs to support real-time multi-user editing and operation auditing. Please analyze based on the requirements above."
                    }
                  ],
                  "role": "user"
                }
              ]
            }
            """;

        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();

        HttpClient client = HttpClient.newHttpClient();
        HttpResponse<String> response = client.send(request, HttpResponse.BodyHandlers.ofString());

        System.out.println("Status Code: " + response.statusCode());
        System.out.println(response.body());
    }
}
package main

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

func main() {
    baseUrl := "https://www.sagelib.com"
    apiKey := "***"
    url := "https://www.sagelib.com/gemini/v1beta/models/gemini-nano-banana-2.1:streamGenerateContent"

    jsonRequestBody := `
            {
              "contents": [
                {
                  "parts": [
                    {
                      "text": "Please read the following product requirements document, identify its core functional modules, explain the dependencies between the modules, and output a brief feature list:\n\nWe plan to build a team collaboration kanban system. Core features include task kanban, member management, milestone tracking, file attachments and message notifications. The kanban organizes task status by columns: To Do, In Progress, Done. Each task supports priority labels, due dates and assigned members. The system needs to support real-time multi-user editing and operation auditing. Please analyze based on the requirements above."
                    }
                  ],
                  "role": "user"
                }
              ]
            }
            `

    req, _ := http.NewRequest("POST", url, bytes.NewBufferString(jsonRequestBody))
    req.Header.Set("x-goog-api-key", apiKey)
    req.Header.Set("Content-Type", "application/json")

    resp, err := http.DefaultClient.Do(req)
    if err != nil {
        panic(err)
    }
    defer resp.Body.Close()

    body, _ := io.ReadAll(resp.Body)
    fmt.Println("Status Code:", resp.StatusCode)
    fmt.Println(string(body))
}
curl -v 'https://www.sagelib.com/gemini/v1beta/models/gemini-nano-banana-2.1:streamGenerateContent' \
  -H "x-goog-api-key: ***" \
  -H "Content-Type: application/json" \
  -d '{
    "contents": [
      {
        "parts": [
          {
            "text": "What are the major AI news stories globally in the past week? Please search the latest information online and cite your sources."
          }
        ],
        "role": "user"
      }
    ],
    "tools": [
      {
        "google_search": {}
      }
    ]
  }'
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-nano-banana-2.1:streamGenerateContent"

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

data = {
    "contents": [
        {
            "parts": [
                {
                    "text": "What are the major AI news stories globally in the past week? Please search the latest information online and cite your sources."
                }
            ],
            "role": "user"
        }
    ],
    "tools": [
        {
            "google_search": {}
        }
    ]
}

# 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-nano-banana-2.1:streamGenerateContent";

        String jsonRequestBody = """
            {
              "contents": [
                {
                  "parts": [
                    {
                      "text": "What are the major AI news stories globally in the past week? Please search the latest information online and cite your sources."
                    }
                  ],
                  "role": "user"
                }
              ],
              "tools": [
                {
                  "google_search": {}
                }
              ]
            }
            """;

        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();

        HttpClient client = HttpClient.newHttpClient();
        HttpResponse<String> response = client.send(request, HttpResponse.BodyHandlers.ofString());

        System.out.println("Status Code: " + response.statusCode());
        System.out.println(response.body());
    }
}
package main

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

func main() {
    baseUrl := "https://www.sagelib.com"
    apiKey := "***"
    url := "https://www.sagelib.com/gemini/v1beta/models/gemini-nano-banana-2.1:streamGenerateContent"

    jsonRequestBody := `
            {
              "contents": [
                {
                  "parts": [
                    {
                      "text": "What are the major AI news stories globally in the past week? Please search the latest information online and cite your sources."
                    }
                  ],
                  "role": "user"
                }
              ],
              "tools": [
                {
                  "google_search": {}
                }
              ]
            }
            `

    req, _ := http.NewRequest("POST", url, bytes.NewBufferString(jsonRequestBody))
    req.Header.Set("x-goog-api-key", apiKey)
    req.Header.Set("Content-Type", "application/json")

    resp, err := http.DefaultClient.Do(req)
    if err != nil {
        panic(err)
    }
    defer resp.Body.Close()

    body, _ := io.ReadAll(resp.Body)
    fmt.Println("Status Code:", resp.StatusCode)
    fmt.Println(string(body))
}
curl -v 'https://www.sagelib.com/gemini/v1beta/models/gemini-nano-banana-2.1:streamGenerateContent' \
  -H "x-goog-api-key: ***" \
  -H "Content-Type: application/json" \
  -d '{
    "contents": [
      {
        "parts": [
          {
            "fileData": {
              "mimeType": "image/png",
              "fileUri": "${image_url}"
            }
          },
          {
            "text": "Please look at this image carefully and describe the main subject, scene and style details."
          }
        ],
        "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-nano-banana-2.1:streamGenerateContent"

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

data = {
    "contents": [
        {
            "parts": [
                {
                    "fileData": {
                        "mimeType": "image/png",
                        "fileUri": "${image_url}"
                    }
                },
                {
                    "text": "Please look at this image carefully and describe the main subject, scene and style details."
                }
            ],
            "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-nano-banana-2.1:streamGenerateContent";

        String jsonRequestBody = """
            {
              "contents": [
                {
                  "parts": [
                    {
                      "fileData": {
                        "mimeType": "image/png",
                        "fileUri": "${image_url}"
                      }
                    },
                    {
                      "text": "Please look at this image carefully and describe the main subject, scene and style details."
                    }
                  ],
                  "role": "user"
                }
              ]
            }
            """;

        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();

        HttpClient client = HttpClient.newHttpClient();
        HttpResponse<String> response = client.send(request, HttpResponse.BodyHandlers.ofString());

        System.out.println("Status Code: " + response.statusCode());
        System.out.println(response.body());
    }
}
package main

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

func main() {
    baseUrl := "https://www.sagelib.com"
    apiKey := "***"
    url := "https://www.sagelib.com/gemini/v1beta/models/gemini-nano-banana-2.1:streamGenerateContent"

    jsonRequestBody := `
            {
              "contents": [
                {
                  "parts": [
                    {
                      "fileData": {
                        "mimeType": "image/png",
                        "fileUri": "${image_url}"
                      }
                    },
                    {
                      "text": "Please look at this image carefully and describe the main subject, scene and style details."
                    }
                  ],
                  "role": "user"
                }
              ]
            }
            `

    req, _ := http.NewRequest("POST", url, bytes.NewBufferString(jsonRequestBody))
    req.Header.Set("x-goog-api-key", apiKey)
    req.Header.Set("Content-Type", "application/json")

    resp, err := http.DefaultClient.Do(req)
    if err != nil {
        panic(err)
    }
    defer resp.Body.Close()

    body, _ := io.ReadAll(resp.Body)
    fmt.Println("Status Code:", resp.StatusCode)
    fmt.Println(string(body))
}

响应参数

Body 参数

参数名称 描述
candidates array 候选结果数组
    candidates[].content.role string 可选值:model
固定为 model
    candidates[].content.parts array 混合数组:同时包含文本部分与 inlineData 部分,二者交错排列
        candidates[].content.parts[].text string 可读文本部分(通常附带 thoughtSignature 签名)
        candidates[].content.parts[].inlineData object 二进制数据部分:{ "mimeType": "image/png", "data": "" },可为生成图或思考图
        candidates[].content.parts[].thought boolean 为 true 表示该 inlineData 是思考中间图(不计费),该部分不含 text 键
    candidates[].finishReason string 可选值:STOP
生成终止原因,正常为 STOP
createTime string 响应创建时间(UTC)
modelVersion string 可选值:gemini-nano-banana-2.1
实际服务模型版本,如 gemini-nano-banana-2.1
responseId string 响应唯一标识
usageMetadata object token 用量元数据
    usageMetadata.promptTokenCount integer 输入 token 数
    usageMetadata.candidatesTokenCount integer 输出 token 数
    usageMetadata.totalTokenCount integer 总 token 数
    usageMetadata.candidatesTokensDetails array 输出按模态拆分(TEXT / IMAGE 各自 tokenCount)
    usageMetadata.promptTokensDetails array 输入按模态拆分(TEXT / IMAGE / VIDEO 各自 tokenCount)