146 Commits

Author SHA1 Message Date
ccnetcore
1ada6360d4 feat: 完成意心ai3.4版本发布 2026-01-24 17:55:42 +08:00
ccnetcore
21b7ef4d74 feat: 完成全站深色主题改造 2026-01-24 17:28:12 +08:00
ccnetcore
9a87b41027 Merge branch 'ai-hub' into ai-hub-dark 2026-01-24 17:13:33 +08:00
Gsh
886cc3155f fix: 用量查看优化 2026-01-24 16:03:03 +08:00
Gsh
020ad797f2 Merge remote-tracking branch 'origin/ai-hub' into ai-hub 2026-01-24 15:48:30 +08:00
Gsh
1d5bca773f fix: 用量查看优化 2026-01-24 15:05:24 +08:00
ccnetcore
6b86957556 fix: 修复工具调用用量关联错误并优化细节配置
- 修复前端工具调用中用量统计先后顺序导致未正确绑定的问题
- 优化聊天代理指令文案,补充平台知识库优先策略说明
- 调整聊天列表滚动条样式,提升界面体验
- 移除未使用的 VITE_BUILD_COMPRESS 类型声明
2026-01-24 01:16:38 +08:00
ccnetcore
caa90cc227 feat: 今日模型使用统计返回模型图标信息
为 GetTodayModelUsage 接口补充模型图标数据,新增 ModelTodayUsageDto.IconUrl 字段
通过 ModelManager 查询已启用模型的 IconUrl 并映射到结果中
同时统一部分代码格式,提升可读性
2026-01-23 22:13:51 +08:00
chenchun
87c93534a5 fix: 静态文件中间件允许未知文件类型并设置默认 Content-Type 2026-01-23 16:43:35 +08:00
chenchun
b8c79ac61c feat: 新增近24小时每小时与今日模型使用量统计接口及实现 2026-01-23 14:50:46 +08:00
ccnetcore
2db8d6e699 style: 控制台暗黑主题改造 2026-01-23 00:01:54 +08:00
ccnetcore
0983837ff7 fix: 正确处理 Anthropic 流式响应结束标记
在解析流式数据时增加对 [DONE] 结束标记的判断,避免在流结束后继续反序列化数据导致异常。
2026-01-22 00:36:38 +08:00
ccnetcore
efa948154f style: 首页暗黑主题改造 2026-01-21 22:58:57 +08:00
ccnetcore
e8c1111cbc Merge branch 'ai-hub' into ai-hub-dark
# Conflicts:
#	Yi.Ai.Vue3/.claude/settings.local.json
2026-01-21 21:49:47 +08:00
ccnetcore
c9c92dcf97 Merge branch 'ai-hub' into ai-hub-dark 2026-01-21 21:49:00 +08:00
Gsh
f2c2c60127 fix: 号池管理交互优化,移动端兼容 2026-01-20 00:38:37 +08:00
Gsh
d280cc6d35 fix: 增加号池快捷切换 2026-01-20 00:15:33 +08:00
Gsh
a1e38234a7 Merge remote-tracking branch 'origin/ai-hub' into ai-hub 2026-01-19 23:00:06 +08:00
Gsh
ace5a9a1ec fix: 完善活动公告,修复图片生成参考图无法放大问题。 2026-01-19 22:58:20 +08:00
Gsh
4ce77ececc fix: 对话框支持粘贴图片 2026-01-19 22:15:01 +08:00
ccnetcore
be9442c113 feat: 新增AI应用快捷配置列表接口
新增 AI 应用快捷配置查询能力,在 IChannelService 中定义获取快捷配置列表接口,并在 ChannelService 中实现对应接口,支持按排序号及创建时间获取快捷配置数据。
2026-01-19 22:12:07 +08:00
Gsh
5895f9e794 fix: 前端打包时增加git hash 信息 2026-01-18 23:46:05 +08:00
Gsh
b0d1820919 fix: 前端打包时增加git hash 信息 2026-01-18 23:45:48 +08:00
ccnetcore
8b183e289c feat: 增加图片生成内容安全拦截校验并优化日志信息 2026-01-18 17:46:34 +08:00
ccnetcore
09ecddb552 fix: 修复图片解析、角色Claim类型及错误日志问题
- 优化 Gemini 图片解析逻辑,递归遍历 JSON 并支持从 markdown 中提取图片
- 修复管理员角色 Claim 使用错误类型的问题,统一为 ClaimTypes.Role
- 修正图片生成失败时日志内容,输出完整响应数据以便排查
2026-01-18 17:21:07 +08:00
ccnetcore
127639c20e fix: 修正JWT角色声明类型
将 RoleClaimType 从自定义字符串改为 ClaimTypes.Role,确保角色识别与授权逻辑正确运行
2026-01-18 15:53:26 +08:00
ccnetcore
9a0dc6f089 log: 升级3.3版本 2026-01-18 14:43:35 +08:00
Gsh
0c8f01c00a fix: 支持粘贴图片 2026-01-17 17:38:54 +08:00
ccnetcore
c2f074cb08 style: 支持深色主题 2026-01-13 22:55:43 +08:00
Gsh
6b6ddcf550 fix: 充值记录支持分页查询 2026-01-11 22:00:19 +08:00
ccnetcore
d9f5f1f050 style: 修改模型选择列表 2026-01-11 21:00:02 +08:00
ccnetcore
7ed7201d10 style: 修改模型选择列表 2026-01-11 20:39:53 +08:00
Gsh
a1ddd1c3e2 fix: 模型选择优化 2026-01-11 19:42:33 +08:00
Gsh
4800543a77 Merge remote-tracking branch 'origin/ai-hub' into ai-hub 2026-01-11 19:22:16 +08:00
Gsh
4090046946 fix: 模型选择优化 2026-01-11 19:21:48 +08:00
Gsh
3a19c75ca1 fix: 模型选择优化 2026-01-11 19:07:47 +08:00
ccnetcore
a67af0485e fix: 优化 Gemini 图片 base64 获取逻辑
从最后一个 part 逆序查找 inlineData 和 text,避免只读取首个 part 导致图片缺失
支持根据 inlineData.mimeType 动态生成 data:image 前缀
增强对多 part 返回结构的兼容性,提高图片解析成功率
2026-01-11 17:27:57 +08:00
ccnetcore
5de968f6c7 Merge remote-tracking branch 'origin/ai-hub' into ai-hub 2026-01-11 14:22:12 +08:00
ccnetcore
1edb92f6e8 feat: 调整VIP商品规格并下架2026限时尊享包
- 将 YiXinVip 6个月 改为 5个月方案,更新价格与枚举值
- 下架 2026 元旦限购的尊享包商品(注释保留定义)
2026-01-11 14:22:02 +08:00
Gsh
2b9bbca400 fix: ai应用侧边栏调整 2026-01-11 14:21:06 +08:00
Gsh
3bd1a977f7 fix: 联系客服优化 2026-01-11 14:13:43 +08:00
Gsh
d2b5704294 Merge remote-tracking branch 'origin/ai-hub' into ai-hub 2026-01-11 14:08:04 +08:00
Gsh
611c5ce59a fix: 对话列表折叠状态修复 2026-01-11 14:07:05 +08:00
ccnetcore
fc61b67fc0 feat: 模型列表返回中新增供应商名称字段
在模型列表查询中增加 ProviderName 字段,并在 ModelGetListOutput DTO 中暴露,用于按供应商(如 OpenAI、Anthropic 等)分组展示模型。
2026-01-11 13:57:05 +08:00
ccnetcore
a2da4c36fe feat: 模型列表返回中新增图标地址字段
在模型列表 DTO 中新增 IconUrl 属性,并在 AiChatService 查询映射时返回模型图标地址,支持前端展示模型图标。
2026-01-11 13:53:33 +08:00
ccnetcore
5e37859157 feat: 流式处理统一返回用户/系统内容并完善消息存储
引入 StreamProcessResult 统一封装流式处理结果,补充各 API 类型下用户输入与系统输出内容的提取与累计,用于会话消息持久化与用量统计;同时增强 Gemini 请求与响应内容解析能力,确保流式场景下消息与 token 使用数据完整一致。
2026-01-11 13:48:20 +08:00
Gsh
6f316d3e51 Merge remote-tracking branch 'origin/ai-hub' into ai-hub 2026-01-11 01:04:04 +08:00
Gsh
53d70ef9d7 fix: 对话格式兼容改造 2026-01-11 01:03:24 +08:00
ccnetcore
a9a9e45b7c feat: 聊天模型查询不再限制 Completions 接口类型
移除对 ModelApiType 为 Completions 的过滤条件,使聊天服务可使用更多类型的模型配置。
2026-01-11 01:03:05 +08:00
ccnetcore
629012d32a feat: 聊天模型查询不再限制 Completions 接口类型
移除对 ModelApiType 为 Completions 的过滤条件,使聊天服务可使用更多类型的模型配置。
2026-01-10 15:42:22 +08:00
ccnetcore
5f2133eb50 feat: 账户充值记录查询支持分页与条件筛选
为已登录账户的充值记录查询新增分页能力,支持按时间区间、是否免费、充值金额范围等条件筛选,并统一返回 PagedResultDto 结构,同时同步更新服务接口定义。
2026-01-10 00:56:22 +08:00
ccnetcore
ad85890907 fix: 修正 ModelApiTypeEnum 中 OpenAI 描述拼写错误 2026-01-10 00:41:19 +08:00
ccnetcore
87518af562 feat: 新增统一流式转发与统计能力,支持多API类型
新增统一流式处理机制,支持 Completions、Anthropic Messages、OpenAI Responses、Gemini GenerateContent 四种 API 的原封不动 SSE 转发
统一处理 token 用量统计、倍率计算、尊享包扣费与消息记录
新增统一发送接口 ai-chat/unified/send,支持从请求体自动解析模型 ID
提升多模型流式接入的一致性与扩展性
2026-01-10 00:22:57 +08:00
Gsh
62b26bc2a4 Merge remote-tracking branch 'origin/ai-hub' into ai-hub 2026-01-09 20:33:13 +08:00
Gsh
f237137791 fix: 模型库页面优化 2026-01-09 20:30:35 +08:00
Gsh
0d4d847e08 fix: 模型库页面优化 2026-01-09 20:27:00 +08:00
Gsh
12f1854d31 fix: 模型库页面优化 2026-01-09 17:39:31 +08:00
Gsh
73f5d43ada fix: 产品弹窗优化 2026-01-09 17:26:10 +08:00
Gsh
551122de10 fix: 产品弹窗优化 2026-01-09 17:06:18 +08:00
ccnetcore
d092254822 fix: 临时调整在线搜索时间参数处理
- 暂时忽略 daysAgo 动态计算逻辑
2026-01-09 00:05:51 +08:00
Gsh
1027006e63 fix: 前端联系我们、购买等优化 2026-01-08 23:55:39 +08:00
ccnetcore
2544c01e9d fix: 修复用量统计线程问题并完善搜索与Token计算逻辑
- OnlineSearch 增加 daysAgo 非法值保护,避免无效时间范围
- 修复 UsageStatistics 中 Prompt/Completion Token 为 0 时的统计异常
- 引入独立 UnitOfWork,解决流式处理下的并发与事务问题
- 确保用量统计、系统消息与尊享包扣减的原子性
- 补充前端 Element Plus 组件类型声明
- 统一并优化部分代码格式,不影响业务逻辑
2026-01-08 23:46:57 +08:00
ccnetcore
2f1f25ca37 fix: 更新免费模型默认ID
将 FreeModelId 从 DeepSeek-V3 调整为 DeepSeek-V3-0324,确保使用最新可用的免费模型配置
2026-01-08 22:39:21 +08:00
ccnetcore
5489f33d54 refactor: DateTimeTool 注入为单例依赖
为 DateTimeTool 实现 ISingletonDependency,统一生命周期管理,便于依赖注入使用
2026-01-08 22:24:56 +08:00
ccnetcore
6665d2fb2e feat: 新增日期时间工具并调整前端类型定义
新增 DateTimeTool Agent 工具,用于获取当前系统日期与时间
精简 Vue3 组件类型声明,移除未使用组件并补充容器、时间线等类型
移除无用的 VITE_BUILD_COMPRESS 环境变量声明
2026-01-08 22:22:32 +08:00
ccnetcore
b5ff6c141c feat: 联网搜索支持按时间范围过滤
- OnlineSearch 方法新增 daysAgo 参数,支持按最近天数筛选搜索结果
- 百度搜索请求增加 search_filter 时间范围(gte/lte)
- 补充相关模型与 JSON 源生成配置
- 更新工具描述,明确近期与实时信息范围
2026-01-08 22:19:36 +08:00
ccnetcore
f1e8b66689 fix: 完善AI网关与Anthropic异常处理日志信息
- 图片生成解析失败时补充错误日志,便于问题定位
- Anthropic 非流式对话异常时,根据提示词过长场景补充返回信息
- 统一并优化 Anthropic 流式与非流式异常日志格式,提升可读性
2026-01-08 22:09:42 +08:00
ccnetcore
c727aeed99 feat: 完成模型api改造 2026-01-08 21:38:36 +08:00
ccnetcore
40aa47bb1e chore: 清理组件类型定义并更新配置与版本标识
- 移除未使用的 Element Plus 组件与指令类型声明
- 新增 VITE_BUILD_COMPRESS 环境变量类型定义
- 更新首页加载动画中的版本号显示为 3.1
2026-01-07 22:27:58 +08:00
ccnetcore
40234343ff feat: 完成意心ai agent 2026-01-07 22:25:54 +08:00
ccnetcore
00a9bd00e5 perf: 调整公告加载与排序逻辑,优化有效公告优先级展示 2026-01-07 20:10:42 +08:00
chenchun
55c17211d8 fix: 为 Anthropic 聊天异常日志添加 ErrorId 并优化异常提示
在非流式与流式错误分支中生成 errorId,记录到日志并在抛出的异常中返回该 errorId,避免直接暴露完整响应内容并便于排查。调整了日志模板和异常提示文本。
2026-01-07 18:02:38 +08:00
chenchun
db7dc0e9a7 Merge remote-tracking branch 'origin/ai-hub' into ai-hub 2026-01-07 11:27:50 +08:00
chenchun
1727107190 feat: 为 Anthropic DTO 添加 signature、stop_sequence、cache_creation 和 service_tier 字段
在 Yi.Framework.AiHub.Domain.Shared/Dtos/Anthropic/AnthropicChatCompletionDto.cs 中新增字段:
- AnthropicChatCompletionDto: Signature、StopSequence(带 JsonPropertyName)
- AnthropicChatCompletionDtoContentBlock: signature(小写字段)
- AnthropicCompletionDtoUsage: CacheCreation、ServiceTier(带 JsonPropertyName)
2026-01-07 11:27:14 +08:00
ccnetcore
e680ac4cac feat: 引入基于 Redis 的每日任务配置缓存
将每日任务配置从硬编码字典改为通过 IDistributedCache 从 Redis 获取
新增默认任务配置作为兜底,在缓存不存在时自动写入
统一任务配置读取逻辑,支持后续动态调整任务等级与奖励
不影响现有任务流程与业务规则,仅增强配置灵活性
2026-01-06 22:13:18 +08:00
ccnetcore
6053899516 fix: 仅获取已启用的聊天模型
在获取聊天模型列表时新增 IsEnabled 条件过滤,避免返回未启用的模型,确保模型选择结果正确。
2026-01-05 22:19:23 +08:00
chenchun
5157eac35c fix: 修复 Anthropic TokenUsage 计算与流式响应的用量统计 2026-01-05 19:34:48 +08:00
chenchun
537104037b fix: 修复 AiGateWayManager 中 TokenUsage 判定逻辑,避免空引用
将条件从 "responseResult.Item2?.TokenUsage is not null || responseResult.Item2?.TokenUsage.TotalTokens > 0" 改为 "responseResult.Item2?.TokenUsage is not null && responseResult.Item2?.TokenUsage.TotalTokens > 0",
确保在访问 TotalTokens 之前先判空,避免 NullReferenceException 并正确记录 tokenUsage(文件:Yi.Framework.AiHub.Domain/Managers/AiGateWayManager.cs)。
2026-01-05 15:58:44 +08:00
chenchun
29c1768ded feat: 兼容claude格式 2026-01-05 15:54:14 +08:00
chenchun
b4a97e8b09 feat: 完成系统监控页面 2026-01-05 15:44:48 +08:00
chenchun
6101ea46d3 fix: 获取图像模型时仅返回启用模型
在查询图像模型列表时加入 IsEnabled == true 过滤,避免返回已禁用的模型。文件:AiImageService.cs
2026-01-05 14:15:21 +08:00
chenchun
cad145f067 fix: 修复 GetProviderListAsync 查询过滤与排序,避免遗漏提供商 2026-01-05 10:29:18 +08:00
Gsh
9d8f8b3125 feat: 图片广场优化 2026-01-05 10:12:35 +08:00
Gsh
4f70356a5c feat: 图片详情优化 2026-01-05 00:32:15 +08:00
ccnetcore
69a8b47245 feat: 完善渠道商管理 2026-01-05 00:11:06 +08:00
ccnetcore
88225a97b8 feat: 调整边框 2026-01-04 23:31:16 +08:00
Gsh
c697d12f8b Merge remote-tracking branch 'origin/ai-hub' into ai-hub 2026-01-04 22:49:09 +08:00
Gsh
7bb8f52813 feat: 失败提示 2026-01-04 22:48:36 +08:00
ccnetcore
b84f385d2d perf: 优化图片广场 2026-01-04 22:47:53 +08:00
Gsh
450e023b3b feat: 图片广场优化 2026-01-04 21:58:11 +08:00
Gsh
9f3b9fc513 Merge remote-tracking branch 'origin/ai-hub' into ai-hub 2026-01-04 21:29:07 +08:00
Gsh
9721b8bd74 feat: 图片广场优化 2026-01-04 21:15:41 +08:00
chenchun
bd30a40a6f feat: 完成图片模型单独扣费 2026-01-04 12:32:31 +08:00
Gsh
9ec9ace8e2 Merge remote-tracking branch 'origin/ai-hub' into ai-hub 2026-01-04 00:33:14 +08:00
Gsh
a437d55f9f feat: markdown移动端兼容 2026-01-04 00:32:01 +08:00
ccnetcore
d75a734bc1 Merge remote-tracking branch 'origin/ai-hub' into ai-hub 2026-01-04 00:08:24 +08:00
ccnetcore
9c058e9545 feat: 支持模型尊享标识并统一扣减尊享用量逻辑
新增模型是否为尊享的标识字段 IsPremium,并在网关层透传到模型描述。
使用模型描述中的 IsPremium 统一判断是否扣减尊享 token,用以替代多处重复的数据库查询。
同时整理了相关代码与注释,使尊享用量扣减逻辑更加集中和清晰。
2026-01-04 00:08:08 +08:00
Gsh
accbaf3ecb feat: 移动端兼容优化 2026-01-03 23:46:31 +08:00
Gsh
f8f2d7568c feat: 移动端兼容优化 2026-01-03 23:26:58 +08:00
Gsh
158226601b feat: 移动端兼容优化 2026-01-03 22:58:30 +08:00
Gsh
63aa8d9536 feat: 移动端兼容优化 2026-01-03 22:18:19 +08:00
ccnetcore
0147457329 Merge remote-tracking branch 'origin/ai-hub' into ai-hub 2026-01-03 22:09:41 +08:00
ccnetcore
1d47b26d0d feat: 更新图片存储地址并扩展图片记录返回信息
- 将图片存储服务地址由本地地址调整为线上正式地址
- 图片列表返回结果中新增 UserName、UserId、IsAnonymous 字段,完善用户相关信息返回
2026-01-03 22:09:30 +08:00
Gsh
cc1bc6dd82 feat: 图片广场优化 2026-01-03 22:07:20 +08:00
ccnetcore
922596c128 Merge branch 'ai-agent' into ai-hub
# Conflicts:
#	Yi.Abp.Net8/module/ai-hub/Yi.Framework.AiHub.Domain/Managers/AiGateWayManager.cs
2026-01-03 21:31:09 +08:00
ccnetcore
67cb142c07 stlyle: 发布3.0版本 2026-01-03 21:24:44 +08:00
Gsh
f164b7dccc feat: 图片广场优化 2026-01-03 20:53:17 +08:00
Gsh
6cc14c1e32 feat: 图片广场优化 2026-01-03 19:21:26 +08:00
ccnetcore
e992cfc928 fix: 修复类型映射问题 2026-01-03 18:19:52 +08:00
Gsh
42edd4c230 feat: 路由动态权限控制、图片广场优化 2026-01-03 17:04:34 +08:00
ccnetcore
3892ff1937 feat: 完成匿名字段功能 2026-01-03 16:17:57 +08:00
ccnetcore
12878ba022 feat: 完成条件 2026-01-03 16:00:18 +08:00
Gsh
a3259ad36f feat: 前端新增图片生成功能 2026-01-03 15:16:18 +08:00
ccnetcore
5bb7dfb7cd feat: token 下拉列表支持可选是否包含默认项
为 GetSelectListAsync 接口新增 includeDefault 查询参数,允许调用方控制是否返回“默认”选项,默认保持原有行为。
2026-01-03 14:39:17 +08:00
ccnetcore
3447e2dc5d refactor: 清理无用代码并统一网关处理逻辑
- 移除未使用的 using 和多余空行,优化代码可读性
- 统一 yi- 前缀模型名处理逻辑,减少重复代码
- 使用 EnsureSuccessStatusCode 简化图片上传错误处理流程
- 不影响现有功能,仅做代码结构和规范优化
2026-01-03 14:07:04 +08:00
ccnetcore
88fae0cdc2 fix: 优化图片生成与上传错误处理及任务信息返回
- 图片上传接口新增状态码校验,返回明确错误信息
- 图片生成任务失败时记录完整错误信息与堆栈
- 图片任务查询结果补充发布状态、分类及错误信息
- 网关层模型名规范化与少量代码格式优化
2026-01-03 14:03:24 +08:00
ccnetcore
f7ebe44fb6 fix: 修复 SSE 事件前缀重复写入问题
注释掉重复写入 EventPrefix 的代码,避免 SSE 响应中事件类型前缀重复,确保事件格式正确。
2026-01-03 12:49:32 +08:00
ccnetcore
5a7f0ab108 feat: 支持更多类型的图片模型 2026-01-03 03:19:31 +08:00
ccnetcore
be5f57f654 feat: 完成渠道商限制 2026-01-03 02:58:21 +08:00
ccnetcore
a6e7a5e906 feat: 完成渠道商拦截 2026-01-03 02:20:52 +08:00
ccnetcore
c4ab176089 style: 优化整体title显示 2026-01-03 02:15:28 +08:00
ccnetcore
a50f877964 style: 优化控制台样式 2026-01-03 01:54:22 +08:00
ccnetcore
28cdc29369 fix: 修复图片模型会员标识判断逻辑
将 IsPremiumPackage 的判断从使用 PremiumPackageConst.ModeIds 改为直接读取模型的 IsPremium 属性,避免因配置不一致导致会员标识错误。
2026-01-03 01:46:40 +08:00
ccnetcore
e39cbaf5e7 fix: 修复模型为空问题 2026-01-03 01:45:27 +08:00
ccnetcore
9d1dd72584 style: 优化滚动条样式 2026-01-03 01:29:47 +08:00
ccnetcore
ea403fcae0 feat: 新增错误信息返回 2026-01-03 01:12:47 +08:00
ccnetcore
91533909c2 style: 优化滚动条样式 2026-01-03 01:10:04 +08:00
ccnetcore
61d5d40dbb chore: 暂时禁用多个定时任务执行逻辑
在相关 Job 的 DoWorkAsync 方法中提前 return,防止自动执行挖矿、行情生成、新闻生成及资产更新等后台任务运行。
2026-01-03 00:03:23 +08:00
ccnetcore
38dbd0aca7 Merge remote-tracking branch 'origin/ai-agent' into ai-agent 2026-01-03 00:00:25 +08:00
ccnetcore
343347ea11 feat: 新增图片广场、发布及模型查询接口
- 图片任务列表区分为“我的任务”和“图片广场(已发布)”
- 新增图片发布到广场接口,支持分类
- 新增图片模型列表查询接口
- 注释掉图片 Base64 前缀字段,统一使用 URL
- 调整相关依赖注入,支持模型仓储查询
2026-01-03 00:00:17 +08:00
Gsh
a9e11d161c fix: 前端页面架构重构优化 2026-01-02 23:08:40 +08:00
Gsh
d25ca6dc4a fix: 前端页面架构重构优化 2026-01-02 22:47:09 +08:00
ccnetcore
ba95d1798f feat: 优化AI图片存储与访问流程
- 统一图片存储服务地址常量,返回完整可访问URL
- 图片上传接口支持匿名访问,并按日期创建存储目录
- ImageStoreTask 移除无用生成图片 Base64 字段,调整大字段存储配置
- 创建图片任务时补充 ModelId 信息
- 优先使用 Authorization 头部,避免覆盖已有认证信息
- 前端补充 Element Plus Descriptions 组件类型声明
2026-01-02 21:32:48 +08:00
ccnetcore
436b5b910c Merge branch 'ai-agent-backend' into ai-agent
# Conflicts:
#	Yi.Ai.Vue3/src/pages/console/index.vue
#	Yi.Ai.Vue3/src/routers/modules/staticRouter.ts
2026-01-02 19:45:55 +08:00
ccnetcore
560a76558a feat: 完成图片生成功能 2026-01-02 19:26:09 +08:00
ccnetcore
d7f4e49c2a fix: 统一处理 yi- 前缀模型并修正统计与计费记录
- 调用模型前去除 yi- 前缀,避免实际请求模型不匹配
- 存储消息、使用量统计及尊享套餐扣减统一使用原始模型ID
- 尊享套餐常量新增 gpt-5.2、gemini-3 等模型
- 前端补充 Element Plus ElSubMenu 类型声明
2026-01-02 00:57:30 +08:00
ccnetcore
3f53eb14ab chore: 添加 OpenAI NuGet 依赖
在 Stock.Domain 项目中引入 OpenAI 2.8.0 包,为后续 AI 能力集成做准备
2026-01-01 22:39:55 +08:00
ccnetcore
e46044e217 chore: 添加 OpenAI NuGet 依赖到 ChatHub Domain 模块 2026-01-01 22:36:24 +08:00
Gsh
9c842ab802 fix: 前端页面架构重构优化 2026-01-01 18:53:27 +08:00
Gsh
b8c0f9a212 fix: 前端页面架构重构优化 2026-01-01 18:53:27 +08:00
ccnetcore
6cc0059691 Revert "feat: 支持尊享包渠道"
This reverts commit 70ae2fab44.
2026-01-01 18:53:26 +08:00
ccnetcore
33d28a8cb0 feat: 支持尊享包渠道 2026-01-01 18:53:26 +08:00
Gsh
e4621d9049 fix: 前端页面架构重构初版 2026-01-01 18:53:25 +08:00
ccnetcore
c649ad31c2 fix: 修正2026元旦限购礼包的Token数量配置 2026-01-01 12:15:28 +08:00
ccnetcore
50fc8c5f0a feat: 新增活动激活码礼包与2026元旦限购商品
- 新增 888w、666w、100w 尊享Token 活动激活码礼包
- 新增 2026 元旦限购 1亿 / 2亿 Tokens 商品
- 调整原 1亿 Tokens 商品展示文案
2026-01-01 12:13:14 +08:00
ccnetcore
19ea76bd60 feat: 新增 gpt-5.2-codex 高级套餐模型支持 2025-12-31 00:20:36 +08:00
187 changed files with 19999 additions and 4864 deletions

1
.gitignore vendored
View File

@@ -280,3 +280,4 @@ database_backup
package-lock.json
.claude
components.d.ts

View File

@@ -0,0 +1,42 @@
namespace Yi.Framework.AiHub.Application.Contracts.Dtos.Channel;
/// <summary>
/// AI应用快捷配置DTO
/// </summary>
public class AiAppShortcutDto
{
/// <summary>
/// 应用ID
/// </summary>
public Guid Id { get; set; }
/// <summary>
/// 应用名称
/// </summary>
public string Name { get; set; }
/// <summary>
/// 应用终结点
/// </summary>
public string Endpoint { get; set; }
/// <summary>
/// 额外URL
/// </summary>
public string? ExtraUrl { get; set; }
/// <summary>
/// 应用Key
/// </summary>
public string ApiKey { get; set; }
/// <summary>
/// 排序
/// </summary>
public int OrderNum { get; set; }
/// <summary>
/// 创建时间
/// </summary>
public DateTime CreationTime { get; set; }
}

View File

@@ -93,4 +93,9 @@ public class AiModelCreateInput
/// 是否为尊享模型
/// </summary>
public bool IsPremium { get; set; }
/// <summary>
/// 是否启用
/// </summary>
public bool IsEnabled { get; set; } = true;
}

View File

@@ -81,4 +81,9 @@ public class AiModelDto
/// 是否为尊享模型
/// </summary>
public bool IsPremium { get; set; }
/// <summary>
/// 是否启用
/// </summary>
public bool IsEnabled { get; set; }
}

View File

@@ -99,4 +99,9 @@ public class AiModelUpdateInput
/// 是否为尊享模型
/// </summary>
public bool IsPremium { get; set; }
/// <summary>
/// 是否启用
/// </summary>
public bool IsEnabled { get; set; }
}

View File

@@ -15,7 +15,7 @@ public class AgentSendInput
/// <summary>
/// api密钥Id
/// </summary>
public string Token { get; set; }
public Guid TokenId { get; set; }
/// <summary>
/// 模型id

View File

@@ -5,6 +5,11 @@ namespace Yi.Framework.AiHub.Application.Contracts.Dtos.Chat;
/// </summary>
public class ImageGenerationInput
{
/// <summary>
/// 密钥id
/// </summary>
public Guid? TokenId { get; set; }
/// <summary>
/// 提示词
/// </summary>
@@ -16,7 +21,7 @@ public class ImageGenerationInput
public string ModelId { get; set; } = string.Empty;
/// <summary>
/// 参考图Base64列表可选包含前缀如 data:image/png;base64,...
/// 参考图PrefixBase64列表可选包含前缀如 data:image/png;base64,...
/// </summary>
public List<string>? ReferenceImagesBase64 { get; set; }
public List<string>? ReferenceImagesPrefixBase64 { get; set; }
}

