İçeriğe geç
ajan.io

Belgeler menüsü

Bu sayfada

Agents Completions API

Vercel AI SDK uyumlu biçim kullanarak belirli bir Agent için model yanıtı oluşturur.

Belirli bir agent ID için model yanıtı oluşturur veya isteğinizde kullanılacak bir Agent yapılandırması geçirirsiniz. Bu endpoint, modern AI uygulamalarıyla sorunsuz entegrasyon için Vercel AI SDK uyumlu mesaj biçimini kullanır.

Başlamadan önce

  • Agent access: Bir agent'ı API anahtarıyla paylaşmak için bu kılavuza bakın.
  • Vercel AI SDK compatible: Bu endpoint Vercel AI SDK'nın UIMessage biçimini kullanır; useChat hook'u ve diğer Vercel AI SDK özellikleriyle uyumludur.
  • MCP: Agent'larınıza ajan MCP Server üzerinden de erişebilirsiniz; MCP uyumlu AI istemcileri agent'larınızı doğrudan çağırabilir.

Base URL

https://api.ajan.io/agent/v1/chat/completions

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

Parameters

ParameterTypeRequiredDescription
agentIdstringOne of agentId/agent requiredKullanılacak mevcut agent'ın ID'si
agentobjectOne of agentId/agent requiredGeçici agent yapılandırması
messagesarrayYesUIMessage nesneleri dizisi (Vercel AI SDK biçimi)
streambooleanNoStreaming yanıtları etkinleştir (varsayılan: false)
outputobjectNoStructured output biçim spesifikasyonu
maxStepsintegerNoMaksimum tool adımı sayısı (1-20)
imageResponseFormatstringNoAgent tarafından üretilen görüntüler için yanıt biçimi. "url" imzalı URL, "b64_json" base64 kodlu görüntü verisi döndürür.

Message Format (Vercel AI SDK UIMessage)

Agents API, modern AI çerçeveleriyle maksimum uyumluluk için Vercel AI SDK'nın UIMessage biçimini kullanır.

UIMessage Structure

messages dizisindeki her mesaj şunları içermelidir:

typescript
interface UIMessage {
  id: string;           // Unique identifier for this message
  role: 'system' | 'user' | 'assistant';
  parts: MessagePart[]; // Array of message parts
  metadata?: {          // Optional metadata
    attachments?: string[];  // Array of attachment UUIDs
  };
}

Message Part Types

User message parts (gönderme için):

TypeFieldsDescription
texttype: "text", text: stringDüz metin içeriği
filetype: "file", mediaType: string, url: string, filename?: stringSatır içi dosya referansı

Agent message parts (yanıtlarda döner — takip mesajları gönderirken konuşma geçmişine dahil edin):

TypeKey FieldsDescription
texttype: "text", text: stringMetin yanıtı
reasoningtype: "reasoning", text: stringModel reasoning / chain-of-thought
tool-{name}type: "tool-{name}", toolCallId: string, state: "input-streaming" | "input-available" | "output-available" | "output-error", input?: any, output?: any, errorText?: stringTool call ve sonuç
source-urltype: "source-url", sourceId: string, url: string, title?: stringWeb kaynak referansı
source-documenttype: "source-document", sourceId: string, mediaType: string, title: string, filename?: stringBelge kaynak referansı

Example Messages

Metin içeren kullanıcı mesajı

javascript
{
  id: "msg_1",
  role: "user",
  parts: [
    {
      type: "text",
      text: "Hello, how are you?"
    }
  ]
}

Attachment içeren kullanıcı mesajı

javascript
{
  id: "msg_2",
  role: "user",
  parts: [
    {
      type: "text",
      text: "Please analyze this document"
    }
  ],
  metadata: {
    attachments: ["550e8400-e29b-41d4-a716-446655440000"]
  }
}

Bir mesaja dosya eklemek için Upload Attachment API ile yükleyin ve dönen UUID'leri mesajın metadata.attachments dizisinde referans verin. Yüklenen attachment'lar için type: "file" part kullanmayın — bu biçim satır içi dosya referansları (ör. data URI) içindir.

