首頁  >  文章  >  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:30267瀏覽

我很無聊。你也是嗎? ?

嗯...?

建立一個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來處理通知、載入狀態、使用者提示和貼圖網址。
  • 功能
    • 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