View File

@@ -1,24 +1,26 @@
using Volo.Abp.Application.Dtos;
using Yi.Framework.AiHub.Domain.Shared.Enums;
using Yi.Framework.Ddd.Application.Contracts;
namespace Yi.Framework.AiHub.Application.Contracts.Dtos.Chat;
/// <summary>
/// 图片任务分页查询输入
/// </summary>
public class ImageTaskPageInput
public class ImageMyTaskPageInput: PagedAllResultRequestDto
{
/// <summary>
/// 页码从1开始
/// 提示词
/// </summary>
public int PageIndex { get; set; } = 1;
/// <summary>
/// 每页数量
/// </summary>
public int PageSize { get; set; } = 10;
public string? Prompt { get; set; }
/// <summary>
/// 任务状态筛选(可选)
/// </summary>
public TaskStatusEnum? TaskStatus { get; set; }
/// <summary>
/// 发布状态
/// </summary>
public PublishStatusEnum? PublishStatus { get; set; }
}

View File

@@ -0,0 +1,31 @@
using Volo.Abp.Application.Dtos;
using Yi.Framework.AiHub.Domain.Shared.Enums;
using Yi.Framework.Ddd.Application.Contracts;
namespace Yi.Framework.AiHub.Application.Contracts.Dtos.Chat;
/// <summary>
/// 图片任务分页查询输入
/// </summary>
public class ImagePlazaPageInput: PagedAllResultRequestDto
{
/// <summary>
/// 分类
/// </summary>
public string? Categories { get; set; }
/// <summary>
/// 提示词
/// </summary>
public string? Prompt { get; set; }
/// <summary>
/// 任务状态筛选(可选)
/// </summary>
public TaskStatusEnum? TaskStatus { get; set; }
/// <summary>
/// 用户名
/// </summary>
public string? UserName{ get; set; }
}

View File

@@ -18,19 +18,9 @@ public class ImageTaskOutput
public string Prompt { get; set; } = string.Empty;
/// <summary>
/// 参考图Base64列表
/// 是否匿名
/// </summary>
public List<string>? ReferenceImagesBase64 { get; set; }
/// <summary>
/// 参考图URL列表
/// </summary>
public List<string>? ReferenceImagesUrl { get; set; }
/// <summary>
/// 生成图片Base64包含前缀
/// </summary>
public string? StoreBase64 { get; set; }
public bool IsAnonymous { get; set; }
/// <summary>
/// 生成图片URL
@@ -42,8 +32,35 @@ public class ImageTaskOutput
/// </summary>
public TaskStatusEnum TaskStatus { get; set; }
/// <summary>
/// 发布状态
/// </summary>
public PublishStatusEnum PublishStatus { get; set; }
/// <summary>
/// 分类标签
/// </summary>
[SqlSugar.SugarColumn( IsJson = true)]
public List<string> Categories { get; set; } = new();
/// <summary>
/// 创建时间
/// </summary>
public DateTime CreationTime { get; set; }
/// <summary>
/// 错误信息
/// </summary>
public string? ErrorInfo { get; set; }
/// <summary>
/// 用户名称
/// </summary>
public string? UserName { get; set; }
/// <summary>
/// 用户名称Id
/// </summary>
public Guid? UserId { get; set; }
}

View File

@@ -0,0 +1,22 @@
namespace Yi.Framework.AiHub.Application.Contracts.Dtos.Chat;
/// <summary>
/// 发布图片输入
/// </summary>
public class PublishImageInput
{
/// <summary>
/// 是否匿名
/// </summary>
public bool IsAnonymous { get; set; } = false;
/// <summary>
/// 任务ID
/// </summary>
public Guid TaskId { get; set; }
/// <summary>
/// 分类标签
/// </summary>
public List<string> Categories { get; set; } = new();
}

View File

@@ -0,0 +1,43 @@
namespace Yi.Framework.AiHub.Application.Contracts.Dtos.DailyTask;
/// <summary>
/// 每日任务配置缓存DTO
/// </summary>
public class DailyTaskConfigCacheDto
{
/// <summary>
/// 任务配置列表
/// </summary>
public List<DailyTaskConfigItem> Tasks { get; set; } = new();
}
/// <summary>
/// 每日任务配置项
/// </summary>
public class DailyTaskConfigItem
{
/// <summary>
/// 任务等级
/// </summary>
public int Level { get; set; }
/// <summary>
/// 需要消耗的Token数量
/// </summary>
public long RequiredTokens { get; set; }
/// <summary>
/// 奖励的Token数量
/// </summary>
public long RewardTokens { get; set; }
/// <summary>
/// 任务名称
/// </summary>
public string Name { get; set; } = string.Empty;
/// <summary>
/// 任务描述
/// </summary>
public string Description { get; set; } = string.Empty;
}

View File

@@ -1,4 +1,6 @@
namespace Yi.Framework.AiHub.Application.Contracts.Dtos;
using Yi.Framework.AiHub.Domain.Shared.Enums;
namespace Yi.Framework.AiHub.Application.Contracts.Dtos;
public class ModelGetListOutput
{
@@ -6,13 +8,7 @@ public class ModelGetListOutput
/// 模型ID
/// </summary>
public Guid Id { get; set; }
/// <summary>
/// 模型分类
/// </summary>
public string Category { get; set; }
/// <summary>
/// 模型id
/// </summary>
@@ -28,36 +24,6 @@ public class ModelGetListOutput
/// </summary>
public string? ModelDescribe { get; set; }
/// <summary>
/// 模型价格
/// </summary>
public double ModelPrice { get; set; }
/// <summary>
/// 模型类型
/// </summary>
public string ModelType { get; set; }
/// <summary>
/// 模型展示状态
/// </summary>
public string ModelShow { get; set; }
/// <summary>
/// 系统提示
/// </summary>
public string SystemPrompt { get; set; }
/// <summary>
/// API 主机地址
/// </summary>
public string ApiHost { get; set; }
/// <summary>
/// API 密钥
/// </summary>
public string ApiKey { get; set; }
/// <summary>
/// 备注信息
/// </summary>
@@ -67,4 +33,23 @@ public class ModelGetListOutput
/// 是否为尊享包
/// </summary>
public bool IsPremiumPackage { get; set; }
/// <summary>
/// 是否免费模型
/// </summary>
public bool IsFree { get; set; }
/// <summary>
/// 模型Api类型现支持同一个模型id多种接口格式
/// </summary>
public ModelApiTypeEnum ModelApiType { get; set; }
/// <summary>
/// 模型图标URL
/// </summary>
public string? IconUrl { get; set; }
/// <summary>
/// 供应商分组名称(如OpenAI、Anthropic、Google等)
/// </summary>
public string? ProviderName { get; set; }
}

View File

@@ -0,0 +1,24 @@
using Yi.Framework.Ddd.Application.Contracts;
namespace Yi.Framework.AiHub.Application.Contracts.Dtos.Recharge;
/// <summary>
/// 充值记录查询输入
/// </summary>
public class RechargeGetListInput : PagedAllResultRequestDto
{
/// <summary>
/// 是否免费充值金额等于0
/// </summary>
public bool? IsFree { get; set; }
/// <summary>
/// 充值金额最小值
/// </summary>
public decimal? MinRechargeAmount { get; set; }
/// <summary>
/// 充值金额最大值
/// </summary>
public decimal? MaxRechargeAmount { get; set; }
}

View File

@@ -1,8 +1,15 @@
namespace Yi.Framework.AiHub.Application.Contracts.Dtos;
using Yi.Framework.AiHub.Domain.Shared.Enums;
namespace Yi.Framework.AiHub.Application.Contracts.Dtos;
public class SessionCreateAndUpdateInput
{
public string SessionTitle { get; set; }
public string SessionContent { get; set; }
public string? Remark { get; set; }
/// <summary>
/// 会话类型
/// </summary>
public SessionTypeEnum SessionType { get; set; } = SessionTypeEnum.Chat;
}

View File

@@ -1,4 +1,5 @@
using Volo.Abp.Application.Dtos;
using Yi.Framework.AiHub.Domain.Shared.Enums;
namespace Yi.Framework.AiHub.Application.Contracts.Dtos;
@@ -7,4 +8,9 @@ public class SessionDto : FullAuditedEntityDto<Guid>
public string SessionTitle { get; set; }
public string SessionContent { get; set; }
public string Remark { get; set; }
/// <summary>
/// 会话类型
/// </summary>
public SessionTypeEnum SessionType { get; set; }
}

View File

@@ -1,8 +1,14 @@
using Yi.Framework.Ddd.Application.Contracts;
using Yi.Framework.AiHub.Domain.Shared.Enums;
using Yi.Framework.Ddd.Application.Contracts;
namespace Yi.Framework.AiHub.Application.Contracts.Dtos;
public class SessionGetListInput:PagedAllResultRequestDto
public class SessionGetListInput : PagedAllResultRequestDto
{
public string? SessionTitle { get; set; }
/// <summary>
/// 会话类型
/// </summary>
public SessionTypeEnum? SessionType { get; set; }
}

View File

@@ -0,0 +1,42 @@
namespace Yi.Framework.AiHub.Application.Contracts.Dtos.SystemStatistics;
/// <summary>
/// 模型Token统计DTO
/// </summary>
public class ModelTokenStatisticsDto
{
/// <summary>
/// 模型ID
/// </summary>
public string ModelId { get; set; }
/// <summary>
/// 模型名称
/// </summary>
public string ModelName { get; set; }
/// <summary>
/// Token消耗量
/// </summary>
public long Tokens { get; set; }
/// <summary>
/// Token消耗量(万)
/// </summary>
public decimal TokensInWan { get; set; }
/// <summary>
/// 使用次数
/// </summary>
public long Count { get; set; }
/// <summary>
/// 成本(RMB)
/// </summary>
public decimal Cost { get; set; }
/// <summary>
/// 1亿Token成本(RMB)
/// </summary>
public decimal CostPerHundredMillion { get; set; }
}

View File

@@ -0,0 +1,12 @@
namespace Yi.Framework.AiHub.Application.Contracts.Dtos.SystemStatistics;
/// <summary>
/// 利润统计输入
/// </summary>
public class ProfitStatisticsInput
{
/// <summary>
/// 当前成本(RMB)
/// </summary>
public decimal CurrentCost { get; set; }
}

View File

@@ -0,0 +1,62 @@
namespace Yi.Framework.AiHub.Application.Contracts.Dtos.SystemStatistics;
/// <summary>
/// 利润统计输出
/// </summary>
public class ProfitStatisticsOutput
{
/// <summary>
/// 日期
/// </summary>
public string Date { get; set; }
/// <summary>
/// 尊享包已消耗Token数(单位:个)
/// </summary>
public long TotalUsedTokens { get; set; }
/// <summary>
/// 尊享包已消耗Token数(单位:亿)
/// </summary>
public decimal TotalUsedTokensInHundredMillion { get; set; }
/// <summary>
/// 尊享包剩余库存Token数(单位:个)
/// </summary>
public long TotalRemainingTokens { get; set; }
/// <summary>
/// 尊享包剩余库存Token数(单位:亿)
/// </summary>
public decimal TotalRemainingTokensInHundredMillion { get; set; }
/// <summary>
/// 当前成本(RMB)
/// </summary>
public decimal CurrentCost { get; set; }
/// <summary>
/// 1亿Token成本(RMB)
/// </summary>
public decimal CostPerHundredMillion { get; set; }
/// <summary>
/// 总成本(RMB)
/// </summary>
public decimal TotalCost { get; set; }
/// <summary>
/// 总收益(RMB)
/// </summary>
public decimal TotalRevenue { get; set; }
/// <summary>
/// 利润率(%)
/// </summary>
public decimal ProfitRate { get; set; }
/// <summary>
/// 按200售价计算的成本(RMB)
/// </summary>
public decimal CostAt200Price { get; set; }
}

View File

@@ -0,0 +1,12 @@
namespace Yi.Framework.AiHub.Application.Contracts.Dtos.SystemStatistics;
/// <summary>
/// Token统计输入
/// </summary>
public class TokenStatisticsInput
{
/// <summary>
/// 指定日期(当天零点)
/// </summary>
public DateTime Date { get; set; }
}

View File

@@ -0,0 +1,17 @@
namespace Yi.Framework.AiHub.Application.Contracts.Dtos.SystemStatistics;
/// <summary>
/// Token统计输出
/// </summary>
public class TokenStatisticsOutput
{
/// <summary>
/// 日期
/// </summary>
public string Date { get; set; }
/// <summary>
/// 模型统计列表
/// </summary>
public List<ModelTokenStatisticsDto> ModelStatistics { get; set; } = new();
}

View File

@@ -0,0 +1,22 @@
namespace Yi.Framework.AiHub.Application.Contracts.Dtos.UsageStatistics;
/// <summary>
/// 每小时Token使用量统计DTO柱状图
/// </summary>
public class HourlyTokenUsageDto
{
/// <summary>
/// 小时时间点
/// </summary>
public DateTime Hour { get; set; }
/// <summary>
/// 该小时总Token消耗量
/// </summary>
public long TotalTokens { get; set; }
/// <summary>
/// 各模型Token消耗明细
/// </summary>
public List<ModelTokenBreakdownDto> ModelBreakdown { get; set; } = new();
}

View File

@@ -0,0 +1,27 @@
namespace Yi.Framework.AiHub.Application.Contracts.Dtos.UsageStatistics;
/// <summary>
/// 模型今日使用量统计DTO卡片列表
/// </summary>
public class ModelTodayUsageDto
{
/// <summary>
/// 模型ID
/// </summary>
public string ModelId { get; set; }
/// <summary>
/// 今日使用次数
/// </summary>
public int UsageCount { get; set; }
/// <summary>
/// 今日消耗总Token数
/// </summary>
public long TotalTokens { get; set; }
/// <summary>
/// 模型图标URL
/// </summary>
public string? IconUrl { get; set; }
}

View File

@@ -0,0 +1,17 @@
namespace Yi.Framework.AiHub.Application.Contracts.Dtos.UsageStatistics;
/// <summary>
/// 模型Token堆叠数据DTO用于柱状图
/// </summary>
public class ModelTokenBreakdownDto
{
/// <summary>
/// 模型ID
/// </summary>
public string ModelId { get; set; }
/// <summary>
/// Token消耗量
/// </summary>
public long Tokens { get; set; }
}

View File

@@ -83,4 +83,14 @@ public interface IChannelService
Task DeleteModelAsync(Guid id);
#endregion
#region AI应用快捷配置
/// <summary>
/// 获取AI应用快捷配置列表
/// </summary>
/// <returns>快捷配置列表</returns>
Task<List<AiAppShortcutDto>> GetAppShortcutListAsync();
#endregion
}

View File

@@ -1,9 +1,15 @@
using Yi.Framework.AiHub.Application.Contracts.Dtos.Recharge;
using Volo.Abp.Application.Dtos;
using Yi.Framework.AiHub.Application.Contracts.Dtos.Recharge;
namespace Yi.Framework.AiHub.Application.Contracts.IServices;
public interface IRechargeService
{
/// <summary>
/// 查询已登录的账户充值记录(分页)
/// </summary>
Task<PagedResultDto<RechargeGetListOutput>> GetListByAccountAsync(RechargeGetListInput input);
/// <summary>
/// 移除用户vip及角色
/// </summary>

View File

@@ -0,0 +1,19 @@
using Yi.Framework.AiHub.Application.Contracts.Dtos.SystemStatistics;
namespace Yi.Framework.AiHub.Application.Contracts.IServices;
/// <summary>
/// 系统使用量统计服务接口
/// </summary>
public interface ISystemUsageStatisticsService
{
/// <summary>
/// 获取利润统计数据
/// </summary>
Task<ProfitStatisticsOutput> GetProfitStatisticsAsync(ProfitStatisticsInput input);
/// <summary>
/// 获取指定日期各模型Token统计
/// </summary>
Task<TokenStatisticsOutput> GetTokenStatisticsAsync(TokenStatisticsInput input);
}

View File

@@ -24,4 +24,16 @@ public interface IUsageStatisticsService
/// </summary>
/// <returns>尊享服务Token用量统计</returns>
Task<PremiumTokenUsageDto> GetPremiumTokenUsageAsync();
/// <summary>
/// 获取当前用户近24小时每小时Token消耗统计柱状图
/// </summary>
/// <returns>每小时Token使用量列表包含各模型堆叠数据</returns>
Task<List<HourlyTokenUsageDto>> GetLast24HoursTokenUsageAsync(UsageStatisticsGetInput input);
/// <summary>
/// 获取当前用户今日各模型使用量统计(卡片列表)
/// </summary>
/// <returns>模型今日使用量列表包含使用次数和总Token</returns>
Task<List<ModelTodayUsageDto>> GetTodayModelUsageAsync(UsageStatisticsGetInput input);
}

View File

@@ -30,32 +30,101 @@ public class ImageGenerationJob : AsyncBackgroundJob<ImageGenerationJobArgs>, IT
public override async Task ExecuteAsync(ImageGenerationJobArgs args)
{
_logger.LogInformation("开始执行图片生成任务TaskId: {TaskId}, ModelId: {ModelId}, UserId: {UserId}",
args.TaskId, args.ModelId, args.UserId);
var task = await _imageStoreTaskRepository.GetFirstAsync(x => x.Id == args.TaskId);
if (task is null)
{
throw new UserFriendlyException($"{args.TaskId} 图片生成任务不存在");
}
_logger.LogInformation("开始执行图片生成任务TaskId: {TaskId}, ModelId: {ModelId}, UserId: {UserId}",
task.Id, task.ModelId, task.UserId);
try
{
var request = JsonSerializer.Deserialize<JsonElement>(args.RequestJson);
// 构建 Gemini API 请求对象
var parts = new List<object>
{
new { text = task.Prompt }
};
// 添加参考图(如果有)
foreach (var prefixBase64 in task.ReferenceImagesPrefixBase64)
{
var (mimeType, base64Data) = ParsePrefixBase64(prefixBase64);
parts.Add(new
{
inline_data = new
{
mime_type = mimeType,
data = base64Data
}
});
}
var requestObj = new
{
contents = new[]
{
new
{
role = "user", parts = new List<object>
{
new { text = "我只要图片,直接生成图片,不要询问我" }
}
},
new { role = "user", parts }
}
};
var request = JsonSerializer.Deserialize<JsonElement>(
JsonSerializer.Serialize(requestObj));
//里面生成成功已经包含扣款了
await _aiGateWayManager.GeminiGenerateContentImageForStatisticsAsync(
args.TaskId,
args.ModelId,
task.Id,
task.ModelId,
request,
args.UserId);
task.UserId,
tokenId: task.TokenId);
_logger.LogInformation("图片生成任务完成TaskId: {TaskId}", args.TaskId);
}
catch (Exception ex)
{
_logger.LogError(ex, "图片生成任务失败TaskId: {TaskId}, Error: {Error}", args.TaskId, ex.Message);
var error = $"图片任务失败TaskId: {args.TaskId},错误信息: {ex.Message},错误堆栈:{ex.StackTrace}";
_logger.LogError(ex, error);
// 更新任务状态为失败
var task = await _imageStoreTaskRepository.GetFirstAsync(x => x.Id == args.TaskId);
if (task != null)
{
task.TaskStatus = TaskStatusEnum.Fail;
await _imageStoreTaskRepository.UpdateAsync(task);
}
task.TaskStatus = TaskStatusEnum.Fail;
task.ErrorInfo = error;
await _imageStoreTaskRepository.UpdateAsync(task);
}
}
}
/// <summary>
/// 解析带前缀的 Base64 字符串,提取 mimeType 和纯 base64 数据
/// </summary>
private static (string mimeType, string base64Data) ParsePrefixBase64(string prefixBase64)
{
// 默认值
var mimeType = "image/png";
var base64Data = prefixBase64;
if (prefixBase64.Contains(","))
{
var parts = prefixBase64.Split(',');
if (parts.Length == 2)
{
var header = parts[0];
if (header.Contains(":") && header.Contains(";"))
{
mimeType = header.Split(':')[1].Split(';')[0];
}
base64Data = parts[1];
}
}
return (mimeType, base64Data);
}
}

View File

@@ -9,19 +9,4 @@ public class ImageGenerationJobArgs
/// 图片任务ID
/// </summary>
public Guid TaskId { get; set; }
/// <summary>
/// 模型ID
/// </summary>
public string ModelId { get; set; } = string.Empty;
/// <summary>
/// 请求JSON字符串
/// </summary>
public string RequestJson { get; set; } = string.Empty;
/// <summary>
/// 用户ID
/// </summary>
public Guid UserId { get; set; }
}

View File

@@ -1,8 +1,10 @@
using Medallion.Threading;
using Microsoft.AspNetCore.Authorization;
using Microsoft.Extensions.Caching.Distributed;
using Microsoft.Extensions.Logging;
using SqlSugar;
using Volo.Abp.Application.Services;
using Volo.Abp.Caching;
using Volo.Abp.Users;
using Yi.Framework.AiHub.Application.Contracts.Dtos.DailyTask;
using Yi.Framework.AiHub.Domain.Entities;
@@ -25,27 +27,33 @@ public class DailyTaskService : ApplicationService
private readonly ISqlSugarRepository<MessageAggregateRoot> _messageRepository;
private readonly ISqlSugarRepository<PremiumPackageAggregateRoot> _premiumPackageRepository;
private readonly ILogger<DailyTaskService> _logger;
private readonly IDistributedCache<DailyTaskConfigCacheDto> _taskConfigCache;
private IDistributedLockProvider DistributedLock => LazyServiceProvider.LazyGetRequiredService<IDistributedLockProvider>();
private readonly ISqlSugarRepository<AiModelEntity> _aiModelRepository;
// 任务配置
private readonly Dictionary<int, (long RequiredTokens, long RewardTokens, string Name, string Description)>
_taskConfigs = new()
{
{ 1, (10000000, 1000000, "尊享包1000w token任务", "累积使用尊享包 1000w token") }, // 1000w消耗 -> 100w奖励
{ 2, (30000000, 2000000, "尊享包3000w token任务", "累积使用尊享包 3000w token") } // 3000w消耗 -> 200w奖励
};
private const string TaskConfigCacheKey = "AiHub:DailyTaskConfig";
// 默认任务配置当Redis中没有配置时使用
private static readonly List<DailyTaskConfigItem> DefaultTaskConfigs = new()
{
new DailyTaskConfigItem { Level = 1, RequiredTokens = 10000000, RewardTokens = 1000000, Name = "尊享包1000w token任务", Description = "累积使用尊享包 1000w token" },
new DailyTaskConfigItem { Level = 2, RequiredTokens = 30000000, RewardTokens = 2000000, Name = "尊享包3000w token任务", Description = "累积使用尊享包 3000w token" }
};
public DailyTaskService(
ISqlSugarRepository<DailyTaskRewardRecordAggregateRoot> dailyTaskRepository,
ISqlSugarRepository<MessageAggregateRoot> messageRepository,
ISqlSugarRepository<PremiumPackageAggregateRoot> premiumPackageRepository,
ILogger<DailyTaskService> logger, ISqlSugarRepository<AiModelEntity> aiModelRepository)
ILogger<DailyTaskService> logger,
ISqlSugarRepository<AiModelEntity> aiModelRepository,
IDistributedCache<DailyTaskConfigCacheDto> taskConfigCache)
{
_dailyTaskRepository = dailyTaskRepository;
_messageRepository = messageRepository;
_premiumPackageRepository = premiumPackageRepository;
_logger = logger;
_aiModelRepository = aiModelRepository;
_taskConfigCache = taskConfigCache;
}
/// <summary>
@@ -57,20 +65,23 @@ public class DailyTaskService : ApplicationService
var userId = CurrentUser.GetId();
var today = DateTime.Today;
// 1. 统计今日尊享包Token消耗量
// 1. 获取任务配置
var taskConfigs = await GetTaskConfigsAsync();
// 2. 统计今日尊享包Token消耗量
var todayConsumed = await GetTodayPremiumTokenConsumptionAsync(userId, today);
// 2. 查询今日已领取的任务
// 3. 查询今日已领取的任务
var claimedTasks = await _dailyTaskRepository._DbQueryable
.Where(x => x.UserId == userId && x.TaskDate == today)
.Select(x => new { x.TaskLevel, x.IsRewarded })
.ToListAsync();
// 3. 构建任务列表
// 4. 构建任务列表
var tasks = new List<DailyTaskItem>();
foreach (var (level, config) in _taskConfigs)
foreach (var config in taskConfigs)
{
var claimed = claimedTasks.FirstOrDefault(x => x.TaskLevel == level);
var claimed = claimedTasks.FirstOrDefault(x => x.TaskLevel == config.Level);
int status;
if (claimed != null && claimed.IsRewarded)
@@ -92,7 +103,7 @@ public class DailyTaskService : ApplicationService
tasks.Add(new DailyTaskItem
{
Level = level,
Level = config.Level,
Name = config.Name,
Description = config.Description,
RequiredTokens = config.RequiredTokens,
@@ -120,17 +131,20 @@ public class DailyTaskService : ApplicationService
//自旋等待,防抖
await using var handle =
await DistributedLock.AcquireLockAsync($"Yi:AiHub:ClaimTaskRewardLock:{userId}");
var today = DateTime.Today;
// 1. 验证任务等级
if (!_taskConfigs.TryGetValue(input.TaskLevel, out var taskConfig))
// 1. 获取任务配置
var taskConfigs = await GetTaskConfigsAsync();
var taskConfig = taskConfigs.FirstOrDefault(x => x.Level == input.TaskLevel);
// 2. 验证任务等级
if (taskConfig == null)
{
throw new UserFriendlyException($"无效的任务等级: {input.TaskLevel}");
}
// 2. 检查是否已领取
// 3. 检查是否已领取
var existingRecord = await _dailyTaskRepository._DbQueryable
.Where(x => x.UserId == userId && x.TaskDate == today && x.TaskLevel == input.TaskLevel)
.FirstAsync();
@@ -140,7 +154,7 @@ public class DailyTaskService : ApplicationService
throw new UserFriendlyException("今日该任务奖励已领取,请明天再来!");
}
// 3. 验证今日Token消耗是否达标
// 4. 验证今日Token消耗是否达标
var todayConsumed = await GetTodayPremiumTokenConsumptionAsync(userId, today);
if (todayConsumed < taskConfig.RequiredTokens)
{
@@ -148,18 +162,17 @@ public class DailyTaskService : ApplicationService
$"Token消耗未达标需要 {taskConfig.RequiredTokens / 10000}w当前 {todayConsumed / 10000}w");
}
// 4. 创建奖励包(使用 PremiumPackageManager
// 5. 创建奖励包
var premiumPackage =
new PremiumPackageAggregateRoot(userId, taskConfig.RewardTokens, $"每日任务:{taskConfig.Name}")
{
PurchaseAmount = 0, // 奖励不需要付费
PurchaseAmount = 0,
Remark = $"{today:yyyy-MM-dd} 每日任务奖励"
};
await _premiumPackageRepository.InsertAsync(premiumPackage);
// 5. 记录领取记录
// 6. 记录领取记录
var record = new DailyTaskRewardRecordAggregateRoot(userId, input.TaskLevel, today, taskConfig.RewardTokens)
{
Remark = $"完成任务{input.TaskLevel},名称:{taskConfig.Name},消耗 {todayConsumed / 10000}w token"
@@ -197,4 +210,21 @@ public class DailyTaskService : ApplicationService
return totalTokens;
}
/// <summary>
/// 从Redis获取任务配置如果不存在则写入默认配置
/// </summary>
private async Task<List<DailyTaskConfigItem>> GetTaskConfigsAsync()
{
var cacheData = await _taskConfigCache.GetOrAddAsync(
TaskConfigCacheKey,
() => Task.FromResult(new DailyTaskConfigCacheDto { Tasks = DefaultTaskConfigs }),
() => new DistributedCacheEntryOptions
{
// 不设置过期时间,永久缓存,需要手动更新
}
);
return cacheData?.Tasks ?? DefaultTaskConfigs;
}
}

View File

