> For clean Markdown of any page, append .md to the page URL.
> For a complete documentation index, see https://docs.beatapi.io/llms.txt.
> For AI client integration (Claude Code, Cursor, etc.), connect to the MCP server at https://docs.beatapi.io/_mcp/server.

# Gemini 네이티브

POST https://direct.beatapi.io/v1beta/models/{model}:generateContent
Content-Type: application/json

Gemini generateContent 요청과 BeatAPI 키 하나로 Gemini 4 Argon, Gemini 4 Carbon, Gemini 3.8 Flash, Gemini 3.1 Pro를 호출합니다.- 현재 모든 Gemini 모델에 `POST /v1beta/models/{model}:generateContent`를, 스트리밍에는 `:streamGenerateContent?alt=sse`를 사용합니다.
- 텍스트·이미지 입력, 텍스트 출력, 스트리밍, 함수 호출, 사고.
- 키는 `x-goog-api-key` 헤더나 Bearer 토큰으로 보내세요.
- 모델은 본문이 아니라 URL에 지정합니다.텍스트 요청의 기본 URL로는 `https://direct.beatapi.io`를 사용하세요. Cloudflare의 100초 제한을 받지 않으므로 스트리밍하지 않는 긴 요청도 끊기지 않습니다. `https://api.beatapi.io`도 동작하며, 네트워크에서 `direct.beatapi.io`에 접근할 수 없을 때의 대안입니다. 키, 모델, 가격은 양쪽이 같습니다. 이미지와 영상 API는 `https://api.beatapi.io`만 사용합니다.POST/v1beta/models/{model}:generateContent실행해 보기API Explorer에서 이 엔드포인트를 엽니다. BeatAPI API 키를 입력하고 전송하세요. 실제 호출이며 본인 잔액에서 과금됩니다.## 모델URL의 `{model}` 자리에 다음 ID 중 하나를 넣으세요.| 모델 ID                    | 컨텍스트(토큰)  | 최대 출력(토큰) | 포지셔닝                                                                      | 입력, 1M 토큰당 USD | 출력, 1M 토큰당 USD |
| ------------------------ | --------- | --------- | ------------------------------------------------------------------------- | -------------- | -------------- |
| `gemini-4-argon`         | —         | 1,000,000 | 최대 1M 토큰까지 출력할 수 있는 Google의 Gemini 4 플래그십 모델.                             | \$1.00         | \$5.00         |
| `gemini-4-carbon`        | —         | 1,000,000 | 복잡한 디버깅, 과학적 분석, 에이전트를 위한 Gemini 4 추론 모델                                  | \$1.00         | \$5.00         |
| `gemini-3.8-flash`       | —         | —         | 장기 소프트웨어 엔지니어링, 자율 에이전트, 복잡한 엔터프라이즈 워크플로를 위해 설계된 Google의 가장 지능적인 Flash 모델 | \$0.375        | \$1.875        |
| `gemini-3.1-pro-preview` | 1,048,576 | 65,536    | 에이전트 코딩과 복잡한 문제 해결을 위한 추론 중심 Gemini 프리뷰                                   | \$1.00         | \$6.00         |- 가격은 할인이 적용된 기본 등급입니다. 롱 컨텍스트 등급, 캐시 입력 요금, 캐시 쓰기는 이 표에 없습니다. [가격표](https://beatapi.io/pricing)를 참고하세요.
- `—`는 카탈로그에서 해당 수치를 공개하지 않는다는 뜻입니다.이 계열의 이전 ID도 계속 동작하며 [레거시 모델](/text-api/legacy-models)에 나와 있습니다.## 빠른 시작키는 `BEATAPI_API_KEY`에 보관하고 브라우저 코드에는 절대 넣지 마세요. 모델 ID는 URL에 들어가므로 본문에는 `model` 필드가 없습니다. 아래는 요청 예시이며 실제로 기록된 모델 출력이 아닙니다.`candidates[0].content.parts[0].text`에서 답변을 읽은 다음 `candidates[0].finishReason`과 `usageMetadata`를 확인하세요. HTTP 200만으로는 답변이 작업 요구를 충족한다고 볼 수 없으니 애플리케이션에서 검증하세요. 텍스트 요청은 바로 반환되므로 `/v1/tasks`를 폴링하지 마세요.```bash title="cURL"
curl --request POST \
  --url https://direct.beatapi.io/v1beta/models/gemini-3.8-flash:generateContent \
  --header "x-goog-api-key: $BEATAPI_API_KEY" \
  --header 'Content-Type: application/json' \
  --data '{
  "contents": [
    {
      "role": "user",
      "parts": [
        {
          "text": "Design a resilient webhook retry strategy for a payments API."
        }
      ]
    }
  ]
}'
``````python title="Python"
import os
import requests

