| 123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392 |
- using Microsoft.Extensions.Configuration;
- using Microsoft.Extensions.DependencyInjection;
- using Microsoft.Extensions.Logging;
- namespace OASystem.API.OAMethodLib.TokenHubAI;
- public static class TokenHubServiceExtensions
- {
- /// <summary>
- /// 注册 TokenHub 服务到 DI 容器(使用 API Key + 配置委托)
- /// </summary>
- /// <param name="services">服务集合</param>
- /// <param name="apiKey">TokenHub API 密钥</param>
- /// <param name="baseUrl">API 端点地址(可选)</param>
- /// <param name="configure">配置委托</param>
- /// <returns>服务集合</returns>
- public static IServiceCollection AddTokenHubService(
- this IServiceCollection services,
- string apiKey,
- string? baseUrl = null,
- Action<TokenHubServiceOptions>? configure = null)
- {
- var options = new TokenHubServiceOptions();
- configure?.Invoke(options);
- services.AddSingleton<ITokenHubService>(provider =>
- {
- var logger = provider.GetService<ILogger<TokenHubService>>();
- var service = new TokenHubService(apiKey, baseUrl, logger);
- if (options.Timeout.HasValue)
- service.SetTimeout(options.Timeout.Value);
- if (options.MaxRetries > 0)
- {
- service.SetRetryPolicy(
- options.MaxRetries,
- options.InitialRetryDelay ?? TimeSpan.FromSeconds(1),
- options.MaxRetryDelay ?? TimeSpan.FromSeconds(30)
- );
- }
- return service;
- });
- return services;
- }
- /// <summary>
- /// 注册 TokenHub 服务到 DI 容器(使用配置对象)
- /// </summary>
- /// <param name="services">服务集合</param>
- /// <param name="apiKey">TokenHub API 密钥</param>
- /// <param name="baseUrl">API 端点地址(可选)</param>
- /// <param name="options">配置对象</param>
- /// <returns>服务集合</returns>
- public static IServiceCollection AddTokenHubService(
- this IServiceCollection services,
- string apiKey,
- string? baseUrl,
- TokenHubServiceOptions options)
- {
- services.AddSingleton<ITokenHubService>(provider =>
- {
- var logger = provider.GetService<ILogger<TokenHubService>>();
- var service = new TokenHubService(apiKey, baseUrl, logger);
- if (options.Timeout.HasValue)
- service.SetTimeout(options.Timeout.Value);
- if (options.MaxRetries > 0)
- {
- service.SetRetryPolicy(
- options.MaxRetries,
- options.InitialRetryDelay ?? TimeSpan.FromSeconds(1),
- options.MaxRetryDelay ?? TimeSpan.FromSeconds(30)
- );
- }
- return service;
- });
- return services;
- }
- /// <summary>
- /// 从 IConfiguration 注册 TokenHub 服务
- /// </summary>
- /// <param name="services">服务集合</param>
- /// <param name="configuration">应用程序配置</param>
- /// <param name="configSection">配置节名称,默认 "TokenHub"</param>
- /// <returns>服务集合</returns>
- /// <exception cref="InvalidOperationException">当未找到 ApiKey 时抛出</exception>
- public static IServiceCollection AddTokenHubService(
- this IServiceCollection services,
- IConfiguration configuration,
- string configSection = "TokenHub")
- {
- var config = configuration.GetSection(configSection);
- var tokenHubConfig = new TokenHubConfiguration();
- config.Bind(tokenHubConfig);
- if (string.IsNullOrWhiteSpace(tokenHubConfig.ApiKey))
- throw new InvalidOperationException(
- $"未找到 TokenHub API Key 配置: {configSection}:ApiKey");
- // 构建选项
- var options = new TokenHubServiceOptions
- {
- MaxRetries = tokenHubConfig.MaxRetries,
- Timeout = tokenHubConfig.TimeoutSeconds > 0
- ? TimeSpan.FromSeconds(tokenHubConfig.TimeoutSeconds)
- : null,
- InitialRetryDelay = tokenHubConfig.InitialRetryDelaySeconds > 0
- ? TimeSpan.FromSeconds(tokenHubConfig.InitialRetryDelaySeconds)
- : TimeSpan.FromSeconds(1),
- MaxRetryDelay = tokenHubConfig.MaxRetryDelaySeconds > 0
- ? TimeSpan.FromSeconds(tokenHubConfig.MaxRetryDelaySeconds)
- : TimeSpan.FromSeconds(30)
- };
- return services.AddTokenHubService(
- apiKey: tokenHubConfig.ApiKey,
- baseUrl: tokenHubConfig.BaseUrl,
- options: options
- );
- }
- }
- /// <summary>
- /// TokenHub 配置类,用于绑定 appsettings.json 中的配置
- /// </summary>
- /// <remarks>
- /// 配置示例:
- /// <code>
- /// {
- /// "TokenHub": {
- /// "ApiKey": "sk-xxxxxxxx",
- /// "BaseUrl": "https://tokenhub.tencentmaas.com/v1/chat/completions",
- /// "DefaultModel": "hunyuan-2.0-instruct-20251111",
- /// "MaxRetries": 3,
- /// "TimeoutSeconds": 120,
- /// "InitialRetryDelaySeconds": 1,
- /// "MaxRetryDelaySeconds": 30
- /// }
- /// }
- /// </code>
- /// </remarks>
- public class TokenHubConfiguration
- {
- // ============ 必填参数 ============
- /// <summary>
- /// 获取或设置 TokenHub API 密钥(必填)
- /// </summary>
- /// <value>从 TokenHub 控制台获取的 API 密钥</value>
- /// <remarks>
- /// 获取地址:https://console.cloud.tencent.com/tokenhub/
- /// 格式示例:sk-xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx
- /// </remarks>
- public string ApiKey { get; set; } = string.Empty;
- // ============ 基础配置 ============
- /// <summary>
- /// 获取或设置 TokenHub API 端点地址(可选)
- /// </summary>
- /// <value>API 服务的完整 URL</value>
- /// <remarks>
- /// 默认值:https://tokenhub.tencentmaas.com/v1/chat/completions
- /// </remarks>
- public string? BaseUrl { get; set; }
- /// <summary>
- /// 获取或设置默认使用的 AI 模型(可选)
- /// </summary>
- /// <value>模型名称,默认 "hunyuan-2.0-instruct-20251111"</value>
- /// <remarks>
- /// 混元模型:
- /// - hunyuan-2.0-instruct-20251111: 混元 2.0 Instruct(推荐)
- /// - hunyuan-turbo: 混元 Turbo(速度快)
- /// - hunyuan-pro: 混元 Pro(复杂任务)
- /// - hunyuan-lite: 混元 Lite(轻量级)
- ///
- /// 第三方模型:
- /// - glm-5.1: 智谱 GLM-5.1
- /// - deepseek-v3: DeepSeek V3
- /// - deepseek-r1: DeepSeek R1
- /// - minimax-m2.7: MiniMax M2.7
- /// - qwen-2.5-72b: 通义千问 2.5 72B
- /// </remarks>
- public string DefaultModel { get; set; } = "hunyuan-2.0-instruct-20251111";
- // ============ 重试策略配置 ============
- /// <summary>
- /// 获取或设置请求失败时的最大重试次数(可选)
- /// </summary>
- /// <value>重试次数,默认 3,范围 0-10</value>
- /// <remarks>
- /// 0:不重试
- /// 建议生产环境设置为 3-5 次
- /// </remarks>
- public int MaxRetries { get; set; } = 3;
- /// <summary>
- /// 获取或设置请求超时时间(秒)(可选)
- /// </summary>
- /// <value>超时秒数,默认 120,范围 1-600</value>
- /// <remarks>
- /// 实时对话:30-60 秒
- /// 批量处理:120-300 秒
- /// 流式输出:60-120 秒
- /// </remarks>
- public int TimeoutSeconds { get; set; } = 120;
- /// <summary>
- /// 获取或设置首次重试的延迟时间(秒)(可选)
- /// </summary>
- /// <value>延迟秒数,默认 1,范围 0.1-60</value>
- /// <remarks>
- /// 使用指数退避策略:1s, 2s, 4s, 8s, 16s, 30s
- /// </remarks>
- public int InitialRetryDelaySeconds { get; set; } = 1;
- /// <summary>
- /// 获取或设置最大重试延迟时间(秒)(可选)
- /// </summary>
- /// <value>最大延迟秒数,默认 30,范围 1-300</value>
- public int MaxRetryDelaySeconds { get; set; } = 30;
- // ============ 日志配置 ============
- /// <summary>
- /// 获取或设置是否启用日志记录(可选)
- /// </summary>
- /// <value>默认 true</value>
- public bool EnableLogging { get; set; } = true;
- /// <summary>
- /// 获取或设置日志级别(可选)
- /// </summary>
- /// <value>默认 "Information"</value>
- /// <remarks>可选值:Debug, Information, Warning, Error</remarks>
- public string LogLevel { get; set; } = "Information";
- /// <summary>
- /// 获取或设置是否启用性能指标收集(可选)
- /// </summary>
- /// <value>默认 false</value>
- public bool EnableMetrics { get; set; } = false;
- /// <summary>
- /// 获取或设置是否记录请求内容(可选)
- /// </summary>
- /// <value>默认 false,仅开发环境开启</value>
- public bool LogRequestContent { get; set; } = false;
- /// <summary>
- /// 获取或设置是否记录响应内容(可选)
- /// </summary>
- /// <value>默认 false,仅开发环境开启</value>
- public bool LogResponseContent { get; set; } = false;
- // ============ 默认请求参数 ============
- /// <summary>
- /// 获取或设置默认最大输出 Token 数(可选)
- /// </summary>
- /// <value>Token 数量,默认 1024,范围 1-8192</value>
- public int DefaultMaxTokens { get; set; } = 1024;
- /// <summary>
- /// 获取或设置默认温度参数(可选)
- /// </summary>
- /// <value>温度值,默认 0.7,范围 0.0-2.0</value>
- /// <remarks>
- /// 0.0-0.3:确定性输出
- /// 0.4-0.6:平衡模式
- /// 0.7-1.0:创造性模式
- /// 1.0-2.0:高随机性
- /// </remarks>
- public double DefaultTemperature { get; set; } = 0.7;
- /// <summary>
- /// 获取或设置默认 Top-P 参数(可选)
- /// </summary>
- /// <value>Top-P 值,范围 0.0-1.0,null 表示不设置</value>
- public double? DefaultTopP { get; set; }
- /// <summary>
- /// 获取或设置默认频率惩罚(可选)
- /// </summary>
- /// <value>惩罚值,范围 -2.0 到 2.0,null 表示不设置</value>
- public double? DefaultFrequencyPenalty { get; set; }
- /// <summary>
- /// 获取或设置默认存在惩罚(可选)
- /// </summary>
- /// <value>惩罚值,范围 -2.0 到 2.0,null 表示不设置</value>
- public double? DefaultPresencePenalty { get; set; }
- // ============ 安全和权限配置 ============
- /// <summary>
- /// 获取或设置是否启用内容安全过滤(可选)
- /// </summary>
- /// <value>默认 true,建议保持开启</value>
- public bool EnableContentFilter { get; set; } = true;
- /// <summary>
- /// 获取或设置允许使用的模型列表(白名单)(可选)
- /// </summary>
- /// <value>模型名称列表,null 表示不限制</value>
- public List<string>? AllowedModels { get; set; }
- /// <summary>
- /// 获取或设置禁止使用的模型列表(黑名单)(可选)
- /// </summary>
- /// <value>模型名称列表,null 表示不限制</value>
- public List<string>? BlockedModels { get; set; }
- // ============ 缓存配置 ============
- /// <summary>
- /// 获取或设置是否启用响应缓存(可选)
- /// </summary>
- /// <value>默认 false</value>
- public bool EnableCache { get; set; } = false;
- /// <summary>
- /// 获取或设置缓存有效期(秒)(可选)
- /// </summary>
- /// <value>默认 300,范围 60-86400</value>
- public int CacheDurationSeconds { get; set; } = 300;
- /// <summary>
- /// 获取或设置最大缓存条目数(可选)
- /// </summary>
- /// <value>默认 100,范围 1-10000</value>
- public int MaxCacheSize { get; set; } = 100;
- // ============ 高级配置 ============
- /// <summary>
- /// 获取或设置自定义 HTTP 请求头(可选)
- /// </summary>
- public Dictionary<string, string>? CustomHeaders { get; set; }
- /// <summary>
- /// 获取或设置自定义请求参数(可选)
- /// </summary>
- public Dictionary<string, object>? CustomParameters { get; set; }
- /// <summary>
- /// 获取或设置代理服务器地址(可选)
- /// </summary>
- /// <example>"http://proxy.company.com:8080"</example>
- public string? ProxyUrl { get; set; }
- /// <summary>
- /// 获取或设置是否跳过 SSL 证书验证(可选)
- /// </summary>
- /// <value>默认 false,仅测试环境开启</value>
- public bool BypassSSLValidation { get; set; } = false;
- }
- /// <summary>
- /// TokenHub 服务选项(代码配置用)
- /// </summary>
- public class TokenHubServiceOptions
- {
- /// <summary>
- /// 最大重试次数
- /// </summary>
- public int MaxRetries { get; set; } = 3;
- /// <summary>
- /// 请求超时时间
- /// </summary>
- public TimeSpan? Timeout { get; set; }
- /// <summary>
- /// 首次重试延迟
- /// </summary>
- public TimeSpan? InitialRetryDelay { get; set; }
- /// <summary>
- /// 最大重试延迟
- /// </summary>
- public TimeSpan? MaxRetryDelay { get; set; }
- }
|