前端 UI 組件的 AI 時(shí)代來(lái)了!!!
共 22319字,需瀏覽 45分鐘
·
2024-06-05 09:15
點(diǎn)擊上方 前端Q,關(guān)注公眾號(hào)
回復(fù)加群,加入前端Q技術(shù)交流群
本文將教您如何構(gòu)建一個(gè)AI驅(qū)動(dòng)的前端UI組件生成器,它可以幫助您生成Next.js Tailwind CSS UI組件,并提供實(shí)現(xiàn)教程。我們將涵蓋以下內(nèi)容:
-
使用Next.js、TypeScript和Tailwind CSS構(gòu)建UI組件生成器Web應(yīng)用程序。 -
使用CopilotKit將AI功能集成到UI組件生成器中。 -
集成嵌入式代碼編輯器,以對(duì)生成的代碼進(jìn)行更改。
前提條件
為了充分理解本教程,您需要對(duì)React或Next.js有基本的了解。以下是構(gòu)建AI驅(qū)動(dòng)的UI組件生成器所需的工具:
-
Ace Code Editor - 一個(gè)使用JavaScript編寫(xiě)的可嵌入代碼編輯器,具有與原生編輯器相匹配的功能和性能。。 -
Langchain - 提供一個(gè)框架,使AI代理能夠搜索網(wǎng)絡(luò)并研究任何主題。 -
OpenAI API - 提供一個(gè)API密鑰,使您能夠使用ChatGPT模型執(zhí)行各種任務(wù)。 -
Tavily AI - 一個(gè)搜索引擎,使AI代理能夠在應(yīng)用程序中進(jìn)行研究并訪問(wèn)實(shí)時(shí)知識(shí)。。 -
CopilotKit - 一個(gè)用于構(gòu)建自定義AI聊天機(jī)器人、應(yīng)用內(nèi)AI代理和文本區(qū)域的開(kāi)源協(xié)作框架。
項(xiàng)目設(shè)置和包安裝
首先,在終端中運(yùn)行下面的代碼片段來(lái)創(chuàng)建一個(gè)Next.js應(yīng)用程序:
npx create-next-app@latest aiuigenerator
接下來(lái),安裝Ace代碼編輯器和Langchain包及其依賴(lài)項(xiàng)。
npm install react-ace @langchain/langgraph
最后,安裝CopilotKit。這些包使我們能夠從React狀態(tài)中檢索數(shù)據(jù)并將AI協(xié)同助手添加到應(yīng)用程序中。
npm install @copilotkit/react-ui @copilotkit/react-textarea @copilotkit/react-core @copilotkit/backend
恭喜!您現(xiàn)在已經(jīng)準(zhǔn)備好構(gòu)建一個(gè)由人工智能驅(qū)動(dòng)的博客了。
構(gòu)建UI組件生成器前端界面
在這個(gè)部分中,我將帶您逐步完成創(chuàng)建UI組件生成器前端的過(guò)程,使用靜態(tài)內(nèi)容來(lái)定義生成器的用戶(hù)界面。
首先,打開(kāi)您的代碼編輯器,前往/[root]/src/app目錄,并創(chuàng)建一個(gè)名為components的文件夾。在components文件夾內(nèi),創(chuàng)建兩個(gè)文件,分別命名為Header.tsx和CodeTutorial.tsx。
在Header.tsx文件中,添加以下代碼,定義一個(gè)名為Header的函數(shù)組件,用于渲染生成器的導(dǎo)航欄。
"use client";
import Link from "next/link";
export default function Header() {
return (
<>
<header className="flex flex-wrap sm:justify-start sm:flex-nowrap z-50 w-full bg-gray-800 border-b border-gray-200 text-sm py-3 sm:py-0 ">
<nav
className="relative max-w-7xl w-full mx-auto px-4 sm:flex sm:items-center sm:justify-between sm:px-6 lg:px-8"
aria-label="Global">
<div className="flex items-center justify-between">
<Link
className="w-full flex-none text-xl text-white font-semibold p-6"
href="/"
aria-label="Brand">
AI-UI-Components-Generator
</Link>
</div>
</nav>
</header>
</>
);
}
在CodeTutorial.tsx文件中,添加以下代碼,定義一個(gè)名為CodeTutorial的函數(shù)組件,用于渲染生成器的主頁(yè),顯示生成的UI組件、嵌入式代碼編輯器和生成的實(shí)現(xiàn)教程。
"use client";
import Markdown from "react-markdown";
import { useState } from "react";
import AceEditor from "react-ace";
import React from "react";
export default function CodeTutorial() {
const [code, setCode] = useState<string[]>([
`<h1 class="text-red-500">Hello World</h1>`,
]);
const [codeToDisplay, setCodeToDisplay] = useState<string>(code[0] || "");
const [codeTutorial, setCodeTutorial] = useState(``);
function onChange(newCode: any) {
setCodeToDisplay(newCode);
}
return (
<>
<main className=" min-h-screen px-4">
<div className="w-full h-full min-h-[70vh] flex justify-between gap-x-1 ">
<div className="w-2/3 min-h-[60vh] rounded-lg bg-white shadow-lg p-2 border mt-8 overflow-auto">
<div
className="w-full min-h-[60vh] rounded-lg"
dangerouslySetInnerHTML={{ __html: codeToDisplay }}
/>
</div>
<AceEditor
placeholder="Placeholder Text"
mode="html"
theme="monokai"
name="blah2"
className="w-[50%] min-h-[60vh] p-2 mt-8 rounded-lg"
onChange={onChange}
fontSize={14}
lineHeight={19}
showPrintMargin={true}
showGutter={true}
highlightActiveLine={true}
value={codeToDisplay}
setOptions={{
enableBasicAutocompletion: true,
enableLiveAutocompletion: true,
enableSnippets: false,
showLineNumbers: true,
tabSize: 2,
}}
/>
</div>
<div className="w-10/12 mx-auto">
<div className="mt-8">
<h1 className="text-white text-center text-xl font-semibold p-6">
Code Tutorial
</h1>
{codeTutorial ? (
<Markdown className="text-white">{codeTutorial}</Markdown>
) : (
<div className="text-white">
The Code Tutorial Will Appear Here
</div>
)}
</div>
</div>
</main>
</>
);
}
接下來(lái),進(jìn)入/[root]/src/page.tsx文件,并添加以下代碼,導(dǎo)入CodeTutorial和Header組件,并定義一個(gè)名為Home的函數(shù)組件。
import React from "react";
import Header from "./components/Header";
import CodeTutorial from "./components/CodeTutorial";
export default function Home() {
return (
<>
<Header />
<CodeTutorial />
</>
);
}
接下來(lái),刪除 globals.css 文件中的 CSS 代碼,并添加以下 CSS 代碼。
@tailwind base;
@tailwind components;
@tailwind utilities;
body {
height: 100vh;
background-color: rgb(16, 23, 42);
}
pre {
margin: 1rem;
padding: 1rem;
border-radius: 10px;
background-color: black;
overflow: auto;
}
h2,
p {
padding-bottom: 1rem;
padding-top: 1rem;
}
code {
margin-bottom: 2rem;
}
最后,在命令行中運(yùn)行 npm run dev 命令,然后導(dǎo)航至 http://localhost:3000/。
現(xiàn)在您應(yīng)該在瀏覽器上查看UI組件生成器的前端界面,如下所示:
使用 CopilotKit 將人工智能功能集成到組件生成器中
在這個(gè)部分,您將學(xué)習(xí)如何在UI組件生成器中添加一個(gè)AI copilot,使用CopilotKit生成UI組件代碼和實(shí)現(xiàn)教程。
CopilotKit提供了前端和后端兩個(gè)包。它們可以讓您將React狀態(tài)連接起來(lái),并使用AI代理在后端處理應(yīng)用程序數(shù)據(jù)。
首先,讓我們將CopilotKit的React組件添加到博客前端。
將CopilotKit添加到博客前端
在這里,我將引導(dǎo)您完成將UI組件生成器與CopilotKit前端集成的過(guò)程,以促進(jìn)UI組件代碼和實(shí)現(xiàn)教程的生成。
首先,請(qǐng)使用以下代碼片段,在 /[root]/src/app/components/CodeTutorial.tsx 文件的頂部導(dǎo)入 useMakeCopilotReadable 和 useCopilotAction自定義鉤子。
import {
useCopilotAction,
useMakeCopilotReadable,
} from "@copilotkit/react-core";
在 CodeTutorial 函數(shù)內(nèi)部,狀態(tài)變量下面,添加以下代碼,該代碼使用 useMakeCopilotReadable 鉤子(hook)來(lái)添加將作為應(yīng)用內(nèi)聊天機(jī)器人上下文的代碼。該鉤子使得代碼對(duì)于copilot易于可讀。
useMakeCopilotReadable(codeToDisplay);
在上述代碼下方,添加以下代碼,該代碼使用useCopilotAction鉤子來(lái)設(shè)置一個(gè)名為generateCodeAndImplementationTutorial的動(dòng)作,該動(dòng)作將啟用生成UI組件代碼和實(shí)現(xiàn)教程的功能。
該動(dòng)作接收兩個(gè)參數(shù),分別名為code和tutorial,用于生成UI組件代碼和實(shí)現(xiàn)教程。
該動(dòng)作包含一個(gè)處理函數(shù),該函數(shù)根據(jù)給定的提示生成UI組件代碼和實(shí)現(xiàn)教程。
在處理函數(shù)內(nèi)部,codeToDisplay狀態(tài)被更新為新生成的代碼,而codeTutorial狀態(tài)被更新為新生成的教程,如下所示。
useCopilotAction(
{
name: "generateCodeAndImplementationTutorial",
description:
"Create Code Snippet with React.js(Next.js), tailwindcss and an implementation tutorial of the code generated.",
parameters: [
{
name: "code",
type: "string",
description: "Code to be generated",
required: true,
},
{
name: "tutorial",
type: "string",
description:
"Markdown of step by step guide tutorial on how to use the generated code accompanied with the code. Include introduction, prerequisites and what happens at every step accompanied with code generated earlier. Don't forget to add how to render the code on browser.",
required: true,
},
],
handler: async ({ code, tutorial }) => {
setCode((prev) => [...prev, code]);
setCodeToDisplay(code);
setCodeTutorial(tutorial);
},
},
[codeToDisplay, codeTutorial]
);
接下來(lái),進(jìn)入/[root]/src/app/page.tsx文件,并在頂部使用以下代碼導(dǎo)入CopilotKit前端包和樣式。
import { CopilotKit } from "@copilotkit/react-core";
import { CopilotSidebar } from "@copilotkit/react-ui";
import "@copilotkit/react-ui/styles.css";
然后,使用CopilotKit來(lái)包裹CopilotSidebar和CodeTutorial組件,如下所示。CopilotKit組件指定了CopilotKit后端端點(diǎn)的URL(/api/copilotkit/),而CopilotSidebar渲染了應(yīng)用內(nèi)聊天機(jī)器人,你可以通過(guò)它給出提示來(lái)生成UI組件代碼和實(shí)現(xiàn)教程。
export default function Home() {
return (
<>
<Header />
<CopilotKit url="/api/copilotkit">
<CopilotSidebar
instructions="Help the user generate code. Ask the user if to generate its tutorial."
defaultOpen={true}
labels={{
title: "Code & Tutorial Generator",
initial: "Hi! ?? I can help you generate code and its tutorial.",
}}>
<CodeTutorial />
</CopilotSidebar>
</CopilotKit>
</>
);
}
接下來(lái),運(yùn)行開(kāi)發(fā)服務(wù)器并在瀏覽器中導(dǎo)航到http://localhost:3000。你應(yīng)該會(huì)看到應(yīng)用內(nèi)聊天機(jī)器人已經(jīng)被集成到了UI組件生成器中。
將CopilotKit后端添加到博客
在這里,我將引導(dǎo)您完成將UI組件生成器與CopilotKit后端集成的過(guò)程,該后端負(fù)責(zé)處理來(lái)自前端的請(qǐng)求,并提供函數(shù)調(diào)用以及各種大型語(yǔ)言模型(LLM)后端,例如GPT。
此外,我們還將集成一個(gè)名為T(mén)avily的AI agent,它能夠在網(wǎng)上研究任何主題。
要開(kāi)始,請(qǐng)?jiān)陧?xiàng)目的根目錄下創(chuàng)建一個(gè)名為.env.local的文件。然后,在文件中添加以下環(huán)境變量,這些變量將存儲(chǔ)您的ChatGPT和Tavily搜索API密鑰。
OPENAI_API_KEY="Your ChatGPT API key"
TAVILY_API_KEY="Your Tavily Search API key"
要獲取ChatGPT API密鑰,請(qǐng)導(dǎo)航到 https://platform.openai.com/api-keys。
要獲取Tavily搜索API密鑰,請(qǐng)?jiān)L問(wèn) https://app.tavily.com/home。
之后,前往/[root]/src/app目錄并創(chuàng)建一個(gè)名為api的文件夾。在api文件夾中,創(chuàng)建一個(gè)名為copilotkit的文件夾。
在copilotkit文件夾中,創(chuàng)建一個(gè)名為research.ts的文件。然后導(dǎo)航到這個(gè)research.ts gist文件,復(fù)制代碼,并將其添加到research.ts文件中。
接下來(lái),在/[root]/src/app/api/copilotkit文件夾中創(chuàng)建一個(gè)名為route.ts的文件。該文件將包含設(shè)置后端功能以處理POST請(qǐng)求的代碼。它條件性地包含一個(gè)“research”動(dòng)作,該動(dòng)作對(duì)給定主題進(jìn)行研究。
現(xiàn)在,在文件的頂部導(dǎo)入以下模塊:
import { CopilotBackend, OpenAIAdapter } from "@copilotkit/backend"; // For backend functionality with CopilotKit.
import { researchWithLangGraph } from "./research"; // Import a custom function for conducting research.
import { AnnotatedFunction } from "@copilotkit/shared"; // For annotating functions with metadata.
在上述代碼下方,定義一個(gè)運(yùn)行時(shí)環(huán)境變量和一個(gè)名為researchAction的函數(shù),該函數(shù)使用以下代碼研究某個(gè)特定主題。
// Define a runtime environment variable, indicating the environment where the code is expected to run.
export const runtime = "edge";
// Define an annotated function for research. This object includes metadata and an implementation for the function.
const researchAction: AnnotatedFunction<any> = {
name: "research", // Function name.
description: "Call this function to conduct research on a certain topic. Respect other notes about when to call this function", // Function description.
argumentAnnotations: [ // Annotations for arguments that the function accepts.
{
name: "topic", // Argument name.
type: "string", // Argument type.
description: "The topic to research. 5 characters or longer.", // Argument description.
required: true, // Indicates that the argument is required.
},
],
implementation: async (topic) => { // The actual function implementation.
console.log("Researching topic: ", topic); // Log the research topic.
return await researchWithLangGraph(topic); // Call the research function and return its result.
},
};
然后在上述代碼下方添加以下代碼,定義一個(gè)處理POST請(qǐng)求的異步函數(shù)。
// Define an asynchronous function that handles POST requests.
export async function POST(req: Request): Promise<Response> {
const actions: AnnotatedFunction<any>[] = []; // Initialize an array to hold actions.
// Check if a specific environment variable is set, indicating access to certain functionality.
if (process.env.TAVILY_API_KEY) {
actions.push(researchAction); // Add the research action to the actions array if the condition is true.
}
// Instantiate CopilotBackend with the actions defined above.
const copilotKit = new CopilotBackend({
actions: actions,
});
// Use the CopilotBackend instance to generate a response for the incoming request using an OpenAIAdapter.
return copilotKit.response(req, new OpenAIAdapter());
}
如何生成UI組件
現(xiàn)在請(qǐng)轉(zhuǎn)到您之前集成的應(yīng)用內(nèi)聊天機(jī)器人,并給它一個(gè)提示,例如:“生成一個(gè)聯(lián)系表單”。一旦生成完成,您應(yīng)該會(huì)看到生成的聯(lián)系表單組件以及其使用教程,如下所示。您還可以使用嵌入式代碼編輯器修改生成的代碼。
恭喜!您已經(jīng)完成了這個(gè)教程的項(xiàng)目。
結(jié)論
CopilotKit是一個(gè)令人驚嘆的工具,它允許您在幾分鐘內(nèi)將AI副駕駛添加到您的產(chǎn)品中。無(wú)論您對(duì)AI聊天機(jī)器人和助手感興趣,還是希望自動(dòng)化復(fù)雜任務(wù),CopilotKit都能讓這一切變得簡(jiǎn)單。
如果您需要構(gòu)建一個(gè)AI產(chǎn)品或?qū)⑵浼傻侥能浖?yīng)用程序中,您應(yīng)該考慮使用CopilotKit。
您可以在GitHub上找到本教程的源代碼:https://github.com/TheGreatBonnie/AIPoweredUIComponentsGenerator
參考鏈接
https://ace.c9.io/
https://www.langchain.com/
https://platform.openai.com/api-keys
https://tavily.com/
https://github.com/CopilotKit
本文譯者為 360 奇舞團(tuán)前端開(kāi)發(fā)工程師
原文標(biāo)題:AI-Powered Frontend UI Components Generator (Next.js, GPT4, Langchain, & CopilotKit)
原文作者:Bonnie
原文地址:https://dev.to/tcms/ai-powered-frontend-ui-components-generator-nextjs-gpt4-langchain-copilotkit-1hac
往期推薦
最后
歡迎加我微信,拉你進(jìn)技術(shù)群,長(zhǎng)期交流學(xué)習(xí)...
歡迎關(guān)注「前端Q」,認(rèn)真學(xué)前端,做個(gè)專(zhuān)業(yè)的技術(shù)人...
