Syncfusion AI Assistant

How can I help you?

Claude AI Integration with ASP.NET Core Smart TextArea

16 Dec 20259 minutes to read

The Syncfusion ASP.NET Core Smart TextArea control 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 ASP.NET Core App.

Setting Up Claude

  1. Create an Anthropic Account
    Visit Anthropic Console, sign up, and complete the verification process.
  2. Obtain an API Key
    Navigate to API Keys and click “Create Key.”
  3. Review Model Specifications
    Refer to Claude Models Documentation for details on available models.

Create a Claude AI Service

Create a service class to manage interactions with the Claude API, including authentication and response processing for the Smart TextArea.

  1. Create a Services folder in your project.
  2. Add a new file named ClaudeAIService.cs in the Services folder.
  3. Implement the service as shown below, storing the API key securely in a configuration file or environment variable (e.g., appsettings.json).
using Microsoft.Extensions.AI;
using System.Net;
using System.Text;
using System.Text.Json;

public class ClaudeAIService
{
    private readonly string _apiKey;
    private readonly string _modelName = "claude-3-5-sonnet-20241022"; // Example model
    private readonly string _endpoint = "https://api.anthropic.com/v1/messages";
    private static readonly HttpClient HttpClient = new(new SocketsHttpHandler
    {
        PooledConnectionLifetime = TimeSpan.FromMinutes(30),
        EnableMultipleHttp2Connections = true
    })
    {
        DefaultRequestVersion = HttpVersion.Version20 // Fallback to HTTP/2 for compatibility
    };
    private static readonly JsonSerializerOptions JsonOptions = new()
    {
        PropertyNamingPolicy = JsonNamingPolicy.CamelCase
    };

    public ClaudeAIService(IConfiguration configuration)
    {
        _apiKey = configuration["Claude:ApiKey"] ?? throw new ArgumentNullException("Claude API key is missing.");
        if (!HttpClient.DefaultRequestHeaders.Contains("x-api-key"))
        {
            HttpClient.DefaultRequestHeaders.Clear();
            HttpClient.DefaultRequestHeaders.Add("x-api-key", _apiKey);
            HttpClient.DefaultRequestHeaders.Add("anthropic-version", "2023-06-01"); // Check latest version in Claude API docs
        }
    }

    public async Task<string> CompleteAsync(IList<ChatMessage> chatMessages)
    {
        var requestBody = new ClaudeChatRequest
        {
            Model = _modelName,
            Max_tokens = 1000, // Maximum tokens in response
            Messages = chatMessages.Select(m => new ClaudeMessage
            {
                Role = m.Role == ChatRole.User ? "user" : "assistant",
                Content = m.Text
            }).ToList(),
            Stop_sequences  = new List<string> { "END_INSERTION", "NEED_INFO", "END_RESPONSE" } // Configurable stop sequences
        };

        var content = new StringContent(JsonSerializer.Serialize(requestBody, 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<ClaudeChatResponse>(responseString, JsonOptions);
            return responseObject?.Content?.FirstOrDefault()?.Text ?? "No response from Claude model.";
        }
        catch (Exception ex) when (ex is HttpRequestException || ex is JsonException)
        {
            throw new InvalidOperationException("Failed to communicate with Claude API.", ex);
        }
    }
}

NOTE

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 for the latest version.

Define Request and Response Models

Define C# classes to match the Claude API’s JSON request and response format.

  1. Create a new file named ClaudeModels.cs in the Services folder.
  2. Add the following model classes:
public class ClaudeChatRequest
{
    public string Model { get; set; }
    public int Max_tokens { get; set; }
    public List<ClaudeMessage> Messages { get; set; }
    public List<string> Stop_sequences  { get; set; }
}

public class ClaudeMessage
{
    public string Role { get; set; }
    public string Content { get; set; }
}

public class ClaudeChatResponse
{
    public List<ClaudeContentBlock> Content { get; set; }
}

public class ClaudeContentBlock
{
    public string Text { get; set; }
}

Create a Custom AI Service

Implement the IChatInferenceService interface to connect the Smart TextArea to the Claude service, acting as a bridge for AI-generated responses.

  1. Create a new file named ClaudeInferenceService.cs in the Services folder.
  2. Add the following implementation:
using Syncfusion.EJ2.AI;
using System.Threading.Tasks;

public class ClaudeInferenceService : IChatInferenceService
{
    private readonly ClaudeAIService _claudeService;

    public ClaudeInferenceService(ClaudeAIService claudeService)
    {
        _claudeService = claudeService;
    }

    public async Task<string> GenerateResponseAsync(ChatParameters options)
    {
        return await _claudeService.CompleteAsync(options.Messages);
    }
}

Configure the ASP.NET Core App

Register the Claude service and IChatInferenceService implementation in the dependency injection container.

Update the ~/Program.cs file as follows:

using Syncfusion.EJ2.AI;

builder.Services.AddRazorPages();
builder.Services.AddSyncfusionSmartComponents();
builder.Services.AddSingleton<ClaudeAIService>();
builder.Services.AddSingleton<IChatInferenceService, ClaudeInferenceService>();

var app = builder.Build();
// ...

Add ASP.NET Core Smart TextArea Control

Add the Smart TextArea in the ~/Pages/Index.cshtml file to test the Claude AI integration.

@{
    var presets = new { 
        userRole = "Maintainer of an open-source project replying to GitHub issues",
        userPhrases = new[] { "Thank you for contacting us.", "To investigate, we'll need a repro as a public Git repo.", "Could you please post a screenshot of NEED_INFO?", "This sounds like a usage question. This issue tracker is intended for bugs and feature proposals. Unfortunately, we don't have the capacity to answer general usage questions and would recommend StackOverflow for a faster response.", "We don't accept ZIP files as repros." }, 
        placeHolder = "Write your response to the GitHub issue..." };
}

<ejs-smarttextarea id="smartTextarea" user-role="@presets.userRole" user-phrases="@presets.userPhrases" width="75%" placeholder="@presets.placeHolder" floatLabelType="Auto" rows="5"></ejs-smarttextarea>

Press Ctrl+F5 (Windows) or +F5 (macOS) to run the app. Then, the Syncfusion® ASP.NET Core
Smart TextArea control will be rendered in the default web browser.

ASP.NET Core Smart TextArea Control

Troubleshooting

If the Claude AI integration does not work, try the following:

  • No Suggestions Displayed: Verify that the Claude API key and model name are correct in the configuration. Check the ClaudeAIService implementation for errors.
  • 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.
  • Service Registration Errors: Confirm that ClaudeAIService and ClaudeInferenceService are registered in Program.cs.