@@ -81,162 +81,4 @@ public class AiAccountService : ApplicationService
return output;
}
/// <summary>
/// 获取利润统计数据
/// </summary>
/// <param name="currentCost">当前成本(RMB)</param>
/// <returns></returns>
[Authorize]
[HttpGet("account/profit-statistics")]
public async Task<string> GetProfitStatisticsAsync([FromQuery] decimal currentCost)
{
if (CurrentUser.UserName != "Guo" && CurrentUser.UserName != "cc")
{
throw new UserFriendlyException("您暂无权限访问");
}
// 1. 获取尊享包总消耗和剩余库存
var premiumPackages = await _premiumPackageRepository._DbQueryable.ToListAsync();
long totalUsedTokens = premiumPackages.Sum(p => p.UsedTokens);
long totalRemainingTokens = premiumPackages.Sum(p => p.RemainingTokens);
// 2. 计算1亿Token成本
decimal costPerHundredMillion = totalUsedTokens > 0
? currentCost / (totalUsedTokens / 100000000m)
: 0;
// 3. 计算总成本(剩余+已使用的总成本)
long totalTokens = totalUsedTokens + totalRemainingTokens;
decimal totalCost = totalTokens > 0
? (totalTokens / 100000000m) * costPerHundredMillion
: 0;
// 4. 获取总收益(RechargeType=PremiumPackage的充值金额总和)
decimal totalRevenue = await _rechargeRepository._DbQueryable
.Where(x => x.RechargeType == Domain.Shared.Enums.RechargeTypeEnum.PremiumPackage)
.SumAsync(x => x.RechargeAmount);
// 5. 计算利润率
decimal profitRate = totalCost > 0
? (totalRevenue / totalCost - 1) * 100
: 0;
// 6. 按200售价计算成本
decimal costAt200Price = totalRevenue > 0
? (totalCost / totalRevenue) * 200
: 0;
// 7. 格式化输出
var today = DateTime.Now;
string dayOfWeek = today.ToString("dddd", new System.Globalization.CultureInfo("zh-CN"));
string weekDay = dayOfWeek switch
{
"星期一" => "周1",
"星期二" => "周2",
"星期三" => "周3",
"星期四" => "周4",
"星期五" => "周5",
"星期六" => "周6",
"星期日" => "周日",
_ => dayOfWeek
};
var result = $@"{today:M月d日} {weekDay}
尊享包已消耗({totalUsedTokens / 100000000m:F2}亿){totalUsedTokens}
尊享包剩余库存({totalRemainingTokens / 100000000m:F2}亿){totalRemainingTokens}
当前成本:{currentCost:F2}RMB
1亿Token成本:{costPerHundredMillion:F2} RMB=1亿 Token
总成本:{totalCost:F2} RMB
总收益:{totalRevenue:F2}RMB
利润率: {profitRate:F1}%
按200售价来算,成本在{costAt200Price:F2}";
return result;
}
public class TokenStatisticsInput
{
/// <summary>
/// 指定日期(当天零点)
/// </summary>
public DateTime Date { get; set; }
/// <summary>
/// 模型Id -> 1亿Token成本(RMB)
/// </summary>
public Dictionary<string, decimal> ModelCosts { get; set; } = new();
}
/// <summary>
/// 获取指定日期各模型Token统计
/// </summary>
[Authorize]
[HttpPost("account/token-statistics")]
public async Task<string> GetTokenStatisticsAsync([FromBody] TokenStatisticsInput input)
{
if (CurrentUser.UserName != "Guo" && CurrentUser.UserName != "cc")
{
throw new UserFriendlyException("您暂无权限访问");
}
if (input.ModelCosts is null || input.ModelCosts.Count == 0)
{
throw new UserFriendlyException("请提供模型成本配置");
}
var day = input.Date.Date;
var nextDay = day.AddDays(1);
var modelIds = input.ModelCosts.Keys.ToList();
var modelStats = await _messageRepository._DbQueryable
.Where(x => modelIds.Contains(x.ModelId))
.Where(x => x.CreationTime >= day && x.CreationTime < nextDay)
.Where(x => x.Role == "system")
.GroupBy(x => x.ModelId)
.Select(x => new
{
ModelId = x.ModelId,
Tokens = SqlFunc.AggregateSum(x.TokenUsage.TotalTokenCount),
Count = SqlFunc.AggregateCount(x.Id)
})
.ToListAsync();
var modelStatDict = modelStats.ToDictionary(x => x.ModelId, x => x);
string weekDay = day.ToString("dddd", new CultureInfo("zh-CN")) switch
{
"星期一" => "周1",
"星期二" => "周2",
"星期三" => "周3",
"星期四" => "周4",
"星期五" => "周5",
"星期六" => "周6",
"星期日" => "周日",
_ => day.ToString("dddd", new CultureInfo("zh-CN"))
};
var sb = new StringBuilder();
sb.AppendLine($"{day:M月d日} {weekDay}");
foreach (var kvp in input.ModelCosts)
{
var modelId = kvp.Key;
var cost = kvp.Value;
modelStatDict.TryGetValue(modelId, out var stat);
long tokens = stat?.Tokens ?? 0;
long count = stat?.Count ?? 0;
decimal costPerHundredMillion = tokens > 0
? cost / (tokens / 100000000m)
: 0;
decimal tokensInWan = tokens / 10000m;
sb.AppendLine();
sb.AppendLine($"{modelId} 成本:【{cost:F2}RMB】 次数:【{count}次】 token【{tokensInWan:F0}w】 1亿token成本【{costPerHundredMillion:F2}RMB】");
}
return sb.ToString().TrimEnd();
}
}

View File

@@ -53,13 +53,23 @@ public class AnnouncementService : ApplicationService, IAnnouncementService
/// </summary>
private async Task<AnnouncementCacheDto> LoadAnnouncementDataAsync()
{
// 查询所有公告日志,按日期降序排列
// 1⃣ 一次性查出全部公告(不排序)
var logs = await _announcementRepository._DbQueryable
.OrderByDescending(x => x.StartTime)
.ToListAsync();
var now = DateTime.Now;
// 2⃣ 内存中处理排序
var orderedLogs = logs
.OrderByDescending(x =>
x.StartTime <= now &&
(x.EndTime == null || x.EndTime >= now)
)
.ThenByDescending(x => x.StartTime)
.ToList();
// 转换为 DTO
var logDtos = logs.Adapt<List<AnnouncementLogDto>>();
var logDtos = orderedLogs.Adapt<List<AnnouncementLogDto>>();
return new AnnouncementCacheDto
{
Logs = logDtos

View File

@@ -14,18 +14,21 @@ namespace Yi.Framework.AiHub.Application.Services;
/// <summary>
/// 渠道商管理服务实现
/// </summary>
[Authorize]
[Authorize(Roles = "admin")]
public class ChannelService : ApplicationService, IChannelService
{
private readonly ISqlSugarRepository<AiAppAggregateRoot, Guid> _appRepository;
private readonly ISqlSugarRepository<AiModelEntity, Guid> _modelRepository;
private readonly ISqlSugarRepository<AiAppShortcutAggregateRoot, Guid> _appShortcutRepository;
public ChannelService(
ISqlSugarRepository<AiAppAggregateRoot, Guid> appRepository,
ISqlSugarRepository<AiModelEntity, Guid> modelRepository)
ISqlSugarRepository<AiModelEntity, Guid> modelRepository,
ISqlSugarRepository<AiAppShortcutAggregateRoot, Guid> appShortcutRepository)
{
_appRepository = appRepository;
_modelRepository = modelRepository;
_appShortcutRepository = appShortcutRepository;
}
#region AI应用管理
@@ -181,6 +184,7 @@ public class ChannelService : ApplicationService, IChannelService
ProviderName = input.ProviderName,
IconUrl = input.IconUrl,
IsPremium = input.IsPremium,
IsEnabled = input.IsEnabled,
IsDeleted = false
};
@@ -222,6 +226,7 @@ public class ChannelService : ApplicationService, IChannelService
entity.ProviderName = input.ProviderName;
entity.IconUrl = input.IconUrl;
entity.IsPremium = input.IsPremium;
entity.IsEnabled = input.IsEnabled;
await _modelRepository.UpdateAsync(entity);
return entity.Adapt<AiModelDto>();
@@ -237,4 +242,22 @@ public class ChannelService : ApplicationService, IChannelService
}
#endregion
#region AI应用快捷配置
/// <summary>
/// 获取AI应用快捷配置列表
/// </summary>
[HttpGet("channel/app-shortcut")]
public async Task<List<AiAppShortcutDto>> GetAppShortcutListAsync()
{
var entities = await _appShortcutRepository._DbQueryable
.OrderBy(x => x.OrderNum)
.OrderByDescending(x => x.CreationTime)
.ToListAsync();
return entities.Adapt<List<AiAppShortcutDto>>();
}
#endregion
}

View File

@@ -25,6 +25,7 @@ using Yi.Framework.AiHub.Domain.Entities.Model;
using Yi.Framework.AiHub.Domain.Extensions;
using Yi.Framework.AiHub.Domain.Managers;
using Yi.Framework.AiHub.Domain.Shared.Consts;
using System.Text.Json;
using Yi.Framework.AiHub.Domain.Shared.Dtos;
using Yi.Framework.AiHub.Domain.Shared.Dtos.OpenAi;
using Yi.Framework.AiHub.Domain.Shared.Enums;
@@ -50,6 +51,7 @@ public class AiChatService : ApplicationService
private readonly IAccountService _accountService;
private readonly ISqlSugarRepository<AgentStoreAggregateRoot> _agentStoreRepository;
private readonly ISqlSugarRepository<AiModelEntity> _aiModelRepository;
private const string FreeModelId = "DeepSeek-V3-0324";
public AiChatService(IHttpContextAccessor httpContextAccessor,
AiBlacklistManager aiBlacklistManager,
@@ -58,7 +60,8 @@ public class AiChatService : ApplicationService
ModelManager modelManager,
PremiumPackageManager premiumPackageManager,
ChatManager chatManager, TokenManager tokenManager, IAccountService accountService,
ISqlSugarRepository<AgentStoreAggregateRoot> agentStoreRepository, ISqlSugarRepository<AiModelEntity> aiModelRepository)
ISqlSugarRepository<AgentStoreAggregateRoot> agentStoreRepository,
ISqlSugarRepository<AiModelEntity> aiModelRepository)
{
_httpContextAccessor = httpContextAccessor;
_aiBlacklistManager = aiBlacklistManager;
@@ -88,31 +91,38 @@ public class AiChatService : ApplicationService
}
/// <summary>
/// 获取模型列表
/// 获取对话模型列表
/// </summary>
/// <returns></returns>
public async Task<List<ModelGetListOutput>> GetModelAsync()
{
var output = await _aiModelRepository._DbQueryable
.Where(x => x.IsEnabled == true)
.Where(x => x.ModelType == ModelTypeEnum.Chat)
.Where(x => x.ModelApiType == ModelApiTypeEnum.OpenAi)
// .Where(x => x.ModelApiType == ModelApiTypeEnum.Completions)
.OrderByDescending(x => x.OrderNum)
.Select(x => new ModelGetListOutput
{
Id = x.Id,
Category = "chat",
ModelId = x.ModelId,
ModelName = x.Name,
ModelDescribe = x.Description,
ModelPrice = 0,
ModelType = "1",
ModelShow = "0",
SystemPrompt = null,
ApiHost = null,
ApiKey = null,
Remark = x.Description,
IsPremiumPackage = x.IsPremium
IsPremiumPackage = x.IsPremium,
ModelApiType = x.ModelApiType,
IconUrl = x.IconUrl,
ProviderName = x.ProviderName
}).ToListAsync();
output.ForEach(x =>
{
if (x.ModelId == FreeModelId)
{
x.IsPremiumPackage = false;
x.IsFree = true;
}
});
return output;
}
@@ -128,7 +138,7 @@ public class AiChatService : ApplicationService
CancellationToken cancellationToken)
{
//除了免费模型,其他的模型都要校验
if (!input.Model.Contains("DeepSeek-R1"))
if (input.Model!=FreeModelId)
{
//有token需要黑名单校验
if (CurrentUser.IsAuthenticated)
@@ -179,22 +189,10 @@ public class AiChatService : ApplicationService
{
throw new BusinessException("当前接口不支持第三方使用");
}
input.Model = "gpt-5-chat";
if (CurrentUser.IsAuthenticated)
{
await _aiBlacklistManager.VerifiyAiBlacklist(CurrentUser.GetId());
if (CurrentUser.IsAiVip())
{
input.Model = "gpt-5-chat";
}
else
{
input.Model = "gpt-4.1-mini";
}
}
else
{
input.Model = "DeepSeek-R1-0528";
}
//ai网关代理httpcontext
@@ -209,7 +207,7 @@ public class AiChatService : ApplicationService
[HttpPost("ai-chat/agent/send")]
public async Task PostAgentSendAsync([FromBody] AgentSendInput input, CancellationToken cancellationToken)
{
var tokenValidation = await _tokenManager.ValidateTokenAsync(input.Token, input.ModelId);
var tokenValidation = await _tokenManager.ValidateTokenAsync(input.TokenId, input.ModelId);
await _aiBlacklistManager.VerifiyAiBlacklist(tokenValidation.UserId);
// 验证用户是否为VIP
@@ -241,7 +239,7 @@ public class AiChatService : ApplicationService
await _chatManager.AgentCompleteChatStreamAsync(_httpContextAccessor.HttpContext,
input.SessionId,
input.Content,
input.Token,
tokenValidation.Token,
tokenValidation.TokenId,
input.ModelId,
tokenValidation.UserId,
@@ -275,4 +273,89 @@ public class AiChatService : ApplicationService
var data = await _agentStoreRepository.GetFirstAsync(x => x.SessionId == sessionId);
return data?.Store;
}
/// <summary>
/// 统一发送消息 - 支持4种API类型
/// </summary>
/// <param name="apiType">API类型枚举</param>
/// <param name="input">原始请求体JsonElement</param>
/// <param name="modelId">模型IDGemini格式需要从URL传入</param>
/// <param name="sessionId">会话ID</param>
/// <param name="cancellationToken"></param>
[HttpPost("ai-chat/unified/send")]
public async Task PostUnifiedSendAsync(
[FromQuery] ModelApiTypeEnum apiType,
[FromBody] JsonElement input,
[FromQuery] string modelId,
[FromQuery] Guid? sessionId,
CancellationToken cancellationToken)
{
// 从请求体中提取模型ID如果未从URL传入
if (string.IsNullOrEmpty(modelId))
{
modelId = ExtractModelIdFromRequest(apiType, input);
}
// 除了免费模型,其他的模型都要校验
if (modelId != FreeModelId)
{
if (CurrentUser.IsAuthenticated)
{
await _aiBlacklistManager.VerifiyAiBlacklist(CurrentUser.GetId());
if (!CurrentUser.IsAiVip())
{
throw new UserFriendlyException("该模型需要VIP用户才能使用请购买VIP后重新登录重试");
}
}
else
{
throw new UserFriendlyException("未登录用户只能使用未加速的DeepSeek-R1请登录后重试");
}
}
// 如果是尊享包服务,需要校验是否尊享包足够
if (CurrentUser.IsAuthenticated)
{
var isPremium = await _modelManager.IsPremiumModelAsync(modelId);
if (isPremium)
{
var availableTokens = await _premiumPackageManager.GetAvailableTokensAsync(CurrentUser.GetId());
if (availableTokens <= 0)
{
throw new UserFriendlyException("尊享token包用量不足请先购买尊享token包");
}
}
}
// 调用统一流式处理
await _aiGateWayManager.UnifiedStreamForStatisticsAsync(
_httpContextAccessor.HttpContext!,
apiType,
input,
modelId,
CurrentUser.Id,
sessionId,
null,
CancellationToken.None);
}
/// <summary>
/// 从请求体中提取模型ID
/// </summary>
private string ExtractModelIdFromRequest(ModelApiTypeEnum apiType, JsonElement input)
{
try
{
if (input.TryGetProperty("model", out var modelProperty))
{
return modelProperty.GetString() ?? string.Empty;
}
}
catch
{
// 忽略解析错误
}
throw new UserFriendlyException("无法从请求中获取模型ID请在URL参数中指定modelId");
}
}

View File

@@ -3,14 +3,17 @@ using Microsoft.AspNetCore.Authorization;
using Microsoft.AspNetCore.Hosting;
using Microsoft.AspNetCore.Http;
using Microsoft.AspNetCore.Mvc;
using SqlSugar;
using Volo.Abp;
using Volo.Abp.Application.Services;
using Volo.Abp.BackgroundJobs;
using Volo.Abp.Guids;
using Volo.Abp.Users;
using Yi.Framework.AiHub.Application.Contracts.Dtos;
using Yi.Framework.AiHub.Application.Contracts.Dtos.Chat;
using Yi.Framework.AiHub.Application.Jobs;
using Yi.Framework.AiHub.Domain.Entities.Chat;
using Yi.Framework.AiHub.Domain.Entities.Model;
using Yi.Framework.AiHub.Domain.Extensions;
using Yi.Framework.AiHub.Domain.Managers;
using Yi.Framework.AiHub.Domain.Shared.Consts;
@@ -32,6 +35,8 @@ public class AiImageService : ApplicationService
private readonly ModelManager _modelManager;
private readonly IGuidGenerator _guidGenerator;
private readonly IWebHostEnvironment _webHostEnvironment;
private readonly TokenManager _tokenManager;
private readonly ISqlSugarRepository<AiModelEntity> _aiModelRepository;
public AiImageService(
ISqlSugarRepository<ImageStoreTaskAggregateRoot> imageTaskRepository,
@@ -40,7 +45,8 @@ public class AiImageService : ApplicationService
PremiumPackageManager premiumPackageManager,
ModelManager modelManager,
IGuidGenerator guidGenerator,
IWebHostEnvironment webHostEnvironment)
IWebHostEnvironment webHostEnvironment, TokenManager tokenManager,
ISqlSugarRepository<AiModelEntity> aiModelRepository)
{
_imageTaskRepository = imageTaskRepository;
_backgroundJobManager = backgroundJobManager;
@@ -49,6 +55,8 @@ public class AiImageService : ApplicationService
_modelManager = modelManager;
_guidGenerator = guidGenerator;
_webHostEnvironment = webHostEnvironment;
_tokenManager = tokenManager;
_aiModelRepository = aiModelRepository;
}
/// <summary>
@@ -65,6 +73,13 @@ public class AiImageService : ApplicationService
// 黑名单校验
await _aiBlacklistManager.VerifiyAiBlacklist(userId);
//校验token
if (input.TokenId is not null)
{
await _tokenManager.ValidateTokenAsync(input.TokenId, input.ModelId);
}
// VIP校验
if (!CurrentUser.IsAiVip())
{
@@ -86,32 +101,23 @@ public class AiImageService : ApplicationService
var task = new ImageStoreTaskAggregateRoot
{
Prompt = input.Prompt,
ReferenceImagesBase64 = input.ReferenceImagesBase64 ?? new List<string>(),
ReferenceImagesPrefixBase64 = input.ReferenceImagesPrefixBase64 ?? new List<string>(),
ReferenceImagesUrl = new List<string>(),
TaskStatus = TaskStatusEnum.Processing,
UserId = userId
UserId = userId,
UserName = CurrentUser.UserName,
TokenId = input.TokenId,
ModelId = input.ModelId
};
await _imageTaskRepository.InsertAsync(task);
var taskId = task.Id;
// 构建请求JSON
var requestJson = JsonSerializer.Serialize(new
{
prompt = input.Prompt,
referenceImages = input.ReferenceImagesBase64
});
// 入队后台任务
await _backgroundJobManager.EnqueueAsync(new ImageGenerationJobArgs
{
TaskId = taskId,
ModelId = input.ModelId,
RequestJson = requestJson,
UserId = userId
TaskId = task.Id,
});
return taskId;
return task.Id;
}
/// <summary>
@@ -134,12 +140,15 @@ public class AiImageService : ApplicationService
{
Id = task.Id,
Prompt = task.Prompt,
ReferenceImagesBase64 = task.ReferenceImagesBase64,
ReferenceImagesUrl = task.ReferenceImagesUrl,
StoreBase64 = task.StoreBase64,
// ReferenceImagesBase64 = task.ReferenceImagesBase64,
// ReferenceImagesUrl = task.ReferenceImagesUrl,
// StoreBase64 = task.StoreBase64,
StoreUrl = task.StoreUrl,
TaskStatus = task.TaskStatus,
CreationTime = task.CreationTime
PublishStatus = task.PublishStatus,
Categories = task.Categories,
CreationTime = task.CreationTime,
ErrorInfo = task.ErrorInfo,
};
}
@@ -149,6 +158,7 @@ public class AiImageService : ApplicationService
/// <param name="base64Data">Base64图片数据包含前缀如 data:image/png;base64,</param>
/// <returns>图片访问URL</returns>
[HttpPost("ai-image/upload-base64")]
[AllowAnonymous]
public async Task<string> UploadBase64ToUrlAsync([FromBody] string base64Data)
{
if (string.IsNullOrWhiteSpace(base64Data))
@@ -171,6 +181,7 @@ public class AiImageService : ApplicationService
{
mimeType = header.Split(':')[1].Split(';')[0];
}
base64Content = parts[1];
}
}
@@ -197,57 +208,182 @@ public class AiImageService : ApplicationService
throw new UserFriendlyException("Base64格式无效");
}
// 创建存储目录
var uploadPath = Path.Combine(_webHostEnvironment.ContentRootPath, "wwwroot", "ai-images");
// ==============================
// ✅ 按日期创建目录yyyyMMdd
// ==============================
var dateFolder = DateTime.Now.ToString("yyyyMMdd");
var uploadPath = Path.Combine(
_webHostEnvironment.ContentRootPath,
"wwwroot",
"ai-images",
dateFolder
);
if (!Directory.Exists(uploadPath))
{
Directory.CreateDirectory(uploadPath);
}
// 生成文件名并保存
// 保存文件
var fileId = _guidGenerator.Create();
var fileName = $"{fileId}{extension}";
var filePath = Path.Combine(uploadPath, fileName);
await File.WriteAllBytesAsync(filePath, imageBytes);
// 返回访问URL
return $"/ai-images/{fileName}";
// 返回包含日期目录的访问URL
return $"/wwwroot/ai-images/{dateFolder}/{fileName}";
}
/// <summary>
/// 分页查询任务列表
/// 分页查询我的任务列表
/// </summary>
/// <param name="input">分页查询参数</param>
/// <returns>任务列表</returns>
[HttpGet("ai-image/tasks")]
public async Task<PagedResult<ImageTaskOutput>> GetTaskPageAsync([FromQuery] ImageTaskPageInput input)
[HttpGet("ai-image/my-tasks")]
public async Task<PagedResult<ImageTaskOutput>> GetMyTaskPageAsync([FromQuery] ImageMyTaskPageInput input)
{
var userId = CurrentUser.GetId();
var query = _imageTaskRepository._DbQueryable
RefAsync<int> total = 0;
var output = await _imageTaskRepository._DbQueryable
.Where(x => x.UserId == userId)
.WhereIF(input.TaskStatus.HasValue, x => x.TaskStatus == input.TaskStatus!.Value)
.OrderByDescending(x => x.CreationTime);
var total = await query.CountAsync();
var items = await query
.Skip((input.PageIndex - 1) * input.PageSize)
.Take(input.PageSize)
.WhereIF(input.TaskStatus is not null, x => x.TaskStatus == input.TaskStatus)
.WhereIF(!string.IsNullOrWhiteSpace(input.Prompt), x => x.Prompt.Contains(input.Prompt))
.WhereIF(input.PublishStatus is not null, x => x.PublishStatus == input.PublishStatus)
.WhereIF(input.StartTime is not null && input.EndTime is not null,
x => x.CreationTime >= input.StartTime && x.CreationTime <= input.EndTime)
.OrderByDescending(x => x.CreationTime)
.Select(x => new ImageTaskOutput
{
Id = x.Id,
Prompt = x.Prompt,
ReferenceImagesBase64 = x.ReferenceImagesBase64,
ReferenceImagesUrl = x.ReferenceImagesUrl,
StoreBase64 = x.StoreBase64,
StoreUrl = x.StoreUrl,
TaskStatus = x.TaskStatus,
CreationTime = x.CreationTime
PublishStatus = x.PublishStatus,
Categories = x.Categories,
CreationTime = x.CreationTime,
ErrorInfo = x.ErrorInfo,
UserName = x.UserName,
UserId = x.UserId,
IsAnonymous = x.IsAnonymous
})
.ToListAsync();
.ToPageListAsync(input.SkipCount, input.MaxResultCount, total);
return new PagedResult<ImageTaskOutput>(total, items);
return new PagedResult<ImageTaskOutput>(total, output);
}
/// <summary>
/// 删除个人图片
/// </summary>
/// <param name="ids"></param>
[HttpDelete("ai-image/my-tasks")]
public async Task DeleteMyTaskAsync([FromQuery] List<Guid> ids)
{
var userId = CurrentUser.GetId();
await _imageTaskRepository.DeleteAsync(x => ids.Contains(x.Id) && x.UserId == userId);
}
/// <summary>
/// 分页查询图片广场(已发布的图片)
/// </summary>
[HttpGet("ai-image/plaza")]
[AllowAnonymous]
public async Task<PagedResult<ImageTaskOutput>> GetPlazaPageAsync([FromQuery] ImagePlazaPageInput input)
{
RefAsync<int> total = 0;
var output = await _imageTaskRepository._DbQueryable
.Where(x => x.PublishStatus == PublishStatusEnum.Published)
.Where(x => x.TaskStatus == TaskStatusEnum.Success)
.WhereIF(input.TaskStatus is not null, x => x.TaskStatus == input.TaskStatus)
.WhereIF(!string.IsNullOrWhiteSpace(input.Prompt), x => x.Prompt.Contains(input.Prompt))
.WhereIF(!string.IsNullOrWhiteSpace(input.Categories),
x => SqlFunc.JsonLike(x.Categories, input.Categories))
.WhereIF(!string.IsNullOrWhiteSpace(input.UserName), x => x.UserName.Contains(input.UserName))
.WhereIF(input.StartTime is not null && input.EndTime is not null,
x => x.CreationTime >= input.StartTime && x.CreationTime <= input.EndTime)
.OrderByDescending(x => x.CreationTime)
.Select(x => new ImageTaskOutput
{
Id = x.Id,
Prompt = x.Prompt,
IsAnonymous = x.IsAnonymous,
StoreUrl = x.StoreUrl,
TaskStatus = x.TaskStatus,
PublishStatus = x.PublishStatus,
Categories = x.Categories,
CreationTime = x.CreationTime,
ErrorInfo = null,
UserName = x.UserName,
UserId = x.UserId,
})
.ToPageListAsync(input.SkipCount, input.MaxResultCount, total);
;
output.ForEach(x =>
{
if (x.IsAnonymous)
{
x.UserName = null;
x.UserId = null;
}
});
return new PagedResult<ImageTaskOutput>(total, output);
}
/// <summary>
/// 发布图片到广场
/// </summary>
[HttpPost("ai-image/publish")]
public async Task PublishAsync([FromBody] PublishImageInput input)
{
var userId = CurrentUser.GetId();
var task = await _imageTaskRepository.GetFirstAsync(x => x.Id == input.TaskId && x.UserId == userId);
if (task == null)
{
throw new UserFriendlyException("任务不存在或无权访问");
}
if (task.TaskStatus != TaskStatusEnum.Success)
{
throw new UserFriendlyException("只有已完成的任务才能发布");
}
if (task.PublishStatus == PublishStatusEnum.Published)
{
throw new UserFriendlyException("该任务已发布");
}
//设置发布
task.SetPublish(input.IsAnonymous, input.Categories);
await _imageTaskRepository.UpdateAsync(task);
}
/// <summary>
/// 获取图片模型列表
/// </summary>
/// <returns></returns>
[HttpPost("ai-image/model")]
[AllowAnonymous]
public async Task<List<ModelGetListOutput>> GetModelAsync()
{
var output = await _aiModelRepository._DbQueryable
.Where(x=>x.IsEnabled==true)
.Where(x => x.ModelType == ModelTypeEnum.Image)
.Where(x => x.ModelApiType == ModelApiTypeEnum.GenerateContent)
.OrderByDescending(x => x.OrderNum)
.Select(x => new ModelGetListOutput
{
Id = x.Id,
ModelId = x.ModelId,
ModelName = x.Name,
ModelDescribe = x.Description,
Remark = x.Description,
IsPremiumPackage = x.IsPremium
}).ToListAsync();
return output;
}
}
@@ -272,4 +408,4 @@ public class PagedResult<T>
Total = total;
Items = items;
}
}
}

View File

@@ -35,8 +35,9 @@ public class ModelService : ApplicationService, IModelService
{
RefAsync<int> total = 0;
// 查询所有未删除的模型使用WhereIF动态添加筛选条件
// 查询所有未删除且已启用的模型使用WhereIF动态添加筛选条件
var modelIds = (await _modelRepository._DbQueryable
.Where(x => x.IsEnabled)
.WhereIF(!string.IsNullOrWhiteSpace(input.SearchKey), x =>
x.Name.Contains(input.SearchKey) || x.ModelId.Contains(input.SearchKey))
.WhereIF(input.ProviderNames is not null, x =>
@@ -51,6 +52,7 @@ public class ModelService : ApplicationService, IModelService
.ToPageListAsync(input.SkipCount, input.MaxResultCount, total));
var entities = await _modelRepository._DbQueryable.Where(x => modelIds.Contains(x.ModelId))
.Where(x => x.IsEnabled)
.OrderBy(x => x.OrderNum)
.OrderBy(x => x.Name).ToListAsync();
@@ -77,10 +79,9 @@ public class ModelService : ApplicationService, IModelService
public async Task<List<string>> GetProviderListAsync()
{
var providers = await _modelRepository._DbQueryable
.Where(x => !x.IsDeleted)
.Where(x => x.IsEnabled)
.Where(x => !string.IsNullOrEmpty(x.ProviderName))
.GroupBy(x => x.ProviderName)
.OrderBy(x => x.OrderNum)
.Select(x => x.ProviderName)
.ToListAsync();

View File

@@ -84,7 +84,8 @@ public class SessionService : CrudAppService<SessionAggregateRoot, SessionDto, G
RefAsync<int> total = 0;
var userId = CurrentUser.GetId();
var entities = await _repository._DbQueryable
.Where(x=>x.UserId == userId)
.Where(x => x.UserId == userId)
.WhereIF(input.SessionType.HasValue, x => x.SessionType == input.SessionType!.Value)
.OrderByDescending(x => x.Id)
.ToPageListAsync(input.SkipCount, input.MaxResultCount, total);
return new PagedResultDto<SessionDto>(total, entities.Adapt<List<SessionDto>>());

View File

@@ -26,6 +26,7 @@ public class TokenService : ApplicationService
private readonly ISqlSugarRepository<TokenAggregateRoot> _tokenRepository;
private readonly ISqlSugarRepository<UsageStatisticsAggregateRoot> _usageStatisticsRepository;
private readonly ModelManager _modelManager;
public TokenService(
ISqlSugarRepository<TokenAggregateRoot> tokenRepository,
ISqlSugarRepository<UsageStatisticsAggregateRoot> usageStatisticsRepository,
@@ -90,7 +91,7 @@ public class TokenService : ApplicationService
}
[HttpGet("token/select-list")]
public async Task<List<TokenSelectListOutputDto>> GetSelectListAsync()
public async Task<List<TokenSelectListOutputDto>> GetSelectListAsync([FromQuery] bool? includeDefault = true)
{
var userId = CurrentUser.GetId();
var tokens = await _tokenRepository._DbQueryable
@@ -103,13 +104,17 @@ public class TokenService : ApplicationService
Name = x.Name,
IsDisabled = x.IsDisabled
}).ToListAsync();
tokens.Insert(0,new TokenSelectListOutputDto
if (includeDefault == true)
{
TokenId = Guid.Empty,
Name = "默认",
IsDisabled = false
});
tokens.Insert(0, new TokenSelectListOutputDto
{
TokenId = Guid.Empty,
Name = "默认",
IsDisabled = false
});
}
return tokens;
}

