> ## 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.

# Knowledge Graph

> Manage extracted entities and relationships. Optimize graph quality with AI-powered suggestions.

# Knowledge Graph

Each knowledge base can have an automatically extracted knowledge graph containing entities (people, concepts, products, etc.) and relationships between them. The graph enhances search quality and provides structured context to agents.

<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>

## List Entities

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

Get a paginated, filterable list of entities in the knowledge base graph.

### Path Parameters

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

### Query Parameters

<ParamField query="type" type="string">
  Filter by entity type (e.g., `person`, `concept`, `product`, `organization`).
</ParamField>

<ParamField query="search" type="string">
  Full-text search across entity names and aliases.
</ParamField>

<ParamField query="documentId" type="string">
  Filter to entities from a specific document.
</ParamField>

<ParamField query="limit" type="number" default="100">Maximum results.</ParamField>
<ParamField query="offset" type="number" default="0">Pagination offset.</ParamField>

### Response (200)

<ResponseField name="entities" type="object[]">
  Array of entity objects.

  <Expandable title="Entity object">
    <ResponseField name="id" type="string">Entity UUID.</ResponseField>
    <ResponseField name="name" type="string">Canonical entity name.</ResponseField>
    <ResponseField name="type" type="string">Entity type.</ResponseField>
    <ResponseField name="aliases" type="string[]">Alternative names and spellings.</ResponseField>
    <ResponseField name="mentionCount" type="number">Number of times referenced across documents.</ResponseField>
    <ResponseField name="documentIds" type="string[]">Documents where this entity appears.</ResponseField>
    <ResponseField name="createdAt" type="string">ISO 8601 timestamp.</ResponseField>
  </Expandable>
</ResponseField>

<ResponseField name="total" type="number">Total entity count matching filters.</ResponseField>

<CodeGroup>
  ```bash curl theme={null}
  curl "https://your-domain.com/api/knowledge/kb/KB_ID/graph/entities?\
  type=person&limit=50" \
    -H "Authorization: Bearer $TOKEN"
  ```

  ```javascript JavaScript theme={null}
  const params = new URLSearchParams({ type: "person", limit: "50" });
  const response = await fetch(
    `https://your-domain.com/api/knowledge/kb/${kbId}/graph/entities?${params}`,
    { headers: { Authorization: `Bearer ${token}` } }
  );

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

***

## Get Entity Detail

<ParamField method="GET" path="/api/knowledge/kb/:id/graph/entities/:entityId" />

Get a single entity with its connected entities and relationships (1-hop neighborhood).

### Path Parameters

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

### Response (200)

<ResponseField name="entity" type="object">The requested entity with full details.</ResponseField>
<ResponseField name="connectedEntities" type="object[]">Entities connected by relationships.</ResponseField>

<ResponseField name="relationships" type="object[]">
  All relationships involving this entity.

  <Expandable title="Relationship object">
    <ResponseField name="id" type="string">Relationship UUID.</ResponseField>
    <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 (e.g., `works_at`, `related_to`, `part_of`).</ResponseField>
    <ResponseField name="weight" type="number">Relationship strength (0-1).</ResponseField>
    <ResponseField name="documentId" type="string">Source document UUID.</ResponseField>
  </Expandable>
</ResponseField>

***

## Rename Entity

<ParamField method="PATCH" path="/api/knowledge/kb/:id/graph/entities/:entityId" />

Rename an entity. The old name is automatically preserved as an alias.

### Path Parameters

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

### Request Body

<ParamField body="name" type="string" required>New canonical name for the entity.</ParamField>

### Response (200)

<ResponseField name="entity" type="object">Updated entity object.</ResponseField>

***

## Merge Entities

<ParamField method="POST" path="/api/knowledge/kb/:id/graph/entities/:entityId/merge" />

Merge multiple entities into a canonical entity. The target entity absorbs the names (as aliases) and relationships of the merged entities. Use this to resolve duplicates.

### Path Parameters

<ParamField path="id" type="string" required>KB UUID.</ParamField>
<ParamField path="entityId" type="string" required>Canonical (target) entity UUID -- the entity that will absorb others.</ParamField>

### Request Body

<ParamField body="mergeEntityIds" type="string[]" required>
  Array of entity UUIDs to merge into the canonical entity. These entities will be deleted after merging.
</ParamField>

### Response (200)

<ResponseField name="message" type="string">Confirmation with merge count.</ResponseField>
<ResponseField name="canonicalEntityId" type="string">The surviving entity UUID.</ResponseField>
<ResponseField name="mergedCount" type="number">Number of entities merged.</ResponseField>

```bash curl theme={null}
curl -X POST https://your-domain.com/api/knowledge/kb/KB_ID/graph/entities/ENTITY_ID/merge \
  -H "Authorization: Bearer $TOKEN" \
  -H "Content-Type: application/json" \
  -d '{
    "mergeEntityIds": ["dup-entity-1", "dup-entity-2"]
  }'
```

***

## Delete Entity

<ParamField method="DELETE" path="/api/knowledge/kb/:id/graph/entities/:entityId" />

Delete an entity and all of its relationships.

### Path Parameters

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

### Response (204)

No content on success.

***

## Graph Stats

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

Get aggregate statistics about the knowledge graph (entity counts by type, relationship counts, etc.).

### Path Parameters

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

### Response (200)

