Using AI APIs in Your Project
Using AI APIs in Your Project
Integrate OpenAI into Your JavaScript Applications
By AI Learning Assistant · OpenAI API · System Prompts · AI Integration
🤖 AI-POWERED LESSON
This article is paired with a live AI session. You will learn to integrate AI APIs into your Node.js projects — the same pattern used by thousands of production applications. Every code block includes detailed line-by-line comments.
The OpenAI API is your gateway to adding AI capabilities to any JavaScript application. Whether you're building a chatbot, a code assistant, a content generator, or a smart search feature, the pattern is the same: send a prompt, receive an intelligent response.
Today, you'll learn how to set up the OpenAI SDK, send messages to a model, and control the AI's behavior using system prompts. The system prompt is your secret weapon it's how you turn a general-purpose AI into a specialized assistant that behaves exactly how you need.
We will cover installing the OpenAI SDK, initializing the client, sending messages to the API, writing effective system prompts, and building a reusable AI helper function. By the end, you'll have a working AI-powered assistant that can answer JavaScript questions.
What is a System Prompt?
CONTROL BEHAVIOR · SET PERSONA · SHAPE TONE
In the OpenAI API, messages have a role property. The two most important roles are system and user. The system message tells the AI who it is and how it should behave. The user message is the actual question or request.
Think of the system prompt as giving an actor their character description before they perform. Without it, the AI behaves neutrally. With a good system prompt, it becomes a senior developer, a patient teacher, a witty comedian, or a strict security auditor whatever you need.
🎯 SYSTEM PROMPT BEST PRACTICES
Be specific — "You are a senior JavaScript developer" works better than "You are helpful." Set tone rules "Use clear examples. Be patient. Explain the 'why' not just the 'how'." Set boundaries "If you don't know, say you don't know. Never invent APIs."
Build the AI Helper
OPENAI SDK · ASYNC/AWAIT · REUSABLE FUNCTION
📜 CODE BLOCK 1: Complete AI Helper (ai-helper.js with line-by-line comments)
// ============================================ // AI HELPER — Query OpenAI from Node.js // ============================================ // STEP 1: Install the OpenAI package first // $ npm install openai // STEP 2: Import the OpenAI SDK // WHY: require() loads the openai library const OpenAI = require("openai"); // STEP 3: Initialize the client with your API key // WHY: The client handles authentication and API calls // HOW: Get your key from https://platform.openai.com/api-keys // PRO TIP: Never hardcode keys! Use environment variables in production const client = new OpenAI({ apiKey: "YOUR_API_KEY_HERE" // Replace with your actual key }); // ============================================ // REUSABLE AI FUNCTION // ============================================ // WHY: async because we're waiting for the API response // WHY: Takes a question string, returns AI answer as a string async function askAI(question) { // WHY: Call the chat completion endpoint // HOW: We specify model, messages array with system and user roles const response = await client.chat.completions.create({ // model: gpt-3.5-turbo is fast, affordable, and great for most tasks model: "gpt-3.5-turbo", // messages: array of conversation turns messages: [ { // SYSTEM PROMPT — Controls the AI's persona and behavior // This turns GPT from a general model into a specialized assistant role: "system", content: "You are a helpful JavaScript coding assistant for beginner developers. Explain concepts clearly, provide examples, and be patient." }, { // USER PROMPT — The actual question from the user role: "user", content: question } ] }); // WHY: Extract just the answer text from the API response // HOW: response.choices[0].message.content contains the AI's reply return response.choices[0].message.content; } // ============================================ // TEST THE FUNCTION // ============================================ async function main() { // WHY: Ask a real JavaScript question // The AI will respond with multiple methods to reverse a string const answer = await askAI("How do I reverse a string in JavaScript? Show me 3 methods."); // WHY: Print the AI's response to the terminal console.log(answer); } // Run the main function main().catch(error => console.error("Error:", error)); // ============================================ // HOW TO RUN // ============================================ // 1. Save as ai-helper.js // 2. Run: node ai-helper.js // 3. The AI will answer the question in your terminal
📜 CODE BLOCK 2: Production-Ready Version (with .env and error handling)
// PRODUCTION VERSION — Secure and robust // Install: npm install openai dotenv // Load environment variables from .env file require("dotenv").config(); const OpenAI = require("openai"); // Read API key from environment variable (secure!) const client = new OpenAI({ apiKey: process.env.OPENAI_API_KEY }); // Check if API key exists if (!process.env.OPENAI_API_KEY) { console.error("Error: OPENAI_API_KEY not found in environment variables"); console.error("Create a .env file with: OPENAI_API_KEY=your_key_here"); process.exit(1); } // Reusable function with custom system prompt option async function askAI(question, systemPrompt = "You are a helpful JavaScript coding assistant.") { try { const response = await client.chat.completions.create({ model: "gpt-3.5-turbo", messages: [ { role: "system", content: systemPrompt }, { role: "user", content: question } ] }); return response.choices[0].message.content; } catch (error) { console.error("AI API Error:", error.message); return "Sorry, I couldn't process your request. Please check your API key and try again."; } }
System Prompt Comparison
| Prompt Type | Weak Prompt | Strong Prompt |
|---|---|---|
| Persona | "You are helpful" | "You are a senior JS developer with 10 years experience" |
| Tone | Not specified | "Be patient, encouraging, never condescending" |
| Output Format | Not specified | "1) Answer, 2) Example 1, 3) Example 2, 4) Challenge" |
| Boundaries | Not specified | "Never invent APIs. Flag security issues as HIGH PRIORITY" |
API Key Security
NEVER HARDCODE · USE .ENV · GITIGNORE
🚫 NEVER hardcode API keys in your source code!
If you commit an API key to GitHub, bots will find it within minutes and use it to make requests on your dime. Always use environment variables. Create a .env file, add it to .gitignore, and access keys via process.env.KEY_NAME. Use the dotenv package to load them.
🤖 HOW AI ACCELERATES THIS TOPIC
Ask AI: "Improve this system prompt to make the AI give shorter, more concise answers." Iterate on your prompts with AI help.
Ask: "Write a system prompt that makes the AI act as a code reviewer who focuses only on security vulnerabilities." Specialize your assistant.
Ask: "What are the rate limits for the OpenAI API and how should I handle them in my code?" Learn production best practices.
AI-Assisted JavaScript Learning · OpenAI API Integration · Master System Prompts
Complete this lesson
Mark as complete to track your progress