Build an AI Translation with DeepL + GPT-4: Step-by-Step Tutorial 2026

Create a production-ready multilingual content system from scratch

返回教程列表
进阶30 分钟

Build an AI Translation with DeepL + GPT-4: Step-by-Step Tutorial 2026

Create a production-ready multilingual content system from scratch

Build an AI Translation with DeepL + GPT-4 Project Overview In this tutorial, you'll build a complete **multilingual content system** using DeepL + GPT-4. By the end, you'll have a production-ready application you can deploy and customize. **What

ai-translationproject-tutorialbuild-with-aideepl

Build an AI Translation with DeepL + GPT-4

Project Overview

In this tutorial, you'll build a complete multilingual content system using DeepL + GPT-4. By the end, you'll have a production-ready application you can deploy and customize.

What you'll build: A multilingual content system Tech stack: DeepL + GPT-4 Difficulty: Intermediate Time: ~30 minutes

Prerequisites

  • Basic Python or JavaScript knowledge
  • Node.js 18+ or Python 3.10+
  • API keys for relevant services
  • Architecture

    
    User Input → API Layer → AI Processing → Response
                    ↓              ↓
               Validation    Context/Memory
                                  ↓
                             Vector Store (optional)
    

    Step 1: Project Setup

    bash
    

    Create project

    mkdir ai-translation-app && cd ai-translation-app

    Install dependencies

    npm init -y npm install openai @anthropic-ai/sdk langchain dotenv

    Create .env file

    cat > .env << 'EOF' OPENAI_API_KEY=your_key_here ANTHROPIC_API_KEY=your_key_here EOF

    Step 2: Core AI Logic

    typescript
    // src/ai-core.ts
    import OpenAI from 'openai';
    import Anthropic from '@anthropic-ai/sdk';

    const openai = new OpenAI({ apiKey: process.env.OPENAI_API_KEY }); const anthropic = new Anthropic({ apiKey: process.env.ANTHROPIC_API_KEY });

    interface AITranslationConfig { model: 'gpt-4o' | 'gpt-4o-mini' | 'claude-3-5-sonnet-20241022'; maxTokens: number; temperature: number; systemPrompt: string; }

    export async function processAITranslation( input: string, config: AITranslationConfig ): Promise { if (config.model.startsWith('gpt')) { const response = await openai.chat.completions.create({ model: config.model, messages: [ { role: 'system', content: config.systemPrompt }, { role: 'user', content: input } ], max_tokens: config.maxTokens, temperature: config.temperature }); return response.choices[0].message.content || ''; } // Anthropic models const response = await anthropic.messages.create({ model: config.model, max_tokens: config.maxTokens, system: config.systemPrompt, messages: [{ role: 'user', content: input }] }); return response.content[0].type === 'text' ? response.content[0].text : ''; }

    // Streaming version export async function* streamAITranslation( input: string, config: AITranslationConfig ): AsyncGenerator { const stream = await openai.chat.completions.create({ model: config.model.startsWith('gpt') ? config.model : 'gpt-4o-mini', messages: [ { role: 'system', content: config.systemPrompt }, { role: 'user', content: input } ], stream: true }); for await (const chunk of stream) { const content = chunk.choices[0]?.delta?.content; if (content) yield content; } }

    Step 3: API Endpoint

    typescript
    // src/api.ts
    import express from 'express';
    import { processAITranslation, streamAITranslation } from './ai-core';

    const app = express(); app.use(express.json());

    const config = { model: 'gpt-4o-mini' as const, maxTokens: 2048, temperature: 0.7, systemPrompt: `You are an expert AI Translation system. Your goal: Help users with multilingual content system. Be accurate, helpful, and concise.` };

    // Regular endpoint app.post('/api/ai-translation', async (req, res) => { const { input } = req.body; if (!input) { return res.status(400).json({ error: 'Input is required' }); } try { const result = await processAITranslation(input, config); res.json({ result, model: config.model }); } catch (error) { console.error('AI processing error:', error); res.status(500).json({ error: 'Processing failed' }); } });

    // Streaming endpoint app.post('/api/ai-translation/stream', async (req, res) => { const { input } = req.body; res.setHeader('Content-Type', 'text/event-stream'); res.setHeader('Cache-Control', 'no-cache'); try { for await (const chunk of streamAITranslation(input, config)) { res.write(data: ${JSON.stringify({ chunk })}\n\n); } res.write('data: [DONE]\n\n'); res.end(); } catch (error) { res.write(data: ${JSON.stringify({ error: String(error) })}\n\n); res.end(); } });

    app.listen(3000, () => console.log('AI Translation API running on port 3000'));

    Step 4: Frontend (Next.js)

    tsx
    // app/page.tsx
    'use client';

    import { useState } from 'react';

    export default function AITranslationApp() { const [input, setInput] = useState(''); const [output, setOutput] = useState(''); const [loading, setLoading] = useState(false);

    const handleSubmit = async (e: React.FormEvent) => { e.preventDefault(); setLoading(true); setOutput(''); try { // Use streaming for better UX const response = await fetch('/api/ai-translation/stream', { method: 'POST', headers: { 'Content-Type': 'application/json' }, body: JSON.stringify({ input }) }); const reader = response.body?.getReader(); const decoder = new TextDecoder(); if (!reader) return; while (true) { const { done, value } = await reader.read(); if (done) break; const chunk = decoder.decode(value); const lines = chunk.split('\n').filter(l => l.startsWith('data: ')); for (const line of lines) { const data = line.replace('data: ', ''); if (data === '[DONE]') break; try { const { chunk: text } = JSON.parse(data); setOutput(prev => prev + text); } catch {} } } } finally { setLoading(false); } };

    return (

    AI Translation