# Angular Data Grid AI Chat Assistant

The [Angular Grid](https://www.telerik.com/kendo-angular-ui-develop/components/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-angular-ui-develop/components/conversational-ui/chat) component with the Grid's [built-in AI helper methods](https://www.telerik.com/kendo-angular-ui-develop/components/grid/smart-grid/ai-assistant-tools-setup#helper-methods), you can create an intuitive conversational interface where users can perform all [supported Smart Grid operations](https://www.telerik.com/kendo-angular-ui-develop/components/grid/smart-grid#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](https://www.telerik.com/kendo-angular-ui-develop/components/grid/smart-grid/ai-service-setup) 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-angular-ui/demos/grid/ai/ai-grid-chat-demo/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. For example, enable [`sortable`](https://www.telerik.com/kendo-angular-ui-develop/components/grid/api/gridcomponent#sortable), [`filterable`](https://www.telerik.com/kendo-angular-ui-develop/components/grid/api/gridcomponent#filterable), [`groupable`](https://www.telerik.com/kendo-angular-ui-develop/components/grid/api/gridcomponent#groupable), and [`pageable`](https://www.telerik.com/kendo-angular-ui-develop/components/grid/api/gridcomponent#pageable) to allow AI-driven data operations:

   ```html
   <kendo-grid
       [kendoGridBinding]="gridData"
       [sortable]="true"
       [filterable]="true"
       [groupable]="true"
       [pageable]="true"
   >
   </kendo-grid>
   ```

2. Implement a method to process user prompts and communicate with your AI service. Use the [`getAIRequest()`](https://www.telerik.com/kendo-angular-ui-develop/components/grid/api/gridcomponent#getairequest) helper method of the Grid to generate the request body in suitable format, then send it to your AI service:

   ```typescript
   private processUserPrompt(prompt: string): void {
       // Generate request body with prompt and column information
       const requestBody = this.grid.getAIRequest(prompt);

       // Send request to your AI service
       this.aiService.sendGridPromptRequest(requestBody).subscribe({
           // TODO: handle the AI service response.
       });
   }
   ```

   The [`getAIRequest()`](https://www.telerik.com/kendo-angular-ui-develop/components/grid/api/gridcomponent#getairequest) method returns an object containing `role`, `contents` array with the prompt text, and `columns` array with Grid column information.

3. When the response returns, use the [`handleAIResponse()`](https://www.telerik.com/kendo-angular-ui-develop/components/grid/api/gridcomponent#handleairesponse) helper to automatically apply all Grid operations based on the received response:

   ```typescript
   private processUserPrompt(prompt: string): void {
       // Generate request body with prompt and column information
       const requestBody = this.grid.getAIRequest(prompt);

       // Send request to your AI service
       this.aiService.sendGridPromptRequest(requestBody).subscribe({
           next: (response) => {
               if (response.body) {
                   // Apply Grid commands before forwarding the response to the Chat.
                   this.grid.handleAIResponse(response.body);

                   // Emit response to display it in the Chat
                   this.aiResponseReceived.emit(response.body);
               }
           },
           error: (error) => {
               console.error('AI request failed:', error);
           }
       });
   }
   ```

   The [`handleAIResponse()`](https://www.telerik.com/kendo-angular-ui-develop/components/grid/api/gridcomponent#handleairesponse) method processes the AI service response and applies operations including sorting, filtering, grouping, paging, column management, selection, highlighting, and export.

4. Set up the Chat component to collect user prompts and display AI responses. Handle the [`sendMessage`](https://www.telerik.com/kendo-angular-ui-develop/components/conversational-ui/api/chatcomponent#sendmessage) event to process new user input and send it to the Grid:

   ```HTML
   <kendo-chat
       [messages]="messages"
       [authorId]="user.id"
       [suggestions]="suggestions"
       placeholder="Ask me to sort, filter, or analyze your data."
       (sendMessage)="onSendMessage($event)"
   >
   </kendo-chat>
   ```

   ```TypeScript
   public onSendMessage(event: SendMessageEvent): void {
       // Add user message to Chat history
       const userMessage: Message = {
           ...event.message,
           author: this.user,
           timestamp: new Date(),
       };
       this.messages = [...this.messages, userMessage];

       // Send user message to the Grid for AI processing
       this.promptSent.emit(event.message);
   }
   ```

5. Display responses from the AI service in the Chat by extracting the messages from the returned response object. The response contains a `commands` array with Grid operation commands and associated messages, and an optional `message` property with an overall summary:

   ```typescript
   // Track AI response changes using Angular signals and process it
   aiResponse = input<any>(null);

   constructor() {
       effect(() => {
           const response = this.aiResponse();
           if (response) {
               this.addAIResponseMessage(response);
           }
       });
   }

   // Process AI response and add it to Chat conversation
   public addAIResponseMessage(response: any): void {
       // Extract messages from response
       const messages = response.commands?.map(cmd => cmd.message || '').filter(msg => msg) || [];
       if (response.message) {
           messages.unshift(response.message);
       }
       const responseText = messages.length > 0 ? messages.join(' ') : 'Grid updated successfully.';

       // Add AI response to Chat
        const aiMessage: Message = {
           id: guid(),
           author: this.bot,
           text: responseText,
           timestamp: new Date(),
       };

       this.messages = [...this.messages, aiMessage];
   }
   ```

## Suggested Links

* [Angular Data Grid AI Toolbar Assistant](https://www.telerik.com/kendo-angular-ui-develop/components/grid/smart-grid/ai-toolbar-assistant)
* [AI Assistant Tools Setup Helper Methods](https://www.telerik.com/kendo-angular-ui-develop/components/grid/smart-grid/ai-assistant-tools-setup#helper-methods)
* [AI Assistant Tools Setup Manual Integration](https://www.telerik.com/kendo-angular-ui-develop/components/grid/smart-grid/ai-assistant-tools-setup#manual-integration)
* [AI Service Setup](https://www.telerik.com/kendo-angular-ui-develop/components/grid/smart-grid/ai-service-setup)
* [Chat Overview](https://www.telerik.com/kendo-angular-ui-develop/components/conversational-ui/chat)
* [API Index of the Grid](https://www.telerik.com/kendo-angular-ui-develop/components/grid/api)
* [API Reference of the Chat](https://www.telerik.com/kendo-angular-ui-develop/components/conversational-ui/api/chatcomponent)
