使用 CopilotKit 将 Copilot 功能集成到您的 React 应用程序中

2025-06-07

使用 CopilotKit 将 Copilot 功能集成到您的 React 应用程序中

介绍

在不断发展的 Web 开发领域,提升用户体验至关重要。实现这一目标的一种创新方法是将 AI 副驾驶集成到您的应用程序中。受GitHub Copilot等工具的启发,这些工具可以通过实时建议代码片段和完整功能来帮助开发人员,AI 副驾驶可以显著简化应用程序内的用户交互。

什么是 AI Copilot?

AI 副驾驶在您的应用程序中充当智能助手,引导用户完成任务、提供建议,甚至自主执行操作。它们利用 AI 技术根据用户输入和上下文理解和预测需求。

CopilotKit 简介

CopilotKit 是一个专为 React 应用程序设计的开源 AI 平台。它为开发人员提供了将强大的 AI 功能无缝集成到其应用程序中所需的工具。

CopilotKit 的功能

CopilotKit 允许开发人员:

  • 嵌入上下文聊天功能: 通过回答查询和根据对话输入执行任务来直接吸引用户。
  • 实现行动驱动的协助: 允许副驾驶在网络环境内执行特定操作,增强互动性和效率。
  • 提供动态内容推荐: 通过分析用户输入,CopilotKit 可以推荐相关内容,通过满足个人需求和偏好显著改善用户体验。

通过将 CopilotKit 集成到您的 React 项目中,您不仅可以使您的应用程序更智能,还可以显著增强整体用户交互,使其更具吸引力和响应能力。

让我们深入了解如何集成 CopilotKit 并将您的 React 应用程序转变为更智能的平台。

先决条件

要完全理解本教程,您需要对 React 或 Next.js 有基本的了解。

您还需要创建 OpenAI API 密钥才能使用 ChatGPT 模型。目前,CopilotKit 仅支持 OpenAI API。我希望他们将来能够提供更多模型,为开发者提供更多灵活性和选择。

设置和包安装

首先,我们需要将这些依赖项安装到项目中

  • @copilotkit/react-core:CopilotKit 前端包带有反应钩子,用于向副驾驶提供应用程序状态和操作(AI 功能)
  • @copilotkit/react-ui:聊天机器人侧边栏 UI 的 CopilotKit 前端包
  • @copilotkit/react-textarea:CopilotKit 前端包,用于演示文稿演讲者笔记中的 AI 辅助文本编辑。
  • @copilotkit/backend:CopilotKit 后端包

安装这些软件包:

npm i @copilotkit/react-core @copilotkit/react-ui @copilotkit/react-textarea @copilotkit/backend
Enter fullscreen mode Exit fullscreen mode

示例:使用 CopilotKit 增强思维导图生成器

关于示例项目

我们将重点介绍一款思维导图构建器。这款工具支持用户创建思维导图,并允许他们在每个节点中添加和管理内容。通过集成 AI 辅助驾驶,我们旨在通过简化交互和提供智能内容建议来丰富用户体验。

这是应用程序主要流程的演示。

项目技术栈:

如果您想了解有关此技术栈的更多信息,可以查看我的模板项目:https://github.com/ngviethoang/next-shadcn-template

由于本文篇幅有限,我将把这个应用程序的具体实现留到另一篇文章中。如果你感兴趣的话,欢迎留言告诉我。

您可以在此处查看项目源代码:https://github.com/ngviethoang/MindmapCopilot

在接下来的章节中,我将指导您将 CopilotKit 的主要功能集成到项目中。这将包括如何在 Mindmap 应用程序中嵌入上下文聊天功能以及如何提供行动驱动的帮助。

副驾驶聊天机器人侧边栏

设置后端

该项目使用 NextJS App Router,您可以在此处查看更多信息。

添加文件src/app/api/copilotkit/openai/route.ts

import { CopilotBackend, OpenAIAdapter } from '@copilotkit/backend';

export const runtime = 'edge';

export async function POST(req: Request): Promise<Response> {
  const copilotKit = new CopilotBackend();

  return copilotKit.response(req, new OpenAIAdapter({ model: 'gpt-4-turbo' }));
}
Enter fullscreen mode Exit fullscreen mode

