From a557ce12e22ef86e3cf463df4084025b99c3a09d Mon Sep 17 00:00:00 2001 From: "copilot-swe-agent[bot]" <198982749+Copilot@users.noreply.github.com> Date: Sun, 14 Dec 2025 17:09:27 +0000 Subject: [PATCH 1/4] Initial plan From c05e1807a3d4ffb8c72435be98d0d1fea41ef5bf Mon Sep 17 00:00:00 2001 From: "copilot-swe-agent[bot]" <198982749+Copilot@users.noreply.github.com> Date: Sun, 14 Dec 2025 17:12:34 +0000 Subject: [PATCH 2/4] Add OpenAI ChatGPT integration with API endpoints Co-authored-by: lippytm <65956507+lippytm@users.noreply.github.com> --- .env.example | 8 +++ .gitignore | 3 + README.md | 190 ++++++++++++++++++++++++++++++++++++++++++++++++- index.js | 109 ++++++++++++++++++++++++++++ openai-chat.js | 102 ++++++++++++++++++++++++++ package.json | 23 ++++++ 6 files changed, 434 insertions(+), 1 deletion(-) create mode 100644 .env.example create mode 100644 index.js create mode 100644 openai-chat.js create mode 100644 package.json diff --git a/.env.example b/.env.example new file mode 100644 index 0000000..c8776d5 --- /dev/null +++ b/.env.example @@ -0,0 +1,8 @@ +# OpenAI API Configuration +OPENAI_API_KEY=your_openai_api_key_here + +# Server Configuration +PORT=3000 + +# ChatGPT Model Configuration +OPENAI_MODEL=gpt-3.5-turbo diff --git a/.gitignore b/.gitignore index 58ab67f..35d852a 100644 --- a/.gitignore +++ b/.gitignore @@ -1,2 +1,5 @@ *.agdai MAlonzo/** +node_modules/ +.env +package-lock.json diff --git a/README.md b/README.md index 25041f3..03fa19a 100644 --- a/README.md +++ b/README.md @@ -1 +1,189 @@ -# Web3AI \ No newline at end of file +# Web3AI + +Web3AI is a project that integrates OpenAI ChatGPT capabilities, providing RESTful API endpoints to interact with ChatGPT programmatically. + +## Features + +- **OpenAI ChatGPT Integration**: Send prompts and receive AI-generated responses +- **RESTful API**: Simple HTTP endpoints for ChatGPT interaction +- **Conversation History**: Support for maintaining conversation context +- **System Prompts**: Ability to set system-level instructions for the AI + +## Prerequisites + +- Node.js (v14 or higher) +- npm (Node Package Manager) +- OpenAI API Key ([Get one here](https://platform.openai.com/api-keys)) + +## Installation + +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: +```bash +cp .env.example .env +``` + +4. Edit `.env` file and add your OpenAI API key: +```env +OPENAI_API_KEY=your_actual_api_key_here +PORT=3000 +OPENAI_MODEL=gpt-3.5-turbo +``` + +## Usage + +### Starting the Server + +Run the following command to start the server: +```bash +npm start +``` + +The server will start on the port specified in your `.env` file (default: 3000). + +### API Endpoints + +#### 1. Health Check +**GET** `/health` + +Check if the server is running. + +**Example:** +```bash +curl http://localhost:3000/health +``` + +**Response:** +```json +{ + "status": "ok", + "message": "Web3AI Server is running" +} +``` + +#### 2. Chat Endpoint +**POST** `/chat` + +Send a message to ChatGPT and receive a response. + +**Request Body:** +```json +{ + "message": "What is Web3?", + "conversationHistory": [] +} +``` + +**Example:** +```bash +curl -X POST http://localhost:3000/chat \ + -H "Content-Type: application/json" \ + -d '{"message": "What is Web3?"}' +``` + +**Response:** +```json +{ + "success": true, + "message": "Web3 refers to the third generation of the internet...", + "model": "gpt-3.5-turbo", + "usage": { + "prompt_tokens": 10, + "completion_tokens": 50, + "total_tokens": 60 + }, + "finishReason": "stop" +} +``` + +#### 3. Chat with System Prompt +**POST** `/chat/system` + +Send a message with custom system instructions. + +**Request Body:** +```json +{ + "message": "Explain blockchain", + "systemPrompt": "You are a helpful assistant that explains technical concepts in simple terms." +} +``` + +**Example:** +```bash +curl -X POST http://localhost:3000/chat/system \ + -H "Content-Type: application/json" \ + -d '{"message": "Explain blockchain", "systemPrompt": "You are a helpful assistant that explains technical concepts in simple terms."}' +``` + +### Conversation History + +To maintain context across multiple messages, include the conversation history in your requests: + +```json +{ + "message": "Can you elaborate on that?", + "conversationHistory": [ + { "role": "user", "content": "What is Web3?" }, + { "role": "assistant", "content": "Web3 refers to..." } + ] +} +``` + +## Project Structure + +``` +Web3AI/ +├── index.js # Main server file with API endpoints +├── openai-chat.js # OpenAI ChatGPT integration module +├── package.json # Project dependencies and scripts +├── .env.example # Environment variables template +├── .env # Your local environment variables (not in git) +└── README.md # This file +``` + +## Environment Variables + +- `OPENAI_API_KEY`: Your OpenAI API key (required) +- `PORT`: Server port (default: 3000) +- `OPENAI_MODEL`: OpenAI model to use (default: gpt-3.5-turbo) + +## Error Handling + +The API returns appropriate HTTP status codes and error messages: + +- `400`: Bad Request (missing required fields) +- `500`: Internal Server Error (OpenAI API errors or server issues) + +**Error Response Example:** +```json +{ + "success": false, + "error": "Message is required", + "message": null +} +``` + +## Security Notes + +- Never commit your `.env` file or expose your OpenAI API key +- The `.env` file is included in `.gitignore` to prevent accidental commits +- Keep your API key secure and rotate it if compromised + +## License + +ISC + +## Contributing + +Contributions are welcome! Please feel free to submit a Pull Request. diff --git a/index.js b/index.js new file mode 100644 index 0000000..747ceb9 --- /dev/null +++ b/index.js @@ -0,0 +1,109 @@ +require('dotenv').config(); +const express = require('express'); +const OpenAIChat = require('./openai-chat'); + +const app = express(); +const PORT = process.env.PORT || 3000; + +// Middleware to parse JSON bodies +app.use(express.json()); + +// Initialize OpenAI Chat client +const openaiChat = new OpenAIChat( + process.env.OPENAI_API_KEY, + process.env.OPENAI_MODEL || 'gpt-3.5-turbo' +); + +/** + * Health check endpoint + */ +app.get('/health', (req, res) => { + res.json({ status: 'ok', message: 'Web3AI Server is running' }); +}); + +/** + * Chat endpoint - Send messages to ChatGPT + * POST /chat + * Body: { + * "message": "Your message here", + * "conversationHistory": [] // Optional + * } + */ +app.post('/chat', async (req, res) => { + try { + const { message, conversationHistory } = req.body; + + if (!message) { + return res.status(400).json({ + success: false, + error: 'Message is required' + }); + } + + const response = await openaiChat.sendMessage(message, conversationHistory); + + if (response.success) { + res.json(response); + } else { + res.status(500).json(response); + } + } catch (error) { + console.error('Error in /chat endpoint:', error); + res.status(500).json({ + success: false, + error: 'Internal server error', + message: null + }); + } +}); + +/** + * Chat endpoint with system prompt + * POST /chat/system + * Body: { + * "message": "Your message here", + * "systemPrompt": "System instructions" + * } + */ +app.post('/chat/system', async (req, res) => { + try { + const { message, systemPrompt } = req.body; + + if (!message) { + return res.status(400).json({ + success: false, + error: 'Message is required' + }); + } + + if (!systemPrompt) { + return res.status(400).json({ + success: false, + error: 'System prompt is required' + }); + } + + const response = await openaiChat.sendMessageWithSystem(message, systemPrompt); + + if (response.success) { + res.json(response); + } else { + res.status(500).json(response); + } + } catch (error) { + console.error('Error in /chat/system endpoint:', error); + res.status(500).json({ + success: false, + error: 'Internal server error', + message: null + }); + } +}); + +// Start server +app.listen(PORT, () => { + console.log(`Web3AI Server running on port ${PORT}`); + console.log(`Health check: http://localhost:${PORT}/health`); + console.log(`Chat endpoint: POST http://localhost:${PORT}/chat`); + console.log(`Chat with system prompt: POST http://localhost:${PORT}/chat/system`); +}); diff --git a/openai-chat.js b/openai-chat.js new file mode 100644 index 0000000..fa15230 --- /dev/null +++ b/openai-chat.js @@ -0,0 +1,102 @@ +const OpenAI = require('openai'); + +/** + * OpenAI ChatGPT Integration Module + * Handles communication with OpenAI's ChatGPT API + */ +class OpenAIChat { + constructor(apiKey, model = 'gpt-3.5-turbo') { + if (!apiKey) { + throw new Error('OpenAI API key is required'); + } + + this.client = new OpenAI({ + apiKey: apiKey, + }); + + this.model = model; + } + + /** + * Send a chat message to OpenAI ChatGPT and get a response + * @param {string} message - The user's message + * @param {Array} conversationHistory - Optional conversation history + * @returns {Promise} Response object with message and metadata + */ + async sendMessage(message, conversationHistory = []) { + try { + if (!message || typeof message !== 'string') { + throw new Error('Message must be a non-empty string'); + } + + // Build messages array with conversation history + const messages = [ + ...conversationHistory, + { role: 'user', content: message } + ]; + + // Make API call to OpenAI + const completion = await this.client.chat.completions.create({ + model: this.model, + messages: messages, + }); + + // Extract the response + const response = completion.choices[0].message.content; + + return { + success: true, + message: response, + model: this.model, + usage: completion.usage, + finishReason: completion.choices[0].finish_reason + }; + } catch (error) { + console.error('Error communicating with OpenAI:', error.message); + return { + success: false, + error: error.message, + message: null + }; + } + } + + /** + * Send a chat message with system instructions + * @param {string} message - The user's message + * @param {string} systemPrompt - System instructions for the AI + * @returns {Promise} Response object with message and metadata + */ + async sendMessageWithSystem(message, systemPrompt) { + try { + const messages = [ + { role: 'system', content: systemPrompt }, + { role: 'user', content: message } + ]; + + const completion = await this.client.chat.completions.create({ + model: this.model, + messages: messages, + }); + + const response = completion.choices[0].message.content; + + return { + success: true, + message: response, + model: this.model, + usage: completion.usage, + finishReason: completion.choices[0].finish_reason + }; + } catch (error) { + console.error('Error communicating with OpenAI:', error.message); + return { + success: false, + error: error.message, + message: null + }; + } + } +} + +module.exports = OpenAIChat; diff --git a/package.json b/package.json new file mode 100644 index 0000000..87b952b --- /dev/null +++ b/package.json @@ -0,0 +1,23 @@ +{ + "name": "web3ai", + "version": "1.0.0", + "description": "Web3AI - OpenAI ChatGPT Integration", + "main": "index.js", + "scripts": { + "start": "node index.js", + "test": "echo \"Error: no test specified\" && exit 1" + }, + "keywords": [ + "web3", + "ai", + "openai", + "chatgpt" + ], + "author": "", + "license": "ISC", + "dependencies": { + "dotenv": "^16.3.1", + "express": "^4.18.2", + "openai": "^4.20.0" + } +} From 7dbb5efb06411fb19f9be7951174545426f9c216 Mon Sep 17 00:00:00 2001 From: "copilot-swe-agent[bot]" <198982749+Copilot@users.noreply.github.com> Date: Sun, 14 Dec 2025 17:15:10 +0000 Subject: [PATCH 3/4] Fix validation and error handling in openai-chat.js Co-authored-by: lippytm <65956507+lippytm@users.noreply.github.com> --- openai-chat.js | 18 ++++++++++++++++++ 1 file changed, 18 insertions(+) diff --git a/openai-chat.js b/openai-chat.js index fa15230..ad9a8ff 100644 --- a/openai-chat.js +++ b/openai-chat.js @@ -41,6 +41,11 @@ class OpenAIChat { messages: messages, }); + // Validate response + if (!completion.choices || completion.choices.length === 0) { + throw new Error('No response received from OpenAI'); + } + // Extract the response const response = completion.choices[0].message.content; @@ -69,6 +74,14 @@ class OpenAIChat { */ async sendMessageWithSystem(message, systemPrompt) { try { + if (!message || typeof message !== 'string') { + throw new Error('Message must be a non-empty string'); + } + + if (!systemPrompt || typeof systemPrompt !== 'string') { + throw new Error('System prompt must be a non-empty string'); + } + const messages = [ { role: 'system', content: systemPrompt }, { role: 'user', content: message } @@ -79,6 +92,11 @@ class OpenAIChat { messages: messages, }); + // Validate response + if (!completion.choices || completion.choices.length === 0) { + throw new Error('No response received from OpenAI'); + } + const response = completion.choices[0].message.content; return { From d8eadb090a1d6505f417ca021e59f94ed8bba30f Mon Sep 17 00:00:00 2001 From: "copilot-swe-agent[bot]" <198982749+Copilot@users.noreply.github.com> Date: Sun, 14 Dec 2025 17:17:11 +0000 Subject: [PATCH 4/4] Add API key validation at server startup Co-authored-by: lippytm <65956507+lippytm@users.noreply.github.com> --- index.js | 7 +++++++ 1 file changed, 7 insertions(+) diff --git a/index.js b/index.js index 747ceb9..9dd689f 100644 --- a/index.js +++ b/index.js @@ -5,6 +5,13 @@ const OpenAIChat = require('./openai-chat'); const app = express(); const PORT = process.env.PORT || 3000; +// Validate required environment variables +if (!process.env.OPENAI_API_KEY) { + console.error('Error: OPENAI_API_KEY is not set in environment variables'); + console.error('Please set OPENAI_API_KEY in your .env file'); + process.exit(1); +} + // Middleware to parse JSON bodies app.use(express.json());