返回博客

AI 结对编程:LLM 辅助的本体建模与规则编写

Ontology 驱动的智能决策平台功能强大,但学习曲线陡峭:

Coomia发布于 2025年12月30日11 分钟阅读
分享本文Twitter / X

AI 结对编程:LLM 辅助的本体建模与规则编写

系列:S10 设计模式 · 第 15 篇 | 难度:高级 | 阅读时间:18 分钟

#TL;DR

  • AI 结对编程模式将大语言模型(LLM)集成到 coomia-dip 的开发工作流中,辅助用户进行本体建模、规则编写、查询构建和异常诊断。
  • coomia-dip 提供三种 AI 辅助模式:交互式对话(Chat)、代码补全(Copilot)和自动化代理(Agent),分别适用于探索、编码和自动化场景。
  • AI 辅助不替代人类决策,而是增强人类能力——所有 AI 生成的内容都需要人工审核确认后才能应用到生产环境。

#引言:降低 Ontology 平台的使用门槛

Ontology 驱动的智能决策平台功能强大,但学习曲线陡峭:

Code
挑战 1:业务专家不熟悉 ObjectType、LinkType、Action 等概念
挑战 2:规则编写需要同时理解业务逻辑和平台 API
挑战 3:查询语法复杂,需要了解底层数据结构
挑战 4:排查问题需要在多个 Layer 的日志中搜索关联信息

AI 结对编程通过自然语言交互降低这些门槛——用户用业务语言描述需求,AI 翻译为平台操作。

#一、AI 辅助本体建模

#1.1 自然语言到 Schema 转换

Python
class OntologyModelingAssistant:
    """AI assistant for Ontology modeling."""

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

Business Description: {business_description}

Existing ObjectTypes in this World: {context.get('existing_types', []) if context else []}

Requirements:
1. Generate a valid ObjectType name (PascalCase, no spaces)
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 with this structure:
{{
    "name": "ObjectTypeName",
    "display_name": "Human readable name",
    "description": "...",
    "properties": {{
        "field_name": {{
            "type": "string|integer|float|boolean|datetime|reference",
            "required": true|false,
            "description": "...",
            "indexed": true|false
        }}
    }},
    "primary_key": "field_name",
    "relationships": [
        {{
            "target_type": "ExistingType",
            "link_type": "RelationshipName",
            "cardinality": "one_to_many|many_to_many|one_to_one"
        }}
    ],
    "state_machine": null | {{...}}
}}
"""
        response = await self._llm.generate(prompt, temperature=0.3)
        schema = self._parse_json_response(response)

        # 验证生成的 Schema
        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]:
        """Suggest relationships between new and existing types."""
        prompt = f"""
Given a new ObjectType '{new_type}' and the following existing ObjectTypes:
{json.dumps([t['name'] for t in existing_types])}

Suggest meaningful relationships (LinkTypes) between the new type and existing types.
For each suggestion, explain the business rationale.
"""
        response = await self._llm.generate(prompt, temperature=0.3)
        return self._parse_relationships(response)

#1.2 Schema 审核与改进建议

Python
class SchemaReviewAssistant:
    """AI-powered schema review and improvement suggestions."""

    async def review_schema(self, schema: dict) -> dict:
        """Review a schema and suggest improvements."""
        prompt = f"""
Review the following coomia-dip ObjectType schema and provide improvement suggestions:

{json.dumps(schema, indent=2)}

Check for:
1. Missing fields that are commonly needed (created_at, updated_at, etc.)
2. Incorrect data types (e.g., using string for amounts)
3. Missing indexes on frequently queried fields
4. Missing relationships that business logic might need
5. State machine completeness (unreachable states, missing transitions)
6. Naming conventions (PascalCase for types, snake_case for properties)
"""
        response = await self._llm.generate(prompt, temperature=0.2)
        return {
            "suggestions": self._parse_suggestions(response),
            "severity_summary": self._categorize_suggestions(response),
        }

#二、AI 辅助规则编写

#2.1 自然语言到规则转换

Python
class RuleWritingAssistant:
    """AI assistant for writing business rules."""

    async def generate_rule(
        self,
        requirement: str,
        available_types: list[dict],
        available_actions: list[dict],
    ) -> dict:
        """Generate a business rule from natural language requirement."""
        prompt = f"""
