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

# Gemini 네이티브 형식

> Google Gemini 네이티브 형식으로 GravitexAI 호출

## 소개

Gemini Native API는 Google Gemini의 요청 및 응답 형식을 사용합니다. Google 공식 클라이언트(예: `google-generativeai` SDK) 또는 Gemini 데이터 구조를 직접 다루어야 할 때 적합합니다. API는 Gemini 사양을 따르며 사고 모드, 멀티모달 입력, 도구 호출, **Google Search(Grounding)**, 컨텍스트 캐싱, 이미지 생성 등 전체 기능을 지원합니다.

<Note>
  OpenAI 호환 클라이언트(예: OpenAI SDK)로 Gemini를 사용하는 경우 [Gemini OpenAI 형식(Chat)](/ko/api-reference/endpoint/gemini-chat-openai)을 참조하세요. 다른 모델은 [OpenAI Chat Completions](/ko/api-reference/endpoint/chat-openai)를 사용하세요.
</Note>

### OpenAI 형식과의 차이

| 항목       | Gemini Native                                       | OpenAI 호환 (/v1/chat/completions) |
| -------- | --------------------------------------------------- | -------------------------------- |
| 메시지 구조   | `contents[].parts[]` (text / inlineData / fileData) | `messages[].content`             |
| 역할       | `user` / `model`                                    | `user` / `assistant` / `system`  |
| 시스템 프롬프트 | `systemInstruction.parts`                           | role=system인 `messages`          |
| 스트리밍     | `streamGenerateContent?alt=sse`                     | `stream: true`                   |
| 사고 모드    | `generationConfig.thinkingConfig` 또는 모델 접미사         | 모델 접미사(예: `-thinking`)           |

## API 엔드포인트

| 기능            | Method | Path                                                   |
| ------------- | ------ | ------------------------------------------------------ |
| 텍스트 생성(비스트리밍) | POST   | `/v1beta/models/{model}:generateContent`               |
| 텍스트 생성(스트리밍)  | POST   | `/v1beta/models/{model}:streamGenerateContent?alt=sse` |
| 단일 Embedding  | POST   | `/v1beta/models/{model}:embedContent`                  |
| 일괄 Embedding  | POST   | `/v1beta/models/{model}:batchEmbedContents`            |

경로의 `{model}`을 실제 모델 ID(예: `gemini-2.5-pro`, `gemini-3-pro-preview`)로 바꿉니다.

## 인증

다음 중 하나를 사용할 수 있습니다:

<ParamField header="Authorization" type="string">
  Bearer 토큰: `Bearer sk-xxxxxxxxxx` (권장, 다른 GravitexAI 엔드포인트와 동일)
</ParamField>

<ParamField header="x-goog-api-key" type="string">
  Google 스타일 API 키: `x-goog-api-key: sk-xxxxxxxxxx`
</ParamField>

URL에 키를 전달할 수도 있습니다: `?key=sk-xxxxxxxxxx`.

## 요청 매개변수

### generateContent / streamGenerateContent

<ParamField body="contents" type="array" required>
  대화 내용 목록. 각 항목은 `role`(`user` 또는 `model`)과 `parts`를 가집니다. 각 part는 `{"text": "..."}`, `{"inlineData": {"mimeType": "...", "data": "base64..."}}`, 또는 `{"fileData": {"mimeType": "...", "fileUri": "gs://..."}}`일 수 있습니다.
</ParamField>

<ParamField body="generationConfig" type="object">
  생성 설정.

  * `temperature`: 0–2, 무작위성
  * `topP`: nucleus 샘플링
  * `topK`: top-K 샘플링
  * `maxOutputTokens`: 최대 출력 토큰 수
  * `stopSequences`: 중지 시퀀스
  * `responseMimeType`: 예: `text/plain`
  * `responseModalities`: 예: `["TEXT"]` 또는 `["IMAGE"]`
  * `thinkingConfig`: 사고 모드(아래 참조)
  * `imageConfig`: 이미지 생성 설정(아래 참조)
</ParamField>

<ParamField body="systemInstruction" type="object">
  시스템 지시: `{"parts": [{"text": "..."}]}`.
