> ## Documentation Index
> Fetch the complete documentation index at: https://docs.ttapi.io/llms.txt
> Use this file to discover all available pages before exploring further.

# Генерация контента Gemini

> Генерирует ответ модели в нативном REST-формате Gemini generateContent.

<Note>
  Параметры запроса и поля ответа соответствуют официальному формату Gemini API. Полную спецификацию см. в
  <a href="https://ai.google.dev/api/generate-content" target="_blank">официальной документации Google</a>.
</Note>

Передавайте текстовые и мультимодальные сообщения в `contents`. Эндпоинт также
поддерживает системные инструкции, инструменты, настройки безопасности,
кэшированный контент, структурированный вывод и параметры рассуждений.


## OpenAPI

````yaml openapi/ru/llm.json POST /v1beta/models/{model}:generateContent
openapi: 3.1.0
info:
  title: Документация API языковых моделей
  version: 1.0.0
  description: TTAPI LLM API сервис.
servers:
  - url: https://api.ttapi.io
security: []
paths:
  /v1beta/models/{model}:generateContent:
    post:
      summary: Сгенерировать контент Gemini
      description: Генерирует ответ модели в нативном REST-формате Gemini generateContent.
      operationId: generateGeminiContent
      parameters:
        - name: model
          in: path
          required: true
          description: Идентификатор модели Gemini.
          schema:
            type: string
            example: gemini-3.5-flash
      requestBody:
        required: true
        content:
          application/json:
            schema:
              $ref: '#/components/schemas/GeminiGenerateContentRequest'
      responses:
        '200':
          description: Успешный ответ Gemini GenerateContentResponse.
          content:
            application/json:
              schema:
                $ref: '#/components/schemas/GeminiGenerateContentResponse'
        '400':
          $ref: '#/components/responses/400Response'
        '401':
          $ref: '#/components/responses/401Response'
      security:
        - CustomApiKey: []
