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

This endpoint requires a Bearer token obtained through the two-step authentication flow:

  1. First, generate an access token using your API key
  2. Use that access token in the Authorization header

When RBAC is enabled, generate the token with a customerRoleId to scope results to a specific role.

See Authentication for the complete authentication flow.

Path Parameters

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

Headers

HeaderTypeRequiredDescription
AuthorizationstringYesBearer token with access token
organizationidstring (UUID)YesYour organization ID
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

# Step 1: Generate access token (do this once, reuse for multiple requests)
ACCESS_TOKEN=$(curl -s -X POST \
  'https://api.sharely.ai/workspaces/your-workspace-id/generate-access-key-token' \
  -H 'Content-Type: application/json' \
  -H 'x-api-key: sk-sharely-your-api-key' \
  -d '{}' | jq -r '.token')
 
# Step 2: Perform RAG search using the access token
curl -X POST \
  'https://api.sharely.ai/v1/workspaces/your-workspace-id/spaces/your-space-id/rag' \
  -H "Authorization: Bearer $ACCESS_TOKEN" \
  -H 'organizationid: your-organization-id' \
  -H 'Content-Type: application/json' \
  -d '{
    "text": "How do I install the product?"
  }'

With Language Filter

# Using the access token from Step 1 above
curl -X POST \
  'https://api.sharely.ai/v1/workspaces/your-workspace-id/spaces/your-space-id/rag' \
  -H "Authorization: Bearer $ACCESS_TOKEN" \
  -H 'organizationid: your-organization-id' \
  -H 'Content-Type: application/json' \
  -d '{
    "text": "Cómo instalar el producto",
    "languageId": "es",
    "topK": 10
  }'

With RBAC (Role-Scoped Results)

To scope results to a specific role, generate the token with customerRoleId:

# Step 1: Generate role-bound access token
ACCESS_TOKEN=$(curl -s -X POST \
  'https://api.sharely.ai/workspaces/your-workspace-id/generate-access-key-token' \
  -H 'Content-Type: application/json' \
  -H 'x-api-key: sk-sharely-your-api-key' \
  -d '{"customerRoleId": "sales-manager"}' | jq -r '.token')
 
# Step 2: RAG search with role-scoped token
curl -X POST \
  'https://api.sharely.ai/v1/workspaces/your-workspace-id/spaces/your-space-id/rag' \
  -H "Authorization: Bearer $ACCESS_TOKEN" \
  -H 'organizationid: your-organization-id' \
  -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 ORGANIZATION_ID = 'your-organization-id';
const API_BASE_URL = 'https://api.sharely.ai';
 
// Step 1: Generate access token
async function getAccessToken(customerRoleId = null) {
  const response = await fetch(
    `${API_BASE_URL}/workspaces/${WORKSPACE_ID}/generate-access-key-token`,
    {
      method: 'POST',
      headers: {
        'Content-Type': 'application/json',
        'x-api-key': API_KEY
      },
      body: JSON.stringify(customerRoleId ? { customerRoleId } : {})
    }
  );
  const data = await response.json();
  return data.token;
}
 
// Step 2: Perform RAG search
async function ragSearch(accessToken, spaceId, query, options = {}) {
  const response = await fetch(
    `${API_BASE_URL}/v1/workspaces/${WORKSPACE_ID}/spaces/${spaceId}/rag`,
    {
      method: 'POST',
      headers: {
        'Authorization': `Bearer ${accessToken}`,
        'organizationid': ORGANIZATION_ID,
        'Content-Type': 'application/json'
      },
      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 accessToken = await getAccessToken();
const results = await ragSearch(accessToken, 'space-id', 'How to get started?');
console.log('Knowledge results:', results.knowledgeResults);
console.log('Space results:', results.spaceKnowledgeResults);
 
// Search with language filter
const spanishResults = await ragSearch(accessToken, 'space-id', 'Primeros pasos', {
  languageId: 'es',
  topK: 10
});
 
// Role-scoped search (when RBAC is enabled)
const roleToken = await getAccessToken('sales-manager');
const roleResults = await ragSearch(roleToken, 'space-id', 'Sales guidelines');

Use Cases

Building Chat Applications

async function generateResponse(accessToken, spaceId, userQuestion) {
  // Get relevant context using RAG
  const ragResults = await ragSearch(accessToken, 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 };
}
 
// Usage
const accessToken = await getAccessToken();
const response = await generateResponse(accessToken, 'space-id', 'How do I get started?');

Role-Scoped Content Retrieval

// Generate role-bound token for the user's role
const roleToken = await getAccessToken(user.roleId);
 
// RAG search respects role permissions
const results = await ragSearch(roleToken, 'space-id', 'confidential procedures');
// 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