首页  >  文章  >  web前端  >  使用 OpenAI GPT 和 DALL·E 模型,使用 AI/ML API、Next.js、React 和 Tailwind CSS 构建 AI 贴纸制作平台。

使用 OpenAI GPT 和 DALL·E 模型,使用 AI/ML API、Next.js、React 和 Tailwind CSS 构建 AI 贴纸制作平台。

DDD
DDD原创
2024-10-27 02:55:30353浏览

我很无聊。你也是吗? ​​?

嗯...?

创建一个AI Sticker Maker平台怎么样?说实话,这是一个非常有趣的想法。嘿,我们甚至可以通过简单地将 Stripe 整合为支付提供商来产生一些利润。 ?是啊,为什么不呢?

那么,让我们开始吧。或者至少尝试一下! ?

快速介绍?

首先,让我们草拟一些伪代码或制定计划(除非您是一个真正的编写代码的构建者)。它应该是这样的:

  1. 用户输入提示(贴纸外观的文字描述)。
  2. 我们的AI贴纸制作器将生成一个非常可爱的贴纸。哒哒! ?

简单,不是吗? ?

但是等等,让我澄清一下。我们将使用两个模型:GPT-4oDALL·E 3,均来自 OpenAI。他们真的很炒作! ?

我们将使用 AI/ML API,它可以通过单个 API 访问 200 个 AI 模型。让我简单地告诉你吧。

认识 AI/ML API ??

AI/ML API 是一个改变游戏规则的平台,适合希望将尖端 AI 功能集成到其产品中的开发人员和 SaaS 企业家。它提供对 200 多个最先进的人工智能模型的单点访问,涵盖从 NLP 到计算机视觉的所有内容。

面向开发者的主要功能:

  • 广泛的模型库:200 个预训练模型,用于快速原型设计和部署。 ?
  • 自定义选项:微调模型以适应您的特定用例。 ?
  • 开发人员友好的集成:RESTful API 和 SDK,可无缝合并到您的堆栈中。 ?️
  • 无服务器架构:专注于编码,而不是基础设施管理。 ☁️

免费开始(0 美元):aimlapi.com ?

深入了解 AI/ML API 文档(非常详细,非常同意):docs.aimlapi.com ?

技术堆栈成分?

我们将使用

TypeScriptNext.jsReactTailwind CSS 来构建和设计我们的 AI 贴纸制作器平台。

  • TypeScript 只是一种编程语言,但确实是一种很棒的语言! ?
  • Next.js 是 Web 的 React 框架。它使我们能够利用 React 组件的强大功能创建高质量的 Web 应用程序。 ?
  • React 是用于 Web 和本机用户界面的库。 ?️
  • Tailwind CSS 是最好的样式设计——认真地构建你想要的任何东西。 ?
这只是我们将要使用的内容的快速概述。欢迎在这里了解有关它们的更多信息:

  • TypeScript:typescriptlang.org ?
  • Next.js:nextjs.org ⏭️
  • 反应:react.dev ⚛️
  • Tailwind CSS:tailwindcss.com ?️

做饭开始了吗?

让我们动手吧!首先,创建一个文件夹。打开你的终端并输入:

mkdir aiml-tutorial
cd aiml-tutorial

现在,让我们创建一个新的 Next.js 应用程序:

npx create-next-app@latest

它会问你几个问题:

您的项目名称是什么? ​​在这里,您应该输入您的应用程序名称。例如:aistickermaker。对于其余问题,只需按 Enter 键即可。

您将看到以下内容:

✔ Would you like to use TypeScript? … No / Yes
✔ Would you like to use ESLint? … No / Yes
✔ Would you like to use Tailwind CSS? … No / Yes
✔ Would you like your code inside a `src/` directory? … No / Yes
✔ Would you like to use App Router? (recommended) … No / Yes
✔ Would you like to use Turbopack for `next dev`? … No / Yes
✔ Would you like to customize the import alias (`@/*` by default)? … No / Yes

专业提示:请根据您的喜好随意选择“是”或“否”。我不会评判! ?

