用 Form Artifact 收集结构化输入
收集”新建项目” / “用户偏好”等结构化数据用 Form Artifact 比”问一个填一个” 高效得多。
前提
- 同 发送文本
代码
import { HasheeAgent } from "@hasheeai/agent-sdk-ts";import { ulid } from "ulid";
const agent = await HasheeAgent.init({ agentId: process.env.HASHEE_AGENT_ID!, token: process.env.HASHEE_AGENT_TOKEN!, baseUrl: "https://api.hashee.ai", connectionMode: "websocket",});
// 用户 "/new project" 触发表单agent.addMessageHandler(async (msg) => { if (msg.payload?.type !== "text") return; if (msg.payload.text.trim() !== "/new project") return;
await agent.sendArtifact(msg.conversation_id, { artifact: { artifact_id: ulid(), subtype: "form", title: "新建项目", payload: { fields: [ { id: "name", type: "text", label: "项目名", required: true }, { id: "description", type: "textarea", label: "一句话描述" }, { id: "visibility", type: "radio", label: "可见性", options: [{ id: "public", label: "公开" }, { id: "private", label: "私有" }], default: "private", }, { id: "private_enabled", type: "checkbox", label: "启用私密评论", default: false }, ], submit_label: "创建", cancel_label: "取消", }, }, });});
// 收 form submitagent.addEventHandler(async (event) => { if (event.type !== "artifact_response") return; if (event.payload.action !== "submit") return;
const { name, description, visibility, private_enabled } = event.payload.payload;
console.log("项目创建:", { name, description, visibility, private_enabled });
// 业务处理(创建项目 / 入库 / 等) await agent.send(event.payload.conversation_id, { type: "text", text: `✓ 已创建项目 **${name}**(${visibility})`, });});
// 取消agent.addEventHandler(async (event) => { if (event.type !== "artifact_response") return; if (event.payload.action !== "cancel") return; await agent.send(event.payload.conversation_id, { type: "text", text: "已取消。", });});
console.log("[form-bot] up");表单字段类型
| type | 说明 |
|---|---|
text | 单行文本 |
textarea | 多行文本 |
number | 数字 |
date | 日期 |
radio | 单选(带 options) |
checkbox | 布尔 / 多选 |
select | 下拉 |
详见 Artifact 入门。
进阶
- Artifact 高级 — artifact_update
- 团队投票卡 — 更复杂的状态化 form