1. Project Overview
In this project you’ll build a simple web interface where a user can describe a Windows 10 problem. When the user submits their query, your app sends that text to an OpenAI-powered backend. The backend calls the OpenAI API to get troubleshooting advice, then sends the response back to the client for display.
2. Prerequisites
Before starting, make sure you have:
- Node.js and npm installed
- An OpenAI API key (you can sign up on OpenAI’s website to obtain one)
- Install “npm install openai”
- create key, save
- Basic familiarity with JavaScript, HTML, and Node.js
After you make a OpenAI API key, you can test it with:
npm install openai
Then create and run:
const OpenAI = require("openai");
const client = new OpenAI({
apiKey: "your new key"
});
async function getCompletion() {
const completion = await client.chat.completions.create({
model: "gpt-4o-mini",
store: true,
messages: [{ role: "user", content: "write a haiku about ai" }]
});
console.log(completion.choices[0].message);
}
getCompletion();
3. Setting Up the Project
a. Create Your Project Folder
Open your terminal and create a new directory for your project:
mkdir windows10-diagnoser
cd windows10-diagnoser
b. Initialize a Node.js Project
Initialize your project with npm:
npm init -y
c. Install Dependencies
Install Express (to set up a simple server), dotenv (for environment variables), and axios (for HTTP requests, although you could also use node-fetch):
npm install express dotenv axios
Note: You can also use the official OpenAI SDK if preferred.
4. Building the Back-End
a. Create a Server File
Create a file called server.js and add the following code:
// server.js
require('dotenv').config();
const express = require('express');
const axios = require('axios');
const bodyParser = require('body-parser');
const app = express();
const port = process.env.PORT || 3000;
// Middleware
app.use(bodyParser.json());
app.use(express.static('public')); // Serve static files from "public" folder
// Endpoint to handle queries
app.post('/api/diagnose', async (req, res) => {
const userQuery = req.body.query;
if (!userQuery) {
return res.status(400).json({ error: 'No query provided' });
}
try {
// Construct a prompt tailored to diagnose Windows 10 issues
const prompt = `I am a technical assistant for Windows 10. A user describes an issue: "${userQuery}". Provide troubleshooting steps and possible fixes in clear, actionable language.`;
// Call the OpenAI API (adjust the endpoint and parameters as needed)
const response = await axios.post('https://api.openai.com/v1/completions', {
model: "text-davinci-003", // or a ChatGPT model if available
prompt: prompt,
max_tokens: 200,
temperature: 0.5,
}, {
headers: {
'Content-Type': 'application/json',
'Authorization': `Bearer ${process.env.OPENAI_API_KEY}`,
},
});
const diagnosis = response.data.choices[0].text.trim();
res.json({ diagnosis });
} catch (error) {
console.error('Error calling OpenAI API:', error.response ? error.response.data : error.message);
res.status(500).json({ error: 'Failed to get a response from OpenAI' });
}
});
app.listen(port, '0.0.0.0', () => {
console.log(`Server running on port ${port}`);
});
b. Configure Your Environment Variables
Create a .env file in your project root and add your OpenAI API key:
OPENAI_API_KEY=your_openai_api_key_here
Remember: Never commit your API key to version control.
5. Building the Front-End
a. Create a Public Folder and an HTML File
Inside your project directory, create a folder named public and within it, create an index.html file:
<!-- public/index.html -->
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Windows 10 Diagnoser</title>
<style>
body { font-family: Arial, sans-serif; margin: 2em; }
input, button, textarea { font-size: 1em; margin-top: 0.5em; }
#response { margin-top: 1em; padding: 1em; background: #f4f4f4; border: 1px solid #ccc; }
</style>
</head>
<body>
<h1>Windows 10 Diagnostic Assistant</h1>
<p>Describe the issue you're experiencing with Windows 10:</p>
<textarea id="userQuery" rows="4" cols="50" placeholder="e.g., My computer is running very slow, or I'm having network issues."></textarea>
<br>
<button id="submitBtn">Submit</button>
<div id="response"></div>
<script src="app.js"></script>
</body>
</html>
b. Create a JavaScript File for Front-End Logic
Inside the same public folder, create a file called app.js:
// public/app.js
document.getElementById('submitBtn').addEventListener('click', async () => {
const userQuery = document.getElementById('userQuery').value.trim();
if (!userQuery) {
alert('Please describe your issue.');
return;
}
const responseDiv = document.getElementById('response');
responseDiv.textContent = 'Processing your request...';
try {
const res = await fetch('/api/diagnose', {
method: 'POST',
headers: {
'Content-Type': 'application/json'
},
body: JSON.stringify({ query: userQuery })
});
const data = await res.json();
if (data.error) {
responseDiv.textContent = 'Error: ' + data.error;
} else {
responseDiv.textContent = data.diagnosis;
}
} catch (error) {
responseDiv.textContent = 'Error communicating with server.';
}
});
6. Running and Testing the App
a. Start Your Server
In your terminal, run:
node server.js
Your server should start on port 3000 (or the port specified in your environment).
b. Open the App in Your Browser
Navigate to http://localhost:3000 in your browser. Enter a description of your Windows 10 issue and click “Submit” to see the diagnostic advice generated by the OpenAI agent.
7. Enhancements and Next Steps
- Error Handling: Enhance error reporting both on the client and server.
- Security: Ensure the API key is kept secure by restricting API access and not exposing it in the front end.
- UI/UX Improvements: Consider adding loading animations or more sophisticated styling.
- Additional Features: You might expand the app to handle multiple types of diagnostic queries or integrate logging and history of past queries.
Conclusion
You’ve now built a JavaScript web app that interacts with an OpenAI agent to help diagnose and fix Windows 10 issues. By following these steps, you learned how to create a full-stack solution—from setting up a Node.js back end to developing a responsive front end that communicates with OpenAI’s API.