让我们用 VSCode 打开项目:

code .

现在,Visual Studio Code 应该直接通过此应用启动。是时候开始编码了! ?

实施API?️

首先,让我们创建 API 来增强用户提示并生成贴纸。转到 app 文件夹,然后创建一个名为 api 的新文件夹,并在其中创建两个新文件夹:enhancePrompt 和generateSticker。对于每个,创建一个route.ts 文件。

增强提示端点?‍♂️

现在,让我们从enhancePrompt端点开始。打开enhancePrompt文件夹内的route.ts并输入以下代码:

import { NextResponse } from 'next/server';

const systemPrompt = `
You are tasked with enhancing user prompts to generate clear, detailed, and creative descriptions for a sticker creation AI. The final prompt should be imaginative, visually rich, and aligned with the goal of producing a cute, stylized, and highly personalized sticker based on the user's input.

Instructions:

Visual Clarity: The enhanced prompt must provide clear visual details that can be directly interpreted by the image generation model. Break down and elaborate on specific elements of the scene, object, or character based on the user input.

Example: If the user says "A girl with pink hair," elaborate by adding features like "short wavy pink hair with soft, pastel hues."
Style & Theme:

Emphasize that the final output should reflect a cute, playful, and approachable style.
Add terms like "adorable," "cartoonish," "sticker-friendly," or "chibi-like" to guide the output to a lighter, cuter aesthetic.
Include styling prompts like “minimalistic lines,” “soft shading,” and “vibrant yet soothing colors.”
Personalization:

If a reference or context is given, enhance it to make the sticker feel personalized.
Add context-appropriate descriptors like “wearing a cozy blue hoodie,” “soft pink blush on cheeks,” or “a playful expression.”
Expression & Pose:

Where applicable, refine prompts with suggestions about facial expressions or body language. For example, “Smiling softly with big sparkling eyes” or “A cute wink and a slight tilt of the head.”
Background & Accessories:

Optionally suggest simple, complementary backgrounds or accessories, depending on user input. For instance, "A light pastel background with small, floating hearts" or "Holding a tiny, sparkling star."
Colors:

Emphasize the color scheme based on the user's description, making sure it's consistent with a cute, playful style.
Use descriptors like “soft pastels,” “bright and cheerful,” or “warm and friendly hues” to set the mood.
Avoid Overcomplication:

Keep the descriptions short enough to be concise and not overly complex, as the output should retain a sticker-friendly quality.
Avoid unnecessary details that could clutter the design.
Tone and Language:

The tone should be light, imaginative, and fun, matching the playful nature of stickers.

Example:
User Input:
"A girl with pink hair wearing a hoodie."

Enhanced Prompt:
"An adorable girl with short, wavy pink hair in soft pastel hues, wearing a cozy light blue hoodie. She has a sweet smile with big, sparkling eyes, and a playful expression. The sticker style is cartoonish with minimalistic lines and soft shading. The background is a simple light pastel color with small floating hearts, creating a cute and inviting look."
`;

export async function POST(request: Request) {
    try {
        const { userPrompt } = await request.json();
        console.log("/api/enhancePrompt/route.ts userPrompt: ", userPrompt);

        // Make the API call to the external service
          const response = await fetch('https://api.aimlapi.com/chat/completions', {
            method: 'POST',
            headers: {
              'Content-Type': 'application/json',
              'Authorization': `Bearer ${process.env.NEXT_PUBLIC_AIML_API_KEY}`
            },
            body: JSON.stringify({
              model: 'gpt-4o-mini',
              messages: [
                {
                  role: 'system',
                  content: systemPrompt
                },
                {
                  role: 'user',
                  content: userPrompt
                }
              ]
            })
          });

        console.log("response: ", response);

        if (!response.ok) {
            // If the API response isn't successful, return an error response
            return NextResponse.json({ error: "Failed to fetch completion data" }, { status: response.status });
        }

        const data = await response.json();
        console.log("data: ", data);

        const assistantResponse = data.choices[0]?.message?.content || "No response available";

        // Return the assistant's message content
        return NextResponse.json({ message: assistantResponse });
    } catch (error) {
        console.error("Error fetching the data:", error);
        return NextResponse.json({ error: "An error occurred while processing your request." }, { status: 500 });
    }
}

