rust-kgdb 0.8.13 → 0.8.14

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -4958,6 +4958,227 @@ class HyperMindAgent {
4958
4958
  this.intentPatterns = this._buildIntentPatterns()
4959
4959
  }
4960
4960
 
4961
+ /**
4962
+ * 1-LINE SETUP: Create a fully configured HyperMindAgent
4963
+ *
4964
+ * This is the recommended way to create agents - handles all setup automatically:
4965
+ * - Creates GraphDB and loads TTL data
4966
+ * - Auto-detects OWL ontology from data (owl:Class, owl:*Property patterns)
4967
+ * - Optionally trains RDF2Vec embeddings
4968
+ * - Enables prompt optimization with schema context
4969
+ *
4970
+ * @example
4971
+ * // Minimal setup (just data)
4972
+ * const agent = await HyperMindAgent.create({
4973
+ * name: 'my-agent',
4974
+ * data: ttlData
4975
+ * })
4976
+ *
4977
+ * // Full setup with all features
4978
+ * const agent = await HyperMindAgent.create({
4979
+ * name: 'fraud-detector',
4980
+ * data: ttlData,
4981
+ * rdf2vec: true, // Train embeddings automatically
4982
+ * promptOptimize: true, // Enable schema-aware prompts
4983
+ * apiKey: process.env.OPENAI_API_KEY,
4984
+ * model: 'gpt-4o'
4985
+ * })
4986
+ *
4987
+ * // Then just call
4988
+ * const result = await agent.call("Who committed fraud?")
4989
+ *
4990
+ * @param {Object} options - Configuration options
4991
+ * @param {string} options.name - Agent name (required)
4992
+ * @param {string} options.data - TTL/N-Triples data to load (required)
4993
+ * @param {string} [options.baseUri] - Base URI for GraphDB (default: auto-detected)
4994
+ * @param {boolean} [options.rdf2vec=false] - Train RDF2Vec embeddings
4995
+ * @param {boolean} [options.promptOptimize=true] - Enable prompt optimization
4996
+ * @param {string} [options.apiKey] - OpenAI/Anthropic API key
4997
+ * @param {string} [options.model] - LLM model (e.g., 'gpt-4o', 'claude-3-opus')
4998
+ * @param {string} [options.ontology] - Custom ontology TTL (optional, auto-detected if not provided)
4999
+ * @returns {Promise<HyperMindAgent>} Configured agent ready to use
5000
+ */
5001
+ static async create(options) {
5002
+ if (!options.name) {
5003
+ throw new Error('name is required for HyperMindAgent.create()')
5004
+ }
5005
+ if (!options.data) {
5006
+ throw new Error('data (TTL/N-Triples) is required for HyperMindAgent.create()')
5007
+ }
5008
+
5009
+ // 1. Create SchemaAwareGraphDB with auto-detected or provided base URI
5010
+ const baseUri = options.baseUri || HyperMindAgent._detectBaseUri(options.data)
5011
+ const db = new SchemaAwareGraphDB(baseUri, { autoExtract: true })
5012
+
5013
+ // 2. Load TTL data
5014
+ db.loadTtl(options.data, null)
5015
+ const tripleCount = db.countTriples()
5016
+ console.log(`[HyperMindAgent.create] Loaded ${tripleCount} triples`)
5017
+
5018
+ // 3. Auto-detect OWL ontology from data (unless custom ontology provided)
5019
+ let ontology = options.ontology
5020
+ if (!ontology) {
5021
+ ontology = HyperMindAgent._autoDetectOntology(db)
5022
+ if (ontology) {
5023
+ console.log(`[HyperMindAgent.create] Auto-detected OWL ontology from data`)
5024
+ }
5025
+ }
5026
+
5027
+ // 4. Train RDF2Vec embeddings if requested
5028
+ let embeddings = null
5029
+ if (options.rdf2vec) {
5030
+ try {
5031
+ const { Rdf2VecEngine, EmbeddingService } = loadNativeBindingDirect()
5032
+ const rdf2vec = new Rdf2VecEngine()
5033
+ embeddings = new EmbeddingService()
5034
+
5035
+ // Train RDF2Vec on the graph using native GraphDb
5036
+ rdf2vec.train(db._db, {
5037
+ dimensions: options.rdf2vecDimensions || 128,
5038
+ walkLength: options.rdf2vecWalkLength || 10,
5039
+ walksPerEntity: options.rdf2vecWalksPerEntity || 10,
5040
+ windowSize: options.rdf2vecWindowSize || 5,
5041
+ minCount: 1,
5042
+ epochs: options.rdf2vecEpochs || 5
5043
+ })
5044
+
5045
+ if (rdf2vec.isTrained()) {
5046
+ console.log(`[HyperMindAgent.create] Trained RDF2Vec embeddings (${rdf2vec.dimensions()} dimensions)`)
5047
+ embeddings._rdf2vec = rdf2vec
5048
+ }
5049
+ } catch (e) {
5050
+ console.warn(`[HyperMindAgent.create] RDF2Vec training skipped: ${e.message}`)
5051
+ embeddings = null
5052
+ }
5053
+ }
5054
+
5055
+ // 5. Create agent with all components
5056
+ const agent = new HyperMindAgent({
5057
+ name: options.name,
5058
+ kg: db,
5059
+ embeddings: embeddings,
5060
+ apiKey: options.apiKey,
5061
+ model: options.model
5062
+ })
5063
+
5064
+ // 6. Load ontology for reasoning rules
5065
+ if (ontology) {
5066
+ agent.loadOntology(ontology)
5067
+ }
5068
+
5069
+ // 7. Enable prompt optimization (extract schema)
5070
+ if (options.promptOptimize !== false) { // Default to true
5071
+ await agent.extractSchema()
5072
+ console.log(`[HyperMindAgent.create] Schema extracted for prompt optimization`)
5073
+ }
5074
+
5075
+ console.log(`[HyperMindAgent.create] Agent "${options.name}" ready!`)
5076
+ return agent
5077
+ }
5078
+
5079
+ /**
5080
+ * Auto-detect base URI from TTL data
5081
+ * Looks for common patterns like @prefix, @base, or first subject
5082
+ * @private
5083
+ */
5084
+ static _detectBaseUri(data) {
5085
+ // Try to find @base declaration
5086
+ const baseMatch = data.match(/@base\s+<([^>]+)>/)
5087
+ if (baseMatch) return baseMatch[1]
5088
+
5089
+ // Try to find first URI in data
5090
+ const uriMatch = data.match(/<(https?:\/\/[^>#\s]+)/)
5091
+ if (uriMatch) {
5092
+ // Extract base (remove fragment/local part)
5093
+ const uri = uriMatch[1]
5094
+ const lastSlash = uri.lastIndexOf('/')
5095
+ const lastHash = uri.lastIndexOf('#')
5096
+ const cutPoint = Math.max(lastSlash, lastHash)
5097
+ return cutPoint > 0 ? uri.substring(0, cutPoint + 1) : uri
5098
+ }
5099
+
5100
+ return 'http://example.org/'
5101
+ }
5102
+
5103
+ /**
5104
+ * Auto-detect OWL ontology from loaded data
5105
+ * Scans for owl:Class, owl:ObjectProperty, owl:SymmetricProperty, etc.
5106
+ * @private
5107
+ */
5108
+ static _autoDetectOntology(db) {
5109
+ const owlPatterns = []
5110
+
5111
+ // Query for OWL class declarations
5112
+ try {
5113
+ const classes = db.querySelect(`
5114
+ SELECT ?class WHERE {
5115
+ ?class <http://www.w3.org/1999/02/22-rdf-syntax-ns#type> <http://www.w3.org/2002/07/owl#Class> .
5116
+ }
5117
+ `)
5118
+ for (const r of classes) {
5119
+ const cls = r.bindings?.class || r.class
5120
+ if (cls) owlPatterns.push(`<${cls}> a <http://www.w3.org/2002/07/owl#Class> .`)
5121
+ }
5122
+ } catch (e) { /* ignore */ }
5123
+
5124
+ // Query for OWL SymmetricProperty
5125
+ try {
5126
+ const symProps = db.querySelect(`
5127
+ SELECT ?prop WHERE {
5128
+ ?prop <http://www.w3.org/1999/02/22-rdf-syntax-ns#type> <http://www.w3.org/2002/07/owl#SymmetricProperty> .
5129
+ }
5130
+ `)
5131
+ for (const r of symProps) {
5132
+ const prop = r.bindings?.prop || r.prop
5133
+ if (prop) owlPatterns.push(`<${prop}> a <http://www.w3.org/2002/07/owl#SymmetricProperty> .`)
5134
+ }
5135
+ } catch (e) { /* ignore */ }
5136
+
5137
+ // Query for OWL TransitiveProperty
5138
+ try {
5139
+ const transProps = db.querySelect(`
5140
+ SELECT ?prop WHERE {
5141
+ ?prop <http://www.w3.org/1999/02/22-rdf-syntax-ns#type> <http://www.w3.org/2002/07/owl#TransitiveProperty> .
5142
+ }
5143
+ `)
5144
+ for (const r of transProps) {
5145
+ const prop = r.bindings?.prop || r.prop
5146
+ if (prop) owlPatterns.push(`<${prop}> a <http://www.w3.org/2002/07/owl#TransitiveProperty> .`)
5147
+ }
5148
+ } catch (e) { /* ignore */ }
5149
+
5150
+ // Query for OWL ObjectProperty
5151
+ try {
5152
+ const objProps = db.querySelect(`
5153
+ SELECT ?prop WHERE {
5154
+ ?prop <http://www.w3.org/1999/02/22-rdf-syntax-ns#type> <http://www.w3.org/2002/07/owl#ObjectProperty> .
5155
+ }
5156
+ `)
5157
+ for (const r of objProps) {
5158
+ const prop = r.bindings?.prop || r.prop
5159
+ if (prop) owlPatterns.push(`<${prop}> a <http://www.w3.org/2002/07/owl#ObjectProperty> .`)
5160
+ }
5161
+ } catch (e) { /* ignore */ }
5162
+
5163
+ // Query for OWL DatatypeProperty
5164
+ try {
5165
+ const dataProps = db.querySelect(`
5166
+ SELECT ?prop WHERE {
5167
+ ?prop <http://www.w3.org/1999/02/22-rdf-syntax-ns#type> <http://www.w3.org/2002/07/owl#DatatypeProperty> .
5168
+ }
5169
+ `)
5170
+ for (const r of dataProps) {
5171
+ const prop = r.bindings?.prop || r.prop
5172
+ if (prop) owlPatterns.push(`<${prop}> a <http://www.w3.org/2002/07/owl#DatatypeProperty> .`)
5173
+ }
5174
+ } catch (e) { /* ignore */ }
5175
+
5176
+ if (owlPatterns.length > 0) {
5177
+ return owlPatterns.join('\n')
5178
+ }
5179
+ return null
5180
+ }
5181
+
4961
5182
  /**
4962
5183
  * Extract schema from KG (delegates to planner)
4963
5184
  * @returns {Object} Schema with predicates, classes, examples
package/index.d.ts CHANGED
@@ -779,7 +779,75 @@ export interface TraceEntry {
779
779
  * const trace = agent.getTrace()
780
780
  * ```
781
781
  */
782
+ /**
783
+ * Options for HyperMindAgent.create() - the 1-line setup method
784
+ */
785
+ export interface HyperMindAgentCreateOptions {
786
+ /** Agent name (required) */
787
+ name: string
788
+ /** TTL/N-Triples data to load (required) */
789
+ data: string
790
+ /** Base URI for GraphDB (optional - auto-detected from data) */
791
+ baseUri?: string
792
+ /** Train RDF2Vec embeddings (default: false) */
793
+ rdf2vec?: boolean
794
+ /** RDF2Vec dimensions (default: 128) */
795
+ rdf2vecDimensions?: number
796
+ /** RDF2Vec walk length (default: 10) */
797
+ rdf2vecWalkLength?: number
798
+ /** RDF2Vec walks per entity (default: 10) */
799
+ rdf2vecWalksPerEntity?: number
800
+ /** RDF2Vec window size (default: 5) */
801
+ rdf2vecWindowSize?: number
802
+ /** RDF2Vec training epochs (default: 5) */
803
+ rdf2vecEpochs?: number
804
+ /** Enable prompt optimization with schema context (default: true) */
805
+ promptOptimize?: boolean
806
+ /** OpenAI/Anthropic API key */
807
+ apiKey?: string
808
+ /** LLM model (e.g., 'gpt-4o', 'claude-3-opus') */
809
+ model?: string
810
+ /** Custom ontology TTL (optional - auto-detected if not provided) */
811
+ ontology?: string
812
+ }
813
+
782
814
  export class HyperMindAgent {
815
+ /**
816
+ * 1-LINE SETUP: Create a fully configured HyperMindAgent
817
+ *
818
+ * This is the recommended way to create agents - handles all setup automatically:
819
+ * - Creates GraphDB and loads TTL data
820
+ * - Auto-detects OWL ontology from data (owl:Class, owl:*Property patterns)
821
+ * - Optionally trains RDF2Vec embeddings
822
+ * - Enables prompt optimization with schema context
823
+ *
824
+ * @example
825
+ * ```typescript
826
+ * // Minimal setup (just data)
827
+ * const agent = await HyperMindAgent.create({
828
+ * name: 'my-agent',
829
+ * data: ttlData
830
+ * })
831
+ *
832
+ * // Full setup with all features
833
+ * const agent = await HyperMindAgent.create({
834
+ * name: 'fraud-detector',
835
+ * data: ttlData,
836
+ * rdf2vec: true, // Train embeddings automatically
837
+ * promptOptimize: true, // Enable schema-aware prompts
838
+ * apiKey: process.env.OPENAI_API_KEY,
839
+ * model: 'gpt-4o'
840
+ * })
841
+ *
842
+ * // Then just call
843
+ * const result = await agent.call("Who committed fraud?")
844
+ * ```
845
+ *
846
+ * @param options - Configuration options
847
+ * @returns Promise resolving to a fully configured agent
848
+ */
849
+ static create(options: HyperMindAgentCreateOptions): Promise<HyperMindAgent>
850
+
783
851
  /**
784
852
  * Spawn a new HyperMind agent with the given specification
785
853
  * @param spec - Agent specification
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "rust-kgdb",
3
- "version": "0.8.13",
3
+ "version": "0.8.14",
4
4
  "description": "High-performance RDF/SPARQL database with AI agent framework and cross-database federation. GraphDB (449ns lookups, 5-11x faster than RDFox), HyperFederate (KGDB + Snowflake + BigQuery), GraphFrames analytics, Datalog reasoning, HNSW vector embeddings. HyperMindAgent for schema-aware query generation with audit trails. W3C SPARQL 1.1 compliant. Native performance via Rust + NAPI-RS.",
5
5
  "main": "index.js",
6
6
  "types": "index.d.ts",