Skip to content

Conversation

@weibaohui
Copy link
Owner

No description provided.

- Add AiGenerateModal component for natural language YAML generation
- Implement AIGenerate API endpoint in yaml_editor controller
- Register AI generation route in cluster routes
- Integrate AI button in EditorPanel with modal interface
- Provide example prompts for common K8s resources (Nginx, Redis, MySQL, Node.js)
- Support YAML validation and auto-formatting
- Use existing AI service infrastructure for LLM integration

Key features:
- Natural language to YAML conversion
- Real-time preview of generated YAML
- Copy and confirmation options
- Loading states and error handling
- Seamless integration with Monaco editor
将AI生成YAML功能的路由从集群路由(/k8s/plugins/yaml_editor/ai/generate)移至管理路由(/mgm/plugins/yaml_editor/ai/generate),以符合功能的管理属性。前端相应更新API调用地址,并使用统一的fetcher工具进行请求。
清理AI生成模态组件中的console.log语句和多余空行,保持代码简洁
修正AI生成模态框中API响应处理逻辑,移除不必要的JSON.stringify调用并正确解析响应数据结构。使用类型化的接口定义确保类型安全,避免潜在的运行时错误。
@coderabbitai
Copy link
Contributor

coderabbitai bot commented Jan 26, 2026

📝 Walkthrough

Summary by CodeRabbit

发布说明

  • 新功能

    • 新增AI辅助YAML生成功能,支持基于自然语言描述生成YAML并在对话中预览、复制与应用
    • YAML编辑器新增“AI 生成”按钮,一键生成、复制并将结果注入编辑器
  • 功能调整

    • 原日志分析相关入口已调整为以YAML生成为主的AI功能接口

✏️ Tip: You can customize this high-level summary in your review settings.

Walkthrough

新增 AI 辅助 YAML 生成功能:前端添加 AiGenerateModal 并在编辑器集成,后端移除旧日志端点并新增 POST /mgm/plugins/ai/chat/yaml/generate,包含提示词模板与相应的请求/响应类型及 Swagger 文档更新。

Changes

内聚体 / 文件(s) 变更摘要
AI YAML 生成 UI 组件
ui/src/components/Amis/custom/YamlEditor/components/AiGenerateModal.tsx
新增 React 模态组件,包含 prompt 输入、示例、生成/复制/确认逻辑、加载与错误处理,默认导出 AiGenerateModal
编辑器集成
ui/src/components/Amis/custom/YamlEditor/components/EditorPanel.tsx
引入并展示 AI 生成按钮,管理 aiModalVisible 状态,将生成结果通过回调注入 monaco 编辑器。
AI 提示词常量
pkg/plugins/modules/ai/constants/ai_prompt.go
移除 AIPromptTypeLog,新增 AIPromptTypeYamlGenerate 常量。
提示词控制器选项
pkg/plugins/modules/ai/controller/ai_prompt.go
将“日志分析”选项替换为“YAML生成”。
内置提示词模板
pkg/plugins/modules/ai/models/ai_prompt.go
移除日志分析内置提示,新增两条 YAML 生成内置提示模板。
控制器与 API 实现
pkg/plugins/modules/ai/controller/chat.go, pkg/plugins/modules/ai/route/mgm_api.go
移除旧的 Log 处理,新增 YamlGenerate 处理器与 YamlGenerateRequest/YamlGenerateResponse 类型;注册 POST /mgm/plugins/ai/chat/yaml/generate 路由。
Swagger 文档
pkg/plugins/modules/swagger/docs.go
新增 controller.YamlGenerateRequest / controller.YamlGenerateResponse 定义;调整/新增相关 chat 日志与 YAML 生成端点文档。

Sequence Diagram(s)

sequenceDiagram
    participant User as 用户
    participant Modal as AiGenerateModal<br/>前端
    participant Editor as EditorPanel
    participant Server as 后端API
    participant AI as AI服务

    User->>Modal: 输入生成提示并点击生成
    Modal->>Server: POST /mgm/plugins/ai/chat/yaml/generate { prompt }
    Server->>Server: 获取并渲染 YAML 生成提示模板
    Server->>AI: 调用 AI Chat 无历史上下文
    AI->>Server: 返回文本(含 YAML)
    Server->>Server: 去除 Markdown 三反引号等标记
    Server-->>Modal: 响应 YamlGenerateResponse { yaml }
    Modal->>Modal: 显示生成的 YAML
    User->>Modal: 点击“使用”
    Modal->>Editor: onGenerateSuccess(yaml)
    Editor->>Editor: monaco.setValue(yaml)
