RuleStack

Configs

Stacks

Compare

Diff

RuleStack

Configs

Stacks

Compare

Diff

Read API

RuleStack

Configs

Stacks

Compare

Diff

Read API

Diff/xin-lai-codespirit-agents ↔ xin-lai-codespirit-cursor-rules-ai-development

Comparison

A · AGENTS.md · xin-lai/CodeSpiritB · Cursor rules · xin-lai/CodeSpirit
What each file covers, counted
DimensionSharedOnly in AOnly in BOverlap
Sections11475%
Commands0200%
Section tags0310%

What each file covers

Sections

1 shared · 14 only in A · 7 only in B
  • − Copilot instructions
  • − General recommendations for working with Aspire
  • − Running the application
  • − Checking resources
  • − Listing integrations
  • − Debugging issues
  • − Other Aspire MCP tools
  • − Playwright MCP server
  • − Updating the app host
  • − Persistent containers
  • − Aspire workload
  • − Official documentation
  • − BMAD AI 工作流
  • − 与 CodeSpirit 规范集成
  • + AI 长任务处理
  • + AiFormFillAttribute 完整参数
  • + AiFieldFillAttribute 参数
  • + LLM 集成
  • + API 密钥管理
  • + 方式一:LLMAssistant(推荐)
  • + Token 控制
  •   获取帮助

Commands

0 shared · 2 only in A · 0 only in B
  • − dotnet tool install --global dotnet-outdated-tool
  • − dotnet-outdated

Section tags

0 shared · 3 only in A · 1 only in B
  • − code-style
  • − agent-behaviour
  • − docs
  • + api

Line diff

+605 added−68 removed34 unchanged5.3% identical
xin-lai/CodeSpirit · AGENTS.md
@@ −1 @@
1# Copilot instructions
 
 
 
 
2 
3This repository is set up to use Aspire. Aspire is an orchestrator for the entire application and will take care of configuring dependencies, building, and running the application. The resources that make up the application are defined in `apphost.cs` including application code and external dependencies.
4 
5## General recommendations for working with Aspire
61. Before making any changes always run the apphost using `aspire run` and inspect the state of resources to make sure you are building from a known state.
71. Changes to the _apphost.cs_ file will require a restart of the application to take effect.
82. Make changes incrementally and run the aspire application using the `aspire run` command to validate changes.
93. Use the Aspire MCP tools to check the status of resources and debug issues.
10 
11## Running the application
12To run the application run the following command:
 
 
 
 
 
 
13 
 
 
 
 
14```
15aspire run
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
16```
17 
18If there is already an instance of the application running it will prompt to stop the existing instance. You only need to restart the application if code in `apphost.cs` is changed, but if you experience problems it can be useful to reset everything to the starting state.
19 
20## Checking resources
21To check the status of resources defined in the app model use the _list resources_ tool. This will show you the current state of each resource and if there are any issues. If a resource is not running as expected you can use the _execute resource command_ tool to restart it or perform other actions.
 
 
 
 
 
 
 
 
 
22 
23## Listing integrations
24IMPORTANT! When a user asks you to add a resource to the app model you should first use the _list integrations_ tool to get a list of the current versions of all the available integrations. You should try to use the version of the integration which aligns with the version of the Aspire.AppHost.Sdk. Some integration versions may have a preview suffix. Once you have identified the correct integration you should always use the _get integration docs_ tool to fetch the latest documentation for the integration and follow the links to get additional guidance.
25 
26## Debugging issues
27IMPORTANT! Aspire is designed to capture rich logs and telemetry for all resources defined in the app model. Use the following diagnostic tools when debugging issues with the application before making changes to make sure you are focusing on the right things.
28 
291. _list structured logs_; use this tool to get details about structured logs.
302. _list console logs_; use this tool to get details about console logs.
313. _list traces_; use this tool to get details about traces.
324. _list trace structured logs_; use this tool to get logs related to a trace
33 
34## Other Aspire MCP tools
 
 
35 
361. _select apphost_; use this tool if working with multiple app hosts within a workspace.
372. _list apphosts_; use this tool to get details about active app hosts.
38 
39## Playwright MCP server
 
40 
41The playwright MCP server has also been configured in this repository and you should use it to perform functional investigations of the resources defined in the app model as you work on the codebase. To get endpoints that can be used for navigation using the playwright MCP server use the list resources tool.
42 
43## Updating the app host
44The user may request that you update the Aspire apphost. You can do this using the `aspire update` command. This will update the apphost to the latest version and some of the Aspire specific packages in referenced projects, however you may need to manually update other packages in the solution to ensure compatibility. You can consider using the `dotnet-outdated` with the users consent. To install the `dotnet-outdated` tool use the following command:
 
45 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
46```
47dotnet tool install --global dotnet-outdated-tool
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
48```
49 
50## Persistent containers
51IMPORTANT! Consider avoiding persistent containers early during development to avoid creating state management issues when restarting the app.
52 
53## Aspire workload
54IMPORTANT! The aspire workload is obsolete. You should never attempt to install or use the Aspire workload.
 
 
 
 
 
 
 
 
 
 
 
 
55 
56## Official documentation
57IMPORTANT! Always prefer official documentation when available. The following sites contain the official documentation for Aspire and related components
58 
591. https://aspire.dev
602. https://learn.microsoft.com/dotnet/aspire
613. https://nuget.org (for specific integration package details)
 
 
 
 
62 
63## BMAD AI 工作流
 
 
 
 
64 
65本项目已集成 BMAD (Breakthrough Method of Agile AI-Driven Development) 完整工作流,用于结构化的软件开发生命周期管理。
 
66 
67### 快速开始
 
 
 
 
 
 
68 
691. **小型任务/Bug 修复** (Quick Flow):
70 - `/quick-spec` - 创建技术规范
71 - `/quick-dev` - 实现变更
72 - `/code-review` - 代码审查
73 
742. **完整功能开发** (Full Flow):
75 - `/product-brief` - 产品需求简报
76 - `/create-prd` - 创建 PRD
77 - `/create-architecture` - 架构设计
78 - `/create-epics-and-stories` - 拆分为 Epic 和 Story
79 - `/sprint-planning` - Sprint 规划
80 - `/dev-story` - 实现 Story
81 - `/code-review` - 代码审查
82 - `/retrospective` - 复盘
83 
84### 与 CodeSpirit 规范集成
85 
86BMAD 工作流已配置为自动遵循 CodeSpirit 的所有开发规范(位于 `.cursor/rules/`)。在使用 BMAD 时:
87 
88- PRD 会自动考虑多租户、多数据库、AI 功能等项目特性
89- 架构设计会遵循依赖注入、缓存策略等规范
90- Story 实现会应用正确的命名约定、DTO 设计、控制器规范等
91- 代码审查会执行 CodeSpirit 特定的审查清单
 
 
 
 
 
92 
93### 获取帮助
 
 
 
 
 
 
 
 
 
 
 
 
94 
95任何时候,输入 `/bmad-help` 可获取上下文相关的指导。
 
 
 
 
 
 
 
 
 