</ParamField>

<ParamField body="safetySettings" type="array">
  안전 수준, 예: `[{"category": "HARM_CATEGORY_HARASSMENT", "threshold": "OFF"}]`.
</ParamField>

<ParamField body="tools" type="array">
  도구 선언(function calling), 고급 기능 참조.
</ParamField>

<ParamField body="toolConfig" type="object">
  도구 설정, 예: `functionCallingConfig.mode`: `AUTO` / `ANY` / `NONE`.
</ParamField>

<ParamField body="cachedContent" type="string">
  API가 반환한 컨텍스트 캐싱 ID; 캐시된 컨텍스트 재사용에 사용.
</ParamField>

## 응답 형식

비스트리밍 `generateContent`는 JSON을 반환합니다:

<ResponseExample>
  ```json theme={null}
  {
    "candidates": [
      {
        "content": {
          "parts": [{"text": "Response text"}],
          "role": "model"
        },
        "finishReason": "STOP",
        "index": 0,
        "safetyRatings": []
      }
    ],
    "usageMetadata": {
      "promptTokenCount": 10,
      "candidatesTokenCount": 20,
      "totalTokenCount": 30,
      "thoughtsTokenCount": 0,
      "cachedContentTokenCount": 0
    },
    "modelVersion": "gemini-2.5-pro",
    "createTime": "2025-01-01T00:00:00Z"
  }
  ```
</ResponseExample>

스트리밍 엔드포인트는 SSE를 반환합니다. 각 줄은 `data: `로 시작하며 JSON 조각(예: `candidates[].content.parts`)을 포함합니다.

## 기본 예시

<Tabs>
  <Tab title="cURL (non-streaming)">
    ```bash theme={null}
    curl -X POST "https://api.gravitex.ai/v1beta/models/gemini-2.5-pro:generateContent" \
      -H "Content-Type: application/json" \
      -H "Authorization: Bearer sk-xxxxxxxxxx" \
      -d '{
        "contents": [
          {"role": "user", "parts": [{"text": "Describe AI in one sentence"}]}
        ],
        "generationConfig": {
          "temperature": 0.7,
          "maxOutputTokens": 1024
        }
      }'
    ```
  </Tab>

  <Tab title="cURL (streaming)">
    ```bash theme={null}
    curl -N -X POST "https://api.gravitex.ai/v1beta/models/gemini-2.5-pro:streamGenerateContent?alt=sse" \
      -H "Content-Type: application/json" \
      -H "Authorization: Bearer sk-xxxxxxxxxx" \
      -d '{
        "contents": [
          {"role": "user", "parts": [{"text": "Describe AI in one sentence"}]}
        ],
        "generationConfig": {"maxOutputTokens": 1024}
      }'
    ```
  </Tab>

  <Tab title="Python (google-generativeai)">
    ```python theme={null}
    import google.generativeai as genai

    genai.configure(
        api_key="sk-xxxxxxxxxx",
        transport="rest",
        client_options={"api_endpoint": "https://api.gravitex.ai"}
    )

    model = genai.GenerativeModel("gemini-2.5-pro")
    response = model.generate_content("Describe AI in one sentence")
    print(response.text)
    ```
  </Tab>

  <Tab title="Node.js">
    ```javascript theme={null}
    const { GoogleGenerativeAI } = require("@google/generative-ai");

    const genAI = new GoogleGenerativeAI("sk-xxxxxxxxxx");
    genAI.apiKey = "sk-xxxxxxxxxx";
    // If the SDK supports a custom baseUrl, set it to https://api.gravitex.ai
    const model = genAI.getGenerativeModel({ model: "gemini-2.5-pro" });

    const result = await model.generateContent("Describe AI in one sentence");
    const text = result.response.text();
    console.log(text);
    ```
  </Tab>
</Tabs>

<Note>
  기본적으로 `google-generativeai`는 Google API를 호출합니다. GravitexAI를 사용하려면 `client_options` 또는 환경 변수를 통해 `api_endpoint`를 `https://api.gravitex.ai`로 설정하세요. 자세한 내용은 SDK 문서를 참조하세요.
