LLM 設定
Doggy 提供圖形化的 LLM 設定管理系統,支援多廠商、多模型、多角色的彈性設定與執行階段動態切換,為 AI 功能提供統一的模型支援。
概述
LLM 設定系統位於 src/Service/Platform/Llm/,借鏡 Symfony AI Bundle 的 Platform 設計理念:
- 多廠商支援:OpenAI、Azure、Anthropic、Ollama、自訂 OpenAI 相容閘道
- 圖形化管理:非 YAML 設定,後台介面動態管理
- 角色分離:設定與用途解耦,角色綁定模型
- 金鑰加密:API Key 加密儲存,前端不接觸
資料模型
LlmProvider(廠商設定)
| 欄位 | 類型 | 說明 |
|---|---|---|
| name | string | 顯示名稱,如 "GPT-4o" |
| provider | string | 廠商識別:openai / anthropic / azure / ollama / custom |
| model | string | 模型名稱:gpt-4o / claude-3-5-sonnet / ... |
| apiKey | encrypted | API Key(加密儲存) |
| apiEndpoint | string | 介面位址(可選) |
| options | JSON | 額外參數:temperature, max_tokens, top_p 等 |
| isEnabled | boolean | 是否啟用 |
| sortOrder | int | 排序 |
LlmRole(角色/用途)
| 欄位 | 類型 | 說明 |
|---|---|---|
| code | string | 角色編碼:view_editor / entity_generation / workflow_analysis / query_assistant / chat / coding |
| label | string | 顯示名稱 |
| providerId | UUID | 綁定的模型設定 |
| systemPrompt | text | 該角色的系統提示詞 |
| options | JSON | 角色級參數覆寫 |
| isEnabled | boolean | 是否啟用 |
角色用途規劃
| 角色 code | 用途 | 建議模型 |
|---|---|---|
| view_editor | 視圖設計器 AI 助手 | gpt-4o / claude-3.5-sonnet |
| entity_generation | AI 輔助實體產生 | gpt-4o-mini |
| workflow_analysis | 工作流程分析與建議 | gpt-4o |
| query_assistant | 自然語言 → 資料查詢 | gpt-4o-mini |
| chat | 通用 AI 對話助手 | gpt-4o-mini |
| coding | 程式碼產生(Twig/JS/PHP) | gpt-4o / claude-3.5-sonnet |
呼叫鏈路
LlmRouter::chatByRole(roleCode, messages, opts)
├─ 查询 LlmRole(code) → 获取绑定的 LlmProvider
├─ LlmGatewayFactory::create(provider) → 实例化适配器
├─ 解密 API Key(LlmEncryptor)
└─ 调用 LLM API(支持工具调用、流式响应)LlmGatewayFactory
根據 LlmProvider.provider 欄位自動路由配接器:
| provider | 配接器 | 說明 |
|---|---|---|
| openai | OpenAiGateway | OpenAI 相容介面 |
| anthropic | AnthropicGateway | Anthropic Claude API |
| azure | AzureGateway | Azure OpenAI |
| ollama | OllamaGateway | 本機 Ollama |
| custom | CustomGateway | 自訂 OpenAI 相容閘道 |
容錯移轉
LlmRouter 支援 chatByRoleWithFallback,當主要廠商失敗時自動降級至備援模型。
管理介面
入口:系統設定 → LLM 設定(/admin/platform/llm-config)
清單頁
- 廠商卡片式展示,一個廠商可對應多個模型變體
- 直接顯示綁定了該模型的角色/用途
- 開關切換啟用/停用
- 拖曳排序
編輯表單
- 名稱、廠商、模型、API Key(加密儲存)、介面位址
- 角色管理(LlmRoleType):角色編碼、系統提示詞、模型綁定
金鑰加密
LlmEncryptor 使用平台加密金鑰對 API Key 進行加解密,金鑰僅儲存於伺服器端,前端不接觸原始 Key:
php
// 存储时
$encrypted = $llmEncryptor->encrypt($apiKey);
// 调用时
$apiKey = $llmEncryptor->decrypt($provider->getApiKey());與 AI 助手整合
AI 助手(見 AI 助手)重複使用 LlmRole/LlmProvider 體系:
前端 → POST /api/admin/ai/chat
→ LlmRouter.chatByRole(roleCode, messages)
→ 查询 LlmRole → LlmGatewayFactory → LLM API- API Key 僅儲存於伺服器端(資料庫加密儲存)
- 模型切換在管理介面完成,無需修改程式碼
- 多廠商由 LlmGatewayFactory 自動路由
相關檔案
| 檔案 | 職責 |
|---|---|
src/Service/Platform/Llm/LlmGatewayInterface.php | 閘道介面 |
src/Service/Platform/Llm/LlmGatewayFactory.php | 配接器工廠 |
src/Service/Platform/Llm/LlmRouter.php | 角色路由 + 容錯移轉 |
src/Service/Platform/Llm/ModelRegistry.php | 模型註冊表 |
src/Service/Platform/LlmEncryptor.php | API Key 加解密 |
src/Entity/Platform/LlmProvider.php | 廠商設定實體 |
src/Entity/Platform/LlmRole.php | 角色設定實體 |
src/Controller/Admin/Platform/LlmConfigController.php | 管理介面控制器 |