这里是单独的提示:

You are tasked with enhancing user prompts to generate clear, detailed, and creative descriptions for a sticker creation AI. The final prompt should be imaginative, visually rich, and aligned with the goal of producing a cute, stylized, and highly personalized sticker based on the user's input.

Instructions:

Visual Clarity: The enhanced prompt must provide clear visual details that can be directly interpreted by the image generation model. Break down and elaborate on specific elements of the scene, object, or character based on the user input.

Example: If the user says "A girl with pink hair," elaborate by adding features like "short wavy pink hair with soft, pastel hues."
Style & Theme:

Emphasize that the final output should reflect a cute, playful, and approachable style.
Add terms like "adorable," "cartoonish," "sticker-friendly," or "chibi-like" to guide the output to a lighter, cuter aesthetic.
Include styling prompts like “minimalistic lines,” “soft shading,” and “vibrant yet soothing colors.”
Personalization:

If a reference or context is given, enhance it to make the sticker feel personalized.
Add context-appropriate descriptors like “wearing a cozy blue hoodie,” “soft pink blush on cheeks,” or “a playful expression.”
Expression & Pose:

Where applicable, refine prompts with suggestions about facial expressions or body language. For example, “Smiling softly with big sparkling eyes” or “A cute wink and a slight tilt of the head.”
Background & Accessories:

Optionally suggest simple, complementary backgrounds or accessories, depending on user input. For instance, "A light pastel background with small, floating hearts" or "Holding a tiny, sparkling star."
Colors:

Emphasize the color scheme based on the user's description, making sure it's consistent with a cute, playful style.
Use descriptors like “soft pastels,” “bright and cheerful,” or “warm and friendly hues” to set the mood.
Avoid Overcomplication:

Keep the descriptions short enough to be concise and not overly complex, as the output should retain a sticker-friendly quality.
Avoid unnecessary details that could clutter the design.
Tone and Language:

The tone should be light, imaginative, and fun, matching the playful nature of stickers.

Example:
User Input:
"A girl with pink hair wearing a hoodie."

Enhanced Prompt:
"An adorable girl with short, wavy pink hair in soft pastel hues, wearing a cozy light blue hoodie. She has a sweet smile with big, sparkling eyes, and a playful expression. The sticker style is cartoonish with minimalistic lines and soft shading. The background is a simple light pastel color with small floating hearts, creating a cute and inviting look."

这里发生了什么? ?

  • 导入 NextResponse:顺利处理我们的 HTTP 响应。
  • 定义 POST 函数:当有人到达此端点时,魔法就会发生。
  • 获取用户提示:我们正在获取用户提供的提示。
  • 调用AI/ML API的API:我们正在请求使用GPT-4o增强用户的提示。
  • 处理响应:我们检查响应是否正确,解析数据,并提取助手的响应。
  • 错误处理:因为没有人喜欢未处理的错误破坏聚会。

这是人工智能如何增强用户提示的实际示例。 ???

您刚刚输入了提示:

A cute panda eating ice cream under a rainbow

人工智能将对其进行增强,使其更加详细且视觉丰富。因此,您应该得到如下响应:

An adorable, chibi-like panda with big, sparkling eyes and a joyful expression, savoring a colorful scoop of ice cream. The panda is fluffy and round, with classic black-and-white markings, sitting contentedly. The ice cream cone features vibrant, swirling flavors in pastel pink, mint green, and sunny yellow. Above, a playful, cartoonish rainbow arcs across a soft blue sky, adding a cheerful splash of color. The design is sticker-friendly with minimalistic lines and soft shading, ensuring a cute and delightful aesthetic perfect for capturing the joyful scene.

好吧,让我们回到代码大锅,继续烹饪我们的 AI 贴纸制作器! ?

