İçeriğe geç
ajan.io

Belgeler menüsü

Bu sayfada

Knowledge Folder'da attachment güncelle

Bir Knowledge base'deki mevcut bir dosyayı yeni sürümle değiştirin

Bir Knowledge base'deki mevcut bir dosyayı (attachment) yeni bir sürümle değiştirerek günceller. Eski dosya kaldırılır; yeni dosya işlenir ve embedding'lenir.

Başlamadan önce

  • API key scope: KNOWLEDGE_FOLDER_API kapsamına sahip bir API anahtarı gerekir. API anahtarının kendisinin Knowledge base üzerinde Editor rolü olmalıdır. Kurulum için Share Knowledge bases with the API sayfasına bakın.
  • Knowledge bases: Knowledge Folder API, Library'de Knowledge base olarak görünen kaynakları yönetir.

Base URL

https://api.ajan.io

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

Request Format

Bu endpoint, dosyanın eklendiği multipart/form-data isteklerini kabul eder.

Path Parameters

ParameterTypeRequiredDescription
folderIdstringYesKnowledge base ID'si

Form Fields

FieldTypeRequiredDescription
attachmentIdstringYesGüncellenecek attachment ID'si
filefileYesYüklenecek yeni dosya. Aşağıdaki boyut limitlerine bakın.
urlstringNoBu dosya bir yanıtta kullanıldığında kullanıcılara gösterilen URL

Dosya boyutu limitleri türe göre değişir: düz metin, Markdown, JSON ve VTT için 10 MB; XML için 30 MB; diğer desteklenen belge türleri için 256 MB. Desteklenen biçimler için supported file types reference sayfasına bakın.

Examples

Update with cURL

bash
curl -X PATCH "https://api.ajan.io/knowledge/{folderId}" \
  -H "Authorization: Bearer YOUR_API_KEY" \
  -F "attachmentId=att_abc123def456" \
  -F "file=@/path/to/new-document.pdf"

Update with JavaScript

javascript
const FormData = require("form-data");
const fs = require("fs");
const axios = require("axios");

async function updateAttachment(folderId, attachmentId, filePath) {
  const form = new FormData();
  form.append("attachmentId", attachmentId);
  form.append("file", fs.createReadStream(filePath));

  const response = await axios.patch(
    `https://api.ajan.io/knowledge/${folderId}`,
    form,
    {
      headers: {
        Authorization: "Bearer YOUR_API_KEY",
        ...form.getHeaders(),
      },
    }
  );

  return response.data;
}

// Example usage
try {
  const result = await updateAttachment(
    "folder_abc123",
    "att_xyz789",
    "/path/to/updated-report.pdf"
  );
  console.log("Attachment updated:", result);
} catch (error) {
  console.error("Failed to update:", error.response?.data?.message);
}

Update with Source URL

javascript
const FormData = require("form-data");
const fs = require("fs");
const axios = require("axios");

async function updateAttachmentWithUrl(folderId, attachmentId, filePath, sourceUrl) {
  const form = new FormData();
  form.append("attachmentId", attachmentId);
  form.append("file", fs.createReadStream(filePath));
  form.append("url", sourceUrl);

  const response = await axios.patch(
    `https://api.ajan.io/knowledge/${folderId}`,
    form,
    {
      headers: {
        Authorization: "Bearer YOUR_API_KEY",
        ...form.getHeaders(),
      },
    }
  );

  return response.data;
}

Response Format

Success Response (200 OK)

typescript
{
  status: "success";
  result: {
    id: string;          // Unique attachment ID
    name: string;        // Original filename
    mimeType: string;    // MIME type of the file
    createdAt: string;   // ISO 8601 timestamp
    updatedAt: string;   // ISO 8601 timestamp
    url: string | null;  // Source URL if provided
  };
}

Example Response

json
{
  "status": "success",
  "result": {
    "id": "att_abc123def456",
    "name": "updated-report.pdf",
    "mimeType": "application/pdf",
    "createdAt": "2025-01-15T10:30:00.000Z",
    "updatedAt": "2025-01-20T14:45:00.000Z",
    "url": null
  }
}

File Validation Response (400 Bad Request)

Yedek dosya doğrulamadan geçmezse API, nedeni message alanında döndürür:

json
{
  "message": "The file \"updated-report.pdf\" is declared as a PDF but its content does not start with the expected PDF header.",
  "code": "BAD_REQUEST"
}

Error Handling

javascript
try {
  const response = await updateAttachment(folderId, attachmentId, filePath);
} catch (error) {
  if (error.response) {
    console.error(error.response.data.message ?? "Update failed");
  }
}
StatusMeaning
400Geçersiz istek veya dosya doğrulama hatası
401Geçersiz veya eksik API anahtarı
403API anahtarının Knowledge base'e erişimi yok
404Knowledge base veya attachment bulunamadı
408Yükleme zaman aşımına uğradı
413Dosya boyut limitini aşıyor
429Rate limit aşıldı
500Beklenmeyen sunucu hatası
503Depolama kapasitesi aşıldı

Processing Status

