How can I help you?
Groq AI Integration with Blazor Smart Paste Button
16 Oct 202512 minutes to read
The Syncfusion Blazor SmartPaste Button component enables AI-powered, context-aware content pasting into forms, typically using OpenAI or Azure OpenAI. This guide explains how to integrate the Groq AI service with the Smart Paste Button using the IChatInferenceService interface, enabling custom AI-driven responses in a Blazor Web App.
Setting Up Groq
-
Create a Groq Account
Visit Groq Cloud Console, sign up or sign in, and complete the verification process. -
Obtain an API Key
Navigate to API Keys in the Groq Console and click “Create API Key.” -
Review Model Specifications
Refer to Groq Models Documentation for details on available models (e.g.,llama3-8b-8192).
Create a Groq AI Service
Create a service class to manage interactions with the Groq API, including authentication and response processing for the Smart Paste Button.
- Create a
Servicesfolder in your project. - Add a new file named
GroqService.csin theServicesfolder. - Implement the service as shown below, storing the API key securely in a configuration file or environment variable (e.g.,
appsettings.jsonor environment variables).
using System.Net;
using System.Text;
using System.Text.Json;
using Microsoft.Extensions.AI;
public class GroqService
{
private readonly string _apiKey;
private readonly string _modelName = "llama3-8b-8192"; // Example model
private readonly string _endpoint = "https://api.groq.com/openai/v1/chat/completions";
private static readonly HttpClient HttpClient = new(new SocketsHttpHandler
{
PooledConnectionLifetime = TimeSpan.FromMinutes(30),
EnableMultipleHttp2Connections = true
})
{
DefaultRequestVersion = HttpVersion.Version20 // Fallback to HTTP/2 for broader compatibility
};
private static readonly JsonSerializerOptions JsonOptions = new()
{
PropertyNamingPolicy = JsonNamingPolicy.CamelCase
};
public GroqService(IConfiguration configuration)
{
_apiKey = configuration["Groq:ApiKey"] ?? throw new ArgumentNullException("Groq API key is missing.");
if (!HttpClient.DefaultRequestHeaders.Contains("Authorization"))
{
HttpClient.DefaultRequestHeaders.Clear();
HttpClient.DefaultRequestHeaders.Add("Authorization", $"Bearer {_apiKey}");
}
}
public async Task<string> CompleteAsync(IList<ChatMessage> chatMessages)
{
var requestPayload = new GroqChatParameters
{
Model = _modelName,
Messages = chatMessages.Select(m => new Message
{
Role = m.Role == ChatRole.User ? "user" : "assistant",
Content = m.Text
}).ToList(),
Stop = new List<string> { "END_INSERTION", "NEED_INFO", "END_RESPONSE" } // Configurable stop sequences
};
var content = new StringContent(JsonSerializer.Serialize(requestPayload, JsonOptions), Encoding.UTF8, "application/json");
try
{
var response = await HttpClient.PostAsync(_endpoint, content);
response.EnsureSuccessStatusCode();
var responseString = await response.Content.ReadAsStringAsync();
var responseObject = JsonSerializer.Deserialize<GroqResponseObject>(responseString, JsonOptions);
return responseObject?.Choices?.FirstOrDefault()?.Message?.Content ?? "No response from model.";
}
catch (Exception ex) when (ex is HttpRequestException || ex is JsonException)
{
throw new InvalidOperationException("Failed to communicate with Groq API.", ex);
}
}
}NOTE
Store the Groq API key in
appsettings.json(e.g.,{ "Groq": { "ApiKey": "your-api-key" } }) or as an environment variable to ensure security.
Define Request and Response Models
Define C# classes to match the Groq API’s request and response format.
- Create a new file named
GroqModels.csin theServicesfolder. - Add the following model classes:
public class Choice
{
public Message Message { get; set; }
}
public class Message
{
public string Role { get; set; }
public string Content { get; set; }
}
public class GroqChatParameters
{
public string Model { get; set; }
public List<Message> Messages { get; set; }
public List<string> Stop { get; set; }
}
public class GroqResponseObject
{
public string Model { get; set; }
public List<Choice> Choices { get; set; }
}Create a Custom AI Service
Implement the IChatInferenceService interface to connect the Smart Paste Button to the Groq service.
- Create a new file named
GroqInferenceService.csin theServicesfolder. - Add the following implementation:
using Syncfusion.Blazor.AI;
using System.Threading.Tasks;
public class GroqInferenceService : IChatInferenceService
{
private readonly GroqService _groqService;
public GroqInferenceService(GroqService groqService)
{
_groqService = groqService;
}
public async Task<string> GenerateResponseAsync(ChatParameters options)
{
return await _groqService.CompleteAsync(options.Messages);
}
}Configure the Blazor App
Register the Groq service and IChatInferenceService implementation in the dependency injection container.
Update the ~/Program.cs file as follows:
using Microsoft.AspNetCore.Components;
using Microsoft.AspNetCore.Components.Web;
using Syncfusion.Blazor;
using Syncfusion.Blazor.AI;
var builder = WebApplication.CreateBuilder(args);
builder.Services.AddRazorPages();
builder.Services.AddServerSideBlazor();
builder.Services.AddSyncfusionBlazor();
builder.Services.AddSyncfusionSmartComponents();
builder.Services.AddSingleton<GroqService>();
builder.Services.AddSingleton<IChatInferenceService, GroqInferenceService>();
var app = builder.Build();
// ...Add the Smart Paste Button
Add the Smart Paste Button to a form in the ~/Pages/Home.razor file to test the Groq AI integration.
@using Syncfusion.Blazor.DataForm
@using Syncfusion.Blazor.SmartComponents
@using System.ComponentModel.DataAnnotations
<SfDataForm ID="MyForm" Model="@EventRegistrationModel">
<FormValidator>
<DataAnnotationsValidator></DataAnnotationsValidator>
</FormValidator>
<FormItems>
<FormItem Field="@nameof(EventRegistration.Name)" ID="firstname"></FormItem>
<FormItem Field="@nameof(EventRegistration.Email)" ID="email"></FormItem>
<FormItem Field="@nameof(EventRegistration.Phone)" ID="phonenumber"></FormItem>
<FormItem Field="@nameof(EventRegistration.Address)" ID="address"></FormItem>
</FormItems>
<FormButtons>
<SfSmartPasteButton IsPrimary="true" Content="Smart Paste" IconCss="e-icons e-paste"></SfSmartPasteButton>
</FormButtons>
</SfDataForm>
<br>
<h4 style="text-align:center;">Sample Content</h4>
<div>
Hi, my name is Jane Smith. You can reach me at example@domain.com or call me at +1-555-987-6543. I live at 789 Pine Avenue, Suite 12, Los Angeles, CA 90001.
</div>
@code {
private EventRegistration EventRegistrationModel = new();
public class EventRegistration
{
[Required(ErrorMessage = "Please enter your name.")]
[Display(Name = "Name")]
public string Name { get; set; }
[Required(ErrorMessage = "Please enter your email address.")]
[Display(Name = "Email ID")]
public string Email { get; set; }
[Required(ErrorMessage = "Please enter your mobile number.")]
[Display(Name = "Phone Number")]
public string Phone { get; set; }
[Required(ErrorMessage = "Please enter your address.")]
[Display(Name = "Address")]
public string Address { get; set; }
}
}NOTE
Ensure the Syncfusion Blazor DataForm package is installed for form integration.
Testing the Integration
- Configure the Blazor Web App with the Groq AI service and Smart Paste Button as described above.
- Add the code to ~/Pages/Home.razor, Program.cs, and the
Servicesfolder. - Run the application using Ctrl+F5 (Windows) or ⌘+F5 (macOS).
- Copy the sample content provided in the Razor file.
- Click the Smart Paste button to verify that the form fields are populated correctly using the Groq AI service.

NOTE
Troubleshooting
If the Groq AI integration does not work, try the following:
-
No Suggestions Displayed: Verify that the Groq API key and model name are correct in the configuration. Check the
GroqServiceimplementation for errors. -
HTTP Request Failures: Ensure a stable internet connection and that the Groq API endpoint (
https://api.groq.com/openai/v1/chat/completions) is accessible. Test with HTTP/2 instead of HTTP/3 if compatibility issues arise. -
Service Registration Errors: Confirm that
GroqServiceandGroqInferenceServiceare registered in Program.cs.