Back to Blog

AI Pair Programming: LLM-Assisted Ontology Modeling and Rule Writing

Ontology-driven intelligent decision platforms are powerful but have steep learning curves:

CoomiaPublished on December 30, 20257 min read
Share this articleTwitter / X

AI Pair Programming: LLM-Assisted Ontology Modeling and Rule Writing

Series: S10 Design Patterns · Article 15 | Level: Advanced | Reading Time: 18 min

#TL;DR

  • The AI Pair Programming pattern integrates Large Language Models (LLMs) into the coomia-dip development workflow, assisting users with ontology modeling, rule writing, query building, and anomaly diagnosis.
  • coomia-dip provides three AI assistance modes: Interactive Chat, Code Copilot, and Automated Agent — suited for exploration, coding, and automation scenarios respectively.
  • AI assistance does not replace human decision-making but enhances human capabilities — all AI-generated content requires human review and confirmation before production deployment.

#Introduction: Lowering the Ontology Platform Learning Curve

Ontology-driven intelligent decision platforms are powerful but have steep learning curves:

Code
Challenge 1: Business experts are unfamiliar with ObjectType, LinkType, Action concepts
Challenge 2: Rule writing requires understanding both business logic and platform APIs
Challenge 3: Query syntax is complex, requiring knowledge of underlying data structures
Challenge 4: Troubleshooting requires searching correlated information across multiple Layer logs

AI pair programming lowers these barriers through natural language interaction — users describe requirements in business language, and AI translates them into platform operations.

#Part 1: AI-Assisted Ontology Modeling

#1.1 Natural Language to Schema Conversion

Python
class OntologyModelingAssistant:
    async def suggest_schema(
        self, business_description: str, context: dict | None = None
    ) -> dict:
        prompt = f"""
Based on the following business description, generate an coomia-dip ObjectType schema.

Business Description: {business_description}
Existing ObjectTypes: {context.get('existing_types', []) if context else []}

Requirements:
1. Generate a valid ObjectType name (PascalCase)
2. Identify all properties with appropriate types
3. Suggest primary key and indexed fields
4. Identify potential relationships with existing ObjectTypes
5. Suggest state machine if the object has lifecycle stages

Output as JSON.
"""
        response = await self._llm.generate(prompt, temperature=0.3)
        schema = self._parse_json_response(response)
        validation_errors = await self._schema_validator.validate(schema)
        if validation_errors:
            schema = await self._auto_fix_schema(schema, validation_errors)
        return {
            "suggested_schema": schema,
            "confidence": self._calculate_confidence(response),
            "validation_warnings": validation_errors,
        }

    async def suggest_relationships(
        self, new_type: str, existing_types: list[dict]
    ) -> list[dict]:
        prompt = f"""
Given a new ObjectType '{new_type}' and existing types:
{json.dumps([t['name'] for t in existing_types])}
Suggest meaningful relationships and explain the business rationale.
"""
        response = await self._llm.generate(prompt, temperature=0.3)
        return self._parse_relationships(response)

#1.2 Schema Review and Improvement Suggestions

Python
class SchemaReviewAssistant:
    async def review_schema(self, schema: dict) -> dict:
        prompt = f"""
Review this coomia-dip ObjectType schema and suggest improvements:
{json.dumps(schema, indent=2)}

Check for:
1. Missing common fields (created_at, updated_at, etc.)
2. Incorrect data types
3. Missing indexes on frequently queried fields
4. Missing relationships
5. State machine completeness
6. Naming conventions
"""
        response = await self._llm.generate(prompt, temperature=0.2)
        return {
            "suggestions": self._parse_suggestions(response),
            "severity_summary": self._categorize_suggestions(response),
        }

#Part 2: AI-Assisted Rule Writing

#2.1 Natural Language to Rule Conversion

