# 组件参考 (/docs/developers/agent/embed/component-reference)



`<praxis-agent>` 在网页中呈现智能体对话。入口为 `element.setOptions(options)`；本页按属性、方法、事件排列，完整接入步骤见[嵌入到网页](/docs/developers/agent/embed/quickstart)。

## 初始化 [#initialize]

首次设置必须包含 `api.url`、`agent.name`，以及 `api.getToken` 或 `api.publishableKey`。缺少时抛出 `TypeError`。登录用户选择 `getToken`，匿名访客选择 `publishableKey`，请二选一；同时提供时使用 publishable key，不调用 `getToken`。

下面是 Develop 的匿名页面示例。先在该环境创建可公开 key、保存嵌入策略并允许宿主来源，再替换 `PRAXIS_PUBLISHABLE_KEY`，从该来源提供 HTML。公开 key 不是服务器 API Key。脚本地址、版本和完整性值须使用同一发布版本。

```html
<!doctype html>
<html lang="en">
<meta charset="utf-8">
<title>Course assistant</title>
<script type="module"
  src="https://kit-develop.praxisusercontent.com/v0.2.8/praxis-kit.js"
  integrity="sha384-vey+VZZcFIWJq9Fmv/nmLxspKtXRiL8XiDOfg2g2QFvwZi5MA+tkiQvPBtoMS8eU"
  crossorigin="anonymous"></script>
<praxis-agent style="display:block;height:600px;width:100%"></praxis-agent>
<p id="status" role="status"></p>
<script type="module">
  await customElements.whenDefined('praxis-agent');
  const agent = document.querySelector('praxis-agent');
  const status = document.querySelector('#status');
  agent.addEventListener('praxis.ready', () => { status.textContent = 'Interface mounted'; });
  agent.addEventListener('praxis.error', () => { status.textContent = 'Check the failed network request'; });
  agent.setOptions({
    api: {
      url: 'https://api-develop.deepraxis.com',
      publishableKey: 'PRAXIS_PUBLISHABLE_KEY',
    },
    agent: { name: 'Course assistant' },
    locale: 'en',
  });
</script>
</html>
```

**预期结果：** 页面显示聊天界面，发送问题后收到真实回复。`Interface mounted` 只表示挂载；验证还要检查回复和用户隔离。

## 属性 [#properties]

### api 与 agent [#api-agent]

| 属性                   | 类型                                                           | 语义                                                            |
| -------------------- | ------------------------------------------------------------ | ------------------------------------------------------------- |
| `api.url`            | `string`                                                     | 必填，API 源站或以 `/agent/v1` 结尾的基础地址；初始化后不可变                       |
| `api.getToken`       | `(current: string \| null) => Promise<string>`               | 返回嵌入令牌；首次 `current` 为 `null`，刷新时传当前令牌。后端每次重新确认宿主登录态           |
| `api.publishableKey` | `string`                                                     | 匿名令牌入口，替代 `getToken`；初始化后不可变。访客身份由组件保存的私有 `visitor_secret` 延续 |
| `agent.name`         | `string`                                                     | 必填，界面显示名称，不用于选择智能体                                            |
| `agent.avatar`       | `string`                                                     | 头像 URL；实际访问的智能体由凭证决定                                          |
| `onClientTool`       | `(call: { id, name, input }) => unknown \| Promise<unknown>` | 元素属性，不放入 `setOptions`。处理前端工具，未知工具应抛错                          |

### 布局与内容 [#layout-content]

