AI 驱动的前端 UI 组件生成器 (Next.js、GPT4、Langchain 和 CopilotKit)
TL;DR
在本文中,您将学习如何构建一个由 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 代理能够搜索网络并研究任何主题。
- OpenAI API - 提供 API 密钥,使您能够使用 ChatGPT 模型执行各种任务。
- Tavily AI—— 一种搜索引擎,使人工智能代理能够在应用程序内进行研究并访问实时知识。
- CopilotKit - 一个开源副驾驶框架,用于构建自定义 AI 聊天机器人、应用内 AI 代理和文本区域。
项目设置和包安装
首先,通过在终端中运行以下代码片段来创建 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 组件生成器前端
在本节中,我将引导您完成使用静态内容创建 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 组件生成器前端,如下所示。
使用 CopilotKit 将 AI 功能集成到组件生成器
在本节中,您将学习如何将 AI 副驾驶添加到 UI 组件生成器中,以使用 CopilotKit 生成 UI 组件代码和实现教程。
CopilotKit 提供前端和 后端 软件包。它们使您能够接入 React 状态并使用 AI 代理在后端处理应用程序数据。
首先,让我们将 CopilotKit React 组件添加到博客前端。
将 CopilotKit 添加到 UI 组件生成器前端
在这里,我将引导您完成 UI 组件生成器与 CopilotKit 前端集成的过程,以方便生成 UI 组件代码和实现教程。
首先,使用下面的代码片段 在文件顶部 导入useMakeCopilotReadable
、和 、自定义挂钩 。useCopilotAction
/[root]/src/app/components/CodeTutorial.tsx
import {
useCopilotAction,
useMakeCopilotReadable,
} from "@copilotkit/react-core";
在函数内部CodeTutorial
,在状态变量下方,添加以下代码,该代码使用 useMakeCopilotReadable
钩子添加将作为应用内聊天机器人上下文生成的代码。该钩子使副驾驶能够读取代码。
useMakeCopilotReadable(codeToDisplay);
在上面的代码下方,添加以下代码,使用 useCopilotAction
钩子设置一个名为的操作, generateCodeAndImplementationTutorial
这将启用 UI 组件代码和实现教程的生成。
该操作采用两个参数,称为 code
和 tutorial
,用于生成 UI 组件代码和实现教程。
该操作包含一个处理函数,该函数根据给定的提示生成 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
渲染应用内聊天机器人,您可以提示生成 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 组件生成器中。
将 CopilotKit 后端添加到 UI 组件生成器
在这里,我将引导您完成将 UI 组件生成器与 CopilotKit 后端集成的过程,该后端处理来自前端的请求,并提供函数调用和各种 LLM 后端(例如 GPT)。
此外,我们还将整合一个名为 Tavily 的人工智能代理,它可以在网络上研究任何主题。
首先,在根目录中创建一个名为 的文件 。然后在保存您的 搜索 API 密钥.env.local
的文件中添加以下环境变量 。ChatGPT
Tavily
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
文件中
route.ts
接下来,在文件夹中 创建一个名为的文件 /[root]/src/app/api/copilotkit
。该文件将包含设置后端功能以处理 POST 请求的代码。它有条件地包含一个“研究”操作,该操作针对给定主题执行研究。
现在在文件顶部导入以下模块。
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());
}
如何生成 UI 组件
现在转到您之前集成的应用内聊天机器人,并向其发出提示,例如“生成联系表单”。
生成完成后,您将看到生成的联系表单组件及其实现教程,如下所示。您还可以使用嵌入式代码编辑器修改生成的代码。
恭喜!您已完成本教程的项目。
结论
CopilotKit 是一款功能强大的工具,可让您在几分钟内将 AI Copilot 添加到您的产品中。无论您对 AI 聊天机器人和助手感兴趣,还是对复杂任务的自动化感兴趣,CopilotKit 都能让您轻松实现。
如果您需要构建 AI 产品或将 AI 工具集成到您的软件应用程序中,您应该考虑 CopilotKit。
您可以在 GitHub 上找到本教程的源代码:https://github.com/TheGreatBonnie/AIPoweredUIComponentsGenerator
文章来源:https://dev.to/crosspostr/ai-powered-frontend-ui-components-generator-nextjs-gpt4-langchain-copilotkit-1hac