generateSticker 端点?️

所以,我们的 enhancePrompt 端点已经很好地酝酿了。是时候使用 generateSticker 端点来增添趣味了。前往 api/generateSticker 文件夹并打开 route.ts。用这个新代码替换其中的任何内容(可能什么都没有):

mkdir aiml-tutorial
cd aiml-tutorial

这里发生了什么? ?

  • 导入 NextResponse:顺利处理我们的 HTTP 响应。
  • 定义 POST 函数:当有人到达此端点时,魔法就会发生。
  • 获取用户提示:我们正在获取用户提供的提示。
  • 调用AI/ML API的API:我们正在使用DALL·E 3根据提示请求生成图像。
  • 处理响应:我们检查响应是否正常,解析数据并提取图像 URL。
  • 错误处理:因为没有人喜欢未处理的错误破坏聚会。

让我们用熊猫来尝试上面的提示吧! ?

这是我们可爱的熊猫贴纸! ???

Building an AI Sticker Maker Platform with AI/ML API, Next.js, React, and Tailwind CSS using OpenAI GPT-and DALL·E odels.

其他例子?

提示:

npx create-next-app@latest

Building an AI Sticker Maker Platform with AI/ML API, Next.js, React, and Tailwind CSS using OpenAI GPT-and DALL·E odels.

提示:

✔ Would you like to use TypeScript? … No / Yes
✔ Would you like to use ESLint? … No / Yes
✔ Would you like to use Tailwind CSS? … No / Yes
✔ Would you like your code inside a `src/` directory? … No / Yes
✔ Would you like to use App Router? (recommended) … No / Yes
✔ Would you like to use Turbopack for `next dev`? … No / Yes
✔ Would you like to customize the import alias (`@/*` by default)? … No / Yes

Building an AI Sticker Maker Platform with AI/ML API, Next.js, React, and Tailwind CSS using OpenAI GPT-and DALL·E odels.

看起来,真的哇! ?

我们需要一个前端,伙计们! ?

构建前端?

是时候在我们的应用程序上添加面孔了!让我们创建一个用户界面,用户可以在其中输入提示并获得闪亮的新贴纸。

page.tsx 文件?

导航到 app/page.tsx 并使用以下代码更新它:

mkdir aiml-tutorial
cd aiml-tutorial

打破它?

  • 加载器:我们使用非常简单但很好的加载器;三个水平点,带有一些漂亮的动画:
npx create-next-app@latest
  • 状态管理:使用useState来处理通知、加载状态、用户提示和贴纸URL。
  • 功能
    • enhanceUserPrompt:调用我们的 /api/enhancePrompt 端点,让用户的提示更加......好吧,提示
    • generateCuteSticker:点击 /api/generateSticker 端点即可获得可爱的贴纸。
    • generateSticker:当用户单击魔术按钮时编排整个过程。
    • handleDownload:允许用户下载他们的新贴纸。
    • handleClose:关闭贴纸模式。
  • UI 组件
    • 输入字段:用户可以在其中输入他们最疯狂的贴纸梦想。
    • 生成按钮:触发贴纸生成。
    • 模态:显示带有下载或关闭选项的贴纸。
    • 通知:弹出消息以告知用户发生了什么事。

洒一点 FontAwesome ?

我们使用 FontAwesome 作为图标。确保安装它:

✔ Would you like to use TypeScript? … No / Yes
✔ Would you like to use ESLint? … No / Yes
✔ Would you like to use Tailwind CSS? … No / Yes
✔ Would you like your code inside a `src/` directory? … No / Yes
✔ Would you like to use App Router? (recommended) … No / Yes
✔ Would you like to use Turbopack for `next dev`? … No / Yes
✔ Would you like to customize the import alias (`@/*` by default)? … No / Yes

您还可以查看 FontAwesome 文档以获取更多详细信息。或者搜索其他图标 搜索图标。

处理通知?

还记得我们导入的通知组件吗?让我们来创建它。

创建通知组件?

