Copied RSS Feed

Blazor

AI-Powered Text-to-Flowchart: Convert Text into Diagrams Using OpenAI and Blazor

TL;DR: Build an AI-powered text-to-flowchart converter app using the OpenAI and Blazor Diagram component. Learn how to seamlessly convert text descriptions into visual flowcharts, enhancing productivity and workflow efficiency with the help of cutting-edge AI technology.

Flowcharts are essential tools for visualizing processes, defining workflows, and illustrating systems in both development and business contexts. Manually creating these flowcharts, however, can be time-consuming and labor-intensive. This is where AI comes into play, providing intelligent automation to effortlessly convert textual descriptions into visual flowcharts.

In this blog, we’ll see how to create a smart flowchart app that leverages OpenAI and the Syncfusion Blazor Diagram library for seamless text-to-flowchart conversion.

Let’s dive in!

Prerequisites

Before you begin, ensure your environment is ready with the following:

Workflow overview

  • The user will input a textual description of a process.
  • Then, the input will be sent to OpenAI’s API for processing.
  • OpenAI generates a Mermaid structured data representation of the flowchart.
  • The structured data is parsed and converted into the Blazor Diagram nodes and connectors.
  • Finally, the Blazor Diagram component renders the flowchart visually.

Build AI-powered text-to-flowchart converter with OpenAI and Blazor Diagram Library

Step 1: Create a new Blazor project

First, create a Blazor server app using Visual Studio via Microsoft Templates or the Syncfusion Blazor Extension.

Step 2: Install the Syncfusion Blazor Diagram and themes NuGet in the app

To add the Blazor Diagram component in the app, open the NuGet package manager in Visual Studio (Tools → NuGet Package Manager → Manage NuGet Packages for Solution), search and install the Syncfusion.Blazor.Diagram and Syncfusion.Blazor.Themes NuGet packages.

Alternatively, you can use the following package manager commands to achieve the same.

Install-Package Syncfusion.Blazor.Diagram -Version 27.1.48
Install-Package Syncfusion.Blazor.Themes -Version 27.1.48

Step 3: Register Syncfusion Blazor service

Register the Syncfusion Blazor Service in the ~/Program.cs file of your Blazor app.

using Microsoft.AspNetCore.Components;
using Microsoft.AspNetCore.Components.Web;
using Syncfusion.Blazor;

var builder = WebApplication.CreateBuilder(args);

// Add services to the container.
builder.Services.AddRazorPages();
builder.Services.AddServerSideBlazor();
builder.Services.AddSyncfusionBlazor();

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

Step 4: Configure the AI service

Then, create a service to handle interactions with OpenAI.

public class DiagramOpenAIService
{
    private readonly HttpClient _httpClient;
    private readonly string _apiKey;
    private readonly string _deploymentName;

    /// <summary>
    /// Initializes a new instance of the <see cref="DiagramOpenAIService"/> class with the specified HTTP client, API key, and deployment details.
    /// </summary>
    public DiagramOpenAIService(HttpClient httpClient, string apiKey, string deploymentName)
    {
        _httpClient = httpClient;
        _apiKey = apiKey;
        _deploymentName = deploymentName;
    }
}

To configure the AI service, add the following settings to the ~/Program.cs file in your Blazor app.

using Microsoft.AspNetCore.Components;
using Microsoft.AspNetCore.Components.Web;
using Syncfusion.Blazor;

var builder = WebApplication.CreateBuilder(args);

....

builder.Services.AddSyncfusionBlazor();

string apiKey = "api-key";
string deploymentName = "deployment-name";
string endpoint = "end point url";

builder.Services.AddTransient<DiagramOpenAIService>(service =>
{
    var httpClientFactory = new HttpClient { BaseAddress = new Uri(endpoint) };
    return new DiagramOpenAIService(httpClientFactory, apiKey, deploymentName);
});

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

Refer to the configuration details below. 

  • apiKey: “OpenAI or Azure OpenAI API Key”;
  • deploymentName: “Azure OpenAI deployment name”;
  • endpoint: “Azure OpenAI deployment end point URL”;