96 
97详细使用指南请参考:
98- **[BMAD 使用教程](Docs/bmad/bmad-tutorial.md)** - 完整的综合教程(推荐新手阅读)
99- [BMAD 工作流指南](Docs/bmad/bmad-workflow-guide.md) - 详细的工作流使用指南
100- [BMAD 团队培训指南](Docs/bmad/bmad-team-guide.md) - 团队培训材料
101- [BMAD 集成技能](.cursor/skills/bmad-integration/SKILL.md) - BMAD 与 CodeSpirit 集成
102- [项目上下文文档](project-context.md) - 项目上下文和规范引用
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
xin-lai/CodeSpirit · .cursor/rules/ai-development.mdc
@@ +1 @@
1---
2description: CodeSpirit AI功能开发规范 - AI表单填充、长任务处理、LLM集成
3globs: *.cs
4alwaysApply: false
5---
6 
7# AI 功能开发规范
8 
9## 📋 目录
 
 
 
 
10 
111. [架构概览](#架构概览)
122. [AI 表单填充](#ai-表单填充)
133. [AI 长任务处理](#ai-长任务处理)
144. [LLM 集成](#llm-集成)
155. [提示词管理](#提示词管理)
166. [错误处理](#错误处理)
177. [性能优化](#性能优化)
188. [安全最佳实践](#安全最佳实践)
19 
20---
21 
22## 架构概览
23 
24```
25┌─────────────────────────────────────────────────────────────────────────┐
26│ 前端 │
27│ ┌─────────────────┐ ┌──────────────────┐ ┌──────────────────┐ │
28│ │ 表单组件 │───▶│ AI填充按钮 │───▶│ 自动生成UI │ │
29│ └─────────────────┘ └──────────────────┘ └──────────────────┘ │
30└───────────────────────────────────┬─────────────────────────────────────┘
31 │ POST /api/{controller}/ai-fill
32 ▼
33┌─────────────────────────────────────────────────────────────────────────┐
34│ 后端 │
35│ ┌─────────────────────────────────────────────────────────────────┐ │
36│ │ AiFormFill中间件(自动拦截 ai-fill 请求) │ │
37│ └────────────────────────────────┬────────────────────────────────┘ │
38│ ▼ │
39│ ┌─────────────────────────────────────────────────────────────────┐ │
40│ │ AiFormFillService → AiFormPromptBuilder → LLM客户端 │ │
41│ └────────────────────────────────┬────────────────────────────────┘ │
42└───────────────────────────────────┼─────────────────────────────────────┘
43 ▼
44┌─────────────────────────────────────────────────────────────────────────┐
45│ LLM服务(OpenAI / 通义千问 / DeepSeek) │
46└─────────────────────────────────────────────────────────────────────────┘
47```
48 
49### 模式选择决策树
50 
51```
52使用哪种AI填充模式?
53├── 需要基于单个字段触发填充?
54│ └── 是 → 字段触发模式 (TriggerField = "FieldName")
55│
56├── 需要用户输入自定义需求一次性填充整个表单?
57│ └── 是 → 全局填充模式 (GlobalFillPrompt = "提示词")
58│
59└── 需要复杂的AI长任务处理(批量生成、进度跟踪)?
60 └── 是 → AI长任务模式 (HeaderOperation + aiForm)
61```
62 
63---
 
64 
65## AI 表单填充
 
66 
67### 快速开始(零代码方案)
 
 
 
68 
69#### 1. 服务注册
70```csharp
71// Program.cs 或 ApiConfiguration
72 
73// 注册 LLM 服务(必需)
74builder.Services.AddLLMServices();
75 
76// 注册 AI 表单填充自动端点(推荐)
77builder.Services.AddAiFormFillEndpoints();
78 
79var app = builder.Build();
80 
81// 启用 AI 填充中间件
82app.UseAiFormFillEndpoints();
83```
84 
85#### 2. DTO 配置
86```csharp
87[AiFormFill(TriggerField = nameof(Topic))]
88public class CreateQuestionDto
89{
90 [Required]
91 [DisplayName("主题")]
92 public string Topic { get; set; } = string.Empty;
93
94 [DisplayName("题目内容")]
95 [AiFieldFill(Priority = 1, CustomDescription = "根据主题生成的题目内容")]
96 public string? Content { get; set; }
97
98 [DisplayName("选项A")]
99 [AiFieldFill(Priority = 2)]
100 public string? OptionA { get; set; }
101}
102```
103 
104**完成!** 系统自动生成 `POST /api/questions/ai-fill` 端点,无需编写任何控制器代码。
105 
106### AiFormFillAttribute 完整参数
107 
108| 属性 | 类型 | 默认值 | 说明 |
109|------|------|--------|------|
110| `TriggerField` | string | "" | 触发字段名称,为空时启用全局模式 |
111| `IgnoreFields` | string[] | [] | 需要忽略的字段列表 |
112| `CustomPromptTemplate` | string | "" | 自定义提示词模板 |
113| `ApiEndpoint` | string | "ai-fill" | API端点路径 |
114| `MaxTokens` | int | 1000 | 最大Token数量 |
115| `EnableCache` | bool | true | 是否启用缓存 |
116| `CacheExpirationMinutes` | int | 30 | 缓存过期时间(分钟) |
117| `GlobalFillPrompt` | string | "使用AI智能优化表单" | 全局模式提示文本 |
118| `UseIndependentLLM` | bool | false | 是否使用独立的LLM配置 |
119| `LLMSettingsKey` | string | "AiFormFillLLM" | 独立LLM配置的设置键名 |
120| `DisableThinking` | bool | true | 是否禁用思考模式 |
121| `ResponseFormatType` | string | "json_object" | 响应格式类型 |
122| `Temperature` | double | 0.1 | 温度参数,控制随机性 |
123| `TopP` | double | 0.9 | Top-p参数,控制多样性 |
124 
125### AiFieldFillAttribute 参数
126 
127| 属性 | 类型 | 默认值 | 说明 |
128|------|------|--------|------|
129| `Enabled` | bool | true | 是否参与AI填充 |
130| `Weight` | int | 1 | 字段权重(影响提示词中的重要性) |
131| `Priority` | int | 0 | 字段填充优先级 |
132| `CustomDescription` | string | "" | 自定义字段描述(自动添加到JSON注释) |
133 
134### 使用模式
135 
136#### 字段触发模式
137用户输入触发字段后,AI 智能填充其他相关字段:
138 
139```csharp
140[AiFormFill(TriggerField = nameof(Topic))]
141public class CreateSurveyDto
142{
143 [Required]
144 [DisplayName("问卷主题")]
145 public string Topic { get; set; } = string.Empty;
146
147 [DisplayName("问卷描述")]
148 [AiFieldFill(Priority = 1, CustomDescription = "基于主题生成的详细描述")]
149 public string? Description { get; set; }
150
151 [DisplayName("目标受众")]
152 [AiFieldFill(Priority = 2)]
153 public string? TargetAudience { get; set; }
154}
155```
156 
157#### 全局填充模式
158用户在表单顶部输入自定义需求,AI 一次性填充整个表单:
159 
160```csharp
161[AiFormFill(GlobalFillPrompt = "描述您想创建的内容")]
162public class CreateContentDto
163{
164 [DisplayName("标题")]
165 public string? Title { get; set; }
166
167 [DisplayName("内容")]
168 public string? Content { get; set; }
169
170 [DisplayName("标签")]
171 public List<string>? Tags { get; set; }
172}
173```
174 
175### 自定义提示词模板
 
176 
177#### 基础模板(自动追加JSON结构)
178```csharp
179[AiFormFill(
180 TriggerField = nameof(Topic),
181 CustomPromptTemplate = "基于主题 '{Topic}' 生成相关内容,要求专业准确")]
182public class CustomPromptDto { }
183```
184 
185#### 完整模板(包含JSON结构,不会重复追加)
186```csharp
187[AiFormFill(
188 TriggerField = nameof(Description),
189 CustomPromptTemplate = @"你是一个目标管理专家。
190 
191用户输入:{Description}
192请优化目标描述,并提取关键信息。
193 
194**返回JSON结构说明:**
195```json
196{
197 ""description"": ""string, 必填。优化后的目标描述"",
198 ""title"": ""string, 必填。提取的简短标题""
199}
200```
201 
202请严格按照上述JSON结构返回。")]
203public class GoalDto { }
204```
 
205 
206> 💡 系统会智能检测模板中是否已包含 JSON 结构说明(关键词:` ```json `),不会重复追加。
 
 
 
 
 
 
 
 
207 
208### 独立 LLM 配置
209 
210为 AI 表单填充配置专用的 LLM 设置:
211 
212```csharp
213[AiFormFill(
214 TriggerField = nameof(Topic),
215 UseIndependentLLM = true,
216 LLMSettingsKey = "AiFormFillLLM",
217 DisableThinking = true,
218 Temperature = 0.1)]
219public class SmartSurveyDto { }
220```
221 
222配置文件:
223```json
224{
225 "AiFormFillLLM": {
226 "ApiBaseUrl": "https://dashscope.aliyuncs.com/compatible-mode/v1",
227 "ApiKey": "your-api-key",
228 "ModelName": "qwq-plus",
229 "TimeoutSeconds": 120,
230 "DisableThinking": true,
231 "ResponseFormatType": "json_object"
232 }
233}
234```
235 
236### 自动化特性
237系统自动完成:
238- ✅ 生成 AI 填充 API 端点(如 `POST /exam/api/Questions/ai-fill`)
239- ✅ 路由自动推断(根据 DTO 命名空间和类名)
240- ✅ 中间件拦截处理
241- ✅ 前端 UI 自动增强(触发字段显示 AI 填充按钮)
242- ✅ 提示词自动构建(分析 DTO 结构、验证规则、CustomDescription)
243- ✅ 响应自动解析(JSON 转 DTO)
244- ✅ 智能 JSON 结构检测(避免重复追加)
245- ✅ 流式模式自动检测和重试
246 
247---
248 
249## AI 长任务处理
250 
251用于耗时较长的 AI 任务(如批量生成、复杂分析等),支持异步处理和进度跟踪:
252 
253### 定义任务 API
254```csharp
255[HttpPost("ai/generate-async")]
256[HeaderOperation("AI智能生成", "aiForm",
257 Icon = "fa-solid fa-magic",
258 StatusApi = "/exam/api/Questions/ai/task-status", // 状态查询 API(必需)
259 PollingInterval = 2000, // 轮询间隔(毫秒)
260 MaxPollingTime = 300000, // 最大轮询时间(5分钟)
261 FormTitle = "生成配置",
262 StepsTitle = "AI生成进度",
263 LogTitle = "生成日志",
264 ResultTitle = "生成结果")]
265[DisplayName("AI智能生成题目")]
266public async Task<ActionResult<ApiResponse<string>>> GenerateQuestionsAsync(
267 [FromBody] GenerateQuestionsRequest request)
268{
269 var taskId = await _aiGeneratorService.GenerateAsync(request);
270 return SuccessResponse(taskId);
271}
272 
273[HttpGet("ai/task-status")]
274[DisplayName("查询任务状态")]
275public async Task<ActionResult<ApiResponse<AiTaskStatus>>> GetTaskStatus(
276 [FromQuery] string taskId)
277{
278 var status = await _aiGeneratorService.GetTaskStatusAsync(taskId);
279 return SuccessResponse(status);
280}
281```
282 
283### 任务状态响应
284```csharp
285public class AiTaskStatus
286{
287 public string Status { get; set; } // "pending", "processing", "completed", "failed"
288 public int Progress { get; set; } // 0-100
289 public List<string> Logs { get; set; } // 日志列表
290 public object? Result { get; set; } // 任务结果
291 public string? ErrorMessage { get; set; } // 错误消息
292}
293```
294 
295---
296 
297## LLM 集成
298 
299### 方式一:LLMAssistant(推荐)
300 
301```csharp
302using CodeSpirit.LLM;
303 
304public class QuestionGeneratorService : IScopedDependency
305{
306 private readonly LLMAssistant _llmAssistant;
307
308 public QuestionGeneratorService(LLMAssistant llmAssistant)
309 {
310 _llmAssistant = llmAssistant;
311 }
312
313 // 基础内容生成
314 public async Task<string> GenerateContentAsync(string prompt)
315 {
316 return await _llmAssistant.GenerateContentAsync(prompt);
317 }
318
319 // 带系统提示词
320 public async Task<string> GenerateWithSystemPromptAsync(
321 string systemPrompt, string userPrompt)
322 {
323 return await _llmAssistant.GenerateContentAsync(systemPrompt, userPrompt);
324 }
325}
326```
327 
328### 方式二:结构化任务处理(推荐复杂场景)
329 
330```csharp
331public class AuditService : IScopedDependency
332{
333 private readonly LLMAssistant _llmAssistant;
334
335 public async Task<AuditResult> AuditQuestionAsync(QuestionDto question)
336 {
337 var result = await _llmAssistant.ProcessStructuredTaskWithTemplateAsync<AuditResult>(
338 "question_audit", // 模板名称
339 new { question }, // 模板数据
340 new StructuredTaskOptions
341 {
342 EnableRetry = true,
343 MaxRetries = 2
344 });
345
346 if (result.IsSuccess)
347 {
348 return result.Result!;
349 }
350
351 throw new BusinessException($"审核失败: {string.Join("; ", result.Errors)}");
352 }
353}
354```
355 
356### 方式三:批量处理
357 
358```csharp
359public async Task<List<AuditResult>> BatchAuditAsync(List<QuestionDto> questions)
360{
361 var batchResult = await _llmAssistant.ProcessBatchStructuredTaskAsync<QuestionDto, AuditResult>(
362 questions,
363 batch => BuildBatchPrompt(batch),
364 new BatchProcessingOptions
365 {
366 BatchSize = 10,
367 MaxRetries = 2,
368 DelayBetweenBatches = TimeSpan.FromSeconds(1),
369 ContinueOnFailure = true
370 });
371
372 return batchResult.SuccessResults
373 .Where(r => r.IsSuccess)
374 .Select(r => r.Result!)
375 .ToList();
376}
377```
378 
379### 增强功能组件
380 
381#### ILLMJsonProcessor - JSON 处理
382```csharp
383private readonly ILLMJsonProcessor _jsonProcessor;
384 
385public async Task<T> ParseAiResponse<T>(string aiResponse) where T : class
386{
387 var result = await _jsonProcessor.ParseStructuredResponseAsync<T>(aiResponse);
388
389 if (result.IsSuccess)
390 {
391 if (result.WasRepaired)
392 {
393 _logger.LogWarning("JSON已自动修复");
394 }
395 return result.Result!;
396 }
397
398 throw new InvalidOperationException($"解析失败: {string.Join("; ", result.Errors)}");
399}
400```
401 
402#### ILLMPromptBuilder - 提示词构建
403```csharp
404private readonly ILLMPromptBuilder _promptBuilder;
405 
406public string BuildComplexPrompt(object data)
407{
408 return _promptBuilder
409 .Reset()
410 .WithSystemPrompt("你是一个专业的助手")
411 .WithTemplate("my_template", data)
412 .WithValidationRules("规则1", "规则2")
413 .WithOutputFormat<MyResult>()
414 .Build();
415}
416```
417 
418### 流式响应
419```csharp
420public async Task GenerateStreamAsync(string prompt, Func<string, Task> onChunk)
421{
422 var client = await _llmClientFactory.CreateClientAsync();
423
424 await client.GenerateContentStreamAsync(prompt, async chunk =>
425 {
426 await onChunk(chunk);
427 });
428}
429```
430 
431---
432 
433## 提示词管理
434 
435### 最佳实践
436- **角色设定清晰**:明确 AI 扮演的角色
437- **任务描述具体**:明确要完成的任务和要求
438- **输出格式明确**:指定 JSON 格式和字段名称
439- **约束条件清晰**:长度限制、验证规则等
440- **提供示例**:复杂场景提供输出示例
441 
442### 提示词模板示例
443```csharp
444public static class PromptTemplates
445{
446 public const string QuestionGenerator = @"你是一个专业的出题专家。
447 
448任务:根据以下信息生成一道高质量的题目。
449 
450主题:{Topic}
451题型:{QuestionType}
452难度:{Difficulty}
453 
454要求:
4551. 题目内容清晰准确,符合{Difficulty}难度
4562. 选项设计合理,避免明显错误
4573. 只有一个正确答案
4584. 题目内容不超过 2000 字符
459 
460输出格式(JSON):
461{{
462 ""Content"": ""题目内容"",
463 ""OptionA"": ""选项A内容"",
464 ""OptionB"": ""选项B内容"",
465 ""OptionC"": ""选项C内容"",
466 ""OptionD"": ""选项D内容"",
467 ""CorrectAnswer"": ""A""
468}}";
469}
470```
471 
472---
473 
474## 错误处理
475 
476### 常见错误类型
477 
478| 错误类型 | 原因 | 处理方式 |
479|---------|------|---------|
480| 401 Unauthorized | API 密钥无效 | 检查配置,更新密钥 |
481| 400 Bad Request | 模型名称错误 | 验证模型名称是否正确 |
482| 429 Too Many Requests | 请求限流 | 添加重试和延迟 |
483| Timeout | 请求超时 | 增加超时时间,拆分请求 |
484| JSON解析失败 | 响应格式不正确 | 使用 ILLMJsonProcessor 自动修复 |
485 
486### 自动错误处理
487系统自动处理:
488- ✅ **流式模式检测**:自动检测"只支持流式模式"的模型并重试
489- ✅ **JSON 自动修复**:截断、括号不匹配、引号错误等
490- ✅ **重试机制**:支持配置重试次数和延迟
491 
492### 错误处理示例
493```csharp
494public async Task<T> SafeGenerateAsync<T>(string prompt) where T : class
495{
496 try
497 {
498 var result = await _llmAssistant.ProcessStructuredTaskWithTemplateAsync<T>(
499 "template",
500 new { prompt },
501 new StructuredTaskOptions { EnableRetry = true, MaxRetries = 3 });
502
503 if (result.IsSuccess)
504 {
505 return result.Result!;
506 }
507
508 _logger.LogError("AI生成失败: {Errors}", string.Join("; ", result.Errors));
509 throw new BusinessException("AI生成失败,请稍后重试");
510 }
511 catch (HttpRequestException ex)
512 {
513 _logger.LogError(ex, "LLM API请求失败");
514 throw new BusinessException("AI服务暂时不可用");
515 }
516 catch (TaskCanceledException ex)
517 {
518 _logger.LogError(ex, "LLM请求超时");
519 throw new BusinessException("AI响应超时,请缩短输入或稍后重试");
520 }
521}
522```
523 
524### 日志配置
525```json
526{
527 "Logging": {
528 "LogLevel": {
529 "CodeSpirit.AiFormFill": "Information",
530 "CodeSpirit.LLM": "Information"
531 }
532 }
533}
534```
535 
536---
537 
538## 性能优化
539 
540### 缓存策略
541```csharp
542[AiFormFill(
543 TriggerField = nameof(Topic),
544 EnableCache = true, // 启用缓存
545 CacheExpirationMinutes = 30 // 30分钟过期
546)]
547```
548 
549**缓存键规则**:包含输入内容的哈希值,相同输入直接返回缓存结果。
550 
551### 批量处理优化
552```csharp
553var options = new BatchProcessingOptions
554{
555 BatchSize = 10, // 每批10条
556 DelayBetweenBatches = TimeSpan.FromSeconds(1), // 批次间延迟
557 MaxRetries = 2, // 最大重试次数
558 ContinueOnFailure = true // 失败时继续处理
559};
560```
561 
562### Token 控制
563- 合理设置 `MaxTokens`,避免过度消耗
564- 使用缓存减少重复请求
565- 长文本分段处理
566- 定期监控 Token 使用量
567 
568### 并发控制
569```csharp
570// ❌ 避免:直接并发大量请求
571var tasks = topics.Select(t => GenerateAsync(t));
572await Task.WhenAll(tasks); // 可能触发限流
573 
574// ✅ 推荐:使用批量处理器
575await _batchProcessor.ProcessBatchWithRetryAsync(topics, ProcessBatch, options);
576```
577 
578---
579 
580## 安全最佳实践
581 
582### API 密钥管理
583```csharp
584// ✅ 使用 Aspire 统一配置(推荐)
585var llmApiKey = builder.AddParameter("llm-ApiKey", secret: true);
586 
587// ✅ 使用环境变量
588.WithEnvironment("LLM__ApiKey", llmApiKey)
589 
590// ❌ 禁止:硬编码密钥
591var apiKey = "sk-xxxxxxxx"; // 绝对禁止!
592```
593 
594### 敏感数据保护
595```csharp
596// 排除敏感字段
597[AiFieldFill(Enabled = false)]
598public string Password { get; set; }
599 
600[AiFieldFill(Enabled = false)]
601public string IdCard { get; set; }
602 
603// 使用 IgnoreFields
604[AiFormFill(
605 TriggerField = nameof(Name),
606 IgnoreFields = new[] { "Password", "IdCard", "BankAccount" }
607)]
608```
609 
610### 输出审核
611- 对 AI 生成内容进行后处理验证
612- 设置合理的内容长度限制
613- 记录审计日志
614- 敏感词过滤
615 
616### 权限控制
617```csharp
618[HttpPost("ai-fill")]
619[Authorize]
620[RequirePermission("Question.AiFill")]
621public async Task<ActionResult> AiFill([FromBody] CreateQuestionDto dto)
622{
623 // AI 填充需要特定权限
624}
625```
626 
627---
628 
629## 注意事项
630 
631- ✅ AI 填充特性仅用于表单填充场景
632- ✅ 长任务处理必须提供状态查询 API
633- ✅ 提示词应明确输出格式为 JSON
634- ✅ 处理 LLM 响应异常(格式错误、超时等)
635- ✅ 敏感数据不要发送给 LLM
636- ✅ 定期审查 AI 生成的内容质量
637- ✅ 使用 `LLMAssistant` 而非直接使用 `ILLMClient`
638- ✅ 复杂场景使用 `ProcessStructuredTaskWithTemplateAsync`
639 
@@ −1 +1 @@
1−# Copilot instructions
1+---
2+description: CodeSpirit AI功能开发规范 - AI表单填充、长任务处理、LLM集成
3+globs: *.cs
4+alwaysApply: false
5+---
26  
3−This repository is set up to use Aspire. Aspire is an orchestrator for the entire application and will take care of configuring dependencies, building, and running the application. The resources that make up the application are defined in `apphost.cs` including application code and external dependencies.
7+# AI 功能开发规范
48  
5−## General recommendations for working with Aspire
6−1. Before making any changes always run the apphost using `aspire run` and inspect the state of resources to make sure you are building from a known state.
7−1. Changes to the _apphost.cs_ file will require a restart of the application to take effect.
8−2. Make changes incrementally and run the aspire application using the `aspire run` command to validate changes.
9−3. Use the Aspire MCP tools to check the status of resources and debug issues.
9+## 📋 目录
1010  
11−## Running the application
12−To run the application run the following command:
11+1. [架构概览](#架构概览)
12+2. [AI 表单填充](#ai-表单填充)
13+3. [AI 长任务处理](#ai-长任务处理)
14+4. [LLM 集成](#llm-集成)
15+5. [提示词管理](#提示词管理)
16+6. [错误处理](#错误处理)
17+7. [性能优化](#性能优化)
18+8. [安全最佳实践](#安全最佳实践)
1319  
20+---
21+ 
22+## 架构概览
23+ 
1424 ```
15−aspire run
25+┌─────────────────────────────────────────────────────────────────────────┐
26+│ 前端 │
27+│ ┌─────────────────┐ ┌──────────────────┐ ┌──────────────────┐ │
28+│ │ 表单组件 │───▶│ AI填充按钮 │───▶│ 自动生成UI │ │
29+│ └─────────────────┘ └──────────────────┘ └──────────────────┘ │
30+└───────────────────────────────────┬─────────────────────────────────────┘
31+ │ POST /api/{controller}/ai-fill
32+ ▼
33+┌─────────────────────────────────────────────────────────────────────────┐
34+│ 后端 │
35+│ ┌─────────────────────────────────────────────────────────────────┐ │
36+│ │ AiFormFill中间件(自动拦截 ai-fill 请求) │ │
37+│ └────────────────────────────────┬────────────────────────────────┘ │
38+│ ▼ │
39+│ ┌─────────────────────────────────────────────────────────────────┐ │
40+│ │ AiFormFillService → AiFormPromptBuilder → LLM客户端 │ │
41+│ └────────────────────────────────┬────────────────────────────────┘ │
42+└───────────────────────────────────┼─────────────────────────────────────┘
43+ ▼
44+┌─────────────────────────────────────────────────────────────────────────┐
45+│ LLM服务(OpenAI / 通义千问 / DeepSeek) │
46+└─────────────────────────────────────────────────────────────────────────┘
1647 ```
1748  
18−If there is already an instance of the application running it will prompt to stop the existing instance. You only need to restart the application if code in `apphost.cs` is changed, but if you experience problems it can be useful to reset everything to the starting state.
49+### 模式选择决策树
1950  
20−## Checking resources
21−To check the status of resources defined in the app model use the _list resources_ tool. This will show you the current state of each resource and if there are any issues. If a resource is not running as expected you can use the _execute resource command_ tool to restart it or perform other actions.
51+```
52+使用哪种AI填充模式?
53+├── 需要基于单个字段触发填充?
54+│ └── 是 → 字段触发模式 (TriggerField = "FieldName")
55+│
56+├── 需要用户输入自定义需求一次性填充整个表单?
57+│ └── 是 → 全局填充模式 (GlobalFillPrompt = "提示词")
58+│
59+└── 需要复杂的AI长任务处理(批量生成、进度跟踪)?
60+ └── 是 → AI长任务模式 (HeaderOperation + aiForm)
61+```
2262  
23−## Listing integrations
24−IMPORTANT! When a user asks you to add a resource to the app model you should first use the _list integrations_ tool to get a list of the current versions of all the available integrations. You should try to use the version of the integration which aligns with the version of the Aspire.AppHost.Sdk. Some integration versions may have a preview suffix. Once you have identified the correct integration you should always use the _get integration docs_ tool to fetch the latest documentation for the integration and follow the links to get additional guidance.
63+---
2564  
26−## Debugging issues
27−IMPORTANT! Aspire is designed to capture rich logs and telemetry for all resources defined in the app model. Use the following diagnostic tools when debugging issues with the application before making changes to make sure you are focusing on the right things.
65+## AI 表单填充
2866  
29−1. _list structured logs_; use this tool to get details about structured logs.
30−2. _list console logs_; use this tool to get details about console logs.
31−3. _list traces_; use this tool to get details about traces.
32−4. _list trace structured logs_; use this tool to get logs related to a trace
67+### 快速开始(零代码方案)
3368  
34−## Other Aspire MCP tools
69+#### 1. 服务注册
70+```csharp
71+// Program.cs 或 ApiConfiguration
3572  
36−1. _select apphost_; use this tool if working with multiple app hosts within a workspace.
37−2. _list apphosts_; use this tool to get details about active app hosts.
73+// 注册 LLM 服务(必需)
74+builder.Services.AddLLMServices();
3875  
39−## Playwright MCP server
76+// 注册 AI 表单填充自动端点(推荐)
77+builder.Services.AddAiFormFillEndpoints();
4078  
41−The playwright MCP server has also been configured in this repository and you should use it to perform functional investigations of the resources defined in the app model as you work on the codebase. To get endpoints that can be used for navigation using the playwright MCP server use the list resources tool.
79+var app = builder.Build();
4280  
43−## Updating the app host
44−The user may request that you update the Aspire apphost. You can do this using the `aspire update` command. This will update the apphost to the latest version and some of the Aspire specific packages in referenced projects, however you may need to manually update other packages in the solution to ensure compatibility. You can consider using the `dotnet-outdated` with the users consent. To install the `dotnet-outdated` tool use the following command:
81+// 启用 AI 填充中间件
82+app.UseAiFormFillEndpoints();
83+```
4584  
85+#### 2. DTO 配置
86+```csharp
87+[AiFormFill(TriggerField = nameof(Topic))]
88+public class CreateQuestionDto
89+{
90+ [Required]
91+ [DisplayName("主题")]
92+ public string Topic { get; set; } = string.Empty;
93+
94+ [DisplayName("题目内容")]
95+ [AiFieldFill(Priority = 1, CustomDescription = "根据主题生成的题目内容")]
96+ public string? Content { get; set; }
97+
98+ [DisplayName("选项A")]
99+ [AiFieldFill(Priority = 2)]
100+ public string? OptionA { get; set; }
101+}
46102 ```
47−dotnet tool install --global dotnet-outdated-tool
103+ 
104+**完成!** 系统自动生成 `POST /api/questions/ai-fill` 端点,无需编写任何控制器代码。
105+ 
106+### AiFormFillAttribute 完整参数
107+ 
108+| 属性 | 类型 | 默认值 | 说明 |
109+|------|------|--------|------|
110+| `TriggerField` | string | "" | 触发字段名称,为空时启用全局模式 |
111+| `IgnoreFields` | string[] | [] | 需要忽略的字段列表 |
112+| `CustomPromptTemplate` | string | "" | 自定义提示词模板 |
113+| `ApiEndpoint` | string | "ai-fill" | API端点路径 |
114+| `MaxTokens` | int | 1000 | 最大Token数量 |
115+| `EnableCache` | bool | true | 是否启用缓存 |
116+| `CacheExpirationMinutes` | int | 30 | 缓存过期时间(分钟) |
117+| `GlobalFillPrompt` | string | "使用AI智能优化表单" | 全局模式提示文本 |
118+| `UseIndependentLLM` | bool | false | 是否使用独立的LLM配置 |
119+| `LLMSettingsKey` | string | "AiFormFillLLM" | 独立LLM配置的设置键名 |
120+| `DisableThinking` | bool | true | 是否禁用思考模式 |
121+| `ResponseFormatType` | string | "json_object" | 响应格式类型 |
122+| `Temperature` | double | 0.1 | 温度参数,控制随机性 |
123+| `TopP` | double | 0.9 | Top-p参数,控制多样性 |
124+ 
125+### AiFieldFillAttribute 参数
126+ 
127+| 属性 | 类型 | 默认值 | 说明 |
128+|------|------|--------|------|
129+| `Enabled` | bool | true | 是否参与AI填充 |
130+| `Weight` | int | 1 | 字段权重(影响提示词中的重要性) |
131+| `Priority` | int | 0 | 字段填充优先级 |
132+| `CustomDescription` | string | "" | 自定义字段描述(自动添加到JSON注释) |
133+ 
134+### 使用模式
135+ 
136+#### 字段触发模式
137+用户输入触发字段后,AI 智能填充其他相关字段:
138+ 
139+```csharp
140+[AiFormFill(TriggerField = nameof(Topic))]
141+public class CreateSurveyDto
142+{
143+ [Required]
144+ [DisplayName("问卷主题")]
145+ public string Topic { get; set; } = string.Empty;
146+
147+ [DisplayName("问卷描述")]
148+ [AiFieldFill(Priority = 1, CustomDescription = "基于主题生成的详细描述")]
149+ public string? Description { get; set; }
150+
151+ [DisplayName("目标受众")]
152+ [AiFieldFill(Priority = 2)]
153+ public string? TargetAudience { get; set; }
154+}
48155 ```
49156  
50−## Persistent containers
51−IMPORTANT! Consider avoiding persistent containers early during development to avoid creating state management issues when restarting the app.
157+#### 全局填充模式
158+用户在表单顶部输入自定义需求,AI 一次性填充整个表单:
52159  
53−## Aspire workload
54−IMPORTANT! The aspire workload is obsolete. You should never attempt to install or use the Aspire workload.
160+```csharp
161+[AiFormFill(GlobalFillPrompt = "描述您想创建的内容")]
162+public class CreateContentDto
163+{
164+ [DisplayName("标题")]
165+ public string? Title { get; set; }
166+
167+ [DisplayName("内容")]
168+ public string? Content { get; set; }
169+
170+ [DisplayName("标签")]
171+ public List<string>? Tags { get; set; }
172+}
173+```
55174  
56−## Official documentation
57−IMPORTANT! Always prefer official documentation when available. The following sites contain the official documentation for Aspire and related components
175+### 自定义提示词模板
58176  
59−1. https://aspire.dev
60−2. https://learn.microsoft.com/dotnet/aspire
61−3. https://nuget.org (for specific integration package details)
177+#### 基础模板(自动追加JSON结构)
178+```csharp
179+[AiFormFill(
180+ TriggerField = nameof(Topic),
181+ CustomPromptTemplate = "基于主题 '{Topic}' 生成相关内容,要求专业准确")]
182+public class CustomPromptDto { }
183+```
62184  
63−## BMAD AI 工作流
185+#### 完整模板(包含JSON结构,不会重复追加)
186+```csharp
187+[AiFormFill(
188+ TriggerField = nameof(Description),
189+ CustomPromptTemplate = @"你是一个目标管理专家。
64190  
65−本项目已集成 BMAD (Breakthrough Method of Agile AI-Driven Development) 完整工作流,用于结构化的软件开发生命周期管理。
191+用户输入:{Description}
192+请优化目标描述,并提取关键信息。
66193  
67−### 快速开始
194+**返回JSON结构说明:**
195+```json
196+{
197+ ""description"": ""string, 必填。优化后的目标描述"",
198+ ""title"": ""string, 必填。提取的简短标题""
199+}
200+```
68201  
69−1. **小型任务/Bug 修复** (Quick Flow):
70− - `/quick-spec` - 创建技术规范
71− - `/quick-dev` - 实现变更
72− - `/code-review` - 代码审查
202+请严格按照上述JSON结构返回。")]
203+public class GoalDto { }
204+```
73205  
74−2. **完整功能开发** (Full Flow):
75− - `/product-brief` - 产品需求简报
76− - `/create-prd` - 创建 PRD
77− - `/create-architecture` - 架构设计
78− - `/create-epics-and-stories` - 拆分为 Epic 和 Story
79− - `/sprint-planning` - Sprint 规划
80− - `/dev-story` - 实现 Story
81− - `/code-review` - 代码审查
82− - `/retrospective` - 复盘
206+> 💡 系统会智能检测模板中是否已包含 JSON 结构说明(关键词:` ```json `),不会重复追加。
83207  
84−### 与 CodeSpirit 规范集成
208+### 独立 LLM 配置
85209  
86−BMAD 工作流已配置为自动遵循 CodeSpirit 的所有开发规范(位于 `.cursor/rules/`)。在使用 BMAD 时:
210+为 AI 表单填充配置专用的 LLM 设置:
87211  
88−- PRD 会自动考虑多租户、多数据库、AI 功能等项目特性
89−- 架构设计会遵循依赖注入、缓存策略等规范
90−- Story 实现会应用正确的命名约定、DTO 设计、控制器规范等
91−- 代码审查会执行 CodeSpirit 特定的审查清单
212+```csharp
213+[AiFormFill(
214+ TriggerField = nameof(Topic),
215+ UseIndependentLLM = true,
216+ LLMSettingsKey = "AiFormFillLLM",
217+ DisableThinking = true,
218+ Temperature = 0.1)]
219+public class SmartSurveyDto { }
220+```
92221  
93−### 获取帮助
222+配置文件:
223+```json
224+{
225+ "AiFormFillLLM": {
226+ "ApiBaseUrl": "https://dashscope.aliyuncs.com/compatible-mode/v1",
227+ "ApiKey": "your-api-key",
228+ "ModelName": "qwq-plus",
229+ "TimeoutSeconds": 120,
230+ "DisableThinking": true,
231+ "ResponseFormatType": "json_object"
232+ }
233+}
234+```
94235  
95−任何时候,输入 `/bmad-help` 可获取上下文相关的指导。
236+### 自动化特性
237+系统自动完成:
238+- ✅ 生成 AI 填充 API 端点(如 `POST /exam/api/Questions/ai-fill`)
239+- ✅ 路由自动推断(根据 DTO 命名空间和类名)
240+- ✅ 中间件拦截处理
241+- ✅ 前端 UI 自动增强(触发字段显示 AI 填充按钮)
242+- ✅ 提示词自动构建(分析 DTO 结构、验证规则、CustomDescription)
243+- ✅ 响应自动解析(JSON 转 DTO)
244+- ✅ 智能 JSON 结构检测(避免重复追加)
245+- ✅ 流式模式自动检测和重试
96246  
97−详细使用指南请参考:
98−- **[BMAD 使用教程](Docs/bmad/bmad-tutorial.md)** - 完整的综合教程(推荐新手阅读)
99−- [BMAD 工作流指南](Docs/bmad/bmad-workflow-guide.md) - 详细的工作流使用指南
100−- [BMAD 团队培训指南](Docs/bmad/bmad-team-guide.md) - 团队培训材料
101−- [BMAD 集成技能](.cursor/skills/bmad-integration/SKILL.md) - BMAD 与 CodeSpirit 集成
102−- [项目上下文文档](project-context.md) - 项目上下文和规范引用
247+---
248+ 
249+## AI 长任务处理
250+ 
251+用于耗时较长的 AI 任务(如批量生成、复杂分析等),支持异步处理和进度跟踪:
252+ 
253+### 定义任务 API
254+```csharp
255+[HttpPost("ai/generate-async")]
256+[HeaderOperation("AI智能生成", "aiForm",
257+ Icon = "fa-solid fa-magic",
258+ StatusApi = "/exam/api/Questions/ai/task-status", // 状态查询 API(必需)
259+ PollingInterval = 2000, // 轮询间隔(毫秒)
260+ MaxPollingTime = 300000, // 最大轮询时间(5分钟)
261+ FormTitle = "生成配置",
262+ StepsTitle = "AI生成进度",
263+ LogTitle = "生成日志",
264+ ResultTitle = "生成结果")]
265+[DisplayName("AI智能生成题目")]
266+public async Task<ActionResult<ApiResponse<string>>> GenerateQuestionsAsync(
267+ [FromBody] GenerateQuestionsRequest request)
268+{
269+ var taskId = await _aiGeneratorService.GenerateAsync(request);
270+ return SuccessResponse(taskId);
271+}
272+ 
273+[HttpGet("ai/task-status")]
274+[DisplayName("查询任务状态")]
275+public async Task<ActionResult<ApiResponse<AiTaskStatus>>> GetTaskStatus(
276+ [FromQuery] string taskId)
277+{
278+ var status = await _aiGeneratorService.GetTaskStatusAsync(taskId);
279+ return SuccessResponse(status);
280+}
281+```
282+ 
283+### 任务状态响应
284+```csharp
285+public class AiTaskStatus
286+{
287+ public string Status { get; set; } // "pending", "processing", "completed", "failed"
288+ public int Progress { get; set; } // 0-100
289+ public List<string> Logs { get; set; } // 日志列表
290+ public object? Result { get; set; } // 任务结果
291+ public string? ErrorMessage { get; set; } // 错误消息
292+}
293+```
294+ 
295+---
296+ 
297+## LLM 集成
298+ 
299+### 方式一:LLMAssistant(推荐)
300+ 
301+```csharp
302+using CodeSpirit.LLM;
303+ 
304+public class QuestionGeneratorService : IScopedDependency
305+{
306+ private readonly LLMAssistant _llmAssistant;
307+
308+ public QuestionGeneratorService(LLMAssistant llmAssistant)
309+ {
310+ _llmAssistant = llmAssistant;
311+ }
312+
313+ // 基础内容生成
314+ public async Task<string> GenerateContentAsync(string prompt)
315+ {
316+ return await _llmAssistant.GenerateContentAsync(prompt);
317+ }
318+
319+ // 带系统提示词
320+ public async Task<string> GenerateWithSystemPromptAsync(
321+ string systemPrompt, string userPrompt)
322+ {
323+ return await _llmAssistant.GenerateContentAsync(systemPrompt, userPrompt);
324+ }
325+}
326+```
327+ 
328+### 方式二:结构化任务处理(推荐复杂场景)
329+ 
330+```csharp
331+public class AuditService : IScopedDependency
332+{
333+ private readonly LLMAssistant _llmAssistant;
334+
335+ public async Task<AuditResult> AuditQuestionAsync(QuestionDto question)
336+ {
337+ var result = await _llmAssistant.ProcessStructuredTaskWithTemplateAsync<AuditResult>(
338+ "question_audit", // 模板名称
339+ new { question }, // 模板数据
340+ new StructuredTaskOptions
341+ {
342+ EnableRetry = true,
343+ MaxRetries = 2
344+ });
345+
346+ if (result.IsSuccess)
347+ {
348+ return result.Result!;
349+ }
350+
351+ throw new BusinessException($"审核失败: {string.Join("; ", result.Errors)}");
352+ }
353+}
354+```
355+ 
356+### 方式三:批量处理
357+ 
358+```csharp
359+public async Task<List<AuditResult>> BatchAuditAsync(List<QuestionDto> questions)
360+{
361+ var batchResult = await _llmAssistant.ProcessBatchStructuredTaskAsync<QuestionDto, AuditResult>(
362+ questions,
363+ batch => BuildBatchPrompt(batch),
364+ new BatchProcessingOptions
365+ {
366+ BatchSize = 10,
367+ MaxRetries = 2,
368+ DelayBetweenBatches = TimeSpan.FromSeconds(1),
369+ ContinueOnFailure = true
370+ });
371+
372+ return batchResult.SuccessResults
373+ .Where(r => r.IsSuccess)
374+ .Select(r => r.Result!)
375+ .ToList();
376+}
377+```
378+ 
379+### 增强功能组件
380+ 
381+#### ILLMJsonProcessor - JSON 处理
382+```csharp
383+private readonly ILLMJsonProcessor _jsonProcessor;
384+ 
385+public async Task<T> ParseAiResponse<T>(string aiResponse) where T : class
386+{
387+ var result = await _jsonProcessor.ParseStructuredResponseAsync<T>(aiResponse);
388+
389+ if (result.IsSuccess)
390+ {
391+ if (result.WasRepaired)
392+ {
393+ _logger.LogWarning("JSON已自动修复");
394+ }
395+ return result.Result!;
396+ }
397+
398+ throw new InvalidOperationException($"解析失败: {string.Join("; ", result.Errors)}");
399+}
400+```
401+ 
402+#### ILLMPromptBuilder - 提示词构建
403+```csharp
404+private readonly ILLMPromptBuilder _promptBuilder;
405+ 
406+public string BuildComplexPrompt(object data)
407+{
408+ return _promptBuilder
409+ .Reset()
410+ .WithSystemPrompt("你是一个专业的助手")
411+ .WithTemplate("my_template", data)
412+ .WithValidationRules("规则1", "规则2")
413+ .WithOutputFormat<MyResult>()
414+ .Build();
415+}
416+```
417+ 
418+### 流式响应
419+```csharp
420+public async Task GenerateStreamAsync(string prompt, Func<string, Task> onChunk)
421+{
422+ var client = await _llmClientFactory.CreateClientAsync();
423+
424+ await client.GenerateContentStreamAsync(prompt, async chunk =>
425+ {
426+ await onChunk(chunk);
427+ });
428+}
429+```
430+ 
431+---
432+ 
433+## 提示词管理
434+ 
435+### 最佳实践
436+- **角色设定清晰**:明确 AI 扮演的角色
437+- **任务描述具体**:明确要完成的任务和要求
438+- **输出格式明确**:指定 JSON 格式和字段名称
439+- **约束条件清晰**:长度限制、验证规则等
440+- **提供示例**:复杂场景提供输出示例
441+ 
442+### 提示词模板示例
443+```csharp
444+public static class PromptTemplates
445+{
446+ public const string QuestionGenerator = @"你是一个专业的出题专家。
447+ 
448+任务:根据以下信息生成一道高质量的题目。
449+ 
450+主题:{Topic}
451+题型:{QuestionType}
452+难度:{Difficulty}
453+ 
454+要求:
455+1. 题目内容清晰准确,符合{Difficulty}难度
456+2. 选项设计合理,避免明显错误
457+3. 只有一个正确答案
458+4. 题目内容不超过 2000 字符
459+ 
460+输出格式(JSON):
461+{{
462+ ""Content"": ""题目内容"",
463+ ""OptionA"": ""选项A内容"",
464+ ""OptionB"": ""选项B内容"",
465+ ""OptionC"": ""选项C内容"",
466+ ""OptionD"": ""选项D内容"",
467+ ""CorrectAnswer"": ""A""
468+}}";
469+}
470+```
471+ 
472+---
473+ 
474+## 错误处理
475+ 
476+### 常见错误类型
477+ 
478+| 错误类型 | 原因 | 处理方式 |
479+|---------|------|---------|
480+| 401 Unauthorized | API 密钥无效 | 检查配置,更新密钥 |
481+| 400 Bad Request | 模型名称错误 | 验证模型名称是否正确 |
482+| 429 Too Many Requests | 请求限流 | 添加重试和延迟 |
483+| Timeout | 请求超时 | 增加超时时间,拆分请求 |
484+| JSON解析失败 | 响应格式不正确 | 使用 ILLMJsonProcessor 自动修复 |
485+ 
486+### 自动错误处理
487+系统自动处理:
488+- ✅ **流式模式检测**:自动检测"只支持流式模式"的模型并重试
489+- ✅ **JSON 自动修复**:截断、括号不匹配、引号错误等
490+- ✅ **重试机制**:支持配置重试次数和延迟
491+ 
492+### 错误处理示例
493+```csharp
494+public async Task<T> SafeGenerateAsync<T>(string prompt) where T : class
495+{
496+ try
497+ {
498+ var result = await _llmAssistant.ProcessStructuredTaskWithTemplateAsync<T>(
499+ "template",
500+ new { prompt },
501+ new StructuredTaskOptions { EnableRetry = true, MaxRetries = 3 });
502+
503+ if (result.IsSuccess)
504+ {
505+ return result.Result!;
506+ }
507+
508+ _logger.LogError("AI生成失败: {Errors}", string.Join("; ", result.Errors));
509+ throw new BusinessException("AI生成失败,请稍后重试");
510+ }
511+ catch (HttpRequestException ex)
512+ {
513+ _logger.LogError(ex, "LLM API请求失败");
514+ throw new BusinessException("AI服务暂时不可用");
515+ }
516+ catch (TaskCanceledException ex)
517+ {
518+ _logger.LogError(ex, "LLM请求超时");
519+ throw new BusinessException("AI响应超时,请缩短输入或稍后重试");
520+ }
521+}
522+```
523+ 
524+### 日志配置
525+```json
526+{
527+ "Logging": {
528+ "LogLevel": {
529+ "CodeSpirit.AiFormFill": "Information",
530+ "CodeSpirit.LLM": "Information"
531+ }
532+ }
533+}
534+```
535+ 
536+---
537+ 
538+## 性能优化
539+ 
540+### 缓存策略
541+```csharp
542+[AiFormFill(
543+ TriggerField = nameof(Topic),
544+ EnableCache = true, // 启用缓存
545+ CacheExpirationMinutes = 30 // 30分钟过期
546+)]
547+```
548+ 
549+**缓存键规则**:包含输入内容的哈希值,相同输入直接返回缓存结果。
550+ 
551+### 批量处理优化
552+```csharp
553+var options = new BatchProcessingOptions
554+{
555+ BatchSize = 10, // 每批10条
556+ DelayBetweenBatches = TimeSpan.FromSeconds(1), // 批次间延迟
557+ MaxRetries = 2, // 最大重试次数
558+ ContinueOnFailure = true // 失败时继续处理
559+};
560+```
561+ 
562+### Token 控制
563+- 合理设置 `MaxTokens`,避免过度消耗
564+- 使用缓存减少重复请求
565+- 长文本分段处理
566+- 定期监控 Token 使用量
567+ 
568+### 并发控制
569+```csharp
570+// ❌ 避免:直接并发大量请求
571+var tasks = topics.Select(t => GenerateAsync(t));
572+await Task.WhenAll(tasks); // 可能触发限流
573+ 
574+// ✅ 推荐:使用批量处理器
575+await _batchProcessor.ProcessBatchWithRetryAsync(topics, ProcessBatch, options);
576+```
577+ 
578+---
579+ 
580+## 安全最佳实践
581+ 
582+### API 密钥管理
583+```csharp
584+// ✅ 使用 Aspire 统一配置(推荐)
585+var llmApiKey = builder.AddParameter("llm-ApiKey", secret: true);
586+ 
587+// ✅ 使用环境变量
588+.WithEnvironment("LLM__ApiKey", llmApiKey)
589+ 
590+// ❌ 禁止:硬编码密钥
591+var apiKey = "sk-xxxxxxxx"; // 绝对禁止!
592+```
593+ 
594+### 敏感数据保护
595+```csharp
596+// 排除敏感字段
597+[AiFieldFill(Enabled = false)]
598+public string Password { get; set; }
599+ 
600+[AiFieldFill(Enabled = false)]
601+public string IdCard { get; set; }
602+ 
603+// 使用 IgnoreFields
604+[AiFormFill(
605+ TriggerField = nameof(Name),
606+ IgnoreFields = new[] { "Password", "IdCard", "BankAccount" }
607+)]
608+```
609+ 
610+### 输出审核
611+- 对 AI 生成内容进行后处理验证
612+- 设置合理的内容长度限制
613+- 记录审计日志
614+- 敏感词过滤
615+ 
616+### 权限控制
617+```csharp
618+[HttpPost("ai-fill")]
619+[Authorize]
620+[RequirePermission("Question.AiFill")]
621+public async Task<ActionResult> AiFill([FromBody] CreateQuestionDto dto)
622+{
623+ // AI 填充需要特定权限
624+}
625+```
626+ 
627+---
628+ 
629+## 注意事项
630+ 
631+- ✅ AI 填充特性仅用于表单填充场景
632+- ✅ 长任务处理必须提供状态查询 API
633+- ✅ 提示词应明确输出格式为 JSON
634+- ✅ 处理 LLM 响应异常(格式错误、超时等)
635+- ✅ 敏感数据不要发送给 LLM
636+- ✅ 定期审查 AI 生成的内容质量
637+- ✅ 使用 `LLMAssistant` 而非直接使用 `ILLMClient`
638+- ✅ 复杂场景使用 `ProcessStructuredTaskWithTemplateAsync`
639+ 
RuleStack

Built by

Kynth Studio

Directory

Configs
Stacks
Compare formats
Diff two configs
Best AGENTS.md examples

Formats

AGENTS.md
CLAUDE.md
Cursor rules
Copilot instructions

Reference

Read API
Corpus health
Privacy Policy
Terms

RuleStack

RuleStack

Built by

Kynth Studio

Directory

Configs
Stacks
Compare formats
Diff two configs
Best AGENTS.md examples

Formats

AGENTS.md
CLAUDE.md
Cursor rules
Copilot instructions

Reference

Read API
Corpus health
Privacy Policy
Terms

RuleStack

RuleStack

Built by

Kynth Studio

Directory

Configs
Stacks
Compare formats
Diff two configs
Best AGENTS.md examples

Formats

AGENTS.md
CLAUDE.md
Cursor rules
Copilot instructions

Reference

Read API
Corpus health
Privacy Policy
Terms

RuleStack