Skip to content

Plan, apply and roll back changes to a production ontology, with a blast radius report and a proof an auditor can re-check.

feat: configurable embedding models + stronger sketch pipeline

FABIOTESS1d6e4f43665c
diff --git a/src/config.rs b/src/config.rs
index daec11bb..db5f750a 100644
--- a/src/config.rs
+++ b/src/config.rs
@@ -7,6 +7,7 @@ use std::path::Path;
#[derive(Default)]
pub struct Config {
pub general: GeneralConfig,
+ pub embeddings: EmbeddingsConfig,
}
@@ -34,6 +35,24 @@ impl Default for GeneralConfig {
}
}
+#[derive(Debug, Deserialize, Clone)]
+#[serde(default)]
+pub struct EmbeddingsConfig {
+ /// Path to the ONNX model file. Default: ~/.open-ontologies/models/bge-small-en-v1.5.onnx
+ pub model_path: Option<String>,
+ /// Path to the tokenizer.json file. Default: ~/.open-ontologies/models/tokenizer.json
+ pub tokenizer_path: Option<String>,
+}
+
+impl Default for EmbeddingsConfig {
+ fn default() -> Self {
+ Self {
+ model_path: None,
+ tokenizer_path: None,
+ }
+ }
+}
+
/// Expand a leading `~` in a path to the user's home directory.
pub fn expand_tilde(path: &str) -> String {
if (path.starts_with("~/") || path == "~")
diff --git a/src/main.rs b/src/main.rs
index 997fafa8..16e9880b 100644
--- a/src/main.rs
+++ b/src/main.rs
@@ -9,6 +9,10 @@ use open_ontologies::state::StateDb;
const DEFAULT_CONFIG: &str = r#"[general]
data_dir = "~/.open-ontologies"
+
+# [embeddings]
+# model_path = "~/.open-ontologies/models/bge-small-en-v1.5.onnx"
+# tokenizer_path = "~/.open-ontologies/models/tokenizer.json"
"#;
#[derive(Parser)]
@@ -32,6 +36,15 @@ enum Commands {
Init {
#[arg(long, default_value = "~/.open-ontologies")]
data_dir: String,
+ /// Custom ONNX model URL (default: BGE-small-en-v1.5 from Hugging Face)
+ #[arg(long)]
+ model_url: Option<String>,
+ /// Custom tokenizer URL (default: BGE-small-en-v1.5 tokenizer from Hugging Face)
+ #[arg(long)]
+ tokenizer_url: Option<String>,
+ /// Filename for the downloaded ONNX model (default: bge-small-en-v1.5.onnx)
+ #[arg(long)]
+ model_name: Option<String>,
},
/// Start the MCP server (stdio transport)
Serve {
@@ -343,7 +356,7 @@ async fn main() -> anyhow::Result<()> {
let cli = Cli::parse();
match cli.command {
- Commands::Init { data_dir } => {
+ Commands::Init { data_dir, model_url, tokenizer_url, model_name } => {
let data_dir = expand_tilde(&data_dir);
let data_path = std::path::Path::new(&data_dir);
@@ -367,13 +380,20 @@ async fn main() -> anyhow::Result<()> {
let models_dir = data_path.join("models");
std::fs::create_dir_all(&models_dir)?;
- let model_path = models_dir.join("bge-small-en-v1.5.onnx");
+ let onnx_url = model_url.as_deref()
+ .unwrap_or(open_ontologies::embed::BGE_SMALL_ONNX_URL);
+ let tok_url = tokenizer_url.as_deref()
+ .unwrap_or(open_ontologies::embed::BGE_SMALL_TOKENIZER_URL);
+ let onnx_filename = model_name.as_deref()
+ .unwrap_or("bge-small-en-v1.5.onnx");
+
+ let model_path = models_dir.join(onnx_filename);
let tokenizer_path = models_dir.join("tokenizer.json");
if !model_path.exists() {
- println!("Downloading bge-small-en-v1.5 embedding model...");
+ println!("Downloading embedding model from {}...", onnx_url);
open_ontologies::embed::download_model_file(
- open_ontologies::embed::BGE_SMALL_ONNX_URL,
+ onnx_url,
&model_path,
).await?;
println!(" Model saved: {}", model_path.display());
@@ -382,9 +402,9 @@ async fn main() -> anyhow::Result<()> {
}
if !tokenizer_path.exists() {
- println!("Downloading tokenizer...");
+ println!("Downloading tokenizer from {}...", tok_url);
open_ontologies::embed::download_model_file(
- open_ontologies::embed::BGE_SMALL_TOKENIZER_URL,
+ tok_url,
&tokenizer_path,
).await?;
println!(" Tokenizer saved: {}", tokenizer_path.display());
@@ -414,7 +434,7 @@ async fn main() -> anyhow::Result<()> {
std::fs::create_dir_all(&data_dir)?;
let db = StateDb::open(&db_path)?;
- let server = OpenOntologiesServer::new_with_options(db, Arc::new(GraphStore::new()), governance_webhook);
+ let server = OpenOntologiesServer::new_with_full_options(db, Arc::new(GraphStore::new()), governance_webhook, cfg.embeddings);
let service = server.serve(rmcp::transport::stdio()).await?;
service.waiting().await?;
}
@@ -457,12 +477,13 @@ async fn main() -> anyhow::Result<()> {
let shared_graph_for_service = shared_graph.clone();
let gw_for_service = governance_webhook.clone();
+ let embed_config = cfg.embeddings.clone();
let service: StreamableHttpService<_, LocalSessionManager> =
StreamableHttpService::new(
move || {
let db = StateDb::open(&db_path_owned)
.map_err(std::io::Error::other)?;
- Ok(OpenOntologiesServer::new_with_options(db, shared_graph_for_service.clone(), gw_for_service.clone()))
+ Ok(OpenOntologiesServer::new_with_full_options(db, shared_graph_for_service.clone(), gw_for_service.clone(), embed_config.clone()))
},
Default::default(),
http_config,
diff --git a/src/server.rs b/src/server.rs
index d7fa3ca5..2eeba804 100644
--- a/src/server.rs
+++ b/src/server.rs
@@ -47,6 +47,16 @@ impl OpenOntologiesServer {
/// Create a new server with all options including optional governance webhook.
pub fn new_with_options(db: StateDb, graph: Arc<GraphStore>, governance_webhook: Option<String>) -> Self {
+ Self::new_with_full_options(db, graph, governance_webhook, Default::default())
+ }
+
+ /// Create a new server with all options including embedding config.
+ pub fn new_with_full_options(
+ db: StateDb,
+ graph: Arc<GraphStore>,
+ governance_webhook: Option<String>,
+ embed_config: crate::config::EmbeddingsConfig,
+ ) -> Self {
let lineage = crate::lineage::LineageLog::with_governance_webhook(db.clone(), governance_webhook.clone());
let session_id = lineage.new_session();
@@ -55,13 +65,21 @@ impl OpenOntologiesServer {
let mut vs = crate::vecstore::VecStore::new(db.clone());
let _ = vs.load_from_db();
- let model_dir = dirs::home_dir()
+ // Resolve model paths: config overrides > default locations
+ let default_model_dir = dirs::home_dir()
.map(|h| h.join(".open-ontologies/models"));
- let embedder = model_dir.and_then(|dir| {
- let model_path = dir.join("bge-small-en-v1.5.onnx");
- let tokenizer_path = dir.join("tokenizer.json");
- if model_path.exists() && tokenizer_path.exists() {
- crate::embed::TextEmbedder::load(&model_path, &tokenizer_path).ok()
+
+ let model_path = embed_config.model_path
+ .map(|p| std::path::PathBuf::from(crate::config::expand_tilde(&p)))
+ .or_else(|| default_model_dir.as_ref().map(|d| d.join("bge-small-en-v1.5.onnx")));
+
+ let tokenizer_path = embed_config.tokenizer_path
+ .map(|p| std::path::PathBuf::from(crate::config::expand_tilde(&p)))
+ .or_else(|| default_model_dir.as_ref().map(|d| d.join("tokenizer.json")));
+
+ let embedder = model_path.zip(tokenizer_path).and_then(|(m, t)| {
+ if m.exists() && t.exists() {
+ crate::embed::TextEmbedder::load(&m, &t).ok()
} else {
None
}
diff --git a/studio/src-tauri/sidecars/agent/dist/index.js b/studio/src-tauri/sidecars/agent/dist/index.js
index 8fc774f3..f04aeca5 100644
--- a/studio/src-tauri/sidecars/agent/dist/index.js
+++ b/studio/src-tauri/sidecars/agent/dist/index.js
@@ -268,34 +268,59 @@ Report the final ontology statistics.`,
// --- Quick sketch: 3-step lightweight build ---
async function handleSketch(domain) {
const ns = domain.toLowerCase().replace(/[^a-z0-9]+/g, '-');
+ const prefix = `@prefix : <http://example.org/${ns}#> .`;
const steps = [
{
- label: 'Step 1/3: Classes + properties',
- prompt: `Build a quick ontology about "${domain}". Use namespace @prefix : <http://example.org/${ns}#> .
+ label: 'Step 1/5: Foundation — root + branches',
+ prompt: `Build an ontology about "${domain}". Use namespace ${prefix}
Call onto_clear. Then call onto_load with ONE Turtle block containing:
-- 50-80 owl:Class in a subClassOf hierarchy 4-5 levels deep
+- An owl:Ontology declaration
+- A root class for the domain
+- 6-10 major branch classes under the root
+- For each branch, 3-5 subclasses (2-3 levels deep)
+- Every class MUST have rdfs:label and rdfs:comment
+
+Call onto_stats after. Do NOT save yet.`,
+ },
+ {
+ label: 'Step 2/5: Deepen + properties',
+ prompt: `Call onto_query to find leaf classes (classes with no subclasses).
+Then call onto_load with Turtle using the SAME namespace ${prefix} adding:
+- 2-4 more subclass levels under leaf classes that can be subdivided further
- 15-25 owl:ObjectProperty each with rdfs:domain, rdfs:range, rdfs:label, rdfs:comment
-- 8-12 owl:DatatypeProperty
-- owl:inverseOf pairs for key relationships
-- rdfs:label and rdfs:comment on every class and property
+- owl:inverseOf pairs for directional properties
+- 8-12 owl:DatatypeProperty with rdfs:domain, rdfs:range (xsd types), rdfs:label
Call onto_stats after. Do NOT save yet.`,
},
{
- label: 'Step 2/3: Axioms + individuals',
- prompt: `Call onto_load with Turtle adding:
-- owl:disjointWith between sibling classes (15+ pairs)
-- 10-15 owl:NamedIndividual with rdf:type and property values
+ label: 'Step 3/5: Axioms + individuals',
+ prompt: `Call onto_load with Turtle using namespace ${prefix} adding:
+- owl:disjointWith between sibling classes that cannot overlap (15+ pairs)
+- 12-20 owl:NamedIndividual spread across different branches, each with:
+ - rdf:type (the most specific class)
+ - rdfs:label and rdfs:comment
+ - 2-4 property values (both object and datatype properties)
+
+Call onto_stats after. Do NOT save yet.`,
+ },
+ {
+ label: 'Step 4/5: Verify + fix gaps',
+ prompt: `Call onto_stats and onto_query to check: How many individuals exist? What is the max depth? Are there branches with no properties?
+
+If individuals < 10, call onto_load with more individuals.
+If max depth < 5, call onto_load deepening the shallowest branches.
+If any branch has no object properties connecting it, add some.
Call onto_stats after. Do NOT save yet.`,
},
{
- label: 'Step 3/3: Reason + save',
- prompt: `Run onto_reason (profile "rdfs"), then onto_stats, then onto_save ("~/.open-ontologies/studio-live.ttl"). Report final statistics.`,
+ label: 'Step 5/5: Reason + save',
+ prompt: `Run onto_reason (profile "rdfs"), then onto_stats, then onto_save ("~/.open-ontologies/studio-live.ttl"). Report final statistics including class count, property count, individual count, max depth, and triple count.`,
},
];
- send({ type: 'text', content: `**Sketching ontology: ${domain}** (3 steps)\n` });
+ send({ type: 'text', content: `**Sketching ontology: ${domain}** (${steps.length} steps)\n` });
send({ type: 'progress', step: 0, total: steps.length, label: 'Starting sketch...' });
for (let i = 0; i < steps.length; i++) {
const step = steps[i];
diff --git a/studio/src-tauri/sidecars/agent/index.ts b/studio/src-tauri/sidecars/agent/index.ts
index 63fd92a9..cfa50e1a 100644
--- a/studio/src-tauri/sidecars/agent/index.ts
+++ b/studio/src-tauri/sidecars/agent/index.ts
@@ -292,35 +292,61 @@ Report the final ontology statistics.`,
async function handleSketch(domain: string): Promise<void> {
const ns = domain.toLowerCase().replace(/[^a-z0-9]+/g, '-');
+ const prefix = `@prefix : <http://example.org/${ns}#> .`;
+
const steps = [
{
- label: 'Step 1/3: Classes + properties',
- prompt: `Build a quick ontology about "${domain}". Use namespace @prefix : <http://example.org/${ns}#> .
+ label: 'Step 1/5: Foundation — root + branches',
+ prompt: `Build an ontology about "${domain}". Use namespace ${prefix}
Call onto_clear. Then call onto_load with ONE Turtle block containing:
-- 50-80 owl:Class in a subClassOf hierarchy 4-5 levels deep
+- An owl:Ontology declaration
+- A root class for the domain
+- 6-10 major branch classes under the root
+- For each branch, 3-5 subclasses (2-3 levels deep)
+- Every class MUST have rdfs:label and rdfs:comment
+
+Call onto_stats after. Do NOT save yet.`,
+ },
+ {
+ label: 'Step 2/5: Deepen + properties',
+ prompt: `Call onto_query to find leaf classes (classes with no subclasses).
+Then call onto_load with Turtle using the SAME namespace ${prefix} adding:
+- 2-4 more subclass levels under leaf classes that can be subdivided further
- 15-25 owl:ObjectProperty each with rdfs:domain, rdfs:range, rdfs:label, rdfs:comment
-- 8-12 owl:DatatypeProperty
-- owl:inverseOf pairs for key relationships
-- rdfs:label and rdfs:comment on every class and property
+- owl:inverseOf pairs for directional properties
+- 8-12 owl:DatatypeProperty with rdfs:domain, rdfs:range (xsd types), rdfs:label
Call onto_stats after. Do NOT save yet.`,
},
{
- label: 'Step 2/3: Axioms + individuals',
- prompt: `Call onto_load with Turtle adding:
-- owl:disjointWith between sibling classes (15+ pairs)
-- 10-15 owl:NamedIndividual with rdf:type and property values
+ label: 'Step 3/5: Axioms + individuals',
+ prompt: `Call onto_load with Turtle using namespace ${prefix} adding:
+- owl:disjointWith between sibling classes that cannot overlap (15+ pairs)
+- 12-20 owl:NamedIndividual spread across different branches, each with:
+ - rdf:type (the most specific class)
+ - rdfs:label and rdfs:comment
+ - 2-4 property values (both object and datatype properties)
+
+Call onto_stats after. Do NOT save yet.`,
+ },
+ {
+ label: 'Step 4/5: Verify + fix gaps',
+ prompt: `Call onto_stats and onto_query to check: How many individuals exist? What is the max depth? Are there branches with no properties?
+
+If individuals < 10, call onto_load with more individuals.
+If max depth < 5, call onto_load deepening the shallowest branches.
+If any branch has no object properties connecting it, add some.
Call onto_stats after. Do NOT save yet.`,
},
{
- label: 'Step 3/3: Reason + save',
- prompt: `Run onto_reason (profile "rdfs"), then onto_stats, then onto_save ("~/.open-ontologies/studio-live.ttl"). Report final statistics.`,
+ label: 'Step 5/5: Reason + save',
+ prompt: `Run onto_reason (profile "rdfs"), then onto_stats, then onto_save ("~/.open-ontologies/studio-live.ttl"). Report final statistics including class count, property count, individual count, max depth, and triple count.`,
},
];
- send({ type: 'text', content: `**Sketching ontology: ${domain}** (3 steps)\n` });
+ send({ type: 'text', content: `**Sketching ontology: ${domain}** (${steps.length} steps)\n` });
send({ type: 'progress', step: 0, total: steps.length, label: 'Starting sketch...' });
for (let i = 0; i < steps.length; i++) {