Güncellemeden sonra yeni dosya asenkron işlenir. İşleme durumunu kontrol etmek için Retrieve Files endpoint'ini kullanın. syncStatus alanı mevcut durumu gösterir:

  • UPLOADING — Dosya yükleniyor
  • UPLOADED — Dosya yüklendi ve işleme kuyruğunda
  • EXTRACTING — Dosyadan metin çıkarılıyor
  • EMBEDDING — Embedding'ler üretiliyor
  • SYNCED — Dosya arama için hazır
  • ACTION_FAILED, EXTRACTION_FAILED, EMBEDDING_FAILED, TIMEOUT — İşleme başarısız

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:
  /knowledge/{folderId}:
    patch:
      summary: Update a file in a knowledge folder
      parameters:
        - name: folderId
          in: path
          required: true
          description: The ID of the knowledge folder
          schema:
            type: string
      requestBody:
        required: true
        content:
          multipart/form-data:
            schema:
              type: object
              properties:
                file:
                  type: string
                  format: binary
                  description: The new file to upload
                url:
                  type: string
                  description: >-
                    URL that is shown to the user if the file is used in an
                    answer
                attachmentId:
                  type: string
                  description: The ID of the attachment to update
      responses:
        '200':
          description: Attachment updated successfully
        '400':
          description: Invalid request or file validation failed
          content:
            application/json:
              schema:
                oneOf:
                  - type: object
                    additionalProperties: false
                    required:
                      - message
                      - code
                    properties:
                      message:
                        type: string
                        example: >-
                          The file "updated-report.pdf" is declared as a PDF but
                          its content does not start with the expected PDF
                          header.
                      code:
                        type: string
                        enum:
                          - BAD_REQUEST
                  - type: object
                    additionalProperties: false
                    required:
                      - message
                      - errors
                    properties:
                      message:
                        type: string
                        example: Invalid request
                      errors:
                        type: array
                        items:
                          type: object
        '401':
          description: Invalid or missing API key
          content:
            application/json:
              schema:
                type: object
                required:
                  - message
                properties:
                  message:
                    type: string
                    example: The provided API key is invalid.
        '403':
          description: API key does not have access to the knowledge folder
          content:
            application/json:
              schema:
                oneOf:
                  - type: object
                    additionalProperties: false
                    required:
                      - message
                      - code
                    properties:
                      message:
                        type: string
                        example: >-
                          Knowledge folder not shared with this API key. Please
                          share the folder with the API key in the ajan App
                          to upload or update files.
                      code:
                        type: string
                        enum:
                          - FORBIDDEN
                  - type: object
                    additionalProperties: false
                    required:
                      - message
                      - error
                      - details
                    properties:
                      message:
                        type: string
                        example: Insufficient API key permissions.
                      error:
                        type: string
                        enum:
                          - INSUFFICIENT_SCOPES
                      details:
                        type: object
                        required:
                          - required
                          - missing
                        properties:
                          required:
                            type: array
                            items:
                              type: string
                              example: KNOWLEDGE_FOLDER_API
                          missing:
                            type: array
                            items:
                              type: string
                              example: KNOWLEDGE_FOLDER_API
                  - type: object
                    additionalProperties: false
                    required:
                      - message
                    properties:
                      message:
                        type: string
                        example: Forbidden
        '404':
          description: Knowledge folder or attachment not found
          content:
            application/json:
              schema:
                type: object
                required:
                  - message
                  - code
                properties:
                  message:
                    type: string
                    example: >-
                      Attachment with ID '550e8400-e29b-41d4-a716-446655440000'
                      not found in this knowledge folder.
                  code:
                    type: string
                    enum:
                      - NOT_FOUND
        '408':
          description: Upload timed out
          content:
            application/json:
              schema:
                type: object
                required:
                  - message
                  - code
                properties:
                  message:
                    type: string
                    example: >-
                      Upload request timed out. Please try again with a smaller
                      file or check your connection.
                  code:
                    type: string
                    enum:
                      - REQUEST_TIMEOUT
        '413':
          description: File exceeds the size limit
          content:
            application/json:
              schema:
                type: object
                required:
                  - message
                  - code
                properties:
                  message:
                    type: string
                    example: >-
                      File size exceeds the maximum allowed size of 256MB.
                      Please upload a smaller file.
                  code:
                    type: string
                    enum:
                      - PAYLOAD_TOO_LARGE
        '429':
          description: Rate limit exceeded
          content:
            application/json:
              schema:
                type: object
                required:
                  - message
                properties:
                  message:
                    type: string
                    example: >-
                      You have exceeded the maximum number of requests per
                      minute (50)
                  code:
                    type: string
                    enum:
                      - TOO_MANY_REQUESTS
        '500':
          description: Unexpected server error
          content:
            application/json:
              schema:
                type: object
                required:
                  - message
                properties:
                  message:
                    type: string
                    example: Internal server error
        '503':
          description: Storage capacity exceeded
          content:
            application/json:
              schema:
                type: object
                required:
                  - message
                  - code
                properties:
                  message:
                    type: string
                    example: >-
                      Storage capacity exceeded. Please contact your
                      administrator.
                  code:
                    type: string
                    enum:
                      - SERVICE_UNAVAILABLE
      security:
        - bearerAuth: []
components:
  securitySchemes:
    bearerAuth:
      type: http
      scheme: bearer
      bearerFormat: API Key
      description: API key as Bearer token. Format "Bearer YOUR_API_KEY"