Chuyển đến nội dung chính
POST
/
v1beta
/
models
/
{model}
:
{operator}
import os
from google import genai

client = genai.Client(
    api_key=os.environ["COMETAPI_KEY"],
    http_options={"api_version": "v1beta", "base_url": "https://api.cometapi.com"},
)

response = client.models.generate_content(
    model="gemini-3-flash-preview",
    contents="Explain how AI works in a few words",
)

print(response.text)
{
  "candidates": [
    {
      "content": {
        "role": "<string>",
        "parts": [
          {
            "text": "<string>",
            "functionCall": {
              "name": "<string>",
              "args": {}
            },
            "inlineData": {
              "mimeType": "<string>",
              "data": "<string>"
            },
            "thought": true
          }
        ]
      },
      "safetyRatings": [
        {
          "category": "<string>",
          "probability": "<string>",
          "blocked": true
        }
      ],
      "citationMetadata": {
        "citationSources": [
          {
            "startIndex": 123,
            "endIndex": 123,
            "uri": "<string>",
            "license": "<string>"
          }
        ]
      },
      "tokenCount": 123,
      "avgLogprobs": 123,
      "groundingMetadata": {
        "groundingChunks": [
          {
            "web": {
              "uri": "<string>",
              "title": "<string>"
            }
          }
        ],
        "groundingSupports": [
          {
            "groundingChunkIndices": [
              123
            ],
            "confidenceScores": [
              123
            ],
            "segment": {
              "startIndex": 123,
              "endIndex": 123,
              "text": "<string>"
            }
          }
        ],
        "webSearchQueries": [
          "<string>"
        ]
      },
      "index": 123
    }
  ],
  "promptFeedback": {
    "safetyRatings": [
      {
        "category": "<string>",
        "probability": "<string>",
        "blocked": true
      }
    ]
  },
  "usageMetadata": {
    "promptTokenCount": 123,
    "candidatesTokenCount": 123,
    "totalTokenCount": 123,
    "trafficType": "<string>",
    "thoughtsTokenCount": 123,
    "promptTokensDetails": [
      {
        "modality": "<string>",
        "tokenCount": 123
      }
    ],
    "candidatesTokensDetails": [
      {
        "modality": "<string>",
        "tokenCount": 123
      }
    ]
  },
  "modelVersion": "<string>",
  "createTime": "<string>",
  "responseId": "<string>"
}
CometAPI hỗ trợ định dạng API gốc của Gemini, cho phép bạn truy cập đầy đủ vào các tính năng riêng của Gemini như kiểm soát thinking, Google Search grounding, các modality tạo ảnh gốc và nhiều hơn nữa. Hãy dùng endpoint này khi bạn cần các khả năng không có sẵn thông qua endpoint chat tương thích OpenAI.
Cả header x-goog-api-keyAuthorization: Bearer đều được hỗ trợ để xác thực.

Bắt đầu nhanh

Để sử dụng bất kỳ Gemini SDK hoặc HTTP client nào với CometAPI, hãy thay thế base URL và API key:
Cài đặtMặc định của GoogleCometAPI
Base URLgenerativelanguage.googleapis.comapi.cometapi.com
API Key$GEMINI_API_KEY$COMETAPI_KEY

Gửi đầu vào video

Gemini generateContent chấp nhận video như một phần nội dung. Hãy chọn hình dạng đầu vào dựa trên nơi video được lưu trữ:
Nguồn videoPhần requestDùng khi
Tệp video cục bộinlineDataVideo đủ nhỏ để gửi dưới dạng base64 trong JSON request.
URL video công khaifileData.fileUriVideo có sẵn qua URL HTTPS công khai không yêu cầu xác thực.
Đối với request REST và curl, hãy dùng tên trường camelCase của Gemini như inlineData.mimeTypefileData.fileUri. Không gửi media URL dưới dạng file_data.file_uri.
Ví dụ này đọc một tệp MP4 cục bộ, mã hóa nó thành base64 và gửi nó trong phần thân request:
read -rsp "CometAPI API key: " COMETAPI_KEY
printf '\n'
export COMETAPI_KEY
VIDEO_PATH="./your_video.mp4"
VIDEO_B64=$(base64 < "$VIDEO_PATH" | tr -d '\n')

