软件 Copilot 是一种新型助手,内嵌在您的应用/产品中。它们旨在通过提供上下文指导并代表用户执行操作,帮助用户充分利用您的应用。

预览

联系我们,获取关于如何在您的产品中交付可靠、安全的 AI Copilot 或助手方面的建议。

支持的功能

消息流式传输元素音频询问用户聊天历史记录聊天配置文件反馈

嵌入 Copilot

首先,确保您的 Chainlit 服务器正在运行。然后,将以下脚本添加到您网站的 <body> 标签的末尾

此示例假设您的 Chainlit 服务器运行在 http://localhost:8000

<head>
  <meta charset="utf-8" />
</head>
<body>
  <!-- ... -->
  <script src="http://localhost:8000/copilot/index.js"></script>
  <script>
    window.addEventListener("chainlit-call-fn", (e) => {
      const { name, args, callback } = e.detail;
      callback("You sent: " + args.msg);
    });
  </script>
  <script>
    window.mountChainlitWidget({
      chainlitServer: "http://localhost:8000",
    });
  </script>
</body>

请记住,HTML 文件必须由服务器提供,直接在浏览器中打开它将不起作用。您可以使用简单的 HTTP 服务器进行测试。

就是这样!您现在应该会在您网站的右下角看到一个浮动按钮。单击它将打开 Copilot。

您可以使用 window.toggleChainlitCopilot() 以编程方式切换 copilot。

小部件配置

mountChainlitWidget 函数接受以下选项

export interface IWidgetConfig {
  // URL of the Chainlit server
  chainlitServer: string;
  // Required if authentication is enabled on the server
  accessToken?: string;
  // Theme of the copilot
  theme?: "light" | "dark";
  // Custom styling to apply to the widget button
  button?: {
    // ID of the container element to mount the button to
    containerId?: string;
    // URL of the image to use as the button icon
    imageUrl?: string;
    // The tailwind classname to apply to the button
    className?: string;
  };
}

函数调用

Copilot 可以在您的网站上调用函数。这对于代表用户执行操作非常有用。例如,您可以调用函数来创建新文档或打开模态框。

首先,在您的 Chainlit 服务器中创建一个 CopilotFunction

import chainlit as cl


@cl.on_message
async def on_message(msg: cl.Message):
    if cl.context.session.client_type == "copilot":
        fn = cl.CopilotFunction(name="test", args={"msg": msg.content})
        res = await fn.acall()
        await cl.Message(content=res).send()

然后,在您的应用/网站中,添加以下事件监听器

window.addEventListener("chainlit-call-fn", (e) => {
  const { name, args, callback } = e.detail;
  if (name === "test") {
    console.log(name, args);
    callback("You sent: " + args.msg);
  }
});

如您所见,事件监听器接收函数名称、参数和一个回调函数。应使用函数调用的结果调用回调函数。

发送消息

Copilot 还可以直接向 Chainlit 服务器发送消息。这对于向 Chainlit 服务器发送上下文信息或用户操作(例如用户在表格中从单元格 A1 选中到 B1)非常有用。

首先,将带有 @cl.on_message 装饰器的函数更新到您的 Chainlit 服务器中

import chainlit as cl


@cl.on_message
async def on_message(msg: cl.Message):
    if cl.context.session.client_type == "copilot":

        if msg.type == "system_message":
          # do something with the message
          return

        fn = cl.CopilotFunction(name="test", args={"msg": msg.content})
        res = await fn.acall()
        await cl.Message(content=res).send()

然后,在您的应用/网站中,您可以像这样触发一个事件

window.sendChainlitMessage({
  type: "system_message",
  output: "Hello World!",
});

安全性

跨域资源共享 (CORS)

不要忘记将主站点的来源添加到 allow_origins 配置字段中,作为允许来源列表的一部分。

认证

如果您想在 Copilot 上认证用户,可以在 Chainlit 服务器上启用认证

如果 Chainlit 应用和主站部署在不同的域上,您需要将 CHAINLIT_COOKIE_SAMESITE=none 添加到 Chainlit 应用的环境变量中。

虽然独立的 Chainlit 应用处理认证过程,但 Copilot 需要使用访问令牌进行配置。此令牌用于向 Chainlit 服务器认证用户。

主应用/网站负责生成令牌并将其作为 accessToken 传递。以下是在不同语言中生成令牌的示例

您将需要配置认证时生成的 CHAINLIT_AUTH_SECRET

import jwt
from datetime import datetime, timedelta

CHAINLIT_AUTH_SECRET = "your-secret"

def create_jwt(identifier: str, metadata: dict) -> str:
    to_encode = {
      "identifier": identifier,
      "metadata": metadata,
      "exp": datetime.utcnow() + timedelta(minutes=60 * 24 * 15),  # 15 days
      }

    encoded_jwt = jwt.encode(to_encode, CHAINLIT_AUTH_SECRET, algorithm="HS256")
    return encoded_jwt

access_token = create_jwt("user-1", {"name": "John Doe"})