Table of Contents
Setting up a Nuxt.js project for seamless AI integration can significantly enhance your web application's capabilities. This guide walks you through the essential steps to get started quickly and efficiently.
Prerequisites
- Node.js installed on your machine (version 14 or higher)
- npm or yarn package manager
- Basic knowledge of JavaScript and Vue.js
- Access to an AI API service (e.g., OpenAI)
Creating a New Nuxt.js Project
Begin by creating a new Nuxt.js project using the create-nuxt-app CLI tool. Open your terminal and run:
npx create-nuxt-app ai-integration
Follow the prompts to select your preferred package manager, UI framework, and other options. Once completed, navigate into your project directory:
cd ai-integration
Installing Necessary Packages
Install axios for making HTTP requests and dotenv for managing environment variables:
npm install axios dotenv
Configuring Environment Variables
Create a .env file in the root of your project and add your AI API key:
AI_API_KEY=your_api_key_here
Setting Up API Communication
Create a new file services/aiService.js to handle API requests:
import axios from 'axios';
const apiKey = process.env.AI_API_KEY;
const apiUrl = 'https://api.openai.com/v1/engines/davinci/completions';
export async function getAIResponse(prompt) {
const response = await axios.post(apiUrl, {
prompt: prompt,
max_tokens: 150,
}, {
headers: {
'Content-Type': 'application/json',
'Authorization': `Bearer ${apiKey}`,
},
});
return response.data.choices[0].text;
}
Creating a User Interface
Modify the pages/index.vue to include a form for user input and display the AI response:
<template>
<div class="container">
<h1>AI Chat</h1>
<textarea v-model="userPrompt" placeholder="Enter your prompt..."></textarea>
<button @click="fetchAIResponse">Send</button>
<div v-if="aiResponse">
<h2>Response:</h2>
<p>{{ aiResponse }}</p>
</div>
</div>
</template>
<script>
import { getAIResponse } from '../services/aiService';
export default {
data() {
return {
userPrompt: '',
aiResponse: '',
};
},
methods: {
async fetchAIResponse() {
this.aiResponse = 'Loading...';
try {
this.aiResponse = await getAIResponse(this.userPrompt);
} catch (error) {
this.aiResponse = 'Error fetching response.';
}
},
},
};
</script>
<style scoped>
.container {
max-width: 600px;
margin: 0 auto;
padding: 20px;
}
textarea {
width: 100%;
height: 100px;
margin-bottom: 10px;
}
button {
padding: 10px 20px;
}
</style>
Running Your Nuxt.js AI Application
Start the development server with:
npm run dev
Open your browser and navigate to http://localhost:3000. You can now input prompts and receive AI-generated responses seamlessly.
Conclusion
Integrating AI into your Nuxt.js project involves setting up environment variables, creating API service functions, and building a simple user interface. With these steps, you can enhance your web applications with powerful AI capabilities and provide dynamic, interactive experiences for your users.