Search through all files in data folders shared with the API Key
curl --request POST \
--url https://api.langdock.com/knowledge/search \
--header 'Authorization: Bearer <token>' \
--header 'Content-Type: application/json' \
--data '
{
"query": "API Documentation"
}
'import requests
url = "https://api.langdock.com/knowledge/search"
payload = { "query": "API Documentation" }
headers = {
"Authorization": "Bearer <token>",
"Content-Type": "application/json"
}
response = requests.post(url, json=payload, headers=headers)
print(response.text)const options = {
method: 'POST',
headers: {Authorization: 'Bearer <token>', 'Content-Type': 'application/json'},
body: JSON.stringify({query: 'API Documentation'})
};
fetch('https://api.langdock.com/knowledge/search', options)
.then(res => res.json())
.then(res => console.log(res))
.catch(err => console.error(err));<?php
$curl = curl_init();
curl_setopt_array($curl, [
CURLOPT_URL => "https://api.langdock.com/knowledge/search",
CURLOPT_RETURNTRANSFER => true,
CURLOPT_ENCODING => "",
CURLOPT_MAXREDIRS => 10,
CURLOPT_TIMEOUT => 30,
CURLOPT_HTTP_VERSION => CURL_HTTP_VERSION_1_1,
CURLOPT_CUSTOMREQUEST => "POST",
CURLOPT_POSTFIELDS => json_encode([
'query' => 'API Documentation'
]),
CURLOPT_HTTPHEADER => [
"Authorization: Bearer <token>",
"Content-Type: application/json"
],
]);
$response = curl_exec($curl);
$err = curl_error($curl);
curl_close($curl);
if ($err) {
echo "cURL Error #:" . $err;
} else {
echo $response;
}package main
import (
"fmt"
"strings"
"net/http"
"io"
)
func main() {
url := "https://api.langdock.com/knowledge/search"
payload := strings.NewReader("{\n \"query\": \"API Documentation\"\n}")
req, _ := http.NewRequest("POST", url, payload)
req.Header.Add("Authorization", "Bearer <token>")
req.Header.Add("Content-Type", "application/json")
res, _ := http.DefaultClient.Do(req)
defer res.Body.Close()
body, _ := io.ReadAll(res.Body)
fmt.Println(string(body))
}HttpResponse<String> response = Unirest.post("https://api.langdock.com/knowledge/search")
.header("Authorization", "Bearer <token>")
.header("Content-Type", "application/json")
.body("{\n \"query\": \"API Documentation\"\n}")
.asString();require 'uri'
require 'net/http'
url = URI("https://api.langdock.com/knowledge/search")
http = Net::HTTP.new(url.host, url.port)
http.use_ssl = true
request = Net::HTTP::Post.new(url)
request["Authorization"] = 'Bearer <token>'
request["Content-Type"] = 'application/json'
request.body = "{\n \"query\": \"API Documentation\"\n}"
response = http.request(request)
puts response.read_bodyKnowledge Folder API
Search Knowledge bases
Perform semantic search across Knowledge bases shared with your API key
POST
/
knowledge
/
search
Search through all files in data folders shared with the API Key
curl --request POST \
--url https://api.langdock.com/knowledge/search \
--header 'Authorization: Bearer <token>' \
--header 'Content-Type: application/json' \
--data '
{
"query": "API Documentation"
}
'import requests
url = "https://api.langdock.com/knowledge/search"
payload = { "query": "API Documentation" }
headers = {
"Authorization": "Bearer <token>",
"Content-Type": "application/json"
}
response = requests.post(url, json=payload, headers=headers)
print(response.text)const options = {
method: 'POST',
headers: {Authorization: 'Bearer <token>', 'Content-Type': 'application/json'},
body: JSON.stringify({query: 'API Documentation'})
};
fetch('https://api.langdock.com/knowledge/search', options)
.then(res => res.json())
.then(res => console.log(res))
.catch(err => console.error(err));<?php
$curl = curl_init();
curl_setopt_array($curl, [
CURLOPT_URL => "https://api.langdock.com/knowledge/search",
CURLOPT_RETURNTRANSFER => true,
CURLOPT_ENCODING => "",
CURLOPT_MAXREDIRS => 10,
CURLOPT_TIMEOUT => 30,
CURLOPT_HTTP_VERSION => CURL_HTTP_VERSION_1_1,
CURLOPT_CUSTOMREQUEST => "POST",
CURLOPT_POSTFIELDS => json_encode([
'query' => 'API Documentation'
]),
CURLOPT_HTTPHEADER => [
"Authorization: Bearer <token>",
"Content-Type: application/json"
],
]);
$response = curl_exec($curl);
$err = curl_error($curl);
curl_close($curl);
if ($err) {
echo "cURL Error #:" . $err;
} else {
echo $response;
}package main
import (
"fmt"
"strings"
"net/http"
"io"
)
func main() {
url := "https://api.langdock.com/knowledge/search"
payload := strings.NewReader("{\n \"query\": \"API Documentation\"\n}")
req, _ := http.NewRequest("POST", url, payload)
req.Header.Add("Authorization", "Bearer <token>")
req.Header.Add("Content-Type", "application/json")
res, _ := http.DefaultClient.Do(req)
defer res.Body.Close()
body, _ := io.ReadAll(res.Body)
fmt.Println(string(body))
}HttpResponse<String> response = Unirest.post("https://api.langdock.com/knowledge/search")
.header("Authorization", "Bearer <token>")
.header("Content-Type", "application/json")
.body("{\n \"query\": \"API Documentation\"\n}")
.asString();require 'uri'
require 'net/http'
url = URI("https://api.langdock.com/knowledge/search")
http = Net::HTTP.new(url.host, url.port)
http.use_ssl = true
request = Net::HTTP::Post.new(url)
request["Authorization"] = 'Bearer <token>'
request["Content-Type"] = 'application/json'
request.body = "{\n \"query\": \"API Documentation\"\n}"
response = http.request(request)
puts response.read_bodyPerforms 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.langdock.com
Dedicated deploymentsReplace
api.langdock.com with <your-deployment-url>/api/public in all requests.How 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.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
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
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, theresult 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.
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.
Was this page helpful?