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

# Google Completion API

> Generiere Text mit Google Gemini-Modellen über Langdocks öffentliche API. Unterstützt normale und Streaming-Completions und ist vollständig kompatibel mit den offiziellen Vertex AI SDKs (Python / Node).

<Info>
  **⚠️ Du nutzt unsere API in einem Dedicated Deployment?** Ersetze einfach `api.langdock.com` durch die Base URL deines Deployments: **`<deployment-url>/api/public`**
</Info>

# Google Completion Endpoint (v1beta)

Dieser Endpoint stellt Google Gemini-Modelle zur Verfügung, die in Google Vertex AI gehostet werden.
Er spiegelt die Struktur der offiziellen Vertex **generateContent** API wider. Um ihn zu verwenden, musst du:

<Steps>
  <Step title="Verfügbare Modelle abrufen">
    Rufe <code>GET /{`region`}/v1beta/models/</code> auf, um die Liste der Gemini-Modelle abzurufen.
  </Step>

  <Step title="Modell & Aktion auswählen">
    Wähle eine Modell-ID und entscheide zwischen <code>generateContent</code> oder <code>streamGenerateContent</code>.
  </Step>

  <Step title="Anfrage senden">
    POST an <code>/{`region`}/v1beta/models/{`model`}:{`action`}</code> mit deinem Prompt in <code>contents</code>.
  </Step>

  <Step title="Antwort verarbeiten">
    Parse die JSON-Antwort für normale Aufrufe oder konsumiere die SSE-Events für Streaming.
  </Step>
</Steps>

• Regionswahl (`eu` oder `us`)\
• Optionales Server-Sent Event (SSE) Streaming mit denselben Event-Labels wie im Google Python SDK (`message_start`, `message_delta`, `message_stop`)\
• Ein **models** Discovery-Endpoint

## Authentifizierung

Sende einen der folgenden Header mit deinem Langdock API Key:

<ParamField name="Authorization" type="string" required>
  Bearer \<LANGDOCK\_API\_KEY>
</ParamField>

<ParamField name="x-api-key" type="string" required={false}>
  Alternativer Header für denselben API-Schlüssel.
</ParamField>

<ParamField name="x-goog-api-key" type="string" required={false}>
  Convenience-Header verwendet vom offiziellen **google-generative-ai** Python SDK.
</ParamField>

Alle Header werden identisch behandelt. Fehlende oder ungültige Schlüssel geben **401 Unauthorized** zurück.

**Authorization Header Beispiel:**

```bash theme={null}
curl -H "Authorization: Bearer $LD_API_KEY" \
     https://api.langdock.com/google/eu/v1beta/models
```

**x-api-key Header Beispiel:**

```bash theme={null}
curl -H "x-api-key: $LD_API_KEY" \
     https://api.langdock.com/google/eu/v1beta/models
```

**x-goog-api-key Header Beispiel:**

```bash theme={null}
curl -H "x-goog-api-key: $LD_API_KEY" \
     https://api.langdock.com/google/eu/v1beta/models
```

***

## 1. Verfügbare Modelle auflisten

### GET `/{region}/v1beta/models`

`region` muss `eu` oder `us` sein.

#### Erfolgreiche Antwort

<ResponseField name="models" type="array">
  Liste von Objekten mit der folgenden Struktur:

  * **name** – Vollständig qualifizierter Modellname (z.B. `models/gemini-2.5-flash`).
  * **supportedGenerationMethods** – Immer `["generateContent", "streamGenerateContent"]`.
</ResponseField>

```bash theme={null}
curl -H "Authorization: Bearer $LD_API_KEY" \
     https://api.langdock.com/google/eu/v1beta/models
```

***

## 2. Content generieren

### POST `/{region}/v1beta/models/{model}:{action}`

• **model** – Die Modell-ID wie vom *models* Endpoint zurückgegeben (ohne das `models/` Präfix).\
• **action** – `generateContent` **oder** `streamGenerateContent` je nachdem, ob du Streaming verwenden möchtest oder nicht.

Beispiel-Pfad: `google/eu/v1beta/models/gemini-2.5-flash:streamGenerateContent`

