您的浏览器需要启用 JavaScript 才能正常访问此网站。
Hotline:15911225507
Long Xiao
Login
Home-All Posts-Nuxt.js英文-Main Content

Integrating AI APIs in Nuxt 3 for Smart Content Generation and Multilingual Translation

LXLXNuxt.js英文1 months ago0072

With the rapid advancement of large language model (LLM) technology, more and more web applications are integrating AI capabilities—from intelligent customer support and content summarization to automatic translation. AI is reshaping how frontend development works. For developers building full-stack applications with Nuxt 3, knowing how to safely and efficiently call AI APIs within a project is a topic worth exploring in depth. This article will guide you step by step through integrating OpenAI-compatible APIs in a Nuxt 3 project to implement smart content generation and multilingual translation.

1. Why Server-Side Calls

When calling AI APIs in a Nuxt 3 project, the primary consideration is security. All major AI services (OpenAI, Claude, DeepSeek, etc.) require API Key authentication. If you hardcode the API Key in frontend code, anyone can obtain your key through browser developer tools, causing serious security risks and cost leakage.

Nuxt 3's server/api directory provides the perfect solution: API routes run on the server side (Nitro engine), the API Key is stored in .env environment variables, and the frontend calls its own endpoints via $fetch. The server then forwards requests to the AI service. This way, the API Key is never exposed to the client.

2. Environment Setup

First, create a .env file in your Nuxt 3 project root:

NUXT_OPENAI_API_KEY=sk-your-api-key-here
NUXT_OPENAI_BASE_URL=https://api.openai.com/v1
NUXT_AI_MODEL=gpt-4o-mini

No additional configuration is needed in nuxt.config.ts—Nitro automatically reads environment variables prefixed with NUXT_ and exposes them via useRuntimeConfig() on the server side.

3. Creating the AI Service Layer

For code reusability and maintainability, we first create a generic AI service wrapper. In server/utils/ai.ts:

interface ChatMessage {
  role: 'system' | 'user' | 'assistant'
  content: string
}

interface ChatOptions {
  messages: ChatMessage[]
  temperature?: number
  maxTokens?: number
  stream?: boolean
}

export async function chatCompletion(options: ChatOptions) {
  const config = useRuntimeConfig()
  
  const response = await $fetch(`${config.openaiBaseUrl}/chat/completions`, {
    method: 'POST',
    headers: {
      'Authorization': `Bearer ${config.openaiApiKey}`,
      'Content-Type': 'application/json',
    },
    body: {
      model: config.aiModel,
      messages: options.messages,
      temperature: options.temperature ?? 0.7,
      max_tokens: options.maxTokens ?? 2048,
      stream: options.stream ?? false,
    },
  })
  
  return response
}

4. Implementing the Content Generation API Route

Create server/api/ai/generate.post.ts:

export default defineEventHandler(async (event) => {
  const body = await readBody(event)
  const { prompt, systemPrompt } = body

  if (!prompt) {
    throw createError({
      statusCode: 400,
      message: 'The prompt parameter is required',
    })
  }

  try {
    const result = await chatCompletion({
      messages: [
        { role: 'system', content: systemPrompt || 'You are a professional technical content creator.' },
        { role: 'user', content: prompt },
      ],
      temperature: 0.8,
    })

    return {
      success: true,
      content: result.choices[0].message.content,
      usage: result.usage,
    }
  } catch (error: any) {
    throw createError({
      statusCode: 500,
      message: error.message || 'AI service call failed',
    })
  }
})

5. Implementing Streaming Responses (SSE)

For content generation scenarios, streaming responses significantly improve user experience—users can see text being generated word by word rather than waiting several seconds for a one-shot display. Create server/api/ai/stream.post.ts:

export default defineEventHandler(async (event) => {
  const body = await readBody(event)
  const { prompt, systemPrompt } = body
  const config = useRuntimeConfig()

  setHeader(event, 'Content-Type', 'text/event-stream')
  setHeader(event, 'Cache-Control', 'no-cache')
  setHeader(event, 'Connection', 'keep-alive')

  const response = await fetch(
    `${config.openaiBaseUrl}/chat/completions`,
    {
      method: 'POST',
      headers: {
        'Authorization': `Bearer ${config.openaiApiKey}`,
        'Content-Type': 'application/json',
      },
      body: JSON.stringify({
        model: config.aiModel,
        messages: [
          { role: 'system', content: systemPrompt || 'You are a professional assistant.' },
          { role: 'user', content: prompt },
        ],
        stream: true,
      }),
    }
  )

  const reader = response.body?.getReader()
  if (!reader) throw createError({ statusCode: 500 })

  const decoder = new TextDecoder()
  let buffer = ''

  while (true) {
    const { done, value } = await reader.read()
    if (done) {
      sendEventStream(event, { data: '[DONE]' })
      break
    }

    buffer += decoder.decode(value, { stream: true })
    const lines = buffer.split('n')
    buffer = lines.pop() || ''

    for (const line of lines) {
      if (line.startsWith('data: ') && line !== 'data: [DONE]') {
        try {
          const parsed = JSON.parse(line.slice(6))
          const content = parsed.choices[0]?.delta?.content
          if (content) {
            sendEventStream(event, { data: content })
          }
        } catch {}
      }
    }
  }
})