View File

@@ -1,6 +1,8 @@
using Mapster;
using Microsoft.AspNetCore.Authorization;
using Microsoft.AspNetCore.Mvc;
using SqlSugar;
using Volo.Abp.Application.Dtos;
using Volo.Abp.Application.Services;
using Volo.Abp.Users;
using Yi.Framework.AiHub.Application.Contracts.Dtos.Recharge;
@@ -35,19 +37,29 @@ namespace Yi.Framework.AiHub.Application.Services
}
/// <summary>
/// 查询已登录的账户充值记录
/// 查询已登录的账户充值记录(分页)
/// </summary>
/// <returns></returns>
[Route("recharge/account")]
[Authorize]
public async Task<List<RechargeGetListOutput>> GetListByAccountAsync()
public async Task<PagedResultDto<RechargeGetListOutput>> GetListByAccountAsync([FromQuery]RechargeGetListInput input)
{
var userId = CurrentUser.Id;
var entities = await _repository._DbQueryable.Where(x => x.UserId == userId)
RefAsync<int> total = 0;
var entities = await _repository._DbQueryable
.Where(x => x.UserId == userId)
.WhereIF(input.StartTime.HasValue, x => x.CreationTime >= input.StartTime!.Value)
.WhereIF(input.EndTime.HasValue, x => x.CreationTime <= input.EndTime!.Value)
.WhereIF(input.IsFree == true, x => x.RechargeAmount == 0)
.WhereIF(input.IsFree == false, x => x.RechargeAmount > 0)
.WhereIF(input.MinRechargeAmount.HasValue, x => x.RechargeAmount >= input.MinRechargeAmount!.Value)
.WhereIF(input.MaxRechargeAmount.HasValue, x => x.RechargeAmount <= input.MaxRechargeAmount!.Value)
.OrderByDescending(x => x.CreationTime)
.ToListAsync();
.ToPageListAsync(input.SkipCount, input.MaxResultCount, total);
var output = entities.Adapt<List<RechargeGetListOutput>>();
return output;
return new PagedResultDto<RechargeGetListOutput>(total, output);
}
/// <summary>

View File

@@ -0,0 +1,203 @@
using Mapster;
using Microsoft.AspNetCore.Authorization;
using Microsoft.AspNetCore.Mvc;
using SqlSugar;
using System.Globalization;
using Volo.Abp.Application.Services;
using Yi.Framework.AiHub.Application.Contracts.Dtos.SystemStatistics;
using Yi.Framework.AiHub.Application.Contracts.IServices;
using Yi.Framework.AiHub.Domain.Entities;
using Yi.Framework.AiHub.Domain.Entities.Chat;
using Yi.Framework.AiHub.Domain.Entities.Model;
using Yi.Framework.SqlSugarCore.Abstractions;
namespace Yi.Framework.AiHub.Application.Services;
/// <summary>
/// 系统使用量统计服务实现
/// </summary>
[Authorize(Roles = "admin")]
public class SystemUsageStatisticsService : ApplicationService, ISystemUsageStatisticsService
{
private readonly ISqlSugarRepository<PremiumPackageAggregateRoot> _premiumPackageRepository;
private readonly ISqlSugarRepository<AiRechargeAggregateRoot> _rechargeRepository;
private readonly ISqlSugarRepository<MessageAggregateRoot> _messageRepository;
private readonly ISqlSugarRepository<AiModelEntity, Guid> _modelRepository;
public SystemUsageStatisticsService(
ISqlSugarRepository<PremiumPackageAggregateRoot> premiumPackageRepository,
ISqlSugarRepository<AiRechargeAggregateRoot> rechargeRepository,
ISqlSugarRepository<MessageAggregateRoot> messageRepository,
ISqlSugarRepository<AiModelEntity, Guid> modelRepository)
{
_premiumPackageRepository = premiumPackageRepository;
_rechargeRepository = rechargeRepository;
_messageRepository = messageRepository;
_modelRepository = modelRepository;
}
/// <summary>
/// 获取利润统计数据
/// </summary>
[HttpPost("system-statistics/profit")]
public async Task<ProfitStatisticsOutput> GetProfitStatisticsAsync(ProfitStatisticsInput input)
{
// 1. 获取尊享包总消耗和剩余库存
var premiumPackages = await _premiumPackageRepository._DbQueryable.ToListAsync();
long totalUsedTokens = premiumPackages.Sum(p => p.UsedTokens);
long totalRemainingTokens = premiumPackages.Sum(p => p.RemainingTokens);
// 2. 计算1亿Token成本
decimal costPerHundredMillion = totalUsedTokens > 0
? input.CurrentCost / (totalUsedTokens / 100000000m)
: 0;
// 3. 计算总成本(剩余+已使用的总成本)
long totalTokens = totalUsedTokens + totalRemainingTokens;
decimal totalCost = totalTokens > 0
? (totalTokens / 100000000m) * costPerHundredMillion
: 0;
// 4. 获取总收益(RechargeType=PremiumPackage的充值金额总和)
decimal totalRevenue = await _rechargeRepository._DbQueryable
.Where(x => x.RechargeType == Domain.Shared.Enums.RechargeTypeEnum.PremiumPackage)
.SumAsync(x => x.RechargeAmount);
// 5. 计算利润率
decimal profitRate = totalCost > 0
? (totalRevenue / totalCost - 1) * 100
: 0;
// 6. 按200售价计算成本
decimal costAt200Price = totalRevenue > 0
? (totalCost / totalRevenue) * 200
: 0;
// 7. 格式化日期
var today = DateTime.Now;
string dayOfWeek = today.ToString("dddd", new CultureInfo("zh-CN"));
string weekDay = dayOfWeek switch
{
"星期一" => "周1",
"星期二" => "周2",
"星期三" => "周3",
"星期四" => "周4",
"星期五" => "周5",
"星期六" => "周6",
"星期日" => "周日",
_ => dayOfWeek
};
return new ProfitStatisticsOutput
{
Date = $"{today:M月d日} {weekDay}",
TotalUsedTokens = totalUsedTokens,
TotalUsedTokensInHundredMillion = totalUsedTokens / 100000000m,
TotalRemainingTokens = totalRemainingTokens,
TotalRemainingTokensInHundredMillion = totalRemainingTokens / 100000000m,
CurrentCost = input.CurrentCost,
CostPerHundredMillion = costPerHundredMillion,
TotalCost = totalCost,
TotalRevenue = totalRevenue,
ProfitRate = profitRate,
CostAt200Price = costAt200Price
};
}
/// <summary>
/// 获取指定日期各模型Token统计
/// </summary>
[HttpPost("system-statistics/token")]
public async Task<TokenStatisticsOutput> GetTokenStatisticsAsync(TokenStatisticsInput input)
{
var day = input.Date.Date;
var nextDay = day.AddDays(1);
// 1. 获取所有尊享模型(包含被禁用的),按ModelId去重
var premiumModels = await _modelRepository._DbQueryable
.Where(x => x.IsPremium)
.ToListAsync();
if (premiumModels.Count == 0)
{
return new TokenStatisticsOutput
{
Date = FormatDate(day),
ModelStatistics = new List<ModelTokenStatisticsDto>()
};
}
// 按ModelId去重,保留第一个模型的名称
var distinctModels = premiumModels
.GroupBy(x => x.ModelId)
.Select(g => g.First())
.ToList();
var modelIds = distinctModels.Select(x => x.ModelId).ToList();
// 2. 查询指定日期内各模型的Token使用统计
var modelStats = await _messageRepository._DbQueryable
.Where(x => modelIds.Contains(x.ModelId))
.Where(x => x.CreationTime >= day && x.CreationTime < nextDay)
.Where(x => x.Role == "system")
.GroupBy(x => x.ModelId)
.Select(x => new
{
ModelId = x.ModelId,
Tokens = SqlFunc.AggregateSum(x.TokenUsage.TotalTokenCount),
Count = SqlFunc.AggregateCount(x.Id)
})
.ToListAsync();
var modelStatDict = modelStats.ToDictionary(x => x.ModelId, x => x);
// 3. 构建结果列表,使用去重后的模型列表
var result = new List<ModelTokenStatisticsDto>();
foreach (var model in distinctModels)
{
modelStatDict.TryGetValue(model.ModelId, out var stat);
long tokens = stat?.Tokens ?? 0;
long count = stat?.Count ?? 0;
// 这里成本设为0,因为需要前端传入或者从配置中获取
decimal cost = 0;
decimal costPerHundredMillion = tokens > 0 && cost > 0
? cost / (tokens / 100000000m)
: 0;
result.Add(new ModelTokenStatisticsDto
{
ModelId = model.ModelId,
ModelName = model.Name,
Tokens = tokens,
TokensInWan = tokens / 10000m,
Count = count,
Cost = cost,
CostPerHundredMillion = costPerHundredMillion
});
}
return new TokenStatisticsOutput
{
Date = FormatDate(day),
ModelStatistics = result
};
}
private string FormatDate(DateTime date)
{
string dayOfWeek = date.ToString("dddd", new CultureInfo("zh-CN"));
string weekDay = dayOfWeek switch
{
"星期一" => "周1",
"星期二" => "周2",
"星期三" => "周3",
"星期四" => "周4",
"星期五" => "周5",
"星期六" => "周6",
"星期日" => "周日",
_ => dayOfWeek
};
return $"{date:M月d日} {weekDay}";
}
}

View File

@@ -30,6 +30,7 @@ public class UsageStatisticsService : ApplicationService, IUsageStatisticsServic
private readonly ISqlSugarRepository<PremiumPackageAggregateRoot> _premiumPackageRepository;
private readonly ISqlSugarRepository<TokenAggregateRoot> _tokenRepository;
private readonly ModelManager _modelManager;
public UsageStatisticsService(
ISqlSugarRepository<MessageAggregateRoot> messageRepository,
ISqlSugarRepository<UsageStatisticsAggregateRoot> usageStatisticsRepository,
@@ -48,7 +49,7 @@ public class UsageStatisticsService : ApplicationService, IUsageStatisticsServic
/// 获取当前用户近7天的Token消耗统计
/// </summary>
/// <returns>每日Token使用量列表</returns>
public async Task<List<DailyTokenUsageDto>> GetLast7DaysTokenUsageAsync([FromQuery]UsageStatisticsGetInput input)
public async Task<List<DailyTokenUsageDto>> GetLast7DaysTokenUsageAsync([FromQuery] UsageStatisticsGetInput input)
{
var userId = CurrentUser.GetId();
var endDate = DateTime.Today;
@@ -57,9 +58,9 @@ public class UsageStatisticsService : ApplicationService, IUsageStatisticsServic
// 从Message表统计近7天的token消耗
var dailyUsage = await _messageRepository._DbQueryable
.Where(x => x.UserId == userId)
.Where(x => x.Role == "assistant" || x.Role == "system")
.Where(x => x.Role == "system")
.Where(x => x.CreationTime >= startDate && x.CreationTime < endDate.AddDays(1))
.WhereIF(input.TokenId.HasValue,x => x.TokenId == input.TokenId)
.WhereIF(input.TokenId.HasValue, x => x.TokenId == input.TokenId)
.GroupBy(x => x.CreationTime.Date)
.Select(g => new
{
@@ -89,14 +90,14 @@ public class UsageStatisticsService : ApplicationService, IUsageStatisticsServic
/// 获取当前用户各个模型的Token消耗量及占比
/// </summary>
/// <returns>模型Token使用量列表</returns>
public async Task<List<ModelTokenUsageDto>> GetModelTokenUsageAsync([FromQuery]UsageStatisticsGetInput input)
public async Task<List<ModelTokenUsageDto>> GetModelTokenUsageAsync([FromQuery] UsageStatisticsGetInput input)
{
var userId = CurrentUser.GetId();
// 从UsageStatistics表获取各模型的token消耗统计按ModelId聚合因为同一模型可能有多个TokenId的记录
var modelUsages = await _usageStatisticsRepository._DbQueryable
.Where(x => x.UserId == userId)
.WhereIF(input.TokenId.HasValue,x => x.TokenId == input.TokenId)
.WhereIF(input.TokenId.HasValue, x => x.TokenId == input.TokenId)
.GroupBy(x => x.ModelId)
.Select(x => new
{
@@ -221,11 +222,133 @@ public class UsageStatisticsService : ApplicationService, IUsageStatisticsServic
var result = tokenUsages.Select(x => new TokenPremiumUsageDto
{
TokenId = x.TokenId,
TokenName = x.TokenId == Guid.Empty ? "默认" : (tokenNameDict.TryGetValue(x.TokenId, out var name) ? name : "其他"),
TokenName = x.TokenId == Guid.Empty
? "默认"
: (tokenNameDict.TryGetValue(x.TokenId, out var name) ? name : "其他"),
Tokens = x.TotalTokenCount,
Percentage = totalTokens > 0 ? Math.Round((decimal)x.TotalTokenCount / totalTokens * 100, 2) : 0
}).OrderByDescending(x => x.Tokens).ToList();
return result;
}
/// <summary>
/// 获取当前用户近24小时每小时Token消耗统计柱状图
/// </summary>
/// <returns>每小时Token使用量列表包含各模型堆叠数据</returns>
public async Task<List<HourlyTokenUsageDto>> GetLast24HoursTokenUsageAsync(
[FromQuery] UsageStatisticsGetInput input)
{
var userId = CurrentUser.GetId();
var now = DateTime.Now;
var startTime = now.AddHours(-23); // 滚动24小时从23小时前到现在
var startHour = new DateTime(startTime.Year, startTime.Month, startTime.Day, startTime.Hour, 0, 0);
// 从Message表查询近24小时的数据只选择需要的字段
var messages = await _messageRepository._DbQueryable
.Where(x => x.UserId == userId)
.Where(x => x.Role == "system")
.Where(x => x.CreationTime >= startHour)
.WhereIF(input.TokenId.HasValue, x => x.TokenId == input.TokenId)
.Select(x => new
{
x.CreationTime,
x.ModelId,
x.TokenUsage.TotalTokenCount
})
.ToListAsync();
// 在内存中按小时和模型分组统计
var hourlyGrouped = messages
.GroupBy(x => new
{
Hour = new DateTime(x.CreationTime.Year, x.CreationTime.Month, x.CreationTime.Day, x.CreationTime.Hour,
0, 0),
x.ModelId
})
.Select(g => new
{
g.Key.Hour,
g.Key.ModelId,
Tokens = g.Sum(x => x.TotalTokenCount)
})
.ToList();
// 生成完整的24小时数据
var result = new List<HourlyTokenUsageDto>();
for (int i = 0; i < 24; i++)
{
var hour = startHour.AddHours(i);
var hourData = hourlyGrouped.Where(x => x.Hour == hour).ToList();
var modelBreakdown = hourData.Select(x => new ModelTokenBreakdownDto
{
ModelId = x.ModelId,
Tokens = x.Tokens
}).ToList();
result.Add(new HourlyTokenUsageDto
{
Hour = hour,
TotalTokens = modelBreakdown.Sum(x => x.Tokens),
ModelBreakdown = modelBreakdown
});
}
return result;
}
/// <summary>
/// 获取当前用户今日各模型使用量统计(卡片列表)
/// </summary>
/// <returns>模型今日使用量列表包含使用次数和总Token</returns>
public async Task<List<ModelTodayUsageDto>> GetTodayModelUsageAsync([FromQuery] UsageStatisticsGetInput input)
{
var userId = CurrentUser.GetId();
var todayStart = DateTime.Today; // 今天凌晨0点
var tomorrowStart = todayStart.AddDays(1);
// 从Message表查询今天的数据只选择需要的字段
var messages = await _messageRepository._DbQueryable
.Where(x => x.UserId == userId)
.Where(x => x.Role == "system")
.Where(x => x.CreationTime >= todayStart && x.CreationTime < tomorrowStart)
.WhereIF(input.TokenId.HasValue, x => x.TokenId == input.TokenId)
.Select(x => new
{
x.ModelId,
x.TokenUsage.TotalTokenCount
})
.ToListAsync();
// 在内存中按模型分组统计
var modelStats = messages
.GroupBy(x => x.ModelId)
.Select(g => new ModelTodayUsageDto
{
ModelId = g.Key,
UsageCount = g.Count(),
TotalTokens = g.Sum(x => x.TotalTokenCount)
})
.OrderByDescending(x => x.TotalTokens)
.ToList();
if (modelStats.Count > 0)
{
var modelIds = modelStats.Select(x => x.ModelId).ToList();
var modelDic = await _modelManager._aiModelRepository._DbQueryable.Where(x => modelIds.Contains(x.ModelId))
.Distinct()
.Where(x=>x.IsEnabled)
.ToDictionaryAsync<string>(x => x.ModelId, y => y.IconUrl);
modelStats.ForEach(x =>
{
if (modelDic.TryGetValue(x.ModelId, out var icon))
{
x.IconUrl = icon;
}
});
}
return modelStats;
}
}

View File

@@ -15,10 +15,17 @@ public class PremiumPackageConst
"gemini-3-pro-high",
"gemini-3-pro-image-preview",
"gpt-5.2-codex-xhigh",
"gpt-5.2-codex",
"glm-4.7",
"yi-claude-sonnet-4-5-20250929",
"yi-claude-haiku-4-5-20251001",
"yi-claude-opus-4-5-20251101",
"yi-gpt-5.2",
"yi-gpt-5.2-codex",
"yi-gemini-3-pro-high",
"yi-gemini-3-pro",
];
}

View File

@@ -1,4 +1,6 @@
namespace Yi.Framework.AiHub.Domain.Shared.Dtos;
using Yi.Framework.AiHub.Domain.Shared.Enums;
namespace Yi.Framework.AiHub.Domain.Shared.Dtos;
public class AiModelDescribe
{
@@ -61,4 +63,14 @@ public class AiModelDescribe
/// 模型倍率
/// </summary>
public decimal Multiplier { get; set; }
/// <summary>
/// 是否为尊享模型
/// </summary>
public bool IsPremium { get; set; }
/// <summary>
/// 模型类型(聊天/图片等)
/// </summary>
public ModelTypeEnum ModelType { get; set; }
}

View File

@@ -18,39 +18,7 @@ public class AnthropicStreamDto
[JsonPropertyName("usage")] public AnthropicCompletionDtoUsage? Usage { get; set; }
[JsonPropertyName("error")] public AnthropicStreamErrorDto? Error { get; set; }
[JsonIgnore]
public ThorUsageResponse TokenUsage => new ThorUsageResponse
{
PromptTokens = Usage?.InputTokens + Usage?.CacheCreationInputTokens + Usage?.CacheReadInputTokens,
InputTokens = Usage?.InputTokens + Usage?.CacheCreationInputTokens + Usage?.CacheReadInputTokens,
OutputTokens = Usage?.OutputTokens,
InputTokensDetails = null,
CompletionTokens = Usage?.OutputTokens,
TotalTokens = Usage?.InputTokens + Usage?.CacheCreationInputTokens + Usage?.CacheReadInputTokens +
Usage?.OutputTokens,
PromptTokensDetails = null,
CompletionTokensDetails = null
};
public void SupplementalMultiplier(decimal multiplier)
{
if (this.Usage is not null)
{
this.Usage.CacheCreationInputTokens =
(int)Math.Round((this.Usage.CacheCreationInputTokens ?? 0) * multiplier);
this.Usage.CacheReadInputTokens =
(int)Math.Round((this.Usage.CacheReadInputTokens ?? 0) * multiplier);
this.Usage.InputTokens =
(int)Math.Round((this.Usage.InputTokens ?? 0) * multiplier);
this.Usage.OutputTokens =
(int)Math.Round((this.Usage.OutputTokens ?? 0) * multiplier);
}
}
}
public class AnthropicStreamErrorDto
@@ -71,6 +39,11 @@ public class AnthropicChatCompletionDtoDelta
[JsonPropertyName("partial_json")] public string? PartialJson { get; set; }
[JsonPropertyName("stop_reason")] public string? StopReason { get; set; }
[JsonPropertyName("signature")] public string? Signature { get; set; }
[JsonPropertyName("stop_sequence")] public string? StopSequence { get; set; }
}
public class AnthropicChatCompletionDtoContentBlock
@@ -115,38 +88,7 @@ public class AnthropicChatCompletionDto
public object stop_sequence { get; set; }
public AnthropicCompletionDtoUsage? Usage { get; set; }
[JsonIgnore]
public ThorUsageResponse TokenUsage => new ThorUsageResponse
{
PromptTokens = Usage?.InputTokens + Usage?.CacheCreationInputTokens + Usage?.CacheReadInputTokens,
InputTokens = Usage?.InputTokens + Usage?.CacheCreationInputTokens + Usage?.CacheReadInputTokens,
OutputTokens = Usage?.OutputTokens,
InputTokensDetails = null,
CompletionTokens = Usage?.OutputTokens,
TotalTokens = Usage?.InputTokens + Usage?.CacheCreationInputTokens + Usage?.CacheReadInputTokens +
Usage?.OutputTokens,
PromptTokensDetails = null,
CompletionTokensDetails = null
};
public void SupplementalMultiplier(decimal multiplier)
{
if (this.Usage is not null)
{
this.Usage.CacheCreationInputTokens =
(int)Math.Round((this.Usage?.CacheCreationInputTokens ?? 0) * multiplier);
this.Usage.CacheReadInputTokens =
(int)Math.Round((this.Usage?.CacheReadInputTokens ?? 0) * multiplier);
this.Usage.InputTokens =
(int)Math.Round((this.Usage?.InputTokens ?? 0) * multiplier);
this.Usage.OutputTokens =
(int)Math.Round((this.Usage?.OutputTokens ?? 0) * multiplier);
}
}
}
public class AnthropicChatCompletionDtoContent
@@ -166,6 +108,7 @@ public class AnthropicChatCompletionDtoContent
[JsonPropertyName("partial_json")] public string? PartialJson { get; set; }
public string? signature { get; set; }
}
public class AnthropicCompletionDtoUsage
@@ -181,6 +124,12 @@ public class AnthropicCompletionDtoUsage
[JsonPropertyName("output_tokens")] public int? OutputTokens { get; set; }
[JsonPropertyName("server_tool_use")] public AnthropicServerToolUse? ServerToolUse { get; set; }
[JsonPropertyName("cache_creation")] public object? CacheCreation { get; set; }
[JsonPropertyName("service_tier")] public string? ServiceTier { get; set; }
}
public class AnthropicServerToolUse

View File

@@ -6,6 +6,83 @@ namespace Yi.Framework.AiHub.Domain.Shared.Dtos.Gemini;
public static class GeminiGenerateContentAcquirer
{
/// <summary>
/// 从请求体中提取用户最后一条消息内容
/// 路径: contents[last].parts[last].text
/// </summary>
public static string GetLastUserContent(JsonElement request)
{
var contents = request.GetPath("contents");
if (!contents.HasValue || contents.Value.ValueKind != JsonValueKind.Array)
{
return string.Empty;
}
var contentsArray = contents.Value.EnumerateArray().ToList();
if (contentsArray.Count == 0)
{
return string.Empty;
}
var lastContent = contentsArray[^1];
var parts = lastContent.GetPath("parts");
if (!parts.HasValue || parts.Value.ValueKind != JsonValueKind.Array)
{
return string.Empty;
}
var partsArray = parts.Value.EnumerateArray().ToList();
if (partsArray.Count == 0)
{
return string.Empty;
}
// 获取最后一个 part 的 text
var lastPart = partsArray[^1];
return lastPart.GetPath("text").GetString() ?? string.Empty;
}
/// <summary>
/// 从响应中提取文本内容(非 thought 类型)
/// 路径: candidates[0].content.parts[].text (where thought != true)
/// </summary>
public static string GetTextContent(JsonElement response)
{
var candidates = response.GetPath("candidates");
if (!candidates.HasValue || candidates.Value.ValueKind != JsonValueKind.Array)
{
return string.Empty;
}
var candidatesArray = candidates.Value.EnumerateArray().ToList();
if (candidatesArray.Count == 0)
{
return string.Empty;
}
var parts = candidatesArray[0].GetPath("content", "parts");
if (!parts.HasValue || parts.Value.ValueKind != JsonValueKind.Array)
{
return string.Empty;
}
// 遍历所有 parts只取非 thought 的 text
foreach (var part in parts.Value.EnumerateArray())
{
var isThought = part.GetPath("thought").GetBool();
if (!isThought)
{
var text = part.GetPath("text").GetString();
if (!string.IsNullOrEmpty(text))
{
return text;
}
}
}
return string.Empty;
}
public static ThorUsageResponse? GetUsage(JsonElement response)
{
var usage = response.GetPath("usageMetadata");
@@ -20,7 +97,6 @@ public static class GeminiGenerateContentAcquirer
+ usage.Value.GetPath("thoughtsTokenCount").GetInt()
+ usage.Value.GetPath("toolUsePromptTokenCount").GetInt();
return new ThorUsageResponse
{
PromptTokens = inputTokens,
@@ -32,14 +108,159 @@ public static class GeminiGenerateContentAcquirer
}
/// <summary>
/// 获取图片url包含前缀
/// 获取图片 base64包含 data:image 前缀
/// Step 1: 递归遍历整个 JSON 查找最后一个 base64
/// Step 2: 从 text 中查找 markdown 图片
/// </summary>
/// <param name="response"></param>
/// <returns></returns>
public static string GetImageBase64(JsonElement response)
public static string GetImagePrefixBase64(JsonElement response)
{
//todo
//获取他的base64字符串
// Step 1: 递归遍历整个 JSON 查找最后一个 base64
string? lastBase64 = null;
string? lastMimeType = null;
CollectLastBase64(response, ref lastBase64, ref lastMimeType);
if (!string.IsNullOrEmpty(lastBase64))
{
var mimeType = lastMimeType ?? "image/png";
return $"data:{mimeType};base64,{lastBase64}";
}
// Step 2: 从 text 中查找 markdown 图片
return FindMarkdownImageInResponse(response);
}
/// <summary>
/// 递归遍历 JSON 查找最后一个 base64
/// </summary>
private static void CollectLastBase64(JsonElement element, ref string? lastBase64, ref string? lastMimeType, int minLength = 100)
{
switch (element.ValueKind)
{
case JsonValueKind.Object:
string? currentMimeType = null;
string? currentData = null;
foreach (var prop in element.EnumerateObject())
{
var name = prop.Name.ToLowerInvariant();
// 记录 mimeType / mime_type
if (name is "mimetype" or "mime_type" && prop.Value.ValueKind == JsonValueKind.String)
{
currentMimeType = prop.Value.GetString();
}
// 记录 data 字段(检查是否像 base64
else if (name == "data" && prop.Value.ValueKind == JsonValueKind.String)
{
var val = prop.Value.GetString();
if (!string.IsNullOrEmpty(val) && val.Length >= minLength && LooksLikeBase64(val))
{
currentData = val;
}
}
else
{
// 递归处理其他属性
CollectLastBase64(prop.Value, ref lastBase64, ref lastMimeType, minLength);
}
}
// 如果当前对象有 data更新为"最后一个"
if (currentData != null)
{
lastBase64 = currentData;
lastMimeType = currentMimeType;
}
break;
case JsonValueKind.Array:
foreach (var item in element.EnumerateArray())
{
CollectLastBase64(item, ref lastBase64, ref lastMimeType, minLength);
}
break;
}
}
/// <summary>
/// 检查字符串是否像 base64
/// </summary>
private static bool LooksLikeBase64(string str)
{
// 常见图片 base64 开头: JPEG(/9j/), PNG(iVBOR), GIF(R0lGO), WebP(UklGR)
if (str.StartsWith("/9j/") || str.StartsWith("iVBOR") ||
str.StartsWith("R0lGO") || str.StartsWith("UklGR"))
{
return true;
}
// 检查前100个字符是否都是 base64 合法字符
return str.Take(100).All(c => char.IsLetterOrDigit(c) || c == '+' || c == '/' || c == '=');
}
/// <summary>
/// 递归查找 text 字段中的 markdown 图片
/// </summary>
private static string FindMarkdownImageInResponse(JsonElement element)
{
var allTexts = new List<string>();
CollectTextFields(element, allTexts);
// 从最后一个 text 开始查找
for (int i = allTexts.Count - 1; i >= 0; i--)
{
var text = allTexts[i];
// markdown 图片格式: ![image](data:image/png;base64,xxx)
var startMarker = "(data:image/";
var startIndex = text.IndexOf(startMarker, StringComparison.Ordinal);
if (startIndex < 0)
{
continue;
}
startIndex += 1; // 跳过 "("
var endIndex = text.IndexOf(')', startIndex);
if (endIndex > startIndex)
{
return text.Substring(startIndex, endIndex - startIndex);
}
}
return string.Empty;
}
/// <summary>
/// 递归收集所有 text 字段
/// </summary>
private static void CollectTextFields(JsonElement element, List<string> texts)
{
switch (element.ValueKind)
{
case JsonValueKind.Object:
foreach (var prop in element.EnumerateObject())
{
if (prop.Name == "text" && prop.Value.ValueKind == JsonValueKind.String)
{
var val = prop.Value.GetString();
if (!string.IsNullOrEmpty(val))
{
texts.Add(val);
}
}
else
{
CollectTextFields(prop.Value, texts);
}
}
break;
case JsonValueKind.Array:
foreach (var item in element.EnumerateArray())
{
CollectTextFields(item, texts);
}
break;
}
}
}

View File

@@ -101,7 +101,31 @@ public enum ActivationCodeGoodsTypeEnum
/// </summary>
[ActivationCodeGoods(price: 0, tokenAmount: 100000, vipMonths: 0, isCombo: false, isReusable: true,
isSameTypeOnce: false, displayName: "10w 尊享Token", content: "免费包")]
Premium10WFree = 100
Premium10WFree = 100,
/// <summary>
/// 0【888w 尊享Token】活动包
/// </summary>
[ActivationCodeGoods(price: 0, tokenAmount: 8880000, vipMonths: 0, isCombo: false, isReusable: false,
isSameTypeOnce: false, displayName: "888w 尊享Token", content: "888w活动赠送福利包")]
Premium888WFree = 200,
/// <summary>
/// 0【666w 尊享Token】活动包
/// </summary>
[ActivationCodeGoods(price: 0, tokenAmount: 6660000, vipMonths: 0, isCombo: false, isReusable: false,
isSameTypeOnce: false, displayName: "666w 尊享Token", content: "666w活动赠送福利包")]
Premium666WFree = 201,
/// <summary>
/// 0【100w 尊享Token】活动包
/// </summary>
[ActivationCodeGoods(price: 0, tokenAmount: 1000000, vipMonths: 0, isCombo: false, isReusable: false,
isSameTypeOnce: false, displayName: "100w 尊享Token", content: "100w活动赠送福利包")]
Premium100WFree = 202,
}
public static class ActivationCodeGoodsTypeEnumExtensions