app 目录中创建一个名为 utils 的新文件夹。在 utils 中,创建一个名为 notify.tsx 的文件并粘贴:

code .

这是做什么用的? ?

  • 用途:向用户显示临时消息,例如“正在生成可爱的贴纸...”或“发生错误。”
  • 自动关闭功能:3秒后消失,就像我周一早上的动力一样。
  • 样式:根据通知类型更改颜色。

配置图像域?️

由于我们从 OpenAI 的服务器获取图像,Next.js 需要知道是否可以加载它们。打开 next.config.ts 并添加:

import { NextResponse } from 'next/server';

const systemPrompt = `
You are tasked with enhancing user prompts to generate clear, detailed, and creative descriptions for a sticker creation AI. The final prompt should be imaginative, visually rich, and aligned with the goal of producing a cute, stylized, and highly personalized sticker based on the user's input.

Instructions:

Visual Clarity: The enhanced prompt must provide clear visual details that can be directly interpreted by the image generation model. Break down and elaborate on specific elements of the scene, object, or character based on the user input.

Example: If the user says "A girl with pink hair," elaborate by adding features like "short wavy pink hair with soft, pastel hues."
Style & Theme:

Emphasize that the final output should reflect a cute, playful, and approachable style.
Add terms like "adorable," "cartoonish," "sticker-friendly," or "chibi-like" to guide the output to a lighter, cuter aesthetic.
Include styling prompts like “minimalistic lines,” “soft shading,” and “vibrant yet soothing colors.”
Personalization:

If a reference or context is given, enhance it to make the sticker feel personalized.
Add context-appropriate descriptors like “wearing a cozy blue hoodie,” “soft pink blush on cheeks,” or “a playful expression.”
Expression & Pose:

Where applicable, refine prompts with suggestions about facial expressions or body language. For example, “Smiling softly with big sparkling eyes” or “A cute wink and a slight tilt of the head.”
Background & Accessories:

Optionally suggest simple, complementary backgrounds or accessories, depending on user input. For instance, "A light pastel background with small, floating hearts" or "Holding a tiny, sparkling star."
Colors:

Emphasize the color scheme based on the user's description, making sure it's consistent with a cute, playful style.
Use descriptors like “soft pastels,” “bright and cheerful,” or “warm and friendly hues” to set the mood.
Avoid Overcomplication:

Keep the descriptions short enough to be concise and not overly complex, as the output should retain a sticker-friendly quality.
Avoid unnecessary details that could clutter the design.
Tone and Language:

The tone should be light, imaginative, and fun, matching the playful nature of stickers.

Example:
User Input:
"A girl with pink hair wearing a hoodie."

Enhanced Prompt:
"An adorable girl with short, wavy pink hair in soft pastel hues, wearing a cozy light blue hoodie. She has a sweet smile with big, sparkling eyes, and a playful expression. The sticker style is cartoonish with minimalistic lines and soft shading. The background is a simple light pastel color with small floating hearts, creating a cute and inviting look."
`;

export async function POST(request: Request) {
    try {
        const { userPrompt } = await request.json();
        console.log("/api/enhancePrompt/route.ts userPrompt: ", userPrompt);

        // Make the API call to the external service
          const response = await fetch('https://api.aimlapi.com/chat/completions', {
            method: 'POST',
            headers: {
              'Content-Type': 'application/json',
              'Authorization': `Bearer ${process.env.NEXT_PUBLIC_AIML_API_KEY}`
            },
            body: JSON.stringify({
              model: 'gpt-4o-mini',
              messages: [
                {
                  role: 'system',
                  content: systemPrompt
                },
                {
                  role: 'user',
                  content: userPrompt
                }
              ]
            })
          });

        console.log("response: ", response);

        if (!response.ok) {
            // If the API response isn't successful, return an error response
            return NextResponse.json({ error: "Failed to fetch completion data" }, { status: response.status });
        }

        const data = await response.json();
        console.log("data: ", data);

        const assistantResponse = data.choices[0]?.message?.content || "No response available";

        // Return the assistant's message content
        return NextResponse.json({ message: assistantResponse });
    } catch (error) {
        console.error("Error fetching the data:", error);
        return NextResponse.json({ error: "An error occurred while processing your request." }, { status: 500 });
    }
}

