196 Commits

Author SHA1 Message Date
ccnetcore
dbe5a95b47 Merge remote-tracking branch 'origin/ai-hub' into ai-hub 2026-02-09 23:35:45 +08:00
ccnetcore
c1c43c1464 fix: 修复api样式问题 2026-02-09 23:24:41 +08:00
Gsh
13d6fc228a fix: 网页端Anthropic Claude对话格式去除system角色,改为assistant角色 2026-02-07 02:19:29 +08:00
ccnetcore
58ce45ec92 fix: 修复api示例问题 2026-02-07 02:11:35 +08:00
ccnetcore
048a9b9601 chore: 优化日志输出格式并调整组件类型声明
- 统一 Serilog 文件与控制台日志的输出模板,提升可读性
- 降低部分 ASP.NET Core 内部组件的日志级别,减少无关噪音
- 移除前端 types 中未使用的 ElSegmented 组件声明
2026-02-07 01:58:44 +08:00
ccnetcore
097798268b style: 优化vip到期时间展示 2026-02-07 01:31:25 +08:00
ccnetcore
f7eb1b7048 Merge branch 'url' into ai-hub 2026-02-07 01:29:06 +08:00
ccnetcore
9550ed57c0 feat: 新增api接口 2026-02-07 01:28:05 +08:00
Gsh
4133b80d49 fix: 网页端Anthropic Claude对话格式去除system角色,改为assistant角色 2026-02-07 01:17:51 +08:00
Gsh
57b03436f3 fix: 动画超时加载时间设置60秒 2026-02-07 00:48:42 +08:00
Gsh
836ea90145 fix: Anthropic Claude 网页对话格式修改 2026-02-07 00:47:22 +08:00
chenchun
a040b7a16a fix: 修复bug
将 responseResult.Item1 的比较从严格等于改为包含判断,兼容部分 AI 工具返回带前后缀的异常字符串(例如 "exception: ..." 等),避免漏掉异常分支处理。修改文件:Yi.Framework.AiHub.Domain/Managers/AiGateWayManager.cs。
2026-02-06 16:56:37 +08:00
ccnetcore
19b27d8e9a feat: 完成api页面搭建 2026-02-06 00:41:13 +08:00
ccnetcore
0b30dbb8de fix: 识别Claude上下文超限错误提示
补充对“input tokens exceeds the model's maximum context length”错误信息的判断,统一提示上下文过长的解决建议,提升异常提示准确性。
2026-02-04 23:46:22 +08:00
ccnetcore
fadaa0d129 chore: 日志中补充用户ID以增强异常定位
统一在 AiGateWayManager 各类异常日志中输出 userId,并向流式处理方法透传 userId,提升问题排查与审计能力,不影响现有业务逻辑。
2026-02-04 23:45:36 +08:00
ccnetcore
6863b773b4 fix: 延迟设置SSE响应头并兼容异常流数据
在成功获取第一条流式消息后再设置SSE响应头,避免无数据时提前建立连接;同时忽略异常类型的流消息,提升对部分AI工具的兼容性。
2026-02-04 23:34:57 +08:00
ccnetcore
82d97ab0b4 style: 调整3.6.1 2026-02-02 23:19:37 +08:00
Gsh
de94bb260b fix: 暗色主题优化,优化ai对话 2026-02-02 23:17:50 +08:00
ccnetcore
016f930021 style: 调整markdown样式问题 2026-02-02 22:03:48 +08:00
ccnetcore
9b7d98773b style: 整体文章样式优化 2026-02-02 21:33:53 +08:00
ccnetcore
6988dd224f style: 修复markdown问题 2026-02-02 19:50:05 +08:00
chenchun
c9b5418a70 fix: 修复markdown引入问题 2026-02-02 18:32:47 +08:00
chenchun
74d56ced8a Merge remote-tracking branch 'origin/ai-hub' into ai-hub 2026-02-02 18:04:32 +08:00
chenchun
790fca50f3 fix: 修复markdown引入问题 2026-02-02 18:04:12 +08:00
ccnetcore
728b5958f3 fix: 修复实验性功能 2026-02-01 21:12:47 +08:00
ccnetcore
5a39330fdb style: 调整消息操作按钮左边距
移除 .message-wrapper__actions 下 el-button 的左外边距,统一按钮对齐效果
2026-02-01 21:04:08 +08:00
Gsh
70c7e0c331 feat: 消息ui优化 2026-02-01 20:31:31 +08:00
Gsh
67b215ce7a feat: 对话id补充,适配不同类型 2026-02-01 20:17:13 +08:00
ccnetcore
d05324cd12 Merge remote-tracking branch 'origin/ai-hub' into ai-hub 2026-02-01 19:32:54 +08:00
ccnetcore
33937703c7 feat: 完成排行榜功能 2026-02-01 19:32:46 +08:00
Gsh
7f809e0718 feat: 对话id补充 2026-02-01 19:23:21 +08:00
ccnetcore
6d54c650f0 feat: 消息创建返回ID并在流式响应中下发
- 消息管理器创建用户/系统消息时返回 MessageId
- 网关在流式响应中新增消息创建事件,返回 MessageId 与创建时间
- 统一在消息创建完成后发送 [DONE] 标识,优化流式结束时机
2026-02-01 13:02:06 +08:00
Gsh
11cbb1b612 feat: 项目加载优化 2026-02-01 00:52:10 +08:00
Gsh
3b6887dc2e feat: 消息ui优化 2026-01-31 23:38:39 +08:00
Gsh
6af3fb44f4 feat: 消息ui优化 2026-01-31 21:33:18 +08:00
Gsh
f57b5befd7 feat: 消息ui优化 2026-01-31 21:28:13 +08:00
ccnetcore
dbc6b8cf5e feat: 支持消息自定义创建时间并完善TokenUsage初始化
- 用户消息创建支持传入创建时间,用于统计与回放
- TokenUsage 为空时自动初始化,避免空引用问题
- 网关记录消息开始时间并传递至消息管理器
- 标记并停用旧的发送消息接口
- 前端版本号更新至 3.6
- 移除未使用的 VITE_BUILD_COMPRESS 类型声明
2026-01-31 21:22:09 +08:00
Gsh
007a4c223a feat: ai的消息取消气泡样式 2026-01-31 20:33:03 +08:00
Gsh
ab2c11e05c Merge remote-tracking branch 'origin/ai-hub' into ai-hub 2026-01-31 20:26:36 +08:00
Gsh
ec382995b4 feat: 对话中消息编辑与重新生成与删除功能 2026-01-31 20:26:20 +08:00
ccnetcore
7a38526ab3 fix: 修复删除消息接口参数绑定方式
将 DeleteAsync 方法的参数绑定由 FromBody 调整为 FromQuery,避免在删除消息时参数无法正确接收的问题
2026-01-31 16:07:30 +08:00
chenchun
4441244575 feat: 新增消息软删除及批量隐藏接口 2026-01-29 14:40:03 +08:00
chenchun
adafb65221 perf: 优化markdown显示问题 2026-01-28 16:27:07 +08:00
chenchun
74e936c6d3 refactor: 将 AnthropicInput.InputSchema 改为 object 并移除相关强类型定义
将原来的 Input_schema、InputSchemaValue 等强类型移除,AnthropicInput 中的 input_schema 属性类型由 Input_schema? 改为 object?,用于接受任意结构的输入 schema,简化序列化/反序列化处理。
2026-01-28 10:48:11 +08:00
ccnetcore
36aa29f9f1 Merge remote-tracking branch 'origin/ai-hub' into ai-hub 2026-01-26 21:08:45 +08:00
ccnetcore
d4fcbdc390 feat: 发布v3.5版本 2026-01-26 21:08:21 +08:00
chenchun
ca43879cc3 fix: 优化 Anthropic 流式对话错误提示并移除 -thinking 处理
- 统一并增强错误消息:在响应包含 "prompt is too long" 或 "提示词太长" 时,增加友好提示,建议在 claudecode 中执行 /compact 或开启新会话重试。
- 将流式与非流式的异常信息处理统一,抛出包含详细提示的异常并保留日志。
- 移除对 input.Model.EndsWith("-thinking") 及替换 "-thinking" 的处理(清理冗余逻辑)。
2026-01-26 11:37:31 +08:00
ccnetcore
9b5826a6b1 请提供需要提交的变更内容或简要说明(例如:做了什么改动、涉及哪些模块)。
我将按你给定的规范生成对应的提交标题和说明。
2026-01-25 14:13:24 +08:00
ccnetcore
485f19572b feat: 合并知识库目录与内容获取接口
将原有“目录查询”和“按目录获取内容”两个工具合并为单一接口,一次性返回所有目录及对应内容,简化调用方式;新增统一的知识库项模型,并补充异常与失败场景的日志与兜底处理。
2026-01-25 14:09:10 +08:00
ccnetcore
2845f03250 feat: 新增公告管理 2026-01-24 22:08:54 +08:00
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
322 changed files with 29257 additions and 13497 deletions

1
.gitignore vendored
View File

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

View File

@@ -0,0 +1,59 @@
using System.ComponentModel.DataAnnotations;
using Yi.Framework.AiHub.Domain.Shared.Enums;
namespace Yi.Framework.AiHub.Application.Contracts.Dtos.Announcement;
/// <summary>
/// 创建公告输入
/// </summary>
public class AnnouncementCreateInput
{
/// <summary>
/// 标题
/// </summary>
[Required(ErrorMessage = "标题不能为空")]
[StringLength(200, ErrorMessage = "标题不能超过200个字符")]
public string Title { get; set; }
/// <summary>
/// 内容列表
/// </summary>
[Required(ErrorMessage = "内容不能为空")]
[MinLength(1, ErrorMessage = "至少需要一条内容")]
public List<string> Content { get; set; } = new List<string>();
/// <summary>
/// 备注
/// </summary>
[StringLength(500, ErrorMessage = "备注不能超过500个字符")]
public string? Remark { get; set; }
/// <summary>
/// 图片url
/// </summary>
[StringLength(500, ErrorMessage = "图片URL不能超过500个字符")]
public string? ImageUrl { get; set; }
/// <summary>
/// 开始时间
/// </summary>
[Required(ErrorMessage = "开始时间不能为空")]
public DateTime StartTime { get; set; }
/// <summary>
/// 活动结束时间
/// </summary>
public DateTime? EndTime { get; set; }
/// <summary>
/// 公告类型
/// </summary>
[Required(ErrorMessage = "公告类型不能为空")]
public AnnouncementTypeEnum Type { get; set; }
/// <summary>
/// 跳转链接
/// </summary>
[StringLength(500, ErrorMessage = "跳转链接不能超过500个字符")]
public string? Url { get; set; }
}

View File

@@ -0,0 +1,59 @@
using Yi.Framework.AiHub.Domain.Shared.Enums;
namespace Yi.Framework.AiHub.Application.Contracts.Dtos.Announcement;
/// <summary>
/// 公告 DTO后台管理使用
/// </summary>
public class AnnouncementDto
{
/// <summary>
/// 公告ID
/// </summary>
public Guid Id { get; set; }
/// <summary>
/// 标题
/// </summary>
public string Title { get; set; } = string.Empty;
/// <summary>
/// 内容列表
/// </summary>
public List<string> Content { get; set; } = new List<string>();
/// <summary>
/// 备注
/// </summary>
public string? Remark { get; set; }
/// <summary>
/// 图片url
/// </summary>
public string? ImageUrl { get; set; }
/// <summary>
/// 开始时间
/// </summary>
public DateTime StartTime { get; set; }
/// <summary>
/// 活动结束时间
/// </summary>
public DateTime? EndTime { get; set; }
/// <summary>
/// 公告类型
/// </summary>
public AnnouncementTypeEnum Type { get; set; }
/// <summary>
/// 跳转链接
/// </summary>
public string? Url { get; set; }
/// <summary>
/// 创建时间
/// </summary>
public DateTime CreationTime { get; set; }
}

View File

@@ -0,0 +1,29 @@
using Yi.Framework.AiHub.Domain.Shared.Enums;
namespace Yi.Framework.AiHub.Application.Contracts.Dtos.Announcement;
/// <summary>
/// 获取公告列表输入
/// </summary>
public class AnnouncementGetListInput
{
/// <summary>
/// 搜索关键字
/// </summary>
public string? SearchKey { get; set; }
/// <summary>
/// 跳过数量
/// </summary>
public int SkipCount { get; set; } = 0;
/// <summary>
/// 最大结果数量
/// </summary>
public int MaxResultCount { get; set; } = 10;
/// <summary>
/// 公告类型
/// </summary>
public AnnouncementTypeEnum? Type { get; set; }
}

View File

@@ -0,0 +1,65 @@
using System.ComponentModel.DataAnnotations;
using Yi.Framework.AiHub.Domain.Shared.Enums;
namespace Yi.Framework.AiHub.Application.Contracts.Dtos.Announcement;
/// <summary>
/// 更新公告输入
/// </summary>
public class AnnouncementUpdateInput
{
/// <summary>
/// 公告ID
/// </summary>
[Required(ErrorMessage = "公告ID不能为空")]
public Guid Id { get; set; }
/// <summary>
/// 标题
/// </summary>
[Required(ErrorMessage = "标题不能为空")]
[StringLength(200, ErrorMessage = "标题不能超过200个字符")]
public string Title { get; set; }
/// <summary>
/// 内容列表
/// </summary>
[Required(ErrorMessage = "内容不能为空")]
[MinLength(1, ErrorMessage = "至少需要一条内容")]
public List<string> Content { get; set; } = new List<string>();
/// <summary>
/// 备注
/// </summary>
[StringLength(500, ErrorMessage = "备注不能超过500个字符")]
public string? Remark { get; set; }
/// <summary>
/// 图片url
/// </summary>
[StringLength(500, ErrorMessage = "图片URL不能超过500个字符")]
public string? ImageUrl { get; set; }
/// <summary>
/// 开始时间
/// </summary>
[Required(ErrorMessage = "开始时间不能为空")]
public DateTime StartTime { get; set; }
/// <summary>
/// 活动结束时间
/// </summary>
public DateTime? EndTime { get; set; }
/// <summary>
/// 公告类型
/// </summary>
[Required(ErrorMessage = "公告类型不能为空")]
public AnnouncementTypeEnum Type { get; set; }
/// <summary>
/// 跳转链接
/// </summary>
[StringLength(500, ErrorMessage = "跳转链接不能超过500个字符")]
public string? Url { get; set; }
}

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> /// </summary>
public bool IsPremium { get; set; } public bool IsPremium { get; set; }
/// <summary>
/// 是否启用
/// </summary>
public bool IsEnabled { get; set; } = true;
} }

View File

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

View File

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

View File

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

View File