Tool call içeren agent mesajı

javascript
{
  id: "msg_3",
  role: "assistant",
  parts: [
    {
      type: "tool-webSearch",
      toolCallId: "call_123",
      state: "output-available",
      input: {
        query: "latest news"
      },
      output: { /* search results */ }
    }
  ]
}

Agent Configuration

agent parametresiyle geçici bir agent oluştururken şunları belirtebilirsiniz:

  • name — Agent adı (maks. 64 karakter)
  • instructions — System talimatları (maks. 16384 karakter)
  • description — İsteğe bağlı açıklama (maks. 256 karakter)
  • temperature — 0-1 arası temperature
  • model — Kullanılacak model ID (seçenekler için Available Models)
  • capabilities — Web arama, Create & work with files, görüntü üretme, canvas gibi özellikleri etkinleştir
  • knowledgeFolderIds — Kullanılacak Knowledge base ID'leri
  • attachmentIds — Kullanılacak attachment'ları tanımlayan UUID dizisi

Configuration Notes

  • Available models: Kullanılabilir modelleri Models API ile alın.
  • Field naming: Satır içi agent yapılandırma alan adları Create ve Update Agent API'lerinden farklıdır. Bu endpoint instructions (çoğul) ve temperature kullanır; CRUD endpoint'leri instruction (tekil) ve creativity kullanır. Completions endpoint ayrıca iç içe bir capabilities nesnesi kabul eder; CRUD endpoint'leri düz boolean alanlar kullanır.
  • attachmentIds currently not functional: Agent, satır içi yapılandırmadaki attachmentIds ile referans verilen dosyaları okuyamaz. Bunun yerine mesaj başına yüklenen dosyaları metadata.attachments ile referans verin veya Create Agent API ile attachments alanına sahip kalıcı bir agent oluşturun.

API üzerinden Tools kullanımı

