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

# Search

> Unified multi-modal search across knowledge bases with semantic, image, and graph discovery.

# Search

The search endpoints provide unified retrieval across multiple knowledge bases, combining semantic vector search, image similarity, and knowledge graph context.

<Note>
  All API requests require a valid JWT token in the `Authorization: Bearer <token>` header. The API Gateway decodes the JWT and forwards auth context (`user-id`, `organization-id`, `user-email`, `x-platform-role`, `x-org-role`) as headers to downstream services.
</Note>

<Warning>
  This endpoint incurs provider cost and records a billing event via `record_external_cost_event()`. Credits are deducted from the organization's wallet based on the configured margin multiplier.
</Warning>

## Unified Search

<ParamField method="POST" path="/api/knowledge/search" />

Search across one or more knowledge bases using text queries, images, and/or file content. This is the primary search endpoint used by both the manual search UI and the agent RAG pipeline.

### Request Body

<ParamField body="knowledgeBaseIds" type="string[]" required>
  Array of KB UUIDs to search across. Must be non-empty.
</ParamField>

<ParamField body="query" type="string">
  Text search query. At least one of `query`, `images`, or `files` must be provided.
</ParamField>

<ParamField body="images" type="object[]">
  Image inputs for visual similarity search.

  <Expandable title="Image object">
    <ParamField body="base64" type="string" required>Base64-encoded image data.</ParamField>
    <ParamField body="mimeType" type="string" required>Image MIME type (e.g., `image/png`).</ParamField>
  </Expandable>
</ParamField>

<ParamField body="files" type="object[]">
  File content for text-based search.

  <Expandable title="File object">
    <ParamField body="content" type="string" required>File text content.</ParamField>
    <ParamField body="mimeType" type="string" required>File MIME type.</ParamField>
  </Expandable>
</ParamField>

<ParamField body="topK" type="number">
  Maximum number of results to return. Default varies by context.
</ParamField>

### Query Parameters

<ParamField query="source" type="string">
  Search source: `manual` (user-initiated) or `agent_rag` (automated by agent during chat).
</ParamField>

<ParamField query="agentId" type="string">
  Agent UUID (for RAG attribution in search logs).
</ParamField>

<ParamField query="conversationId" type="string">
  Conversation UUID (for RAG attribution).
</ParamField>

<ParamField query="messageId" type="string">
  Message UUID (for RAG attribution).
</ParamField>

### Response (200)

<ResponseField name="results" type="object[]">
  Ranked search results from all queried KBs.

  <Expandable title="Result object">
    <ResponseField name="content" type="string">Chunk text content.</ResponseField>
    <ResponseField name="score" type="number">Combined relevance score (0-1).</ResponseField>
    <ResponseField name="knowledgeBaseId" type="string">Source KB UUID.</ResponseField>

    <ResponseField name="metadata" type="object">
      Result metadata.

      <Expandable title="Metadata">
        <ResponseField name="documentId" type="string">Source document UUID.</ResponseField>
        <ResponseField name="documentTitle" type="string">Document title.</ResponseField>
        <ResponseField name="chunkIndex" type="number">Position within document.</ResponseField>
        <ResponseField name="embeddingType" type="string">`text`, `image`, `video`, `audio`, or `transcript`.</ResponseField>
      </Expandable>
    </ResponseField>

    <ResponseField name="discoveryMethods" type="string[]">
      How this result was found: `semantic`, `image`, and/or `graph`.
    </ResponseField>

    <ResponseField name="relationshipPath" type="string">
      If discovered via graph, the entity relationship path.
    </ResponseField>
  </Expandable>
</ResponseField>

<ResponseField name="suggestedFollowUps" type="string[]">
  AI-suggested follow-up queries based on the results.
</ResponseField>

<CodeGroup>
  ```bash curl theme={null}
  curl -X POST https://your-domain.com/api/knowledge/search \
    -H "Authorization: Bearer $TOKEN" \
    -H "Content-Type: application/json" \
    -d '{
      "knowledgeBaseIds": ["kb-uuid-1", "kb-uuid-2"],
      "query": "What is the return policy for electronics?"
    }'
  ```

  ```javascript JavaScript theme={null}
  const response = await fetch("https://your-domain.com/api/knowledge/search", {
    method: "POST",
    headers: {
      Authorization: `Bearer ${token}`,
      "Content-Type": "application/json",
    },
    body: JSON.stringify({
      knowledgeBaseIds: ["kb-uuid-1", "kb-uuid-2"],
      query: "What is the return policy for electronics?",
    }),
  });

  const { results, suggestedFollowUps } = await response.json();
  ```