6. Frontend Vue Component Integration

Create a reusable AI content generation component:

<script setup lang="ts">
const prompt = ref('')
const generatedContent = ref('')
const isLoading = ref(false)
const isStreaming = ref(false)

async function generateContent() {
  if (!prompt.value.trim()) return
  
  isLoading.value = true
  generatedContent.value = ''
  
  try {
    const data = await $fetch('/api/ai/generate', {
      method: 'POST',
      body: { prompt: prompt.value },
    })
    generatedContent.value = data.content
  } catch (error) {
    console.error('Generation failed:', error)
  } finally {
    isLoading.value = false
  }
}

async function generateStream() {
  if (!prompt.value.trim()) return
  
  isStreaming.value = true
  generatedContent.value = ''
  
  const eventSource = new EventSource(
    `/api/ai/stream?${new URLSearchParams({ prompt: prompt.value })}`
  )
  
  eventSource.onmessage = (event) => {
    if (event.data === '[DONE]') {
      eventSource.close()
      isStreaming.value = false
      return
    }
    generatedContent.value += event.data
  }
  
  eventSource.onerror = () => {
    eventSource.close()
    isStreaming.value = false
  }
}
</script>

7. Implementing Multilingual Translation

Based on the AI service layer above, implementing multilingual translation is straightforward. Create server/api/ai/translate.post.ts:

export default defineEventHandler(async (event) => {
  const { text, targetLang, sourceLang } = await readBody(event)

  const langMap: Record<string, string> = {
    'zh-cn': 'Simplified Chinese',
    'zh-tw': 'Traditional Chinese',
    'en': 'English',
    'ja': 'Japanese',
  }

  const result = await chatCompletion({
    messages: [
      {
        role: 'system',
        content: `You are a professional translator. Translate the following${sourceLang ? ' ' + (langMap[sourceLang] || sourceLang) : ''} text into ${langMap[targetLang] || targetLang}. Return only the translation, without any explanations.`,
      },
      { role: 'user', content: text },
    ],
    temperature: 0.3,
  })

  return {
    success: true,
    translation: result.choices[0].message.content,
    sourceLang,
    targetLang,
  }
})

8. Error Handling and Rate Limiting

In production environments, AI API calls can fail for various reasons—network timeouts, rate limits, insufficient balance, etc. We need robust error handling mechanisms.

Add retry logic in server/utils/ai.ts:

export async function chatCompletionWithRetry(
  options: ChatOptions,
  maxRetries = 3
) {
  for (let i = 0; i < maxRetries; i++) {
    try {
      return await chatCompletion(options)
    } catch (error: any) {
      if (error.statusCode === 429) {
        // Rate limited — wait and retry
        const retryAfter = error.headers?.get('retry-after') || 5
        await new Promise(r => setTimeout(r, retryAfter * 1000))
        continue
      }
      if (i === maxRetries - 1) throw error
      await new Promise(r => setTimeout(r, 1000 * Math.pow(2, i)))
    }
  }
}

It's also recommended to set request body size limits in the Nitro configuration:

// nuxt.config.ts
export default defineNuxtConfig({
  nitro: {
    routeRules: {
      '/api/ai/**': {
        maxBodySize: '1mb',
      },
    },
  },
})

9. Summary

Through Nuxt 3's Server API routes, we've integrated AI capabilities in a secure and efficient manner. Key takeaways:

  • Security: API Keys are stored in server-side environment variables, never exposed to the client
  • Streaming Responses: SSE enables real-time content generation, enhancing user experience
  • Reusable Architecture: Through a service layer abstraction, content generation and translation share the same AI calling logic
  • Robustness: Exponential backoff retry strategy handles rate limiting and network anomalies

This architecture has been running reliably across multiple projects at Salong Network—whether automatically generating technical articles and product descriptions, or handling multilingual site content translation, it performs efficiently. I hope this article helps you successfully integrate AI capabilities into your Nuxt 3 projects.

Tags:
本文来源萨龙网络,经授权后由LX发布,观点不代表龙霄的立场,转载请联系原作者。
LX

LX

Lv1Rec2
Revitalize the WordPress experience with the power of Nuxt.js
229.39W1119
Loading...
Share:
1
Hardening WordPress Custom REST API Security and Automating WeChat Article Formatting
Hardening WordPress Custom REST API Security and Automating WeChat Article FormattingPrevious
Data Caching Optimization Strategies for Nuxt.js Headless WordPress ProjectsNext
Data Caching Optimization Strategies for Nuxt.js Headless WordPress Projects
相关文章
Total: 17
Event Plugin &#8211; Event Management Plugin: An All-in-One Event Operations Solution from Planning to Execution