| 属性                                | 类型 / 默认值                                        | 效果                                            |
| --------------------------------- | ----------------------------------------------- | --------------------------------------------- |
| `layout`                          | `inline`、`sidebar`、`popup`、`modal`；默认 `inline`  | 对话容器形态                                        |
| `width`                           | `number`；400 CSS 像素                             | sidebar 宽度                                    |
| `launcher.type`                   | `none`、`bubble`、`mascot`                        | 提供 launcher 时必填；默认 inline 为 none，其他布局为 bubble |
| `launcher.image`、`launcher.label` | `string`                                        | 启动按钮图片与文字                                     |
| `launcher.position`               | `bottom-right`、`bottom-left`                    | 启动按钮位置，默认右下                                   |
| `header.title`、`header.subtitle`  | `string`                                        | 标题与副标题；标题默认使用 `agent.name`                    |
| `header.icon`                     | `string`                                        | 支持的 Lucide 图标名或图片 URL                         |
| `header.actions`                  | `{ id: string; icon: string; label: string }[]` | 自定义顶栏按钮，点击发出事件                                |
| `history.enabled`                 | `boolean`；默认 `true`                             | 历史入口；关闭时 `showHistory()` 不生效                  |
| `startScreen.greeting`            | `string`                                        | 空会话问候语                                        |
| `startScreen.prompts`             | `{ label: string; prompt: string }[]`           | 显示前 4 个；点击发送对应 prompt                         |
| `composer.placeholder`            | `string`                                        | 默认随语言显示输入提示                                   |
| `composer.attachments.enabled`    | `boolean`；默认 `true`                             | 是否允许选择、粘贴或拖入附件                                |
| `disclaimer`、`footer`             | `string`                                        | 对话说明与底部文字                                     |
| `autoScroll`                      | `boolean`                                       | 新内容到达时是否自动滚动                                  |
| `locale`                          | `zh`、`en`                                       | 未指定时依次取宿主页面语言、浏览器语言；以 zh 开头用中文，否则英文；无语言信息用英文  |

### theme [#theme]

| 属性                 | 值 / 限制                                                     |
| ------------------ | ---------------------------------------------------------- |
| `colorScheme`      | `light`、`dark`、`system`；未设置时为浅色，system 跟随浏览器               |
| `accent`、`surface` | 明确且不透明的 CSS 颜色；拒绝 `var()`、`currentcolor`、透明色，抛 `TypeError` |
| `grayscale`        | `neutral`、`warm`、`cool`                                    |
| `radius`           | `none`、`sm`、`md`、`lg`、`full`；基础圆角依次为 0、4、10、18、9999 CSS 像素 |
| `density`          | `compact`、`normal`、`spacious`；基础间距依次为 3、4、5 CSS 像素         |
| `fontFamily`       | 非空字体族字符串，不能含 `; { } < >`，否则抛 `TypeError`                   |
| `fontSize`         | 正的有限数字，单位 CSS 像素；否则抛 `RangeError`                          |

未设置 accent 时，浅色默认 `#167A43`，深色默认 `#30a46c`。颜色前景按对比度选择。

### React 属性 [#react-props]

React 的 `PraxisAgent` 使用以下属性。&#x2A;*当前 React 绑定仍要求顶层 `getToken`**，即使 `options.api` 的类型包含 `publishableKey`；匿名接入可直接使用上面的 Web Component。

| 属性 / 返回对象                      | 语义                                                                          |
| ------------------------------ | --------------------------------------------------------------------------- |
| `getToken`                     | 必填，与 `api.getToken` 相同的函数签名                                                 |
| `options`                      | 上述选项，但不含 `api.getToken`；省略时呈现未配置元素                                          |
| `layout`、`launcher`            | 分别覆盖 `options.layout`、`options.launcher.type`；launcher 取 none/bubble/mascot |
| `className`、`style`、`children` | 宿主元素样式与 React 子元素                                                           |
| `onClientTool`                 | 前端工具回调；与元素属性同义                                                              |
| `ref` / `usePraxisAgent()`     | ref 提供控制句柄；hook 返回稳定的 `{ ref, control }`                                    |

## 方法 [#methods]