View File

@@ -99,8 +99,8 @@ public enum GoodsTypeEnum
[Price(83.7, 3, 27.9)] [DisplayName("YiXinVip 3 month", "3个月", "短期体验")] [GoodsCategory(GoodsCategoryType.Vip)]
YiXinVip3 = 3,
[Price(155.4, 6, 25.9)] [DisplayName("YiXinVip 6 month", "6个月", "年度热销")] [GoodsCategory(GoodsCategoryType.Vip)]
YiXinVip6 = 6,
[Price(114.5, 5, 22.9)] [DisplayName("YiXinVip 5 month", "5个月", "年度热销")] [GoodsCategory(GoodsCategoryType.Vip)]
YiXinVip5 = 15,
// 尊享包服务 - 需要VIP资格才能购买
[Price(188.9, 0, 1750)]
@@ -110,10 +110,23 @@ public enum GoodsTypeEnum
PremiumPackage5000W = 101,
[Price(248.9, 0, 3500)]
[DisplayName("YiXinPremiumPackage 10000W Tokens", "1亿Tokens(推荐)", "极致性价比")]
[DisplayName("YiXinPremiumPackage 10000W Tokens", "1亿Tokens", "极致性价比")]
[GoodsCategory(GoodsCategoryType.PremiumPackage)]
[TokenAmount(100000000)]
PremiumPackage10000W = 102,
//
// [Price(238.9, 0, 3500)]
// [DisplayName("YiXinPremiumPackage 10000W Tokens", "1亿Tokens2026元旦限购", "活动9.5折特价")]
// [GoodsCategory(GoodsCategoryType.PremiumPackage)]
// [TokenAmount(100000000)]
// PremiumPackage10000W_2026 = 103,
//
// [Price(398.9, 0, 7000)]
// [DisplayName("YiXinPremiumPackage 20000W Tokens", "2亿Tokens2026元旦限购", "史上最低8.8折")]
// [GoodsCategory(GoodsCategoryType.PremiumPackage)]
// [TokenAmount(200000000)]
// PremiumPackage20000W_2026 = 104,
}
public static class GoodsTypeEnumExtensions

View File

@@ -4,15 +4,15 @@ namespace Yi.Framework.AiHub.Domain.Shared.Enums;
public enum ModelApiTypeEnum
{
[Description("OpenAI")]
OpenAi,
[Description("OpenAi Completions")]
Completions,
[Description("Claude")]
Claude,
[Description("Claude Messages")]
Messages,
[Description("Response")]
Response,
[Description("OpenAi Responses")]
Responses,
[Description("GenerateContent")]
[Description("Gemini GenerateContent")]
GenerateContent
}

View File

@@ -0,0 +1,17 @@
namespace Yi.Framework.AiHub.Domain.Shared.Enums;
/// <summary>
/// 发布状态枚举
/// </summary>
public enum PublishStatusEnum
{
/// <summary>
/// 未发布
/// </summary>
Unpublished = 0,
/// <summary>
/// 已发布
/// </summary>
Published = 1
}

View File

@@ -0,0 +1,17 @@
namespace Yi.Framework.AiHub.Domain.Shared.Enums;
/// <summary>
/// 会话类型枚举
/// </summary>
public enum SessionTypeEnum
{
/// <summary>
/// 普通聊天
/// </summary>
Chat = 0,
/// <summary>
/// Agent智能体
/// </summary>
Agent = 1
}

View File

@@ -73,18 +73,24 @@ public class AnthropicChatCompletionsService(
// 大于等于400的状态码都认为是异常
if (response.StatusCode >= HttpStatusCode.BadRequest)
{
Guid errorId = Guid.NewGuid();
var error = await response.Content.ReadAsStringAsync(cancellationToken).ConfigureAwait(false);
logger.LogError("OpenAI对话异常 请求地址:{Address}, StatusCode: {StatusCode} Response: {Response}",
options.Endpoint,
response.StatusCode, error);
throw new Exception( $"恭喜你运气爆棚遇到了错误尊享包对话异常StatusCode【{response.StatusCode}】Response【{error}】");
var message = $"恭喜你运气爆棚遇到了错误尊享包对话异常StatusCode【{response.StatusCode.GetHashCode()}】ErrorId【{errorId}】";
if (error.Contains("prompt is too long"))
{
message += $", Response: {error}";
}
logger.LogError(
$"Anthropic非流式对话异常 请求地址:{options.Endpoint},ErrorId{errorId}, StatusCode: {response.StatusCode.GetHashCode()}, Response: {error}");
throw new Exception(message);
}
var value =
await response.Content.ReadFromJsonAsync<AnthropicChatCompletionDto>(ThorJsonSerializer.DefaultOptions,
cancellationToken: cancellationToken);
return value;
}
@@ -121,12 +127,13 @@ public class AnthropicChatCompletionsService(
// 大于等于400的状态码都认为是异常
if (response.StatusCode >= HttpStatusCode.BadRequest)
{
Guid errorId = Guid.NewGuid();
var error = await response.Content.ReadAsStringAsync(cancellationToken).ConfigureAwait(false);
logger.LogError("OpenAI对话异常 请求地址:{Address}, StatusCode: {StatusCode} Response: {Response}",
options.Endpoint,
response.StatusCode, error);
logger.LogError(
$"Anthropic流式对话异常 请求地址:{options.Endpoint},ErrorId{errorId}, StatusCode: {response.StatusCode.GetHashCode()}, Response: {error}");
throw new Exception("OpenAI对话异常" + response.StatusCode);
throw new Exception(
$"恭喜你运气爆棚遇到了错误尊享包对话异常StatusCode【{response.StatusCode.GetHashCode()}】ErrorId【{errorId}】");
}
using var stream = new StreamReader(await response.Content.ReadAsStreamAsync(cancellationToken));
@@ -164,6 +171,12 @@ public class AnthropicChatCompletionsService(
data = line[OpenAIConstant.Data.Length..].Trim();
// 处理流结束标记
if (data == "[DONE]")
{
break;
}
var result = JsonSerializer.Deserialize<AnthropicStreamDto>(data,
ThorJsonSerializer.DefaultOptions);

View File

@@ -14,23 +14,18 @@ public class ImageStoreTaskAggregateRoot : FullAuditedAggregateRoot<Guid>
public string Prompt { get; set; }
/// <summary>
/// 参考图Base64
/// 参考图PrefixBase64带前缀如 data:image/png;base64,xxx
/// </summary>
[SugarColumn(IsJson = true)]
public List<string> ReferenceImagesBase64 { get; set; }
[SugarColumn(IsJson = true, ColumnDataType = StaticConfig.CodeFirst_BigString)]
public List<string> ReferenceImagesPrefixBase64 { get; set; }
/// <summary>
/// 参考图url
/// </summary>
[SugarColumn(IsJson = true)]
public List<string> ReferenceImagesUrl { get; set; }
/// <summary>
/// 图片base64
/// </summary>
public string? StoreBase64 { get; set; }
/// <summary>
/// 图片绝对路径
/// </summary>
@@ -46,6 +41,43 @@ public class ImageStoreTaskAggregateRoot : FullAuditedAggregateRoot<Guid>
/// </summary>
public Guid UserId { get; set; }
/// <summary>
/// 用户名称
/// </summary>
public string? UserName { get; set; }
/// <summary>
/// 模型id
/// </summary>
public string ModelId { get; set; }
/// <summary>
/// 错误信息
/// </summary>
[SugarColumn(ColumnDataType = StaticConfig.CodeFirst_BigString)]
public string? ErrorInfo { get; set; }
/// <summary>
/// 发布状态
/// </summary>
public PublishStatusEnum PublishStatus { get; set; } = PublishStatusEnum.Unpublished;
/// <summary>
/// 分类标签
/// </summary>
[SugarColumn(IsJson = true)]
public List<string> Categories { get; set; } = new();
/// <summary>
/// 是否匿名
/// </summary>
public bool IsAnonymous { get; set; } = false;
/// <summary>
/// 密钥id
/// </summary>
public Guid? TokenId { get; set; }
/// <summary>
/// 设置成功
/// </summary>
@@ -55,4 +87,18 @@ public class ImageStoreTaskAggregateRoot : FullAuditedAggregateRoot<Guid>
TaskStatus = TaskStatusEnum.Success;
StoreUrl = storeUrl;
}
/// <summary>
/// 设置发布
/// </summary>
/// <param name="isAnonymous"></param>
/// <param name="categories"></param>
public void SetPublish(bool isAnonymous,List<string> categories)
{
this.PublishStatus = PublishStatusEnum.Published;
this.IsAnonymous = isAnonymous;
this.Categories = categories;
}
}

View File

@@ -1,5 +1,6 @@
using SqlSugar;
using Volo.Abp.Domain.Entities.Auditing;
using Yi.Framework.AiHub.Domain.Shared.Enums;
namespace Yi.Framework.AiHub.Domain.Entities.Chat;
@@ -9,8 +10,13 @@ public class SessionAggregateRoot : FullAuditedAggregateRoot<Guid>
{
public Guid UserId { get; set; }
public string SessionTitle { get; set; }
[SugarColumn(ColumnDataType = StaticConfig.CodeFirst_BigString)]
public string SessionContent { get; set; }
public string? Remark { get; set; }
/// <summary>
/// 会话类型0-普通聊天1-Agent智能体
/// </summary>
public SessionTypeEnum SessionType { get; set; } = SessionTypeEnum.Chat;
}

View File

@@ -0,0 +1,37 @@
using SqlSugar;
using Volo.Abp.Domain.Entities.Auditing;
using Yi.Framework.Core.Data;
namespace Yi.Framework.AiHub.Domain.Entities.Model;
/// <summary>
/// AI应用快捷配置表
/// </summary>
[SugarTable("Ai_App_Shortcut")]
public class AiAppShortcutAggregateRoot : FullAuditedAggregateRoot<Guid>, IOrderNum
{
/// <summary>
/// 应用名称
/// </summary>
public string Name { get; set; }
/// <summary>
/// 应用终结点
/// </summary>
public string Endpoint { get; set; }
/// <summary>
/// 额外url
/// </summary>
public string? ExtraUrl { get; set; }
/// <summary>
/// 应用key
/// </summary>
public string ApiKey { get; set; }
/// <summary>
/// 排序
/// </summary>
public int OrderNum { get; set; }
}

View File

@@ -85,4 +85,9 @@ public class AiModelEntity : Entity<Guid>, IOrderNum, ISoftDelete
/// 是否为尊享模型
/// </summary>
public bool IsPremium { get; set; }
/// <summary>
/// 是否启用
/// </summary>
public bool IsEnabled { get; set; } = true;
}

View File

