Skip to main content

High-performance asynchronous behavior tree framework with behavior forest collaboration,

Project description

๐Ÿš€ ABTree

Asynchronous behavior tree framework built on Python asyncio, designed for intelligent decision systems with declarative programming paradigm

PythonLicense StarsForks

ไธญๆ–‡ | English


๐Ÿ“‘ Table of Contents


โœจ Core Features

๐Ÿš€ Async Engine ๐ŸŽฏ Node System ๐Ÿ’พ Data Management ๐ŸŒฒ Behavior Forest
Based on asyncio
High Performance Concurrency
Rich Node Types
Dynamic Registration
Blackboard System
Event Driven
Multi-tree Collaboration
Internal Communication Modes

โšก Asynchronous Behavior Tree Engine

  • High Performance Async Execution - Concurrent node scheduling based on Python asyncio
  • Smart Tick Management - Automated execution cycle management and resource control
  • Event Driven Architecture - Asynchronous event system supporting real-time response
  • Memory Optimization - Efficient state management and garbage collection

๐ŸŽฏ Rich Node System

  • Composite Nodes - Sequence, Selector, Parallel and other classic control flows
  • Decorator Nodes - Inverter, Repeater, UntilSuccess and other behavior modifiers
  • Action Nodes - Action, Log, Wait, SetBlackboard and other execution units
  • Condition Nodes - Condition, CheckBlackboard, Compare and other judgment logic
  • Dynamic Registration - Runtime node type registration and extension mechanism

๐Ÿ’พ Smart Data Management

  • Blackboard System - Cross-node data sharing and state persistence
  • Event System - Asynchronous event listening, publishing and subscription mechanism
  • State Management - Complete tracking of behavior tree execution state
  • Data Validation - Type-safe data access and modification

๐ŸŒฒ Behavior Forest Collaboration

  • Multi-tree Coordination - Multiple behavior trees working together as a forest
  • Communication Modes - Pub/Sub, Req/Resp, Shared Blackboard, State Monitoring, Behavior Invocation, Task Board
  • Forest Management - Centralized forest configuration and lifecycle management
  • Performance Monitoring - Real-time performance analysis and optimization suggestions

๐ŸŽฌ Quick Start

๐Ÿ”ง Environment Setup

# Clone repository
git clone https://github.com/xiongwc/abtree.git
cd abtree

# Install dependencies
pip install -e .

๐Ÿ“ Basic Usage

๐Ÿš€ Method 1: Programmatic Building

import asyncio
from abtree import BehaviorTree, Sequence, Selector, Action, Condition
from abtree.core import Status

# Define action nodes
class OpenDoor(Action):
    async def execute(self, blackboard):
        print("Opening door")
        return Status.SUCCESS

class CloseDoor(Action):
    async def execute(self, blackboard):
        print("Closing door")
        return Status.SUCCESS

# Define condition nodes
class IsDoorOpen(Condition):
    async def evaluate(self, blackboard):
        return blackboard.get("door_open", False)

# Build behavior tree
root = Selector("Robot Decision")
root.add_child(Sequence("Door Control Sequence"))
root.children[0].add_child(IsDoorOpen("Check Door Status"))
root.children[0].add_child(CloseDoor("Close Door"))

# Create behavior tree instance
tree = BehaviorTree()
tree.load_from_node(root)

# Execute
async def main():
    blackboard = tree.blackboard
    blackboard.set("door_open", True)
    
    result = await tree.tick()
    print(f"Execution result: {result}")

asyncio.run(main())

๐Ÿ“„ Method 2: Declarative XML Configuration

import asyncio
from abtree import load_from_xml_string

# Declarative XML: Express behavior logic in a readable, structured format
xml_string = '''<BehaviorTree name="Robot Decision">
    <Selector name="Robot Decision">
        <Sequence name="Door Control Sequence">
            <CheckBlackboard name="Check Door Status" key="door_open" expected_value="true" />
            <Log name="Close Door Log" message="Door detected open, preparing to close" />
            <Wait name="Close Door Wait" duration="1.0" />
        </Sequence>
    </Selector>
</BehaviorTree>'''

