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

# Tạo nội dung

> Tạo nội dung bằng định dạng Google Gemini API

TokenLab hỗ trợ định dạng Google Gemini API gốc cho các mô hình Gemini. Điều này cho phép khả năng tương thích trực tiếp với các Google AI SDK.

## Tham số đường dẫn

<ParamField path="model" type="string" required>
  Tên mô hình (ví dụ: `gemini-2.5-pro`, `gemini-3.5-flash`).

  Đối với các tích hợp trong môi trường production, hãy ưu tiên các phần media dựa trên URL `fileData` / `file_data` với một URL `https` công khai.
  TokenLab sẽ định tuyến các kênh Gemini-native được hỗ trợ qua đường dẫn native khi có thể và tự động chuyển sang đường dẫn chuyển đổi nội bộ tương thích khi không có tuyến sẵn sàng cho native đối với yêu cầu đa phương thức đó.
</ParamField>

## Tham số truy vấn

<ParamField query="key" type="string">
  API key (phương thức thay thế cho xác thực qua header).
</ParamField>

## Xác thực

Các endpoint của Gemini hỗ trợ nhiều phương thức xác thực:

* `?key=YOUR_API_KEY` tham số truy vấn
* tiêu đề `x-goog-api-key: YOUR_API_KEY`
* tiêu đề `Authorization: Bearer YOUR_API_KEY`

## Thân yêu cầu

<ParamField body="contents" type="array" required>
  Nội dung cuộc hội thoại.

  Mỗi đối tượng nội dung bao gồm:

  * `role` (string): `user` hoặc `model`
  * `parts` (array): các part nội dung. TokenLab hiện hỗ trợ:
    * part văn bản: `{ "text": "..." }`
    * part media inline: `inlineData` / `inline_data`
    * part tệp dựa trên URL: `fileData` / `file_data`

  Với các media part, TokenLab hiện chấp nhận MIME type của hình ảnh, âm thanh và video, sau đó chuyển tiếp qua model details tương thích Gemini.

  Giá trị role `user` và `model` được chuẩn hóa không phân biệt hoa thường. `inlineData` / `inline_data` với `application/octet-stream` chỉ được chấp nhận khi TokenLab nhận diện được byte ảnh hoặc video được hỗ trợ; nếu không request sẽ fail trước khi routing. Với request native image-output, chỉ nhóm tool Google search/maps được chấp nhận, và tổ hợp tool không hỗ trợ sẽ fail trước retry upstream.
</ParamField>

<ParamField body="systemInstruction" type="object">
  Chỉ dẫn hệ thống cho mô hình.
</ParamField>

<ParamField body="generationConfig" type="object">
  Cấu hình tạo nội dung:

  * `temperature` (number): Nhiệt độ lấy mẫu (sampling temperature)
  * `topP` (number): Xác suất lấy mẫu hạt (nucleus sampling)
  * `topK` (integer): Lấy mẫu Top-K
  * `maxOutputTokens` (integer): Số lượng token đầu ra tối đa
  * `stopSequences` (array): Các chuỗi dừng (stop sequences)
  * `candidateCount` (integer): Số ứng viên cho tạo nội dung không streaming. Yêu cầu streaming phải bỏ trường này hoặc giữ ở `1`.
  * `responseModalities` (array): Các modality output được yêu cầu cho route native tương thích.
  * `responseMimeType` (string): MIME type của output, như `text/plain` hoặc `application/json`.
  * `responseSchema` (object): JSON schema cho output có cấu trúc khi `responseMimeType` yêu cầu JSON.
  * `thinkingConfig` / `thinking_config` (object): Tùy chọn ngân sách suy nghĩ cho model tương thích.
</ParamField>

<ParamField body="safetySettings" type="array">
  Cài đặt bộ lọc an toàn.
</ParamField>

## Phản hồi

<ResponseField name="candidates" type="array">
  Các ứng viên nội dung được tạo.
</ResponseField>

<ResponseField name="usageMetadata" type="object">
  Thông tin sử dụng token.
</ResponseField>

