diff --git a/ej2-asp-core-mvc/chat-ui/EJ2_ASP.MVC/ai-integrations/gemini-integration.md b/ej2-asp-core-mvc/chat-ui/EJ2_ASP.MVC/ai-integrations/gemini-integration.md new file mode 100644 index 0000000000..6ad8c188d9 --- /dev/null +++ b/ej2-asp-core-mvc/chat-ui/EJ2_ASP.MVC/ai-integrations/gemini-integration.md @@ -0,0 +1,86 @@ +--- +layout: post +title: Gemini AI in ##Platform_Name## Chat UI Control | Syncfusion +description: Checkout and learn about Gemini AI in Syncfusion ##Platform_Name## Chat UI control of Syncfusion Essential JS 2 and more. +platform: ej2-asp-core-mvc +control: Gemini AI +publishingplatform: ##Platform_Name## +documentation: ug +--- + +# Integration of Gemini AI With Chat UI component + +The Syncfusion Chat UI supports integration with [Gemini](https://ai.google.dev/gemini-api/docs), enabling advanced conversational AI features in your MVC applications. + +## Getting Started With the Chat UI Component + +Before integrating Gemini AI, ensure that the Syncfusion Chat UI control is correctly rendered in your MVC application: + +[ MVC Getting Started Guide](../getting-started) + +## Prerequisites + +* Google account to generate API key on accessing `Gemini AI` + +* Syncfusion Chat UI for MVC `Syncfusion.EJ2.MVC5` Install ASP.NET MVC package in the application. + +## Install Dependencies + +Install the Syncfusion ASP.NET MVC package in the application using the Package Manager Console. + +```bash + +NuGet\Install-Package Syncfusion.EJ2.MVC5 + +``` + +Install the Open AI package in the application using the Package Manager Console. + +```bash + +NuGet\Install-Package Mscc.GenerativeAI + +``` + +## Generate API Key + +1. Go to [Google AI Studio](https://aistudio.google.com/app/apikey) and sign in with your Google account. If you don’t have one, create a new account. + +2. Once logged in, click on `Get API Key` from the left-hand menu or the top-right corner of the dashboard. + +3. Click the `Create API Key` button. You’ll be prompted to either select an existing Google Cloud project or create a new one. Choose the appropriate option and proceed. + +4. After selecting or creating a project, your API key will be generated and displayed. Copy the key and store it securely, as it will only be shown once. + +> `Security Note`: Never commit the API key to version control. Use environment variables or a secret manager for production. + +## Integration Gemini AI with Chat UI + +You can add the below respective files in your application: + +* Add your generated `API Key` at the line + +```bash + +const geminiApiKey = 'Place your API key here'; + +``` + +{% tabs %} +{% highlight razor tabtitle="CSHTML" %} +{% include code-snippet/chat-ui/ai-integrations/Asp.net-MVC/gemini/razor %} +{% endhighlight %} +{% highlight c# tabtitle="gemini.cs" %} +{% include code-snippet/chat-ui/ai-integrations/Asp.net-MVC/gemini/gemini.cs %} +{% endhighlight %} +{% endtabs %} + +![gemini](../../images/gemini.png) + +## Run and Test + +Run the application in the browser using the following command. + +Build and run the app (Ctrl + F5). + +Open `https://localhost:44321` to interact with your Gemini AI for dynamic response. \ No newline at end of file diff --git a/ej2-asp-core-mvc/chat-ui/EJ2_ASP.MVC/ai-integrations/openai-integration.md b/ej2-asp-core-mvc/chat-ui/EJ2_ASP.MVC/ai-integrations/openai-integration.md new file mode 100644 index 0000000000..7b03076dde --- /dev/null +++ b/ej2-asp-core-mvc/chat-ui/EJ2_ASP.MVC/ai-integrations/openai-integration.md @@ -0,0 +1,90 @@ +--- +layout: post +title: Azure Open AI in ##Platform_Name## Chat UI Control | Syncfusion +description: Checkout and learn about Integration of Azure Open AI in Syncfusion ##Platform_Name## Chat UI control of Syncfusion Essential JS 2 and more. +platform: ej2-asp-core-mvc +control: Azure Open AI +publishingplatform: ##Platform_Name## +documentation: ug +--- + +# Integration of Azure Open AI With Chat UI component + +The Syncfusion AI AssistView supports integration with [Azure Open AI](https://microsoft.github.io/PartnerResources/skilling/ai-ml-academy/resources/openai), enabling advanced conversational AI features in your MVC applications. + +## Getting Started With the Chat UI Component + +Before integrating Azure Open AI, ensure that the Syncfusion Chat UI control is correctly rendered in your MVC application: +[ MVC Getting Started Guide](../getting-started) + +## Prerequisites + +* An Azure account with access to `Azure Open AI` services and a generated API key. + +* Syncfusion Chat UI for MVC `Syncfusion.EJ2.MVC5` Install ASP.NET MVC package in the application. + +## Install Dependencies + +Install the Syncfusion ASP.NET MVC package in the application using the Package Manager Console. + +```bash + +NuGet\Install-Package Syncfusion.EJ2.MVC5 + +``` + +Install the Open AI and Azure Open AI package in the application using Package Manager Console. + +```bash + +NuGet\Install-Package OpenAI +NuGet\Install-Package Azure.AI.OpenAI +NuGet\Install-Package Azure.Core + +``` + + +## Generate API Key + +1. Log in to the [Azure Portal](https://portal.azure.com/#home) and navigate to your Azure Open AI resource. + +2. Under Resource Management, select Keys and Endpoint to retrieve your API key and endpoint URL. + +3. Copy the API key, endpoint, and deployment name (e.g., gpt-4o-mini). Ensure the API version (e.g., 2024-07-01-preview) matches your resource configuration. + +4. Store these values securely, as they will be used in your application. + +> `Security Note`: Never expose your API key in client-side code for production applications. Use a server-side proxy or environment variables to manage sensitive information securely + +## Integration Azure Open AI with Chat UI + +You can add the below respective files in your application: + +* Update the following configuration values with your Azure Open AI details: + +```bash + +string endpoint = "Your_Azure_OpenAI_Endpoint"; +string apiKey = "Your_Azure_OpenAI_API_Key"; +string deploymentName = "Your_Deployment_Name"; + +``` + +{% tabs %} +{% highlight razor tabtitle="CSHTML" %} +{% include code-snippet/chat-ui/ai-integrations/Asp.net-MVC/openai/razor %} +{% endhighlight %} +{% highlight c# tabtitle="openai.cs" %} +{% include code-snippet/chat-ui/ai-integrations/Asp.net-MVC/openai/openai.cs %} +{% endhighlight %} +{% endtabs %} + +![Azure Open AI](../../images/openai.png) + +## Run and Test + +Run the application in the browser using the following command. + +Build and run the app (Ctrl + F5). + +Open `https://localhost:44321` to interact with your Azure Open AI for dynamic response. \ No newline at end of file diff --git a/ej2-asp-core-mvc/chat-ui/EJ2_ASP.MVC/bot-integrations/integration-with-bot-framework.md b/ej2-asp-core-mvc/chat-ui/EJ2_ASP.MVC/bot-integrations/integration-with-bot-framework.md new file mode 100644 index 0000000000..88006b3400 --- /dev/null +++ b/ej2-asp-core-mvc/chat-ui/EJ2_ASP.MVC/bot-integrations/integration-with-bot-framework.md @@ -0,0 +1,245 @@ +--- +layout: post +title: Microsoft Bot in ##Platform_Name## Chat UI Control | Syncfusion +description: Checkout and learn about Integration of Microsoft Bot in Syncfusion ##Platform_Name## Chat UI control of Syncfusion Essential JS 2 and more. +platform: ej2-asp-core-mvc +control: Integration of Microsoft Bot +publishingplatform: ##Platform_Name## +documentation: ug +--- + +# Microsoft Bot Framework With ASP.NET MVC Chat UI component + +The Syncfusion ASP.NET MVC Chat UI supports integration with a Microsoft Bot Framework bot hosted on Azure, enabling a custom chat interface for seamless user interaction. The process involves setting up a secure backend token server, configuring the bot in Azure, and integrating the Syncfusion Chat UI in an ASP.NET MVC application. + +## Getting Started With the Chat UI Component + +Before integrating Microsoft Bot Framework, ensure that the Syncfusion Chat UI component is correctly rendered in your ASP.NET MVC app: + +[ASP.NET MVC Getting Started Guide](../getting-started) + +## Prerequisites + +* `Microsoft Azure Account`: Required to create and host the bot. +* `Visual Studio`: With ASP.NET MVC development tools. +* `Syncfusion EJ2 ASP.NET MVC`: Install Syncfusion.EJ2.MVC5 in your project. +* `Deployed Azure Bot`: A bot should be created and published using the Bot Framework, accessible via an Azure App Service. Refer to [Microsoft's Bot Creation Guide](https://learn.microsoft.com/en-us/azure/bot-service/). + +## Install Dependencies + +* Install backend dependencies for bot communication using NuGet: + +```bash + +Install-Package Microsoft.Bot.Connector.DirectLine +Install-Package Newtonsoft.Json + +``` + +* Install the Syncfusion EJ2 ASP.NET MVC package: + +```bash + +Install-Package Syncfusion.EJ2.MVC5 + +``` + +## Configure the Azure Bot + +1. In the [Azure Portal](https://portal.azure.com/#home), navigate to your bot resource. + +2. Enable the Direct Line channel: + * Go to `Channels` > `Direct Line` > `Default-Site`. + * Copy one of the displayed secret keys. + +3. Verify the Messaging endpoint in the Configuration section (e.g., https://your-bot-service.azurewebsites.net/api/messages). + +> `Security Note`: Never expose the Direct Line secret key in frontend code. Use a backend token server to handle it securely. + +## Set Up Token Server + +Create a Web API controller in your ASP.NET MVC project to handle Direct Line token generation. Add `Controllers/TokenController.cs`: + +{% tabs %} +{% highlight cs tabtitle="TokenController.cs" %} + +using System; +using System.Configuration; +using System.Net; +using System.Net.Http; +using System.Threading.Tasks; +using System.Web.Http; +using Newtonsoft.Json; + +namespace YourNamespace.Controllers +{ + public class TokenController : ApiController + { + private static readonly HttpClient _httpClient = new HttpClient(); + [HttpPost] + [Route("api/token/directline/token")] + public async Task GenerateToken() + { + var directLineSecret = ConfigurationManager.AppSettings["DirectLineSecret"]; + if (string.IsNullOrEmpty(directLineSecret)) + { + return BadRequest("Direct Line secret is not configured."); + } + try + { + var request = new HttpRequestMessage(HttpMethod.Post, "https://directline.botframework.com/v3/directline/tokens/generate"); + request.Headers.Authorization = new System.Net.Http.Headers.AuthenticationHeaderValue("Bearer", directLineSecret); + var response = await _httpClient.SendAsync(request); + response.EnsureSuccessStatusCode(); + var responseContent = await response.Content.ReadAsStringAsync(); + dynamic tokenResponse = JsonConvert.DeserializeObject(responseContent); + return Ok(new { token = tokenResponse.token }); + } + catch (HttpRequestException ex) + { + return InternalServerError(new Exception("Failed to generate Direct Line token.", ex)); + } + } + } +} + +{% endhighlight %} +{% endtabs %} + +Add the Direct Line secret to `Web.config`: + +{% tabs %} +{% highlight js tabtitle=".env" %} + + + + +{% endhighlight %} +{% endtabs %} + +>`Security Note`: Store the Direct Line secret in a secure configuration, such as Azure Key Vault, for production environments. + +## Integrate ChatUI in ASP.NET MVC + +Use the Chat UI `messageSend` event to handle message exchanges. This event is triggered before a message is sent, allowing you to forward it to the bot via the Direct Line API. Use the `addMessage` method to programmatically add the bot's reply to the Chat UI. + +Create `Views/Home/Index.cshtml` to integrate the Syncfusion Chat UI with the Direct Line API: + +{% tabs %} +{% highlight Html tabtitle="Index.cshtml" %} + +@using Syncfusion.EJ2.InteractiveChat + +@{ + var currentUserModel = new ChatUIUser { Id = "user1", User = "You" }; + var botUserModel = new ChatUIUser { Id = "bot", User = "Bot" }; +} + +
+ @Html.EJS().ChatUI("chatUI").User(currentUserModel).MessageSend("onMessageSend").Created("onCreated").Render() +
+ + + + + +{% endhighlight %} +{% endtabs %} + +>Ensure Syncfusion scripts and styles are included in `_Layout.cshtml` as per the getting started guide. Also, include the Bot Framework Web Chat script for Direct Line functionality. Register the Syncfusion script manager in `_Layout.cshtml`. + +## Configure Web.config for CORS (if needed) + +To enable CORS for API requests, add to `Web.config` under ``: + +{% tabs %} +{% highlight js tabtitle="Web.config.js" %} + + + + + + + + + +{% endhighlight %} +{% endtabs %} + +## Run and Test + +### Start the Application: + +Run the project in Visual Studio or use IIS Express. +Open your app in the browser (e.g., `http://localhost:port`) to interact with your Microsoft Bot Framework chatbot. + +## Troubleshooting + +* `Token Server Error (500)`: Ensure the `DirectLineSecret` in `Web.config` is correct and the token endpoint is accessible. +* `CORS Error`: Verify the CORS configuration in `Web.config` allows requests from your frontend URL. +* `Bot is Not Responding`: + - Test the bot in the Azure Portal using the `Test in Web Chat` feature to ensure it’s running correctly. + - Check the bot’s `Messaging endpoint` in the Configuration section and ensure it is correct and accessible. +* `Connection Fails on Load`: Verify the token controller is running and accessible. Check the browser console for network errors. +* `Token Expiration`: Direct Line tokens are short-lived. The Direct Line client typically handles token refresh, but if issues persist, restart the Direct Line connection. \ No newline at end of file diff --git a/ej2-asp-core-mvc/chat-ui/EJ2_ASP.MVC/bot-integrations/integration-with-dialogflow.md b/ej2-asp-core-mvc/chat-ui/EJ2_ASP.MVC/bot-integrations/integration-with-dialogflow.md new file mode 100644 index 0000000000..978274bffd --- /dev/null +++ b/ej2-asp-core-mvc/chat-ui/EJ2_ASP.MVC/bot-integrations/integration-with-dialogflow.md @@ -0,0 +1,219 @@ +--- +layout: post +title: Integration of Dialogflow in ##Platform_Name## Chat UI Control | Syncfusion +description: Checkout and learn about Integration of Dialogflow in Syncfusion ##Platform_Name## Chat UI control of Syncfusion Essential JS 2 and more. +platform: ej2-asp-core-mvc +control: Integration of Dialogflow +publishingplatform: ##Platform_Name## +documentation: ug +--- + +# Integration of Google Dialogflow With ASP.NET MVC Chat UI component + +The Syncfusion Chat UI supports integration with [Google Dialogflow](https://cloud.google.com/dialogflow/docs), enabling advanced conversational AI features in your ASP.NET MVC applications. + +## Getting Started With the ChatUI Component + +Before integrating Dialogflow, ensure that the Syncfusion Chat UI component is correctly rendered in your ASP.NET MVC app: + +[ASP.NET MVC Getting Started Guide](../getting-started) + +## Prerequisites + +* Google account to access `Dialogflow` and `Google Cloud Console`. +* Visual Studio with ASP.NET MVC development tools. +* Syncfusion EJ2 ASP.NET MVC installed in your project. +* Dialogflow Service Account with the `Dialogflow API Client` role and its JSON key file. + +## Install Dependencies + +* Install backend dependencies for Dialogflow and server setup using NuGet: + +```bash + +Install-Package Google.Cloud.Dialogflow.V2 +Install-Package Newtonsoft.Json + +``` +* Install the Syncfusion EJ2 ASP.NET MVC package in your project: + +```bash + +Install-Package Syncfusion.EJ2.MVC5 + +``` + +## Set Up the Dialogflow Agent + +1. In the Dialogflow console, create an [agent](https://cloud.google.com/agent-assist/docs), set a name (e.g., `MyChatBot`), and configure the default language (e.g., English - `en`). + +2. Add intents with training phrases and responses (e.g., greetings, FAQs). Test using the Dialogflow simulator. + +3. In the Google Cloud Console, go to `APIs & Services` > `Credentials`, create a Service Account with the Dialogflow API Client role, and download the JSON key file. + +> `Security Note`: Never commit the JSON key file to version control. Use environment variables or a secret manager (e.g., Google Cloud Secret Manager) for production. + +## Configure ASP.NET MVC Backend + +Create `service-acct.json` with your Dialogflow service account credentials in your project root: + +{% tabs %} +{% highlight js tabtitle="service-acct.json" %} + +{ + "type": "service_account", + "project_id": "your-dialogflow-project-id", + "private_key_id": "abc123xyz...", + "private_key": "-----BEGIN PRIVATE KEY-----\nMIIEv...", + "client_email": "dialogflow-agent@your-dialogflow-project-id.iam.gserviceaccount.com", + ... +} + +{% endhighlight %} +{% endtabs %} + +Set up a Web API controller in `Controllers/ChatController.cs` to handle Dialogflow requests: + +{% tabs %} +{% highlight cs tabtitle="ChatController.cs" %} + +using Google.Cloud.Dialogflow.V2; +using Google.Apis.Auth.OAuth2; +using System; +using System.Configuration; +using System.Threading.Tasks; +using System.Web.Http; + +namespace YourNamespace.Controllers +{ + public class ChatController : ApiController + { + private readonly SessionsClient _sessionsClient; + private readonly string _projectId; + public ChatController() + { + var credential = GoogleCredential.FromFile("service-acct.json"); + _sessionsClient = SessionsClient.Create(credential.ToChannelCredentials()); + _projectId = ConfigurationManager.AppSettings["DialogflowProjectId"]; // Or hardcode from JSON + } + [HttpPost] + [Route("api/chat/message")] + public async Task SendMessage([FromBody] MessageRequest request) + { + var sessionId = request.SessionId ?? "default-session"; + var session = SessionName.FromProjectSession(_projectId, sessionId); + var queryInput = new QueryInput + { + Text = new TextInput + { + Text = request.Text, + LanguageCode = "en-US" + } + }; + try + { + var response = await _sessionsClient.DetectIntentAsync(new DetectIntentRequest { Session = session.ToString(), QueryInput = queryInput }); + var reply = response.QueryResult.FulfillmentText; + return Ok(new { reply }); + } + catch (Exception ex) + { + return InternalServerError(new Exception("Error connecting to Dialogflow.", ex)); + } + } + } + public class MessageRequest + { + public string Text { get; set; } + public string SessionId { get; set; } + } +} + +{% endhighlight %} +{% endtabs %} + +> Use a unique `sessionId` (e.g., Guid) for each user to maintain conversation context. Add the projectId to Web.config if needed: + +## Integrate ChatUI in ASP.NET MVC + +Use the Chat UI `messageSend` event to exchange messages. This event is triggered before a message is sent, allowing you to forward it to the backend. + +### Forward Message to backend: + +In the `messageSend` event handler, send a POST request to your backend API endpoint (`/api/chat/message`). The backend forwards the message to Dialogflow and returns the response. + +### Displaying Bot response: + +Use the `addMessage` method to programmatically add the bot's reply to the Chat UI. + +Create `Views/Home/Index.cshtml` to integrate the Syncfusion Chat UI with the Dialogflow backend: + +{% tabs %} +{% highlight Html tabtitle="Index.cshtml" %} + +@using Syncfusion.EJ2.InteractiveChat + +@{ + var currentUserModel = new ChatUIUser { Id = "user1", User = "Albert" }; + var botUserModel = new ChatUIUser { Id = "user2", User = "Bot", AvatarUrl = "https://ej2.syncfusion.com/demos/src/chat-ui/images/bot.png" }; +} + +
+ @Html.EJS().ChatUI("chatUI").HeaderText("Bot").HeaderIconCss("e-header-icon").User(currentUserModel).MessageSend("onMessageSend").Render() +
+ + + + +{% endhighlight %} +{% endtabs %} + +> Ensure to include Syncfusion scripts and styles in `_Layout.cshtml` as per the getting started guide. Also, register the Syncfusion script manager in `_Layout.cshtml`. + +## Run and Test + +### Start the Application: + +Run the project in Visual Studio or use IIS Express. + +Open your app in the browser and chat with your Dialogflow-powered bot. + +![ChatUI with Dialogflow](../../images/dialogflow.png) + +## Troubleshooting: + +* `Permission Denied`: Ensure the service account has the `Dialogflow API Client` role in the Google Cloud Console. +* `CORS Error`: If using separate origins, configure CORS in Web.config (e.g., add custom headers under ). +* `No Response`: Test intents in the Dialogflow Console simulator to ensure they are configured correctly. +* `Quota Exceeded`: Check Dialogflow API quotas in the Google Cloud Console. +* `Network Issues`: Confirm the application is running and the frontend is pointing to the correct API URL. +* `Invalid Credentials`: Verify the service account JSON or configuration settings are correctly set up. diff --git a/ej2-asp-core-mvc/chat-ui/EJ2_ASP.NETCORE/ai-integrations/gemini-integration.md b/ej2-asp-core-mvc/chat-ui/EJ2_ASP.NETCORE/ai-integrations/gemini-integration.md new file mode 100644 index 0000000000..33bed56777 --- /dev/null +++ b/ej2-asp-core-mvc/chat-ui/EJ2_ASP.NETCORE/ai-integrations/gemini-integration.md @@ -0,0 +1,86 @@ +--- +layout: post +title: Gemini AI in ##Platform_Name## Chat UI Control | Syncfusion +description: Checkout and learn about Integration of Gemini AI in Syncfusion ##Platform_Name## Chat UI control of Syncfusion Essential JS 2 and more. +platform: ej2-asp-core-mvc +control: Gemini AI +publishingplatform: ##Platform_Name## +documentation: ug +--- + +# Integration of Gemini AI With Chat UI component + +The Syncfusion Chat UI supports integration with [Gemini](https://ai.google.dev/gemini-api/docs), enabling advanced conversational AI features in your Core applications. + +## Getting Started With the Chat UI Component + +Before integrating Gemini AI, ensure that the Syncfusion Chat UI control is correctly rendered in your Core application: + +[ core Getting Started Guide](../getting-started) + +## Prerequisites + +* Google account to generate API key on accessing `Gemini AI` + +* Syncfusion Chat UI for Core `Syncfusion.EJ2.AspNet.Core` Install ASP.NET Core package in the application. + +## Install Dependencies + +Install the Syncfusion ASP.NET Core package in the application using the Package Manager Console. + +```bash + +NuGet\Install-Package Syncfusion.EJ2.AspNet.Core + +``` + +Install the Open AI package in the application using the Package Manager Console. + +```bash + +NuGet\Install-Package Mscc.GenerativeAI + +``` + +## Generate API Key + +1. Go to [Google AI Studio](https://aistudio.google.com/app/apikey) and sign in with your Google account. If you don’t have one, create a new account. + +2. Once logged in, click on `Get API Key` from the left-hand menu or the top-right corner of the dashboard. + +3. Click the `Create API Key` button. You’ll be prompted to either select an existing Google Cloud project or create a new one. Choose the appropriate option and proceed. + +4. After selecting or creating a project, your API key will be generated and displayed. Copy the key and store it securely, as it will only be shown once. + +> `Security Note`: Never commit the API key to version control. Use environment variables or a secret manager for production. + +## Integration Gemini AI with Chat UI + +You can add the below respective files in your application: + +* Add your generated `API Key` at the line + +```bash + +const geminiApiKey = 'Place your API key here'; + +``` + +{% tabs %} +{% highlight tagHelper tabtitle="CSHTML" %} +{% include code-snippet/chat-ui/ai-integrations/Asp.net-core/gemini/tagHelper %} +{% endhighlight %} +{% highlight c# tabtitle="gemini.cs" %} +{% include code-snippet/chat-ui/ai-integrations/Asp.net-core/gemini/gemini.cs %} +{% endhighlight %} +{% endtabs %} + +![Open AI](../../images/gemini.png) + +## Run and Test + +Run the application in the browser using the following command. + +Build and run the app (Ctrl + F5). + +Open `https://localhost:44321` to interact with your Gemini AI for dynamic response. \ No newline at end of file diff --git a/ej2-asp-core-mvc/chat-ui/EJ2_ASP.NETCORE/ai-integrations/openai-integration.md b/ej2-asp-core-mvc/chat-ui/EJ2_ASP.NETCORE/ai-integrations/openai-integration.md new file mode 100644 index 0000000000..11ec9b6d5f --- /dev/null +++ b/ej2-asp-core-mvc/chat-ui/EJ2_ASP.NETCORE/ai-integrations/openai-integration.md @@ -0,0 +1,89 @@ +--- +layout: post +title: Azure Open AI in ##Platform_Name## Chat UI Control | Syncfusion +description: Checkout and learn about Integration of Azure Open AI in Syncfusion ##Platform_Name## Chat UI control of Syncfusion Essential JS 2 and more. +platform: ej2-asp-core-mvc +control: Azure Open AI +publishingplatform: ##Platform_Name## +documentation: ug +--- + +# Integration of Azure Open AI With Chat UI component + +The Syncfusion AI AssistView supports integration with [Azure Open AI](https://microsoft.github.io/PartnerResources/skilling/ai-ml-academy/resources/openai), enabling advanced conversational AI features in your Core applications. + +## Getting Started With the Chat UI Component + +Before integrating Azure Open AI, ensure that the Syncfusion Chat UI control is correctly rendered in your core application: +[ Asp Core Getting Started Guide](../getting-started) + +## Prerequisites + +* An Azure account with access to `Azure Open AI` services and a generated API key. + +* Syncfusion Chat UI for Core `Syncfusion.EJ2.AspNet.Core` Install ASP.NET Core package in the application. + +## Install Dependencies + +Install the Syncfusion ASP.NET Core package in the application using the Package Manager Console. + +```bash + +NuGet\Install-Package Syncfusion.EJ2.AspNet.Core +``` + +Install the Open AI and Azure Open AI package in the application using Package Manager Console. + +```bash + +NuGet\Install-Package OpenAI +NuGet\Install-Package Azure.AI.OpenAI +NuGet\Install-Package Azure.Core + +``` + + +## Configure Azure Open AI + +1. Log in to the [Azure Portal](https://portal.azure.com/#home) and navigate to your Azure Open AI resource. + +2. Under Resource Management, select Keys and Endpoint to retrieve your API key and endpoint URL. + +3. Copy the API key, endpoint, and deployment name (e.g., gpt-4o-mini). Ensure the API version (e.g., 2024-07-01-preview) matches your resource configuration. + +4. Store these values securely, as they will be used in your application. + +> `Security Note`: Never expose your API key in client-side code for production applications. Use a server-side proxy or environment variables to manage sensitive information securely. + +## Integration Azure Open AI with Chat UI + +You can add the below respective files in your application: + +* Update the following configuration values with your Azure Open AI details: + +```bash + +string endpoint = "Your_Azure_OpenAI_Endpoint"; +string apiKey = "Your_Azure_OpenAI_API_Key"; +string deploymentName = "Your_Deployment_Name"; + +``` + +{% tabs %} +{% highlight tagHelper tabtitle="CSHTML" %} +{% include code-snippet/chat-ui/ai-integrations/Asp.net-core/openai/tagHelper %} +{% endhighlight %} +{% highlight c# tabtitle="openai.cs" %} +{% include code-snippet/chat-ui/ai-integrations/Asp.net-core/openai/openai.cs %} +{% endhighlight %} +{% endtabs %} + +![Azure Open AI](../../images/openai.png) + +## Run and Test + +Run the application in the browser using the following command. + +Build and run the app (Ctrl + F5). + +Open `https://localhost:44321` to interact with your Azure Open AI for dynamic response. \ No newline at end of file diff --git a/ej2-asp-core-mvc/chat-ui/EJ2_ASP.NETCORE/bot-integrations/integration-with-bot-framework.md b/ej2-asp-core-mvc/chat-ui/EJ2_ASP.NETCORE/bot-integrations/integration-with-bot-framework.md new file mode 100644 index 0000000000..11910f2113 --- /dev/null +++ b/ej2-asp-core-mvc/chat-ui/EJ2_ASP.NETCORE/bot-integrations/integration-with-bot-framework.md @@ -0,0 +1,275 @@ +--- +layout: post +title: Microsoft Bot in ##Platform_Name## Chat UI Control | Syncfusion +description: Checkout and learn about Integration of Microsoft Bot in Syncfusion ##Platform_Name## Chat UI control of Syncfusion Essential JS 2 and more. +platform: ej2-asp-core-mvc +control: Integration of Microsoft Bot +publishingplatform: ##Platform_Name## +documentation: ug +--- + +# Microsoft Bot Framework With ASP.NET Core Chat UI component + +The Syncfusion ASP.NET Core Chat UI supports integration with a Microsoft Bot Framework bot hosted on Azure, enabling a custom chat interface for seamless user interaction. The process involves setting up a secure backend token server, configuring the bot in Azure, and integrating the Syncfusion Chat UI in an ASP.NET Core application. + +## Getting Started With the ChatUI Component + +Before integrating Microsoft Bot Framework, ensure that the Syncfusion Chat UI component is correctly rendered in your ASP.NET Core app: +[ASP.NET Core Getting Started Guide](../getting-started) + +## Prerequisites + +* `Microsoft Azure Account`: Required to create and host the bot. +* `.NET SDK`: Version 6.0 or higher for ASP.NET Core. +* `Syncfusion EJ2 ASP.NET Core`: Install Syncfusion.EJ2.AspNet.Core in your project. +* `Deployed Azure Bot`: A bot should be created and published using the Bot Framework, accessible via an Azure App Service. Refer to [Microsoft's Bot Creation Guide](https://learn.microsoft.com/en-us/azure/bot-service/). + +## Install Dependencies +* Install backend dependencies for bot communication using NuGet: + +```bash + +dotnet add package Microsoft.Bot.Connector.DirectLine +dotnet add package Microsoft.AspNetCore.Mvc.NewtonsoftJson + +``` + +* Install the Syncfusion EJ2 ASP.NET Core package: + +```bash + +dotnet add package Syncfusion.EJ2.AspNet.Core + +``` + +## Configure the Azure Bot + +1. In the [Azure Portal](https://portal.azure.com/#home), navigate to your bot resource. + +2. Enable the Direct Line channel: + * Go to `Channels` > `Direct Line` > `Default-Site`. + * Copy one of the displayed secret keys. + +3. Verify the Messaging endpoint in the Configuration section (e.g., https://your-bot-service.azurewebsites.net/api/messages). + +> `Security Note`: Never expose the Direct Line secret key in frontend code. Use a backend token server to handle it securely. + +## Set Up Token Server + +Create a controller in your ASP.NET Core project to handle Direct Line token generation. Add `Controllers/TokenController.cs`: + +{% tabs %} +{% highlight cs tabtitle="TokenController.cs" %} + +using Microsoft.AspNetCore.Mvc; +using System.Net.Http; +using System.Threading.Tasks; +using Newtonsoft.Json; + +namespace YourNamespace.Controllers +{ + [ApiController] + [Route("api/[controller]")] + public class TokenController : ControllerBase + { + private readonly IConfiguration _configuration; + private readonly HttpClient _httpClient; + + public TokenController(IConfiguration configuration, IHttpClientFactory httpClientFactory) + { + _configuration = configuration; + _httpClient = httpClientFactory.CreateClient(); + } + + [HttpPost("directline/token")] + public async Task GenerateToken() + { + var directLineSecret = _configuration["DirectLine:Secret"]; + if (string.IsNullOrEmpty(directLineSecret)) + { + return BadRequest(new { error = "Direct Line secret is not configured." }); + } + + try + { + var request = new HttpRequestMessage(HttpMethod.Post, "https://directline.botframework.com/v3/directline/tokens/generate"); + request.Headers.Authorization = new System.Net.Http.Headers.AuthenticationHeaderValue("Bearer", directLineSecret); + + var response = await _httpClient.SendAsync(request); + response.EnsureSuccessStatusCode(); + + var responseContent = await response.Content.ReadAsStringAsync(); + var tokenResponse = JsonConvert.DeserializeObject(responseContent); + return Ok(new { token = tokenResponse.token }); + } + catch (HttpRequestException ex) + { + return StatusCode(500, new { error = "Failed to generate Direct Line token.", details = ex.Message }); + } + } + } +} + +{% endhighlight %} +{% endtabs %} + +Add the Direct Line secret to `appsettings.json`: + +{% tabs %} +{% highlight js tabtitle="appsettings.json" %} + +{ + "DirectLine": { + "Secret": "PASTE_YOUR_DIRECT_LINE_SECRET_HERE" + } +} + +{% endhighlight %} +{% endtabs %} + +> `Security Note`: Store the Direct Line secret in a secure configuration, such as Azure Key Vault, for production environments.| + +## Integrate ChatUI in ASP.NET Core + +Use the Chat UI `messageSend` event to handle message exchanges. This event is triggered before a message is sent, allowing you to forward it to the bot via the Direct Line API. Use the `addMessage` method to programmatically add the bot's reply to the Chat UI. +Create `Views/Home/Index.cshtml` (assuming MVC) to integrate the Syncfusion Chat UI with the Direct Line API: + +{% tabs %} +{% highlight Html tabtitle="Index.cshtml" %} + +@using Syncfusion.EJ2.InteractiveChat + +@{ + var currentUserModel = new ChatUIUser { Id = "user1", User = "You" }; + var botUserModel = new ChatUIUser { Id = "bot", User = "Bot" }; +} + +
+ + + +
+ + + + + +{% endhighlight %} +{% endtabs %} + +> Ensure Syncfusion scripts and styles are included in `_Layout.cshtml` as per the getting started guide. Also, register `` in `_Layout.cshtml`. Include the Bot Framework Web Chat script for Direct Line functionality. + +## Configure Program.cs + +Ensure CORS and HttpClient are configured in `Program.cs`: + +{% tabs %} +{% highlight cs tabtitle="Program.cs" %} + +var builder = WebApplication.CreateBuilder(args); + +builder.Services.AddControllers().AddNewtonsoftJson(); +builder.Services.AddHttpClient(); +builder.Services.AddCors(options => +{ + options.AddPolicy("AllowAll", builder => + { + builder.AllowAnyOrigin().AllowAnyMethod().AllowAnyHeader(); + }); +}); + +var app = builder.Build(); + +app.UseCors("AllowAll"); +app.UseRouting(); +app.MapControllers(); + +app.Run(); + +{% endhighlight %} +{% endtabs %} + +## Run and Test + +### Start the Application: + +Navigate to your project folder and run: + +```bash + +dotnet run + +``` + +Open your app in the browser (e.g., `http://localhost:5000`) to interact with your Microsoft Bot Framework chatbot. + +## Troubleshooting + +* `Token Server Error (500)`: Ensure the DirectLine:Secret in appsettings.json is correct and the token endpoint is accessible. +* `CORS Error`: Verify the CORS policy in Program.cs allows requests from your frontend URL. +* `Bot is Not Responding`: + - Test the bot in the Azure Portal using the `Test in Web Chat` feature to ensure it's running correctly. + - Check the bot's `Messaging endpoint` in the Configuration section and ensure it is correct and accessible. +* `Connection Fails on Load`: Verify the token controller is running and accessible. Check the browser console for network errors. +* `Token Expiration`: Direct Line tokens are short-lived. The Direct Line client typically handles token refresh, but if issues persist, restart the Direct Line connection. \ No newline at end of file diff --git a/ej2-asp-core-mvc/chat-ui/EJ2_ASP.NETCORE/bot-integrations/integration-with-dialogflow.md b/ej2-asp-core-mvc/chat-ui/EJ2_ASP.NETCORE/bot-integrations/integration-with-dialogflow.md new file mode 100644 index 0000000000..15a02f6b7c --- /dev/null +++ b/ej2-asp-core-mvc/chat-ui/EJ2_ASP.NETCORE/bot-integrations/integration-with-dialogflow.md @@ -0,0 +1,216 @@ +--- +layout: post +title: Integration of Dialogflow in ##Platform_Name## Chat UI Control | Syncfusion +description: Checkout and learn about Integration of Dialogflow in Syncfusion ##Platform_Name## Chat UI control of Syncfusion Essential JS 2 and more. +platform: ej2-asp-core-mvc +control: Integration of Dialogflow +publishingplatform: ##Platform_Name## +documentation: ug +--- + +# Integration of Google Dialogflow With ASP.NET Core Chat UI component + +The Syncfusion Chat UI supports integration with [Google Dialogflow](https://cloud.google.com/dialogflow/docs), enabling advanced conversational AI features in your ASP.NET Core applications. + +## Getting Started With the ChatUI Component + +Before integrating Dialogflow, ensure that the Syncfusion Chat UI component is correctly rendered in your ASP.NET Core app: +[ASP.NET Core Getting Started Guide](../getting-started) + +## Prerequisites + +* Google account to access `Dialogflow` and `Google Cloud Console`. +* .NET SDK (version 6.0 or higher) for ASP.NET Core. +* Syncfusion EJ2 ASP.NET Core installed in your project. +* Dialogflow Service Account with the Dialogflow API Client role and its JSON key file. + +## Install Dependencies +* Install backend dependencies for Dialogflow and server setup using NuGet: + +```bash + +dotnet add package Google.Cloud.Dialogflow.V2 +dotnet add package Microsoft.AspNetCore.Mvc.NewtonsoftJson + +``` +* Install the Syncfusion EJ2 ASP.NET Core package in your project: + +```bash + +dotnet add package Syncfusion.EJ2.AspNet.Core + +``` +## Set Up the Dialogflow Agent + +1. In the Dialogflow console, create an [agent](https://cloud.google.com/agent-assist/docs), set a name (e.g., `MyChatBot`), and configure the default language (e.g., English - `en`). + +2. Add intents with training phrases and responses (e.g., greetings, FAQs). Test using the Dialogflow simulator. + +3. In the Google Cloud Console, go to `APIs & Services` > `Credentials`, create a Service Account with the Dialogflow API Client role, and download the JSON key file. + +> `Security Note`: Never commit the JSON key file to version control. Use environment variables or a secret manager (e.g., Google Cloud Secret Manager) for production. + +## Configure Node.js Backend + +Create `service-acct.json` with your Dialogflow service account credentials in your project root (or use User Secrets for development): + +{% tabs %} +{% highlight js tabtitle="service-acct.json" %} + +{ +"type": "service_account", +"project_id": "your-dialogflow-project-id", +"private_key_id": "abc123xyz...", +"private_key": "-----BEGIN PRIVATE KEY-----\nMIIEv...", +"client_email": "dialogflow-agent@your-dialogflow-project-id.iam.gserviceaccount.com", +... +} +{% endhighlight %} +{% endtabs %} + +Set up an API controller in `Controllers/ChatController.cs` to handle Dialogflow requests: + +{% tabs %} +{% highlight cs tabtitle="ChatController.cs" %} + +using Google.Cloud.Dialogflow.V2; +using Google.Apis.Auth.OAuth2; +using Microsoft.AspNetCore.Mvc; +using System.Threading.Tasks; + +namespace YourNamespace.Controllers +{ + [ApiController] + [Route("api/[controller]")] + public class ChatController : ControllerBase + { + private readonly SessionsClient _sessionsClient; + private readonly string _projectId; + public ChatController(IConfiguration configuration) + { + var credential = GoogleCredential.FromFile("service-acct.json"); + _sessionsClient = SessionsClient.Create(credential.ToChannelCredentials()); + _projectId = "your-dialogflow-project-id"; // Or from configuration + } + [HttpPost("message")] + public async Task SendMessage([FromBody] MessageRequest request) + { + var sessionId = request.SessionId ?? "default-session"; + var session = SessionName.FromProjectSession(_projectId, sessionId); + var queryInput = new QueryInput + { + Text = new TextInput + { + Text = request.Text, + LanguageCode = "en-US" + } + }; + try + { + var response = await _sessionsClient.DetectIntentAsync(new DetectIntentRequest { Session = session.ToString(), QueryInput = queryInput }); + var reply = response.QueryResult.FulfillmentText; + return Ok(new { reply }); + } + catch (Exception ex) + { + return StatusCode(500, new { reply = "Error connecting to Dialogflow." }); + } + } + } + public class MessageRequest + { + public string Text { get; set; } + public string SessionId { get; set; } + } +} + +{% endhighlight %} +{% endtabs %} + +> Use a unique `sessionId` (e.g., Guid) for each user to maintain conversation context. Add the projectId to appsettings.json if needed. + +## Integrate ChatUI in ASP.NET Core + +Use the Chat UI `messageSend` event to exchange messages. This event is triggered before a message is sent, allowing you to forward it to the backend. + +### Forward Message to backend: + +In the messageSend event handler, send a POST request to your backend API endpoint (`/api/chat/message`). The backend forwards the message to Dialogflow and returns the response. + +### Displaying Bot response: + +Use the `addMessage` method to programmatically add the bot's reply to the Chat UI. + +Create `Views/Home/Index.cshtml` (assuming MVC) to integrate the Syncfusion Chat UI with the Dialogflow backend: + +{% tabs %} +{% highlight Html tabtitle="Index.cshtml" %} + +@using Syncfusion.EJ2.InteractiveChat +@{ + var currentUserModel = new ChatUIUser { Id = "user1", User = "Albert" }; + var botUserModel = new ChatUIUser { Id = "user2", User = "Bot", AvatarUrl = "https://ej2.syncfusion.com/demos/src/chat-ui/images/bot.png" }; +} +
+ +
+ + + +{% endhighlight %} +{% endtabs %} + +> Ensure to include Syncfusion scripts and styles in _Layout.cshtml as per the getting started guide. Also, register ` in _Layout.cshtml.` + +## Run and Test + +### Start the Application: + +Navigate to your project folder and run: + +```bash + +dotnet run + +``` + + Open your app and chat with your Dialogflow-powered bot. + +![ChatUI with Dialogflow](../../images/dialogflow.png) + +## Troubleshooting: + +* `Permission Denied`: Ensure the service account has the `Dialogflow API Client` role in the Google Cloud Console. +* `CORS Error`: Configure CORS in Program.cs if needed (e.g., app.UseCors()). +* `No Response`: Test intents in the Dialogflow Console simulator to ensure they are configured correctly. +* `Quota Exceeded`: Check Dialogflow API quotas in the Google Cloud Console. +* `Network Issues`: Confirm the application is running and the API URL is correct. +* `Invalid Credentials`: Verify the service account JSON or configuration settings are correctly set up. \ No newline at end of file diff --git a/ej2-asp-core-mvc/chat-ui/images/dialogflow.png b/ej2-asp-core-mvc/chat-ui/images/dialogflow.png new file mode 100644 index 0000000000..8b96f608e9 Binary files /dev/null and b/ej2-asp-core-mvc/chat-ui/images/dialogflow.png differ diff --git a/ej2-asp-core-mvc/chat-ui/images/gemini.png b/ej2-asp-core-mvc/chat-ui/images/gemini.png new file mode 100644 index 0000000000..d548f62208 Binary files /dev/null and b/ej2-asp-core-mvc/chat-ui/images/gemini.png differ diff --git a/ej2-asp-core-mvc/chat-ui/images/openai.png b/ej2-asp-core-mvc/chat-ui/images/openai.png new file mode 100644 index 0000000000..3f56e695a9 Binary files /dev/null and b/ej2-asp-core-mvc/chat-ui/images/openai.png differ diff --git a/ej2-asp-core-mvc/code-snippet/ai-assistview/ai-integrations/gemini-ai/geminicore.cs b/ej2-asp-core-mvc/code-snippet/ai-assistview/ai-integrations/gemini-ai/geminicore.cs index f2e0ab297c..9d34a474eb 100644 --- a/ej2-asp-core-mvc/code-snippet/ai-assistview/ai-integrations/gemini-ai/geminicore.cs +++ b/ej2-asp-core-mvc/code-snippet/ai-assistview/ai-integrations/gemini-ai/geminicore.cs @@ -39,7 +39,7 @@ public async Task OnPostGetAIResponse([FromBody] PromptRequest re string apiKey = ""; // Replace with your key var googleAI = new GoogleAI(apiKey: apiKey); - var model = googleAI.GenerativeModel(model: Model.Gemini15Flash); + var model = googleAI.GenerativeModel(model: Model.Gemini15Flash); //Replace Your Model Name Here var response = await model.GenerateContent(request.Prompt); diff --git a/ej2-asp-core-mvc/code-snippet/ai-assistview/ai-integrations/gemini-ai/geminimvc.cs b/ej2-asp-core-mvc/code-snippet/ai-assistview/ai-integrations/gemini-ai/geminimvc.cs index c94229f8d3..6c0054c9c0 100644 --- a/ej2-asp-core-mvc/code-snippet/ai-assistview/ai-integrations/gemini-ai/geminimvc.cs +++ b/ej2-asp-core-mvc/code-snippet/ai-assistview/ai-integrations/gemini-ai/geminimvc.cs @@ -42,7 +42,7 @@ public async Task GetAIResponse([FromBody] PromptRequest request) string apiKey = ""; // Replace with your key var googleAI = new GoogleAI(apiKey: apiKey); - var model = googleAI.GenerativeModel(model: Model.Gemini15Flash); + var model = googleAI.GenerativeModel(model: Model.Gemini15Flash); //Replace Your Model Name Here var responseText = await model.GenerateContent(request.Prompt); diff --git a/ej2-asp-core-mvc/code-snippet/ai-assistview/ai-integrations/gemini-ai/razor b/ej2-asp-core-mvc/code-snippet/ai-assistview/ai-integrations/gemini-ai/razor index ebec3a9e57..ecd93a6004 100644 --- a/ej2-asp-core-mvc/code-snippet/ai-assistview/ai-integrations/gemini-ai/razor +++ b/ej2-asp-core-mvc/code-snippet/ai-assistview/ai-integrations/gemini-ai/razor @@ -69,7 +69,7 @@ 'Content-Type': 'application/json', 'RequestVerificationToken': token }, - body: JSON.stringify({ prompt: args.prompt || 'Hi' }) + body: JSON.stringify({ prompt: args.prompt}) }) .then(response => { if (!response.ok) { diff --git a/ej2-asp-core-mvc/code-snippet/ai-assistview/ai-integrations/gemini-ai/tagHelper b/ej2-asp-core-mvc/code-snippet/ai-assistview/ai-integrations/gemini-ai/tagHelper index 0e59d545ac..69282bbe0c 100644 --- a/ej2-asp-core-mvc/code-snippet/ai-assistview/ai-integrations/gemini-ai/tagHelper +++ b/ej2-asp-core-mvc/code-snippet/ai-assistview/ai-integrations/gemini-ai/tagHelper @@ -65,7 +65,7 @@ headers: { 'Content-Type': 'application/json' }, - body: JSON.stringify({ prompt: args.prompt || 'Hi' }) + body: JSON.stringify({ prompt: args.prompt}) }) .then(response => { if (!response.ok) { diff --git a/ej2-asp-core-mvc/code-snippet/chat-ui/ai-integrations/Asp.net-MVC/gemini/gemini.cs b/ej2-asp-core-mvc/code-snippet/chat-ui/ai-integrations/Asp.net-MVC/gemini/gemini.cs new file mode 100644 index 0000000000..08e0eb9fc7 --- /dev/null +++ b/ej2-asp-core-mvc/code-snippet/chat-ui/ai-integrations/Asp.net-MVC/gemini/gemini.cs @@ -0,0 +1,62 @@ +using System.Diagnostics; +using Microsoft.AspNetCore.Mvc.RazorPages; +using Microsoft.AspNetCore.Mvc; +using Microsoft.Extensions.AI; +using Mscc.GenerativeAI; +using Syncfusion.EJ2.InteractiveChat; +using Newtonsoft.Json; + +private readonly ILogger _logger; +public List HeaderToolbar { get; set; } = new List(); +public HomeController(ILogger logger) +{ + _logger = logger; +} +public IActionResult Index() +{ + HeaderToolbar.Add(new ToolbarItemModel { align = "Right", iconCss = "e-icons e-refresh", tooltip = "Refresh" }); + ViewBag.HeaderToolbar = HeaderToolbar; + var currentUser = new ChatUIUser { Id = "user1", User = "You" }; + var aiUser = new ChatUIUser { Id = "ai", User = "Gemini" }; + ViewBag.CurrentUser = currentUser; + ViewBag.AIUser = aiUser; + + return View(); +} + +[HttpPost] +public async Task GetAIResponse([FromBody] PromptRequest request) +{ + try + { + _logger.LogInformation("Received request with prompt: {Prompt}", request?.Prompt); + if (string.IsNullOrEmpty(request?.Prompt)) + { + _logger.LogWarning("Prompt is null or empty."); + return BadRequest("Prompt cannot be empty."); + } + string apiKey = ""; // Replace with your key + var googleAI = new GoogleAI(apiKey: apiKey); + var model = googleAI.GenerativeModel(model: Model.Gemini15Flash); // Replace Your Model Name Here + + var responseText = await model.GenerateContent(request.Prompt); + if (string.IsNullOrEmpty(responseText?.Text)) + { + _logger.LogError("Gemini AI API returned no text."); + return BadRequest("No response from Gemini AI."); + } + _logger.LogInformation("Gemini AI response received: {Response}", responseText.Text); + return Json(responseText.Text); + } + catch (Exception ex) + { + _logger.LogError("Exception in Gemini AI call: {Message}", ex.Message); + return BadRequest($"Error generating response: {ex.Message}"); + } +} +public class ToolbarItemModel +{ + public string align { get; set; } + public string iconCss { get; set; } + public string tooltip { get; set; } +} diff --git a/ej2-asp-core-mvc/code-snippet/chat-ui/ai-integrations/Asp.net-MVC/gemini/razor b/ej2-asp-core-mvc/code-snippet/chat-ui/ai-integrations/Asp.net-MVC/gemini/razor new file mode 100644 index 0000000000..08eaac9cd2 --- /dev/null +++ b/ej2-asp-core-mvc/code-snippet/chat-ui/ai-integrations/Asp.net-MVC/gemini/razor @@ -0,0 +1,87 @@ +@using Syncfusion.EJ2.InteractiveChat +@using Newtonsoft.Json +@using Syncfusion.EJ2 +@{ + ViewData["Title"] = "AI Chat with Gemini AI"; +} + +
+ @Html.EJS().ChatUI("chatUI").User(ViewBag.CurrentUser).HeaderText("Chat with Gemini AI").HeaderToolbar(new ChatUIToolbarSettings() { Items = ViewBag.HeaderToolbar, ItemClicked = "itemClicked" }).HeaderIconCss("e-icons e-ai-chat").EmptyChatTemplate("#emptyChatTemplate").MessageSend("onMessageSend").Created("onCreated").Render() +
+ + + + + + \ No newline at end of file diff --git a/ej2-asp-core-mvc/code-snippet/chat-ui/ai-integrations/Asp.net-MVC/openai/openai.cs b/ej2-asp-core-mvc/code-snippet/chat-ui/ai-integrations/Asp.net-MVC/openai/openai.cs new file mode 100644 index 0000000000..835a39f831 --- /dev/null +++ b/ej2-asp-core-mvc/code-snippet/chat-ui/ai-integrations/Asp.net-MVC/openai/openai.cs @@ -0,0 +1,75 @@ +using System.Diagnostics; +using Microsoft.AspNetCore.Mvc.RazorPages; +using Microsoft.AspNetCore.Mvc; +using Microsoft.Extensions.AI; +using OpenAI; +using OpenAI.Chat; +using Syncfusion.EJ2.InteractiveChat; +using Newtonsoft.Json; +using Azure.AI.OpenAI; +using Azure; +private readonly ILogger _logger; +public List HeaderToolbar { get; set; } = new List(); +public HomeController(ILogger logger) +{ + _logger = logger; +} + +public IActionResult Index() +{ + HeaderToolbar.Add(new ToolbarItemModel { align = "Right", iconCss = "e-icons e-refresh", tooltip = "Refresh" }); + ViewBag.HeaderToolbar = HeaderToolbar; + var currentUser = new ChatUIUser { Id = "user1", User = "You" }; + var aiUser = new ChatUIUser { Id = "ai", User = "Azure Open AI" }; + ViewBag.CurrentUser = currentUser; + ViewBag.AIUser = aiUser; + + return View(); +} + +[HttpPost] +public async Task GetAIResponse([FromBody] PromptRequest request) +{ + try + { + _logger.LogInformation("Received request with prompt: {Prompt}", request?.Prompt); + if (string.IsNullOrEmpty(request?.Prompt)) + { + _logger.LogWarning("Prompt is null or empty."); + return BadRequest("Prompt cannot be empty."); + } + string endpoint = "Your_Azure_OpenAI_Endpoint"; // Replace with your Azure OpenAI endpoint + string apiKey = "YOUR_AZURE_OPENAI_API_KEY"; // Replace with your Azure OpenAI API key + string deploymentName = "YOUR_DEPLOYMENT_NAME"; // Replace with your Azure OpenAI deployment name (e.g., gpt-4o-mini) + + var credential = new AzureKeyCredential(apiKey); + var client = new AzureOpenAIClient(new Uri(endpoint), credential); + var chatClient = client.GetChatClient(deploymentName); + + var chatCompletionOptions = new ChatCompletionOptions(); + var completion = await chatClient.CompleteChatAsync( + new[] { new UserChatMessage(request.Prompt) }, + chatCompletionOptions + ); + + string responseText = completion.Value.Content[0].Text; + if (string.IsNullOrEmpty(responseText)) + { + _logger.LogError("Azure OpenAI API returned no text."); + return BadRequest("No response from Azure Open AI."); + } + _logger.LogInformation("Azure OpenAI response received: {Response}", responseText); + return Json(responseText); + } + catch (Exception ex) + { + _logger.LogError("Exception in Azure Open AI call: {Message}", ex.Message); + return BadRequest($"Error generating response: {ex.Message}"); + } +} +public class ToolbarItemModel +{ + public string align { get; set; } + public string iconCss { get; set; } + public string tooltip { get; set; } +} diff --git a/ej2-asp-core-mvc/code-snippet/chat-ui/ai-integrations/Asp.net-MVC/openai/razor b/ej2-asp-core-mvc/code-snippet/chat-ui/ai-integrations/Asp.net-MVC/openai/razor new file mode 100644 index 0000000000..ec39532a80 --- /dev/null +++ b/ej2-asp-core-mvc/code-snippet/chat-ui/ai-integrations/Asp.net-MVC/openai/razor @@ -0,0 +1,87 @@ +@using Syncfusion.EJ2.InteractiveChat +@using Newtonsoft.Json +@using Syncfusion.EJ2 +@{ + ViewData["Title"] = "AI Chat with Azure Open AI"; +} + +
+ @Html.EJS().ChatUI("chatUI").User(ViewBag.CurrentUser).HeaderText("Chat with Azure Open AI").HeaderToolbar(new ChatUIToolbarSettings() { Items = ViewBag.HeaderToolbar, ItemClicked = "itemClicked" }).HeaderIconCss("e-icons e-ai-chat").EmptyChatTemplate("#emptyChatTemplate").MessageSend("onMessageSend").Created("onCreated").Render() +
+ + + + + + \ No newline at end of file diff --git a/ej2-asp-core-mvc/code-snippet/chat-ui/ai-integrations/Asp.net-core/gemini/gemini.cs b/ej2-asp-core-mvc/code-snippet/chat-ui/ai-integrations/Asp.net-core/gemini/gemini.cs new file mode 100644 index 0000000000..b0ef1d5362 --- /dev/null +++ b/ej2-asp-core-mvc/code-snippet/chat-ui/ai-integrations/Asp.net-core/gemini/gemini.cs @@ -0,0 +1,62 @@ +using Microsoft.AspNetCore.Mvc; +using Microsoft.AspNetCore.Mvc.RazorPages; +using Mscc.GenerativeAI; // Correct namespace for Mscc.GenerativeAI package +using System.Threading.Tasks; + +private readonly ILogger _logger; +public List HeaderToolbar { get; set; } = new List(); + +public IndexModel(ILogger logger) +{ + _logger = logger; +} + +public void OnGet() +{ + HeaderToolbar.Add(new ToolbarItemModel { align = "Right", type = "Button", iconCss = "e-icons e-refresh" }); + HeaderToolbar = HeaderToolbar; +} + +public async Task OnPostGetAIResponse([FromBody] PromptRequest request) +{ + try + { + _logger.LogInformation("Received request with prompt: {Prompt}", request?.Prompt); + + if (string.IsNullOrEmpty(request?.Prompt)) + { + _logger.LogWarning("Prompt is null or empty."); + return BadRequest("Prompt cannot be empty."); + } + + string apiKey = ""; // Replace with your key + var googleAI = new GoogleAI(apiKey: apiKey); + var model = googleAI.GenerativeModel(model: Model.Gemini15Flash); // Replace Your Model Name Here + + var response = await model.GenerateContent(request.Prompt); + + if (string.IsNullOrEmpty(response?.Text)) + { + _logger.LogError("Gemini API returned no text."); + return BadRequest("No response from Gemini."); + } + + _logger.LogInformation("Gemini response received: {Response}", response.Text); + return new JsonResult(response.Text); + } + catch (Exception ex) + { + _logger.LogError("Exception in Gemini call: {Message}", ex.Message); + return BadRequest($"Error generating response: {ex.Message}"); + } +} +public class PromptRequest +{ + public string Prompt { get; set; } +} +public class ToolbarItemModel +{ + public string align { get; set; } + public string iconCss { get; set; } + public string type { get; set; } +} diff --git a/ej2-asp-core-mvc/code-snippet/chat-ui/ai-integrations/Asp.net-core/gemini/tagHelper b/ej2-asp-core-mvc/code-snippet/chat-ui/ai-integrations/Asp.net-core/gemini/tagHelper new file mode 100644 index 0000000000..ba3e7f92f4 --- /dev/null +++ b/ej2-asp-core-mvc/code-snippet/chat-ui/ai-integrations/Asp.net-core/gemini/tagHelper @@ -0,0 +1,101 @@ +@page +@model IndexModel +@{ + ViewData["Title"] = "Chat UI with Gemini"; +} + + +
+ + + + +
+ +@section Scripts { + +} \ No newline at end of file diff --git a/ej2-asp-core-mvc/code-snippet/chat-ui/ai-integrations/Asp.net-core/openai/openai.cs b/ej2-asp-core-mvc/code-snippet/chat-ui/ai-integrations/Asp.net-core/openai/openai.cs new file mode 100644 index 0000000000..afb07f147b --- /dev/null +++ b/ej2-asp-core-mvc/code-snippet/chat-ui/ai-integrations/Asp.net-core/openai/openai.cs @@ -0,0 +1,73 @@ +using Microsoft.AspNetCore.Mvc; +using Microsoft.AspNetCore.Mvc.RazorPages; +using System.Threading.Tasks; +using OpenAI.Chat; +using OpenAI; +using Azure; +using Azure.AI.OpenAI; +private readonly ILogger _logger; +public List HeaderToolbar { get; set; } = new List(); + +public IndexModel(ILogger logger) +{ + _logger = logger; +} + +public void OnGet() +{ + HeaderToolbar.Add(new ToolbarItemModel { align = "Right", type = "Button", iconCss = "e-icons e-refresh" }); + HeaderToolbar = HeaderToolbar; +} + +public async Task OnPostGetAIResponse([FromBody] PromptRequest request) +{ + try + { + _logger.LogInformation("Received request with prompt: {Prompt}", request?.Prompt); + + if (string.IsNullOrEmpty(request?.Prompt)) + { + _logger.LogWarning("Prompt is null or empty."); + return BadRequest("Prompt cannot be empty."); + } + + string endpoint = "Your_Azure_OpenAI_Endpoint"; // Replace with your Azure OpenAI endpoint + string apiKey = "YOUR_AZURE_OPENAI_API_KEY"; // Replace with your Azure OpenAI API key + string deploymentName = "YOUR_DEPLOYMENT_NAME"; // Replace with your Azure OpenAI deployment name (e.g., gpt-4o-mini) + + var credential = new AzureKeyCredential(apiKey); + var client = new AzureOpenAIClient(new Uri(endpoint), credential); + var chatClient = client.GetChatClient(deploymentName); + + var chatCompletionOptions = new ChatCompletionOptions(); + var completion = await chatClient.CompleteChatAsync( + new[] { new UserChatMessage(request.Prompt) }, + chatCompletionOptions + ); + string responseText = completion.Value.Content[0].Text; + + if (string.IsNullOrEmpty(responseText)) + { + _logger.LogError("Azure Open AI API returned no text."); + return BadRequest("No response from Azure Open AI."); + } + + _logger.LogInformation("Azure Open AI response received: {Response}", responseText); + return new JsonResult(responseText); + } + catch (Exception ex) + { + _logger.LogError("Exception in Azure Open AI call: {Message}", ex.Message); + return BadRequest($"Error generating response: {ex.Message}"); + } +} +public class PromptRequest +{ + public string Prompt { get; set; } +} +public class ToolbarItemModel +{ + public string align { get; set; } + public string iconCss { get; set; } + public string type { get; set; } +} diff --git a/ej2-asp-core-mvc/code-snippet/chat-ui/ai-integrations/Asp.net-core/openai/tagHelper b/ej2-asp-core-mvc/code-snippet/chat-ui/ai-integrations/Asp.net-core/openai/tagHelper new file mode 100644 index 0000000000..2f1a689619 --- /dev/null +++ b/ej2-asp-core-mvc/code-snippet/chat-ui/ai-integrations/Asp.net-core/openai/tagHelper @@ -0,0 +1,98 @@ +@page +@model IndexModel +@{ + ViewData["Title"] = "Chat UI with Azure Open AI"; +} + + +
+ + + + +
+ +@section Scripts { + +} \ No newline at end of file diff --git a/ej2-asp-core-toc.html b/ej2-asp-core-toc.html index 1d618988f2..6ff7e0027c 100644 --- a/ej2-asp-core-toc.html +++ b/ej2-asp-core-toc.html @@ -570,6 +570,26 @@