-
Notifications
You must be signed in to change notification settings - Fork 0
Add OpenAI ChatGPT integration with REST API endpoints #5
New issue
Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.
By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.
Already on GitHub? Sign in to your account
Open
Copilot
wants to merge
4
commits into
main
Choose a base branch
from
copilot/add-openai-chatgpt-integration
base: main
Could not load branches
Branch not found: {{ refName }}
Loading
Could not load tags
Nothing to show
Loading
Are you sure you want to change the base?
Some commits from the old base branch may be removed from the timeline,
and old review comments may become outdated.
Open
Changes from all commits
Commits
Show all changes
4 commits
Select commit
Hold shift + click to select a range
File filter
Filter by extension
Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
There are no files selected for viewing
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| 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 |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -1,2 +1,5 @@ | ||
| *.agdai | ||
| MAlonzo/** | ||
| node_modules/ | ||
| .env | ||
| package-lock.json |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| 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. |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| 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); | ||
| } | ||
| } 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`); | ||
| }); | ||
Oops, something went wrong.
Oops, something went wrong.
Add this suggestion to a batch that can be applied as a single commit.
This suggestion is invalid because no changes were made to the code.
Suggestions cannot be applied while the pull request is closed.
Suggestions cannot be applied while viewing a subset of changes.
Only one suggestion per line can be applied in a batch.
Add this suggestion to a batch that can be applied as a single commit.
Applying suggestions on deleted lines is not supported.
You must change the existing code in this line in order to create a valid suggestion.
Outdated suggestions cannot be applied.
This suggestion has been applied or marked resolved.
Suggestions cannot be applied from pending reviews.
Suggestions cannot be applied on multi-line comments.
Suggestions cannot be applied while the pull request is queued to merge.
Suggestion cannot be applied right now. Please check back later.
There was a problem hiding this comment.
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-stringmessage) are converted into{ success: false, error: ... }, which the/chatendpoint 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.