Skip to content

Commit 3f2b22b

Browse files
Merge branch 'development' into 983366-accordin
2 parents efa3253 + 66b6531 commit 3f2b22b

File tree

8 files changed

+616
-444
lines changed

8 files changed

+616
-444
lines changed
Lines changed: 155 additions & 110 deletions
Original file line numberDiff line numberDiff line change
@@ -1,124 +1,90 @@
11
---
22
layout: post
3-
title: Claude AI Service with Smart Components in Blazor App | Syncfusion
4-
description: Learn how to integrate and use the Syncfusion component in a Blazor Web App with Claude AI services.
3+
title: Claude AI Integration with Blazor Smart Paste Button | Syncfusion
4+
description: Learn how to integrate the Syncfusion Blazor Smart Paste Button with Claude AI services in a Blazor App.
55
platform: Blazor
66
control: Smart Paste Button
77
documentation: ug
88
---
99

10-
# Getting Started with Smart Components using Claude AI
10+
# Claude AI Integration with Blazor Smart Paste Button
1111

12-
This guide walks you through integrating Anthropic's Claude AI with Syncfusion<sup style="font-size:70%">&reg;</sup> Smart Components in your Blazor App.
12+
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 Anthropic Claude AI service with the Smart Paste Button using the `IChatInferenceService` interface, enabling custom AI-driven responses in a Blazor Web App.
1313

14-
## Prerequisites
14+
## Setting Up Claude
1515

