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 AsOf(ctx context.Context, at time.Time) context.Context
- func DecisionID(id string) string
- func DefaultDBPath() string
- func EntityNodeID(idOrName string) string
- func KnowledgeMemoryCollectEntities(seed []string, memories []MemorySearchHit, knowledge []KnowledgeSearchHit, ...) []string
- func KnowledgeMemoryThemes(req KnowledgeMemoryReflectRequest, recall KnowledgeMemoryRecallResponse, ...) []string
- func ValidateContract(meta map[string]string) error
- type ActionApplyRequest
- type ActionApplyResponse
- type ActionEdit
- type ActionListRequest
- type ActionListResponse
- type ActionRuleKind
- type ApplyInferenceRequest
- type ApplyInferenceResponse
- type BaseEmbedder
- type Config
- type ContractError
- type ContractTally
- type ContractTallyRequest
- 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) ApplyRules(ctx context.Context, req RulesApplyRequest) (*RulesApplyResponse, error)
- func (db *DB) Backup(ctx context.Context, path string) error
- func (db *DB) Close() error
- func (db *DB) ContractTally(ctx context.Context) (ContractTally, error)
- func (db *DB) ContractTallyTool(ctx context.Context, _ ContractTallyRequest) (ContractTally, error)
- func (db *DB) DecisionChain(ctx context.Context, id string, maxDepth int) (DecisionChain, error)
- func (db *DB) DecisionChainTool(ctx context.Context, req DecisionChainToolRequest) (DecisionChain, error)
- func (db *DB) DecisionsBy(ctx context.Context, actor string, limit int) ([]DecisionRecord, 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) DeleteRules(ctx context.Context, req RulesDeleteRequest) (*RulesDeleteResponse, error)
- func (db *DB) Dialect() sqldialect.Dialect
- func (db *DB) DiffOntologySchema(ctx context.Context, req OntologyDiffRequest) (*OntologyDiffResponse, error)
- func (db *DB) DimensionReport(ctx context.Context) (*core.DimensionReport, error)
- func (db *DB) DraftOntology(ctx context.Context, req OntologyDraftRequest) (*OntologyDraftResponse, error)
- func (db *DB) ExplainInference(ctx context.Context, req InferenceExplainRequest) (*InferenceExplainResponse, 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) FactProvenanceFor(ctx context.Context, edgeID string, withText bool) (*FactProvenance, error)
- func (db *DB) FactProvenanceTool(ctx context.Context, req ToolFactProvenanceRequest) (ToolFactProvenanceResponse, 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) GradedRecords(ctx context.Context, q GradedQuery) ([]GradedRecord, error)
- func (db *DB) Graph() *graph.GraphStore
- func (db *DB) GraphDiff(ctx context.Context, from, to time.Time, opts graph.DiffOptions) (*graph.GraphDiffResult, error)
- func (db *DB) GraphDiffTool(ctx context.Context, req GraphDiffToolRequest) (graph.GraphDiffResult, error)
- func (db *DB) GraphRAGTools() *GraphRAGToolbox
- func (db *DB) GraphSnapshotAt(ctx context.Context, at time.Time, opts SnapshotOptions) (*GraphSnapshot, error)
- func (db *DB) GraphSnapshotTool(ctx context.Context, req GraphSnapshotToolRequest) (GraphSnapshot, error)
- 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) LinkSingleValued(ctx context.Context, linkType string) (single bool, known bool)
- 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) ListRules(ctx context.Context, req RulesListRequest) (*RulesListResponse, error)
- func (db *DB) NeedsAttention(ctx context.Context, limit int) ([]GradedRecord, error)
- func (db *DB) NeedsAttentionTool(ctx context.Context, req NeedsAttentionRequest) (NeedsAttentionResponse, error)
- func (db *DB) NewMCPServer(opts MCPServerOptions) *mcp.Server
- func (db *DB) Precedents(ctx context.Context, q PrecedentsQuery) ([]DecisionRecord, error)
- func (db *DB) PrecedentsTool(ctx context.Context, req DecisionPrecedentsToolRequest) (DecisionPrecedentsToolResponse, error)
- 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) QuerySources() []string
- func (db *DB) Quick() *Quick
- func (db *DB) RecordDecision(ctx context.Context, req DecisionRecordRequest) (DecisionRecord, error)
- func (db *DB) RecordDecisionTool(ctx context.Context, req DecisionRecordToolRequest) (DecisionRecordToolResponse, error)
- 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) SaveRules(ctx context.Context, req RulesSaveRequest) (*RulesSaveResponse, 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) UncitedFacts(ctx context.Context, limit int) ([]FactProvenance, error)
- func (db *DB) UncitedFactsTool(ctx context.Context, req ToolUncitedFactsRequest) (ToolUncitedFactsResponse, 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) VacuumGraph(ctx context.Context, before time.Time, dryRun bool) (*graph.PurgeReport, error)
- func (db *DB) VacuumGraphTool(ctx context.Context, req VacuumGraphToolRequest) (graph.PurgeReport, error)
- func (db *DB) ValidateKnowledgeGraphSHACL(ctx context.Context, req KnowledgeGraphSHACLValidateRequest) (*KnowledgeGraphSHACLValidateResponse, error)
- func (db *DB) Vector() core.Store
- type DBInfo
- type DecisionChain
- type DecisionChainToolRequest
- type DecisionPrecedentsToolRequest
- type DecisionPrecedentsToolResponse
- type DecisionPremise
- type DecisionRecord
- type DecisionRecordRequest
- type DecisionRecordToolRequest
- type DecisionRecordToolResponse
- type Embedder
- type ExtractedRelation
- type FactProvenance
- type GradedQuery
- type GradedRecord
- type GraphDiffToolRequest
- 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) ApplyRules(ctx context.Context, req RulesApplyRequest) (*RulesApplyResponse, 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) DeleteRules(ctx context.Context, req RulesDeleteRequest) (*RulesDeleteResponse, error)
- func (t *GraphRAGToolbox) DiffOntologySchema(ctx context.Context, req OntologyDiffRequest) (*OntologyDiffResponse, error)
- func (t *GraphRAGToolbox) DraftOntology(ctx context.Context, req OntologyDraftRequest) (*OntologyDraftResponse, error)
- func (t *GraphRAGToolbox) ExpandGraph(ctx context.Context, req ToolExpandGraphRequest) (*ToolExpandGraphResponse, error)
- func (t *GraphRAGToolbox) ExplainInference(ctx context.Context, req InferenceExplainRequest) (*InferenceExplainResponse, 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) ListRules(ctx context.Context, req RulesListRequest) (*RulesListResponse, 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) SaveRules(ctx context.Context, req RulesSaveRequest) (*RulesSaveResponse, 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 GraphSnapshot
- type GraphSnapshotToolRequest
- type ImportAgentMemoryOptions
- type ImportAgentMemoryReport
- type InferenceExplainRequest
- type InferenceExplainResponse
- 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 NeedsAttentionRequest
- type NeedsAttentionResponse
- 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 OntologyDraftDecision
- type OntologyDraftLinkFinding
- type OntologyDraftReport
- type OntologyDraftRequest
- type OntologyDraftResponse
- type OntologyDraftRule
- type OntologyDraftSource
- type OntologyDraftTypeFinding
- 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 PrecedentsQuery
- type PredicateOp
- type QueryCondition
- type QueryFieldBoost
- type QueryFilter
- type QueryNumericBoost
- type QueryPrefetch
- type QueryRequest
- type QueryResponse
- type QueryResult
- type QueryScoreFormula
- type QuerySource
- type QuerySourceHit
- type QuerySourceRequest
- 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 RuleDefinition
- type RuleDerivedEdge
- type RulesApplyRequest
- type RulesApplyResponse
- type RulesDeleteRequest
- type RulesDeleteResponse
- type RulesListRequest
- type RulesListResponse
- type RulesSaveRequest
- type RulesSaveResponse
- type SnapshotOptions
- 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 ToolFactProvenanceRequest
- type ToolFactProvenanceResponse
- 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 ToolUncitedFactsRequest
- type ToolUncitedFactsResponse
- type ToolUpsertEntitiesRequest
- type ToolUpsertEntitiesResponse
- type ToolUpsertRelationsRequest
- type ToolUpsertRelationsResponse
- type VacuumGraphToolRequest
- type ValueSourceKind
- type VectorDimensionRepairRequest
- type VectorDimensionRepairResponse
Examples ¶
Constants ¶
const ( // ContractPrefix separates contract keys from the source's own attributes. ContractPrefix = "_" // KeySource is where the record came from: a URL, a file, a job, an // engagement or database name. Never a DSN, never a path with credentials // in it — this store is shared, and a source string is read by everyone // who can read the record. KeySource = ContractPrefix + "source" // KeyChunk is the chunk index within the source, or -1 when the producer // did not work in chunks (DDL, graph import, a measurement). KeyChunk = ContractPrefix + "chunk" // KeyProducer is how the record was made. Values are the Producer* // constants below. KeyProducer = ContractPrefix + "producer" // KeyGrade is by what kind of thing the record's truth is established. // Values are the Grade* constants below. KeyGrade = ContractPrefix + "grade" // KeyState is the producer's own word for where the record stands, // verbatim. It is displayed as detail and never interpreted across // producers — that is what keeps KeyGrade from flattening anything. KeyState = ContractPrefix + "state" // KeyAt is when the record was produced, RFC 3339: when a measurement was // taken, when a claim was published, when a person asserted. A writer that // has no producer-side time (alchemy stamps none on an extraction, because // its results are content-addressed and a clock would change every // address) writes the moment it put the record on the shelf. That is a // true statement about the record, and _run/_source point back to the job. KeyAt = ContractPrefix + "at" // KeyBy is the named person who asserted this record into the graph. Not // the speaker a report quotes — that is what a claim is about, and it // belongs in the graph as an edge (argus: attributed_to) where it can be // queried; folding it in here would make "who put this here" and "who the // report says said it" one field. KeyBy = ContractPrefix + "by" // KeyWhy is the reason a record is held or refused, in words a person can // act on. A refusal without a reason is noise the reader will delete. KeyWhy = ContractPrefix + "why" // KeyContradicts is a JSON array of record ids this record cannot // both-be-true with. Written on both records by whoever detects it. The // disagreement is information, not an error, and both records stay. KeyContradicts = ContractPrefix + "contradicts" // KeyConfidence is an extraction confidence in [0,1]. It is never a // substitute for KeyGrade: a model's confidence in its own output is not // evidence about the world. KeyConfidence = ContractPrefix + "confidence" )
const ( ProducerDDL = "ddl" ProducerGraphImport = "graph-import" ProducerTabular = "tabular" ProducerLLMExtract = "llm-extract" ProducerHuman = "human" // ProducerMeasured is a value obtained by running a governed query against // a system of record. The value itself does not travel — see the hard rule // in the spec — only the judgement about it does. ProducerMeasured = "measured" // ProducerCompiled is derived deterministically from a declared model: a // metric definition, a schema. ProducerCompiled = "compiled" )
Producer values. The first five are the strings alchemy's Producer type already puts on the wire (pkg/alchemy/types.go: "ddl", "graph-import", …) and its CortexDB connector already writes under _producer — not the proto enum names, which never leave the RPC layer. The contract ratifies what is written, so a record alchemy stored last month validates today. Two more for a producer whose output is a governed number rather than an extraction.
const ( // GradeVerified: established by something outside the producer — a // re-measurement, an external published figure, a named person's review. GradeVerified = "verified" // GradeSelfConsistent: internal coherence only. Derived deterministically // from something already stated; not checked against the world. GradeSelfConsistent = "self_consistent" // GradeAsserted: a source or a model said so and nothing has checked it. // Every claim is asserted by construction, and stays so after review — // reviewing a claim confirms the outlet said it, not that it is true. GradeAsserted = "asserted" // GradeHeld: nothing yet; a person has to look. Requires KeyWhy. GradeHeld = "held" // GradeRefused: the producer declined to produce it and can say why. // Requires KeyWhy. A refusal is a record, not an absence — the reader must // be able to tell "we have no precedent" from "we refused to form one". GradeRefused = "refused" )
Grade values: by what kind of thing a record's truth is established.
Five, and deliberately not a ladder that the producers' own verdicts map onto one-to-one. di-consult's Met/Short/Missed are outcomes of an acceptance; di-anchor's Anchored/Ambiguous are how a figure was pinned; alchemy's confidence-plus-review is about an extraction. One axis for all three would flatten exactly the distinctions each of them documents at length. So Grade answers one narrow question and the finer word goes in KeyState untouched.
const ( // DecisionEdgeBasedOn points at a premise: the node or fact the decision // rested on. For a fact (an edge) the target is the fact's subject node // and the edge names the fact in premise_edge_id — see the file comment. DecisionEdgeBasedOn = "based_on" // DecisionEdgeAbout points at what the decision was about. DecisionEdgeAbout = "about" // DecisionEdgeSupersedes points at the decision this one replaces. DecisionEdgeSupersedes = "supersedes" )
The three edge types a decision writes.
const ( // DecisionKindLoad: data was taken in, or refused. "we loaded the March // extract", "we declined this feed". DecisionKindLoad = "load" // DecisionKindReview: a person looked at something and passed judgement. DecisionKindReview = "review" // DecisionKindAction: something was done in the world. DecisionKindAction = "action" // DecisionKindAssert: a claim was adopted as the house position. DecisionKindAssert = "assert" )
The kinds the product uses. The vocabulary is open — a caller may write its own word and everything here still works — but these four are what the ledger was built for, and a caller that uses them gets precedents that line up with everybody else's.
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 ( // OntologyBucketDomain is a candidate object type: something in the world. OntologyBucketDomain = "domain" // OntologyBucketBookkeeping is a record kind: a unit of storage the system // writes about its own contents. OntologyBucketBookkeeping = "bookkeeping" // OntologyBucketUnclassified is a type that says nothing — the extraction // fallback, or no type at all. On a real brain this is the headline // finding rather than a type. OntologyBucketUnclassified = "unclassified" )
The three buckets a node type can land in. They are never merged by the machine, because collapsing them is exactly the mistake: `entity` is not a small type, it is the absence of one, and `memory` is not a rare entity, it is a record. Both would look like ordinary object types after a merge, and the finding — that most of this store is unclassified — would be gone.
const ( // OntologyDraftRuleOverride is the caller's own decision, recorded as // such so a report never presents a person's judgement as its own. OntologyDraftRuleOverride = "override:caller" // OntologyDraftRuleUntyped is a node with no type at all. OntologyDraftRuleUntyped = "unclassified:untyped" // OntologyDraftRuleFallbackType is a type name that means "nothing was // given" — the word a writer stamps when it recognised nothing. OntologyDraftRuleFallbackType = "unclassified:fallback-type" // OntologyDraftRuleWriterStamped is a record kind this library's own // storage writers stamp. OntologyDraftRuleWriterStamped = "bookkeeping:writer-stamped" // OntologyDraftRuleRecordShaped is a record kind nobody listed, recognised // by the shape a record has in a graph. OntologyDraftRuleRecordShaped = "bookkeeping:record-shaped" // OntologyDraftRuleProvenanceAttachment is an edge from a record to what // it holds, rather than between two things. OntologyDraftRuleProvenanceAttachment = "provenance:record-attachment" // OntologyDraftRuleCoOccurrence is an edge that reports two things having // been seen together — a statistic about the corpus. OntologyDraftRuleCoOccurrence = "provenance:co-occurrence" // OntologyDraftRuleFallbackEdge is the relation-side counterpart of // OntologyDraftRuleFallbackType. OntologyDraftRuleFallbackEdge = "provenance:fallback-type" // OntologyDraftRuleRemainder is what is left when no exclusion fired. It // is a rule and not a default: "nothing said otherwise" is the reasoning, // and a reader is entitled to see it stated. OntologyDraftRuleRemainder = "domain:remainder" // The withholding rules. A type these fire on keeps its bucket — the // verdict about what it is stands — and stays out of the schema, because // the schema cannot express it until somebody decides something. OntologyDraftRuleSpellingCollision = "withheld:spelling-collision" OntologyDraftRuleNotAnAPIName = "withheld:not-an-api-name" OntologyDraftRuleBelowThreshold = "withheld:below-threshold" OntologyDraftRuleEndsNotDeclared = "withheld:ends-not-declared" )
The rules. Each is a name a finding can carry and a statement the report repeats, so that a verdict never arrives without the reasoning that produced it. Adding one means adding it to ontologyDraftRulebook below.
const ( OntologyDecisionMerge = "merge_candidate" OntologyDecisionPrimaryKey = "primary_key_guess" OntologyDecisionNoPrimaryKey = "no_primary_key_candidate" OntologyDecisionCardinality = "cardinality_suspicion" OntologyDecisionRename = "rename_required" OntologyDecisionLinkShape = "link_shape_ambiguous" OntologyDecisionOrphanLink = "relation_without_declared_ends" )
The kinds of thing a person has to decide. Every one of them is a question the data cannot answer, which is why they are a list beside the draft rather than a value inside it.
const ( QueryPrefetchVector = "vector" QueryPrefetchLexical = "lexical" QueryPrefetchHybrid = "hybrid" QueryPrefetchGraph = "graph" // QueryPrefetchSource routes a lane to a registered external retrieval // system. See query_source.go — it names candidates, it does not supply them. QueryPrefetchSource = "source" QueryFusionRRF = "rrf" QueryFusionWeightedRRF = "weighted_rrf" QueryFusionDBSF = "dbsf" QueryFilterEqual = "eq" QueryFilterNotEqual = "neq" QueryFilterIn = "in" QueryFilterContains = "contains" QueryFilterGTE = "gte" QueryFilterLTE = "lte" )
const DecisionIDPrefix = "decision:"
DecisionIDPrefix namespaces decision node ids away from entities. Callers may pass an id with or without it; everything returned carries it.
const DecisionNodeType = "Decision"
DecisionNodeType is the node_type every decision carries. A graph view that groups by type shows the ledger without being told about it.
const EntityNodeIDPrefix = "entity:"
EntityNodeIDPrefix is what every entity node's id starts with.
Exported for the same reason as EntityNodeID: the namespacing is otherwise an internal detail, and a consumer that wants "the entity nodes" — to pass as graph.NodeLabelQuery.IDPrefix, say — would have to hardcode the convention and go stale silently if it ever changed.
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 ( // OntologyDraftFallbackNodeTypes are the words a writer stamps when it // recognised nothing. `entity` is not a guess: it is the literal default // this package's own write path applies. // // Deliberately short. Every entry here silently removes a type from the // draft, so a word that is generic in English and specific in somebody's // domain does not belong: `node` was in this list until a real brain // showed four cluster nodes and two Nodes being filed as "we recognised // nothing". A word earns a place here by meaning nothing anywhere. OntologyDraftFallbackNodeTypes = []string{"entity", "unknown", "untyped", "thing", "other", "misc", "unspecified"} // OntologyDraftFallbackEdgeTypes is the same on the relation side, where // `related_to` is this package's literal default. OntologyDraftFallbackEdgeTypes = []string{"related_to", "relatesto", "related", "linked_to", "links_to", "unknown", "unspecified"} // OntologyDraftRecordNodeTypes are the record kinds CortexDB's own writers // stamp — grep NodeType: through pkg/ and this is what comes back. A store // whose records are called something else is caught by the shape rule // instead, and a caller who disagrees overrules either. OntologyDraftRecordNodeTypes = []string{"chunk", "document", "memory", "message", "conversation", "session", "transcript", "summary", "episode", "record"} // OntologyDraftCoOccurrenceEdgeTypes name a statistic rather than an // assertion: that two things turned up in the same place. OntologyDraftCoOccurrenceEdgeTypes = []string{"co_occurs", "co_occurred", "co_occurrence", "cooccurs", "appears_with", "seen_with", "similar_to", "near"} )
The vocabularies the naming rules match against, exported so a caller can read what the deriver believes before trusting what it says. Matching is on the folded name (lower case, separators removed), so `co_occurs`, `coOccurs` and `CO_OCCURS` are one entry rather than three.
var ErrBackupUnsupported = errors.New("cortexdb: backend does not support in-process backup")
ErrBackupUnsupported is returned when the backend behind this DB cannot copy itself. It is a sentinel so callers can tell "this brain does not do backups" apart from "the backup failed" — the first is a fact about the deployment and wants a different answer from the operator than a retry.
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 AsOf ¶ added in v2.99.0
AsOf returns a context whose graph reads answer as the store stood at that instant.
Re-exported from pkg/graph so the ordinary caller — which holds a *DB and never imports the graph package — can reach it:
past := cortexdb.AsOf(ctx, before) nodes, err := db.Graph().ListNodes(past, nil) prov, err := db.FactProvenanceFor(past, edgeID, true)
It is a context value and not an argument on purpose; pkg/graph's ReadOptions says why. The one rule a caller has to keep is that it is a *read* setting: every write refuses a context carrying one rather than writing at the wrong moment.
func DecisionID ¶ added in v2.98.0
DecisionID normalizes a decision id to its prefixed form, so a caller may hold either the bare id it minted or the node id it read back.
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
func ValidateContract ¶ added in v2.93.0
ValidateContract checks a record's metadata against the knowledge contract.
It returns nil when the record carries what it must, or a *ContractError naming each problem. It does not reject keys it does not know: everything outside the `_` prefix is the source's own attribute, and contract keys it does not validate (alchemy's _model, _ontology, …) are passed through.
The server does not call this. A producer does, before it writes; the store keeps what it is given. Enforcement at the door is a later decision, once the producers write conformant records and the rejections are known.
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"`
// UnchangedEdgeIDs are edges these rules re-derived that the same rule had
// already written. Reported rather than rewritten, so a second run of the
// same rules is a no-op that says so instead of a run that looks empty.
UnchangedEdgeIDs []string `json:"unchanged_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 ContractError ¶ added in v2.93.0
type ContractError struct {
Problems []string
}
ContractError lists every way a metadata map fails the contract, so a producer fixes them in one pass rather than one per write attempt.
func (*ContractError) Error ¶ added in v2.93.0
func (e *ContractError) Error() string
type ContractTally ¶ added in v2.93.0
type ContractTally struct {
Verified graph.PropertyCount `json:"verified"`
SelfConsistent graph.PropertyCount `json:"self_consistent"`
Asserted graph.PropertyCount `json:"asserted"`
Held graph.PropertyCount `json:"held"`
Refused graph.PropertyCount `json:"refused"`
Untagged graph.PropertyCount `json:"untagged"`
Unknown map[string]graph.PropertyCount `json:"unknown,omitempty"`
}
ContractTally is how much of the shelf stands on what.
The five graded fields are the contract's closed set. The two that are not are the point of the type:
- Untagged is every record carrying no _grade at all. On a shelf that predates the contract, or that one producer writes and another does not, this is the largest number in the result, and a five-bar chart drawn without it describes 3% of the data while looking like all of it.
- Unknown is every _grade this build does not recognise. A value here means a producer is writing something the contract does not define — a typo, a newer contract, or a vocabulary somebody invented. Silently folding those into Untagged would hide the one case a maintainer has to act on.
type ContractTallyRequest ¶ added in v2.93.0
type ContractTallyRequest struct{}
ContractTallyRequest takes nothing: the tally is over the whole store, and narrowing it to a collection would answer a different question than the one a reader opens with ("what is on this shelf").
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) ApplyRules ¶ added in v2.98.0
func (db *DB) ApplyRules(ctx context.Context, req RulesApplyRequest) (*RulesApplyResponse, error)
ApplyRules forward-chains rules over the graph to a fixpoint and writes what they derive, with the provenance inference_explain reads back.
func (*DB) Backup ¶ added in v2.91.0
Backup writes a consistent copy of the whole brain — vectors, documents, memory, graph, and every sibling package's tables, since they all live in the one database — to path, while the DB stays open and writable.
path must not already exist; the backend refuses to overwrite a backup.
Whether this works at all depends on the backend, which is why core.Backupper is an optional interface rather than part of BrainStore: SQLite can snapshot itself into a file, PostgreSQL is backed up by pg_dump and the operations team that runs it. When the backend cannot, the error wraps ErrBackupUnsupported and names the backend, so the message tells an operator what to do instead of only that they cannot do this.
func (*DB) ContractTally ¶ added in v2.93.0
func (db *DB) ContractTally(ctx context.Context) (ContractTally, error)
ContractTally counts every node and edge by its _grade.
func (*DB) ContractTallyTool ¶ added in v2.93.0
func (db *DB) ContractTallyTool(ctx context.Context, _ ContractTallyRequest) (ContractTally, error)
ContractTallyTool answers contract_tally.
func (*DB) DecisionChain ¶ added in v2.98.0
DecisionChain walks back from a decision to what it rested on.
It follows two kinds of link and nothing else: supersedes, because the decision this one replaced is part of why it was made, and premises that are themselves decisions, because that is how a chain of reasoning is recorded. Premises that are facts are reported on each decision with their contract grade and source — the chain carries how sure, not just what — but they are leaves: walking into a fact's own provenance is what fact_provenance is for and folding it in here would make one call answer two questions badly.
Cycles terminate. A ledger should not contain one, but a graph anybody can write into eventually does — two decisions superseding each other after a merge, most plausibly — and a walk that hangs on it is a worse failure than any wrong answer.
func (*DB) DecisionChainTool ¶ added in v2.98.0
func (db *DB) DecisionChainTool(ctx context.Context, req DecisionChainToolRequest) (DecisionChain, error)
DecisionChainTool answers decision_chain.
func (*DB) DecisionsBy ¶ added in v2.98.0
DecisionsBy lists what one actor decided, newest first.
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) DeleteRules ¶ added in v2.98.0
func (db *DB) DeleteRules(ctx context.Context, req RulesDeleteRequest) (*RulesDeleteResponse, error)
DeleteRules removes stored rules. The edges they derived stay: deleting a rule says what will not be derived next time, not that what was derived was wrong.
func (*DB) Dialect ¶ added in v2.82.0
func (db *DB) Dialect() sqldialect.Dialect
Dialect names the SQL this DB speaks, for the sibling packages that build their own queries against SQL().
Decided by the DSN at Open. Queries written against it were already correct when this always answered SQLite, which is the point of having had the seam before there was anything on the other side of it.
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) DraftOntology ¶ added in v2.94.0
func (db *DB) DraftOntology(ctx context.Context, req OntologyDraftRequest) (*OntologyDraftResponse, error)
DraftOntology reads the graph and proposes a first schema for it, with the reasoning and the open questions beside it.
It writes nothing. The result goes to a person, who saves it — or a corrected version of it — through ontology_save.
func (*DB) ExplainInference ¶ added in v2.98.0
func (db *DB) ExplainInference(ctx context.Context, req InferenceExplainRequest) (*InferenceExplainResponse, error)
ExplainInference returns the derivation of one edge: whether it was inferred, by which rule, and the premise edges under it, each explained in turn.
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) FactProvenanceFor ¶ added in v2.82.0
func (db *DB) FactProvenanceFor(ctx context.Context, edgeID string, withText bool) (*FactProvenance, error)
FactProvenanceFor returns where an edge came from, optionally loading the supporting text.
withText is a parameter rather than always-on because the two questions have different costs: "is this cited at all" is one row, and "show me the words" is a second query plus the chunk bodies.
func (*DB) FactProvenanceTool ¶ added in v2.82.0
func (db *DB) FactProvenanceTool(ctx context.Context, req ToolFactProvenanceRequest) (ToolFactProvenanceResponse, error)
FactProvenanceTool serves the MCP tool of the same name.
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) GradedRecords ¶ added in v2.93.0
func (db *DB) GradedRecords(ctx context.Context, q GradedQuery) ([]GradedRecord, error)
GradedRecords lists records by grade, with the keys a reader needs to say why it is showing them.
func (*DB) GraphDiff ¶ added in v2.99.0
func (db *DB) GraphDiff(ctx context.Context, from, to time.Time, opts graph.DiffOptions) (*graph.GraphDiffResult, error)
GraphDiff reports what changed between two instants. See graph.GraphStore.GraphDiff; this is the facade's spelling of it, so a caller holding a *DB does not have to reach through Graph().
func (*DB) GraphDiffTool ¶ added in v2.99.0
func (db *DB) GraphDiffTool(ctx context.Context, req GraphDiffToolRequest) (graph.GraphDiffResult, error)
GraphDiffTool answers graph_diff.
`to` defaults to now because the overwhelmingly common ask is "what has changed since", and making the caller name the current instant would be an invitation to name it slightly wrong.
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) GraphSnapshotAt ¶ added in v2.99.0
func (db *DB) GraphSnapshotAt(ctx context.Context, at time.Time, opts SnapshotOptions) (*GraphSnapshot, error)
GraphSnapshotAt counts the graph as it stood at an instant, optionally listing some of it.
The counts come from the same as-of machinery every other past read uses, so a snapshot and a GetNode at the same instant can never disagree about whether something was there.
func (*DB) GraphSnapshotTool ¶ added in v2.99.0
func (db *DB) GraphSnapshotTool(ctx context.Context, req GraphSnapshotToolRequest) (GraphSnapshot, error)
GraphSnapshotTool answers graph_snapshot.
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) LinkSingleValued ¶ added in v2.82.0
LinkSingleValued reports whether a link type reaches at most one object from its subject, and whether the ontology had an opinion at all.
known is false when there is no active schema, or the schema does not describe this link type. Callers must treat that as "do not assume": closing a fact that was not actually contradicted destroys history, and unlike a wrong search result nothing afterwards reveals it.
The subject's object type is not resolved, so the rule is structural: a link with one ONE side and one MANY side is single-valued from the ONE side, which is the side a fact is written from in every case this serves — Person lives_in City, Person works_at Company. A link that is MANY on both sides (Person knows Person) is never single-valued, which is the case that matters most to get right, because that is the one where closing an old fact would be silent data loss.
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 edges that only wire chunks. 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) ListRules ¶ added in v2.98.0
func (db *DB) ListRules(ctx context.Context, req RulesListRequest) (*RulesListResponse, error)
ListRules returns the declared rules in id order.
func (*DB) NeedsAttention ¶ added in v2.93.0
NeedsAttention is everything held or refused, with its reason.
It is a named call rather than a GradedQuery a caller assembles because it is the one question the contract exists to make answerable, and because the two grades belong together: held is "nobody has looked yet" and refused is "somebody looked and said no", and a reader working through a shelf wants both in one list, told apart by Grade. Splitting them into two calls makes it likely that only one gets rendered.
Every record here carries a Why — ValidateContract requires it for both grades — so a caller can show what to do about each one rather than only that something is wrong.
func (*DB) NeedsAttentionTool ¶ added in v2.93.0
func (db *DB) NeedsAttentionTool(ctx context.Context, req NeedsAttentionRequest) (NeedsAttentionResponse, error)
NeedsAttentionTool answers contract_needs_attention.
It asks for one more record than the caller wanted, which is how it knows it truncated without a second count over the same predicate — and then reports the true total from the tally, because "50 shown of 50" and "50 shown of 900" are different situations and the cap alone cannot tell them apart.
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) Precedents ¶ added in v2.98.0
func (db *DB) Precedents(ctx context.Context, q PrecedentsQuery) ([]DecisionRecord, error)
Precedents lists earlier decisions of the same kind, or about the same subject, newest first.
Both empty is refused rather than meaning "the whole ledger": a caller asking for every decision anybody ever made is not asking about a precedent, and on a shared brain that is other people's ledger.
func (*DB) PrecedentsTool ¶ added in v2.98.0
func (db *DB) PrecedentsTool(ctx context.Context, req DecisionPrecedentsToolRequest) (DecisionPrecedentsToolResponse, error)
PrecedentsTool answers decision_precedents.
It asks for one more than the caller wanted, which is how it reports that it truncated without a second query — the same trick NeedsAttentionTool uses, and for the same reason: a capped list that does not say it is capped reads as the whole answer.
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) QuerySources ¶ added in v2.91.0
QuerySources lists the registered lanes, sorted. Useful in a health endpoint, and in the error a misnamed prefetch produces.
func (*DB) RecordDecision ¶ added in v2.98.0
func (db *DB) RecordDecision(ctx context.Context, req DecisionRecordRequest) (DecisionRecord, error)
RecordDecision writes a decision and the edges that explain it.
It fails closed and it fails before writing anything: an empty actor, an empty note, a premise that does not exist, a subject that does not exist, a supersedes target that is not a decision, or metadata the knowledge contract refuses. The order matters — every check runs against the store before the node is upserted — because a decision that half-wrote leaves a ledger entry with fewer premises than the caller believes it has, and nothing downstream can tell that from a decision that genuinely rested on less.
func (*DB) RecordDecisionTool ¶ added in v2.98.0
func (db *DB) RecordDecisionTool(ctx context.Context, req DecisionRecordToolRequest) (DecisionRecordToolResponse, error)
RecordDecisionTool answers decision_record.
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) SaveRules ¶ added in v2.98.0
func (db *DB) SaveRules(ctx context.Context, req RulesSaveRequest) (*RulesSaveResponse, error)
SaveRules stores rules under their ids.
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) UncitedFacts ¶ added in v2.82.0
UncitedFacts lists edges that cannot say where they came from.
The single lookup above answers "says who?" for one fact. This is the question a knowledge base has to be able to ask about itself: how much of what I am about to tell someone is backed by anything?
An edge counts as cited when it carries supporting chunks, a document, or — for a derived fact — the rule that derived it. Nothing else is required: this reports what is missing, it does not judge whether the citation is any good. Checking that the text still says what the fact says needs the text, which is what FactProvenanceFor is for.
func (*DB) UncitedFactsTool ¶ added in v2.82.0
func (db *DB) UncitedFactsTool(ctx context.Context, req ToolUncitedFactsRequest) (ToolUncitedFactsResponse, error)
UncitedFactsTool serves the MCP tool of the same name.
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) VacuumGraph ¶ added in v2.99.0
func (db *DB) VacuumGraph(ctx context.Context, before time.Time, dryRun bool) (*graph.PurgeReport, error)
VacuumGraph physically removes graph history that closed before a cutoff.
The only hard delete in the temporal machinery, and the reason everything else can keep the record: retraction and versioning both trade storage for the ability to answer "what did we believe then", and an operator has to be able to decide how far back that is worth paying for.
func (*DB) VacuumGraphTool ¶ added in v2.99.0
func (db *DB) VacuumGraphTool(ctx context.Context, req VacuumGraphToolRequest) (graph.PurgeReport, error)
VacuumGraphTool answers vacuum_graph.
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 DecisionChain ¶ added in v2.98.0
type DecisionChain struct {
// Root is the decision that was asked about, normalized to its node id.
Root string `json:"root"`
// Decisions is the root first, then every decision reachable from it
// through supersedes and through premises that are themselves decisions,
// in the order the walk found them — breadth first, so the ones nearest
// the root come first and a truncated chain is truncated at the far end.
Decisions []DecisionRecord `json:"decisions"`
// Depth is how many hops the walk actually took.
Depth int `json:"depth"`
// Truncated says the depth bound stopped the walk with decisions still
// unvisited. A chain that quietly stopped reads as a complete account of
// why something was done, which is the one thing it must never do.
Truncated bool `json:"truncated,omitempty"`
}
DecisionChain is a decision and everything it stands on.
type DecisionChainToolRequest ¶ added in v2.98.0
type DecisionChainToolRequest struct {
ID string `json:"id"`
MaxDepth int `json:"max_depth,omitempty"`
}
DecisionChainToolRequest asks why one decision was made.
type DecisionPrecedentsToolRequest ¶ added in v2.98.0
type DecisionPrecedentsToolRequest struct {
Kind string `json:"kind,omitempty"`
Subject string `json:"subject,omitempty"`
Exclude string `json:"exclude,omitempty"`
Limit int `json:"limit,omitempty"`
}
DecisionPrecedentsToolRequest asks what was decided this way before.
type DecisionPrecedentsToolResponse ¶ added in v2.98.0
type DecisionPrecedentsToolResponse struct {
Decisions []DecisionRecord `json:"decisions"`
Count int `json:"count"`
// Truncated says the limit cut the list short, so "3 precedents" is never
// mistaken for "only 3 precedents".
Truncated bool `json:"truncated,omitempty"`
}
DecisionPrecedentsToolResponse lists them, newest first.
type DecisionPremise ¶ added in v2.98.0
type DecisionPremise struct {
// ID is the node or edge id, as the caller gave it.
ID string `json:"id"`
// Edge says the premise is a fact — a relation — rather than a thing.
Edge bool `json:"edge,omitempty"`
// Type is node_type or edge_type.
Type string `json:"type,omitempty"`
// Content is a node's label; edges have none.
Content string `json:"content,omitempty"`
// From and To are a fact's ends.
From string `json:"from,omitempty"`
To string `json:"to,omitempty"`
// Decision says this premise is itself a decision, which is what makes the
// chain recurse.
Decision bool `json:"decision,omitempty"`
// Grade and Source are the premise's own contract keys. Empty means the
// record carries none — which is an answer, and a different one from
// "asserted".
Grade string `json:"grade,omitempty"`
Source string `json:"source,omitempty"`
// Missing says the premise was recorded and has since been deleted. It
// cannot happen at write time — RecordDecision refuses an unknown premise
// — so it means the shelf changed under a decision that already stands,
// which is exactly what a reader has to be told rather than shown a gap.
Missing bool `json:"missing,omitempty"`
}
DecisionPremise is one thing a decision rested on, with how sure that thing was. The grade is the point: a chain that lists its premises without saying how well established each one is looks like evidence and is not.
type DecisionRecord ¶ added in v2.98.0
type DecisionRecord struct {
ID string `json:"id"`
Kind string `json:"kind,omitempty"`
Actor string `json:"actor,omitempty"`
At string `json:"at,omitempty"`
Verdict string `json:"verdict,omitempty"`
Subject string `json:"subject,omitempty"`
Note string `json:"note,omitempty"`
Grade string `json:"grade,omitempty"`
Source string `json:"source,omitempty"`
Producer string `json:"producer,omitempty"`
State string `json:"state,omitempty"`
Why string `json:"why,omitempty"`
Premises []DecisionPremise `json:"premises,omitempty"`
// Supersedes is what this decision replaced. A list rather than a single
// id because a decision that consolidates three earlier ones is ordinary,
// and a field that could only hold one would make the ledger lie by
// arithmetic.
Supersedes []string `json:"supersedes,omitempty"`
}
DecisionRecord is one ledger entry read back.
type DecisionRecordRequest ¶ added in v2.98.0
type DecisionRecordRequest struct {
// ID names the decision. Empty mints one from the actor, the note and the
// moment. Given, it makes the write idempotent, which is what lets a
// caller replay a transcript without doubling its ledger.
ID string `json:"id,omitempty"`
// Kind is the shape of the decision: load, review, action, assert, or a
// word of the caller's own. Precedents groups by it.
Kind string `json:"kind,omitempty"`
// Actor is who decided. Required: a decision nobody made is a note.
Actor string `json:"actor"`
// Note is the decision in words. Required, for the same reason a refusal
// needs a why — a ledger entry a reader cannot act on is noise.
Note string `json:"note"`
// Verdict is the outcome in the caller's own word: "hold", "ship",
// "rejected". Never interpreted here, for the reason KeyState is not.
Verdict string `json:"verdict,omitempty"`
// Subject is the node the decision was about. It must exist.
Subject string `json:"subject,omitempty"`
// Premises are the node ids and edge ids the decision rested on. Every one
// must exist: a decision resting on a fact that does not exist is not a
// decision, and accepting it would produce a chain that reads as evidence
// while pointing at nothing.
Premises []string `json:"premises,omitempty"`
// Supersedes is the decision this one replaces. It must exist, and it must
// be a decision.
Supersedes string `json:"supersedes,omitempty"`
// At is when it was decided. Zero means now.
At time.Time `json:"at,omitempty"`
// The contract keys a caller may override. The defaults are the case the
// ledger exists for — a named person signing a decision, which is
// established by something outside any producer and so is verified — and
// an agent recording its own decision says so by setting Producer and
// Grade to what is true of it.
Source string `json:"source,omitempty"`
Producer string `json:"producer,omitempty"`
Grade string `json:"grade,omitempty"`
State string `json:"state,omitempty"`
// Why is required by the contract when Grade is held or refused.
Why string `json:"why,omitempty"`
}
DecisionRecordRequest records why something was done.
type DecisionRecordToolRequest ¶ added in v2.98.0
type DecisionRecordToolRequest struct {
ID string `json:"id,omitempty"`
Kind string `json:"kind,omitempty"`
Actor string `json:"actor"`
Note string `json:"note"`
Verdict string `json:"verdict,omitempty"`
Subject string `json:"subject,omitempty"`
Premises []string `json:"premises,omitempty"`
Supersedes string `json:"supersedes,omitempty"`
At string `json:"at,omitempty"`
Source string `json:"source,omitempty"`
Producer string `json:"producer,omitempty"`
Grade string `json:"grade,omitempty"`
State string `json:"state,omitempty"`
Why string `json:"why,omitempty"`
}
DecisionRecordToolRequest records a decision. It is DecisionRecordRequest with the time as a string, because a tool argument arrives as JSON from a model and an RFC 3339 string is what a model writes; the zero value still means now.
type DecisionRecordToolResponse ¶ added in v2.98.0
type DecisionRecordToolResponse struct {
Decision DecisionRecord `json:"decision"`
}
DecisionRecordToolResponse is the entry as it was written.
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 FactProvenance ¶ added in v2.82.0
type FactProvenance struct {
EdgeID string `json:"edge_id"`
From string `json:"from"`
To string `json:"to"`
Type string `json:"type"`
DocumentID string `json:"document_id,omitempty"`
ChunkIDs []string `json:"chunk_ids,omitempty"`
// Inferred says the fact was derived rather than read, in which case Rule
// names the derivation and the chunks below support the premises, not this
// conclusion.
Inferred bool `json:"inferred,omitempty"`
Rule string `json:"rule,omitempty"`
// Source is free-text provenance an ingester attached.
Source string `json:"source,omitempty"`
// Chunks is the supporting text itself, when it was asked for and still
// exists. A chunk id that no longer resolves is reported in Missing rather
// than dropped: a citation pointing at deleted text is exactly the thing
// worth surfacing.
Chunks []ToolChunk `json:"chunks,omitempty"`
Missing []string `json:"missing_chunk_ids,omitempty"`
}
FactProvenance is where one edge came from.
func (FactProvenance) Cited ¶ added in v2.82.0
func (p FactProvenance) Cited() bool
Cited reports whether anything at all backs this fact.
An inferred fact with no supporting chunks is still accounted for — its rule is its account — but a stated fact with neither a document nor a chunk was written by something that did not say where it got it.
type GradedQuery ¶ added in v2.93.0
type GradedQuery struct {
// Grades keeps records whose _grade is any of these. Empty is refused
// rather than meaning "all": a reader asking for everything on a shared
// shelf is asking for other people's records too, and the useful questions
// all name a grade.
Grades []string
// Sources, if set, keeps only records from these _source values.
Sources []string
// Limit caps the rows. 0 means no cap.
Limit int
}
GradedQuery narrows GradedRecords.
type GradedRecord ¶ added in v2.93.0
type GradedRecord struct {
ID string `json:"id"`
Edge bool `json:"edge"`
Type string `json:"type"`
Content string `json:"content,omitempty"`
From string `json:"from,omitempty"`
To string `json:"to,omitempty"`
Grade string `json:"grade"`
State string `json:"state,omitempty"`
Why string `json:"why,omitempty"`
Source string `json:"source,omitempty"`
Producer string `json:"producer,omitempty"`
At string `json:"at,omitempty"`
By string `json:"by,omitempty"`
}
GradedRecord is one record with the contract keys a reader renders.
The contract's other keys (_chunk, _model, _confidence, and whatever a producer adds under the prefix) are deliberately not here: this is what a wall shows and what an agent cites, and a struct that grew a field per key would be a second place to keep the contract in step. A caller wanting the rest has the record id.
type GraphDiffToolRequest ¶ added in v2.99.0
type GraphDiffToolRequest struct {
From string `json:"from"`
To string `json:"to,omitempty"`
NodeTypes []string `json:"node_types,omitempty"`
EdgeTypes []string `json:"edge_types,omitempty"`
Limit int `json:"limit,omitempty"`
Cursor string `json:"cursor,omitempty"`
MaxIntervalPairs int `json:"max_interval_pairs,omitempty"`
}
GraphDiffToolRequest asks what changed between two instants.
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
// VectorScore and LexicalScore are what each retriever thought of this
// chunk, kept because Score is a reciprocal-rank-fusion value that is
// right to order by and wrong to read: at k=60 the top three results
// score 1/61, 1/62 and 1/63 whatever the corpus. VectorRank and
// LexicalRank are the chunk's 1-based position in each list; zero means
// that retriever never returned it, which is not the same as scoring it
// zero. Populated only by hybrid retrieval.
VectorScore float64
LexicalScore float64
VectorRank int
LexicalRank int
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) ApplyRules ¶ added in v2.98.0
func (t *GraphRAGToolbox) ApplyRules(ctx context.Context, req RulesApplyRequest) (*RulesApplyResponse, error)
ApplyRules forward-chains rules 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) DeleteRules ¶ added in v2.98.0
func (t *GraphRAGToolbox) DeleteRules(ctx context.Context, req RulesDeleteRequest) (*RulesDeleteResponse, error)
DeleteRules removes rules through the tool surface.
func (*GraphRAGToolbox) DiffOntologySchema ¶ added in v2.67.0
func (t *GraphRAGToolbox) DiffOntologySchema(ctx context.Context, req OntologyDiffRequest) (*OntologyDiffResponse, error)
func (*GraphRAGToolbox) DraftOntology ¶ added in v2.94.0
func (t *GraphRAGToolbox) DraftOntology(ctx context.Context, req OntologyDraftRequest) (*OntologyDraftResponse, 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) ExplainInference ¶ added in v2.98.0
func (t *GraphRAGToolbox) ExplainInference(ctx context.Context, req InferenceExplainRequest) (*InferenceExplainResponse, error)
ExplainInference explains one edge through the tool surface.
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) ListRules ¶ added in v2.98.0
func (t *GraphRAGToolbox) ListRules(ctx context.Context, req RulesListRequest) (*RulesListResponse, error)
ListRules lists rules through the tool surface.
func (*GraphRAGToolbox) Query ¶ added in v2.27.0
func (t *GraphRAGToolbox) Query(ctx context.Context, req QueryRequest) (*QueryResponse, error)
Query runs the composable CortexDB Query API through the toolbox surface.
func (*GraphRAGToolbox) QueryKnowledgeGraph ¶ added in v2.16.0
func (t *GraphRAGToolbox) QueryKnowledgeGraph(ctx context.Context, req KnowledgeGraphQueryRequest) (*KnowledgeGraphQueryResponse, error)
QueryKnowledgeGraph executes a SPARQL query via the toolbox surface.
func (*GraphRAGToolbox) RefreshKnowledgeGraphInference ¶ added in v2.16.0
func (t *GraphRAGToolbox) RefreshKnowledgeGraphInference(ctx context.Context, req KnowledgeGraphInferenceRefreshRequest) (*KnowledgeGraphInferenceRefreshResponse, error)
RefreshKnowledgeGraphInference recomputes inferred triples via the toolbox surface.
func (*GraphRAGToolbox) 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) SaveRules ¶ added in v2.98.0
func (t *GraphRAGToolbox) SaveRules(ctx context.Context, req RulesSaveRequest) (*RulesSaveResponse, error)
SaveRules stores rules through the tool surface.
func (*GraphRAGToolbox) SearchChunksByEntities ¶ added in v2.11.0
func (t *GraphRAGToolbox) SearchChunksByEntities(ctx context.Context, req ToolSearchChunksByEntitiesRequest) (*ToolSearchChunksByEntitiesResponse, error)
SearchChunksByEntities finds chunks that are linked to the requested entities.
func (*GraphRAGToolbox) SearchGraphRAGLexical ¶ added in v2.11.0
func (t *GraphRAGToolbox) SearchGraphRAGLexical(ctx context.Context, req ToolSearchGraphRAGLexicalRequest) (*GraphRAGQueryResult, error)
SearchGraphRAGLexical performs no-embedder GraphRAG retrieval for external LLM orchestration.
func (*GraphRAGToolbox) SearchKnowledge ¶ added in v2.12.0
func (t *GraphRAGToolbox) SearchKnowledge(ctx context.Context, req KnowledgeSearchRequest) (*KnowledgeSearchResponse, error)
SearchKnowledge searches durable knowledge through the tool surface.
func (*GraphRAGToolbox) SearchMemory ¶ added in v2.12.0
func (t *GraphRAGToolbox) SearchMemory(ctx context.Context, req MemorySearchRequest) (*MemorySearchResponse, error)
SearchMemory searches memory through the tool surface.
func (*GraphRAGToolbox) SearchText ¶ added in v2.11.0
func (t *GraphRAGToolbox) SearchText(ctx context.Context, req ToolSearchTextRequest) (*ToolSearchTextResponse, error)
SearchText runs lexical retrieval over chunk content.
func (*GraphRAGToolbox) SummarizeKnowledgeGraphInference ¶ added in v2.18.0
func (t *GraphRAGToolbox) SummarizeKnowledgeGraphInference(ctx context.Context, req KnowledgeGraphInferenceSummaryRequest) (*KnowledgeGraphInferenceSummaryResponse, error)
SummarizeKnowledgeGraphInference returns persisted inference counts and rule breakdowns via the toolbox surface.
func (*GraphRAGToolbox) UpdateKnowledge ¶ added in v2.12.0
func (t *GraphRAGToolbox) UpdateKnowledge(ctx context.Context, req KnowledgeUpdateRequest) (*KnowledgeSaveResponse, error)
UpdateKnowledge updates a knowledge item through the tool surface.
func (*GraphRAGToolbox) UpdateMemory ¶ added in v2.12.0
func (t *GraphRAGToolbox) UpdateMemory(ctx context.Context, req MemoryUpdateRequest) (*MemorySaveResponse, error)
UpdateMemory updates a memory item through the tool surface.
func (*GraphRAGToolbox) UpsertEntities ¶ added in v2.11.0
func (t *GraphRAGToolbox) UpsertEntities(ctx context.Context, req ToolUpsertEntitiesRequest) (*ToolUpsertEntitiesResponse, error)
UpsertEntities writes entity nodes and mention edges for caller-supplied structured extraction.
func (*GraphRAGToolbox) UpsertKnowledgeGraph ¶ added in v2.16.0
func (t *GraphRAGToolbox) UpsertKnowledgeGraph(ctx context.Context, req KnowledgeGraphUpsertRequest) (*KnowledgeGraphUpsertResponse, error)
UpsertKnowledgeGraph writes triples/quads via the toolbox surface.
func (*GraphRAGToolbox) UpsertKnowledgeNamespace ¶ added in v2.16.0
func (t *GraphRAGToolbox) UpsertKnowledgeNamespace(ctx context.Context, req KnowledgeGraphNamespaceUpsertRequest) (*KnowledgeGraphNamespaceUpsertResponse, error)
UpsertKnowledgeNamespace stores one knowledge-graph namespace via the toolbox surface.
func (*GraphRAGToolbox) UpsertRelations ¶ added in v2.11.0
func (t *GraphRAGToolbox) UpsertRelations(ctx context.Context, req ToolUpsertRelationsRequest) (*ToolUpsertRelationsResponse, error)
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 GraphSnapshot ¶ added in v2.99.0
type GraphSnapshot struct {
AsOf time.Time `json:"as_of"`
Nodes int `json:"nodes"`
Edges int `json:"edges"`
// Orphans is how many of those nodes no edge touched — the same health
// number Connectivity reports for the present, so a caller can watch it
// move rather than only read today's.
Orphans int `json:"orphans"`
// NodeSample and EdgeSample are filled only when the caller asked to see
// rows. A snapshot is a count first: "how big was the graph then" is the
// question, and returning four hundred thousand nodes to answer it is not
// a listing, it is a denial of service on the caller's context window.
NodeSample []graph.NodeVersion `json:"node_sample,omitempty"`
EdgeSample []graph.EdgeVersion `json:"edge_sample,omitempty"`
Truncated bool `json:"truncated,omitempty"`
}
GraphSnapshot is the shape of the graph at one instant.
type GraphSnapshotToolRequest ¶ added in v2.99.0
type GraphSnapshotToolRequest struct {
AsOf string `json:"as_of"`
NodeTypes []string `json:"node_types,omitempty"`
EdgeTypes []string `json:"edge_types,omitempty"`
Sample int `json:"sample,omitempty"`
}
GraphSnapshotToolRequest asks what the graph looked like at an instant.
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 InferenceExplainRequest ¶ added in v2.98.0
type InferenceExplainRequest struct {
EdgeID string `json:"edge_id"`
Depth int `json:"depth,omitempty"`
}
InferenceExplainRequest asks why an edge is in the graph.
type InferenceExplainResponse ¶ added in v2.98.0
type InferenceExplainResponse struct {
Explanation graph.RuleEdgeExplanation `json:"explanation"`
Trace []graph.RuleEdgeTraceEntry `json:"trace,omitempty"`
}
InferenceExplainResponse is the derivation of one edge: the edge itself, and the premise chain under it flattened in preorder.
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"`
// Rank is this hit's 1-based position in Results. Score is a fusion
// value that is right to order by and wrong to read (see
// GraphRAGChunkResult); Rank is what a caller comparing two runs wants.
Rank int `json:"rank"`
// VectorScore and LexicalScore are the best each retriever gave any chunk
// of this document, zero when that retriever did not run or did not
// return it. Populated only by hybrid retrieval.
VectorScore float64 `json:"vector_score,omitempty"`
LexicalScore float64 `json:"lexical_score,omitempty"`
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 NeedsAttentionRequest ¶ added in v2.93.0
type NeedsAttentionRequest struct {
// Limit caps the records returned. 0 uses defaultNeedsAttentionLimit.
Limit int `json:"limit,omitempty"`
}
NeedsAttentionRequest caps the list.
type NeedsAttentionResponse ¶ added in v2.93.0
type NeedsAttentionResponse struct {
Records []GradedRecord `json:"records"`
// Truncated and Total let a capped caller say what it is not showing. A
// list that quietly stopped at fifty reads as "fifty things need a person",
// and the number is the half a reader acts on.
Truncated bool `json:"truncated,omitempty"`
Total int `json:"total"`
}
NeedsAttentionResponse is the work waiting on the shelf.
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 OntologyDraftDecision ¶ added in v2.94.0
type OntologyDraftDecision struct {
Kind string `json:"kind"`
Target string `json:"target"`
// Detail is the question in a sentence; Evidence is what was observed, so
// a person can decide without going back to the graph.
Detail string `json:"detail"`
Evidence string `json:"evidence"`
}
OntologyDraftDecision is one question the data cannot answer.
type OntologyDraftLinkFinding ¶ added in v2.94.0
type OntologyDraftLinkFinding struct {
Type string `json:"type"`
Edges int `json:"edges"`
Included bool `json:"included"`
Rule string `json:"rule"`
Why string `json:"why"`
// Shapes is every (from type, to type, count) this edge type was observed
// in, capped so one promiscuous provenance edge cannot fill the report.
Shapes []graph.EdgeShape `json:"shapes,omitempty"`
// ShapesTotal is how many there were before the cap.
ShapesTotal int `json:"shapes_total,omitempty"`
}
OntologyDraftLinkFinding is the same for one edge type, carrying the shapes the edges actually have — which is the evidence for a link type's two ends, and the only evidence there is.
type OntologyDraftReport ¶ added in v2.94.0
type OntologyDraftReport struct {
Source OntologyDraftSource `json:"source"`
Rules []OntologyDraftRule `json:"rules"`
NodeTypes []OntologyDraftTypeFinding `json:"node_types"`
EdgeTypes []OntologyDraftLinkFinding `json:"edge_types"`
Notes []string `json:"notes"`
}
OntologyDraftReport is the reasoning: what was read, which rule fired on each type, and the rulebook itself.
type OntologyDraftRequest ¶ added in v2.94.0
type OntologyDraftRequest struct {
// SchemaID names the draft. It is not saved under it — nothing here saves
// — but a caller comparing two drafts, or running ontology_diff against a
// stored schema, needs the id to be theirs to choose.
SchemaID string `json:"schema_id,omitempty"`
// MinNodes and MinEdges keep small types out of the *draft*. They never
// keep anything out of the report: a threshold that silently dropped the
// long tail would describe a fraction of the vocabulary while looking like
// all of it.
MinNodes int `json:"min_nodes,omitempty"`
MinEdges int `json:"min_edges,omitempty"`
// DomainTypes and BookkeepingTypes overrule the bucketing for named node
// types. The report says the caller decided, not the deriver.
DomainTypes []string `json:"domain_types,omitempty"`
BookkeepingTypes []string `json:"bookkeeping_types,omitempty"`
}
OntologyDraftRequest asks for a draft. Every field is a way for a person to overrule the deriver rather than to configure it.
type OntologyDraftResponse ¶ added in v2.94.0
type OntologyDraftResponse struct {
Schema OntologySchema `json:"schema"`
Report OntologyDraftReport `json:"report"`
Decisions []OntologyDraftDecision `json:"to_decide"`
}
OntologyDraftResponse is the three things a caller must tell apart.
type OntologyDraftRule ¶ added in v2.94.0
type OntologyDraftRule struct {
Name string `json:"name"`
AppliesTo string `json:"applies_to"`
Statement string `json:"statement"`
}
OntologyDraftRule is one rule, stated. The report carries the whole rulebook beside the verdicts, because "bookkeeping" without a definition of bookkeeping is a verdict asking to be trusted.
type OntologyDraftSource ¶ added in v2.94.0
type OntologyDraftSource struct {
Nodes int `json:"nodes"`
Edges int `json:"edges"`
NodeTypes int `json:"node_types"`
EdgeTypes int `json:"edge_types"`
Buckets map[string]int `json:"buckets"`
PropertyScope string `json:"property_scope"`
DerivedAt time.Time `json:"derived_at"`
}
OntologyDraftSource is what was read, so a reader can tell a small brain from a partial read.
type OntologyDraftTypeFinding ¶ added in v2.94.0
type OntologyDraftTypeFinding struct {
// Type is the spelling in the data. The empty string is the untyped.
Type string `json:"type"`
Nodes int `json:"nodes"`
Bucket string `json:"bucket"`
// Rule is which rule assigned the bucket, and Why is what it saw.
Rule string `json:"rule"`
Why string `json:"why"`
// APIName is what the draft calls it, empty when the draft is silent
// about it.
APIName string `json:"api_name,omitempty"`
// Withheld says why a domain type is nonetheless absent from the draft.
// It is not a re-bucketing: the verdict about what the type *is* stands,
// and the schema simply cannot express it until somebody decides
// something.
Withheld string `json:"withheld,omitempty"`
// SkippedProperties are property keys on this type's records that cannot
// be API names. Reported rather than rewritten: renaming somebody's field
// is a decision.
SkippedProperties []string `json:"skipped_properties,omitempty"`
}
OntologyDraftTypeFinding is what the deriver concluded about one node type, with the counts it concluded it from.
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 WithQuerySource ¶ added in v2.91.0
func WithQuerySource(src QuerySource) Option
WithQuerySource registers an external retrieval lane under its own name. Registering the same name twice replaces the earlier one, which is what a caller reconfiguring a client means by it.
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 PrecedentsQuery ¶ added in v2.98.0
type PrecedentsQuery struct {
// Kind narrows to decisions of the same shape.
Kind string `json:"kind,omitempty"`
// Subject narrows to decisions about the same node.
Subject string `json:"subject,omitempty"`
// Exclude leaves one decision out — the one being decided now, whose own
// entry is not a precedent for itself.
Exclude string `json:"exclude,omitempty"`
// Limit caps the rows. 0 takes defaultPrecedentsLimit.
Limit int `json:"limit,omitempty"`
}
PrecedentsQuery asks what was decided this way before.
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"`
// Source names the registered QuerySource for a Kind of "source".
Source string `json:"source,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 QuerySource ¶ added in v2.91.0
type QuerySource interface {
// Name identifies the lane. It is what a prefetch asks for, and what
// appears in SourceRanks/SourceScores on every result the lane voted for.
Name() string
// Search returns candidates best-first. Returning an error fails the
// query: a lane that vanishes quietly would change what retrieval means
// without saying so.
Search(ctx context.Context, req QuerySourceRequest) ([]QuerySourceHit, error)
}
QuerySource is an external retrieval lane.
Implementations live outside this package — CortexDB depends on no search SDK, the same way it depends on no LLM SDK. examples/17_query_source has one written against Meilisearch's HTTP API with nothing but net/http.
type QuerySourceHit ¶ added in v2.91.0
QuerySourceHit is one candidate: an id this brain should look at, and the score the external system gave it. Scores are only compared within a lane — fusion ranks them, so a Meilisearch relevance and a cosine similarity never have to mean the same thing.
type QuerySourceRequest ¶ added in v2.91.0
type QuerySourceRequest struct {
Query string `json:"query,omitempty"`
Collection string `json:"collection,omitempty"`
Limit int `json:"limit,omitempty"`
Keywords []string `json:"keywords,omitempty"`
AlternateQueries []string `json:"alternate_queries,omitempty"`
}
QuerySourceRequest is what a lane is asked. It carries the same query material the lexical lane gets, so a source that can use keywords or alternate phrasings is not forced to re-derive them.
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 RuleDefinition ¶ added in v2.98.0
type RuleDefinition struct {
ID string `json:"id"`
Name string `json:"name,omitempty"`
Text string `json:"text,omitempty"`
// When and Then are the structured form. Ignored when Text is set.
When []graph.Atom `json:"when,omitempty"`
Then *graph.Atom `json:"then,omitempty"`
// Confidence multiplies into every derived edge's confidence. Zero is 1.0.
Confidence float64 `json:"confidence,omitempty"`
// Weight overrides the derived edge weight. Zero means the mean of the
// premise weights.
Weight float64 `json:"weight,omitempty"`
Note string `json:"note,omitempty"`
Metadata map[string]string `json:"metadata,omitempty"`
// Enabled defaults to true on save. A disabled rule stays in the table and
// out of rules_apply's default set.
Enabled *bool `json:"enabled,omitempty"`
}
RuleDefinition is a rule as a caller supplies it.
Two ways in, one rule: Text is the written form ("IF p(?x, ?y) AND q(?y, ?z) THEN r(?x, ?z)"), When/Then the structured form a program builds. Supplying Text is what a person does; supplying both is an error rather than a silent preference, because the two disagreeing is exactly the confusion this would otherwise create.
type RuleDerivedEdge ¶ added in v2.98.0
type RuleDerivedEdge struct {
EdgeID string `json:"edge_id"`
FromNodeID string `json:"from_node_id"`
ToNodeID string `json:"to_node_id"`
EdgeType string `json:"edge_type"`
Weight float64 `json:"weight,omitempty"`
Confidence float64 `json:"confidence,omitempty"`
RuleID string `json:"rule_id,omitempty"`
RuleText string `json:"rule_text,omitempty"`
SupportEdgeIDs []string `json:"support_edge_ids,omitempty"`
}
RuleDerivedEdge is one derived edge with the provenance it carries.
type RulesApplyRequest ¶ added in v2.98.0
type RulesApplyRequest struct {
// RuleIDs selects stored rules. Rules supplies ad-hoc ones that are not
// saved. With neither, every enabled stored rule runs.
RuleIDs []string `json:"rule_ids,omitempty"`
Rules []RuleDefinition `json:"rules,omitempty"`
// DocumentID scopes which edges take part and is stamped onto what is
// derived.
DocumentID string `json:"document_id,omitempty"`
// DryRun reports what would be derived and writes nothing.
DryRun bool `json:"dry_run,omitempty"`
// DeleteExisting removes the edges these rules derived before rerunning.
DeleteExisting bool `json:"delete_existing,omitempty"`
MaxIterations int `json:"max_iterations,omitempty"`
MaxDerived int `json:"max_derived,omitempty"`
}
RulesApplyRequest forward-chains rules over the graph.
type RulesApplyResponse ¶ added in v2.98.0
type RulesApplyResponse struct {
RuleIDs []string `json:"rule_ids"`
Iterations int `json:"iterations"`
CandidateEdges int `json:"candidate_edges"`
CreatedEdgeIDs []string `json:"created_edge_ids,omitempty"`
UnchangedEdgeIDs []string `json:"unchanged_edge_ids,omitempty"`
DeletedEdgeIDs []string `json:"deleted_edge_ids,omitempty"`
Edges []RuleDerivedEdge `json:"edges,omitempty"`
UnresolvedTerms []string `json:"unresolved_terms,omitempty"`
DryRun bool `json:"dry_run,omitempty"`
}
RulesApplyResponse reports one forward-chaining run.
type RulesDeleteRequest ¶ added in v2.98.0
type RulesDeleteRequest struct {
RuleIDs []string `json:"rule_ids"`
}
RulesDeleteRequest removes stored rules by id.
type RulesDeleteResponse ¶ added in v2.98.0
type RulesDeleteResponse struct {
DeletedRuleIDs []string `json:"deleted_rule_ids"`
MissingRuleIDs []string `json:"missing_rule_ids,omitempty"`
}
RulesDeleteResponse separates what was there from what was not, because "deleted 0 of 3" is the answer a caller needs and a bare success is not.
type RulesListRequest ¶ added in v2.98.0
type RulesListRequest struct {
OnlyEnabled bool `json:"only_enabled,omitempty"`
}
RulesListRequest lists the declared rules.
type RulesListResponse ¶ added in v2.98.0
type RulesListResponse struct {
Rules []graph.StoredRule `json:"rules"`
}
RulesListResponse returns the stored rules in id order.
type RulesSaveRequest ¶ added in v2.98.0
type RulesSaveRequest struct {
Rules []RuleDefinition `json:"rules"`
}
RulesSaveRequest stores rules under their ids, replacing any already there.
type RulesSaveResponse ¶ added in v2.98.0
type RulesSaveResponse struct {
Rules []graph.StoredRule `json:"rules"`
}
RulesSaveResponse returns the rules as stored, rendered back into text.
type SnapshotOptions ¶ added in v2.99.0
type SnapshotOptions struct {
NodeTypes []string
EdgeTypes []string
// Sample lists up to this many nodes and edges alongside the counts. Zero
// lists none.
Sample int
}
SnapshotOptions narrows and bounds a snapshot.
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"`
// Mutates reports whether calling this tool changes the brain.
//
// It exists so authorization can tell a read from a write through the
// generic CallTool entry point, which otherwise dispatches on an opaque
// name and forces every tool to be treated as a write — making a read-only
// key unable to call anything at all, including search.
//
// The declaration lives here, next to the tool, rather than in a table
// beside the policy: a second list would have to be hand-synced with this
// one, and the failure mode of that drifting is a write classified as a
// read. The zero value is false, so a definition that forgets to say is
// claimed to be a read — which is why TestEveryToolDeclaresWhetherItWrites
// exists to make forgetting impossible rather than merely unlikely.
Mutates bool `json:"mutates,omitempty"`
}
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
func ToolDefinitions ¶ added in v2.91.0
func ToolDefinitions() []ToolDefinition
ToolDefinitions returns the same catalogue as GraphRAGToolbox.Definitions without needing an open database.
The catalogue is static — names, descriptions, schemas and Mutates are literals, and none of them is read off the store. Authorization needs it that way: pkg/authz decides whether a key may run a named tool before any handler runs, and a policy that could only answer once a database was open would be a policy that fails open on the path where there is none.
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 ToolFactProvenanceRequest ¶ added in v2.82.0
type ToolFactProvenanceRequest struct {
EdgeID string `json:"edge_id"`
WithText bool `json:"with_text,omitempty"`
}
ToolFactProvenanceRequest asks where one edge came from.
type ToolFactProvenanceResponse ¶ added in v2.82.0
type ToolFactProvenanceResponse struct {
Provenance FactProvenance `json:"provenance"`
// Cited is carried explicitly rather than left to the caller to work out
// from the fields, so a model asking "is this backed by anything" gets an
// answer instead of a rule to apply.
Cited bool `json:"cited"`
}
ToolFactProvenanceResponse is the edge's account of itself.
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 ToolUncitedFactsRequest ¶ added in v2.82.0
type ToolUncitedFactsRequest struct {
Limit int `json:"limit,omitempty"`
}
ToolUncitedFactsRequest sweeps for facts with no source.
type ToolUncitedFactsResponse ¶ added in v2.82.0
type ToolUncitedFactsResponse struct {
Facts []FactProvenance `json:"facts"`
Count int `json:"count"`
// Truncated says the limit cut the list short, so "12 uncited facts" is
// never mistaken for "only 12 uncited facts".
Truncated bool `json:"truncated,omitempty"`
}
ToolUncitedFactsResponse lists them.
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 VacuumGraphToolRequest ¶ added in v2.99.0
type VacuumGraphToolRequest struct {
Before string `json:"before"`
DryRun bool `json:"dry_run,omitempty"`
}
VacuumGraphToolRequest reclaims history closed before a cutoff.
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
¶
- backup.go
- brain.go
- brain_graph_facts.go
- brain_tool_api.go
- brain_tooldefs.go
- brain_types.go
- contract.go
- contract_query.go
- contract_tooldefs.go
- cortexdb.go
- decision.go
- decision_query.go
- decision_tooldefs.go
- embedder.go
- extract_conversation.go
- fact_provenance.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
- memory_vector.go
- objectset_resolve.go
- objectset_types.go
- ontology_action_apply.go
- ontology_action_types.go
- ontology_api.go
- ontology_cardinality.go
- ontology_compile.go
- ontology_diff.go
- ontology_dispatch.go
- ontology_draft.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_source.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
- rules_api.go
- rules_tooldefs.go
- sql_chunking.go
- sql_exec.go
- temporal.go
- temporal_tooldefs.go
- text_search.go