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 | 管理界面控制器 |