如何使用Chainlit让所有网站快速嵌入一个AI聊天助手Copilot

ops/2024/10/18 5:46:01/

Copilot 副驾驶

Software 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.mountChainlitWidget({AINLIT.html" title=chainlit>chainlitServer: "http://localhost:8000",});</script>
</body>
  • 请记住,HTML 文件必须由服务器提供,直接在浏览器中打开它是行不通的。您可以使用简单的 HTTP 服务器进行测试。

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

小部件配置

mountChainlitWidget函数接受以下选项:

export interface IWidgetConfig {// URL of the Chainlit serverAINLIT.html" title=chainlit>chainlitServer: string;// Required if authentication is enabled on the serveraccessToken?: string;// Theme of the copilottheme?: "light" | "dark";// Font family to use. It is up to the website to load the fontfontFamily?: string;// Custom styling to apply to the widget buttonbutton?: {// ID of the container element to mount the button tocontainerId?: string;// URL of the image to use as the button iconimageUrl?: string;style?: {size?: string;bgcolor?: string;color?: string;bgcolorHover?: string;borderColor?: string;borderWidth?: string;borderStyle?: string;borderRadius?: string;boxShadow?: string;};};
}

函数调用

Copilot 可以调用您网站上的函数。这对于代表用户采取行动非常有用。例如,您可以调用函数来创建新文档或打开模式。

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

import AINLIT.html" title=chainlit>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("AINLIT.html" title=chainlit>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 AINLIT.html" title=chainlit>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 messagereturnfn = 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)

默认情况下,Chainlit 服务器接受来自任何来源的请求。这对于开发很有用,但不建议用于生产。

为了限制可以访问服务器的来源(从而嵌入副驾驶),请将 allow_origins配置字段设置为允许的来源列表。

[project]
# Whether to enable telemetry (default: true). No personal data is collected.
enable_telemetry = true# List of environment variables to be provided by each user to use the app.
user_env = []# Duration (in seconds) during which the session is saved when the connection is lost
session_timeout = 3600# Enable third parties caching (e.g LangChain cache)
cache = false# Follow symlink for asset mount (see https://github.com/Chainlit/AINLIT.html" title=chainlit>chainlit/issues/317)
# follow_symlink = false

验证

如果您想限制每个用户对 Copilot 的访问,您可以在 Chainlit 服务器上启用身份验证。

虽然独立的 Chainlit 应用程序会处理身份验证过程,但 Copilot 需要配置访问令牌。此令牌用于向 Chainlit 服务器验证用户身份。

主机应用/网站负责生成令牌并将其传递给 Copilot。以下是如何以不同语言生成令牌的示例:

您将需要配置身份验证CHAINLIT_AUTH_SECRET时生成的。

jwt.py

import jwt
from datetime import datetime, timedeltaCHAINLIT_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_jwtaccess_token = create_jwt("user-1", {"name": "John Doe"})

jwt.ts

import jwt from "jsonwebtoken";const CHAINLIT_AUTH_SECRET = "your-secret";interface Metadata {[key: string]: any;
}function createJwt(identifier: string, metadata: Metadata): string {const toEncode = {identifier: identifier,metadata: metadata,exp: Math.floor(Date.now() / 1000) + 60 * 60 * 24 * 15, // 15 days};const encodedJwt = jwt.sign(toEncode, CHAINLIT_AUTH_SECRET, {algorithm: "HS256",});return encodedJwt;
}const accessToken = createJwt("user-1", { name: "John Doe" });

示例

运行应用程序

要启动 ·Chainlit· 应用程序,请打开终端并导航到包含的目录·app.py·。然后运行以下命令:

 AINLIT.html" title=chainlit>chainlit run app.py -w   
  • -w标志告知 Chainlit 启用自动重新加载,因此您无需在每次更改应用程序时重新启动服务器。您的聊天机器人 UI 现在应该可以通过http://localhost:8000访问。
  • 自定义端口可以追加--port 80

网站html嵌入

以index.html为例,代码如下:

<!DOCTYPE html>
<html><head><meta charset="UTF-8" />
</head><body><h1>Chainlit Copilot Test</h1><script src="http://localhost:8000/copilot/index.js"></script><script>window.mountChainlitWidget({AINLIT.html" title=chainlit>chainlitServer: "http://localhost:8000",});window.addEventListener("AINLIT.html" title=chainlit>chainlit-call-fn", (e) => {const { name, args, callback } = e.detail;if (name === "test") {callback("You sent: " + args.msg);}});</script>
</body></html>

http://www.ppmy.cn/ops/112523.html

相关文章

aspcms webshell漏洞复现

ASPCMS是由上谷网络开发的全新内核的开源企业建站系统&#xff0c;能够胜任企业多种建站需求&#xff0c;并且支持模版自定义、支持扩展插件等等&#xff0c;能够在短时间内完成企业建站。 姿势一&#xff1a;后台修改配置文件拿Shell 步骤一&#xff1a;访问后台&#xff0c;…

海外问卷调查:选择静态IP还是动态IP?

在全球化的市场研究中&#xff0c;海外问卷调查是一种重要的数据收集手段。然而&#xff0c;选择合适的IP类型对于确保调查的效率、质量和合法性至关重要。本文将探讨在进行海外问卷调查时&#xff0c;静态IP与动态IP的优劣&#xff0c;并提供决策指导。 一、IP类型基础 在深入…

享元模式详解:解锁高效资源管理的终极武器

&#x1f3af; 设计模式专栏&#xff0c;持续更新中 欢迎订阅&#xff1a;JAVA实现设计模式 &#x1f6e0;️ 希望小伙伴们一键三连&#xff0c;有问题私信都会回复&#xff0c;或者在评论区直接发言 享元模式 享元模式&#xff08;Flyweight Pattern&#xff09; 是一种结构型…

OpenHarmony鸿蒙( Beta5.0)摄像头实践开发详解

鸿蒙开发往期必看&#xff1a; 一分钟了解”纯血版&#xff01;鸿蒙HarmonyOS Next应用开发&#xff01; “非常详细的” 鸿蒙HarmonyOS Next应用开发学习路线&#xff01;&#xff08;从零基础入门到精通&#xff09; “一杯冰美式的时间” 了解鸿蒙HarmonyOS Next应用开发路…

使用 PHPstudy 建立ThinkPHP8 本地集成环境

安装Composer 下载地址&#xff1a;https://getcomposer.org/Composer-Setup.exehttps://getcomposer.org/Composer-Setup.exe 打开PHPstudy创建网站&#xff1a; cmd终端进入PHPstudy www根目录下&#xff1a; 执行代码&#xff1a;cd phpstudy www 根目录地址 cd C:\phpst…

从底层原理上解释 clickhouse 保证完全的幂等性

在分布式系统中&#xff0c;幂等性是指某个操作被多次执行&#xff0c;其效果和结果应该和执行一次相同。ClickHouse作为一个高效的OLAP数据库&#xff0c;在其底层架构和查询引擎中&#xff0c;通过多个机制和策略来确保操作的幂等性。具体来说&#xff0c;ClickHouse的幂等性…

【嘉立创EDA】画PCB板中为什么要两面铺铜为GND,不能一面GND一面VCC吗?

在新手画板子铺铜时&#xff0c;经常会铺一面GND一面VCC。但一般情况下我们不会这样铺铜。下面将详细分析为什么要两面铺铜为GND&#xff0c;而不是一面GND一面VCC的原因&#xff1a; 提高散热能力 金属导热性&#xff1a;金属具有良好的导热性&#xff0c;铺铜可以有效分散PCB…

【计网】数据链路层:概述之位置|地位|链路|数据链路|帧

✨ Blog’s 主页: 白乐天_ξ( ✿&#xff1e;◡❛) &#x1f308; 个人Motto&#xff1a;他强任他强&#xff0c;清风拂山岗&#xff01; &#x1f4ab; 欢迎来到我的学习笔记&#xff01; ① ② ③ ④ ⑤ ⑥ ⑦ ⑧ ⑨ ⑩ 1. 在OSI体系结构中的位置 1. 位置&#xff1a;数…