AI Integration
Integrating AI services with the Telerik UI for ASP.NET MVC Chat component transforms a simple messaging interface into an intelligent conversational experience. Such integration allows you to create applications that can understand natural language, provide contextual responses, and deliver real-time AI-powered assistance to users.
By leveraging streaming responses, the available client-side Chat events and methods, and its built-in UI components, such as SpeechToTextButton, message actions, and tools, you can implement robust AI integrations with minimal custom infrastructure.
In this article, you will build a practical, end-to-end example that demonstrates how to wire the Chat component to a lightweight AI chat client. This implementation covers opening a chat session, sending messages or quick replies, and streaming the AI model's response into the chat conversation.
Getting Started
To create an AI chat service that connects to the Chat, follow the steps below:
The example uses a Telerik-hosted AI service for demonstration purposes only. For production applications, you can implement your own AI service that understands your specific domain, data, and business requirements.
-
Add references to the AI service client and the required formatting libraries for enhanced message display:
JS<!-- Syntax highlighting for code blocks in AI responses --> <link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/highlight.js/11.11.0/styles/default.min.css"> <!-- Markdown parsing library for formatting AI responses --> <script src="https://cdnjs.cloudflare.com/ajax/libs/marked/16.2.0/lib/marked.umd.min.js" integrity="sha512-iFFK3wF8x/wQX/7dko0SsJeEgxUorBdYHFGRpGhnOsfnuewBBQ9a80cn0q1xjNB3kkBjA15NaRHFT7gQoG+V1g==" crossorigin="anonymous" referrerpolicy="no-referrer"></script> <!-- Markdown syntax highlighting integration --> <script src="https://cdnjs.cloudflare.com/ajax/libs/marked-highlight/2.2.2/index.umd.min.js" integrity="sha512-T5TNAGHd65imlc6xoRDq9hARHowETqOlOGMJ443E+PohphJHbzPpwQNBtcpmcjmHmQKLctZ/W3H2cY/T8EGDPA==" crossorigin="anonymous" referrerpolicy="no-referrer"></script> <!-- Code syntax highlighting engine --> <script src="https://cdnjs.cloudflare.com/ajax/libs/highlight.js/11.11.1/highlight.min.js" integrity="sha512-EBLzUL8XLl+va/zAsmXwS7Z2B1F9HUHkZwyS/VKwh3S7T/U0nF4BaU29EP/ZSf6zgiIxYAnKLu6bJ8dqpmX5uw==" crossorigin="anonymous" referrerpolicy="no-referrer"></script> <!-- AI service client --> <script src="~/ai-service.js"></script>
How does the AI service client work?
- Session Management: Creates chat sessions (
POST /chat/conversations
), loads existing conversations (GET /chat/conversations
), and manages individual chat rooms (GET /chat/{chatId}
). - Message Streaming: Sends messages with optional file attachments to
/chat/{chatId}
and processes streaming responses in real-time using the Fetch API and ReadableStream. - Callback System: Invokes structured callbacks based on stream status:
onStart
(when streaming begins),onStreaming
(for each chunk of data), andonComplete
(when finished). Also handlesonAbort
andonError
for cancellation and error scenarios. - Request Cancellation: Supports aborting in-flight requests through
abortRequest()
using AbortController for immediate cancellation. - File Support: Handles image file uploads alongside text messages using FormData for multimodal AI interactions.
- Chat Lifecycle: Provides full CRUD operations including creating new chats and deleting existing conversations (
DELETE /chat/conversations/{chatId}
).
- Session Management: Creates chat sessions (
-
Define the Chat component with predefined suggestions and a Download file action that will be displayed when the message contains an attachment.
Razor@(Html.Kendo().Chat() .Name("chat") .SkipSanitization(true) .AuthorId("user-123") // Specifies the unique identifier of the current user. If not set, a GUID will be generated automatically. .AllowMessageCollapse(true) .Suggestions(suggestions => { suggestions.Add().Text("Analyse my photo"); suggestions.Add().Text("Provide CV template"); suggestions.Add().Text("Generate a cover letter"); }) .FileActions(actions => { actions.Add().Name("download").Text("Download").Icon("download"); }) )
-
Handle the following Chat client events:
-
SendMessage
event—Fires when a message is about to be sent (the user clicks the Send button) or when the send process is triggered. Within the event handler, get the message object (e.message
) and post a message as a reply based on the received message text. For example, if the message text matches any of the predefined quick actions, post a templated answer. Otherwise, start the asynchronous call to the AI service. Provide the following callbacks:onStart
: creates a new AI message in the Chat and toggles the Send button to generating state to show the loading indicator;onStreaming
: accumulates the raw response for final processing, updates the displayed message with HTML-encoded content, and scrolls the chat to bottom to follow the streaming text;onComplete
: callscompleteStream()
to process the final message with Markdown formatting and updates token usage display withdata.message
;onError
: clears the current AI message reference and stops the generating indicator;onAbort
: callscompleteStream()
to finalize whatever content was received before cancellation;
-
Download
event—Fires when a download action is triggered, either from the Download All button or from a file menu download action. Within the event handler, iterate through each file in the message, convert the file URL to a downloadable blob, and trigger a browser download usingkendo.saveAs()
method.
Razor@(Html.Kendo().Chat() .Name("chat") .Events(events => { ev.Download("onDownload"); ev.SendMessage("onSendMessage"); }) ... // Additional configuration. )
-
For the complete example, visit the AI Integration Demo of the Chat component.