Event Plugin – Event Management Plugin: An All-in-One Event Operations Solution from Planning to Execution

Behind every successful event lies complex coordination — venue management, guest invitations, registration, check-in, and ticketing. The Event …
LXLXNuxt.js英文, WordPress英文3 months ago002.89K0
Nuxt.js + WordPress Architecture: A Comprehensive Guide to Performance, Speed, Security, and Caching

Nuxt.js + WordPress Architecture: A Comprehensive Guide to Performance, Speed, Security, and Caching

When Nuxt.js's modern frontend engineering capabilities meet WordPress's powerful content management ecosystem, combined through a Headless arch…
LXLXNuxt.js英文, WordPress英文3 months ago004.26K0
LongXiao Theme Four Little Monsters Guarding the Login: A Deep Dive into Playful Interaction Design

LongXiao Theme Four Little Monsters Guarding the Login: A Deep Dive into Playful Interaction Design

They peek when you type your password. They tilt their heads to follow your mouse. This isn't a game — it's the login page of a Nuxt 4 project. …
LXLXNuxt.js英文, Vue.js英文3 months ago004.54K0
Nuxt 4 i18n Architecture &amp; Multi-Language Routing Strategy

Nuxt 4 i18n Architecture & Multi-Language Routing Strategy

A complete guide to a three-language (zh-CN/zh-TW/en) i18n setup with @nuxtjs/i18n v10, covering the prefix_except_default routing strategy, bro…
LXLXNuxt.js英文, Vue.js英文3 months ago002.69K0
Pinia State Persistence &amp; Memory Governance in Nuxt 4

Pinia State Persistence & Memory Governance in Nuxt 4

A systematic walkthrough of state management across 25 Pinia Stores in a large Nuxt 4 project, covering shallowRef memory optimization, localSto…
LXLXNuxt.js英文, Vue.js英文3 months ago004.84K0
Longxiao Theme &#8211; E-Commerce Platform: A Unified Transaction Engine for Course, Physical Product, and Event Marketing Plugins

Longxiao Theme – E-Commerce Platform: A Unified Transaction Engine for Course, Physical Product, and Event Marketing Plugins

One underlying transaction pipeline, three product types, unified shopping cart, combined checkout, centralized order management — the Commercia…
LXLXNuxt.js英文3 months ago002.65K0
One-Click Intelligence, Trilingual Mastery: How LongXiao AI Translation Doubles Your Multilingual Site Management Efficiency

One-Click Intelligence, Trilingual Mastery: How LongXiao AI Translation Doubles Your Multilingual Site Management Efficiency

I. The Pain Points: Three Mountains of Multilingual Website ManagementRunning a website that supports Simplified Chinese, Traditional Chines…
LXLXNuxt.js英文, Vue.js英文, WordPress英文2 months ago00990
Longxiao Theme-Visual Page Builder: Build Professional-Grade Websites in One Afternoon

Longxiao Theme-Visual Page Builder: Build Professional-Grade Websites in One Afternoon

Say goodbye to the traditional website building workflow of writing code, tweaking styles, and wiring APIs. Drag modules, configure parameters, …
LXLXNuxt.js英文, WordPress英文3 months ago002.59K0
Nitro Server Architecture: Security Proxy Layer &amp; Performance Engine

Nitro Server Architecture: Security Proxy Layer & Performance Engine

An invisible shield that completely isolates the WordPress backend from the public internet, while delivering stable, efficient, and secure data…
LXLXNuxt.js英文3 months ago002.65K0
Nuxt 4 + WordPress GraphQL: Data Management Strategy &amp; Performance Optimization

Nuxt 4 + WordPress GraphQL: Data Management Strategy & Performance Optimization

A deep dive into the production-grade data layer of a Nuxt 4 + WordPress GraphQL project, covering server-side SHA-256 caching, in-flight reques…
LXLXNuxt.js英文, Vue.js英文, WordPress英文3 months ago106.92K0
Embracing Modern Web Development: The Nuxt.js + WordPress Architectural Revolution

Embracing Modern Web Development: The Nuxt.js + WordPress Architectural Revolution

一、Performance Optimization: The Perfect Balance of Static Generation and Dynamic RenderingIn today's fast-paced digital era, website perform…
LXLXNuxt.js英文, WordPress英文3 months ago002.96K0
LongXiao Theme Affiliate System: Frontend Tracking, Multi-Language Support, and the Full Pipeline from Traffic to Commission

LongXiao Theme Affiliate System: Frontend Tracking, Multi-Language Support, and the Full Pipeline from Traffic to Commission

IntroductionIn the digital business ecosystem, affiliate marketing has become a cornerstone strategy for brands to expand sales channels and…
LXLXNuxt.js英文, Vue.js英文1 months ago00810
评论表单游客 您好,欢迎参与讨论。
Loading...
评论列表
Total: 0
Long Xiao
No relevant content