@@ -71,6 +71,7 @@ public class AiGateWayManager : DomainService
.LeftJoin<AiAppAggregateRoot>((model, app) => model.AiAppId == app.Id)
.Where((model, app) => model.ModelId == modelId)
.Where((model, app) => model.ModelApiType == modelApiType)
.Where((model, app) => model.IsEnabled)
.Select((model, app) =>
new AiModelDescribe
{
@@ -85,19 +86,23 @@ public class AiGateWayManager : DomainService
Description = model.Description,
AppExtraUrl = app.ExtraUrl,
ModelExtraInfo = model.ExtraInfo,
Multiplier = model.Multiplier
Multiplier = model.Multiplier,
IsPremium = model.IsPremium,
ModelType = model.ModelType
})
.FirstAsync();
if (aiModelDescribe is null)
{
throw new UserFriendlyException($"【{modelId}】模型当前版本【{modelApiType}】格式不支持");
}
// ✅ 统一处理 -nx 后缀(网关层模型规范化)
// ✅ 统一处理 yi- 后缀(网关层模型规范化)
if (!string.IsNullOrEmpty(aiModelDescribe.ModelId) &&
aiModelDescribe.ModelId.StartsWith("yi-", StringComparison.OrdinalIgnoreCase))
{
aiModelDescribe.ModelId = aiModelDescribe.ModelId[3..];
}
return aiModelDescribe;
}
@@ -123,9 +128,17 @@ public class AiGateWayManager : DomainService
var response = httpContext.Response;
// 设置响应头,声明是 json
//response.ContentType = "application/json; charset=UTF-8";
var modelDescribe = await GetModelAsync(ModelApiTypeEnum.OpenAi, request.Model);
var modelDescribe = await GetModelAsync(ModelApiTypeEnum.Completions, request.Model);
var chatService =
LazyServiceProvider.GetRequiredKeyedService<IChatCompletionService>(modelDescribe.HandlerName);
var sourceModelId = request.Model;
if (!string.IsNullOrEmpty(request.Model) &&
request.Model.StartsWith("yi-", StringComparison.OrdinalIgnoreCase))
{
request.Model = request.Model[3..];
}
var data = await chatService.CompleteChatAsync(modelDescribe, request, cancellationToken);
data.SupplementalMultiplier(modelDescribe.Multiplier);
if (userId is not null)
@@ -134,7 +147,7 @@ public class AiGateWayManager : DomainService
new MessageInputDto
{
Content = sessionId is null ? "不予存储" : request.Messages?.LastOrDefault().Content ?? string.Empty,
ModelId = request.Model,
ModelId = sourceModelId,
TokenUsage = data.Usage,
}, tokenId);
@@ -143,19 +156,13 @@ public class AiGateWayManager : DomainService
{
Content =
sessionId is null ? "不予存储" : data.Choices?.FirstOrDefault()?.Delta.Content ?? string.Empty,
ModelId = request.Model,
ModelId = sourceModelId,
TokenUsage = data.Usage
}, tokenId);
await _usageStatisticsManager.SetUsageAsync(userId.Value, request.Model, data.Usage, tokenId);
await _usageStatisticsManager.SetUsageAsync(userId.Value, sourceModelId, data.Usage, tokenId);
// 扣减尊享token包用量
var isPremium = await _aiModelRepository._DbQueryable
.Where(x => x.ModelId == request.Model)
.Select(x => x.IsPremium)
.FirstAsync();
if (isPremium)
if (modelDescribe.IsPremium)
{
var totalTokens = data.Usage?.TotalTokens ?? 0;
if (totalTokens > 0)
@@ -195,10 +202,17 @@ public class AiGateWayManager : DomainService
_specialCompatible.Compatible(request);
var modelDescribe = await GetModelAsync(ModelApiTypeEnum.OpenAi, request.Model);
var modelDescribe = await GetModelAsync(ModelApiTypeEnum.Completions, request.Model);
var chatService =
LazyServiceProvider.GetRequiredKeyedService<IChatCompletionService>(modelDescribe.HandlerName);
var sourceModelId = request.Model;
if (!string.IsNullOrEmpty(request.Model) &&
request.Model.StartsWith("yi-", StringComparison.OrdinalIgnoreCase))
{
request.Model = request.Model[3..];
}
var completeChatResponse = chatService.CompleteChatStreamAsync(modelDescribe, request, cancellationToken);
var tokenUsage = new ThorUsageResponse();
@@ -290,7 +304,7 @@ public class AiGateWayManager : DomainService
new MessageInputDto
{
Content = sessionId is null ? "不予存储" : request.Messages?.LastOrDefault()?.MessagesStore ?? string.Empty,
ModelId = request.Model,
ModelId = sourceModelId,
TokenUsage = tokenUsage,
}, tokenId);
@@ -298,21 +312,16 @@ public class AiGateWayManager : DomainService
new MessageInputDto
{
Content = sessionId is null ? "不予存储" : backupSystemContent.ToString(),
ModelId = request.Model,
ModelId = sourceModelId,
TokenUsage = tokenUsage
}, tokenId);
await _usageStatisticsManager.SetUsageAsync(userId, request.Model, tokenUsage, tokenId);
await _usageStatisticsManager.SetUsageAsync(userId, sourceModelId, tokenUsage, tokenId);
// 扣减尊享token包用量
if (userId is not null)
{
var isPremium = await _aiModelRepository._DbQueryable
.Where(x => x.ModelId == request.Model)
.Select(x => x.IsPremium)
.FirstAsync();
if (isPremium)
if (modelDescribe.IsPremium)
{
var totalTokens = tokenUsage.TotalTokens ?? 0;
if (totalTokens > 0)
@@ -342,7 +351,7 @@ public class AiGateWayManager : DomainService
var model = request.Model;
if (string.IsNullOrEmpty(model)) model = "dall-e-2";
var modelDescribe = await GetModelAsync(ModelApiTypeEnum.OpenAi, model);
var modelDescribe = await GetModelAsync(ModelApiTypeEnum.Completions, model);
// 获取渠道指定的实现类型的服务
var imageService =
@@ -375,21 +384,13 @@ public class AiGateWayManager : DomainService
await _usageStatisticsManager.SetUsageAsync(userId, model, response.Usage, tokenId);
// 扣减尊享token包用量
// 直接扣减尊享token包用量
if (userId is not null)
{
var isPremium = await _aiModelRepository._DbQueryable
.Where(x => x.ModelId == request.Model)
.Select(x => x.IsPremium)
.FirstAsync();
if (isPremium)
var totalTokens = response.Usage.TotalTokens ?? 0;
if (totalTokens > 0)
{
var totalTokens = response.Usage.TotalTokens ?? 0;
if (totalTokens > 0)
{
await PremiumPackageManager.TryConsumeTokensAsync(userId.Value, totalTokens);
}
await PremiumPackageManager.TryConsumeTokensAsync(userId.Value, totalTokens);
}
}
}
@@ -421,7 +422,7 @@ public class AiGateWayManager : DomainService
using var embedding =
Activity.Current?.Source.StartActivity("向量模型调用");
var modelDescribe = await GetModelAsync(ModelApiTypeEnum.OpenAi, input.Model);
var modelDescribe = await GetModelAsync(ModelApiTypeEnum.Completions, input.Model);
// 获取渠道指定的实现类型的服务
var embeddingService =
@@ -535,7 +536,7 @@ public class AiGateWayManager : DomainService
var response = httpContext.Response;
// 设置响应头,声明是 json
//response.ContentType = "application/json; charset=UTF-8";
var modelDescribe = await GetModelAsync(ModelApiTypeEnum.Claude, request.Model);
var modelDescribe = await GetModelAsync(ModelApiTypeEnum.Messages, request.Model);
var sourceModelId = request.Model;
if (!string.IsNullOrEmpty(request.Model) &&
@@ -543,12 +544,21 @@ public class AiGateWayManager : DomainService
{
request.Model = request.Model[3..];
}
var chatService =
LazyServiceProvider.GetRequiredKeyedService<IAnthropicChatCompletionService>(modelDescribe.HandlerName);
var data = await chatService.ChatCompletionsAsync(modelDescribe, request, cancellationToken);
data.SupplementalMultiplier(modelDescribe.Multiplier);
var currentUsage = data.Usage;
ThorUsageResponse tokenUsage = new ThorUsageResponse
{
InputTokens = (currentUsage?.InputTokens??0) + (currentUsage?.CacheCreationInputTokens??0)+ (currentUsage?.CacheReadInputTokens??0),
OutputTokens = (currentUsage?.OutputTokens??0),
TotalTokens = (currentUsage?.InputTokens??0) + (currentUsage?.CacheCreationInputTokens??0)+ (currentUsage?.CacheReadInputTokens??0)+(currentUsage?.OutputTokens??0)
};
tokenUsage.SetSupplementalMultiplier(modelDescribe.Multiplier);
if (userId is not null)
{
@@ -557,7 +567,7 @@ public class AiGateWayManager : DomainService
{
Content = "不予存储",
ModelId = sourceModelId,
TokenUsage = data.TokenUsage,
TokenUsage = tokenUsage,
}, tokenId);
await _aiMessageManager.CreateSystemMessageAsync(userId.Value, sessionId,
@@ -565,13 +575,13 @@ public class AiGateWayManager : DomainService
{
Content = "不予存储",
ModelId = sourceModelId,
TokenUsage = data.TokenUsage
TokenUsage = tokenUsage
}, tokenId);
await _usageStatisticsManager.SetUsageAsync(userId.Value, sourceModelId, data.TokenUsage, tokenId);
await _usageStatisticsManager.SetUsageAsync(userId.Value, sourceModelId, tokenUsage, tokenId);
// 扣减尊享token包用量
var totalTokens = data.TokenUsage.TotalTokens ?? 0;
// 直接扣减尊享token包用量
var totalTokens = tokenUsage.TotalTokens ?? 0;
if (totalTokens > 0)
{
await PremiumPackageManager.TryConsumeTokensAsync(userId.Value, totalTokens);
@@ -607,7 +617,7 @@ public class AiGateWayManager : DomainService
response.Headers.TryAdd("Connection", "keep-alive");
_specialCompatible.AnthropicCompatible(request);
var modelDescribe = await GetModelAsync(ModelApiTypeEnum.Claude, request.Model);
var modelDescribe = await GetModelAsync(ModelApiTypeEnum.Messages, request.Model);
var chatService =
LazyServiceProvider.GetRequiredKeyedService<IAnthropicChatCompletionService>(modelDescribe.HandlerName);
@@ -617,22 +627,43 @@ public class AiGateWayManager : DomainService
{
request.Model = request.Model[3..];
}
var completeChatResponse = chatService.StreamChatCompletionsAsync(modelDescribe, request, cancellationToken);
ThorUsageResponse? tokenUsage = null;
StringBuilder backupSystemContent = new StringBuilder();
ThorUsageResponse? tokenUsage = new ThorUsageResponse();
try
{
await foreach (var responseResult in completeChatResponse)
{
responseResult.Item2.SupplementalMultiplier(modelDescribe.Multiplier);
//message_start是为了保底机制
if (responseResult.Item1.Contains("message_delta") || responseResult.Item1.Contains("message_start"))
//部分供应商message_start放一部分
if (responseResult.Item1.Contains("message_start"))
{
tokenUsage = responseResult.Item2?.TokenUsage;
var currentTokenUsage = responseResult.Item2.Message.Usage;
if ((currentTokenUsage.InputTokens ?? 0) != 0)
{
tokenUsage.InputTokens = (currentTokenUsage?.InputTokens??0) + (currentTokenUsage?.CacheCreationInputTokens??0)+ (currentTokenUsage?.CacheReadInputTokens??0);
}
if ((currentTokenUsage.OutputTokens ?? 0) != 0)
{
tokenUsage.OutputTokens = currentTokenUsage.OutputTokens;
}
}
backupSystemContent.Append(responseResult.Item2?.Delta?.Text);
//message_delta又放一部分
if (responseResult.Item1.Contains("message_delta"))
{
var currentTokenUsage = responseResult.Item2.Usage;
if ((currentTokenUsage.InputTokens ?? 0) != 0)
{
tokenUsage.InputTokens = (currentTokenUsage?.InputTokens??0) + (currentTokenUsage?.CacheCreationInputTokens??0)+ (currentTokenUsage?.CacheReadInputTokens??0);;
}
if ((currentTokenUsage.OutputTokens ?? 0) != 0)
{
tokenUsage.OutputTokens = currentTokenUsage.OutputTokens;
}
}
await WriteAsEventStreamDataAsync(httpContext, responseResult.Item1, responseResult.Item2,
cancellationToken);
}
@@ -643,7 +674,8 @@ public class AiGateWayManager : DomainService
var errorContent = $"对话Ai异常异常信息\n当前Ai模型{sourceModelId}\n异常信息{e.Message}\n异常堆栈{e}";
throw new UserFriendlyException(errorContent);
}
tokenUsage.TotalTokens = (tokenUsage.InputTokens ?? 0) + (tokenUsage.OutputTokens ?? 0);
tokenUsage.SetSupplementalMultiplier(modelDescribe.Multiplier);
await _aiMessageManager.CreateUserMessageAsync(userId, sessionId,
new MessageInputDto
{
@@ -662,7 +694,7 @@ public class AiGateWayManager : DomainService
await _usageStatisticsManager.SetUsageAsync(userId, sourceModelId, tokenUsage, tokenId);
// 扣减尊享token包用量
// 直接扣减尊享token包用量
if (userId.HasValue && tokenUsage is not null)
{
var totalTokens = tokenUsage.TotalTokens ?? 0;
@@ -694,10 +726,17 @@ public class AiGateWayManager : DomainService
var response = httpContext.Response;
// 设置响应头,声明是 json
//response.ContentType = "application/json; charset=UTF-8";
var modelDescribe = await GetModelAsync(ModelApiTypeEnum.Response, request.Model);
var modelDescribe = await GetModelAsync(ModelApiTypeEnum.Responses, request.Model);
var chatService =
LazyServiceProvider.GetRequiredKeyedService<IOpenAiResponseService>(modelDescribe.HandlerName);
var sourceModelId = request.Model;
if (!string.IsNullOrEmpty(request.Model) &&
request.Model.StartsWith("yi-", StringComparison.OrdinalIgnoreCase))
{
request.Model = request.Model[3..];
}
var data = await chatService.ResponsesAsync(modelDescribe, request, cancellationToken);
data.SupplementalMultiplier(modelDescribe.Multiplier);
@@ -714,7 +753,7 @@ public class AiGateWayManager : DomainService
new MessageInputDto
{
Content = "不予存储",
ModelId = request.Model,
ModelId = sourceModelId,
TokenUsage = tokenUsage,
}, tokenId);
@@ -722,13 +761,13 @@ public class AiGateWayManager : DomainService
new MessageInputDto
{
Content = "不予存储",
ModelId = request.Model,
ModelId = sourceModelId,
TokenUsage = tokenUsage
}, tokenId);
await _usageStatisticsManager.SetUsageAsync(userId.Value, request.Model, tokenUsage, tokenId);
await _usageStatisticsManager.SetUsageAsync(userId.Value, sourceModelId, tokenUsage, tokenId);
// 扣减尊享token包用量
// 直接扣减尊享token包用量
var totalTokens = tokenUsage.TotalTokens ?? 0;
if (totalTokens > 0)
{
@@ -764,9 +803,15 @@ public class AiGateWayManager : DomainService
response.Headers.TryAdd("Cache-Control", "no-cache");
response.Headers.TryAdd("Connection", "keep-alive");
var modelDescribe = await GetModelAsync(ModelApiTypeEnum.Response, request.Model);
var modelDescribe = await GetModelAsync(ModelApiTypeEnum.Responses, request.Model);
var chatService =
LazyServiceProvider.GetRequiredKeyedService<IOpenAiResponseService>(modelDescribe.HandlerName);
var sourceModelId = request.Model;
if (!string.IsNullOrEmpty(request.Model) &&
request.Model.StartsWith("yi-", StringComparison.OrdinalIgnoreCase))
{
request.Model = request.Model[3..];
}
var completeChatResponse = chatService.ResponsesStreamAsync(modelDescribe, request, cancellationToken);
ThorUsageResponse? tokenUsage = null;
@@ -807,7 +852,7 @@ public class AiGateWayManager : DomainService
new MessageInputDto
{
Content = "不予存储",
ModelId = request.Model,
ModelId = sourceModelId,
TokenUsage = tokenUsage,
}, tokenId);
@@ -815,13 +860,13 @@ public class AiGateWayManager : DomainService
new MessageInputDto
{
Content = "不予存储",
ModelId = request.Model,
ModelId = sourceModelId,
TokenUsage = tokenUsage
}, tokenId);
await _usageStatisticsManager.SetUsageAsync(userId, request.Model, tokenUsage, tokenId);
await _usageStatisticsManager.SetUsageAsync(userId, sourceModelId, tokenUsage, tokenId);
// 扣减尊享token包用量
// 直接扣减尊享token包用量
if (userId.HasValue && tokenUsage is not null)
{
var totalTokens = tokenUsage.TotalTokens ?? 0;
@@ -859,7 +904,20 @@ public class AiGateWayManager : DomainService
var data = await chatService.GenerateContentAsync(modelDescribe, request, cancellationToken);
var tokenUsage = GeminiGenerateContentAcquirer.GetUsage(data);
tokenUsage.SetSupplementalMultiplier(modelDescribe.Multiplier);
//如果是图片模型,单独扣费
if (modelDescribe.ModelType == ModelTypeEnum.Image)
{
tokenUsage = new ThorUsageResponse
{
InputTokens = (int)modelDescribe.Multiplier,
OutputTokens = (int)modelDescribe.Multiplier,
TotalTokens = (int)modelDescribe.Multiplier
};
}
else
{
tokenUsage.SetSupplementalMultiplier(modelDescribe.Multiplier);
}
if (userId is not null)
{
@@ -881,7 +939,7 @@ public class AiGateWayManager : DomainService
await _usageStatisticsManager.SetUsageAsync(userId.Value, modelId, tokenUsage, tokenId);
// 扣减尊享token包用量
// 直接扣减尊享token包用量
var totalTokens = tokenUsage.TotalTokens ?? 0;
if (totalTokens > 0)
{
@@ -932,7 +990,20 @@ public class AiGateWayManager : DomainService
if (responseResult!.Value.GetPath("candidates", 0, "finishReason").GetString() == "STOP")
{
tokenUsage = GeminiGenerateContentAcquirer.GetUsage(responseResult!.Value);
tokenUsage.SetSupplementalMultiplier(modelDescribe.Multiplier);
//如果是图片模型,单独扣费
if (modelDescribe.ModelType == ModelTypeEnum.Image)
{
tokenUsage = new ThorUsageResponse
{
InputTokens = (int)modelDescribe.Multiplier,
OutputTokens = (int)modelDescribe.Multiplier,
TotalTokens = (int)modelDescribe.Multiplier
};
}
else
{
tokenUsage.SetSupplementalMultiplier(modelDescribe.Multiplier);
}
}
await response.WriteAsync($"data: {JsonSerializer.Serialize(responseResult)}\n\n", Encoding.UTF8,
@@ -965,7 +1036,7 @@ public class AiGateWayManager : DomainService
await _usageStatisticsManager.SetUsageAsync(userId, modelId, tokenUsage, tokenId);
// 扣减尊享token包用量
// 直接扣减尊享token包用量
if (userId.HasValue && tokenUsage is not null)
{
var totalTokens = tokenUsage.TotalTokens ?? 0;
@@ -976,6 +1047,7 @@ public class AiGateWayManager : DomainService
}
}
private const string ImageStoreHost = "https://ccnetcore.com/prod-api";
/// <summary>
/// Gemini 生成(Image)-非流式-缓存处理
@@ -1004,17 +1076,30 @@ public class AiGateWayManager : DomainService
LazyServiceProvider.GetRequiredKeyedService<IGeminiGenerateContentService>(modelDescribe.HandlerName);
var data = await chatService.GenerateContentAsync(modelDescribe, request, cancellationToken);
// 检查是否被大模型内容安全策略拦截
var rawResponse = data.GetRawText();
if (rawResponse.Contains("policies.google.com/terms/generative-ai/use-policy"))
{
_logger.LogWarning($"图片生成被内容安全策略拦截,模型:【{modelId}】,请求信息:【{request}】");
throw new UserFriendlyException("您的提示词涉及敏感信息,已被大模型拦截,请调整提示词后再试!");
}
//解析json获取base64字符串
var imageBase64 = GeminiGenerateContentAcquirer.GetImageBase64(data);
var imagePrefixBase64 = GeminiGenerateContentAcquirer.GetImagePrefixBase64(data);
if (string.IsNullOrWhiteSpace(imagePrefixBase64))
{
_logger.LogError($"图片生成解析失败,模型:【{modelId}】,请求信息:【{request}】,请求响应信息:【{data}】");
throw new UserFriendlyException("大模型没有返回图片,请调整提示词或稍后再试");
}
//远程调用上传接口将base64转换为URL
var httpClient = LazyServiceProvider.LazyGetRequiredService<IHttpClientFactory>().CreateClient();
var uploadUrl = $"https://ccnetcore.com/prod-api/ai-hub/ai-image/upload-base64";
var content = new StringContent(JsonSerializer.Serialize(imageBase64), Encoding.UTF8, "application/json");
// var uploadUrl = $"https://ccnetcore.com/prod-api/ai-hub/ai-image/upload-base64";
var uploadUrl = $"{ImageStoreHost}/ai-image/upload-base64";
var content = new StringContent(JsonSerializer.Serialize(imagePrefixBase64), Encoding.UTF8, "application/json");
var uploadResponse = await httpClient.PostAsync(uploadUrl, content, cancellationToken);
uploadResponse.EnsureSuccessStatusCode();
var storeUrl = await uploadResponse.Content.ReadAsStringAsync(cancellationToken);
storeUrl = storeUrl.Trim('"'); // 移除JSON字符串的引号
var tokenUsage = new ThorUsageResponse
{
@@ -1033,7 +1118,7 @@ public class AiGateWayManager : DomainService
await _usageStatisticsManager.SetUsageAsync(userId, modelId, tokenUsage, tokenId);
// 扣减尊享token包用量
// 直接扣减尊享token包用量
var totalTokens = tokenUsage.TotalTokens ?? 0;
if (totalTokens > 0)
{
@@ -1041,11 +1126,485 @@ public class AiGateWayManager : DomainService
}
//设置存储base64和url
imageStoreTask.StoreBase64 = imageBase64;
imageStoreTask.SetSuccess(storeUrl);
imageStoreTask.SetSuccess($"{ImageStoreHost}{storeUrl}");
await _imageStoreTaskRepository.UpdateAsync(imageStoreTask);
}
/// <summary>
/// 统一流式处理 - 支持4种API类型的原封不动转发
/// </summary>
public async Task UnifiedStreamForStatisticsAsync(
HttpContext httpContext,
ModelApiTypeEnum apiType,
JsonElement requestBody,
string modelId,
Guid? userId = null,
Guid? sessionId = null,
Guid? tokenId = null,
CancellationToken cancellationToken = default)
{
var response = httpContext.Response;
// 设置响应头,声明是 SSE 流
response.ContentType = "text/event-stream;charset=utf-8;";
response.Headers.TryAdd("Cache-Control", "no-cache");
response.Headers.TryAdd("Connection", "keep-alive");
var sourceModelId = modelId;
// 处理 yi- 前缀
if (!string.IsNullOrEmpty(modelId) &&
modelId.StartsWith("yi-", StringComparison.OrdinalIgnoreCase))
{
modelId = modelId[3..];
}
var modelDescribe = await GetModelAsync(apiType, sourceModelId);
// 公共缓存队列
var messageQueue = new ConcurrentQueue<string>();
var outputInterval = TimeSpan.FromMilliseconds(75);
var isComplete = false;
// 公共消费任务
var outputTask = Task.Run(async () =>
{
while (!(isComplete && messageQueue.IsEmpty))
{
if (messageQueue.TryDequeue(out var message))
{
await response.WriteAsync(message, Encoding.UTF8, cancellationToken).ConfigureAwait(false);
await response.Body.FlushAsync(cancellationToken).ConfigureAwait(false);
}
if (!isComplete)
{
await Task.Delay(outputInterval, cancellationToken).ConfigureAwait(false);
}
else
{
await Task.Delay(10, cancellationToken).ConfigureAwait(false);
}
}
}, cancellationToken);
StreamProcessResult? processResult = null;
switch (apiType)
{
case ModelApiTypeEnum.Completions:
processResult = await ProcessCompletionsStreamAsync(messageQueue, requestBody, modelDescribe, cancellationToken);
break;
case ModelApiTypeEnum.Messages:
processResult = await ProcessAnthropicStreamAsync(messageQueue, requestBody, modelDescribe, cancellationToken);
break;
case ModelApiTypeEnum.Responses:
processResult = await ProcessOpenAiResponsesStreamAsync(messageQueue, requestBody, modelDescribe, cancellationToken);
break;
case ModelApiTypeEnum.GenerateContent:
processResult = await ProcessGeminiStreamAsync(messageQueue, requestBody, modelDescribe, cancellationToken);
break;
default:
throw new UserFriendlyException($"不支持的API类型: {apiType}");
}
// 标记完成并等待消费任务结束
isComplete = true;
await outputTask;
// 统一的统计处理
await _aiMessageManager.CreateUserMessageAsync(userId, sessionId,
new MessageInputDto
{
Content = sessionId is null ? "不予存储" : processResult?.UserContent ?? string.Empty,
ModelId = sourceModelId,
TokenUsage = processResult?.TokenUsage,
}, tokenId);
await _aiMessageManager.CreateSystemMessageAsync(userId, sessionId,
new MessageInputDto
{
Content = sessionId is null ? "不予存储" : processResult?.SystemContent ?? string.Empty,
ModelId = sourceModelId,
TokenUsage = processResult?.TokenUsage
}, tokenId);
await _usageStatisticsManager.SetUsageAsync(userId, sourceModelId, processResult?.TokenUsage, tokenId);
// 扣减尊享token包用量
if (userId.HasValue && processResult?.TokenUsage is not null && modelDescribe.IsPremium)
{
var totalTokens = processResult?.TokenUsage.TotalTokens ?? 0;
if (totalTokens > 0)
{
await PremiumPackageManager.TryConsumeTokensAsync(userId.Value, totalTokens);
}
}
}
#region - API类型的具体实现
/// <summary>
/// 流式处理结果,包含用户输入、系统输出和 token 使用情况
/// </summary>
private class StreamProcessResult
{
public string UserContent { get; set; } = string.Empty;
public string SystemContent { get; set; } = string.Empty;
public ThorUsageResponse TokenUsage { get; set; } = new();
}
/// <summary>
/// 处理 OpenAI Completions 格式流式响应
/// </summary>
private async Task<StreamProcessResult> ProcessCompletionsStreamAsync(
ConcurrentQueue<string> messageQueue,
JsonElement requestBody,
AiModelDescribe modelDescribe,
CancellationToken cancellationToken)
{
var request = requestBody.Deserialize<ThorChatCompletionsRequest>(ThorJsonSerializer.DefaultOptions)!;
_specialCompatible.Compatible(request);
// 提取用户最后一条消息
var userContent = request.Messages?.LastOrDefault()?.MessagesStore ?? string.Empty;
// 处理 yi- 前缀
if (!string.IsNullOrEmpty(request.Model) &&
request.Model.StartsWith("yi-", StringComparison.OrdinalIgnoreCase))
{
request.Model = request.Model[3..];
}
var chatService = LazyServiceProvider.GetRequiredKeyedService<IChatCompletionService>(modelDescribe.HandlerName);
var completeChatResponse = chatService.CompleteChatStreamAsync(modelDescribe, request, cancellationToken);
var tokenUsage = new ThorUsageResponse();
var systemContentBuilder = new StringBuilder();
try
{
await foreach (var data in completeChatResponse)
{
data.SupplementalMultiplier(modelDescribe.Multiplier);
if (data.Usage is not null && (data.Usage.CompletionTokens > 0 || data.Usage.OutputTokens > 0))
{
tokenUsage = data.Usage;
}
// 累加系统输出内容 (choices[].delta.content)
var deltaContent = data.Choices?.FirstOrDefault()?.Delta?.Content;
if (!string.IsNullOrEmpty(deltaContent))
{
systemContentBuilder.Append(deltaContent);
}
var message = JsonSerializer.Serialize(data, ThorJsonSerializer.DefaultOptions);
messageQueue.Enqueue($"data: {message}\n\n");
}
}
catch (Exception e)
{
_logger.LogError(e, "Ai对话异常");
var errorContent = $"对话Ai异常异常信息\n当前Ai模型{request.Model}\n异常信息{e.Message}\n异常堆栈{e}";
systemContentBuilder.Append(errorContent);
var model = new ThorChatCompletionsResponse()
{
Choices = new List<ThorChatChoiceResponse>()
{
new ThorChatChoiceResponse()
{
Delta = new ThorChatMessage()
{
Content = errorContent
}
}
}
};
var errorMessage = JsonConvert.SerializeObject(model, new JsonSerializerSettings
{
ContractResolver = new CamelCasePropertyNamesContractResolver()
});
messageQueue.Enqueue($"data: {errorMessage}\n\n");
}
messageQueue.Enqueue("data: [DONE]\n\n");
return new StreamProcessResult
{
UserContent = userContent,
SystemContent = systemContentBuilder.ToString(),
TokenUsage = tokenUsage
};
}
/// <summary>
/// 处理 Anthropic Messages 格式流式响应
/// </summary>
private async Task<StreamProcessResult> ProcessAnthropicStreamAsync(
ConcurrentQueue<string> messageQueue,
JsonElement requestBody,
AiModelDescribe modelDescribe,
CancellationToken cancellationToken)
{
var request = requestBody.Deserialize<AnthropicInput>(ThorJsonSerializer.DefaultOptions)!;
_specialCompatible.AnthropicCompatible(request);
// 提取用户最后一条消息
var lastMessage = request.Messages?.LastOrDefault();
var userContent = lastMessage?.Content ?? string.Empty;
if (string.IsNullOrEmpty(userContent) && lastMessage?.Contents != null && lastMessage.Contents.Any())
{
// 如果是 Contents 数组,提取第一个 text 类型的内容
var textContent = lastMessage.Contents.FirstOrDefault(c => c.Type == "text");
userContent = textContent?.Text ?? System.Text.Json.JsonSerializer.Serialize(lastMessage.Contents);
}
// 处理 yi- 前缀
if (!string.IsNullOrEmpty(request.Model) &&
request.Model.StartsWith("yi-", StringComparison.OrdinalIgnoreCase))
{
request.Model = request.Model[3..];
}
var chatService = LazyServiceProvider.GetRequiredKeyedService<IAnthropicChatCompletionService>(modelDescribe.HandlerName);
var completeChatResponse = chatService.StreamChatCompletionsAsync(modelDescribe, request, cancellationToken);
var tokenUsage = new ThorUsageResponse();
var systemContentBuilder = new StringBuilder();
try
{
await foreach (var responseResult in completeChatResponse)
{
// 部分供应商message_start放一部分
if (responseResult.Item1.Contains("message_start"))
{
var currentTokenUsage = responseResult.Item2?.Message?.Usage;
if (currentTokenUsage != null)
{
if ((currentTokenUsage.InputTokens ?? 0) != 0)
{
tokenUsage.InputTokens = (currentTokenUsage.InputTokens ?? 0) +
(currentTokenUsage.CacheCreationInputTokens ?? 0) +
(currentTokenUsage.CacheReadInputTokens ?? 0);
}
if ((currentTokenUsage.OutputTokens ?? 0) != 0)
{
tokenUsage.OutputTokens = currentTokenUsage.OutputTokens;
}
}
}
// message_delta又放一部分
if (responseResult.Item1.Contains("message_delta"))
{
var currentTokenUsage = responseResult.Item2?.Usage;
if (currentTokenUsage != null)
{
if ((currentTokenUsage.InputTokens ?? 0) != 0)
{
tokenUsage.InputTokens = (currentTokenUsage.InputTokens ?? 0) +
(currentTokenUsage.CacheCreationInputTokens ?? 0) +
(currentTokenUsage.CacheReadInputTokens ?? 0);
}
if ((currentTokenUsage.OutputTokens ?? 0) != 0)
{
tokenUsage.OutputTokens = currentTokenUsage.OutputTokens;
}
}
}
// 累加系统输出内容 (delta.text)
var deltaText = responseResult.Item2?.Delta?.Text;
if (!string.IsNullOrEmpty(deltaText))
{
systemContentBuilder.Append(deltaText);
}
// 序列化为SSE格式字符串
var data = JsonSerializer.Serialize(responseResult.Item2, ThorJsonSerializer.DefaultOptions);
messageQueue.Enqueue($"{responseResult.Item1.Trim()}\ndata: {data}\n\n");
}
}
catch (Exception e)
{
_logger.LogError(e, "Ai对话异常");
var errorContent = $"对话Ai异常异常信息\n当前Ai模型{request.Model}\n异常信息{e.Message}\n异常堆栈{e}";
systemContentBuilder.Append(errorContent);
throw new UserFriendlyException(errorContent);
}
tokenUsage.TotalTokens = (tokenUsage.InputTokens ?? 0) + (tokenUsage.OutputTokens ?? 0);
tokenUsage.SetSupplementalMultiplier(modelDescribe.Multiplier);
return new StreamProcessResult
{
UserContent = userContent,
SystemContent = systemContentBuilder.ToString(),
TokenUsage = tokenUsage
};
}
/// <summary>
/// 处理 OpenAI Responses 格式流式响应
/// </summary>
private async Task<StreamProcessResult> ProcessOpenAiResponsesStreamAsync(
ConcurrentQueue<string> messageQueue,
JsonElement requestBody,
AiModelDescribe modelDescribe,
CancellationToken cancellationToken)
{
var request = requestBody.Deserialize<OpenAiResponsesInput>(ThorJsonSerializer.DefaultOptions)!;
// 提取用户输入内容 (input 字段可能是字符串或数组)
var userContent = string.Empty;
if (request.Input.ValueKind == JsonValueKind.String)
{
userContent = request.Input.GetString() ?? string.Empty;
}
else if (request.Input.ValueKind == JsonValueKind.Array)
{
// 获取最后一个 user 角色的消息
var inputArray = request.Input.EnumerateArray().ToList();
var lastUserMessage = inputArray.LastOrDefault(x =>
x.TryGetProperty("role", out var role) && role.GetString() == "user");
if (lastUserMessage.ValueKind != JsonValueKind.Undefined)
{
if (lastUserMessage.TryGetProperty("content", out var content))
{
userContent = content.GetString() ?? string.Empty;
}
}
}
// 处理 yi- 前缀
if (!string.IsNullOrEmpty(request.Model) &&
request.Model.StartsWith("yi-", StringComparison.OrdinalIgnoreCase))
{
request.Model = request.Model[3..];
}
var chatService = LazyServiceProvider.GetRequiredKeyedService<IOpenAiResponseService>(modelDescribe.HandlerName);
var completeChatResponse = chatService.ResponsesStreamAsync(modelDescribe, request, cancellationToken);
ThorUsageResponse? tokenUsage = null;
var systemContentBuilder = new StringBuilder();
try
{
await foreach (var responseResult in completeChatResponse)
{
// 提取输出文本内容 (response.output_text.delta 事件)
if (responseResult.Item1.Contains("response.output_text.delta"))
{
var delta = responseResult.Item2?.GetPath("delta").GetString();
if (!string.IsNullOrEmpty(delta))
{
systemContentBuilder.Append(delta);
}
}
if (responseResult.Item1.Contains("response.completed"))
{
var obj = responseResult.Item2!.Value;
int inputTokens = obj.GetPath("response", "usage", "input_tokens").GetInt();
int outputTokens = obj.GetPath("response", "usage", "output_tokens").GetInt();
inputTokens = Convert.ToInt32(inputTokens * modelDescribe.Multiplier);
outputTokens = Convert.ToInt32(outputTokens * modelDescribe.Multiplier);
tokenUsage = new ThorUsageResponse
{
PromptTokens = inputTokens,
InputTokens = inputTokens,
OutputTokens = outputTokens,
CompletionTokens = outputTokens,
TotalTokens = inputTokens + outputTokens,
};
}
// 序列化为SSE格式字符串
var data = JsonSerializer.Serialize(responseResult.Item2, ThorJsonSerializer.DefaultOptions);
messageQueue.Enqueue($"{responseResult.Item1.Trim()}\ndata: {data}\n\n");
}
}
catch (Exception e)
{
_logger.LogError(e, "Ai响应异常");
var errorContent = $"响应Ai异常异常信息\n当前Ai模型{request.Model}\n异常信息{e.Message}\n异常堆栈{e}";
systemContentBuilder.Append(errorContent);
throw new UserFriendlyException(errorContent);
}
return new StreamProcessResult
{
UserContent = userContent,
SystemContent = systemContentBuilder.ToString(),
TokenUsage = tokenUsage ?? new ThorUsageResponse()
};
}
/// <summary>
/// 处理 Gemini GenerateContent 格式流式响应
/// </summary>
private async Task<StreamProcessResult> ProcessGeminiStreamAsync(
ConcurrentQueue<string> messageQueue,
JsonElement requestBody,
AiModelDescribe modelDescribe,
CancellationToken cancellationToken)
{
// 提取用户最后一条消息 (contents[last].parts[last].text)
var userContent = GeminiGenerateContentAcquirer.GetLastUserContent(requestBody);
var chatService = LazyServiceProvider.GetRequiredKeyedService<IGeminiGenerateContentService>(modelDescribe.HandlerName);
var completeChatResponse = chatService.GenerateContentStreamAsync(modelDescribe, requestBody, cancellationToken);
ThorUsageResponse? tokenUsage = null;
var systemContentBuilder = new StringBuilder();
try
{
await foreach (var responseResult in completeChatResponse)
{
// 累加系统输出内容 (candidates[0].content.parts[].text排除 thought)
var textContent = GeminiGenerateContentAcquirer.GetTextContent(responseResult!.Value);
if (!string.IsNullOrEmpty(textContent))
{
systemContentBuilder.Append(textContent);
}
if (responseResult!.Value.GetPath("candidates", 0, "finishReason").GetString() == "STOP")
{
tokenUsage = GeminiGenerateContentAcquirer.GetUsage(responseResult!.Value);
// 如果是图片模型,单独扣费
if (modelDescribe.ModelType == ModelTypeEnum.Image)
{
tokenUsage = new ThorUsageResponse
{
InputTokens = (int)modelDescribe.Multiplier,
OutputTokens = (int)modelDescribe.Multiplier,
TotalTokens = (int)modelDescribe.Multiplier
};
}
else
{
tokenUsage.SetSupplementalMultiplier(modelDescribe.Multiplier);
}
}
messageQueue.Enqueue($"data: {JsonSerializer.Serialize(responseResult)}\n\n");
}
}
catch (Exception e)
{
_logger.LogError(e, "Ai生成异常");
var errorContent = $"生成Ai异常异常信息\n当前Ai模型{modelDescribe.ModelId}\n异常信息{e.Message}\n异常堆栈{e}";
systemContentBuilder.Append(errorContent);
throw new UserFriendlyException(errorContent);
}
return new StreamProcessResult
{
UserContent = userContent,
SystemContent = systemContentBuilder.ToString(),
TokenUsage = tokenUsage ?? new ThorUsageResponse()
};
}
#endregion
#region Http响应
private static readonly byte[] EventPrefix = "event: "u8.ToArray();
@@ -1068,7 +1627,8 @@ public class AiGateWayManager : DomainService
// e.g. Content-Type: text/event-stream; charset=utf-8
await response.StartAsync(cancellationToken).ConfigureAwait(false);
// 写事件类型
await bodyStream.WriteAsync(EventPrefix, cancellationToken).ConfigureAwait(false);
//此处事件前缀重复了
// await bodyStream.WriteAsync(EventPrefix, cancellationToken).ConfigureAwait(false);
await WriteUtf8StringAsync(bodyStream, @event.Trim(), cancellationToken).ConfigureAwait(false);
await bodyStream.WriteAsync(NewLine, cancellationToken).ConfigureAwait(false);
// 写 data: + JSON

View File

@@ -8,17 +8,15 @@ using Microsoft.AspNetCore.Http;
using Microsoft.Extensions.AI;
using Microsoft.Extensions.DependencyInjection;
using Microsoft.Extensions.Logging;
using ModelContextProtocol.Server;
using OpenAI;
using OpenAI.Chat;
using Volo.Abp.Domain.Services;
using Volo.Abp.Uow;
using Yi.Framework.AiHub.Application.Contracts.Dtos.Chat;
using Yi.Framework.AiHub.Domain.AiGateWay;
using Yi.Framework.AiHub.Domain.Entities.Chat;
using Yi.Framework.AiHub.Domain.Entities.Model;
using Yi.Framework.AiHub.Domain.Entities.OpenApi;
using Yi.Framework.AiHub.Domain.Shared.Attributes;
using Yi.Framework.AiHub.Domain.Shared.Consts;
using Yi.Framework.AiHub.Domain.Shared.Dtos;
using Yi.Framework.AiHub.Domain.Shared.Dtos.OpenAi;
using Yi.Framework.AiHub.Domain.Shared.Enums;
@@ -36,12 +34,14 @@ public class ChatManager : DomainService
private readonly PremiumPackageManager _premiumPackageManager;
private readonly AiGateWayManager _aiGateWayManager;
private readonly ISqlSugarRepository<AiModelEntity, Guid> _aiModelRepository;
private readonly IUnitOfWorkManager _unitOfWorkManager;
public ChatManager(ILoggerFactory loggerFactory,
ISqlSugarRepository<MessageAggregateRoot> messageRepository,
ISqlSugarRepository<AgentStoreAggregateRoot> agentStoreRepository, AiMessageManager aiMessageManager,
UsageStatisticsManager usageStatisticsManager, PremiumPackageManager premiumPackageManager,
AiGateWayManager aiGateWayManager, ISqlSugarRepository<AiModelEntity, Guid> aiModelRepository)
AiGateWayManager aiGateWayManager, ISqlSugarRepository<AiModelEntity, Guid> aiModelRepository,
IUnitOfWorkManager unitOfWorkManager)
{
_loggerFactory = loggerFactory;
_messageRepository = messageRepository;
@@ -51,6 +51,7 @@ public class ChatManager : DomainService
_premiumPackageManager = premiumPackageManager;
_aiGateWayManager = aiGateWayManager;
_aiModelRepository = aiModelRepository;
_unitOfWorkManager = unitOfWorkManager;
}
/// <summary>
@@ -82,7 +83,7 @@ public class ChatManager : DomainService
response.Headers.TryAdd("Cache-Control", "no-cache");
response.Headers.TryAdd("Connection", "keep-alive");
var modelDescribe = await _aiGateWayManager.GetModelAsync(ModelApiTypeEnum.OpenAi, modelId);
var modelDescribe = await _aiGateWayManager.GetModelAsync(ModelApiTypeEnum.Completions, modelId);
//token状态检查在应用层统一处理
var client = new OpenAIClient(new ApiKeyCredential(token),
@@ -99,9 +100,11 @@ public class ChatManager : DomainService
ChatOptions = new()
{
Instructions = """
Ai
Ai
Ai平台YxaiKnowledgeDirectory和YxaiKnowledge查找意心Ai知识库内容
"""
},
Name = "橙子小弟",
@@ -189,53 +192,59 @@ public class ChatManager : DomainService
//用量统计
case UsageContent usageContent:
var usage = new ThorUsageResponse
//由于MAF线程问题
using (var uow = _unitOfWorkManager.Begin(requiresNew: true))
{
InputTokens = Convert.ToInt32(usageContent.Details.InputTokenCount ?? 0),
OutputTokens = Convert.ToInt32(usageContent.Details.OutputTokenCount ?? 0),
TotalTokens = usageContent.Details.TotalTokenCount ?? 0,
};
//设置倍率
usage.SetSupplementalMultiplier(modelDescribe.Multiplier);
//创建系统回答,用于计费统计
await _aiMessageManager.CreateSystemMessageAsync(userId, sessionId, new MessageInputDto
{
Content = "不与存储",
ModelId = modelId,
TokenUsage = usage
}, tokenId);
//创建用量统计,用于统计分析
await _usageStatisticsManager.SetUsageAsync(userId, modelId, usage, tokenId);
//扣减尊享token包用量
var isPremium = await _aiModelRepository._DbQueryable
.Where(x => x.ModelId == modelId)
.Select(x => x.IsPremium)
.FirstAsync();
if (isPremium)
{
var totalTokens = usage?.TotalTokens ?? 0;
if (totalTokens > 0)
var usage = new ThorUsageResponse
{
await _premiumPackageManager.TryConsumeTokensAsync(userId, totalTokens);
InputTokens = Convert.ToInt32(usageContent.Details.InputTokenCount ?? 0),
OutputTokens = Convert.ToInt32(usageContent.Details.OutputTokenCount ?? 0),
TotalTokens = usageContent.Details.TotalTokenCount ?? 0,
};
//设置倍率
usage.SetSupplementalMultiplier(modelDescribe.Multiplier);
//创建系统回答,用于计费统计
await _aiMessageManager.CreateSystemMessageAsync(userId, sessionId, new MessageInputDto
{
Content = "不与存储",
ModelId = modelId,
TokenUsage = usage
}, tokenId);
//创建用量统计,用于统计分析
await _usageStatisticsManager.SetUsageAsync(userId, modelId, usage, tokenId);
//扣减尊享token包用量
var isPremium = await _aiModelRepository._DbQueryable
.Where(x => x.ModelId == modelId)
.Select(x => x.IsPremium)
.FirstAsync();
if (isPremium)
{
var totalTokens = usage?.TotalTokens ?? 0;
if (totalTokens > 0)
{
await _premiumPackageManager.TryConsumeTokensAsync(userId, totalTokens);
}
}
}
await SendHttpStreamMessageAsync(httpContext,
new AgentResultOutput
{
TypeEnum = update.RawRepresentation is ChatResponseUpdate raw
? raw.FinishReason?.Value == "tool_calls"
? AgentResultTypeEnum.ToolCallUsage
: AgentResultTypeEnum.Usage
: AgentResultTypeEnum.Usage,
Content = usage!
},
isDone: false, cancellationToken);
break;
await uow.CompleteAsync();
await SendHttpStreamMessageAsync(httpContext,
new AgentResultOutput
{
TypeEnum = update.RawRepresentation is ChatResponseUpdate raw
? raw.FinishReason?.Value == "tool_calls"
? AgentResultTypeEnum.ToolCallUsage
: AgentResultTypeEnum.Usage
: AgentResultTypeEnum.Usage,
Content = usage!
},
isDone: false, cancellationToken);
break;
}
}
}
}
@@ -247,8 +256,13 @@ public class ChatManager : DomainService
string serializedJson = currentThread.Serialize(JsonSerializerOptions.Web).GetRawText();
agentStore.Store = serializedJson;
//插入或者更新
await _agentStoreRepository.InsertOrUpdateAsync(agentStore);
//由于MAF线程问题
using (var uow = _unitOfWorkManager.Begin(requiresNew: true))
{
//插入或者更新
await _agentStoreRepository.InsertOrUpdateAsync(agentStore);
await uow.CompleteAsync();
}
}

View File

@@ -11,7 +11,7 @@ namespace Yi.Framework.AiHub.Domain.Managers;
/// </summary>
public class ModelManager : DomainService
{
private readonly ISqlSugarRepository<AiModelEntity> _aiModelRepository;
public readonly ISqlSugarRepository<AiModelEntity> _aiModelRepository;
private readonly IDistributedCache<List<string>, string> _distributedCache;
private readonly ILogger<ModelManager> _logger;
private const string PREMIUM_MODEL_IDS_CACHE_KEY = "PremiumModelIds";
@@ -38,7 +38,7 @@ public class ModelManager : DomainService
{
// 从数据库查询
var premiumModelIds = await _aiModelRepository._DbQueryable
.Where(x => x.IsPremium)
.Where(x => x.IsPremium && x.IsEnabled)
.Select(x => x.ModelId)
.ToListAsync();
return premiumModelIds;

View File

@@ -22,6 +22,11 @@ public class TokenValidationResult
/// Token Id
/// </summary>
public Guid TokenId { get; set; }
/// <summary>
/// token
/// </summary>
public string Token { get; set; }
}
public class TokenManager : DomainService
@@ -43,25 +48,36 @@ public class TokenManager : DomainService
/// <summary>
/// 验证Token并返回用户Id和TokenId
/// </summary>
/// <param name="token">Token密钥</param>
/// <param name="tokenOrId">Token密钥或者TokenId</param>
/// <param name="modelId">模型Id用于判断是否是尊享模型需要检查额度</param>
/// <returns>Token验证结果</returns>
public async Task<TokenValidationResult> ValidateTokenAsync(string? token, string? modelId = null)
public async Task<TokenValidationResult> ValidateTokenAsync(object tokenOrId, string? modelId = null)
{
if (token is null)
if (tokenOrId is null)
{
throw new UserFriendlyException("当前请求未包含token", "401");
}
if (!token.StartsWith("yi-"))
TokenAggregateRoot entity;
if (tokenOrId is Guid tokenId)
{
throw new UserFriendlyException("当前请求token非法", "401");
entity = await _tokenRepository._DbQueryable
.Where(x => x.Id == tokenId)
.FirstAsync();
}
var entity = await _tokenRepository._DbQueryable
.Where(x => x.Token == token)
.FirstAsync();
else
{
var tokenStr = tokenOrId.ToString();
if (!tokenStr.StartsWith("yi-"))
{
throw new UserFriendlyException("当前请求token非法", "401");
}
entity = await _tokenRepository._DbQueryable
.Where(x => x.Token == tokenStr)
.FirstAsync();
}
if (entity is null)
{
throw new UserFriendlyException("当前请求token无效", "401");
@@ -100,7 +116,8 @@ public class TokenManager : DomainService
return new TokenValidationResult
{
UserId = entity.UserId,
TokenId = entity.Id
TokenId = entity.Id,
Token = entity.Token
};
}

View File

@@ -22,13 +22,13 @@ public class UsageStatisticsManager : DomainService
{
var actualTokenId = tokenId ?? Guid.Empty;
long inputTokenCount = tokenUsage?.PromptTokens
?? tokenUsage?.InputTokens
?? 0;
long inputTokenCount = tokenUsage?.PromptTokens > 0
? tokenUsage.PromptTokens.Value
: tokenUsage?.InputTokens ?? 0;
long outputTokenCount = tokenUsage?.CompletionTokens
?? tokenUsage?.OutputTokens
?? 0;
long outputTokenCount = tokenUsage?.CompletionTokens > 0
? tokenUsage.CompletionTokens.Value
: tokenUsage?.OutputTokens ?? 0;
await using (await DistributedLock.AcquireLockAsync($"UsageStatistics:{userId?.ToString()}:{actualTokenId}:{modelId}"))
{

View File

@@ -0,0 +1,15 @@
using System.ComponentModel;
using Volo.Abp.DependencyInjection;
using Yi.Framework.AiHub.Domain.Shared.Attributes;
namespace Yi.Framework.AiHub.Domain.Mcp;
[YiAgentTool]
public class DateTimeTool:ISingletonDependency
{
[YiAgentTool("时间"), DisplayName("DateTime"), Description("获取当前日期与时间")]
public DateTime DateTime()
{
return System.DateTime.Now;
}
}

View File

@@ -1,16 +1,244 @@
using System.ComponentModel;
using ModelContextProtocol.Server;
using System.Net.Http.Json;
using System.Text;
using System.Text.Json;
using System.Text.Json.Serialization;
using Microsoft.Extensions.Configuration;
using Microsoft.Extensions.Logging;
using Volo.Abp.DependencyInjection;
using Yi.Framework.AiHub.Domain.Shared.Attributes;
namespace Yi.Framework.AiHub.Domain.Mcp;
[YiAgentTool]
public class OnlineSearchTool:ISingletonDependency
public class OnlineSearchTool : ISingletonDependency
{
[YiAgentTool("联网搜索"),DisplayName("OnlineSearch"), Description("进行在线搜索")]
public string OnlineSearch(string keyword)
private readonly IHttpClientFactory _httpClientFactory;
private readonly ILogger<OnlineSearchTool> _logger;
private readonly string _baiduApiKey;
private const string BaiduSearchUrl = "https://qianfan.baidubce.com/v2/ai_search/web_search";
public OnlineSearchTool(
IHttpClientFactory httpClientFactory,
ILogger<OnlineSearchTool> logger,
IConfiguration configuration)
{
return "奥德赛第一中学学生会会长是:郭老板";
_httpClientFactory = httpClientFactory;
_logger = logger;
_baiduApiKey = configuration["BaiduSearch:ApiKey"] ?? "";
}
}
[YiAgentTool("联网搜索"), DisplayName("OnlineSearch"), Description("进行在线搜索获取最新的网络信息近期信息是7天实时信息是1天")]
public async Task<string> OnlineSearch([Description("搜索关键字")] string keyword,
[Description("距离现在多久天")] int? daysAgo = null)
{
if (daysAgo <= 0)
{
daysAgo = 1;
}
if (string.IsNullOrWhiteSpace(keyword))
{
return "搜索关键词不能为空";
}
try
{
var client = _httpClientFactory.CreateClient();
// 构建请求体
var requestBody = new BaiduSearchRequest
{
Messages = new List<BaiduSearchMessage>
{
new() { Role = "user", Content = keyword }
}
};
// 设置时间范围过滤
if (daysAgo.HasValue)
{
requestBody.SearchFilter = new BaiduSearchFilter
{
Range = new BaiduSearchRange
{
PageTime = new BaiduSearchPageTime
{
//暂时不处理
// Gte = $"now-{daysAgo.Value}d/d",
Gte = "now-1w/d"
}
}
};
}
var jsonContent = JsonSerializer.Serialize(requestBody, BaiduJsonContext.Default.BaiduSearchRequest);
var content = new StringContent(jsonContent, Encoding.UTF8, "application/json");
// 设置请求头
var request = new HttpRequestMessage(HttpMethod.Post, BaiduSearchUrl)
{
Content = content
};
request.Headers.Add("Authorization", $"Bearer {_baiduApiKey}");
// 发送请求
var response = await client.SendAsync(request);
if (!response.IsSuccessStatusCode)
{
var errorContent = await response.Content.ReadAsStringAsync();
_logger.LogError("百度搜索接口调用失败: {StatusCode}, {Error}", response.StatusCode, errorContent);
return $"搜索失败: {response.StatusCode}";
}
var responseJson = await response.Content.ReadAsStringAsync();
var searchResult = JsonSerializer.Deserialize(responseJson, BaiduJsonContext.Default.BaiduSearchResponse);
if (searchResult?.References == null || searchResult.References.Count == 0)
{
return "未找到相关搜索结果";
}
// 格式化搜索结果返回给AI
return FormatSearchResults(searchResult.References);
}
catch (HttpRequestException ex)
{
_logger.LogError(ex, "百度搜索网络请求异常");
return "搜索服务暂时不可用,请稍后重试";
}
catch (TaskCanceledException ex)
{
_logger.LogError(ex, "百度搜索请求超时");
return "搜索请求超时,请稍后重试";
}
catch (JsonException ex)
{
_logger.LogError(ex, "百度搜索结果解析失败");
return "搜索结果解析失败";
}
catch (Exception ex)
{
_logger.LogError(ex, "百度搜索发生未知异常");
return "搜索发生异常,请稍后重试";
}
}
/// <summary>
/// 格式化搜索结果
/// </summary>
private string FormatSearchResults(List<BaiduSearchReference> references)
{
var sb = new StringBuilder();
sb.AppendLine("搜索结果:");
sb.AppendLine();
var count = 0;
foreach (var item in references.Take(10)) // 最多返回10条
{
count++;
sb.AppendLine($"【{count}】{item.Title}");
sb.AppendLine($"来源:{item.Website} | 时间:{item.Date}");
sb.AppendLine($"摘要:{item.Snippet}");
sb.AppendLine($"链接:{item.Url}");
sb.AppendLine();
}
return sb.ToString();
}
}
#region DTO
/// <summary>
/// 百度搜索请求
/// </summary>
public class BaiduSearchRequest
{
[JsonPropertyName("messages")] public List<BaiduSearchMessage> Messages { get; set; } = new();
[JsonPropertyName("search_filter")]
[JsonIgnore(Condition = JsonIgnoreCondition.WhenWritingNull)]
public BaiduSearchFilter? SearchFilter { get; set; }
}
/// <summary>
/// 百度搜索过滤器
/// </summary>
public class BaiduSearchFilter
{
[JsonPropertyName("range")] public BaiduSearchRange? Range { get; set; }
}
/// <summary>
/// 百度搜索范围
/// </summary>
public class BaiduSearchRange
{
[JsonPropertyName("page_time")] public BaiduSearchPageTime? PageTime { get; set; }
}
/// <summary>
/// 百度搜索时间范围
/// </summary>
public class BaiduSearchPageTime
{
[JsonPropertyName("gte")] public string? Gte { get; set; }
// [JsonPropertyName("lte")] public string? Lte { get; set; }
}
/// <summary>
/// 百度搜索消息
/// </summary>
public class BaiduSearchMessage
{
[JsonPropertyName("role")] public string Role { get; set; } = "user";
[JsonPropertyName("content")] public string Content { get; set; } = "";
}
/// <summary>
/// 百度搜索响应
/// </summary>
public class BaiduSearchResponse
{
[JsonPropertyName("request_id")] public string? RequestId { get; set; }
[JsonPropertyName("references")] public List<BaiduSearchReference>? References { get; set; }
}
/// <summary>
/// 百度搜索结果项
/// </summary>
public class BaiduSearchReference
{
[JsonPropertyName("id")] public int Id { get; set; }
[JsonPropertyName("url")] public string? Url { get; set; }
[JsonPropertyName("title")] public string? Title { get; set; }
[JsonPropertyName("date")] public string? Date { get; set; }
[JsonPropertyName("snippet")] public string? Snippet { get; set; }
[JsonPropertyName("website")] public string? Website { get; set; }
}
#endregion
#region JSON
[JsonSerializable(typeof(BaiduSearchRequest))]
[JsonSerializable(typeof(BaiduSearchResponse))]
[JsonSerializable(typeof(BaiduSearchFilter))]
[JsonSerializable(typeof(BaiduSearchRange))]
[JsonSerializable(typeof(BaiduSearchPageTime))]
[JsonSourceGenerationOptions(PropertyNamingPolicy = JsonKnownNamingPolicy.CamelCase)]
internal partial class BaiduJsonContext : JsonSerializerContext
{
}
#endregion

View File

@@ -0,0 +1,115 @@
using System.ComponentModel;
using System.Text.Json;
using System.Text.Json.Serialization;
using Microsoft.Extensions.Logging;
using Volo.Abp.DependencyInjection;
using Yi.Framework.AiHub.Domain.Shared.Attributes;
namespace Yi.Framework.AiHub.Domain.Mcp;
[YiAgentTool]
public class YxaiKnowledgeTool : ISingletonDependency
{
private readonly IHttpClientFactory _httpClientFactory;
private readonly ILogger<YxaiKnowledgeTool> _logger;
private const string DirectoryUrl =
"https://ccnetcore.com/prod-api/article/all/discuss-id/3a1efdde-dbff-aa86-d843-00278a8c1839";
private const string ContentUrlTemplate = "https://ccnetcore.com/prod-api/article/{0}";
public YxaiKnowledgeTool(
IHttpClientFactory httpClientFactory,
ILogger<YxaiKnowledgeTool> logger)
{
_httpClientFactory = httpClientFactory;
_logger = logger;
}
[YiAgentTool("意心Ai平台知识库目录"), DisplayName("YxaiKnowledgeDirectory"),
Description("获取意心AI相关内容的知识库目录列表")]
public async Task<List<YxaiKnowledgeDirectoryItem>> YxaiKnowledgeDirectory()
{
try
{
var client = _httpClientFactory.CreateClient();
var response = await client.GetAsync(DirectoryUrl);
if (!response.IsSuccessStatusCode)
{
_logger.LogError("意心知识库目录接口调用失败: {StatusCode}", response.StatusCode);
return new List<YxaiKnowledgeDirectoryItem>();
}
var json = await response.Content.ReadAsStringAsync();
var result = JsonSerializer.Deserialize(json, YxaiKnowledgeJsonContext.Default.ListYxaiKnowledgeDirectoryItem);
return result ?? new List<YxaiKnowledgeDirectoryItem>();
}
catch (Exception ex)
{
_logger.LogError(ex, "获取意心知识库目录发生异常");
return new List<YxaiKnowledgeDirectoryItem>();
}
}
[YiAgentTool("意心Ai平台知识库内容"), DisplayName("YxaiKnowledge"),
Description("根据目录ID获取意心AI知识库的具体内容")]
public async Task<string> YxaiKnowledge([Description("知识库目录ID")] string directoryId)
{
if (string.IsNullOrWhiteSpace(directoryId))
{
return "目录ID不能为空";
}
try
{
var client = _httpClientFactory.CreateClient();
var url = string.Format(ContentUrlTemplate, directoryId);
var response = await client.GetAsync(url);
if (!response.IsSuccessStatusCode)
{
_logger.LogError("意心知识库内容接口调用失败: {StatusCode}, DirectoryId: {DirectoryId}",
response.StatusCode, directoryId);
return "获取知识库内容失败";
}
var json = await response.Content.ReadAsStringAsync();
var result = JsonSerializer.Deserialize(json, YxaiKnowledgeJsonContext.Default.YxaiKnowledgeContentResponse);
return result?.Content ?? "未找到相关内容";
}
catch (Exception ex)
{
_logger.LogError(ex, "获取意心知识库内容发生异常, DirectoryId: {DirectoryId}", directoryId);
return "获取知识库内容发生异常";
}
}
}
#region DTO
public class YxaiKnowledgeDirectoryItem
{
[JsonPropertyName("id")] public string Id { get; set; } = "";
[JsonPropertyName("name")] public string Name { get; set; } = "";
}
public class YxaiKnowledgeContentResponse
{
[JsonPropertyName("content")] public string? Content { get; set; }
}
#endregion
#region JSON
[JsonSerializable(typeof(List<YxaiKnowledgeDirectoryItem>))]
[JsonSerializable(typeof(YxaiKnowledgeContentResponse))]
internal partial class YxaiKnowledgeJsonContext : JsonSerializerContext
{
}
#endregion

View File

@@ -1,6 +1,7 @@
<Project Sdk="Microsoft.NET.Sdk">
<Import Project="..\..\..\common.props" />
<ItemGroup>
<PackageReference Include="OpenAI" Version="2.8.0" />
<PackageReference Include="Volo.Abp.Ddd.Domain" Version="$(AbpVersion)" />
<PackageReference Include="Volo.Abp.Caching" Version="$(AbpVersion)" />
<PackageReference Include="Microsoft.SemanticKernel" Version="1.57.0" />

View File

@@ -7,6 +7,7 @@
</ItemGroup>
<ItemGroup>
<PackageReference Include="OpenAI" Version="2.8.0" />
<PackageReference Include="Volo.Abp.AspNetCore.SignalR" Version="$(AbpVersion)" />
<PackageReference Include="Volo.Abp.Ddd.Domain" Version="$(AbpVersion)" />
<PackageReference Include="Volo.Abp.Caching" Version="$(AbpVersion)" />

View File

@@ -235,7 +235,7 @@ namespace Yi.Framework.Rbac.Domain.Managers
if (UserConst.Admin.Equals(dto.User.UserName))
{
AddToClaim(claims, TokenTypeConst.Permission, UserConst.AdminPermissionCode);
AddToClaim(claims, TokenTypeConst.Roles, UserConst.AdminRolesCode);
AddToClaim(claims, ClaimTypes.Role, UserConst.AdminRolesCode);
}
else
{

View File

@@ -21,6 +21,7 @@ namespace Yi.Abp.Web.Jobs.ai_stock
public override async Task DoWorkAsync(CancellationToken cancellationToken = new CancellationToken())
{
return;
// 每次触发只有2/24的概率执行生成新闻
var random = new Random();
var probability = random.Next(0, 24);

View File

@@ -20,6 +20,7 @@ namespace Yi.Abp.Web.Jobs.ai_stock
public override async Task DoWorkAsync(CancellationToken cancellationToken = new CancellationToken())
{
return;
await _stockMarketManager.GenerateStocksAsync();
}
}

View File

@@ -32,6 +32,7 @@ public class AutoPassInGoodsJob: HangfireBackgroundWorkerBase
}
public override async Task DoWorkAsync(CancellationToken cancellationToken = new CancellationToken())
{
return;
await _marketManager.AutoPassInGoodsAsync();
}
}

View File

@@ -37,7 +37,7 @@ public class AutoRefreshMiningPoolJob : HangfireBackgroundWorkerBase
}
public override async Task DoWorkAsync(CancellationToken cancellationToken = new CancellationToken())
{
return;
//刷新矿池
await _miningPoolManager.RefreshMiningPoolAsync();
//刷新用户限制

View File

@@ -20,6 +20,7 @@ public class AutoUpdateCollectiblesValueJob : HangfireBackgroundWorkerBase
public override async Task DoWorkAsync(CancellationToken cancellationToken = new CancellationToken())
{
return;
await _collectiblesManager.UpdateAllValueAsync();
}
}

View File

@@ -31,6 +31,7 @@ public class OnHookAutoMiningJob : HangfireBackgroundWorkerBase
}
public override async Task DoWorkAsync(CancellationToken cancellationToken = new CancellationToken())
{
return;
await _miningPoolManager.OnHookMiningAsync();
}
}

