# Avachain

A lightweight, efficient library for creating and running AI agents with tools. Avachain focuses on OpenAI-compatible APIs and provides a minimal interface for building powerful AI agents with tool-calling capabilities.

## ✨ Features

- 🚀 **Lightweight & Fast**: Minimal dependencies, maximum performance
- 🔧 **Tool Integration**: Easy tool creation and management
- 💬 **Conversation Memory**: Intelligent context management
- 🎯 **Streaming Support**: Real-time response streaming
- 📊 **Callback System**: Monitor and handle agent events
- 🎨 **Colored Output**: Beautiful console output with print_color
- 🔄 **Function/Tool Calling**: Support for both modern and legacy function calling
- 📝 **Context Management**: Advanced message trimming and context preservation
- 🛠️ **Tool Creator**: Built-in tool creation and management utilities
- 👤 **Persona Creator**: Agent persona creation and management system

## 🏗️ Architecture Overview

Avachain follows a modular architecture designed for flexibility and extensibility:

```
avachain/
├── avachain.py           # Core classes: BaseTool, LLM, OpenaiLLM, CallbackHandler
├── avachain_executor.py  # Main AvaAgent orchestrator and execution engine
├── avachain_utils.py     # Utility functions for resource management
├── tool_creator.py       # Tool creation and JSON conversion utilities
└── persona_creator.py    # Agent persona management system
```

## 📦 Dependencies

Avachain keeps dependencies minimal for maximum compatibility:

- **pydantic (≥2.6.1)**: Data validation and settings management
- **requests (≥2.31.0)**: HTTP client for API calls
- **tokenizers (==0.19.1)**: Text tokenization utilities
- **openai (==1.63.0)**: OpenAI API client
- **numpy**: Numerical computing support
- **print_color**: Colored console output

## Api Keys

To use Avachain, you need API keys for the services you want to integrate. Follow these steps to set up your API keys:

1. **Ava API Key**: Sign up at [AvaConsole](https://console.ava.pathor.in/) and create an API key.

Store your API keys in a secure location and reference them in your code as needed.

## Prerequisites

Ensure you have the following installed on your system:
- Python (3.10 or higher recommended)
- Git
- pip (Python package installer)

## 🚀 Quick Start

### 1. Clone the Repository
```bash
git clone https://github.com/OnlinePage/Avachain.git
cd Avachain
```

### 2. Install the Package
```bash
# For basic installation
python setup.py sdist

# For development (includes linting tools):
pip install -e ".[dev]"

# For testing (includes pytest):
pip install -e ".[test]"
```

### 3. Basic Usage

```python
from avachain.avachain_executor import AvaAgent
from avachain import OpenaiLLM, BaseTool
from pydantic import BaseModel, Field

# Initialize the LLM
llm = OpenaiLLM(
    model="gpt-4o-mini",
    api_key="your-ava-api-key", # Visit https://console.ava.pathor.in/
    base_url="https://api.ava.pathor.in/v1",
    temperature=0.7
)

class SearchArgs(BaseModel):
    query: str = Field(description="Search query")
    status: str = Field(
        description="What are you doing in first person format as status. Should be casual, personalized addressing user friendly!",
    )

# Define a custom tool
class SearchTool(BaseTool):
    name: str = "web_search"
    description: str = "Search the web for information"
    args_schema: Type[BaseModel] = SearchArgs

    def _run(self, query: str):
        # Your search implementation here
        return f"Search results for: {query}"


# Create the agent with comprehensive configuration
agent = AvaAgent(
    sys_prompt="You are a helpful assistant with web search capabilities.",
    ava_llm=llm,
    tools_list=[SearchTool()],
    logging=True,
    pickup_mes_count=10,
)

# Chat with the agent using the run method
response = agent.run("Search for Python tutorials")
print(response)
```



### Plugin Creator Module

Advanced tool creation and management utilities.

```python
from avachain.tool_creator import convert_tool_to_json

# Convert tool with metadata for external systems
tool_json = convert_tool_to_json(
    tool=my_tool,
    tool_id="unique_id",
    human_description="User-friendly description",
    public_name="Display Name",
    logo="path/to/logo.png",
    isAnonymous=False,
    authentication_required=True,
    tags=["search", "web", "utility"],
    supports_android=False,
    supports_windows=True
)
```

### Persona Creator Module

Agent persona creation and management system.

```python
from avachain import persona_creator, validate_logo_path

# Create and manage agent personas
persona_creator = PersonaCreator()

# Validate logo file
logo_path = validate_logo_path("path/to/logo.png")

# Create persona with tools and configuration
persona_data = {
    "name": "Research Assistant",
    "description": "AI assistant specialized in research tasks",
    "system_prompt": "You are a research assistant...",
    "tools": [search_tool, analysis_tool],
    "logo_path": logo_path
}
```

## 🤝 Contributing

We welcome contributions! Please see our [Contributing Guide](CONTRIBUTING.md) for detailed information on how to contribute to Avachain, including development setup, coding standards, and submission guidelines.

## � Security Considerations

- **API Key Management**: Never hardcode API keys in your code. Use environment variables or secure configuration files.
- **Tool Security**: Validate all tool inputs and sanitize outputs. Be cautious with tools that execute system commands.
- **Input Validation**: Always validate user inputs before processing.
- **Error Handling**: Don't expose sensitive information in error messages.

```python
import os
from avachain import OpenaiLLM, AvaAgent

# Secure API key handling
api_key = os.getenv("OPENAI_API_KEY")
if not api_key:
    raise ValueError("OPENAI_API_KEY environment variable not set")

llm = OpenaiLLM(api_key=api_key, model="gpt-3.5-turbo")
```

## 🚀 Performance Tips

1. **Context Management**: Use appropriate `pickup_mes_count` to balance context and performance
2. **Tool Optimization**: Keep tool execution time minimal
3. **Streaming**: Use streaming for better perceived performance in interactive applications
4. **Caching**: Implement caching in tools for frequently accessed data
5. **Async Operations**: Consider async patterns for I/O heavy tools

## 📊 Monitoring and Logging

### Built-in Logging

```python
# Enable comprehensive logging
agent = AvaAgent(
    sys_prompt="Your system prompt",
    ava_llm=llm,
    logging=True,
    deeper_logs=True,  # More detailed logs
    agent_name_identifier="MyAgent"
)
```


## 📝 License

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


**Made with ❤️ for the AI community**
