🎉 让我们使用 Gemini API、Next.js 和 TailwindCSS 构建一个 AI Twitter 帖子项目 🚀
推特工艺
2025 年已经到来 ,还有什么比构建一个精彩的 Twitter 帖子项目来开启新的一年更好的方式呢?🎯 在本篇博文中,我将向您展示如何将 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
Enter fullscreen mode
Exit fullscreen mode
2. 安装 Gemini API 包 📦
现在,让我们安装 Gemini npm 包:
npm i @google/generative-ai
Enter fullscreen mode
Exit fullscreen mode
.env.local
在根目录中 创建一个文件并添加您的 Gemini API 密钥:
GEMINI_API_KEY=your_api_key_here
Enter fullscreen mode
Exit fullscreen mode
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 });
}
}
Enter fullscreen mode
Exit fullscreen mode
以上代码的功能描述为:
生成推文: 获取描述,使用 Google 的 AI 基于此创建推文。
错误处理: 如果没有提供描述或者 AI 失败,则返回错误。
使用的 AI 模型: 用于 gemini-1.5-flash
内容生成。
generate tweet
4. 处理 : , copy tweet
. 的主要前端逻辑 regenerate tweet
是:
这是简单的 server side
html,tailwindcss 组件:
import { RiTwitterXLine } from " react-icons/ri " ;
import InteractiveForm from " ./components/InteractiveForm " ;
export default function Home () {
return (
< div className = "flex flex-col justify-center items-center min-h-screen bg-[#1a1a1a] w-full" >
< RiTwitterXLine size = { 50 } color = "white" />
< div className = "flex flex-col justify-center items-center mt-7 w-full max-w-4xl py-3" >
< p className = "text-white text-4xl font-extrabold" > Idea to tweet in seconds.</ p >
< p className = "text-white text-2xl" > Tweet Craft is your superhuman tweet-writing expert.</ p >
< InteractiveForm />
</ div >
</ div >
);
}
Enter fullscreen mode
Exit fullscreen mode
处理所有推文生成、复制、重新生成的主要部分是 client side component
:
' use client ' ;
import { useState } from ' react ' ;
import { BsArrowRightCircle } from " react-icons/bs " ;
export default function InteractiveForm () {
const [ tweet , setTweet ] = useState < string | null > ( 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 (
< div className = "w-full relative" >
< form onSubmit = { handleSubmit } className = "w-full" >
< div className = "relative" >
< textarea
id = "description"
name = "description"
rows = { 10 }
placeholder = "Write your thoughts here..."
className = "
block
w-full
px-4
py-3
mt-4
bg- [# 1a1a1a ]
text-lg
border
border-gray-300
text-white
rounded-md
focus : outline-none
focus : ring-2
focus : ring-gray-300
focus : border-transparent
"
/>
< button
type = "submit"
className = "
absolute
bottom-2
right-2
p-2
rounded-full
text-white
bg-transparent
hover : bg-gray-700
"
disabled = { loading }
>
< BsArrowRightCircle size = { 30 } />
</ button >
</ div >
</ form >
{ tweet && (
< div className = "mt-6 text-white" >
< p className = "text-lg" > { tweet } </ p >
< div className = "flex gap-4 mt-4" >
< button
onClick = { handleCopy }
className = "px-4 py-2 bg-blue-500 rounded-full text-white hover:bg-blue-400"
>
Copy
</ button >
< button
onClick = { handleRegenerate }
className = "px-4 py-2 bg-green-500 rounded-full text-white hover:bg-green-400"
>
Regenerate
</ button >
</ div >
</ div >
) }
{ loading && (
< div className = "absolute top-0 left-0 w-full h-full flex items-center justify-center bg-opacity-50" >
< span className = "text-white" > Generating tweet...</ span >
</ div >
) }
</ div >
);
}
Enter fullscreen mode
Exit fullscreen mode
您可以使用 Tailwind 类轻松更改颜色、间距和其他设计元素。
5.运行项目🚀
现在,是时候运行你的项目了:
npm run dev
Enter fullscreen mode
Exit fullscreen mode
在浏览器中打开 http://localhost:3000
,你会看到类似 Twitter 的帖子动态!🎉
为代码库做出贡献💻
我很期待看到你能用这个项目构建出什么!欢迎随意 fork 此仓库、创建问题,甚至提交拉取请求。让我们一起让这个项目更加强大!
比如嵌入 twitter api、添加建议按钮功能等。
在这里查看 GitHub 存储库🚀:
Tweet Craft 是一款基于 Next.js 构建的 AI 应用,可根据用户描述生成推文。通过使用 Gemini 的 API,该应用允许用户根据自己的输入轻松创建推文,非常适合那些寻求快速且富有创意的社交媒体内容的用户。
推特工艺
Tweet Craft 是一款基于 Next.js 构建的 AI 应用,可根据用户描述生成推文。通过使用 Gemini 的 API,该应用允许用户根据自己的输入轻松创建推文,非常适合那些寻求快速创意社交媒体内容的用户。视频链接: https://vimeo.com/1043260556? share=copy
特征
AI 推文生成 :用户提供描述,应用程序根据输入生成推文。
Gemini API 集成 :该应用程序利用 Gemini 的 API 来处理自然语言描述并创建推文。
安装
先决条件
Node.js(>= 18.0)
npm 或 yarn(包管理器)
入门步骤
克隆存储库:
git clone https://github.com/Jagroop2001/tweet-craft
cd tweet-craft
Enter fullscreen mode
Exit fullscreen mode
安装依赖项:
npm install
# OR
yarn install
Enter fullscreen mode
Exit fullscreen mode
设置您的 Gemini API 密钥:
.env.local
在项目的根目录中 创建一个文件。
将您的 Gemini API 密钥添加到文件中:
GEMINI_AI_API_KEY=" YOUR GEMINI API KEY"
Enter fullscreen mode
Exit fullscreen mode
跑步…
祝你编程愉快,2025 年一切顺利!🎉 让我们一起创造更多酷炫的东西!
🚀 保持联系,关注我的旅程! 🌟 👉 在 Twitter 上关注我 🐦 👉 查看我的 GitHub 💻
鏂囩珷鏉ユ簮锛�https://dev.to/jagroop2001/lets-build-an-ai-twitter-post-project-using-gemini-api-nextjs-and-tailwindcss-3194