16-
Before you begin, ensure you have:
16+
1. **Create an Anthropic Account**
17+
Visit [Anthropic Console](https://console.anthropic.com), sign up, and complete the verification process.
18+
2. **Obtain an API Key**
19+
Navigate to [API Keys](https://console.anthropic.com/settings/keys) and click "Create Key."
20+
3. **Review Model Specifications**
21+
Refer to [Claude Models Documentation](https://docs.anthropic.com/claude/docs/models-overview) for details on available models.
1722

18-
* [System requirements for Blazor components](https://blazor.syncfusion.com/documentation/system-requirements)
19-
* Claude account and API key (see setup instructions below)
23+
## Create a Claude AI Service
2024

21-
### Setting Up Claude
25+
Create a service class to manage interactions with the Claude API, including authentication and response processing for the Smart Paste Button.
2226

23-
1. **Create an Anthropic Account**
24-
* Visit [Anthropic Console](https://console.anthropic.com)
25-
* Sign up for a new account
26-
27-
2. **Get Your API Key**
28-
* Navigate to [API Keys](https://console.anthropic.com/settings/keys)
29-
* Click "Create Key"
30-
31-
### Models
32-
33-
For detailed specifications and capabilities, visit the [Claude Models Documentation](https://docs.anthropic.com/claude/docs/models-overview).
34-
35-
---
36-
37-
## Getting Started for Claude AI with SmartPasteButton
38-
39-
After completing this setup, you can:
40-
41-
1. [Add Smart Components to your Blazor pages](https://blazor.syncfusion.com/documentation/smart-paste/getting-started)
42-
2. [Configure form annotations for better AI understanding](https://blazor.syncfusion.com/documentation/smart-paste/annotation)
43-
3. [Customize the appearance and behavior of Smart Components](https://blazor.syncfusion.com/documentation/smart-paste/customization)
44-
45-
---
46-
47-
## Step 1: Create a Claude AI Service
48-
49-
In this step, we'll create a service that handles all communication with Claude's AI. This service is to:
50-
51-
* Manage secure API authentication
52-
* Send prompts to Claude's models
53-
* Process AI responses
54-
55-
### Implementation Steps
56-
57-
1. Create a new file named `ClaudeAIService.cs`
58-
2. Add the required namespaces for HTTP and JSON handling
59-
3. Implement the service class following the code below
27+
1. Create a `Services` folder in your project.
28+
2. Add a new file named `ClaudeAIService.cs` in the `Services` folder.
29+
3. Implement the service as shown below, storing the API key securely in a configuration file or environment variable (e.g., `appsettings.json`).
6030

6131
```csharp
62-
using Microsoft.Extensions.AI;
6332
using System.Net;
6433
using System.Text;
6534
using System.Text.Json;
35+
using Microsoft.Extensions.AI;
36+
6637
public class ClaudeAIService
6738
{
68-
private const string ApiKey = "Your API Key";
69-
private const string ModelName = "Your Model Name";
70-
private const string Endpoint = "https://api.anthropic.com/v1/messages";
71-
39+
private readonly string _apiKey;
40+
private readonly string _modelName = "claude-3-5-sonnet-20241022"; // Example model
41+
private readonly string _endpoint = "https://api.anthropic.com/v1/messages";
7242
private static readonly HttpClient HttpClient = new(new SocketsHttpHandler
7343
{
7444
PooledConnectionLifetime = TimeSpan.FromMinutes(30),
75-
EnableMultipleHttp2Connections = true,
45+
EnableMultipleHttp2Connections = true
7646
})
7747
{
78-
DefaultRequestVersion = HttpVersion.Version30
48+
DefaultRequestVersion = HttpVersion.Version20 // Fallback to HTTP/2 for compatibility
7949
};
80-
8150
private static readonly JsonSerializerOptions JsonOptions = new()
8251
{
8352
PropertyNamingPolicy = JsonNamingPolicy.CamelCase
8453
};
8554

86-
public ClaudeAIService()
55+
public ClaudeAIService(IConfiguration configuration)
8756
{
57+
_apiKey = configuration["Claude:ApiKey"] ?? throw new ArgumentNullException("Claude API key is missing.");
8858
if (!HttpClient.DefaultRequestHeaders.Contains("x-api-key"))
8959
{
9060
HttpClient.DefaultRequestHeaders.Clear();
91-
HttpClient.DefaultRequestHeaders.Add("x-api-key", ApiKey);
92-
HttpClient.DefaultRequestHeaders.Add("anthropic-version", "2023-06-01");
61+
HttpClient.DefaultRequestHeaders.Add("x-api-key", _apiKey);
62+
HttpClient.DefaultRequestHeaders.Add("anthropic-version", "2023-06-01"); // Check latest version in Claude API docs
9363
}
9464
}
9565

9666
public async Task<string> CompleteAsync(IList<ChatMessage> chatMessages)
9767
{
98-
99-
var requestBody = new ClaudeChatRequest
100-
{
101-
Model = ModelName,
102-
Max_tokens = 1000,
103-
Messages = chatMessages.Select(m => new ClaudeMessage
68+
var requestBody = new ClaudeChatRequest
10469
{
105-
Role = m.Role == ChatRole.User ? "user" : "assistant",
106-
Content = m.Text
107-
}).ToList(),
108-
Stop_sequences = new() { "END_INSERTION", "NEED_INFO", "END_RESPONSE" }
109-
};
110-
111-
var json = JsonSerializer.Serialize(requestBody, JsonOptions);
112-
var content = new StringContent(json, Encoding.UTF8, "application/json");
113-
114-
try
70+
Model = _modelName,
71+
Max_tokens = 1000, // Maximum tokens in response
72+
Messages = chatMessages.Select(m => new ClaudeMessage
73+
{
74+
Role = m.Role == ChatRole.User ? "user" : "assistant",
75+
Content = m.Text
76+
}).ToList(),
77+
Stop_sequences = new List<string> { "END_INSERTION", "NEED_INFO", "END_RESPONSE" } // Configurable stop sequences
78+
};
79+
80+
var content = new StringContent(JsonSerializer.Serialize(requestBody, JsonOptions), Encoding.UTF8, "application/json");
81+
82+
try
11583
{
116-
var response = await HttpClient.PostAsync(Endpoint, content);
84+
var response = await HttpClient.PostAsync(_endpoint, content);
11785
response.EnsureSuccessStatusCode();
118-
11986
var responseString = await response.Content.ReadAsStringAsync();
12087
var responseObject = JsonSerializer.Deserialize<ClaudeChatResponse>(responseString, JsonOptions);
121-
12288
return responseObject?.Content?.FirstOrDefault()?.Text ?? "No response from Claude model.";
12389
}
12490
catch (Exception ex) when (ex is HttpRequestException || ex is JsonException)
@@ -129,32 +95,30 @@ public class ClaudeAIService
12995
}
13096
```
13197

132-
## Step 2: Define Request and Response Models
98+
N> Store the Claude API key in `appsettings.json` (e.g., `{ "Claude": { "ApiKey": "your-api-key" } }`) or as an environment variable to ensure security. Verify the `anthropic-version` header in [Claude API Documentation](https://docs.anthropic.com/claude/docs) for the latest version.
13399

134-
To effectively communicate with Claude's API, we need to define structured models for our requests and responses. These models ensure type safety and make the code more maintainable.
100+
## Define Request and Response Models
135101

136-
### Request Models
137-
The request models define the structure of data we send to Claude.
102+
Define C# classes to match the Claude API’s JSON request and response format.
138103

139-
### Response Models
140-
The response models handle Claude's API responses.
104+
1. Create a new file named `ClaudeModels.cs` in the `Services` folder.
105+
2. Add the following model classes:
141106

142-
```CSharp
107+
```csharp
143108
public class ClaudeChatRequest
144109
{
145110
public string Model { get; set; }
146111
public int Max_tokens { get; set; }
147112
public List<ClaudeMessage> Messages { get; set; }
148-
public List<string> Stop_sequences { get; set; }
113+
public List<string> Stop_sequences { get; set; }
149114
}
150115

151116
public class ClaudeMessage
152117
{
153-
public string Role { get; set; } // "user" or "assistant"
118+
public string Role { get; set; }
154119
public string Content { get; set; }
155120
}
156121

157-
// Claude response format
158122
public class ClaudeChatResponse
159123
{
160124
public List<ClaudeContentBlock> Content { get; set; }
@@ -166,53 +130,134 @@ public class ClaudeContentBlock
166130
}
167131
```
168132

169-
## Step 3: Create a Custom AI Service
133+
## Create a Custom AI Service
170134

171-
To integrate Claude with Syncfusion<sup style="font-size:70%">&reg;</sup> Smart Components, you need to implement the `IChatInferenceService` interface. This interface acts as a bridge between Syncfusion's components and Claude's AI capabilities.
135+
Implement the `IChatInferenceService` interface to connect the Smart Paste Button to the Claude service, acting as a bridge for AI-generated responses.
172136

173-
The `IChatInferenceService` interface is designed to allow custom AI service implementations. It defines the contract for how Syncfusion<sup style="font-size:70%">&reg;</sup> components communicate with AI services:
137+
1. Create a new file named `ClaudeInferenceService.cs` in the `Services` folder.
138+
2. Add the following implementation:
174139

175-
1. Create a new file named `MyCustomService.cs`
176-
2. Add the Syncfusion<sup style="font-size:70%">&reg;</sup> namespace
177-
3. Implement the interface as shown below
178-
179-
```CSharp
140+
```csharp
180141
using Syncfusion.Blazor.AI;
181-
public class MyCustomService : IChatInferenceService
142+
using System.Threading.Tasks;
143+
144+
public class ClaudeInferenceService : IChatInferenceService
182145
{
183-
private readonly ClaudeService _ClaudeService;
146+
private readonly ClaudeAIService _claudeService;
184147

185-
public MyCustomService(ClaudeAIService ClaudeService)
148+
public ClaudeInferenceService(ClaudeAIService claudeService)
186149
{
187-
_ClaudeService = ClaudeService;
150+
_claudeService = claudeService;
188151
}
189152

190-
public Task<string> GenerateResponseAsync(ChatParameters options)
153+
public async Task<string> GenerateResponseAsync(ChatParameters options)
191154
{
192-
return _ClaudeService.CompleteAsync(options.Messages);
155+
return await _claudeService.CompleteAsync(options.Messages);
193156
}
194157
}
195158
```
196159

160+
## Configure the Blazor App
197161

198-
## Step 4: Configure the Blazor App
199-
200-
Configure your Blazor application to use the Claude AI service with Syncfusion<sup style="font-size:70%">&reg;</sup> Smart Components. This involves registering necessary services and setting up the dependency injection container.
162+
Register the Claude service and `IChatInferenceService` implementation in the dependency injection container.
201163

202-
```CSharp
164+
Update the **~/Program.cs** file as follows:
203165

204-
using Syncfusion.Blazor.SmartComponents;
166+
```csharp
167+
using Microsoft.AspNetCore.Components;
168+
using Microsoft.AspNetCore.Components.Web;
169+
using Syncfusion.Blazor;
205170
using Syncfusion.Blazor.AI;
206-
var builder = WebApplication.CreateBuilder(args);
207171

208-
....
172+
var builder = WebApplication.CreateBuilder(args);
209173

174+
builder.Services.AddRazorPages();
175+
builder.Services.AddServerSideBlazor();
210176
builder.Services.AddSyncfusionBlazor();
211177
builder.Services.AddSyncfusionSmartComponents();
212178
builder.Services.AddSingleton<ClaudeAIService>();
213-
builder.Services.AddSingleton<IChatInferenceService, MyCustomService>();
179+
builder.Services.AddSingleton<IChatInferenceService, ClaudeInferenceService>();
214180

215181
var app = builder.Build();
216-
....
182+
// ...
183+
```
184+
185+
## Add the Smart Paste Button
186+
187+
Add the Smart Paste Button to a form in the **~/Pages/Home.razor** file to test the Groq AI integration.
188+
189+
```razor
190+
@using Syncfusion.Blazor.DataForm
191+
@using Syncfusion.Blazor.SmartComponents
192+
@using System.ComponentModel.DataAnnotations
193+
194+
<SfDataForm ID="MyForm" Model="@EventRegistrationModel">
195+
<FormValidator>
196+
<DataAnnotationsValidator></DataAnnotationsValidator>
197+
</FormValidator>
198+
<FormItems>
199+
<FormItem Field="@nameof(EventRegistration.Name)" ID="firstname"></FormItem>
200+
<FormItem Field="@nameof(EventRegistration.Email)" ID="email"></FormItem>
201+
<FormItem Field="@nameof(EventRegistration.Phone)" ID="phonenumber"></FormItem>
202+
<FormItem Field="@nameof(EventRegistration.Address)" ID="address"></FormItem>
203+
</FormItems>
204+
<FormButtons>
205+
<SfSmartPasteButton IsPrimary="true" Content="Smart Paste" IconCss="e-icons e-paste"></SfSmartPasteButton>
206+
</FormButtons>
207+
</SfDataForm>
208+
209+
<br>
210+
<h4 style="text-align:center;">Sample Content</h4>
211+
<div>
212+
Hi, my name is Jane Smith. You can reach me at [email protected] or call me at +1-555-987-6543. I live at 789 Pine Avenue, Suite 12, Los Angeles, CA 90001.
213+
</div>
214+
215+
@code {
216+
private EventRegistration EventRegistrationModel = new();
217+
218+
public class EventRegistration
219+
{
220+
[Required(ErrorMessage = "Please enter your name.")]
221+
[Display(Name = "Name")]
222+
public string Name { get; set; }
223+
224+
[Required(ErrorMessage = "Please enter your email address.")]
225+
[Display(Name = "Email ID")]
226+
public string Email { get; set; }
227+
228+
[Required(ErrorMessage = "Please enter your mobile number.")]
229+
[Display(Name = "Phone Number")]
230+
public string Phone { get; set; }
231+
232+
[Required(ErrorMessage = "Please enter your address.")]
233+
[Display(Name = "Address")]
234+
public string Address { get; set; }
235+
}
236+
}
237+
```
238+
239+
N> Ensure the [Syncfusion Blazor DataForm](https://blazor.syncfusion.com/documentation/data-form/getting-started-with-web-app) package is installed for form integration.
240+
241+
## Testing the Integration
242+
243+
1. Configure the Blazor Web App with the Groq AI service and Smart Paste Button as described above.
244+
2. Add the code to **~/Pages/Home.razor**, **Program.cs**, and the `Services` folder.
245+
3. Run the application using <kbd>Ctrl</kbd>+<kbd>F5</kbd> (Windows) or <kbd>⌘</kbd>+<kbd>F5</kbd> (macOS).
246+
4. Copy the sample content provided in the Razor file.
247+
5. Click the **Smart Paste** button to verify that the form fields are populated correctly using the Groq AI service.
248+
249+
![Syncfusion Blazor Smart Paste Button with Groq AI](images/smart-paste.gif)
250+
251+
N> [View Sample in GitHub](https://github.com/syncfusion/smart-ai-samples).
252+
253+
## Troubleshooting
254+
255+
If the Claude AI integration does not work, try the following:
256+
- **No Suggestions Displayed**: Verify that the Claude API key and model name are correct in the configuration. Check the `ClaudeAIService` implementation for errors.
257+
- **HTTP Request Failures**: Ensure a stable internet connection and that the Claude API endpoint (`https://api.anthropic.com/v1/messages`) is accessible. Test with HTTP/2 if compatibility issues arise.
258+
- **Service Registration Errors**: Confirm that `ClaudeAIService` and `ClaudeInferenceService` are registered in **Program.cs**.
259+
260+
## See Also
217261

218-
```
262+
- [Getting Started with Syncfusion Blazor Smart Paste Button in Blazor Web App](https://blazor.syncfusion.com/documentation/smart-paste/getting-started-webapp)
263+
- [Customizing Smart Paste Button Suggestions](https://blazor.syncfusion.com/documentation/smart-paste/customization)

0 commit comments

Comments
 (0)