curl -X POST \
  "https://api.cometapi.com/v1beta/models/gemini-3.5-flash:generateContent" \
  -H "Content-Type: application/json" \
  -H "x-goog-api-key: $COMETAPI_KEY" \
  --data-binary @- <<EOF
{
  "contents": [
    {
      "role": "user",
      "parts": [
        {
          "inlineData": {
            "mimeType": "video/mp4",
            "data": "${VIDEO_B64}"
          }
        },
        {
          "text": "Analyze this video and list the key scenes."
        }
      ]
    }
  ],
  "generationConfig": {
    "maxOutputTokens": 512,
    "thinkingConfig": {"thinkingLevel": "MINIMAL"}
  }
}
EOF
Ví dụ này gửi một URL MP4 công khai bằng fileData.fileUri:
read -rsp "CometAPI API key: " COMETAPI_KEY
printf '\n'
export COMETAPI_KEY
VIDEO_URL="https://interactive-examples.mdn.mozilla.net/media/cc0-videos/flower.mp4"

curl -X POST \
  "https://api.cometapi.com/v1beta/models/gemini-3.5-flash:generateContent" \
  -H "Content-Type: application/json" \
  -H "x-goog-api-key: $COMETAPI_KEY" \
  --data-binary @- <<EOF
{
  "contents": [
    {
      "role": "user",
      "parts": [
        {
          "fileData": {
            "mimeType": "video/mp4",
            "fileUri": "${VIDEO_URL}"
          }
        },
        {
          "text": "Analyze this video and list the key scenes."
        }
      ]
    }
  ],
  "generationConfig": {
    "maxOutputTokens": 512,
    "thinkingConfig": {"thinkingLevel": "MINIMAL"}
  }
}
EOF
CometAPI không khuyến nghị quy trình tải lên qua Gemini Files API riêng cho endpoint này. Hãy gửi media ngay trong chính request generateContent bằng inlineData hoặc fileData.fileUri.

Cấu hình thinking (reasoning)

Các model Gemini có thể thực hiện reasoning nội bộ trước khi tạo phản hồi. Phương thức điều khiển phụ thuộc vào thế hệ model.
Các model Gemini 3 sử dụng thinkingLevel để kiểm soát độ sâu reasoning. Các mức khả dụng: MINIMAL, LOW, MEDIUM, HIGH.Sử dụng gemini-3-flash-preview làm model ví dụ mặc định trừ khi bạn thực sự cần một biến thể Gemini 3 khác.
curl "https://api.cometapi.com/v1beta/models/gemini-3-flash-preview:generateContent" \
  -H "Content-Type: application/json" \
  -H "x-goog-api-key: $COMETAPI_KEY" \
  -d '{
    "contents": [{"parts": [{"text": "Explain quantum physics simply."}]}],
    "generationConfig": {
      "thinkingConfig": {"thinkingLevel": "LOW"}
    }
  }'
Việc dùng thinkingLevel với các model Gemini 2.5 (hoặc thinkingBudget với các model Gemini 3) có thể gây ra lỗi. Hãy dùng đúng tham số cho phiên bản model của bạn.

Stream phản hồi

Để nhận Server-Sent Events khi model đang tạo nội dung, hãy dùng streamGenerateContent?alt=sse làm operator. Mỗi sự kiện SSE chứa một dòng data: với một đối tượng JSON GenerateContentResponse.
curl "https://api.cometapi.com/v1beta/models/gemini-3-flash-preview:streamGenerateContent?alt=sse" \
  -H "Content-Type: application/json" \
  -H "x-goog-api-key: $COMETAPI_KEY" \
  --no-buffer \
  -d '{
    "contents": [{"parts": [{"text": "Write a short poem about the stars"}]}]
  }'

Đặt hướng dẫn hệ thống

Để định hướng hành vi của model trong toàn bộ cuộc hội thoại, hãy dùng systemInstruction:
curl "https://api.cometapi.com/v1beta/models/gemini-3-flash-preview:generateContent" \
  -H "Content-Type: application/json" \
  -H "x-goog-api-key: $COMETAPI_KEY" \
  -d '{
    "contents": [{"parts": [{"text": "What is 2+2?"}]}],
    "systemInstruction": {
      "parts": [{"text": "You are a math tutor. Always show your work."}]
    }
  }'

Yêu cầu đầu ra JSON

Để buộc đầu ra JSON có cấu trúc, hãy đặt responseMimeType. Bạn cũng có thể cung cấp responseSchema để xác thực schema nghiêm ngặt:
curl "https://api.cometapi.com/v1beta/models/gemini-3-flash-preview:generateContent" \
  -H "Content-Type: application/json" \
  -H "x-goog-api-key: $COMETAPI_KEY" \
  -d '{
    "contents": [{"parts": [{"text": "List 3 planets with their distances from the sun"}]}],
    "generationConfig": {
      "responseMimeType": "application/json"
    }
  }'

