Skip to content

Commit c7e20e8

Browse files
committed
feat: Add OpenAI Moderation API example
1 parent d551d77 commit c7e20e8

File tree

6 files changed

+146
-26
lines changed

6 files changed

+146
-26
lines changed

.env.example

Lines changed: 2 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -58,6 +58,8 @@ LOB_KEY=test_814e892b199d65ef6dbb3e4ad24689559ca
5858

5959
NYT_KEY=9548be6f3a64163d23e1539f067fcabd:5:68537648
6060

61+
OPENAI_API_KEY=sk-xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx
62+
6163
PAYPAL_ID=AdGE8hDyixVoHmbhASqAThfbBcrbcgiJPBwlAM7u7Kfq3YU-iPGc6BXaTppt
6264
PAYPAL_SECRET=EPN0WxB5PaRaumTB1ZpCuuTqLqIlF6_EWUcAbZV99Eu86YeNBVm9KVsw_Ez5
6365

README.md

Lines changed: 14 additions & 26 deletions
Original file line numberDiff line numberDiff line change
@@ -396,6 +396,17 @@ Obtain SMTP credentials from a provider for transactional emails. Set the SMTP_U
396396

397397
<hr>
398398

399+
<img src="https://i.imgur.com/iCsCgp6.png" height="75">
400+
401+
The OpenAI moderation API for checking harmful inputs is free to use as long as you have paid credits in your OpenAI developer account. The cost of using their other models depends on the model, as well as the input and output size of the API call.
402+
403+
- Visit <a href="https://platform.openai.com/api-keys" target="_blank">OpenAI API Keys</a>
404+
- Sign in or create an OpenAI account.
405+
- Click on **Create new secret key** to generate an API key.
406+
- Copy and paste the generated API key into your `.env` file as `OPENAI_API_KEY` or set it as an environment variable.
407+
408+
<hr>
409+
399410
<img src="https://i.imgur.com/QMjwCk6.png" height="50">
400411

