CoolFace
Apppublic

im-amrith/nerve

sourceHugging Faceupdated 8mo agoView on Hugging Face
0likes
setup_validation.py272 linesDownload Raw Back to root
1"""2Setup and validation script for Agentic Brokerage OS3Run this after installation to verify everything is configured correctly.4"""5 6import os7import sys8from pathlib import Path9 10 11def check_python_version():12    """Verify Python version >= 3.10"""13    print("Checking Python version...", end=" ")14    version = sys.version_info15    if version.major >= 3 and version.minor >= 10:16        print(f"✅ Python {version.major}.{version.minor}.{version.micro}")17        return True18    else:19        print(f"❌ Python {version.major}.{version.minor} (requires 3.10+)")20        return False21 22 23def check_dependencies():24    """Check if required packages are installed"""25    print("\nChecking dependencies...")26    # Map package names to their import names27    required = {28        "langgraph": "langgraph",29        "langchain": "langchain",30        "groq": "groq",31        "opencv-python-headless": "cv2",32        "Pillow": "PIL",33        "pandas": "pandas",34        "numpy": "numpy",35        "pydantic": "pydantic",36        "loguru": "loguru"37    }38    39    missing = []40    for package, import_name in required.items():41        try:42            __import__(import_name)43            print(f"  ✅ {package}")44        except ImportError:45            print(f"  ❌ {package} (missing)")46            missing.append(package)47    48    if missing:49        print(f"\n⚠️  Missing packages: {', '.join(missing)}")50        print("Run: pip install -r requirements.txt")51        return False52    53    return True54 55 56def check_environment():57    """Check environment variables"""58    print("\nChecking environment configuration...")59    60    # Check .env file exists61    env_file = Path(".env")62    if not env_file.exists():63        print("  ⚠️  .env file not found")64        print("     Copy .env.example to .env and configure")65        66        # Try to read from .env.example67        if Path(".env.example").exists():68            print("  📝 Creating .env from .env.example...")69            import shutil70            shutil.copy(".env.example", ".env")71            print("  ✅ Created .env (please edit and add your API keys)")72    else:73        print("  ✅ .env file exists")74    75    # Load and check keys76    from dotenv import load_dotenv77    load_dotenv()78    79    groq_key = os.getenv("GROQ_API_KEY")80    if groq_key and not groq_key.startswith("your_"):81        print("  ✅ GROQ_API_KEY is set")82        key_valid = True83    else:84        print("  ❌ GROQ_API_KEY not configured")85        print("     Get your key from: https://console.groq.com/keys")86        key_valid = False87    88    # Optional keys89    news_key = os.getenv("NEWS_API_KEY")90    if news_key and not news_key.startswith("your_"):91        print("  ✅ NEWS_API_KEY is set (optional)")92    else:93        print("  ℹ️  NEWS_API_KEY not set (optional, for news sentiment)")94    95    pinecone_key = os.getenv("PINECONE_API_KEY")96    if pinecone_key and not pinecone_key.startswith("your_"):97        print("  ✅ PINECONE_API_KEY is set (optional)")98    else:99        print("  ℹ️  PINECONE_API_KEY not set (optional, for vector memory)")100    101    return key_valid102 103 104def check_directories():105    """Create necessary directories"""106    print("\nChecking directory structure...")107    108    dirs = ["logs", "screenshots", "config", "data"]109    for dir_name in dirs:110        dir_path = Path(dir_name)111        if dir_path.exists():112            print(f"  ✅ {dir_name}/")113        else:114            print(f"  📁 Creating {dir_name}/")115            dir_path.mkdir(exist_ok=True)116    117    return True118 119 120def test_groq_connection():121    """Test Groq API connection"""122    print("\nTesting Groq API connection...", end=" ")123    124    try:125        from dotenv import load_dotenv126        load_dotenv()127        128        groq_key = os.getenv("GROQ_API_KEY")129        if not groq_key or groq_key.startswith("your_"):130            print("⏭️  Skipped (no API key)")131            return True  # Don't fail the setup132        133        from groq import Groq134        client = Groq(api_key=groq_key)135        136        # Simple test request137        response = client.chat.completions.create(138            model="llama-3.1-8b-instant",139            messages=[{"role": "user", "content": "Say 'ready' if you can read this."}],140            max_tokens=10141        )142        143        if response.choices:144            print("✅ Connection successful")145            return True146        else:147            print("❌ Connection failed")148            return False149            150    except Exception as e:151        print(f"❌ Error: {e}")152        return False153 154 155def test_imports():156    """Test critical imports"""157    print("\nTesting project imports...")158    159    try:160        print("  Importing core modules...", end=" ")161        from src.core.state import AgentState, UserConstitution162        from src.core.perception import PerceptionEngine163        from src.core.orchestrator import Orchestrator164        print("✅")165        166        print("  Importing engines...", end=" ")167        from src.engines.pre_trade_sentinel import PreTradeSentinel168        from src.engines.strategy_engine import StrategyEngine169        from src.engines.rag_journal import RAGJournal170        print("✅")171        172        return True173    except Exception as e:174        print(f"❌ Import failed: {e}")175        return False176 177 178def run_quick_test():179    """Run a quick functionality test"""180    print("\nRunning functionality test...")181    182    try:183        from dotenv import load_dotenv184        load_dotenv()185        186        from src.core.state import UserConstitution187        188        print("  Creating user constitution...", end=" ")189        constitution = UserConstitution(190            max_position_size=10000,191            enable_kill_switch=True192        )193        print("✅")194        195        groq_key = os.getenv("GROQ_API_KEY")196        if groq_key and not groq_key.startswith("your_"):197            from src.engines.pre_trade_sentinel import PreTradeSentinel198            from src.core.state import TradeIntent199            from datetime import datetime200            201            print("  Testing sentinel...", end=" ")202            sentinel = PreTradeSentinel(groq_key, constitution)203            204            intent = TradeIntent(205                action="buy",206                symbol="TEST",207                quantity=10,208                order_type="market",209                timestamp=datetime.now()210            )211            212            result = sentinel.check_trade(intent, {"total_value": 100000})213            214            if result and hasattr(result, 'inference_time_ms'):215                print(f"✅ ({result.inference_time_ms:.1f}ms)")216            else:217                print("✅")218        else:219            print("  Sentinel test skipped (no API key)")220        221        return True222        223    except Exception as e:224        print(f"❌ Test failed: {e}")225        import traceback226        traceback.print_exc()227        return False228 229 230def main():231    """Main setup validation"""232    print("="*70)233    print("🚀 AGENTIC BROKERAGE OS - SETUP VALIDATION")234    print("="*70)235    236    results = []237    238    results.append(("Python Version", check_python_version()))239    results.append(("Dependencies", check_dependencies()))240    results.append(("Environment", check_environment()))241    results.append(("Directories", check_directories()))242    results.append(("Groq Connection", test_groq_connection()))243    results.append(("Project Imports", test_imports()))244    results.append(("Functionality", run_quick_test()))245    246    print("\n" + "="*70)247    print("📊 SETUP VALIDATION RESULTS")248    print("="*70)249    250    for name, passed in results:251        status = "✅ PASS" if passed else "❌ FAIL"252        print(f"{name:.<30} {status}")253    254    all_passed = all(r[1] for r in results)255    256    print("="*70)257    258    if all_passed:259        print("\n🎉 Setup validation complete! You're ready to go.")260        print("\nNext steps:")261        print("  1. Run demos: python demos/ui_adaptation_demo.py")262        print("  2. Start interactive mode: python src/main.py")263        print("  3. Read docs: docs/QUICKSTART.md")264    else:265        print("\n⚠️  Some checks failed. Please fix the issues above.")266        print("   See docs/QUICKSTART.md for troubleshooting.")267        sys.exit(1)268 269 270if __name__ == "__main__":271    main()272