AI 前端组件自动生成工具
基于 GPT4 + Langchain 的 Next.js 组件生成器,将样式图转化为生产级组件代码,大幅提升前端开发效率。
基于 GPT4 + Langchain 的 Next.js 组件生成器,将样式图转化为生产级组件代码,大幅提升前端开发效率。
在本文中,你将学习如何构建一个 AI 驱动的前端 UI 组件生成器,使你能够生成 Next.js Tailwind CSS UI 组件,并提供实现教程。
学习内容:
使用 Next.js、TypeScript 和 Tailwind CSS 构建 UI 组件生成器 web 应用。
使用 CopilotKit 将 AI 功能集成到 UI 组件生成器中。
集成嵌入式代码编辑器以对生成的代码进行修改。
要充分理解本教程,你需要对 React 或 Next.js 有基本的了解。
以下是构建 AI 驱动的 UI 组件生成器所需的工具:
Ace Code Editor - 用 JavaScript 编写的可嵌入代码编辑器,功能和性能都与原生编辑器相匹配。
Langchain - 提供一个框架,使 AI agents 能够搜索网页和研究任何主题。
OpenAI API - 提供 API 密钥,使你能够使用 ChatGPT 模型执行各种任务。
Tavily AI - 一个搜索引擎,使 AI agents 能够进行研究并在应用中访问实时知识。
CopilotKit - 一个开源的 copilot 框架,用于构建自定义 AI 聊天机器人、应用内 AI agents 和文本区域。
首先,在终端中运行以下代码片段创建一个 Next.js 应用:
npx create-next-app@latest aiuigenerator
选择你喜欢的配置设置。在本教程中,我们将使用 TypeScript 和 Next.js App Router。
接下来,安装 Ace 代码编辑器、Langchain 包及其依赖。
npm install react-ace @langchain/langgraph
最后,安装 CopilotKit 包。这些包使我们能够从 React 状态中检索数据并向应用中添加 AI copilot。
npm install @copilotkit/react-ui @copilotkit/react-textarea @copilotkit/react-core @copilotkit/backend
恭喜!你现在已准备好构建一个 AI 驱动的博客。
在本部分中,我将引导你完成创建 UI 组件生成器前端的过程,使用静态内容来定义生成器的用户界面。
首先,进入代码编辑器中的 /[root]/src/app 目录并创建一个名为 components 的文件夹。在 components 文件夹中,创建两个文件,分别名为 Header.tsx 和 CodeTutorial.tsx。
在 Header.tsx 文件中,添加以下代码,定义一个名为 Header 的函数式组件,它将渲染生成器的导航栏。
"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 文件中,添加以下代码,定义一个名为 CodeTutorial 的函数式组件,它渲染 UI 组件生成器主页,显示生成的 UI 组件、嵌入式代码编辑器和生成的实现教程。
"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>
</>
);
}
接下来,进入 /[root]/src/page.tsx 文件,添加以下代码,导入 CodeTutorial 和 Header 组件,并定义一个名为 Home 的函数式组件。
import React from "react";
import Header from "./components/Header";
import CodeTutorial from "./components/CodeTutorial";
export default function Home() {
return (
<>
<Header />
<CodeTutorial />
</>
);
}
接下来,删除 globals.css 文件中的 CSS 代码,并添加以下 CSS 代码。
@tailwind base;
@tailwind components;
@tailwind utilities;
@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;
}
最后,在命令行上运行命令 npm run dev,然后导航到 http://localhost:3000/。
现在你应该能在浏览器上看到 UI 组件生成器前端。
在本部分中,你将学习如何向 UI 组件生成器添加 AI copilot,使用 CopilotKit 生成 UI 组件代码和实现教程。
CopilotKit 提供前端和后端包。它们使你能够连接到 React 状态并使用 AI agents 在后端处理应用数据。
首先,让我们将 CopilotKit React 组件添加到博客前端。
在这里,我将引导你完成将 UI 组件生成器与 CopilotKit 前端集成的过程,以促进 UI 组件代码和实现教程生成。
首先,使用以下代码片段在 /[root]/src/app/components/CodeTutorial.tsx 文件的顶部导入 useMakeCopilotReadable 和 useCopilotAction 自定义 hooks。
import {
useCopilotAction,
useMakeCopilotReadable,
} from "@copilotkit/react-core";
在 CodeTutorial 函数内部,在状态变量下方,添加以下代码,使用 useMakeCopilotReadable hook 来添加将生成的代码作为应用内聊天机器人的上下文。该 hook 使代码对 copilot 可读。
useMakeCopilotReadable(codeToDisplay);
在上方代码下方,添加以下代码,使用 useCopilotAction hook 来设置一个名为 generateCodeAndImplementationTutorial 的 action,它将启用 UI 组件代码和实现教程的生成。
该 action 接受两个名为 code 和 tutorial 的参数,这些参数启用 UI 组件代码和实现教程的生成。
该 action 包含一个处理函数,该函数基于给定的 prompt 生成 UI 组件代码和实现教程。
在处理函数内部,codeToDisplay 状态使用新生成的代码进行更新,而 codeTutorial 状态使用新生成的教程进行更新,如下所示。
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]
);
在那之后,进入 /[root]/src/app/page.tsx 文件并在顶部使用下面的代码导入 CopilotKit 前端包和样式。
import { CopilotKit } from "@copilotkit/react-core";
import { CopilotSidebar } from "@copilotkit/react-ui";
import "@copilotkit/react-ui/styles.css";
然后使用 CopilotKit 来包装 CopilotSidebar 和 CodeTutorial 组件,如下所示。CopilotKit 组件指定 CopilotKit 后端端点的 URL (/api/copilotkit/),而 CopilotSidebar 渲染应用内聊天机器人,你可以向其提供 prompt 来生成 UI 组件代码和实现教程。
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>
</>
);
}
之后,运行开发服务器并导航到 http://localhost:3000。你应该看到应用内聊天机器人已集成到 UI 组件生成器中。
在这里,我将引导你完成将 UI 组件生成器与 CopilotKit 后端集成的过程,该后端处理来自前端的请求,并提供函数调用和各种 LLM 后端(如 GPT)。
同时,我们将集成一个名为 Tavily 的 AI agent,它可以在网上研究任何主题。
首先,在根目录中创建一个名为 .env.local 的文件。然后在文件中添加以下环境变量,其中包含你的 ChatGPT 和 Tavily Search API 密钥。
OPENAI_API_KEY="Your ChatGPT API key"
TAVILY_API_KEY="Your Tavily Search API key"
要获取 ChatGPT API 密钥,请导航到 https://platform.openai.com/api-keys。
要获取 Tavily Search API 密钥,请导航到 https://app.tavily.com/home。
在那之后,进入 /[root]/src/app 并创建一个名为 api 的文件夹。在 api 文件夹中,创建一个名为 copilotkit 的文件夹。
在 copilotkit 文件夹中,创建一个名为 research.ts 的文件。然后导航到这个 research.ts gist 文件,复制代码,并将其添加到 research.ts 文件中。
接下来,在 /[root]/src/app/api/copilotkit 文件夹中创建一个名为 route.ts 的文件。该文件将包含设置后端功能以处理 POST 请求的代码。它有条件地包含一个执行关于给定主题的研究的"research" action。
现在在文件顶部导入以下模块。
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.
在上方代码下方,定义一个运行时环境变量和一个名为 researchAction 的函数,使用以下代码研究某个主题。
// 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.
},
};
然后在上方代码下方添加以下代码,定义一个处理 POST 请求的异步函数。
// 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());
}
现在进入你之前集成的应用内聊天机器人,向它提供一个 prompt,例如"generate a contact form"。
生成完成后,你应该看到生成的联系表单组件及其实现教程。你还可以使用嵌入式代码编辑器修改生成的代码。
恭喜!你已完成本教程的项目。
CopilotKit 是一个令人难以置信的工具,使你能够在几分钟内向产品添加 AI Copilots。无论你是对 AI 聊天机器人和助手感兴趣,还是想自动化复杂任务,CopilotKit 都能让它变得简单。
如果你需要构建 AI 产品或将 AI 工具集成到软件应用中,你应该考虑 CopilotKit。
你可以在 GitHub 上找到本教程的源代码:https://github.com/TheGreatBonnie/AIPoweredUIComponentsGenerator