借助操作,ChatKit SDK 前端可以触发流式响应,无需用户提交消息。操作也可以触发 ChatKit SDK 之外的副作用。
触发操作
响应用户与小组件的交互
您可以将 ActionConfig 绑定到任何支持它的小组件节点,以便通过该节点触发操作。例如,您可以响应按钮的点击事件。用户点击按钮时,前端会将操作发送到您的服务器。您可以在服务器上更新小组件、运行推理或以流式方式发送新的会话条目等。
button = Button(
label="Example",
onClickAction=ActionConfig(
type="example",
payload={"id": 123},
),
)您的前端也可以直接调用 sendCustomAction() 发送操作。当您需要让 ChatKit 响应发生在 ChatKit 之外的交互时,这种方式尤其有用。如果客户端和服务器都需要作出响应,您也可以用这种方式串联多个操作(详见下文)。
await chatKit.sendCustomAction({
type: "example",
payload: { id: 123 },
});处理操作
在服务器端处理
默认情况下,前端会将操作发送到您的服务器。要在服务器端处理操作,请实现 action 方法,该方法属于 ChatKitServer。
class MyChatKitServer(ChatKitServer[RequestContext]):
async def action(
self,
thread: ThreadMetadata,
action: Action[str, Any],
sender: WidgetItem | None,
context: RequestContext,
) -> AsyncIterator[Event]:
if action.type == "example":
await do_thing(action.payload["id"])
# Often you'll want to add a HiddenContextItem so the model
# can see that the user did something.
await self.store.add_thread_item(
thread.id,
HiddenContextItem(
id=self.store.generate_item_id("message", thread, context),
thread_id=thread.id,
created_at=datetime.now(),
content="<USER_ACTION>The user did a thing</USER_ACTION>",
),
context,
)
# Then you might want to run inference to stream a response
# back to the user.
async for event in self.generate(context, thread):
yield event操作及其载荷由客户端发送到您的服务器,因此请将两者都视为不可信数据。
在客户端处理
有时,您可能希望在客户端集成代码中处理操作。为此,请将 handler="client" 添加到 ActionConfig,指定由客户端的操作处理程序接收该操作。
button = Button(
label="Example",
onClickAction=ActionConfig(type="example", payload={"id": 123}, handler="client"),
)这样,操作触发时,ChatKit 就会将其传给您在实例化 ChatKit 时提供的回调函数。
async function handleWidgetAction(action: { type: string }) {
if (action.type === "example") {
const res = await doSomething(action);
// You can fire off actions to your server from here as well.
// For example, stream new thread items or update a widget.
await chatKit.sendCustomAction({
type: "example_complete",
payload: res,
});
}
}
chatKit.setOptions({
// Other options...
widgets: { onAction: handleWidgetAction },
});强类型操作
默认情况下,Action 和 ActionConfig 都不是强类型。不过,您可以使用 create 辅助方法,它由 Action 提供,可根据一组强类型操作生成相应的 ActionConfig。
class ExamplePayload(BaseModel):
id: int
ExampleAction = Action[Literal["example"], ExamplePayload]
OtherAction = Action[Literal["other"], None]
AppAction = Annotated[
ExampleAction | OtherAction,
Field(discriminator="type"),
]
ActionAdapter: TypeAdapter[AppAction] = TypeAdapter(AppAction)
def parse_app_action(action: Action[str, Any]) -> AppAction:
return ActionAdapter.validate_python(action)
# Usage in a widget
# Action provides a create helper which makes it easy to generate
# ActionConfigs from strongly typed actions.
button = Button(
label="Example",
onClickAction=ExampleAction.create(ExamplePayload(id=123)),
)
# usage in action handler
class MyChatKitServer(ChatKitServer[RequestContext]):
async def action(
self,
thread: ThreadMetadata,
action: Action[str, Any],
sender: WidgetItem | None,
context: RequestContext,
) -> AsyncIterator[Event]:
# add custom error handling if needed
app_action = parse_app_action(action)
if app_action.type == "example":
await do_thing(app_action.payload.id)
yield ThreadItemDoneEvent(
item=AssistantMessageItem(
id=self.store.generate_item_id("message", thread, context),
thread_id=thread.id,
created_at=datetime.now(),
content=[AssistantMessageContent(text="Action complete.")],
)
)使用小组件和操作创建自定义表单
如果将接收用户输入的小组件节点挂载到 Form 中,这些字段的值就会包含在 payload 中。这适用于从该 Form 内部触发的所有操作。
表单值存储在 payload 中,以字段的 name 为键。例如:
Select(name="title")→action.payload.titleSelect(name="todo.title")→action.payload.todo.title
form = Form(
direction="col",
onSubmitAction=ActionConfig(
type="update_todo",
payload={"id": todo.id},
),
children=[
Title(value="Edit Todo"),
Text(value="Title", color="secondary", size="sm"),
Text(
value=todo.title,
editable=EditableProps(name="title", required=True),
),
Text(value="Description", color="secondary", size="sm"),
Text(
value=todo.description,
editable=EditableProps(name="description"),
),
Button(label="Save", submit=True),
],
)
class MyChatKitServer(ChatKitServer[RequestContext]):
async def action(
self,
thread: ThreadMetadata,
action: Action[str, Any],
sender: WidgetItem | None,
context: RequestContext,
) -> AsyncIterator[Event]:
if action.type == "update_todo":
todo_id = action.payload["id"]
# Any action that originates from within the Form will
# include title and description.
title = action.payload["title"]
description = action.payload["description"]
await update_todo(todo_id, title, description)
yield ThreadItemDoneEvent(
item=AssistantMessageItem(
id=self.store.generate_item_id("message", thread, context),
thread_id=thread.id,
created_at=datetime.now(),
content=[AssistantMessageContent(text="Todo updated.")],
)
)验证
Form 使用基本的原生表单验证,会对配置了 required 或 pattern 的字段执行相应检查。只要有一个字段未通过验证,表单就无法提交。
未来我们可能会添加新的验证模式,改善用户体验,支持更灵活的验证规则和自定义错误展示等。在此之前,对于验证逻辑复杂的表单,小组件并不理想。如果您有这类需求,更合适的做法是通过客户端操作处理程序打开模态对话框,在其中显示自定义表单,然后使用 sendAction 将结果传回 ChatKit。
将 Card 用作 Form
您可以将 asForm=True 传给 Card,使其像 Form 一样执行验证,并将收集到的字段值传给卡片的 confirm 操作。
载荷中的键名冲突
如果表单字段名与载荷中已有的预定义键同名,该字段的值会被忽略。这种冲突很可能意味着程序有误,因此 ChatKit 会在检测到冲突时发出 error 事件。
控制小组件中的加载状态
使用 ActionConfig.loadingBehavior 可以控制操作如何在小组件中触发不同的加载状态。
button = Button(
label="This may take a while...",
onClickAction=ActionConfig(
type="long_running_action_that_should_block_other_ui_interactions",
loadingBehavior="container",
),
)| 值 | 行为 |
|---|---|
auto |
根据操作的使用方式自动决定加载行为。(默认值) |
self |
使绑定了该操作的小组件节点进入加载状态。 |
container |
使整个小组件容器进入加载状态。小组件会略微变淡,用户此时无法与其交互。 |
none |
不触发加载状态。 |
使用 auto 行为
通常建议使用默认值 auto。auto 会根据操作的绑定位置决定加载行为,例如:
Button.onClickAction→selfSelect.onChangeAction→noneCard.confirm.action→container