Генерация контента
Используйте нативный формат API Gemini через CometAPI для генерации текста, multimodal-ввода, reasoning, function calling, grounding через Google Search, режима JSON и streaming.
x-goog-api-key и Authorization: Bearer.Быстрый старт
Чтобы использовать любой Gemini SDK или HTTP-клиент с CometAPI, замените базовый URL и API key:Отправка видео в качестве входных данных
GeminigenerateContent принимает видео как часть content. Выберите форму входных данных в зависимости от того, где хранится видео:
inlineData.mimeType и fileData.fileUri. Не отправляйте URL-медиа как file_data.file_uri.fileData.fileUri:
generateContent, используя inlineData или fileData.fileUri.
Настройка thinking (reasoning)
Модели Gemini могут выполнять внутреннее рассуждение перед генерацией ответа. Способ управления зависит от поколения модели.- Gemini 3 (thinkingLevel)
- Gemini 2.5 (thinkingBudget)
thinkingLevel для управления глубиной рассуждения. Доступные уровни: MINIMAL, LOW, MEDIUM, HIGH.Используйте gemini-3-flash-preview в качестве модели-примера по умолчанию, если вам не нужен конкретный другой вариант Gemini 3.Потоковые Responses
Чтобы получать Server-Sent Events по мере генерации контента моделью, используйтеstreamGenerateContent?alt=sse в качестве оператора. Каждое событие SSE содержит строку data: с JSON-объектом GenerateContentResponse.
Задание system instructions
Чтобы управлять поведением модели на протяжении всего разговора, используйтеsystemInstruction:
Запрос вывода в JSON
Чтобы принудительно включить структурированный JSON-вывод, задайтеresponseMimeType. При необходимости можно также указать responseSchema для строгой валидации схемы:
Grounding с Google Search
Чтобы включить поиск в интернете в реальном времени, добавьте инструментgoogleSearch:
groundingMetadata с URL-адресами источников и оценками достоверности.
Пример ответа
Типичный ответ от Gemini endpoint в CometAPI:thoughtsTokenCount в usageMetadata показывает, сколько токенов модель потратила на внутреннее рассуждение, даже если thinking output не включён в ответ.Сравнение с OpenAI-compatible endpoint
Авторизации
Your CometAPI key passed via the x-goog-api-key header. Bearer token authentication (Authorization: Bearer $COMETAPI_KEY) is also supported.
Параметры пути
Gemini model ID. Example: gemini-3-flash-preview, gemini-2.5-pro. See the Models page for current options.
The operation to perform. Use generateContent for synchronous responses, or streamGenerateContent?alt=sse for Server-Sent Events streaming.
generateContent, streamGenerateContent?alt=sse Тело
Conversation content. Each entry has an optional role (user or model) and a parts array.
System instructions that guide the model's behavior across the entire conversation. Text only.
Tools the model may use to generate responses. Supports function declarations, Google Search, Google Maps, and code execution.
Configuration for tool usage, such as function calling mode.
Safety filter settings. Override default thresholds for specific harm categories.
Configuration for model generation behavior including temperature, output length, and response format.
The name of cached content to use as context. Format: cachedContents/{id}. See the Gemini context caching documentation for details.
Ответ
Successful response. For streaming requests, the response is a stream of SSE events, each containing a GenerateContentResponse JSON object prefixed with data:.
The generated response candidates.
Feedback on the prompt, including safety blocking information.
Token usage statistics for the request.
The model version that generated this response.
The timestamp when this response was created (ISO 8601 format).
Unique identifier for this response.