# Load behavior tree from declarative XML configuration
tree = load_from_xml_string(xml_string)

# Execute
async def main():
    blackboard = tree.blackboard
    blackboard.set("door_open", True)
    
    result = await tree.tick()
    print(f"Execution result: {result}")

asyncio.run(main())

๐ŸŒฒ Behavior Forest Example

import asyncio
from abtree import (
    BehaviorForest, ForestNode, ForestNodeType,
    PubSubMiddleware, SharedBlackboardMiddleware,
    BehaviorTree, Sequence, Selector, Action, Condition
)
from abtree.core import Status

# Simple robot action node
class RobotAction(Action):
    def __init__(self, name: str, action_type: str):
        super().__init__(name)
        self.action_type = action_type
    
    async def execute(self, blackboard):
        print(f"Robot {self.action_type}")
        if self.action_type == "cleaning":
            blackboard.set("cleaning_needed", False)
        return Status.SUCCESS

# Simple condition node
class SimpleCondition(Condition):
    def __init__(self, name: str, key: str, default: bool = True):
        super().__init__(name)
        self.key = key
        self.default = default
    
    async def evaluate(self, blackboard):
        return blackboard.get(self.key, self.default)

def create_robot_tree(robot_id: str) -> BehaviorTree:
    """Create a simple robot behavior tree"""
    root = Selector(f"Robot_{robot_id}")
    
    # Cleaning sequence
    cleaning_seq = Sequence("Cleaning")
    cleaning_seq.add_child(SimpleCondition("Check Cleaning", "cleaning_needed"))
    cleaning_seq.add_child(RobotAction("Clean", "cleaning"))
    cleaning_seq.add_child(RobotAction("Navigate", "navigating"))
    root.add_child(cleaning_seq)
    
    tree = BehaviorTree()
    tree.load_from_node(root)
    return tree

async def main():
    # Create behavior forest
    forest = BehaviorForest("Robot Forest")
    
    # Add middleware
    forest.add_middleware(PubSubMiddleware("PubSub"))
    forest.add_middleware(SharedBlackboardMiddleware("Shared Blackboard"))
    
    # Add robot nodes
    for robot_id in ["R1", "R2", "R3"]:
        tree = create_robot_tree(robot_id)
        node = ForestNode(
            name=f"Robot_{robot_id}",
            tree=tree,
            node_type=ForestNodeType.WORKER,
            capabilities={"cleaning", "navigation"}
        )
        forest.add_node(node)
    
    # Start forest
    await forest.start()
    
    # Execute ticks
    for i in range(3):
        results = await forest.tick()
        print(f"Tick {i+1}: {results}")
        await asyncio.sleep(0.5)
    
    await forest.stop()

if __name__ == "__main__":
    asyncio.run(main())

๐Ÿ“– Documentation

๐Ÿ“ Project Structure

abtree/
โ”œโ”€โ”€ abtree/                     # ๐Ÿ“ฆ Core package
โ”‚   โ”œโ”€โ”€ core/                   # ๐Ÿ”ง Core functionality
โ”‚   โ”œโ”€โ”€ engine/                 # โš™๏ธ Engine system
โ”‚   โ”œโ”€โ”€ forest/                 # ๐ŸŒฒ Behavior forest
โ”‚   โ”œโ”€โ”€ nodes/                  # ๐ŸŽฏ Node implementations
โ”‚   โ”œโ”€โ”€ parser/                 # ๐Ÿ“ Configuration parsing
โ”‚   โ”œโ”€โ”€ registry/               # ๐Ÿ“‹ Node registration
โ”‚   โ””โ”€โ”€ utils/                  # ๐Ÿ”ง Utilities
โ”œโ”€โ”€ cli/                        # ๐Ÿ–ฅ๏ธ Command line tools
โ”œโ”€โ”€ docs/                       # ๐Ÿ“– Documentation
โ”œโ”€โ”€ examples/                   # ๐Ÿ“š Example code
โ”œโ”€โ”€ tests/                      # ๐Ÿงช Test suite
โ”œโ”€โ”€ scripts/                    # ๐Ÿ“œ Script tools
โ”œโ”€โ”€ test_reports/               # ๐Ÿ“Š Test reports
โ””โ”€โ”€ pyproject.toml              # โš™๏ธ Build and dependency configuration

