Skip to main content

Akr Agent - A flexible rule-based AI Agent framework

Project description

AKR-Agent: Agent Know Rules

PyPI version Python Version License: MIT

AKR-Agent is a flexible rule-based AI Agent framework, designed to help developers quickly build and deploy intelligent agents. The framework supports dynamic rule configuration, tool registration, and context management, making it easy for developers to create various types of intelligent agent applications.

Installation

pip install akr-agent

Quick Start

import asyncio
import os
from akr_agent import Agent, ToolCenter
from akr_agent.tools.tool_llm import LLMCallTool

# Register LLM tool
ToolCenter.register(
    tool=LLMCallTool(
        api_key=os.environ.get("OPENAI_API_KEY"),
        model="gpt-4o-mini",
        temperature=0.7,
        max_tokens=1000,
        stream=True,
    )
)

async def main():
    # Create Agent instance, specify config directory
    agent = Agent(config_dir="prompts/CoachLi/v1")
    
    # User input
    user_input = "I want to start fitness, what are the suggestions?"
    print(f"\n--- User Input ---\n{user_input}")
    
    # Run Agent and get response
    print("\n--- Agent Response ---")
    async for chunk in agent.run_dynamic(user_input):
        print(chunk.content, end="", flush=True)
    
    print("\n\n--- Done ---")

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

Architecture Design

  • Advantage:
    • Agent is the core class to manage the entire process
    • DynamicDispatcher responsible for rule scheduling and execution
    • ObservableContext provides reactive context management
    • EventBus implements event-driven mechanism
    • ToolCenter provides tool registration and invocation capability

Core Function

  1. Rule Engine: Flexible rule system based on configuration, supports conditional matching and dynamic rule generation
  2. Context Management: Implements observable context management, supports data change notifications
  3. Tool System: Provides a unified interface for tool registration and invocation, supports asynchronous streaming output
  4. LLM Integration: Wraps OpenAI API, supports streaming responses and tool calls

Configuration System

  • Manage Agent behavior using YAML configuration files, including system prompts, rule definitions, etc.
  • Support Jinja2 template rendering, allowing dynamic generation of prompts based on context

Configuration Directory Structure

prompts/
└── YourAgent/version_x/
    ├── meta.yaml           # Agent metadata
    ├── system_prompt.yaml  # System prompt
    └── rules/              # Rule directory
        ├── rule1.yaml      # Rule 1
        ├── rule2.yaml      # Rule 2
        └── ...             # At least one rule must be able to handle user input

meta.yaml Example

agent:
  name: "Your Agent Name"
  version: "v1"

meta:
  name: "Agent Display Name"
  desc: "Description of your agent"
  parameters:
    skill: 
      - "Skill 1"
      - "Skill 2"
    advantages:
      - "Advantage 1"
    disadvantages:
      - "Disadvantage 1"

system_prompt.yaml Example

content: |
  You are {{ meta.name }}, you are a {{ meta.desc }}.
  You are very willing to help users with {{ meta.parameters.skill | join(', ') }}.
  You are better at helping users with {{ meta.parameters.advantages | join(', ') }},
  but not good at helping users with {{ meta.parameters.disadvantages | join(', ') }}.

Rule Configuration Example

name: "basic_reply"
depend_ctx_key:
  - "user_input"
match_condition: "True"  # Always match
prompt: |
  Please provide a useful answer based on the user's question.
prompt_detail: |
  The user's question is: {{ user_input }}
tool: "LLMCallTool" # The tool registered in advance
tool_params:
  ctx: ["user_input"]
  config: ["prompt", "prompt_detail"]
  extra:
    - tools:
      - "ToolNameThatLLMCanUse"
tool_result_target: "DIRECT_RETURN" # Directly return to user

Custom Tools

You can create custom tools by inheriting the Tool base class:

from typing import AsyncGenerator
from akr_agent import Tool, ToolCenter

class WeatherTool(Tool):
    """Get weather information"""
    
    name = "WeatherTool"
    description = "Get weather information for a specified city"
    
    def __init__(self, api_key=None):
        self.api_key = api_key
    
    async def run(self, city: str, **kwargs) -> AsyncGenerator[str, None]:
        """
        Get weather information for a specified city
        
        Args:
            city: City name
        """
        # Implement weather API call logic
        weather_info = f"{city} weather: sunny, temperature 25°C"
        yield weather_info

# Register tool
ToolCenter.register(tool=WeatherTool(api_key="your_weather_api_key"))

Development Guide

Install development dependencies

pip install -e ".[dev]"

Run tests

python -m pytest tests

Code Style

We use Black and isort to maintain consistent code style:

black akr_agent
isort akr_agent

Type Checking

Use mypy for type checking:

mypy akr_agent

Contribution Guide

We welcome all forms of contributions, including but not limited to:

  1. Reporting issues and suggesting improvements
  2. Submitting code fixes or new features
  3. Improving documentation
  4. Adding test cases

Contribution Process

  1. Fork the project repository
  2. Create your 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. Create a Pull Request

Roadmap

  • Support more LLM providers
  • Add more built-in tools
  • Improve error handling and recovery mechanisms
  • Add more examples and documentation
  • Implement caching mechanisms and performance optimization

License

This project is licensed under the MIT License - see the LICENSE file for details

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

akr_agent-0.1.3.tar.gz (65.8 kB view details)

Uploaded Source

Built Distribution

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

akr_agent-0.1.3-py3-none-any.whl (62.2 kB view details)

Uploaded Python 3

File details

Details for the file akr_agent-0.1.3.tar.gz.

File metadata

  • Download URL: akr_agent-0.1.3.tar.gz
  • Upload date:
  • Size: 65.8 kB
  • Tags: Source
  • Uploaded using Trusted Publishing? No
  • Uploaded via: twine/6.1.0 CPython/3.12.9

File hashes

Hashes for akr_agent-0.1.3.tar.gz
Algorithm Hash digest
SHA256 b1cb48a423a31f6ad20e568ddf9e369e652f1e6d1479dc1774ec8e9681b01216
MD5 58c30ba225a5270c8f3912b254478e0a
BLAKE2b-256 c4e27fb058f0d36b81b02cb6bd53b1a65db31d7b2d8ac0c877620e68f536b115

See more details on using hashes here.

File details

Details for the file akr_agent-0.1.3-py3-none-any.whl.

File metadata

  • Download URL: akr_agent-0.1.3-py3-none-any.whl
  • Upload date:
  • Size: 62.2 kB
  • Tags: Python 3
  • Uploaded using Trusted Publishing? No
  • Uploaded via: twine/6.1.0 CPython/3.12.9

File hashes

Hashes for akr_agent-0.1.3-py3-none-any.whl
Algorithm Hash digest
SHA256 2b6db30e29255fd703a522816993bd5daa5382b1bf9f8deed8933c578d5e4375
MD5 a3b269cd6b750cc4b7522789c84708ad
BLAKE2b-256 e5b259752a4cd8171e1d504905353891d06a3cb0cb6dd5b11fbf74d03e3afd52

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