useGenerativeUIFunction
Run your own code when a generated component calls a declared function, such as add to cart
Open your coding agent in your project's folder, or in an empty folder for a new app.This runs in a coding agent on your computer.
Overview
A user clicks "Add to cart" on a generated ProductCard. That click must add to the cart, with no message to the agent. useGenerativeUIFunction mounts the handler of a function that you declare in createGenerativeUI({ functions }). When generated UI calls the function, your handler runs.
Generative UI is experimental. Call useGenerativeUIFunction in setup()
(or <script setup>) of a component under a
CopilotKitProvider that has
a generativeUI config. Outside such a provider, the composable throws an
error.
For a full walkthrough, see State and actions.
Import
import { useGenerativeUIFunction } from "@copilotkit/vue/v2/generative-ui";Signature
import type { GenerativeUIFunctionArgs } from "@copilotkit/vue/v2/generative-ui";
useGenerativeUIFunction<UI, Name>(
ui: UI,
name: Name,
handler: (args: GenerativeUIFunctionArgs<UI, Name>) => unknown,
): void;Parameters
Prop
Type
Prop
Type
Prop
Type
Return value
None. The handler stays mounted until the effect scope is disposed.
Example
shopUI declares the function:
export const shopUI = createGenerativeUI({
id: "acme/shop@1",
functions: {
addToCart: {
description: "Add a product to the cart",
parameters: z.object({ productId: z.string(), quantity: z.number().default(1) }),
},
},
components: {
/* ... */
},
});Mount the handler from a component:
<script setup lang="ts">
import { useGenerativeUIFunction } from "@copilotkit/vue/v2/generative-ui";
import { useCartStore } from "./cart-store";
import { shopUI } from "./shop-ui";
const cart = useCartStore();
useGenerativeUIFunction(shopUI, "addToCart", ({ productId, quantity }) => {
cart.addItem(productId, quantity);
return { added: productId };
});
</script>
<template>
<slot />
</template>Behavior
- Generated UI can call the function only while exactly one handler for it is mounted. Mount one handler for each function.
- The handler is registered once. It reads refs, props, and stores when it runs, so it sees their current values.
- The handler is unregistered when the effect scope is disposed, for example when the component unmounts.
- Failures go to
errorBoundary.onErrorof the provider'sgenerativeUIconfig.
Related
useGenerativeUIState- give generated components live app stateGenerativeUISurface- mark an area of your page for generated UICopilotKitProvider- give the provider thegenerativeUIconfig