response = requests.post(
    "https://direct.beatapi.io/v1beta/models/gemini-3.8-flash:generateContent",
    headers={"x-goog-api-key": os.environ["BEATAPI_API_KEY"]},
    json={
      "contents": [
        {
          "role": "user",
          "parts": [
            {
              "text": "Design a resilient webhook retry strategy for a payments API."
            }
          ]
        }
      ]
    },
    timeout=120,
)
response.raise_for_status()
print(response.json()["candidates"][0]["content"]["parts"][0]["text"])
``````javascript title="JavaScript"
const response = await fetch("https://direct.beatapi.io/v1beta/models/gemini-3.8-flash:generateContent", {
  method: "POST",
  headers: {
    "x-goog-api-key": process.env.BEATAPI_API_KEY,
    "Content-Type": "application/json",
  },
  body: JSON.stringify({
    "contents": [
      {
        "role": "user",
        "parts": [
          {
            "text": "Design a resilient webhook retry strategy for a payments API."
          }
        ]
      }
    ]
  }),
});
if (!response.ok) throw new Error(await response.text());
const data = await response.json();
console.log(data.candidates[0].content.parts[0].text);
```## 엔드포인트와 인증`POST https://direct.beatapi.io/v1beta/models/{model}:generateContent`x-goog-api-key
string
필수`x-goog-api-key` 헤더에 넣는 BeatAPI 키입니다. `Authorization: Bearer <BEATAPI_API_KEY>`도 받습니다.스트리밍은 `POST /v1beta/models/{model}:streamGenerateContent?alt=sse`를 호출하세요. 키는 `x-goog-api-key` 헤더나 `Authorization: Bearer <key>`에 넣으며 둘 다 동작합니다.`:countTokens`는 사용할 수 없으며 `404`를 반환합니다.## 요청 파라미터아래는 효과가 있는 필드입니다. 다른 Gemini 필드(`generationConfig.thinkingConfig`, `generationConfig.responseMimeType`, `generationConfig.responseSchema`, `generationConfig.seed`, `safetySettings`, `toolConfig`, `cachedContent`)는 요청에서 받지만 효과가 없으니 의존하지 마세요.contents
object[]
필수대화 내용이며 오래된 턴부터 나열합니다. 각 항목에는 `role`(`user` 또는 `model`)와 `parts`가 있습니다. 파트는 `text`, `inlineData`(`mimeType`과 base64 `data`), `fileData`(`mimeType`과 `fileUri`), `functionCall` 또는 `functionResponse`입니다.- 현재 모든 Gemini 모델이 이미지 입력을 지원합니다. `inlineData`를 쓰거나 이미지 URL과 함께 `fileData`를 사용하세요. 다른 미디어는 사용하기 전에 파일 형식을 테스트하세요.
- `contents`가 비어 있거나 없으면 `400 bad_request`입니다.**예시**```json
[
  {
    "role": "user",
    "parts": [
      { "text": "What is in this image?" },
      { "inlineData": { "mimeType": "image/png", "data": "<base64>" } }
    ]
  }
]
```systemInstruction
object
선택시스템 프롬프트이며 `{ "parts": [{ "text": "..." }] }` 형식입니다. `text` 파트만 사용됩니다.**예시**```json
{
  "parts": [{ "text": "Answer in one short paragraph." }]
}
```generationConfig
object
선택생성 옵션입니다. 효과가 있는 하위 필드: `maxOutputTokens`, `temperature`, `topP`, `topK`, `stopSequences`, `candidateCount`.**예시**```json
{
  "temperature": 0.7,
  "topP": 0.95,
  "maxOutputTokens": 2048,
  "stopSequences": ["END"]
}
```generationConfig.maxOutputTokens
integer
선택생성 토큰의 상한이며, 사고 토큰을 포함합니다.- 허용되는 최댓값은 1,073,741,823이며, 그보다 크면 `400 bad_request`입니다. 위 표에 있는 모델의 최대 출력 이하로 설정하세요.
- Gemini 모델은 기본적으로 사고하며, 사고 토큰은 출력으로 과금되고 이 한도에 포함됩니다. 값이 작으면 사고에 모두 쓰여 `finishReason: "MAX_TOKENS"`와 함께 빈 답변이 나올 수 있습니다. 짧은 답변이라도 최소 1,000토큰을 잡으세요.
- `maxOutputTokens`는 요청에 필요한 잔액을 추정하는 데도 쓰입니다. 실제 출력이 작더라도 값이 너무 크면 `402 insufficient_credits`로 거부될 수 있습니다. 필요한 만큼만 설정하세요.generationConfig.temperature
number
선택샘플링 온도입니다.generationConfig.topP
number
선택누클리어스 샘플링입니다. `0` 값은 무시됩니다.generationConfig.topK
integer
선택Top-K 샘플링입니다. `0` 값은 무시됩니다.generationConfig.stopSequences
string[]
선택생성을 멈추는 문자열입니다. 최대 4개까지 사용됩니다.generationConfig.candidateCount
integer
선택반환할 후보 수입니다. 둘 이상이 필요하지 않다면 설정하지 마세요.tools
object[]
선택모델이 호출할 수 있는 함수 선언이며 `[{ "functionDeclarations": [...] }]` 형식입니다. 각 선언에는 `name`, `description`, `parameters`(JSON Schema)가 있습니다. 호출은 `functionCall` 파트로 반환되며, 결과는 다음 `user` 턴의 `functionResponse` 파트로 반환하세요.- `functionDeclarations`만 사용됩니다. `googleSearch`, `codeExecution` 같은 내장 도구는 무시됩니다.**예시**```json
[
  {
    "functionDeclarations": [
      {
        "name": "get_weather",
        "description": "Get the current weather for a city.",
        "parameters": {
          "type": "object",
          "properties": { "city": { "type": "string" } },
          "required": ["city"]
        }
      }
    ]
  }
]
```## 응답스트리밍하지 않는 호출은 JSON 객체 하나를 반환합니다. 아래는 축약한 예시입니다.```json
{
  "candidates": [
    {
      "content": {
        "role": "model",
        "parts": [
          {
            "text": "Retry with exponential backoff and jitter, and make every handler idempotent."
          }
        ]
      },
      "finishReason": "STOP",
      "index": 0
    }
  ],
  "usageMetadata": {
    "promptTokenCount": 19,
    "candidatesTokenCount": 16,
    "totalTokenCount": 120,
    "thoughtsTokenCount": 85
  }
}
```### 응답 필드| 필드                                          | 타입        | 설명                                                                                    |
| ------------------------------------------- | --------- | ------------------------------------------------------------------------------------- |
| `candidates[].content.parts[].text`         | `string`  | 답변 텍스트입니다.                                                                            |
| `candidates[].content.parts[].functionCall` | `object`  | 도구 호출이며 `name`과 `args`가 있습니다.                                                         |
| `candidates[].finishReason`                 | `string`  | 완전한 답변이나 도구 호출이면 `STOP`, `maxOutputTokens`에 도달하면 `MAX_TOKENS`, 답변이 필터링되면 `SAFETY`입니다. |
| `usageMetadata.promptTokenCount`            | `integer` | 입력 토큰입니다.                                                                             |
| `usageMetadata.candidatesTokenCount`        | `integer` | 보이는 답변의 출력 토큰입니다.                                                                     |
| `usageMetadata.thoughtsTokenCount`          | `integer` | 사고 토큰입니다. 출력으로 과금됩니다. 사고 텍스트 자체는 반환되지 않습니다.                                           |
| `usageMetadata.totalTokenCount`             | `integer` | 호출의 전체 토큰입니다.                                                                         |## 스트리밍`:streamGenerateContent?alt=sse`를 호출하세요. 모든 이벤트는 `candidates` 객체를 담은 `data: {...}` 한 줄이며, 스트리밍하지 않는 답변과 형식이 같습니다.- 마지막 이벤트에는 `finishReason`이 있습니다(예: `"STOP"`).
- 응답은 `text/event-stream`입니다. 모델 호출 전에 발생한 실패는 스트림 이벤트가 아니라 HTTP 상태와 함께 일반 JSON 오류로 반환됩니다.
- 명시적인 시간 제한을 설정하고, 스트리밍 응답은 안전하게 다시 연결하세요.```text
data: {"candidates":[{"content":{"role":"model","parts":[{"text":"Retry"}]},"index":0}]}

