Search Knowledge bases
Perform semantic search across Knowledge bases shared with your API key
Performs a semantic search across all Knowledge bases shared with your API key. Returns relevant document chunks ranked by similarity to your query.
Before You Start
- API key scope: Requires an API key with the
KNOWLEDGE_FOLDER_APIscope. The search is scoped to all Knowledge bases shared with the API key. See Share Knowledge bases with the API for setup instructions. - Knowledge bases: The Knowledge Folder API manages resources that appear as Knowledge bases in the Library.
Base URL
https://api.ajan.ioHow It Works
- Your query is converted to an embedding using your workspace's default embedding model
- The system performs vector similarity search across all documents in shared Knowledge bases
- Results are filtered by relevance threshold and re-ranked using an LLM
- Only the highest-scoring chunk per document is returned
Request Format
Request Body
| Parameter | Type | Required | Description |
|---|---|---|---|
query | string | Yes | The search query to find relevant documents |
Examples
Search with cURL
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
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
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)
{
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
{
"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
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
Write clear, specific queries - The search uses semantic similarity, so natural language questions work well. Be specific about what you're looking for.
Handle empty results - If no relevant documents are found, the result array will be empty. Your application should handle this gracefully.
Use similarity scores - The similarity score ranges from 0 to 1. Higher scores indicate better matches. Consider filtering results below a certain threshold for your use case.
Cite sources - Use the subname and url fields to provide attribution when displaying results to users.
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"