嵌入到网页
在你的网页中加入 Agent Kit,让登录用户与服务智能体对话。本页用本地订单助手跑通授权码签发、前端挂载和身份隔离;其他形态见选择接入方式。
准备 Bun、一个可用的服务智能体及运行环境,以及同组织的 API Key。API Key 仅存为后端环境变量 PRAXIS_API_KEY。浏览器登录宿主后,由宿主核验身份、向 Praxis 申请一次性授权码,Kit 用它换取客户访问令牌并自行续期。
1. 准备智能体
在控制台进入服务智能体,选择已有智能体。在设置 → 指令保存指令;在接入 → 接入方式与外观 → 嵌入设置中打开允许 localhost(本地开发),点保存嵌入设置。本页宿主页为 http://localhost:4242,授权码绑定这个来源。请使用专用测试智能体;上线到 HTTPS 网站时,添加该网站的来源,并把授权码的 origin 改为它。
嵌入设置可在控制台或用 API 设置,见嵌入设置。复制公开智能体 ID(agent_…)备用,后端签发和前端 agent.id 都用它。页面显示“已保存,不产生新版本”后,继续实际签发;保存提示本身不能证明对话可用。
运行环境与凭据库跟随授权码固定的智能体版本:在配置中设置 environment_id 和 vault_ids,保存并生效后再签发新授权码。旧嵌入策略中的同名字段已弃用,不决定会话环境。
2. 创建授权码端点
新建目录,把代码保存为 server.ts。这是仅绑定本机的演示服务器,用 HTTP Basic 验证两个测试账户。DEMO_PASSWORD 是你自行设置的测试密码,与 Praxis API Key 无关。服务器从验证成功的账户取用户 ID,不读取浏览器提交的用户 ID。
import { timingSafeEqual } from "node:crypto";
const apiKey = process.env.PRAXIS_API_KEY;const agentId = process.env.PRAXIS_AGENT_ID;const password = process.env.DEMO_PASSWORD;if (!apiKey || !agentId || !password) throw new Error("Set the three server variables");const origin = "http://localhost:4242";const noStore = { "Cache-Control": "no-store" };function authenticate(request: Request): string | undefined { const supplied = Buffer.from(request.headers.get("Authorization") ?? ""); for (const id of ["customer_123", "customer_456"]) { const expected = Buffer.from("Basic " + Buffer.from(`${id}:${password}`).toString("base64")); if (supplied.length === expected.length && timingSafeEqual(supplied, expected)) return id; }}Bun.serve({ hostname: "127.0.0.1", port: 4242, async fetch(request) { const url = new URL(request.url); if (url.origin !== origin) return new Response("Use localhost:4242", { status: 403 }); const userId = authenticate(request); if (!userId) return new Response("Sign in", { status: 401, headers: { ...noStore, "WWW-Authenticate": 'Basic realm="Local demo"' }, }); if (request.method === "GET" && url.pathname === "/") { return new Response(Bun.file("index.html"), { headers: noStore }); } if (request.method !== "POST" || url.pathname !== "/api/praxis-grant-code") { return new Response("Not found", { status: 404 }); } if (request.headers.get("Origin") !== origin) { return new Response("Origin rejected", { status: 403 }); } try { const response = await fetch("https://api.deepraxis.com/customer/v1/grant_codes", { method: "POST", headers: { Authorization: `Bearer ${apiKey}`, "Content-Type": "application/json" }, body: JSON.stringify({ customer_id: userId, origin, resources: [`agent:${agentId}:chat`] }), signal: AbortSignal.timeout(30_000), }); if (!response.ok) return new Response("Grant code failed", { status: response.status, headers: noStore, }); const data = await response.json(); if (typeof data.code !== "string") throw new Error("Invalid grant code response"); return Response.json({ code: data.code }, { headers: noStore }); } catch { return new Response("Sign-in service unavailable", { status: 502, headers: noStore }); } },});console.log(origin);将三个环境变量放入服务端进程;PRAXIS_AGENT_ID 替换为实际 ID。启动前还需在下一步保存 index.html。
export PRAXIS_AGENT_ID="agent_REPLACE_ME"# Set PRAXIS_API_KEY and DEMO_PASSWORD in this server process, then run:bun server.ts期望:终端输出本地网址。未认证请求被宿主拒绝;已认证且同源的请求才会调用 Praxis。Praxis 签发成功返回 HTTP 201;宿主端点只返回一次性的 code,并禁止缓存。
接入已有应用时,将 authenticate 替换为应用的会话验证,把路由接在登录与 CSRF 保护之后,保留每次签发的身份核验。不要将本地测试账户机制用于线上登录。有效期、续期和匿名访客合并见客户登录。
3. 挂载组件
选择一种前端实现。API 地址、CDN 和智能体必须属于同一环境。示例从 /v1/ 加载 Kit,它始终指向当前发布的版本;要固定版本并做完整性校验,见安全。
保存为同目录的 index.html,然后运行上一步启动命令。
<!doctype html><html lang="zh"><meta charset="utf-8"><title>Order assistant</title><script type="module" src="https://cdn.deepraxis.com/v1/praxis-kit.js"></script><praxis-agent style="display:block;height:600px;width:100%"></praxis-agent><p id="status" role="status"></p><script type="module"> import { configure } from "https://cdn.deepraxis.com/v1/praxis-session.js"; await customElements.whenDefined("praxis-agent"); const agent = document.querySelector("praxis-agent"); agent.addEventListener("praxis.error", () => { document.querySelector("#status").textContent = "Chat unavailable. Check your sign-in and configuration."; }); // 授权码由你的后端为当前登录用户签发,不要写死。 const { code } = await (await fetch("/api/praxis-grant-code", { method: "POST", credentials: "same-origin", cache: "no-store", headers: { "Content-Type": "application/json" }, })).json(); configure({ api: { url: "https://api.deepraxis.com", grantCode: code } }); agent.setOptions({ agent: { id: "agent_REPLACE_ME", name: "Order assistant" } });</script></html>在已有 React 应用的 HTML 入口加入下面的模块脚本:先用 configure() 登录一次,再注册元素。将授权码路由接入应用后端,确保 /api/praxis-grant-code 与页面同源且受登录保护;React 页面无需由演示服务器提供。
<script type="module"> import { configure } from "https://cdn.deepraxis.com/v1/praxis-session.js"; // 授权码由你的后端为当前登录用户签发,不要写死。 const { code } = await (await fetch("/api/praxis-grant-code", { method: "POST", credentials: "same-origin", cache: "no-store", headers: { "Content-Type": "application/json" }, })).json(); configure({ api: { url: "https://api.deepraxis.com", grantCode: code } });</script><script type="module" src="https://cdn.deepraxis.com/v1/praxis-kit.js"></script>保存为 Support.jsx,在已登录的页面渲染 <Support />。组件使用 CDN 注册的 Web Component,并在卸载时移除它。
import { useEffect, useRef, useState } from "react";
export default function Support() { const container = useRef(null); const [error, setError] = useState(""); useEffect(() => { let cancelled = false; let agent; const onError = () => setError("Chat unavailable. Check your sign-in and configuration."); async function mount() { await customElements.whenDefined("praxis-agent"); if (cancelled) return; agent = document.createElement("praxis-agent"); agent.style.cssText = "display:block;height:600px;width:100%"; agent.addEventListener("praxis.error", onError); // 页面入口已用 configure() 登录一次,元素从这次登录取身份。 agent.setOptions({ agent: { id: "agent_REPLACE_ME", name: "Order assistant" } }); container.current.appendChild(agent); } mount().catch(onError); return () => { cancelled = true; agent?.removeEventListener("praxis.error", onError); agent?.remove(); }; }, []); return <><div ref={container} /><p role="status">{error}</p></>;}期望:页面出现高度为 600 像素的对话区。页面用 configure() 登录一次,grantCode 是宿主后端签发的一次性授权码,agent.id 是同一个公开 ID(替换 agent_REPLACE_ME),agent.name 是界面名称。页面会话自己换取、续期令牌;授权码只能用一次,需要重新登录时页面重新取码并 configure()。React 应用也可以安装 @deepraxis/kit-react,见组件参考。等待元素注册后再调用 setOptions。praxis.ready 只表示组件挂载;必须收到真实回复才能证明接入成功。
4. 验证接入
- 打开
http://localhost:4242,用customer_123和所设测试密码登录。发送“你好,请介绍你能帮助处理的订单问题”,确认收到回复。 - 在网络面板检查
/api/praxis-grant-code成功、响应只有code,随后POST /customer/v1/access_tokens返回 HTTP 201;会话请求使用客户访问令牌。不要把令牌复制到日志或截图。 - 用独立浏览器配置或无痕窗口登录
customer_456,期望看不到第一个账户的会话。不能用两个同登录态的标签页代替此检查。 - 不带凭据请求本地授权码端点,验证宿主返回 HTTP 401。已有应用还应验证退出登录后不能再签发,并在退出时调用
element.signOut()。
curl --silent --output /dev/null --write-out "%{http_code}\n" \ -X POST http://localhost:4242/api/praxis-grant-code \ -H "Origin: http://localhost:4242"失败时检查
以下是接口定义的失败分支,按网络面板中的实际响应检查:
- 签发 HTTP 400:确认已保存嵌入设置;
origin必须在允许来源中(本地需打开允许 localhost)。 - 签发 HTTP 404:确认 API Key 与服务智能体属于同组织,ID 已替换正确。
- 换取返回
GRANT_CODE_INVALID(HTTP 401):授权码只能用一次;确认页面重新取码并configure(),agent.id与授权码resources里的智能体相同。 - 换取或对话返回
ORIGIN_NOT_ALLOWED(HTTP 403):核对实际页面来源与授权码的origin一致。