@@ -5,6 +5,11 @@ namespace Yi.Framework.AiHub.Application.Contracts.Dtos.Chat;
/// </summary> /// </summary>
public class ImageGenerationInput public class ImageGenerationInput
{ {
/// <summary>
/// 密钥id
/// </summary>
public Guid? TokenId { get; set; }
/// <summary> /// <summary>
/// 提示词 /// 提示词
/// </summary> /// </summary>
@@ -16,7 +21,7 @@ public class ImageGenerationInput
public string ModelId { get; set; } = string.Empty; public string ModelId { get; set; } = string.Empty;
/// <summary> /// <summary>
/// 参考图Base64列表可选包含前缀如 data:image/png;base64,... /// 参考图PrefixBase64列表可选包含前缀如 data:image/png;base64,...
/// </summary> /// </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.AiHub.Domain.Shared.Enums;
using Yi.Framework.Ddd.Application.Contracts;
namespace Yi.Framework.AiHub.Application.Contracts.Dtos.Chat; namespace Yi.Framework.AiHub.Application.Contracts.Dtos.Chat;
/// <summary> /// <summary>
/// 图片任务分页查询输入 /// 图片任务分页查询输入
/// </summary> /// </summary>
public class ImageTaskPageInput public class ImageMyTaskPageInput: PagedAllResultRequestDto
{ {
/// <summary> /// <summary>
/// 页码从1开始 /// 提示词
/// </summary> /// </summary>
public int PageIndex { get; set; } = 1; public string? Prompt { get; set; }
/// <summary>
/// 每页数量
/// </summary>
public int PageSize { get; set; } = 10;
/// <summary> /// <summary>
/// 任务状态筛选(可选) /// 任务状态筛选(可选)
/// </summary> /// </summary>
public TaskStatusEnum? TaskStatus { get; set; } 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; public string Prompt { get; set; } = string.Empty;
/// <summary> /// <summary>
/// 参考图Base64列表 /// 是否匿名
/// </summary> /// </summary>
public List<string>? ReferenceImagesBase64 { get; set; } public bool IsAnonymous { get; set; }
/// <summary>
/// 参考图URL列表
/// </summary>
public List<string>? ReferenceImagesUrl { get; set; }
/// <summary>
/// 生成图片Base64包含前缀
/// </summary>
public string? StoreBase64 { get; set; }
/// <summary> /// <summary>
/// 生成图片URL /// 生成图片URL
@@ -42,8 +32,35 @@ public class ImageTaskOutput
/// </summary> /// </summary>
public TaskStatusEnum TaskStatus { get; set; } 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>
/// 创建时间 /// 创建时间
/// </summary> /// </summary>
public DateTime CreationTime { get; set; } 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,47 @@
using System.Reflection;
using System.Text.Json.Serialization;
namespace Yi.Framework.AiHub.Application.Contracts.Dtos.Chat;
/// <summary>
/// 消息创建结果输出
/// </summary>
public class MessageCreatedOutput
{
/// <summary>
/// 消息类型
/// </summary>
[JsonIgnore]
public ChatMessageTypeEnum TypeEnum { get; set; }
/// <summary>
/// 消息类型
/// </summary>
public string Type => TypeEnum.ToString();
/// <summary>
/// 消息ID
/// </summary>
public Guid MessageId { get; set; }
/// <summary>
/// 消息创建时间
/// </summary>
public DateTime CreationTime { get; set; }
}
/// <summary>
/// 消息类型枚举
/// </summary>
public enum ChatMessageTypeEnum
{
/// <summary>
/// 用户消息
/// </summary>
UserMessage,
/// <summary>
/// 系统消息
/// </summary>
SystemMessage
}

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

@@ -8,3 +8,17 @@ public class MessageGetListInput:PagedAllResultRequestDto
[Required] [Required]
public Guid SessionId { get; set; } public Guid SessionId { get; set; }
} }
public class MessageDeleteInput
{
/// <summary>
/// 要删除的消息Id列表
/// </summary>
[Required]
public List<Guid> Ids { get; set; } = new();
/// <summary>
/// 是否同时隐藏后续消息(同一会话中时间大于当前消息的所有消息)
/// </summary>
public bool IsDeleteSubsequent { get; set; } = false;
}

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 public class ModelGetListOutput
{ {
@@ -7,12 +9,6 @@ public class ModelGetListOutput
/// </summary> /// </summary>
public Guid Id { get; set; } public Guid Id { get; set; }
/// <summary>
/// 模型分类
/// </summary>
public string Category { get; set; }
/// <summary> /// <summary>
/// 模型id /// 模型id
/// </summary> /// </summary>
@@ -28,36 +24,6 @@ public class ModelGetListOutput
/// </summary> /// </summary>
public string? ModelDescribe { get; set; } 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>
/// 备注信息 /// 备注信息
/// </summary> /// </summary>
@@ -67,4 +33,23 @@ public class ModelGetListOutput
/// 是否为尊享包 /// 是否为尊享包
/// </summary> /// </summary>
public bool IsPremiumPackage { get; set; } 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,14 @@
using Yi.Framework.AiHub.Domain.Shared.Enums;
namespace Yi.Framework.AiHub.Application.Contracts.Dtos;
/// <summary>
/// 排行榜查询输入
/// </summary>
public class RankingGetListInput
{
/// <summary>
/// 排行榜类型0-模型1-工具,不传返回全部
/// </summary>
public RankingTypeEnum? Type { get; set; }
}

View File

@@ -0,0 +1,41 @@
using Yi.Framework.AiHub.Domain.Shared.Enums;
namespace Yi.Framework.AiHub.Application.Contracts.Dtos;
/// <summary>
/// 排行榜项DTO
/// </summary>
public class RankingItemDto
{
public Guid Id { get; set; }
/// <summary>
/// 名称
/// </summary>
public string Name { get; set; } = null!;
/// <summary>
/// 描述
/// </summary>
public string Description { get; set; } = null!;
/// <summary>
/// Logo地址
/// </summary>
public string? LogoUrl { get; set; }
/// <summary>
/// 得分
/// </summary>
public decimal Score { get; set; }
/// <summary>
/// 提供者
/// </summary>
public string Provider { get; set; } = null!;
/// <summary>
/// 排行榜类型
/// </summary>
public RankingTypeEnum Type { 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 class SessionCreateAndUpdateInput
{ {
public string SessionTitle { get; set; } public string SessionTitle { get; set; }
public string SessionContent { get; set; } public string SessionContent { get; set; }
public string? Remark { 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 Volo.Abp.Application.Dtos;
using Yi.Framework.AiHub.Domain.Shared.Enums;
namespace Yi.Framework.AiHub.Application.Contracts.Dtos; namespace Yi.Framework.AiHub.Application.Contracts.Dtos;
@@ -7,4 +8,9 @@ public class SessionDto : FullAuditedEntityDto<Guid>
public string SessionTitle { get; set; } public string SessionTitle { get; set; }
public string SessionContent { get; set; } public string SessionContent { get; set; }
public string Remark { 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; namespace Yi.Framework.AiHub.Application.Contracts.Dtos;
public class SessionGetListInput:PagedAllResultRequestDto public class SessionGetListInput : PagedAllResultRequestDto
{ {
public string? SessionTitle { get; set; } 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

@@ -1,3 +1,4 @@
using Volo.Abp.Application.Dtos;
using Yi.Framework.AiHub.Application.Contracts.Dtos.Announcement; using Yi.Framework.AiHub.Application.Contracts.Dtos.Announcement;
namespace Yi.Framework.AiHub.Application.Contracts.IServices; namespace Yi.Framework.AiHub.Application.Contracts.IServices;
@@ -8,8 +9,42 @@ namespace Yi.Framework.AiHub.Application.Contracts.IServices;
public interface IAnnouncementService public interface IAnnouncementService
{ {
/// <summary> /// <summary>
/// 获取公告信息 /// 获取公告信息(前端首页使用)
/// </summary> /// </summary>
/// <returns>公告信息</returns> /// <returns>公告信息</returns>
Task<List<AnnouncementLogDto>> GetAsync(); Task<List<AnnouncementLogDto>> GetAsync();
/// <summary>
/// 获取公告列表(后台管理使用)
/// </summary>
/// <param name="input">查询参数</param>
/// <returns>分页公告列表</returns>
Task<PagedResultDto<AnnouncementDto>> GetListAsync(AnnouncementGetListInput input);
/// <summary>
/// 根据ID获取公告
/// </summary>
/// <param name="id">公告ID</param>
/// <returns>公告详情</returns>
Task<AnnouncementDto> GetByIdAsync(Guid id);
/// <summary>
/// 创建公告
/// </summary>
/// <param name="input">创建输入</param>
/// <returns>创建的公告</returns>
Task<AnnouncementDto> CreateAsync(AnnouncementCreateInput input);
/// <summary>
/// 更新公告
/// </summary>
/// <param name="input">更新输入</param>
/// <returns>更新后的公告</returns>
Task<AnnouncementDto> UpdateAsync(AnnouncementUpdateInput input);
/// <summary>
/// 删除公告
/// </summary>
/// <param name="id">公告ID</param>
Task DeleteAsync(Guid id);
} }

View File

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

View File

@@ -0,0 +1,16 @@
using Yi.Framework.AiHub.Application.Contracts.Dtos;
namespace Yi.Framework.AiHub.Application.Contracts.IServices;
/// <summary>
/// 排行榜服务接口
/// </summary>
public interface IRankingService
{
/// <summary>
/// 获取排行榜列表(全量返回)
/// </summary>
/// <param name="input">查询条件</param>
/// <returns>排行榜列表</returns>
Task<List<RankingItemDto>> GetListAsync(RankingGetListInput input);
}

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; namespace Yi.Framework.AiHub.Application.Contracts.IServices;
public interface IRechargeService public interface IRechargeService
{ {
/// <summary>
/// 查询已登录的账户充值记录(分页)
/// </summary>
Task<PagedResultDto<RechargeGetListOutput>> GetListByAccountAsync(RechargeGetListInput input);
/// <summary> /// <summary>
/// 移除用户vip及角色 /// 移除用户vip及角色
/// </summary> /// </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> /// </summary>
/// <returns>尊享服务Token用量统计</returns> /// <returns>尊享服务Token用量统计</returns>
Task<PremiumTokenUsageDto> GetPremiumTokenUsageAsync(); 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) public override async Task ExecuteAsync(ImageGenerationJobArgs args)
{ {
_logger.LogInformation("开始执行图片生成任务TaskId: {TaskId}, ModelId: {ModelId}, UserId: {UserId}", var task = await _imageStoreTaskRepository.GetFirstAsync(x => x.Id == args.TaskId);
args.TaskId, args.ModelId, args.UserId); if (task is null)
{
throw new UserFriendlyException($"{args.TaskId} 图片生成任务不存在");
}
_logger.LogInformation("开始执行图片生成任务TaskId: {TaskId}, ModelId: {ModelId}, UserId: {UserId}",
task.Id, task.ModelId, task.UserId);
try 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( await _aiGateWayManager.GeminiGenerateContentImageForStatisticsAsync(
args.TaskId, task.Id,
args.ModelId, task.ModelId,
request, request,
args.UserId); task.UserId,
tokenId: task.TokenId);
_logger.LogInformation("图片生成任务完成TaskId: {TaskId}", args.TaskId); _logger.LogInformation("图片生成任务完成TaskId: {TaskId}", args.TaskId);
} }
catch (Exception ex) 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);
// 更新任务状态为失败 task.TaskStatus = TaskStatusEnum.Fail;
var task = await _imageStoreTaskRepository.GetFirstAsync(x => x.Id == args.TaskId); task.ErrorInfo = error;
if (task != null)
{ await _imageStoreTaskRepository.UpdateAsync(task);
task.TaskStatus = TaskStatusEnum.Fail;
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 /// 图片任务ID
/// </summary> /// </summary>
public Guid TaskId { get; set; } 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 Medallion.Threading;
using Microsoft.AspNetCore.Authorization; using Microsoft.AspNetCore.Authorization;
using Microsoft.Extensions.Caching.Distributed;
using Microsoft.Extensions.Logging; using Microsoft.Extensions.Logging;
using SqlSugar; using SqlSugar;
using Volo.Abp.Application.Services; using Volo.Abp.Application.Services;
using Volo.Abp.Caching;
using Volo.Abp.Users; using Volo.Abp.Users;
using Yi.Framework.AiHub.Application.Contracts.Dtos.DailyTask; using Yi.Framework.AiHub.Application.Contracts.Dtos.DailyTask;
using Yi.Framework.AiHub.Domain.Entities; using Yi.Framework.AiHub.Domain.Entities;
@@ -25,27 +27,33 @@ public class DailyTaskService : ApplicationService
private readonly ISqlSugarRepository<MessageAggregateRoot> _messageRepository; private readonly ISqlSugarRepository<MessageAggregateRoot> _messageRepository;
private readonly ISqlSugarRepository<PremiumPackageAggregateRoot> _premiumPackageRepository; private readonly ISqlSugarRepository<PremiumPackageAggregateRoot> _premiumPackageRepository;
private readonly ILogger<DailyTaskService> _logger; private readonly ILogger<DailyTaskService> _logger;
private readonly IDistributedCache<DailyTaskConfigCacheDto> _taskConfigCache;
private IDistributedLockProvider DistributedLock => LazyServiceProvider.LazyGetRequiredService<IDistributedLockProvider>(); private IDistributedLockProvider DistributedLock => LazyServiceProvider.LazyGetRequiredService<IDistributedLockProvider>();
private readonly ISqlSugarRepository<AiModelEntity> _aiModelRepository; private readonly ISqlSugarRepository<AiModelEntity> _aiModelRepository;
// 任务配置
private readonly Dictionary<int, (long RequiredTokens, long RewardTokens, string Name, string Description)> private const string TaskConfigCacheKey = "AiHub:DailyTaskConfig";
_taskConfigs = new()
{ // 默认任务配置当Redis中没有配置时使用
{ 1, (10000000, 1000000, "尊享包1000w token任务", "累积使用尊享包 1000w token") }, // 1000w消耗 -> 100w奖励 private static readonly List<DailyTaskConfigItem> DefaultTaskConfigs = new()
{ 2, (30000000, 2000000, "尊享包3000w token任务", "累积使用尊享包 3000w token") } // 3000w消耗 -> 200w奖励 {
}; 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( public DailyTaskService(
ISqlSugarRepository<DailyTaskRewardRecordAggregateRoot> dailyTaskRepository, ISqlSugarRepository<DailyTaskRewardRecordAggregateRoot> dailyTaskRepository,
ISqlSugarRepository<MessageAggregateRoot> messageRepository, ISqlSugarRepository<MessageAggregateRoot> messageRepository,
ISqlSugarRepository<PremiumPackageAggregateRoot> premiumPackageRepository, ISqlSugarRepository<PremiumPackageAggregateRoot> premiumPackageRepository,
ILogger<DailyTaskService> logger, ISqlSugarRepository<AiModelEntity> aiModelRepository) ILogger<DailyTaskService> logger,
ISqlSugarRepository<AiModelEntity> aiModelRepository,
IDistributedCache<DailyTaskConfigCacheDto> taskConfigCache)
{ {
_dailyTaskRepository = dailyTaskRepository; _dailyTaskRepository = dailyTaskRepository;
_messageRepository = messageRepository; _messageRepository = messageRepository;
_premiumPackageRepository = premiumPackageRepository; _premiumPackageRepository = premiumPackageRepository;
_logger = logger; _logger = logger;
_aiModelRepository = aiModelRepository; _aiModelRepository = aiModelRepository;
_taskConfigCache = taskConfigCache;
} }
/// <summary> /// <summary>
@@ -57,20 +65,23 @@ public class DailyTaskService : ApplicationService
var userId = CurrentUser.GetId(); var userId = CurrentUser.GetId();
var today = DateTime.Today; var today = DateTime.Today;
// 1. 统计今日尊享包Token消耗量 // 1. 获取任务配置
var taskConfigs = await GetTaskConfigsAsync();
// 2. 统计今日尊享包Token消耗量
var todayConsumed = await GetTodayPremiumTokenConsumptionAsync(userId, today); var todayConsumed = await GetTodayPremiumTokenConsumptionAsync(userId, today);
// 2. 查询今日已领取的任务 // 3. 查询今日已领取的任务
var claimedTasks = await _dailyTaskRepository._DbQueryable var claimedTasks = await _dailyTaskRepository._DbQueryable
.Where(x => x.UserId == userId && x.TaskDate == today) .Where(x => x.UserId == userId && x.TaskDate == today)
.Select(x => new { x.TaskLevel, x.IsRewarded }) .Select(x => new { x.TaskLevel, x.IsRewarded })
.ToListAsync(); .ToListAsync();
// 3. 构建任务列表 // 4. 构建任务列表
var tasks = new List<DailyTaskItem>(); 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; int status;
if (claimed != null && claimed.IsRewarded) if (claimed != null && claimed.IsRewarded)
@@ -92,7 +103,7 @@ public class DailyTaskService : ApplicationService
tasks.Add(new DailyTaskItem tasks.Add(new DailyTaskItem
{ {
Level = level, Level = config.Level,
Name = config.Name, Name = config.Name,
Description = config.Description, Description = config.Description,
RequiredTokens = config.RequiredTokens, RequiredTokens = config.RequiredTokens,
@@ -121,16 +132,19 @@ public class DailyTaskService : ApplicationService
await using var handle = await using var handle =
await DistributedLock.AcquireLockAsync($"Yi:AiHub:ClaimTaskRewardLock:{userId}"); await DistributedLock.AcquireLockAsync($"Yi:AiHub:ClaimTaskRewardLock:{userId}");
var today = DateTime.Today; var today = DateTime.Today;
// 1. 验证任务等级 // 1. 获取任务配置
if (!_taskConfigs.TryGetValue(input.TaskLevel, out var taskConfig)) var taskConfigs = await GetTaskConfigsAsync();
var taskConfig = taskConfigs.FirstOrDefault(x => x.Level == input.TaskLevel);
// 2. 验证任务等级
if (taskConfig == null)
{ {
throw new UserFriendlyException($"无效的任务等级: {input.TaskLevel}"); throw new UserFriendlyException($"无效的任务等级: {input.TaskLevel}");
} }
// 2. 检查是否已领取 // 3. 检查是否已领取
var existingRecord = await _dailyTaskRepository._DbQueryable var existingRecord = await _dailyTaskRepository._DbQueryable
.Where(x => x.UserId == userId && x.TaskDate == today && x.TaskLevel == input.TaskLevel) .Where(x => x.UserId == userId && x.TaskDate == today && x.TaskLevel == input.TaskLevel)
.FirstAsync(); .FirstAsync();
@@ -140,7 +154,7 @@ public class DailyTaskService : ApplicationService
throw new UserFriendlyException("今日该任务奖励已领取,请明天再来!"); throw new UserFriendlyException("今日该任务奖励已领取,请明天再来!");
} }
// 3. 验证今日Token消耗是否达标 // 4. 验证今日Token消耗是否达标
var todayConsumed = await GetTodayPremiumTokenConsumptionAsync(userId, today); var todayConsumed = await GetTodayPremiumTokenConsumptionAsync(userId, today);
if (todayConsumed < taskConfig.RequiredTokens) if (todayConsumed < taskConfig.RequiredTokens)
{ {
@@ -148,18 +162,17 @@ public class DailyTaskService : ApplicationService
$"Token消耗未达标需要 {taskConfig.RequiredTokens / 10000}w当前 {todayConsumed / 10000}w"); $"Token消耗未达标需要 {taskConfig.RequiredTokens / 10000}w当前 {todayConsumed / 10000}w");
} }
// 4. 创建奖励包(使用 PremiumPackageManager // 5. 创建奖励包
var premiumPackage = var premiumPackage =
new PremiumPackageAggregateRoot(userId, taskConfig.RewardTokens, $"每日任务:{taskConfig.Name}") new PremiumPackageAggregateRoot(userId, taskConfig.RewardTokens, $"每日任务:{taskConfig.Name}")
{ {
PurchaseAmount = 0, // 奖励不需要付费 PurchaseAmount = 0,
Remark = $"{today:yyyy-MM-dd} 每日任务奖励" Remark = $"{today:yyyy-MM-dd} 每日任务奖励"
}; };
await _premiumPackageRepository.InsertAsync(premiumPackage); await _premiumPackageRepository.InsertAsync(premiumPackage);
// 5. 记录领取记录 // 6. 记录领取记录
var record = new DailyTaskRewardRecordAggregateRoot(userId, input.TaskLevel, today, taskConfig.RewardTokens) var record = new DailyTaskRewardRecordAggregateRoot(userId, input.TaskLevel, today, taskConfig.RewardTokens)
{ {
Remark = $"完成任务{input.TaskLevel},名称:{taskConfig.Name},消耗 {todayConsumed / 10000}w token" Remark = $"完成任务{input.TaskLevel},名称:{taskConfig.Name},消耗 {todayConsumed / 10000}w token"
@@ -197,4 +210,21 @@ public class DailyTaskService : ApplicationService
return totalTokens; 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

@@ -13,6 +13,7 @@ using Yi.Framework.Rbac.Application.Contracts.IServices;
using Yi.Framework.Rbac.Domain.Shared.Dtos; using Yi.Framework.Rbac.Domain.Shared.Dtos;
using Yi.Framework.SqlSugarCore.Abstractions; using Yi.Framework.SqlSugarCore.Abstractions;
using Yi.Framework.AiHub.Domain.Extensions; using Yi.Framework.AiHub.Domain.Extensions;
using Yi.Framework.AiHub.Domain.Shared.Enums;
namespace Yi.Framework.AiHub.Application.Services; namespace Yi.Framework.AiHub.Application.Services;
@@ -58,7 +59,7 @@ public class AiAccountService : ApplicationService
if (output.IsVip) if (output.IsVip)
{ {
var recharges = await _rechargeRepository._DbQueryable var recharges = await _rechargeRepository._DbQueryable
.Where(x => x.UserId == userId) .Where(x => x.UserId == userId && x.RechargeType == RechargeTypeEnum.Vip)
.ToListAsync(); .ToListAsync();
if (recharges.Any()) if (recharges.Any())
@@ -81,162 +82,4 @@ public class AiAccountService : ApplicationService
return output; 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

@@ -1,6 +1,10 @@
using Mapster; using Mapster;
using Microsoft.AspNetCore.Authorization;
using Microsoft.AspNetCore.Mvc;
using Microsoft.Extensions.Caching.Distributed; using Microsoft.Extensions.Caching.Distributed;
using Microsoft.Extensions.Configuration; using Microsoft.Extensions.Configuration;
using SqlSugar;
using Volo.Abp.Application.Dtos;
using Volo.Abp.Application.Services; using Volo.Abp.Application.Services;
using Volo.Abp.Caching; using Volo.Abp.Caching;
using Yi.Framework.AiHub.Application.Contracts.Dtos.Announcement; using Yi.Framework.AiHub.Application.Contracts.Dtos.Announcement;
@@ -31,8 +35,9 @@ public class AnnouncementService : ApplicationService, IAnnouncementService
} }
/// <summary> /// <summary>
/// 获取公告信息 /// 获取公告信息(前端首页使用,允许匿名访问)
/// </summary> /// </summary>
[AllowAnonymous]
public async Task<List<AnnouncementLogDto>> GetAsync() public async Task<List<AnnouncementLogDto>> GetAsync()
{ {
// 使用 GetOrAddAsync 从缓存获取或添加数据缓存1小时 // 使用 GetOrAddAsync 从缓存获取或添加数据缓存1小时
@@ -48,18 +53,134 @@ public class AnnouncementService : ApplicationService, IAnnouncementService
return cacheData?.Logs ?? new List<AnnouncementLogDto>(); return cacheData?.Logs ?? new List<AnnouncementLogDto>();
} }
/// <summary>
/// 获取公告列表(后台管理使用)
/// </summary>
[Authorize(Roles = "admin")]
[HttpGet("announcement/list")]
public async Task<PagedResultDto<AnnouncementDto>> GetListAsync(AnnouncementGetListInput input)
{
var query = _announcementRepository._DbQueryable
.WhereIF(!string.IsNullOrWhiteSpace(input.SearchKey),
x => x.Title.Contains(input.SearchKey!) || (x.Remark != null && x.Remark.Contains(input.SearchKey!)))
.WhereIF(input.Type.HasValue, x => x.Type == input.Type!.Value)
.OrderByDescending(x => x.StartTime);
var totalCount = await query.CountAsync();
var items = await query
.Skip(input.SkipCount)
.Take(input.MaxResultCount)
.ToListAsync();
return new PagedResultDto<AnnouncementDto>(
totalCount,
items.Adapt<List<AnnouncementDto>>()
);
}
/// <summary>
/// 根据ID获取公告
/// </summary>
[Authorize(Roles = "admin")]
[HttpGet("{id}")]
public async Task<AnnouncementDto> GetByIdAsync(Guid id)
{
var entity = await _announcementRepository.GetByIdAsync(id);
if (entity == null)
{
throw new Exception("公告不存在");
}
return entity.Adapt<AnnouncementDto>();
}
/// <summary>
/// 创建公告
/// </summary>
[Authorize(Roles = "admin")]
[HttpPost]
public async Task<AnnouncementDto> CreateAsync(AnnouncementCreateInput input)
{
var entity = input.Adapt<AnnouncementAggregateRoot>();
await _announcementRepository.InsertAsync(entity);
// 清除缓存
await _announcementCache.RemoveAsync(AnnouncementCacheKey);
return entity.Adapt<AnnouncementDto>();
}
/// <summary>
/// 更新公告
/// </summary>
[Authorize(Roles = "admin")]
[HttpPut]
public async Task<AnnouncementDto> UpdateAsync(AnnouncementUpdateInput input)
{
var entity = await _announcementRepository.GetByIdAsync(input.Id);
if (entity == null)
{
throw new Exception("公告不存在");
}
// 更新字段
entity.Title = input.Title;
entity.Content = input.Content;
entity.Remark = input.Remark;
entity.ImageUrl = input.ImageUrl;
entity.StartTime = input.StartTime;
entity.EndTime = input.EndTime;
entity.Type = input.Type;
entity.Url = input.Url;
await _announcementRepository.UpdateAsync(entity);
// 清除缓存
await _announcementCache.RemoveAsync(AnnouncementCacheKey);
return entity.Adapt<AnnouncementDto>();
}
/// <summary>
/// 删除公告
/// </summary>
[Authorize(Roles = "admin")]
[HttpDelete("announcement/{id}")]
public async Task DeleteAsync(Guid id)
{
var entity = await _announcementRepository.GetByIdAsync(id);
if (entity == null)
{
throw new Exception("公告不存在");
}
await _announcementRepository.DeleteAsync(entity);
// 清除缓存
await _announcementCache.RemoveAsync(AnnouncementCacheKey);
}
/// <summary> /// <summary>
/// 从数据库加载公告数据 /// 从数据库加载公告数据
/// </summary> /// </summary>
private async Task<AnnouncementCacheDto> LoadAnnouncementDataAsync() private async Task<AnnouncementCacheDto> LoadAnnouncementDataAsync()
{ {
// 查询所有公告日志,按日期降序排列 // 一次性查出全部公告(不排序)
var logs = await _announcementRepository._DbQueryable var logs = await _announcementRepository._DbQueryable
.OrderByDescending(x => x.StartTime)
.ToListAsync(); .ToListAsync();
var now = DateTime.Now;
// 内存中处理排序
var orderedLogs = logs
.OrderByDescending(x =>
x.StartTime <= now &&
(x.EndTime == null || x.EndTime >= now)
)
.ThenByDescending(x => x.StartTime)
.ToList();
// 转换为 DTO // 转换为 DTO
var logDtos = logs.Adapt<List<AnnouncementLogDto>>(); var logDtos = orderedLogs.Adapt<List<AnnouncementLogDto>>();
return new AnnouncementCacheDto return new AnnouncementCacheDto
{ {
Logs = logDtos Logs = logDtos

View File

@@ -14,18 +14,21 @@ namespace Yi.Framework.AiHub.Application.Services;
/// <summary> /// <summary>
/// 渠道商管理服务实现 /// 渠道商管理服务实现
/// </summary> /// </summary>
[Authorize] [Authorize(Roles = "admin")]
public class ChannelService : ApplicationService, IChannelService public class ChannelService : ApplicationService, IChannelService
{ {
private readonly ISqlSugarRepository<AiAppAggregateRoot, Guid> _appRepository; private readonly ISqlSugarRepository<AiAppAggregateRoot, Guid> _appRepository;
private readonly ISqlSugarRepository<AiModelEntity, Guid> _modelRepository; private readonly ISqlSugarRepository<AiModelEntity, Guid> _modelRepository;
private readonly ISqlSugarRepository<AiAppShortcutAggregateRoot, Guid> _appShortcutRepository;
public ChannelService( public ChannelService(
ISqlSugarRepository<AiAppAggregateRoot, Guid> appRepository, ISqlSugarRepository<AiAppAggregateRoot, Guid> appRepository,
ISqlSugarRepository<AiModelEntity, Guid> modelRepository) ISqlSugarRepository<AiModelEntity, Guid> modelRepository,
ISqlSugarRepository<AiAppShortcutAggregateRoot, Guid> appShortcutRepository)
{ {
_appRepository = appRepository; _appRepository = appRepository;
_modelRepository = modelRepository; _modelRepository = modelRepository;
_appShortcutRepository = appShortcutRepository;
} }
#region AI应用管理 #region AI应用管理
@@ -181,6 +184,7 @@ public class ChannelService : ApplicationService, IChannelService
ProviderName = input.ProviderName, ProviderName = input.ProviderName,
IconUrl = input.IconUrl, IconUrl = input.IconUrl,
IsPremium = input.IsPremium, IsPremium = input.IsPremium,
IsEnabled = input.IsEnabled,
IsDeleted = false IsDeleted = false
}; };
@@ -222,6 +226,7 @@ public class ChannelService : ApplicationService, IChannelService
entity.ProviderName = input.ProviderName; entity.ProviderName = input.ProviderName;
entity.IconUrl = input.IconUrl; entity.IconUrl = input.IconUrl;
entity.IsPremium = input.IsPremium; entity.IsPremium = input.IsPremium;
entity.IsEnabled = input.IsEnabled;
await _modelRepository.UpdateAsync(entity); await _modelRepository.UpdateAsync(entity);
return entity.Adapt<AiModelDto>(); return entity.Adapt<AiModelDto>();
@@ -237,4 +242,22 @@ public class ChannelService : ApplicationService, IChannelService
} }
#endregion #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.Extensions;
using Yi.Framework.AiHub.Domain.Managers; using Yi.Framework.AiHub.Domain.Managers;
using Yi.Framework.AiHub.Domain.Shared.Consts; 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;
using Yi.Framework.AiHub.Domain.Shared.Dtos.OpenAi; using Yi.Framework.AiHub.Domain.Shared.Dtos.OpenAi;
using Yi.Framework.AiHub.Domain.Shared.Enums; using Yi.Framework.AiHub.Domain.Shared.Enums;
@@ -50,6 +51,7 @@ public class AiChatService : ApplicationService
private readonly IAccountService _accountService; private readonly IAccountService _accountService;
private readonly ISqlSugarRepository<AgentStoreAggregateRoot> _agentStoreRepository; private readonly ISqlSugarRepository<AgentStoreAggregateRoot> _agentStoreRepository;
private readonly ISqlSugarRepository<AiModelEntity> _aiModelRepository; private readonly ISqlSugarRepository<AiModelEntity> _aiModelRepository;
private const string FreeModelId = "DeepSeek-V3-0324";
public AiChatService(IHttpContextAccessor httpContextAccessor, public AiChatService(IHttpContextAccessor httpContextAccessor,
AiBlacklistManager aiBlacklistManager, AiBlacklistManager aiBlacklistManager,
@@ -58,7 +60,8 @@ public class AiChatService : ApplicationService
ModelManager modelManager, ModelManager modelManager,
PremiumPackageManager premiumPackageManager, PremiumPackageManager premiumPackageManager,
ChatManager chatManager, TokenManager tokenManager, IAccountService accountService, ChatManager chatManager, TokenManager tokenManager, IAccountService accountService,
ISqlSugarRepository<AgentStoreAggregateRoot> agentStoreRepository, ISqlSugarRepository<AiModelEntity> aiModelRepository) ISqlSugarRepository<AgentStoreAggregateRoot> agentStoreRepository,
ISqlSugarRepository<AiModelEntity> aiModelRepository)
{ {
_httpContextAccessor = httpContextAccessor; _httpContextAccessor = httpContextAccessor;
_aiBlacklistManager = aiBlacklistManager; _aiBlacklistManager = aiBlacklistManager;
@@ -88,83 +91,91 @@ public class AiChatService : ApplicationService
} }
/// <summary> /// <summary>
/// 获取模型列表 /// 获取对话模型列表
/// </summary> /// </summary>
/// <returns></returns> /// <returns></returns>
public async Task<List<ModelGetListOutput>> GetModelAsync() public async Task<List<ModelGetListOutput>> GetModelAsync()
{ {
var output = await _aiModelRepository._DbQueryable var output = await _aiModelRepository._DbQueryable
.Where(x => x.IsEnabled == true)
.Where(x => x.ModelType == ModelTypeEnum.Chat) .Where(x => x.ModelType == ModelTypeEnum.Chat)
.Where(x => x.ModelApiType == ModelApiTypeEnum.OpenAi) // .Where(x => x.ModelApiType == ModelApiTypeEnum.Completions)
.OrderByDescending(x => x.OrderNum) .OrderByDescending(x => x.OrderNum)
.Select(x => new ModelGetListOutput .Select(x => new ModelGetListOutput
{ {
Id = x.Id, Id = x.Id,
Category = "chat",
ModelId = x.ModelId, ModelId = x.ModelId,
ModelName = x.Name, ModelName = x.Name,
ModelDescribe = x.Description, ModelDescribe = x.Description,
ModelPrice = 0,
ModelType = "1",
ModelShow = "0",
SystemPrompt = null,
ApiHost = null,
ApiKey = null,
Remark = x.Description, Remark = x.Description,
IsPremiumPackage = x.IsPremium IsPremiumPackage = x.IsPremium,
ModelApiType = x.ModelApiType,
IconUrl = x.IconUrl,
ProviderName = x.ProviderName
}).ToListAsync(); }).ToListAsync();
output.ForEach(x =>
{
if (x.ModelId == FreeModelId)
{
x.IsPremiumPackage = false;
x.IsFree = true;
}
});
return output; return output;
} }
/// <summary> // /// <summary>
/// 发送消息 // /// 发送消息
/// </summary> // /// </summary>
/// <param name="input"></param> // /// <param name="input"></param>
/// <param name="sessionId"></param> // /// <param name="sessionId"></param>
/// <param name="cancellationToken"></param> // /// <param name="cancellationToken"></param>
[HttpPost("ai-chat/send")] // [HttpPost("ai-chat/send")]
public async Task PostSendAsync([FromBody] ThorChatCompletionsRequest input, [FromQuery] Guid? sessionId, // [Obsolete]
CancellationToken cancellationToken) // public async Task PostSendAsync([FromBody] ThorChatCompletionsRequest input, [FromQuery] Guid? sessionId,
{ // CancellationToken cancellationToken)
//除了免费模型,其他的模型都要校验 // {
if (!input.Model.Contains("DeepSeek-R1")) // //除了免费模型,其他的模型都要校验
{ // if (input.Model!=FreeModelId)
//有token需要黑名单校验 // {
if (CurrentUser.IsAuthenticated) // //有token需要黑名单校验
{ // if (CurrentUser.IsAuthenticated)
await _aiBlacklistManager.VerifiyAiBlacklist(CurrentUser.GetId()); // {
if (!CurrentUser.IsAiVip()) // await _aiBlacklistManager.VerifiyAiBlacklist(CurrentUser.GetId());
{ // if (!CurrentUser.IsAiVip())
throw new UserFriendlyException("该模型需要VIP用户才能使用请购买VIP后重新登录重试"); // {
} // throw new UserFriendlyException("该模型需要VIP用户才能使用请购买VIP后重新登录重试");
} // }
else // }
{ // else
throw new UserFriendlyException("未登录用户只能使用未加速的DeepSeek-R1请登录后重试"); // {
} // throw new UserFriendlyException("未登录用户只能使用未加速的DeepSeek-R1请登录后重试");
} // }
// }
//如果是尊享包服务,需要校验是是否尊享包足够 //
if (CurrentUser.IsAuthenticated) // //如果是尊享包服务,需要校验是是否尊享包足够
{ // if (CurrentUser.IsAuthenticated)
var isPremium = await _modelManager.IsPremiumModelAsync(input.Model); // {
// var isPremium = await _modelManager.IsPremiumModelAsync(input.Model);
if (isPremium) //
{ // if (isPremium)
// 检查尊享token包用量 // {
var availableTokens = await _premiumPackageManager.GetAvailableTokensAsync(CurrentUser.GetId()); // // 检查尊享token包用量
if (availableTokens <= 0) // var availableTokens = await _premiumPackageManager.GetAvailableTokensAsync(CurrentUser.GetId());
{ // if (availableTokens <= 0)
throw new UserFriendlyException("尊享token包用量不足请先购买尊享token包"); // {
} // throw new UserFriendlyException("尊享token包用量不足请先购买尊享token包");
} // }
} // }
// }
//ai网关代理httpcontext //
await _aiGateWayManager.CompleteChatStreamForStatisticsAsync(_httpContextAccessor.HttpContext, input, // //ai网关代理httpcontext
CurrentUser.Id, sessionId, null, CancellationToken.None); // await _aiGateWayManager.CompleteChatStreamForStatisticsAsync(_httpContextAccessor.HttpContext, input,
} // CurrentUser.Id, sessionId, null, CancellationToken.None);
// }
/// <summary> /// <summary>
/// 发送消息 /// 发送消息
@@ -179,22 +190,10 @@ public class AiChatService : ApplicationService
{ {
throw new BusinessException("当前接口不支持第三方使用"); throw new BusinessException("当前接口不支持第三方使用");
} }
input.Model = "gpt-5-chat";
if (CurrentUser.IsAuthenticated) if (CurrentUser.IsAuthenticated)
{ {
await _aiBlacklistManager.VerifiyAiBlacklist(CurrentUser.GetId()); 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 //ai网关代理httpcontext
@@ -209,7 +208,7 @@ public class AiChatService : ApplicationService
[HttpPost("ai-chat/agent/send")] [HttpPost("ai-chat/agent/send")]
public async Task PostAgentSendAsync([FromBody] AgentSendInput input, CancellationToken cancellationToken) 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); await _aiBlacklistManager.VerifiyAiBlacklist(tokenValidation.UserId);
// 验证用户是否为VIP // 验证用户是否为VIP
@@ -241,7 +240,7 @@ public class AiChatService : ApplicationService
await _chatManager.AgentCompleteChatStreamAsync(_httpContextAccessor.HttpContext, await _chatManager.AgentCompleteChatStreamAsync(_httpContextAccessor.HttpContext,
input.SessionId, input.SessionId,
input.Content, input.Content,
input.Token, tokenValidation.Token,
tokenValidation.TokenId, tokenValidation.TokenId,
input.ModelId, input.ModelId,
tokenValidation.UserId, tokenValidation.UserId,
@@ -275,4 +274,89 @@ public class AiChatService : ApplicationService
var data = await _agentStoreRepository.GetFirstAsync(x => x.SessionId == sessionId); var data = await _agentStoreRepository.GetFirstAsync(x => x.SessionId == sessionId);
return data?.Store; 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.Hosting;
using Microsoft.AspNetCore.Http; using Microsoft.AspNetCore.Http;
using Microsoft.AspNetCore.Mvc; using Microsoft.AspNetCore.Mvc;
using SqlSugar;
using Volo.Abp; using Volo.Abp;
using Volo.Abp.Application.Services; using Volo.Abp.Application.Services;
using Volo.Abp.BackgroundJobs; using Volo.Abp.BackgroundJobs;
using Volo.Abp.Guids; using Volo.Abp.Guids;
using Volo.Abp.Users; using Volo.Abp.Users;
using Yi.Framework.AiHub.Application.Contracts.Dtos;
using Yi.Framework.AiHub.Application.Contracts.Dtos.Chat; using Yi.Framework.AiHub.Application.Contracts.Dtos.Chat;
using Yi.Framework.AiHub.Application.Jobs; using Yi.Framework.AiHub.Application.Jobs;
using Yi.Framework.AiHub.Domain.Entities.Chat; 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.Extensions;
using Yi.Framework.AiHub.Domain.Managers; using Yi.Framework.AiHub.Domain.Managers;
using Yi.Framework.AiHub.Domain.Shared.Consts; using Yi.Framework.AiHub.Domain.Shared.Consts;
@@ -32,6 +35,8 @@ public class AiImageService : ApplicationService
private readonly ModelManager _modelManager; private readonly ModelManager _modelManager;
private readonly IGuidGenerator _guidGenerator; private readonly IGuidGenerator _guidGenerator;
private readonly IWebHostEnvironment _webHostEnvironment; private readonly IWebHostEnvironment _webHostEnvironment;
private readonly TokenManager _tokenManager;
private readonly ISqlSugarRepository<AiModelEntity> _aiModelRepository;
public AiImageService( public AiImageService(
ISqlSugarRepository<ImageStoreTaskAggregateRoot> imageTaskRepository, ISqlSugarRepository<ImageStoreTaskAggregateRoot> imageTaskRepository,
@@ -40,7 +45,8 @@ public class AiImageService : ApplicationService
PremiumPackageManager premiumPackageManager, PremiumPackageManager premiumPackageManager,
ModelManager modelManager, ModelManager modelManager,
IGuidGenerator guidGenerator, IGuidGenerator guidGenerator,
IWebHostEnvironment webHostEnvironment) IWebHostEnvironment webHostEnvironment, TokenManager tokenManager,
ISqlSugarRepository<AiModelEntity> aiModelRepository)
{ {
_imageTaskRepository = imageTaskRepository; _imageTaskRepository = imageTaskRepository;
_backgroundJobManager = backgroundJobManager; _backgroundJobManager = backgroundJobManager;
@@ -49,6 +55,8 @@ public class AiImageService : ApplicationService
_modelManager = modelManager; _modelManager = modelManager;
_guidGenerator = guidGenerator; _guidGenerator = guidGenerator;
_webHostEnvironment = webHostEnvironment; _webHostEnvironment = webHostEnvironment;
_tokenManager = tokenManager;
_aiModelRepository = aiModelRepository;
} }
/// <summary> /// <summary>
@@ -65,6 +73,13 @@ public class AiImageService : ApplicationService
// 黑名单校验 // 黑名单校验
await _aiBlacklistManager.VerifiyAiBlacklist(userId); await _aiBlacklistManager.VerifiyAiBlacklist(userId);
//校验token
if (input.TokenId is not null)
{
await _tokenManager.ValidateTokenAsync(input.TokenId, input.ModelId);
}
// VIP校验 // VIP校验
if (!CurrentUser.IsAiVip()) if (!CurrentUser.IsAiVip())
{ {
@@ -86,32 +101,23 @@ public class AiImageService : ApplicationService
var task = new ImageStoreTaskAggregateRoot var task = new ImageStoreTaskAggregateRoot
{ {
Prompt = input.Prompt, Prompt = input.Prompt,
ReferenceImagesBase64 = input.ReferenceImagesBase64 ?? new List<string>(), ReferenceImagesPrefixBase64 = input.ReferenceImagesPrefixBase64 ?? new List<string>(),
ReferenceImagesUrl = new List<string>(), ReferenceImagesUrl = new List<string>(),
TaskStatus = TaskStatusEnum.Processing, TaskStatus = TaskStatusEnum.Processing,
UserId = userId UserId = userId,
UserName = CurrentUser.UserName,
TokenId = input.TokenId,
ModelId = input.ModelId
}; };
await _imageTaskRepository.InsertAsync(task); 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 await _backgroundJobManager.EnqueueAsync(new ImageGenerationJobArgs
{ {
TaskId = taskId, TaskId = task.Id,
ModelId = input.ModelId,
RequestJson = requestJson,
UserId = userId
}); });
return taskId; return task.Id;
} }
/// <summary> /// <summary>
@@ -134,12 +140,15 @@ public class AiImageService : ApplicationService
{ {
Id = task.Id, Id = task.Id,
Prompt = task.Prompt, Prompt = task.Prompt,
ReferenceImagesBase64 = task.ReferenceImagesBase64, // ReferenceImagesBase64 = task.ReferenceImagesBase64,
ReferenceImagesUrl = task.ReferenceImagesUrl, // ReferenceImagesUrl = task.ReferenceImagesUrl,
StoreBase64 = task.StoreBase64, // StoreBase64 = task.StoreBase64,
StoreUrl = task.StoreUrl, StoreUrl = task.StoreUrl,
TaskStatus = task.TaskStatus, 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> /// <param name="base64Data">Base64图片数据包含前缀如 data:image/png;base64,</param>
/// <returns>图片访问URL</returns> /// <returns>图片访问URL</returns>
[HttpPost("ai-image/upload-base64")] [HttpPost("ai-image/upload-base64")]
[AllowAnonymous]
public async Task<string> UploadBase64ToUrlAsync([FromBody] string base64Data) public async Task<string> UploadBase64ToUrlAsync([FromBody] string base64Data)
{ {
if (string.IsNullOrWhiteSpace(base64Data)) if (string.IsNullOrWhiteSpace(base64Data))
@@ -171,6 +181,7 @@ public class AiImageService : ApplicationService
{ {
mimeType = header.Split(':')[1].Split(';')[0]; mimeType = header.Split(':')[1].Split(';')[0];
} }
base64Content = parts[1]; base64Content = parts[1];
} }
} }
@@ -197,57 +208,182 @@ public class AiImageService : ApplicationService
throw new UserFriendlyException("Base64格式无效"); 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)) if (!Directory.Exists(uploadPath))
{ {
Directory.CreateDirectory(uploadPath); Directory.CreateDirectory(uploadPath);
} }
// 生成文件名并保存 // 保存文件
var fileId = _guidGenerator.Create(); var fileId = _guidGenerator.Create();
var fileName = $"{fileId}{extension}"; var fileName = $"{fileId}{extension}";
var filePath = Path.Combine(uploadPath, fileName); var filePath = Path.Combine(uploadPath, fileName);
await File.WriteAllBytesAsync(filePath, imageBytes); await File.WriteAllBytesAsync(filePath, imageBytes);
// 返回访问URL // 返回包含日期目录的访问URL
return $"/ai-images/{fileName}"; return $"/wwwroot/ai-images/{dateFolder}/{fileName}";
} }
/// <summary> /// <summary>
/// 分页查询任务列表 /// 分页查询我的任务列表
/// </summary> /// </summary>
/// <param name="input">分页查询参数</param> [HttpGet("ai-image/my-tasks")]
/// <returns>任务列表</returns> public async Task<PagedResult<ImageTaskOutput>> GetMyTaskPageAsync([FromQuery] ImageMyTaskPageInput input)
[HttpGet("ai-image/tasks")]
public async Task<PagedResult<ImageTaskOutput>> GetTaskPageAsync([FromQuery] ImageTaskPageInput input)
{ {
var userId = CurrentUser.GetId(); var userId = CurrentUser.GetId();
var query = _imageTaskRepository._DbQueryable RefAsync<int> total = 0;
var output = await _imageTaskRepository._DbQueryable
.Where(x => x.UserId == userId) .Where(x => x.UserId == userId)
.WhereIF(input.TaskStatus.HasValue, x => x.TaskStatus == input.TaskStatus!.Value) .WhereIF(input.TaskStatus is not null, x => x.TaskStatus == input.TaskStatus)
.OrderByDescending(x => x.CreationTime); .WhereIF(!string.IsNullOrWhiteSpace(input.Prompt), x => x.Prompt.Contains(input.Prompt))
.WhereIF(input.PublishStatus is not null, x => x.PublishStatus == input.PublishStatus)
var total = await query.CountAsync(); .WhereIF(input.StartTime is not null && input.EndTime is not null,
var items = await query x => x.CreationTime >= input.StartTime && x.CreationTime <= input.EndTime)
.Skip((input.PageIndex - 1) * input.PageSize) .OrderByDescending(x => x.CreationTime)
.Take(input.PageSize)
.Select(x => new ImageTaskOutput .Select(x => new ImageTaskOutput
{ {
Id = x.Id, Id = x.Id,
Prompt = x.Prompt, Prompt = x.Prompt,
ReferenceImagesBase64 = x.ReferenceImagesBase64,
ReferenceImagesUrl = x.ReferenceImagesUrl,
StoreBase64 = x.StoreBase64,
StoreUrl = x.StoreUrl, StoreUrl = x.StoreUrl,
TaskStatus = x.TaskStatus, 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;
} }
} }

View File

@@ -35,8 +35,59 @@ public class MessageService : ApplicationService
var entities = await _repository._DbQueryable var entities = await _repository._DbQueryable
.Where(x => x.SessionId == input.SessionId) .Where(x => x.SessionId == input.SessionId)
.Where(x=>x.UserId == userId) .Where(x=>x.UserId == userId)
.Where(x => !x.IsHidden)
.OrderBy(x => x.Id) .OrderBy(x => x.Id)
.ToPageListAsync(input.SkipCount, input.MaxResultCount, total); .ToPageListAsync(input.SkipCount, input.MaxResultCount, total);
return new PagedResultDto<MessageDto>(total, entities.Adapt<List<MessageDto>>()); return new PagedResultDto<MessageDto>(total, entities.Adapt<List<MessageDto>>());
} }
/// <summary>
/// 删除消息(软删除,标记为隐藏)
/// </summary>
/// <param name="input">删除参数包含消息Id列表和是否删除后续消息的开关</param>
[Authorize]
public async Task DeleteAsync([FromQuery] MessageDeleteInput input)
{
var userId = CurrentUser.GetId();
// 获取要删除的消息
var messages = await _repository._DbQueryable
.Where(x => input.Ids.Contains(x.Id))
.Where(x => x.UserId == userId)
.ToListAsync();
if (messages.Count == 0)
{
return;
}
// 标记当前消息为隐藏
var idsToHide = messages.Select(x => x.Id).ToList();
// 如果需要删除后续消息
if (input.IsDeleteSubsequent)
{
foreach (var message in messages)
{
// 获取同一会话中时间大于当前消息的所有消息Id
var subsequentIds = await _repository._DbQueryable
.Where(x => x.SessionId == message.SessionId)
.Where(x => x.UserId == userId)
.Where(x => x.CreationTime > message.CreationTime)
.Where(x => !x.IsHidden)
.Select(x => x.Id)
.ToListAsync();
idsToHide.AddRange(subsequentIds);
}
idsToHide = idsToHide.Distinct().ToList();
}
// 批量更新为隐藏状态
await _repository._Db.Updateable<MessageAggregateRoot>()
.SetColumns(x => x.IsHidden == true)
.Where(x => idsToHide.Contains(x.Id))
.ExecuteCommandAsync();
}
} }

View File

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

View File

@@ -84,7 +84,8 @@ public class SessionService : CrudAppService<SessionAggregateRoot, SessionDto, G
RefAsync<int> total = 0; RefAsync<int> total = 0;
var userId = CurrentUser.GetId(); var userId = CurrentUser.GetId();
var entities = await _repository._DbQueryable 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) .OrderByDescending(x => x.Id)
.ToPageListAsync(input.SkipCount, input.MaxResultCount, total); .ToPageListAsync(input.SkipCount, input.MaxResultCount, total);
return new PagedResultDto<SessionDto>(total, entities.Adapt<List<SessionDto>>()); 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<TokenAggregateRoot> _tokenRepository;
private readonly ISqlSugarRepository<UsageStatisticsAggregateRoot> _usageStatisticsRepository; private readonly ISqlSugarRepository<UsageStatisticsAggregateRoot> _usageStatisticsRepository;
private readonly ModelManager _modelManager; private readonly ModelManager _modelManager;
public TokenService( public TokenService(
ISqlSugarRepository<TokenAggregateRoot> tokenRepository, ISqlSugarRepository<TokenAggregateRoot> tokenRepository,
ISqlSugarRepository<UsageStatisticsAggregateRoot> usageStatisticsRepository, ISqlSugarRepository<UsageStatisticsAggregateRoot> usageStatisticsRepository,
@@ -90,7 +91,7 @@ public class TokenService : ApplicationService
} }
[HttpGet("token/select-list")] [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 userId = CurrentUser.GetId();
var tokens = await _tokenRepository._DbQueryable var tokens = await _tokenRepository._DbQueryable
@@ -104,12 +105,16 @@ public class TokenService : ApplicationService
IsDisabled = x.IsDisabled IsDisabled = x.IsDisabled
}).ToListAsync(); }).ToListAsync();
tokens.Insert(0,new TokenSelectListOutputDto if (includeDefault == true)
{ {
TokenId = Guid.Empty, tokens.Insert(0, new TokenSelectListOutputDto
Name = "默认", {
IsDisabled = false TokenId = Guid.Empty,
}); Name = "默认",
IsDisabled = false
});
}
return tokens; return tokens;
} }

View File

@@ -0,0 +1,38 @@
using Mapster;
using Microsoft.AspNetCore.Authorization;
using Microsoft.AspNetCore.Mvc;
using Volo.Abp.Application.Services;
using Yi.Framework.AiHub.Application.Contracts.Dtos;
using Yi.Framework.AiHub.Application.Contracts.IServices;
using Yi.Framework.AiHub.Domain.Entities;
using Yi.Framework.SqlSugarCore.Abstractions;
namespace Yi.Framework.AiHub.Application.Services;
/// <summary>
/// 排行榜服务
/// </summary>
public class RankingService : ApplicationService, IRankingService
{
private readonly ISqlSugarRepository<RankingItemAggregateRoot, Guid> _repository;
public RankingService(ISqlSugarRepository<RankingItemAggregateRoot, Guid> repository)
{
_repository = repository;
}
/// <summary>
/// 获取排行榜列表(全量返回,按得分降序)
/// </summary>
[HttpGet("ranking/list")]
[AllowAnonymous]
public async Task<List<RankingItemDto>> GetListAsync([FromQuery] RankingGetListInput input)
{
var query = _repository._DbQueryable
.WhereIF(input.Type.HasValue, x => x.Type == input.Type!.Value)
.OrderByDescending(x => x.Score);
var entities = await query.ToListAsync();
return entities.Adapt<List<RankingItemDto>>();
}
}

View File

@@ -1,6 +1,8 @@
using Mapster; using Mapster;
using Microsoft.AspNetCore.Authorization; using Microsoft.AspNetCore.Authorization;
using Microsoft.AspNetCore.Mvc; using Microsoft.AspNetCore.Mvc;
using SqlSugar;
using Volo.Abp.Application.Dtos;
using Volo.Abp.Application.Services; using Volo.Abp.Application.Services;
using Volo.Abp.Users; using Volo.Abp.Users;
using Yi.Framework.AiHub.Application.Contracts.Dtos.Recharge; using Yi.Framework.AiHub.Application.Contracts.Dtos.Recharge;
@@ -35,19 +37,29 @@ namespace Yi.Framework.AiHub.Application.Services
} }
/// <summary> /// <summary>
/// 查询已登录的账户充值记录 /// 查询已登录的账户充值记录(分页)
/// </summary> /// </summary>
/// <returns></returns> /// <returns></returns>
[Route("recharge/account")] [Route("recharge/account")]
[Authorize] [Authorize]
public async Task<List<RechargeGetListOutput>> GetListByAccountAsync() public async Task<PagedResultDto<RechargeGetListOutput>> GetListByAccountAsync([FromQuery]RechargeGetListInput input)
{ {
var userId = CurrentUser.Id; 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) .OrderByDescending(x => x.CreationTime)
.ToListAsync(); .ToPageListAsync(input.SkipCount, input.MaxResultCount, total);
var output = entities.Adapt<List<RechargeGetListOutput>>(); var output = entities.Adapt<List<RechargeGetListOutput>>();
return output; return new PagedResultDto<RechargeGetListOutput>(total, output);
} }
/// <summary> /// <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<PremiumPackageAggregateRoot> _premiumPackageRepository;
private readonly ISqlSugarRepository<TokenAggregateRoot> _tokenRepository; private readonly ISqlSugarRepository<TokenAggregateRoot> _tokenRepository;
private readonly ModelManager _modelManager; private readonly ModelManager _modelManager;
public UsageStatisticsService( public UsageStatisticsService(
ISqlSugarRepository<MessageAggregateRoot> messageRepository, ISqlSugarRepository<MessageAggregateRoot> messageRepository,
ISqlSugarRepository<UsageStatisticsAggregateRoot> usageStatisticsRepository, ISqlSugarRepository<UsageStatisticsAggregateRoot> usageStatisticsRepository,
@@ -48,7 +49,7 @@ public class UsageStatisticsService : ApplicationService, IUsageStatisticsServic
/// 获取当前用户近7天的Token消耗统计 /// 获取当前用户近7天的Token消耗统计
/// </summary> /// </summary>
/// <returns>每日Token使用量列表</returns> /// <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 userId = CurrentUser.GetId();
var endDate = DateTime.Today; var endDate = DateTime.Today;
@@ -57,9 +58,9 @@ public class UsageStatisticsService : ApplicationService, IUsageStatisticsServic
// 从Message表统计近7天的token消耗 // 从Message表统计近7天的token消耗
var dailyUsage = await _messageRepository._DbQueryable var dailyUsage = await _messageRepository._DbQueryable
.Where(x => x.UserId == userId) .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)) .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) .GroupBy(x => x.CreationTime.Date)
.Select(g => new .Select(g => new
{ {
@@ -89,14 +90,14 @@ public class UsageStatisticsService : ApplicationService, IUsageStatisticsServic
/// 获取当前用户各个模型的Token消耗量及占比 /// 获取当前用户各个模型的Token消耗量及占比
/// </summary> /// </summary>
/// <returns>模型Token使用量列表</returns> /// <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(); var userId = CurrentUser.GetId();
// 从UsageStatistics表获取各模型的token消耗统计按ModelId聚合因为同一模型可能有多个TokenId的记录 // 从UsageStatistics表获取各模型的token消耗统计按ModelId聚合因为同一模型可能有多个TokenId的记录
var modelUsages = await _usageStatisticsRepository._DbQueryable var modelUsages = await _usageStatisticsRepository._DbQueryable
.Where(x => x.UserId == userId) .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) .GroupBy(x => x.ModelId)
.Select(x => new .Select(x => new
{ {
@@ -221,11 +222,133 @@ public class UsageStatisticsService : ApplicationService, IUsageStatisticsServic
var result = tokenUsages.Select(x => new TokenPremiumUsageDto var result = tokenUsages.Select(x => new TokenPremiumUsageDto
{ {
TokenId = x.TokenId, 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, Tokens = x.TotalTokenCount,
Percentage = totalTokens > 0 ? Math.Round((decimal)x.TotalTokenCount / totalTokens * 100, 2) : 0 Percentage = totalTokens > 0 ? Math.Round((decimal)x.TotalTokenCount / totalTokens * 100, 2) : 0
}).OrderByDescending(x => x.Tokens).ToList(); }).OrderByDescending(x => x.Tokens).ToList();
return result; 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-high",
"gemini-3-pro-image-preview", "gemini-3-pro-image-preview",
"gpt-5.2-codex-xhigh", "gpt-5.2-codex-xhigh",
"gpt-5.2-codex",
"glm-4.7", "glm-4.7",
"yi-claude-sonnet-4-5-20250929", "yi-claude-sonnet-4-5-20250929",
"yi-claude-haiku-4-5-20251001", "yi-claude-haiku-4-5-20251001",
"yi-claude-opus-4-5-20251101", "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 public class AiModelDescribe
{ {
@@ -61,4 +63,14 @@ public class AiModelDescribe
/// 模型倍率 /// 模型倍率
/// </summary> /// </summary>
public decimal Multiplier { get; set; } public decimal Multiplier { get; set; }
/// <summary>
/// 是否为尊享模型
/// </summary>
public bool IsPremium { get; set; }
/// <summary>
/// 模型类型(聊天/图片等)
/// </summary>
public ModelTypeEnum ModelType { get; set; }
} }

View File

@@ -19,38 +19,6 @@ public class AnthropicStreamDto
[JsonPropertyName("error")] public AnthropicStreamErrorDto? Error { 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 public class AnthropicStreamErrorDto
@@ -71,6 +39,11 @@ public class AnthropicChatCompletionDtoDelta
[JsonPropertyName("partial_json")] public string? PartialJson { get; set; } [JsonPropertyName("partial_json")] public string? PartialJson { get; set; }
[JsonPropertyName("stop_reason")] public string? StopReason { 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 public class AnthropicChatCompletionDtoContentBlock
@@ -116,37 +89,6 @@ public class AnthropicChatCompletionDto
public AnthropicCompletionDtoUsage? Usage { 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 public class AnthropicChatCompletionDtoContent
@@ -166,6 +108,7 @@ public class AnthropicChatCompletionDtoContent
[JsonPropertyName("partial_json")] public string? PartialJson { get; set; } [JsonPropertyName("partial_json")] public string? PartialJson { get; set; }
public string? signature { get; set; } public string? signature { get; set; }
} }
public class AnthropicCompletionDtoUsage public class AnthropicCompletionDtoUsage
@@ -181,6 +124,12 @@ public class AnthropicCompletionDtoUsage
[JsonPropertyName("output_tokens")] public int? OutputTokens { get; set; } [JsonPropertyName("output_tokens")] public int? OutputTokens { get; set; }
[JsonPropertyName("server_tool_use")] public AnthropicServerToolUse? ServerToolUse { 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 public class AnthropicServerToolUse

View File

@@ -133,28 +133,5 @@ public class AnthropicMessageTool
[JsonPropertyName("description")] public string? Description { get; set; } [JsonPropertyName("description")] public string? Description { get; set; }
[JsonPropertyName("input_schema")] public Input_schema? InputSchema { get; set; } [JsonPropertyName("input_schema")] public object? InputSchema { get; set; }
}
public class Input_schema
{
[JsonPropertyName("type")] public string? Type { get; set; }
[JsonPropertyName("properties")] public Dictionary<string, InputSchemaValue>? Properties { get; set; }
[JsonPropertyName("required")] public string[]? Required { get; set; }
}
public class InputSchemaValue
{
public string? type { get; set; }
public string? description { get; set; }
public InputSchemaValueItems? items { get; set; }
}
public class InputSchemaValueItems
{
public string? type { get; set; }
} }

View File

@@ -6,6 +6,83 @@ namespace Yi.Framework.AiHub.Domain.Shared.Dtos.Gemini;
public static class GeminiGenerateContentAcquirer 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) public static ThorUsageResponse? GetUsage(JsonElement response)
{ {
var usage = response.GetPath("usageMetadata"); var usage = response.GetPath("usageMetadata");
@@ -20,7 +97,6 @@ public static class GeminiGenerateContentAcquirer
+ usage.Value.GetPath("thoughtsTokenCount").GetInt() + usage.Value.GetPath("thoughtsTokenCount").GetInt()
+ usage.Value.GetPath("toolUsePromptTokenCount").GetInt(); + usage.Value.GetPath("toolUsePromptTokenCount").GetInt();
return new ThorUsageResponse return new ThorUsageResponse
{ {
PromptTokens = inputTokens, PromptTokens = inputTokens,
@@ -32,14 +108,159 @@ public static class GeminiGenerateContentAcquirer
} }
/// <summary> /// <summary>
/// 获取图片url包含前缀 /// 获取图片 base64包含 data:image 前缀
/// Step 1: 递归遍历整个 JSON 查找最后一个 base64
/// Step 2: 从 text 中查找 markdown 图片
/// </summary> /// </summary>
/// <param name="response"></param> public static string GetImagePrefixBase64(JsonElement response)
/// <returns></returns>
public static string GetImageBase64(JsonElement response)
{ {
//todo // Step 1: 递归遍历整个 JSON 查找最后一个 base64
//获取他的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; 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> /// </summary>
[ActivationCodeGoods(price: 0, tokenAmount: 100000, vipMonths: 0, isCombo: false, isReusable: true, [ActivationCodeGoods(price: 0, tokenAmount: 100000, vipMonths: 0, isCombo: false, isReusable: true,
isSameTypeOnce: false, displayName: "10w 尊享Token", content: "免费包")] 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 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)] [Price(83.7, 3, 27.9)] [DisplayName("YiXinVip 3 month", "3个月", "短期体验")] [GoodsCategory(GoodsCategoryType.Vip)]
YiXinVip3 = 3, YiXinVip3 = 3,
[Price(155.4, 6, 25.9)] [DisplayName("YiXinVip 6 month", "6个月", "年度热销")] [GoodsCategory(GoodsCategoryType.Vip)] [Price(91.6, 4, 22.9)] [DisplayName("YiXinVip 4 month", "4个月", "年度热销")] [GoodsCategory(GoodsCategoryType.Vip)]
YiXinVip6 = 6, YiXinVip5 = 14,
// 尊享包服务 - 需要VIP资格才能购买 // 尊享包服务 - 需要VIP资格才能购买
[Price(188.9, 0, 1750)] [Price(188.9, 0, 1750)]
@@ -110,10 +110,23 @@ public enum GoodsTypeEnum
PremiumPackage5000W = 101, PremiumPackage5000W = 101,
[Price(248.9, 0, 3500)] [Price(248.9, 0, 3500)]
[DisplayName("YiXinPremiumPackage 10000W Tokens", "1亿Tokens(推荐)", "极致性价比")] [DisplayName("YiXinPremiumPackage 10000W Tokens", "1亿Tokens", "极致性价比")]
[GoodsCategory(GoodsCategoryType.PremiumPackage)] [GoodsCategory(GoodsCategoryType.PremiumPackage)]
[TokenAmount(100000000)] [TokenAmount(100000000)]
PremiumPackage10000W = 102, 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 public static class GoodsTypeEnumExtensions

View File

@@ -4,15 +4,15 @@ namespace Yi.Framework.AiHub.Domain.Shared.Enums;
public enum ModelApiTypeEnum public enum ModelApiTypeEnum
{ {
[Description("OpenAI")] [Description("OpenAi Completions")]
OpenAi, Completions,
[Description("Claude")] [Description("Claude Messages")]
Claude, Messages,
[Description("Response")] [Description("OpenAi Responses")]
Response, Responses,
[Description("GenerateContent")] [Description("Gemini GenerateContent")]
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 RankingTypeEnum
{
/// <summary>
/// 模型
/// </summary>
Model = 0,
/// <summary>
/// 工具
/// </summary>
Tool = 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,12 +73,18 @@ public class AnthropicChatCompletionsService(
// 大于等于400的状态码都认为是异常 // 大于等于400的状态码都认为是异常
if (response.StatusCode >= HttpStatusCode.BadRequest) if (response.StatusCode >= HttpStatusCode.BadRequest)
{ {
Guid errorId = Guid.NewGuid();
var error = await response.Content.ReadAsStringAsync(cancellationToken).ConfigureAwait(false); 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") || error.Contains("提示词太长")||error.Contains("input tokens exceeds the model's maximum context length"))
{
message += $", tip: 当前提示词过长,上下文已达到上限,如在 claudecode中使用建议执行/compact压缩当前会话或开启新会话后重试";
}
logger.LogError(
$"Anthropic非流式对话异常 请求地址:{options.Endpoint},ErrorId{errorId}, StatusCode: {response.StatusCode.GetHashCode()}, Response: {error}");
throw new Exception(message);
} }
var value = var value =
@@ -109,9 +115,6 @@ public class AnthropicChatCompletionsService(
{ "anthropic-version", "2023-06-01" } { "anthropic-version", "2023-06-01" }
}; };
var isThinking = input.Model.EndsWith("thinking");
input.Model = input.Model.Replace("-thinking", string.Empty);
var response = await client.HttpRequestRaw(options.Endpoint.TrimEnd('/') + "/v1/messages", input, string.Empty, var response = await client.HttpRequestRaw(options.Endpoint.TrimEnd('/') + "/v1/messages", input, string.Empty,
headers); headers);
@@ -121,12 +124,19 @@ public class AnthropicChatCompletionsService(
// 大于等于400的状态码都认为是异常 // 大于等于400的状态码都认为是异常
if (response.StatusCode >= HttpStatusCode.BadRequest) if (response.StatusCode >= HttpStatusCode.BadRequest)
{ {
Guid errorId = Guid.NewGuid();
var error = await response.Content.ReadAsStringAsync(cancellationToken).ConfigureAwait(false); 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("OpenAI对话异常" + response.StatusCode); var message = $"恭喜你运气爆棚遇到了错误尊享包对话异常StatusCode【{response.StatusCode.GetHashCode()}】ErrorId【{errorId}】";
if (error.Contains("prompt is too long") || error.Contains("提示词太长")||error.Contains("input tokens exceeds the model's maximum context length"))
{
message += $", tip: 当前提示词过长,上下文已达到上限,如在 claudecode中使用建议执行/compact压缩当前会话或开启新会话后重试";
}
logger.LogError(
$"Anthropic流式对话异常 请求地址:{options.Endpoint},ErrorId{errorId}, StatusCode: {response.StatusCode.GetHashCode()}, Response: {error}");
throw new Exception(message);
} }
using var stream = new StreamReader(await response.Content.ReadAsStreamAsync(cancellationToken)); using var stream = new StreamReader(await response.Content.ReadAsStreamAsync(cancellationToken));
@@ -164,6 +174,12 @@ public class AnthropicChatCompletionsService(
data = line[OpenAIConstant.Data.Length..].Trim(); data = line[OpenAIConstant.Data.Length..].Trim();
// 处理流结束标记
if (data == "[DONE]")
{
break;
}
var result = JsonSerializer.Deserialize<AnthropicStreamDto>(data, var result = JsonSerializer.Deserialize<AnthropicStreamDto>(data,
ThorJsonSerializer.DefaultOptions); ThorJsonSerializer.DefaultOptions);

View File

@@ -14,10 +14,10 @@ public class ImageStoreTaskAggregateRoot : FullAuditedAggregateRoot<Guid>
public string Prompt { get; set; } public string Prompt { get; set; }
/// <summary> /// <summary>
/// 参考图Base64 /// 参考图PrefixBase64带前缀如 data:image/png;base64,xxx
/// </summary> /// </summary>
[SugarColumn(IsJson = true)] [SugarColumn(IsJson = true, ColumnDataType = StaticConfig.CodeFirst_BigString)]
public List<string> ReferenceImagesBase64 { get; set; } public List<string> ReferenceImagesPrefixBase64 { get; set; }
/// <summary> /// <summary>
/// 参考图url /// 参考图url
@@ -26,11 +26,6 @@ public class ImageStoreTaskAggregateRoot : FullAuditedAggregateRoot<Guid>
public List<string> ReferenceImagesUrl { get; set; } public List<string> ReferenceImagesUrl { get; set; }
/// <summary>
/// 图片base64
/// </summary>
public string? StoreBase64 { get; set; }
/// <summary> /// <summary>
/// 图片绝对路径 /// 图片绝对路径
/// </summary> /// </summary>
@@ -46,6 +41,43 @@ public class ImageStoreTaskAggregateRoot : FullAuditedAggregateRoot<Guid>
/// </summary> /// </summary>
public Guid UserId { get; set; } 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>
/// 设置成功 /// 设置成功
/// </summary> /// </summary>
@@ -55,4 +87,18 @@ public class ImageStoreTaskAggregateRoot : FullAuditedAggregateRoot<Guid>
TaskStatus = TaskStatusEnum.Success; TaskStatus = TaskStatusEnum.Success;
StoreUrl = storeUrl; 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

@@ -53,6 +53,15 @@ public class MessageAggregateRoot : FullAuditedAggregateRoot<Guid>
TotalTokenCount = tokenUsage.TotalTokens ?? 0 TotalTokenCount = tokenUsage.TotalTokens ?? 0
}; };
} }
else
{
this.TokenUsage = new TokenUsageValueObject
{
OutputTokenCount = 0,
InputTokenCount = 0,
TotalTokenCount = 0
};
}
this.MessageType = sessionId is null ? MessageTypeEnum.Api : MessageTypeEnum.Web; this.MessageType = sessionId is null ? MessageTypeEnum.Api : MessageTypeEnum.Web;
} }
@@ -75,4 +84,9 @@ public class MessageAggregateRoot : FullAuditedAggregateRoot<Guid>
[SugarColumn(IsOwnsOne = true)] public TokenUsageValueObject TokenUsage { get; set; } = new TokenUsageValueObject(); [SugarColumn(IsOwnsOne = true)] public TokenUsageValueObject TokenUsage { get; set; } = new TokenUsageValueObject();
public MessageTypeEnum MessageType { get; set; } public MessageTypeEnum MessageType { get; set; }
/// <summary>
/// 是否隐藏(软删除标记,隐藏后不返回给前端)
/// </summary>
public bool IsHidden { get; set; } = false;
} }

View File

@@ -1,5 +1,6 @@
using SqlSugar; using SqlSugar;
using Volo.Abp.Domain.Entities.Auditing; using Volo.Abp.Domain.Entities.Auditing;
using Yi.Framework.AiHub.Domain.Shared.Enums;
namespace Yi.Framework.AiHub.Domain.Entities.Chat; namespace Yi.Framework.AiHub.Domain.Entities.Chat;
@@ -13,4 +14,9 @@ public class SessionAggregateRoot : FullAuditedAggregateRoot<Guid>
[SugarColumn(ColumnDataType = StaticConfig.CodeFirst_BigString)] [SugarColumn(ColumnDataType = StaticConfig.CodeFirst_BigString)]
public string SessionContent { get; set; } public string SessionContent { get; set; }
public string? Remark { 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> /// </summary>
public bool IsPremium { get; set; } public bool IsPremium { get; set; }
/// <summary>
/// 是否启用
/// </summary>
public bool IsEnabled { get; set; } = true;
} }

View File

@@ -0,0 +1,42 @@
using SqlSugar;
using Volo.Abp.Domain.Entities.Auditing;
using Yi.Framework.AiHub.Domain.Shared.Enums;
namespace Yi.Framework.AiHub.Domain.Entities;
/// <summary>
/// 排行榜项聚合根
/// </summary>
[SugarTable("Ai_RankingItem")]
public class RankingItemAggregateRoot : FullAuditedAggregateRoot<Guid>
{
/// <summary>
/// 名称
/// </summary>
public string Name { get; set; }
/// <summary>
/// 描述
/// </summary>
public string? Description { get; set; }
/// <summary>
/// Logo地址
/// </summary>
public string? LogoUrl { get; set; }
/// <summary>
/// 得分
/// </summary>
public decimal Score { get; set; }
/// <summary>
/// 提供者
/// </summary>
public string? Provider { get; set; }
/// <summary>
/// 排行榜类型0-模型1-工具
/// </summary>
public RankingTypeEnum Type { get; set; }
}

View File

@@ -24,11 +24,12 @@ public class AiMessageManager : DomainService
/// <param name="input">消息输入</param> /// <param name="input">消息输入</param>
/// <param name="tokenId">Token IdWeb端传Guid.Empty</param> /// <param name="tokenId">Token IdWeb端传Guid.Empty</param>
/// <returns></returns> /// <returns></returns>
public async Task CreateSystemMessageAsync(Guid? userId, Guid? sessionId, MessageInputDto input, Guid? tokenId = null) public async Task<Guid> CreateSystemMessageAsync(Guid? userId, Guid? sessionId, MessageInputDto input, Guid? tokenId = null)
{ {
input.Role = "system"; input.Role = "system";
var message = new MessageAggregateRoot(userId, sessionId, input.Content, input.Role, input.ModelId, input.TokenUsage, tokenId); var message = new MessageAggregateRoot(userId, sessionId, input.Content, input.Role, input.ModelId, input.TokenUsage, tokenId);
await _repository.InsertAsync(message); await _repository.InsertAsync(message);
return message.Id;
} }
/// <summary> /// <summary>
@@ -38,11 +39,16 @@ public class AiMessageManager : DomainService
/// <param name="sessionId">会话Id</param> /// <param name="sessionId">会话Id</param>
/// <param name="input">消息输入</param> /// <param name="input">消息输入</param>
/// <param name="tokenId">Token IdWeb端传Guid.Empty</param> /// <param name="tokenId">Token IdWeb端传Guid.Empty</param>
/// <param name="createTime"></param>
/// <returns></returns> /// <returns></returns>
public async Task CreateUserMessageAsync(Guid? userId, Guid? sessionId, MessageInputDto input, Guid? tokenId = null) public async Task<Guid> CreateUserMessageAsync( Guid? userId, Guid? sessionId, MessageInputDto input, Guid? tokenId = null,DateTime? createTime=null)
{ {
input.Role = "user"; input.Role = "user";
var message = new MessageAggregateRoot(userId, sessionId, input.Content, input.Role, input.ModelId, input.TokenUsage, tokenId); var message = new MessageAggregateRoot(userId, sessionId, input.Content, input.Role, input.ModelId, input.TokenUsage, tokenId)
{
CreationTime = createTime??DateTime.Now
};
await _repository.InsertAsync(message); await _repository.InsertAsync(message);
return message.Id;
} }
} }

View File

@@ -8,17 +8,15 @@ using Microsoft.AspNetCore.Http;
using Microsoft.Extensions.AI; using Microsoft.Extensions.AI;
using Microsoft.Extensions.DependencyInjection; using Microsoft.Extensions.DependencyInjection;
using Microsoft.Extensions.Logging; using Microsoft.Extensions.Logging;
using ModelContextProtocol.Server;
using OpenAI; using OpenAI;
using OpenAI.Chat; using OpenAI.Chat;
using Volo.Abp.Domain.Services; using Volo.Abp.Domain.Services;
using Volo.Abp.Uow;
using Yi.Framework.AiHub.Application.Contracts.Dtos.Chat; using Yi.Framework.AiHub.Application.Contracts.Dtos.Chat;
using Yi.Framework.AiHub.Domain.AiGateWay; using Yi.Framework.AiHub.Domain.AiGateWay;
using Yi.Framework.AiHub.Domain.Entities.Chat; using Yi.Framework.AiHub.Domain.Entities.Chat;
using Yi.Framework.AiHub.Domain.Entities.Model; 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.Attributes;
using Yi.Framework.AiHub.Domain.Shared.Consts;
using Yi.Framework.AiHub.Domain.Shared.Dtos; using Yi.Framework.AiHub.Domain.Shared.Dtos;
using Yi.Framework.AiHub.Domain.Shared.Dtos.OpenAi; using Yi.Framework.AiHub.Domain.Shared.Dtos.OpenAi;
using Yi.Framework.AiHub.Domain.Shared.Enums; using Yi.Framework.AiHub.Domain.Shared.Enums;
@@ -36,12 +34,14 @@ public class ChatManager : DomainService
private readonly PremiumPackageManager _premiumPackageManager; private readonly PremiumPackageManager _premiumPackageManager;
private readonly AiGateWayManager _aiGateWayManager; private readonly AiGateWayManager _aiGateWayManager;
private readonly ISqlSugarRepository<AiModelEntity, Guid> _aiModelRepository; private readonly ISqlSugarRepository<AiModelEntity, Guid> _aiModelRepository;
private readonly IUnitOfWorkManager _unitOfWorkManager;
public ChatManager(ILoggerFactory loggerFactory, public ChatManager(ILoggerFactory loggerFactory,
ISqlSugarRepository<MessageAggregateRoot> messageRepository, ISqlSugarRepository<MessageAggregateRoot> messageRepository,
ISqlSugarRepository<AgentStoreAggregateRoot> agentStoreRepository, AiMessageManager aiMessageManager, ISqlSugarRepository<AgentStoreAggregateRoot> agentStoreRepository, AiMessageManager aiMessageManager,
UsageStatisticsManager usageStatisticsManager, PremiumPackageManager premiumPackageManager, UsageStatisticsManager usageStatisticsManager, PremiumPackageManager premiumPackageManager,
AiGateWayManager aiGateWayManager, ISqlSugarRepository<AiModelEntity, Guid> aiModelRepository) AiGateWayManager aiGateWayManager, ISqlSugarRepository<AiModelEntity, Guid> aiModelRepository,
IUnitOfWorkManager unitOfWorkManager)
{ {
_loggerFactory = loggerFactory; _loggerFactory = loggerFactory;
_messageRepository = messageRepository; _messageRepository = messageRepository;
@@ -51,6 +51,7 @@ public class ChatManager : DomainService
_premiumPackageManager = premiumPackageManager; _premiumPackageManager = premiumPackageManager;
_aiGateWayManager = aiGateWayManager; _aiGateWayManager = aiGateWayManager;
_aiModelRepository = aiModelRepository; _aiModelRepository = aiModelRepository;
_unitOfWorkManager = unitOfWorkManager;
} }
/// <summary> /// <summary>
@@ -82,7 +83,7 @@ public class ChatManager : DomainService
response.Headers.TryAdd("Cache-Control", "no-cache"); response.Headers.TryAdd("Cache-Control", "no-cache");
response.Headers.TryAdd("Connection", "keep-alive"); response.Headers.TryAdd("Connection", "keep-alive");
var modelDescribe = await _aiGateWayManager.GetModelAsync(ModelApiTypeEnum.OpenAi, modelId); var modelDescribe = await _aiGateWayManager.GetModelAsync(ModelApiTypeEnum.Completions, modelId);
//token状态检查在应用层统一处理 //token状态检查在应用层统一处理
var client = new OpenAIClient(new ApiKeyCredential(token), var client = new OpenAIClient(new ApiKeyCredential(token),
@@ -99,9 +100,11 @@ public class ChatManager : DomainService
ChatOptions = new() ChatOptions = new()
{ {
Instructions = """ Instructions = """
Ai Ai
Ai平台YxaiKnowledgeDirectory和YxaiKnowledge查找意心Ai知识库内容
""" """
}, },
Name = "橙子小弟", Name = "橙子小弟",
@@ -189,53 +192,59 @@ public class ChatManager : DomainService
//用量统计 //用量统计
case UsageContent usageContent: case UsageContent usageContent:
var usage = new ThorUsageResponse //由于MAF线程问题
using (var uow = _unitOfWorkManager.Begin(requiresNew: true))
{ {
InputTokens = Convert.ToInt32(usageContent.Details.InputTokenCount ?? 0), var usage = new ThorUsageResponse
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); 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, await uow.CompleteAsync();
new AgentResultOutput
{ await SendHttpStreamMessageAsync(httpContext,
TypeEnum = update.RawRepresentation is ChatResponseUpdate raw new AgentResultOutput
? raw.FinishReason?.Value == "tool_calls" {
? AgentResultTypeEnum.ToolCallUsage TypeEnum = update.RawRepresentation is ChatResponseUpdate raw
: AgentResultTypeEnum.Usage ? raw.FinishReason?.Value == "tool_calls"
: AgentResultTypeEnum.Usage, ? AgentResultTypeEnum.ToolCallUsage
Content = usage! : AgentResultTypeEnum.Usage
}, : AgentResultTypeEnum.Usage,
isDone: false, cancellationToken); Content = usage!
break; },
isDone: false, cancellationToken);
break;
}
} }
} }
} }
@@ -247,8 +256,13 @@ public class ChatManager : DomainService
string serializedJson = currentThread.Serialize(JsonSerializerOptions.Web).GetRawText(); string serializedJson = currentThread.Serialize(JsonSerializerOptions.Web).GetRawText();
agentStore.Store = serializedJson; agentStore.Store = serializedJson;
//插入或者更新 //由于MAF线程问题
await _agentStoreRepository.InsertOrUpdateAsync(agentStore); 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> /// </summary>
public class ModelManager : DomainService public class ModelManager : DomainService
{ {
private readonly ISqlSugarRepository<AiModelEntity> _aiModelRepository; public readonly ISqlSugarRepository<AiModelEntity> _aiModelRepository;
private readonly IDistributedCache<List<string>, string> _distributedCache; private readonly IDistributedCache<List<string>, string> _distributedCache;
private readonly ILogger<ModelManager> _logger; private readonly ILogger<ModelManager> _logger;
private const string PREMIUM_MODEL_IDS_CACHE_KEY = "PremiumModelIds"; private const string PREMIUM_MODEL_IDS_CACHE_KEY = "PremiumModelIds";
@@ -38,7 +38,7 @@ public class ModelManager : DomainService
{ {
// 从数据库查询 // 从数据库查询
var premiumModelIds = await _aiModelRepository._DbQueryable var premiumModelIds = await _aiModelRepository._DbQueryable
.Where(x => x.IsPremium) .Where(x => x.IsPremium && x.IsEnabled)
.Select(x => x.ModelId) .Select(x => x.ModelId)
.ToListAsync(); .ToListAsync();
return premiumModelIds; return premiumModelIds;

View File

@@ -22,6 +22,11 @@ public class TokenValidationResult
/// Token Id /// Token Id
/// </summary> /// </summary>
public Guid TokenId { get; set; } public Guid TokenId { get; set; }
/// <summary>
/// token
/// </summary>
public string Token { get; set; }
} }
public class TokenManager : DomainService public class TokenManager : DomainService
@@ -43,24 +48,35 @@ public class TokenManager : DomainService
/// <summary> /// <summary>
/// 验证Token并返回用户Id和TokenId /// 验证Token并返回用户Id和TokenId
/// </summary> /// </summary>
/// <param name="token">Token密钥</param> /// <param name="tokenOrId">Token密钥或者TokenId</param>
/// <param name="modelId">模型Id用于判断是否是尊享模型需要检查额度</param> /// <param name="modelId">模型Id用于判断是否是尊享模型需要检查额度</param>
/// <returns>Token验证结果</returns> /// <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"); 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();
}
else
{
var tokenStr = tokenOrId.ToString();
if (!tokenStr.StartsWith("yi-"))
{
throw new UserFriendlyException("当前请求token非法", "401");
}
entity = await _tokenRepository._DbQueryable
.Where(x => x.Token == tokenStr)
.FirstAsync();
} }
var entity = await _tokenRepository._DbQueryable
.Where(x => x.Token == token)
.FirstAsync();
if (entity is null) if (entity is null)
{ {
@@ -100,7 +116,8 @@ public class TokenManager : DomainService
return new TokenValidationResult return new TokenValidationResult
{ {
UserId = entity.UserId, 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; var actualTokenId = tokenId ?? Guid.Empty;
long inputTokenCount = tokenUsage?.PromptTokens long inputTokenCount = tokenUsage?.PromptTokens > 0
?? tokenUsage?.InputTokens ? tokenUsage.PromptTokens.Value
?? 0; : tokenUsage?.InputTokens ?? 0;
long outputTokenCount = tokenUsage?.CompletionTokens long outputTokenCount = tokenUsage?.CompletionTokens > 0
?? tokenUsage?.OutputTokens ? tokenUsage.CompletionTokens.Value
?? 0; : tokenUsage?.OutputTokens ?? 0;
await using (await DistributedLock.AcquireLockAsync($"UsageStatistics:{userId?.ToString()}:{actualTokenId}:{modelId}")) 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

@@ -0,0 +1,143 @@
using System.ComponentModel;
using System.Text;
using System.Text.Json;
using Microsoft.Extensions.Logging;
using Volo.Abp.DependencyInjection;
using Yi.Framework.AiHub.Domain.Shared.Attributes;
namespace Yi.Framework.AiHub.Domain.Mcp;
[YiAgentTool]
public class HttpRequestTool : ISingletonDependency
{
private readonly IHttpClientFactory _httpClientFactory;
private readonly ILogger<HttpRequestTool> _logger;
public HttpRequestTool(
IHttpClientFactory httpClientFactory,
ILogger<HttpRequestTool> logger)
{
_httpClientFactory = httpClientFactory;
_logger = logger;
}
[YiAgentTool("HTTP请求"), DisplayName("HttpRequest"),
Description("发送HTTP请求支持GET/POST/PUT/DELETE等方法获取指定URL的响应内容")]
public async Task<string> HttpRequest(
[Description("请求的URL地址")] string url,
[Description("HTTP方法GET、POST、PUT、DELETE等")] string method = "GET",
[Description("请求体内容JSON字符串POST/PUT时使用")] string? body = null,
[Description("请求头格式key1:value1,key2:value2")] string? headers = null)
{
if (string.IsNullOrWhiteSpace(url))
{
return "URL不能为空";
}
if (string.IsNullOrWhiteSpace(method))
{
method = "GET";
}
try
{
var client = _httpClientFactory.CreateClient();
var request = new HttpRequestMessage(new HttpMethod(method.ToUpper()), url);
// 添加请求体
if (!string.IsNullOrWhiteSpace(body))
{
request.Content = new StringContent(body, Encoding.UTF8, "application/json");
}
// 添加自定义请求头
if (!string.IsNullOrWhiteSpace(headers))
{
AddHeaders(request, headers);
}
var response = await client.SendAsync(request);
return await FormatResponse(response);
}
catch (Exception ex)
{
_logger.LogError(ex, "HTTP {Method}请求失败: {Url}", method, url);
return $"请求失败: {ex.Message}";
}
}
/// <summary>
/// 添加请求头
/// </summary>
private void AddHeaders(HttpRequestMessage request, string headers)
{
var headerPairs = headers.Split(',', StringSplitOptions.RemoveEmptyEntries | StringSplitOptions.TrimEntries);
foreach (var pair in headerPairs)
{
var parts = pair.Split(':', 2, StringSplitOptions.RemoveEmptyEntries | StringSplitOptions.TrimEntries);
if (parts.Length == 2)
{
request.Headers.TryAddWithoutValidation(parts[0], parts[1]);
}
}
}
/// <summary>
/// 格式化响应结果
/// </summary>
private async Task<string> FormatResponse(HttpResponseMessage response)
{
var sb = new StringBuilder();
sb.AppendLine($"状态码: {(int)response.StatusCode} {response.StatusCode}");
sb.AppendLine($"Content-Type: {response.Content.Headers.ContentType?.ToString() ?? ""}");
sb.AppendLine();
var content = await response.Content.ReadAsStringAsync();
if (string.IsNullOrWhiteSpace(content))
{
sb.AppendLine("响应内容为空");
}
else
{
// 尝试格式化JSON
if (IsJsonContentType(response.Content.Headers.ContentType?.MediaType))
{
try
{
var jsonDoc = JsonDocument.Parse(content);
sb.AppendLine("响应内容JSON格式化");
sb.AppendLine(JsonSerializer.Serialize(jsonDoc, new JsonSerializerOptions
{
WriteIndented = true
}));
}
catch
{
sb.AppendLine("响应内容:");
sb.AppendLine(content);
}
}
else
{
sb.AppendLine("响应内容:");
sb.AppendLine(content);
}
}
return sb.ToString();
}
/// <summary>
/// 判断是否为JSON内容类型
/// </summary>
private bool IsJsonContentType(string? contentType)
{
if (string.IsNullOrWhiteSpace(contentType))
{
return false;
}
return contentType.Contains("application/json", StringComparison.OrdinalIgnoreCase) ||
contentType.Contains("text/json", StringComparison.OrdinalIgnoreCase);
}
}

View File

@@ -1,16 +1,244 @@
using System.ComponentModel; 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 Volo.Abp.DependencyInjection;
using Yi.Framework.AiHub.Domain.Shared.Attributes; using Yi.Framework.AiHub.Domain.Shared.Attributes;
namespace Yi.Framework.AiHub.Domain.Mcp; namespace Yi.Framework.AiHub.Domain.Mcp;
[YiAgentTool] [YiAgentTool]
public class OnlineSearchTool:ISingletonDependency public class OnlineSearchTool : ISingletonDependency
{ {
[YiAgentTool("联网搜索"),DisplayName("OnlineSearch"), Description("进行在线搜索")] private readonly IHttpClientFactory _httpClientFactory;
public string OnlineSearch(string keyword) 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,147 @@
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("YxaiKnowledge"),
Description("获取意心AI相关内容的知识库目录及内容列表")]
public async Task<List<YxaiKnowledgeItem>> YxaiKnowledge()
{
try
{
var client = _httpClientFactory.CreateClient();
// 1. 先获取目录列表
var directoryResponse = await client.GetAsync(DirectoryUrl);
if (!directoryResponse.IsSuccessStatusCode)
{
_logger.LogError("意心知识库目录接口调用失败: {StatusCode}", directoryResponse.StatusCode);
return new List<YxaiKnowledgeItem>();
}
var directoryJson = await directoryResponse.Content.ReadAsStringAsync();
var directories = JsonSerializer.Deserialize(directoryJson,
YxaiKnowledgeJsonContext.Default.ListYxaiKnowledgeDirectoryItem);
if (directories == null || directories.Count == 0)
{
return new List<YxaiKnowledgeItem>();
}
// 2. 循环调用内容接口获取每个目录的内容
var result = new List<YxaiKnowledgeItem>();
foreach (var directory in directories)
{
try
{
var contentUrl = string.Format(ContentUrlTemplate, directory.Id);
var contentResponse = await client.GetAsync(contentUrl);
if (contentResponse.IsSuccessStatusCode)
{
var contentJson = await contentResponse.Content.ReadAsStringAsync();
var contentResult = JsonSerializer.Deserialize(contentJson,
YxaiKnowledgeJsonContext.Default.YxaiKnowledgeContentResponse);
result.Add(new YxaiKnowledgeItem
{
Name = directory.Name,
Content = contentResult?.Content ?? ""
});
}
else
{
_logger.LogWarning("获取知识库内容失败: {StatusCode}, DirectoryId: {DirectoryId}",
contentResponse.StatusCode, directory.Id);
result.Add(new YxaiKnowledgeItem
{
Name = directory.Name,
Content = $"获取内容失败: {contentResponse.StatusCode}"
});
}
}
catch (Exception ex)
{
_logger.LogError(ex, "获取知识库内容发生异常, DirectoryId: {DirectoryId}", directory.Id);
result.Add(new YxaiKnowledgeItem
{
Name = directory.Name,
Content = "获取内容发生异常"
});
}
}
return result;
}
catch (Exception ex)
{
_logger.LogError(ex, "获取意心知识库发生异常");
return new List<YxaiKnowledgeItem>();
}
}
}
#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; }
}
/// <summary>
/// 合并后的知识库项,包含目录和内容
/// </summary>
public class YxaiKnowledgeItem
{
/// <summary>
/// 目录名称
/// </summary>
public string Name { get; set; } = "";
/// <summary>
/// 知识库内容
/// </summary>
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"> <Project Sdk="Microsoft.NET.Sdk">
<Import Project="..\..\..\common.props" /> <Import Project="..\..\..\common.props" />
<ItemGroup> <ItemGroup>
<PackageReference Include="OpenAI" Version="2.8.0" />
<PackageReference Include="Volo.Abp.Ddd.Domain" Version="$(AbpVersion)" /> <PackageReference Include="Volo.Abp.Ddd.Domain" Version="$(AbpVersion)" />
<PackageReference Include="Volo.Abp.Caching" Version="$(AbpVersion)" /> <PackageReference Include="Volo.Abp.Caching" Version="$(AbpVersion)" />
<PackageReference Include="Microsoft.SemanticKernel" Version="1.57.0" /> <PackageReference Include="Microsoft.SemanticKernel" Version="1.57.0" />

View File

@@ -7,6 +7,7 @@
</ItemGroup> </ItemGroup>
<ItemGroup> <ItemGroup>
<PackageReference Include="OpenAI" Version="2.8.0" />
<PackageReference Include="Volo.Abp.AspNetCore.SignalR" Version="$(AbpVersion)" /> <PackageReference Include="Volo.Abp.AspNetCore.SignalR" Version="$(AbpVersion)" />
<PackageReference Include="Volo.Abp.Ddd.Domain" Version="$(AbpVersion)" /> <PackageReference Include="Volo.Abp.Ddd.Domain" Version="$(AbpVersion)" />
<PackageReference Include="Volo.Abp.Caching" 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)) if (UserConst.Admin.Equals(dto.User.UserName))
{ {
AddToClaim(claims, TokenTypeConst.Permission, UserConst.AdminPermissionCode); AddToClaim(claims, TokenTypeConst.Permission, UserConst.AdminPermissionCode);
AddToClaim(claims, TokenTypeConst.Roles, UserConst.AdminRolesCode); AddToClaim(claims, ClaimTypes.Role, UserConst.AdminRolesCode);
} }
else else
{ {

View File

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

View File

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

View File

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

View File

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

View File

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

View File

@@ -4,6 +4,7 @@ using Serilog.Events;
using Yi.Abp.Web; using Yi.Abp.Web;
//创建日志,可使用{SourceContext}记录 //创建日志,可使用{SourceContext}记录
var outputTemplate = "{Timestamp:yyyy-MM-dd HH:mm:ss.fff zzz}【{SourceContext}】[{Level:u3}]{Message:lj}{NewLine}{Exception}";
Log.Logger = new LoggerConfiguration() Log.Logger = new LoggerConfiguration()
//由于后端处理请求中,前端请求已经结束,此类日志可不记录 //由于后端处理请求中,前端请求已经结束,此类日志可不记录
.Filter.ByExcluding(log =>log.Exception?.GetType() == typeof(TaskCanceledException)||log.MessageTemplate.Text.Contains("\"message\": \"A task was canceled.\"")) .Filter.ByExcluding(log =>log.Exception?.GetType() == typeof(TaskCanceledException)||log.MessageTemplate.Text.Contains("\"message\": \"A task was canceled.\""))
@@ -11,10 +12,15 @@ Log.Logger = new LoggerConfiguration()
.MinimumLevel.Override("Microsoft", LogEventLevel.Information) .MinimumLevel.Override("Microsoft", LogEventLevel.Information)
.MinimumLevel.Override("Microsoft.AspNetCore.Hosting.Diagnostics", LogEventLevel.Error) .MinimumLevel.Override("Microsoft.AspNetCore.Hosting.Diagnostics", LogEventLevel.Error)
.MinimumLevel.Override("Quartz", LogEventLevel.Warning) .MinimumLevel.Override("Quartz", LogEventLevel.Warning)
.MinimumLevel.Override("Microsoft.AspNetCore.Authentication.JwtBearer.JwtBearerHandler", LogEventLevel.Warning)
.MinimumLevel.Override("Microsoft.AspNetCore.Cors.Infrastructure.CorsService", LogEventLevel.Warning)
.MinimumLevel.Override("Microsoft.AspNetCore.Authorization.DefaultAuthorizationService", LogEventLevel.Warning)
.MinimumLevel.Override("Microsoft.AspNetCore.Routing.EndpointMiddleware", LogEventLevel.Warning)
.MinimumLevel.Override("Hangfire.Server.ServerHeartbeatProcess", LogEventLevel.Warning)
.Enrich.FromLogContext() .Enrich.FromLogContext()
.WriteTo.Async(c => c.File("logs/all/log-.txt", rollingInterval: RollingInterval.Day, restrictedToMinimumLevel: LogEventLevel.Debug)) .WriteTo.Async(c => c.File("logs/all/log-.txt", rollingInterval: RollingInterval.Day, restrictedToMinimumLevel: LogEventLevel.Debug,outputTemplate:outputTemplate))
.WriteTo.Async(c => c.File("logs/error/errorlog-.txt", rollingInterval: RollingInterval.Day, restrictedToMinimumLevel: LogEventLevel.Error)) .WriteTo.Async(c => c.File("logs/error/errorlog-.txt", rollingInterval: RollingInterval.Day, restrictedToMinimumLevel: LogEventLevel.Error,outputTemplate:outputTemplate))
.WriteTo.Async(c => c.Console()) .WriteTo.Async(c => c.Console(outputTemplate:outputTemplate))
.CreateLogger(); .CreateLogger();
try try

View File

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

View File

@@ -0,0 +1,23 @@
import type { Plugin } from 'vite';
import { config, library } from '@fortawesome/fontawesome-svg-core';
import { fas } from '@fortawesome/free-solid-svg-icons';
/**
* Vite 插件:配置 FontAwesome
* 预注册所有图标,避免运行时重复注册
*/
export default function fontAwesomePlugin(): Plugin {
// 在模块加载时配置 FontAwesome
library.add(fas);
return {
name: 'vite-plugin-fontawesome',
config() {
return {
define: {
// 确保 FontAwesome 在客户端正确初始化
},
};
},
};
}

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,13 +10,21 @@ import Components from 'unplugin-vue-components/vite';
import viteCompression from 'vite-plugin-compression'; import viteCompression from 'vite-plugin-compression';
import envTyped from 'vite-plugin-env-typed'; import envTyped from 'vite-plugin-env-typed';
import fontAwesomePlugin from './fontawesome';
import gitHashPlugin from './git-hash';
import preloadPlugin from './preload';
import createSvgIcon from './svg-icon'; import createSvgIcon from './svg-icon';
import versionHtmlPlugin from './version-html';
const root = path.resolve(__dirname, '../../'); const root = path.resolve(__dirname, '../../');
function plugins({ mode, command }: ConfigEnv): PluginOption[] { function plugins({ mode, command }: ConfigEnv): PluginOption[] {
return [ return [
versionHtmlPlugin(), // 最先处理 HTML 版本号
gitHashPlugin(),
preloadPlugin(),
UnoCSS(), UnoCSS(),
fontAwesomePlugin(),
envTyped({ envTyped({
mode, mode,
envDir: root, envDir: root,
@@ -33,7 +41,18 @@ function plugins({ mode, command }: ConfigEnv): PluginOption[] {
dts: path.join(root, 'types', 'auto-imports.d.ts'), dts: path.join(root, 'types', 'auto-imports.d.ts'),
}), }),
Components({ Components({
resolvers: [ElementPlusResolver()], resolvers: [
ElementPlusResolver(),
// 自动导入 FontAwesomeIcon 组件
(componentName) => {
if (componentName === 'FontAwesomeIcon') {
return {
name: 'FontAwesomeIcon',
from: '@/components/FontAwesomeIcon/index.vue',
};
}
},
],
dts: path.join(root, 'types', 'components.d.ts'), dts: path.join(root, 'types', 'components.d.ts'),
}), }),
createSvgIcon(command === 'build'), createSvgIcon(command === 'build'),

View File

@@ -0,0 +1,47 @@
import type { Plugin } from 'vite';
/**
* Vite 插件:资源预加载优化
* 自动添加 Link 标签预加载关键资源
*/
export default function preloadPlugin(): Plugin {
return {
name: 'vite-plugin-preload-optimization',
apply: 'build',
transformIndexHtml(html, context) {
// 只在生产环境添加预加载
if (process.env.NODE_ENV === 'development') {
return html;
}
const bundle = context.bundle || {};
const preloadLinks: string[] = [];
// 收集关键资源
const criticalChunks = ['vue-vendor', 'element-plus', 'pinia'];
const criticalAssets: string[] = [];
Object.entries(bundle).forEach(([fileName, chunk]) => {
if (chunk.type === 'chunk' && criticalChunks.some(name => fileName.includes(name))) {
criticalAssets.push(`/${fileName}`);
}
});
// 生成预加载标签
criticalAssets.forEach(href => {
if (href.endsWith('.js')) {
preloadLinks.push(`<link rel="modulepreload" href="${href}" crossorigin>`);
} else if (href.endsWith('.css')) {
preloadLinks.push(`<link rel="preload" href="${href}" as="style">`);
}
});
// 将预加载标签插入到 </head> 之前
if (preloadLinks.length > 0) {
return html.replace('</head>', `${preloadLinks.join('\n ')}\n</head>`);
}
return html;
},
};
}

View File

@@ -0,0 +1,20 @@
import type { Plugin } from 'vite';
import { APP_VERSION, APP_NAME } from '../../src/config/version';
/**
* Vite 插件:在 HTML 中注入版本号
* 替换 HTML 中的占位符为实际版本号
*/
export default function versionHtmlPlugin(): Plugin {
return {
name: 'vite-plugin-version-html',
enforce: 'pre',
transformIndexHtml(html) {
// 替换 HTML 中的版本占位符
return html
.replace(/%APP_NAME%/g, APP_NAME)
.replace(/%APP_VERSION%/g, APP_VERSION)
.replace(/%APP_FULL_NAME%/g, `${APP_NAME} ${APP_VERSION}`);
},
};
}

View File

@@ -3,7 +3,14 @@
"allow": [ "allow": [
"Bash(npx vue-tsc --noEmit)", "Bash(npx vue-tsc --noEmit)",
"Bash(timeout 60 npx vue-tsc:*)", "Bash(timeout 60 npx vue-tsc:*)",
"Bash(npm run dev:*)" "Bash(npm run dev:*)",
"Bash(taskkill:*)",
"Bash(timeout /t 5 /nobreak)",
"Bash(git checkout:*)",
"Bash(npm install marked --save)",
"Bash(pnpm add marked)",
"Bash(pnpm lint:*)",
"Bash(pnpm list:*)"
], ],
"deny": [], "deny": [],
"ask": [] "ask": []

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