# KendoReact Grid AI Chat Assistant

The KendoReact Grid can be enhanced with an AI-powered chat assistant that allows users to interact with Grid data using natural language commands.

By integrating the [Chat](https://www.telerik.com/kendo-react-ui-develop/components/conversationalui/chat) component with the Grid's built-in AI features, you can create an intuitive conversational interface where users can perform all [supported Smart Grid operations](https://www.telerik.com/kendo-react-ui-develop/components/grid/smart#supported-operations) through simple text commands instead of navigating through multiple UI controls.

> The demo in this article uses a Telerik-hosted AI service for demonstration purposes only. For production applications, you should implement your own AI service that understands your specific domain, data, and business requirements.

The following example demonstrates how to implement an AI Chat Assistant that enables users to manage Grid data through natural language commands. Click the **AI Grid** button in the Grid toolbar to open the Chat panel and try inserting a prompt to interact with the data.

[Demo Source](https://demos.telerik.com/kendo-react-ui/grid/smart/ai-chat-assistant/source.txt)

## Implementation Steps

To implement an AI Chat Assistant for your Grid, follow the steps below:

1. Configure the Grid with the features you want to make available through AI commands. Enable [`sortable`](https://www.telerik.com/kendo-react-ui-develop/components/grid/api/gridprops#sortable), [`groupable`](https://www.telerik.com/kendo-react-ui-develop/components/grid/api/gridprops#groupable), and other features to allow AI-driven data operations:

   ```tsx
   <Grid
       data={data}
       sortable={true}
       groupable={{ enabled: true, footer: 'visible' }}
       resizable={true}
       reorderable={true}
       pdf={true}
   ></Grid>
   ```

2. Manage the Grid state using the [`GridAIState`](https://www.telerik.com/kendo-react-ui-develop/components/grid/api/gridaistate) interface. This state object holds the current sort, filter, group, and column configuration that the AI can modify:

   ```tsx
   import { GridAIState } from '@progress/kendo-react-grid';
   const App = () => {
       const [gridState, setGridState] = React.useState<GridAIState>({
           sort: [],
           filter: undefined,
           group: [],
           columnsState: initialColumnsState
       });

       return (
           <Grid
               ...
               // handleAIResponse needs the Grid instance to apply AI commands.
               ref={gridRef}
               // Bind the Grid to gridState so AI-applied changes take effect.
               {...gridState}
               onSortChange={(e) => setGridState((prev) => ({ ...prev, sort: e.sort }))}
               onFilterChange={(e) => setGridState((prev) => ({ ...prev, filter: e.filter }))}
               onGroupChange={(e) => setGridState((prev) => ({ ...prev, group: e.group }))}
               onColumnsStateChange={(e) => setGridState((prev) => ({ ...prev, columnsState: e.columnsState }))}
               onPageChange={(e) => setGridState((prev) => ({ ...prev, skip: e.page.skip, take: e.page.take }))}
           />
       );
   };
   ```

3. Implement a function to send user prompts to your AI service. The request should include the prompt text and column information so the AI understands the Grid structure:

   ```tsx
   const handleBeforeRequest = (event: { columns: unknown; prompt?: string }) => {
       // Show typing indicator while waiting for response
       setMessages((prev) => [...prev, { id: 'typing', author: bot, typing: true }]);

       // Send request to your AI service
       fetch('your-ai-service-endpoint', {
           method: 'POST',
           headers: { 'Content-Type': 'application/json' },
           body: JSON.stringify({
               role: 'user',
               contents: [{ $type: 'text', text: event.prompt }],
               columns: event.columns
           })
       })
           .then((res) => res.json())
           .then((data) => onResponseSuccess({ data }))
           .catch(onResponseError);
   };
   ```

4. When the response returns, use the [`handleAIResponse`](https://www.telerik.com/kendo-react-ui-develop/components/grid/api/handleairesponse) helper function from `@progress/kendo-react-grid` to process the AI response and extract the new Grid state and messages:

   ```tsx
   import { handleAIResponse } from '@progress/kendo-react-grid';

   const onResponseSuccess = (response: { data: any }) => {
       // Remove typing indicator
       setMessages((prev) => prev.filter((msg) => msg.id !== 'typing'));

       // Process AI response using the helper function
       const result = handleAIResponse(response, gridState, gridRef.current);

       // Update Grid state with all changes
       setGridState(result.state);

       // Handle PDF export if requested
       if (result.shouldExportPdf) {
           exportPDFWithMethod();
       }

       // Add AI response messages to Chat
       for (const message of result.messages) {
           setMessages((prev) => [...prev, { id: Date.now().toString(), text: message, author: bot }]);
       }
   };
   ```

   The `handleAIResponse` function returns an object containing the updated `state`, an array of `messages` to display, and a `shouldExportPdf` flag.

5. Set up the Chat component to collect user prompts and display AI responses. Use the [`inputValue`](https://www.telerik.com/kendo-react-ui-develop/components/conversationalui/api/chatprops#inputValue) and [`onInputValueChange`](https://www.telerik.com/kendo-react-ui-develop/components/conversationalui/api/chatprops#onInputValueChange) props to control the input field, and handle the [`onSendMessage`](https://www.telerik.com/kendo-react-ui-develop/components/conversationalui/api/chatprops#onSendMessage) event to process user messages:

   ```tsx
   <Chat
       messages={messages}
       authorId={user.id}
       inputValue={inputValue}
       onInputValueChange={(value) => setInputValue(value)}
       suggestions={suggestions}
       onSuggestionClick={(suggestion) => setInputValue(suggestion.text)}
       onSendMessage={onSendMessage}
       placeholder="Ask me to sort, filter, or analyze your data."
   />
   ```

6. Handle the send message event to add the user message to the chat history and trigger the AI request:

   ```tsx
   const addNewMessage = (event: ChatSendMessageEvent) => {
       const messageText = event.message.text || '';

       // Add user message to chat
       setMessages((prev) => [
           ...prev,
           { ...event.message, text: messageText, id: Date.now().toString(), author: user }
       ]);

       // Send request to AI service
       handleBeforeRequest({
           columns: gridState.columnsState,
           prompt: messageText
       });
   };
   ```

## Suggested Links

* [React Grid AI Toolbar Assistant](https://www.telerik.com/kendo-react-ui-develop/components/grid/smart/ai-toolbar-assistant)
* [AI Service Manual Integration](https://www.telerik.com/kendo-react-ui-develop/components/grid/smart/ai-assistant-tools-setup#manual-integration)
* [Smart Extensions](https://www.telerik.com/kendo-react-ui-develop/components/grid/smart)
* [Chat Overview](https://www.telerik.com/kendo-react-ui-develop/components/conversationalui/chat)
* [API Index of the Grid](https://www.telerik.com/kendo-react-ui-develop/components/grid/api)
* [API Reference of the Chat](https://www.telerik.com/kendo-react-ui-develop/components/conversationalui/api)
