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 ActionApplyRequest
- type ActionApplyResponse
- type ActionEdit
- type ActionListRequest
- type ActionListResponse
- type ActionRuleKind
- type ApplyInferenceRequest
- type ApplyInferenceResponse
- type BaseEmbedder
- type Config
- type DB
- func (db *DB) ApplyAction(ctx context.Context, req ActionApplyRequest) (*ActionApplyResponse, error)
- 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) DiffOntologySchema(ctx context.Context, req OntologyDiffRequest) (*OntologyDiffResponse, error)
- func (db *DB) DimensionReport(ctx context.Context) (*core.DimensionReport, 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) GenerateOntologyTools(ctx context.Context, options OntologyToolGenOptions) ([]ToolDefinition, 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) ListActionTypes(ctx context.Context, _ ActionListRequest) (*ActionListResponse, error)
- func (db *DB) ListAllMemories(ctx context.Context) ([]MemoryRecord, error)
- func (db *DB) ListAllMemoriesPaged(ctx context.Context, req MemoryListAllRequest) (*MemoryListAllResponse, error)
- func (db *DB) ListGraphAll(ctx context.Context, req GraphListAllRequest) (*GraphListAllResponse, 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) PruneJunkEntities(ctx context.Context, opts GraphMaintenanceOptions) (*GraphPruneReport, error)
- 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) ReembedMemoryVectors(ctx context.Context, opts ReembedOptions) (*ReembedReport, error)
- func (db *DB) ReembedMismatchedVectors(ctx context.Context, opts ReembedOptions) (*ReembedReport, error)
- func (db *DB) RefreshKnowledgeGraphInference(ctx context.Context, req KnowledgeGraphInferenceRefreshRequest) (*KnowledgeGraphInferenceRefreshResponse, error)
- func (db *DB) ReindexMemoryGraph(ctx context.Context, opts GraphMaintenanceOptions) (*GraphReindexReport, error)
- func (db *DB) RepairVectorDimensions(ctx context.Context, req VectorDimensionRepairRequest) (*VectorDimensionRepairResponse, error)
- func (db *DB) ResolveObjectSet(ctx context.Context, set ObjectSet) (map[string]struct{}, error)
- func (db *DB) ResolveObjectSetObjects(ctx context.Context, req ObjectSetResolveRequest) (*ObjectSetResolveResponse, 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 GraphListAllEdge
- type GraphListAllNode
- type GraphListAllRequest
- type GraphListAllResponse
- type GraphMaintenanceOptions
- type GraphPruneReport
- type GraphRAGChunkResult
- type GraphRAGDocument
- type GraphRAGExtractor
- type GraphRAGIngestOptions
- type GraphRAGIngestResult
- type GraphRAGQueryOptions
- type GraphRAGQueryResult
- type GraphRAGToolbox
- func (t *GraphRAGToolbox) ApplyAction(ctx context.Context, req ActionApplyRequest) (*ActionApplyResponse, error)
- 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) DeleteDocumentGraph(ctx context.Context, req ToolDeleteDocumentGraphRequest) (*ToolDeleteDocumentGraphResponse, error)
- func (t *GraphRAGToolbox) DeleteEntities(ctx context.Context, req ToolDeleteEntitiesRequest) (*ToolDeleteEntitiesResponse, error)
- 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) DiffOntologySchema(ctx context.Context, req OntologyDiffRequest) (*OntologyDiffResponse, 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) FindNodes(ctx context.Context, req ToolFindNodesRequest) (*ToolFindNodesResponse, 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) ListActionTypes(ctx context.Context, req ActionListRequest) (*ActionListResponse, 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) ResolveObjectSet(ctx context.Context, req ObjectSetResolveRequest) (*ObjectSetResolveResponse, 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 GraphReindexReport
- 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 MemoryListAllRequest
- type MemoryListAllResponse
- type MemoryRecord
- type MemorySaveRequest
- type MemorySaveResponse
- type MemorySearchHit
- type MemorySearchRequest
- type MemorySearchResponse
- type MemorySyncOptions
- type MemorySyncPlan
- type MemorySyncReport
- type MemoryUpdateRequest
- type ObjectSet
- type ObjectSetKind
- type ObjectSetPredicate
- type ObjectSetResolveRequest
- type ObjectSetResolveResponse
- type OntologyActionParameter
- type OntologyActionRule
- type OntologyActionType
- type OntologyCardinality
- type OntologyChange
- type OntologyDataKind
- type OntologyDataType
- type OntologyDeleteRequest
- type OntologyDeleteResponse
- type OntologyDiff
- type OntologyDiffRequest
- type OntologyDiffResponse
- type OntologyEnforcement
- type OntologyGetRequest
- type OntologyGetResponse
- type OntologyInterfaceType
- type OntologyLinkSide
- type OntologyLinkType
- type OntologyListRequest
- type OntologyListResponse
- type OntologyNamedObjectSet
- type OntologyObjectType
- type OntologyProperty
- type OntologySaveRequest
- type OntologySaveResponse
- type OntologySchema
- type OntologyStatus
- type OntologySubmissionCriterion
- type OntologyToolGenOptions
- type OntologyValueSource
- type OntologyVisibility
- type Option
- type PredicateOp
- 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 ReembedOptions
- type ReembedReport
- type RerankItem
- type RerankOptions
- type Reranker
- type ResolvedObject
- type RetrievalDecision
- type RetrievalFilters
- type RetrievalPlan
- type TextSearchOptions
- type ToolBuildContextRequest
- type ToolBuildContextResponse
- type ToolChunk
- type ToolDefinition
- type ToolDeleteDocumentGraphRequest
- type ToolDeleteDocumentGraphResponse
- type ToolDeleteEntitiesRequest
- type ToolDeleteEntitiesResponse
- type ToolEntityInput
- type ToolExpandGraphRequest
- type ToolExpandGraphResponse
- type ToolExtractConversationRequest
- type ToolExtractConversationResponse
- type ToolFindNodesRequest
- type ToolFindNodesResponse
- type ToolGetChunksRequest
- type ToolGetChunksResponse
- type ToolGetNodesRequest
- type ToolGetNodesResponse
- type ToolIngestDocumentRequest
- type ToolIngestDocumentResponse
- type ToolNodeNameMatch
- type ToolRelationInput
- type ToolSearchChunksByEntitiesRequest
- type ToolSearchChunksByEntitiesResponse
- type ToolSearchGraphRAGLexicalRequest
- type ToolSearchTextRequest
- type ToolSearchTextResponse
- type ToolUpsertEntitiesRequest
- type ToolUpsertEntitiesResponse
- type ToolUpsertRelationsRequest
- type ToolUpsertRelationsResponse
- type ValueSourceKind
- type VectorDimensionRepairRequest
- type VectorDimensionRepairResponse
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
var ErrInvalidOntology = errors.New("invalid ontology schema")
ErrInvalidOntology marks every ontology rejection: a schema that does not hold together, and a write that does not conform to the active schema. Callers at a protocol boundary need to tell "you sent something bad" apart from "the server broke"; matching on it is reliable in a way that sniffing the message text is not.
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 ActionApplyRequest ¶ added in v2.67.0
type ActionApplyRequest struct {
Action string `json:"action"`
Parameters map[string]string `json:"parameters,omitempty"`
// ValidateOnly checks parameters and submission criteria without
// writing. Mutually exclusive with ReturnEdits, matching OSDK.
ValidateOnly bool `json:"validate_only,omitempty"`
// ReturnEdits includes the graph edits the action made.
ReturnEdits bool `json:"return_edits,omitempty"`
// Actor is recorded in the audit trail and resolves current_user value
// sources.
Actor string `json:"actor,omitempty"`
}
ActionApplyRequest runs one action type.
type ActionApplyResponse ¶ added in v2.67.0
type ActionApplyResponse struct {
Action string `json:"action"`
Valid bool `json:"valid"`
Applied bool `json:"applied"`
Errors []string `json:"errors,omitempty"`
Edits []ActionEdit `json:"edits,omitempty"`
}
ActionApplyResponse reports validity and, when asked, the edits applied.
type ActionEdit ¶ added in v2.67.0
type ActionEdit struct {
Kind string `json:"kind"`
ObjectID string `json:"object_id,omitempty"`
ObjectType string `json:"object_type,omitempty"`
LinkType string `json:"link_type,omitempty"`
FromID string `json:"from_id,omitempty"`
ToID string `json:"to_id,omitempty"`
}
ActionEdit is one graph change an action made.
type ActionListRequest ¶ added in v2.67.0
type ActionListRequest struct{}
ActionListRequest lists the action types on the active ontology.
type ActionListResponse ¶ added in v2.67.0
type ActionListResponse struct {
Actions []OntologyActionType `json:"actions"`
}
ActionListResponse returns the callable action types. The full definitions are returned, not just their names: an agent reads this to work out how to call an action, so the parameters and criteria are the useful part.
type ActionRuleKind ¶ added in v2.67.0
type ActionRuleKind string
ActionRuleKind enumerates the ontology edits an action can make. Foundry also has function rules and side-effect rules (notification, webhook, schedule build); those need a runtime CortexDB deliberately does not have, so they are out of scope.
const ( ActionRuleCreateObject ActionRuleKind = "create_object" ActionRuleModifyObject ActionRuleKind = "modify_object" ActionRuleCreateOrModifyObject ActionRuleKind = "create_or_modify_object" ActionRuleDeleteObject ActionRuleKind = "delete_object" ActionRuleCreateLink ActionRuleKind = "create_link" ActionRuleDeleteLink ActionRuleKind = "delete_link" )
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) ApplyAction ¶ added in v2.67.0
func (db *DB) ApplyAction(ctx context.Context, req ActionApplyRequest) (*ActionApplyResponse, error)
ApplyAction runs one governed write.
Two failure modes are deliberately different shapes. A request that does not name a runnable action is an error: nothing about it can be retried by fixing a value. A request whose parameters or submission criteria do not hold comes back as a normal response with Valid=false, because that is a verdict on the inputs, and validate-only callers ask for exactly that.
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)
func (*DB) DiffOntologySchema ¶ added in v2.67.0
func (db *DB) DiffOntologySchema(ctx context.Context, req OntologyDiffRequest) (*OntologyDiffResponse, error)
DiffOntologySchema compares a candidate schema against the stored one of the same ID, so a caller can see what applying it would invalidate before it is applied. The stored schema is the `before` side: the question being answered is what happens to the data already written under it.
func (*DB) DimensionReport ¶ added in v2.59.0
DimensionReport surfaces vector-dimension drift across the store, so a caller can see whether a re-embedding pass is needed.
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) GenerateOntologyTools ¶ added in v2.67.0
func (db *DB) GenerateOntologyTools(ctx context.Context, options OntologyToolGenOptions) ([]ToolDefinition, error)
GenerateOntologyTools turns the active ontology into typed tool definitions: one per action type, and optionally one list tool per object type. Typed tools beat a generic upsert because the parameter names, types and required-ness live in the schema the model is shown rather than in prose it has to be trusted to follow.
The result is deliberately not wired into NewMCPServer. Exposing it is the caller's decision, because the cost of a larger tool list is paid on every request, including the ones that have nothing to do with the ontology.
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)
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) ListActionTypes ¶ added in v2.67.0
func (db *DB) ListActionTypes(ctx context.Context, _ ActionListRequest) (*ActionListResponse, error)
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) ListAllMemoriesPaged ¶ added in v2.63.2
func (db *DB) ListAllMemoriesPaged(ctx context.Context, req MemoryListAllRequest) (*MemoryListAllResponse, error)
ListAllMemoriesPaged wraps ListAllMemories with a bound and a truncation flag.
func (*DB) ListGraphAll ¶ added in v2.65.0
func (db *DB) ListGraphAll(ctx context.Context, req GraphListAllRequest) (*GraphListAllResponse, error)
ListGraphAll returns the meaningful entity graph: every non-chunk node and the edges between them, excluding structural (has_chunk/next) edges. When the node count exceeds the limit it keeps the most-connected core, which is what makes a large graph readable rather than an arbitrary slice of it.
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)
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) PruneJunkEntities ¶ added in v2.75.1
func (db *DB) PruneJunkEntities(ctx context.Context, opts GraphMaintenanceOptions) (*GraphPruneReport, error)
PruneJunkEntities removes generic entity nodes whose names the current extraction rules would never produce.
The old Title Case pattern collected English grammar — real stores grew entity nodes named "This", "Only", "Requires", "Measured" — and co-occurrence paired each with everything nearby, so every junk node radiated junk edges. The extraction fix stops new ones; this retires the stock. Only untyped nodes are candidates: a node somebody saved with a type ("host", "Flight") was declared, not scraped, and stays whatever its name looks like.
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) ReembedMemoryVectors ¶ added in v2.75.0
func (db *DB) ReembedMemoryVectors(ctx context.Context, opts ReembedOptions) (*ReembedReport, error)
ReembedMemoryVectors embeds stored memories whose vector is missing or has the wrong dimensionality for the configured embedder.
ReembedMismatchedVectors covers knowledge chunks only; memories live in the messages table and were left out, so a store that ran without an embedder accumulated memories with no vector — invisible to semantic recall while lexical search still found them, which masked the gap. Only memory buckets (session ids under the `memory:` prefix) are touched, not chat history.
func (*DB) ReembedMismatchedVectors ¶ added in v2.59.0
func (db *DB) ReembedMismatchedVectors(ctx context.Context, opts ReembedOptions) (*ReembedReport, error)
ReembedMismatchedVectors recomputes vectors whose stored dimensionality differs from the configured embedder's.
Such rows appear whenever a store outlives an embedding model. They cannot enter the vector index — a graph holds one dimensionality — so they quietly stop being retrievable by similarity while lexical search still finds them, which masks the problem. The numbers cannot be salvaged by truncating or padding: vectors from two models occupy unrelated spaces, so the only honest repair is to embed the stored text again with the current model.
Returns ErrEmbedderNotConfigured when the DB has no embedder.
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) ReindexMemoryGraph ¶ added in v2.75.1
func (db *DB) ReindexMemoryGraph(ctx context.Context, opts GraphMaintenanceOptions) (*GraphReindexReport, error)
ReindexMemoryGraph gives stored memories the graph presence new saves get.
Memories saved before they had graph nodes — or without explicit entities — are unreachable through entity_names: the edges recall would walk were never written. This pass extracts entities from each memory's text with the current rules and writes the same memory-node-plus-mentions shape SaveMemory now writes, so the backlog becomes reachable the same way new memories are. Idempotent: everything it writes is an upsert keyed on stable ids.
func (*DB) RepairVectorDimensions ¶ added in v2.59.0
func (db *DB) RepairVectorDimensions(ctx context.Context, req VectorDimensionRepairRequest) (*VectorDimensionRepairResponse, error)
RepairVectorDimensions backs the `vector_dimension_repair` MCP tool. It always reports the drift; it only rewrites vectors when dry_run is explicitly false.
func (*DB) ResolveObjectSet ¶ added in v2.67.0
ResolveObjectSet evaluates an object set definition to the node IDs it selects. Scalar predicates read properties, text predicates match terms, nearest_neighbors goes through the vector index and search_around walks link edges — all of them composable inside one expression.
func (*DB) ResolveObjectSetObjects ¶ added in v2.67.0
func (db *DB) ResolveObjectSetObjects(ctx context.Context, req ObjectSetResolveRequest) (*ObjectSetResolveResponse, error)
ResolveObjectSetObjects evaluates an object set and loads its members.
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)
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 GraphListAllEdge ¶ added in v2.65.0
type GraphListAllEdge struct {
From string `json:"from"`
To string `json:"to"`
Type string `json:"type,omitempty"`
}
GraphListAllEdge is one edge in a bulk listing.
type GraphListAllNode ¶ added in v2.65.0
type GraphListAllNode struct {
ID string `json:"id"`
Label string `json:"label"`
Type string `json:"type,omitempty"`
// Degree is how many meaningful edges touch this node. The caller ranks by
// it when it has to show only part of a large graph.
Degree int `json:"degree"`
}
GraphListAllNode is one node in a bulk listing.
type GraphListAllRequest ¶ added in v2.65.0
type GraphListAllRequest struct {
// Limit caps how many nodes come back (0 = defaultGraphListLimit). Edges are
// then restricted to those between returned nodes, so the result is always a
// self-consistent subgraph rather than one with dangling ends.
Limit int `json:"limit,omitempty"`
}
GraphListAllRequest asks for the whole meaningful entity graph.
type GraphListAllResponse ¶ added in v2.65.0
type GraphListAllResponse struct {
Nodes []GraphListAllNode `json:"nodes"`
Edges []GraphListAllEdge `json:"edges"`
// Truncated is true when Limit dropped nodes. A view that silently showed
// part of a graph would look like the whole one.
Truncated bool `json:"truncated,omitempty"`
// TotalNodes is how many meaningful nodes exist, so a truncated caller can
// report what it is not showing.
TotalNodes int `json:"total_nodes"`
}
GraphListAllResponse carries the subgraph and whether it was cut short.
type GraphMaintenanceOptions ¶ added in v2.75.1
type GraphMaintenanceOptions struct {
// DryRun reports what would change without writing anything.
DryRun bool
// Limit caps how many rows are processed (0 = all).
Limit int
}
GraphMaintenanceOptions controls PruneJunkEntities and ReindexMemoryGraph.
type GraphPruneReport ¶ added in v2.75.1
type GraphPruneReport struct {
Scanned int `json:"scanned"`
Pruned int `json:"pruned"`
EdgesRemoved int `json:"edges_removed"`
DryRun bool `json:"dry_run"`
Names []string `json:"names,omitempty"`
}
GraphPruneReport says what a junk-entity prune did, naming every node it removed — a deletion justified only by a count is not auditable.
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) ApplyAction ¶ added in v2.67.0
func (t *GraphRAGToolbox) ApplyAction(ctx context.Context, req ActionApplyRequest) (*ActionApplyResponse, error)
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) DeleteDocumentGraph ¶ added in v2.69.0
func (t *GraphRAGToolbox) DeleteDocumentGraph(ctx context.Context, req ToolDeleteDocumentGraphRequest) (*ToolDeleteDocumentGraphResponse, error)
DeleteDocumentGraph removes a document's chunk and document nodes, its relation edges, and the entities it alone asserted. Embeddings are not touched: they live in the caller's collection and the caller knows which they are; the graph does not.
func (*GraphRAGToolbox) DeleteEntities ¶ added in v2.65.0
func (t *GraphRAGToolbox) DeleteEntities(ctx context.Context, req ToolDeleteEntitiesRequest) (*ToolDeleteEntitiesResponse, error)
DeleteEntities removes entity nodes and their edges.
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)
func (*GraphRAGToolbox) DiffOntologySchema ¶ added in v2.67.0
func (t *GraphRAGToolbox) DiffOntologySchema(ctx context.Context, req OntologyDiffRequest) (*OntologyDiffResponse, error)
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) FindNodes ¶ added in v2.62.0
func (t *GraphRAGToolbox) FindNodes(ctx context.Context, req ToolFindNodesRequest) (*ToolFindNodesResponse, error)
FindNodes resolves names to graph nodes.
Until this existed the property graph could only be entered by ID, which meant a caller holding a name had to *derive* the ID the writer would have produced — re-implementing someone else's hashing, guessing the entity type, and getting an empty subgraph when either was wrong. Empty is the same answer the graph gives for a subject it genuinely knows nothing about, so the failure was silent and looked like missing data.
It also cannot work across wordings, and that is where it bites hardest. A graph built from mixed-language material holds "Left-Hand Limit" next to "含绝对值的极限"; a reader asking for 左极限 hashes to nothing, and is told the material does not cover it. Three matching passes, weakest last, so a caller learns not just what was found but how sure it should be.
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)
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) ListActionTypes ¶ added in v2.67.0
func (t *GraphRAGToolbox) ListActionTypes(ctx context.Context, req ActionListRequest) (*ActionListResponse, error)
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)
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) ResolveObjectSet ¶ added in v2.67.0
func (t *GraphRAGToolbox) ResolveObjectSet(ctx context.Context, req ObjectSetResolveRequest) (*ObjectSetResolveResponse, error)
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)
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)
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 GraphReindexReport ¶ added in v2.75.1
type GraphReindexReport struct {
Memories int `json:"memories"`
Indexed int `json:"indexed"`
Skipped int `json:"skipped"`
EntitiesSeen int `json:"entities_seen"`
DryRun bool `json:"dry_run"`
}
GraphReindexReport summarizes a memory-graph backfill pass.
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 MemoryListAllRequest ¶ added in v2.63.2
type MemoryListAllRequest struct {
// Limit caps how many records come back (0 = defaultMemoryListLimit).
// A brain with tens of thousands of memories should not be pulled into one
// message by accident; a caller that wants them all raises this on purpose.
Limit int `json:"limit,omitempty"`
}
MemoryListAllRequest asks for every stored memory.
type MemoryListAllResponse ¶ added in v2.63.2
type MemoryListAllResponse struct {
Memories []MemoryRecord `json:"memories"`
// Truncated is true when Limit cut the listing short. An export that
// silently dropped records would look complete and not be.
Truncated bool `json:"truncated,omitempty"`
}
MemoryListAllResponse carries the records and says whether it had to stop.
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"`
// Supersedes names memories this one replaces. They stay stored and
// exported, but recall stops presenting them as current — without this the
// old wording keeps answering with stale facts in a confident voice, and
// the only fix was hunting down its id and deleting history.
Supersedes []string `json:"supersedes,omitempty"`
// Entities and Relations let a caller record what this memory is ABOUT in
// the same call that stores it, the way SaveKnowledge already can. Without
// them the graph could only be filled by a separate extraction pass, which
// is what made agent-written memories arrive with no graph presence.
Entities []ToolEntityInput `json:"entities,omitempty"`
Relations []ToolRelationInput `json:"relations,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"`
// EntityNames let recall reach a memory through the graph when the memory
// never spells the entity the way the question does. Lexical search cannot
// do that, so before memories had graph nodes this hint had nowhere to go.
EntityNames []string `json:"entity_names,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 MemorySyncOptions ¶ added in v2.74.0
type MemorySyncOptions struct {
// Dir holds one Markdown file per memory, in the shape --export-memory
// writes: YAML frontmatter carrying metadata.id, then the body. MEMORY.md is
// the index and is skipped.
Dir string
// Prune deletes memories that the directory no longer contains. Off by
// default: an import that only ever adds cannot lose anything, whereas a
// prune against the wrong directory would empty the brain.
Prune bool
}
MemorySyncOptions configures PlanMemorySync.
type MemorySyncPlan ¶ added in v2.74.0
type MemorySyncPlan struct {
// Scanned counts memory files read from the directory.
Scanned int
// Create are memories in the directory that the store does not have — a file
// written by hand, or one restored from a backup.
Create []MemorySaveRequest
// Update are memories whose file body differs from the stored content.
Update []MemorySaveRequest
// Delete are ids the store has and the directory does not. Empty unless
// Prune is set.
Delete []string
// Unchanged counts files whose body already matches the store.
Unchanged int
}
MemorySyncPlan is what a sync would do, computed before anything is written.
Planning is separated from applying because the brain is not always local: the CLI applies the same plan over gRPC when CORTEXDB_REMOTE is set. Keeping the decision pure also makes it testable without a database.
func PlanMemorySync ¶ added in v2.74.0
func PlanMemorySync(current []MemoryRecord, opts MemorySyncOptions) (*MemorySyncPlan, error)
PlanMemorySync diffs a directory of memory Markdown files against the memories a store currently holds.
The directory is the source of truth, which is the whole point: editing a memory means editing a file, and deleting one means deleting a file. Without this the only way to remove a wrong memory was to call the delete tool with an id nobody has written down.
func (*MemorySyncPlan) Empty ¶ added in v2.74.0
func (p *MemorySyncPlan) Empty() bool
Empty reports whether applying this plan would change nothing.
type MemorySyncReport ¶ added in v2.74.0
type MemorySyncReport struct {
Created int `json:"created"`
Updated int `json:"updated"`
Deleted int `json:"deleted"`
Unchanged int `json:"unchanged"`
IDs []string `json:"ids,omitempty"`
}
MemorySyncReport is the outcome of applying a plan.
func ApplyMemorySync ¶ added in v2.74.0
func ApplyMemorySync(ctx context.Context, db *DB, plan *MemorySyncPlan) (*MemorySyncReport, error)
ApplyMemorySync writes a plan to a local store. The CLI applies the same plan over gRPC when the brain is remote.
func SyncMemoryDir ¶ added in v2.74.0
func SyncMemoryDir(ctx context.Context, db *DB, opts MemorySyncOptions) (*MemorySyncReport, error)
SyncMemoryDir plans and applies in one call against a local store.
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 ObjectSet ¶ added in v2.67.0
type ObjectSet struct {
Kind ObjectSetKind `json:"kind"`
// base
ObjectType string `json:"object_type,omitempty"`
// interface_base
InterfaceType string `json:"interface_type,omitempty"`
// static
ObjectIDs []string `json:"object_ids,omitempty"`
// reference — a saved object set on the active schema
Reference string `json:"reference,omitempty"`
// filter / search_around
Source *ObjectSet `json:"source,omitempty"`
Where *ObjectSetPredicate `json:"where,omitempty"`
// search_around: the link *side* api name to traverse
Link string `json:"link,omitempty"`
// union / intersect / subtract
Operands []ObjectSet `json:"operands,omitempty"`
}
ObjectSet is a composable description of a set of objects. It is the one place where vector search, full-text search and graph traversal are peers rather than three separate APIs.
The type is recursive through Source and Operands. encoding/json handles that unaided because the self-reference goes through a pointer and a slice, so no custom marshaller is needed. What does not handle it is the MCP SDK's schema inference, so any tool carrying an ObjectSet has to declare its input schema rather than let the SDK reflect one.
type ObjectSetKind ¶ added in v2.67.0
type ObjectSetKind string
ObjectSetKind is the discriminator of the ObjectSet union type.
const ( ObjectSetBase ObjectSetKind = "base" ObjectSetInterfaceBase ObjectSetKind = "interface_base" ObjectSetStatic ObjectSetKind = "static" ObjectSetFilter ObjectSetKind = "filter" ObjectSetUnion ObjectSetKind = "union" ObjectSetIntersect ObjectSetKind = "intersect" ObjectSetSubtract ObjectSetKind = "subtract" ObjectSetSearchAround ObjectSetKind = "search_around" ObjectSetReference ObjectSetKind = "reference" )
type ObjectSetPredicate ¶ added in v2.67.0
type ObjectSetPredicate struct {
Op PredicateOp `json:"op"`
Property string `json:"property,omitempty"`
Value string `json:"value,omitempty"`
Values []string `json:"values,omitempty"`
Operands []ObjectSetPredicate `json:"operands,omitempty"`
// K bounds a nearest_neighbors predicate. Foundry caps this at 100.
K int `json:"k,omitempty"`
// Vector is the query vector for nearest_neighbors. When empty the
// resolver embeds Value instead, which is what agents will normally send.
Vector []float32 `json:"vector,omitempty"`
}
ObjectSetPredicate is the filter expression tree.
type ObjectSetResolveRequest ¶ added in v2.67.0
type ObjectSetResolveRequest struct {
ObjectSet ObjectSet `json:"object_set"`
Limit int `json:"limit,omitempty"`
}
ObjectSetResolveRequest evaluates an object set and returns its members.
type ObjectSetResolveResponse ¶ added in v2.67.0
type ObjectSetResolveResponse struct {
Objects []ResolvedObject `json:"objects"`
Total int `json:"total"`
}
ObjectSetResolveResponse returns the resolved members, plus how many there were before the limit was applied.
type OntologyActionParameter ¶ added in v2.67.0
type OntologyActionParameter struct {
APIName string `json:"api_name"`
DisplayName string `json:"display_name,omitempty"`
Description string `json:"description,omitempty"`
DataType OntologyDataType `json:"data_type"`
Required bool `json:"required,omitempty"`
// ObjectType marks this as an object reference parameter: its value is
// the node ID, or the primary key, of an existing object of that type.
ObjectType string `json:"object_type,omitempty"`
// AllowedValues restricts the parameter to a fixed set.
AllowedValues []string `json:"allowed_values,omitempty"`
}
OntologyActionParameter is one input to an action.
type OntologyActionRule ¶ added in v2.67.0
type OntologyActionRule struct {
Kind ActionRuleKind `json:"kind"`
// object rules
ObjectType string `json:"object_type,omitempty"`
// Target names the object reference parameter identifying which object
// to modify or delete.
Target string `json:"target,omitempty"`
PropertyValues map[string]OntologyValueSource `json:"property_values,omitempty"`
// link rules
LinkType string `json:"link_type,omitempty"`
From OntologyValueSource `json:"from,omitempty"`
To OntologyValueSource `json:"to,omitempty"`
}
OntologyActionRule is one edit an action makes.
type OntologyActionType ¶ added in v2.67.0
type OntologyActionType struct {
APIName string `json:"api_name"`
DisplayName string `json:"display_name,omitempty"`
Description string `json:"description,omitempty"`
Status OntologyStatus `json:"status,omitempty"`
Parameters []OntologyActionParameter `json:"parameters,omitempty"`
Rules []OntologyActionRule `json:"rules,omitempty"`
SubmissionCriteria []OntologySubmissionCriterion `json:"submission_criteria,omitempty"`
}
OntologyActionType is a governed, auditable set of graph edits.
type OntologyCardinality ¶ added in v2.67.0
type OntologyCardinality string
OntologyCardinality is the multiplicity of one side of a link type.
const ( OntologyCardinalityOne OntologyCardinality = "ONE" OntologyCardinalityMany OntologyCardinality = "MANY" )
type OntologyChange ¶ added in v2.67.0
type OntologyChange struct {
Kind string `json:"kind"`
Target string `json:"target"`
Detail string `json:"detail"`
Breaking bool `json:"breaking"`
}
OntologyChange is one difference between two schema versions.
type OntologyDataKind ¶ added in v2.67.0
type OntologyDataKind string
OntologyDataKind enumerates the property base types CortexDB supports. This is Foundry's discriminator list minus the types that need a Foundry backend (attachment, mediaReference, timeseries, geotimeSeriesReference).
const ( OntologyDataString OntologyDataKind = "string" OntologyDataInteger OntologyDataKind = "integer" OntologyDataLong OntologyDataKind = "long" OntologyDataDouble OntologyDataKind = "double" OntologyDataDecimal OntologyDataKind = "decimal" OntologyDataBoolean OntologyDataKind = "boolean" OntologyDataDate OntologyDataKind = "date" OntologyDataTimestamp OntologyDataKind = "timestamp" OntologyDataGeoPoint OntologyDataKind = "geopoint" OntologyDataGeoShape OntologyDataKind = "geoshape" OntologyDataVector OntologyDataKind = "vector" OntologyDataArray OntologyDataKind = "array" OntologyDataStruct OntologyDataKind = "struct" OntologyDataMarking OntologyDataKind = "marking" )
type OntologyDataType ¶ added in v2.67.0
type OntologyDataType struct {
Kind OntologyDataKind `json:"kind"`
ItemType *OntologyDataType `json:"item_type,omitempty"`
Fields []OntologyProperty `json:"fields,omitempty"`
Dimension int `json:"dimension,omitempty"`
}
OntologyDataType describes a property's base type, including the nested element type for arrays, the field list for structs, and the dimension for vectors.
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 OntologyDiff ¶ added in v2.67.0
type OntologyDiff struct {
Changes []OntologyChange `json:"changes"`
HasBreakingChanges bool `json:"has_breaking_changes"`
}
OntologyDiff reports what changed between two schema versions, and whether any change invalidates data already in the graph.
func DiffOntologySchemas ¶ added in v2.67.0
func DiffOntologySchemas(before OntologySchema, after OntologySchema) OntologyDiff
DiffOntologySchemas compares two schema versions. "Breaking" means objects or edges already written under `before` would no longer validate under `after` — which is exactly the class of change that silently corrupts a graph if applied without warning.
Both sides are expanded first. Storage keeps a schema exactly as it was written, so an object type that names a shared property without restating its data type is stored as a bare placeholder; comparing two placeholders finds them identical and would hide the most far-reaching change of all — retyping a shared property retypes it on every object type that uses it.
The comparison covers object types and link types, the two kinds that describe data already on disk. Interfaces, actions and saved object sets describe how that data is read and written rather than what shape it has, so changing them cannot invalidate a stored node or edge.
type OntologyDiffRequest ¶ added in v2.67.0
type OntologyDiffRequest struct {
SchemaID string `json:"schema_id"`
Candidate OntologySchema `json:"candidate"`
}
OntologyDiffRequest compares a candidate schema against a stored one.
type OntologyDiffResponse ¶ added in v2.67.0
type OntologyDiffResponse struct {
Diff OntologyDiff `json:"diff"`
}
OntologyDiffResponse reports the differences and whether any break data.
type OntologyEnforcement ¶ added in v2.69.0
type OntologyEnforcement string
OntologyEnforcement is what an active schema does to writes that do not conform to it.
const ( // OntologyEnforcementStrict rejects non-conforming writes: unknown object // types, missing primary keys, undeclared properties, undeclared link // types, violated cardinality. This is the default, and the only behaviour // that existed before the field did. OntologyEnforcementStrict OntologyEnforcement = "strict" // OntologyEnforcementVocabulary keeps the schema as a shared vocabulary — // canonical type spellings, interface expansion for retrieval — without // gating writes on it. An entity of a declared type still gets its typed // node ID when its primary key is supplied; one that cannot state a // primary key (the normal case for LLM extraction from prose, which has // no storage identity to offer) falls back to the name-derived ID instead // of being refused. Undeclared types pass through untouched. // // The field exists because the strict default forced a choice on // extraction pipelines: activate the schema and lose every extracted // entity, or leave it inactive and lose canonicalization and interface // retrieval with it. OntologyEnforcementVocabulary OntologyEnforcement = "vocabulary" )
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 OntologyInterfaceType ¶ added in v2.67.0
type OntologyInterfaceType struct {
APIName string `json:"api_name"`
DisplayName string `json:"display_name,omitempty"`
Description string `json:"description,omitempty"`
Extends []string `json:"extends,omitempty"`
Properties []OntologyProperty `json:"properties,omitempty"`
}
OntologyInterfaceType is an abstract shape that object types implement, giving polymorphic retrieval across unrelated concrete types.
type OntologyLinkSide ¶ added in v2.67.0
type OntologyLinkSide struct {
APIName string `json:"api_name"`
DisplayName string `json:"display_name,omitempty"`
ObjectTypeAPIName string `json:"object_type_api_name"`
// Cardinality is how many objects a traversal starting at ObjectTypeAPIName
// reaches. A ONE side is the side that carries the foreign key.
Cardinality OntologyCardinality `json:"cardinality"`
ForeignKeyProperty string `json:"foreign_key_property,omitempty"`
}
OntologyLinkSide is one end of a link type. Foundry models multiplicity per side rather than as a single one-to-many enum: a one-to-many link is one side ONE and one side MANY.
type OntologyLinkType ¶ added in v2.67.0
type OntologyLinkType struct {
APIName string `json:"api_name"`
Description string `json:"description,omitempty"`
Status OntologyStatus `json:"status,omitempty"`
A OntologyLinkSide `json:"a"`
B OntologyLinkSide `json:"b"`
}
OntologyLinkType is a bidirectional relationship between two object types. Graph edges carry the link type APIName as their EdgeType; the side API names are traversal labels only.
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 OntologyNamedObjectSet ¶ added in v2.67.0
type OntologyNamedObjectSet struct {
APIName string `json:"api_name"`
Description string `json:"description,omitempty"`
Definition ObjectSet `json:"definition"`
}
OntologyNamedObjectSet is a saved, reusable object set definition.
type OntologyObjectType ¶ added in v2.67.0
type OntologyObjectType struct {
APIName string `json:"api_name"`
DisplayName string `json:"display_name,omitempty"`
PluralDisplayName string `json:"plural_display_name,omitempty"`
Description string `json:"description,omitempty"`
Status OntologyStatus `json:"status,omitempty"`
Visibility OntologyVisibility `json:"visibility,omitempty"`
Icon string `json:"icon,omitempty"`
PrimaryKey string `json:"primary_key"`
TitleProperty string `json:"title_property,omitempty"`
Properties []OntologyProperty `json:"properties,omitempty"`
Implements []string `json:"implements,omitempty"`
Aliases []string `json:"aliases,omitempty"`
}
OntologyObjectType is the schema definition of a real-world entity. PrimaryKey is mandatory: it is what gives objects a stable identity.
type OntologyProperty ¶ added in v2.67.0
type OntologyProperty struct {
APIName string `json:"api_name"`
DisplayName string `json:"display_name,omitempty"`
Description string `json:"description,omitempty"`
DataType OntologyDataType `json:"data_type"`
Required bool `json:"required,omitempty"`
// Searchable routes the property value into FTS5 so ObjectSet text
// predicates can match on it.
Searchable bool `json:"searchable,omitempty"`
// Vectorized routes the property value into the vector index so
// ObjectSet nearest-neighbour predicates can match on it.
Vectorized bool `json:"vectorized,omitempty"`
}
OntologyProperty is a typed characteristic of an object type or interface.
type OntologySaveRequest ¶ added in v2.14.0
type OntologySaveRequest struct {
Schema OntologySchema `json:"schema"`
Activate bool `json:"activate,omitempty"`
Deactivate bool `json:"deactivate,omitempty"`
}
OntologySaveRequest stores or updates a v2 ontology 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"`
// StrictActions closes the generic upsert tools once action types are
// defined, making actions the only write path. Defaults to false.
StrictActions bool `json:"strict_actions,omitempty"`
// Enforcement chooses between rejecting non-conforming writes ("strict",
// the default) and treating the schema as a non-gating vocabulary
// ("vocabulary"). See the OntologyEnforcement constants.
Enforcement OntologyEnforcement `json:"enforcement,omitempty"`
Metadata map[string]string `json:"metadata,omitempty"`
ObjectTypes []OntologyObjectType `json:"object_types,omitempty"`
LinkTypes []OntologyLinkType `json:"link_types,omitempty"`
InterfaceTypes []OntologyInterfaceType `json:"interface_types,omitempty"`
ActionTypes []OntologyActionType `json:"action_types,omitempty"`
ObjectSets []OntologyNamedObjectSet `json:"object_sets,omitempty"`
CreatedAt time.Time `json:"created_at"`
UpdatedAt time.Time `json:"updated_at"`
}
OntologySchema is the full stored ontology.
type OntologyStatus ¶ added in v2.67.0
type OntologyStatus string
OntologyStatus is the lifecycle stage of a type, mirroring Foundry's release status.
const ( OntologyStatusActive OntologyStatus = "active" OntologyStatusExperimental OntologyStatus = "experimental" OntologyStatusDeprecated OntologyStatus = "deprecated" )
type OntologySubmissionCriterion ¶ added in v2.67.0
type OntologySubmissionCriterion struct {
Parameter string `json:"parameter"`
Op PredicateOp `json:"op,omitempty"`
Value string `json:"value,omitempty"`
Values []string `json:"values,omitempty"`
Regex string `json:"regex,omitempty"`
FailureMessage string `json:"failure_message,omitempty"`
}
OntologySubmissionCriterion gates whether an action may be submitted. Criteria see parameters only, never the graph — matching Foundry's Validate Action, which explicitly does not consult existing data.
type OntologyToolGenOptions ¶ added in v2.67.0
type OntologyToolGenOptions struct {
// IncludeObjectTypes also emits one list tool per object type.
IncludeObjectTypes bool `json:"include_object_types,omitempty"`
// MaxTools caps the number of generated tools. Zero uses the default.
MaxTools int `json:"max_tools,omitempty"`
}
OntologyToolGenOptions controls tool generation from the active ontology.
type OntologyValueSource ¶ added in v2.67.0
type OntologyValueSource struct {
Kind ValueSourceKind `json:"kind"`
// parameter
Parameter string `json:"parameter,omitempty"`
// object_property: read Property off the object the named parameter points at
Property string `json:"property,omitempty"`
// static
Static string `json:"static,omitempty"`
}
OntologyValueSource resolves to a concrete value at apply time.
type OntologyVisibility ¶ added in v2.67.0
type OntologyVisibility string
OntologyVisibility controls how prominently a type surfaces to callers.
const ( OntologyVisibilityNormal OntologyVisibility = "normal" OntologyVisibilityProminent OntologyVisibility = "prominent" OntologyVisibilityHidden OntologyVisibility = "hidden" )
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 PredicateOp ¶ added in v2.67.0
type PredicateOp string
PredicateOp is the discriminator of a filter predicate.
const ( PredicateEq PredicateOp = "eq" PredicateLt PredicateOp = "lt" PredicateLte PredicateOp = "lte" PredicateGt PredicateOp = "gt" PredicateGte PredicateOp = "gte" PredicateIsNull PredicateOp = "is_null" PredicateIn PredicateOp = "in" PredicateContains PredicateOp = "contains" PredicateStartsWith PredicateOp = "starts_with" PredicateContainsAllTerms PredicateOp = "contains_all_terms" PredicateContainsAnyTerm PredicateOp = "contains_any_term" PredicateNearestNeighbors PredicateOp = "nearest_neighbors" PredicateAnd PredicateOp = "and" PredicateOr PredicateOp = "or" PredicateNot PredicateOp = "not" )
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 ReembedOptions ¶ added in v2.59.0
type ReembedOptions struct {
// Limit caps how many rows are processed (0 = all of them).
Limit int
// BatchSize is how many texts go to the embedder per call (0 = 16).
BatchSize int
// DryRun reports what would change without writing anything.
DryRun bool
}
ReembedOptions controls a re-embedding pass.
type ReembedReport ¶ added in v2.59.0
type ReembedReport struct {
TargetDim int `json:"targetDim"`
Candidates int `json:"candidates"`
Reembedded int `json:"reembedded"`
Failed int `json:"failed"`
DryRun bool `json:"dryRun"`
// Collections whose declared dimension was brought in line with their contents.
Reconciled int `json:"reconciled"`
Errors []string `json:"errors,omitempty"`
}
ReembedReport is the outcome of a re-embedding pass.
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 ResolvedObject ¶ added in v2.67.0
type ResolvedObject struct {
ObjectID string `json:"object_id"`
ObjectType string `json:"object_type"`
Title string `json:"title,omitempty"`
Properties map[string]string `json:"properties,omitempty"`
}
ResolvedObject is one member of a resolved object set.
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"`
// Collection is shorthand for Filters.Collection.
//
// `collection` is a top-level parameter of the same call and also lives at
// `plan.filters.collection`, so a model reaches for `plan.collection` — and with
// additionalProperties:false that was a hard schema rejection, costing a whole model round trip on
// every scoped search before it guessed the longer spelling. Accepting it is cheaper than being
// right about it. Filters.Collection is the more specific spelling and wins.
Collection string `json:"collection,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 ToolDeleteDocumentGraphRequest ¶ added in v2.69.0
type ToolDeleteDocumentGraphRequest struct {
DocumentID string `json:"document_id"`
// DryRun reports what would be removed without removing it.
DryRun bool `json:"dry_run,omitempty"`
}
ToolDeleteDocumentGraphRequest removes everything a document put in the graph.
type ToolDeleteDocumentGraphResponse ¶ added in v2.69.0
type ToolDeleteDocumentGraphResponse struct {
// EntityNodesDeleted counts entities whose only source was this document.
EntityNodesDeleted int `json:"entity_nodes_deleted"`
// EntityNodesDetached counts entities other documents also assert: this
// document's claim was removed, the entity stays.
EntityNodesDetached int `json:"entity_nodes_detached"`
ChunkNodesDeleted int `json:"chunk_nodes_deleted"`
DocumentNodeDeleted bool `json:"document_node_deleted"`
RelationEdgesDeleted int `json:"relation_edges_deleted"`
DryRun bool `json:"dry_run,omitempty"`
}
ToolDeleteDocumentGraphResponse says what went, what stayed, and why.
type ToolDeleteEntitiesRequest ¶ added in v2.65.0
type ToolDeleteEntitiesRequest struct {
// Names are entity names or full node ids ("entity:foo"). Names are
// resolved the same way upsert_entities resolves them, so a caller can pass
// back exactly what it saw.
Names []string `json:"names"`
// DryRun reports what would be removed without removing it. Deletion is not
// reversible, so a caller that is guessing should look first.
DryRun bool `json:"dry_run,omitempty"`
}
ToolDeleteEntitiesRequest removes entities and every edge touching them.
type ToolDeleteEntitiesResponse ¶ added in v2.65.0
type ToolDeleteEntitiesResponse struct {
Deleted []string `json:"deleted,omitempty"`
// NotFound names nothing was stored under, so a typo surfaces instead of
// being reported as a successful deletion of nothing.
NotFound []string `json:"not_found,omitempty"`
EdgesRemoved int `json:"edges_removed"`
DryRun bool `json:"dry_run,omitempty"`
}
ToolDeleteEntitiesResponse says what went and what was not there.
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 ToolFindNodesRequest ¶ added in v2.62.0
type ToolFindNodesRequest struct {
Names []string `json:"names"`
// Optional filter, e.g. []string{"Concept"}. Empty means any type.
NodeTypes []string `json:"node_types,omitempty"`
// Per-name cap. Zero means the default.
Limit int `json:"limit,omitempty"`
}
ToolFindNodesRequest looks graph nodes up by what they are called.
type ToolFindNodesResponse ¶ added in v2.62.0
type ToolFindNodesResponse struct {
Matches []ToolNodeNameMatch `json:"matches"`
}
ToolFindNodesResponse returns what each requested name resolved to.
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 ToolNodeNameMatch ¶ added in v2.62.0
type ToolNodeNameMatch struct {
Name string `json:"name"`
Nodes []*graph.GraphNode `json:"nodes"`
// How the best node was found: "exact", "fold" (case/space/punctuation
// collapsed) or "contains". Reported because the three carry very different
// confidence, and a caller acting on a "contains" hit should be able to
// choose not to.
Match string `json:"match,omitempty"`
}
ToolNodeNameMatch is one requested name and the nodes it found, best first.
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"`
// Written is how many edges reached the store. It is reported because it is not always
// len(EdgeIDs): an edge whose endpoints do not exist as nodes is rejected by the store, and the
// batch result carrying that news used to be discarded — a call that wrote nothing returned the
// ids of everything it had been asked to write.
Written int `json:"written"`
// Rejected names the edges the store would not take, so a caller can see which relation had an
// endpoint that was never created rather than discovering later that the graph has no edges.
Rejected []string `json:"rejected,omitempty"`
}
ToolUpsertRelationsResponse summarizes written relation edges.
type ValueSourceKind ¶ added in v2.67.0
type ValueSourceKind string
ValueSourceKind is where a rule gets a value from.
const ( ValueSourceParameter ValueSourceKind = "parameter" ValueSourceObjectProperty ValueSourceKind = "object_property" ValueSourceStatic ValueSourceKind = "static" ValueSourceCurrentUser ValueSourceKind = "current_user" ValueSourceCurrentTime ValueSourceKind = "current_time" )
type VectorDimensionRepairRequest ¶ added in v2.59.0
type VectorDimensionRepairRequest struct {
DryRun *bool `json:"dry_run,omitempty"`
Limit int `json:"limit,omitempty"`
BatchSize int `json:"batch_size,omitempty"`
}
VectorDimensionRepairRequest is the `vector_dimension_repair` MCP tool input.
type VectorDimensionRepairResponse ¶ added in v2.59.0
type VectorDimensionRepairResponse struct {
Report *core.DimensionReport `json:"report"`
Repair *ReembedReport `json:"repair,omitempty"`
}
VectorDimensionRepairResponse pairs the drift report with the repair outcome.
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_delete_entities.go
- graph_list_all.go
- graph_maintenance.go
- graph_runtime.go
- graph_runtime_sql.go
- graphrag.go
- graphrag_helpers.go
- graphrag_tool_defs.go
- graphrag_tool_delete_document.go
- graphrag_tool_find_nodes.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
- memory_list_all.go
- memory_sync.go
- objectset_resolve.go
- objectset_types.go
- ontology_action_apply.go
- ontology_action_types.go
- ontology_api.go
- ontology_compile.go
- ontology_diff.go
- ontology_dispatch.go
- ontology_identity.go
- ontology_interface.go
- ontology_mcp.go
- ontology_normalize.go
- ontology_sdk.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
- reembed.go
- rerank.go
- reranker.go
- retrieval_plan.go
- retrieval_plan_schema.go
- retrieval_plan_types.go
- sql_chunking.go
- text_search.go