Documentation
¶
Overview ¶
Package cortexdb provides a lightweight SQLite-based vector database for Go AI projects
Example (Embedder) ¶
Example_embedder shows how to use the Embedder interface
package main
import (
"context"
"fmt"
"math"
"github.com/liliang-cn/cortexdb/v2/pkg/cortexdb"
)
// DummyEmbedder is a simple embedder for testing purposes.
// It generates deterministic vectors based on text content.
// In production, replace this with OpenAI, Ollama, or other embedding providers.
type DummyEmbedder struct {
dim int
}
func NewDummyEmbedder(dim int) *DummyEmbedder {
return &DummyEmbedder{dim: dim}
}
func (d *DummyEmbedder) Embed(ctx context.Context, text string) ([]float32, error) {
vector := make([]float32, d.dim)
for i := range vector {
seed := float64(0)
for j, b := range text {
seed += float64(b) * float64(j+1) * float64(i+1)
}
vector[i] = float32(math.Sin(seed * 0.001))
}
norm := float32(0)
for _, v := range vector {
norm += v * v
}
norm = float32(math.Sqrt(float64(norm)))
if norm > 0 {
for i := range vector {
vector[i] /= norm
}
}
return vector, nil
}
func (d *DummyEmbedder) EmbedBatch(ctx context.Context, texts []string) ([][]float32, error) {
vectors := make([][]float32, len(texts))
for i, text := range texts {
vec, err := d.Embed(ctx, text)
if err != nil {
return nil, err
}
vectors[i] = vec
}
return vectors, nil
}
func (d *DummyEmbedder) Dim() int {
return d.dim
}
func main() {
ctx := context.Background()
// 1. Open database with an embedder
db, err := cortexdb.Open(
cortexdb.DefaultConfig("test.db"),
cortexdb.WithEmbedder(NewDummyEmbedder(128)),
)
if err != nil {
panic(err)
}
defer db.Close()
// 2. Insert text - embedding is generated automatically
err = db.InsertText(ctx, "doc1", "The quick brown fox jumps over the lazy dog", nil)
if err != nil {
panic(err)
}
// 3. Search using text - query embedding is generated automatically
results, err := db.SearchText(ctx, "fox jumps", 5)
if err != nil {
panic(err)
}
for _, r := range results {
fmt.Printf("Score: %.3f, Content: %s\n", r.Score, r.Content)
}
}
Output:
Example (TextOnly) ¶
Example_textOnly shows how to use text-only search without an embedder
package main
import (
"context"
"fmt"
mrand "math/rand"
"github.com/liliang-cn/cortexdb/v2/pkg/cortexdb"
)
func main() {
ctx := context.Background()
// 1. Open database WITHOUT an embedder
db, err := cortexdb.Open(cortexdb.DefaultConfig("test.db"))
if err != nil {
panic(err)
}
defer db.Close()
// 2. Insert vectors manually (you need to provide the vectors)
vector := make([]float32, 128)
for i := range vector {
vector[i] = mrand.Float32() // Just for demo - use real embeddings
}
quick := db.Quick()
id, err := quick.Add(ctx, vector, "The quick brown fox jumps over the lazy dog")
if err != nil {
panic(err)
}
fmt.Println("Inserted:", id)
// 3. Search using FTS5 text search (no embedding needed!)
results, err := db.SearchTextOnly(ctx, "fox OR dog", cortexdb.TextSearchOptions{
TopK: 5,
})
if err != nil {
panic(err)
}
for _, r := range results {
fmt.Printf("Score: %.3f, Content: %s\n", r.Score, r.Content)
}
}
Output:
Index ¶
- Constants
- Variables
- func DefaultDBPath() string
- func EntityNodeID(idOrName string) string
- func KnowledgeMemoryCollectEntities(seed []string, memories []MemorySearchHit, knowledge []KnowledgeSearchHit, ...) []string
- func KnowledgeMemoryThemes(req KnowledgeMemoryReflectRequest, recall KnowledgeMemoryRecallResponse, ...) []string
- type ApplyInferenceRequest
- type ApplyInferenceResponse
- type BaseEmbedder
- type Config
- type DB
- func (db *DB) ApplyInferenceRules(ctx context.Context, req ApplyInferenceRequest) (*ApplyInferenceResponse, error)
- func (db *DB) Close() error
- func (db *DB) DeleteKnowledge(ctx context.Context, req KnowledgeDeleteRequest) (*KnowledgeDeleteResponse, error)
- func (db *DB) DeleteKnowledgeGraph(ctx context.Context, req KnowledgeGraphDeleteRequest) (*KnowledgeGraphDeleteResponse, error)
- func (db *DB) DeleteMemory(ctx context.Context, req MemoryDeleteRequest) (*MemoryDeleteResponse, error)
- func (db *DB) DeleteOntologySchema(ctx context.Context, req OntologyDeleteRequest) (*OntologyDeleteResponse, error)
- func (db *DB) ExplainKnowledgeGraphInference(ctx context.Context, req KnowledgeGraphInferenceExplainRequest) (*KnowledgeGraphInferenceExplainResponse, error)
- func (db *DB) ExplainKnowledgeGraphInferenceMatch(ctx context.Context, req KnowledgeGraphInferenceExplainMatchRequest) (*KnowledgeGraphInferenceExplainMatchResponse, error)
- func (db *DB) ExportKnowledgeGraph(ctx context.Context, req KnowledgeGraphExportRequest) (*KnowledgeGraphExportResponse, error)
- func (db *DB) FindKnowledgeGraph(ctx context.Context, req KnowledgeGraphFindRequest) (*KnowledgeGraphFindResponse, error)
- func (db *DB) GetKnowledge(ctx context.Context, req KnowledgeGetRequest) (*KnowledgeGetResponse, error)
- func (db *DB) GetMemory(ctx context.Context, req MemoryGetRequest) (*MemoryGetResponse, error)
- func (db *DB) GetOntologySchema(ctx context.Context, req OntologyGetRequest) (*OntologyGetResponse, error)
- func (db *DB) Graph() *graph.GraphStore
- func (db *DB) GraphRAGTools() *GraphRAGToolbox
- func (db *DB) HasEmbedder() bool
- func (db *DB) HybridSearchText(ctx context.Context, query string, topK int) ([]core.ScoredEmbedding, error)
- func (db *DB) HybridSearchTextWithOptions(ctx context.Context, query string, opts TextSearchOptions) ([]core.ScoredEmbedding, error)
- func (db *DB) ImportKnowledgeGraph(ctx context.Context, req KnowledgeGraphImportRequest) (*KnowledgeGraphImportResponse, error)
- func (db *DB) Info() DBInfo
- func (db *DB) InsertGraphDocument(ctx context.Context, doc GraphRAGDocument, opts GraphRAGIngestOptions) (*GraphRAGIngestResult, error)
- func (db *DB) InsertText(ctx context.Context, id string, text string, metadata map[string]string) error
- func (db *DB) InsertTextBatch(ctx context.Context, texts map[string]string, metadata map[string]string) error
- func (db *DB) InsertTextBatchWithVectors(ctx context.Context, texts map[string]string, vectors [][]float32, ...) error
- func (db *DB) InsertTextWithVector(ctx context.Context, id string, text string, vector []float32, ...) error
- func (db *DB) KnowledgeMemory() *KnowledgeMemory
- func (db *DB) ListAllMemories(ctx context.Context) ([]MemoryRecord, error)
- func (db *DB) ListKnowledgeNamespaces(ctx context.Context) (*KnowledgeGraphNamespaceListResponse, error)
- func (db *DB) ListOntologySchemas(ctx context.Context, req OntologyListRequest) (*OntologyListResponse, error)
- func (db *DB) NewMCPServer(opts MCPServerOptions) *mcp.Server
- func (db *DB) Query(ctx context.Context, req QueryRequest) (*QueryResponse, error)
- func (db *DB) QueryKnowledgeGraph(ctx context.Context, req KnowledgeGraphQueryRequest) (*KnowledgeGraphQueryResponse, error)
- func (db *DB) Quick() *Quick
- func (db *DB) RefreshKnowledgeGraphInference(ctx context.Context, req KnowledgeGraphInferenceRefreshRequest) (*KnowledgeGraphInferenceRefreshResponse, error)
- func (db *DB) RunMCPStdio(ctx context.Context, opts MCPServerOptions) error
- func (db *DB) SQL() *sql.DB
- func (db *DB) SaveKnowledge(ctx context.Context, req KnowledgeSaveRequest) (*KnowledgeSaveResponse, error)
- func (db *DB) SaveMemory(ctx context.Context, req MemorySaveRequest) (*MemorySaveResponse, error)
- func (db *DB) SaveOntologySchema(ctx context.Context, req OntologySaveRequest) (*OntologySaveResponse, error)
- func (db *DB) SearchGraphRAG(ctx context.Context, query string, opts GraphRAGQueryOptions) (*GraphRAGQueryResult, error)
- func (db *DB) SearchKnowledge(ctx context.Context, req KnowledgeSearchRequest) (*KnowledgeSearchResponse, error)
- func (db *DB) SearchMemory(ctx context.Context, req MemorySearchRequest) (*MemorySearchResponse, error)
- func (db *DB) SearchText(ctx context.Context, query string, topK int) ([]core.ScoredEmbedding, error)
- func (db *DB) SearchTextInCollection(ctx context.Context, collection string, query string, topK int) ([]core.ScoredEmbedding, error)
- func (db *DB) SearchTextOnly(ctx context.Context, query string, opts TextSearchOptions) ([]core.ScoredEmbedding, error)
- func (db *DB) SummarizeKnowledgeGraphInference(ctx context.Context, _ KnowledgeGraphInferenceSummaryRequest) (*KnowledgeGraphInferenceSummaryResponse, error)
- func (db *DB) UpdateKnowledge(ctx context.Context, req KnowledgeUpdateRequest) (*KnowledgeSaveResponse, error)
- func (db *DB) UpdateMemory(ctx context.Context, req MemoryUpdateRequest) (*MemorySaveResponse, error)
- func (db *DB) UpsertKnowledgeGraph(ctx context.Context, req KnowledgeGraphUpsertRequest) (*KnowledgeGraphUpsertResponse, error)
- func (db *DB) UpsertKnowledgeNamespace(ctx context.Context, req KnowledgeGraphNamespaceUpsertRequest) (*KnowledgeGraphNamespaceUpsertResponse, error)
- func (db *DB) ValidateKnowledgeGraphSHACL(ctx context.Context, req KnowledgeGraphSHACLValidateRequest) (*KnowledgeGraphSHACLValidateResponse, error)
- func (db *DB) Vector() core.Store
- type DBInfo
- type Embedder
- type ExtractedRelation
- type GraphEntity
- type GraphExtraction
- type GraphRAGChunkResult
- type GraphRAGDocument
- type GraphRAGExtractor
- type GraphRAGIngestOptions
- type GraphRAGIngestResult
- type GraphRAGQueryOptions
- type GraphRAGQueryResult
- type GraphRAGToolbox
- func (t *GraphRAGToolbox) ApplyInferenceRules(ctx context.Context, req ApplyInferenceRequest) (*ApplyInferenceResponse, error)
- func (t *GraphRAGToolbox) BuildContext(ctx context.Context, req ToolBuildContextRequest) (*ToolBuildContextResponse, error)
- func (t *GraphRAGToolbox) Call(ctx context.Context, name string, input json.RawMessage) (any, error)
- func (t *GraphRAGToolbox) Definitions() []ToolDefinition
- func (t *GraphRAGToolbox) DeleteKnowledge(ctx context.Context, req KnowledgeDeleteRequest) (*KnowledgeDeleteResponse, error)
- func (t *GraphRAGToolbox) DeleteKnowledgeGraph(ctx context.Context, req KnowledgeGraphDeleteRequest) (*KnowledgeGraphDeleteResponse, error)
- func (t *GraphRAGToolbox) DeleteMemory(ctx context.Context, req MemoryDeleteRequest) (*MemoryDeleteResponse, error)
- func (t *GraphRAGToolbox) DeleteOntologySchema(ctx context.Context, req OntologyDeleteRequest) (*OntologyDeleteResponse, error)
- func (t *GraphRAGToolbox) ExpandGraph(ctx context.Context, req ToolExpandGraphRequest) (*ToolExpandGraphResponse, error)
- func (t *GraphRAGToolbox) ExplainKnowledgeGraphInference(ctx context.Context, req KnowledgeGraphInferenceExplainRequest) (*KnowledgeGraphInferenceExplainResponse, error)
- func (t *GraphRAGToolbox) ExplainKnowledgeGraphInferenceMatch(ctx context.Context, req KnowledgeGraphInferenceExplainMatchRequest) (*KnowledgeGraphInferenceExplainMatchResponse, error)
- func (t *GraphRAGToolbox) ExportKnowledgeGraph(ctx context.Context, req KnowledgeGraphExportRequest) (*KnowledgeGraphExportResponse, error)
- func (t *GraphRAGToolbox) ExtractConversation(ctx context.Context, req ToolExtractConversationRequest) (*ToolExtractConversationResponse, error)
- func (t *GraphRAGToolbox) FindKnowledgeGraph(ctx context.Context, req KnowledgeGraphFindRequest) (*KnowledgeGraphFindResponse, error)
- func (t *GraphRAGToolbox) GetChunks(ctx context.Context, req ToolGetChunksRequest) (*ToolGetChunksResponse, error)
- func (t *GraphRAGToolbox) GetKnowledge(ctx context.Context, req KnowledgeGetRequest) (*KnowledgeGetResponse, error)
- func (t *GraphRAGToolbox) GetMemory(ctx context.Context, req MemoryGetRequest) (*MemoryGetResponse, error)
- func (t *GraphRAGToolbox) GetNodes(ctx context.Context, req ToolGetNodesRequest) (*ToolGetNodesResponse, error)
- func (t *GraphRAGToolbox) GetOntologySchema(ctx context.Context, req OntologyGetRequest) (*OntologyGetResponse, error)
- func (t *GraphRAGToolbox) ImportKnowledgeGraph(ctx context.Context, req KnowledgeGraphImportRequest) (*KnowledgeGraphImportResponse, error)
- func (t *GraphRAGToolbox) IngestDocument(ctx context.Context, req ToolIngestDocumentRequest) (*ToolIngestDocumentResponse, error)
- func (t *GraphRAGToolbox) KnowledgeMemoryBuildContextPack(ctx context.Context, req KnowledgeMemoryBuildContextPackRequest) (*KnowledgeMemoryBuildContextPackResponse, error)
- func (t *GraphRAGToolbox) KnowledgeMemoryConsolidate(ctx context.Context, req KnowledgeMemoryConsolidateRequest) (*KnowledgeMemoryConsolidateResponse, error)
- func (t *GraphRAGToolbox) KnowledgeMemoryExpandEntityContext(ctx context.Context, req KnowledgeMemoryExpandEntityContextRequest) (*KnowledgeMemoryExpandEntityContextResponse, error)
- func (t *GraphRAGToolbox) KnowledgeMemoryNeighbors(ctx context.Context, req KnowledgeMemoryNeighborsRequest) (*KnowledgeMemoryNeighborsResponse, error)
- func (t *GraphRAGToolbox) KnowledgeMemoryPromoteToKnowledge(ctx context.Context, req KnowledgeMemoryPromoteToKnowledgeRequest) (*KnowledgeMemoryPromoteToKnowledgeResponse, error)
- func (t *GraphRAGToolbox) KnowledgeMemoryRecall(ctx context.Context, req KnowledgeMemoryRecallRequest) (*KnowledgeMemoryRecallResponse, error)
- func (t *GraphRAGToolbox) KnowledgeMemoryReflect(ctx context.Context, req KnowledgeMemoryReflectRequest) (*KnowledgeMemoryReflectResponse, error)
- func (t *GraphRAGToolbox) KnowledgeMemoryRemember(ctx context.Context, req KnowledgeMemoryRememberRequest) (*KnowledgeMemoryRememberResponse, error)
- func (t *GraphRAGToolbox) KnowledgeMemoryShortestPath(ctx context.Context, req KnowledgeMemoryShortestPathRequest) (*KnowledgeMemoryShortestPathResponse, error)
- func (t *GraphRAGToolbox) ListKnowledgeNamespaces(ctx context.Context) (*KnowledgeGraphNamespaceListResponse, error)
- func (t *GraphRAGToolbox) ListOntologySchemas(ctx context.Context, req OntologyListRequest) (*OntologyListResponse, error)
- func (t *GraphRAGToolbox) Query(ctx context.Context, req QueryRequest) (*QueryResponse, error)
- func (t *GraphRAGToolbox) QueryKnowledgeGraph(ctx context.Context, req KnowledgeGraphQueryRequest) (*KnowledgeGraphQueryResponse, error)
- func (t *GraphRAGToolbox) RefreshKnowledgeGraphInference(ctx context.Context, req KnowledgeGraphInferenceRefreshRequest) (*KnowledgeGraphInferenceRefreshResponse, error)
- func (t *GraphRAGToolbox) SaveKnowledge(ctx context.Context, req KnowledgeSaveRequest) (*KnowledgeSaveResponse, error)
- func (t *GraphRAGToolbox) SaveMemory(ctx context.Context, req MemorySaveRequest) (*MemorySaveResponse, error)
- func (t *GraphRAGToolbox) SaveOntologySchema(ctx context.Context, req OntologySaveRequest) (*OntologySaveResponse, error)
- func (t *GraphRAGToolbox) SearchChunksByEntities(ctx context.Context, req ToolSearchChunksByEntitiesRequest) (*ToolSearchChunksByEntitiesResponse, error)
- func (t *GraphRAGToolbox) SearchGraphRAGLexical(ctx context.Context, req ToolSearchGraphRAGLexicalRequest) (*GraphRAGQueryResult, error)
- func (t *GraphRAGToolbox) SearchKnowledge(ctx context.Context, req KnowledgeSearchRequest) (*KnowledgeSearchResponse, error)
- func (t *GraphRAGToolbox) SearchMemory(ctx context.Context, req MemorySearchRequest) (*MemorySearchResponse, error)
- func (t *GraphRAGToolbox) SearchText(ctx context.Context, req ToolSearchTextRequest) (*ToolSearchTextResponse, error)
- func (t *GraphRAGToolbox) SummarizeKnowledgeGraphInference(ctx context.Context, req KnowledgeGraphInferenceSummaryRequest) (*KnowledgeGraphInferenceSummaryResponse, error)
- func (t *GraphRAGToolbox) UpdateKnowledge(ctx context.Context, req KnowledgeUpdateRequest) (*KnowledgeSaveResponse, error)
- func (t *GraphRAGToolbox) UpdateMemory(ctx context.Context, req MemoryUpdateRequest) (*MemorySaveResponse, error)
- func (t *GraphRAGToolbox) UpsertEntities(ctx context.Context, req ToolUpsertEntitiesRequest) (*ToolUpsertEntitiesResponse, error)
- func (t *GraphRAGToolbox) UpsertKnowledgeGraph(ctx context.Context, req KnowledgeGraphUpsertRequest) (*KnowledgeGraphUpsertResponse, error)
- func (t *GraphRAGToolbox) UpsertKnowledgeNamespace(ctx context.Context, req KnowledgeGraphNamespaceUpsertRequest) (*KnowledgeGraphNamespaceUpsertResponse, error)
- func (t *GraphRAGToolbox) UpsertRelations(ctx context.Context, req ToolUpsertRelationsRequest) (*ToolUpsertRelationsResponse, error)
- func (t *GraphRAGToolbox) ValidateKnowledgeGraphSHACL(ctx context.Context, req KnowledgeGraphSHACLValidateRequest) (*KnowledgeGraphSHACLValidateResponse, error)
- type GraphRelationship
- type ImportAgentMemoryOptions
- type ImportAgentMemoryReport
- type InferenceRule
- type KnowledgeDeleteRequest
- type KnowledgeDeleteResponse
- type KnowledgeGetRequest
- type KnowledgeGetResponse
- type KnowledgeGraphDeleteRequest
- type KnowledgeGraphDeleteResponse
- type KnowledgeGraphExportRequest
- type KnowledgeGraphExportResponse
- type KnowledgeGraphFindRequest
- type KnowledgeGraphFindResponse
- type KnowledgeGraphImportRequest
- type KnowledgeGraphImportResponse
- type KnowledgeGraphInferenceExplainMatchRequest
- type KnowledgeGraphInferenceExplainMatchResponse
- type KnowledgeGraphInferenceExplainRequest
- type KnowledgeGraphInferenceExplainResponse
- type KnowledgeGraphInferenceExplanation
- type KnowledgeGraphInferenceMatchExplanation
- type KnowledgeGraphInferenceRefreshRequest
- type KnowledgeGraphInferenceRefreshResponse
- type KnowledgeGraphInferenceRefreshResult
- type KnowledgeGraphInferenceSummary
- type KnowledgeGraphInferenceSummaryRequest
- type KnowledgeGraphInferenceSummaryResponse
- type KnowledgeGraphInferenceTraceEntry
- type KnowledgeGraphNamespace
- type KnowledgeGraphNamespaceListResponse
- type KnowledgeGraphNamespaceUpsertRequest
- type KnowledgeGraphNamespaceUpsertResponse
- type KnowledgeGraphQueryRequest
- type KnowledgeGraphQueryResponse
- type KnowledgeGraphQueryResult
- type KnowledgeGraphSHACLReport
- type KnowledgeGraphSHACLValidateRequest
- type KnowledgeGraphSHACLValidateResponse
- type KnowledgeGraphTerm
- type KnowledgeGraphTriple
- type KnowledgeGraphTriplePattern
- type KnowledgeGraphUpsertRequest
- type KnowledgeGraphUpsertResponse
- type KnowledgeMemory
- func (b *KnowledgeMemory) BuildContextPack(ctx context.Context, req KnowledgeMemoryBuildContextPackRequest) (*KnowledgeMemoryBuildContextPackResponse, error)
- func (b *KnowledgeMemory) Consolidate(ctx context.Context, req KnowledgeMemoryConsolidateRequest) (*KnowledgeMemoryConsolidateResponse, error)
- func (b *KnowledgeMemory) ExpandEntityContext(ctx context.Context, req KnowledgeMemoryExpandEntityContextRequest) (*KnowledgeMemoryExpandEntityContextResponse, error)
- func (b *KnowledgeMemory) Neighbors(ctx context.Context, req KnowledgeMemoryNeighborsRequest) (*KnowledgeMemoryNeighborsResponse, error)
- func (b *KnowledgeMemory) PromoteToKnowledge(ctx context.Context, req KnowledgeMemoryPromoteToKnowledgeRequest) (*KnowledgeMemoryPromoteToKnowledgeResponse, error)
- func (b *KnowledgeMemory) Recall(ctx context.Context, req KnowledgeMemoryRecallRequest) (*KnowledgeMemoryRecallResponse, error)
- func (b *KnowledgeMemory) Reflect(ctx context.Context, req KnowledgeMemoryReflectRequest) (*KnowledgeMemoryReflectResponse, error)
- func (b *KnowledgeMemory) Remember(ctx context.Context, req KnowledgeMemoryRememberRequest) (*KnowledgeMemoryRememberResponse, error)
- func (b *KnowledgeMemory) ShortestPath(ctx context.Context, req KnowledgeMemoryShortestPathRequest) (*KnowledgeMemoryShortestPathResponse, error)
- type KnowledgeMemoryBuildContextPackRequest
- type KnowledgeMemoryBuildContextPackResponse
- type KnowledgeMemoryConsolidateRequest
- type KnowledgeMemoryConsolidateResponse
- type KnowledgeMemoryContextPack
- type KnowledgeMemoryContextSection
- type KnowledgeMemoryExpandEntityContextRequest
- type KnowledgeMemoryExpandEntityContextResponse
- type KnowledgeMemoryGraphFact
- type KnowledgeMemoryNeighborsRequest
- type KnowledgeMemoryNeighborsResponse
- type KnowledgeMemoryPromoteToKnowledgeRequest
- type KnowledgeMemoryPromoteToKnowledgeResponse
- type KnowledgeMemoryRecallRequest
- type KnowledgeMemoryRecallResponse
- type KnowledgeMemoryReflectInput
- type KnowledgeMemoryReflectRequest
- type KnowledgeMemoryReflectResponse
- type KnowledgeMemoryReflection
- type KnowledgeMemoryReflector
- type KnowledgeMemoryRememberRequest
- type KnowledgeMemoryRememberResponse
- type KnowledgeMemoryShortestPathRequest
- type KnowledgeMemoryShortestPathResponse
- type KnowledgeRecord
- type KnowledgeSaveRequest
- type KnowledgeSaveResponse
- type KnowledgeSearchHit
- type KnowledgeSearchRequest
- type KnowledgeSearchResponse
- type KnowledgeUpdateRequest
- type MCPServerOptions
- type MemoryDeleteRequest
- type MemoryDeleteResponse
- type MemoryGetRequest
- type MemoryGetResponse
- type MemoryRecord
- type MemorySaveRequest
- type MemorySaveResponse
- type MemorySearchHit
- type MemorySearchRequest
- type MemorySearchResponse
- type MemoryUpdateRequest
- type OntologyDeleteRequest
- type OntologyDeleteResponse
- type OntologyEntityType
- type OntologyGetRequest
- type OntologyGetResponse
- type OntologyListRequest
- type OntologyListResponse
- type OntologyRelationType
- type OntologySaveRequest
- type OntologySaveResponse
- type OntologySchema
- type Option
- type QueryCondition
- type QueryFieldBoost
- type QueryFilter
- type QueryNumericBoost
- type QueryPrefetch
- type QueryRequest
- type QueryResponse
- type QueryResult
- type QueryScoreFormula
- type QueryTransform
- type QueryTransformer
- type Quick
- func (q *Quick) Add(ctx context.Context, vector []float32, content string) (string, error)
- func (q *Quick) AddBatchWithVectors(ctx context.Context, vectors [][]float32, contents []string, ...) ([]string, error)
- func (q *Quick) AddBatchWithVectorsToCollection(ctx context.Context, collection string, vectors [][]float32, contents []string, ...) ([]string, error)
- func (q *Quick) AddText(ctx context.Context, text string, metadata map[string]string) (string, error)
- func (q *Quick) AddTextToCollection(ctx context.Context, collection string, text string, ...) (string, error)
- func (q *Quick) AddToCollection(ctx context.Context, collection string, vector []float32, content string) (string, error)
- func (q *Quick) AddWithVector(ctx context.Context, vector []float32, content string, ...) (string, error)
- func (q *Quick) AddWithVectorToCollection(ctx context.Context, collection string, vector []float32, content string, ...) (string, error)
- func (q *Quick) Info() DBInfo
- func (q *Quick) Search(ctx context.Context, query []float32, topK int) ([]core.ScoredEmbedding, error)
- func (q *Quick) SearchInCollection(ctx context.Context, collection string, query []float32, topK int) ([]core.ScoredEmbedding, error)
- func (q *Quick) SearchText(ctx context.Context, query string, topK int) ([]core.ScoredEmbedding, error)
- func (q *Quick) SearchTextInCollection(ctx context.Context, collection string, query string, topK int) ([]core.ScoredEmbedding, error)
- func (q *Quick) SearchTextOnly(ctx context.Context, query string, topK int) ([]core.ScoredEmbedding, error)
- type RerankItem
- type RerankOptions
- type Reranker
- type RetrievalDecision
- type RetrievalFilters
- type RetrievalPlan
- type TextSearchOptions
- type ToolBuildContextRequest
- type ToolBuildContextResponse
- type ToolChunk
- type ToolDefinition
- type ToolEntityInput
- type ToolExpandGraphRequest
- type ToolExpandGraphResponse
- type ToolExtractConversationRequest
- type ToolExtractConversationResponse
- type ToolGetChunksRequest
- type ToolGetChunksResponse
- type ToolGetNodesRequest
- type ToolGetNodesResponse
- type ToolIngestDocumentRequest
- type ToolIngestDocumentResponse
- type ToolRelationInput
- type ToolSearchChunksByEntitiesRequest
- type ToolSearchChunksByEntitiesResponse
- type ToolSearchGraphRAGLexicalRequest
- type ToolSearchTextRequest
- type ToolSearchTextResponse
- type ToolUpsertEntitiesRequest
- type ToolUpsertEntitiesResponse
- type ToolUpsertRelationsRequest
- type ToolUpsertRelationsResponse
Examples ¶
Constants ¶
const ( // RetrievalModeAuto enables lightweight heuristics to decide whether graph expansion is worth the cost. RetrievalModeAuto = "auto" // RetrievalModeLexical disables graph expansion and uses only lexical/vector seed retrieval plus packing. RetrievalModeLexical = "lexical" // RetrievalModeGraph always enables graph expansion and entity enrichment. RetrievalModeGraph = "graph" // RetrievalModeHybrid fuses vector and lexical retrieval with reciprocal // rank fusion. It is what SearchKnowledge uses under auto when an embedder is // available, so exact-keyword and semantic matches are combined. RetrievalModeHybrid = "hybrid" )
const ( // KnowledgeGraphFormatNTriples exports triples in N-Triples format. KnowledgeGraphFormatNTriples = string(graph.RDFFormatNTriples) // KnowledgeGraphFormatNQuads exports triples/quads in N-Quads format. KnowledgeGraphFormatNQuads = string(graph.RDFFormatNQuads) // KnowledgeGraphFormatTurtle exports default-graph triples in Turtle format. KnowledgeGraphFormatTurtle = string(graph.RDFFormatTurtle) // KnowledgeGraphFormatTriG exports quads in TriG format. KnowledgeGraphFormatTriG = string(graph.RDFFormatTriG) // KnowledgeGraphInferenceRefreshModeFull forces a full inferred-triple rebuild. KnowledgeGraphInferenceRefreshModeFull = "full" // KnowledgeGraphInferenceRefreshModeIncremental recomputes only the neighborhood // affected by the supplied triples, IDs, or pattern. KnowledgeGraphInferenceRefreshModeIncremental = "incremental" )
const ( // MemoryScopeGlobal stores memories in a shared global bucket. MemoryScopeGlobal = "global" // MemoryScopeUser stores memories in a per-user bucket. MemoryScopeUser = "user" // MemoryScopeSession stores memories in a per-session bucket. MemoryScopeSession = "session" )
const ( QueryPrefetchVector = "vector" QueryPrefetchLexical = "lexical" QueryPrefetchHybrid = "hybrid" QueryPrefetchGraph = "graph" QueryFusionRRF = "rrf" QueryFusionWeightedRRF = "weighted_rrf" QueryFusionDBSF = "dbsf" QueryFilterEqual = "eq" QueryFilterNotEqual = "neq" QueryFilterIn = "in" QueryFilterContains = "contains" QueryFilterGTE = "gte" QueryFilterLTE = "lte" )
Variables ¶
var ( // ErrEmbedderNotConfigured is returned when text operations are called // but no embedder was configured during initialization. ErrEmbedderNotConfigured = errors.New("cortexdb: embedder not configured, use WithEmbedder option or call vector methods directly") // ErrEmptyText is returned when an empty text string is provided. ErrEmptyText = errors.New("cortexdb: empty text provided") // ErrEmbeddingFailed is returned when the embedder fails to produce a vector. ErrEmbeddingFailed = errors.New("cortexdb: embedding failed") // ErrInvalidVector is returned when a vector is invalid (nil or wrong dimension). ErrInvalidVector = errors.New("cortexdb: invalid vector") )
Errors related to embedder operations
Functions ¶
func DefaultDBPath ¶ added in v2.36.0
func DefaultDBPath() string
DefaultDBPath returns the default database path for the CortexDB tools and plugin: a single global store at ~/.cortexdb/cortexdb.db, so every session on a machine shares one memory/knowledge brain instead of a separate per-project file. Multiple processes may open this file concurrently — SQLite runs in WAL mode, so concurrent readers plus a serialized writer are safe on local disk.
If the user home directory cannot be resolved, it falls back to a relative .cortexdb/cortexdb.db in the current directory. Callers should still honor an explicit CORTEXDB_PATH override before using this default.
func EntityNodeID ¶ added in v2.26.0
EntityNodeID returns the normalized graph node id that cortexdb stores an entity under, given its raw id or name. Consumers that need to map a chunk or source id to its entity node (e.g. to seed ExpandGraph) should use this rather than reimplementing the normalization, which is otherwise an internal detail.
func KnowledgeMemoryCollectEntities ¶ added in v2.18.0
func KnowledgeMemoryCollectEntities(seed []string, memories []MemorySearchHit, knowledge []KnowledgeSearchHit, chunks []GraphRAGChunkResult) []string
func KnowledgeMemoryThemes ¶ added in v2.18.0
func KnowledgeMemoryThemes(req KnowledgeMemoryReflectRequest, recall KnowledgeMemoryRecallResponse, maxThemes int) []string
Types ¶
type ApplyInferenceRequest ¶ added in v2.14.0
type ApplyInferenceRequest struct {
DocumentID string `json:"document_id,omitempty"`
Rules []InferenceRule `json:"rules"`
DeleteExisting bool `json:"delete_existing,omitempty"`
}
ApplyInferenceRequest executes deterministic inference rules against stored relations.
type ApplyInferenceResponse ¶ added in v2.14.0
type ApplyInferenceResponse struct {
CreatedEdgeIDs []string `json:"created_edge_ids"`
DeletedEdgeIDs []string `json:"deleted_edge_ids,omitempty"`
}
ApplyInferenceResponse summarizes inferred edge materialization.
type BaseEmbedder ¶
type BaseEmbedder struct {
// contains filtered or unexported fields
}
BaseEmbedder provides a default implementation of EmbedBatch that calls Embed for each text. Embedders can embed this to get batch support for free.
func (*BaseEmbedder) EmbedBatch ¶
EmbedBatch provides a default batch implementation using goroutines.
type Config ¶
type Config struct {
Path string // Database file path
Dimensions int // Vector dimensions (0 for auto-detect)
SimilarityFn core.SimilarityFunc // Similarity function (default: cosine)
IndexType core.IndexType // Index type (HNSW, IVF, Flat)
}
Config represents database configuration
func DefaultConfig ¶
DefaultConfig returns default configuration
type DB ¶
type DB struct {
KnowledgeMemoryReflector KnowledgeMemoryReflector
// contains filtered or unexported fields
}
DB represents a SQLite vector database instance
func Open ¶
Open opens or creates a vector database. Additional options can be passed to configure the database, such as WithEmbedder.
func (*DB) ApplyInferenceRules ¶ added in v2.14.0
func (db *DB) ApplyInferenceRules(ctx context.Context, req ApplyInferenceRequest) (*ApplyInferenceResponse, error)
ApplyInferenceRules materializes inferred relation edges from explicit relation edges.
func (*DB) DeleteKnowledge ¶ added in v2.12.0
func (db *DB) DeleteKnowledge(ctx context.Context, req KnowledgeDeleteRequest) (*KnowledgeDeleteResponse, error)
DeleteKnowledge removes a knowledge item and its retrieval artifacts.
func (*DB) DeleteKnowledgeGraph ¶ added in v2.16.0
func (db *DB) DeleteKnowledgeGraph(ctx context.Context, req KnowledgeGraphDeleteRequest) (*KnowledgeGraphDeleteResponse, error)
DeleteKnowledgeGraph removes triples/quads from the embedded knowledge graph.
func (*DB) DeleteMemory ¶ added in v2.12.0
func (db *DB) DeleteMemory(ctx context.Context, req MemoryDeleteRequest) (*MemoryDeleteResponse, error)
DeleteMemory removes a memory record by ID.
func (*DB) DeleteOntologySchema ¶ added in v2.14.0
func (db *DB) DeleteOntologySchema(ctx context.Context, req OntologyDeleteRequest) (*OntologyDeleteResponse, error)
DeleteOntologySchema deletes one ontology-lite schema.
func (*DB) ExplainKnowledgeGraphInference ¶ added in v2.16.0
func (db *DB) ExplainKnowledgeGraphInference(ctx context.Context, req KnowledgeGraphInferenceExplainRequest) (*KnowledgeGraphInferenceExplainResponse, error)
ExplainKnowledgeGraphInference returns provenance for one explicit or inferred triple.
func (*DB) ExplainKnowledgeGraphInferenceMatch ¶ added in v2.18.0
func (db *DB) ExplainKnowledgeGraphInferenceMatch(ctx context.Context, req KnowledgeGraphInferenceExplainMatchRequest) (*KnowledgeGraphInferenceExplainMatchResponse, error)
ExplainKnowledgeGraphInferenceMatch expands explanations for all triples matched by a pattern.
func (*DB) ExportKnowledgeGraph ¶ added in v2.16.0
func (db *DB) ExportKnowledgeGraph(ctx context.Context, req KnowledgeGraphExportRequest) (*KnowledgeGraphExportResponse, error)
ExportKnowledgeGraph serializes RDF content from the embedded knowledge graph.
func (*DB) FindKnowledgeGraph ¶ added in v2.16.0
func (db *DB) FindKnowledgeGraph(ctx context.Context, req KnowledgeGraphFindRequest) (*KnowledgeGraphFindResponse, error)
FindKnowledgeGraph queries triples/quads from the embedded knowledge graph.
func (*DB) GetKnowledge ¶ added in v2.12.0
func (db *DB) GetKnowledge(ctx context.Context, req KnowledgeGetRequest) (*KnowledgeGetResponse, error)
GetKnowledge fetches a durable knowledge item by ID.
func (*DB) GetMemory ¶ added in v2.12.0
func (db *DB) GetMemory(ctx context.Context, req MemoryGetRequest) (*MemoryGetResponse, error)
GetMemory fetches a memory record by ID.
func (*DB) GetOntologySchema ¶ added in v2.14.0
func (db *DB) GetOntologySchema(ctx context.Context, req OntologyGetRequest) (*OntologyGetResponse, error)
GetOntologySchema fetches one ontology-lite schema by ID.
func (*DB) GraphRAGTools ¶ added in v2.11.0
func (db *DB) GraphRAGTools() *GraphRAGToolbox
GraphRAGTools returns the tool/function surface intended for external LLM orchestration.
func (*DB) HasEmbedder ¶ added in v2.11.0
HasEmbedder reports whether the DB has an in-process embedder configured.
func (*DB) HybridSearchText ¶
func (db *DB) HybridSearchText(ctx context.Context, query string, topK int) ([]core.ScoredEmbedding, error)
HybridSearchText performs hybrid search combining vector and keyword matching.
func (*DB) HybridSearchTextWithOptions ¶ added in v2.33.0
func (db *DB) HybridSearchTextWithOptions(ctx context.Context, query string, opts TextSearchOptions) ([]core.ScoredEmbedding, error)
HybridSearchTextWithOptions is the full retrieval pipeline for production RAG: hybrid recall (vector + BM25 when an embedder is set, BM25-only otherwise), then the optional retrieval-layer stages in order:
recall(over-fetch) → Authorize(RBAC/ABAC) → Reranker → MinScore → TopK
Keeping these stages inside the retrieval call makes access control and the relevance floor non-bypassable by callers.
func (*DB) ImportKnowledgeGraph ¶ added in v2.16.0
func (db *DB) ImportKnowledgeGraph(ctx context.Context, req KnowledgeGraphImportRequest) (*KnowledgeGraphImportResponse, error)
ImportKnowledgeGraph parses RDF content into the embedded knowledge graph.
func (*DB) Info ¶
Info returns information about the database configuration. It includes the database path, vector dimensions, index type, and other non-sensitive configuration parameters.
func (*DB) InsertGraphDocument ¶ added in v2.10.0
func (db *DB) InsertGraphDocument(ctx context.Context, doc GraphRAGDocument, opts GraphRAGIngestOptions) (*GraphRAGIngestResult, error)
InsertGraphDocument ingests a document into the vector store and graph store for GraphRAG retrieval.
func (*DB) InsertText ¶
func (db *DB) InsertText(ctx context.Context, id string, text string, metadata map[string]string) error
InsertText inserts text with automatic embedding generation.
func (*DB) InsertTextBatch ¶
func (db *DB) InsertTextBatch(ctx context.Context, texts map[string]string, metadata map[string]string) error
InsertTextBatch inserts multiple texts with automatic embedding generation.
func (*DB) InsertTextBatchWithVectors ¶ added in v2.13.0
func (db *DB) InsertTextBatchWithVectors(ctx context.Context, texts map[string]string, vectors [][]float32, metadata map[string]string) error
InsertTextBatchWithVectors inserts multiple texts with pre-computed vectors.
func (*DB) InsertTextWithVector ¶ added in v2.13.0
func (db *DB) InsertTextWithVector(ctx context.Context, id string, text string, vector []float32, metadata map[string]string) error
InsertTextWithVector inserts text with a pre-computed vector.
func (*DB) KnowledgeMemory ¶ added in v2.15.1
func (db *DB) KnowledgeMemory() *KnowledgeMemory
KnowledgeMemory returns the high-level memory/knowledge facade over memory, knowledge, graph, and context packing APIs.
func (*DB) ListAllMemories ¶ added in v2.53.0
func (db *DB) ListAllMemories(ctx context.Context) ([]MemoryRecord, error)
ListAllMemories returns every stored memory record across all scopes, newest first, skipping expired ones. It scans the memory buckets only (session ids under the `memory:` prefix), not arbitrary chat history. Intended for export/backup — see the --export-memory tool.
func (*DB) ListKnowledgeNamespaces ¶ added in v2.16.0
func (db *DB) ListKnowledgeNamespaces(ctx context.Context) (*KnowledgeGraphNamespaceListResponse, error)
ListKnowledgeNamespaces returns the registered knowledge-graph namespaces.
func (*DB) ListOntologySchemas ¶ added in v2.14.0
func (db *DB) ListOntologySchemas(ctx context.Context, req OntologyListRequest) (*OntologyListResponse, error)
ListOntologySchemas lists ontology-lite schemas.
func (*DB) NewMCPServer ¶ added in v2.11.0
func (db *DB) NewMCPServer(opts MCPServerOptions) *mcp.Server
NewMCPServer returns an MCP server that exposes the GraphRAG tool surface.
func (*DB) Query ¶ added in v2.27.0
func (db *DB) Query(ctx context.Context, req QueryRequest) (*QueryResponse, error)
Query runs a composable retrieval request over CortexDB embeddings.
func (*DB) QueryKnowledgeGraph ¶ added in v2.16.0
func (db *DB) QueryKnowledgeGraph(ctx context.Context, req KnowledgeGraphQueryRequest) (*KnowledgeGraphQueryResponse, error)
QueryKnowledgeGraph executes a SPARQL SELECT/ASK subset against the embedded knowledge graph.
func (*DB) RefreshKnowledgeGraphInference ¶ added in v2.16.0
func (db *DB) RefreshKnowledgeGraphInference(ctx context.Context, req KnowledgeGraphInferenceRefreshRequest) (*KnowledgeGraphInferenceRefreshResponse, error)
RefreshKnowledgeGraphInference recomputes persisted RDFS-lite inferred triples.
func (*DB) RunMCPStdio ¶ added in v2.11.0
func (db *DB) RunMCPStdio(ctx context.Context, opts MCPServerOptions) error
RunMCPStdio runs the CortexDB MCP server over stdin/stdout.
func (*DB) SQL ¶ added in v2.19.0
SQL returns the underlying *sql.DB handle. It is intended for sibling workflow packages that need to manage their own tables on the same SQLite file (e.g. pkg/agentmem). Callers must not close the returned handle.
func (*DB) SaveKnowledge ¶ added in v2.12.0
func (db *DB) SaveKnowledge(ctx context.Context, req KnowledgeSaveRequest) (*KnowledgeSaveResponse, error)
SaveKnowledge stores or replaces a knowledge item and its retrieval artifacts.
func (*DB) SaveMemory ¶ added in v2.12.0
func (db *DB) SaveMemory(ctx context.Context, req MemorySaveRequest) (*MemorySaveResponse, error)
SaveMemory stores a memory record in a resolved memory bucket.
func (*DB) SaveOntologySchema ¶ added in v2.14.0
func (db *DB) SaveOntologySchema(ctx context.Context, req OntologySaveRequest) (*OntologySaveResponse, error)
SaveOntologySchema stores or updates an ontology-lite schema.
func (*DB) SearchGraphRAG ¶ added in v2.10.0
func (db *DB) SearchGraphRAG(ctx context.Context, query string, opts GraphRAGQueryOptions) (*GraphRAGQueryResult, error)
SearchGraphRAG performs seed chunk retrieval plus graph neighborhood expansion.
func (*DB) SearchKnowledge ¶ added in v2.12.0
func (db *DB) SearchKnowledge(ctx context.Context, req KnowledgeSearchRequest) (*KnowledgeSearchResponse, error)
SearchKnowledge searches durable knowledge and groups chunk results by knowledge document.
func (*DB) SearchMemory ¶ added in v2.12.0
func (db *DB) SearchMemory(ctx context.Context, req MemorySearchRequest) (*MemorySearchResponse, error)
SearchMemory searches a resolved memory bucket, using semantic session search when an embedder is available.
func (*DB) SearchText ¶
func (db *DB) SearchText(ctx context.Context, query string, topK int) ([]core.ScoredEmbedding, error)
SearchText performs similarity search using text query.
func (*DB) SearchTextInCollection ¶
func (db *DB) SearchTextInCollection(ctx context.Context, collection string, query string, topK int) ([]core.ScoredEmbedding, error)
SearchTextInCollection performs similarity search using text query within a collection.
func (*DB) SearchTextOnly ¶
func (db *DB) SearchTextOnly(ctx context.Context, query string, opts TextSearchOptions) ([]core.ScoredEmbedding, error)
SearchTextOnly performs pure FTS5 full-text search without embeddings.
func (*DB) SummarizeKnowledgeGraphInference ¶ added in v2.18.0
func (db *DB) SummarizeKnowledgeGraphInference(ctx context.Context, _ KnowledgeGraphInferenceSummaryRequest) (*KnowledgeGraphInferenceSummaryResponse, error)
SummarizeKnowledgeGraphInference returns persisted inference counts and rule breakdowns.
func (*DB) UpdateKnowledge ¶ added in v2.12.0
func (db *DB) UpdateKnowledge(ctx context.Context, req KnowledgeUpdateRequest) (*KnowledgeSaveResponse, error)
UpdateKnowledge updates a knowledge item and refreshes retrieval artifacts when necessary.
func (*DB) UpdateMemory ¶ added in v2.12.0
func (db *DB) UpdateMemory(ctx context.Context, req MemoryUpdateRequest) (*MemorySaveResponse, error)
UpdateMemory updates a memory record and refreshes its vector when needed.
func (*DB) UpsertKnowledgeGraph ¶ added in v2.16.0
func (db *DB) UpsertKnowledgeGraph(ctx context.Context, req KnowledgeGraphUpsertRequest) (*KnowledgeGraphUpsertResponse, error)
UpsertKnowledgeGraph writes RDF triples/quads into the embedded knowledge graph.
func (*DB) UpsertKnowledgeNamespace ¶ added in v2.16.0
func (db *DB) UpsertKnowledgeNamespace(ctx context.Context, req KnowledgeGraphNamespaceUpsertRequest) (*KnowledgeGraphNamespaceUpsertResponse, error)
UpsertKnowledgeNamespace stores or replaces one knowledge-graph namespace.
func (*DB) ValidateKnowledgeGraphSHACL ¶ added in v2.18.0
func (db *DB) ValidateKnowledgeGraphSHACL(ctx context.Context, req KnowledgeGraphSHACLValidateRequest) (*KnowledgeGraphSHACLValidateResponse, error)
ValidateKnowledgeGraphSHACL validates graph data with supplied SHACL-lite shape triples.
type DBInfo ¶
type DBInfo struct {
Path string `json:"path"`
Dimensions int `json:"dimensions"`
IndexType string `json:"indexType"`
SimilarityFn string `json:"similarityFn"`
Embedder string `json:"embedder,omitempty"`
HNSW core.HNSWConfig `json:"hnsw,omitempty"`
IVF core.IVFConfig `json:"ivf,omitempty"`
TextSimilarity core.TextSimilarityConfig `json:"textSimilarity,omitempty"`
Quantization core.QuantizationConfig `json:"quantization,omitempty"`
}
DBInfo provides information about the database instance
type Embedder ¶
type Embedder interface {
// Embed converts a single text string into a vector.
Embed(ctx context.Context, text string) ([]float32, error)
// EmbedBatch converts multiple texts into vectors in a single call.
// This is optional but recommended for better performance with batch operations.
EmbedBatch(ctx context.Context, texts []string) ([][]float32, error)
// Dim returns the dimension of vectors produced by this embedder.
Dim() int
}
Embedder defines the interface for text-to-vector embedding. Users can implement this interface to integrate any embedding model (OpenAI, Ollama, local models, etc.) with cortexdb.
type ExtractedRelation ¶ added in v2.49.0
type ExtractedRelation struct {
From string `json:"from"`
To string `json:"to"`
Type string `json:"type"`
}
ExtractedRelation is a subject-predicate-object relation extracted from text.
type GraphEntity ¶ added in v2.10.0
GraphEntity describes an extracted entity.
type GraphExtraction ¶ added in v2.10.0
type GraphExtraction struct {
Entities []GraphEntity
Relationships []GraphRelationship
}
GraphExtraction holds entities and relationships extracted from text.
type GraphRAGChunkResult ¶ added in v2.10.0
type GraphRAGChunkResult struct {
ID string
DocumentID string
Content string
Score float64
BaseScore float64
RerankScore float64
Entities []string
}
GraphRAGChunkResult is a retrieved chunk plus graph context.
type GraphRAGDocument ¶ added in v2.10.0
GraphRAGDocument is the source unit ingested into the GraphRAG workflow.
type GraphRAGExtractor ¶ added in v2.10.0
type GraphRAGExtractor interface {
Extract(ctx context.Context, text string) (*GraphExtraction, error)
}
GraphRAGExtractor extracts entities and relationships from text.
type GraphRAGIngestOptions ¶ added in v2.10.0
type GraphRAGIngestOptions struct {
Collection string
ChunkSize int
ChunkOverlap int
Extractor GraphRAGExtractor
}
GraphRAGIngestOptions controls GraphRAG ingestion behavior.
type GraphRAGIngestResult ¶ added in v2.10.0
type GraphRAGIngestResult struct {
DocumentNodeID string
ChunkNodeIDs []string
EntityNodeIDs []string
}
GraphRAGIngestResult summarizes the graph artifacts created during ingestion.
type GraphRAGQueryOptions ¶ added in v2.10.0
type GraphRAGQueryOptions struct {
Collection string
TopK int
MaxHops int
MaxRelatedChunks int
MaxContextChunks int
MaxContextChars int
PerDocumentLimit int
Rerank bool
DisableRerank bool
DiversityLambda float64
DisableGraph bool
RetrievalMode string
GraphLight bool
MaxExpansionSeeds int
MaxTraversalNodes int
MaxEntitiesPerChunk int
Plan *RetrievalPlan
// EmbedText, when non-empty, is embedded for the vector query instead of the
// raw query (HyDE). The raw query still drives lexical and graph scoring;
// only the semantic seed vector comes from this hypothetical answer passage.
EmbedText string
}
GraphRAGQueryOptions controls GraphRAG retrieval behavior.
type GraphRAGQueryResult ¶ added in v2.10.0
type GraphRAGQueryResult struct {
Query string
Plan RetrievalPlan
Decision RetrievalDecision
Chunks []GraphRAGChunkResult
Entities []string
Context string
}
GraphRAGQueryResult contains the assembled GraphRAG retrieval output.
type GraphRAGToolbox ¶ added in v2.11.0
type GraphRAGToolbox struct {
// contains filtered or unexported fields
}
GraphRAGToolbox exposes no-embedder-safe functions for external LLM orchestration.
func (*GraphRAGToolbox) ApplyInferenceRules ¶ added in v2.14.0
func (t *GraphRAGToolbox) ApplyInferenceRules(ctx context.Context, req ApplyInferenceRequest) (*ApplyInferenceResponse, error)
ApplyInferenceRules executes deterministic inference through the tool surface.
func (*GraphRAGToolbox) BuildContext ¶ added in v2.11.0
func (t *GraphRAGToolbox) BuildContext(ctx context.Context, req ToolBuildContextRequest) (*ToolBuildContextResponse, error)
BuildContext packs chunk text into a bounded context string.
func (*GraphRAGToolbox) Call ¶ added in v2.11.0
func (t *GraphRAGToolbox) Call(ctx context.Context, name string, input json.RawMessage) (any, error)
Call dispatches a tool request from JSON input to a typed implementation.
func (*GraphRAGToolbox) Definitions ¶ added in v2.11.0
func (t *GraphRAGToolbox) Definitions() []ToolDefinition
Definitions returns the JSON-schema-like definitions for the available tools.
func (*GraphRAGToolbox) DeleteKnowledge ¶ added in v2.12.0
func (t *GraphRAGToolbox) DeleteKnowledge(ctx context.Context, req KnowledgeDeleteRequest) (*KnowledgeDeleteResponse, error)
DeleteKnowledge deletes a knowledge item through the tool surface.
func (*GraphRAGToolbox) DeleteKnowledgeGraph ¶ added in v2.16.0
func (t *GraphRAGToolbox) DeleteKnowledgeGraph(ctx context.Context, req KnowledgeGraphDeleteRequest) (*KnowledgeGraphDeleteResponse, error)
DeleteKnowledgeGraph removes triples/quads via the toolbox surface.
func (*GraphRAGToolbox) DeleteMemory ¶ added in v2.12.0
func (t *GraphRAGToolbox) DeleteMemory(ctx context.Context, req MemoryDeleteRequest) (*MemoryDeleteResponse, error)
DeleteMemory deletes a memory item through the tool surface.
func (*GraphRAGToolbox) DeleteOntologySchema ¶ added in v2.14.0
func (t *GraphRAGToolbox) DeleteOntologySchema(ctx context.Context, req OntologyDeleteRequest) (*OntologyDeleteResponse, error)
DeleteOntologySchema deletes one ontology-lite schema through the tool surface.
func (*GraphRAGToolbox) ExpandGraph ¶ added in v2.11.0
func (t *GraphRAGToolbox) ExpandGraph(ctx context.Context, req ToolExpandGraphRequest) (*ToolExpandGraphResponse, error)
ExpandGraph expands a graph neighborhood and returns a materialized subgraph.
func (*GraphRAGToolbox) ExplainKnowledgeGraphInference ¶ added in v2.16.0
func (t *GraphRAGToolbox) ExplainKnowledgeGraphInference(ctx context.Context, req KnowledgeGraphInferenceExplainRequest) (*KnowledgeGraphInferenceExplainResponse, error)
ExplainKnowledgeGraphInference fetches provenance for a triple via the toolbox surface.
func (*GraphRAGToolbox) ExplainKnowledgeGraphInferenceMatch ¶ added in v2.18.0
func (t *GraphRAGToolbox) ExplainKnowledgeGraphInferenceMatch(ctx context.Context, req KnowledgeGraphInferenceExplainMatchRequest) (*KnowledgeGraphInferenceExplainMatchResponse, error)
ExplainKnowledgeGraphInferenceMatch fetches explanations for triples matched by a pattern.
func (*GraphRAGToolbox) ExportKnowledgeGraph ¶ added in v2.16.0
func (t *GraphRAGToolbox) ExportKnowledgeGraph(ctx context.Context, req KnowledgeGraphExportRequest) (*KnowledgeGraphExportResponse, error)
ExportKnowledgeGraph exports RDF content via the toolbox surface.
func (*GraphRAGToolbox) ExtractConversation ¶ added in v2.49.0
func (t *GraphRAGToolbox) ExtractConversation(ctx context.Context, req ToolExtractConversationRequest) (*ToolExtractConversationResponse, error)
ExtractConversation pulls key information — a summary, themes, entities, and co-occurrence relations — out of conversation text, deterministically (no LLM or embedder). Optionally it persists the result: entities/relations into the knowledge graph and the summary into durable knowledge, so a conversation becomes recallable and graph-queryable in one call.
Extraction is heuristic (proper-noun/identifier entities, sentence co-occurrence, keyword themes, lead-sentence summary); for typed relations and abstractive summaries, run an LLM over the same text and persist via knowledge_save / upsert_relations instead.
func (*GraphRAGToolbox) FindKnowledgeGraph ¶ added in v2.16.0
func (t *GraphRAGToolbox) FindKnowledgeGraph(ctx context.Context, req KnowledgeGraphFindRequest) (*KnowledgeGraphFindResponse, error)
FindKnowledgeGraph queries triples/quads via the toolbox surface.
func (*GraphRAGToolbox) GetChunks ¶ added in v2.11.0
func (t *GraphRAGToolbox) GetChunks(ctx context.Context, req ToolGetChunksRequest) (*ToolGetChunksResponse, error)
GetChunks fetches chunk records by ID.
func (*GraphRAGToolbox) GetKnowledge ¶ added in v2.12.0
func (t *GraphRAGToolbox) GetKnowledge(ctx context.Context, req KnowledgeGetRequest) (*KnowledgeGetResponse, error)
GetKnowledge fetches a knowledge item through the tool surface.
func (*GraphRAGToolbox) GetMemory ¶ added in v2.12.0
func (t *GraphRAGToolbox) GetMemory(ctx context.Context, req MemoryGetRequest) (*MemoryGetResponse, error)
GetMemory fetches a memory item through the tool surface.
func (*GraphRAGToolbox) GetNodes ¶ added in v2.11.0
func (t *GraphRAGToolbox) GetNodes(ctx context.Context, req ToolGetNodesRequest) (*ToolGetNodesResponse, error)
GetNodes fetches graph nodes by ID.
func (*GraphRAGToolbox) GetOntologySchema ¶ added in v2.14.0
func (t *GraphRAGToolbox) GetOntologySchema(ctx context.Context, req OntologyGetRequest) (*OntologyGetResponse, error)
GetOntologySchema fetches one ontology-lite schema through the tool surface.
func (*GraphRAGToolbox) ImportKnowledgeGraph ¶ added in v2.16.0
func (t *GraphRAGToolbox) ImportKnowledgeGraph(ctx context.Context, req KnowledgeGraphImportRequest) (*KnowledgeGraphImportResponse, error)
ImportKnowledgeGraph imports RDF content via the toolbox surface.
func (*GraphRAGToolbox) IngestDocument ¶ added in v2.11.0
func (t *GraphRAGToolbox) IngestDocument(ctx context.Context, req ToolIngestDocumentRequest) (*ToolIngestDocumentResponse, error)
IngestDocument stores lexical chunks and graph nodes without requiring an embedder.
func (*GraphRAGToolbox) KnowledgeMemoryBuildContextPack ¶ added in v2.18.0
func (t *GraphRAGToolbox) KnowledgeMemoryBuildContextPack(ctx context.Context, req KnowledgeMemoryBuildContextPackRequest) (*KnowledgeMemoryBuildContextPackResponse, error)
KnowledgeMemoryBuildContextPack assembles a context pack through the tool surface.
func (*GraphRAGToolbox) KnowledgeMemoryConsolidate ¶ added in v2.18.0
func (t *GraphRAGToolbox) KnowledgeMemoryConsolidate(ctx context.Context, req KnowledgeMemoryConsolidateRequest) (*KnowledgeMemoryConsolidateResponse, error)
KnowledgeMemoryConsolidate reflects, stores a summary memory, and optionally promotes it to knowledge through the tool surface.
func (*GraphRAGToolbox) KnowledgeMemoryExpandEntityContext ¶ added in v2.18.0
func (t *GraphRAGToolbox) KnowledgeMemoryExpandEntityContext(ctx context.Context, req KnowledgeMemoryExpandEntityContextRequest) (*KnowledgeMemoryExpandEntityContextResponse, error)
KnowledgeMemoryExpandEntityContext expands graph context around entities through the tool surface.
func (*GraphRAGToolbox) KnowledgeMemoryNeighbors ¶ added in v2.18.0
func (t *GraphRAGToolbox) KnowledgeMemoryNeighbors(ctx context.Context, req KnowledgeMemoryNeighborsRequest) (*KnowledgeMemoryNeighborsResponse, error)
KnowledgeMemoryNeighbors resolves and returns graph neighbors through the tool surface.
func (*GraphRAGToolbox) KnowledgeMemoryPromoteToKnowledge ¶ added in v2.18.0
func (t *GraphRAGToolbox) KnowledgeMemoryPromoteToKnowledge(ctx context.Context, req KnowledgeMemoryPromoteToKnowledgeRequest) (*KnowledgeMemoryPromoteToKnowledgeResponse, error)
KnowledgeMemoryPromoteToKnowledge promotes memories into durable knowledge through the tool surface.
func (*GraphRAGToolbox) KnowledgeMemoryRecall ¶ added in v2.18.0
func (t *GraphRAGToolbox) KnowledgeMemoryRecall(ctx context.Context, req KnowledgeMemoryRecallRequest) (*KnowledgeMemoryRecallResponse, error)
KnowledgeMemoryRecall retrieves fused memory and knowledge context through the tool surface.
func (*GraphRAGToolbox) KnowledgeMemoryReflect ¶ added in v2.18.0
func (t *GraphRAGToolbox) KnowledgeMemoryReflect(ctx context.Context, req KnowledgeMemoryReflectRequest) (*KnowledgeMemoryReflectResponse, error)
KnowledgeMemoryReflect synthesizes a structured reflection through the tool surface.
func (*GraphRAGToolbox) KnowledgeMemoryRemember ¶ added in v2.18.0
func (t *GraphRAGToolbox) KnowledgeMemoryRemember(ctx context.Context, req KnowledgeMemoryRememberRequest) (*KnowledgeMemoryRememberResponse, error)
KnowledgeMemoryRemember stores a memory item through the tool surface.
func (*GraphRAGToolbox) KnowledgeMemoryShortestPath ¶ added in v2.18.0
func (t *GraphRAGToolbox) KnowledgeMemoryShortestPath(ctx context.Context, req KnowledgeMemoryShortestPathRequest) (*KnowledgeMemoryShortestPathResponse, error)
KnowledgeMemoryShortestPath resolves and returns a graph shortest path through the tool surface.
func (*GraphRAGToolbox) ListKnowledgeNamespaces ¶ added in v2.16.0
func (t *GraphRAGToolbox) ListKnowledgeNamespaces(ctx context.Context) (*KnowledgeGraphNamespaceListResponse, error)
ListKnowledgeNamespaces returns all knowledge-graph namespaces via the toolbox surface.
func (*GraphRAGToolbox) ListOntologySchemas ¶ added in v2.14.0
func (t *GraphRAGToolbox) ListOntologySchemas(ctx context.Context, req OntologyListRequest) (*OntologyListResponse, error)
ListOntologySchemas lists ontology-lite schemas through the tool surface.
func (*GraphRAGToolbox) Query ¶ added in v2.27.0
func (t *GraphRAGToolbox) Query(ctx context.Context, req QueryRequest) (*QueryResponse, error)
Query runs the composable CortexDB Query API through the toolbox surface.
func (*GraphRAGToolbox) QueryKnowledgeGraph ¶ added in v2.16.0
func (t *GraphRAGToolbox) QueryKnowledgeGraph(ctx context.Context, req KnowledgeGraphQueryRequest) (*KnowledgeGraphQueryResponse, error)
QueryKnowledgeGraph executes a SPARQL query via the toolbox surface.
func (*GraphRAGToolbox) RefreshKnowledgeGraphInference ¶ added in v2.16.0
func (t *GraphRAGToolbox) RefreshKnowledgeGraphInference(ctx context.Context, req KnowledgeGraphInferenceRefreshRequest) (*KnowledgeGraphInferenceRefreshResponse, error)
RefreshKnowledgeGraphInference recomputes inferred triples via the toolbox surface.
func (*GraphRAGToolbox) SaveKnowledge ¶ added in v2.12.0
func (t *GraphRAGToolbox) SaveKnowledge(ctx context.Context, req KnowledgeSaveRequest) (*KnowledgeSaveResponse, error)
SaveKnowledge stores or replaces a knowledge item through the tool surface.
func (*GraphRAGToolbox) SaveMemory ¶ added in v2.12.0
func (t *GraphRAGToolbox) SaveMemory(ctx context.Context, req MemorySaveRequest) (*MemorySaveResponse, error)
SaveMemory stores a memory item through the tool surface.
func (*GraphRAGToolbox) SaveOntologySchema ¶ added in v2.14.0
func (t *GraphRAGToolbox) SaveOntologySchema(ctx context.Context, req OntologySaveRequest) (*OntologySaveResponse, error)
SaveOntologySchema stores or updates an ontology-lite schema through the tool surface.
func (*GraphRAGToolbox) SearchChunksByEntities ¶ added in v2.11.0
func (t *GraphRAGToolbox) SearchChunksByEntities(ctx context.Context, req ToolSearchChunksByEntitiesRequest) (*ToolSearchChunksByEntitiesResponse, error)
SearchChunksByEntities finds chunks that are linked to the requested entities.
func (*GraphRAGToolbox) SearchGraphRAGLexical ¶ added in v2.11.0
func (t *GraphRAGToolbox) SearchGraphRAGLexical(ctx context.Context, req ToolSearchGraphRAGLexicalRequest) (*GraphRAGQueryResult, error)
SearchGraphRAGLexical performs no-embedder GraphRAG retrieval for external LLM orchestration.
func (*GraphRAGToolbox) SearchKnowledge ¶ added in v2.12.0
func (t *GraphRAGToolbox) SearchKnowledge(ctx context.Context, req KnowledgeSearchRequest) (*KnowledgeSearchResponse, error)
SearchKnowledge searches durable knowledge through the tool surface.
func (*GraphRAGToolbox) SearchMemory ¶ added in v2.12.0
func (t *GraphRAGToolbox) SearchMemory(ctx context.Context, req MemorySearchRequest) (*MemorySearchResponse, error)
SearchMemory searches memory through the tool surface.
func (*GraphRAGToolbox) SearchText ¶ added in v2.11.0
func (t *GraphRAGToolbox) SearchText(ctx context.Context, req ToolSearchTextRequest) (*ToolSearchTextResponse, error)
SearchText runs lexical retrieval over chunk content.
func (*GraphRAGToolbox) SummarizeKnowledgeGraphInference ¶ added in v2.18.0
func (t *GraphRAGToolbox) SummarizeKnowledgeGraphInference(ctx context.Context, req KnowledgeGraphInferenceSummaryRequest) (*KnowledgeGraphInferenceSummaryResponse, error)
SummarizeKnowledgeGraphInference returns persisted inference counts and rule breakdowns via the toolbox surface.
func (*GraphRAGToolbox) UpdateKnowledge ¶ added in v2.12.0
func (t *GraphRAGToolbox) UpdateKnowledge(ctx context.Context, req KnowledgeUpdateRequest) (*KnowledgeSaveResponse, error)
UpdateKnowledge updates a knowledge item through the tool surface.
func (*GraphRAGToolbox) UpdateMemory ¶ added in v2.12.0
func (t *GraphRAGToolbox) UpdateMemory(ctx context.Context, req MemoryUpdateRequest) (*MemorySaveResponse, error)
UpdateMemory updates a memory item through the tool surface.
func (*GraphRAGToolbox) UpsertEntities ¶ added in v2.11.0
func (t *GraphRAGToolbox) UpsertEntities(ctx context.Context, req ToolUpsertEntitiesRequest) (*ToolUpsertEntitiesResponse, error)
UpsertEntities writes entity nodes and mention edges for caller-supplied structured extraction.
func (*GraphRAGToolbox) UpsertKnowledgeGraph ¶ added in v2.16.0
func (t *GraphRAGToolbox) UpsertKnowledgeGraph(ctx context.Context, req KnowledgeGraphUpsertRequest) (*KnowledgeGraphUpsertResponse, error)
UpsertKnowledgeGraph writes triples/quads via the toolbox surface.
func (*GraphRAGToolbox) UpsertKnowledgeNamespace ¶ added in v2.16.0
func (t *GraphRAGToolbox) UpsertKnowledgeNamespace(ctx context.Context, req KnowledgeGraphNamespaceUpsertRequest) (*KnowledgeGraphNamespaceUpsertResponse, error)
UpsertKnowledgeNamespace stores one knowledge-graph namespace via the toolbox surface.
func (*GraphRAGToolbox) UpsertRelations ¶ added in v2.11.0
func (t *GraphRAGToolbox) UpsertRelations(ctx context.Context, req ToolUpsertRelationsRequest) (*ToolUpsertRelationsResponse, error)
UpsertRelations writes relation edges between entities.
func (*GraphRAGToolbox) ValidateKnowledgeGraphSHACL ¶ added in v2.18.0
func (t *GraphRAGToolbox) ValidateKnowledgeGraphSHACL(ctx context.Context, req KnowledgeGraphSHACLValidateRequest) (*KnowledgeGraphSHACLValidateResponse, error)
ValidateKnowledgeGraphSHACL validates graph data with supplied SHACL-lite shape triples via the toolbox surface.
type GraphRelationship ¶ added in v2.10.0
GraphRelationship describes a directed relationship between entities.
type ImportAgentMemoryOptions ¶ added in v2.47.0
type ImportAgentMemoryOptions struct {
// Roots to scan for agent memory. When empty, defaults to the Claude Code
// home (~/.claude). Add ~/.codex or a project dir to include those.
Roots []string
// Collection to store imported knowledge under (default "agent_memory").
Collection string
// IncludeInstructions also imports CLAUDE.md / AGENTS.md instruction files,
// not just the file-based memory store.
IncludeInstructions bool
// DryRun scans and reports without writing anything.
DryRun bool
}
ImportAgentMemoryOptions configures ImportAgentMemory.
type ImportAgentMemoryReport ¶ added in v2.47.0
type ImportAgentMemoryReport struct {
FilesScanned int `json:"files_scanned"`
Imported int `json:"imported"`
Skipped int `json:"skipped"`
IDs []string `json:"ids,omitempty"`
}
ImportAgentMemoryReport summarizes an import pass.
func ImportAgentMemory ¶ added in v2.47.0
func ImportAgentMemory(ctx context.Context, db *DB, opts ImportAgentMemoryOptions) (*ImportAgentMemoryReport, error)
ImportAgentMemory ingests Claude Code / Codex memory into CortexDB so it is searchable through knowledge_memory_recall. It reads the file-based memory store (<root>/projects/*/memory/*.md, each a markdown note with YAML frontmatter) and, optionally, the CLAUDE.md / AGENTS.md instruction files, saving each as durable knowledge. Re-running is idempotent (stable ids).
type InferenceRule ¶ added in v2.14.0
type InferenceRule struct {
RuleID string `json:"rule_id"`
Description string `json:"description,omitempty"`
LeftRelationType string `json:"left_relation_type"`
RightRelationType string `json:"right_relation_type"`
ResultRelationType string `json:"result_relation_type"`
Weight float64 `json:"weight,omitempty"`
Metadata map[string]string `json:"metadata,omitempty"`
}
InferenceRule defines a deterministic two-hop relation composition rule.
type KnowledgeDeleteRequest ¶ added in v2.12.0
type KnowledgeDeleteRequest struct {
KnowledgeID string `json:"knowledge_id"`
}
KnowledgeDeleteRequest deletes a knowledge item by ID.
type KnowledgeDeleteResponse ¶ added in v2.12.0
type KnowledgeDeleteResponse struct {
KnowledgeID string `json:"knowledge_id"`
Deleted bool `json:"deleted"`
}
KnowledgeDeleteResponse confirms a delete operation.
type KnowledgeGetRequest ¶ added in v2.12.0
type KnowledgeGetRequest struct {
KnowledgeID string `json:"knowledge_id"`
}
KnowledgeGetRequest fetches a knowledge item by ID.
type KnowledgeGetResponse ¶ added in v2.12.0
type KnowledgeGetResponse struct {
Knowledge KnowledgeRecord `json:"knowledge"`
}
KnowledgeGetResponse returns one knowledge item.
type KnowledgeGraphDeleteRequest ¶ added in v2.16.0
type KnowledgeGraphDeleteRequest struct {
TripleIDs []string `json:"triple_ids,omitempty"`
Triples []KnowledgeGraphTriple `json:"triples,omitempty"`
Pattern *KnowledgeGraphTriplePattern `json:"pattern,omitempty"`
}
KnowledgeGraphDeleteRequest removes triples/quads by IDs, explicit triples, or a pattern.
type KnowledgeGraphDeleteResponse ¶ added in v2.16.0
type KnowledgeGraphDeleteResponse struct {
Deleted int `json:"deleted"`
}
KnowledgeGraphDeleteResponse summarizes deletion results.
type KnowledgeGraphExportRequest ¶ added in v2.16.0
type KnowledgeGraphExportRequest struct {
Format string `json:"format"`
}
KnowledgeGraphExportRequest serializes RDF content out of the graph.
type KnowledgeGraphExportResponse ¶ added in v2.16.0
type KnowledgeGraphExportResponse struct {
Format string `json:"format"`
Content string `json:"content"`
}
KnowledgeGraphExportResponse returns serialized RDF content.
type KnowledgeGraphFindRequest ¶ added in v2.16.0
type KnowledgeGraphFindRequest struct {
Pattern KnowledgeGraphTriplePattern `json:"pattern"`
}
KnowledgeGraphFindRequest queries triples/quads by pattern.
type KnowledgeGraphFindResponse ¶ added in v2.16.0
type KnowledgeGraphFindResponse struct {
Triples []KnowledgeGraphTriple `json:"triples"`
}
KnowledgeGraphFindResponse returns matched triples/quads.
type KnowledgeGraphImportRequest ¶ added in v2.16.0
type KnowledgeGraphImportRequest struct {
Format string `json:"format"`
Content string `json:"content"`
}
KnowledgeGraphImportRequest loads RDF content into the graph.
type KnowledgeGraphImportResponse ¶ added in v2.16.0
KnowledgeGraphImportResponse summarizes import results.
type KnowledgeGraphInferenceExplainMatchRequest ¶ added in v2.18.0
type KnowledgeGraphInferenceExplainMatchRequest struct {
Pattern KnowledgeGraphTriplePattern `json:"pattern"`
Depth int `json:"depth,omitempty"`
}
KnowledgeGraphInferenceExplainMatchRequest explains all triples matched by a pattern.
type KnowledgeGraphInferenceExplainMatchResponse ¶ added in v2.18.0
type KnowledgeGraphInferenceExplainMatchResponse struct {
Matches []KnowledgeGraphInferenceMatchExplanation `json:"matches"`
}
KnowledgeGraphInferenceExplainMatchResponse returns matched explanations.
type KnowledgeGraphInferenceExplainRequest ¶ added in v2.16.0
type KnowledgeGraphInferenceExplainRequest struct {
TripleID string `json:"triple_id"`
Depth int `json:"depth,omitempty"`
}
KnowledgeGraphInferenceExplainRequest fetches provenance for a triple.
type KnowledgeGraphInferenceExplainResponse ¶ added in v2.16.0
type KnowledgeGraphInferenceExplainResponse struct {
Explanation KnowledgeGraphInferenceExplanation `json:"explanation"`
Trace []KnowledgeGraphInferenceTraceEntry `json:"trace,omitempty"`
}
KnowledgeGraphInferenceExplainResponse returns inference provenance for a triple.
type KnowledgeGraphInferenceExplanation ¶ added in v2.16.0
type KnowledgeGraphInferenceExplanation = graph.RDFSInferenceExplanation
KnowledgeGraphInferenceExplanation aliases the low-level inference explanation type.
type KnowledgeGraphInferenceMatchExplanation ¶ added in v2.18.0
type KnowledgeGraphInferenceMatchExplanation = graph.RDFSInferenceMatchExplanation
KnowledgeGraphInferenceMatchExplanation aliases the low-level match explanation type.
type KnowledgeGraphInferenceRefreshRequest ¶ added in v2.16.0
type KnowledgeGraphInferenceRefreshRequest struct {
Mode string `json:"mode,omitempty"`
TripleIDs []string `json:"triple_ids,omitempty"`
Triples []KnowledgeGraphTriple `json:"triples,omitempty"`
Pattern *KnowledgeGraphTriplePattern `json:"pattern,omitempty"`
}
KnowledgeGraphInferenceRefreshRequest recomputes inferred triples.
type KnowledgeGraphInferenceRefreshResponse ¶ added in v2.16.0
type KnowledgeGraphInferenceRefreshResponse struct {
Result KnowledgeGraphInferenceRefreshResult `json:"result"`
}
KnowledgeGraphInferenceRefreshResponse summarizes an inference refresh run.
type KnowledgeGraphInferenceRefreshResult ¶ added in v2.16.0
type KnowledgeGraphInferenceRefreshResult = graph.RDFSInferenceRefreshResult
KnowledgeGraphInferenceRefreshResult aliases the low-level RDFS inference refresh result type.
type KnowledgeGraphInferenceSummary ¶ added in v2.18.0
type KnowledgeGraphInferenceSummary = graph.RDFSInferenceSummary
KnowledgeGraphInferenceSummary aliases the low-level inference summary type.
type KnowledgeGraphInferenceSummaryRequest ¶ added in v2.18.0
type KnowledgeGraphInferenceSummaryRequest struct{}
KnowledgeGraphInferenceSummaryRequest fetches inference summary counts.
type KnowledgeGraphInferenceSummaryResponse ¶ added in v2.18.0
type KnowledgeGraphInferenceSummaryResponse struct {
Result KnowledgeGraphInferenceSummary `json:"result"`
}
KnowledgeGraphInferenceSummaryResponse returns persisted inference counts and rule breakdowns.
type KnowledgeGraphInferenceTraceEntry ¶ added in v2.16.0
type KnowledgeGraphInferenceTraceEntry = graph.RDFSInferenceTraceEntry
KnowledgeGraphInferenceTraceEntry aliases the low-level flattened inference trace entry type.
type KnowledgeGraphNamespace ¶ added in v2.16.0
KnowledgeGraphNamespace aliases the low-level graph namespace type for the high-level DB API.
type KnowledgeGraphNamespaceListResponse ¶ added in v2.16.0
type KnowledgeGraphNamespaceListResponse struct {
Namespaces []KnowledgeGraphNamespace `json:"namespaces"`
}
KnowledgeGraphNamespaceListResponse returns all namespaces visible to the graph layer.
type KnowledgeGraphNamespaceUpsertRequest ¶ added in v2.16.0
type KnowledgeGraphNamespaceUpsertRequest struct {
Prefix string `json:"prefix"`
URI string `json:"uri"`
}
KnowledgeGraphNamespaceUpsertRequest stores one namespace mapping.
type KnowledgeGraphNamespaceUpsertResponse ¶ added in v2.16.0
type KnowledgeGraphNamespaceUpsertResponse struct {
Namespace KnowledgeGraphNamespace `json:"namespace"`
}
KnowledgeGraphNamespaceUpsertResponse returns the stored namespace mapping.
type KnowledgeGraphQueryRequest ¶ added in v2.16.0
type KnowledgeGraphQueryRequest struct {
Query string `json:"query"`
}
KnowledgeGraphQueryRequest executes a SPARQL SELECT/ASK subset against the embedded knowledge graph.
type KnowledgeGraphQueryResponse ¶ added in v2.16.0
type KnowledgeGraphQueryResponse struct {
Result KnowledgeGraphQueryResult `json:"result"`
}
KnowledgeGraphQueryResponse returns the SPARQL execution result.
type KnowledgeGraphQueryResult ¶ added in v2.16.0
type KnowledgeGraphQueryResult = graph.SPARQLResult
KnowledgeGraphQueryResult aliases the low-level SPARQL result type for the high-level DB API.
type KnowledgeGraphSHACLReport ¶ added in v2.18.0
type KnowledgeGraphSHACLReport = graph.SHACLReport
KnowledgeGraphSHACLReport aliases the low-level SHACL validation report type.
type KnowledgeGraphSHACLValidateRequest ¶ added in v2.18.0
type KnowledgeGraphSHACLValidateRequest struct {
Shapes []KnowledgeGraphTriple `json:"shapes"`
}
KnowledgeGraphSHACLValidateRequest validates graph data with supplied SHACL-lite shape triples.
type KnowledgeGraphSHACLValidateResponse ¶ added in v2.18.0
type KnowledgeGraphSHACLValidateResponse struct {
Report KnowledgeGraphSHACLReport `json:"report"`
}
KnowledgeGraphSHACLValidateResponse returns the SHACL-lite validation report.
type KnowledgeGraphTerm ¶ added in v2.16.0
KnowledgeGraphTerm aliases the low-level RDF term type for the high-level DB API.
type KnowledgeGraphTriple ¶ added in v2.16.0
KnowledgeGraphTriple aliases the low-level RDF triple type for the high-level DB API.
type KnowledgeGraphTriplePattern ¶ added in v2.16.0
type KnowledgeGraphTriplePattern = graph.TriplePattern
KnowledgeGraphTriplePattern aliases the low-level triple pattern type for the high-level DB API.
type KnowledgeGraphUpsertRequest ¶ added in v2.16.0
type KnowledgeGraphUpsertRequest struct {
Triples []KnowledgeGraphTriple `json:"triples"`
}
KnowledgeGraphUpsertRequest writes triples/quads into the knowledge graph.
type KnowledgeGraphUpsertResponse ¶ added in v2.16.0
type KnowledgeGraphUpsertResponse struct {
TripleIDs []string `json:"triple_ids"`
Count int `json:"count"`
}
KnowledgeGraphUpsertResponse summarizes a triple write operation.
type KnowledgeMemory ¶ added in v2.18.0
type KnowledgeMemory struct {
// contains filtered or unexported fields
}
KnowledgeMemory exposes CortexDB as a higher-level memory, knowledge, and graph facade.
func (*KnowledgeMemory) BuildContextPack ¶ added in v2.18.0
func (b *KnowledgeMemory) BuildContextPack(ctx context.Context, req KnowledgeMemoryBuildContextPackRequest) (*KnowledgeMemoryBuildContextPackResponse, error)
BuildContextPack returns the same fused retrieval response as Recall, centered on the assembled context pack.
func (*KnowledgeMemory) Consolidate ¶ added in v2.18.0
func (b *KnowledgeMemory) Consolidate(ctx context.Context, req KnowledgeMemoryConsolidateRequest) (*KnowledgeMemoryConsolidateResponse, error)
Consolidate reflects over relevant context, stores a summary memory, and can optionally promote it to knowledge.
func (*KnowledgeMemory) ExpandEntityContext ¶ added in v2.18.0
func (b *KnowledgeMemory) ExpandEntityContext(ctx context.Context, req KnowledgeMemoryExpandEntityContextRequest) (*KnowledgeMemoryExpandEntityContextResponse, error)
ExpandEntityContext expands graph context around entity nodes and builds a chunk context pack.
func (*KnowledgeMemory) Neighbors ¶ added in v2.18.0
func (b *KnowledgeMemory) Neighbors(ctx context.Context, req KnowledgeMemoryNeighborsRequest) (*KnowledgeMemoryNeighborsResponse, error)
Neighbors returns the graph neighbors around one node or entity.
func (*KnowledgeMemory) PromoteToKnowledge ¶ added in v2.18.0
func (b *KnowledgeMemory) PromoteToKnowledge(ctx context.Context, req KnowledgeMemoryPromoteToKnowledgeRequest) (*KnowledgeMemoryPromoteToKnowledgeResponse, error)
PromoteToKnowledge promotes one or more memory records into durable knowledge.
func (*KnowledgeMemory) Recall ¶ added in v2.18.0
func (b *KnowledgeMemory) Recall(ctx context.Context, req KnowledgeMemoryRecallRequest) (*KnowledgeMemoryRecallResponse, error)
Recall retrieves a fused memory and knowledge view plus a packed context.
func (*KnowledgeMemory) Reflect ¶ added in v2.18.0
func (b *KnowledgeMemory) Reflect(ctx context.Context, req KnowledgeMemoryReflectRequest) (*KnowledgeMemoryReflectResponse, error)
Reflect retrieves relevant context and synthesizes a structured reflection.
func (*KnowledgeMemory) Remember ¶ added in v2.18.0
func (b *KnowledgeMemory) Remember(ctx context.Context, req KnowledgeMemoryRememberRequest) (*KnowledgeMemoryRememberResponse, error)
Remember stores one episodic memory item.
func (*KnowledgeMemory) ShortestPath ¶ added in v2.18.0
func (b *KnowledgeMemory) ShortestPath(ctx context.Context, req KnowledgeMemoryShortestPathRequest) (*KnowledgeMemoryShortestPathResponse, error)
ShortestPath resolves and traverses the shortest path between two nodes or entities.
type KnowledgeMemoryBuildContextPackRequest ¶ added in v2.18.0
type KnowledgeMemoryBuildContextPackRequest = KnowledgeMemoryRecallRequest
KnowledgeMemoryBuildContextPackRequest retrieves and assembles a context pack from the KnowledgeMemory.
type KnowledgeMemoryBuildContextPackResponse ¶ added in v2.18.0
type KnowledgeMemoryBuildContextPackResponse = KnowledgeMemoryRecallResponse
KnowledgeMemoryBuildContextPackResponse returns the assembled context pack plus source diagnostics.
type KnowledgeMemoryConsolidateRequest ¶ added in v2.18.0
type KnowledgeMemoryConsolidateRequest struct {
Reflect KnowledgeMemoryReflectRequest `json:"reflect"`
MemoryID string `json:"memory_id,omitempty"`
UserID string `json:"user_id,omitempty"`
SessionID string `json:"session_id,omitempty"`
Scope string `json:"scope,omitempty"`
Namespace string `json:"namespace,omitempty"`
Role string `json:"role,omitempty"`
Metadata map[string]any `json:"metadata,omitempty"`
Importance float64 `json:"importance,omitempty"`
TTLSeconds int `json:"ttl_seconds,omitempty"`
PromoteToKnowledge bool `json:"promote_to_knowledge,omitempty"`
Promotion *KnowledgeMemoryPromoteToKnowledgeRequest `json:"promotion,omitempty"`
}
KnowledgeMemoryConsolidateRequest reflects over sources, persists a summary memory, and can optionally promote it to knowledge.
type KnowledgeMemoryConsolidateResponse ¶ added in v2.18.0
type KnowledgeMemoryConsolidateResponse struct {
Reflection KnowledgeMemoryReflection `json:"reflection"`
Recall KnowledgeMemoryRecallResponse `json:"recall"`
Memory MemoryRecord `json:"memory"`
Knowledge *KnowledgeRecord `json:"knowledge,omitempty"`
}
KnowledgeMemoryConsolidateResponse contains the saved summary memory and optional promoted knowledge.
type KnowledgeMemoryContextPack ¶ added in v2.18.0
type KnowledgeMemoryContextPack struct {
Query string `json:"query"`
Text string `json:"text"`
Sections []KnowledgeMemoryContextSection `json:"sections,omitempty"`
MemoryIDs []string `json:"memory_ids,omitempty"`
KnowledgeIDs []string `json:"knowledge_ids,omitempty"`
ChunkIDs []string `json:"chunk_ids,omitempty"`
Entities []string `json:"entities,omitempty"`
}
KnowledgeMemoryContextPack is the assembled prompt/context payload plus source attribution.
func KnowledgeMemoryContextPackFromSections ¶ added in v2.18.0
func KnowledgeMemoryContextPackFromSections(query string, sections []KnowledgeMemoryContextSection, memoryIDs, knowledgeIDs, chunkIDs, entities []string) KnowledgeMemoryContextPack
type KnowledgeMemoryContextSection ¶ added in v2.18.0
type KnowledgeMemoryContextSection struct {
Kind string `json:"kind"`
Title string `json:"title,omitempty"`
Text string `json:"text"`
SourceIDs []string `json:"source_ids,omitempty"`
}
KnowledgeMemoryContextSection is one debug-friendly part of a built context pack.
type KnowledgeMemoryExpandEntityContextRequest ¶ added in v2.18.0
type KnowledgeMemoryExpandEntityContextRequest struct {
EntityIDs []string `json:"entity_ids,omitempty"`
EntityNames []string `json:"entity_names,omitempty"`
MaxHops int `json:"max_hops,omitempty"`
EdgeTypes []string `json:"edge_types,omitempty"`
NodeTypes []string `json:"node_types,omitempty"`
Limit int `json:"limit,omitempty"`
TopKChunks int `json:"top_k_chunks,omitempty"`
MaxContextChunks int `json:"max_context_chunks,omitempty"`
MaxContextChars int `json:"max_context_chars,omitempty"`
PerDocumentLimit int `json:"per_document_limit,omitempty"`
RetrievalMode string `json:"retrieval_mode,omitempty"`
DisableGraph bool `json:"disable_graph,omitempty"`
GraphLight bool `json:"graph_light,omitempty"`
MaxEntitiesPerChunk int `json:"max_entities_per_chunk,omitempty"`
}
KnowledgeMemoryExpandEntityContextRequest expands graph context around one or more entities.
type KnowledgeMemoryExpandEntityContextResponse ¶ added in v2.18.0
type KnowledgeMemoryExpandEntityContextResponse struct {
EntityNodeIDs []string `json:"entity_node_ids,omitempty"`
Nodes []*graph.GraphNode `json:"nodes,omitempty"`
Edges []*graph.GraphEdge `json:"edges,omitempty"`
Chunks []GraphRAGChunkResult `json:"chunks,omitempty"`
ContextPack KnowledgeMemoryContextPack `json:"context_pack"`
}
KnowledgeMemoryExpandEntityContextResponse returns the expanded subgraph and packed chunk context.
type KnowledgeMemoryGraphFact ¶ added in v2.39.0
type KnowledgeMemoryGraphFact struct {
Subject string `json:"subject"`
Predicate string `json:"predicate"`
Object string `json:"object"`
SubjectID string `json:"subject_id,omitempty"`
ObjectID string `json:"object_id,omitempty"`
}
KnowledgeMemoryGraphFact is a single entity↔entity relation surfaced from the knowledge graph during recall, e.g. {Subject: "Alice", Predicate: "uses", Object: "Apollo"}. These come from graph edges (edge-accurate) rather than lexical chunk matching, so relational questions are answered reliably even without an embedder.
type KnowledgeMemoryNeighborsRequest ¶ added in v2.18.0
type KnowledgeMemoryNeighborsRequest struct {
NodeID string `json:"node_id,omitempty"`
EntityName string `json:"entity_name,omitempty"`
MaxDepth int `json:"max_depth,omitempty"`
EdgeTypes []string `json:"edge_types,omitempty"`
NodeTypes []string `json:"node_types,omitempty"`
Direction string `json:"direction,omitempty"`
Limit int `json:"limit,omitempty"`
}
KnowledgeMemoryNeighborsRequest expands neighbors around one node or entity.
type KnowledgeMemoryNeighborsResponse ¶ added in v2.18.0
type KnowledgeMemoryNeighborsResponse struct {
ResolvedNodeID string `json:"resolved_node_id"`
Neighbors []*graph.GraphNode `json:"neighbors,omitempty"`
}
KnowledgeMemoryNeighborsResponse returns a resolved node ID and its neighbors.
type KnowledgeMemoryPromoteToKnowledgeRequest ¶ added in v2.18.0
type KnowledgeMemoryPromoteToKnowledgeRequest struct {
MemoryIDs []string `json:"memory_ids,omitempty"`
KnowledgeID string `json:"knowledge_id,omitempty"`
Title string `json:"title,omitempty"`
SourceURL string `json:"source_url,omitempty"`
Author string `json:"author,omitempty"`
Collection string `json:"collection,omitempty"`
ChunkSize int `json:"chunk_size,omitempty"`
ChunkOverlap int `json:"chunk_overlap,omitempty"`
JoinWith string `json:"join_with,omitempty"`
Metadata map[string]string `json:"metadata,omitempty"`
Entities []ToolEntityInput `json:"entities,omitempty"`
Relations []ToolRelationInput `json:"relations,omitempty"`
}
KnowledgeMemoryPromoteToKnowledgeRequest promotes one or more memories into durable knowledge.
type KnowledgeMemoryPromoteToKnowledgeResponse ¶ added in v2.18.0
type KnowledgeMemoryPromoteToKnowledgeResponse struct {
Knowledge KnowledgeRecord `json:"knowledge"`
Memories []MemoryRecord `json:"memories,omitempty"`
DocumentNodeID string `json:"document_node_id,omitempty"`
EntityNodeIDs []string `json:"entity_node_ids,omitempty"`
RelationEdgeIDs []string `json:"relation_edge_ids,omitempty"`
}
KnowledgeMemoryPromoteToKnowledgeResponse returns the saved knowledge plus source memories.
type KnowledgeMemoryRecallRequest ¶ added in v2.18.0
type KnowledgeMemoryRecallRequest struct {
Query string `json:"query"`
UserID string `json:"user_id,omitempty"`
SessionID string `json:"session_id,omitempty"`
Scope string `json:"scope,omitempty"`
Namespace string `json:"namespace,omitempty"`
Collection string `json:"collection,omitempty"`
TopKMemories int `json:"top_k_memories,omitempty"`
TopKKnowledge int `json:"top_k_knowledge,omitempty"`
MaxMemoryItems int `json:"max_memory_items,omitempty"`
MaxMemoryChars int `json:"max_memory_chars,omitempty"`
Keywords []string `json:"keywords,omitempty"`
AlternateQueries []string `json:"alternate_queries,omitempty"`
EntityNames []string `json:"entity_names,omitempty"`
RetrievalMode string `json:"retrieval_mode,omitempty"`
DisableMemory bool `json:"disable_memory,omitempty"`
DisableKnowledge bool `json:"disable_knowledge,omitempty"`
DisableGraph bool `json:"disable_graph,omitempty"`
GraphLight bool `json:"graph_light,omitempty"`
MaxHops int `json:"max_hops,omitempty"`
MaxRelatedChunks int `json:"max_related_chunks,omitempty"`
MaxContextChunks int `json:"max_context_chunks,omitempty"`
MaxContextChars int `json:"max_context_chars,omitempty"`
PerDocumentLimit int `json:"per_document_limit,omitempty"`
MaxExpansionSeeds int `json:"max_expansion_seeds,omitempty"`
MaxTraversalNodes int `json:"max_traversal_nodes,omitempty"`
MaxEntitiesPerChunk int `json:"max_entities_per_chunk,omitempty"`
Plan *RetrievalPlan `json:"plan,omitempty"`
}
KnowledgeMemoryRecallRequest retrieves a fused view across episodic memory and durable knowledge.
type KnowledgeMemoryRecallResponse ¶ added in v2.18.0
type KnowledgeMemoryRecallResponse struct {
Query string `json:"query"`
MemoryPlan RetrievalPlan `json:"memory_plan"`
MemoryDecision RetrievalDecision `json:"memory_decision"`
KnowledgePlan RetrievalPlan `json:"knowledge_plan"`
KnowledgeDecision RetrievalDecision `json:"knowledge_decision"`
Memories []MemorySearchHit `json:"memories,omitempty"`
Knowledge []KnowledgeSearchHit `json:"knowledge,omitempty"`
Chunks []GraphRAGChunkResult `json:"chunks,omitempty"`
Entities []string `json:"entities,omitempty"`
GraphFacts []KnowledgeMemoryGraphFact `json:"graph_facts,omitempty"`
ContextPack KnowledgeMemoryContextPack `json:"context_pack"`
}
KnowledgeMemoryRecallResponse returns fused memory, knowledge, graph chunks, and packed context.
type KnowledgeMemoryReflectInput ¶ added in v2.18.0
type KnowledgeMemoryReflectInput struct {
Recall KnowledgeMemoryRecallResponse `json:"recall"`
}
KnowledgeMemoryReflectInput is the structured input passed to a pluggable reflector.
type KnowledgeMemoryReflectRequest ¶ added in v2.18.0
type KnowledgeMemoryReflectRequest struct {
Recall KnowledgeMemoryRecallRequest `json:"recall"`
Instructions string `json:"instructions,omitempty"`
MaxSummaryChars int `json:"max_summary_chars,omitempty"`
MaxFacts int `json:"max_facts,omitempty"`
MaxThemes int `json:"max_themes,omitempty"`
}
KnowledgeMemoryReflectRequest collects sources and synthesizes a reflection.
type KnowledgeMemoryReflectResponse ¶ added in v2.18.0
type KnowledgeMemoryReflectResponse struct {
Reflection KnowledgeMemoryReflection `json:"reflection"`
Recall KnowledgeMemoryRecallResponse `json:"recall"`
}
KnowledgeMemoryReflectResponse contains the reflection and its retrieval inputs.
type KnowledgeMemoryReflection ¶ added in v2.18.0
type KnowledgeMemoryReflection struct {
Summary string `json:"summary"`
Themes []string `json:"themes,omitempty"`
Entities []string `json:"entities,omitempty"`
Facts []string `json:"facts,omitempty"`
SourceMemoryIDs []string `json:"source_memory_ids,omitempty"`
SourceKnowledgeIDs []string `json:"source_knowledge_ids,omitempty"`
SourceChunkIDs []string `json:"source_chunk_ids,omitempty"`
ContextPack KnowledgeMemoryContextPack `json:"context_pack"`
}
KnowledgeMemoryReflection is a synthesized summary over retrieved memories and knowledge.
type KnowledgeMemoryReflector ¶ added in v2.18.0
type KnowledgeMemoryReflector interface {
Reflect(ctx context.Context, req KnowledgeMemoryReflectRequest, input KnowledgeMemoryReflectInput) (*KnowledgeMemoryReflection, error)
}
KnowledgeMemoryReflector synthesizes higher-order reflections on top of CortexDB retrieval results.
type KnowledgeMemoryRememberRequest ¶ added in v2.18.0
type KnowledgeMemoryRememberRequest = MemorySaveRequest
KnowledgeMemoryRememberRequest stores one episodic memory item.
type KnowledgeMemoryRememberResponse ¶ added in v2.18.0
type KnowledgeMemoryRememberResponse = MemorySaveResponse
KnowledgeMemoryRememberResponse returns the stored memory item.
type KnowledgeMemoryShortestPathRequest ¶ added in v2.18.0
type KnowledgeMemoryShortestPathRequest struct {
FromNodeID string `json:"from_node_id,omitempty"`
ToNodeID string `json:"to_node_id,omitempty"`
FromEntityName string `json:"from_entity_name,omitempty"`
ToEntityName string `json:"to_entity_name,omitempty"`
}
KnowledgeMemoryShortestPathRequest resolves and traverses a shortest path between two nodes/entities.
type KnowledgeMemoryShortestPathResponse ¶ added in v2.18.0
type KnowledgeMemoryShortestPathResponse struct {
FromNodeID string `json:"from_node_id"`
ToNodeID string `json:"to_node_id"`
Path *graph.PathResult `json:"path,omitempty"`
}
KnowledgeMemoryShortestPathResponse contains the resolved IDs and path result.
type KnowledgeRecord ¶ added in v2.12.0
type KnowledgeRecord struct {
ID string `json:"id"`
Title string `json:"title,omitempty"`
Content string `json:"content,omitempty"`
SourceURL string `json:"source_url,omitempty"`
Author string `json:"author,omitempty"`
Collection string `json:"collection,omitempty"`
Metadata map[string]string `json:"metadata,omitempty"`
ChunkIDs []string `json:"chunk_ids,omitempty"`
Entities []string `json:"entities,omitempty"`
CreatedAt time.Time `json:"created_at,omitempty"`
UpdatedAt time.Time `json:"updated_at,omitempty"`
}
KnowledgeRecord is the high-level durable knowledge object returned by the library and tools.
type KnowledgeSaveRequest ¶ added in v2.12.0
type KnowledgeSaveRequest struct {
KnowledgeID string `json:"knowledge_id"`
Title string `json:"title,omitempty"`
Content string `json:"content"`
SourceURL string `json:"source_url,omitempty"`
Author string `json:"author,omitempty"`
Collection string `json:"collection,omitempty"`
ChunkSize int `json:"chunk_size,omitempty"`
ChunkOverlap int `json:"chunk_overlap,omitempty"`
Metadata map[string]string `json:"metadata,omitempty"`
Entities []ToolEntityInput `json:"entities,omitempty"`
Relations []ToolRelationInput `json:"relations,omitempty"`
}
KnowledgeSaveRequest stores or replaces a durable knowledge item.
type KnowledgeSaveResponse ¶ added in v2.12.0
type KnowledgeSaveResponse struct {
Knowledge KnowledgeRecord `json:"knowledge"`
DocumentNodeID string `json:"document_node_id,omitempty"`
EntityNodeIDs []string `json:"entity_node_ids,omitempty"`
RelationEdgeIDs []string `json:"relation_edge_ids,omitempty"`
}
KnowledgeSaveResponse summarizes a knowledge write.
type KnowledgeSearchHit ¶ added in v2.12.0
type KnowledgeSearchHit struct {
KnowledgeID string `json:"knowledge_id"`
Title string `json:"title,omitempty"`
SourceURL string `json:"source_url,omitempty"`
Author string `json:"author,omitempty"`
Snippet string `json:"snippet,omitempty"`
Score float64 `json:"score"`
ChunkIDs []string `json:"chunk_ids,omitempty"`
Entities []string `json:"entities,omitempty"`
Metadata map[string]string `json:"metadata,omitempty"`
}
KnowledgeSearchHit is a document-shaped search result aggregated from chunk retrieval.
type KnowledgeSearchRequest ¶ added in v2.12.0
type KnowledgeSearchRequest struct {
Query string `json:"query"`
Collection string `json:"collection,omitempty"`
TopK int `json:"top_k,omitempty"`
MaxHops int `json:"max_hops,omitempty"`
MaxRelatedChunks int `json:"max_related_chunks,omitempty"`
MaxContextChunks int `json:"max_context_chunks,omitempty"`
MaxContextChars int `json:"max_context_chars,omitempty"`
PerDocumentLimit int `json:"per_document_limit,omitempty"`
DiversityLambda float64 `json:"diversity_lambda,omitempty"`
DisableRerank bool `json:"disable_rerank,omitempty"`
EntityNames []string `json:"entity_names,omitempty"`
Keywords []string `json:"keywords,omitempty"`
AlternateQueries []string `json:"alternate_queries,omitempty"`
RetrievalMode string `json:"retrieval_mode,omitempty"`
DisableGraph bool `json:"disable_graph,omitempty"`
GraphLight bool `json:"graph_light,omitempty"`
MaxExpansionSeeds int `json:"max_expansion_seeds,omitempty"`
MaxTraversalNodes int `json:"max_traversal_nodes,omitempty"`
MaxEntitiesPerChunk int `json:"max_entities_per_chunk,omitempty"`
Plan *RetrievalPlan `json:"plan,omitempty"`
}
KnowledgeSearchRequest searches durable knowledge with vector GraphRAG when available or lexical GraphRAG otherwise.
type KnowledgeSearchResponse ¶ added in v2.12.0
type KnowledgeSearchResponse struct {
Query string `json:"query"`
Plan RetrievalPlan `json:"plan"`
Decision RetrievalDecision `json:"decision"`
Results []KnowledgeSearchHit `json:"results"`
Chunks []GraphRAGChunkResult `json:"chunks,omitempty"`
Entities []string `json:"entities,omitempty"`
Context string `json:"context,omitempty"`
}
KnowledgeSearchResponse contains grouped knowledge hits and the packed GraphRAG context.
type KnowledgeUpdateRequest ¶ added in v2.12.0
type KnowledgeUpdateRequest struct {
KnowledgeID string `json:"knowledge_id"`
Title *string `json:"title,omitempty"`
Content *string `json:"content,omitempty"`
SourceURL *string `json:"source_url,omitempty"`
Author *string `json:"author,omitempty"`
Collection *string `json:"collection,omitempty"`
ChunkSize *int `json:"chunk_size,omitempty"`
ChunkOverlap *int `json:"chunk_overlap,omitempty"`
Metadata map[string]string `json:"metadata,omitempty"`
Entities []ToolEntityInput `json:"entities,omitempty"`
Relations []ToolRelationInput `json:"relations,omitempty"`
}
KnowledgeUpdateRequest updates a durable knowledge item.
type MCPServerOptions ¶ added in v2.11.0
type MCPServerOptions struct {
Implementation *mcp.Implementation
Instructions string
Logger *slog.Logger
}
MCPServerOptions configures the CortexDB MCP server wrapper.
type MemoryDeleteRequest ¶ added in v2.12.0
type MemoryDeleteRequest struct {
MemoryID string `json:"memory_id"`
}
MemoryDeleteRequest deletes a memory by ID.
type MemoryDeleteResponse ¶ added in v2.12.0
type MemoryDeleteResponse struct {
MemoryID string `json:"memory_id"`
Deleted bool `json:"deleted"`
}
MemoryDeleteResponse confirms a memory delete.
type MemoryGetRequest ¶ added in v2.12.0
type MemoryGetRequest struct {
MemoryID string `json:"memory_id"`
}
MemoryGetRequest fetches a memory by ID.
type MemoryGetResponse ¶ added in v2.12.0
type MemoryGetResponse struct {
Memory MemoryRecord `json:"memory"`
}
MemoryGetResponse returns one memory.
type MemoryRecord ¶ added in v2.12.0
type MemoryRecord struct {
ID string `json:"id"`
UserID string `json:"user_id,omitempty"`
SessionID string `json:"session_id,omitempty"`
Scope string `json:"scope,omitempty"`
Namespace string `json:"namespace,omitempty"`
Role string `json:"role,omitempty"`
Content string `json:"content"`
Metadata map[string]any `json:"metadata,omitempty"`
Importance float64 `json:"importance,omitempty"`
TTLSeconds int `json:"ttl_seconds,omitempty"`
ExpiresAt *time.Time `json:"expires_at,omitempty"`
CreatedAt time.Time `json:"created_at,omitempty"`
}
MemoryRecord is a high-level memory object stored in a dedicated memory bucket.
type MemorySaveRequest ¶ added in v2.12.0
type MemorySaveRequest struct {
MemoryID string `json:"memory_id"`
UserID string `json:"user_id,omitempty"`
SessionID string `json:"session_id,omitempty"`
Scope string `json:"scope,omitempty"`
Namespace string `json:"namespace,omitempty"`
Role string `json:"role,omitempty"`
Content string `json:"content"`
Metadata map[string]any `json:"metadata,omitempty"`
Importance float64 `json:"importance,omitempty"`
TTLSeconds int `json:"ttl_seconds,omitempty"`
}
MemorySaveRequest stores a memory in a dedicated memory bucket.
type MemorySaveResponse ¶ added in v2.12.0
type MemorySaveResponse struct {
Memory MemoryRecord `json:"memory"`
}
MemorySaveResponse returns the stored memory.
type MemorySearchHit ¶ added in v2.12.0
type MemorySearchHit struct {
Memory MemoryRecord `json:"memory"`
Score float64 `json:"score"`
}
MemorySearchHit is one scored memory result.
type MemorySearchRequest ¶ added in v2.12.0
type MemorySearchRequest struct {
Query string `json:"query"`
UserID string `json:"user_id,omitempty"`
SessionID string `json:"session_id,omitempty"`
Scope string `json:"scope,omitempty"`
Namespace string `json:"namespace,omitempty"`
TopK int `json:"top_k,omitempty"`
Keywords []string `json:"keywords,omitempty"`
AlternateQueries []string `json:"alternate_queries,omitempty"`
RetrievalMode string `json:"retrieval_mode,omitempty"`
Plan *RetrievalPlan `json:"plan,omitempty"`
}
MemorySearchRequest searches memories inside a resolved memory bucket.
type MemorySearchResponse ¶ added in v2.12.0
type MemorySearchResponse struct {
Query string `json:"query"`
Plan RetrievalPlan `json:"plan"`
Decision RetrievalDecision `json:"decision"`
Results []MemorySearchHit `json:"results"`
}
MemorySearchResponse contains retrieved memories.
type MemoryUpdateRequest ¶ added in v2.12.0
type MemoryUpdateRequest struct {
MemoryID string `json:"memory_id"`
Content *string `json:"content,omitempty"`
Metadata map[string]any `json:"metadata,omitempty"`
Importance *float64 `json:"importance,omitempty"`
TTLSeconds *int `json:"ttl_seconds,omitempty"`
}
MemoryUpdateRequest updates a memory item.
type OntologyDeleteRequest ¶ added in v2.14.0
type OntologyDeleteRequest struct {
SchemaID string `json:"schema_id"`
}
OntologyDeleteRequest deletes one ontology schema by ID.
type OntologyDeleteResponse ¶ added in v2.14.0
type OntologyDeleteResponse struct {
SchemaID string `json:"schema_id"`
Deleted bool `json:"deleted"`
}
OntologyDeleteResponse confirms ontology deletion.
type OntologyEntityType ¶ added in v2.14.0
type OntologyEntityType struct {
Name string `json:"name"`
Description string `json:"description,omitempty"`
RequiredProperties []string `json:"required_properties,omitempty"`
}
OntologyEntityType declares a canonical entity type and its required metadata.
type OntologyGetRequest ¶ added in v2.14.0
type OntologyGetRequest struct {
SchemaID string `json:"schema_id"`
}
OntologyGetRequest fetches one ontology schema by ID.
type OntologyGetResponse ¶ added in v2.14.0
type OntologyGetResponse struct {
Schema OntologySchema `json:"schema"`
}
OntologyGetResponse returns one ontology schema.
type OntologyListRequest ¶ added in v2.14.0
type OntologyListRequest struct {
ActiveOnly bool `json:"active_only,omitempty"`
}
OntologyListRequest lists ontology schemas.
type OntologyListResponse ¶ added in v2.14.0
type OntologyListResponse struct {
Schemas []OntologySchema `json:"schemas"`
}
OntologyListResponse returns ontology schemas.
type OntologyRelationType ¶ added in v2.14.0
type OntologyRelationType struct {
Name string `json:"name"`
Description string `json:"description,omitempty"`
AllowedFromTypes []string `json:"allowed_from_types,omitempty"`
AllowedToTypes []string `json:"allowed_to_types,omitempty"`
RequiredProperties []string `json:"required_properties,omitempty"`
}
OntologyRelationType declares a relation type plus legal source and target entity types.
type OntologySaveRequest ¶ added in v2.14.0
type OntologySaveRequest struct {
SchemaID string `json:"schema_id"`
Name string `json:"name,omitempty"`
Description string `json:"description,omitempty"`
Version int `json:"version,omitempty"`
Activate bool `json:"activate,omitempty"`
Deactivate bool `json:"deactivate,omitempty"`
Metadata map[string]string `json:"metadata,omitempty"`
EntityTypes []OntologyEntityType `json:"entity_types,omitempty"`
RelationTypes []OntologyRelationType `json:"relation_types,omitempty"`
}
OntologySaveRequest stores or updates an ontology-lite schema.
type OntologySaveResponse ¶ added in v2.14.0
type OntologySaveResponse struct {
Schema OntologySchema `json:"schema"`
}
OntologySaveResponse returns the persisted schema.
type OntologySchema ¶ added in v2.14.0
type OntologySchema struct {
SchemaID string `json:"schema_id"`
Name string `json:"name"`
Description string `json:"description,omitempty"`
Version int `json:"version"`
Active bool `json:"active"`
Metadata map[string]string `json:"metadata,omitempty"`
EntityTypes []OntologyEntityType `json:"entity_types,omitempty"`
RelationTypes []OntologyRelationType `json:"relation_types,omitempty"`
CreatedAt time.Time `json:"created_at"`
UpdatedAt time.Time `json:"updated_at"`
}
OntologySchema is the stored ontology-lite schema used to validate graph writes.
type Option ¶
type Option func(*DB)
Option is a functional option for configuring the DB.
func WithEmbedder ¶
WithEmbedder configures the DB with an embedder for text operations. When set, you can use InsertText, SearchText and other text-based methods.
func WithKnowledgeMemoryReflector ¶ added in v2.18.0
func WithKnowledgeMemoryReflector(r KnowledgeMemoryReflector) Option
WithKnowledgeMemoryReflector configures the DB with a pluggable reflection/consolidation engine. This lets callers keep CortexDB as the persistent KnowledgeMemory substrate while delegating higher-order summarization and synthesis to an external reasoning component.
func WithQueryTransformer ¶ added in v2.56.0
func WithQueryTransformer(t QueryTransformer) Option
WithQueryTransformer configures the DB with a pre-retrieval query transformer. When set, SearchKnowledge rewrites the raw query before retrieval: the transformer's AlternateQueries and Keywords are fused into the plan (multi-query recall), and when an embedder is present its HypotheticalDocument drives the semantic query vector (HyDE) instead of the literal question. Optional and best-effort: without one — or if the transformer errors — retrieval runs on the raw query unchanged, and the no-embedder lexical path is unaffected.
func WithReranker ¶ added in v2.53.0
WithReranker configures the DB with a cross-encoder reranker. When set, the retrieval path (SearchKnowledge, GraphRAG, hybrid) uses the reranker's query-document relevance scores as the base relevance signal before the built-in MMR diversity/dedup pass — upgrading the default lexical-overlap rerank to a semantic cross-encoder. Optional: without it, the dependency-free heuristic rerank is used unchanged.
type QueryCondition ¶ added in v2.27.0
type QueryCondition struct {
Field string `json:"field"`
Op string `json:"op,omitempty"`
Value string `json:"value,omitempty"`
Values []string `json:"values,omitempty"`
Number float64 `json:"number,omitempty"`
HasNumber bool `json:"has_number,omitempty"`
}
QueryCondition checks one payload or top-level field.
type QueryFieldBoost ¶ added in v2.27.0
type QueryFieldBoost struct {
Field string `json:"field"`
Equals string `json:"equals,omitempty"`
Contains string `json:"contains,omitempty"`
Weight float64 `json:"weight"`
}
QueryFieldBoost adds Weight when Field matches Equals or contains Contains.
type QueryFilter ¶ added in v2.27.0
type QueryFilter struct {
Must []QueryCondition `json:"must,omitempty"`
Should []QueryCondition `json:"should,omitempty"`
MustNot []QueryCondition `json:"must_not,omitempty"`
}
QueryFilter is a small payload filter model for embeddings metadata plus a few top-level fields such as id, doc_id, collection, and content.
type QueryNumericBoost ¶ added in v2.27.0
type QueryNumericBoost struct {
Field string `json:"field"`
Weight float64 `json:"weight"`
MaxValue float64 `json:"max_value,omitempty"`
}
QueryNumericBoost adds a normalized numeric payload contribution.
type QueryPrefetch ¶ added in v2.27.0
type QueryPrefetch struct {
Name string `json:"name,omitempty"`
Kind string `json:"kind,omitempty"`
Query string `json:"query,omitempty"`
QueryVector []float32 `json:"query_vector,omitempty"`
EntityNames []string `json:"entity_names,omitempty"`
Weight float64 `json:"weight,omitempty"`
Limit int `json:"limit,omitempty"`
MaxHops int `json:"max_hops,omitempty"`
Keywords []string `json:"keywords,omitempty"`
AlternateQueries []string `json:"alternate_queries,omitempty"`
}
QueryPrefetch describes one retrieval lane in a multi-stage query.
type QueryRequest ¶ added in v2.27.0
type QueryRequest struct {
Collection string `json:"collection,omitempty"`
Query string `json:"query,omitempty"`
QueryVector []float32 `json:"query_vector,omitempty"`
EntityNames []string `json:"entity_names,omitempty"`
Prefetch []QueryPrefetch `json:"prefetch,omitempty"`
Fusion string `json:"fusion,omitempty"`
Filter *QueryFilter `json:"filter,omitempty"`
Formula *QueryScoreFormula `json:"formula,omitempty"`
Limit int `json:"limit,omitempty"`
RRFK float64 `json:"rrf_k,omitempty"`
IncludeRaw bool `json:"include_raw,omitempty"`
}
QueryRequest is CortexDB's composable retrieval API. It runs one or more prefetch queries, fuses their candidate sets, then applies optional formula scoring for application-specific ranking signals.
type QueryResponse ¶ added in v2.27.0
type QueryResponse struct {
Query string `json:"query,omitempty"`
Fusion string `json:"fusion"`
Results []QueryResult `json:"results"`
Prefetches []string `json:"prefetches,omitempty"`
}
QueryResponse returns fused and reranked retrieval results.
type QueryResult ¶ added in v2.27.0
type QueryResult struct {
ID string `json:"id"`
Collection string `json:"collection,omitempty"`
Content string `json:"content,omitempty"`
DocID string `json:"doc_id,omitempty"`
Metadata map[string]string `json:"metadata,omitempty"`
Score float64 `json:"score"`
BaseScore float64 `json:"base_score,omitempty"`
SourceRanks map[string]int `json:"source_ranks,omitempty"`
SourceScores map[string]float64 `json:"source_scores,omitempty"`
}
QueryResult is one ranked result from Query.
type QueryScoreFormula ¶ added in v2.27.0
type QueryScoreFormula struct {
BaseWeight float64 `json:"base_weight,omitempty"`
FieldBoosts []QueryFieldBoost `json:"field_boosts,omitempty"`
NumericBoosts []QueryNumericBoost `json:"numeric_boosts,omitempty"`
}
QueryScoreFormula layers deterministic ranking logic on top of fused scores.
type QueryTransform ¶ added in v2.56.0
type QueryTransform struct {
AlternateQueries []string
Keywords []string
HypotheticalDocument string
}
QueryTransform is the result of pre-retrieval query transformation. It lets a caller-supplied model rewrite a raw user query into signals that retrieve better than the literal question:
- AlternateQueries — paraphrases / sub-questions fused into the lexical and graph seed expansion (multi-query retrieval).
- Keywords — salient terms, synonyms, aliases, and multilingual variants that seed lexical recall.
- HypotheticalDocument — a HyDE passage: a plausible answer to the query. When an embedder is present, the *semantic* query vector is derived from this passage instead of the raw question, so vector search matches passages by content rather than by question phrasing.
type QueryTransformer ¶ added in v2.56.0
type QueryTransformer interface {
// TransformQuery returns rewrite signals for query. Returning a nil result
// (or an error) leaves retrieval on the raw query — it must never make
// retrieval fail.
TransformQuery(ctx context.Context, query string) (*QueryTransform, error)
}
QueryTransformer rewrites a raw query before retrieval. CortexDB never imports a model SDK — a transformer is supplied via WithQueryTransformer (e.g. an OpenAI-compatible chat endpoint that returns the JSON shape above). It stays optional: without one, retrieval uses the raw query and caller-provided keywords/alternates unchanged.
type Quick ¶
type Quick struct {
// contains filtered or unexported fields
}
Quick is a simplified interface for common operations.
func (*Quick) AddBatchWithVectors ¶ added in v2.13.0
func (q *Quick) AddBatchWithVectors(ctx context.Context, vectors [][]float32, contents []string, metadata map[string]string) ([]string, error)
AddBatchWithVectors adds multiple vectors with automatic ID generation.
func (*Quick) AddBatchWithVectorsToCollection ¶ added in v2.13.0
func (q *Quick) AddBatchWithVectorsToCollection(ctx context.Context, collection string, vectors [][]float32, contents []string, metadata map[string]string) ([]string, error)
AddBatchWithVectorsToCollection adds multiple vectors to a specific collection with automatic ID generation.
func (*Quick) AddText ¶
func (q *Quick) AddText(ctx context.Context, text string, metadata map[string]string) (string, error)
AddText adds text with automatic ID generation and embedding.
func (*Quick) AddTextToCollection ¶
func (q *Quick) AddTextToCollection(ctx context.Context, collection string, text string, metadata map[string]string) (string, error)
AddTextToCollection adds text to a specific collection with automatic ID generation.
func (*Quick) AddToCollection ¶
func (q *Quick) AddToCollection(ctx context.Context, collection string, vector []float32, content string) (string, error)
AddToCollection adds a vector to a specific collection with automatic ID generation.
func (*Quick) AddWithVector ¶ added in v2.13.0
func (q *Quick) AddWithVector(ctx context.Context, vector []float32, content string, metadata map[string]string) (string, error)
AddWithVector adds a vector with automatic ID generation using a pre-computed vector.
func (*Quick) AddWithVectorToCollection ¶ added in v2.13.0
func (q *Quick) AddWithVectorToCollection(ctx context.Context, collection string, vector []float32, content string, metadata map[string]string) (string, error)
AddWithVectorToCollection adds a vector to a specific collection with automatic ID generation.
func (*Quick) Search ¶
func (q *Quick) Search(ctx context.Context, query []float32, topK int) ([]core.ScoredEmbedding, error)
Search performs similarity search.
func (*Quick) SearchInCollection ¶
func (q *Quick) SearchInCollection(ctx context.Context, collection string, query []float32, topK int) ([]core.ScoredEmbedding, error)
SearchInCollection performs similarity search within a collection.
func (*Quick) SearchText ¶
func (q *Quick) SearchText(ctx context.Context, query string, topK int) ([]core.ScoredEmbedding, error)
SearchText performs similarity search using text query.
func (*Quick) SearchTextInCollection ¶
func (q *Quick) SearchTextInCollection(ctx context.Context, collection string, query string, topK int) ([]core.ScoredEmbedding, error)
SearchTextInCollection performs similarity search using text query within a collection.
func (*Quick) SearchTextOnly ¶
func (q *Quick) SearchTextOnly(ctx context.Context, query string, topK int) ([]core.ScoredEmbedding, error)
SearchTextOnly performs pure FTS5 full-text search without embeddings.
type RerankItem ¶ added in v2.37.0
type RerankItem struct {
ID string // caller's identifier (carried through, opaque to Rerank)
Text string // primary content scored against the query
Score float64 // base retrieval score (any scale; min-max normalized internally)
Entities []string // optional: entity strings for the entity-overlap signal
GroupKey string // optional: diversity/dedup group (e.g. a document id)
// RerankScore is the blended relevance, filled in by Rerank.
RerankScore float64
}
RerankItem is one candidate to rerank. Only ID, Text, and Score are required; Entities and GroupKey enrich the entity-overlap and diversity signals.
func Rerank ¶ added in v2.37.0
func Rerank(query string, items []RerankItem, opts RerankOptions) []RerankItem
Rerank re-scores candidates jointly with the query — normalized base score + query/text term overlap + query/item entity overlap — then selects with Maximal Marginal Relevance so the head is both relevant and non-redundant. Items whose GroupKey matches an already-selected item are penalized as near-duplicates. The returned slice is ordered best-first with RerankScore set.
type RerankOptions ¶ added in v2.37.0
type RerankOptions struct {
TopN int // keep at most N results (0 = keep all)
DiversityLambda float64 // 0..1: relevance vs. novelty in MMR selection (default 0.75)
BaseWeight float64 // weight of the normalized base score (default 0.60)
TermWeight float64 // weight of query/text term overlap (default 0.25)
EntityWeight float64 // weight of query/item entity overlap (default 0.15)
}
RerankOptions tunes the relevance blend and MMR diversity. Zero values fall back to the defaults CortexDB uses internally (0.6/0.25/0.15, lambda 0.75).
type Reranker ¶ added in v2.53.0
type Reranker interface {
// Rerank returns one relevance score per document, in the same order as
// documents (score[i] corresponds to documents[i]). Higher is more relevant;
// the scale is arbitrary (the retrieval path normalizes before blending).
Rerank(ctx context.Context, query string, documents []string) ([]float64, error)
}
Reranker is a cross-encoder that scores how relevant each document is to the query. It is the semantic upgrade to the built-in lexical-overlap rerank: where the heuristic Rerank blends term/entity overlap, a Reranker jointly encodes (query, document) with a model and returns a true relevance score.
CortexDB never imports a model SDK — a Reranker is supplied via WithReranker (e.g. an OpenAI-compatible /rerank endpoint, Cohere, Jina, or a local text-embeddings-inference server running a bge-reranker). It stays optional: without one, retrieval uses the dependency-free heuristic rerank.
type RetrievalDecision ¶ added in v2.14.0
type RetrievalDecision struct {
RequestedMode string `json:"requested_mode"`
EffectiveMode string `json:"effective_mode"`
UseGraph bool `json:"use_graph"`
Reason string `json:"reason,omitempty"`
}
RetrievalDecision explains how CortexDB interpreted the caller's requested mode.
type RetrievalFilters ¶ added in v2.14.0
type RetrievalFilters struct {
Collection string `json:"collection,omitempty"`
DocumentIDs []string `json:"document_ids,omitempty"`
UserID string `json:"user_id,omitempty"`
SessionID string `json:"session_id,omitempty"`
Scope string `json:"scope,omitempty"`
Namespace string `json:"namespace,omitempty"`
}
RetrievalFilters captures optional structured constraints for search.
type RetrievalPlan ¶ added in v2.14.0
type RetrievalPlan struct {
Query string `json:"query,omitempty"`
Keywords []string `json:"keywords,omitempty"`
AlternateQueries []string `json:"alternate_queries,omitempty"`
EntityNames []string `json:"entity_names,omitempty"`
RetrievalMode string `json:"retrieval_mode,omitempty"`
Filters *RetrievalFilters `json:"filters,omitempty"`
}
RetrievalPlan is the structured search plan that an external LLM can produce before calling CortexDB search APIs or MCP tools.
type TextSearchOptions ¶
type TextSearchOptions struct {
Collection string
TopK int
Threshold float64
Keywords []string
AlternateQueries []string
// Authorize, when set, is a retrieval-layer security gate: it is applied to
// every candidate and only authorized rows count toward TopK. The search
// over-fetches internally so the caller still receives up to TopK authorized
// results. This pushes access control (RBAC/ABAC) into the retrieval boundary
// instead of leaving it to post-filtering in application code.
Authorize func(core.ScoredEmbedding) bool
// Reranker, when set, re-scores and reorders the authorized candidate set
// (typically a cross-encoder or LLM) before MinScore filtering and TopK
// truncation — the standard recall→precision second stage.
Reranker core.Reranker
// MinScore, when > 0, drops candidates whose (possibly reranked) Score is
// below the threshold — a relevance floor that prevents weak tail matches
// from being surfaced.
MinScore float64
}
TextSearchOptions defines options for text-only search.
type ToolBuildContextRequest ¶ added in v2.11.0
type ToolBuildContextRequest struct {
ChunkIDs []string `json:"chunk_ids"`
MaxContextChunks int `json:"max_context_chunks,omitempty"`
MaxContextChars int `json:"max_context_chars,omitempty"`
PerDocumentLimit int `json:"per_document_limit,omitempty"`
RetrievalMode string `json:"retrieval_mode,omitempty"`
DisableGraph bool `json:"disable_graph,omitempty"`
GraphLight bool `json:"graph_light,omitempty"`
MaxEntitiesPerChunk int `json:"max_entities_per_chunk,omitempty"`
}
ToolBuildContextRequest packs chunk text into a prompt context budget.
type ToolBuildContextResponse ¶ added in v2.11.0
type ToolBuildContextResponse struct {
Chunks []GraphRAGChunkResult `json:"chunks"`
Context string `json:"context"`
}
ToolBuildContextResponse returns packed chunks and the assembled context.
type ToolChunk ¶ added in v2.11.0
type ToolChunk struct {
ID string `json:"id"`
DocumentID string `json:"document_id,omitempty"`
Content string `json:"content"`
Score float64 `json:"score,omitempty"`
Metadata map[string]string `json:"metadata,omitempty"`
Entities []string `json:"entities,omitempty"`
}
ToolChunk is a chunk-shaped response used by tool APIs.
type ToolDefinition ¶ added in v2.11.0
type ToolDefinition struct {
Name string `json:"name"`
Description string `json:"description"`
InputSchema map[string]any `json:"input_schema"`
}
ToolDefinition describes a tool/function that an external LLM can call.
func KnowledgeMemoryFacadeToolDefinitions ¶ added in v2.18.0
func KnowledgeMemoryFacadeToolDefinitions() []ToolDefinition
func KnowledgeMemoryToolDefinitions ¶ added in v2.18.0
func KnowledgeMemoryToolDefinitions() []ToolDefinition
type ToolEntityInput ¶ added in v2.11.0
type ToolEntityInput struct {
ID string `json:"id,omitempty"`
Name string `json:"name"`
Type string `json:"type,omitempty"`
Description string `json:"description,omitempty"`
ChunkIDs []string `json:"chunk_ids,omitempty"`
Metadata map[string]string `json:"metadata,omitempty"`
}
ToolEntityInput represents an extracted entity and where it was mentioned.
type ToolExpandGraphRequest ¶ added in v2.11.0
type ToolExpandGraphRequest struct {
NodeIDs []string `json:"node_ids"`
MaxHops int `json:"max_hops,omitempty"`
EdgeTypes []string `json:"edge_types,omitempty"`
NodeTypes []string `json:"node_types,omitempty"`
Limit int `json:"limit,omitempty"`
}
ToolExpandGraphRequest expands a graph neighborhood.
type ToolExpandGraphResponse ¶ added in v2.11.0
type ToolExpandGraphResponse struct {
Nodes []*graph.GraphNode `json:"nodes"`
Edges []*graph.GraphEdge `json:"edges"`
}
ToolExpandGraphResponse returns a subgraph around the requested nodes.
type ToolExtractConversationRequest ¶ added in v2.49.0
type ToolExtractConversationRequest struct {
// Text is the conversation content to analyze. If empty, SessionID is used
// to load the session's messages.
Text string `json:"text,omitempty"`
// SessionID loads and concatenates that session's messages when Text is empty.
SessionID string `json:"session_id,omitempty"`
// Persist writes the extracted entities/relations into the knowledge graph
// and the summary into durable knowledge.
Persist bool `json:"persist,omitempty"`
// Collection for the persisted summary (default "conversations").
Collection string `json:"collection,omitempty"`
// MaxEntities caps extracted entities (default 30).
MaxEntities int `json:"max_entities,omitempty"`
}
ToolExtractConversationRequest asks to extract key information from a chunk of conversation text (or a stored session's messages).
type ToolExtractConversationResponse ¶ added in v2.49.0
type ToolExtractConversationResponse struct {
Summary string `json:"summary"`
Themes []string `json:"themes,omitempty"`
Entities []string `json:"entities,omitempty"`
Relations []ExtractedRelation `json:"relations,omitempty"`
Persisted bool `json:"persisted"`
KnowledgeID string `json:"knowledge_id,omitempty"`
}
ToolExtractConversationResponse is the extracted key information.
type ToolGetChunksRequest ¶ added in v2.11.0
type ToolGetChunksRequest struct {
ChunkIDs []string `json:"chunk_ids"`
RetrievalMode string `json:"retrieval_mode,omitempty"`
DisableGraph bool `json:"disable_graph,omitempty"`
GraphLight bool `json:"graph_light,omitempty"`
MaxEntitiesPerChunk int `json:"max_entities_per_chunk,omitempty"`
}
ToolGetChunksRequest fetches chunk records by chunk ID.
type ToolGetChunksResponse ¶ added in v2.11.0
type ToolGetChunksResponse struct {
Chunks []ToolChunk `json:"chunks"`
}
ToolGetChunksResponse returns chunk records.
type ToolGetNodesRequest ¶ added in v2.11.0
type ToolGetNodesRequest struct {
NodeIDs []string `json:"node_ids"`
}
ToolGetNodesRequest fetches graph nodes by ID.
type ToolGetNodesResponse ¶ added in v2.11.0
ToolGetNodesResponse returns graph nodes.
type ToolIngestDocumentRequest ¶ added in v2.11.0
type ToolIngestDocumentRequest struct {
DocumentID string `json:"document_id"`
Title string `json:"title,omitempty"`
Content string `json:"content"`
Collection string `json:"collection,omitempty"`
ChunkSize int `json:"chunk_size,omitempty"`
ChunkOverlap int `json:"chunk_overlap,omitempty"`
Metadata map[string]string `json:"metadata,omitempty"`
}
ToolIngestDocumentRequest stores a document and its chunks without requiring an embedder.
type ToolIngestDocumentResponse ¶ added in v2.11.0
type ToolIngestDocumentResponse struct {
DocumentNodeID string `json:"document_node_id"`
ChunkNodeIDs []string `json:"chunk_node_ids"`
Collection string `json:"collection"`
}
ToolIngestDocumentResponse summarizes lexical ingestion output.
type ToolRelationInput ¶ added in v2.11.0
type ToolRelationInput struct {
From string `json:"from"`
To string `json:"to"`
Type string `json:"type,omitempty"`
Weight float64 `json:"weight,omitempty"`
ChunkIDs []string `json:"chunk_ids,omitempty"`
Metadata map[string]string `json:"metadata,omitempty"`
Inferred bool `json:"inferred,omitempty"`
Provenance string `json:"provenance,omitempty"`
RuleID string `json:"rule_id,omitempty"`
SupportEdgeIDs []string `json:"support_edge_ids,omitempty"`
}
ToolRelationInput represents a relation extracted by an external LLM.
type ToolSearchChunksByEntitiesRequest ¶ added in v2.11.0
type ToolSearchChunksByEntitiesRequest struct {
EntityNames []string `json:"entity_names"`
TopK int `json:"top_k,omitempty"`
MaxHops int `json:"max_hops,omitempty"`
}
ToolSearchChunksByEntitiesRequest finds chunks connected to the given entities.
type ToolSearchChunksByEntitiesResponse ¶ added in v2.11.0
type ToolSearchChunksByEntitiesResponse struct {
Chunks []ToolChunk `json:"chunks"`
}
ToolSearchChunksByEntitiesResponse returns chunks linked to entity nodes.
type ToolSearchGraphRAGLexicalRequest ¶ added in v2.11.0
type ToolSearchGraphRAGLexicalRequest struct {
Query string `json:"query"`
Collection string `json:"collection,omitempty"`
TopK int `json:"top_k,omitempty"`
MaxHops int `json:"max_hops,omitempty"`
MaxRelatedChunks int `json:"max_related_chunks,omitempty"`
MaxContextChunks int `json:"max_context_chunks,omitempty"`
MaxContextChars int `json:"max_context_chars,omitempty"`
PerDocumentLimit int `json:"per_document_limit,omitempty"`
DisableRerank bool `json:"disable_rerank,omitempty"`
DiversityLambda float64 `json:"diversity_lambda,omitempty"`
EntityNames []string `json:"entity_names,omitempty"`
Keywords []string `json:"keywords,omitempty"`
AlternateQueries []string `json:"alternate_queries,omitempty"`
RetrievalMode string `json:"retrieval_mode,omitempty"`
DisableGraph bool `json:"disable_graph,omitempty"`
GraphLight bool `json:"graph_light,omitempty"`
MaxExpansionSeeds int `json:"max_expansion_seeds,omitempty"`
MaxTraversalNodes int `json:"max_traversal_nodes,omitempty"`
MaxEntitiesPerChunk int `json:"max_entities_per_chunk,omitempty"`
Plan *RetrievalPlan `json:"plan,omitempty"`
}
ToolSearchGraphRAGLexicalRequest performs no-embedder GraphRAG retrieval.
type ToolSearchTextRequest ¶ added in v2.11.0
type ToolSearchTextRequest struct {
Query string `json:"query"`
Collection string `json:"collection,omitempty"`
TopK int `json:"top_k,omitempty"`
Threshold float64 `json:"threshold,omitempty"`
Keywords []string `json:"keywords,omitempty"`
AlternateQueries []string `json:"alternate_queries,omitempty"`
RetrievalMode string `json:"retrieval_mode,omitempty"`
DisableGraph bool `json:"disable_graph,omitempty"`
GraphLight bool `json:"graph_light,omitempty"`
MaxEntitiesPerChunk int `json:"max_entities_per_chunk,omitempty"`
Plan *RetrievalPlan `json:"plan,omitempty"`
}
ToolSearchTextRequest performs lexical seed retrieval.
type ToolSearchTextResponse ¶ added in v2.11.0
type ToolSearchTextResponse struct {
Plan RetrievalPlan `json:"plan"`
Decision RetrievalDecision `json:"decision"`
Chunks []ToolChunk `json:"chunks"`
}
ToolSearchTextResponse returns chunk hits from lexical retrieval.
type ToolUpsertEntitiesRequest ¶ added in v2.11.0
type ToolUpsertEntitiesRequest struct {
DocumentID string `json:"document_id,omitempty"`
Entities []ToolEntityInput `json:"entities"`
}
ToolUpsertEntitiesRequest writes entity nodes and mention edges.
type ToolUpsertEntitiesResponse ¶ added in v2.11.0
type ToolUpsertEntitiesResponse struct {
EntityNodeIDs []string `json:"entity_node_ids"`
MentionEdgeCount int `json:"mention_edge_count"`
}
ToolUpsertEntitiesResponse summarizes entity writes.
type ToolUpsertRelationsRequest ¶ added in v2.11.0
type ToolUpsertRelationsRequest struct {
DocumentID string `json:"document_id,omitempty"`
Relations []ToolRelationInput `json:"relations"`
}
ToolUpsertRelationsRequest writes graph edges between entities.
type ToolUpsertRelationsResponse ¶ added in v2.11.0
type ToolUpsertRelationsResponse struct {
EdgeIDs []string `json:"edge_ids"`
}
ToolUpsertRelationsResponse summarizes written relation edges.
Source Files
¶
- brain.go
- brain_graph_facts.go
- brain_tool_api.go
- brain_tooldefs.go
- brain_types.go
- cortexdb.go
- embedder.go
- extract_conversation.go
- graph_cleanup.go
- graph_runtime.go
- graph_runtime_sql.go
- graphrag.go
- graphrag_helpers.go
- graphrag_tool_defs.go
- graphrag_tool_helpers.go
- graphrag_tool_ingest.go
- graphrag_tool_search.go
- graphrag_tool_types.go
- import_agent_memory.go
- inference_api.go
- inference_dispatch.go
- inference_mcp.go
- inference_runtime.go
- inference_tooldefs.go
- inference_types.go
- knowledge_api.go
- knowledge_graph_api.go
- knowledge_graph_tools.go
- knowledge_graph_types.go
- knowledge_helpers.go
- knowledge_hybrid.go
- knowledge_memory_helpers.go
- knowledge_memory_tooldefs.go
- knowledge_memory_types.go
- knowledge_tx.go
- mcp.go
- memory_api.go
- ontology_api.go
- ontology_dispatch.go
- ontology_mcp.go
- ontology_storage.go
- ontology_tooldefs.go
- ontology_types.go
- ontology_validation.go
- query_api.go
- query_tool_schema.go
- query_transform.go
- quick.go
- rerank.go
- reranker.go
- retrieval_plan.go
- retrieval_plan_schema.go
- retrieval_plan_types.go
- sql_chunking.go
- text_search.go