> ## Documentation Index
> Fetch the complete documentation index at: https://docs.xhuoapi.ai/llms.txt
> Use this file to discover all available pages before exploring further.

# Gemini Generate Content API 使用说明

> Gemini AI 集成指南 - XHuoAPI

Google Gemini 是一个非常强大的 AI 对话系统，通过输入提示就能在几秒内生成流畅自然的回复。本文档主要描述 Gemini Generate Content API 的使用方法，这是 Google 官方原生 API 格式，支持 `generateContent` 和 `streamGenerateContent` 两个端点。

## 与 Chat Completions API 的区别

Gemini Generate Content API 使用 Google 官方原生请求格式（`contents` 字段），而不是 OpenAI 兼容格式（`messages` 字段）。如果你已经使用 Google Gemini SDK 或熟悉官方 API 格式，可以直接使用此 API 而无需修改请求格式。

## 申请流程

使用 Gemini Generate Content API 前，请先访问 [Gemini Generate Content API](https://api.xhuoapi.ai/documents/gemini-generate-content-api) 页面，点击 "获取" 按钮来获得请求所需的凭证。

如果尚未登录或注册，会自动跳转到登录页面。首次申请会有免费额度。

## 基本用法

### Non-Streaming（非流式）

发送 POST 请求到 `/v1beta/models/{model}:generateContent`：

```bash theme={null}
curl -X POST "https://api.xhuoapi.ai/v1/v1beta/models/gemini-2.5-flash:generateContent" \
  -H "Authorization: Bearer your_token_here" \
  -H "Content-Type: application/json" \
  -d '{
    "contents": [
      {
        "role": "user",
        "parts": [
          {
            "text": "你好，请介绍一下你自己"
          }
        ]
      }
    ]
  }'
```

返回结果示例：

```json theme={null}
{
  "candidates": [
    {
      "content": {
        "parts": [
          {
            "text": "你好！我是 Gemini，是由 Google 开发的大型语言模型..."
          }
        ],
        "role": "model"
      },
      "finishReason": "STOP",
      "index": 0
    }
  ],
  "usageMetadata": {
    "promptTokenCount": 10,
    "candidatesTokenCount": 150,
    "totalTokenCount": 160
  },
  "modelVersion": "gemini-2.5-flash"
}
```

### Streaming（流式）

发送 POST 请求到 `/v1beta/models/{model}:streamGenerateContent?alt=sse`：

```bash theme={null}
curl -X POST "https://api.xhuoapi.ai/v1/v1beta/models/gemini-2.5-flash:streamGenerateContent?alt=sse" \
  -H "Authorization: Bearer your_token_here" \
  -H "Content-Type: application/json" \
  -d '{
    "contents": [
      {
        "role": "user",
        "parts": [
          {
            "text": "写一首关于春天的诗"
          }
        ]
      }
    ]
  }'
```

流式返回会以 SSE（Server-Sent Events）格式逐步返回内容。

## 支持的模型

| 模型名称                     | 说明                |
| ------------------------ | ----------------- |
| `gemini-2.5-flash`       | 性价比优秀，适合高数据量低延迟任务 |
| `gemini-2.5-pro`         | 最先进的模型，复杂任务深度推理   |
| `gemini-2.5-flash-lite`  | 最快最经济的多模态模型       |
| `gemini-3-flash-preview` | 前沿级性能，成本更低        |
| `gemini-3.1-pro`         | 先进智能，强大代理和编码能力    |
| `gemini-2.0-flash`       | 第二代主力模型           |

## 高级功能

### 系统指令

```json theme={null}
{
  "contents": [
    {
      "role": "user",
      "parts": [{"text": "你好"}]
    }
  ],
  "systemInstruction": {
    "parts": [{"text": "你是一个专业的诗人，所有回复都用诗歌形式。"}]
  }
}
```

### 生成配置

```json theme={null}
{
  "contents": [
    {
      "role": "user",
      "parts": [{"text": "讲一个故事"}]
    }
  ],
  "generationConfig": {
    "temperature": 0.7,
    "maxOutputTokens": 1024,
    "topP": 0.9,
    "topK": 40
  }
}
```

### JSON 模式

```json theme={null}
{
  "contents": [
    {
      "role": "user",
      "parts": [{"text": "列出三个中国城市及其人口"}]
    }
  ],
  "generationConfig": {
    "responseMimeType": "application/json",
    "responseSchema": {
      "type": "array",
      "items": {
        "type": "object",
        "properties": {
          "city": {"type": "string"},
          "population": {"type": "integer"}
        }
      }
    }
  }
}
```

### 思考模式（Thinking）

支持思考功能的模型（如 gemini-2.5-flash、gemini-2.5-pro）可以启用思考模式：

```json theme={null}
{
  "contents": [
    {
      "role": "user",
      "parts": [{"text": "解释量子纠缠"}]
    }
  ],
  "generationConfig": {
    "thinkingConfig": {
      "includeThoughts": true,
      "thinkingBudget": 2048
    }
  }
}
```

### 函数调用

```json theme={null}
{
  "contents": [
    {
      "role": "user",
      "parts": [{"text": "北京现在的天气怎么样？"}]
    }
  ],
  "tools": [
    {
      "functionDeclarations": [
        {
          "name": "get_weather",
          "description": "获取指定城市的天气信息",
          "parameters": {
            "type": "object",
            "properties": {
              "city": {
                "type": "string",
                "description": "城市名称"
              }
            },
            "required": ["city"]
          }
        }
      ]
    }
  ]
}
```

### 多轮对话

```json theme={null}
{
  "contents": [
    {
      "role": "user",
      "parts": [{"text": "你好，我叫小明"}]
    },
    {
      "role": "model",
      "parts": [{"text": "你好小明！很高兴认识你。"}]
    },
    {
      "role": "user",
      "parts": [{"text": "我叫什么名字？"}]
    }
  ]
}
```

### 图片理解

```json theme={null}
{
  "contents": [
    {
      "role": "user",
      "parts": [
        {"text": "描述这张图片"},
        {
          "inlineData": {
            "mimeType": "image/jpeg",
            "data": "base64_encoded_image_data..."
          }
        }
      ]
    }
  ]
}
```

## 安全设置

可通过 `safetySettings` 控制内容过滤：

```json theme={null}
{
  "contents": [...],
  "safetySettings": [
    {
      "category": "HARM_CATEGORY_HARASSMENT",
      "threshold": "BLOCK_ONLY_HIGH"
    }
  ]
}
```

## 错误处理

| HTTP 状态码 | 含义             |
| -------- | -------------- |
| 400      | 请求参数无效         |
| 401      | 认证失败，请检查 Token |
| 403      | 内容被安全过滤器拦截     |
| 429      | 请求过于频繁         |
| 500      | 服务器内部错误        |