<ResponseField name="stats" type="object">
  Graph statistics.

  <Expandable title="Stats">
    <ResponseField name="totalEntities" type="number">Total entity count.</ResponseField>
    <ResponseField name="totalRelationships" type="number">Total relationship count.</ResponseField>
    <ResponseField name="entitiesByType" type="object">Count per entity type.</ResponseField>
  </Expandable>
</ResponseField>

***

## Graph Optimization

The optimization endpoints help improve graph quality by detecting and resolving duplicate entities, suggesting merges, and cleaning up the graph.

### Get Optimization Stats

<ParamField method="GET" path="/api/knowledge/kb/:id/graph/optimize/stats" />

Get counts of optimization suggestions by type and status.

#### Path Parameters

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

***

### List Optimization Suggestions

<ParamField method="GET" path="/api/knowledge/kb/:id/graph/optimize/suggestions" />

Get paginated list of optimization suggestions (e.g., merge duplicates, rename inconsistent entities).

#### Path Parameters

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

#### Query Parameters

<ParamField query="status" type="string">Filter by status: `pending`, `approved`, `rejected`, `applied`.</ParamField>
<ParamField query="type" type="string">Filter by suggestion type.</ParamField>
<ParamField query="limit" type="number">Maximum results.</ParamField>
<ParamField query="offset" type="number">Pagination offset.</ParamField>

***

### Generate Suggestions

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

Trigger asynchronous generation of optimization suggestions for the knowledge graph. Queues a background job.

#### Path Parameters

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

#### Response (200)

<ResponseField name="message" type="string">"Suggestion generation started"</ResponseField>
<ResponseField name="jobId" type="string">Background job ID for tracking.</ResponseField>

***

### AI Auto-Resolve Suggestions

<ParamField method="POST" path="/api/knowledge/kb/:id/graph/optimize/ai-resolve" />

Use AI to automatically approve or reject pending optimization suggestions. Queues a background job that evaluates each suggestion using an LLM.

#### Path Parameters

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

#### Response (200)

<ResponseField name="message" type="string">"AI resolve started"</ResponseField>
<ResponseField name="jobId" type="string">Background job ID.</ResponseField>

***

### Update Suggestion Status

<ParamField method="PATCH" path="/api/knowledge/kb/:id/graph/optimize/suggestions/:suggestionId" />

Manually approve or reject a single optimization suggestion.

#### Path Parameters

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

#### Request Body

<ParamField body="status" type="string" required>
  New status: `approved` or `rejected`.
</ParamField>

#### Response (200)

<ResponseField name="suggestion" type="object">Updated suggestion object.</ResponseField>

***

### Apply Approved Suggestions

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

Apply a set of approved suggestions to the knowledge graph (execute merges, renames, etc.).

#### Path Parameters

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

#### Request Body

<ParamField body="suggestionIds" type="string[]" required>
  Array of approved suggestion UUIDs to apply.
</ParamField>

#### Response (200)

<ResponseField name="applied" type="number">Number of suggestions successfully applied.</ResponseField>
<ResponseField name="failed" type="number">Number of suggestions that failed to apply.</ResponseField>
<ResponseField name="errors" type="string[]">Error messages for failed suggestions.</ResponseField>

<CodeGroup>
  ```bash curl theme={null}
  # 1. Generate suggestions
  curl -X POST https://your-domain.com/api/knowledge/kb/KB_ID/graph/optimize/generate \
    -H "Authorization: Bearer $TOKEN"

  # 2. AI auto-resolve
  curl -X POST https://your-domain.com/api/knowledge/kb/KB_ID/graph/optimize/ai-resolve \
    -H "Authorization: Bearer $TOKEN"

  # 3. Apply approved suggestions
  curl -X POST https://your-domain.com/api/knowledge/kb/KB_ID/graph/optimize/apply \
    -H "Authorization: Bearer $TOKEN" \
    -H "Content-Type: application/json" \
    -d '{"suggestionIds": ["suggestion-1", "suggestion-2"]}'
  ```

  ```javascript JavaScript theme={null}
  // 1. Generate suggestions
  await fetch(
    `https://your-domain.com/api/knowledge/kb/${kbId}/graph/optimize/generate`,
    { method: "POST", headers: { Authorization: `Bearer ${token}` } }
  );

  // 2. AI auto-resolve
  await fetch(
    `https://your-domain.com/api/knowledge/kb/${kbId}/graph/optimize/ai-resolve`,
    { method: "POST", headers: { Authorization: `Bearer ${token}` } }
  );

  // 3. Get approved suggestions
  const { suggestions } = await fetch(
    `https://your-domain.com/api/knowledge/kb/${kbId}/graph/optimize/suggestions?status=approved`,
    { headers: { Authorization: `Bearer ${token}` } }
  ).then(r => r.json());

  // 4. Apply them
  await fetch(
    `https://your-domain.com/api/knowledge/kb/${kbId}/graph/optimize/apply`,
    {
      method: "POST",
      headers: {
        Authorization: `Bearer ${token}`,
        "Content-Type": "application/json",
      },
      body: JSON.stringify({
        suggestionIds: suggestions.map(s => s.id),
      }),
    }
  );
  ```
</CodeGroup>

***

## Pinned Entities

### Get Pinned Entities

<ParamField method="GET" path="/api/knowledge/kb/:id/graph/pinned-entities" />

Get user-defined known entities that are used to seed future graph extractions.

### Update Pinned Entities

<ParamField method="PUT" path="/api/knowledge/kb/:id/graph/pinned-entities" />

Set the list of known entities for a KB. These entities are provided to the extraction LLM as context, improving entity recognition consistency across documents.