data: {"candidates":[{"content":{"role":"model","parts":[{"text":" with backoff"}]},"finishReason":"STOP","index":0}],"usageMetadata":{"promptTokenCount":19,"candidatesTokenCount":16,"totalTokenCount":120,"thoughtsTokenCount":85}}
```## 오류| 오류 또는 증상                                         | 원인                                                       | 해결 방법                                                         |
| ------------------------------------------------ | -------------------------------------------------------- | ------------------------------------------------------------- |
| `400`: `contents`는 필수입니다                         | `contents`가 비어 있거나 없습니다.                                 | `contents`에 턴을 하나 이상 보내세요.                                    |
| `400`: `maxOutputTokens`가 잘못되었습니다                | `generationConfig.maxOutputTokens`가 1,073,741,823보다 큽니다. | 필요한 만큼으로 낮추세요.                                                |
| `402 insufficient_credits`                       | 잔액이 요청 가격보다 적습니다. 대개 `maxOutputTokens`가 너무 크기 때문입니다.     | 충전하거나 `maxOutputTokens`를 낮추세요.                                |
| `403 forbidden`                                  | 계정이 무료 크레딧 상태인데 모델이 무료 목록에 없거나, 모델이 키의 그룹 밖에 있습니다.       | 충전하거나, 무료 모델을 쓰거나, 그룹에서 해당 모델에 접근할 수 있는 키를 사용하세요.             |
| `404 not_found`                                  | 알 수 없는 모델 ID이거나, 이 키에서 사용할 수 없거나, `:countTokens` 액션입니다.  | `GET /v1/models`로 사용 가능한 모델을 확인하세요.                           |
| `429 rate_limit_exceeded`                        | 계정 또는 무료 모델 한도에 도달했습니다.                                  | `Retry-After`만큼 기다린 뒤 재시도하세요.                                 |
| `finishReason: "MAX_TOKENS"`와 함께 `text` 없이 `200` | 답변을 쓰기 전에 사고가 `maxOutputTokens`를 모두 써 버렸습니다.             | `generationConfig.maxOutputTokens`를 높이세요. 짧은 답변도 최소 1,000입니다. |### HTTP 오류 요약Gemini 네이티브 엔드포인트의 오류 형식은 `{"error": {"message", "type": "beatapi_error", "code"}}` 하나입니다. 코드는 `error.code`에 있고, 요청 id는 `message`로 끝나며, `retryable` 필드는 없습니다. [오류](/errors#text-endpoints)를 참고하세요.| HTTP 상태 | 코드                                                         | 조치                                                             |
| ------- | ---------------------------------------------------------- | -------------------------------------------------------------- |
| 400     | `bad_request`, `content_policy_violation`                  | 요청이나 입력을 수정하세요. 그대로 다시 보내지 마세요.                                |
| 401     | `missing_api_key`, `invalid_api_key`                       | 키를 확인하세요. 재시도하지 마세요.                                           |
| 402     | `insufficient_credits`                                     | 충전하거나 키 한도를 높이세요. `max_tokens`가 너무 크면 발생할 수 있습니다.              |
| 403     | `forbidden`                                                | 모델이 키의 그룹이나 IP 허용 목록 밖에 있거나, 무료 크레딧으로 이 모델을 호출할 수 없습니다.        |
| 404     | `not_found`                                                | 알 수 없는 모델입니다. `GET /v1/models`로 사용 가능한 모델 목록을 확인하세요.           |
| 429     | `rate_limit_exceeded`                                      | `Retry-After` 또는 `retry_after_seconds`만큼 기다린 뒤 백오프를 두고 재시도하세요. |
| 500     | `internal_error`, `temporary_error`                        | 백오프를 적용해 한두 번 재시도하세요.                                          |
| 503     | `model_unavailable`, `upstream_timeout`, `temporary_error` | 백오프를 적용해 재시도하거나 다른 모델을 사용하세요.                                  |전체 코드 표와 재시도 정책: [오류](/errors#text-endpoints).## 참고- Gemini 모델은 Chat Completions, Responses, Anthropic Messages에서도 응답합니다. 다른 Gemini 페이지를 참고하세요.
- 사고 토큰은 출력 토큰으로 과금됩니다. 답변만이 아니라 사고와 답변을 합친 만큼 출력 한도를 잡으세요.
- API 키는 신뢰할 수 있는 서버에 두고, 응답의 요청 ID를 기록하며, `429`, `500`, `503`만 재시도하세요.

Reference: https://docs.beatapi.io/api-reference/text-api/gemini-native

## Authentication

- `Authorization` header (bearer token, required) — API 키를 `Authorization: Bearer <BEATAPI_API_KEY>`로 보내세요.

## Servers

- `https://direct.beatapi.io` (Direct, default)
- `https://api.beatapi.io` (API)