components:
  schemas:
    GeminiGenerateContentRequest:
      type: object
      description: Тело запроса в нативном REST-формате Gemini generateContent.
      properties:
        contents:
          type: array
          description: >-
            Содержимое текущего диалога. Для многошагового запроса передайте
            полную историю.
          items:
            $ref: '#/components/schemas/GeminiContent'
          minItems: 1
        tools:
          type: array
          description: >-
            Функции, выполнение кода и поддерживаемые встроенные инструменты,
            доступные модели.
          items:
            type: object
            additionalProperties: true
        toolConfig:
          type: object
          description: Общая конфигурация инструментов в этом запросе.
          additionalProperties: true
        safetySettings:
          type: array
          description: Пороговые значения блокировки по категориям безопасности.
          items:
            $ref: '#/components/schemas/GeminiSafetySetting'
        systemInstruction:
          $ref: '#/components/schemas/GeminiContent'
        generationConfig:
          $ref: '#/components/schemas/GeminiGenerationConfig'
        cachedContent:
          type: string
          example: cachedContents/abc123
          description: >-
            Ресурс кэшированного контента для контекста. Формат:
            cachedContents/{cachedContent}.
        serviceTier:
          type: string
          enum:
            - unspecified
            - standard
            - flex
            - priority
          description: Уровень обслуживания для этого запроса.
        store:
          type: boolean
          description: Переопределяет настройку журналирования запросов на уровне проекта.
      required:
        - contents
    GeminiGenerateContentResponse:
      type: object
      properties:
        candidates:
          type: array
          items:
            $ref: '#/components/schemas/GeminiCandidate'
        promptFeedback:
          type: object
          properties:
            blockReason:
              type: string
            safetyRatings:
              type: array
              items:
                type: object
                additionalProperties: true
        usageMetadata:
          $ref: '#/components/schemas/GeminiUsageMetadata'
        modelVersion:
          type: string
        responseId:
          type: string
        modelStatus:
          type: object
          additionalProperties: true
    GeminiContent:
      type: object
      properties:
        role:
          type: string
          enum:
            - user
            - model
            - system
          description: Роль автора контента. В диалоге обычно используются user и model.
        parts:
          type: array
          items:
            $ref: '#/components/schemas/GeminiPart'
          minItems: 1
      required:
        - parts
    GeminiSafetySetting:
      type: object
      properties:
        category:
          type: string
          enum:
            - HARM_CATEGORY_HARASSMENT
            - HARM_CATEGORY_HATE_SPEECH
            - HARM_CATEGORY_SEXUALLY_EXPLICIT
            - HARM_CATEGORY_DANGEROUS_CONTENT
            - HARM_CATEGORY_CIVIC_INTEGRITY
        threshold:
          type: string
          enum:
            - HARM_BLOCK_THRESHOLD_UNSPECIFIED
            - BLOCK_LOW_AND_ABOVE
            - BLOCK_MEDIUM_AND_ABOVE
            - BLOCK_ONLY_HIGH
            - BLOCK_NONE
            - 'OFF'
      required:
        - category
        - threshold
    GeminiGenerationConfig:
      type: object
      description: Настройки генерации и вывода. Доступность параметров зависит от модели.
      properties:
        stopSequences:
          type: array
          maxItems: 5
          items:
            type: string
        responseMimeType:
          type: string
          enum:
            - text/plain
            - application/json
            - text/x.enum
        responseSchema:
          type: object
          additionalProperties: true
        responseJsonSchema:
          type: object
          additionalProperties: true
        responseModalities:
          type: array
          items:
            type: string
            enum:
              - TEXT
              - IMAGE
              - AUDIO
        candidateCount:
          type: integer
          minimum: 1
          default: 1
        maxOutputTokens:
          type: integer
          minimum: 1
        temperature:
          type: number
          minimum: 0
          maximum: 2
        topP:
          type: number
          minimum: 0
          maximum: 1
        topK:
          type: integer
          minimum: 1
        seed:
          type: integer
        presencePenalty:
          type: number
        frequencyPenalty:
          type: number
        responseLogprobs:
          type: boolean
        logprobs:
          type: integer
          minimum: 0
          maximum: 20
        enableEnhancedCivicAnswers:
          type: boolean
        thinkingConfig:
          type: object
          properties:
            includeThoughts:
              type: boolean
            thinkingBudget:
              type: integer
            thinkingLevel:
              type: string
              enum:
                - THINKING_LEVEL_UNSPECIFIED
                - MINIMAL
                - LOW
                - MEDIUM
                - HIGH
        imageConfig:
          type: object
          properties:
            aspectRatio:
              type: string
            imageSize:
              type: string
              enum:
                - '512'
                - 1K
                - 2K
                - 4K
        mediaResolution:
          type: string
          enum:
            - MEDIA_RESOLUTION_UNSPECIFIED
            - MEDIA_RESOLUTION_LOW
            - MEDIA_RESOLUTION_MEDIUM
            - MEDIA_RESOLUTION_HIGH
        responseFormat:
          type: object
          additionalProperties: true
    GeminiCandidate:
      type: object
      properties:
        content:
          $ref: '#/components/schemas/GeminiContent'
        finishReason:
          type: string
          enum:
            - FINISH_REASON_UNSPECIFIED
            - STOP
            - MAX_TOKENS
            - SAFETY
            - RECITATION
            - LANGUAGE
            - OTHER
            - BLOCKLIST
            - PROHIBITED_CONTENT
            - SPII
            - MALFORMED_FUNCTION_CALL
            - IMAGE_SAFETY
            - UNEXPECTED_TOOL_CALL
        finishMessage:
          type: string
        safetyRatings:
          type: array
          items:
            type: object
            additionalProperties: true
        citationMetadata:
          type: object
          additionalProperties: true
        groundingMetadata:
          type: object
          additionalProperties: true
        avgLogprobs:
          type: number
        index:
          type: integer
    GeminiUsageMetadata:
      type: object
      properties:
        promptTokenCount:
          type: integer
        cachedContentTokenCount:
          type: integer
        candidatesTokenCount:
          type: integer
        toolUsePromptTokenCount:
          type: integer
        thoughtsTokenCount:
          type: integer
        totalTokenCount:
          type: integer
        serviceTier:
          type: string
    GeminiPart:
      type: object
      description: >-
        Одна часть контента: текст, медиа, вызов функции или результат
        выполнения кода.
      properties:
        text:
          type: string
        inlineData:
          type: object
          properties:
            mimeType:
              type: string
              example: image/jpeg
            data:
              type: string
              description: Данные в кодировке Base64.
          required:
            - mimeType
            - data
        fileData:
          type: object
          properties:
            mimeType:
              type: string
            fileUri:
              type: string
          required:
            - fileUri
        functionCall:
          type: object
          properties:
            name:
              type: string
            args:
              type: object
              additionalProperties: true
        functionResponse:
          type: object
          properties:
            name:
              type: string
            response:
              type: object
              additionalProperties: true
        executableCode:
          type: object
          additionalProperties: true
        codeExecutionResult:
          type: object
          additionalProperties: true
        thought:
          type: boolean
        thoughtSignature:
          type: string
      additionalProperties: true
  responses:
    400Response:
      description: Ошибка параметров
      content:
        application/json:
          schema:
            type: object
            properties:
              status:
                type: string
                example: FAILED
              message:
                type: string
                example: '"prompt" cannot be empty.'
              data:
                type: object
            required:
              - status
              - message
    401Response:
      description: Ошибка авторизации
      content:
        application/json:
          schema:
            type: object
            properties:
              status:
                type: string
                example: FAILED
              message:
                type: string
                example: Wrong TT-API-KEY or email is not activated.
            required:
              - status
              - message
  securitySchemes:
    CustomApiKey:
      type: apiKey
      in: header
      name: TT-API-KEY
      description: >-
        Вы можете получить API-ключ в <a href='https://dashboard.ttapi.io'
        target='_blank'>панель управления TTAPI</a>.

````