๐Ÿ”ง Technology Stack

Component Technology Version
Language Python 3.8+
Async Framework asyncio Built-in
Data Validation Pydantic 2.0+
XML Processing xml.etree Built-in
Testing pytest 7.0+
Type Checking mypy 1.0+

๐Ÿ“‹ Code Standards

  • Follow PEP 8 coding standards
  • Use Google style docstrings
  • Add type annotations for all functions
  • Write unit tests for key functionality

๐Ÿ—บ๏ธ Roadmap

  • โœ… v0.1 - Core asynchronous behavior tree framework
  • โœ… v0.2 - XML configuration support
  • โœ… v0.3 - Event system and blackboard optimization
  • ๐ŸŽฏ v0.4 - Advanced node types

๐Ÿค Contributing

  1. Fork the project repository
  2. Create a feature branch (git checkout -b feature/amazing-feature)
  3. Commit your changes (git commit -m 'Add some amazing feature')
  4. Push to the branch (git push origin feature/amazing-feature)
  5. Open a Pull Request

๐Ÿ™ Acknowledgments

Inspiration from BehaviorTree.CPP.


๐Ÿ“œ License

This project is licensed under the MIT License.


โญ If this project helps you, please give us a Star to support development! โญ

GitHub DiscussionsGitHub IssuesGitHub Pull Requests

Project details


Download files

Download the file for your platform. If you're not sure which to choose, learn more about installing packages.

Source Distribution

abtree-0.3.1.tar.gz (68.6 kB view details)

Uploaded Source

Built Distribution

If you're not sure about the file name format, learn more about wheel file names.

abtree-0.3.1-py3-none-any.whl (67.3 kB view details)

Uploaded Python 3

File details

Details for the file abtree-0.3.1.tar.gz.

File metadata

  • Download URL: abtree-0.3.1.tar.gz
  • Upload date:
  • Size: 68.6 kB
  • Tags: Source
  • Uploaded using Trusted Publishing? No
  • Uploaded via: twine/6.1.0 CPython/3.11.13

File hashes

Hashes for abtree-0.3.1.tar.gz
Algorithm Hash digest
SHA256 6f9dd3b0958db584c0ca82a5dd34217d2e34bfd66f28f1829ab1b4a3c2a4eb51
MD5 38809e28c157f62d5f214f815ed30844
BLAKE2b-256 292f4f7c2d4bc870d1978591ebde24a90061fa9a90e5ab5291746596c8b52b99

See more details on using hashes here.

File details

Details for the file abtree-0.3.1-py3-none-any.whl.

File metadata

  • Download URL: abtree-0.3.1-py3-none-any.whl
  • Upload date:
  • Size: 67.3 kB
  • Tags: Python 3
  • Uploaded using Trusted Publishing? No
  • Uploaded via: twine/6.1.0 CPython/3.11.13

File hashes

Hashes for abtree-0.3.1-py3-none-any.whl
Algorithm Hash digest
SHA256 01d5dd5ea5da8d5becd7794db91475e11f4bc9783ee2c86310b6f7292378c1a8
MD5 16953b599759774c2c9dabc331c8884c
BLAKE2b-256 9e38ee88dec2cd567fc8824082ffe4bf2601a0dde368be974266acd0cf781e00

See more details on using hashes here.

Supported by

AWS Cloud computing and Security Sponsor Datadog Monitoring Depot Continuous Integration Fastly CDN Google Download Analytics Pingdom Monitoring Sentry Error logging StatusPage Status page