Source: https://wiki.niceai.dev/guide/api/gemini

# Gemini 接口

调用 Gemini 原生接口时，请求 `POST https://api.niceai.dev/v1beta/models/<模型名>:generateContent`，用 `x-goog-api-key` 请求头传 NiceAI 密钥（分组选 **Gemini**）。使用 Google 官方 SDK 时，Base URL 只填 `https://api.niceai.dev`，SDK 会自己拼上 `/v1beta`。

## 请求示例

**-group**

```bash [curl]
curl "https://api.niceai.dev/v1beta/models/<模型名>:generateContent" \
  -H "x-goog-api-key: $NICEAI_API_KEY" \
  -H "Content-Type: application/json" \
  -d '{
    "contents": [{"role": "user", "parts": [{"text": "用一句话解释什么是 token"}]}]
  }'
```

```python [Python（google-genai）]
import os
from google import genai
from google.genai import types

client = genai.Client(
    api_key=os.environ["NICEAI_API_KEY"],
    http_options=types.HttpOptions(base_url="https://api.niceai.dev"),
)
resp = client.models.generate_content(model="<模型名>", contents="用一句话解释什么是 token")
print(resp.text)
```



## 流式输出

把路径里的 `generateContent` 换成 `streamGenerateContent`，并加上 `?alt=sse`，返回就会变成 SSE 事件流：

```bash
curl -N "https://api.niceai.dev/v1beta/models/<模型名>:streamGenerateContent?alt=sse" \
  -H "x-goog-api-key: $NICEAI_API_KEY" \
  -H "Content-Type: application/json" \
  -d '{"contents": [{"parts": [{"text": "写一首四行短诗"}]}]}'
```

## 请求体要点

| 字段 | 说明 |
| --- | --- |
| `contents` | 对话内容，每条包含 `role`（`user` / `model`）和 `parts` |
| `systemInstruction` | 系统提示词，格式为 `{"parts": [{"text": "..."}]}` |
| `generationConfig` | 生成参数，例如 `temperature`、`maxOutputTokens` |
| `tools` | 函数声明（`functionDeclarations`），需模型支持 |

## 地址写法对照

| 场景 | 填写 |
| --- | --- |
| 直接发 REST 请求 | `https://api.niceai.dev/v1beta/models/<模型名>:generateContent` |
| google-genai SDK | `base_url="https://api.niceai.dev"` |
| Gemini CLI | `GOOGLE_GEMINI_BASE_URL=https://api.niceai.dev`，见 [Gemini CLI 接入](https://wiki.niceai.dev/guide/clients/gemini-cli) |

## 常见问题

### 返回 404？

检查路径中是否带了 `/v1beta`，以及模型名后面的冒号和方法名（`:generateContent`）是否完整。

### 返回 401 或 403？

确认密钥分组为 Gemini，并通过 `x-goog-api-key` 请求头传递。

## 下一步

- [Gemini CLI 接入](https://wiki.niceai.dev/guide/clients/gemini-cli)
- [流式输出（SSE）](https://wiki.niceai.dev/guide/api/streaming)
