Skip to content
Draft
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
3 changes: 3 additions & 0 deletions .env.example
Original file line number Diff line number Diff line change
@@ -0,0 +1,3 @@
# OpenAI API Configuration
# Get your API key from: https://platform.openai.com/api-keys
OPENAI_API_KEY=your_openai_api_key_here
10 changes: 10 additions & 0 deletions .gitignore
Original file line number Diff line number Diff line change
@@ -1,2 +1,12 @@
*.agdai
MAlonzo/**

# Environment variables
.env

# Dependencies
node_modules/

# Logs
*.log
npm-debug.log*
124 changes: 124 additions & 0 deletions INTEGRATION_SUMMARY.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,124 @@
# OpenAI ChatGPT Integration Summary

## What Was Implemented

This integration adds OpenAI's ChatGPT capabilities to the Web3AI repository with the following components:

### 1. Project Structure
- **Node.js Project**: Initialized with npm, using ES modules (`"type": "module"`)
- **Dependencies**:
- `openai` (v6.1.0): Official OpenAI SDK
- `dotenv` (v17.2.3): Environment variable management

### 2. Core Files

#### `chatgpt.js`
Main service class that encapsulates OpenAI API interactions:
- **Features**:
- Secure API key loading from environment variables
- Two methods: `chat()` for complete responses, `streamChat()` for streaming
- Customizable options (model, temperature, max tokens, system prompt)
- Error handling with informative messages
- Web3/blockchain-specialized default system prompt

#### `index.js`
Demo script showcasing three use cases:
1. Simple chat query about Web3
2. Custom model parameters (temperature, max tokens)
3. Streaming response for real-time output

#### `.env.example`
Template for environment variables with:
- OPENAI_API_KEY placeholder
- Instructions on where to get the API key

#### `.gitignore`
Updated to exclude:
- `.env` (protect API keys)
- `node_modules/` (dependencies)
- Log files

#### `README.md`
Comprehensive documentation including:
- Features overview
- Prerequisites (Node.js v18+, OpenAI API key)
- Step-by-step setup instructions
- Usage examples
- API reference
- Security best practices

### 3. Security Features

βœ… **API Key Protection**:
- Environment variables for sensitive data
- `.env` excluded from git
- `.env.example` provides safe template
- Clear warnings in README about not committing keys

βœ… **Error Handling**:
- Validates API key presence on initialization
- Graceful error messages for API failures
- Token usage tracking

### 4. OpenAI Pro Account Features

The integration is designed to leverage OpenAI Pro capabilities:
- **GPT-4 Model**: Default model set to `gpt-4` (most advanced)
- **Higher Rate Limits**: Pro accounts have higher API rate limits
- **Advanced Features**: Access to latest models and features
- **Priority Support**: Better API response times

### 5. How to Use

**Setup:**
```bash
npm install
cp .env.example .env
# Edit .env with your OpenAI API key
npm start
```

**In Your Code:**
```javascript
import ChatGPTService from './chatgpt.js';

const chatGPT = new ChatGPTService();
const response = await chatGPT.chat('Your question here');
console.log(response.message);
```

### 6. Customization Options

All API calls support customization:
- `model`: Choose between gpt-4, gpt-4-turbo, gpt-3.5-turbo
- `temperature`: Control creativity (0 = deterministic, 1 = creative)
- `maxTokens`: Limit response length
- `systemPrompt`: Customize AI behavior/expertise

### 7. Testing Performed

βœ… JavaScript syntax validation
βœ… API key validation (error when missing)
βœ… Module imports working correctly
βœ… Git security (no secrets committed)
βœ… Documentation completeness

## Next Steps for Users

1. **Get OpenAI API Key**: Visit https://platform.openai.com/api-keys
2. **Set Up Environment**: Copy `.env.example` to `.env` and add your key
3. **Run Demo**: Execute `npm start` to see examples
4. **Integrate**: Use `ChatGPTService` class in your own code
5. **Customize**: Adjust models, prompts, and parameters as needed

## Files Modified/Created

- βœ… `package.json` - Created with OpenAI and dotenv dependencies
- βœ… `package-lock.json` - Created (dependency lock file)
- βœ… `chatgpt.js` - Created (main ChatGPT service)
- βœ… `index.js` - Created (demo/example script)
- βœ… `.env.example` - Created (environment template)
- βœ… `.gitignore` - Updated (added .env, node_modules, logs)
- βœ… `README.md` - Updated (comprehensive documentation)

All changes follow security best practices and provide a production-ready ChatGPT integration.
150 changes: 149 additions & 1 deletion README.md
Original file line number Diff line number Diff line change
@@ -1 +1,149 @@
# Web3AI
# Web3AI

AI-powered assistant using OpenAI's ChatGPT, specialized in Web3 and blockchain technology.

## Features

- πŸ€– Integration with OpenAI's GPT-4 model
- πŸ” Secure API key management using environment variables
- πŸ’¬ Simple chat interface with customizable options
- 🌊 Support for streaming responses
- 🎯 Specialized system prompts for Web3/blockchain topics

## Prerequisites

- Node.js (v18 or higher)
- npm or yarn
- OpenAI API key (requires OpenAI account with Pro access for advanced capabilities)

## Setup Instructions

### 1. Clone the Repository

```bash
git clone https://github.com/lippytm/Web3AI.git
cd Web3AI
```

### 2. Install Dependencies

```bash
npm install
```

### 3. Configure Environment Variables

1. Copy the example environment file:
```bash
cp .env.example .env
```

2. Edit the `.env` file and add your OpenAI API key:
```
OPENAI_API_KEY=your_actual_openai_api_key_here
```

**To 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
- Create a new secret key
- Copy and paste it into your `.env` file

⚠️ **Security Note**: Never commit your `.env` file to version control. It's already included in `.gitignore`.

## Usage

### Run the Demo

```bash
npm start
```

This will run the example script demonstrating three use cases:
1. Simple Web3 question
2. Custom model and temperature settings
3. Streaming response

### Using the ChatGPT Service in Your Code

```javascript
import ChatGPTService from './chatgpt.js';

const chatGPT = new ChatGPTService();

// Simple chat
const response = await chatGPT.chat('What is Web3?');
console.log(response.message);

// Chat with custom options
const customResponse = await chatGPT.chat(
'Explain smart contracts',
{
model: 'gpt-4',
temperature: 0.5,
maxTokens: 500,
systemPrompt: 'You are a blockchain expert.'
}
);

// Streaming response
const stream = await chatGPT.streamChat('What is DeFi?');
for await (const chunk of stream) {
const content = chunk.choices[0]?.delta?.content || '';
process.stdout.write(content);
}
```

## API Reference

### ChatGPTService

#### `chat(message, options)`

Send a message and get a complete response.

**Parameters:**
- `message` (string): The user's message/question
- `options` (object, optional):
- `model` (string): OpenAI model to use (default: 'gpt-4')
- `temperature` (number): Creativity level 0-1 (default: 0.7)
- `maxTokens` (number): Maximum response length (default: 1000)
- `systemPrompt` (string): System instruction for the AI

**Returns:** Promise resolving to an object with:
- `success` (boolean): Whether the request succeeded
- `message` (string): The AI's response
- `usage` (object): Token usage information
- `error` (string): Error message if failed

#### `streamChat(message, options)`

Send a message and get a streaming response.

**Parameters:** Same as `chat()`

**Returns:** Promise resolving to an async iterable stream

## Environment Variables

- `OPENAI_API_KEY` (required): Your OpenAI API key

## Models

This integration supports various OpenAI models:
- `gpt-4`: Most capable model (recommended, requires Pro account)
- `gpt-4-turbo`: Faster GPT-4 variant
- `gpt-3.5-turbo`: Faster and cheaper alternative

## Contributing

Contributions are welcome! Please feel free to submit a Pull Request.

## License

ISC

## Support

For issues or questions, please open an issue on GitHub.
78 changes: 78 additions & 0 deletions chatgpt.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,78 @@
import OpenAI from 'openai';
import dotenv from 'dotenv';

dotenv.config();

class ChatGPTService {
constructor() {
if (!process.env.OPENAI_API_KEY) {
throw new Error('OPENAI_API_KEY is not set in environment variables');
}

this.client = new OpenAI({
apiKey: process.env.OPENAI_API_KEY,
});
}

async chat(message, options = {}) {
const {
model = 'gpt-4',
temperature = 0.7,
maxTokens = 1000,
systemPrompt = 'You are a helpful AI assistant specialized in Web3 and blockchain technology.'
} = options;

try {
const response = await this.client.chat.completions.create({
model: model,
messages: [
{ role: 'system', content: systemPrompt },
{ role: 'user', content: message }
],
temperature: temperature,
max_tokens: maxTokens,
});

return {
success: true,
message: response.choices[0].message.content,
usage: response.usage
};
} catch (error) {
console.error('Error calling OpenAI API:', error.message);
return {
success: false,
error: error.message
};
}
}

async streamChat(message, options = {}) {
const {
model = 'gpt-4',
temperature = 0.7,
maxTokens = 1000,
systemPrompt = 'You are a helpful AI assistant specialized in Web3 and blockchain technology.'
} = options;

try {
const stream = await this.client.chat.completions.create({
model: model,
messages: [
{ role: 'system', content: systemPrompt },
{ role: 'user', content: message }
],
temperature: temperature,
max_tokens: maxTokens,
stream: true,
});

return stream;
} catch (error) {
console.error('Error calling OpenAI API:', error.message);
throw error;
}
}
}

export default ChatGPTService;
Loading