Convert the following 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 a rule with:
1. Conditions (when to trigger)
2. Actions (what to do)
3. Priority (1-10)
4. Description
5. Guard conditions
6. Error handling

Output as JSON.
"""
        response = await self._llm.generate(prompt, temperature=0.2)
        rule = self._parse_json_response(response)

        # 验证规则引用的类型和 Action 是否存在
        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:
        """Explain an existing rule in natural language."""
        prompt = f"""
Explain the following coomia-dip business rule in plain language that a business user can understand:

{json.dumps(rule, indent=2)}

Provide:
1. What triggers this rule
2. What actions it takes
3. Under what conditions it applies
4. What happens if it fails
"""
        return await self._llm.generate(prompt, temperature=0.3)

    async def suggest_test_cases(self, rule: dict) -> list[dict]:
        """Suggest test cases for a business rule."""
        prompt = f"""
Generate test cases for the following business rule:
{json.dumps(rule, indent=2)}

For each test case provide:
1. Input data
2. Expected outcome
3. Edge case description
4. Why this test case is important
"""
        response = await self._llm.generate(prompt, temperature=0.4)
        return self._parse_test_cases(response)

#三、AI 辅助查询构建

#3.1 自然语言到 OQL 转换

Python
class QueryAssistant:
    """AI assistant for building Ontology queries."""

    async def natural_language_to_query(
        self,
        question: str,
        available_types: list[dict],
        context: dict,
    ) -> dict:
        """Convert a natural language question to an OQL query."""
        type_descriptions = "\n".join([
            f"- {t['name']}: {t.get('description', '')} (fields: {', '.join(t.get('properties', {}).keys())})"
            for t in available_types
        ])

        prompt = f"""
Convert this natural language question to an coomia-dip OQL (Ontology Query Language) query:

Question: {question}

Available ObjectTypes:
{type_descriptions}

Relationships between types:
{json.dumps(context.get('relationships', []))}

Generate:
1. The OQL query
2. Explanation of what the query does
3. Expected result structure
4. Performance notes (e.g., missing indexes)
"""
        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:
        """Suggest query optimizations based on execution plan."""
        prompt = f"""
Given this OQL query and its execution plan, suggest optimizations:

Query: {query}

Execution Plan:
{json.dumps(explain_plan, indent=2)}

Suggest:
1. Index recommendations
2. Query rewrites for better performance
3. Caching opportunities
4. Partition pruning hints
"""
        return await self._llm.generate(prompt, temperature=0.2)

#四、AI 辅助异常诊断

#4.1 智能故障诊断

Python
class DiagnosticsAssistant:
    """AI assistant for diagnosing platform issues."""

    async def diagnose_error(
        self,
        error_message: str,
        error_context: dict,
    ) -> dict:
        """Diagnose an error and suggest fixes."""
        # 收集相关上下文
        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 the following error in an coomia-dip platform:

Error: {error_message}

Context:
- Layer: {error_context.get('Layer', 'unknown')}
- Operation: {error_context.get('operation', 'unknown')}
- Tenant: {error_context.get('tenant_id', 'unknown')}
- Timestamp: {error_context.get('timestamp', 'unknown')}

Related log entries (last 5 minutes):
{json.dumps(related_logs[:20], indent=2, default=str)}

Recent changes (last 24 hours):
{json.dumps(recent_changes[:10], indent=2, default=str)}

Provide:
1. Root cause analysis
2. Recommended fix steps
3. Prevention measures
4. 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:
        """Explain why a Saga failed in plain language."""
        saga = await self._saga_store.get(saga_id)
        events = await self._event_store.get_saga_events(saga_id)

        prompt = f"""
Explain why this Saga (distributed transaction) failed:

Saga: {saga.name}
Status: {saga.status}

Steps and their statuses:
{json.dumps([{"step": e.step_name, "status": e.action, "data": e.data} for e in events], indent=2)}

