🎉 让我们使用 Gemini API、Next.js 和 TailwindCSS 构建一个 AI Twitter 帖子项目 🚀

**2025 年已经到来**,还有什么比建立一个出色的 Twitter Post 项目更好的方式开启新的一年呢?🎯 在这篇博客中,我将向您展示如何将 **Gemini API** 与 **Next.js** 集成,并使用 **TailwindCSS** 对其进行样式设置,以创建一个简单但有效的帖子系统。此外,我们将使用 **Gemini API Key** 来获取帖子并显示它们。

让我们首先预览一下我们的最终小项目是什么样子的:

现在,让我们开始吧!🔥

先决条件📋

在开始之前,请确保您已:

  • 已安装 Node.js
  • Gemini API 密钥(在 Gemini 上设置密钥)
  • 熟悉 Next.js/React.js 和 TailwindCSS(如果您需要复习或想学习 Nextjs/Reactjs,请查看本课程:
  • 1.创建一个 Next.js 项目

    首先创建一个新的 Next.js 项目:

    npx create-next-app twitter-post
    cd twitter-post

    2. 安装 Gemini API 包

    现在,让我们安装 Gemini npm 包:

    npm i @google/generative-ai

    在根目录中创建一个 `.env.local` 文件并添加您的 Gemini API 密钥:

    GEMINI_API_KEY=your_api_key_here

    3. 使用 Gemini API 获取 Twitter 帖子🔥

    在项目中创建 `app/api/submit/route.ts` 路径,在 route.ts 中我们将使用 Gemini API 获取类似 Twitter 的帖子并显示它们。

    import { GoogleGenerativeAI } from '@google/generative-ai';
    import { NextResponse } from 'next/server';
    
    const API_KEY = process.env.GEMINI_AI_API_KEY || "";
    
    export async function POST(req: Request) {
      const { description } = await req.json();
    
      if (!description) {
        return NextResponse.json(
          { error: 'Description is required.' },
          { status: 400 }
        );
      }
    
      try {
        const genAI = new GoogleGenerativeAI(API_KEY);
        const model = await genAI.getGenerativeModel({ model: 'gemini-1.5-flash' });
        const prompt = `Generate twitter tweet on the basis of this description: ${description}`;
        const result = await model.generateContent([prompt]);
    
        if (result && result.response) {
          const generatedText = await result.response.text();
          return NextResponse.json({ tweet: generatedText });
        } else {
          throw new Error('No response received from model.');
        }
      } catch (error) {
        console.error('Error generating tweet:', error);
        return NextResponse.json({ error: 'Failed to generate tweet' }, { status: 500 });
      }
    }

    以上代码的功能描述为:

  • 生成推文:获取描述,使用 Google 的 AI 基于此创建推文。
  • 错误处理:如果没有提供描述或者 AI 失败,则返回错误。
  • 使用的 AI 模型:使用 gemini-1.5-flash 进行内容生成。
  • 4. 处理的主要前端逻辑:生成推文,复制推文。重新生成推文是:

    这是简单的“服务器端” html,tailwindcss 组件:

    import { RiTwitterXLine } from "react-icons/ri";
    import InteractiveForm from "./components/InteractiveForm";
    
    export default function Home() {
      return (
        

    Idea to tweet in seconds.

    Tweet Craft is your superhuman tweet-writing expert.

    ); }

    处理所有推文生成、复制、重新生成的主要部分是“客户端组件”,即:

    'use client';
    
    import { useState } from 'react';
    import { BsArrowRightCircle } from "react-icons/bs";
    
    export default function InteractiveForm() {
      const [tweet, setTweet] = useState(null);
      const [loading, setLoading] = useState(false);
    
      const handleSubmit = async (e: any) => {
        e.preventDefault();
        const description = e.target.description.value;
        setLoading(true);
    
        const response = await fetch('/api/submit', {
          method: 'POST',
          headers: {
            'Content-Type': 'application/json',
          },
          body: JSON.stringify({ description }),
        });
    
        const result = await response.json();
        setLoading(false);
    
        if (result.tweet) {
          setTweet(result.tweet);
        } else {
          console.error('Error:', result.error);
        }
      };
    
      const handleCopy = () => {
        if (tweet) {
          navigator.clipboard.writeText(tweet);
          alert('Tweet copied to clipboard!');
        }
      };
    
      const handleRegenerate = async () => {
        if (tweet) {
          setLoading(true);
          const description = tweet;
          const response = await fetch('/api/submit', {
            method: 'POST',
            headers: {
              'Content-Type': 'application/json',
            },
            body: JSON.stringify({ description }),
          });
    
          const result = await response.json();
          setLoading(false);
    
          if (result.tweet) {
            setTweet(result.tweet);
          }
        }
      };
    
      return (