İçeriğe geç
ajan.io

Belgeler menüsü

Bu sayfada

Google Completion API

ajan'ın public API'si üzerinden Google Gemini modelleriyle metin üretin. Normal ve streaming completion'ları destekler; resmi Vertex AI SDK'leriyle (Python / Node) tam uyumludur.

Google Completion Endpoint (v1beta)

Başlamadan önce

  • API key: API'yi kullanmak için bir personal API key oluşturun veya workspace admin'inizden Completion API kapsamına sahip bir workspace API anahtarı isteyin.

Base URL

https://api.ajan.io/google/{region}/v1beta/models/{model}:generateContent

Dedicated deployments Tüm isteklerde api.ajan.com'u /api/public ile değiştirin.

Nasıl çalışır

Bu endpoint, Google Vertex AI'da barındırılan Google Gemini modellerini açığa çıkarır.\ Resmi Vertex generateContent API'sinin yapısını yansıtır. Kullanmak için:

Kullanılabilir modelleri alın

Gemini modellerinin listesini almak için GET /{region}/v1beta/models/ çağırın.

Bir model ve action seçin

Bir model ID seçin ve generateContent ile streamGenerateContent arasında karar verin.

İsteğinizi gönderin

Prompt'unuzu contents içinde göndererek /{region}/v1beta/models/{model}:{action} adresine POST yapın.

Yanıtı işleyin

Normal çağrılar için JSON yanıtını ayrıştırın veya streaming için SSE event'lerini tüketin.

• Bölge seçimi (eu veya us)\ • Google Python SDK ile aynı event etiketlerini kullanan isteğe bağlı Server-Sent Event (SSE) streaming (message_start, message_delta, message_stop)\ • Bir models discovery endpoint'i

Authentication

ajan API Key kullanırken aşağıdaki header'lardan birini gönderin:

Bearer \

Aynı API anahtarı için alternatif header.

Resmi google-generative-ai Python SDK'sinin kullandığı kolaylık header'ı.

Tüm header'lar aynı şekilde işlenir. Eksik veya geçersiz anahtarlar 401 Unauthorized döndürür.

Authorization header örneği:

bash
curl -H "Authorization: Bearer $LD_API_KEY" \
     https://api.ajan.io/google/eu/v1beta/models

x-api-key header örneği:

bash
curl -H "x-api-key: $LD_API_KEY" \
     https://api.ajan.io/google/eu/v1beta/models

x-goog-api-key header örneği:

bash
curl -H "x-goog-api-key: $LD_API_KEY" \
     https://api.ajan.io/google/eu/v1beta/models

1. Kullanılabilir modelleri listele

GET /{region}/v1beta/models

region değeri eu veya us olmalıdır.

Successful response

Aşağıdaki şekle sahip nesnelerin listesi:

  • name – Tam nitelikli model adı (ör. models/gemini-2.5-flash).
  • supportedGenerationMethods – Her zaman ["generateContent", "streamGenerateContent"].
bash
curl -H "Authorization: Bearer $LD_API_KEY" \
     https://api.ajan.io/google/eu/v1beta/models

2. İçerik üret

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

• model – models endpoint'inin döndürdüğü model ID (models/ öneki olmadan).\ • action – Streaming kullanıp kullanmadığınıza göre generateContent veya streamGenerateContent.

Örnek path: google/eu/v1beta/models/gemini-2.5-flash:streamGenerateContent

Request body

İstek gövdesi resmi GenerateContentRequest yapısını izler.

Required fields

contents (Content[], required)\ Konuşma geçmişi. Her nesnenin bir role (string) değeri ve text (string) içeren nesnelerden oluşan bir parts dizisi vardır.

json
"contents": [
  {
    "role": "user", 
    "parts": [
      {
        "text": "What's the weather like?"
      }
    ]
  }
]

Parts ayrıca function calling için functionCall ve functionResponse nesneleri de olabilir. Gemini 3 modeli kullandığınızda, modelin functionCall part'ından gelen thoughtSignature (ve function-call id) değerini sonraki isteğinizde değiştirmeden döndürün. Resmi SDK'ler bunu sizin için yapar; istekleri elle oluşturuyorsanız alanları olduğu gibi kopyalayın.

model (string, required)\ Üretim için kullanılacak model (ör. "gemini-2.5-pro", "gemini-2.5-flash").

Optional fields

generationConfig (object, optional)\ Metin üretimi yapılandırması. Desteklenen alanlar:

  • temperature (number): Rastgeleliği kontrol eder (0.0-2.0)
  • topP (number): Nucleus sampling parametresi (0.0-1.0)
  • topK (number): Top-k sampling parametresi
  • candidateCount (number): Üretilecek yanıt adaylarının sayısı
  • maxOutputTokens (number): Üretilecek maksimum token sayısı
  • stopSequences (string[]): Üretimi durduracak diziler
  • responseMimeType (string): Yanıtın MIME türü
  • responseSchema (object): Yapılandırılmış çıktı için şema
json
"generationConfig": {
  "temperature": 0.7,
  "topP": 0.9,
  "topK": 40,
  "maxOutputTokens": 1000,
  "stopSequences": ["END", "STOP"]
}