</CodeGroup>

### Search Pipeline

The unified search orchestrates multiple discovery methods in parallel:

1. **Semantic search**: Embed the query using Gemini Embedding 2, then vector search across all specified KBs
2. **Image search**: If images are provided, embed them and search for visually similar content
3. **Graph-informed discovery**: Use the knowledge graph to find related documents through entity relationships
4. **Merge and deduplicate**: Combine results from all methods, deduplicate, and rank by combined score
5. **Tag discovery methods**: Each result is tagged with how it was found (`semantic`, `image`, `graph`)

***

## Graph Entity Search

<ParamField method="POST" path="/api/knowledge/kb/:id/graph/search" />

Search the knowledge graph for entities and relationships matching a query. Returns structured entity data with relationship context.

### Path Parameters

<ParamField path="id" type="string" required>KB UUID.</ParamField>

### Request Body

<ParamField body="query" type="string" required>
  Search query for entity matching.
</ParamField>

<ParamField body="imageBase64" type="string">
  Optional base64-encoded image for visual entity matching.
</ParamField>

<ParamField body="mimeType" type="string">
  MIME type of the image (required if `imageBase64` is provided).
</ParamField>

### Response (200)

<ResponseField name="query" type="string">The original query.</ResponseField>

<ResponseField name="entities" type="object[]">
  Matched entities.

  <Expandable title="Entity object">
    <ResponseField name="id" type="string">Entity UUID.</ResponseField>
    <ResponseField name="name" type="string">Entity name.</ResponseField>
    <ResponseField name="type" type="string">Entity type (e.g., `person`, `concept`, `product`).</ResponseField>
    <ResponseField name="aliases" type="string[]">Alternative names.</ResponseField>
    <ResponseField name="mentionCount" type="number">Number of document mentions.</ResponseField>
  </Expandable>
</ResponseField>

<ResponseField name="relationships" type="object[]">
  Relationships between matched entities.

  <Expandable title="Relationship object">
    <ResponseField name="sourceEntityId" type="string">Source entity UUID.</ResponseField>
    <ResponseField name="targetEntityId" type="string">Target entity UUID.</ResponseField>
    <ResponseField name="type" type="string">Relationship type.</ResponseField>
    <ResponseField name="weight" type="number">Relationship strength.</ResponseField>
  </Expandable>
</ResponseField>

<ResponseField name="formattedContext" type="string">
  Human-readable context string for LLM consumption.
</ResponseField>

<ResponseField name="matchedEntityNames" type="string[]">
  Names of entities directly matched by the query.
</ResponseField>

***

## KB Document Map

<ParamField method="GET" path="/api/knowledge/kb/:id/map" />

Get the document registry for a knowledge base, including summaries and topics for each document. Used by agents for document awareness.

### Path Parameters

<ParamField path="id" type="string" required>KB UUID.</ParamField>

### Response (200)

<ResponseField name="knowledgeBaseId" type="string">KB UUID.</ResponseField>
<ResponseField name="knowledgeBaseName" type="string">KB name.</ResponseField>
<ResponseField name="total" type="number">Number of documents.</ResponseField>

<ResponseField name="documents" type="object[]">
  Document registry entries.

  <Expandable title="Document entry">
    <ResponseField name="documentId" type="string">Document UUID.</ResponseField>
    <ResponseField name="title" type="string">Document title.</ResponseField>
    <ResponseField name="summary" type="string">AI-generated document summary.</ResponseField>
    <ResponseField name="topics" type="string[]">Key topics covered.</ResponseField>
    <ResponseField name="chunkCount" type="number">Number of chunks.</ResponseField>
  </Expandable>
</ResponseField>

```bash curl theme={null}
curl https://your-domain.com/api/knowledge/kb/KB_ID/map \
  -H "Authorization: Bearer $TOKEN"
```

***

## Search Logs

### Get Search History

<ParamField method="GET" path="/api/knowledge/kb/:id/search/log" />

Get paginated search log history for a knowledge base.

### Path Parameters

<ParamField path="id" type="string" required>KB UUID.</ParamField>

### Clear Search History

<ParamField method="DELETE" path="/api/knowledge/kb/:id/search/log" />

Clear all search log entries for a knowledge base.