这里我用的是gpt-4-turbo最新型号,你也可以将其更改为其他型号。

要使用 ChatGPT 模型,我们当然需要添加 OpenAI API 密钥。让我们创建.env文件并输入您的密钥。

OPENAI_API_KEY=sk-<your-api-key>
Enter fullscreen mode Exit fullscreen mode

您可以在这里获取钥匙

设置前端

首先,让我们将CopilotKit组件包裹在文件中的布局组件外面src/app/layout.tsx

url这里的 propsCopilotKit我们上面设置的后端 URL。

要使用聊天机器人侧边栏组件,我们需要将CopilotSidebar组件添加到所需的页面中。这里我直接将其添加到布局组件中。

export default function RootLayout({
  children,
}: {
  children: React.ReactNode;
}) {
  return (
    <html lang="en">
      <body className={inter.className}>
        <ThemeProvider
          attribute="class"
          defaultTheme="system"
          enableSystem
          disableTransitionOnChange={false}
        >
          <CopilotKit url="/api/copilotkit/openai">
            <CopilotSidebar
              labels={{
                initial:
                  'Welcome to the Mindmap Copilot app! How can I help you?',
              }}
            >
              {children}
            </CopilotSidebar>
          </CopilotKit>
          <Analytics />
        </ThemeProvider>
      </body>
    </html>
  );
}
Enter fullscreen mode Exit fullscreen mode

初始标签是聊天机器人用来欢迎用户的第一条消息。您可以根据需要更改它。

为聊天机器人提供上下文

为了向聊天机器人提供有关应用程序的更多信息,我们使用了useMakeCopilotReadable钩子。

useCopilotReadable 是一个 React Hook,用于向 Copilot 提供应用状态和其他信息。此外,该 Hook 还可以处理应用中的层级状态,并将这些父子关系传递给 Copilot。

在这个项目中,我希望为聊天机器人提供用户正在创建的思维导图当前节点的上下文。这样,聊天机器人就能获得足够的信息来回答用户的问题并据此执行操作。

让我们将这个钩子添加到文件中的思维导图组件中src/components/mindmap/index.tsx

useMakeCopilotReadable(JSON.stringify(nodes));
Enter fullscreen mode Exit fullscreen mode

您还可以将钩子用于其他文档类型,例如 Google Docs。点击此处useMakeCopilotDocumentReadable阅读文档

演示:

副驾驶动作

useCopilotAction 是一个 React 钩子,可让您在 Copilot 聊天中集成可操作的函数。Copilot 可以调用这些操作来触发应用程序中的操作,从而实现由 Copilot 控制的交互式动态行为。

让我们以这个应用程序中的操作为例:副驾驶将在任何节点中自动添加用户要求的节点。

让我们将这个钩子添加到文件中的思维导图组件中src/components/mindmap/index.tsx

useCopilotAction({
  name: 'addNodes', // The name of the action
  description: 'Add some nodes to the mindmap', // A description of the action. This is used to instruct the Copilot on how to use the action.
  parameters: [
    {
      name: 'nodes', // The name of the parameter
      type: 'object[]', // The type of the argument.
      description: 'The nodes to add', // A description of the argument. This is used to instruct the Copilot on what this argument is used for.
      attributes: [  // define the attributes of the complex object
        {
          name: 'label',
          type: 'string',
          description: 'The name of the node',
        },
        {
          name: 'parentId',
          type: 'string',
          description: 'The id of the parent node based on provided nodes',
        },
      ],
    },
  ],
  handler: (props) => { // The handler of the action
    const { nodes } = props;
    addNodesFromCopilot(nodes);
  },
});
Enter fullscreen mode Exit fullscreen mode

对于handler函数,我们将nodesChatGPT 响应中的 props 传递给一个预定义函数。该函数addNodesFromCopilot是一个 Zustand 操作,用于将新节点添加到思维导图中的精确位置。

您可以使用此方法在您的应用中添加更多操作,让副驾驶决定道具和何时调用该功能。

