> ## Documentation Index
> Fetch the complete documentation index at: https://docs.langdock.com/llms.txt
> Use this file to discover all available pages before exploring further.

# Search Knowledge Folders

> Perform semantic search across knowledge folders shared with your API key

<Info>
  **Using our API via a dedicated deployment?** Just replace `api.langdock.com` with your deployment's base URL: **`<deployment-url>/api/public`**
</Info>

Performs a semantic search across all knowledge folders shared with your API key. Returns relevant document chunks ranked by similarity to your query.

<Info>
  Requires an API key with the `KNOWLEDGE_FOLDER_API` scope. The search is scoped to all knowledge folders shared with the API key. See [Share Knowledge Folders with the API](/en/developer/knowledge-folder-api/sharing) for setup instructions.
</Info>

## How It Works

1. Your query is converted to an embedding using your workspace's default embedding model
2. The system performs vector similarity search across all documents in shared knowledge folders
3. Results are filtered by relevance threshold and re-ranked using an LLM
4. 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

```bash theme={null}
curl -X POST "https://api.langdock.com/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 theme={null}
const axios = require("axios");

async function searchKnowledge(query) {
  const response = await axios.post(
    "https://api.langdock.com/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 theme={null}
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 theme={null}
{
  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 theme={null}
{
  "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.xlsx",
      "url": null,
      "index": 1
    }
  ]
}
```

## Error Handling

```typescript theme={null}
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.

<Info>
  Langdock intentionally blocks browser-origin requests to protect your API key and ensure your applications remain secure. For more information, please see our guide on [API Key Best Practices](/en/admin/ai-adoption-and-rollout/best-practices/api-key-best-practices).
</Info>


## OpenAPI

````yaml post /knowledge/search
openapi: 3.0.0
info:
  title: Langdock API
  version: 3.0.0
servers:
  - url: https://api.langdock.com
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"

````