Loading

预计代码审查工作量

🎯 4 (复杂) | ⏱️ ~50 分钟

可能相关的PR

  • PR #428: 与 YamlEditor 前端集成直接相关,修改相同编辑器组件及 AI 生成 UI。
  • PR #407: 涉及 AI 插件后端修改(控制器/路由/提示词),与本次后端变更高度重合。
  • PR #438: 对 AI chat 控制器和提示类型的调整与本次新增/替换的端点与提示类型存在交集。

诗句

🐰 提示轻敲键盘,YAML 花开成行,
生成一瞬成稿,复制就把它藏。
兔子点点确认,编辑器里闪亮,
新端点替旧路,AI 与我共忙。

🚥 Pre-merge checks | ✅ 1 | ❌ 2
❌ Failed checks (1 warning, 1 inconclusive)
Check name Status Explanation Resolution
Docstring Coverage ⚠️ Warning Docstring coverage is 0.00% which is insufficient. The required threshold is 80.00%. Write docstrings for the functions missing them to satisfy the coverage threshold.
Description check ❓ Inconclusive PR描述为空,无法验证是否与变更集相关。 建议添加PR描述,说明该功能的目的、实现方式和使用方法,以帮助审阅者更好地理解变更。
✅ Passed checks (1 passed)
Check name Status Explanation
Title check ✅ Passed PR标题准确地总结了主要变更:添加使用AI生成YAML的功能,与所有提交的代码变更高度相关。

✏️ Tip: You can configure your own custom pre-merge checks in the settings.

✨ Finishing touches
  • 📝 Generate docstrings
🧪 Generate unit tests (beta)
  • Create PR with unit tests
  • Post copyable unit tests in a comment
  • Commit unit tests in branch feature/ai-yaml-generation

Thanks for using CodeRabbit! It's free for OSS, and your support helps us grow. If you like it, consider giving us a shout-out.

❤️ Share

Comment @coderabbitai help to get the list of available commands and usage tips.

Copy link
Contributor

@coderabbitai coderabbitai bot left a comment

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Actionable comments posted: 3

🤖 Fix all issues with AI agents
In `@pkg/plugins/modules/yaml_editor/controller/controller.go`:
- Around line 29-47: After parsing into aiGenerateRequest (variable req) using
c.ShouldBindJSON, add a non-empty validation for req.Prompt and return early
with an error response (e.g., via amis.WriteJsonError) if it's blank; this
should be placed before building the prompt string (variable prompt) so the
handler does not call the AI with an empty prompt, and ensure the error message
clearly indicates the prompt is required.
- Around line 49-53: The code creates a background context (ctx :=
context.Background()) before calling
service.GetChatService().ChatWithCtxNoHistory which ignores client cancellation
and timeouts; change to derive ctx from the request (use the incoming gin
context request context, e.g. c.Request.Context()), wrap it with a sensible
timeout using context.WithTimeout and defer the cancel, then pass that ctx into
ChatWithCtxNoHistory so the AI call respects client cancellations and the
configured timeout.

In `@ui/src/components/Amis/custom/YamlEditor/components/AiGenerateModal.tsx`:
- Around line 44-76: handleGenerate can be called repeatedly while a request is
in progress, causing duplicate requests; add a guard at the start of
handleGenerate that returns immediately if loading is true (use the existing
loading state variable) so the function exits when a request is in flight,
preserving the existing validation (prompt.trim()) logic and ensuring
setLoading(true) only runs when no request is active.

- Remove AI generation logic from yaml_editor plugin
- Add YamlGenerate method to ai plugin controller
- Register /k8s/plugins/ai/yaml/generate route in ai cluster routes
- Update frontend to call new AI plugin API endpoint
- Add proper type interfaces for API response handling
- Import strings package for YAML cleaning operations

Benefits:
- Better separation of concerns
- AI functionality centralized in ai plugin
- Reuses existing AI service infrastructure
- Maintains type safety without @ts-ignore

