İçeriğe geç
ajan.io

Belgeler menüsü

Bu sayfada

Knowledge base'lerde ara

API anahtarınızla paylaşılan Knowledge base'lerde anlamsal arama yapın

API anahtarınızla paylaşılan tüm Knowledge base'lerde anlamsal arama yapar. Sorgunuza benzerliğe göre sıralanmış ilgili belge parçalarını döndürür.

Başlamadan önce

  • API key scope: KNOWLEDGE_FOLDER_API kapsamına sahip bir API anahtarı gerekir. Arama, API anahtarıyla paylaşılan tüm Knowledge base'lerle sınırlı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.

How It Works

  1. Sorgunuz workspace'inizin varsayılan embedding modeli ile bir embedding'e dönüştürülür
  2. Sistem, paylaşılan Knowledge base'lerdeki tüm belgelerde vektör benzerlik araması yapar
  3. Sonuçlar alaka eşiğine göre filtrelenir ve bir LLM ile yeniden sıralanır
  4. Belge başına yalnızca en yüksek skorlu chunk döndürülür

Request Format

Request Body

ParameterTypeRequiredDescription
querystringYesİlgili belgeleri bulmak için arama sorgusu

Examples

Search with cURL

bash
curl -X POST "https://api.ajan.io/knowledge/search" \
  -H "Authorization: Bearer YOUR_API_KEY" \
  -H "Content-Type: application/json" \
  -d '{"query": "What are the Q4 revenue projections?"}'

Search with JavaScript

javascript
const axios = require("axios");

async function searchKnowledge(query) {
  const response = await axios.post(
    "https://api.ajan.io/knowledge/search",
    { query },
    {
      headers: {
        Authorization: "Bearer YOUR_API_KEY",
        "Content-Type": "application/json",
      },
    }
  );

  return response.data;
}

// Example usage
const results = await searchKnowledge("What are the Q4 revenue projections?");
console.log(`Found ${results.result.length} relevant documents`);

results.result.forEach((chunk, i) => {
  console.log(`\n--- Result ${i + 1} ---`);
  console.log(`File: ${chunk.subname}`);
  console.log(`Similarity: ${(chunk.similarity * 100).toFixed(1)}%`);
  console.log(`Text: ${chunk.text.substring(0, 200)}...`);
});

Using Search Results for RAG

javascript
async function answerWithContext(question) {
  // Search for relevant context
  const searchResults = await searchKnowledge(question);

  // Build context from search results
  const context = searchResults.result
    .map((chunk) => `Source: ${chunk.subname}\n${chunk.text}`)
    .join("\n\n---\n\n");

  // Use context with your LLM
  const prompt = `Based on the following context, answer the question.

Context:
${context}

Question: ${question}

Answer:`;

  // Call your preferred LLM endpoint
  return callLLM(prompt);
}

Response Format

Success Response (200 OK)

typescript
{
  status: "success";
  result: Array<{
    id: string;           // Unique chunk ID
    text: string;         // The text content of the chunk
    similarity: number;   // Similarity score (0-1)
    subsource: string;    // Attachment ID
    subname: string;      // Filename
    url: string | null;   // Source URL if provided during upload
    index: number;        // Result index (0-based)
  }>;
}

Example Response

json
{
  "status": "success",
  "result": [
    {
      "id": "chunk_abc123",
      "text": "Q4 revenue projections indicate a 15% increase compared to Q3, driven primarily by strong enterprise sales in the EMEA region...",
      "similarity": 0.89,
      "subsource": "att_xyz789",
      "subname": "quarterly-report-2024.pdf",
      "url": "https://example.com/reports/q4-2024",
      "index": 0
    },
    {
      "id": "chunk_def456",
      "text": "The projected revenue for the fourth quarter takes into account seasonal trends and the impact of new product launches...",
      "similarity": 0.82,
      "subsource": "att_abc456",
      "subname": "financial-forecast.docx",
      "url": null,
      "index": 1
    }
  ]
}

Error Handling

typescript
try {
  const response = await searchKnowledge(query);
} catch (error) {
  if (error.response) {
    switch (error.response.status) {
      case 400:
        console.error("Invalid request:", error.response.data.message);
        // Possible causes: missing query parameter
        break;
      case 401:
        console.error("Invalid or missing API key");
        break;
      case 403:
        console.error("API key does not have KNOWLEDGE_FOLDER_API scope");
        break;
      case 429:
        console.error("Rate limit exceeded");
        break;
      case 500:
        console.error("Server error");
        break;
    }
  }
}

Best Practices

Net, spesifik sorgular yazın — Arama anlamsal benzerlik kullanır; doğal dil soruları iyi çalışır. Ne aradığınızı netleştirin.

Boş sonuçları ele alın — İlgili belge bulunamazsa result dizisi boş olur. Uygulamanız bunu zarifçe işlemelidir.

Similarity skorlarını kullanın — similarity skoru 0 ile 1 arasındadır. Daha yüksek skorlar daha iyi eşleşmeleri gösterir. Kullanım senaryonuza göre belirli bir eşiğin altındaki sonuçları filtrelemeyi düşünün.

Kaynakları belirtin — Sonuçları kullanıcılara gösterirken atıf için subname ve url alanlarını kullanın.

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/search:
    post:
      summary: Search through all files in data folders shared with the API Key
      parameters: []
      requestBody:
        required: true
        content:
          application/json:
            schema:
              type: object
              required:
                - query
              properties:
                query:
                  type: string
                  description: The search query
                  example: API Documentation
      responses:
        '200':
          description: Successfully found search result
      security:
        - bearerAuth: []
components:
  securitySchemes:
    bearerAuth:
      type: http
      scheme: bearer
      bearerFormat: API Key
      description: API key as Bearer token. Format "Bearer YOUR_API_KEY"