### Install Dependencies and Run BKN Editor (Bash) Source: https://github.com/kweaver-ai/bkn-specification/blob/main/bkn_editor/README.md Installs project dependencies using npm install and starts the development server with npm run dev. Assumes Node.js and npm are installed. ```bash npm install npm run dev ``` -------------------------------- ### Install BKN Python SDK Source: https://github.com/kweaver-ai/bkn-specification/blob/main/sdk/python/README.md Instructions for installing the BKN Python SDK using pip. Supports installation from the repository root, a specific path, or with optional kweaver API support. Requires Python 3.9+. ```bash # From repo root cd sdk/python pip install -e . # Or with path pip install -e path/to/bkn-specification/sdk/python # With kweaver API support pip install -e ".[api]" ``` -------------------------------- ### Install and Run Python SDK Tests Source: https://github.com/kweaver-ai/bkn-specification/blob/main/sdk/python/README.md This snippet details how to install the Python SDK with development dependencies and execute the test suite using pytest. Ensure you are in the 'sdk/python' directory before running these commands. This process verifies the functionality of the SDK. ```bash cd sdk/python pip install -e ".[dev]" python -m pytest tests/ -v ``` -------------------------------- ### Python BKN SDK Quick Example: Load and Transform Network Source: https://github.com/kweaver-ai/bkn-specification/blob/main/sdk/README.md A concise example demonstrating how to load a BKN network file using the Python SDK and transform it into JSON format or write it to files using KweaverTransformer. Requires the 'bkn' library. ```python from bkn import load_network from bkn.transformers import KweaverTransformer network = load_network("docs/examples/supplychain-hd/supplychain.bkn") transformer = KweaverTransformer(id_prefix="supplychain_") payload = transformer.to_json(network) # Get kweaver import JSON transformer.to_files(network, "output/") # Or write to files ``` -------------------------------- ### Install and Test Python BKN SDK Source: https://github.com/kweaver-ai/bkn-specification/blob/main/sdk/README.md Instructions for installing the Python BKN SDK locally using pip and running its test suite with pytest. This is essential for development and verifying SDK functionality. ```bash cd sdk/python pip install -e . python -m pytest tests/ -v ``` -------------------------------- ### Relation View Mapping Example Source: https://github.com/kweaver-ai/bkn-specification/blob/main/docs/SPECIFICATION.en.md Demonstrates a 'data_view' relation type, which associates entities through an intermediate view. This example defines a 'user_likes_post' relation using a view. ```markdown ## Relation: user_likes_post | Source | Target | Type | Required | Min | Max | |--------|--------|------|----------|-----|-----| | user | post | data_view | NO | 0 | - | ### Mapping View | Type | ID | |------|-----| | data_view | user_post_likes_view | ### Source Mapping | Source Property | View Property | |-----------------|---------------| | user_id | uid | ### Target Mapping | View Property | Target Property | |---------------|-----------------| | pid | post_id | ``` -------------------------------- ### BKN File Organization: One Definition per File Pattern Source: https://github.com/kweaver-ai/bkn-specification/blob/main/docs/SPECIFICATION.en.md Illustrates the 'One Definition per File' pattern for large networks, showing a directory structure and an example of a single entity file (`pod.bkn`). ```markdown --- type: entity id: pod name: Pod Instance network: k8s-network --- ## Entity: pod **Pod Instance** Minimal deployable unit in Kubernetes. ## Data Source | Type | ID | |------|-----| | data_view | view_123 | ## Data Properties | Property | Primary Key | Display Key | |----------|:-----------:|:-----------:| | id | YES | | | pod_name | | YES | ``` -------------------------------- ### BKN File Organization: Single File Pattern Source: https://github.com/kweaver-ai/bkn-specification/blob/main/docs/SPECIFICATION.en.md Markdown example demonstrating the 'Single File' pattern for small networks, where all definitions (network, entities, relations, actions) reside in a single `.bkn` file. ```markdown --- type: network id: my-network --- # My Network ## Entity: entity1 ... ## Entity: entity2 ... ## Relation: rel1 ... ## Action: action1 ... ``` -------------------------------- ### Patch Operation: Add (BKN) Source: https://github.com/kweaver-ai/bkn-specification/blob/main/docs/SPECIFICATION.en.md Illustrates how to use a 'patch' with an 'add' operation to insert new definitions or properties into an existing BKN file. This example adds a 'cpu_usage' metric to the 'pod' entity. ```markdown --- type: patch id: 2026-01-31-add-metric target: k8s-topology.bkn operation: add --- # Add CPU Metric Add after `### Logic Properties` in `## Entity: pod`: #### cpu_usage - **Type**: metric - **Source**: cpu_metric ``` -------------------------------- ### Relation Direct Mapping Example Source: https://github.com/kweaver-ai/bkn-specification/blob/main/docs/SPECIFICATION.en.md Illustrates a 'direct' relation type where entities are associated via property value matching. This example shows a 'pod_belongs_node' relation. ```markdown ## Relation: pod_belongs_node | Source | Target | Type | Required | Min | Max | |--------|--------|------|----------|-----|-----| | pod | node | direct | YES | 1 | 1 | Each Pod must belong to exactly one Node. ### Mapping Rules | Source Property | Target Property | |-----------------|-----------------| | pod_node_name | node_name | ``` -------------------------------- ### BKN Entity Definition Example Source: https://context7.com/kweaver-ai/bkn-specification/llms.txt Illustrates how to define an entity in BKN, including its metadata, data source, properties with constraints, property overrides for search configuration, and logic properties for computed fields. This example defines a 'service' entity. ```markdown ## Entity: service **Service** - Kubernetes service abstraction layer - **Tags**: networking, core - **Owner**: platform-team ### Data Source | Type | ID | Name | |------|-----|------| | data_view | view_789 | service_info_view | ### Data Properties | Property | Display Name | Type | Constraint | Description | Primary Key | Display Key | Index | |----------|--------------|------|------------|-------------|:-----------:|:-----------:|:-----:| | id | ID | int64 | not_null | Primary key | YES | | YES | | service_name | Name | VARCHAR | not_null; regex:^[a-z0-9-]+$ | Service name | | YES | YES | | service_type | Type | VARCHAR | in(ClusterIP,NodePort,LoadBalancer) | Service type | | | | | port | Port | int32 | range(1,65535) | Service port | | | | ### Property Override | Property | Display Name | Index Config | Constraint | Description | |----------|--------------|--------------|------------|-------------| | service_name | Name | keyword + fulltext(standard) | | Exact and fuzzy search | | description | Description | fulltext(ik_max_word) + vector(model_123) | | Full-text and semantic search | ### Logic Properties #### service_metrics - **Type**: metric - **Source**: prometheus (metric-model) - **Description**: Service monitoring metrics | Parameter | Type | Source | Binding | Description | |-----------|------|--------|---------|-------------| | service_id | int64 | property | id | Service primary key | | time_range | string | input | - | Query time range | | metric_name | string | const | request_rate | Metric to query | ``` -------------------------------- ### BKN Index Config Syntax Examples Source: https://context7.com/kweaver-ai/bkn-specification/llms.txt Illustrates different index configurations for properties, such as `keyword`, `fulltext`, and `vector`, including options for length limits and specific analyzers or models. This enables efficient searching and retrieval of data. ```yaml ### Property Override | Property | Index Config | Description | |----------|--------------|-------------| | name | keyword | Basic keyword index | | name | keyword(2048) | Keyword with max length | | description | fulltext | Full-text with default analyzer | | description | fulltext(ik_max_word) | Full-text with Chinese analyzer | | content | vector | Vector index with default model | | content | vector(model_123) | Vector with specific model ID | | title | keyword + fulltext(standard) | Combined keyword and full-text | | body | keyword(1024) + fulltext(standard) + vector(model_456) | All three index types | ``` -------------------------------- ### BKN File Organization: Split by Type Pattern Source: https://github.com/kweaver-ai/bkn-specification/blob/main/docs/SPECIFICATION.en.md Markdown example illustrating the 'Split by Type' pattern for medium networks. An `index.bkn` file includes definitions from other files like `entities.bkn`, `relations.bkn`, and `actions.bkn`. ```markdown --- type: network id: my-network includes: - entities.bkn - relations.bkn - actions.bkn --- # My Network Network description... ``` -------------------------------- ### Markdown Table Formatting Source: https://github.com/kweaver-ai/bkn-specification/blob/main/docs/SPECIFICATION.en.md Demonstrates standard Markdown table syntax for data representation. Includes an example for center alignment, often used for boolean values. ```markdown | Col1 | Col2 | Col3 | |------|------|------| | Val1 | Val2 | Val3 | ``` ```markdown | Col1 | Col2 | |------|:----:| | Val1 | YES | ``` -------------------------------- ### Patch Operation: Modify (BKN) Source: https://github.com/kweaver-ai/bkn-specification/blob/main/docs/SPECIFICATION.en.md Demonstrates using a 'patch' with a 'modify' operation to update specific parts of an existing definition. This example modifies the trigger condition for the 'restart_pod' action. ```markdown --- type: patch id: 2026-01-31-update-condition target: k8s-topology.bkn operation: modify --- # Update Trigger Condition Modify the trigger condition of `## Action: restart_pod` to: ```yaml field: pod_status operation: in value: [Unknown, Failed, CrashLoopBackOff] `` ` ``` -------------------------------- ### BKN Network File Structure Example Source: https://context7.com/kweaver-ai/bkn-specification/llms.txt Demonstrates the basic structure of a BKN network file, including YAML frontmatter for metadata and Markdown sections for defining the network, entities, relations, and actions. It shows how to include other BKN files. ```markdown --- type: network id: k8s-topology name: Kubernetes Topology Network version: 1.0.0 tags: [Kubernetes, topology, ops] description: Knowledge network for Kubernetes cluster topology includes: - entities.bkn - relations.bkn - actions.bkn --- # Kubernetes Topology Network Network description and overview... ## Entity: pod **Pod Instance** - Minimal deployable unit in Kubernetes ### Data Source | Type | ID | Name | |------|-----|------| | data_view | d2mio43q6gt6p380dis0 | pod_info_view | ### Data Properties | Property | Display Name | Type | Constraint | Description | Primary Key | Display Key | Index | |----------|--------------|------|------------|-------------|:-----------:|:-----------:|:-----:| | id | ID | int64 | | Primary key | YES | | YES | | pod_name | Pod Name | VARCHAR | not_null | Pod name | | YES | YES | | pod_status | Status | VARCHAR | in(Running,Pending,Failed,Unknown) | Pod status | | | YES | ## Relation: pod_belongs_node **Pod Belongs to Node** - Ownership relation between Pod and Node | Source | Target | Type | Required | Min | Max | |--------|--------|------|----------|-----|-----| | pod | node | direct | YES | 1 | 1 | ### Mapping Rules | Source Property | Target Property | |-----------------|-----------------| | pod_node_name | node_name | ## Action: restart_pod **Restart Pod** - Auto-restart pod when status is abnormal | Bound Entity | Action Type | |--------------|-------------| | pod | modify | ### Tool Configuration | Type | Tool ID | |------|---------| | tool | kubectl_delete_pod | ``` -------------------------------- ### Blockquote for Key Information Source: https://github.com/kweaver-ai/bkn-specification/blob/main/docs/SPECIFICATION.en.md Example of using Markdown blockquotes to highlight important notes or critical information, such as requirements for an entity. ```markdown > **Note**: This entity requires an approval workflow ``` -------------------------------- ### BKN Constraint Syntax Examples Source: https://context7.com/kweaver-ai/bkn-specification/llms.txt Demonstrates various constraint types for data properties, including `not_null`, regular expressions (`regex`), range checks (`range`), and enumerated values (`in`). These constraints ensure data integrity and validity. ```yaml ### Data Properties | Property | Type | Constraint | Description | |----------|------|------------|-------------| | id | int64 | not_null | Required field | | name | VARCHAR | not_null; regex:^[a-z0-9_]+$ | Lowercase alphanumeric | | quantity | int32 | >= 0 | Non-negative | | price | float64 | range(0,10000) | Price range 0-10000 | | status | VARCHAR | in(Active,Inactive,Archived) | Enum values | | priority | int32 | not_null; range(1,5) | Priority 1-5 | | score | float64 | >= 0; <= 100 | Percentage score | | code | VARCHAR | not_null; regex:^[A-Z]{3}$ | 3-letter code | ``` -------------------------------- ### BKN Relation Definition Example Source: https://context7.com/kweaver-ai/bkn-specification/llms.txt Shows how to define a relation between entities in BKN, specifying the source and target entities, relation type, cardinality (required, min, max), and mapping rules for properties between the source and target. This example defines a 'service_routes_pod' relation. ```markdown ## Relation: service_routes_pod **Service Routes to Pod** - Traffic routing from Service to Pod | Source | Target | Type | Required | Min | Max | |--------|--------|------|----------|-----|-----| | service | pod | direct | NO | 0 | - | ``` -------------------------------- ### Patch Operation: Delete (BKN) Source: https://github.com/kweaver-ai/bkn-specification/blob/main/docs/SPECIFICATION.en.md Shows how to use a 'patch' with a 'delete' operation to remove definitions or parts of definitions from a BKN file. This example deletes a deprecated action. ```markdown --- type: patch id: 2026-01-31-remove-action target: k8s-topology.bkn operation: delete --- # Delete Deprecated Action Delete `## Action: deprecated_action` ``` -------------------------------- ### Mermaid Diagram for Visualizing Relations Source: https://github.com/kweaver-ai/bkn-specification/blob/main/docs/SPECIFICATION.en.md Shows how to embed Mermaid diagrams in Markdown to visually represent relationships between elements, using a simple graph example. ```mermaid graph LR A --> B B --> C ``` -------------------------------- ### Access BKN entity and relation structure Source: https://github.com/kweaver-ai/bkn-specification/blob/main/sdk/python/README.md Provides examples of how to access the detailed structure of entities and relations within a loaded BKN network. It shows how to retrieve information about data sources, data properties, property overrides for entities, and endpoint and mapping rule details for relations. ```python entity = network.all_entities[0] print(entity.data_source.type, entity.data_source.id) for dp in entity.data_properties: print(dp.property, dp.type, dp.primary_key) for po in entity.property_overrides: print(po.property, po.index_config) # fulltext(standard) + vector(id) relation = network.all_relations[0] ep = relation.endpoints[0] print(ep.source, "->", ep.target, ep.type) for mr in relation.mapping_rules: print(mr.source_property, "->", mr.target_property) ``` -------------------------------- ### Import BKN network to Kweaver via API Source: https://github.com/kweaver-ai/bkn-specification/blob/main/sdk/python/README.md Details how to import a BKN network directly into the kweaver ontology-manager using the `KweaverClient`. This requires `pip install -e "[api]"` and involves configuring the client with API credentials and the network details. A dry-run option is available to perform transformations without API calls. ```python from bkn import load_network from bkn.transformers import KweaverClient, KweaverTransformer network = load_network("docs/examples/supplychain-hd/supplychain.bkn") client = KweaverClient( base_url="http://ontology-manager-svc:13014", account_id="your_account_id", account_type="your_account_type", business_domain="your_domain_id", ) transformer = KweaverTransformer(id_prefix="supplychain_") result = client.import_network(network, transformer) # result.knowledge_network_id -> created knowledge network ID # result.object_types_created -> number of object types created # result.relation_types_created -> number of relation types created # result.errors -> list of errors (if any) # result.success -> True if no errors # Dry-run mode (transform only, no API calls): result = client.import_network(network, transformer, dry_run=True) ``` -------------------------------- ### Transform BKN network to Kweaver JSON Source: https://github.com/kweaver-ai/bkn-specification/blob/main/sdk/python/README.md Illustrates transforming a loaded BKN network into a JSON format suitable for the kweaver ontology-manager API. It uses `KweaverTransformer` to convert the network and provides options to get the JSON as a dictionary or write it directly to files. ```python from bkn import load_network from bkn.transformers import KweaverTransformer network = load_network("docs/examples/supplychain-hd/supplychain.bkn") transformer = KweaverTransformer( branch="main", base_version="", id_prefix="supplychain_", # Entity/relation ID prefix, e.g. po -> supplychain_po ) # Get JSON dict payload = transformer.to_json(network) # payload["knowledge_network"] - Create knowledge network request body # payload["object_types"] - Object types (entities) list # payload["relation_types"] - Relation types list # Or write to files transformer.to_files(network, "output/") # Creates: output/knowledge_network.json, object_types.json, relation_types.json ``` -------------------------------- ### Import BKN to Kweaver API (Python) Source: https://context7.com/kweaver-ai/bkn-specification/llms.txt This Python snippet demonstrates importing BKN networks directly to the kweaver ontology-manager via HTTP API. It utilizes `KweaverClient` for API communication and `KweaverTransformer` for data transformation. The example shows how to perform a dry run before a full import, ensuring no changes are made during the initial test. ```python from bkn import load_network from bkn.transformers import KweaverClient, KweaverTransformer # Load network network = load_network("docs/examples/supplychain-hd/supplychain.bkn") # Create API client client = KweaverClient( base_url="http://ontology-manager-svc:13014", account_id="your_account_id", account_type="your_account_type", business_domain="your_domain_id", timeout=30 ) # Create transformer transformer = KweaverTransformer( branch="main", id_prefix="supplychain_" ) # Dry-run mode: transform only, no API calls dry_result = client.import_network(network, transformer, dry_run=True) print("Dry run completed - no changes made") # Full import to kweaver result = client.import_network(network, transformer) ``` -------------------------------- ### Access Aggregated Definitions from BKN Network (Python) Source: https://context7.com/kweaver-ai/bkn-specification/llms.txt This snippet demonstrates how to access and print aggregated definitions from a BKN network object. It shows how to get the total counts of entities, relations, and actions, and then iterate through all entities to print their IDs, data sources, data properties, property overrides, and logic properties. This requires a pre-loaded 'network' object. ```python print(f"Total entities: {len(network.all_entities)}") print(f"Total relations: {len(network.all_relations)}") print(f"Total actions: {len(network.all_actions)}") # Iterate over all entities from all included files for entity in network.all_entities: print(f"Entity: {entity.id}") # Access data source if entity.data_source: print(f" Source: {entity.data_source.type} / {entity.data_source.id}") # Access data properties for dp in entity.data_properties: flags = [] if dp.primary_key: flags.append("PRIMARY KEY") if dp.display_key: flags.append("DISPLAY KEY") if dp.index: flags.append("INDEX") print(f" {dp.property}: {dp.type} {' '.join(flags)}") # Access property overrides for po in entity.property_overrides: print(f" Override {po.property}: {po.index_config}") # Access logic properties for lp in entity.logic_properties: print(f" Logic: {lp.name} ({lp.lp_type})") for param in lp.parameters: print(f" - {param.parameter}: {param.source} -> {param.binding}") ``` -------------------------------- ### Batch Import Fragment (BKN) Source: https://github.com/kweaver-ai/bkn-specification/blob/main/docs/SPECIFICATION.en.md Demonstrates how to import a 'fragment' which can contain multiple definitions like entities and actions. This is useful for organizing related components into a single importable unit. ```markdown --- type: fragment id: monitoring-extension name: Monitoring Extension network: k8s-network --- # Monitoring Extension Add monitoring-related entities and actions. ## Entity: alert **Alert** ### Data Source | Type | ID | |------|-----| | data_view | alert_view | ### Data Properties | Property | Primary Key | Display Key | |----------|:-----------:|:-----------:| | id | YES | | | alert_name | | YES | --- ## Action: send_alert **Send Alert** | Bound Entity | Action Type | |--------------|-------------| | alert | add | ### Tool Configuration | Type | Tool ID | |------|---------| | tool | alert_sender | ``` -------------------------------- ### Add New Entity Definition (BKN) Source: https://github.com/kweaver-ai/bkn-specification/blob/main/docs/SPECIFICATION.en.md Demonstrates how to define and import a new entity into an existing network. This involves specifying the entity's type, ID, name, and network, along with its data sources and properties. ```markdown --- type: entity id: deployment name: Deployment network: k8s-network --- ## Entity: deployment **Deployment** Kubernetes deployment controller. ## Data Source | Type | ID | |------|-----| | data_view | deployment_view | ## Data Properties | Property | Primary Key | Display Key | |----------|:-----------:|:-----------:| | id | YES | | | deployment_name | | YES | ``` -------------------------------- ### Load a BKN network with includes Source: https://github.com/kweaver-ai/bkn-specification/blob/main/sdk/python/README.md Shows how to load an entire BKN network, including files referenced via `includes`, using the `load_network` function. It demonstrates accessing the root frontmatter name and the total counts of entities, relations, and actions within the network. ```python from bkn import load_network network = load_network("docs/examples/supplychain-hd/supplychain.bkn") print(network.root.frontmatter.name) # HD供应链业务知识网络_v2 print(len(network.all_entities)) # 12 print(len(network.all_relations)) # 14 print(len(network.all_actions)) # 0 ``` -------------------------------- ### Python SDK: Load Network with Includes Source: https://context7.com/kweaver-ai/bkn-specification/llms.txt Demonstrates how to use the BKN Python SDK to load an entire network, including all recursively included files. It shows how to access the root document and count the total number of included files. ```python from bkn import load_network # Load network with all includes resolved network = load_network("docs/examples/k8s-network/index.bkn") # Access root document print(f"Network: {network.root.frontmatter.name}") print(f"Includes: {len(network.includes)} files") ``` -------------------------------- ### Action Definition Syntax Source: https://github.com/kweaver-ai/bkn-specification/blob/main/docs/SPECIFICATION.en.md Outlines the structure for defining actions, including their ID, display name, bound entity, action type, trigger conditions, pre-conditions, tool configuration, parameter binding, and schedule. ```markdown ## Action: {action_id} **{Display Name}** - {Brief description} | Bound Entity | Action Type | |--------------|--------------| | {entity_id} | add | modify | delete | ### Trigger Condition ```yaml field: {property_name} operation: == | != | > | < | >= | <= | in | not_in | exist | not_exist value: {value} ``` ### Pre-conditions (Optional) Data conditions required before execution; if not satisfied, action is blocked | Entity | Check | Condition | Message | |--------|-------|-----------|---------| | {entity_id} | relation:{relation_id} | exist | Violation message | | {entity_id} | property:{property_name} | {op} {value} | Violation message | - `Check`: `property:{name}` or `relation:{id}`, specifies what to check - `Condition`: Reuses Trigger Condition operator syntax - Trigger determines "when to run"; Pre-conditions determine "whether execution is allowed" ### Tool Configuration | Type | Tool ID | |------|--------| | tool | {tool_id} | or | Type | MCP | |------|-----| | mcp | {mcp_id}/{tool_name} | ### Parameter Binding | Parameter | Type | Source | Binding | Description | |-----------|------|--------|---------|-------------| | {param_name} | string | property | {property_name} | {description} | | {param_name} | string | input | - | {description} | | {param_name} | string | const | {value} | {description} | ### Schedule Configuration (Optional) | Type | Expression | |------|------------| | FIX_RATE | {interval} | | CRON | {cron_expr} | ### Execution Description (Optional) Detailed execution flow... ``` -------------------------------- ### Python SDK: Load and Parse Single BKN File Source: https://context7.com/kweaver-ai/bkn-specification/llms.txt Demonstrates how to use the BKN Python SDK to load a single BKN file. It shows how to access the file's frontmatter (type, ID, name, version, tags), entities, relations, and actions. ```python from bkn import load # Load a single BKN file doc = load("docs/examples/k8s-topology.bkn") # Access frontmatter metadata print(f"Type: {doc.frontmatter.type}") # network print(f"ID: {doc.frontmatter.id}") # k8s-topology print(f"Name: {doc.frontmatter.name}") # Kubernetes拓扑网络 print(f"Version: {doc.frontmatter.version}") # 1.0.0 print(f"Tags: {doc.frontmatter.tags}") # ['Kubernetes', '拓扑架构', '运维'] # Access entities print(f"Entities: {len(doc.entities)}") for entity in doc.entities: print(f" - {entity.id}: {entity.name}") print(f" Data source: {entity.data_source.id if entity.data_source else 'None'}") print(f" Properties: {len(entity.data_properties)}") for dp in entity.data_properties: pk = "PK" if dp.primary_key else "" dk = "DK" if dp.display_key else "" print(f" {dp.property}: {dp.type} {pk} {dk}") # Access relations print(f"Relations: {len(doc.relations)}") for rel in doc.relations: if rel.endpoints: ep = rel.endpoints[0] print(f" - {rel.id}: {ep.source} -> {ep.target} ({ep.type})") # Access actions print(f"Actions: {len(doc.actions)}") for action in doc.actions: print(f" - {action.id}: {action.action_type} on {action.bound_entity}") ``` -------------------------------- ### Parse a single BKN file Source: https://github.com/kweaver-ai/bkn-specification/blob/main/sdk/python/README.md Demonstrates how to parse a single BKN file using the `load` function from the `bkn` library. It shows how to access the document's frontmatter type and iterate through its entities, printing their IDs, names, and the number of properties. ```python from bkn import load doc = load("docs/examples/supplychain-hd/entities.bkn") print(doc.frontmatter.type) # fragment print(len(doc.entities)) # 12 for e in doc.entities: print(e.id, e.name, len(e.data_properties), "properties") ``` -------------------------------- ### Update Existing Entity Definition (BKN) Source: https://github.com/kweaver-ai/bkn-specification/blob/main/docs/SPECIFICATION.en.md Illustrates how to update an existing entity definition by importing a new file with the same entity ID. The import process will overwrite the old definition with the new one. ```markdown --- type: entity id: pod name: Pod Instance (Updated) network: k8s-network --- ## Entity: pod **Pod Instance (Updated)** Updated definition... ``` -------------------------------- ### Parse BKN content from a string Source: https://github.com/kweaver-ai/bkn-specification/blob/main/sdk/python/README.md Demonstrates parsing BKN content directly from a string using the `parse` function. This is useful for dynamic generation or when BKN content is not stored in a file. It shows how to parse the entire document or specific parts like frontmatter and body. ```python from bkn import parse, parse_frontmatter, parse_body text = """ --- type: entity id: my_entity name: My Entity --- ## Entity: my_entity **My Entity** - Example entity ### Data Source | Type | ID | Name | |------|-----|------| | data_view | 123 | my_view | ### Data Properties | Property | Display Name | Type | Primary Key | Display Key | |----------|--------------|------|:-----------:|:-----------:| | id | ID | int64 | YES | | | name | Name | VARCHAR | | YES | """ doc = parse(text) ``` -------------------------------- ### Entity Definition Syntax (Markdown) Source: https://github.com/kweaver-ai/bkn-specification/blob/main/docs/SPECIFICATION.en.md Defines the structure for an entity within the BKN specification using Markdown. It includes fields for entity ID, display name, description, tags, owner, data source, and data properties. ```markdown ## Entity: {entity_id} **{Display Name}** - {Brief description} - **Tags**: {tag1}, {tag2} (optional, definition-level tags) - **Owner**: {owner} (optional, owner/team) ### Data Source | Type | ID | Name | |------|-----|------| | data_view | {view_id} | {view_name} | ### Data Properties | Property | Display Name | Type | Constraint | Description | Primary Key | Display Key | Index | |----------|--------------|------|------------|-------------|:-----------:|:-----------:|:-----:| | {prop} | {name} | {type} | | {desc} | YES | | YES | | {prop} | {name} | {type} | | {desc} | | YES | | - `Primary Key`: Property marked `YES` uniquely identifies an instance; at least one required - `Display Key`: Property marked `YES` is used for UI display and search; at least one required - `Constraint` column is optional; declares valid value ranges for instance data. Leave empty for no constraint. See "Constraint Column Syntax" below for details ### Property Override (Optional) Declare only properties needing special configuration | Property | Display Name | Index Config | Constraint | Description | |----------|--------------|--------------|------------|-------------| | ... | ... | ... | ... | ... | ``` -------------------------------- ### Define Action: Restart Pod with Kubectl Source: https://context7.com/kweaver-ai/bkn-specification/llms.txt Defines an action to restart a pod using the 'kubectl_delete_pod' tool. It includes trigger conditions based on pod status, pre-conditions related to scheduling and restart count, and parameter binding for pod name, namespace, grace period, and force flag. ```yaml condition: object_type_id: pod field: pod_status operation: in value: - Unknown - Failed - CrashLoopBackOff --- # Pre-conditions # Pod must be scheduled to a Node # Restart limit not exceeded --- # Scope of Impact # Delete and recreate Pod --- # Tool Configuration tool: kubectl_delete_pod --- # Parameter Binding parameter: pod: string source: property binding: pod_name namespace: string source: property binding: pod_namespace grace_period: number source: const binding: 30 force: boolean source: input --- # Schedule expression: 5m ``` -------------------------------- ### Network File Definition (YAML) Source: https://github.com/kweaver-ai/bkn-specification/blob/main/docs/SPECIFICATION.en.md Defines a full knowledge network, including its ID, name, version, tags, description, and included files. This is a foundational file for organizing knowledge networks. ```yaml --- type: network # Full knowledge network id: string # Network ID, unique identifier name: string # Network display name version: string # Version (semver) tags: [string] # Optional, tag list description: string # Optional, network description includes: [string] # Optional, referenced files --- ``` -------------------------------- ### BKN Importer Capability Requirements Source: https://github.com/kweaver-ai/bkn-specification/blob/main/docs/SPECIFICATION.en.md Markdown table detailing the required capabilities for a BKN Importer, including validation, diffing, dry runs, applying changes, and exporting the network state. Each capability has a description and purpose. ```markdown | Capability | Description | Purpose | |------------|-------------|---------| | `validate` | Structure/table/YAML block validation, reference integrity, parameter binding check | Prevent errors from entering the system | | `diff` | Compute change set (add/update/delete) and impact scope | Make changes explainable and auditable | | `dry_run` | Execute validate + diff without applying | Pre-deployment rehearsal | | `apply` | Execute changes (per deterministic semantics and conflict strategy) | Controlled execution | | `export` | Export knowledge network state to BKN (round-trip capable) | Prevent drift, rollback, reproducibility | ``` -------------------------------- ### Single Action File Definition (YAML) Source: https://github.com/kweaver-ai/bkn-specification/blob/main/docs/SPECIFICATION.en.md Defines a single action within a network. This includes action type, version, network reference, and optional fields for namespace, owner, enablement status, risk level, and approval requirements. ```yaml --- type: action # Single action definition id: string # Action ID, unique identifier name: string # Action display name action_type: add | modify | delete # Action type version: string # Optional, version network: string # Network ID (recommended required for import determinism) namespace: string # Optional, namespace/package owner: string # Optional, owner/team enabled: boolean # Optional, whether enabled (default false recommended) risk_level: low | medium | high # Optional, risk level requires_approval: boolean # Optional, whether approval required --- ``` -------------------------------- ### Relation Definition Syntax Source: https://github.com/kweaver-ai/bkn-specification/blob/main/docs/SPECIFICATION.en.md Provides the general syntax for defining relations between entities. It includes fields for relation ID, display name, tags, owner, source, target, type, and cardinality constraints. ```markdown ## Relation: {relation_id} **{Display Name}** - {Brief description} - **Tags**: {tag1}, {tag2} (optional, definition-level tags) - **Owner**: {owner} (optional, owner/team) | Source | Target | Type | Required | Min | Max | |--------|--------|------|----------|-----|-----| | {source_entity} | {target_entity} | direct \| data_view | YES \| NO | 0 | - | - `Required`: YES/NO, whether at least one relation must exist (from Source side) - `Min`: Minimum relation count, default 0 - `Max`: Maximum relation count, `-` means unlimited - Required / Min / Max are optional columns; omit to apply no constraint ### Mapping Rules | Source Property | Target Property | |-----------------|-----------------| | {source_prop} | {target_prop} | ### Business Semantics (Optional) Description of relation business meaning... ``` -------------------------------- ### Single Entity File Definition (YAML) Source: https://github.com/kweaver-ai/bkn-specification/blob/main/docs/SPECIFICATION.en.md Defines a single entity within a network. It includes an ID, name, version, and references the network it belongs to. Optional fields for namespace and owner are also supported. ```yaml --- type: entity # Single entity definition id: string # Entity ID, unique identifier name: string # Entity display name version: string # Optional, version network: string # Network ID (recommended required for import determinism) namespace: string # Optional, namespace/package owner: string # Optional, owner/team tags: [string] # Optional, tag list --- ``` -------------------------------- ### Parse BKN Content from String (Python) Source: https://context7.com/kweaver-ai/bkn-specification/llms.txt This Python snippet shows how to parse BKN content directly from a string using the `bkn` SDK. It demonstrates parsing the complete document, only the frontmatter, and only the body (entities, relations, actions). This is useful when BKN content is available as a string rather than a file. ```python from bkn import parse, parse_frontmatter, parse_body bkn_content = """ --- type: entity id: deployment name: Deployment network: k8s-network namespace: platform.k8s owner: ops-team tags: [workload, controller] --- ## Entity: deployment **Deployment** - Kubernetes deployment controller ### Data Source | Type | ID | Name | |------|-----|------| | data_view | deployment_view | Deployment View | ### Data Properties | Property | Display Name | Type | Primary Key | Display Key | |----------|--------------|------|:-----------:|:-----------:| | id | ID | int64 | YES | | | name | Name | VARCHAR | | YES | | replicas | Replicas | int32 | | | | strategy | Strategy | VARCHAR | | | """ # Parse complete document doc = parse(bkn_content) print(f"Type: {doc.frontmatter.type}") # entity print(f"Entity: {doc.entities[0].id}") # deployment # Parse only frontmatter fm = parse_frontmatter(bkn_content) print(f"Namespace: {fm.namespace}") # platform.k8s print(f"Owner: {fm.owner}") # ops-team # Parse only body (entities, relations, actions) entities, relations, actions = parse_body(bkn_content) print(f"Parsed {len(entities)} entities") ``` -------------------------------- ### Mixed Fragment File Definition (YAML) Source: https://github.com/kweaver-ai/bkn-specification/blob/main/docs/SPECIFICATION.en.md Defines a mixed fragment, used for grouping various elements. It requires an ID, name, and target network ID. Namespace and owner are optional. ```yaml --- type: fragment # Mixed fragment id: string # Fragment ID name: string # Fragment name version: string # Optional, version network: string # Target network ID (recommended required for import determinism) namespace: string # Optional, namespace/package owner: string # Optional, owner/team --- ``` -------------------------------- ### Transform BKN to Kweaver JSON (Python) Source: https://context7.com/kweaver-ai/bkn-specification/llms.txt This Python snippet demonstrates transforming loaded BKN network data into JSON payloads compatible with the kweaver ontology-manager API. It uses the `KweaverTransformer` class, allowing configuration of branch, base version, and ID prefixes. The output can be accessed as a dictionary or written to separate JSON files. ```python from bkn import load_network from bkn.transformers import KweaverTransformer # Load network network = load_network("docs/examples/supplychain-hd/supplychain.bkn") # Create transformer with options transformer = KweaverTransformer( branch="main", # Target branch name base_version="", # Base version string id_prefix="supplychain_" # Prefix for entity/relation IDs ) # Transform to JSON dict payload = transformer.to_json(network) # Access transformed payloads knowledge_network = payload["knowledge_network"] print(f"Network name: {knowledge_network['name']}") print(f"Branch: {knowledge_network['branch']}") object_types = payload["object_types"] print(f"Object types: {len(object_types)}") for ot in object_types: print(f" - {ot['id']}: {ot['name']}") print(f" Primary keys: {ot['primary_keys']}") print(f" Display key: {ot['display_key']}") relation_types = payload["relation_types"] print(f"Relation types: {len(relation_types)}") for rt in relation_types: print(f" - {rt['id']}: {rt.get('source_object_type_id')} -> {rt.get('target_object_type_id')}") # Write to separate JSON files created_files = transformer.to_files(network, "output/") # Creates: output/knowledge_network.json, output/object_types.json, output/relation_types.json print(f"Created files: {[str(f) for f in created_files]}") ``` -------------------------------- ### Delete Definition (BKN) Source: https://github.com/kweaver-ai/bkn-specification/blob/main/docs/SPECIFICATION.en.md Shows how to explicitly delete definitions (entities, relations, etc.) using the `type: delete` directive. This is used for cleaning up unused or deprecated definitions. ```markdown --- type: delete network: k8s-network targets: - entity: deprecated_entity - relation: old_relation --- # Delete Deprecated Definitions Clean up unused definitions. ``` -------------------------------- ### BKN Network Definition: Single File Source: https://context7.com/kweaver-ai/bkn-specification/llms.txt Defines a simple network named 'Simple Network' with two entities, 'user' and 'post', and a relation 'user_creates_post'. This format is suitable for small networks where all definitions can be contained within a single BKN file. ```yaml --- type: network id: simple-network name: Simple Network version: 1.0.0 --- # Simple Network ## Entity: user **User** - Application user ### Data Properties | Property | Primary Key | Display Key | |----------|:-----------:|:-----------:| | id | YES | | | username | | YES | --- ## Entity: post **Post** - User post ### Data Properties | Property | Primary Key | Display Key | |----------|:-----------:|:-----------:| | id | YES | | | title | | YES | --- ## Relation: user_creates_post | Source | Target | Type | |--------|--------|------| | user | post | direct | ### Mapping Rules | Source Property | Target Property | |-----------------|-----------------| | id | author_id | ``` -------------------------------- ### BKN Network Definition: One Definition per File Source: https://context7.com/kweaver-ai/bkn-specification/llms.txt Defines a modular Kubernetes network ('k8s-modular') by including individual files for each definition, such as entities, relations, and actions. This approach is recommended for large networks to facilitate collaboration and maintainability. ```yaml --- type: network id: k8s-modular name: Kubernetes Modular includes: - entities/pod.bkn - entities/node.bkn - relations/pod_belongs_node.bkn - actions/restart_pod.bkn --- ``` ```yaml --- type: entity id: pod name: Pod Instance network: k8s-modular namespace: platform.k8s owner: platform-team --- ## Entity: pod **Pod Instance** - Minimal deployable unit ### Data Source | Type | ID | |------|-----| | data_view | view_123 | ### Data Properties | Property | Primary Key | Display Key | |----------|:-----------:|:-----------:| | id | YES | | | pod_name | | YES | ``` -------------------------------- ### Entity Service Definition Source: https://github.com/kweaver-ai/bkn-specification/blob/main/docs/SPECIFICATION.en.md Defines an entity named 'service' with its data source and properties. It specifies property types, constraints, and indexing for search capabilities. ```markdown ## Entity: service **Service** ### Data Source | Type | ID | |------|-----| | data_view | view_789 | ### Data Properties | Property | Display Name | Type | Constraint | Description | Primary Key | Display Key | Index | |----------|--------------|------|------------|-------------|:-----------:|:-----------:|:-----:| | id | ID | int64 | | Primary key | YES | | YES | | service_name | Name | VARCHAR | not_null | Service name | | YES | YES | | service_type | Service Type | VARCHAR | in(ClusterIP,NodePort,LoadBalancer) | Service type | | | | ``` -------------------------------- ### Single Relation File Definition (YAML) Source: https://github.com/kweaver-ai/bkn-specification/blob/main/docs/SPECIFICATION.en.md Defines a single relation within a network. Similar to entity definition, it includes an ID, name, version, and network reference. Namespace and owner are optional. ```yaml --- type: relation # Single relation definition id: string # Relation ID, unique identifier name: string # Relation display name version: string # Optional, version network: string # Network ID (recommended required for import determinism) namespace: string # Optional, namespace/package owner: string # Optional, owner/team --- ``` -------------------------------- ### Define Action: Cordon Node with MCP Tool Source: https://context7.com/kweaver-ai/bkn-specification/llms.txt Defines an action to cordon a node (mark as unschedulable) using an MCP tool. The trigger condition is when the node status is 'NotReady'. It binds the node name as a parameter. ```yaml condition: object_type_id: node field: node_status operation: == value: NotReady --- # Tool Configuration mcp: kubernetes-mcp/cordon_node --- # Parameter Binding parameter: node: string source: property binding: node_name ```