diff --git a/.env.example b/.env.example new file mode 100644 index 0000000..ce40fdd --- /dev/null +++ b/.env.example @@ -0,0 +1,6 @@ +# OpenAI API Configuration +OPENAI_API_KEY=your_openai_api_key_here + +# Application Configuration +PORT=3000 +NODE_ENV=development diff --git a/.gitignore b/.gitignore index 58ab67f..31729f4 100644 --- a/.gitignore +++ b/.gitignore @@ -1,2 +1,24 @@ *.agdai MAlonzo/** + +# Node.js +node_modules/ +npm-debug.log +yarn-error.log +package-lock.json + +# Environment variables +.env + +# Python +__pycache__/ +*.py[cod] +*$py.class +*.so +.Python +venv/ +env/ +ENV/ +*.egg-info/ +dist/ +build/ diff --git a/README.md b/README.md index 25041f3..8dc3497 100644 --- a/README.md +++ b/README.md @@ -1 +1,180 @@ -# Web3AI \ No newline at end of file +# Web3AI + +Web3AI is an AI-powered blockchain and Web3 development toolkit that integrates OpenAI's capabilities with blockchain technologies. + +## 🌟 Features + +- **Node.js Backend**: Server-side JavaScript for Web3 applications +- **OpenAI Integration**: AI-powered smart contract analysis, code generation, and blockchain insights +- **Python AI Scripts**: Advanced AI capabilities for blockchain development +- **Modular Architecture**: Easy to extend with additional AI or blockchain features + +## šŸ“‹ Prerequisites + +Before you begin, ensure you have the following installed: + +- **Node.js** (v14 or higher) - [Download here](https://nodejs.org/) +- **npm** (comes with Node.js) +- **Python** (v3.8 or higher) - [Download here](https://www.python.org/downloads/) +- **pip** (comes with Python) + +## šŸš€ Getting Started + +### 1. Clone the Repository + +```bash +git clone https://github.com/lippytm/Web3AI.git +cd Web3AI +``` + +### 2. Set Up Node.js Environment + +Install Node.js dependencies: + +```bash +npm install +``` + +### 3. Set Up Python Environment (Optional) + +For Python AI scripts, install required packages: + +```bash +pip install -r requirements.txt +``` + +Or create a virtual environment (recommended): + +```bash +# Create virtual environment +python -m venv venv + +# Activate virtual environment +# On Windows: +venv\Scripts\activate +# On macOS/Linux: +source venv/bin/activate + +# Install dependencies +pip install -r requirements.txt +``` + +### 4. Configure OpenAI API Key + +1. **Get your OpenAI API key**: + - Visit [OpenAI Platform](https://platform.openai.com/api-keys) + - Sign in or create an account + - Navigate to API Keys section + - Click "Create new secret key" + - Copy your API key (you won't be able to see it again!) + +2. **Set up environment variables**: + +```bash +# Copy the example environment file +cp .env.example .env + +# Edit .env and add your API key +# Replace 'your_openai_api_key_here' with your actual API key +``` + +Your `.env` file should look like this: + +``` +OPENAI_API_KEY=sk-your-actual-api-key-here +PORT=3000 +NODE_ENV=development +``` + +āš ļø **Important**: Never commit your `.env` file to version control. It's already included in `.gitignore`. + +## šŸŽÆ Usage + +### Running the Node.js Application + +Start the main application: + +```bash +npm start +``` + +This will run the OpenAI integration demo and show you how to interact with AI models. + +### Running Python AI Scripts + +Execute the sample AI script: + +```bash +python ai_scripts/sample_ai.py +``` + +This demonstrates: +- Explaining Web3 concepts using AI +- Analyzing smart contract code +- Integration with OpenAI's Python library + +## šŸ“ Project Structure + +``` +Web3AI/ +ā”œā”€ā”€ backend/ # Node.js backend code +│ └── openai.js # OpenAI API integration module +ā”œā”€ā”€ ai_scripts/ # Python AI scripts +│ └── sample_ai.py # Sample AI functionality demo +ā”œā”€ā”€ .env.example # Environment variable template +ā”œā”€ā”€ .gitignore # Git ignore rules +ā”œā”€ā”€ index.js # Main entry point +ā”œā”€ā”€ package.json # Node.js dependencies and scripts +ā”œā”€ā”€ requirements.txt # Python dependencies +└── README.md # This file +``` + +## šŸ”§ Available Scripts + +- `npm start` - Run the main application +- `npm test` - Run tests (to be implemented) + +## šŸ¤ Contributing + +Contributions are welcome! Please feel free to submit a Pull Request. + +## šŸ“ License + +This project is licensed under the ISC License. + +## šŸ†˜ Troubleshooting + +### "OpenAI API key not configured" Error + +Make sure you have: +1. Created a `.env` file in the project root +2. Added your OpenAI API key to the `.env` file +3. The key starts with `sk-` + +### "Module not found" Error + +Run `npm install` to install Node.js dependencies or `pip install openai python-dotenv` for Python. + +### Python Import Errors + +Make sure you have activated your virtual environment (if using one) and installed all required packages. + +## šŸ”® Future Enhancements + +- Integration with blockchain networks (Ethereum, Polygon, etc.) +- Smart contract deployment automation +- AI-powered security auditing +- Web3 wallet integration +- NFT generation and analysis +- DeFi protocol interaction + +## šŸ“š Resources + +- [OpenAI API Documentation](https://platform.openai.com/docs) +- [Node.js Documentation](https://nodejs.org/docs) +- [Python OpenAI Library](https://github.com/openai/openai-python) +- [Web3.js Documentation](https://web3js.readthedocs.io/) + +--- + +Made with ā¤ļø for the Web3 and AI community diff --git a/ai_scripts/sample_ai.py b/ai_scripts/sample_ai.py new file mode 100644 index 0000000..45ca461 --- /dev/null +++ b/ai_scripts/sample_ai.py @@ -0,0 +1,180 @@ +#!/usr/bin/env python3 +""" +Web3AI - Python AI Script Example + +This script demonstrates how to use OpenAI's Python library to interact +with AI models for Web3 and blockchain-related tasks. + +Requirements: + pip install openai python-dotenv +""" + +import os +from dotenv import load_dotenv + +# Load environment variables from .env file +load_dotenv() + + +def setup_openai(): + """ + Initialize OpenAI client with API key from environment + """ + try: + from openai import OpenAI + + api_key = os.getenv('OPENAI_API_KEY') + + if not api_key or api_key == 'your_openai_api_key_here': + print('āš ļø Warning: OpenAI API key not configured!') + print('šŸ“ Please set OPENAI_API_KEY in your .env file') + return None + + client = OpenAI(api_key=api_key) + print('āœ… OpenAI client initialized successfully\n') + return client + + except ImportError: + print('āŒ Error: openai package not installed') + print(' Install it with: pip install openai') + return None + + +def analyze_smart_contract(client, contract_code): + """ + Example function to analyze smart contract code using AI + + Args: + client: OpenAI client instance + contract_code: Smart contract code to analyze + + Returns: + AI analysis of the contract + """ + if not client: + return "Client not initialized" + + try: + response = client.chat.completions.create( + model="gpt-3.5-turbo", + messages=[ + { + "role": "system", + "content": "You are an expert in blockchain and smart contract security. Analyze smart contracts for potential vulnerabilities and best practices." + }, + { + "role": "user", + "content": f"Analyze this smart contract code:\n\n{contract_code}" + } + ], + max_tokens=300, + temperature=0.5 + ) + + return response.choices[0].message.content + + except Exception as e: + return f"Error analyzing contract: {str(e)}" + + +def explain_web3_concept(client, concept): + """ + Get AI explanation of Web3 concepts + + Args: + client: OpenAI client instance + concept: Web3 concept to explain + + Returns: + AI explanation + """ + if not client: + return "Client not initialized" + + try: + response = client.chat.completions.create( + model="gpt-3.5-turbo", + messages=[ + { + "role": "system", + "content": "You are a Web3 educator. Explain blockchain and Web3 concepts in simple, clear terms." + }, + { + "role": "user", + "content": f"Explain: {concept}" + } + ], + max_tokens=200, + temperature=0.7 + ) + + return response.choices[0].message.content + + except Exception as e: + return f"Error getting explanation: {str(e)}" + + +def run_demo(): + """ + Run demonstration of AI capabilities + """ + print('šŸš€ Web3AI Python Demo') + print('=' * 50) + print() + + # Initialize OpenAI client + client = setup_openai() + + if not client: + print('\nšŸ’” To run this demo:') + print(' 1. Install dependencies: pip install openai python-dotenv') + print(' 2. Set OPENAI_API_KEY in .env file') + print(' 3. Get API key from: https://platform.openai.com/api-keys') + return + + # Demo 1: Explain a Web3 concept + print('šŸ“š Demo 1: Explaining Web3 Concepts') + print('-' * 50) + concept = "What is a blockchain consensus mechanism?" + print(f'Question: {concept}\n') + print('Thinking... šŸ¤”\n') + + explanation = explain_web3_concept(client, concept) + print('AI Response:') + print(explanation) + print() + + # Demo 2: Smart contract analysis + print('\nšŸ” Demo 2: Smart Contract Analysis') + print('-' * 50) + + sample_contract = """ + pragma solidity ^0.8.0; + + contract SimpleStorage { + uint256 private data; + + function set(uint256 _data) public { + data = _data; + } + + function get() public view returns (uint256) { + return data; + } + } + """ + + print('Analyzing sample Solidity contract...\n') + print('Thinking... šŸ¤”\n') + + analysis = analyze_smart_contract(client, sample_contract) + print('AI Analysis:') + print(analysis) + print() + + print('\nāœ… Demo completed successfully!') + print('=' * 50) + + +if __name__ == '__main__': + run_demo() diff --git a/backend/openai.js b/backend/openai.js new file mode 100644 index 0000000..a763476 --- /dev/null +++ b/backend/openai.js @@ -0,0 +1,75 @@ +/** + * OpenAI Integration Module + * + * This module demonstrates how to interact with OpenAI's API using the official SDK. + * It includes examples of using GPT models for various AI tasks. + */ + +const OpenAI = require('openai'); + +// Initialize OpenAI client +const openai = new OpenAI({ + apiKey: process.env.OPENAI_API_KEY, +}); + +/** + * Simple chat completion example + * Demonstrates basic interaction with GPT models + */ +async function chatCompletion(prompt) { + try { + const completion = await openai.chat.completions.create({ + model: "gpt-3.5-turbo", + messages: [ + { + role: "system", + content: "You are a helpful AI assistant specialized in Web3 and blockchain technologies." + }, + { + role: "user", + content: prompt + } + ], + max_tokens: 150, + temperature: 0.7, + }); + + return completion.choices[0].message.content; + } catch (error) { + console.error('Error calling OpenAI API:', error.message); + throw error; + } +} + +/** + * Run a demo of the OpenAI integration + */ +async function runDemo() { + console.log('šŸ¤– OpenAI Integration Demo'); + console.log('─────────────────────────────\n'); + + try { + const prompt = "What is Web3 and how does AI enhance blockchain development?"; + console.log(`Question: ${prompt}\n`); + + console.log('Thinking... šŸ¤”\n'); + const response = await chatCompletion(prompt); + + console.log('AI Response:'); + console.log('─────────────────────────────'); + console.log(response); + console.log('─────────────────────────────\n'); + + console.log('āœ… Demo completed successfully!\n'); + } catch (error) { + console.error('āŒ Demo failed:', error.message); + if (error.status === 401) { + console.error(' Invalid API key. Please check your OPENAI_API_KEY in .env file.'); + } + } +} + +module.exports = { + chatCompletion, + runDemo, +}; diff --git a/index.js b/index.js new file mode 100644 index 0000000..2a9806c --- /dev/null +++ b/index.js @@ -0,0 +1,35 @@ +/** + * Web3AI - Main Entry Point + * + * This is the main entry point for the Web3AI application. + * It demonstrates the integration of AI capabilities with Web3 technologies. + */ + +require('dotenv').config(); + +console.log('šŸš€ Welcome to Web3AI!'); +console.log('=========================================='); +console.log('A toolkit for AI-powered Web3 development'); +console.log('==========================================\n'); + +// Check if OpenAI API key is configured +if (!process.env.OPENAI_API_KEY || process.env.OPENAI_API_KEY === 'your_openai_api_key_here') { + console.warn('āš ļø Warning: OpenAI API key not configured!'); + console.log('šŸ“ Please create a .env file based on .env.example'); + console.log(' and add your OpenAI API key.\n'); +} else { + console.log('āœ… OpenAI API key configured\n'); +} + +// Import and run OpenAI demo if API key is set +if (process.env.OPENAI_API_KEY && process.env.OPENAI_API_KEY !== 'your_openai_api_key_here') { + const openaiDemo = require('./backend/openai'); + + console.log('Running OpenAI integration demo...\n'); + openaiDemo.runDemo().catch(error => { + console.error('Error running OpenAI demo:', error.message); + }); +} else { + console.log('šŸ’” Set up your API key to run the OpenAI demo.'); + console.log(' Get your API key from: https://platform.openai.com/api-keys\n'); +} diff --git a/package.json b/package.json new file mode 100644 index 0000000..2ef5ada --- /dev/null +++ b/package.json @@ -0,0 +1,22 @@ +{ + "name": "web3ai", + "version": "1.0.0", + "description": "Web3AI - AI-powered blockchain and Web3 development toolkit", + "main": "index.js", + "scripts": { + "start": "node index.js", + "test": "echo \"Error: no test specified\" && exit 1" + }, + "keywords": [ + "web3", + "ai", + "blockchain", + "openai" + ], + "author": "", + "license": "ISC", + "dependencies": { + "dotenv": "^17.2.3", + "openai": "^6.10.0" + } +} diff --git a/requirements.txt b/requirements.txt new file mode 100644 index 0000000..5ab3a8d --- /dev/null +++ b/requirements.txt @@ -0,0 +1,3 @@ +# Python dependencies for Web3AI +openai>=1.0.0 +python-dotenv>=1.0.0