<RequestExample>
  ```bash cURL theme={null}
  curl -X POST "https://api.tokenlab.sh/v1beta/models/gemini-2.5-pro:generateContent?key=sk-your-api-key" \
    -H "Content-Type: application/json" \
    -d '{
      "contents": [
        {
          "parts": [{"text": "Hello, Gemini!"}]
        }
      ],
      "generationConfig": {
        "temperature": 0.7,
        "maxOutputTokens": 1024
      }
    }'
  ```

  ```python Python theme={null}
  import google.generativeai as genai

  genai.configure(
      api_key="sk-your-api-key",
      transport="rest",
      client_options={"api_endpoint": "api.tokenlab.sh"}
  )

  model = genai.GenerativeModel("gemini-2.5-pro")
  response = model.generate_content("Hello, Gemini!")

  print(response.text)
  ```

  ```javascript JavaScript theme={null}
  import { GoogleGenerativeAI } from "@google/generative-ai";

  const genAI = new GoogleGenerativeAI("sk-your-api-key", {
    baseUrl: "https://api.tokenlab.sh"
  });

  const model = genAI.getGenerativeModel({ model: "gemini-2.5-pro" });
  const result = await model.generateContent("Hello, Gemini!");

  console.log(result.response.text());
  ```

  ```go Go theme={null}
  package main

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

  func main() {
      payload := map[string]interface{}{
          "contents": []map[string]interface{}{
              {
                  "parts": []map[string]string{
                      {"text": "Hello, Gemini!"},
                  },
              },
          },
          "generationConfig": map[string]interface{}{
              "temperature":    0.7,
              "maxOutputTokens": 1024,
          },
      }

      jsonData, _ := json.Marshal(payload)
      req, _ := http.NewRequest("POST",
          "https://api.tokenlab.sh/v1beta/models/gemini-2.5-pro:generateContent?key=sk-your-api-key",
          bytes.NewBuffer(jsonData))
      req.Header.Set("Content-Type", "application/json")

      client := &http.Client{}
      resp, _ := client.Do(req)
      defer resp.Body.Close()

      body, _ := io.ReadAll(resp.Body)
      fmt.Println(string(body))
  }
  ```

  ```php PHP theme={null}
  <?php
  $payload = [
      'contents' => [
          [
              'parts' => [
                  ['text' => 'Hello, Gemini!']
              ]
          ]
      ],
      'generationConfig' => [
          'temperature' => 0.7,
          'maxOutputTokens' => 1024
      ]
  ];

  $ch = curl_init('https://api.tokenlab.sh/v1beta/models/gemini-2.5-pro:generateContent?key=sk-your-api-key');

  curl_setopt_array($ch, [
      CURLOPT_RETURNTRANSFER => true,
      CURLOPT_POST => true,
      CURLOPT_HTTPHEADER => [
          'Content-Type: application/json'
      ],
      CURLOPT_POSTFIELDS => json_encode($payload)
  ]);

  $response = curl_exec($ch);
  curl_close($ch);

  $data = json_decode($response, true);
  echo $data['candidates'][0]['content']['parts'][0]['text'];
  ```
</RequestExample>

## Ví dụ đầu vào đa phương thức

Với các yêu cầu Gemini đa phương thức, hãy đặt media vào `contents[].parts[]` bằng byte inline hoặc tham chiếu tệp dựa trên URL.

Các loại media hiện được hỗ trợ trong model details Gemini:

* hình ảnh
* âm thanh
* video

Với media inline, dùng `inlineData` hoặc `inline_data` và truyền byte tệp được mã hoá Base64.

Với media qua URL, dùng `fileData` hoặc `file_data` và truyền một URL công khai `https`.

### Ví dụ đầu vào hình ảnh

```json theme={null}
{
  "contents": [
    {
      "role": "user",
      "parts": [
        { "text": "Hãy mô tả hình ảnh này." },
        {
          "inlineData": {
            "mimeType": "image/jpeg",
            "data": "/9j/4AAQSkZJRgABAQ..."
          }
        }
      ]
    }
  ]
}
```

### Ví dụ đầu vào âm thanh

```json theme={null}
{
  "contents": [
    {
      "role": "user",
      "parts": [
        { "text": "Hãy chép lời và tóm tắt đoạn âm thanh này." },
        {
          "file_data": {
            "mime_type": "audio/mpeg",
            "file_uri": "https://example.com/sample.mp3"
          }
        }
      ]
    }
  ]
}
```

### Ví dụ đầu vào video

```json theme={null}
{
  "contents": [
    {
      "role": "user",
      "parts": [
        { "text": "Hãy mô tả ngắn gọn video này." },
        {
          "fileData": {
            "mimeType": "video/mp4",
            "fileUri": "https://example.com/sample.mp4"
          }
        }
      ]
    }
  ]
}
```

<ResponseExample>
  ```json Response theme={null}
  {
    "candidates": [
      {
        "content": {
          "role": "model",
          "parts": [
            {"text": "Hello! How can I assist you today?"}
          ]
        },
        "finishReason": "STOP",
        "safetyRatings": [
          {"category": "HARM_CATEGORY_HARASSMENT", "probability": "NEGLIGIBLE"}
        ]
      }
    ],
    "usageMetadata": {
      "promptTokenCount": 5,
      "candidatesTokenCount": 10,
      "totalTokenCount": 15
    }
  }
  ```
</ResponseExample>

## Ví dụ đầu vào video

```json theme={null}
{
  "contents": [
    {
      "role": "user",
      "parts": [
        { "text": "Please describe this video." },
        {
          "fileData": {
            "mimeType": "video/mp4",
            "fileUri": "https://example.com/demo.mp4"
          }
        }
      ]
    }
  ]
}
```

## Ví dụ đầu vào âm thanh

```json theme={null}
{
  "contents": [
    {
      "role": "user",
      "parts": [
        { "text": "Please describe this audio." },
        {
          "fileData": {
            "mimeType": "audio/mpeg",
            "fileUri": "https://example.com/demo.mp3"
          }
        }
      ]
    }
  ]
}
```
