AI / LLM Integrations

Build intelligent apps with AI in Next.js

🤖 What are AI / LLM Integrations?

AI and Large Language Model integrations bring intelligent features to Next.js apps. Use OpenAI, Anthropic, or other AI services to add chatbots, content generation, image creation, and smart automation to your applications effortlessly.


// Simple AI chat with Vercel AI SDK
import { generateText } from 'ai'

const { text } = await generateText({
  model: 'gpt-4',
  prompt: 'Explain Next.js in simple terms'
})

console.log(text)
// Output: "Next.js is a React framework that makes building 
// web applications easier..."
                                    

Key AI Integration Features

💬

Chat Interfaces

Build conversational AI

const { messages } = useChat({
  api: '/api/chat'
})
✍️

Text Generation

Generate content with AI

generateText({
  model: 'gpt-4',
  prompt: 'Write...'
})
🎨

Image Generation

Create images from text

generateImage({
  model: 'dall-e-3',
  prompt: 'A sunset'
})
🔄

Streaming

Stream AI responses

streamText({
  model: 'gpt-4',
  prompt: 'Explain...'
})

🔹 Setup Vercel AI SDK

The Vercel AI SDK simplifies AI integration in Next.js with built-in support for streaming, chat interfaces, and multiple AI providers like OpenAI, Anthropic, and Google.

# Install Vercel AI SDK
npm install ai @ai-sdk/openai
// .env.local
OPENAI_API_KEY=your_api_key_here

// app/api/chat/route.js
import { openai } from '@ai-sdk/openai'
import { streamText } from 'ai'

export async function POST(req) {
  const { messages } = await req.json()

  const result = await streamText({
    model: openai('gpt-4'),
    messages
  })

  return result.toDataStreamResponse()
}

🔹 Build a Chat Interface

Create an interactive chat interface using the useChat hook. It handles message state, streaming responses, and user input automatically for seamless AI conversations.

// components/ChatBot.jsx
'use client'
import { useChat } from 'ai/react'

export default function ChatBot() {
  const { messages, input, handleInputChange, handleSubmit } = useChat()

  return (
    <div className="flex flex-col h-screen max-w-2xl mx-auto p-4">
      <div className="flex-1 overflow-y-auto space-y-4">
        {messages.map(message => (
          <div 
            key={message.id}
            className={`p-4 rounded-lg ${
              message.role === 'user' 
                ? 'bg-blue-100 ml-auto' 
                : 'bg-gray-100'
            }`}
          >
            <p className="font-semibold">
              {message.role === 'user' ? 'You' : 'AI'}
            </p>
            <p>{message.content}</p>
          </div>
        ))}
      </div>

      <form onSubmit={handleSubmit} className="mt-4">
        <input
          value={input}
          onChange={handleInputChange}
          placeholder="Ask me anything..."
          className="w-full p-3 border rounded-lg"
        />
      </form>
    </div>
  )
}

Output:

You

What is Next.js?

AI

Next.js is a React framework for building web applications...

🔹 Text Generation

Generate text content on-demand using AI models. Perfect for content creation, summaries, translations, or any text-based automation in your Next.js application.

// app/api/generate/route.js
import { openai } from '@ai-sdk/openai'
import { generateText } from 'ai'

export async function POST(req) {
  const { prompt } = await req.json()

  const { text } = await generateText({
    model: openai('gpt-4'),
    prompt: prompt
  })

  return Response.json({ text })
}

// components/TextGenerator.jsx
'use client'
import { useState } from 'react'

export default function TextGenerator() {
  const [prompt, setPrompt] = useState('')
  const [result, setResult] = useState('')
  const [loading, setLoading] = useState(false)

  const generate = async () => {
    setLoading(true)
    const response = await fetch('/api/generate', {
      method: 'POST',
      body: JSON.stringify({ prompt })
    })
    const data = await response.json()
    setResult(data.text)
    setLoading(false)
  }

  return (
    <div>
      <textarea
        value={prompt}
        onChange={(e) => setPrompt(e.target.value)}
        placeholder="Enter your prompt..."
        className="w-full p-3 border rounded"
      />
      <button onClick={generate} disabled={loading}>
        {loading ? 'Generating...' : 'Generate'}
      </button>
      {result && <div className="mt-4 p-4 bg-gray-100 rounded">{result}</div>}
    </div>
  )
}

🔹 Streaming Responses

Stream AI responses in real-time for better user experience. Users see content as it's generated rather than waiting for complete responses, making interactions feel faster.

// app/api/stream/route.js
import { openai } from '@ai-sdk/openai'
import { streamText } from 'ai'

export async function POST(req) {
  const { prompt } = await req.json()

  const result = await streamText({
    model: openai('gpt-4'),
    prompt: prompt
  })

  return result.toDataStreamResponse()
}

// components/StreamingText.jsx
'use client'
import { useCompletion } from 'ai/react'

export default function StreamingText() {
  const { completion, input, handleInputChange, handleSubmit } = useCompletion({
    api: '/api/stream'
  })

  return (
    <div>
      <form onSubmit={handleSubmit}>
        <input
          value={input}
          onChange={handleInputChange}
          placeholder="Ask something..."
        />
        <button type="submit">Generate</button>
      </form>
      
      {completion && (
        <div className="mt-4 p-4 bg-gray-100 rounded">
          {completion}
        </div>
      )}
    </div>
  )
}

🔹 AI with Server Actions

Combine AI with Next.js Server Actions for secure, server-side AI operations. Keep API keys safe and process AI requests without exposing credentials to the client.

// app/actions.js
'use server'
import { openai } from '@ai-sdk/openai'
import { generateText } from 'ai'

export async function generateSummary(text) {
  const { text: summary } = await generateText({
    model: openai('gpt-4'),
    prompt: `Summarize this text: ${text}`
  })
  
  return summary
}

// components/Summarizer.jsx
'use client'
import { useState } from 'react'
import { generateSummary } from '@/app/actions'

export default function Summarizer() {
  const [text, setText] = useState('')
  const [summary, setSummary] = useState('')

  const handleSummarize = async () => {
    const result = await generateSummary(text)
    setSummary(result)
  }

  return (
    <div>
      <textarea
        value={text}
        onChange={(e) => setText(e.target.value)}
        placeholder="Enter text to summarize..."
      />
      <button onClick={handleSummarize}>Summarize</button>
      {summary && <div>{summary}</div>}
    </div>
  )
}

🔹 Multiple AI Providers

Switch between different AI providers easily with the AI SDK. Use OpenAI, Anthropic, Google, or other providers based on your needs, pricing, or feature requirements.

// Using OpenAI
import { openai } from '@ai-sdk/openai'
const result = await generateText({
  model: openai('gpt-4'),
  prompt: 'Hello'
})

// Using Anthropic
import { anthropic } from '@ai-sdk/anthropic'
const result = await generateText({
  model: anthropic('claude-3-opus-20240229'),
  prompt: 'Hello'
})

// Using Google
import { google } from '@ai-sdk/google'
const result = await generateText({
  model: google('gemini-pro'),
  prompt: 'Hello'
})

🧠 Test Your Knowledge

What hook is used for chat interfaces in Vercel AI SDK?