View File

@@ -1,4 +1,5 @@
using System.Globalization;
using System.Security.Claims;
using System.Text;
using System.Text.Json.Serialization;
using System.Text.Json.Serialization.Metadata;
@@ -280,6 +281,7 @@ namespace Yi.Abp.Web
{
options.TokenValidationParameters = new TokenValidationParameters
{
RoleClaimType = ClaimTypes.Role,
ClockSkew = TimeSpan.Zero,
ValidateIssuerSigningKey = true,
ValidIssuer = jwtOptions.Issuer,
@@ -298,7 +300,8 @@ namespace Yi.Abp.Web
}
else
{
if (messageContext.Request.Cookies.TryGetValue("Token", out var cookiesToken))
if (!messageContext.Request.Headers.ContainsKey("Authorization") &&
messageContext.Request.Cookies.TryGetValue("Token", out var cookiesToken))
{
messageContext.Token = cookiesToken;
}
@@ -358,8 +361,8 @@ namespace Yi.Abp.Web
var app = context.GetApplicationBuilder();
app.UseRouting();
//app.ApplicationServices.GetRequiredService<ISqlSugarDbContext>().SqlSugarClient.CodeFirst.InitTables<AiModelEntity>();
// app.ApplicationServices.GetRequiredService<ISqlSugarDbContext>().SqlSugarClient.CodeFirst.InitTables<ActivationCodeRecordAggregateRoot>();
//app.ApplicationServices.GetRequiredService<ISqlSugarDbContext>().SqlSugarClient.CodeFirst.InitTables<SessionAggregateRoot>();
// app.ApplicationServices.GetRequiredService<ISqlSugarDbContext>().SqlSugarClient.CodeFirst.InitTables<ActivationCodeRecordAggregateRoot>();
// app.ApplicationServices.GetRequiredService<ISqlSugarDbContext>().SqlSugarClient.CodeFirst.InitTables<UsageStatisticsAggregateRoot>();
//跨域
@@ -399,9 +402,11 @@ namespace Yi.Abp.Web
{
Mappings =
{
[".wxss"] = "text/css"
[".wxss"] = "text/css",
}
}
},
ServeUnknownFileTypes = true,
DefaultContentType = "application/octet-stream"
});
app.UseDefaultFiles();
app.UseDirectoryBrowser("/api/app/wwwroot");

View File

@@ -0,0 +1,60 @@
import type { Plugin } from 'vite';
import { execSync } from 'node:child_process';
import path from 'node:path';
/**
* 获取 Git 提交哈希值插件
* Git 仓库在上一级目录
*/
export default function gitHashPlugin(): Plugin {
let gitHash = 'unknown';
let gitBranch = 'unknown';
let gitDate = 'unknown';
try {
// Git 仓库在上一级目录
const execOptions = { cwd: path.resolve(__dirname, '../../..'), encoding: 'utf-8' as BufferEncoding };
// 获取完整的 commit hash
gitHash = execSync('git rev-parse HEAD', execOptions)
.toString()
.trim();
// 获取短 hash (前7位)
const shortHash = gitHash.substring(0, 7);
// 获取分支名
gitBranch = execSync('git rev-parse --abbrev-ref HEAD', execOptions)
.toString()
.trim();
// 获取提交时间
gitDate = execSync('git log -1 --format=%cd --date=iso', execOptions)
.toString()
.trim();
console.log(`\n📦 Git Info:`);
console.log(` Branch: ${gitBranch}`);
console.log(` Commit: ${shortHash}`);
console.log(` Date: ${gitDate}\n`);
gitHash = shortHash; // 使用短 hash
} catch (error: any) {
console.warn('⚠️ 无法获取 Git 信息:', error?.message || error);
}
return {
name: 'vite-plugin-git-hash',
config() {
// 在 config 钩子中返回配置
return {
define: {
__GIT_HASH__: JSON.stringify(gitHash),
__GIT_BRANCH__: JSON.stringify(gitBranch),
__GIT_DATE__: JSON.stringify(gitDate),
__BUILD_TIME__: JSON.stringify(new Date().toISOString()),
},
};
},
};
}

View File

