RAG (Retrieval-Augmented Generation)

Perform semantic search across workspace knowledge and space-specific knowledge. This endpoint retrieves relevant content that can be used to augment AI-generated responses.

Endpoint

POST /v1/workspaces/{workspaceId}/spaces/{spaceId}/rag

Authentication

Requires API key authentication via x-api-key header. When RBAC is enabled, you can also include a Bearer token to scope results to a specific role.

Path Parameters

ParameterTypeRequiredDescription
workspaceIdstring (UUID)YesThe ID of your workspace
spaceIdstring (UUID)YesThe ID of the space

Headers

HeaderTypeRequiredDescription
x-api-keystringYesYour workspace API key
AuthorizationstringNoBearer token for RBAC-scoped results
Content-TypestringYesMust be application/json

Request Body

FieldTypeRequiredDescription
textstringYesThe query text to search for
languageIdstringNoFilter results by language code (e.g., en, es)
topKintegerNoMaximum number of results to return. Default: 5, Max: 10

Response

Success Response

Status Code: 200 OK

Body:

{
  "knowledgeResults": [
    {
      "text": "The installation process requires...",
      "source": "https://docs.example.com/install"
    },
    {
      "text": "Configuration steps include...",
      "source": "1:Installation Guide:knowledge-uuid"
    }
  ],
  "spaceKnowledgeResults": [
    {
      "text": "Team-specific guidelines state...",
      "source": "2:Team Guidelines:space-knowledge-uuid"
    }
  ]
}

Response Fields

FieldTypeDescription
knowledgeResultsarrayResults from workspace-level knowledge
knowledgeResults[].textstringRelevant text content
knowledgeResults[].sourcestringSource URL or reference (format: pageNumber:title:knowledgeId for files)
spaceKnowledgeResultsarrayResults from space-specific knowledge
spaceKnowledgeResults[].textstringRelevant text content
spaceKnowledgeResults[].sourcestringSource reference

Source Format

The source field format depends on the content type and permissions:

FormatDescription
https://...URL source (from web content)
pageNumber:titleFile with source permission only
pageNumber:title:knowledgeIdFile with download permission
Empty stringSource not available (blob without permissions)

Examples

Basic RAG Query

curl -X POST \
  'https://api.sharely.ai/v1/workspaces/{workspaceId}/spaces/{spaceId}/rag' \
  -H 'x-api-key: sk-sharely-your-api-key' \
  -H 'Content-Type: application/json' \
  -d '{
    "text": "How do I install the product?"
  }'

With Language Filter

curl -X POST \
  'https://api.sharely.ai/v1/workspaces/{workspaceId}/spaces/{spaceId}/rag' \
  -H 'x-api-key: sk-sharely-your-api-key' \
  -H 'Content-Type: application/json' \
  -d '{
    "text": "Cómo instalar el producto",
    "languageId": "es",
    "topK": 10
  }'

With RBAC Token

curl -X POST \
  'https://api.sharely.ai/v1/workspaces/{workspaceId}/spaces/{spaceId}/rag' \
  -H 'x-api-key: sk-sharely-your-api-key' \
  -H 'Authorization: Bearer {role-bound-token}' \
  -H 'Content-Type: application/json' \
  -d '{
    "text": "What are the sales guidelines?",
    "topK": 5
  }'

JavaScript Example

const API_KEY = 'sk-sharely-your-api-key';
const WORKSPACE_ID = 'your-workspace-id';
const BASE_URL = 'https://api.sharely.ai';
 
async function ragSearch(spaceId, query, options = {}) {
  const headers = {
    'x-api-key': API_KEY,
    'Content-Type': 'application/json'
  };
 
  // Add role-bound token for RBAC if available
  if (options.authToken) {
    headers['Authorization'] = `Bearer ${options.authToken}`;
  }
 
  const response = await fetch(
    `${BASE_URL}/v1/workspaces/${WORKSPACE_ID}/spaces/${spaceId}/rag`,
    {
      method: 'POST',
      headers,
      body: JSON.stringify({
        text: query,
        languageId: options.languageId,
        topK: options.topK || 5
      })
    }
  );
 
  if (!response.ok) {
    throw new Error(`RAG search failed: ${response.statusText}`);
  }
 
  return await response.json();
}
 
// Basic search
const results = await ragSearch('space-id', 'How to get started?');
console.log('Knowledge results:', results.knowledgeResults);
console.log('Space results:', results.spaceKnowledgeResults);
 
// Search with options
const spanishResults = await ragSearch('space-id', 'Primeros pasos', {
  languageId: 'es',
  topK: 10
});

Use Cases

Building Chat Applications

async function generateResponse(spaceId, userQuestion) {
  // Get relevant context using RAG
  const ragResults = await ragSearch(spaceId, userQuestion);
 
  // Combine all relevant content
  const context = [
    ...ragResults.knowledgeResults.map(r => r.text),
    ...ragResults.spaceKnowledgeResults.map(r => r.text)
  ].join('\n\n');
 
  // Use context with your LLM
  const response = await callLLM({
    systemPrompt: 'Answer based on the following context:\n' + context,
    userMessage: userQuestion
  });
 
  // Include sources in response
  const sources = [
    ...ragResults.knowledgeResults.filter(r => r.source),
    ...ragResults.spaceKnowledgeResults.filter(r => r.source)
  ];
 
  return { answer: response, sources };
}

Role-Scoped Content Retrieval

// Get role-bound token from authentication
const userToken = await authenticateUserWithRole(user);
 
// RAG search respects role permissions
const results = await ragSearch('space-id', 'confidential procedures', {
  authToken: userToken.sharelyToken
});
// Only returns content the user's role has access to

Error Responses

404 Not Found

Space not found:

{
  "error": "Error",
  "message": "Space not found"
}

Workspace mismatch:

{
  "error": "Error",
  "message": "Workspace ID does not match"
}

400 Bad Request

Invalid role (when using RBAC token):

{
  "error": "Error",
  "message": "Role not found"
}

Notes

  • Results are sorted by relevance score
  • The topK parameter affects both workspace and space knowledge results independently
  • When RBAC is enabled and a role-bound token is provided, only knowledge assigned to that role is returned
  • Language filtering applies to both workspace and space knowledge
  • Source URLs are only included based on knowledge permissions settings