Categories
Artificial Intelligence

Building an AI Translation App With Next.js by Extracting JSON From OpenAI’s API

In this tutorial, we will embark on a journey to create a translation app using Next.js and OpenAI’s API. This project is designed not only to teach you the technicalities of working with AI and APIs but also to give you a real-world application of these technologies.

Building this app provides a hands-on learning experience, allowing you to understand how artificial intelligence can be integrated into modern web development. By translating text into multiple languages, the app demonstrates how AI can break language barriers, making communication seamless and accessible.

We’ll leverage OpenAI’s GPT models to perform translations and format the results as JSON, ensuring clarity and usability. This tool is highly versatile and can be applied in various real-world scenarios. Imagine businesses using it to craft multilingual content, students learning new languages through instant feedback, or customer support systems delivering real-time translations to bridge communication gaps.

Through this tutorial, you’ll not only learn the fundamentals but also discover how AI solutions can address practical challenges effectively. Let’s get started!

Prerequisites

Before we begin, ensure you have the following:

  • Basic knowledge of Next.js and React.
  • Node.js installed on your machine.
  • An API key for OpenAI’s GPT.

Step 1: Setting Up the Next.js Project

Create a new Next.js app:

npx create-next-app@latest ai-translation-app
cd ai-translation-app

Install required dependencies:

npm install axios

Create a .env.local file in the root of your project to store the OpenAI API key:

OPENAI_API_KEY=your_openai_api_key_here

Step 2: Setting Up the OpenAI API Integration

Inside the pages/api folder, create a new file translate.js:

import axios from 'axios';

export default async function handler(req, res) {
  if (req.method !== 'POST') {
    return res.status(405).json({ error: 'Method not allowed' });
  }

  const { text, targetLanguages } = req.body;

  if (!text || !targetLanguages || !Array.isArray(targetLanguages)) {
    return res.status(400).json({ error: 'Invalid input' });
  }

  try {
    const response = await axios.post(
      'https://api.openai.com/v1/completions',
      {
        model: 'text-davinci-003',
        prompt: `Translate the following text into the specified languages and return the translations as a JSON object:
        
        Text: "${text}"
        Languages: ${targetLanguages.join(', ')}
        
        Output format: { "language": "translation" }`,
        max_tokens: 1000,
        temperature: 0.7,
      },
      {
        headers: {
          'Authorization': `Bearer ${process.env.OPENAI_API_KEY}`,
          'Content-Type': 'application/json',
        },
      }
    );

    const translations = JSON.parse(response.data.choices[0].text.trim());
    res.status(200).json(translations);
  } catch (error) {
    console.error(error);
    res.status(500).json({ error: 'Failed to fetch translations' });
  }
}

Restart your Next.js server to apply the changes.

Step 3: Creating the Translation UI

Open pages/index.js and replace its content with the following

import { useState } from 'react';

export default function Home() {
  const [text, setText] = useState('');
  const [languages, setLanguages] = useState('');
  const [translations, setTranslations] = useState(null);
  const [error, setError] = useState(null);
  const [loading, setLoading] = useState(false);

  const handleTranslate = async () => {
    setLoading(true);
    setError(null);
    setTranslations(null);

    try {
      const response = await fetch('/api/translate', {
        method: 'POST',
        headers: {
          'Content-Type': 'application/json',
        },
        body: JSON.stringify({
          text,
          targetLanguages: languages.split(',').map(lang => lang.trim()),
        }),
      });

      if (!response.ok) {
        throw new Error('Translation failed');
      }

      const data = await response.json();
      setTranslations(data);
    } catch (err) {
      setError(err.message);
    } finally {
      setLoading(false);
    }
  };

  return (
    <div style={{ padding: '2rem', maxWidth: '600px', margin: '0 auto' }}>
      <h1>AI Translation App</h1>
      <textarea
        placeholder="Enter text to translate"
        value={text}
        onChange={(e) => setText(e.target.value)}
        style={{ width: '100%', height: '100px', marginBottom: '1rem' }}
      />
      <input
        type="text"
        placeholder="Enter target languages (e.g., French, Spanish)"
        value={languages}
        onChange={(e) => setLanguages(e.target.value)}
        style={{ width: '100%', marginBottom: '1rem' }}
      />
      <button onClick={handleTranslate} disabled={loading}>
        {loading ? 'Translating...' : 'Translate'}
      </button>

      {error && <p style={{ color: 'red' }}>{error}</p>}
      {translations && (
        <div>
          <h2>Translations</h2>
          <pre>{JSON.stringify(translations, null, 2)}</pre>
        </div>
      )}
    </div>
  );
}

Step 4: Running the App

Start your development server:

npm run dev

Open http://localhost:3000 in your browser.

Enter some text and specify the target languages (comma-separated), then click “Translate.”

Conclusion

You’ve successfully built an AI-powered translation app using Next.js and OpenAI’s API. This app demonstrates how to fetch translations and handle JSON outputs effectively. You can further enhance it by adding more features like saving translations or supporting additional APIs.