401412
- Sign in at <a href="https://developer.x.com/" target="_blank">https://developer.x.com/</a>
@@ -1321,42 +1332,19 @@ To view the app, find your docker IP address + port 8080 ( this will typically b
13211332

13221333
## Deployment
13231334

1324-
Using a local instance on your laptop with ngrok is a good solution for your demo during the hackathon, and you wouldn't necessarily need to deploy to a cloud platform. If you wish to have your app run 24x7 for a general audience, once you are ready to deploy your app, you will need to create an account with a cloud platform to host it. There are a number of cloud service providers out there that you can research. Service providers like AWS provide a free tier of service which can help you get started with just some minor costs (such as traffic overage if any, etc).
1325-
1326-
---
1327-
1328-
### AWS
1329-
1330-
<img src="https://upload.wikimedia.org/wikipedia/commons/thumb/9/93/Amazon_Web_Services_Logo.svg/512px-Amazon_Web_Services_Logo.svg.png" width="100">
1331-
1332-
[AWS Free Tier](https://aws.amazon.com/free) provides 12 months of compute (EC2 Windows or Linux) for free. AWS has up-to-date guides and instructions for setting up your host.
1333-
1334-
| Service | Setup |
1335-
| ----------------------------------------------------------------------------------------------------------------------------------------- | ----------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- |
1336-
| <img src="https://icon.icepanel.io/AWS/svg/Compute/EC2.svg" width="50"><br>**EC2 Instance** | EC2 is the compute server to host your application. You can run your application on your EC2 instance similar to how you run applications on your computer.<br><br>**Setup Steps:**<br>1. Create an AWS account and/or login to AWS console<br>2. In the search bar search for "EC2", and then pick EC2 from the services<br>3. Click on Launch an instance<br>4. Pick an OS image and Instance type. You can go with a free-tier one to try EC2 before upgrading to an instance that matches your traffic and application requirements<br>5. Under the Network settings, Create a security group, but remove checkboxes from Allow SSH, HTTPS, and HTTP. You will expose the proper ports later<br>6. You can go with the defaults for the remaining setting as long as they match with the free-tier if that is what you are choosing to use<br>7. Launch the instance, and wait for it to be provisioned |
1337-
| <img src="https://icon.icepanel.io/AWS/svg/Networking-Content-Delivery/Virtual-Private-Cloud.svg" width="50"><br>**VPC / Security Group** | A security group controls the traffic that is allowed to reach and leave the resources that it is associated with. <br><br>**Setup Steps:**<br>1. ---.<br>2. ---.<br>3. ---.<br>4. ---.<br> |
1338-
| <img src="https://icon.icepanel.io/AWS/svg/Developer-Tools/CodeDeploy.svg" width="50"><br>**CodeDeploy** | AWS CodeDeploy is a deployment service that automates application deployments to various compute platforms such as Amazon EC2 instances, on-premises instances, serverless AWS Lambda functions, and Amazon ECS services. You can use it to have your instance auto-update from your git repo like github, bitbucket, etc. Note that using the CodeDeploy service would require S3 storage usage as well. <br><br>**Setup Steps:**<br>1. ---.<br>2. ---.<br>3. ---.<br>4. ---.<br> |
1339-
| <img src="https://icon.icepanel.io/AWS/svg/Compute/App-Runner.svg" width="50"><br>**App Runner** | If your application is stable and you expect surges of traffic, you can move from direct EC2 deployment to AWS App Runner which can scale the number of hosts that the application runs on up and down depending on the traffic to your host. <br><br>**Setup Steps:**<br>1. ---.<br>2. ---.<br>3. ---.<br>4. ---.<br> |
1340-
| <img src="https://icon.icepanel.io/AWS/svg/Compute/Elastic-Beanstalk.svg" width="50"><br>**Elastic Beanstalk** | You can use an Elastic Beanstalk deployment instead of an EC2 deployment of your application. When using Elastic Beanstalk deployments you are just provided with a code execution environment and you are no longer required to maintain the OS for the server (i.e. Windows or Linux security patching, etc.) <br><br>**Setup Steps:**<br>1. ---.<br>2. ---.<br>3. ---.<br>4. ---.<br> |
1341-
| <img src="https://icon.icepanel.io/AWS/svg/Containers/Elastic-Container-Service.svg" width="50"><br>**Elastic Container Service** | ECS is the fully managed AWS container service that enables you to run docker containers on EC2 instances. <br><br>**Setup Steps:**<br>1. ---.<br>2. ---.<br>3. ---.<br>4. ---.<br> |
1342-
| <img src="https://icon.icepanel.io/AWS/svg/Compute/Fargate.svg" width="50"><br>**Fargate** | Fargate takes your container deployment to the next level by moving you to a serverless setup for running containers. <br><br>**Setup Steps:**<br>1. ---.<br>2. ---.<br>3. ---.<br>4. ---.<br> |
1343-
| <img src="https://icon.icepanel.io/AWS/svg/Compute/Bottlerocket.svg" width="50"><br>**Bedrock** | Bedrock provides serverless access to use Foundational LLM models such as Llama, Amazon Titan, Amazon Nova, etc. <br><br>**Setup Steps:**<br>1. ---.<br>2. ---.<br>3. ---.<br>4. ---.<br> |
1344-
| <img src="https://icon.icepanel.io/AWS/svg/Networking-Content-Delivery/CloudFront.svg" width="50"><br>**CloudFront** | You can use AWS CloudFront as the edge service that fronts client requests. CloudFront can cache static content to reduce resource usage and speed up data delivery. It can also serve as an extra layer of security because your application server isn't directly exposed to the internet traffic. <br><br>**Setup Steps:**<br>1. ---.<br>2. ---.<br>3. ---.<br>4. ---.<br> |
1345-
| <img src="https://icon.icepanel.io/AWS/svg/Networking-Content-Delivery/CloudFront.svg" width="50"><br>**Simple Email Service** | You can use AWS SES just like an SMTP server. Don't try to set up an email server on your EC2 instance to send out email, use SES. Note that SES strictly enforces anti-spam rules, so don't send anything that a recipient may mark as spam as it will get reported back to AWS. If **1%** of your emails get reported as spam by recipients AWS will suspend your SES service. Also you should set up mail settings such as SPF, DMARC and DKIM so others can't spoof your email address causing your domain to get tagged as a spam domain, since it may cause automated spam marking of your emails by email service providers such as gmail, yahoo, etc.<br><br>**Setup Steps:**<br>1. ---.<br>2. ---.<br>3. ---.<br>4. ---.<br> |
1335+
Using a local instance on your laptop with ngrok is a good solution for your demo during the hackathon, and you wouldn't necessarily need to deploy to a cloud platform. If you wish to have your app run 24x7 for a general audience, once you are ready to deploy your app, you will need to create an account with a cloud platform to host it. There are a number of cloud service providers out there that you can research. Service providers like AWS and Azure provide a free tier of service which can help you get started with just some minor costs (such as traffic overage if any, etc).
13461336
13471337
---
13481338
1349-
### Hosted MongoDB Atlas (can be on AWS)
1339+
### Hosted MongoDB Atlas
13501340
13511341
<img src="https://www.mongodb.com/assets/images/global/MongoDB_Logo_Dark.svg" width="200">
13521342
1353-
You can create an account with **MongoDB Atlas** and then pick one of the providers below which could be AWS for the deployment.
1354-
13551343
- Go to [https://www.mongodb.com/](https://www.mongodb.com/)
13561344
- Click the green **Try free** button
13571345
- Fill in your information then hit **Create your Atlas account**
13581346
- You will be redirected to Create New Cluster page.
1359-
- Select a **Cloud Provider and Region** (such as AWS and a free tier region)
1347+
- Select a **Cloud Provider and Region**
13601348
- Select cluster Tier to Free forever **Shared** Cluster
13611349
- Give Cluster a name (default: Cluster0)
13621350
- Click on green **:zap:Create Cluster button**

app.js

Lines changed: 2 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -230,6 +230,8 @@ app.get('/api/chart', apiController.getChart);
230230
app.get('/api/google/sheets', passportConfig.isAuthenticated, passportConfig.isAuthorized, apiController.getGoogleSheets);
231231
app.get('/api/quickbooks', passportConfig.isAuthenticated, passportConfig.isAuthorized, apiController.getQuickbooks);
232232
app.get('/api/trakt', apiController.getTrakt);
233+
app.get('/api/openai-moderation', apiController.getOpenAIModeration);
234+
app.post('/api/openai-moderation', apiController.postOpenAIModeration);
233235

234236
/**
235237
* OAuth authentication routes. (Sign in)

controllers/api.js

Lines changed: 61 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -1427,3 +1427,64 @@ exports.getTrakt = async (req, res, next) => {
14271427
next(error);
14281428
}
14291429
};
1430+
1431+
/**
1432+
* GET /api/openai-moderation
1433+
* OpenAI Moderation API example.
1434+
*/
1435+
exports.getOpenAIModeration = (req, res) => {
1436+
res.render('api/openai-moderation', {
1437+
title: 'OpenAI Input Moderation',
1438+
result: null,
1439+
error: null,
1440+
input: '',
1441+
});
1442+
};
1443+
1444+
/**
1445+
* POST /api/openai-moderation
1446+
* OpenAI Moderation API example.
1447+
*/
1448+
exports.postOpenAIModeration = async (req, res) => {
1449+
const openAiKey = process.env.OPENAI_API_KEY;
1450+
const inputText = req.body.inputText || '';
1451+
let result = null;
1452+
let error = null;
1453+
1454+
if (!openAiKey) {
1455+
error = 'OpenAI API key is not set in environment variables.';
1456+
} else if (!inputText.trim()) {
1457+
error = 'Text for input modaration check:';
1458+
} else {
1459+
try {
1460+
const response = await fetch('https://api.openai.com/v1/moderations', {
1461+
method: 'POST',
1462+
headers: {
1463+
'Content-Type': 'application/json',
1464+
Authorization: `Bearer ${openAiKey}`,
1465+
},
1466+
body: JSON.stringify({
1467+
model: 'text-moderation-latest',
1468+
input: inputText,
1469+
}),
1470+
});
1471+
if (!response.ok) {
1472+
const errData = await response.json().catch(() => ({}));
1473+
error = errData.error && errData.error.message ? errData.error.message : `API Error: ${response.status}`;
1474+
} else {
1475+
const data = await response.json();
1476+
result = data.results && data.results[0];
1477+
}
1478+
} catch (err) {
1479+
console.error('OpenAI Moderation API Error:', err);
1480+
error = 'Failed to call OpenAI Moderation API.';
1481+
}
1482+
}
1483+
1484+
res.render('api/openai-moderation', {
1485+
title: 'OpenAI Moderation API',
1486+
result,
1487+
error,
1488+
input: inputText,
1489+
});
1490+
};

views/api/index.pug

Lines changed: 6 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -131,3 +131,9 @@ block content
131131
.card-body
132132
img(src='https://i.imgur.com/Adtl9qg.png', height=40, style='padding: 0px 10px 0px 0px')
133133
| trakt.tv
134+
.col-md-4
135+
a(href='/api/openai-moderation', style='color: #000')
136+
.card.mb-3(style='background-color: #f5f5f5')
137+
.card-body
138+
img(src='https://i.imgur.com/E0QdCiI.png', height=40, style='padding: 0px 10px 0px 0px')
139+
| OpenAI Input Moderation

0 commit comments

Comments
 (0)