Bir agent'ta tool'lar yapılandırılmışsa (ajan UI'da "Actions" olarak adlandırılır), uygun olduğunda API isteklerine yanıt vermek için bunları otomatik kullanır.

Tool'lar agent üzerindeki önceden seçilmiş bir bağlantıyla veya API anahtarıyla paylaşılan bir bağlantıyla kimlik doğrular.

Workspace API anahtarı bir service account olarak çalışır. Tool'lar önceden seçilmiş bir bağlantı veya bu anahtarla paylaşılan bir bağlantı gerektirir.

"Require human confirmation" etkin tool'lar API üzerinden çalışmaz — ajan UI'da manuel onay gerektirir. Bir tool'u API üzerinden kullanmak için agent yapılandırmasında bu ayarı kapatın.

Structured Output

İsteğe bağlı output parametresiyle structured output biçimi belirtebilirsiniz:

FieldTypeDescription
type"object" | "array" | "enum"Structured output türü
schemaobjectÇıktı için JSON Schema tanımı (object/array türleri için)
enumstring\[]İzin verilen değerler dizisi (enum türü için)

output parametresi davranışı belirtilen türe bağlıdır:

  • type: "object" şemasız: Yanıtı tek bir JSON nesnesi olmaya zorlar (belirli yapı yok)
  • type: "object" şemalı: Yanıtı sağlanan JSON Schema ile eşleşmeye zorlar
  • type: "array" şemalı: Yanıtı sağlanan şemayla eşleşen nesne dizisi olmaya zorlar
  • type: "enum": Yanıtı enum dizisindeki değerlerden biri olmaya zorlar

Örnek JSON nesnelerinden JSON Schema üretmek için easy-json-schema gibi araçlar kullanabilirsiniz.

Streaming Responses

stream true olduğunda API, useChat hook'u ve diğer Vercel AI SDK özellikleriyle uyumlu Vercel AI SDK streaming biçiminde bir stream döndürür.

Non-streaming istekler 100 saniye sonra HTTP 524 hatasıyla sonlandırılır. Agent tool çalıştırır, uzun yanıt üretir veya daha yavaş modeller kullanırsa istekler bu limiti aşabilir. Bağlantıyı açık tutmak ve zaman aşımlarını önlemek için stream: true ayarlayın.

Vercel AI SDK useChat Hook ile kullanım

typescript
'use client';

import { useChat } from '@ai-sdk/react';

export default function Chat() {
  const { messages, input, handleInputChange, handleSubmit } = useChat({
    api: 'https://api.ajan.io/agent/v1/chat/completions',
    headers: {
      'Authorization': `Bearer ${process.env.NEXT_PUBLIC_AJAN_API_KEY}`
    },
    body: {
      agentId: 'your-agent-id'
    }
  });

  return (
    
      {messages.map(m => (
        
          {m.role === 'user' ? 'User: ' : 'AI: '}
          {m.content}
        
      ))}

      
        
      
    
  );
}

Manuel stream işleme

javascript
const response = await fetch('https://api.ajan.io/agent/v1/chat/completions', {
  method: 'POST',
  headers: {
    'Authorization': 'Bearer YOUR_API_KEY',
    'Content-Type': 'application/json',
  },
  body: JSON.stringify({
    agentId: 'agent_123',
    messages: [
      {
        id: 'msg_1',
        role: 'user',
        parts: [{ type: 'text', text: 'Hello' }]
      }
    ],
    stream: true
  }),
});

const reader = response.body.getReader();
const decoder = new TextDecoder();

while (true) {
  const { done, value } = await reader.read();
  if (done) break;

  const chunk = decoder.decode(value);
  console.log(chunk);  // Process streaming chunks
}

Attachment ID'lerini alma

Agent konuşmalarında attachment kullanmak için önce Upload Attachment API ile dosyaları yükleyin. Her dosya için bir attachmentId (UUID) döner. Attachment'ları iki şekilde kullanabilirsiniz:

  1. Per-message (önerilen): Attachment UUID'lerini mesajın metadata.attachments dizisine ekleyin. Aynı konuşmada farklı mesajlarda farklı dosyalara referans vermenizi sağlar.
  2. Agent-level: Kalıcı bir agent oluştururken veya güncellerken UUID'leri attachments dizisine ekleyin. Bu agent'a gönderilen tüm mesajlar bu dosyalara erişir.

Response Format

API, agent'ın yanıtını içeren bir messages dizisine sahip JSON nesnesi döndürür:

typescript
interface CompletionResponse {
  messages: Array<{
    id: string;
    role: "assistant";
    content: string;
  }>;

  // Structured output - included when requested
  output?: object | array | string;
}

Standard Response

Yanıt bir messages dizisi içerir. Her mesajda:

  • id — Mesaj için benzersiz tanımlayıcı
  • role — Completion yanıtlarında her zaman "assistant"
  • content — Agent'ın düz dize olarak metin yanıtı

Structured Output

İstek bir output parametresi içeriyorsa yanıt, biçimlendirilmiş structured veriyi içeren bir output alanını otomatik ekler. Bu alanın türü istenen çıktı biçimine bağlıdır:

  • output.type "object" ise: JSON nesnesi döndürür (şema sağlandıysa şema doğrulamasıyla)
  • output.type "array" ise: Sağlanan şemayla eşleşen nesne dizisi döndürür
  • output.type "enum" ise: Sağlanan enum değerlerinden biriyle eşleşen dize döndürür

Examples

Attachment ile mevcut agent kullanımı

javascript
const response = await fetch(
  "https://api.ajan.io/agent/v1/chat/completions",
  {
    method: "POST",
    headers: {
      "Authorization": "Bearer YOUR_API_KEY",
      "Content-Type": "application/json"
    },
    body: JSON.stringify({
      agentId: "agent_123",
      messages: [
        {
          id: "msg_1",
          role: "user",
          parts: [
            {
              type: "text",
              text: "Can you analyze this document for me?"
            }
          ],
          metadata: {
            attachments: ["550e8400-e29b-41d4-a716-446655440000"]
          }
        }
      ]
    })
  }
);

const data = await response.json();
const responseText = data.messages[0].content;
console.log(responseText);

Geçici agent yapılandırması kullanımı

javascript
const response = await fetch(
  "https://api.ajan.io/agent/v1/chat/completions",
  {
    method: "POST",
    headers: {
      "Authorization": "Bearer YOUR_API_KEY",
      "Content-Type": "application/json"
    },
    body: JSON.stringify({
      agent: {
        name: "Document Analyzer",
        instructions: "You are a helpful agent who analyzes documents and answers questions about them",
        temperature: 0.7,
        model: "gpt-5",
        capabilities: {
          webSearch: true
        }
      },
      messages: [
        {
          id: "msg_1",
          role: "user",
          parts: [
            {
              type: "text",
              text: "What are the key points in the document?"
            }
          ]
        }
      ]
    })
  }
);

const data = await response.json();
console.log(data);

Schema ile Structured Output kullanımı

javascript
const response = await fetch(
  "https://api.ajan.io/agent/v1/chat/completions",
  {
    method: "POST",
    headers: {
      "Authorization": "Bearer YOUR_API_KEY",
      "Content-Type": "application/json"
    },
    body: JSON.stringify({
      agent: {
        name: "Weather Agent",
        instructions: "You are a helpful weather agent",
        model: "gpt-5",
        capabilities: {
          webSearch: true
        }
      },
      messages: [
        {
          id: "msg_1",
          role: "user",
          parts: [
            {
              type: "text",
              text: "What's the weather in Paris, Berlin and London today?"
            }
          ]
        }
      ],
      output: {
        type: "array",
        schema: {
          type: "object",
          properties: {
            weather: {
              type: "object",
              properties: {
                city: { type: "string" },
                tempInCelsius: { type: "number" },
                tempInFahrenheit: { type: "number" }
              },
              required: ["city", "tempInCelsius", "tempInFahrenheit"]
            }
          }
        }
      }
    })
  }
);

const data = await response.json();
console.log(data.output);
// Output:
// [
//   { "weather": { "city": "Paris", "tempInCelsius": 1, "tempInFahrenheit": 33 } },
//   { "weather": { "city": "Berlin", "tempInCelsius": 1, "tempInFahrenheit": 35 } },
//   { "weather": { "city": "London", "tempInCelsius": 7, "tempInFahrenheit": 45 } }
// ]

Next.js Server Actions ile kullanım

typescript
// app/actions.ts
'use server';

import { generateId } from 'ai';

export async function chatWithAgent(message: string) {
  const response = await fetch(
    'https://api.ajan.io/agent/v1/chat/completions',
    {
      method: 'POST',
      headers: {
        'Authorization': `Bearer ${process.env.AJAN_API_KEY}`,
        'Content-Type': 'application/json'
      },
      body: JSON.stringify({
        agentId: process.env.AGENT_ID,
        messages: [
          {
            id: generateId(),
            role: 'user',
            parts: [
              {
                type: 'text',
                text: message
              }
            ]
          }
        ]
      })
    }
  );

  const data = await response.json();
  return data.messages[0].content;
}

Rate Limits

Varsayılan limitler 500 RPM (dakika başına istek) ve 150.000 TPM (dakika başına token)'dır.

  • RPM workspace, model ve API anahtarı başına uygulanır.
  • TPM, bir workspace'te aynı modeli kullanan tüm API anahtarları arasında paylaşılır.
  • Özel dağıtımlarda admin'ler Settings > Workspace > Products > API içinde model başına özel limitler yapılandırabilir.

Rate limit'inizi aşarsanız 429 Too Many Requests yanıtı alırsınız.

Error Handling

javascript
try {
  const response = await fetch('https://api.ajan.io/agent/v1/chat/completions', options);

  if (!response.ok) {
    const error = await response.json();
    throw new Error(error.message || 'Request failed');
  }

  const data = await response.json();
  // Process response
} catch (error) {
  console.error('Error:', error.message);
}

Yaygın hata durum kodları:

  • 400 — Geçersiz istek parametreleri, hatalı mesaj biçimi, agent bulunamadı veya agent API anahtarıyla paylaşılmamış
  • 401 — Geçersiz veya eksik API anahtarı
  • 429 — Rate limit aşıldı
  • 500 — Sunucu hatası

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:
  /agent/v1/chat/completions:
    post:
      tags:
        - Agent
      summary: Creates a chat completion with an agent (Vercel AI SDK compatible)
      description: Creates a model response using Vercel AI SDK compatible UIMessage format
      parameters: []
      requestBody:
        required: true
        content:
          application/json:
            examples:
              streamingEnabled:
                summary: Request with streaming enabled
                value:
                  agentId: agent_123
                  messages:
                    - id: msg_1
                      role: user
                      parts:
                        - type: text
                          text: Hello, how can you help me?
                  stream: true
            schema:
              type: object
              oneOf:
                - type: object
                  required:
                    - agentId
                    - messages
                  properties:
                    agentId:
                      type: string
                      description: ID of an existing agent to use
                    messages:
                      type: array
                      description: Array of UIMessage objects (Vercel AI SDK format)
                      items:
                        type: object
                        required:
                          - id
                          - role
                          - parts
                        properties:
                          id:
                            type: string
                            description: Unique message identifier
                          role:
                            type: string
                            enum:
                              - user
                              - assistant
                              - system
                              - tool
                          parts:
                            type: array
                            items:
                              type: object
                              required:
                                - type
                              properties:
                                type:
                                  type: string
                                  enum:
                                    - text
                                    - file
                                    - tool-invocation
                                    - tool-result
                                text:
                                  type: string
                                  description: Text content for text parts
                                url:
                                  type: string
                                  description: File URL for file parts
                                name:
                                  type: string
                                  description: File name
                                mimeType:
                                  type: string
                                  description: MIME type of the file
                                toolCallId:
                                  type: string
                                  description: Tool call identifier
                                toolName:
                                  type: string
                                  description: Name of the tool
                                args:
                                  type: object
                                  description: Tool arguments
                                result:
                                  type: object
                                  description: Tool result
                    stream:
                      type: boolean
                      default: false
                    output:
                      $ref: '#/components/schemas/StructuredOutputConfig'
                    imageResponseFormat:
                      type: string
                      enum:
                        - url
                        - b64_json
                      description: >-
                        Response format for images generated by the agent. "url"
                        returns a signed URL, "b64_json" returns base64-encoded
                        image data.
      responses:
        '200':
          description: Successful chat completion
          content:
            application/json:
              schema:
                type: object
                description: UIMessage response (Vercel AI SDK format)
                required:
                  - id
                  - role
                  - parts
                properties:
                  id:
                    type: string
                  role:
                    type: string
                    enum:
                      - assistant
                  parts:
                    type: array
                    items:
                      type: object
                  output:
                    description: Structured output if requested
        '400':
          description: Invalid request parameters
        '429':
          description: Rate limit exceeded
        '500':
          description: Internal server error
components:
  schemas:
    StructuredOutputConfig:
      type: object
      description: >-
        Specification for structured output format. When type is object/array
        and no schema is provided, the response will be JSON but can have any
        structure. When the type is enum, you must provide an enum parameter
        with an array of strings as options.
      properties:
        type:
          type: string
          enum:
            - object
            - array
            - enum
          description: The type of structured output
        schema:
          type: object
          description: >-
            JSON Schema definition for the output (required for object/array
            types with specific structure). Search for "JSON to JSON Schema" in
            the web to find a tool to convert any JSON into the required JSON
            Schema format.
        enum:
          type: array
          items:
            type: string
          description: >-
            Array of allowed values (required for enum type). Values must be of
            type string.
      oneOf:
        - properties:
            type:
              enum:
                - enum
            enum:
              items:
                type: string
              type: array
        - properties:
            type:
              enum:
                - object
                - array
            schema:
              type: object
        - properties:
            type:
              enum:
                - object
                - array
  securitySchemes:
    bearerAuth:
      type: http
      scheme: bearer
      bearerFormat: API Key
      description: API key as Bearer token. Format "Bearer YOUR_API_KEY"