## Request

### Path parameters

- `model` (enum, required)
  - Allowed values: `gemini-4-argon`, `gemini-4-carbon`, `gemini-3.8-flash`, `gemini-3.1-pro-preview`

### Body (application/json)

This endpoint expects an object.

- `contents` (list of V1BetaModelsModelGenerateContentPostRequestBodyContentApplicationJsonSchemaContentsItems, required) — 대화 내용이며 오래된 턴부터 나열합니다. 각 항목에는 `role`(`user` 또는 `model`)와 `parts`가 있습니다. 파트는 `text`, `inlineData`(`mimeType`과 base64 `data`), `fileData`(`mimeType`과 `fileUri`), `functionCall` 또는 `functionResponse`입니다. 현재 모든 Gemini 모델이 이미지 입력을 지원합니다. `inlineData`를 쓰거나 이미지 URL과 함께 `fileData`를 사용하세요. 다른 미디어는 사용하기 전에 파일 형식을 테스트하세요. `contents`가 비어 있거나 없으면 `400 bad_request`입니다.
- `systemInstruction` (V1BetaModelsModelGenerateContentPostRequestBodyContentApplicationJsonSchemaSystemInstruction, optional) — 시스템 프롬프트이며 `{ "parts": [{ "text": "..." }] }` 형식입니다. `text` 파트만 사용됩니다.
- `generationConfig` (V1BetaModelsModelGenerateContentPostRequestBodyContentApplicationJsonSchemaGenerationConfig, optional) — 생성 옵션입니다. 효과가 있는 하위 필드: `maxOutputTokens`, `temperature`, `topP`, `topK`, `stopSequences`, `candidateCount`.
- `tools` (list of V1BetaModelsModelGenerateContentPostRequestBodyContentApplicationJsonSchemaToolsItems, optional) — 모델이 호출할 수 있는 함수 선언이며 `[{ "functionDeclarations": [...] }]` 형식입니다. 각 선언에는 `name`, `description`, `parameters`(JSON Schema)가 있습니다. 호출은 `functionCall` 파트로 반환되며, 결과는 다음 `user` 턴의 `functionResponse` 파트로 반환하세요. `functionDeclarations`만 사용됩니다. `googleSearch`, `codeExecution` 같은 내장 도구는 무시됩니다.

