Перейти к основному содержанию
POST
/
v1beta
/
models
/
{model}
:
{operator}
from google import genai

client = genai.Client(
    api_key="<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
          }
        ]
      },
      "finishReason": "STOP",
      "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": {
    "blockReason": "SAFETY",
    "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 поддерживает нативный формат API Gemini, предоставляя вам полный доступ к функциям, специфичным для Gemini, таким как управление thinking, grounding через Google Search, нативные modality генерации изображений и многое другое. Используйте этот endpoint, когда вам нужны возможности, недоступные через чат-эндпоинт, совместимый с OpenAI.
Для аутентификации поддерживаются оба заголовка: x-goog-api-key и Authorization: Bearer.

Быстрый старт

Чтобы использовать любой SDK Gemini или HTTP-клиент с CometAPI, замените базовый URL и API key:
SettingGoogle DefaultCometAPI
Base URLgenerativelanguage.googleapis.comapi.cometapi.com
API Key$GEMINI_API_KEY$COMETAPI_KEY

Настройка thinking (reasoning)

Модели Gemini могут выполнять внутреннее reasoning перед генерацией ответа. Метод управления зависит от поколения модели.
Модели Gemini 3 используют thinkingLevel для управления глубиной reasoning. Доступные уровни: MINIMAL, LOW, MEDIUM, HIGH.Используйте gemini-3-flash-preview как модель-пример по умолчанию, если вам не нужен конкретный другой вариант Gemini 3.
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"}
    }
  }'
Использование thinkingLevel с моделями Gemini 2.5 (или thinkingBudget с моделями Gemini 3) может вызывать ошибки. Используйте правильный параметр для версии вашей модели.

Потоковые ответы

Чтобы получать Server-Sent Events по мере генерации контента моделью, используйте streamGenerateContent?alt=sse в качестве operator. Каждое SSE-событие содержит строку data: с 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"}]}]
  }'

Задание system instructions

Чтобы направлять поведение модели на протяжении всего разговора, используйте 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."}]
    }
  }'

Запрос вывода в JSON

Чтобы принудительно получить структурированный JSON-вывод, задайте responseMimeType. При необходимости можно также указать responseSchema для строгой валидации схемы:
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"
    }
  }'

Чтобы включить веб-поиск в реальном времени, добавьте инструмент 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": {}}]
  }'
Ответ включает groundingMetadata с URL-адресами источников и оценками уверенности.

Пример ответа

Типичный ответ от endpoint Gemini в 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"
}
Поле thoughtsTokenCount в usageMetadata показывает, сколько Token модель потратила на внутреннее reasoning, даже если thinking-вывод не включён в ответ.

Сравнение с endpoint, совместимым с OpenAI

FeatureGemini Native (/v1beta/models/...)OpenAI-Compatible (/v1/chat/completions)
Thinking controlthinkingConfig with thinkingLevel / thinkingBudgetНедоступно
Google Search groundingtools: [\{"google_search": \{\}\}]Недоступно
Google Maps groundingtools: [\{"googleMaps": \{\}\}]Недоступно
Image generation modalityresponseModalities: ["IMAGE"]Недоступно
Auth headerx-goog-api-key or BearerТолько Bearer
Response formatGemini native (candidates, parts)Формат OpenAI (choices, message)

Авторизации

x-goog-api-key
string
header
обязательно

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

Параметры пути

model
string
обязательно

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

operator
enum<string>
обязательно

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

Доступные опции:
generateContent,
streamGenerateContent?alt=sse

Тело

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.

Ответ

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.