Changes:
- pkg/plugins/modules/ai/controller/chat.go: Add YamlGenerate method
- pkg/plugins/modules/ai/route/mgm_api.go: Register yaml/generate route
- pkg/plugins/modules/yaml_editor/controller/controller.go: Remove AI generation
- pkg/plugins/modules/yaml_editor/route/route.go: Remove AI route
- ui/src/components/Amis/custom/YamlEditor/components/AiGenerateModal.tsx: Update API path
将YAML生成API路由从集群路由移至管理路由,以匹配前端调用的端点路径。
将/k8s/plugins/ai/yaml/generate更正为/mgm/plugins/ai/chat/yaml/generate,以保持API端点命名一致性并修复路由映射错误。
将硬编码的YAML生成提示词提取为内置提示词模板,便于统一管理和维护。同时更新API路由路径以符合规范,使用模板渲染机制动态生成提示词内容。
清理不再使用的日志分析功能,包括删除对应的常量定义、路由、内置提示模板以及控制器方法。为保持代码库的整洁和可维护性,移除未使用的代码。同时,在类型选项列表中添加了“YAML生成”类型。
更新YAML生成接口的路由路径,从/k8s/plugins/ai/yaml/generate改为/mgm/plugins/ai/chat/yaml/generate
在Swagger文档中添加日志智能问答(/mgm/plugins/ai/chat/log/ask)和日志智能总结(/mgm/plugins/ai/chat/log/summary)接口
添加YAML生成接口(/mgm/plugins/ai/chat/yaml/generate)到Swagger文档
添加controller.ResourceData、controller.YamlGenerateRequest和controller.YamlGenerateResponse的类型定义
Copy link
Contributor

@coderabbitai coderabbitai bot left a comment

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Actionable comments posted: 2

🤖 Fix all issues with AI agents
In `@pkg/plugins/modules/ai/controller/chat.go`:
- Around line 449-471: In YamlGenerate, add the same AI-plugin enabled check
used elsewhere by calling
plugins.ManagerInstance().IsRunning(modules.PluginNameAI) and return an amis
JSON error if it is not running, and replace the use of context.Background()
when calling service.GetChatService().ChatWithCtxNoHistory with the
request-aware context from amis.GetContextWithUser(c) so user identity and
cancellation propagate; locate these changes around the YamlGenerate function
where templateStr is rendered and before calling ChatWithCtxNoHistory.

In `@pkg/plugins/modules/swagger/docs.go`:
- Around line 10276-10303: Swagger shows two "in: body" parameters (data and
question) which violates OpenAPI 2.0; update the handler annotation so LogAsk in
pkg/plugins/modules/ai/controller/chat.go uses a single body parameter that
contains both fields (e.g. controller.ResourceData with Data and Question),
remove the extra `in: body` parameter annotation, and regenerate the Swagger
docs so the generated docs (pkg/plugins/modules/swagger/docs.go) only contain
one body parameter for the /mgm/plugins/ai/chat/log/ask POST.
🧹 Nitpick comments (2)
pkg/plugins/modules/ai/controller/chat.go (2)

473-478: Markdown 代码块标记清理可考虑大小写变体

当前逻辑使用 strings.TrimPrefix 区分大小写,但 AI 模型可能返回 \``YAML```Yaml` 等变体。

♻️ 可选优化:使用大小写不敏感的处理
 	// 清理可能存在的 markdown 代码块标记
 	result = strings.TrimSpace(result)
-	result = strings.TrimPrefix(result, "```yaml")
-	result = strings.TrimPrefix(result, "```")
+	if strings.HasPrefix(strings.ToLower(result), "```yaml") {
+		result = result[7:] // len("```yaml") == 7
+	} else if strings.HasPrefix(result, "```") {
+		result = result[3:]
+	}
 	result = strings.TrimSuffix(result, "```")
 	result = strings.TrimSpace(result)

480-493: 建议使用定义的响应类型以保持一致性

已定义 YamlGenerateResponse 结构体,但实际返回使用的是 response.H{"yaml": result}。虽然两者产生相同的 JSON 结构,但使用定义的类型更具类型安全性且与 Swagger 文档保持一致。

♻️ 可选:使用定义的类型
-	amis.WriteJsonData(c, response.H{
-		"yaml": result,
-	})
+	amis.WriteJsonData(c, YamlGenerateResponse{
+		Yaml: result,
+	})

将日志智能问答接口的两个独立请求参数 `data` 和 `question` 合并为一个名为 `request` 的单一参数,以简化 API 调用。
在 YamlGenerate 方法中添加 AI 插件启用状态检查,并统一使用用户上下文。
@weibaohui weibaohui merged commit 7d95c12 into main Jan 26, 2026
6 checks passed
@weibaohui weibaohui deleted the feature/ai-yaml-generation branch January 26, 2026 14:59
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

2 participants