</Note>

## 고급 기능

### 사고 모드

세 가지 방식으로 지원됩니다:

1. **generationConfig.thinkingConfig** (Gemini 2.5 Pro): `thinkingBudget`(토큰 수) 사용
2. **thinkingConfig.thinkingLevel** (Gemini 3 Pro): `LOW` / `HIGH` 사용
3. **모델 접미사**: `-thinking`, `-thinking-8192`, `-nothinking`, `-thinking-low`, `-thinking-high`

<Tabs>
  <Tab title="thinkingBudget (2.5 Pro)">
    ```json theme={null}
    {
      "contents": [{"role": "user", "parts": [{"text": "Give a geometry problem and solve it step by step"}]}],
      "generationConfig": {
        "maxOutputTokens": 8192,
        "thinkingConfig": {
          "includeThoughts": true,
          "thinkingBudget": 8192
        }
      }
    }
    ```
  </Tab>

  <Tab title="thinkingLevel (3 Pro)">
    ```json theme={null}
    {
      "contents": [{"role": "user", "parts": [{"text": "Give a geometry problem and solve it step by step"}]}],
      "generationConfig": {
        "maxOutputTokens": 8192,
        "thinkingConfig": {
          "includeThoughts": true,
          "thinkingLevel": "HIGH"
        }
      }
    }
    ```
  </Tab>
</Tabs>

### 멀티모달 입력

`contents[].parts`에서 텍스트와 미디어를 혼합할 수 있습니다:

```json theme={null}
{
  "contents": [
    {
      "role": "user",
      "parts": [
        {"text": "Describe this image"},
        {
          "inlineData": {
            "mimeType": "image/jpeg",
            "data": "/9j/4AAQSkZJRg..."
          }
        }
      ]
    }
  ]
}
```

* **이미지**: base64 `data`가 있는 `inlineData`, 또는 `fileUri`(예: `gs://...`)가 있는 `fileData`
* **오디오**: `audio/mp3` 등의 `mimeType`이 있는 `inlineData`

### 도구 호출(Function Calling)

```json theme={null}
{
  "contents": [{"role": "user", "parts": [{"text": "What is the weather in Shanghai today?"}]}],
  "tools": [
    {
      "functionDeclarations": [
        {
          "name": "get_weather",
          "description": "Get weather for a city",
          "parameters": {
            "type": "object",
            "properties": {
              "location": {"type": "string"}
            },
            "required": ["location"]
          }
        }
      ]
    }
  ],
  "toolConfig": {
    "functionCallingConfig": {
      "mode": "AUTO",
      "allowedFunctionNames": []
    }
  }
}
```

모델이 `functionCall` part를 반환할 수 있습니다. 다음 `contents`에 해당 `functionResponse`를 포함하여 다시 요청하세요.

### Google Search(Grounding)

활성화하면 모델이 실시간 웹 검색을 사용하여 답변을 개선할 수 있습니다(예: 날씨, 뉴스). `tools`에 `googleSearch`를 추가하세요:

```json theme={null}
{
  "contents": [{"role": "user", "parts": [{"text": "What is the weather in Beijing today?"}]}],
  "tools": [
    {
      "googleSearch": {}
    }
  ],
  "toolConfig": {
    "functionCallingConfig": {
      "mode": "AUTO"
    }
  }
}
```

function calling과 Google Search를 함께 사용하려면 동일한 `tools` 배열에 `googleSearch: {}`와 `functionDeclarations`를 별도 요소로 포함하세요. 응답에 검색 메타데이터(예: `groundingMetadata`)가 포함될 수 있습니다.

### 스트리밍

사용: `POST /v1beta/models/{model}:streamGenerateContent?alt=sse`. 요청 본문은 `generateContent`와 동일합니다. 응답은 SSE이며, 각 `data:` 줄이 JSON 청크입니다.

### 컨텍스트 캐싱

첫 요청에는 `cachedContent`를 포함하지 않습니다. 서버가 캐시 ID를 반환하면 이후 요청에서 다음과 같이 전송할 수 있습니다:

