نحوه ایجاد لیست کارهایی که مبتنی بر هوش مصنوعی هستند (Next.js، GPT4 و CopilotKit)

TL; DR
لیست کارها یک پروژه کلاسیک برای هر توسعه دهنده است. در دنیای امروز، یادگیری نحوه ساخت با هوش مصنوعی و داشتن چند پروژه هوش مصنوعی در مجموعه خود بسیار عالی است.
امروز، گام به گام نحوه ساختن لیست کارهایی را با کمک خلبان هوش مصنوعی تعبیه شده برای جادوی هوش مصنوعی شرح خواهم داد.
ما نحوه انجام موارد زیر را پوشش خواهیم داد:
- با استفاده از Next.js، TypeScript و Tailwind CSS، برنامه وب تولیدکننده لیست کارها را بسازید.
- از CopilotKit برای ادغام قابلیتهای هوش مصنوعی در تولیدکننده فهرست کارها استفاده کنید.
- از ربات چت هوش مصنوعی برای افزودن لیست ها، اختصاص لیست ها به شخصی، علامت گذاری لیست ها به عنوان تکمیل شده و حذف لیست ها استفاده کنید.
CopilotKit: چارچوبی برای ساختن کوپیلوت های هوش مصنوعی درون برنامه ای
CopilotKit یک چارچوب منبع باز AI Copilot است. ما ادغام هوش مصنوعی قدرتمند را در برنامه های React شما آسان می کنیم.
ساختن:
- ChatBot: چترباتهای درونبرنامهای آگاه از زمینه که میتوانند اقدامات درون برنامهای انجام دهند.
- CopilotTextArea: فیلدهای متنی مبتنی بر هوش مصنوعی با تکمیل خودکار و درجهای متنی 📝
- Co-Agents: عوامل هوش مصنوعی درون برنامه ای که می توانند با برنامه و کاربران شما تعامل داشته باشند.
Star CopilotKit ⭐️
پیش نیازها
برای درک کامل این آموزش، باید درک اولیه ای از React یا Next.js داشته باشید.
در اینجا ابزارهای مورد نیاز برای ساختن مولد لیست کارهای انجام شده با هوش مصنوعی وجود دارد:
-
Nanoid – یک تولید کننده شناسه رشته ای کوچک، ایمن، سازگار با URL و منحصر به فرد برای جاوا اسکریپت.
-
OpenAI API – یک کلید API را ارائه می دهد که به شما امکان می دهد وظایف مختلفی را با استفاده از مدل های ChatGPT انجام دهید.
-
CopilotKit – یک چارچوب منبع باز کمکی برای ساخت چت ربات های سفارشی هوش مصنوعی، عوامل هوش مصنوعی درون برنامه ای و مناطق متنی.
راه اندازی پروژه و نصب بسته
ابتدا با اجرای قطعه کد زیر در ترمینال خود، یک برنامه Next.js ایجاد کنید:
npx create-next-app@latest todolistgenerator
تنظیمات پیکربندی دلخواه خود را انتخاب کنید. برای این آموزش، از TypeScript و Next.js App Router استفاده خواهیم کرد.
در مرحله بعد پکیج Nanoid و وابستگی های آن را نصب کنید.
npm i nanoid
در نهایت بسته های CopilotKit را نصب کنید. این بستهها ما را قادر میسازند تا دادهها را از حالت React بازیابی کنیم و کوپایلوت هوش مصنوعی را به برنامه اضافه کنیم.
npm install @copilotkit/react-ui @copilotkit/react-textarea @copilotkit/react-core @copilotkit/backend @copilotkit/shared
تبریک می گویم! شما اکنون آماده ساختن یک تولید کننده لیست وظایف با هوش مصنوعی هستید.
ساخت جبهه تولید کننده لیست کارها
در این بخش، من شما را از طریق فرآیند ایجاد نمایه مولد لیست کارها با محتوای ثابت برای تعریف رابط کاربری مولد راهنمایی خواهم کرد.
برای شروع، به /[root]/src/app
در ویرایشگر کد خود پوشه ای به نام ایجاد کنید types
. در پوشه Type ها، فایلی به نام ایجاد کنید todo.ts
و کد زیر را اضافه کنید که یک رابط TypeScript به نام تعریف می کند Todo
.
این Todo
اینترفیس یک ساختار شی را تعریف می کند که در آن هر مورد باید دارای یک باشد id
، text
، و isCompleted
وضعیت، در حالی که ممکن است به صورت اختیاری دارای یک assignedTo
ویژگی.
export interface Todo {
id: string;
text: string;
isCompleted: boolean;
assignedTo?: string;
}
سپس برو به /[root]/src/app
در ویرایشگر کد خود و ایجاد یک پوشه به نام components
. در داخل پوشه کامپوننت، سه فایل با نام ایجاد کنید Header.tsx
، TodoList.tsx
و TodoItem.tsx
.
در Header.tsx
فایل، کد زیر را اضافه کنید که یک جزء کاربردی به نام را تعریف می کند Header
که نوار ناوبری ژنراتور را نمایش می دهد.
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="https://dev.to/"
aria-label="Brand">
To-Do List Generator
Link>
div>
nav>
header>
>
);
}
در TodoItem.tsx
کد زیر را اضافه کنید که یک جزء تابعی React به نام را تعریف می کند TodoItem
. از TypeScript برای اطمینان از ایمنی نوع و تعریف لوازمی که مؤلفه می پذیرد استفاده می کند.
import { Todo } from "../types/todo"; // Importing the Todo type from a types file
// Defining the interface for the props that the TodoItem component will receive
interface TodoItemProps {
todo: Todo; // A single todo item
toggleComplete: (id: string) => void; // Function to toggle the completion status of a todo
deleteTodo: (id: string) => void; // Function to delete a todo
assignPerson: (id: string, person: string | null) => void; // Function to assign a person to a todo
hasBorder?: boolean; // Optional prop to determine if the item should have a border
}
// Defining the TodoItem component as a functional component with the specified props
export const TodoItem: React.FC<TodoItemProps> = ({
todo,
toggleComplete,
deleteTodo,
assignPerson,
hasBorder,
}) => {
return (
<div
className={
"flex items-center justify-between px-4 py-2 group" +
(hasBorder ? " border-b" : "") // Conditionally adding a border class if hasBorder is true
}>
<div className="flex items-center">
<input
className="h-5 w-5 text-blue-500"
type="checkbox"
checked={todo.isCompleted} // Checkbox is checked if the todo is completed
onChange={() => toggleComplete(todo.id)} // Toggle completion status on change
/>
<span
className={`ml-2 text-sm text-white ${
todo.isCompleted ? "text-gray-500 line-through" : "text-gray-900" // Apply different styles if the todo is completed
}`}>
{todo.assignedTo && (
<span className="border rounded-md text-xs py-[2px] px-1 mr-2 border-purple-700 uppercase bg-purple-400 text-black font-medium">
{todo.assignedTo} {/* Display the assigned person's name if available */}
span>
)}
{todo.text} {/* Display the todo text */}
span>
div>
<div>
<button
onClick={() => deleteTodo(todo.id)} // Delete the todo on button click
className="text-red-500 opacity-0 group-hover:opacity-100 transition-opacity duration-200">
<svg
xmlns="http://www.w3.org/2000/svg"
fill="none"
viewBox="0 0 24 24"
strokeWidth={1.5}
stroke="currentColor"
className="w-5 h-5">
<path
strokeLinecap="round"
strokeLinejoin="round"
d="m14.74 9-.346 9m-4.788 0L9.26 9m9.968-3.21c.342.052.682.107 1.022.166m-1.022-.165L18.16 19.673a2.25 2.25 0 0 1-2.244 2.077H8.084a2.25 2.25 0 0 1-2.244-2.077L4.772 5.79m14.456 0a48.108 48.108 0 0 0-3.478-.397m-12 .562c.34-.059.68-.114 1.022-.165m0 0a48.11 48.11 0 0 1 3.478-.397m7.5 0v-.916c0-1.18-.91-2.164-2.09-2.201a51.964 51.964 0 0 0-3.32 0c-1.18.037-2.09 1.022-2.09 2.201v.916m7.5 0a48.667 48.667 0 0 0-7.5 0"
/>
svg>
button>
<button
onClick={() => {
const name = prompt("Assign person to this task:");
assignPerson(todo.id, name);
}}
className="ml-2 text-blue-500 opacity-0 group-hover:opacity-100 transition-opacity duration-200">
<svg
xmlns="http://www.w3.org/2000/svg"
fill="none"
viewBox="0 0 24 24"
strokeWidth={1.5}
stroke="currentColor"
className="w-5 h-5">
<path
strokeLinecap="round"
strokeLinejoin="round"
d="M18 7.5v3m0 0v3m0-3h3m-3 0h-3m-2.25-4.125a3.375 3.375 0 1 1-6.75 0 3.375 3.375 0 0 1 6.75 0ZM3 19.235v-.11a6.375 6.375 0 0 1 12.75 0v.109A12.318 12.318 0 0 1 9.374 21c-2.331 0-4.512-.645-6.374-1.766Z"
/>
svg>
button>
div>
div>
);
};
در TodoList.tsx
فایل، کد زیر را اضافه کنید که یک جزء تابعی React را با نام تعریف می کند TodoList
. این کامپوننت برای مدیریت و نمایش لیستی از موارد کار استفاده می شود.
"use client";
import { TodoItem } from "./TodoItem"; // Importing the TodoItem component
import { nanoid } from "nanoid"; // Importing the nanoid library for generating unique IDs
import { useState } from "react"; // Importing the useState hook from React
import { Todo } from "../types/todo"; // Importing the Todo type
// Defining the TodoList component as a functional component
export const TodoList: React.FC = () => {
// State to hold the list of todos
const [todos, setTodos] = useState<Todo[]>([]);
// State to hold the current input value
const [input, setInput] = useState("");
// Function to add a new todo
const addTodo = () => {
if (input.trim() !== "") {
// Check if the input is not empty
const newTodo: Todo = {
id: nanoid(), // Generate a unique ID for the new todo
text: input.trim(), // Trim the input text
isCompleted: false, // Set the initial completion status to false
};
setTodos([...todos, newTodo]); // Add the new todo to the list
setInput(""); // Clear the input field
}
};
// Function to handle key press events
const handleKeyPress = (e: React.KeyboardEvent) => {
if (e.key === "Enter") {
// Check if the Enter key was pressed
addTodo(); // Add the todo
}
};
// Function to toggle the completion status of a todo
const toggleComplete = (id: string) => {
setTodos(
todos.map((todo) =>
todo.id === id ? { ...todo, isCompleted: !todo.isCompleted } : todo
)
);
};
// Function to delete a todo
const deleteTodo = (id: string) => {
setTodos(todos.filter((todo) => todo.id !== id));
};
// Function to assign a person to a todo
const assignPerson = (id: string, person: string | null) => {
setTodos(
todos.map((todo) =>
todo.id === id
? { ...todo, assignedTo: person ? person : undefined }
: todo
)
);
};
return (
<div>
<div className="flex mb-4">
<input
className="border rounded-md p-2 flex-1 mr-2"
value={input}
onChange={(e) => setInput(e.target.value)}
onKeyDown={handleKeyPress} // Add this to handle the Enter key press
/>
<button
className="bg-blue-500 rounded-md p-2 text-white"
onClick={addTodo}>
Add Todo
button>
div>
{todos.length > 0 && ( // Check if there are any todos
<div className="border rounded-lg">
{todos.map((todo, index) => (
<TodoItem
key={todo.id} // Unique key for each todo item
todo={todo} // Pass the todo object as a prop
toggleComplete={toggleComplete} // Pass the toggleComplete function as a prop
deleteTodo={deleteTodo} // Pass the deleteTodo function as a prop
assignPerson={assignPerson} // Pass the assignPerson function as a prop
hasBorder={index !== todos.length - 1} // Conditionally add a border to all but the last item
/>
))}
div>
)}
div>
);
};
بعد، به /[root]/src/page.tsx
فایل، و کد زیر را که وارد می کند اضافه کنید TodoList
و Header
اجزاء و یک جزء کاربردی به نام تعریف می کند Home
.
import Header from "./components/Header";
import { TodoList } from "./components/TodoList";
export default function Home() {
return (
<>
<Header />
<div className="border rounded-md max-w-2xl mx-auto p-4 mt-4">
<h1 className="text-2xl text-white font-bold mb-4">
Create a to-do list
h1>
<TodoList />
div>
>
);
}
در مرحله بعد، کد CSS را حذف کنید globals.css
فایل و کد CSS زیر را اضافه کنید.
@tailwind base;
@tailwind components;
@tailwind utilities;
body {
height: 100vh;
background-color: rgb(16, 23, 42);
}
در نهایت دستور را اجرا کنید npm run dev
در خط فرمان و سپس به http://localhost:3000/ بروید.
اکنون باید نمایه مولد To-Do List را مانند شکل زیر در مرورگر خود مشاهده کنید.
ادغام عملکردهای هوش مصنوعی به ژنراتور فهرست کار با استفاده از CopilotKit
در این بخش، یاد خواهید گرفت که چگونه یک کوپایلوت هوش مصنوعی را به ژنراتور To-Do List اضافه کنید تا با استفاده از CopilotKit لیست تولید کنید.
CopilotKit هر دو بسته frontend و backend را ارائه می دهد. آنها شما را قادر می سازند تا به حالت های React متصل شوید و داده های برنامه را در backend با استفاده از عوامل هوش مصنوعی پردازش کنید.
ابتدا، اجازه دهید کامپوننت های CopilotKit React را به فرانت اند مولد لیست کارهای انجام شده اضافه کنیم.
افزودن CopilotKit به Frontend Generator List To-Do
در اینجا، من شما را از طریق فرآیند یکپارچه سازی مولد To-Do List با CopilotKit frontend برای تسهیل تولید لیست ها راهنمایی می کنم.
برای شروع، از قطعه کد زیر برای وارد کردن استفاده کنید useCopilotReadable
، و useCopilotAction
، قلاب های سفارشی در بالای /[root]/src/app/components/TodoList.tsx
فایل.
import { useCopilotAction, useCopilotReadable } from "@copilotkit/react-core";
درون TodoList
تابع، زیر متغیرهای حالت، کد زیر را اضافه کنید که از آن استفاده می کند useCopilotReadable
برای افزودن لیست کارهایی که به عنوان زمینه برای چت ربات درون برنامه ای ایجاد می شود، قلاب کنید. قلاب باعث میشود فهرستهای کارها برای خلبان قابل خواندن باشند.
useCopilotReadable({
description: "The user's todo list.",
value: todos,
});
در زیر کد بالا، کد زیر را اضافه کنید که از کد استفاده می کند useCopilotAction
قلاب برای تنظیم یک عمل به نام updateTodoList
که تولید لیست کارها را امکان پذیر می کند.
این عمل یک پارامتر به نام آیتم ها را می گیرد که تولید لیست های کار را امکان پذیر می کند و حاوی یک تابع کنترل کننده است که لیست های کار را بر اساس یک اعلان داده شده تولید می کند.
در داخل تابع هندلر، todos
وضعیت با لیست کارهای جدید ایجاد شده، همانطور که در زیر نشان داده شده است، به روز می شود.
// Define the "updateTodoList" action using the useCopilotAction function
useCopilotAction({
// Name of the action
name: "updateTodoList",
// Description of what the action does
description: "Update the users todo list",
// Define the parameters that the action accepts
parameters: [
{
// The name of the parameter
name: "items",
// The type of the parameter, an array of objects
type: "object[]",
// Description of the parameter
description: "The new and updated todo list items.",
// Define the attributes of each object in the items array
attributes: [
{
// The id of the todo item
name: "id",
type: "string",
description:
"The id of the todo item. When creating a new todo item, just make up a new id.",
},
{
// The text of the todo item
name: "text",
type: "string",
description: "The text of the todo item.",
},
{
// The completion status of the todo item
name: "isCompleted",
type: "boolean",
description: "The completion status of the todo item.",
},
{
// The person assigned to the todo item
name: "assignedTo",
type: "string",
description:
"The person assigned to the todo item. If you don't know, assign it to 'YOU'.",
// This attribute is required
required: true,
},
],
},
],
// Define the handler function that executes when the action is invoked
handler: ({ items }) => {
// Log the items to the console for debugging purposes
console.log(items);
// Create a copy of the existing todos array
const newTodos = [...todos];
// Iterate over each item in the items array
for (const item of items) {
// Find the index of the existing todo item with the same id
const existingItemIndex = newTodos.findIndex(
(todo) => todo.id === item.id
);
// If an existing item is found, update it
if (existingItemIndex !== -1) {
newTodos[existingItemIndex] = item;
}
// If no existing item is found, add the new item to the newTodos array
else {
newTodos.push(item);
}
}
// Update the state with the new todos array
setTodos(newTodos);
},
// Provide feedback or a message while the action is processing
render: "Updating the todo list...",
});
در زیر کد بالا، کد زیر را اضافه کنید که از کد استفاده می کند useCopilotAction
قلاب برای تنظیم یک عمل به نام deleteTodo
که به شما امکان می دهد یک مورد را حذف کنید.
این اکشن پارامتری به نام id را می گیرد که به شما امکان می دهد یک مورد todo را با شناسه حذف کنید و حاوی یک تابع کنترل کننده است که با فیلتر کردن آیتم todo حذف شده با شناسه داده شده، وضعیت todos را به روز می کند.
// Define the "deleteTodo" action using the useCopilotAction function
useCopilotAction({
// Name of the action
name: "deleteTodo",
// Description of what the action does
description: "Delete a todo item",
// Define the parameters that the action accepts
parameters: [
{
// The name of the parameter
name: "id",
// The type of the parameter, a string
type: "string",
// Description of the parameter
description: "The id of the todo item to delete.",
},
],
// Define the handler function that executes when the action is invoked
handler: ({ id }) => {
// Update the state by filtering out the todo item with the given id
setTodos(todos.filter((todo) => todo.id !== id));
},
// Provide feedback or a message while the action is processing
render: "Deleting a todo item...",
});
پس از آن، به /[root]/src/app/page.tsx
با استفاده از کد زیر، بستهها و سبکهای ظاهری CopilotKit را در بالا وارد کنید.
import { CopilotKit } from "@copilotkit/react-core";
import { CopilotPopup } from "@copilotkit/react-ui";
import "@copilotkit/react-ui/styles.css";
سپس استفاده کنید CopilotKit
برای پیچیدن CopilotPopup
و TodoList
اجزاء، همانطور که در زیر نشان داده شده است. این CopilotKit
مؤلفه URL را برای نقطه پایانی CopilotKit مشخص می کند (/api/copilotkit/
) در حالی که CopilotPopup
ربات چت درونبرنامهای را ارائه میکند که میتوانید برای تولید فهرستهای انجام کار به آن دستور بدهید.
export default function Home() {
return (
<>
<Header />
<div className="border rounded-md max-w-2xl mx-auto p-4 mt-4">
<h1 className="text-2xl text-white font-bold mb-4">
Create a to-do list
h1>
<CopilotKit runtimeUrl="/api/copilotkit">
<TodoList />
<CopilotPopup
instructions={
"Help the user manage a todo list. If the user provides a high level goal, " +
"break it down into a few specific tasks and add them to the list"
}
defaultOpen={true}
labels={{
title: "Todo List Copilot",
initial: "Hi you! 👋 I can help you manage your todo list.",
}}
clickOutsideToClose={false}
/>
CopilotKit>
div>
>
);
}
پس از آن، سرور توسعه را اجرا کنید و به http://localhost:3000 بروید. باید ببینید که چت ربات درون برنامه ای در تولیدکننده لیست کارها ادغام شده است.
اضافه کردن CopilotKit Backend به وبلاگ
در اینجا، من شما را از طریق فرآیند ادغام مولد لیستهای کار با باطن CopilotKit که درخواستهای فرانتاند را مدیریت میکند و فراخوانی تابع و پشتیبانهای مختلف LLM مانند GPT را ارائه میکند، راهنمایی میکنم.
برای شروع، یک فایل به نام ایجاد کنید .env.local
در دایرکتوری ریشه سپس متغیر محیطی زیر را در فایلی که شما را نگه می دارد اضافه کنید ChatGPT
کلیدهای API
OPENAI_API_KEY="Your ChatGPT API key”
برای دریافت کلید ChatGPT API، به https://platform.openai.com/api-keys بروید.
پس از آن، به /[root]/src/app
و یک پوشه به نام ایجاد کنید api
. در api
پوشه، پوشه ای به نام ایجاد کنید copilotkit
.
در copilotkit
پوشه، یک فایل به نام ایجاد کنید route.ts
که حاوی کدی است که یک عملکرد پشتیبان را برای پردازش درخواست های POST تنظیم می کند.
// Import the necessary modules from the "@copilotkit/backend" package
import { CopilotRuntime, OpenAIAdapter } from "@copilotkit/backend";
// Define an asynchronous function to handle POST requests
export async function POST(req: Request): Promise<Response> {
// Create a new instance of CopilotRuntime
const copilotKit = new CopilotRuntime({});
// Use the copilotKit to generate a response using the OpenAIAdapter
// Pass the incoming request (req) and a new instance of OpenAIAdapter to the response method
return copilotKit.response(req, new OpenAIAdapter());
}
نحوه ایجاد لیست Todo
اکنون به چت ربات درون برنامهای که قبلاً ادغام کردهاید بروید و به آن اعلان کنید: «میخواهم برای انجام یک تمرین کامل بدن به باشگاه بروم. برنامه تمرینی را که باید دنبال کنم به لیست اضافه کنم
همانطور که در زیر نشان داده شده است، پس از اتمام کار، باید لیستی از برنامه تمرینی تمام بدن را که باید دنبال کنید، مشاهده کنید.
میتوانید با دادن اعلان به چتبات، فهرست کارها را به شخصی اختصاص دهید، مانند «تخصیص فهرست کارها به Doe».
میتوانید با دادن اعلان به چتبات مانند «لیست کارها را بهعنوان تکمیلشده علامتگذاری کنید»، فهرست کارها را بهعنوان تکمیلشده علامتگذاری کنید.
میتوانید با دادن اعلان به چتبات مانند «لیست کارها را حذف کنید»، فهرست کارها را حذف کنید.
تبریک می گویم! شما پروژه این آموزش را تکمیل کرده اید.
نتیجه
CopilotKit ابزاری باورنکردنی است که به شما امکان می دهد ظرف چند دقیقه به محصولات خود AI Copilot اضافه کنید. چه به چت ربات ها و دستیاران هوش مصنوعی علاقه مند باشید و چه به خودکارسازی وظایف پیچیده، CopilotKit این کار را آسان می کند.
اگر نیاز به ساخت یک محصول هوش مصنوعی یا ادغام ابزار هوش مصنوعی در برنامه های نرم افزاری خود دارید، باید CopilotKit را در نظر بگیرید.
می توانید کد منبع این آموزش را در GitHub پیدا کنید: https://github.com/TheGreatBonnie/AIpoweredToDoListGenerator