Python
class RuleWritingAssistant:
    async def generate_rule(
        self, requirement: str, available_types: list[dict], available_actions: list[dict]
    ) -> dict:
        prompt = f"""
Convert this business requirement into an coomia-dip rule definition:
Requirement: {requirement}
Available ObjectTypes: {json.dumps([t['name'] for t in available_types])}
Available Actions: {json.dumps([a['name'] for a in available_actions])}

Generate conditions, actions, priority, description, guard conditions, and error handling.
Output as JSON.
"""
        response = await self._llm.generate(prompt, temperature=0.2)
        rule = self._parse_json_response(response)
        validation = await self._validate_rule_references(rule, available_types, available_actions)
        return {
            "generated_rule": rule,
            "validation": validation,
            "explanation": self._extract_explanation(response),
        }

    async def explain_rule(self, rule: dict) -> str:
        prompt = f"""
Explain this coomia-dip business rule in plain language:
{json.dumps(rule, indent=2)}
What triggers it, what actions it takes, conditions, and failure handling.
"""
        return await self._llm.generate(prompt, temperature=0.3)

    async def suggest_test_cases(self, rule: dict) -> list[dict]:
        prompt = f"""
Generate test cases for this business rule:
{json.dumps(rule, indent=2)}
Include input data, expected outcome, edge case description, and importance.
"""
        response = await self._llm.generate(prompt, temperature=0.4)
        return self._parse_test_cases(response)

#Part 3: AI-Assisted Query Building

#3.1 Natural Language to OQL

Python
class QueryAssistant:
    async def natural_language_to_query(
        self, question: str, available_types: list[dict], context: dict
    ) -> dict:
        type_descriptions = "\n".join([
            f"- {t['name']}: {t.get('description', '')} "
            f"(fields: {', '.join(t.get('properties', {}).keys())})"
            for t in available_types
        ])
        prompt = f"""
Convert this question to an coomia-dip OQL query:
Question: {question}
Available ObjectTypes:
{type_descriptions}
Generate the query, explanation, expected result structure, and performance notes.
"""
        response = await self._llm.generate(prompt, temperature=0.2)
        query_result = self._parse_query_response(response)
        validation = await self._query_validator.validate(query_result["query"], context)
        return {
            "query": query_result["query"],
            "explanation": query_result["explanation"],
            "validation": validation,
        }

    async def optimize_query(self, query: str, explain_plan: dict) -> dict:
        prompt = f"""
Given this OQL query and execution plan, suggest optimizations:
Query: {query}
Plan: {json.dumps(explain_plan, indent=2)}
Suggest index recommendations, query rewrites, caching, and partition pruning.
"""
        return await self._llm.generate(prompt, temperature=0.2)

#Part 4: AI-Assisted Anomaly Diagnosis

#4.1 Intelligent Fault Diagnosis

Python
class DiagnosticsAssistant:
    async def diagnose_error(self, error_message: str, error_context: dict) -> dict:
        related_logs = await self._log_service.search(
            trace_id=error_context.get("trace_id"),
            time_range=(
                error_context.get("timestamp", datetime.utcnow()) - timedelta(minutes=5),
                error_context.get("timestamp", datetime.utcnow()) + timedelta(minutes=1),
            ),
        )
        recent_changes = await self._change_log.get_recent(
            tenant_id=error_context.get("tenant_id"), hours=24,
        )

        prompt = f"""
Diagnose this error in coomia-dip:
Error: {error_message}
Context: Layer={error_context.get('Layer')}, Operation={error_context.get('operation')}
Related logs: {json.dumps(related_logs[:20], indent=2, default=str)}
Recent changes: {json.dumps(recent_changes[:10], indent=2, default=str)}

Provide root cause analysis, fix steps, prevention measures, and related known issues.
"""
        response = await self._llm.generate(prompt, temperature=0.2)
        return {
            "diagnosis": self._parse_diagnosis(response),
            "suggested_actions": self._extract_actions(response),
            "confidence": self._calculate_confidence(response),
        }

    async def explain_saga_failure(self, saga_id: str) -> str:
        saga = await self._saga_store.get(saga_id)
        events = await self._event_store.get_saga_events(saga_id)
        prompt = f"""
Explain why this Saga failed:
Saga: {saga.name}, Status: {saga.status}
Steps: {json.dumps([{"step": e.step_name, "status": e.action} for e in events])}
Explain what it was trying to do, which step failed, compensations taken, and needed manual actions.
"""
        return await self._llm.generate(prompt, temperature=0.3)

#Part 5: AI Agent Automation

#5.1 Automated Workflow Agent

