Hey there, fellow code wranglers! Ready to dive into the world of AI-powered conversations? You're in the right place. We're about to embark on a journey to integrate the ChatGPT API into your JavaScript projects using the nifty chatgpt
package. Buckle up!
Before we hit the ground running, make sure you've got:
Let's get this show on the road:
mkdir chatgpt-integration cd chatgpt-integration npm init -y npm install chatgpt
Boom! You're all set.
Time to bring in the big guns:
import { ChatGPTAPI } from 'chatgpt' const api = new ChatGPTAPI({ apiKey: process.env.OPENAI_API_KEY })
Pro tip: Keep that API key safe in an environment variable. No one likes a leaked key!
Let's chat it up:
async function chatWithGPT(message) { const response = await api.sendMessage(message) console.log(response.text) } chatWithGPT("What's the meaning of life?")
Easy peasy, right? ChatGPT might not have all the answers, but it'll sure try!
Want to keep the conversation flowing? Here's how:
const conversation = api.getConversation() await conversation.sendMessage("Hi there!") await conversation.sendMessage("What was my first message?")
For that real-time feel:
const response = await api.sendMessage('Tell me a long story', { onProgress: (partialResponse) => console.log(partialResponse.text) })
Always be prepared:
try { const response = await api.sendMessage('Hello, ChatGPT!') } catch (error) { console.error('Oops! Something went wrong:', error) }
Let's put it all together with a simple chatbot:
import readline from 'readline' import { ChatGPTAPI } from 'chatgpt' const api = new ChatGPTAPI({ apiKey: process.env.OPENAI_API_KEY }) const rl = readline.createInterface({ input: process.stdin, output: process.stdout }) async function chat() { const conversation = api.getConversation() console.log("Chat with GPT! (Type 'exit' to quit)") const askQuestion = () => { rl.question('You: ', async (input) => { if (input.toLowerCase() === 'exit') { rl.close() return } try { const response = await conversation.sendMessage(input) console.log('ChatGPT:', response.text) } catch (error) { console.error('Error:', error) } askQuestion() }) } askQuestion() } chat()
And there you have it! You're now armed and dangerous with ChatGPT integration skills. Remember, with great power comes great responsibility (and possibly some hilarious AI conversations).
Hit a snag? Here are some common hiccups:
Now go forth and create some AI magic! Happy coding!