Skip to content
中文

Embed in a web page

Add Agent Kit to your page so signed-in users can talk to a service agent. This local order-assistant example covers grant code issuance, mounting, and user isolation. For other interfaces, see Choose an integration.

You need Bun, an available service agent and runtime environment, and an API key in the same organization. Store PRAXIS_API_KEY only in the backend environment. The browser authenticates with your host; your host verifies identity and asks Praxis for a one-time grant code; Kit exchanges it for a customer access token and renews that token itself.

1. Prepare your agent

In the Dashboard, open 服务智能体 (Service agents) and select an existing agent. Save its instructions under 设置 → 指令. Under 接入 → 接入方式与外观 → 嵌入设置, enable 允许 localhost(本地开发), and click 保存嵌入设置. The example runs at http://localhost:4242, and each grant code is bound to that origin. Use a dedicated test agent. When moving to HTTPS hosting, add your website’s origin and set the grant code origin to it.

Embed settings can be configured in the Dashboard or through the API; see embed settings. Copy the public agent ID (agent_…); both the backend and the page’s agent.id use it. After the saved confirmation appears, continue with actual issuance; saving settings alone does not prove that chat works.

Runtime environment and vaults come from the agent version pinned by the grant code. Set environment_id and vault_ids in the agent configuration, save and apply it, then issue a new grant code. The old embed-policy fields are deprecated and do not choose the session environment.

2. Create a grant code endpoint

Create a directory and save this as server.ts. This loopback-only demo uses HTTP Basic authentication for two test accounts. Set your own test password in DEMO_PASSWORD; it is unrelated to your Praxis API key. The server derives the user ID from the authenticated account and ignores any client-supplied user 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);

Set the three variables in the server process. Replace PRAXIS_AGENT_ID with the actual ID. Save index.html in the next step before starting.

终端窗口
export PRAXIS_AGENT_ID="agent_REPLACE_ME"
# Set PRAXIS_API_KEY and DEMO_PASSWORD in this server process, then run:
bun server.ts

Expected: the terminal prints the local URL. The host rejects unauthenticated requests. Only authenticated, same-origin requests reach Praxis. Praxis returns HTTP 201 on issuance; the host returns only the one-time code, with caching disabled.

For an existing application, replace authenticate with its session validation. Mount the route behind login and CSRF protection, and recheck identity on every issuance. Do not use these test accounts as your production login system. See Customer sign-in for lifetimes, renewal, and merging anonymous visitors.

3. Mount the component

Choose one frontend implementation. The API address, CDN, and agent must use the same environment. The examples load Kit from /v1/, which always points to the current release; to pin a version and verify integrity, see Security.

Save this as index.html in the same directory, then run the startup command above.

<!doctype html>
<html lang="en">
<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.";
});
// The code comes from your backend for the signed-in user; never hard-code it.
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>

Expected: a chat area appears with a height of 600 pixels. The page signs in once with configure(), grantCode is a one-time grant code from your backend, agent.id is the same public ID (replace agent_REPLACE_ME), and agent.name sets the display name. The page session exchanges and renews the token itself; a code works once, so on a needed sign-in the page takes a new code and calls configure() again. React applications can also install @deepraxis/kit-react; see the component reference. Wait for registration before calling setOptions. The praxis.ready event only confirms mounting. A real reply is required to verify the integration.

4. Verify the integration

  1. Open http://localhost:4242. Sign in as customer_123 using your test password. Ask what order questions the assistant can help with and confirm a reply arrives.
  2. In the network panel, check that /api/praxis-grant-code succeeds and returns only code, then that POST /customer/v1/access_tokens returns HTTP 201. Session requests use the customer access token. Do not copy credentials into logs or screenshots.
  3. In a separate browser profile or private window, sign in as customer_456. Expect no access to the first account’s conversations. Two tabs sharing one login do not test isolation.
  4. Request the local grant code endpoint without credentials. Expect HTTP 401 from the host. In your application, also verify that signing out prevents further issuance, and call element.signOut() on sign-out.
终端窗口
curl --silent --output /dev/null --write-out "%{http_code}\n" \
-X POST http://localhost:4242/api/praxis-grant-code \
-H "Origin: http://localhost:4242"

Troubleshoot failures

These are defined API failure cases. Check the actual response in your network panel:

  • Issuance HTTP 400: confirm that the embed settings are saved; origin must be an allowed origin (enable localhost for local testing).
  • Issuance HTTP 404: check the agent ID and confirm the API key and service agent belong to the same organization.
  • The exchange returns GRANT_CODE_INVALID (HTTP 401): a code works once; make sure the page takes a new code and calls configure() again, and that agent.id matches the agent in the grant code resources.
  • The exchange or chat returns ORIGIN_NOT_ALLOWED (HTTP 403): check that the page origin matches the grant code origin.

Next steps