using System; using System.IO; using System.Text.Json; namespace AI { /// /// AI 服务配置 /// public class AISettings { /// /// 模型 ID /// public string ModelId { get; set; } = string.Empty; /// /// API Key /// public string ApiKey { get; set; } = string.Empty; /// /// API Endpoint(OpenAI 兼容接口地址) /// public string Endpoint { get; set; } = string.Empty; /// /// 从 DLL 所在目录旁的 ai-settings.json 加载配置。 /// 若文件不存在,抛出 FileNotFoundException。 /// public static AISettings Load() { string baseDir = AppContext.BaseDirectory; string configPath = Path.Combine(baseDir, "ai-settings.json"); if (!File.Exists(configPath)) { throw new FileNotFoundException( $"AI 配置文件未找到,请在以下位置创建 ai-settings.json:{configPath}\n" + "文件格式示例:\n" + "{\n" + " \"ModelId\": \"deepseek-v3\",\n" + " \"ApiKey\": \"sk-xxx\",\n" + " \"Endpoint\": \"https://dashscope.aliyuncs.com/compatible-mode/v1\"\n" + "}", configPath); } string json = File.ReadAllText(configPath); var settings = JsonSerializer.Deserialize(json, new JsonSerializerOptions { PropertyNameCaseInsensitive = true }); if (settings == null) { throw new InvalidOperationException("ai-settings.json 解析失败,请检查 JSON 格式。"); } if (string.IsNullOrWhiteSpace(settings.ModelId)) throw new InvalidOperationException("ai-settings.json 中 ModelId 不能为空。"); if (string.IsNullOrWhiteSpace(settings.ApiKey)) throw new InvalidOperationException("ai-settings.json 中 ApiKey 不能为空。"); if (string.IsNullOrWhiteSpace(settings.Endpoint)) throw new InvalidOperationException("ai-settings.json 中 Endpoint 不能为空。"); return settings; } } }