Skip to content

About

Download files generated by an OpenAI agent directly from DevExpress Blazor AI Chat responses.

Topics

Resources

Stars

0 stars

Watchers

0 watching

Forks

Repository files navigation

Blazor AI Chat — Download Files Generated by an AI Assistant

AI assistants can generate files in response to user messages. In such instances, AI assistant responses may contain links/annotations associated with the generated file(s). This example pre-processes such messages to display custom links routed to an ASP.NET Core minimal API endpoint. When a user clicks a link, the endpoint downloads the requested file from OpenAI and returns it to the browser.

Note

DevExpress AI-powered extensions operate on a "bring your own key" (BYOK) model. DevExpress does not offer a proprietary REST API or bundled language models (LLMs/SLMs).

You can either deploy a self-hosted model or connect to a cloud AI provider and obtain necessary connection parameters (such as endpoint, API key, language model identifier). Configure these parameters at application startup to register an AI client and enable extension functionality.

Warning

This example demonstrates the minimum configuration required to download AI-generated files. As such, the API endpoint does not check authentication or authorization.

In a real application, secure the endpoint against potentially malicious requests. For example, you can add authorization as described in the Microsoft documentation and implement custom resource-based access to ensure users can only download files that they generated themselves.

Implementation Details

  1. Connect the DevExpress Blazor AI Chat component to the OpenAI provider:

  2. Use HostedCodeInterpreterTool to allow the OpenAI Agent to generate files:

    AIAgent agent = openAIClient.GetResponsesClient().AsAIAgent(
        model: openAiServiceSettings.DeploymentName,
        instructions: "You are a helpful assistant that can generate files using code.",
        name: "CodeInterpreterAgent",
        tools: [new HostedCodeInterpreterTool()]
    );
    builder.Services.AddSingleton(agent.AsIChatResponseProvider());

Note

Multiple OpenAI .NET SDK APIs used in this example are marked as experimental. To compile the associated code, suppress the OPENAI001 diagnostic (for example, run #pragma warning disable OPENAI001).

  1. Define a MessageContentTemplate for DxAIChat and process file links in the message as follows (see Index.razor):

    • Find file annotations. Iterate through the message's Contents collection and check the Annotations collection of each content item. OpenAI file links are CitationAnnotation objects. Each object's RawRepresentation property returns a ContainerFileCitationMessageAnnotation object.
    • Build download URLs. ContainerId and FileId uniquely identify the file. Use them as URL route parameters for the downloads path. Build a URL in the following format: downloads/{ContainerId}/{FileId}?filename={Filename}. Note that Filename must be URL-encoded.
    • Replace original links. StartIndex and EndIndex specify the original link position in the message text. Replace this text range with the new URL. Process annotations from the last to first to ensure that each replacement does not shift the positions of the remaining links.
    • Render sanitized HTML. Use a third-party processor to convert Markdown text to HTML and sanitize the result. This example uses Markdig and HtmlSanitizer.
  2. Define a minimal API endpoint that handles requests to the "downloads" path. Validate containerId and fileId route parameters and the filename query parameter. Pass the IDs to the OpenAI Containers API to download the file.

    public static partial class RegexHelper {
        [GeneratedRegex(@"^cntr_[a-z0-9]+$", RegexOptions.IgnoreCase)]
        public static partial Regex ContainerIdRegex();
    
        [GeneratedRegex(@"^cfile_[a-z0-9]+$", RegexOptions.IgnoreCase)]
        public static partial Regex FileIdRegex();
    }
    app.MapGet("/downloads/{containerId}/{fileId}", async (string containerId, string fileId, [FromQuery] string filename) => {
        if(string.IsNullOrWhiteSpace(containerId) || string.IsNullOrWhiteSpace(fileId) || string.IsNullOrWhiteSpace(filename)
            || containerId.Length > 128 || fileId.Length > 128 || filename.Length > 260) {
            return Results.BadRequest();
        }
    
        if(!(RegexHelper.ContainerIdRegex().IsMatch(containerId) && RegexHelper.FileIdRegex().IsMatch(fileId) && filename.IndexOfAny(Path.GetInvalidFileNameChars()) < 0)) {
            return Results.BadRequest();
        }
    
        try {
            BinaryData fileData = await openAIClient.GetContainerClient().DownloadContainerFileAsync(
                containerId,
                fileId);
            var contentType = "application/octet-stream";
            return Results.File(fileData.ToArray(), contentType, filename);
        }
        catch(ClientResultException clientEx) when(clientEx.Status == 404) {
            return Results.NotFound();
        }
        catch {
            return Results.StatusCode(500);
        }
    });

Files to Review

Documentation

Does This Example Address Your Development Requirements/Objectives?

(you will be redirected to DevExpress.com to submit your response)

About

Download files generated by an OpenAI agent directly from DevExpress Blazor AI Chat responses.

Topics

Resources

Stars

0 stars

Watchers

0 watching

Forks

Contributors

Languages