Skip to content

Commit e5f66f4

Browse files
Merge pull request #6649 from syncfusion-content/983466-SmartTextArea-AI
983466: Updated the SmartTextArea Custom AI Service UG Section.
2 parents 1eac44f + 972f81a commit e5f66f4

File tree

4 files changed

+463
-435
lines changed

4 files changed

+463
-435
lines changed
Lines changed: 119 additions & 110 deletions
Original file line numberDiff line numberDiff line change
@@ -1,123 +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 TextArea | Syncfusion
4+
description: Learn how to integrate the Syncfusion Blazor Smart TextArea with Claude AI services in a Blazor App.
55
platform: Blazor
66
control: Smart TextArea
77
documentation: ug
88
---
99

10-
# Getting Started with Smart Components using Claude AI
10+
# Claude AI Integration with Blazor Smart TextArea
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 Smart TextArea component provides AI-powered autocompletion for context-aware text input, typically using OpenAI or Azure OpenAI. This guide explains how to integrate the Anthropic Claude AI service with the Smart TextArea 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 TextArea.
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 SmartTextArea
38-
39-
After completing this setup, you can:
40-
41-
1. [Add Smart TextArea to your Blazor pages](https://blazor.syncfusion.com/documentation/smart-textarea/getting-started)
42-
2. [Customize Smart TextArea features](https://blazor.syncfusion.com/documentation/smart-textarea/customization)
43-
44-
---
45-
46-
## Step 1: Create a Claude AI Service
47-
48-
In this step, we'll create a service that handles all communication with Claude's AI. This service is to:
49-
50-
* Manage secure API authentication
51-
* Send prompts to Claude's models
52-
* Process AI responses
53-
54-
### Implementation Steps
55-
56-
1. Create a new file named `ClaudeAIService.cs`
57-
2. Add the required namespaces for HTTP and JSON handling
58-
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`).
5930

6031
```csharp
61-
using Microsoft.Extensions.AI;
6232
using System.Net;
6333
using System.Text;
6434
using System.Text.Json;
35+
using Microsoft.Extensions.AI;
36+
6537
public class ClaudeAIService
6638
{
67-
private const string ApiKey = "Your API Key";
68-
private const string ModelName = "Your Model Name";
69-
private const string Endpoint = "https://api.anthropic.com/v1/messages";
70-
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";
7142
private static readonly HttpClient HttpClient = new(new SocketsHttpHandler
7243
{
7344
PooledConnectionLifetime = TimeSpan.FromMinutes(30),
74-
EnableMultipleHttp2Connections = true,
45+
EnableMultipleHttp2Connections = true
7546
})
7647
{
77-
DefaultRequestVersion = HttpVersion.Version30
48+
DefaultRequestVersion = HttpVersion.Version20 // Fallback to HTTP/2 for compatibility
7849
};
79-
8050
private static readonly JsonSerializerOptions JsonOptions = new()
8151
{
8252
PropertyNamingPolicy = JsonNamingPolicy.CamelCase
8353
};
8454

85-
public ClaudeAIService()
55+
public ClaudeAIService(IConfiguration configuration)
8656
{
57+
_apiKey = configuration["Claude:ApiKey"] ?? throw new ArgumentNullException("Claude API key is missing.");
8758
if (!HttpClient.DefaultRequestHeaders.Contains("x-api-key"))
8859
{
8960
HttpClient.DefaultRequestHeaders.Clear();
90-
HttpClient.DefaultRequestHeaders.Add("x-api-key", ApiKey);
91-
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
9263
}
9364
}
9465

9566
public async Task<string> CompleteAsync(IList<ChatMessage> chatMessages)
9667
{
97-
98-
var requestBody = new ClaudeChatRequest
99-
{
100-
Model = ModelName,
101-
Max_tokens = 1000,
102-
Messages = chatMessages.Select(m => new ClaudeMessage
68+
var requestBody = new ClaudeChatRequest
10369
{
104-
Role = m.Role == ChatRole.User ? "user" : "assistant",
105-
Content = m.Text
106-
}).ToList(),
107-
Stop_sequences = new() { "END_INSERTION", "NEED_INFO", "END_RESPONSE" }
108-
};
109-
110-
var json = JsonSerializer.Serialize(requestBody, JsonOptions);
111-
var content = new StringContent(json, Encoding.UTF8, "application/json");
112-
113-
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
11483
{
115-
var response = await HttpClient.PostAsync(Endpoint, content);
84+
var response = await HttpClient.PostAsync(_endpoint, content);
11685
response.EnsureSuccessStatusCode();
117-
11886
var responseString = await response.Content.ReadAsStringAsync();
11987
var responseObject = JsonSerializer.Deserialize<ClaudeChatResponse>(responseString, JsonOptions);
120-
12188
return responseObject?.Content?.FirstOrDefault()?.Text ?? "No response from Claude model.";
12289
}
12390
catch (Exception ex) when (ex is HttpRequestException || ex is JsonException)
@@ -128,32 +95,30 @@ public class ClaudeAIService
12895
}
12996
```
13097

131-
## 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.
13299

133-
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
134101

135-
### Request Models
136-
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.
137103

138-
### Response Models
139-
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:
140106

141-
```CSharp
107+
```csharp
142108
public class ClaudeChatRequest
143109
{
144110
public string Model { get; set; }
145111
public int Max_tokens { get; set; }
146112
public List<ClaudeMessage> Messages { get; set; }
147-
public List<string> Stop_sequences { get; set; }
113+
public List<string> Stop_sequences { get; set; }
148114
}
149115

150116
public class ClaudeMessage
151117
{
152-
public string Role { get; set; } // "user" or "assistant"
118+
public string Role { get; set; }
153119
public string Content { get; set; }
154120
}
155121

156-
// Claude response format
157122
public class ClaudeChatResponse
158123
{
159124
public List<ClaudeContentBlock> Content { get; set; }
@@ -165,54 +130,98 @@ public class ClaudeContentBlock
165130
}
166131
```
167132

133+
## Create a Custom AI Service
168134

169-
## Step 3: Create a Custom AI Service
170-
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 TextArea 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 ClaudeAIService _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
162+
Register the Claude service and `IChatInferenceService` implementation in the dependency injection container.
199163

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.
164+
Update the **~/Program.cs** file as follows:
201165

202-
```CSharp
203-
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+
## Use Claude AI with Smart TextArea
186+
187+
Add the Smart TextArea component to a Razor file (e.g., `~/Pages/Home.razor`) to use Claude AI for autocompletion:
188+
189+
```razor
190+
@using Syncfusion.Blazor.SmartComponents
191+
192+
<SfSmartTextArea UserRole="@userRole" UserPhrases="@userPhrases" Placeholder="Enter your queries here" @bind-Value="prompt" Width="75%" RowCount="5">
193+
</SfSmartTextArea>
194+
195+
@code {
196+
private string? prompt;
197+
// Defines the context for AI autocompletion
198+
private string userRole = "Customer support representative";
199+
// Predefined phrases for AI to suggest during typing
200+
private string[] userPhrases = [
201+
"Thank you for reaching out.",
202+
"Please provide more details.",
203+
"We are investigating your issue."
204+
];
205+
}
206+
```
207+
208+
## Test the Integration
209+
210+
1. Ensure all services are registered in **Program.cs** and the Smart TextArea is added to a Razor file.
211+
2. Run the application using <kbd>Ctrl</kbd>+<kbd>F5</kbd> (Windows) or <kbd>⌘</kbd>+<kbd>F5</kbd> (macOS).
212+
3. Type phrases like "Thank" or "Please provide" in the Smart TextArea to verify that Claude AI generates appropriate suggestions.
213+
4. Check that suggestions appear as configured (e.g., inline or pop-up, based on the `ShowSuggestionOnPopup` setting).
214+
215+
![Smart TextArea with Claude AI](images/smart-textarea.gif)
216+
217+
## Troubleshooting
218+
219+
If the Claude AI integration does not work, try the following:
220+
- **No Suggestions Displayed**: Verify that the Claude API key and model name are correct in the configuration. Check the `ClaudeAIService` implementation for errors.
221+
- **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.
222+
- **Service Registration Errors**: Confirm that `ClaudeAIService` and `ClaudeInferenceService` are registered in **Program.cs**.
223+
224+
## See Also
217225

218-
```
226+
- [Getting Started with Syncfusion Blazor Smart TextArea in Blazor Web App](https://blazor.syncfusion.com/documentation/smart-textarea/getting-started-webapp)
227+
- [Customizing Smart TextArea Suggestions](https://blazor.syncfusion.com/documentation/smart-textarea/customization)

0 commit comments

Comments
 (0)