```json theme={null}
{
  "cachedContent": "cached-content-id",
  "contents": [{"role": "user", "parts": [{"text": "Continue from the context above"}]}]
}
```

긴 반복 컨텍스트의 비용과 지연 시간을 줄일 수 있습니다.

### 이미지 생성(예: Gemini 2.5 Flash)

모델이 이미지 출력을 지원할 때 `generationConfig`에서 설정:

```json theme={null}
{
  "contents": [{"role": "user", "parts": [{"text": "Draw a cat"}]}],
  "generationConfig": {
    "responseModalities": ["IMAGE"],
    "imageConfig": {
      "aspectRatio": "1:1",
      "imageSize": "1K",
      "imageOutputOptions": {"mimeType": "image/png"}
    }
  }
}
```

응답 `candidates[].content.parts`에 `inlineData`(예: base64 이미지)가 포함될 수 있습니다.

## Embedding API

### 단일: embedContent

**엔드포인트**: `POST https://api.gravitex.ai/v1beta/models/{model}:embedContent`

**요청 본문 예시**:

```json theme={null}
{
  "model": "text-embedding-004",
  "content": {
    "parts": [{"text": "Text to embed"}]
  }
}
```

또는 경로에 `model`을 넣습니다: `/v1beta/models/text-embedding-004:embedContent`, 본문에는 `content`만 포함.

### 일괄: batchEmbedContents

**엔드포인트**: `POST https://api.gravitex.ai/v1beta/models/{model}:batchEmbedContents`

**요청 본문 예시**:

```json theme={null}
{
  "requests": [
    {"content": {"parts": [{"text": "First text"}]}},
    {"content": {"parts": [{"text": "Second text"}]}}
  ]
}
```

응답은 요청당 하나의 임베딩이 포함된 배열입니다.

## 오류 처리

오류는 HTTP 상태 코드와 JSON 본문으로 반환됩니다:

<ResponseExample>
  ```json theme={null}
  {
    "error": {
      "code": 400,
      "message": "Invalid request: ...",
      "status": "INVALID_ARGUMENT"
    }
  }
  ```
</ResponseExample>

일반적인 경우:

| Status | Meaning                                |
| ------ | -------------------------------------- |
| 400    | 잘못된 요청(예: `contents` 누락, 지원되지 않는 매개변수) |
| 401    | 인증 실패(유효하지 않거나 누락된 API 키)              |
| 404    | 모델을 찾을 수 없거나 경로 오류                     |
| 429    | 속도 제한; 나중에 재시도                         |
| 500    | 서버 오류                                  |

클라이언트에서 `error.message`를 파싱하고 재시도 또는 사용자 메시지를 적절히 처리하세요.

## OpenAI 형식과의 비교

| 항목         | Gemini Native                                      | OpenAI (/v1/chat/completions)    |
| ---------- | -------------------------------------------------- | -------------------------------- |
| 기본 경로      | `/v1beta/models/{model}:generateContent`           | `/v1/chat/completions`           |
| 인증         | `Authorization: Bearer sk-xxx` 또는 `x-goog-api-key` | `Authorization: Bearer sk-xxx`   |
| 메시지 형식     | `contents[].parts[]` (text/inlineData/fileData)    | `messages[].content` (문자열 또는 배열) |
| 시스템 프롬프트   | `systemInstruction.parts`                          | `role: "system"`인 `messages`     |
| 스트리밍       | `streamGenerateContent?alt=sse`                    | `stream: true`                   |
| 사고         | `thinkingConfig` 또는 모델 접미사                         | 모델 접미사(예: `-thinking`)           |
| 도구         | `tools[].functionDeclarations`                     | `tools[].function` (OpenAI 형식)   |
| 일반적인 클라이언트 | Google SDK, 커스텀 HTTP 클라이언트                         | OpenAI SDK, OpenAI 호환 클라이언트      |

Google Gemini 도구에 의존하거나 Gemini 전용 필드(예: `thinkingConfig`, 네이티브 멀티모달 parts)가 필요할 때 네이티브 엔드포인트를 사용하세요. OpenAI 생태계 내에서 작업하려면 `/v1/chat/completions`를 사용하세요.
