Ana içeriğe atla
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-2.5-flash",
    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>"
}

Genel Bakış

CometAPI, Gemini yerel API formatını destekler ve size thinking kontrolü, Google Search grounding, yerel görsel üretim modaliteleri ve daha fazlası gibi Gemini’ye özgü özelliklere tam erişim sağlar. OpenAI uyumlu chat endpoint’i üzerinden sunulmayan yeteneklere ihtiyaç duyduğunuzda bu endpoint’i kullanın.

Hızlı Başlangıç

Herhangi bir Gemini SDK’sında veya HTTP istemcisinde base URL ile API anahtarını değiştirin:
AyarGoogle VarsayılanıCometAPI
Base URLgenerativelanguage.googleapis.comapi.cometapi.com
API Key$GEMINI_API_KEY$COMETAPI_KEY
Kimlik doğrulama için hem x-goog-api-key hem de Authorization: Bearer başlıkları desteklenir.

Thinking (Reasoning)

Gemini modelleri, bir yanıt üretmeden önce dahili reasoning gerçekleştirebilir. Kontrol yöntemi model nesline bağlıdır.
Gemini 3 modelleri, reasoning derinliğini kontrol etmek için thinkingLevel kullanır. Kullanılabilir seviyeler: MINIMAL, LOW, MEDIUM, HIGH.
curl "https://api.cometapi.com/v1beta/models/gemini-3.1-pro-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"}
    }
  }'
Gemini 2.5 modelleriyle thinkingLevel kullanmak (veya Gemini 3 modelleriyle thinkingBudget kullanmak) hatalara neden olabilir. Model sürümünüz için doğru parametreyi kullanın.

Streaming

Model içerik üretirken Server-Sent Events almak için operatör olarak streamGenerateContent?alt=sse kullanın. Her SSE olayı, JSON GenerateContentResponse nesnesi içeren bir data: satırı barındırır.
curl "https://api.cometapi.com/v1beta/models/gemini-2.5-flash: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

Tüm konuşma boyunca modelin davranışını systemInstruction ile yönlendirin:
curl "https://api.cometapi.com/v1beta/models/gemini-2.5-flash: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 Mode

Yapılandırılmış JSON çıktısını responseMimeType ile zorlayın. İsteğe bağlı olarak, katı şema doğrulaması için bir responseSchema sağlayabilirsiniz:
curl "https://api.cometapi.com/v1beta/models/gemini-2.5-flash: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"
    }
  }'

Google Search Grounding

Bir googleSearch aracı ekleyerek gerçek zamanlı web aramasını etkinleştirin:
curl "https://api.cometapi.com/v1beta/models/gemini-2.5-flash: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": {}}]
  }'
Yanıt, kaynak URL’leri ve güven skorlarıyla birlikte groundingMetadata içerir.

Yanıt Örneği

CometAPI’nin Gemini endpoint’inden tipik bir yanıt:
{
  "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-2.5-flash",
  "createTime": "2026-03-25T04:21:43.756483Z",
  "responseId": "CeynaY3LDtvG4_UP0qaCuQY"
}
usageMetadata içindeki thoughtsTokenCount alanı, düşünme çıktısı yanıta dahil edilmese bile modelin dahili akıl yürütme için kaç token harcadığını gösterir.

OpenAI-Compatible Endpoint’ten Temel Farklar

ÖzellikGemini Native (/v1beta/models/...)OpenAI-Compatible (/v1/chat/completions)
Thinking kontrolüthinkingConfig ile thinkingLevel / thinkingBudgetMevcut değil
Google Search groundingtools: [\{"google_search": \{\}\}]Mevcut değil
Google Maps groundingtools: [\{"googleMaps": \{\}\}]Mevcut değil
Görsel oluşturma modality’siresponseModalities: ["IMAGE"]Mevcut değil
Auth headerx-goog-api-key veya BearerYalnızca Bearer
Yanıt biçimiGemini native (candidates, parts)OpenAI biçimi (choices, message)

Yetkilendirmeler

x-goog-api-key
string
header
gerekli

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

Yol Parametreleri

model
string
gerekli

The Gemini model ID to use. See the Models page for current Gemini model IDs.

Örnek:

"gemini-2.5-flash"

operator
enum<string>
gerekli

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

Mevcut seçenekler:
generateContent,
streamGenerateContent?alt=sse
Örnek:

"generateContent"

Gövde

application/json
contents
object[]
gerekli

The conversation history and current input. For single-turn queries, provide a single item. For multi-turn conversations, include all previous turns.

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.

Yanıt

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.