| 方法                              | 返回 / 行为                                                                                                     |
| ------------------------------- | ----------------------------------------------------------------------------------------------------------- |
| `setOptions(partial)`           | 初始化或合并选项                                                                                                    |
| `sendUserMessage(text)`         | `Promise<"accepted" \| "rejected" \| "unknown">`；空白、超长、等待审批或无法提交时可拒绝；accepted 不代表回复成功，unknown 时先检查会话，不要盲目重发 |
| `setComposerValue(text)`        | 替换草稿，不发送                                                                                                    |
| `focusComposer()`               | 聚焦输入框；历史面板打开时不生效                                                                                            |
| `setThreadId(id)`               | 切换会话并关闭历史；`null` 回到空会话，不切换用户身份                                                                              |
| `showHistory()`、`hideHistory()` | 打开、关闭历史面板                                                                                                   |
| `open()`、`close()`、`toggle()`   | 展开、收起或切换面板；inline 下无效果                                                                                      |
| `setReadable(name, value)`      | 注册页面上下文；名称 1–64 字符，仅字母、数字与 `_ . : -`；值为字符串或可 JSON 序列化值                                                      |
| `removeReadable(name)`          | 删除该页面上下文值                                                                                                   |

React 控制句柄包含上表从 `sendUserMessage` 到 `toggle` 的方法。`onReady` 前或卸载后调用会抛出未就绪错误，不会排队。React 页面上下文与工具用 `usePraxisReadable`、`usePraxisTool`，需要共享注册范围时使用 `PraxisProvider`，见下方指南。

## 事件 [#events]

事件均为可冒泡、可穿过 Shadow DOM 的 `CustomEvent`。React 回调收到同一个事件对象，通过 `event.detail` 读取内容。

| 事件 / React 回调                                                                   | detail 与时机                                                          |
| ------------------------------------------------------------------------------- | ------------------------------------------------------------------- |
| `praxis.ready` / `onReady`                                                      | 无；界面已挂载，不代表认证或网络成功                                                  |
| `praxis.error` / `onError`                                                      | `KitError`（code、status、retryable、message）或仅 `{ message }`；先检查字段是否存在 |
| `praxis.thread.change` / `onThreadChange`                                       | `{ threadId: string \| null }`；当前会话变化                               |
| `praxis.response.start` / `onResponseStart`                                     | 无；开始忙碌处理                                                            |
| `praxis.response.end` / `onResponseEnd`                                         | 无；结束忙碌处理，不是成功断言                                                     |
| `praxis.open`、`praxis.close` / `onOpen`、`onClose`                               | 无；面板展开、收起                                                           |
| `praxis.history.open`、`praxis.history.close` / `onHistoryOpen`、`onHistoryClose` | 无；历史面板打开、关闭                                                         |
| `praxis.header.action` / `onHeaderAction`                                       | `{ id: string }`；点击顶栏自定义按钮                                          |
| `praxis.tool.change` / `onToolChange`                                           | `{ id, name, status: "start" \| "end", isError? }`；前端工具执行变化         |
| `praxis.log` / `onLog`                                                          | `{ level: "info" \| "warn" \| "error", message, data? }`；上下文裁剪或工具诊断 |
| `praxis.frame.close`                                                            | 无；请求宿主关闭 iframe；React 无对应回调属性                                       |

## 默认行为与生命周期 [#defaults]

`setOptions` 递归合并对象、整体替换数组；显式 `undefined` 重置字段。`api.url` 和 `api.publishableKey` 初始化后不能改，变更会抛 `TypeError`；换后端或用户时销毁旧元素并重新创建。移除元素会释放连接与刷新计时器，不会撤销已签发令牌。

页面上下文快照最多 32 项、4096 UTF-8 字节，超出时从最早注册项开始省略并发出 log。Kit 的这些运行时选项与控制台保存的 iframe/Hosted 外观不是同一个配置入口，持久化外观有自己的字段与大小限制。

## 使用指南 [#guides]

[嵌入令牌与用户](/docs/developers/agent/embed/tokens) · [传入上下文](/docs/developers/agent/embed/context) · [接入前端工具](/docs/developers/agent/embed/client-tools) · [自定义外观](/docs/developers/agent/embed/appearance)