演示:

副驾驶文本区域

最后,我们希望副驾驶能够将推荐内容添加到文本区域。为此,我们可以使用CopilotTextareaCopilotKit 中的组件。

在这个项目中,我创建了一个自定义组件,以便它可以在多个页面中重复使用。

检查这个文件src/components/common/custom-copilot-textarea.tsx

import { CopilotTextarea } from '@copilotkit/react-textarea';
import { useRef, useState } from 'react';
import { cn } from '@/lib/utils';

interface CustomCopilotTextareaProps {
  placeholder: string;
  textareaPurpose: string;
  maxTokens?: number;
  defaultValue?: string;
  debounceDuration?: number;
  onDebouncedUpdate?: (value: string) => void;
  className?: string;
}

export function CustomCopilotTextarea({
  placeholder,
  textareaPurpose,
  maxTokens,
  defaultValue,
  debounceDuration,
  onDebouncedUpdate,
  className,
}: CustomCopilotTextareaProps) {
  const [text, setText] = useState(defaultValue || '');

  // debounce the update
  let timeout = useRef<any>(null);

  const debouncedUpdate = (value: string) => {
    timeout.current && clearTimeout(timeout.current);
    timeout.current = setTimeout(() => {
      onDebouncedUpdate?.(value);
    }, debounceDuration || 750);
  };

  // update the value
  const handleValueChange = (value: string) => {
    setText(value);
    debouncedUpdate(value);
  };

  return (
    <CopilotTextarea
      className={cn('w-full h-full p-4 overflow-hidden', className)}
      value={text}
      onValueChange={handleValueChange}
      placeholder={placeholder}
      autosuggestionsConfig={{ // ChatGPT config
        textareaPurpose,
        chatApiConfigs: {
          suggestionsApiConfig: {
            forwardedParams: {
              max_tokens: maxTokens || 50,
              stop: ['.', '?', '!'],
            },
          },
        },
      }}
    />
  );
}
Enter fullscreen mode Exit fullscreen mode

在文件中src/components/mindmap/node-detail/index.tsx,我们添加这个组件。

<CustomCopilotTextarea
  placeholder="Enter content here..."
  textareaPurpose={getNodeContentPurpose}
  defaultValue={selectedNode.data.content || ''}
  onDebouncedUpdate={(val) => {
    setData(
      nodes.map((node) => {
        if (node.id === selectedNode.id) {
          return {
            ...node,
            data: {
              ...node.data,
              content: val,
            },
          };
        }
        return node;
      }),
      edges
    );
  }}
/>
Enter fullscreen mode Exit fullscreen mode

我们通过此函数为该 textarea 组件提供上下文。

const getNodeContentPurpose = useMemo(() => {
  if (!selectedNode) {
    return '';
  }
  const parents = [];
  let curNode = selectedNode;
  while (curNode) {
    const parent = nodes.find((n) => n.id === curNode.parentNode);
    if (!parent) {
      break;
    }
    parents.push(parent);
    curNode = parent;
  }
  const parentsString = parents.map((node) => node.data.label).join(', ');
  return `Content of the node: ${selectedNode?.data.label} (${parentsString})`;
}, [selectedNode, nodes]);
Enter fullscreen mode Exit fullscreen mode

演示:

CopilotKit 的附加功能

该示例项目未包含某些功能,但我建议您尝试一下,看看它是否适合您的需求。

结论

CopilotKit 是一款功能强大的工具,可让您在几分钟内将 AI Copilot 添加到您的产品中。无论您对 AI 聊天机器人和助手感兴趣,还是对复杂任务的自动化感兴趣,CopilotKit 都能让您轻松实现。

您可以在 GitHub 上找到本教程的源代码:https://github.com/ngviethoang/MindmapCopilot

感谢您的阅读:)

文章来源:https://dev.to/ngviethoang/integrate-copilot-feature-into-your-react-applications-using-copilotkit-2nga
PREV
改变你的 CSS 游戏:收藏这 10 个 CSS 生成器
NEXT
宣布 NgRx v17:介绍 NgRx 信号、操作符、性能改进、研讨会等!