Python
class AIWorkflowAgent:
    async def execute_task(
        self, task_description: str, permissions: list[str], sandbox_id: str | None = None
    ) -> dict:
        if not sandbox_id:
            sandbox = await self._sandbox_manager.create(
                SandboxConfig(
                    name="ai-agent-task", level=SandboxLevel.BRANCH,
                    source_world_id="production", owner_id="ai-agent",
                    tenant_id="system",
                    expires_at=datetime.utcnow() + timedelta(hours=1),
                )
            )
            sandbox_id = sandbox.sandbox_id

        context = await self._sandbox_manager.get_context(sandbox_id)
        plan = await self._plan_task(task_description, permissions)

        results = []
        for step in plan["steps"]:
            if not self._is_allowed(step, permissions):
                results.append({"step": step["description"], "status": "skipped", "reason": "insufficient permissions"})
                continue
            result = await self._execute_step(step, context)
            results.append(result)
            if result["status"] == "failed":
                break

        return {"task": task_description, "plan": plan, "results": results, "sandbox_id": sandbox_id}

#Part 6: Safety and Governance

#6.1 AI Content Review

Python
class AIContentGovernance:
    async def review_ai_output(self, output_type: str, content: dict, context: dict) -> dict:
        review = {"approved": True, "warnings": [], "blocked_reasons": []}

        if output_type == "rule" and self._contains_destructive_actions(content):
            review["approved"] = False
            review["blocked_reasons"].append(
                "AI-generated rules with destructive actions require manual approval"
            )

        policy_check = await self._policy_engine.check(content, context)
        if not policy_check["compliant"]:
            review["approved"] = False
            review["blocked_reasons"].extend(policy_check["violations"])

        hallucination_check = await self._check_hallucinations(content, context)
        if hallucination_check["has_hallucinations"]:
            review["approved"] = False
            review["warnings"].append(
                f"AI referenced non-existent entities: {hallucination_check['details']}"
            )
        return review

    async def _check_hallucinations(self, content: dict, context: dict) -> dict:
        referenced_types = self._extract_type_references(content)
        existing_types = set(context.get("existing_types", []))
        non_existent = referenced_types - existing_types
        return {
            "has_hallucinations": bool(non_existent),
            "details": list(non_existent) if non_existent else [],
        }

#6.2 AI Usage Audit

Python
class AIUsageAudit:
    async def log_ai_interaction(
        self, interaction_type: str, input_data: dict,
        output_data: dict, applied: bool, actor_id: str
    ) -> None:
        await self._event_store.append([
            DomainEvent(
                event_id=generate_id(),
                event_type=f"ai.{interaction_type}",
                aggregate_id=actor_id,
                aggregate_type="ai_interaction",
                sequence_number=0,
                timestamp=datetime.utcnow(),
                payload={
                    "interaction_type": interaction_type,
                    "input_summary": self._summarize(input_data),
                    "output_summary": self._summarize(output_data),
                    "applied": applied,
                },
                metadata=EventMetadata(
                    actor_id=actor_id, actor_type="user",
                    tenant_id=input_data.get("tenant_id", ""),
                    world_id=input_data.get("world_id", ""),
                    source_plane="sdk", trace_id=generate_trace_id(),
                ),
            )
        ])

#Key Takeaways

  1. Natural Language Driven: Describe requirements in business language, AI translates to platform operations
  2. Three Modes: Chat (exploration), Copilot (coding assistance), Agent (automated execution)
  3. Human-AI Collaboration: AI generates suggestions, humans review and confirm, ensuring quality and safety
  4. Hallucination Detection: Automatically detect references to non-existent entities in AI-generated content
  5. Sandbox Isolation: AI Agents execute in sandboxes, keeping production safe
  6. Complete Audit Trail: All AI interactions are auditable for compliance

#Series Conclusion

This 15-article series explored coomia-dip design patterns from multiple dimensions: from the Ontology as API core concept, through distributed patterns like Event Sourcing, Saga, and State Machine, to platform-specific patterns like Sandbox, Federation, and Cascade, and finally to the frontier of AI Pair Programming. These patterns together form coomia-dip's design philosophy: unify business semantics through Ontology, reduce system complexity through pattern-based design, and lower barriers through AI empowerment.

#Tags

#DesignPatterns #AIPairProgramming #LLM #OntologyModeling #RuleWriting #QueryBuilding #AnomalyDiagnosis #AgentAutomation #Governance