如需完整的文件索引,請參閱 llms.txt。在文件頁面的網址末尾加上 .md ,即可取得該頁面的 Markdown 版本。
主要導覽
主題

ChatKit 中的動作

透過對話中的使用者互動,在伺服器上觸發動作。

即使使用者沒有送出訊息,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.title
  • Select(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 動作。

承載資料中的鍵名衝突

如果表單欄位名稱與承載資料中既有的預定義鍵同名,該欄位的值就會被忽略。這通常表示程式有誤,因此我們會在偵測到衝突時發出 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 → self
  • Select.onChangeAction → none
  • Card.confirm.action → container