为什么要这样做? ?‍♂️

因为 Next.js 有点过度保护(就像直升机父母一样),除非您特别允许,否则不会从外部域加载图像。此设置告诉 Next.js,“这很酷,这些图像在我身边。”

环境变量?

现在,在您兴奋地运行应用程序并想知道为什么它不起作用之前,让我们设置环境变量。

设置您的 AI/ML API 密钥?️

在项目的根目录中创建一个名为 .env.local 的文件并添加:

mkdir aiml-tutorial
cd aiml-tutorial

your_api_key_here 替换为您的实际 AI/ML API 密钥。如果您没有,您可能需要在 AI/ML API 上注册并获取它。绝对免费开始使用!

这里有一个关于如何获取 API 密钥的快速教程:如何从 AI/ML API 获取 API 密钥。带有屏幕截图的快速分步教程,以便更好地理解。

警告:请保密此密钥!不要公开共享它或将其提交到 Git。将其视为您的 Netflix 密码。

点燃它! ?

是时候看看这个宝宝的行动了。

运行开发服务器?‍♀️

在您的终端中,运行:

npx create-next-app@latest

这将启动开发服务器。打开浏览器并导航至 http://localhost:3000.

您应该会看到您的 AI Sticker Maker 平台。 ?

Building an AI Sticker Maker Platform with AI/ML API, Next.js, React, and Tailwind CSS using OpenAI GPT-and DALL·E odels.

测试一下?

  • 输入提示:类似“一个留着白色灰色短发、穿着超大衬衫的女孩”。疯狂吧!

Building an AI Sticker Maker Platform with AI/ML API, Next.js, React, and Tailwind CSS using OpenAI GPT-and DALL·E odels.

  • 单击按钮:点击生成按钮并观看奇迹的展开。
  • 等待...:您会看到通知,让您随时了解情况。
  • 瞧!:您的 AI 生成的贴纸应该会出现。沐浴在它的荣耀之中。

Building an AI Sticker Maker Platform with AI/ML API, Next.js, React, and Tailwind CSS using OpenAI GPT-and DALL·E odels.

故障排除?️

  • “无法获取完成数据”:仔细检查您的 API 密钥并确保其设置正确。
  • 图像未加载:确保您的next.config.ts 文件设置如上所示。
  • 应用程序崩溃:打开控制台并查看弹出的错误。谷歌是你的朋友!

结束了吗?

恭喜!您刚刚构建了一个既有趣又实用的 AI 贴纸制作器。您不仅深入研究了 AI 和 Next.js 的世界,还制作了一些可以给人们带来微笑的东西。

接下来是什么? ?

  • 造型:自定义外观和感觉。随心所欲地打造精美或极简风格。
  • 功能:添加用户帐户、贴纸库,甚至创建贴纸包的功能。
  • 货币化:集成 Stripe 并开始对高级贴纸收费。是时候赚点钱了!

最后的想法?

构建这个应用程序就像制作一个具有多层技术优势的三明治。我们有 AI 模型作为馅料,Next.js 作为面包,还有一点幽默作为秘方。

记住,世界是你的牡蛎(或贴纸)。不断尝试,不断构建,最重要的是,玩得开心!

编码愉快! ?

Github AI Sticker Maker 上提供完整实施。

开始完全免费!立即尝试点击

也看看这个教程,非常有趣!使用 AI/ML API、Deepgram Aura 和 IndexedDB 集成从头开始构建 Chrome 扩展

如果您有任何疑问或需要进一步帮助,请随时通过电子邮件联系 abdibrokhim@gmail.com。

以上是使用 OpenAI GPT 和 DALL·E 模型,使用 AI/ML API、Next.js、React 和 Tailwind CSS 构建 AI 贴纸制作平台。的详细内容。更多信息请关注PHP中文网其他相关文章!

声明:
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系admin@php.cn