Back to Devexpress

Custom AI-powered Extensions

wpf-405337-ai-powered-extensions-custom-ai-powered-extensions.md

latest3.1 KB
Original Source

Custom AI-powered Extensions

  • Jan 20, 2025
  • 2 minutes to read

The following example creates a custom AI-powered extension (AuthoredStyleExtension) and behavior (AuthoredStyleBehavior).

Run Demo

Create an Extension

The AuthoredStyleExtension is based on the DevExpress ChangeStyleExtension. The example overrides the GetSystemPrompt method to customize the prompt:

csharp
public class AuthoredStyleExtension : ChangeTextExtension<AuthoredStyleRequest> {
    public AuthoredStyleExtension(IServiceProvider serviceProvider) : base(serviceProvider) { }

    protected override string GetSystemPrompt(AuthoredStyleRequest request) =>
        $"Rewrite this text in the {request.Author} style";
}

public class AuthoredStyleRequest : TextRequest {
    public AuthoredStyleRequest(string author, string text) : base(text) {
        Author = author;
    }
    public string Author { get; set; }
}

Create a Custom Behavior

The AuthoredStyleBehavior is based on the DevExpress TextModificationBehavior (the base class for ChangeStyleBehavior, ChangeToneBehavior, etc.):

csharp
class AuthoredStyleBehavior : TextModificationBehavior {
    static AuthoredStyleBehavior() {
        RegisterBehaviorSource<TextEdit, AuthoredStyleBehavior>(te => new TextEditBehaviorSource(te));
        AIExtensionsContainerDesktop.Default.Register<AuthoredStyleRequest, AuthoredStyleExtension>();
    }

    public AuthoredStyleBehavior() {
        AuthoredStyleCommand = CreateCommand<string>(AuthoredStyleAsync);
    }

    ICommand AuthoredStyleCommand { get; set; }

    Task AuthoredStyleAsync(string author) => ExecuteAsync(
        input => new AuthoredStyleRequest(author, input),
        (container, request, token) => {
            var extension = (AuthoredStyleExtension)container.GetExtension(typeof(AuthoredStyleRequest));
            var result = extension.ExecuteAsync(request, token);
            return result;
        });

    protected override ItemInfo BuildItem() {
        return new ItemInfo {
            Caption = "Authored Style",
            Items = new[] { "Mark Twain", "Ernest Hemingway", "Maya Angelou" }.Select(author => new ItemInfo {
                Caption = author,
                Command = AuthoredStyleCommand,
                CommandParameter = author
            }).ToList()
        };
    }
}

Apply a Custom Extension/Behavior to a Text Editor

xaml
<dxe:TextEdit HorizontalAlignment="Left"
              VerticalContentAlignment="Top"
              VerticalScrollBarVisibility="Auto"
              TextWrapping="Wrap" Width="661">
              <dxmvvm:Interaction.Behaviors>
                  <local:AuthoredStyleBehavior/>
              </dxmvvm:Interaction.Behaviors>
</dxe:TextEdit>