### Request Body

Der Request Body folgt der offiziellen
[`GenerateContentRequest`](https://docs.cloud.google.com/vertex-ai/generative-ai/docs/model-reference/inference) Struktur.

#### Pflichtfelder

**`contents`** (Content\[], erforderlich)\
Gesprächsverlauf. Jedes Objekt hat eine **role** (string) und **parts** Array mit Objekten, die **text** (string) enthalten.

```json theme={null}
"contents": [
  {
    "role": "user", 
    "parts": [
      {
        "text": "Wie ist das Wetter?"
      }
    ]
  }
]
```

**`model`** (string, erforderlich)\
Das Modell für die Generierung (z.B. "gemini-2.5-pro", "gemini-2.5-flash").

#### Optionale Felder

**`generationConfig`** (object, optional)\
Konfiguration für die Textgenerierung. Unterstützte Felder:

* `temperature` (number): Steuert Zufälligkeit (0.0-2.0)
* `topP` (number): Nucleus-Sampling-Parameter (0.0-1.0)
* `topK` (number): Top-k-Sampling-Parameter
* `candidateCount` (number): Anzahl der zu generierenden Antwort-Kandidaten
* `maxOutputTokens` (number): Maximale Anzahl zu generierender Token
* `stopSequences` (string\[]): Sequenzen, die die Generierung stoppen
* `responseMimeType` (string): MIME-Typ der Antwort
* `responseSchema` (object): Schema für strukturierte Ausgabe

```json theme={null}
"generationConfig": {
  "temperature": 0.7,
  "topP": 0.9,
  "topK": 40,
  "maxOutputTokens": 1000,
  "stopSequences": ["END", "STOP"]
}
```

**`safetySettings`** (SafetySetting\[], optional)\
Array von Safety-Setting-Objekten. Jedes Objekt enthält:

* `category` (string): Die Harm-Kategorie (z.B. "HARM\_CATEGORY\_HARASSMENT")
* `threshold` (string): Der Blocking-Schwellwert (z.B. "BLOCK\_MEDIUM\_AND\_ABOVE")

```json theme={null}
"safetySettings": [
  {
    "category": "HARM_CATEGORY_HARASSMENT",
    "threshold": "BLOCK_MEDIUM_AND_ABOVE"
  }
]
```

**`tools`** (Tool\[], optional)\
Array von Tool-Objekten für Function Calling. Jedes Tool enthält ein `functionDeclarations` Array mit:

* `name` (string): Funktionsname
* `description` (string): Funktionsbeschreibung
* `parameters` (object): JSON-Schema, das Funktionsparameter definiert

```json theme={null}
"tools": [
  {
    "functionDeclarations": [
      {
        "name": "get_weather",
        "description": "Aktuelle Wetterinformationen abrufen",
        "parameters": {
          "type": "object",
          "properties": {
            "location": {
              "type": "string",
              "description": "Stadtname"
            }
          }
        }
      }
    ]
  }
]
```

**`toolConfig`** (object, optional)\
Konfiguration für Function Calling. Enthält `functionCallingConfig` mit:

* `mode` (string): Function-Calling-Modus ("ANY", "AUTO", "NONE")
* `allowedFunctionNames` (string\[]): Array erlaubter Funktionsnamen

```json theme={null}
"toolConfig": {
  "functionCallingConfig": {
    "mode": "ANY",
    "allowedFunctionNames": ["get_weather"]
  }
}
```

**`systemInstruction`** (string | Content, optional)\
Systemanweisung zur Steuerung des Modellverhaltens. Kann ein String oder Content-Objekt mit Rolle und Teilen sein.

```json theme={null}
"systemInstruction": {
  "role": "system",
  "parts": [
    {
      "text": "Du bist ein Wetter-Agent. Verwende das Wetter-Tool, wenn nach dem Wetter gefragt wird."
    }
  ]
}
```

<Info>
  Wenn `toolConfig.functionCallingConfig.allowedFunctionNames` bereitgestellt wird, **muss** `mode` `ANY` sein.
</Info>

#### Minimales Beispiel

```bash theme={null}
curl -X POST \
     -H "Content-Type: application/json" \
     -H "Authorization: Bearer $LD_API_KEY" \
     https://api.langdock.com/google/us/v1beta/models/gemini-2.5-pro:generateContent \
     -d '{
       "contents": [{
         "role": "user",
         "parts": [{"text": "Schreibe ein kurzes Gedicht über das Meer."}]
       }]
     }'
```

### Streaming

Wenn **action** `streamGenerateContent` ist, gibt der Endpoint einen
`text/event-stream` mit kompatiblen Events zurück:

• `message_start` – erster Chunk, der Content enthält\
• `message_delta` – nachfolgende Chunks\
• `message_stop` – letzter Chunk (enthält `finishReason` und Nutzungs-Metadaten)

Beispiel `message_delta` Event:

```
event: message_delta
data: {
  "candidates": [
    {
      "index": 0,
      "content": {
        "role": "model",
        "parts": [{ "text": "Das Meer flüstert..." }]
      }
    }
  ]
}
```

{/* A JSON array wrapper (`[ ... ]`) is sent around the event stream so that the
response can be consumed directly by the Google Python SDK. This might cause issues
with the first chunk event. */}

**Python SDK Beispiel mit Function Calling:**

```python theme={null}
import google.generativeai as genai

def get_current_weather(location):
    """Das aktuelle Wetter an einem gegebenen Ort abrufen"""
    return f"Das aktuelle Wetter in {location} ist sonnig mit einer Temperatur von 21 Grad und einer Windgeschwindigkeit von 8 km/h."

genai.configure(
    api_key="<YOUR_LANGDOCK_API_KEY>",

    transport="rest",  
    client_options={"api_endpoint": "https://api.langdock.com/google/<REGION>/"},
)

model = genai.GenerativeModel("gemini-2.5-flash", tools=[get_current_weather])

response = model.generate_content(
    "Bitte sag mir das Wetter in San Francisco, dann erzähl mir eine Geschichte über die Geschichte der Stadt"
)

print(response)
```

**Python SDK Streaming Beispiel:**

```python theme={null}
model = genai.GenerativeModel("gemini-2.5-flash")

response = model.generate_content(
    "Erzähl mir eine ausführliche Geschichte über die Geschichte der Stadt San Francisco",
    stream=True,
)

for chunk in response:
    if chunk.text:
        print(chunk.text)
```

## Google-kompatible Bibliotheken verwenden

Der Endpoint ist vollständig kompatibel mit offiziellen Google SDKs, einschließlich der Vertex AI Node SDK (`@google-cloud/vertexai`), der Google Generative AI Python Bibliothek (`google-generative-ai`) und der Vercel AI SDK für Edge Streaming.

<Info>
  Langdock blockiert bewusst Browser-basierte Anfragen, um deinen API-Schlüssel zu schützen und die Sicherheit deiner Anwendungen zu gewährleisten. Weitere Informationen findest du in unserem Guide zu [Best Practices für API-Schlüssel](/de/admin/ai-adoption-and-rollout/best-practices/api-key-best-practices).
</Info>


## OpenAPI

````yaml POST /google/{region}/v1beta/models/{model}:generateContent
openapi: 3.0.0
info:
  title: Langdock API
  version: 3.0.0
servers:
  - url: https://api.langdock.com
    description: Production
security:
  - bearerAuth: []
paths:
  /google/{region}/v1beta/models/{model}:generateContent:
    post:
      tags:
        - Google
      summary: Generate Content
      description: >-
        Generate content using Google Gemini models.

        This endpoint mirrors the structure of the official Vertex AI
        generateContent API while adding API-key based authentication and region
        selection.
      operationId: google_generate_content_post
      parameters:
        - name: region
          in: path
          required: true
          description: The region of the API to use.
          schema:
            type: string
            enum:
              - eu
              - us
        - name: model
          in: path
          required: true
          description: The model ID (e.g., gemini-2.5-pro, gemini-2.5-flash).
          schema:
            type: string
      requestBody:
        required: true
        content:
          application/json:
            schema:
              type: object
              properties:
                contents:
                  type: array
                  description: The content to generate a response for.
                  items:
                    type: object
                    properties:
                      role:
                        type: string
                        enum:
                          - user
                          - model
                      parts:
                        type: array
                        items:
                          type: object
                          properties:
                            text:
                              type: string
              required:
                - contents
            example:
              contents:
                - role: user
                  parts:
                    - text: Write a short haiku about the ocean.
      responses:
        '200':
          description: Successful Response
          content:
            application/json:
              schema:
                type: object
                properties:
                  candidates:
                    type: array
                    items:
                      type: object
                      properties:
                        content:
                          type: object
                        finishReason:
                          type: string
                  usageMetadata:
                    type: object
        4XX:
          description: Error response
          content:
            application/json:
              schema:
                $ref: '#/components/schemas/ErrorResponse'
      security:
        - bearerAuth: []
components:
  schemas:
    ErrorResponse:
      properties:
        type:
          default: error
          enum:
            - error
          title: Type
          type: string
        error:
          discriminator:
            mapping:
              api_error:
                $ref: '#/components/schemas/APIError'
              authentication_error:
                $ref: '#/components/schemas/AuthenticationError'
              invalid_request_error:
                $ref: '#/components/schemas/InvalidRequestError'
              not_found_error:
                $ref: '#/components/schemas/NotFoundError'
              overloaded_error:
                $ref: '#/components/schemas/OverloadedError'
              permission_error:
                $ref: '#/components/schemas/PermissionError'
              rate_limit_error:
                $ref: '#/components/schemas/RateLimitError'
            propertyName: type
          oneOf:
            - $ref: '#/components/schemas/InvalidRequestError'
            - $ref: '#/components/schemas/AuthenticationError'
            - $ref: '#/components/schemas/PermissionError'
            - $ref: '#/components/schemas/NotFoundError'
            - $ref: '#/components/schemas/RateLimitError'
            - $ref: '#/components/schemas/APIError'
            - $ref: '#/components/schemas/OverloadedError'
          title: Error
      required:
        - type
        - error
      title: ErrorResponse
      type: object
    APIError:
      properties:
        type:
          default: api_error
          enum:
            - api_error
          title: Type
          type: string
        message:
          default: Internal server error
          title: Message
          type: string
      required:
        - type
        - message
      title: APIError
      type: object
    AuthenticationError:
      properties:
        type:
          default: authentication_error
          enum:
            - authentication_error
          title: Type
          type: string
        message:
          default: Authentication error
          title: Message
          type: string
      required:
        - type
        - message
      title: AuthenticationError
      type: object
    InvalidRequestError:
      properties:
        type:
          default: invalid_request_error
          enum:
            - invalid_request_error
          title: Type
          type: string
        message:
          default: Invalid request
          title: Message
          type: string
      required:
        - type
        - message
      title: InvalidRequestError
      type: object
    NotFoundError:
      properties:
        type:
          default: not_found_error
          enum:
            - not_found_error
          title: Type
          type: string
        message:
          default: Not found
          title: Message
          type: string
      required:
        - type
        - message
      title: NotFoundError
      type: object
    OverloadedError:
      properties:
        type:
          default: overloaded_error
          enum:
            - overloaded_error
          title: Type
          type: string
        message:
          default: Overloaded
          title: Message
          type: string
      required:
        - type
        - message
      title: OverloadedError
      type: object
    PermissionError:
      properties:
        type:
          default: permission_error
          enum:
            - permission_error
          title: Type
          type: string
        message:
          default: Permission denied
          title: Message
          type: string
      required:
        - type
        - message
      title: PermissionError
      type: object
    RateLimitError:
      properties:
        type:
          default: rate_limit_error
          enum:
            - rate_limit_error
          title: Type
          type: string
        message:
          default: Rate limited
          title: Message
          type: string
      required:
        - type
        - message
      title: RateLimitError
      type: object
  securitySchemes:
    bearerAuth:
      type: http
      scheme: bearer
      bearerFormat: API Key
      description: API key as Bearer token. Format "Bearer YOUR_API_KEY"

````