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.
-
Connect the DevExpress Blazor AI Chat component to the OpenAI provider:
- Install the NuGet packages listed in the following help topic: Manual AI Services Integration - OpenAI.
- Install Microsoft.Agents.AI.OpenAI and DevExpress.AIIntegration.Agents packages to enable AI agent integration.
- Specify your OpenAI API key and model name in the
OpenAISettingssection of theappsettings.jsonfile (KeyandDeploymentNamesettings). If your code omits these settings, the application throws an exception at startup.
-
Use
HostedCodeInterpreterToolto 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).
-
Define a
MessageContentTemplateforDxAIChatand process file links in the message as follows (see Index.razor):- Find file annotations. Iterate through the message's
Contentscollection and check theAnnotationscollection of each content item. OpenAI file links areCitationAnnotationobjects. Each object'sRawRepresentationproperty returns aContainerFileCitationMessageAnnotationobject. - Build download URLs.
ContainerIdandFileIduniquely identify the file. Use them as URL route parameters for thedownloadspath. Build a URL in the following format:downloads/{ContainerId}/{FileId}?filename={Filename}. Note thatFilenamemust be URL-encoded. - Replace original links.
StartIndexandEndIndexspecify 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.
- Find file annotations. Iterate through the message's
-
Define a minimal API endpoint that handles requests to the "downloads" path. Validate
containerIdandfileIdroute parameters and thefilenamequery 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); } });
(you will be redirected to DevExpress.com to submit your response)