使用DeepL + GPT-4构建AI翻译系统:2026年逐步教程
从零开始构建一个可用于生产的多语言内容系统
使用DeepL + GPT-4构建AI翻译系统:2026年逐步教程
从零开始构建一个可用于生产的多语言内容系统
使用DeepL + GPT-4构建AI翻译系统 项目概述 在本教程中,你将使用DeepL + GPT-4构建一个完整的**多语言内容系统**。最终,你将拥有一个可部署和定制的生产级应用程序。 **你将构建的内容:** 一个多语言内容系统 **技术栈:** DeepL + GPT-4 **难度:** 中级 **时间:** 约30分钟
使用DeepL + GPT-4构建AI翻译系统
项目概述
在本教程中,你将使用DeepL + GPT-4构建一个完整的多语言内容系统。最终,你将拥有一个可部署和定制的生产级应用程序。
你将构建的内容: 一个多语言内容系统 技术栈: DeepL + GPT-4 难度: 中级 时间: 约30分钟
前置条件
架构
用户输入 → API层 → AI处理 → 响应
↓ ↓
验证 上下文/记忆
↓
向量存储(可选)
步骤1:项目设置
bash
创建项目
mkdir ai-translation-app && cd ai-translation-app安装依赖
npm init -y
npm install openai @anthropic-ai/sdk langchain dotenv创建.env文件
cat > .env << 'EOF'
OPENAI_API_KEY=your_key_here
ANTHROPIC_API_KEY=your_key_here
EOF
步骤2:核心AI逻辑
typescript
// src/ai-core.ts
import OpenAI from 'openai';
import Anthropic from '@anthropic-ai/sdk';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模型
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 : '';
}
// 流式版本
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;
}
}
步骤3:API端点
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: `你是一位专家级AI翻译系统。
你的目标:帮助用户处理多语言内容系统。
请准确、有帮助且简洁。`
};
// 常规端点
app.post('/api/ai-translation', async (req, res) => {
const { input } = req.body;
if (!input) {
return res.status(400).json({ error: '需要输入内容' });
}
try {
const result = await processAITranslation(input, config);
res.json({ result, model: config.model });
} catch (error) {
console.error('AI处理错误:', error);
res.status(500).json({ error: '处理失败' });
}
});
// 流式端点
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翻译API运行在端口3000'));
步骤4:前端(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 {
// 使用流式传输以获得更好的用户体验
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翻译
{output && (
结果:
{output}
)}
);
}
步骤5:部署到Vercel
bash
安装Vercel CLI
npm install -g vercel部署
vercel deploy --prod设置环境变量
vercel env add OPENAI_API_KEY production
vercel env add ANTHROPIC_API_KEY production
测试
bash
测试API
curl -X POST http://localhost:3000/api/ai-translation \
-H "Content-Type: application/json" \
-d '{"input": "AI翻译的测试输入"}'预期响应:
{"result": "AI生成的响应...", "model": "gpt-4o-mini"}
扩展考虑
随着你的多语言内容系统增长:
结论
你已经使用DeepL + GPT-4构建了一个可用于生产的多语言内容系统!关键组件包括:
后续步骤:添加身份验证、持久化对话历史和使用分析。
*AI翻译教程 | DeepL + GPT-4 | 2026年5月*
相关工具