Saltar para o conteúdo principal
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>"
}
O CometAPI oferece suporte ao formato de API nativo do Gemini, dando a você acesso total a recursos específicos do Gemini, como controle de thinking, grounding com Google Search, modalidades nativas de geração de imagem e muito mais. Use este endpoint quando precisar de capacidades que não estão disponíveis por meio do endpoint de chat compatível com OpenAI.
Tanto os headers x-goog-api-key quanto Authorization: Bearer são compatíveis para autenticação.

Início rápido

Para usar qualquer SDK do Gemini ou cliente HTTP com o CometAPI, substitua a URL base e a chave de API:
ConfiguraçãoPadrão do GoogleCometAPI
URL basegenerativelanguage.googleapis.comapi.cometapi.com
Chave de API$GEMINI_API_KEY$COMETAPI_KEY

Configurar thinking (reasoning)

Os modelos Gemini podem realizar reasoning interno antes de gerar uma resposta. O método de controle depende da geração do modelo.
Os modelos Gemini 3 usam thinkingLevel para controlar a profundidade do reasoning. Níveis disponíveis: MINIMAL, LOW, MEDIUM, HIGH.Use gemini-3-flash-preview como model de exemplo padrão, a menos que você precise especificamente de uma variante diferente do 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"}
    }
  }'
Usar thinkingLevel com modelos Gemini 2.5 (ou thinkingBudget com modelos Gemini 3) pode causar erros. Use o parâmetro correto para a versão do seu modelo.

Respostas em streaming

Para receber Server-Sent Events enquanto o modelo gera conteúdo, use streamGenerateContent?alt=sse como operator. Cada evento SSE contém uma linha data: com um objeto 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"}]}]
  }'

Definir instruções de sistema

Para orientar o comportamento do modelo ao longo de toda a conversa, use 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."}]
    }
  }'

Solicitar saída JSON

Para forçar uma saída JSON estruturada, defina responseMimeType. Opcionalmente, forneça um responseSchema para validação rigorosa de schema:
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"
    }
  }'

Para habilitar pesquisa na web em tempo real, adicione uma ferramenta 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": {}}]
  }'
A resposta inclui groundingMetadata com URLs de origem e pontuações de confiança.

Exemplo de resposta

Uma resposta típica do endpoint Gemini do 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"
}
O campo thoughtsTokenCount em usageMetadata mostra quantos tokens o modelo gastou em reasoning interno, mesmo quando a saída de thinking não é incluída na resposta.

Comparar com o endpoint compatível com OpenAI

RecursoGemini nativo (/v1beta/models/...)Compatível com OpenAI (/v1/chat/completions)
Controle de thinkingthinkingConfig com thinkingLevel / thinkingBudgetNão disponível
Grounding com Google Searchtools: [\{"google_search": \{\}\}]Não disponível
Grounding com Google Mapstools: [\{"googleMaps": \{\}\}]Não disponível
Modalidade de geração de imagemresponseModalities: ["IMAGE"]Não disponível
Header de autenticaçãox-goog-api-key ou BearerApenas Bearer
Formato de respostaGemini nativo (candidates, parts)Formato OpenAI (choices, message)

Autorizações

x-goog-api-key
string
header
obrigatório

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

Parâmetros de caminho

model
string
obrigatório

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

operator
enum<string>
obrigatório

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

Opções disponíveis:
generateContent,
streamGenerateContent?alt=sse

Corpo

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.

Resposta

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.