### Run the Example Application
Source: https://github.com/iotsharp/antdesignxblazor/blob/main/README.md
Instructions to run the local example application located in the 'examples/AntDesign.X.Blazor.Demo/' directory.
```powershell
dotnet run --project external/AntDesignXBlazor/examples/AntDesign.X.Blazor.Demo/AntDesign.X.Blazor.Demo.csproj
```
--------------------------------
### Install and Register AntDesign.X.Blazor Services
Source: https://context7.com/iotsharp/antdesignxblazor/llms.txt
Install the AntDesignX.Blazor NuGet package and register its services in Program.cs. Configure base address, API keys, paths, and timeouts for AI services.
```csharp
// Install
dotnet add package AntDesignX.Blazor
// Program.cs
using AntDesign.X;
builder.Services.AddAntDesign();
builder.Services.AddAntDesignX(options =>
{
options.BaseAddress = new Uri("https://api.deepseek.com");
options.DefaultHeaders["Authorization"] = "Bearer sk-xxxxxxxx";
options.ChatPath = "/v1/chat/completions"; // Default value
options.AgentPath = "/v1/agents/run"; // Default value
options.Timeout = TimeSpan.FromSeconds(120);
});
```
--------------------------------
### Complete AI Workbench Example in Blazor
Source: https://context7.com/iotsharp/antdesignxblazor/llms.txt
This comprehensive example integrates various AntDesign.X.Blazor components to create a functional AI workbench. It includes conversation management, message display, prompt suggestions, and theme toggling. Ensure XChatStore is registered in your DI container.
```razor
@page "/chat"
@using AntDesign.X.Components
@inject XChatStore Chat
@implements IDisposable
@if (!Chat.Messages.Any())
{
}
else
{
}
@code {
private string theme = "light";
private string? draft;
private string? currentKey;
private readonly List conversations = [];
private readonly List quickPrompts =
[
new() { Key = "q1", Title = "总结这篇文章", Icon = "file-text" },
new() { Key = "q2", Title = "帮我写单元测试", Icon = "code" },
new() { Key = "q3", Title = "解释这个错误", Icon = "bug" },
];
private readonly Dictionary roleConfigs = new()
{
["user"] = new() { Placement = XBubblePlacement.End, AvatarIcon = "user", Variant = XBubbleVariant.Filled },
["assistant"] = new() { Placement = XBubblePlacement.Start, AvatarIcon = "robot", Variant = XBubbleVariant.Outlined, Markdown = true },
};
protected override void OnInitialized()
{
Chat.Changed += () => InvokeAsync(StateHasChanged);
NewConversation();
}
private void NewConversation()
{
var key = Guid.NewGuid().ToString("N");
conversations.Insert(0, new XConversationItem
{
Key = key,
Title = "新会话",
Icon = "message",
UpdatedAt = DateTimeOffset.UtcNow,
});
currentKey = key;
Chat.ConversationKey = key;
Chat.ReplaceMessages([]);
}
private Task SwitchConversation(XConversationItem item)
{
currentKey = item.Key;
Chat.ConversationKey = item.Key;
Chat.ReplaceMessages([]);
return Task.CompletedTask;
}
private Task DeleteConversation(XConversationItem item)
{
conversations.Remove(item);
if (currentKey == item.Key) NewConversation();
return Task.CompletedTask;
}
private Task ApplyPrompt(XPromptItem prompt)
{
draft = prompt.Title;
return Task.CompletedTask;
}
private async Task Submit(XSenderRequest request)
{
await Chat.SubmitAsync(request);
}
private void ToggleTheme() => theme = theme == "light" ? "dark" : "light";
public void Dispose() => Chat.Changed -= () => InvokeAsync(StateHasChanged);
}
```
--------------------------------
### Add AntDesignX.Blazor Package
Source: https://github.com/iotsharp/antdesignxblazor/blob/main/news-release-v1.0.0.md
Install the AntDesignX.Blazor package using the .NET CLI.
```powershell
dotnet add package AntDesignX.Blazor
```
--------------------------------
### Parsing Streaming Data with XStreamReader
Source: https://context7.com/iotsharp/antdesignxblazor/llms.txt
Shows how to use XStreamReader to parse SSE or newline-delimited stream data. Includes an example of extracting content from OpenAI SSE responses.
```csharp
// 也可直接解析流
await using var stream = await httpClient.GetStreamAsync("https://api.example.com/stream");
await foreach (var chunk in XStreamReader.ReadAsync(stream, new XStreamReaderOptions
{
Mode = XStreamReadMode.Sse,
ParseJsonData = true,
}))
{
if (chunk.IsDone) break;
if (XStreamReader.TryReadOpenAiContent(chunk, out var text))
Console.Write(text);
}
```
--------------------------------
### XPrompts Component Usage
Source: https://context7.com/iotsharp/antdesignxblazor/llms.txt
Displays a collection of preset prompts with support for nesting, tags, disabling, and click events. Useful for guiding user input on welcome pages.
```razor
@using AntDesign.X.Components
@code {
private readonly List prompts =
[
new()
{
Key = "coding",
Title = "编程助手",
Icon = "code",
Tag = "热门",
Children =
[
new() { Key = "debug", Title = "帮我调试这段代码", Icon = "bug" },
new() { Key = "review", Title = "代码审查", Icon = "audit" },
],
},
new()
{
Key = "write",
Title = "写作助手",
Icon = "edit",
Description = "撰写邮件、报告、文案",
},
new()
{
Key = "premium",
Title = "高级功能(会员)",
Icon = "crown",
Disabled = true,
},
];
private Task OnPromptSelect(XPromptItem item)
{
Console.WriteLine($"选中提示词:{item.Title}");
// 可将 item.Title 填入 XSender
return Task.CompletedTask;
}
}
```
--------------------------------
### Run AntDesignX.Blazor Demo Application
Source: https://github.com/iotsharp/antdesignxblazor/blob/main/news-release-v1.0.0.md
Clone the repository and run the demo project to explore the full AI workbench features.
```powershell
git clone https://github.com/IoTSharp/AntDesignXBlazor.git
dotnet run --project AntDesignXBlazor/examples/AntDesign.X.Blazor.Demo/AntDesign.X.Blazor.Demo.csproj
```
--------------------------------
### XWelcome Component Usage
Source: https://context7.com/iotsharp/antdesignxblazor/llms.txt
Serves as the welcome screen for an AI workbench, displaying a title, description, and optional extra content like quick action buttons. Used for empty state guidance before a session begins.
```razor
@using AntDesign.X.Components
@code {
private string? draft;
}
```
--------------------------------
### Include AntDesign.X.Blazor CSS and JS
Source: https://context7.com/iotsharp/antdesignxblazor/llms.txt
Include the necessary CSS and JavaScript files for AntDesign.Blazor and AntDesign.X.Blazor in your host file (_Host.cshtml or index.html). Mermaid.js is optional for XMermaid.
```html
```
--------------------------------
### Making Custom SSE Requests with IXRequestClient
Source: https://context7.com/iotsharp/antdesignxblazor/llms.txt
Demonstrates how to use IXRequestClient to send custom Server-Sent Events (SSE) requests to OpenAI-compatible endpoints. Handles chunked responses and errors using callbacks.
```csharp
// 直接使用 IXRequestClient 发起自定义 SSE 请求
@inject IXRequestClient RequestClient
var handle = await RequestClient.RequestAsync(new XRequestOptions
{
RequestUri = new Uri("/v1/chat/completions", UriKind.Relative),
Method = HttpMethod.Post,
Stream = true,
StreamMode = XStreamReadMode.Sse,
Body = new
{
model = "deepseek-chat",
stream = true,
messages = new[]
{
new { role = "user", content = "解释什么是 SSE" },
},
},
OnChunk = async chunk =>
{
if (XStreamReader.TryReadOpenAiContent(chunk, out var delta) &&
!string.IsNullOrEmpty(delta))
{
Console.Write(delta); // 增量打字机输出
}
},
OnError = async ctx =>
{
Console.WriteLine($"请求错误 [{ctx.StatusCode}]:{ctx.Exception.Message}");
},
OnCompleted = async ctx =>
{
Console.WriteLine($"请求完成,RequestId={ctx.RequestId}");
},
});
// 等待流结束
await handle.Completion;
```
--------------------------------
### Use XProvider for Theming
Source: https://context7.com/iotsharp/antdesignxblazor/llms.txt
Wrap your AI components with XProvider to manage global themes. Switch between light and dark themes using the 'Theme' property and inject custom CSS variables via 'Tokens'.
```razor
@using AntDesign.X.Components
@code {
private readonly XThemeTokens DarkTokens = new() {
PrimaryColor = "#1677ff",
ColorBgBubbleAi = "#1a1a2e",
ColorTextBubbleAi = "#e0e0e0",
ColorBgChat = "#0f0f1a",
BorderRadius = "12px",
};
}
```
--------------------------------
### Basic XBubble Component Usage
Source: https://github.com/iotsharp/antdesignxblazor/blob/main/README.md
Demonstrates the basic usage of the XBubble component with a light theme, avatar, header, and markdown content.
```razor
```
--------------------------------
### Include AntDesign and AntDesign.X.Blazor Stylesheets and Scripts
Source: https://github.com/iotsharp/antdesignxblazor/blob/main/README.md
Link the necessary CSS and JavaScript files for AntDesign and AntDesign.X.Blazor in your Blazor application's index.html or _Layout.cshtml.
```html
```
--------------------------------
### Basic XBubble Component Usage
Source: https://github.com/iotsharp/antdesignxblazor/blob/main/news-release-v1.0.0.md
Demonstrates the basic usage of the XBubble component within an XProvider for theming. Ensure Ant Design X components are imported.
```razor
@using AntDesign.X
@using AntDesign.X.Components
```
--------------------------------
### Full Input Interaction Loop with XBubbleList and XSender
Source: https://github.com/iotsharp/antdesignxblazor/blob/main/README.md
Implements a complete input interaction loop using XBubbleList to display messages and XSender for user input, attachments, and actions.
```razor
```
--------------------------------
### Reference AntDesign.X.Blazor Project Locally
Source: https://github.com/iotsharp/antdesignxblazor/blob/main/README.md
If developing locally within the repository, use a project reference to include AntDesign.X.Blazor.
```xml
```
--------------------------------
### Configure and Display Global Notifications
Source: https://context7.com/iotsharp/antdesignxblazor/llms.txt
Set up the XNotification component in your layout for global notifications. Inject IXNotificationService to configure notification settings and open/close notifications with various statuses and options.
```razor
@* Layout.razor — 放置通知宿主 *@@using AntDesign.X.Components
@* 在任意页面注入服务并推送通知 *@
@inject IXNotificationService NotificationService
@code {
protected override async Task OnInitializedAsync()
{
NotificationService.Configure(maxCount: 5, defaultDuration: TimeSpan.FromSeconds(4));
// 推送成功通知
await NotificationService.OpenAsync(new XNotificationItem
{
Title = "操作成功",
Description = "文件已上传并处理完毕",
Status = XSemanticStatus.Success,
Icon = "check-circle",
Closable = true,
});
// 推送错误通知(永久显示直到手动关闭)
var item = await NotificationService.OpenAsync(new XNotificationItem
{
Key = "upload-error",
Title = "上传失败",
Description = "网络超时,请稍后重试",
Status = XSemanticStatus.Error,
Duration = TimeSpan.Zero, // 不自动关闭
});
// 稍后手动关闭
await Task.Delay(8000);
await NotificationService.CloseAsync("upload-error");
}
}
```
--------------------------------
### Using XAgentStore for Agent Task Tracking in Blazor
Source: https://context7.com/iotsharp/antdesignxblazor/llms.txt
Integrates XAgentStore to track messages, thoughts, tool calls, and sources within an agent run. Requires injecting XAgentStore and handling its Changed event for UI updates.
```razor
@using AntDesign.X.Components
@inject XAgentStore Agent
@implements IDisposable
@code {
private string? prompt;
protected override void OnInitialized()
{
Agent.AgentKey = "research-agent";
Agent.Changed += () => InvokeAsync(StateHasChanged);
}
private async Task OnRun(XSenderRequest request)
{
await Agent.RunAsync(new XAgentRequest
{
Prompt = request.Text,
Attachments = request.Attachments,
Metadata = new Dictionary
{
["session_id"] = Guid.NewGuid().ToString("N"),
["user_lang"] = "zh-CN",
},
});
}
private Task OnToolAction(string key)
{
var tool = Agent.ToolCalls.FirstOrDefault(t => t.Key == key);
Console.WriteLine($"工具调用:{tool?.Name},参数:{tool?.Arguments}");
return Task.CompletedTask;
}
public void Dispose() => Agent.Changed -= () => InvokeAsync(StateHasChanged);
}
```
--------------------------------
### XThoughtChain Component Usage
Source: https://context7.com/iotsharp/antdesignxblazor/llms.txt
Visualizes an AI's reasoning process as an ordered list of steps. Supports collapsing, nested sub-steps, and status-based icons and styles (Processing, Success, Warning, Error).
```razor
@using AntDesign.X.Components
@code {
private readonly List thoughts =
[
new()
{
Key = "search",
Title = "检索相关文档",
Description = "共找到 42 篇相关资料",
Status = XSemanticStatus.Success,
Children =
[
new() { Key = "doc1", Title = "Blazor 官方文档", Status = XSemanticStatus.Success },
new() { Key = "doc2", Title = "AntDesign.Blazor 源码", Status = XSemanticStatus.Success },
],
},
new()
{
Key = "analyze",
Title = "分析内容",
Description = "正在归纳核心要点…",
Status = XSemanticStatus.Processing,
},
new()
{
Key = "generate",
Title = "生成回答",
Status = XSemanticStatus.Default,
},
];
private Task OnThoughtClick(XThoughtItem item)
{
Console.WriteLine($"点击步骤:{item.Title}(状态:{item.Status})");
return Task.CompletedTask;
}
}
```
--------------------------------
### Handle User Input and Message Submission
Source: https://github.com/iotsharp/antdesignxblazor/blob/main/README.md
Provides the C# code to handle user submissions from the XSender component, adding messages to the list and clearing the draft.
```csharp
private string? draft;
private readonly List attachments = [];
private Task Submit(XSenderRequest request)
{
messages.Add(new XBubbleItem
{
Role = "You",
Placement = XBubblePlacement.End,
AvatarIcon = "user",
Content = request.Text,
Attachments = request.Attachments
});
draft = string.Empty;
return Task.CompletedTask;
}
```
--------------------------------
### Render Markdown with Code Highlighting and Mermaid
Source: https://context7.com/iotsharp/antdesignxblazor/llms.txt
Use XMarkdown to render Markdown content with integrated code highlighting and copy functionality. XMermaid can be used separately for diagram rendering.
```razor
@using AntDesign.X.Components
@code {
private const string markdownText = @"## 快速排序算法
时间复杂度:**O(n log n)**
```csharp
int[] QuickSort(int[] arr)
{
if (arr.Length <= 1) return arr;
var pivot = arr[arr.Length / 2];
var left = arr.Where(x => x < pivot).ToArray();
var middle = arr.Where(x => x == pivot).ToArray();
var right = arr.Where(x => x > pivot).ToArray();
return QuickSort(left).Concat(middle).Concat(QuickSort(right)).ToArray();
}
```
";
private const string csharpCode = @"var store = new XChatStore(requestClient, options);
store.Changed += () => InvokeAsync(StateHasChanged);
await store.SubmitAsync(new XSenderRequest { Text = "你好" });
";
private const string mermaidDef = @"sequenceDiagram
用户->>XSender: 输入消息
XSender->>XChatStore: SubmitAsync()
XChatStore->>AI服务: SSE 流式请求
AI服务-->>XChatStore: 增量 chunk
XChatStore-->>XBubbleList: Changed 事件
";
}
```
--------------------------------
### Configure XSender Message Input Component
Source: https://context7.com/iotsharp/antdesignxblazor/llms.txt
Configure the XSender component for AI chat input, supporting features like multi-line text, attachments, voice input, custom actions, and flexible send modes. Ensure necessary using directives are included.
```razor
@using AntDesign.X.Components
@using Microsoft.AspNetCore.Components.Forms
@code {
private string? draft;
private bool _loading;
private readonly List attachments = [];
private readonly List senderActions =
[
new() { Key = "translate", Icon = "translation", Label = "翻译", Tooltip = "翻译内容" },
new() { Key = "clear", Icon = "clear", Tooltip = "清空", Danger = true },
];
private async Task OnSubmit(XSenderRequest request)
{
if (string.IsNullOrWhiteSpace(request.Text)) return;
_loading = true;
// 发送 request.Text 和 request.Attachments 到后端…
await Task.Delay(2000); // 模拟 AI 响应
_loading = false;
}
private void OnCancel() => _loading = false;
private Task OnFilesSelected(IReadOnlyList files)
{
foreach (var file in files)
{
attachments.Add(new XAttachmentItem
{
Name = file.Name,
Size = file.Size,
ContentType = file.ContentType,
Status = XFileCardStatus.Done,
});
}
return Task.CompletedTask;
}
private Task OnAttachmentRemove(string id)
{
attachments.RemoveAll(a => a.Id == id);
return Task.CompletedTask;
}
}
```
--------------------------------
### Include Mermaid for XMermaid Component
Source: https://github.com/iotsharp/antdesignxblazor/blob/main/README.md
If using the XMermaid component, include the Mermaid.js library from a CDN in your HTML.
```html
```
--------------------------------
### Manage Chat State with XChatStore
Source: https://context7.com/iotsharp/antdesignxblazor/llms.txt
Utilize XChatStore for managing chat conversations, handling SSE streaming requests, message lists, loading states, and retries. Subscribe to the Changed event for UI updates.
```razor
@using AntDesign.X.Components
@inject XChatStore Chat
@implements IDisposable
@if (Chat.LastError is not null)
{
错误:@Chat.LastError.Message
}
@code {
private string? draft;
private readonly Dictionary roleConfigs = new()
{
["user"] = new() { Placement = XBubblePlacement.End, AvatarIcon = "user", Header = "我" },
["assistant"] = new() { Placement = XBubblePlacement.Start, AvatarIcon = "robot", Header = "AI", Markdown = true },
};
protected override void OnInitialized()
{
Chat.ConversationKey = "my-session";
Chat.Changed += () => InvokeAsync(StateHasChanged);
}
private async Task OnSubmit(XSenderRequest request)
{
await Chat.SubmitAsync(request);
}
public void Dispose() => Chat.Changed -= () => InvokeAsync(StateHasChanged);
}
```
--------------------------------
### Configure Services for AntDesignX.Blazor
Source: https://github.com/iotsharp/antdesignxblazor/blob/main/news-release-v1.0.0.md
Register Ant Design and AntDesignX services in your Blazor application's service collection.
```csharp
builder.Services.AddAntDesign();
builder.Services.AddAntDesignX();
```
--------------------------------
### Render Chat Message List with XBubbleList
Source: https://context7.com/iotsharp/antdesignxblazor/llms.txt
Use XBubbleList to render a list of chat messages. It supports unified configuration for roles using RoleConfigs, allowing consistent styling for different message senders.
```razor
@using AntDesign.X.Components
@code {
private readonly List messages =
[
new() { Role = "user", Content = "Hello, introduce yourself", Status = XMessageStatus.Success },
new() { Role = "assistant", Content = "I am an AI assistant, how can I help you?", Markdown = true, Status = XMessageStatus.Success },
new() { Role = "assistant", Content = "", Loading = true, Status = XMessageStatus.Loading },
];
private readonly Dictionary roleConfigs = new()
{
["user"] = new()
{
Placement = XBubblePlacement.End,
AvatarIcon = "user",
Variant = XBubbleVariant.Filled,
Header = "Me",
},
["assistant"] = new()
{
Placement = XBubblePlacement.Start,
AvatarIcon = "robot",
Variant = XBubbleVariant.Outlined,
Header = "Assistant",
Markdown = true,
},
};
private Task HandleBubbleAction(string key) => HandleAction(key);
private Task HandleAction(string key)
{
Console.WriteLine($"Bubble action: {key}");
return Task.CompletedTask;
}
}
```
--------------------------------
### Configure XConversations Conversation List Component
Source: https://context7.com/iotsharp/antdesignxblazor/llms.txt
Implement the XConversations component to display a list of chat conversations. Supports grouping, active state highlighting, inline renaming, delete confirmation, and custom menu actions. Ensure necessary using directives are included.
```razor
@using AntDesign.X.Components
@code {
private string? activeKey;
private readonly List conversations =
[
new()
{
Key = "conv-1",
Title = "如何使用 Blazor?",
Group = "今天",
Icon = "message",
UpdatedAt = DateTimeOffset.UtcNow,
},
new()
{
Key = "conv-2",
Title = "AI 组件库选型",
Group = "昨天",
Icon = "robot",
Count = 12,
UpdatedAt = DateTimeOffset.UtcNow.AddDays(-1),
},
new()
{
Key = "conv-3",
Title = "已归档会话",
Group = "上周",
Disabled = true,
},
];
private Task OnSelectConversation(XConversationItem item)
{
Console.WriteLine($"切换会话:{item.Title}");
return Task.CompletedTask;
}
private Task OnRename(XConversationRenameRequest req)
{
var item = conversations.FirstOrDefault(c => c.Key == req.Key);
if (item is not null)
{
var index = conversations.IndexOf(item);
conversations[index] = item with { Title = req.Title };
}
return Task.CompletedTask;
}
private Task OnDelete(XConversationItem item)
{
conversations.Remove(item);
return Task.CompletedTask;
}
}
```
--------------------------------
### Display Single Chat Bubble with XBubble
Source: https://context7.com/iotsharp/antdesignxblazor/llms.txt
Use XBubble to render individual chat messages. Supports Markdown rendering, attachments, typewriter effects, and action buttons. Configure placement, avatar, header, and status.
```razor
@using AntDesign.X.Components
@code {
private string markdownContent = "**AI Answer:** This is a `Markdown` content\n\n```csharp\nConsole.WriteLine(\"Hello\");\n```";
private bool isStreaming = false;
private XMessageStatus messageStatus = XMessageStatus.Success;
private readonly List bubbleActions =
[
new() { Key = "copy", Icon = "copy", Tooltip = "Copy" },
new() { Key = "like", Icon = "like", Tooltip = "Like" },
new() { Key = "retry", Icon = "reload", Tooltip = "Retry", Danger = false },
];
private Task HandleAction(string key)
{
Console.WriteLine($"Bubble action: {key}");
return Task.CompletedTask;
}
}
```
=== COMPLETE CONTENT === This response contains all available snippets from this library. No additional content exists. Do not make further requests.