safetySettings (SafetySetting[], optional)\ Güvenlik ayarı nesnelerinin dizisi. Her nesne şunları içerir:

  • category (string): Zarar kategorisi (ör. "HARM_CATEGORY_HARASSMENT")
  • threshold (string): Engelleme eşiği (ör. "BLOCK_MEDIUM_AND_ABOVE")
json
"safetySettings": [
  {
    "category": "HARM_CATEGORY_HARASSMENT",
    "threshold": "BLOCK_MEDIUM_AND_ABOVE"
  }
]

tools (Tool[], optional)\ Function calling için tool nesnelerinin dizisi. Her tool, şunları içeren bir functionDeclarations dizisi barındırır:

  • name (string): Fonksiyon adı
  • description (string): Fonksiyon açıklaması
  • parameters (object): Fonksiyon parametrelerini tanımlayan JSON şeması
json
"tools": [
  {
    "functionDeclarations": [
      {
        "name": "get_weather",
        "description": "Get current weather information",
        "parameters": {
          "type": "object",
          "properties": {
            "location": {
              "type": "string",
              "description": "City name"
            }
          }
        }
      }
    ]
  }
]

toolConfig (object, optional)\ Function calling yapılandırması. Şunları içeren functionCallingConfig barındırır:

  • mode (string): Function calling modu ("ANY", "AUTO", "NONE")
  • allowedFunctionNames (string[]): İzin verilen fonksiyon adlarının dizisi
json
"toolConfig": {
  "functionCallingConfig": {
    "mode": "ANY",
    "allowedFunctionNames": ["get_weather"]
  }
}

systemInstruction (string | Content, optional)\ Modelin davranışını yönlendiren sistem talimatı. String veya role ve parts içeren bir Content nesnesi olabilir.

json
"systemInstruction": {
  "role": "system",
  "parts": [
    {
      "text": "You are a weather agent. Use the weather tool when asked about weather."
    }
  ]
}

toolConfig.functionCallingConfig.allowedFunctionNames sağlanırsa mode mutlaka ANY olmalıdır.

Minimal example

bash
curl -X POST \
     -H "Content-Type: application/json" \
     -H "Authorization: Bearer $LD_API_KEY" \
     https://api.ajan.io/google/us/v1beta/models/gemini-2.5-pro:generateContent \
     -d '{
       "contents": [{
         "role": "user",
         "parts": [{"text": "Write a short poem about the ocean."}]
       }]
     }'

Streaming

action streamGenerateContent olduğunda endpoint, uyumlu event'lerle bir text/event-stream döndürür:

• message_start – içerik içeren ilk chunk\ • message_delta – sonraki chunk'lar\ • message_stop – son chunk (finishReason ve usage metadata içerir)

Örnek message_delta event'i:

event: message_delta
data: {
  "candidates": [
    {
      "index": 0,
      "content": {
        "role": "model",
        "parts": [{ "text": "The ocean whispers..." }]
      }
    }
  ]
}

Function calling ile Python SDK örneği:

python
import google.generativeai as genai

def get_current_weather(location):
    """Get the current weather in a given location"""
    return f"The current weather in {location} is sunny with a temperature of 70 degrees and a wind speed of 5 mph."

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

    transport="rest",  
    client_options={"api_endpoint": "https://api.ajan.io/google//"},
)

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

response = model.generate_content(
    "Please tell me the weather in San Francisco, then tell me a story on the history of the city"
)

print(response)

Python SDK streaming örneği:

python
model = genai.GenerativeModel("gemini-2.5-flash")

response = model.generate_content(
    "Tell me an elaborate story on the history of the city of San Francisco",
    stream=True,
)

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

Google uyumlu kütüphaneleri kullanma

Endpoint; Vertex AI Node SDK (@google-cloud/vertexai), Google Generative AI Python kütüphanesi (google-generative-ai) ve edge streaming için Vercel AI SDK dahil resmi Google SDK'leriyle tam uyumludur.

ajan, API anahtarınızı korumak ve uygulamalarınızın güvenliğini sağlamak için tarayıcı kaynaklı istekleri bilinçli olarak engeller. Daha fazla bilgi için API Key Best Practices kılavuzuna bakın.

OpenAPI

openapi: 3.0.0
info:
  title: ajan API
  version: 3.0.0
servers:
  - url: https://api.ajan.io
    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: >-
                    Conversation history. Parts may be text, functionCall, or
                    functionResponse.
                  items:
                    type: object
                    properties:
                      role:
                        type: string
                        enum:
                          - user
                          - model
                      parts:
                        type: array
                        items:
                          type: object
                          properties:
                            text:
                              type: string
                            thoughtSignature:
                              type: string
                              description: >-
                                Return unchanged on the follow-up turn (required
                                for Gemini 3).
                            functionCall:
                              type: object
                              properties:
                                name:
                                  type: string
                                args:
                                  type: object
                                id:
                                  type: string
                                  description: >-
                                    Return unchanged on the follow-up turn
                                    (required for Gemini 3).
                            functionResponse:
                              type: object
                              properties:
                                name:
                                  type: string
                                response:
                                  type: object
                                id:
                                  type: string
                                  description: >-
                                    Return unchanged on the follow-up turn
                                    (required for Gemini 3).
              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"