Lesson 1.2: Introduction to the OpenAI API
Setting up an API Key and Environment
To use the OpenAI API, you’ll need an API key and the right environment setup. Here’s a step-by-step guide for both Python and JavaScript.
1. Python Environment Setup
To set up the OpenAI API in Python, you’ll need to install the OpenAI Python package. Run the following command:
pip install openai
After installation, set your API key by importing the OpenAI package and configuring it in your script:
import openai # Set up your OpenAI API key openai.api_key = "your-api-key-here"
2. JavaScript Environment Setup
In JavaScript, you can make API requests using the fetch
function. Store your API key securely and ensure the environment supports fetch
calls (e.g., Node.js or browser with CORS permissions):
const apiKey = 'your-api-key-here';
Basic API Requests: Interacting with ChatGPT via HTTP Requests
Once you’ve set up your environment, you can start making requests to ChatGPT. Here’s how to make a basic request in both Python and JavaScript:
Python Example
Use the ChatCompletion.create
method to send a prompt to ChatGPT:
response = openai.ChatCompletion.create( model="gpt-3.5-turbo", messages=[{"role": "user", "content": "Hello, ChatGPT! Can you explain machine learning?"}] ) print(response.choices[0].message['content'])
JavaScript Example
Using the fetch
API, make a POST request to the OpenAI API endpoint:
fetch('https://api.openai.com/v1/chat/completions', { method: 'POST', headers: { 'Content-Type': 'application/json', 'Authorization': `Bearer ${apiKey}` }, body: JSON.stringify({ model: "gpt-3.5-turbo", messages: [{role: "user", content: "Hello, ChatGPT! Can you explain machine learning?"}] }) }) .then(response => response.json()) .then(data => console.log(data.choices[0].message.content)) .catch(error => console.error('Error:', error));
Examples: Sending a Basic Prompt and Reading the Response
Here are some example prompts to experiment with using the OpenAI API. Each prompt has an expected type of response to help you better understand the model’s capabilities:
Example Prompts and Responses
Prompt: "Summarize the key benefits of cloud computing." Expected Response: "Cloud computing offers scalability, cost savings, flexibility, and access to advanced technologies." Prompt: "Explain the difference between AI and machine learning in simple terms." Expected Response: "AI is the broader concept of machines being able to carry out tasks in a smart way, while machine learning is a subset of AI that allows systems to learn from data." Prompt: "Provide a Python function to calculate the factorial of a number." Expected Response: "Here’s a Python function for factorial: def factorial(n): return 1 if n == 0 else n * factorial(n-1)" Prompt: "List 5 tips for effective remote work." Expected Response: "1. Set up a dedicated workspace, 2. Keep a consistent schedule, 3. Minimize distractions, 4. Take regular breaks, 5. Communicate effectively." Prompt: "What are some applications of machine learning in healthcare?" Expected Response: "Applications include diagnostics, personalized treatment plans, drug discovery, patient monitoring, and predictive analytics." Prompt: "Translate 'Hello, how are you?' to Spanish." Expected Response: "Hola, ¿cómo estás?" Prompt: "Suggest a project idea for a beginner Python programmer." Expected Response: "A great project is creating a simple calculator, to practice functions, user input, and basic error handling." Prompt: "What’s the best way to learn programming for beginners?" Expected Response: "Start with a language like Python, work on small projects, practice regularly, and gradually move to more complex topics." Prompt: "Write a short story about a robot discovering emotions." Expected Response: "Once there was a robot named Byte who discovered emotions. Every time it helped someone, it felt a new warmth inside, sparking a journey into understanding kindness, joy, and sorrow." Prompt: "Explain recursion in programming with a simple example." Expected Response: "Recursion is when a function calls itself. For example, a function calculating factorial: def factorial(n): return 1 if n == 0 else n * factorial(n-1)"