Skip to content
Open
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
8 changes: 8 additions & 0 deletions .env.example
Original file line number Diff line number Diff line change
@@ -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
3 changes: 3 additions & 0 deletions .gitignore
Original file line number Diff line number Diff line change
@@ -1,2 +1,5 @@
*.agdai
MAlonzo/**
node_modules/
.env
package-lock.json
190 changes: 189 additions & 1 deletion README.md
Original file line number Diff line number Diff line change
@@ -1 +1,189 @@
# Web3AI
# 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.
116 changes: 116 additions & 0 deletions index.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,116 @@
require('dotenv').config();
const express = require('express');
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());

// 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);
}
Comment on lines +39 to +56
Copy link

Copilot AI Feb 1, 2026

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Validation errors in OpenAIChat.sendMessage (e.g. non-string message) are converted into { success: false, error: ... }, which the /chat endpoint then returns with HTTP 500, even though these are client-side input issues. To keep API semantics clear, consider either performing full input validation in the route handler and returning HTTP 400 for invalid payloads, or distinguishing validation errors from upstream/OpenAI failures so that only true server errors result in 500 responses.

Copilot uses AI. Check for mistakes.
} 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`);
});
Loading
Loading