For Azure OpenAI, first, deploy an Azure OpenAI service resource and model, then values for apiKey, deploymentName, and endpoint will be provided to you after deployment.

If you are using OpenAI, create an API key and place it at apiKey, leaving the endpoint as “”. The value for deploymentName is the model you wish to use (e.g., gpt-3.5-turbo, gpt-4, etc.).

Step 5: Add stylesheet and script resources

The theme stylesheet and script can be accessed from NuGet through static web assets. Reference the stylesheet and script in the <head> and <body> of the main page as follows:

  • For the .NET 8 and .NET 9 Blazor server apps, include it in the ~Components/App.razor file.

_Layout.cshtml (or) App.razor

<head>
    ....
    <link href="_content/Syncfusion.Blazor.Themes/tailwind.css" rel="stylesheet" />
</head>

    ….
<body>
    ....
    <script src="_content/Syncfusion.Blazor.Core/scripts/syncfusion-blazor.min.js" type="text/javascript"></script>
</body>

Step 6: Configure the Blazor Diagram for visualization

The Blazor Diagram is a feature-rich architecture diagram library for visualizing, creating, and editing interactive diagrams. Its intuitive API and rich feature set make it easy to create, style, and manage flowcharts.

In the Index.razor file, define and configure the Blazor Diagram component, which will serve as the core tool of our flowchart generator.

@using Syncfusion.Blazor.Diagram

<SfDiagramComponent @ref="@Diagram" @bind-Connectors="@connectors" Created="Created" HistoryChanged="@OnHistoryChange" ScrollChanged="ScrollChanged" Height="700px" Width="100%" @bind-Nodes="@nodes" SelectionSettings="@selectionSettings" NodeCreating="OnNodeCreating" ConnectorCreating="OnConnectorCreating" DragDrop="DragDropEvent" @bind-InteractionController="@DiagramTool">
    <RulerSettings>
        <HorizontalRuler>
        </HorizontalRuler>
        <VerticalRuler>
        </VerticalRuler>
    </RulerSettings>
    <SnapSettings>
        <HorizontalGridLines LineColor="#e0e0e0 " LineIntervals="@GridLineIntervals">
        </HorizontalGridLines>
        <VerticalGridLines LineColor="#e0e0e0" LineIntervals="@GridLineIntervals">
        </VerticalGridLines>
    </SnapSettings>
    <PageSettings MultiplePage="true">
    </PageSettings>
    <ContextMenuSettings Show="true" ContextMenuItemClicked="@ContextMenuItemClickHandler"></ContextMenuSettings>
    <Layout Type="LayoutType.Flowchart" @bind-HorizontalSpacing="@HorizontalSpacing" @bind-VerticalSpacing="@VerticalSpacing">
    </Layout>
</SfDiagramComponent>

This configuration sets up a responsive diagram with a flowchart layout, ruler settings, snap settings, scroll settings, and some event bindings.

Step 7: Create an AI assist dialog for user input

Let’s create a dialog for AI-assisted flowchart generation with suggested prompts, a textbox to get user input, and a button to send the user input to OpenAI.

@using Syncfusion.Blazor.Buttons
@using Syncfusion.Blazor.Popups
@using Syncfusion.Blazor.Inputs
@inject DiagramOpenAIService ChatGptService

<SfFab IconCss="e-icons e-ai-chat" Content="AI Assist" OnClick="OnFabClicked"></SfFab>
<SfDialog Width="570px" IsModal="true" ShowCloseIcon="true" CssClass="custom-dialog" Visible="@ShowAIAssistDialog">
    <DialogTemplates>
        <Header> <span class="e-icons e-ai-chat" style="color: black; font-size: 16px;"></span> AI Assist</Header>
        <Content>
            <p style="margin-bottom: 10px;">Suggested Prompts</p>
            <SfButton style="flex: 1; overflow: visible; border-radius: 8px;margin-bottom: 10px;" @>

Then, set up event callbacks and handlers to manage user interactions, such as entering a prompt and triggering the conversion of text to a flowchart.