Explain in plain language:
1. What the Saga was trying to do
2. Which step failed and why
3. What compensation actions were taken
4. What the current state is
5. What manual actions (if any) are needed
"""
        return await self._llm.generate(prompt, temperature=0.3)

#五、AI Agent 自动化

#5.1 自动化工作流 Agent

Python
class AIWorkflowAgent:
    """AI Agent that can autonomously perform platform operations."""

    async def execute_task(
        self,
        task_description: str,
        permissions: list[str],
        sandbox_id: str | None = None,
    ) -> dict:
        """Execute a complex task using AI planning and execution."""
        # 在沙箱中执行(安全隔离)
        if sandbox_id:
            context = await self._sandbox_manager.get_context(sandbox_id)
        else:
            # 创建临时沙箱
            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),
                )
            )
            context = await self._sandbox_manager.get_context(sandbox.sandbox_id)

        # AI 规划执行步骤
        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 or sandbox.sandbox_id,
        }

    async def _plan_task(
        self, task_description: str, permissions: list[str]
    ) -> dict:
        """Use LLM to plan task execution steps."""
        prompt = f"""
Plan the execution steps for the following task on coomia-dip:

Task: {task_description}

Available permissions: {permissions}

Available operations:
- create_object_type(schema)
- update_object_type(type_id, changes)
- create_link_type(link_definition)
- register_action(action_definition)
- deploy_rule(rule_definition)
- execute_query(oql_query)
- create_sandbox(config)

Generate a step-by-step execution plan as JSON.
"""
        response = await self._llm.generate(prompt, temperature=0.2)
        return self._parse_plan(response)

#六、安全与治理

#6.1 AI 生成内容的审核

Python
class AIContentGovernance:
    """Governance for AI-generated content."""

    async def review_ai_output(
        self,
        output_type: str,
        content: dict,
        context: dict,
    ) -> dict:
        """Review AI-generated content before application."""
        review = {
            "approved": True,
            "warnings": [],
            "blocked_reasons": [],
        }

        # 检查是否包含敏感操作
        if output_type == "rule":
            if 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:
        """Check if AI-generated content references non-existent entities."""
        has_hallucinations = False
        details = []

        # 检查引用的 ObjectType 是否存在
        referenced_types = self._extract_type_references(content)
        existing_types = set(context.get("existing_types", []))
        non_existent = referenced_types - existing_types
        if non_existent:
            has_hallucinations = True
            details.append(f"Non-existent types: {non_existent}")

        return {"has_hallucinations": has_hallucinations, "details": details}

#6.2 AI 使用审计

Python
class AIUsageAudit:
    """Audit trail for AI-assisted operations."""

    async def log_ai_interaction(
        self,
        interaction_type: str,
        input_data: dict,
        output_data: dict,
        applied: bool,
        actor_id: str,
    ) -> None:
        """Log an AI interaction for audit purposes."""
        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,
                    "model_version": self._model_version,
                },
                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. 自然语言驱动:用业务语言描述需求,AI 翻译为平台操作,降低使用门槛
  2. 三种模式:Chat(探索)、Copilot(编码辅助)、Agent(自动化执行)
  3. 人机协作:AI 生成建议,人类审核确认,确保质量和安全
  4. 幻觉检测:自动检测 AI 生成内容中引用不存在实体的错误
  5. 沙箱隔离:AI Agent 在沙箱中执行操作,不影响生产环境
  6. 完整审计:所有 AI 交互记录可审计,满足合规要求

#Series Conclusion

本系列 15 篇文章从不同维度探讨了 coomia-dip 的设计模式:从 Ontology as API 的核心理念,到事件溯源、Saga、状态机等分布式模式,再到沙箱、联邦、级联等平台特有模式,最后到 AI 结对编程的前沿探索。这些模式共同构成了 coomia-dip 的设计哲学:用 Ontology 统一业务语义,用模式化设计降低系统复杂度,用 AI 赋能降低使用门槛

#Tags

#设计模式 #AI结对编程 #LLM #本体建模 #规则编写 #查询构建 #异常诊断 #Agent自动化 #治理审计