Skip to content

Commit

Permalink
Merge pull request #5
Browse files Browse the repository at this point in the history
Enhance Quickstart & Agent Config
  • Loading branch information
jbarnes850 authored Jan 16, 2025
2 parents 2c49226 + 68f68d6 commit b8657fd
Show file tree
Hide file tree
Showing 25 changed files with 2,211 additions and 1,243 deletions.
82 changes: 37 additions & 45 deletions README.md
Original file line number Diff line number Diff line change
@@ -1,6 +1,6 @@
# NEAR AI Agent Studio

A production-ready starter kit for building AI agents and multi-agent swarms on NEAR. This template provides the essential building blocks for creating autonomous agents that can interact with the NEAR blockchain, make decisions using LLMs, and collaborate in swarms. The NEAR AI Agent Studio is an educational and interactive starter kit designed for developers looking to build AI agents and agentic applications on NEAR.
A production-ready starter kit for building AI agents and multi-agent swarms on NEAR. This template provides the essential building blocks for creating autonomous agents that can interact with the NEAR blockchain, make decisions using LLMs, and collaborate in swarms. The NEAR AI Agent Studio is an educational and interactive starter kit designed for developers looking to build AI agents and agentic applications on NEAR.

[![License: MIT](https://img.shields.io/badge/License-MIT-yellow.svg)](https://opensource.org/licenses/MIT)
[![NEAR](https://img.shields.io/badge/NEAR-Protocol-blue.svg)](https://near.org)
Expand All @@ -10,6 +10,9 @@ A production-ready starter kit for building AI agents and multi-agent swarms on
[![Hyperbolic](https://img.shields.io/badge/LLM-Hyperbolic-purple.svg)](https://hyperbolic.xyz)
[![Lava Network](https://img.shields.io/badge/RPC-Lava%20Network-orange.svg)](https://www.lavanet.xyz/get-started/near)


![NEAR AI Agent Studio](./public/near-agent-studio.png)

## ⚡️ Getting Started

### Prerequisites
Expand All @@ -35,9 +38,6 @@ Before you begin, ensure you have:
- Hyperbolic API key for LLM capabilities
- Sign up at [hyperbolic.xyz](https://hyperbolic.xyz)
- Free tier available for development
- ElevenLabs API key for voice features (optional)
- Register at [elevenlabs.io](https://elevenlabs.io)
- Free tier includes basic voice synthesis

### Quick Start
```bash
Expand All @@ -57,6 +57,26 @@ chmod +x scripts/quickstart.sh # Make script executable
./scripts/quickstart.sh
```

The quickstart script will:
1. Set up your development environment
2. Create a NEAR testnet account
3. Install example agents
4. Launch an interactive chat assistant to help you create your first agent

### Interactive Chat
After setup, you'll enter an interactive chat session where you can:
- Create new agents with `/create agent <name>`
- Configure agents with `/config agent <name>`
- Run multiple agents together with `/run-agents`
- List available agents with `/list`
- Get help anytime with `/help`

Start the chat manually anytime:
```bash
near-swarm chat # Regular mode
near-swarm chat --tutorial create-first-agent # Guided tutorial
```

### Environment Setup
```bash
# Copy environment template
Expand All @@ -68,11 +88,6 @@ cp .env.example .env
# - NEAR_PRIVATE_KEY=your-private-key
# - LLM_PROVIDER=hyperbolic
# - LLM_API_KEY=your-api-key
# Optional:
# - ELEVENLABS_API_KEY=your-key # For voice features

# Verify installation
near-swarm config validate
```

## Core Components
Expand Down Expand Up @@ -149,6 +164,12 @@ graph TB
SwarmAgent --> Evaluation
```


The architecture combines a flexible agent framework with swarm intelligence capabilities:

1. **Agent Framework Core**
- Agent Registry for managing available agents

The architecture combines a flexible agent system with swarm intelligence capabilities:

1. **Agent Framework Core**
Expand All @@ -171,6 +192,13 @@ The architecture combines a flexible agent system with swarm intelligence capabi
- Consensus building through multi-agent voting
- Role-based evaluation with LLM reasoning

This architecture enables:
- Easy extension through agent plugins
- Coordinated decision-making via swarm intelligence
- Secure transaction handling
- Market-aware operations
- LLM-powered reasoning

### Project Structure
```bash
near-swarm-intelligence/
Expand Down Expand Up @@ -256,42 +284,6 @@ peer_agent = SwarmAgent(config, SwarmConfig(role="risk_manager"))
await main_agent.join_swarm([peer_agent])
```

## 📚 Interactive Features

### Voice Commands
- Portfolio queries
- Market analysis
- Transaction requests
- Strategy suggestions

### Chat Commands
- Market Analysis
```bash
/market [symbol] # Get market analysis
/trend [timeframe] # Get trend analysis
/volume [symbol] # Volume analysis
```

- Risk Management
```bash
/risk [action] # Risk assessment
/balance # Check portfolio balance
/positions # List open positions
```

- Strategy
```bash
/strategy [action] # Strategy suggestions
/portfolio # Portfolio overview
```

- Development Tools
```bash
/ws # Manage workspace
/env # Configure environment
/config # View/modify settings
```

## 📄 Examples

For more examples and reference implementations, check out our [examples directory](near_swarm/examples/):
Expand Down
30 changes: 30 additions & 0 deletions agents/decision-maker.yaml
Original file line number Diff line number Diff line change
@@ -0,0 +1,30 @@
name: decision-maker
environment: development
log_level: INFO

llm:
provider: hyperbolic
api_key: ${LLM_API_KEY}
model: ${LLM_MODEL}
temperature: 0.7
max_tokens: 2000
api_url: ${LLM_API_URL}

plugins:
- name: decision-maker
role: strategy_optimizer
capabilities:
- strategy_optimization
- decision_making
- risk_management
custom_settings:
min_confidence_threshold: 0.8
risk_tolerance: medium
max_retries: 3
timeout: 30
decision_interval: 300
risk_threshold: 0.1

custom_settings:
environment: development
log_level: INFO
30 changes: 30 additions & 0 deletions agents/price-monitor.yaml
Original file line number Diff line number Diff line change
@@ -0,0 +1,30 @@
name: price-monitor
environment: development
log_level: INFO

llm:
provider: hyperbolic
api_key: ${LLM_API_KEY}
model: ${LLM_MODEL}
temperature: 0.7
max_tokens: 2000
api_url: ${LLM_API_URL}

plugins:
- name: price-monitor
role: market_analyzer
capabilities:
- price_monitoring
- trend_analysis
- market_assessment
custom_settings:
min_confidence_threshold: 0.7
risk_tolerance: medium
max_retries: 3
timeout: 30
update_interval: 60
alert_threshold: 0.05

custom_settings:
environment: development
log_level: INFO
7 changes: 7 additions & 0 deletions near_swarm/agents/decision-maker/__init__.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,7 @@
"""
Decision Making Agent Package
"""

from .plugin import DecisionMakerPlugin

__all__ = ['DecisionMakerPlugin']
40 changes: 40 additions & 0 deletions near_swarm/agents/decision-maker/agent.yaml
Original file line number Diff line number Diff line change
@@ -0,0 +1,40 @@
# Decision Maker Agent Configuration
name: decision-maker
environment: development
log_level: INFO

# LLM Configuration
llm:
provider: hyperbolic
model: deepseek-ai/DeepSeek-V3
api_key: ${LLM_API_KEY}
temperature: 0.7
max_tokens: 2000
api_url: https://api.hyperbolic.xyz/v1
system_prompt: |
You are a decision-making agent in the NEAR swarm.
Evaluate market opportunities and make strategic decisions.
Always respond in JSON format with confidence levels.
# Agent Settings
custom_settings:
min_confidence_threshold: 0.7
risk_tolerance: medium
max_retries: 3
timeout: 30

# Plugin Configuration
plugins:
- name: decision-maker
role: strategy_optimizer
capabilities:
- strategy_optimization
- decision_making
- risk_management
custom_settings:
min_confidence_threshold: 0.7
risk_tolerance: medium
max_retries: 3
timeout: 30
min_profit_threshold: 0.002 # 0.2% minimum profit
max_position_size: 10000 # Maximum position size in USD
117 changes: 117 additions & 0 deletions near_swarm/agents/decision-maker/plugin.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,117 @@
"""
Decision Making Agent Plugin
Makes strategic decisions based on market analysis
"""

from typing import Dict, Any, Optional
from near_swarm.plugins.base import AgentPlugin
from near_swarm.core.llm_provider import create_llm_provider, LLMConfig
from near_swarm.plugins import register_plugin
import logging

logger = logging.getLogger(__name__)

class DecisionMakerPlugin(AgentPlugin):
"""Decision making agent implementation"""

async def initialize(self) -> None:
"""Initialize plugin resources"""
# Initialize LLM provider
llm_config = LLMConfig(
provider=self.agent_config.llm.provider,
api_key=self.agent_config.llm.api_key,
model=self.agent_config.llm.model,
temperature=self.agent_config.llm.temperature,
max_tokens=self.agent_config.llm.max_tokens,
api_url=self.agent_config.llm.api_url,
system_prompt="""You are a strategic decision-making agent in the NEAR ecosystem.
Your role is to evaluate market opportunities and make risk-managed decisions.
Key responsibilities:
1. Evaluate market analysis and opportunities
2. Calculate optimal position sizes
3. Manage risk exposure
4. Make strategic recommendations
Always provide your decisions in a structured format with:
- Analysis: Your evaluation of the situation
- Strategy: Your recommended course of action
- Rationale: Detailed reasoning behind the decision
- Risk: Assessment of potential risks
- Confidence: Your confidence level (0-1)"""
)
self.llm_provider = create_llm_provider(llm_config)

# Load custom settings
self.min_confidence = self.plugin_config.settings.get(
'min_confidence_threshold', 0.7
)
self.risk_tolerance = self.plugin_config.settings.get(
'risk_tolerance', 'medium'
)
self.max_position_size = self.plugin_config.settings.get(
'max_position_size', 100000
)

async def evaluate(self, context: Dict[str, Any]) -> Dict[str, Any]:
"""Evaluate and make strategic decisions"""
if not self.llm_provider:
raise RuntimeError("Plugin not initialized")

# Extract data from context
market_analysis = context.get('market_analysis', {})
current_positions = context.get('positions', [])
request = context.get('request', '')

# Create decision prompt
prompt = f"""Evaluate the current market situation and make strategic decisions:
Market Analysis: {market_analysis}
Current Positions: {current_positions}
Risk Tolerance: {self.risk_tolerance}
Max Position Size: {self.max_position_size}
{request}
Provide your decision in JSON format with:
- analysis: Your evaluation of the situation
- strategy: Recommended course of action
- rationale: Detailed reasoning
- risk: Risk assessment
- confidence: Your confidence level (0-1)
"""

# Get LLM decision
try:
response = await self.llm_provider.query(prompt, expect_json=True)

# Validate confidence threshold
if response.get('confidence', 0) < self.min_confidence:
response['strategy'] = "Hold - Confidence too low for action"

return response

except Exception as e:
logger.error(f"Error during decision making: {e}")
return {
"analysis": "Error during analysis",
"strategy": "Unable to make decision",
"rationale": str(e),
"risk": "Unknown - Analysis failed",
"confidence": 0
}

async def execute(self, operation: Optional[str] = None, **kwargs) -> Any:
"""Execute plugin operation"""
if operation == "decide":
return await self.evaluate(kwargs)
else:
raise ValueError(f"Unsupported operation: {operation}")

async def cleanup(self) -> None:
"""Cleanup plugin resources"""
if self.llm_provider:
await self.llm_provider.close()

# Register the plugin
register_plugin("decision-maker", DecisionMakerPlugin)
7 changes: 7 additions & 0 deletions near_swarm/agents/price-monitor/__init__.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,7 @@
"""
Price Monitoring Agent Package
"""

from .plugin import PriceMonitorPlugin

__all__ = ['PriceMonitorPlugin']
Loading

0 comments on commit b8657fd

Please sign in to comment.