@@ -10,12 +10,14 @@ import Components from 'unplugin-vue-components/vite';
import viteCompression from 'vite-plugin-compression';
import envTyped from 'vite-plugin-env-typed';
import gitHashPlugin from './git-hash';
import createSvgIcon from './svg-icon';
const root = path.resolve(__dirname, '../../');
function plugins({ mode, command }: ConfigEnv): PluginOption[] {
return [
gitHashPlugin(),
UnoCSS(),
envTyped({
mode,

View File

@@ -3,7 +3,10 @@
"allow": [
"Bash(npx vue-tsc --noEmit)",
"Bash(timeout 60 npx vue-tsc:*)",
"Bash(npm run dev:*)"
"Bash(npm run dev:*)",
"Bash(taskkill:*)",
"Bash(timeout /t 5 /nobreak)",
"Bash(git checkout:*)"
],
"deny": [],
"ask": []

View File

@@ -70,3 +70,87 @@ dotnet run
- [ ] 文件上传
- [ ] 其他...
深色主题样式编写指南
1. 在 src/styles/dark-theme.scss 中添加样式
所有深色主题样式都使用 [data-theme="dark"] 选择器包裹:
/* ========== 组件名称深色样式 ========== */
[data-theme="dark"] {
.your-component-class {
background-color: #1f2937 !important;
color: #e5e7eb !important;
border-color: #374151 !important;
}
}
2. 常用深色主题颜色值
┌─────────────────────────┬───────────────────┐
│ 用途 │ 颜色值 │
├─────────────────────────┼───────────────────┤
│ 主背景 │ #111827
├─────────────────────────┼───────────────────┤
│ 次级背景(卡片、弹窗) │ #1f2937
├─────────────────────────┼───────────────────┤
│ 三级背景hover、表头#374151
├─────────────────────────┼───────────────────┤
│ 主文字 │ #f3f4f6 / #f9fafb
├─────────────────────────┼───────────────────┤
│ 次级文字 │ #e5e7eb
├─────────────────────────┼───────────────────┤
│ 三级文字 │ #9ca3af
├─────────────────────────┼───────────────────┤
│ 边框浅色 │ #374151
├─────────────────────────┼───────────────────┤
│ 边框深色 │ #4b5563
├─────────────────────────┼───────────────────┤
│ 主色调 │ #60a5fa
└─────────────────────────┴───────────────────┘
3. 覆盖 Tailwind 工具类
[data-theme="dark"] {
.bg-white {
background-color: #374151 !important;
}
.text-gray-700 {
color: #e5e7eb !important;
}
}
4. 覆盖 Element Plus 组件
[data-theme="dark"] {
.el-card {
background-color: #1f2937 !important;
border-color: #374151 !important;
}
}
5. 使用 CSS 变量(推荐)
在 src/styles/var.scss 的 [data-theme="dark"] 块中定义变量,然后在组件中使用:
// var.scss
[data-theme="dark"] {
--my-component-bg: #1f2937;
}
// dark-theme.scss
[data-theme="dark"] {
.my-component {
background-color: var(--my-component-bg) !important;
}
}
6. 组件内动态颜色JS 方式)
如果需要在 JS 中动态获取颜色:
<script setup>
import { useColorMode } from '@vueuse/core';
const mode = useColorMode();
const bgColor = computed(() => mode.value === 'dark' ? '#1f2937' : '#ffffff');
</script>

View File

@@ -112,7 +112,7 @@
<body>
<!-- 加载动画容器 -->
<div id="yixinai-loader" class="loader-container">
<div class="loader-title">意心Ai 2.9</div>
<div class="loader-title">意心Ai 3.4</div>
<div class="loader-subtitle">海外地址仅首次访问预计加载约10秒无需梯子</div>
<div class="loader-logo">
<div class="pulse-box"></div>

View File

@@ -158,7 +158,7 @@ importers:
devDependencies:
'@antfu/eslint-config':
specifier: ^4.16.2
version: 4.17.0(@vue/compiler-sfc@3.5.17)(eslint@9.31.0(jiti@2.4.2))(typescript@5.8.3)(vitest@3.2.4(@types/debug@4.1.12)(@types/node@22.15.30)(@vitest/browser@3.2.4)(jiti@2.4.2)(sass-embedded@1.89.2)(sass@1.97.0)(terser@5.44.1)(tsx@4.21.0)(yaml@2.8.0))
version: 4.17.0(@vue/compiler-sfc@3.5.17)(eslint@9.31.0(jiti@2.4.2))(typescript@5.8.3)(vitest@3.2.4)
'@changesets/cli':
specifier: ^2.29.5
version: 2.29.5
@@ -188,7 +188,7 @@ importers:
version: 8.6.14(react-dom@19.2.3(react@19.1.0))(react@19.1.0)(storybook@8.6.14(prettier@3.6.2))
'@storybook/experimental-addon-test':
specifier: ^8.6.14
version: 8.6.14(@vitest/browser@3.2.4(playwright@1.57.0)(vite@6.3.5(@types/node@22.15.30)(jiti@2.4.2)(sass-embedded@1.89.2)(sass@1.97.0)(terser@5.44.1)(tsx@4.21.0)(yaml@2.8.0))(vitest@3.2.4))(@vitest/runner@3.2.4)(react-dom@19.2.3(react@19.1.0))(react@19.1.0)(storybook@8.6.14(prettier@3.6.2))(vitest@3.2.4(@types/debug@4.1.12)(@types/node@22.15.30)(@vitest/browser@3.2.4)(jiti@2.4.2)(sass-embedded@1.89.2)(sass@1.97.0)(terser@5.44.1)(tsx@4.21.0)(yaml@2.8.0))
version: 8.6.14(@vitest/browser@3.2.4)(@vitest/runner@3.2.4)(react-dom@19.2.3(react@19.1.0))(react@19.1.0)(storybook@8.6.14(prettier@3.6.2))(vitest@3.2.4)
'@storybook/manager-api':
specifier: ^8.6.14
version: 8.6.14(storybook@8.6.14(prettier@3.6.2))
@@ -227,7 +227,7 @@ importers:
version: 3.2.4(playwright@1.57.0)(vite@6.3.5(@types/node@22.15.30)(jiti@2.4.2)(sass-embedded@1.89.2)(sass@1.97.0)(terser@5.44.1)(tsx@4.21.0)(yaml@2.8.0))(vitest@3.2.4)
'@vitest/coverage-v8':
specifier: ^3.2.4
version: 3.2.4(@vitest/browser@3.2.4(playwright@1.57.0)(vite@6.3.5(@types/node@22.15.30)(jiti@2.4.2)(sass-embedded@1.89.2)(sass@1.97.0)(terser@5.44.1)(tsx@4.21.0)(yaml@2.8.0))(vitest@3.2.4))(vitest@3.2.4(@types/debug@4.1.12)(@types/node@22.15.30)(@vitest/browser@3.2.4)(jiti@2.4.2)(sass-embedded@1.89.2)(sass@1.97.0)(terser@5.44.1)(tsx@4.21.0)(yaml@2.8.0))
version: 3.2.4(@vitest/browser@3.2.4)(vitest@3.2.4)
'@vue/tsconfig':
specifier: ^0.7.0
version: 0.7.0(typescript@5.8.3)(vue@3.5.17(typescript@5.8.3))
@@ -427,28 +427,24 @@ packages:
engines: {node: '>= 10'}
cpu: [arm64]
os: [linux]
libc: [glibc]
'@ast-grep/napi-linux-arm64-musl@0.36.3':
resolution: {integrity: sha512-2XRmNYuovZu0Pa4J3or4PKMkQZnXXfpVcCrPwWB/2ytX7XUo+TWLgYE8rPVnJOyw5zujkveFb0XUrro9mQgLzw==}
engines: {node: '>= 10'}
cpu: [arm64]
os: [linux]
libc: [musl]
'@ast-grep/napi-linux-x64-gnu@0.36.3':
resolution: {integrity: sha512-mTwPRbBi1feGqR2b5TWC5gkEDeRi8wfk4euF5sKNihfMGHj6pdfINHQ3QvLVO4C7z0r/wgWLAvditFA0b997dg==}
engines: {node: '>= 10'}
cpu: [x64]
os: [linux]
libc: [glibc]
'@ast-grep/napi-linux-x64-musl@0.36.3':
resolution: {integrity: sha512-tMGPrT+zuZzJK6n1cD1kOii7HYZE9gUXjwtVNE/uZqXEaWP6lmkfoTMbLjnxEe74VQbmaoDGh1/cjrDBnqC6Uw==}
engines: {node: '>= 10'}
cpu: [x64]
os: [linux]
libc: [musl]
'@ast-grep/napi-win32-arm64-msvc@0.36.3':
resolution: {integrity: sha512-7pFyr9+dyV+4cBJJ1I57gg6PDXP3GBQeVAsEEitzEruxx4Hb4cyNro54gGtlsS+6ty+N0t004tPQxYO2VrsPIg==}
@@ -1245,35 +1241,30 @@ packages:
engines: {node: '>= 10'}
cpu: [arm64]
os: [linux]
libc: [glibc]
'@napi-rs/canvas-linux-arm64-musl@0.1.84':
resolution: {integrity: sha512-VyZq0EEw+OILnWk7G3ZgLLPaz1ERaPP++jLjeyLMbFOF+Tr4zHzWKiKDsEV/cT7btLPZbVoR3VX+T9/QubnURQ==}
engines: {node: '>= 10'}
cpu: [arm64]
os: [linux]
libc: [musl]
'@napi-rs/canvas-linux-riscv64-gnu@0.1.84':
resolution: {integrity: sha512-PSMTh8DiThvLRsbtc/a065I/ceZk17EXAATv9uNvHgkgo7wdEfTh2C3aveNkBMGByVO3tvnvD5v/YFtZL07cIg==}
engines: {node: '>= 10'}
cpu: [riscv64]
os: [linux]
libc: [glibc]
'@napi-rs/canvas-linux-x64-gnu@0.1.84':
resolution: {integrity: sha512-N1GY3noO1oqgEo3rYQIwY44kfM11vA0lDbN0orTOHfCSUZTUyiYCY0nZ197QMahZBm1aR/vYgsWpV74MMMDuNA==}
engines: {node: '>= 10'}
cpu: [x64]
os: [linux]
libc: [glibc]
'@napi-rs/canvas-linux-x64-musl@0.1.84':
resolution: {integrity: sha512-vUZmua6ADqTWyHyei81aXIt9wp0yjeNwTH0KdhdeoBb6azHmFR8uKTukZMXfLCC3bnsW0t4lW7K78KNMknmtjg==}
engines: {node: '>= 10'}
cpu: [x64]
os: [linux]
libc: [musl]
'@napi-rs/canvas-win32-x64-msvc@0.1.84':
resolution: {integrity: sha512-YSs8ncurc1xzegUMNnQUTYrdrAuaXdPMOa+iYYyAxydOtg0ppV386hyYMsy00Yip1NlTgLCseRG4sHSnjQx6og==}
@@ -1330,42 +1321,36 @@ packages:
engines: {node: '>= 10.0.0'}
cpu: [arm]
os: [linux]
libc: [glibc]
'@parcel/watcher-linux-arm-musl@2.5.1':
resolution: {integrity: sha512-6E+m/Mm1t1yhB8X412stiKFG3XykmgdIOqhjWj+VL8oHkKABfu/gjFj8DvLrYVHSBNC+/u5PeNrujiSQ1zwd1Q==}
engines: {node: '>= 10.0.0'}
cpu: [arm]
os: [linux]
libc: [musl]
'@parcel/watcher-linux-arm64-glibc@2.5.1':
resolution: {integrity: sha512-LrGp+f02yU3BN9A+DGuY3v3bmnFUggAITBGriZHUREfNEzZh/GO06FF5u2kx8x+GBEUYfyTGamol4j3m9ANe8w==}
engines: {node: '>= 10.0.0'}
cpu: [arm64]
os: [linux]
libc: [glibc]
'@parcel/watcher-linux-arm64-musl@2.5.1':
resolution: {integrity: sha512-cFOjABi92pMYRXS7AcQv9/M1YuKRw8SZniCDw0ssQb/noPkRzA+HBDkwmyOJYp5wXcsTrhxO0zq1U11cK9jsFg==}
engines: {node: '>= 10.0.0'}
cpu: [arm64]
os: [linux]
libc: [musl]
'@parcel/watcher-linux-x64-glibc@2.5.1':
resolution: {integrity: sha512-GcESn8NZySmfwlTsIur+49yDqSny2IhPeZfXunQi48DMugKeZ7uy1FX83pO0X22sHntJ4Ub+9k34XQCX+oHt2A==}
engines: {node: '>= 10.0.0'}
cpu: [x64]
os: [linux]
libc: [glibc]
'@parcel/watcher-linux-x64-musl@2.5.1':
resolution: {integrity: sha512-n0E2EQbatQ3bXhcH2D1XIAANAcTZkQICBPVaxMeaCVBtOpBZpWJuf7LwyWPSBDITb7In8mqQgJ7gH8CILCURXg==}
engines: {node: '>= 10.0.0'}
cpu: [x64]
os: [linux]
libc: [musl]
'@parcel/watcher-win32-arm64@2.5.1':
resolution: {integrity: sha512-RFzklRvmc3PkjKjry3hLF9wD7ppR4AKcWNzH7kXR7GUe0Igb3Nz8fyPwtZCSquGrhU5HhUNDr/mKBqj7tqA2Vw==}
@@ -1450,67 +1435,56 @@ packages:
resolution: {integrity: sha512-wC53ZNDgt0pqx5xCAgNunkTzFE8GTgdZ9EwYGVcg+jEjJdZGtq9xPjDnFgfFozQI/Xm1mh+D9YlYtl+ueswNEg==}
cpu: [arm]
os: [linux]
libc: [glibc]
'@rollup/rollup-linux-arm-musleabihf@4.41.1':
resolution: {integrity: sha512-jwKCca1gbZkZLhLRtsrka5N8sFAaxrGz/7wRJ8Wwvq3jug7toO21vWlViihG85ei7uJTpzbXZRcORotE+xyrLA==}
cpu: [arm]
os: [linux]
libc: [musl]
'@rollup/rollup-linux-arm64-gnu@4.41.1':
resolution: {integrity: sha512-g0UBcNknsmmNQ8V2d/zD2P7WWfJKU0F1nu0k5pW4rvdb+BIqMm8ToluW/eeRmxCared5dD76lS04uL4UaNgpNA==}
cpu: [arm64]
os: [linux]
libc: [glibc]
'@rollup/rollup-linux-arm64-musl@4.41.1':
resolution: {integrity: sha512-XZpeGB5TKEZWzIrj7sXr+BEaSgo/ma/kCgrZgL0oo5qdB1JlTzIYQKel/RmhT6vMAvOdM2teYlAaOGJpJ9lahg==}
cpu: [arm64]
os: [linux]
libc: [musl]
'@rollup/rollup-linux-loongarch64-gnu@4.41.1':
resolution: {integrity: sha512-bkCfDJ4qzWfFRCNt5RVV4DOw6KEgFTUZi2r2RuYhGWC8WhCA8lCAJhDeAmrM/fdiAH54m0mA0Vk2FGRPyzI+tw==}
cpu: [loong64]
os: [linux]
libc: [glibc]
'@rollup/rollup-linux-powerpc64le-gnu@4.41.1':
resolution: {integrity: sha512-3mr3Xm+gvMX+/8EKogIZSIEF0WUu0HL9di+YWlJpO8CQBnoLAEL/roTCxuLncEdgcfJcvA4UMOf+2dnjl4Ut1A==}
cpu: [ppc64]
os: [linux]
libc: [glibc]
'@rollup/rollup-linux-riscv64-gnu@4.41.1':
resolution: {integrity: sha512-3rwCIh6MQ1LGrvKJitQjZFuQnT2wxfU+ivhNBzmxXTXPllewOF7JR1s2vMX/tWtUYFgphygxjqMl76q4aMotGw==}
cpu: [riscv64]
os: [linux]
libc: [glibc]
'@rollup/rollup-linux-riscv64-musl@4.41.1':
resolution: {integrity: sha512-LdIUOb3gvfmpkgFZuccNa2uYiqtgZAz3PTzjuM5bH3nvuy9ty6RGc/Q0+HDFrHrizJGVpjnTZ1yS5TNNjFlklw==}
cpu: [riscv64]
os: [linux]
libc: [musl]
'@rollup/rollup-linux-s390x-gnu@4.41.1':
resolution: {integrity: sha512-oIE6M8WC9ma6xYqjvPhzZYk6NbobIURvP/lEbh7FWplcMO6gn7MM2yHKA1eC/GvYwzNKK/1LYgqzdkZ8YFxR8g==}
cpu: [s390x]
os: [linux]
libc: [glibc]
'@rollup/rollup-linux-x64-gnu@4.41.1':
resolution: {integrity: sha512-cWBOvayNvA+SyeQMp79BHPK8ws6sHSsYnK5zDcsC3Hsxr1dgTABKjMnMslPq1DvZIp6uO7kIWhiGwaTdR4Og9A==}
cpu: [x64]
os: [linux]
libc: [glibc]
'@rollup/rollup-linux-x64-musl@4.41.1':
resolution: {integrity: sha512-y5CbN44M+pUCdGDlZFzGGBSKCA4A/J2ZH4edTYSSxFg7ce1Xt3GtydbVKWLlzL+INfFIZAEg1ZV6hh9+QQf9YQ==}
cpu: [x64]
os: [linux]
libc: [musl]
'@rollup/rollup-win32-arm64-msvc@4.41.1':
resolution: {integrity: sha512-lZkCxIrjlJlMt1dLO/FbpZbzt6J/A8p4DnqzSa4PWqPEUUUnzXLeki/iyPLfV0BmHItlYgHUqJe+3KiyydmiNQ==}
@@ -6913,8 +6887,8 @@ packages:
vue-component-type-helpers@2.2.12:
resolution: {integrity: sha512-YbGqHZ5/eW4SnkPNR44mKVc6ZKQoRs/Rux1sxC6rdwXb4qpbOSYfDr9DsTHolOTGmIKgM9j141mZbBeg05R1pw==}
vue-component-type-helpers@3.1.8:
resolution: {integrity: sha512-oaowlmEM6BaYY+8o+9D9cuzxpWQWHqHTMKakMxXu0E+UCIOMTljyIPO15jcnaCwJtZu/zWDotK7mOIHvWD9mcw==}
vue-component-type-helpers@3.2.3:
resolution: {integrity: sha512-lpJTa8a+12Cgy/n5OdlQTzQhSWOCu+6zQoNFbl3KYxwAoB95mYIgMLKEYMvQykPJ2ucBDjJJISdIBHc1d9Hd3w==}
vue-demi@0.14.10:
resolution: {integrity: sha512-nMZBOwuzabUO0nLgIcc6rycZEebF6eeUfaiQx9+WSk8e29IbLvPU9feI6tqW4kTo3hvoYAJkMh8n8D0fuISphg==}
@@ -7133,7 +7107,7 @@ snapshots:
'@jridgewell/gen-mapping': 0.3.8
'@jridgewell/trace-mapping': 0.3.25
'@antfu/eslint-config@4.17.0(@vue/compiler-sfc@3.5.17)(eslint@9.31.0(jiti@2.4.2))(typescript@5.8.3)(vitest@3.2.4(@types/debug@4.1.12)(@types/node@22.15.30)(@vitest/browser@3.2.4)(jiti@2.4.2)(sass-embedded@1.89.2)(sass@1.97.0)(terser@5.44.1)(tsx@4.21.0)(yaml@2.8.0))':
'@antfu/eslint-config@4.17.0(@vue/compiler-sfc@3.5.17)(eslint@9.31.0(jiti@2.4.2))(typescript@5.8.3)(vitest@3.2.4)':
dependencies:
'@antfu/install-pkg': 1.1.0
'@clack/prompts': 0.11.0
@@ -7142,7 +7116,7 @@ snapshots:
'@stylistic/eslint-plugin': 5.2.0(eslint@9.31.0(jiti@2.4.2))
'@typescript-eslint/eslint-plugin': 8.37.0(@typescript-eslint/parser@8.37.0(eslint@9.31.0(jiti@2.4.2))(typescript@5.8.3))(eslint@9.31.0(jiti@2.4.2))(typescript@5.8.3)
'@typescript-eslint/parser': 8.37.0(eslint@9.31.0(jiti@2.4.2))(typescript@5.8.3)
'@vitest/eslint-plugin': 1.3.4(eslint@9.31.0(jiti@2.4.2))(typescript@5.8.3)(vitest@3.2.4(@types/debug@4.1.12)(@types/node@22.15.30)(@vitest/browser@3.2.4)(jiti@2.4.2)(sass-embedded@1.89.2)(sass@1.97.0)(terser@5.44.1)(tsx@4.21.0)(yaml@2.8.0))
'@vitest/eslint-plugin': 1.3.4(eslint@9.31.0(jiti@2.4.2))(typescript@5.8.3)(vitest@3.2.4)
ansis: 4.1.0
cac: 6.7.14
eslint: 9.31.0(jiti@2.4.2)
@@ -8494,7 +8468,7 @@ snapshots:
dependencies:
type-fest: 2.19.0
'@storybook/experimental-addon-test@8.6.14(@vitest/browser@3.2.4(playwright@1.57.0)(vite@6.3.5(@types/node@22.15.30)(jiti@2.4.2)(sass-embedded@1.89.2)(sass@1.97.0)(terser@5.44.1)(tsx@4.21.0)(yaml@2.8.0))(vitest@3.2.4))(@vitest/runner@3.2.4)(react-dom@19.2.3(react@19.1.0))(react@19.1.0)(storybook@8.6.14(prettier@3.6.2))(vitest@3.2.4(@types/debug@4.1.12)(@types/node@22.15.30)(@vitest/browser@3.2.4)(jiti@2.4.2)(sass-embedded@1.89.2)(sass@1.97.0)(terser@5.44.1)(tsx@4.21.0)(yaml@2.8.0))':
'@storybook/experimental-addon-test@8.6.14(@vitest/browser@3.2.4)(@vitest/runner@3.2.4)(react-dom@19.2.3(react@19.1.0))(react@19.1.0)(storybook@8.6.14(prettier@3.6.2))(vitest@3.2.4)':
dependencies:
'@storybook/global': 5.0.0
'@storybook/icons': 1.6.0(react-dom@19.2.3(react@19.1.0))(react@19.1.0)
@@ -8639,7 +8613,7 @@ snapshots:
ts-dedent: 2.2.0
type-fest: 2.19.0
vue: 3.5.17(typescript@5.8.3)
vue-component-type-helpers: 3.1.8
vue-component-type-helpers: 3.2.3
'@stylistic/eslint-plugin@5.2.0(eslint@9.31.0(jiti@2.4.2))':
dependencies:
@@ -9301,7 +9275,7 @@ snapshots:
- utf-8-validate
- vite
'@vitest/coverage-v8@3.2.4(@vitest/browser@3.2.4(playwright@1.57.0)(vite@6.3.5(@types/node@22.15.30)(jiti@2.4.2)(sass-embedded@1.89.2)(sass@1.97.0)(terser@5.44.1)(tsx@4.21.0)(yaml@2.8.0))(vitest@3.2.4))(vitest@3.2.4(@types/debug@4.1.12)(@types/node@22.15.30)(@vitest/browser@3.2.4)(jiti@2.4.2)(sass-embedded@1.89.2)(sass@1.97.0)(terser@5.44.1)(tsx@4.21.0)(yaml@2.8.0))':
'@vitest/coverage-v8@3.2.4(@vitest/browser@3.2.4)(vitest@3.2.4)':
dependencies:
'@ampproject/remapping': 2.3.0
'@bcoe/v8-coverage': 1.0.2
@@ -9322,7 +9296,7 @@ snapshots:
transitivePeerDependencies:
- supports-color
'@vitest/eslint-plugin@1.3.4(eslint@9.31.0(jiti@2.4.2))(typescript@5.8.3)(vitest@3.2.4(@types/debug@4.1.12)(@types/node@22.15.30)(@vitest/browser@3.2.4)(jiti@2.4.2)(sass-embedded@1.89.2)(sass@1.97.0)(terser@5.44.1)(tsx@4.21.0)(yaml@2.8.0))':
'@vitest/eslint-plugin@1.3.4(eslint@9.31.0(jiti@2.4.2))(typescript@5.8.3)(vitest@3.2.4)':
dependencies:
'@typescript-eslint/utils': 8.33.1(eslint@9.31.0(jiti@2.4.2))(typescript@5.8.3)
eslint: 9.31.0(jiti@2.4.2)
@@ -14721,7 +14695,7 @@ snapshots:
vue-component-type-helpers@2.2.12: {}
vue-component-type-helpers@3.1.8: {}
vue-component-type-helpers@3.2.3: {}
vue-demi@0.14.10(vue@3.5.17(typescript@5.8.3)):
dependencies:

Binary file not shown.

View File

@@ -4,5 +4,11 @@
<template>
<router-view />
</template>
<!-- 全局样式 -->
<style scoped lang="scss"></style>
<style>
.popover-content
{
z-index: 99;
}
</style>

View File

@@ -0,0 +1,25 @@
import type { AgentSendInput, AgentToolOutput } from './types';
import { get, post } from '@/utils/request';
/**
* Agent 发送消息
*/
export function agentSend(data: AgentSendInput) {
return post('/ai-chat/agent/send', data);
}
/**
* 获取 Agent 工具列表
*/
export function getAgentTools() {
return post<AgentToolOutput[]>('/ai-chat/agent/tool').json();
}
/**
* 获取 Agent 上下文
*/
export function getAgentContext(sessionId: string) {
return post<string>(`/ai-chat/agent/context/${sessionId}`).json();
}
export * from './types';

View File

@@ -0,0 +1,51 @@
/**
* Agent 发送消息输入
*/
export interface AgentSendInput {
/** 会话id */
sessionId: string;
/** 用户内容 */
content: string;
/** api密钥Id */
tokenId: string;
/** 模型id */
modelId: string;
/** 已选择工具 */
tools: string[];
}
/**
* Agent 工具输出
*/
export interface AgentToolOutput {
/** 工具代码 */
code: string;
/** 工具名称 */
name: string;
}
/**
* Agent 结果类型
*/
export type AgentResultType = 'text' | 'toolCalling' | 'toolCalled' | 'usage' | 'toolCallUsage';
/**
* Agent 流式结果输出
*/
export interface AgentResultOutput {
/** 类型 */
type: AgentResultType;
/** 内容载体 */
content: any;
}
/**
* Agent 用量信息
*/
export interface AgentUsage {
input_tokens?: number;
output_tokens?: number;
total_tokens?: number;
prompt_tokens?: number;
completion_tokens?: number;
}

View File

@@ -0,0 +1,38 @@
import type {
GenerateImageRequest,
ImageModel,
PublishImageRequest,
TaskListRequest,
TaskListResponse,
TaskStatusResponse,
} from './types';
import { del, get, post } from '@/utils/request';
export function generateImage(data: GenerateImageRequest) {
return post<string>('/ai-image/generate', data).json();
}
export function getTaskStatus(taskId: string) {
return get<TaskStatusResponse>(`/ai-image/task/${taskId}`).json();
}
export function getMyTasks(params: TaskListRequest) {
return get<TaskListResponse>('/ai-image/my-tasks', params).json();
}
export function getImagePlaza(params: TaskListRequest) {
return get<TaskListResponse>('/ai-image/plaza', params).json();
}
export function publishImage(data: PublishImageRequest) {
return post<void>('/ai-image/publish', data).json();
}
export function getImageModels() {
return post<ImageModel[]>('/ai-image/model').json();
}
export function deleteMyTasks(taskIds: string[]) {
const query = taskIds.map(id => `ids=${encodeURIComponent(id)}`).join('&');
const url = `/ai-image/my-tasks${query ? `?${query}` : ''}`;
return del<void>(url).json();
}

View File

@@ -0,0 +1,69 @@
export interface GenerateImageRequest {
tokenId: string;
prompt: string;
modelId: string;
referenceImagesPrefixBase64?: string[];
}
export interface TaskStatusResponse {
id: string;
prompt: string;
storePrefixBase64?: string;
storeUrl?: string;
taskStatus: 'Processing' | 'Success' | 'Fail';
publishStatus: string;
categories: string[];
creationTime: string;
errorInfo?: string;
}
export interface TaskListRequest {
SkipCount: number;
MaxResultCount: number;
TaskStatus?: 'Processing' | 'Success' | 'Fail';
Prompt?: string;
PublishStatus?: 'Unpublished' | 'Published';
StartTime?: string;
EndTime?: string;
OrderByColumn?: string;
IsAsc?: string;
IsAscending?: boolean;
Sorting?: string;
Categories?: string;
UserName?: string;
}
export interface TaskItem {
id: string;
prompt: string;
storePrefixBase64?: string;
storeUrl?: string;
taskStatus: 'Processing' | 'Success' | 'Fail';
publishStatus: string;
categories: string[];
creationTime: string;
errorInfo?: string;
isAnonymous?: boolean;
userName?: string | null;
userId?: string | null;
}
export interface TaskListResponse {
total: number;
items: TaskItem[];
}
export interface PublishImageRequest {
taskId: string;
categories: string[];
isAnonymous?: boolean;
}
export interface ImageModel {
id: string;
modelId: string;
modelName: string;
modelDescribe: string;
remark: string;
isPremiumPackage: boolean;
}

View File

@@ -8,6 +8,7 @@ import type {
AiModelCreateInput,
AiModelUpdateInput,
AiModelGetListInput,
AppShortcutDto,
PagedResultDto,
} from './types';
@@ -98,3 +99,15 @@ export function updateModel(data: AiModelUpdateInput) {
export function deleteModel(id: string) {
return del(`/channel/model/${id}`).json();
}
// 清除尊享模型ID缓存
export function clearPremiumModelCache() {
return post('/model/clear-premium-cache').json();
}
// ==================== 快捷渠道 ====================
// 获取快捷渠道列表
export function getAppShortcutList() {
return get<AppShortcutDto[]>('/channel/app-shortcut').json();
}

View File

@@ -66,6 +66,7 @@ export interface AiModelDto {
providerName?: string;
iconUrl?: string;
isPremium: boolean;
isEnabled: boolean;
}
// 创建AI模型输入
@@ -84,6 +85,7 @@ export interface AiModelCreateInput {
providerName?: string;
iconUrl?: string;
isPremium: boolean;
isEnabled: boolean;
}
// 更新AI模型输入
@@ -103,6 +105,7 @@ export interface AiModelUpdateInput {
providerName?: string;
iconUrl?: string;
isPremium: boolean;
isEnabled: boolean;
}
// 获取AI模型列表输入
@@ -114,6 +117,17 @@ export interface AiModelGetListInput {
maxResultCount?: number;
}
// 快捷渠道DTO
export interface AppShortcutDto {
id: string;
name: string;
endpoint: string;
extraUrl?: string;
apiKey: string;
orderNum: number;
creationTime: string;
}
// 分页结果
export interface PagedResultDto<T> {
items: T[];

View File

@@ -1,7 +1,7 @@
import type { ChatMessageVo, GetChatListParams, SendDTO } from './types';
import { get, post } from '@/utils/request';
// 发送消息
// 发送消息(旧接口)
export function send(data: SendDTO) {
const url = data.sessionId !== 'not_login'
? `/ai-chat/send/?sessionId=${data.sessionId}`
@@ -9,6 +9,12 @@ export function send(data: SendDTO) {
return post(url, data);
}
// 统一发送消息接口支持4种API类型
export function unifiedSend(data: any, apiType: string, modelId: string, sessionId: string) {
const url = `/ai-chat/unified/send?apiType=${apiType}&modelId=${modelId}&sessionId=${sessionId}`;
return post(url, data);
}
// 新增对应会话聊天记录
export function addChat(data: ChatMessageVo) {
return post('/system/message', data).json();

View File

@@ -1,4 +1,5 @@
export * from './announcement'
export * from './agent';
export * from './auth';
export * from './chat';
export * from './file';
@@ -6,3 +7,4 @@ export * from './model';
export * from './pay';
export * from './session';
export * from './user';
export * from './aiImage';

View File

@@ -60,9 +60,57 @@ export function getApiKey() {
return get<any>('/token').json();
}
// 充值记录查询参数类型
export interface RechargeLogQueryParams {
skipCount?: number;
maxResultCount?: number;
isFree?: boolean;
minRechargeAmount?: number;
maxRechargeAmount?: number;
startTime?: string;
endTime?: string;
orderByColumn?: string;
isAsc?: string;
isAscending?: boolean;
}
// 查询充值记录
export function getRechargeLog() {
return get<any>('/recharge/account').json();
export function getRechargeLog(params?: RechargeLogQueryParams) {
const queryParams = new URLSearchParams();
if (params?.skipCount !== undefined) {
queryParams.append('SkipCount', params.skipCount.toString());
}
if (params?.maxResultCount !== undefined) {
queryParams.append('MaxResultCount', params.maxResultCount.toString());
}
if (params?.isFree !== undefined) {
queryParams.append('IsFree', params.isFree.toString());
}
if (params?.minRechargeAmount !== undefined) {
queryParams.append('MinRechargeAmount', params.minRechargeAmount.toString());
}
if (params?.maxRechargeAmount !== undefined) {
queryParams.append('MaxRechargeAmount', params.maxRechargeAmount.toString());
}
if (params?.startTime) {
queryParams.append('StartTime', params.startTime);
}
if (params?.endTime) {
queryParams.append('EndTime', params.endTime);
}
if (params?.orderByColumn) {
queryParams.append('OrderByColumn', params.orderByColumn);
}
if (params?.isAsc) {
queryParams.append('IsAsc', params.isAsc);
}
if (params?.isAscending !== undefined) {
queryParams.append('IsAscending', params.isAscending.toString());
}
const queryString = queryParams.toString();
const url = queryString ? `/recharge/account?${queryString}` : '/recharge/account';
return get<any>(url).json();
}
// 查询用户近7天token消耗
@@ -138,7 +186,8 @@ export function disableToken(id: string) {
// 新增接口2
// 获取可选择的token信息
export function getSelectableTokenInfo() {
return get<any>('/token/select-list').json();
// return get<any>('/token/select-list').json();
return get<any>('/token/select-list?includeDefault=false').json();
}
/*
返回数据
@@ -162,3 +211,44 @@ export function getPremiumPackageTokenUsage() {
"percentage": 0
}
] */
// 获取当前用户近24小时每小时Token消耗统计
// tokenId: 可选传入则查询该token的用量不传则查询全部
export function getLast24HoursTokenUsage(tokenId?: string) {
const url = tokenId
? `/usage-statistics/last24Hours-token-usage?tokenId=${tokenId}`
: '/usage-statistics/last24Hours-token-usage';
return get<any>(url).json();
}
/* 返回数据
[
{
"hour": "2026-01-23T13:32:49.237Z",
"totalTokens": 0,
"modelBreakdown": [
{
"modelId": "string",
"tokens": 0
}
]
}
]
*/
// 获取当前用户今日各模型使用量统计
// tokenId: 可选传入则查询该token的用量不传则查询全部
export function getTodayModelUsage(tokenId?: string) {
const url = tokenId
? `/usage-statistics/today-model-usage?tokenId=${tokenId}`
: '/usage-statistics/today-model-usage';
return get<any>(url).json();
}
/* 返回数据
[
{
"modelId": "string",
"usageCount": 0,
"totalTokens": 0
}
]
*/

View File

@@ -1,6 +1,6 @@
// 查询用户模型列表返回的数据结构
export interface GetSessionListVO {
id?: number;
id?: number | string;
category?: string;
modelName?: string;
modelDescribe?: string;
@@ -12,6 +12,11 @@ export interface GetSessionListVO {
apiKey?: string;
remark?: string;
modelId?: string;
isFree?: boolean; // 是否为免费模型
isPremiumPackage?: boolean; // 是否为尊享套餐模型
modelApiType?: string; // API 格式类型: Completions | Messages | Responses | GenerateContent
providerName?: string;
iconUrl?: string;
}
// 模型类型枚举

View File

@@ -1,5 +1,15 @@
import type { Component } from 'vue';
/**
* 会话类型枚举
*/
export enum SessionTypeEnum {
/** 普通聊天 */
Chat = 0,
/** Agent智能体 */
Agent = 1,
}
export interface GetSessionListParams {
/**
* 创建者
@@ -61,6 +71,10 @@ export interface GetSessionListParams {
* 用户id
*/
userId: number;
/**
* 会话类型
*/
sessionType?: SessionTypeEnum;
}
/**
@@ -96,6 +110,10 @@ export interface ChatSessionVo {
* 自定义的消息前缀图标字段
*/
prefixIcon?: Component;
/**
* 会话类型
*/
sessionType?: SessionTypeEnum;
}
/**
@@ -147,6 +165,10 @@ export interface CreateSessionDTO {
* 用户id
*/
userId: number;
/**
* 会话类型
*/
sessionType?: SessionTypeEnum;
}
// export interface CreateSessionVO {

View File

@@ -0,0 +1,17 @@
import { post } from '@/utils/request';
import type {
ProfitStatisticsInput,
ProfitStatisticsOutput,
TokenStatisticsInput,
TokenStatisticsOutput,
} from './types';
// 获取利润统计数据
export function getProfitStatistics(data: ProfitStatisticsInput) {
return post<ProfitStatisticsOutput>('/system-statistics/profit', data).json();
}
// 获取指定日期各模型Token统计
export function getTokenStatistics(data: TokenStatisticsInput) {
return post<TokenStatisticsOutput>('/system-statistics/token', data).json();
}

View File

@@ -0,0 +1,41 @@
// 利润统计输入
export interface ProfitStatisticsInput {
currentCost: number;
}
// 利润统计输出
export interface ProfitStatisticsOutput {
date: string;
totalUsedTokens: number;
totalUsedTokensInHundredMillion: number;
totalRemainingTokens: number;
totalRemainingTokensInHundredMillion: number;
currentCost: number;
costPerHundredMillion: number;
totalCost: number;
totalRevenue: number;
profitRate: number;
costAt200Price: number;
}
// Token统计输入
export interface TokenStatisticsInput {
date: string;
}
// 模型Token统计DTO
export interface ModelTokenStatisticsDto {
modelId: string;
modelName: string;
tokens: number;
tokensInWan: number;
count: number;
cost: number;
costPerHundredMillion: number;
}
// Token统计输出
export interface TokenStatisticsOutput {
date: string;
modelStatistics: ModelTokenStatisticsDto[];
}

Binary file not shown.

Before

Width:  |  Height:  |  Size: 51 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 86 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 12 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 206 KiB

Some files were not shown because too many files have changed in this diff Show More