|
| 1 | +--- |
| 2 | +layout: post |
| 3 | +title: Claude AI for AI-Powered Scheduler | Syncfusion® |
| 4 | +description: Learn how to implement a custom AI service using the Claude API with Syncfusion<sup>®</sup> AI-Powered Scheduler (SfSmartScheduler) control. |
| 5 | +platform: maui |
| 6 | +control: SfSmartScheduler |
| 7 | +documentation: ug |
| 8 | +--- |
| 9 | + |
| 10 | +# Claude AI Integration with .NET MAUI AI-Powered Scheduler |
| 11 | + |
| 12 | +The Syncfusion [.NET MAUI AI-Powered Scheduler] (SfSmartScheduler) can provide AI-powered suggestions while appointment scheduling. You can integrate Anthropic `Claude AI` using the `IChatInferenceService` interface, which acts as a bridge between the scheduler and your custom AI service. |
| 13 | + |
| 14 | +## Setting Up Claude |
| 15 | + |
| 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. |
| 22 | + |
| 23 | +## Create a Claude AI Service |
| 24 | + |
| 25 | +This service handles communication with the Claude API, including authentication and response parsing. |
| 26 | + |
| 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`). |
| 30 | + |
| 31 | +{% tabs %} |
| 32 | +{% highlight c# tabtitle="ClaudeAIService.cs" %} |
| 33 | + |
| 34 | +using System.Net; |
| 35 | +using System.Text; |
| 36 | +using System.Text.Json; |
| 37 | +using Microsoft.Extensions.AI; |
| 38 | + |
| 39 | +public class ClaudeAIService |
| 40 | +{ |
| 41 | + private readonly string _apiKey; |
| 42 | + private readonly string _modelName = "claude-3-5-sonnet-20241022"; // Example model |
| 43 | + private readonly string _endpoint = "https://api.anthropic.com/v1/messages"; |
| 44 | + private static readonly HttpClient HttpClient = new(new SocketsHttpHandler |
| 45 | + { |
| 46 | + PooledConnectionLifetime = TimeSpan.FromMinutes(30), |
| 47 | + EnableMultipleHttp2Connections = true |
| 48 | + }) |
| 49 | + { |
| 50 | + DefaultRequestVersion = HttpVersion.Version20 // Fallback to HTTP/2 for compatibility |
| 51 | + }; |
| 52 | + private static readonly JsonSerializerOptions JsonOptions = new() |
| 53 | + { |
| 54 | + PropertyNamingPolicy = JsonNamingPolicy.CamelCase |
| 55 | + }; |
| 56 | + |
| 57 | + public ClaudeAIService(IConfiguration configuration) |
| 58 | + { |
| 59 | + _apiKey = configuration["Claude:ApiKey"] ?? throw new ArgumentNullException("Claude API key is missing."); |
| 60 | + if (!HttpClient.DefaultRequestHeaders.Contains("x-api-key")) |
| 61 | + { |
| 62 | + HttpClient.DefaultRequestHeaders.Clear(); |
| 63 | + HttpClient.DefaultRequestHeaders.Add("x-api-key", _apiKey); |
| 64 | + HttpClient.DefaultRequestHeaders.Add("anthropic-version", "2023-06-01"); // Check latest version in Claude API docs |
| 65 | + } |
| 66 | + } |
| 67 | + |
| 68 | + public async Task<string> CompleteAsync(List<ChatMessage> chatMessages) |
| 69 | + { |
| 70 | + var requestBody = new ClaudeChatRequest |
| 71 | + { |
| 72 | + Model = _modelName, |
| 73 | + Max_tokens = 1000, // Maximum tokens in response |
| 74 | + Messages = chatMessages.Select(m => new ClaudeMessage |
| 75 | + { |
| 76 | + Role = m.Role == ChatRole.User ? "user" : "assistant", |
| 77 | + Content = m.Text |
| 78 | + }).ToList(), |
| 79 | + Stop_sequences = new List<string> { "END_INSERTION", "NEED_INFO", "END_RESPONSE" } // Configurable stop sequences |
| 80 | + }; |
| 81 | + |
| 82 | + var content = new StringContent(JsonSerializer.Serialize(requestBody, JsonOptions), Encoding.UTF8, "application/json"); |
| 83 | + |
| 84 | + try |
| 85 | + { |
| 86 | + var response = await HttpClient.PostAsync(_endpoint, content); |
| 87 | + response.EnsureSuccessStatusCode(); |
| 88 | + var responseString = await response.Content.ReadAsStringAsync(); |
| 89 | + var responseObject = JsonSerializer.Deserialize<ClaudeChatResponse>(responseString, JsonOptions); |
| 90 | + return responseObject?.Content?.FirstOrDefault()?.Text ?? "No response from Claude model."; |
| 91 | + } |
| 92 | + catch (Exception ex) when (ex is HttpRequestException || ex is JsonException) |
| 93 | + { |
| 94 | + throw new InvalidOperationException("Failed to communicate with Claude API.", ex); |
| 95 | + } |
| 96 | + } |
| 97 | +} |
| 98 | + |
| 99 | +{% endhighlight %} |
| 100 | +{% endtabs %} |
| 101 | + |
| 102 | +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. |
| 103 | + |
| 104 | +## Define Request and Response Models |
| 105 | + |
| 106 | +Create a file named `ClaudeModels.cs` in the Services folder and add: |
| 107 | + |
| 108 | +{% tabs %} |
| 109 | +{% highlight c# tabtitle="ClaudeModels.cs" %} |
| 110 | + |
| 111 | +public class ClaudeChatRequest |
| 112 | +{ |
| 113 | + public string? Model { get; set; } |
| 114 | + public int Max_tokens { get; set; } |
| 115 | + public List<ClaudeMessage>? Messages { get; set; } |
| 116 | + public List<string>? Stop_sequences { get; set; } |
| 117 | +} |
| 118 | + |
| 119 | +public class ClaudeMessage |
| 120 | +{ |
| 121 | + public string? Role { get; set; } |
| 122 | + public string? Content { get; set; } |
| 123 | +} |
| 124 | + |
| 125 | +public class ClaudeChatResponse |
| 126 | +{ |
| 127 | + public List<ClaudeContentBlock>? Content { get; set; } |
| 128 | +} |
| 129 | + |
| 130 | +public class ClaudeContentBlock |
| 131 | +{ |
| 132 | + public string? Text { get; set; } |
| 133 | +} |
| 134 | + |
| 135 | +{% endhighlight %} |
| 136 | +{% endtabs %} |
| 137 | + |
| 138 | +## Implement IChatInferenceService |
| 139 | + |
| 140 | +Create `ClaudeInferenceService.cs`: |
| 141 | + |
| 142 | +{% tabs %} |
| 143 | +{% highlight c# tabtitle="ClaudeInferenceService.cs" %} |
| 144 | + |
| 145 | +using Syncfusion.Maui.SmartComponents; |
| 146 | + |
| 147 | +public class ClaudeInferenceService : IChatInferenceService |
| 148 | +{ |
| 149 | + private readonly ClaudeAIService _claudeService; |
| 150 | + |
| 151 | + public ClaudeInferenceService(ClaudeAIService claudeService) |
| 152 | + { |
| 153 | + _claudeService = claudeService; |
| 154 | + } |
| 155 | + |
| 156 | + public async Task<string> GenerateResponseAsync(List<ChatMessage> chatMessages) |
| 157 | + { |
| 158 | + return await _claudeService.CompleteAsync(chatMessages); |
| 159 | + } |
| 160 | +} |
| 161 | + |
| 162 | +{% endhighlight %} |
| 163 | +{% endtabs %} |
| 164 | + |
| 165 | +## Register Services in MAUI |
| 166 | + |
| 167 | +Update `MauiProgram.cs`: |
| 168 | + |
| 169 | +{% tabs %} |
| 170 | +{% highlight c# tabtitle="MauiProgram.cs" hl_lines="9 10" %} |
| 171 | + |
| 172 | +using Syncfusion.Maui.Core.Hosting; |
| 173 | +using Syncfusion.Maui.SmartComponents; |
| 174 | + |
| 175 | +var builder = MauiApp.CreateBuilder(); |
| 176 | +builder |
| 177 | + .UseMauiApp<App>() |
| 178 | + .ConfigureSyncfusionCore(); |
| 179 | + |
| 180 | +builder.Services.AddSingleton<ClaudeAIService>(); |
| 181 | +builder.Services.AddSingleton<IChatInferenceService, ClaudeInferenceService>(); |
| 182 | + |
| 183 | + |
| 184 | +{% endhighlight %} |
| 185 | +{% endtabs %} |
0 commit comments