## Response

### 200

스트리밍하지 않는 호출은 JSON 객체 하나를 반환합니다. 아래는 축약한 예시입니다.

- `candidates` (list of V1BetaModelsModelGenerateContentPostResponsesContentApplicationJsonSchemaCandidatesItems, optional)
- `usageMetadata` (V1BetaModelsModelGenerateContentPostResponsesContentApplicationJsonSchemaUsageMetadata, optional)

## Errors

### 400 Bad Request Error

`bad_request`, `content_policy_violation` 요청이나 입력을 수정하세요. 그대로 다시 보내지 마세요. Gemini 네이티브 엔드포인트의 오류 형식은 `{"error": {"message", "type": "beatapi_error", "code"}}` 하나입니다. 코드는 `error.code`에 있고, 요청 id는 `message`로 끝나며, `retryable` 필드는 없습니다. [오류](/errors#text-endpoints)를 참고하세요.

- `map from string to any`

### 401 Unauthorized Error

`missing_api_key`, `invalid_api_key` 키를 확인하세요. 재시도하지 마세요. Gemini 네이티브 엔드포인트의 오류 형식은 `{"error": {"message", "type": "beatapi_error", "code"}}` 하나입니다. 코드는 `error.code`에 있고, 요청 id는 `message`로 끝나며, `retryable` 필드는 없습니다. [오류](/errors#text-endpoints)를 참고하세요.

- `map from string to any`

### 402 Payment Required Error

`insufficient_credits` 충전하거나 키 한도를 높이세요. `max_tokens`가 너무 크면 발생할 수 있습니다. Gemini 네이티브 엔드포인트의 오류 형식은 `{"error": {"message", "type": "beatapi_error", "code"}}` 하나입니다. 코드는 `error.code`에 있고, 요청 id는 `message`로 끝나며, `retryable` 필드는 없습니다. [오류](/errors#text-endpoints)를 참고하세요.

- `map from string to any`

### 403 Forbidden Error

`forbidden` 모델이 키의 그룹이나 IP 허용 목록 밖에 있거나, 무료 크레딧으로 이 모델을 호출할 수 없습니다. Gemini 네이티브 엔드포인트의 오류 형식은 `{"error": {"message", "type": "beatapi_error", "code"}}` 하나입니다. 코드는 `error.code`에 있고, 요청 id는 `message`로 끝나며, `retryable` 필드는 없습니다. [오류](/errors#text-endpoints)를 참고하세요.

- `map from string to any`

### 404 Not Found Error

`not_found` 알 수 없는 모델입니다. `GET /v1/models`로 사용 가능한 모델 목록을 확인하세요. Gemini 네이티브 엔드포인트의 오류 형식은 `{"error": {"message", "type": "beatapi_error", "code"}}` 하나입니다. 코드는 `error.code`에 있고, 요청 id는 `message`로 끝나며, `retryable` 필드는 없습니다. [오류](/errors#text-endpoints)를 참고하세요.

- `map from string to any`

### 429 Too Many Requests Error

`rate_limit_exceeded` `Retry-After` 또는 `retry_after_seconds`만큼 기다린 뒤 백오프를 두고 재시도하세요. Gemini 네이티브 엔드포인트의 오류 형식은 `{"error": {"message", "type": "beatapi_error", "code"}}` 하나입니다. 코드는 `error.code`에 있고, 요청 id는 `message`로 끝나며, `retryable` 필드는 없습니다. [오류](/errors#text-endpoints)를 참고하세요.

- `map from string to any`

### 500 Internal Server Error

`internal_error`, `temporary_error` 백오프를 적용해 한두 번 재시도하세요. Gemini 네이티브 엔드포인트의 오류 형식은 `{"error": {"message", "type": "beatapi_error", "code"}}` 하나입니다. 코드는 `error.code`에 있고, 요청 id는 `message`로 끝나며, `retryable` 필드는 없습니다. [오류](/errors#text-endpoints)를 참고하세요.

- `map from string to any`

### 503 Service Unavailable Error

`model_unavailable`, `upstream_timeout`, `temporary_error` 백오프를 적용해 재시도하거나 다른 모델을 사용하세요. Gemini 네이티브 엔드포인트의 오류 형식은 `{"error": {"message", "type": "beatapi_error", "code"}}` 하나입니다. 코드는 `error.code`에 있고, 요청 id는 `message`로 끝나며, `retryable` 필드는 없습니다. [오류](/errors#text-endpoints)를 참고하세요.

- `map from string to any`

## Types

### V1BetaModelsModelGenerateContentPostRequestBodyContentApplicationJsonSchemaContentsItems

- `parts` (list of V1BetaModelsModelGenerateContentPostRequestBodyContentApplicationJsonSchemaContentsItemsPartsItems, required)
- `role` (string, optional)

### V1BetaModelsModelGenerateContentPostRequestBodyContentApplicationJsonSchemaSystemInstruction

시스템 프롬프트이며 `{ "parts": [{ "text": "..." }] }` 형식입니다. `text` 파트만 사용됩니다.

### V1BetaModelsModelGenerateContentPostRequestBodyContentApplicationJsonSchemaGenerationConfig

생성 옵션입니다. 효과가 있는 하위 필드: `maxOutputTokens`, `temperature`, `topP`, `topK`, `stopSequences`, `candidateCount`.

- `maxOutputTokens` (integer, optional) — 생성 토큰의 상한이며, 사고 토큰을 포함합니다. 허용되는 최댓값은 1,073,741,823이며, 그보다 크면 `400 bad_request`입니다. 위 표에 있는 모델의 최대 출력 이하로 설정하세요. Gemini 모델은 기본적으로 사고하며, 사고 토큰은 출력으로 과금되고 이 한도에 포함됩니다. 값이 작으면 사고에 모두 쓰여 `finishReason: "MAX_TOKENS"`와 함께 빈 답변이 나올 수 있습니다. 짧은 답변이라도 최소 1,000토큰을 잡으세요. `maxOutputTokens`는 요청에 필요한 잔액을 추정하는 데도 쓰입니다. 실제 출력이 작더라도 값이 너무 크면 `402 insufficient_credits`로 거부될 수 있습니다. 필요한 만큼만 설정하세요.
- `temperature` (double, optional) — 샘플링 온도입니다.
- `topP` (double, optional) — 누클리어스 샘플링입니다. `0` 값은 무시됩니다.
- `topK` (integer, optional) — Top-K 샘플링입니다. `0` 값은 무시됩니다.
- `stopSequences` (list of string, optional) — 생성을 멈추는 문자열입니다. 최대 4개까지 사용됩니다.
- `candidateCount` (integer, optional) — 반환할 후보 수입니다. 둘 이상이 필요하지 않다면 설정하지 마세요.

### V1BetaModelsModelGenerateContentPostRequestBodyContentApplicationJsonSchemaToolsItems

### V1BetaModelsModelGenerateContentPostResponsesContentApplicationJsonSchemaCandidatesItems

- `content` (V1BetaModelsModelGenerateContentPostResponsesContentApplicationJsonSchemaCandidatesItemsContent, optional)
- `finishReason` (string, optional) — 완전한 답변이나 도구 호출이면 `STOP`, `maxOutputTokens`에 도달하면 `MAX_TOKENS`, 답변이 필터링되면 `SAFETY`입니다.

### V1BetaModelsModelGenerateContentPostResponsesContentApplicationJsonSchemaUsageMetadata

- `promptTokenCount` (integer, optional) — 입력 토큰입니다.
- `candidatesTokenCount` (integer, optional) — 보이는 답변의 출력 토큰입니다.
- `thoughtsTokenCount` (integer, optional) — 사고 토큰입니다. 출력으로 과금됩니다. 사고 텍스트 자체는 반환되지 않습니다.
- `totalTokenCount` (integer, optional) — 호출의 전체 토큰입니다.

### V1BetaModelsModelGenerateContentPostRequestBodyContentApplicationJsonSchemaContentsItemsPartsItems

- `text` (string, optional)
- `inlineData` (V1BetaModelsModelGenerateContentPostRequestBodyContentApplicationJsonSchemaContentsItemsPartsItemsInlineData, optional)
- `fileData` (V1BetaModelsModelGenerateContentPostRequestBodyContentApplicationJsonSchemaContentsItemsPartsItemsFileData, optional)
- `functionCall` (V1BetaModelsModelGenerateContentPostRequestBodyContentApplicationJsonSchemaContentsItemsPartsItemsFunctionCall, optional)
- `functionResponse` (V1BetaModelsModelGenerateContentPostRequestBodyContentApplicationJsonSchemaContentsItemsPartsItemsFunctionResponse, optional)

### V1BetaModelsModelGenerateContentPostResponsesContentApplicationJsonSchemaCandidatesItemsContent

- `parts` (list of V1BetaModelsModelGenerateContentPostResponsesContentApplicationJsonSchemaCandidatesItemsContentPartsItems, optional)

### V1BetaModelsModelGenerateContentPostRequestBodyContentApplicationJsonSchemaContentsItemsPartsItemsInlineData

- `mimeType` (string, optional)
- `data` (string, optional)

### V1BetaModelsModelGenerateContentPostRequestBodyContentApplicationJsonSchemaContentsItemsPartsItemsFileData

- `mimeType` (string, optional)
- `fileUri` (string, optional)

### V1BetaModelsModelGenerateContentPostRequestBodyContentApplicationJsonSchemaContentsItemsPartsItemsFunctionCall

### V1BetaModelsModelGenerateContentPostRequestBodyContentApplicationJsonSchemaContentsItemsPartsItemsFunctionResponse

### V1BetaModelsModelGenerateContentPostResponsesContentApplicationJsonSchemaCandidatesItemsContentPartsItems

- `text` (string, optional) — 답변 텍스트입니다.
- `functionCall` (V1BetaModelsModelGenerateContentPostResponsesContentApplicationJsonSchemaCandidatesItemsContentPartsItemsFunctionCall, optional) — 도구 호출이며 `name`과 `args`가 있습니다.

### V1BetaModelsModelGenerateContentPostResponsesContentApplicationJsonSchemaCandidatesItemsContentPartsItemsFunctionCall

도구 호출이며 `name`과 `args`가 있습니다.

## Examples

**Request**

```json
{
  "contents": [
    {
      "parts": [
        {
          "text": "Design a resilient webhook retry strategy for a payments API."
        }
      ],
      "role": "user"
    }
  ]
}
```

**Response**

```json
{
  "candidates": [
    {
      "content": {
        "parts": [
          {
            "text": "Retry with exponential backoff and jitter, and make every handler idempotent."
          }
        ],
        "role": "model"
      },
      "finishReason": "STOP",
      "index": 0
    }
  ],
  "usageMetadata": {
    "promptTokenCount": 19,
    "candidatesTokenCount": 16,
    "thoughtsTokenCount": 85,
    "totalTokenCount": 120
  }
}
```

**SDK Code**

```python 빠른 시작
import requests

url = "https://direct.beatapi.io/v1beta/models/gemini-3.8-flash:generateContent"

payload = { "contents": [
        {
            "parts": [{ "text": "Design a resilient webhook retry strategy for a payments API." }],
            "role": "user"
        }
    ] }
headers = {
    "Authorization": "Bearer <token>",
    "Content-Type": "application/json"
}

response = requests.post(url, json=payload, headers=headers)

print(response.json())
```

```javascript 빠른 시작
const url = 'https://direct.beatapi.io/v1beta/models/gemini-3.8-flash:generateContent';
const options = {
  method: 'POST',
  headers: {Authorization: 'Bearer <token>', 'Content-Type': 'application/json'},
  body: '{"contents":[{"parts":[{"text":"Design a resilient webhook retry strategy for a payments API."}],"role":"user"}]}'
};

try {
  const response = await fetch(url, options);
  const data = await response.json();
  console.log(data);
} catch (error) {
  console.error(error);
}
```

```go 빠른 시작
package main

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

func main() {

	url := "https://direct.beatapi.io/v1beta/models/gemini-3.8-flash:generateContent"

	payload := strings.NewReader("{\n  \"contents\": [\n    {\n      \"parts\": [\n        {\n          \"text\": \"Design a resilient webhook retry strategy for a payments API.\"\n        }\n      ],\n      \"role\": \"user\"\n    }\n  ]\n}")

	req, _ := http.NewRequest("POST", url, payload)

	req.Header.Add("Authorization", "Bearer <token>")
	req.Header.Add("Content-Type", "application/json")

	res, _ := http.DefaultClient.Do(req)

	defer res.Body.Close()
	body, _ := io.ReadAll(res.Body)

	fmt.Println(res)
	fmt.Println(string(body))

}
```

```ruby 빠른 시작
require 'uri'
require 'net/http'

url = URI("https://direct.beatapi.io/v1beta/models/gemini-3.8-flash:generateContent")

http = Net::HTTP.new(url.host, url.port)
http.use_ssl = true

request = Net::HTTP::Post.new(url)
request["Authorization"] = 'Bearer <token>'
request["Content-Type"] = 'application/json'
request.body = "{\n  \"contents\": [\n    {\n      \"parts\": [\n        {\n          \"text\": \"Design a resilient webhook retry strategy for a payments API.\"\n        }\n      ],\n      \"role\": \"user\"\n    }\n  ]\n}"

response = http.request(request)
puts response.read_body
```

```java 빠른 시작
import com.mashape.unirest.http.HttpResponse;
import com.mashape.unirest.http.Unirest;

HttpResponse<String> response = Unirest.post("https://direct.beatapi.io/v1beta/models/gemini-3.8-flash:generateContent")
  .header("Authorization", "Bearer <token>")
  .header("Content-Type", "application/json")
  .body("{\n  \"contents\": [\n    {\n      \"parts\": [\n        {\n          \"text\": \"Design a resilient webhook retry strategy for a payments API.\"\n        }\n      ],\n      \"role\": \"user\"\n    }\n  ]\n}")
  .asString();
```

```php 빠른 시작
<?php
require_once('vendor/autoload.php');

$client = new \GuzzleHttp\Client();

$response = $client->request('POST', 'https://direct.beatapi.io/v1beta/models/gemini-3.8-flash:generateContent', [
  'body' => '{
  "contents": [
    {
      "parts": [
        {
          "text": "Design a resilient webhook retry strategy for a payments API."
        }
      ],
      "role": "user"
    }
  ]
}',
  'headers' => [
    'Authorization' => 'Bearer <token>',
    'Content-Type' => 'application/json',
  ],
]);

echo $response->getBody();
```

```csharp 빠른 시작
using RestSharp;

var client = new RestClient("https://direct.beatapi.io/v1beta/models/gemini-3.8-flash:generateContent");
var request = new RestRequest(Method.POST);
request.AddHeader("Authorization", "Bearer <token>");
request.AddHeader("Content-Type", "application/json");
request.AddParameter("application/json", "{\n  \"contents\": [\n    {\n      \"parts\": [\n        {\n          \"text\": \"Design a resilient webhook retry strategy for a payments API.\"\n        }\n      ],\n      \"role\": \"user\"\n    }\n  ]\n}", ParameterType.RequestBody);
IRestResponse response = client.Execute(request);
```

```swift 빠른 시작
import Foundation

let headers = [
  "Authorization": "Bearer <token>",
  "Content-Type": "application/json"
]
let parameters = ["contents": [
    [
      "parts": [["text": "Design a resilient webhook retry strategy for a payments API."]],
      "role": "user"
    ]
  ]] as [String : Any]

let postData = JSONSerialization.data(withJSONObject: parameters, options: [])

let request = NSMutableURLRequest(url: NSURL(string: "https://direct.beatapi.io/v1beta/models/gemini-3.8-flash:generateContent")! as URL,
                                        cachePolicy: .useProtocolCachePolicy,
                                    timeoutInterval: 10.0)
request.httpMethod = "POST"
request.allHTTPHeaderFields = headers
request.httpBody = postData as Data

let session = URLSession.shared
let dataTask = session.dataTask(with: request as URLRequest, completionHandler: { (data, response, error) -> Void in
  if (error != nil) {
    print(error as Any)
  } else {
    let httpResponse = response as? HTTPURLResponse
    print(httpResponse)
  }
})

dataTask.resume()
```