Passer au contenu 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
          }
        ]
      },
      "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>"
}

Documentation Index

Fetch the complete documentation index at: https://apidoc.cometapi.com/llms.txt

Use this file to discover all available pages before exploring further.

CometAPI prend en charge le format natif de l’API Gemini, vous offrant un accès complet aux fonctionnalités propres à Gemini comme le contrôle du raisonnement, l’ancrage Google Search, les modalités natives de génération d’images, et plus encore. Utilisez ce endpoint lorsque vous avez besoin de capacités qui ne sont pas disponibles via le endpoint de chat compatible OpenAI.
Les en-têtes x-goog-api-key et Authorization: Bearer sont tous deux pris en charge pour l’authentification.

Démarrage rapide

Pour utiliser n’importe quel SDK Gemini ou client HTTP avec CometAPI, remplacez l’URL de base et la clé API :
ParamètreValeur par défaut GoogleCometAPI
URL de basegenerativelanguage.googleapis.comapi.cometapi.com
Clé API$GEMINI_API_KEY$COMETAPI_KEY

Configurer le raisonnement

Les modèles Gemini peuvent effectuer un raisonnement interne avant de générer une réponse. La méthode de contrôle dépend de la génération du modèle.
Les modèles Gemini 3 utilisent thinkingLevel pour contrôler la profondeur du raisonnement. Niveaux disponibles : MINIMAL, LOW, MEDIUM, HIGH.Utilisez gemini-3-flash-preview comme modèle d’exemple par défaut, sauf si vous avez spécifiquement besoin d’une autre variante de 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"}
    }
  }'
L’utilisation de thinkingLevel avec les modèles Gemini 2.5 (ou de thinkingBudget avec les modèles Gemini 3) peut provoquer des erreurs. Utilisez le paramètre approprié à votre version de modèle.

Diffuser les réponses en streaming

Pour recevoir des événements Server-Sent Events pendant que le modèle génère du contenu, utilisez streamGenerateContent?alt=sse comme opérateur. Chaque événement SSE contient une ligne data: avec un objet 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"}]}]
  }'

Définir des instructions système

Pour guider le comportement du modèle sur l’ensemble de la conversation, utilisez 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."}]
    }
  }'

Sortie JSON de la requête

Pour forcer une sortie JSON structurée, définissez responseMimeType. Vous pouvez aussi fournir un responseSchema pour une validation stricte du schéma :
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"
    }
  }'

Pour activer la recherche web en temps réel, ajoutez un outil 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": {}}]
  }'
La réponse inclut groundingMetadata avec les URL des sources et les scores de confiance.

Exemple de réponse

Une réponse typique du point de terminaison Gemini de 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"
}
Le champ thoughtsTokenCount dans usageMetadata indique combien de tokens le modèle a consacrés à son raisonnement interne, même lorsque la sortie de réflexion n’est pas incluse dans la réponse.

Comparer avec le point de terminaison compatible OpenAI

FonctionnalitéGemini Native (/v1beta/models/...)Compatible OpenAI (/v1/chat/completions)
Contrôle de la réflexionthinkingConfig avec thinkingLevel / thinkingBudgetNon disponible
Ancrage Google Searchtools: [\{"google_search": \{\}\}]Non disponible
Ancrage Google Mapstools: [\{"googleMaps": \{\}\}]Non disponible
Modalité de génération d’imageresponseModalities: ["IMAGE"]Non disponible
En-tête d’authentificationx-goog-api-key ou BearerBearer uniquement
Format de réponseFormat natif Gemini (candidates, parts)Format OpenAI (choices, message)

Autorisations

x-goog-api-key
string
header
requis

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

Paramètres de chemin

model
string
requis

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

operator
enum<string>
requis

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

Options disponibles:
generateContent,
streamGenerateContent?alt=sse

Corps

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.

Réponse

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.