Để bật tìm kiếm web theo thời gian thực, hãy thêm một công cụ googleSearch:
curl "https://api.cometapi.com/v1beta/models/gemini-3-flash-preview:generateContent" \
  -H "Content-Type: application/json" \
  -H "x-goog-api-key: $COMETAPI_KEY" \
  -d '{
    "contents": [{"parts": [{"text": "Who won the euro 2024?"}]}],
    "tools": [{"google_search": {}}]
  }'
Phản hồi bao gồm groundingMetadata với URL nguồn và điểm độ tin cậy.

Ví dụ phản hồi

Một phản hồi điển hình từ endpoint Gemini của CometAPI:
{
  "candidates": [
    {
      "content": {
        "role": "model",
        "parts": [{"text": "Hello"}]
      },
      "finishReason": "STOP",
      "avgLogprobs": -0.0023
    }
  ],
  "usageMetadata": {
    "promptTokenCount": 5,
    "candidatesTokenCount": 1,
    "totalTokenCount": 30,
    "trafficType": "ON_DEMAND",
    "thoughtsTokenCount": 24,
    "promptTokensDetails": [{"modality": "TEXT", "tokenCount": 5}],
    "candidatesTokensDetails": [{"modality": "TEXT", "tokenCount": 1}]
  },
  "modelVersion": "gemini-3-flash-preview",
  "createTime": "2026-03-25T04:21:43.756483Z",
  "responseId": "CeynaY3LDtvG4_UP0qaCuQY"
}
Trường thoughtsTokenCount trong usageMetadata cho biết model đã dùng bao nhiêu token cho suy luận nội bộ, ngay cả khi đầu ra suy nghĩ không được đưa vào phản hồi.

So sánh với endpoint tương thích OpenAI

Tính năngGemini Native (/v1beta/models/...)Tương thích OpenAI (/v1/chat/completions)
Điều khiển thinkingthinkingConfig với thinkingLevel / thinkingBudgetKhông khả dụng
Grounding với Google Searchtools: [\{"google_search": \{\}\}]Không khả dụng
Grounding với Google Mapstools: [\{"googleMaps": \{\}\}]Không khả dụng
Phương thức image generationresponseModalities: ["IMAGE"]Không khả dụng
Header xác thựcx-goog-api-key hoặc BearerChỉ Bearer
Định dạng phản hồiĐịnh dạng gốc Gemini (candidates, parts)Định dạng OpenAI (choices, message)

Ủy quyền

x-goog-api-key
string
header
bắt buộc

Your CometAPI key passed via the x-goog-api-key header. Bearer token authentication (Authorization: Bearer $COMETAPI_KEY) is also supported.

Tham số đường dẫn

model
string
bắt buộc

Gemini model ID. Example: gemini-3-flash-preview, gemini-2.5-pro. See the Models page for current options.

operator
enum<string>
bắt buộc

The operation to perform. Use generateContent for synchronous responses, or streamGenerateContent?alt=sse for Server-Sent Events streaming.

Tùy chọn có sẵn:
generateContent,
streamGenerateContent?alt=sse

Nội dung

application/json
contents
object[]
systemInstruction
object

System instructions that guide the model's behavior across the entire conversation. Text only.

tools
object[]

Tools the model may use to generate responses. Supports function declarations, Google Search, Google Maps, and code execution.

toolConfig
object

Configuration for tool usage, such as function calling mode.

safetySettings
object[]

Safety filter settings. Override default thresholds for specific harm categories.

generationConfig
object

Configuration for model generation behavior including temperature, output length, and response format.

cachedContent
string

The name of cached content to use as context. Format: cachedContents/{id}. See the Gemini context caching documentation for details.

Phản hồi

200 - application/json

Successful response. For streaming requests, the response is a stream of SSE events, each containing a GenerateContentResponse JSON object prefixed with data:.

candidates
object[]

The generated response candidates.

promptFeedback
object

Feedback on the prompt, including safety blocking information.

usageMetadata
object

Token usage statistics for the request.

modelVersion
string

The model version that generated this response.

createTime
string

The timestamp when this response was created (ISO 8601 format).

responseId
string

Unique identifier for this response.