public bool ShowAIAssistDialog;
public string OpenAIPrompt;

public void OnFabClicked()
{
    ShowAIAssistDialog = !ShowAIAssistDialog;
}
private void DialogClose(Object args)
{
    ShowAIAssistDialog = false;
}
public async void GenerateFlowchart(string value)
{
    OpenAIPrompt = value;
    await GenerateTextToFlowchart();
}
public async Task GenerateTextToFlowchart()
{
      ShowAIAssistDialog = false; 
      await ChatGptService.ConvertTextToFlowchart(OpenAIPrompt, Diagram);
}

Step 8: Integrating OpenAI for text-to-flowchart conversion

Finally, implement the ConvertTextToFlowchart method in the DiagramOpenAIService, which will act as the main driver for transforming AI-generated text into a flowchart using the Blazor Diagram API.

public class DiagramOpenAIService
{
    /// <summary>
    /// Gets the response from OpenAI for the provided prompt and generates a flowchart diagram.
    /// </summary>
    public async Task ConvertTextToFlowchart(string prompt, SfDiagramComponent Diagram)
    {
        var requestContent = new
        {
            messages = new[]
            {
                new { role = "system", content = "You are an expert in creating mind map diagram data sources. Generate a structured data source for a mind map based on the user's query, using tab indentation to indicate hierarchy. The root parent should have no indentation, while each subsequent child level should be indented by one tab space. Avoid using any symbols such as '+' or '-' before any level of data." },
                new { role = "user", content = $"Generate the mindmap diagram data source for the following prompt: {prompt}." },
            },
            max_tokens = 500,
            temperature = 0.9
        };

        var requestBody = new StringContent(JsonSerializer.Serialize(requestContent), Encoding.UTF8, "application/json");
        var requestMessage = new HttpRequestMessage(HttpMethod.Post, $"openai/deployments/{_deploymentName}/chat/completions?api-version=2023-05-15")
        {
            Content = requestBody
        };
        // Add the API key to the request headers.
        requestMessage.Headers.Add("api-key", _apiKey);
        var response = await _httpClient.SendAsync(requestMessage);

        // Ensure the response is valid.
        response.EnsureSuccessStatusCode();

        // Parse the response content.
        var responseContent = await response.Content.ReadAsStringAsync();
        var jsonResponse = JsonDocument.Parse(responseContent);
        var mermaidData = jsonResponse.RootElement.GetProperty("choices")[0].GetProperty("message").GetProperty("content").GetString();
        // Load the diagram from mermaid text       
        await Diagram.LoadDiagramFromMermaidAsync(mermaidData);
    }
}

The core function ConvertTextToFlowchart sends a request to the OpenAI API with a user-initiated prompt to generate Mermaid structured flowchart data from text descriptions. It then uses the Blazor Diagram’s LoadDiagramFromMermaidAsync method to render the flowchart.

After executing the above code examples, we’ll get the output that resembles the following image. 

Building an AI-powered text-to-flowchart converter using the Blazor Diagram Library

GitHub reference

For more details, refer to creating an AI-powered smart text-to-flowchart converter using the Blazor Diagram GitHub demo.

Syncfusion Blazor components can be transformed into stunning and efficient web apps.

Conclusion

Thanks for reading! In this blog, we’ve explored how to build an AI-powered smart text-to-flowchart converter app using the  Blazor Diagram component. With this, you can automate the conversion of text descriptions into visual flowcharts, enhancing efficiency and productivity. This AI-powered solution simplifies flowchart creation, making it faster and more intuitive for developers and businesses. Try it out and streamline your workflow today!

Existing customers can download the latest version of Essential Studio® from the License and Downloads page. If you are not a customer, try our 30-day free trial to check out these new features.

If you have questions, contact us through our support forumsupport portal, or feedback portal.  We are always happy to assist you!

Meet the Author

Sarathkumar V

Sarathkumar is a Product Manager for Diagram and HeatMap products at Syncfusion. He has been a .NET developer since 2013. He is specialized in WPF, UWP, Xamarin and other .Net frameworks.