mirror of
https://gitee.com/ccnetcore/Yi
synced 2026-03-03 00:00:58 +08:00
Compare commits
199 Commits
| Author | SHA1 | Date | |
|---|---|---|---|
|
|
bb894e14a4 | ||
|
|
b492d82442 | ||
|
|
5eaffe2ec2 | ||
|
|
d7bcad9da7 | ||
|
|
04e11d15e2 | ||
|
|
97e3dc5eed | ||
|
|
695bd56a27 | ||
|
|
7919383be3 | ||
|
|
d6cc3c5d96 | ||
|
|
19f0d05a69 | ||
|
|
3c5e575e9b | ||
|
|
f875617de1 | ||
|
|
9976e8a6e2 | ||
|
|
38e8cbc5ca | ||
|
|
d95c14c903 | ||
|
|
ffb2f2fb4c | ||
|
|
4bd2fc357d | ||
|
|
da23d17af8 | ||
|
|
c1a6046107 | ||
|
|
2ec7b5f4fd | ||
|
|
d21f61646a | ||
|
|
eecdf442fb | ||
|
|
1b4c3cbb8d | ||
|
|
b7756e2112 | ||
|
|
cb49059e84 | ||
|
|
690cabfd96 | ||
|
|
4521212a90 | ||
|
|
771ecd9d81 | ||
|
|
94834f45c3 | ||
|
|
a9b2979a21 | ||
|
|
22ac150acd | ||
|
|
17337b8d78 | ||
|
|
09fb43ee14 | ||
|
|
477c0e3f2c | ||
|
|
2e4f520dac | ||
|
|
067b25b9af | ||
|
|
36370c215d | ||
|
|
e24731acfe | ||
|
|
927e9df7de | ||
|
|
114b41144e | ||
|
|
5019a36138 | ||
|
|
e15eb6149b | ||
|
|
9d401a9c93 | ||
|
|
eacf86e118 | ||
|
|
c4b631c815 | ||
|
|
fb25e75a3a | ||
|
|
e9099bbe04 | ||
|
|
f02fb91175 | ||
|
|
5beef22269 | ||
|
|
933cbb91d8 | ||
|
|
efd917d184 | ||
|
|
e906208f4a | ||
|
|
cf137f6307 | ||
|
|
e6b991fe86 | ||
|
|
3e75792e43 | ||
|
|
dd3f6325bb | ||
|
|
108ba348f6 | ||
|
|
bcdcec40e0 | ||
|
|
2ce8baea42 | ||
|
|
c6425ca206 | ||
|
|
acb359ec33 | ||
|
|
a1395d9a33 | ||
|
|
609de29e71 | ||
|
|
2efed4f4a5 | ||
|
|
aec90ec9d6 | ||
|
|
1aaff2942d | ||
|
|
cdbfc5383d | ||
|
|
f302555e0c | ||
|
|
86c5890476 | ||
|
|
a13ee395c7 | ||
|
|
9abcd72aca | ||
|
|
4ddea6d468 | ||
|
|
867a2dc861 | ||
|
|
4a72e3fa0d | ||
|
|
8b4371aabb | ||
|
|
799dd08ec0 | ||
|
|
c5c22224cf | ||
|
|
2dae47e85c | ||
|
|
375dd4f797 | ||
|
|
acb2db8397 | ||
|
|
b7a3e76d0b | ||
|
|
48150b712a | ||
|
|
6db9dfc308 | ||
|
|
2d6c1f3c46 | ||
|
|
161e10d2d1 | ||
|
|
a9a2a91183 | ||
|
|
1c9a6f108e | ||
|
|
d6adf9b736 | ||
|
|
959eb3f782 | ||
|
|
7a53e0c90c | ||
|
|
533b87fc5b | ||
|
|
15713cf7fe | ||
|
|
31dc756868 | ||
|
|
52f6b6130f | ||
|
|
16945b3d5b | ||
|
|
bdc664fc44 | ||
|
|
9555ef10e0 | ||
|
|
49e6cb26fc | ||
|
|
3ace29e692 | ||
|
|
aa9dd0129b | ||
|
|
1464271fbd | ||
|
|
754f145559 | ||
|
|
6afd0cb955 | ||
|
|
d32906702a | ||
|
|
9bcdaf6bd8 | ||
|
|
db82a8cf08 | ||
|
|
a9e8b2b01f | ||
|
|
85bd1ce8d6 | ||
|
|
4d09243efd | ||
|
|
5934056fe6 | ||
|
|
2a81062fa3 | ||
|
|
fdc868323f | ||
|
|
593b3a4cdd | ||
|
|
2b12e18e6c | ||
|
|
345ed80ec8 | ||
|
|
29dc1ae250 | ||
|
|
9fdd41b134 | ||
|
|
31ee5e8ffb | ||
|
|
d7922bb71d | ||
|
|
1cc5f2a14f | ||
|
|
d9997eeb28 | ||
|
|
06e77aa8fd | ||
|
|
e9e2228f6e | ||
|
|
d516a381d0 | ||
|
|
4e792ba976 | ||
|
|
fa3ac91ba4 | ||
|
|
f90d3871fa | ||
|
|
e7c152e955 | ||
|
|
0223b5c104 | ||
|
|
9e41a7c446 | ||
|
|
2ba0ffc1b7 | ||
|
|
7d038e1266 | ||
|
|
b98285f314 | ||
|
|
73438da666 | ||
|
|
85f2e1b579 | ||
|
|
ece89ebad0 | ||
|
|
6e2dd39246 | ||
|
|
a61286e534 | ||
|
|
4f944a5466 | ||
|
|
d29aac088a | ||
|
|
8abd122773 | ||
|
|
08084aa0bc | ||
|
|
e69cd5a73c | ||
|
|
76aa3bdc64 | ||
|
|
93251104af | ||
|
|
3cae477f3e | ||
|
|
25c736dc0a | ||
|
|
96a09d8980 | ||
|
|
72387235a0 | ||
|
|
1b00e505b7 | ||
|
|
1c54e47b9e | ||
|
|
ba07e2c905 | ||
|
|
bde4611a50 | ||
|
|
e7326fea7b | ||
|
|
d13b23ad2e | ||
|
|
8b1830a711 | ||
|
|
b70c530754 | ||
|
|
d90e24f9ed | ||
|
|
1fbd521d1a | ||
|
|
2ae6183e7f | ||
|
|
7905911624 | ||
|
|
c5b6b33d8e | ||
|
|
5d29fd6d3b | ||
|
|
ad8f48f36b | ||
|
|
f9843c13d4 | ||
|
|
6bd561b094 | ||
|
|
d2c6238df1 | ||
|
|
1d108983e8 | ||
|
|
b768bca638 | ||
|
|
28fcd6c9ce | ||
|
|
6005b9329d | ||
|
|
10559a925c | ||
|
|
942e218a9e | ||
|
|
f6af9edc38 | ||
|
|
e0f6331ec3 | ||
|
|
06f0c6caa7 | ||
|
|
56ec260e3a | ||
|
|
176cf84369 | ||
|
|
6de3b722ed | ||
|
|
2cf6326764 | ||
|
|
ec27ee58b4 | ||
|
|
4e42e2202e | ||
|
|
e60d8eceb7 | ||
|
|
08fb939b38 | ||
|
|
482dd73afd | ||
|
|
f09a9fee75 | ||
|
|
9a31d14b41 | ||
|
|
2fd7f88f04 | ||
|
|
9d4cc802e9 | ||
|
|
ee6b4827fa | ||
|
|
48d8c528f6 | ||
|
|
40c0a5ac64 | ||
|
|
9d4b3e7d0c | ||
|
|
72795382a1 | ||
|
|
35cdff2afa | ||
|
|
dcf547f513 | ||
|
|
8660d45f36 | ||
|
|
63dd55e7a4 | ||
|
|
40cd89f90c |
1
.gitignore
vendored
1
.gitignore
vendored
@@ -265,6 +265,7 @@ src/Acme.BookStore.Blazor.Server.Tiered/Logs/*
|
||||
**/wwwroot/libs/*
|
||||
public
|
||||
dist
|
||||
dist - 副本
|
||||
.vscode
|
||||
/Yi.Abp.Net8/src/Yi.Abp.Web/appsettings.Development.json
|
||||
/Yi.Abp.Net8/src/Yi.Abp.Web/appsettings.Production.json
|
||||
|
||||
10
README.md
10
README.md
@@ -7,6 +7,12 @@
|
||||
[](https://gitee.com/ccnetcore/Yi)
|
||||
[](https://gitee.com/ccnetcore/Yi)
|
||||
|
||||
本项目 CDN 加速及安全防护由 Tencent EdgeOne 赞助
|
||||
|
||||
[亚洲最佳CDN、边缘和安全解决方案 - Tencent EdgeOne](https://edgeone.ai/zh?from=github)
|
||||
|
||||
<img src="readme/edgeone.png"/>
|
||||
|
||||
[English](README-en.md) | 简体中文
|
||||
****
|
||||
## 🍍 简介:
|
||||
@@ -60,9 +66,9 @@ bbs前端:`docker run -d --name yi.bbs -p 18001:18001 -v /home/Yi/Yi.Bbs.Vue3/
|
||||
|
||||
Yi社区官网网址(Bbs社区正式):[ccnetcore.com](https://ccnetcore.com) (已上线,欢迎加入)
|
||||
|
||||
Rbac后台演示地址:https://ccnetcore.com:1000 (用户cc、密码123456)
|
||||
Rbac后台演示地址:https://data.ccnetcore.com:1000 (用户cc、密码123456)
|
||||
|
||||
Pure后台演示地址:https://ccnetcore.com:1001 (用户cc、密码123456)
|
||||
Pure后台演示地址:https://data.ccnetcore.com:1001 (用户cc、密码123456)
|
||||
|
||||
## 🍏 支持:
|
||||
|
||||
|
||||
10
Yi.Abp.Net8/.claude/settings.local.json
Normal file
10
Yi.Abp.Net8/.claude/settings.local.json
Normal file
@@ -0,0 +1,10 @@
|
||||
{
|
||||
"permissions": {
|
||||
"allow": [
|
||||
"Bash(dotnet build \"E:\\code\\github\\Yi\\Yi.Abp.Net8\\module\\ai-hub\\Yi.Framework.AiHub.Application\\Yi.Framework.AiHub.Application.csproj\" --no-restore)",
|
||||
"Read(//e/code/github/Yi/Yi.Ai.Vue3/**)"
|
||||
],
|
||||
"deny": [],
|
||||
"ask": []
|
||||
}
|
||||
}
|
||||
@@ -1,4 +1,4 @@
|
||||
// MIT 许可证
|
||||
// MIT 许可证
|
||||
//
|
||||
// 版权 © 2020-present 百小僧, 百签科技(广东)有限公司 和所有贡献者
|
||||
//
|
||||
@@ -17,25 +17,25 @@ using Microsoft.AspNetCore.Mvc;
|
||||
using Microsoft.AspNetCore.Mvc.Filters;
|
||||
using Microsoft.Extensions.DependencyInjection;
|
||||
using Microsoft.Extensions.Logging;
|
||||
using Newtonsoft.Json;
|
||||
using Volo.Abp.AspNetCore.Mvc;
|
||||
using Volo.Abp.DependencyInjection;
|
||||
using Volo.Abp.Validation;
|
||||
using Yi.Framework.Core.Extensions;
|
||||
|
||||
namespace Yi.Framework.AspNetCore.UnifyResult.Fiters;
|
||||
|
||||
/// <summary>
|
||||
/// 友好异常拦截器
|
||||
/// 友好异常拦截器
|
||||
/// </summary>
|
||||
public sealed class FriendlyExceptionFilter : IAsyncExceptionFilter
|
||||
{
|
||||
/// <summary>
|
||||
/// 异常拦截
|
||||
/// 异常拦截
|
||||
/// </summary>
|
||||
/// <param name="context"></param>
|
||||
/// <returns></returns>
|
||||
public async Task OnExceptionAsync(ExceptionContext context)
|
||||
{
|
||||
|
||||
// 排除 WebSocket 请求处理
|
||||
if (context.HttpContext.IsWebSocketRequest()) return;
|
||||
|
||||
@@ -44,20 +44,23 @@ public sealed class FriendlyExceptionFilter : IAsyncExceptionFilter
|
||||
|
||||
// 解析异常信息
|
||||
var exceptionMetadata = GetExceptionMetadata(context);
|
||||
|
||||
IUnifyResultProvider unifyResult = context.GetRequiredService<IUnifyResultProvider>();
|
||||
var unifyResult = context.GetRequiredService<IUnifyResultProvider>();
|
||||
// 执行规范化异常处理
|
||||
context.Result = unifyResult.OnException(context, exceptionMetadata);
|
||||
|
||||
// 创建日志记录器
|
||||
var logger = context.HttpContext.RequestServices.GetRequiredService<ILogger<FriendlyExceptionFilter>>();
|
||||
|
||||
var errorMsg = "";
|
||||
if (exceptionMetadata.Errors != null) errorMsg = "\n" + JsonConvert.SerializeObject(exceptionMetadata.Errors);
|
||||
|
||||
|
||||
// 记录拦截日常
|
||||
logger.LogError(context.Exception, context.Exception.Message);
|
||||
logger.LogError(context.Exception, context.Exception.Message + errorMsg);
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// 获取异常元数据
|
||||
/// 获取异常元数据
|
||||
/// </summary>
|
||||
/// <param name="context"></param>
|
||||
/// <returns></returns>
|
||||
@@ -74,22 +77,25 @@ public sealed class FriendlyExceptionFilter : IAsyncExceptionFilter
|
||||
// 判断是否是 ExceptionContext 或者 ActionExecutedContext
|
||||
var exception = context is ExceptionContext exContext
|
||||
? exContext.Exception
|
||||
: (
|
||||
context is ActionExecutedContext edContext
|
||||
? edContext.Exception
|
||||
: default
|
||||
);
|
||||
: context is ActionExecutedContext edContext
|
||||
? edContext.Exception
|
||||
: default;
|
||||
|
||||
if (exception is AbpValidationException validationException)
|
||||
{
|
||||
errors = validationException.ValidationErrors;
|
||||
isValidationException = true;
|
||||
}
|
||||
|
||||
// 判断是否是友好异常
|
||||
if (exception is UserFriendlyException friendlyException)
|
||||
{
|
||||
int statusCode2 = 500;
|
||||
var statusCode2 = 500;
|
||||
int.TryParse(friendlyException.Code, out statusCode2);
|
||||
isFriendlyException = true;
|
||||
errorCode = friendlyException.Code;
|
||||
originErrorCode = friendlyException.Code;
|
||||
statusCode = statusCode2==0?403:statusCode2;
|
||||
isValidationException = false;
|
||||
statusCode = statusCode2 == 0 ? 403 : statusCode2;
|
||||
errors = friendlyException.Message;
|
||||
data = friendlyException.Data;
|
||||
}
|
||||
|
||||
@@ -2,6 +2,7 @@
|
||||
using Microsoft.Extensions.DependencyInjection;
|
||||
using Swashbuckle.AspNetCore.SwaggerGen;
|
||||
using Volo.Abp.AspNetCore.Mvc.ExceptionHandling;
|
||||
using Volo.Abp.AspNetCore.Mvc.Response;
|
||||
using Yi.Framework.AspNetCore.UnifyResult.Fiters;
|
||||
|
||||
namespace Yi.Framework.AspNetCore.UnifyResult;
|
||||
@@ -20,9 +21,10 @@ public static class UnifyResultExtensions
|
||||
services.AddTransient<FriendlyExceptionFilter>();
|
||||
services.AddMvc(options =>
|
||||
{
|
||||
options.Filters.RemoveAll(x => (x as ServiceFilterAttribute)?.ServiceType == typeof(AbpExceptionFilter));
|
||||
options.Filters.RemoveAll(x => (x as ServiceFilterAttribute)?.ServiceType == typeof(AbpNoContentActionFilter));
|
||||
options.Filters.AddService<SucceededUnifyResultFilter>(99);
|
||||
options.Filters.AddService<FriendlyExceptionFilter>(100);
|
||||
options.Filters.RemoveAll(x => (x as ServiceFilterAttribute)?.ServiceType == typeof(AbpExceptionFilter));
|
||||
});
|
||||
return services;
|
||||
}
|
||||
|
||||
@@ -199,11 +199,11 @@ namespace Yi.Framework.Ddd.Application
|
||||
/// <summary>
|
||||
/// 批量删除实体
|
||||
/// </summary>
|
||||
/// <param name="ids">实体ID集合</param>
|
||||
/// <param name="id">实体ID集合</param>
|
||||
[RemoteService(isEnabled: true)]
|
||||
public virtual async Task DeleteAsync(IEnumerable<TKey> ids)
|
||||
public virtual async Task DeleteAsync(IEnumerable<TKey> id)
|
||||
{
|
||||
await Repository.DeleteManyAsync(ids);
|
||||
await Repository.DeleteManyAsync(id);
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
|
||||
@@ -1,7 +1,8 @@
|
||||
using Microsoft.Extensions.DependencyInjection;
|
||||
using Microsoft.Extensions.DependencyInjection;
|
||||
using Volo.Abp.Modularity;
|
||||
using Volo.Abp.ObjectMapping;
|
||||
using Yi.Framework.Core;
|
||||
using Mapster;
|
||||
|
||||
namespace Yi.Framework.Mapster
|
||||
{
|
||||
@@ -22,7 +23,8 @@ namespace Yi.Framework.Mapster
|
||||
public override void ConfigureServices(ServiceConfigurationContext context)
|
||||
{
|
||||
var services = context.Services;
|
||||
|
||||
// 扫描并注册所有映射配置
|
||||
TypeAdapterConfig.GlobalSettings.Scan(AppDomain.CurrentDomain.GetAssemblies());
|
||||
// 注册Mapster相关服务
|
||||
services.AddTransient<IAutoObjectMappingProvider, MapsterAutoObjectMappingProvider>();
|
||||
services.AddTransient<IObjectMapper, MapsterObjectMapper>();
|
||||
|
||||
@@ -60,8 +60,8 @@ namespace Yi.Framework.SqlSugarCore.Abstractions
|
||||
public bool EnabledSaasMultiTenancy { get; set; } = false;
|
||||
|
||||
/// <summary>
|
||||
/// 并发乐观锁异常,否则不处理
|
||||
/// 是否开启更新并发乐观锁
|
||||
/// </summary>
|
||||
public bool EnabledConcurrencyException { get; set; } = true;
|
||||
public bool EnabledConcurrencyException { get;set; } = false;
|
||||
}
|
||||
}
|
||||
@@ -1,12 +1,7 @@
|
||||
using System.Linq;
|
||||
using System.Linq.Expressions;
|
||||
using System.Text;
|
||||
using Microsoft.Extensions.Logging;
|
||||
using Microsoft.Extensions.Options;
|
||||
using Nito.AsyncEx;
|
||||
using SqlSugar;
|
||||
using Volo.Abp;
|
||||
using Volo.Abp.Auditing;
|
||||
using Volo.Abp.Data;
|
||||
using Volo.Abp.DependencyInjection;
|
||||
using Volo.Abp.Domain.Entities;
|
||||
@@ -17,8 +12,7 @@ using Yi.Framework.SqlSugarCore.Abstractions;
|
||||
|
||||
namespace Yi.Framework.SqlSugarCore.Repositories
|
||||
{
|
||||
public class SqlSugarRepository<TEntity> : ISqlSugarRepository<TEntity>, IRepository<TEntity>
|
||||
where TEntity : class, IEntity, new()
|
||||
public class SqlSugarRepository<TEntity> : ISqlSugarRepository<TEntity>, IRepository<TEntity> where TEntity : class, IEntity, new()
|
||||
{
|
||||
public ISqlSugarClient _Db => AsyncContext.Run(async () => await GetDbContextAsync());
|
||||
|
||||
@@ -27,8 +21,8 @@ namespace Yi.Framework.SqlSugarCore.Repositories
|
||||
private readonly ISugarDbContextProvider<ISqlSugarDbContext> _dbContextProvider;
|
||||
|
||||
public IAbpLazyServiceProvider LazyServiceProvider { get; set; }
|
||||
protected DbConnOptions? Options => LazyServiceProvider?.LazyGetService<IOptions<DbConnOptions>>().Value;
|
||||
|
||||
protected DbConnOptions? Options => LazyServiceProvider?.LazyGetService<IOptions<DbConnOptions>>().Value;
|
||||
/// <summary>
|
||||
/// 异步查询执行器
|
||||
/// </summary>
|
||||
@@ -64,26 +58,22 @@ namespace Yi.Framework.SqlSugarCore.Repositories
|
||||
|
||||
#region Abp模块
|
||||
|
||||
public virtual async Task<TEntity?> FindAsync(Expression<Func<TEntity, bool>> predicate,
|
||||
bool includeDetails = true, CancellationToken cancellationToken = default)
|
||||
public virtual async Task<TEntity?> FindAsync(Expression<Func<TEntity, bool>> predicate, bool includeDetails = true, CancellationToken cancellationToken = default)
|
||||
{
|
||||
return await GetFirstAsync(predicate);
|
||||
}
|
||||
|
||||
public virtual async Task<TEntity> GetAsync(Expression<Func<TEntity, bool>> predicate,
|
||||
bool includeDetails = true, CancellationToken cancellationToken = default)
|
||||
public virtual async Task<TEntity> GetAsync(Expression<Func<TEntity, bool>> predicate, bool includeDetails = true, CancellationToken cancellationToken = default)
|
||||
{
|
||||
return await GetFirstAsync(predicate);
|
||||
}
|
||||
|
||||
public virtual async Task DeleteAsync(Expression<Func<TEntity, bool>> predicate, bool autoSave = false,
|
||||
CancellationToken cancellationToken = default)
|
||||
public virtual async Task DeleteAsync(Expression<Func<TEntity, bool>> predicate, bool autoSave = false, CancellationToken cancellationToken = default)
|
||||
{
|
||||
await this.DeleteAsync(predicate);
|
||||
}
|
||||
|
||||
public virtual async Task DeleteDirectAsync(Expression<Func<TEntity, bool>> predicate,
|
||||
CancellationToken cancellationToken = default)
|
||||
public virtual async Task DeleteDirectAsync(Expression<Func<TEntity, bool>> predicate, CancellationToken cancellationToken = default)
|
||||
{
|
||||
await this.DeleteAsync(predicate);
|
||||
}
|
||||
@@ -113,71 +103,60 @@ namespace Yi.Framework.SqlSugarCore.Repositories
|
||||
throw new NotImplementedException();
|
||||
}
|
||||
|
||||
public virtual async Task<List<TEntity>> GetListAsync(Expression<Func<TEntity, bool>> predicate,
|
||||
bool includeDetails = false, CancellationToken cancellationToken = default)
|
||||
public virtual async Task<List<TEntity>> GetListAsync(Expression<Func<TEntity, bool>> predicate, bool includeDetails = false, CancellationToken cancellationToken = default)
|
||||
{
|
||||
return await GetListAsync(predicate);
|
||||
}
|
||||
|
||||
public virtual async Task<TEntity> InsertAsync(TEntity entity, bool autoSave = false,
|
||||
CancellationToken cancellationToken = default)
|
||||
public virtual async Task<TEntity> InsertAsync(TEntity entity, bool autoSave = false, CancellationToken cancellationToken = default)
|
||||
{
|
||||
return await InsertReturnEntityAsync(entity);
|
||||
}
|
||||
|
||||
public virtual async Task InsertManyAsync(IEnumerable<TEntity> entities, bool autoSave = false,
|
||||
CancellationToken cancellationToken = default)
|
||||
public virtual async Task InsertManyAsync(IEnumerable<TEntity> entities, bool autoSave = false, CancellationToken cancellationToken = default)
|
||||
{
|
||||
await InsertRangeAsync(entities.ToList());
|
||||
}
|
||||
|
||||
public virtual async Task<TEntity> UpdateAsync(TEntity entity, bool autoSave = false,
|
||||
CancellationToken cancellationToken = default)
|
||||
public virtual async Task<TEntity> UpdateAsync(TEntity entity, bool autoSave = false, CancellationToken cancellationToken = default)
|
||||
{
|
||||
await UpdateAsync(entity);
|
||||
return entity;
|
||||
}
|
||||
|
||||
public virtual async Task UpdateManyAsync(IEnumerable<TEntity> entities, bool autoSave = false,
|
||||
CancellationToken cancellationToken = default)
|
||||
public virtual async Task UpdateManyAsync(IEnumerable<TEntity> entities, bool autoSave = false, CancellationToken cancellationToken = default)
|
||||
{
|
||||
await UpdateRangeAsync(entities.ToList());
|
||||
}
|
||||
|
||||
public virtual async Task DeleteAsync(TEntity entity, bool autoSave = false,
|
||||
CancellationToken cancellationToken = default)
|
||||
public virtual async Task DeleteAsync(TEntity entity, bool autoSave = false, CancellationToken cancellationToken = default)
|
||||
{
|
||||
await DeleteAsync(entity);
|
||||
}
|
||||
|
||||
public virtual async Task DeleteManyAsync(IEnumerable<TEntity> entities, bool autoSave = false,
|
||||
CancellationToken cancellationToken = default)
|
||||
public virtual async Task DeleteManyAsync(IEnumerable<TEntity> entities, bool autoSave = false, CancellationToken cancellationToken = default)
|
||||
{
|
||||
await DeleteAsync(entities.ToList());
|
||||
}
|
||||
|
||||
public virtual async Task<List<TEntity>> GetListAsync(bool includeDetails = false,
|
||||
CancellationToken cancellationToken = default)
|
||||
public virtual async Task<List<TEntity>> GetListAsync(bool includeDetails = false, CancellationToken cancellationToken = default)
|
||||
{
|
||||
return await GetListAsync();
|
||||
}
|
||||
|
||||
public virtual async Task<long> GetCountAsync(CancellationToken cancellationToken = default)
|
||||
{
|
||||
return await this.CountAsync(_ => true);
|
||||
return await this.CountAsync(_=>true);
|
||||
}
|
||||
|
||||
public virtual async Task<List<TEntity>> GetPagedListAsync(int skipCount, int maxResultCount, string sorting,
|
||||
bool includeDetails = false, CancellationToken cancellationToken = default)
|
||||
public virtual async Task<List<TEntity>> GetPagedListAsync(int skipCount, int maxResultCount, string sorting, bool includeDetails = false, CancellationToken cancellationToken = default)
|
||||
{
|
||||
return await GetPageListAsync(_ => true, skipCount, maxResultCount);
|
||||
}
|
||||
|
||||
#endregion
|
||||
|
||||
|
||||
#region 内置DB快捷操作
|
||||
|
||||
public virtual async Task<IDeleteable<TEntity>> AsDeleteable()
|
||||
{
|
||||
return (await GetDbSimpleClientAsync()).AsDeleteable();
|
||||
@@ -232,11 +211,9 @@ namespace Yi.Framework.SqlSugarCore.Repositories
|
||||
{
|
||||
return (await GetDbSimpleClientAsync()).AsUpdateable(updateObjs);
|
||||
}
|
||||
|
||||
#endregion
|
||||
|
||||
#region SimpleClient模块
|
||||
|
||||
public virtual async Task<int> CountAsync(Expression<Func<TEntity, bool>> whereExpression)
|
||||
{
|
||||
return await (await GetDbSimpleClientAsync()).CountAsync(whereExpression);
|
||||
@@ -253,6 +230,7 @@ namespace Yi.Framework.SqlSugarCore.Repositories
|
||||
{
|
||||
return await (await GetDbSimpleClientAsync()).DeleteAsync(deleteObj);
|
||||
}
|
||||
|
||||
}
|
||||
|
||||
public virtual async Task<bool> DeleteAsync(List<TEntity> deleteObjs)
|
||||
@@ -272,13 +250,13 @@ namespace Yi.Framework.SqlSugarCore.Repositories
|
||||
{
|
||||
if (typeof(ISoftDelete).IsAssignableFrom(typeof(TEntity)))
|
||||
{
|
||||
return await (await GetDbSimpleClientAsync()).AsUpdateable()
|
||||
.SetColumns(nameof(ISoftDelete.IsDeleted), true).Where(whereExpression).ExecuteCommandAsync() > 0;
|
||||
return await (await GetDbSimpleClientAsync()).AsUpdateable().SetColumns(nameof(ISoftDelete.IsDeleted), true).Where(whereExpression).ExecuteCommandAsync() > 0;
|
||||
}
|
||||
else
|
||||
{
|
||||
return await (await GetDbSimpleClientAsync()).DeleteAsync(whereExpression);
|
||||
}
|
||||
|
||||
}
|
||||
|
||||
public virtual async Task<bool> DeleteByIdAsync(dynamic id)
|
||||
@@ -286,11 +264,7 @@ namespace Yi.Framework.SqlSugarCore.Repositories
|
||||
if (typeof(ISoftDelete).IsAssignableFrom(typeof(TEntity)))
|
||||
{
|
||||
var entity = await GetByIdAsync(id);
|
||||
if (entity is null)
|
||||
{
|
||||
return false;
|
||||
}
|
||||
|
||||
if (entity == null) return false;
|
||||
//反射赋值
|
||||
ReflexHelper.SetModelValue(nameof(ISoftDelete.IsDeleted), true, entity);
|
||||
return await UpdateAsync(entity);
|
||||
@@ -311,7 +285,6 @@ namespace Yi.Framework.SqlSugarCore.Repositories
|
||||
{
|
||||
return false;
|
||||
}
|
||||
|
||||
//反射赋值
|
||||
entities.ForEach(e => ReflexHelper.SetModelValue(nameof(ISoftDelete.IsDeleted), true, e));
|
||||
return await UpdateRangeAsync(entities);
|
||||
@@ -320,6 +293,7 @@ namespace Yi.Framework.SqlSugarCore.Repositories
|
||||
{
|
||||
return await (await GetDbSimpleClientAsync()).DeleteByIdAsync(ids);
|
||||
}
|
||||
|
||||
}
|
||||
|
||||
public virtual async Task<TEntity> GetByIdAsync(dynamic id)
|
||||
@@ -328,6 +302,7 @@ namespace Yi.Framework.SqlSugarCore.Repositories
|
||||
}
|
||||
|
||||
|
||||
|
||||
public virtual async Task<TEntity> GetFirstAsync(Expression<Func<TEntity, bool>> whereExpression)
|
||||
{
|
||||
return await (await GetDbSimpleClientAsync()).GetFirstAsync(whereExpression);
|
||||
@@ -343,19 +318,14 @@ namespace Yi.Framework.SqlSugarCore.Repositories
|
||||
return await (await GetDbSimpleClientAsync()).GetListAsync(whereExpression);
|
||||
}
|
||||
|
||||
public virtual async Task<List<TEntity>> GetPageListAsync(Expression<Func<TEntity, bool>> whereExpression,
|
||||
int pageNum, int pageSize)
|
||||
public virtual async Task<List<TEntity>> GetPageListAsync(Expression<Func<TEntity, bool>> whereExpression, int pageNum, int pageSize)
|
||||
{
|
||||
return await (await GetDbSimpleClientAsync()).GetPageListAsync(whereExpression,
|
||||
new PageModel() { PageIndex = pageNum, PageSize = pageSize });
|
||||
return await (await GetDbSimpleClientAsync()).GetPageListAsync(whereExpression, new PageModel() { PageIndex = pageNum, PageSize = pageSize });
|
||||
}
|
||||
|
||||
public virtual async Task<List<TEntity>> GetPageListAsync(Expression<Func<TEntity, bool>> whereExpression,
|
||||
int pageNum, int pageSize, Expression<Func<TEntity, object>>? orderByExpression = null,
|
||||
OrderByType orderByType = OrderByType.Asc)
|
||||
public virtual async Task<List<TEntity>> GetPageListAsync(Expression<Func<TEntity, bool>> whereExpression, int pageNum, int pageSize, Expression<Func<TEntity, object>>? orderByExpression = null, OrderByType orderByType = OrderByType.Asc)
|
||||
{
|
||||
return await (await GetDbSimpleClientAsync()).GetPageListAsync(whereExpression,
|
||||
new PageModel { PageIndex = pageNum, PageSize = pageSize }, orderByExpression, orderByType);
|
||||
return await (await GetDbSimpleClientAsync()).GetPageListAsync(whereExpression, new PageModel { PageIndex = pageNum, PageSize = pageSize }, orderByExpression, orderByType);
|
||||
}
|
||||
|
||||
public virtual async Task<TEntity> GetSingleAsync(Expression<Func<TEntity, bool>> whereExpression)
|
||||
@@ -410,9 +380,9 @@ namespace Yi.Framework.SqlSugarCore.Repositories
|
||||
|
||||
public virtual async Task<bool> UpdateAsync(TEntity updateObj)
|
||||
{
|
||||
if (typeof(TEntity).IsAssignableTo<IHasConcurrencyStamp>()) //带版本号乐观锁更新
|
||||
if (Options is not null && Options.EnabledConcurrencyException)
|
||||
{
|
||||
if (Options is not null && Options.EnabledConcurrencyException)
|
||||
if (typeof(TEntity).IsAssignableTo<IHasConcurrencyStamp>()) //带版本号乐观锁更新
|
||||
{
|
||||
try
|
||||
{
|
||||
@@ -426,24 +396,18 @@ namespace Yi.Framework.SqlSugarCore.Repositories
|
||||
$"{ex.Message}[更新失败:ConcurrencyStamp不是最新版本],entityInfo:{updateObj}", ex);
|
||||
}
|
||||
}
|
||||
else
|
||||
{
|
||||
int num = await (await GetDbSimpleClientAsync())
|
||||
.Context.Updateable(updateObj).ExecuteCommandAsync();
|
||||
return num > 0;
|
||||
}
|
||||
}
|
||||
|
||||
return await (await GetDbSimpleClientAsync()).UpdateAsync(updateObj);
|
||||
}
|
||||
|
||||
public virtual async Task<bool> UpdateAsync(Expression<Func<TEntity, TEntity>> columns,
|
||||
Expression<Func<TEntity, bool>> whereExpression)
|
||||
public virtual async Task<bool> UpdateAsync(Expression<Func<TEntity, TEntity>> columns, Expression<Func<TEntity, bool>> whereExpression)
|
||||
{
|
||||
return await (await GetDbSimpleClientAsync()).UpdateAsync(columns, whereExpression);
|
||||
}
|
||||
|
||||
|
||||
|
||||
public virtual async Task<bool> UpdateRangeAsync(List<TEntity> updateObjs)
|
||||
{
|
||||
return await (await GetDbSimpleClientAsync()).UpdateRangeAsync(updateObjs);
|
||||
@@ -452,34 +416,28 @@ namespace Yi.Framework.SqlSugarCore.Repositories
|
||||
#endregion
|
||||
}
|
||||
|
||||
public class SqlSugarRepository<TEntity, TKey> : SqlSugarRepository<TEntity>, ISqlSugarRepository<TEntity, TKey>,
|
||||
IRepository<TEntity, TKey> where TEntity : class, IEntity<TKey>, new()
|
||||
public class SqlSugarRepository<TEntity, TKey> : SqlSugarRepository<TEntity>, ISqlSugarRepository<TEntity, TKey>, IRepository<TEntity, TKey> where TEntity : class, IEntity<TKey>, new()
|
||||
{
|
||||
public SqlSugarRepository(ISugarDbContextProvider<ISqlSugarDbContext> dbContextProvider) : base(
|
||||
dbContextProvider)
|
||||
public SqlSugarRepository(ISugarDbContextProvider<ISqlSugarDbContext> sugarDbContextProvider) : base(sugarDbContextProvider)
|
||||
{
|
||||
}
|
||||
|
||||
public virtual async Task DeleteAsync(TKey id, bool autoSave = false,
|
||||
CancellationToken cancellationToken = default)
|
||||
public virtual async Task DeleteAsync(TKey id, bool autoSave = false, CancellationToken cancellationToken = default)
|
||||
{
|
||||
await DeleteByIdAsync(id);
|
||||
}
|
||||
|
||||
public virtual async Task DeleteManyAsync(IEnumerable<TKey> ids, bool autoSave = false,
|
||||
CancellationToken cancellationToken = default)
|
||||
public virtual async Task DeleteManyAsync(IEnumerable<TKey> ids, bool autoSave = false, CancellationToken cancellationToken = default)
|
||||
{
|
||||
await DeleteByIdsAsync(ids.Select(x => (object)x).ToArray());
|
||||
}
|
||||
|
||||
public virtual async Task<TEntity?> FindAsync(TKey id, bool includeDetails = true,
|
||||
CancellationToken cancellationToken = default)
|
||||
public virtual async Task<TEntity?> FindAsync(TKey id, bool includeDetails = true, CancellationToken cancellationToken = default)
|
||||
{
|
||||
return await GetByIdAsync(id);
|
||||
}
|
||||
|
||||
public virtual async Task<TEntity> GetAsync(TKey id, bool includeDetails = true,
|
||||
CancellationToken cancellationToken = default)
|
||||
public virtual async Task<TEntity> GetAsync(TKey id, bool includeDetails = true, CancellationToken cancellationToken = default)
|
||||
{
|
||||
return await GetByIdAsync(id);
|
||||
}
|
||||
|
||||
@@ -0,0 +1,21 @@
|
||||
using Yi.Framework.Rbac.Domain.Shared.Dtos;
|
||||
|
||||
namespace Yi.Framework.AiHub.Application.Contracts.Dtos;
|
||||
|
||||
public class AiUserRoleMenuDto:UserRoleMenuDto
|
||||
{
|
||||
/// <summary>
|
||||
/// 是否绑定服务号
|
||||
/// </summary>
|
||||
public bool IsBindFuwuhao { get; set; }
|
||||
|
||||
/// <summary>
|
||||
/// 是否为VIP用户
|
||||
/// </summary>
|
||||
public bool IsVip { get; set; }
|
||||
|
||||
/// <summary>
|
||||
/// VIP到期时间
|
||||
/// </summary>
|
||||
public DateTime? VipExpireTime { get; set; }
|
||||
}
|
||||
@@ -0,0 +1,22 @@
|
||||
namespace Yi.Framework.AiHub.Application.Contracts.Dtos.Announcement;
|
||||
|
||||
/// <summary>
|
||||
/// 公告缓存 DTO
|
||||
/// </summary>
|
||||
public class AnnouncementCacheDto
|
||||
{
|
||||
/// <summary>
|
||||
/// 版本号
|
||||
/// </summary>
|
||||
public string Version { get; set; } = string.Empty;
|
||||
|
||||
/// <summary>
|
||||
/// 公告日志列表
|
||||
/// </summary>
|
||||
public List<AnnouncementLogDto> Logs { get; set; } = new List<AnnouncementLogDto>();
|
||||
|
||||
/// <summary>
|
||||
/// 跳转链接
|
||||
/// </summary>
|
||||
public string? Url { get; set; }
|
||||
}
|
||||
@@ -0,0 +1,44 @@
|
||||
using Yi.Framework.AiHub.Domain.Shared.Enums;
|
||||
|
||||
namespace Yi.Framework.AiHub.Application.Contracts.Dtos.Announcement;
|
||||
|
||||
/// <summary>
|
||||
/// 公告日志 DTO
|
||||
/// </summary>
|
||||
public class AnnouncementLogDto
|
||||
{
|
||||
/// <summary>
|
||||
/// 标题
|
||||
/// </summary>
|
||||
public string Title { get; set; }
|
||||
|
||||
/// <summary>
|
||||
/// 内容列表
|
||||
/// </summary>
|
||||
public List<string> Content { get; set; } = new List<string>();
|
||||
|
||||
/// <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; }
|
||||
}
|
||||
@@ -0,0 +1,17 @@
|
||||
namespace Yi.Framework.AiHub.Application.Contracts.Dtos.Announcement;
|
||||
|
||||
/// <summary>
|
||||
/// 公告输出 DTO
|
||||
/// </summary>
|
||||
public class AnnouncementOutput
|
||||
{
|
||||
/// <summary>
|
||||
/// 版本号
|
||||
/// </summary>
|
||||
public string Version { get; set; } = string.Empty;
|
||||
|
||||
/// <summary>
|
||||
/// 公告日志列表
|
||||
/// </summary>
|
||||
public List<AnnouncementLogDto> Logs { get; set; } = new List<AnnouncementLogDto>();
|
||||
}
|
||||
@@ -0,0 +1,93 @@
|
||||
namespace Yi.Framework.AiHub.Application.Contracts.Dtos.CardFlip;
|
||||
|
||||
/// <summary>
|
||||
/// 翻牌任务状态输出
|
||||
/// </summary>
|
||||
public class CardFlipStatusOutput
|
||||
{
|
||||
/// <summary>
|
||||
/// 本周总翻牌次数
|
||||
/// </summary>
|
||||
public int TotalFlips { get; set; }
|
||||
|
||||
/// <summary>
|
||||
/// 剩余免费次数
|
||||
/// </summary>
|
||||
public int RemainingFreeFlips { get; set; }
|
||||
|
||||
/// <summary>
|
||||
/// 剩余赠送次数
|
||||
/// </summary>
|
||||
public int RemainingBonusFlips { get; set; }
|
||||
|
||||
/// <summary>
|
||||
/// 剩余邀请解锁次数
|
||||
/// </summary>
|
||||
public int RemainingInviteFlips { get; set; }
|
||||
|
||||
/// <summary>
|
||||
/// 是否可以翻牌
|
||||
/// </summary>
|
||||
public bool CanFlip { get; set; }
|
||||
|
||||
/// <summary>
|
||||
/// 用户的邀请码
|
||||
/// </summary>
|
||||
public string? MyInviteCode { get; set; }
|
||||
|
||||
/// <summary>
|
||||
/// 本周邀请人数
|
||||
/// </summary>
|
||||
public int InvitedCount { get; set; }
|
||||
|
||||
/// <summary>
|
||||
/// 翻牌记录
|
||||
/// </summary>
|
||||
public List<CardFlipRecord> FlipRecords { get; set; } = new();
|
||||
|
||||
/// <summary>
|
||||
/// 下次可翻牌提示
|
||||
/// </summary>
|
||||
public string? NextFlipTip { get; set; }
|
||||
|
||||
/// <summary>
|
||||
/// 当前用户是否已经填写过邀请码
|
||||
/// </summary>
|
||||
public bool IsFilledInviteCode { get; set; }
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// 翻牌记录
|
||||
/// </summary>
|
||||
public class CardFlipRecord
|
||||
{
|
||||
/// <summary>
|
||||
/// 翻牌序号(1-10)
|
||||
/// </summary>
|
||||
public int FlipNumber { get; set; }
|
||||
|
||||
/// <summary>
|
||||
/// 是否已翻
|
||||
/// </summary>
|
||||
public bool IsFlipped { get; set; }
|
||||
|
||||
/// <summary>
|
||||
/// 是否中奖
|
||||
/// </summary>
|
||||
public bool IsWin { get; set; }
|
||||
|
||||
/// <summary>
|
||||
/// 奖励金额(token数)
|
||||
/// </summary>
|
||||
public long? RewardAmount { get; set; }
|
||||
|
||||
/// <summary>
|
||||
/// 翻牌类型描述
|
||||
/// </summary>
|
||||
public string? FlipTypeDesc { get; set; }
|
||||
|
||||
/// <summary>
|
||||
/// 在翻牌顺序中的位置(1-10,表示第几个翻)
|
||||
/// </summary>
|
||||
public int FlipOrderIndex { get; set; }
|
||||
}
|
||||
@@ -0,0 +1,12 @@
|
||||
namespace Yi.Framework.AiHub.Application.Contracts.Dtos.CardFlip;
|
||||
|
||||
/// <summary>
|
||||
/// 翻牌输入
|
||||
/// </summary>
|
||||
public class FlipCardInput
|
||||
{
|
||||
/// <summary>
|
||||
/// 翻牌序号(1-10)
|
||||
/// </summary>
|
||||
public int FlipNumber { get; set; }
|
||||
}
|
||||
@@ -0,0 +1,32 @@
|
||||
namespace Yi.Framework.AiHub.Application.Contracts.Dtos.CardFlip;
|
||||
|
||||
/// <summary>
|
||||
/// 翻牌输出
|
||||
/// </summary>
|
||||
public class FlipCardOutput
|
||||
{
|
||||
/// <summary>
|
||||
/// 翻牌序号(1-10)
|
||||
/// </summary>
|
||||
public int FlipNumber { get; set; }
|
||||
|
||||
/// <summary>
|
||||
/// 是否中奖
|
||||
/// </summary>
|
||||
public bool IsWin { get; set; }
|
||||
|
||||
/// <summary>
|
||||
/// 奖励金额(token数)
|
||||
/// </summary>
|
||||
public long? RewardAmount { get; set; }
|
||||
|
||||
/// <summary>
|
||||
/// 奖励描述
|
||||
/// </summary>
|
||||
public string? RewardDesc { get; set; }
|
||||
|
||||
/// <summary>
|
||||
/// 剩余可翻次数
|
||||
/// </summary>
|
||||
public int RemainingFlips { get; set; }
|
||||
}
|
||||
@@ -0,0 +1,48 @@
|
||||
namespace Yi.Framework.AiHub.Application.Contracts.Dtos.CardFlip;
|
||||
|
||||
/// <summary>
|
||||
/// 邀请码信息输出
|
||||
/// </summary>
|
||||
public class InviteCodeOutput
|
||||
{
|
||||
/// <summary>
|
||||
/// 我的邀请码
|
||||
/// </summary>
|
||||
public string? MyInviteCode { get; set; }
|
||||
|
||||
/// <summary>
|
||||
/// 本周邀请人数
|
||||
/// </summary>
|
||||
public int InvitedCount { get; set; }
|
||||
|
||||
/// <summary>
|
||||
/// 是否已被邀请
|
||||
/// </summary>
|
||||
public bool IsInvited { get; set; }
|
||||
|
||||
/// <summary>
|
||||
/// 邀请历史记录
|
||||
/// </summary>
|
||||
public List<InvitationHistoryItem> InvitationHistory { get; set; } = new();
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// 邀请历史记录项
|
||||
/// </summary>
|
||||
public class InvitationHistoryItem
|
||||
{
|
||||
/// <summary>
|
||||
/// 被邀请人昵称(脱敏)
|
||||
/// </summary>
|
||||
public string InvitedUserName { get; set; } = string.Empty;
|
||||
|
||||
/// <summary>
|
||||
/// 邀请时间
|
||||
/// </summary>
|
||||
public DateTime InvitationTime { get; set; }
|
||||
|
||||
/// <summary>
|
||||
/// 本周所在
|
||||
/// </summary>
|
||||
public string WeekDescription { get; set; } = string.Empty;
|
||||
}
|
||||
@@ -0,0 +1,12 @@
|
||||
namespace Yi.Framework.AiHub.Application.Contracts.Dtos.CardFlip;
|
||||
|
||||
/// <summary>
|
||||
/// 使用邀请码输入
|
||||
/// </summary>
|
||||
public class UseInviteCodeInput
|
||||
{
|
||||
/// <summary>
|
||||
/// 邀请码
|
||||
/// </summary>
|
||||
public string InviteCode { get; set; } = string.Empty;
|
||||
}
|
||||
@@ -0,0 +1,12 @@
|
||||
namespace Yi.Framework.AiHub.Application.Contracts.Dtos.DailyTask;
|
||||
|
||||
/// <summary>
|
||||
/// 领取任务奖励输入
|
||||
/// </summary>
|
||||
public class ClaimTaskRewardInput
|
||||
{
|
||||
/// <summary>
|
||||
/// 任务等级(1=1000w任务,2=3000w任务)
|
||||
/// </summary>
|
||||
public int TaskLevel { get; set; }
|
||||
}
|
||||
@@ -0,0 +1,58 @@
|
||||
namespace Yi.Framework.AiHub.Application.Contracts.Dtos.DailyTask;
|
||||
|
||||
/// <summary>
|
||||
/// 每日任务状态输出
|
||||
/// </summary>
|
||||
public class DailyTaskStatusOutput
|
||||
{
|
||||
/// <summary>
|
||||
/// 今日消耗的尊享包Token数
|
||||
/// </summary>
|
||||
public long TodayConsumedTokens { get; set; }
|
||||
|
||||
/// <summary>
|
||||
/// 任务列表
|
||||
/// </summary>
|
||||
public List<DailyTaskItem> Tasks { get; set; } = new();
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// 每日任务项
|
||||
/// </summary>
|
||||
public class DailyTaskItem
|
||||
{
|
||||
/// <summary>
|
||||
/// 任务等级(1=1000w任务,2=3000w任务)
|
||||
/// </summary>
|
||||
public int Level { get; set; }
|
||||
|
||||
/// <summary>
|
||||
/// 任务名称
|
||||
/// </summary>
|
||||
public string Name { get; set; } = string.Empty;
|
||||
|
||||
/// <summary>
|
||||
/// 任务描述
|
||||
/// </summary>
|
||||
public string Description { get; set; } = string.Empty;
|
||||
|
||||
/// <summary>
|
||||
/// 任务要求的Token消耗量
|
||||
/// </summary>
|
||||
public long RequiredTokens { get; set; }
|
||||
|
||||
/// <summary>
|
||||
/// 奖励的Token数量
|
||||
/// </summary>
|
||||
public long RewardTokens { get; set; }
|
||||
|
||||
/// <summary>
|
||||
/// 任务状态:0=未完成,1=可领取,2=已领取
|
||||
/// </summary>
|
||||
public int Status { get; set; }
|
||||
|
||||
/// <summary>
|
||||
/// 任务进度百分比(0-100)
|
||||
/// </summary>
|
||||
public decimal Progress { get; set; }
|
||||
}
|
||||
@@ -0,0 +1,14 @@
|
||||
namespace Yi.Framework.AiHub.Application.Contracts.Dtos.FileMaster;
|
||||
|
||||
public class VerifyNextInput
|
||||
{
|
||||
/// <summary>
|
||||
/// 文件数
|
||||
/// </summary>
|
||||
public int FileCount { get; set; }
|
||||
|
||||
/// <summary>
|
||||
/// 文件夹数
|
||||
/// </summary>
|
||||
public int DirectoryCount { get; set; }
|
||||
}
|
||||
@@ -0,0 +1,14 @@
|
||||
namespace Yi.Framework.AiHub.Application.Contracts.Dtos.Fuwuhao;
|
||||
|
||||
public class QrCodeOutput
|
||||
{
|
||||
/// <summary>
|
||||
/// Qrcode url
|
||||
/// </summary>
|
||||
public string QrCodeUrl { get; set; }
|
||||
|
||||
/// <summary>
|
||||
/// 场景值
|
||||
/// </summary>
|
||||
public string Scene { get; set; }
|
||||
}
|
||||
@@ -0,0 +1,21 @@
|
||||
using Yi.Framework.AiHub.Domain.Shared.Enums.Fuwuhao;
|
||||
|
||||
namespace Yi.Framework.AiHub.Application.Contracts.Dtos.Fuwuhao;
|
||||
|
||||
public class QrCodeResultOutput
|
||||
{
|
||||
/// <summary>
|
||||
/// 返回状态
|
||||
/// </summary>
|
||||
public SceneResultEnum SceneResult { get; set; } = SceneResultEnum.Wait;
|
||||
|
||||
/// <summary>
|
||||
/// 如果是已登录,返回token
|
||||
/// </summary>
|
||||
public string? Token { get; set; }
|
||||
|
||||
/// <summary>
|
||||
/// 刷新token
|
||||
/// </summary>
|
||||
public string? RefreshToken { get; set; }
|
||||
}
|
||||
@@ -0,0 +1,16 @@
|
||||
using Yi.Framework.AiHub.Domain.Shared.Enums.Fuwuhao;
|
||||
|
||||
namespace Yi.Framework.AiHub.Application.Contracts.Dtos.Fuwuhao;
|
||||
|
||||
public class SceneCacheDto
|
||||
{
|
||||
public SceneResultEnum SceneResult { get; set; } = SceneResultEnum.Wait;
|
||||
|
||||
public SceneTypeEnum SceneType { get; set; }
|
||||
|
||||
/// <summary>
|
||||
/// 如果是绑定类型,需要用户id
|
||||
/// </summary>
|
||||
public Guid? UserId { get; set; }
|
||||
}
|
||||
|
||||
@@ -1,3 +1,4 @@
|
||||
using System.ComponentModel.DataAnnotations;
|
||||
using Yi.Framework.AiHub.Domain.Shared.Enums;
|
||||
|
||||
namespace Yi.Framework.AiHub.Application.Contracts.Dtos.Pay;
|
||||
@@ -10,5 +11,8 @@ public class CreateOrderInput
|
||||
/// <summary>
|
||||
/// 商品类型
|
||||
/// </summary>
|
||||
[Required]
|
||||
public GoodsTypeEnum GoodsType { get; set; }
|
||||
|
||||
public string? ReturnUrl{ get; set; }
|
||||
}
|
||||
@@ -0,0 +1,16 @@
|
||||
using Yi.Framework.AiHub.Domain.Shared.Enums;
|
||||
|
||||
namespace Yi.Framework.AiHub.Application.Contracts.Dtos.Pay;
|
||||
|
||||
/// <summary>
|
||||
/// 获取商品列表输入DTO
|
||||
/// </summary>
|
||||
public class GetGoodsListInput
|
||||
{
|
||||
/// <summary>
|
||||
/// 商品类别(可选)
|
||||
/// 如果不传,则返回所有商品
|
||||
/// 如果传了,则只返回指定类别的商品(VIP服务或尊享包)
|
||||
/// </summary>
|
||||
public GoodsCategoryType? GoodsCategoryType { get; set; }
|
||||
}
|
||||
@@ -0,0 +1,55 @@
|
||||
using Yi.Framework.AiHub.Domain.Shared.Enums;
|
||||
|
||||
namespace Yi.Framework.AiHub.Application.Contracts.Dtos.Pay;
|
||||
|
||||
/// <summary>
|
||||
/// 商品列表输出DTO
|
||||
/// </summary>
|
||||
public class GoodsListOutput
|
||||
{
|
||||
/// <summary>
|
||||
/// 商品名称
|
||||
/// </summary>
|
||||
public string GoodsName { get; set; }
|
||||
|
||||
/// <summary>
|
||||
/// 商品原价
|
||||
/// </summary>
|
||||
public decimal OriginalPrice { get; set; }
|
||||
|
||||
/// <summary>
|
||||
/// 商品参考价格
|
||||
/// </summary>
|
||||
public decimal ReferencePrice { get; set; }
|
||||
|
||||
/// <summary>
|
||||
/// 商品实际价格(折扣后的价格)
|
||||
/// </summary>
|
||||
public decimal GoodsPrice { get; set; }
|
||||
|
||||
/// <summary>
|
||||
/// 折扣金额(仅尊享包)
|
||||
/// </summary>
|
||||
public decimal? DiscountAmount { get; set; }
|
||||
|
||||
/// <summary>
|
||||
/// 商品类别
|
||||
/// </summary>
|
||||
public string GoodsCategory { get; set; }
|
||||
|
||||
/// <summary>
|
||||
/// 商品备注
|
||||
/// </summary>
|
||||
public string Remark { get; set; }
|
||||
|
||||
|
||||
/// <summary>
|
||||
/// 折扣说明(仅尊享包)
|
||||
/// </summary>
|
||||
public string? DiscountDescription { get; set; }
|
||||
|
||||
/// <summary>
|
||||
/// 商品类型
|
||||
/// </summary>
|
||||
public GoodsTypeEnum GoodsType { get; set; }
|
||||
}
|
||||
@@ -25,9 +25,10 @@ public class RechargeCreateInput
|
||||
public string Content { get; set; } = string.Empty;
|
||||
|
||||
/// <summary>
|
||||
/// 到期时间(为空表示永久VIP)
|
||||
/// VIP月数(为空或0表示永久VIP)
|
||||
/// </summary>
|
||||
public DateTime? ExpireDateTime { get; set; }
|
||||
[Range(0, int.MaxValue, ErrorMessage = "月数必须大于等于0")]
|
||||
public int? Months { get; set; }
|
||||
|
||||
/// <summary>
|
||||
/// 备注
|
||||
|
||||
@@ -0,0 +1,22 @@
|
||||
namespace Yi.Framework.AiHub.Application.Contracts.Dtos.UsageStatistics;
|
||||
|
||||
/// <summary>
|
||||
/// 尊享服务Token用量统计DTO
|
||||
/// </summary>
|
||||
public class PremiumTokenUsageDto
|
||||
{
|
||||
/// <summary>
|
||||
/// 总Token数
|
||||
/// </summary>
|
||||
public long PremiumTotalTokens { get; set; }
|
||||
|
||||
/// <summary>
|
||||
/// 已使用Token数
|
||||
/// </summary>
|
||||
public long PremiumUsedTokens { get; set; }
|
||||
|
||||
/// <summary>
|
||||
/// 剩余Token数
|
||||
/// </summary>
|
||||
public long PremiumRemainingTokens { get; set; }
|
||||
}
|
||||
@@ -0,0 +1,12 @@
|
||||
using Volo.Abp.Application.Dtos;
|
||||
using Yi.Framework.Ddd.Application.Contracts;
|
||||
|
||||
namespace Yi.Framework.AiHub.Application.Contracts.Dtos.UsageStatistics;
|
||||
|
||||
public class PremiumTokenUsageGetListInput : PagedAllResultRequestDto
|
||||
{
|
||||
/// <summary>
|
||||
/// 是否免费
|
||||
/// </summary>
|
||||
public bool? IsFree { get; set; }
|
||||
}
|
||||
@@ -0,0 +1,57 @@
|
||||
using Volo.Abp.Application.Dtos;
|
||||
using Yi.Framework.Ddd.Application.Contracts;
|
||||
|
||||
namespace Yi.Framework.AiHub.Application.Contracts.Dtos.UsageStatistics;
|
||||
|
||||
public class PremiumTokenUsageGetListOutput : CreationAuditedEntityDto
|
||||
{
|
||||
/// <summary>
|
||||
/// id
|
||||
/// </summary>
|
||||
public Guid Id { get; set; }
|
||||
|
||||
/// <summary>
|
||||
/// 用户ID
|
||||
/// </summary>
|
||||
public Guid UserId { get; set; }
|
||||
|
||||
/// <summary>
|
||||
/// 包名称
|
||||
/// </summary>
|
||||
public string PackageName { get; set; }
|
||||
|
||||
/// <summary>
|
||||
/// 总用量(总token数)
|
||||
/// </summary>
|
||||
public long TotalTokens { get; set; }
|
||||
|
||||
/// <summary>
|
||||
/// 剩余用量(剩余token数)
|
||||
/// </summary>
|
||||
public long RemainingTokens { get; set; }
|
||||
|
||||
/// <summary>
|
||||
/// 已使用token数
|
||||
/// </summary>
|
||||
public long UsedTokens { get; set; }
|
||||
|
||||
/// <summary>
|
||||
/// 到期时间
|
||||
/// </summary>
|
||||
public DateTime? ExpireDateTime { get; set; }
|
||||
|
||||
/// <summary>
|
||||
/// 是否激活
|
||||
/// </summary>
|
||||
public bool IsActive { get; set; }
|
||||
|
||||
/// <summary>
|
||||
/// 购买金额
|
||||
/// </summary>
|
||||
public decimal PurchaseAmount { get; set; }
|
||||
|
||||
/// <summary>
|
||||
/// 备注
|
||||
/// </summary>
|
||||
public string? Remark { get; set; }
|
||||
}
|
||||
@@ -0,0 +1,15 @@
|
||||
using Yi.Framework.AiHub.Application.Contracts.Dtos.Announcement;
|
||||
|
||||
namespace Yi.Framework.AiHub.Application.Contracts.IServices;
|
||||
|
||||
/// <summary>
|
||||
/// 公告服务接口
|
||||
/// </summary>
|
||||
public interface IAnnouncementService
|
||||
{
|
||||
/// <summary>
|
||||
/// 获取公告信息
|
||||
/// </summary>
|
||||
/// <returns>公告信息</returns>
|
||||
Task<List<AnnouncementLogDto>> GetAsync();
|
||||
}
|
||||
@@ -0,0 +1,41 @@
|
||||
using Yi.Framework.AiHub.Application.Contracts.Dtos.CardFlip;
|
||||
|
||||
namespace Yi.Framework.AiHub.Application.Contracts.IServices;
|
||||
|
||||
/// <summary>
|
||||
/// 翻牌服务接口
|
||||
/// </summary>
|
||||
public interface ICardFlipService
|
||||
{
|
||||
/// <summary>
|
||||
/// 获取本周翻牌任务状态
|
||||
/// </summary>
|
||||
/// <returns></returns>
|
||||
Task<CardFlipStatusOutput> GetWeeklyTaskStatusAsync();
|
||||
|
||||
/// <summary>
|
||||
/// 翻牌
|
||||
/// </summary>
|
||||
/// <param name="input">翻牌输入</param>
|
||||
/// <returns></returns>
|
||||
Task<FlipCardOutput> FlipCardAsync(FlipCardInput input);
|
||||
|
||||
/// <summary>
|
||||
/// 使用邀请码解锁翻牌次数
|
||||
/// </summary>
|
||||
/// <param name="input">邀请码输入</param>
|
||||
/// <returns></returns>
|
||||
Task UseInviteCodeAsync(UseInviteCodeInput input);
|
||||
|
||||
/// <summary>
|
||||
/// 获取我的邀请码信息
|
||||
/// </summary>
|
||||
/// <returns></returns>
|
||||
Task<InviteCodeOutput> GetMyInviteCodeAsync();
|
||||
|
||||
/// <summary>
|
||||
/// 生成我的邀请码(如果没有)
|
||||
/// </summary>
|
||||
/// <returns></returns>
|
||||
Task<string> GenerateMyInviteCodeAsync();
|
||||
}
|
||||
@@ -30,4 +30,11 @@ public interface IPayService : IApplicationService
|
||||
/// <param name="input">查询订单状态输入</param>
|
||||
/// <returns>订单状态信息</returns>
|
||||
Task<QueryOrderStatusOutput> QueryOrderStatusAsync([FromQuery] QueryOrderStatusInput input);
|
||||
|
||||
/// <summary>
|
||||
/// 获取商品列表
|
||||
/// </summary>
|
||||
/// <param name="input">获取商品列表输入</param>
|
||||
/// <returns>商品列表</returns>
|
||||
Task<List<GoodsListOutput>> GetGoodsListAsync([FromQuery] GetGoodsListInput input);
|
||||
}
|
||||
@@ -1,4 +1,6 @@
|
||||
namespace Yi.Framework.AiHub.Application.Contracts.IServices;
|
||||
using Yi.Framework.AiHub.Application.Contracts.Dtos.Recharge;
|
||||
|
||||
namespace Yi.Framework.AiHub.Application.Contracts.IServices;
|
||||
|
||||
public interface IRechargeService
|
||||
{
|
||||
@@ -6,4 +8,11 @@ public interface IRechargeService
|
||||
/// 移除用户vip及角色
|
||||
/// </summary>
|
||||
Task RemoveVipRoleByExpireAsync();
|
||||
|
||||
/// <summary>
|
||||
/// 给用户充值VIP
|
||||
/// </summary>
|
||||
/// <param name="input">充值输入参数</param>
|
||||
/// <returns></returns>
|
||||
Task RechargeVipAsync(RechargeCreateInput input);
|
||||
}
|
||||
@@ -18,4 +18,10 @@ public interface IUsageStatisticsService
|
||||
/// </summary>
|
||||
/// <returns>模型Token使用量列表</returns>
|
||||
Task<List<ModelTokenUsageDto>> GetModelTokenUsageAsync();
|
||||
|
||||
/// <summary>
|
||||
/// 获取当前用户尊享服务Token用量统计
|
||||
/// </summary>
|
||||
/// <returns>尊享服务Token用量统计</returns>
|
||||
Task<PremiumTokenUsageDto> GetPremiumTokenUsageAsync();
|
||||
}
|
||||
@@ -0,0 +1,151 @@
|
||||
using Mapster;
|
||||
using Microsoft.AspNetCore.Authorization;
|
||||
using Microsoft.AspNetCore.Mvc;
|
||||
using Volo.Abp.Application.Services;
|
||||
using Volo.Abp.Users;
|
||||
using Yi.Framework.AiHub.Application.Contracts.Dtos;
|
||||
using Yi.Framework.AiHub.Domain.Entities;
|
||||
using Yi.Framework.Rbac.Application.Contracts.IServices;
|
||||
using Yi.Framework.Rbac.Domain.Shared.Dtos;
|
||||
using Yi.Framework.SqlSugarCore.Abstractions;
|
||||
using Yi.Framework.AiHub.Domain.Extensions;
|
||||
|
||||
namespace Yi.Framework.AiHub.Application.Services;
|
||||
|
||||
public class AiAccountService : ApplicationService
|
||||
{
|
||||
private IAccountService _accountService;
|
||||
private ISqlSugarRepository<AiUserExtraInfoEntity> _userRepository;
|
||||
private ISqlSugarRepository<AiRechargeAggregateRoot> _rechargeRepository;
|
||||
private ISqlSugarRepository<PremiumPackageAggregateRoot> _premiumPackageRepository;
|
||||
|
||||
public AiAccountService(
|
||||
IAccountService accountService,
|
||||
ISqlSugarRepository<AiUserExtraInfoEntity> userRepository,
|
||||
ISqlSugarRepository<AiRechargeAggregateRoot> rechargeRepository,
|
||||
ISqlSugarRepository<PremiumPackageAggregateRoot> premiumPackageRepository)
|
||||
{
|
||||
_accountService = accountService;
|
||||
_userRepository = userRepository;
|
||||
_rechargeRepository = rechargeRepository;
|
||||
_premiumPackageRepository = premiumPackageRepository;
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// 获取ai用户信息
|
||||
/// </summary>
|
||||
/// <returns></returns>
|
||||
[Authorize]
|
||||
[HttpGet("account/ai")]
|
||||
public async Task<AiUserRoleMenuDto> GetAsync()
|
||||
{
|
||||
var userId = CurrentUser.GetId();
|
||||
var userAccount = await _accountService.GetAsync(null, null, userId: CurrentUser.GetId());
|
||||
var output = userAccount.Adapt<AiUserRoleMenuDto>();
|
||||
|
||||
// 是否绑定服务号
|
||||
output.IsBindFuwuhao = await _userRepository.IsAnyAsync(x => userId == x.UserId);
|
||||
|
||||
// 是否为VIP用户
|
||||
output.IsVip = CurrentUser.IsAiVip();
|
||||
|
||||
// 获取VIP到期时间
|
||||
if (output.IsVip)
|
||||
{
|
||||
var recharges = await _rechargeRepository._DbQueryable
|
||||
.Where(x => x.UserId == userId)
|
||||
.ToListAsync();
|
||||
|
||||
if (recharges.Any())
|
||||
{
|
||||
// 如果有任何一个充值记录的过期时间为null,说明是永久VIP
|
||||
if (recharges.Any(x => !x.ExpireDateTime.HasValue))
|
||||
{
|
||||
output.VipExpireTime = null; // 永久VIP
|
||||
}
|
||||
else
|
||||
{
|
||||
// 取最大的过期时间
|
||||
output.VipExpireTime = recharges
|
||||
.Where(x => x.ExpireDateTime.HasValue)
|
||||
.Max(x => x.ExpireDateTime);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
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;
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,68 @@
|
||||
using Mapster;
|
||||
using Microsoft.Extensions.Caching.Distributed;
|
||||
using Microsoft.Extensions.Configuration;
|
||||
using Volo.Abp.Application.Services;
|
||||
using Volo.Abp.Caching;
|
||||
using Yi.Framework.AiHub.Application.Contracts.Dtos.Announcement;
|
||||
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 AnnouncementService : ApplicationService, IAnnouncementService
|
||||
{
|
||||
private readonly ISqlSugarRepository<AnnouncementAggregateRoot> _announcementRepository;
|
||||
private readonly IConfiguration _configuration;
|
||||
private readonly IDistributedCache<AnnouncementCacheDto> _announcementCache;
|
||||
private const string AnnouncementCacheKey = "AiHub:Announcement";
|
||||
|
||||
public AnnouncementService(
|
||||
ISqlSugarRepository<AnnouncementAggregateRoot> announcementRepository,
|
||||
IConfiguration configuration,
|
||||
IDistributedCache<AnnouncementCacheDto> announcementCache)
|
||||
{
|
||||
_announcementRepository = announcementRepository;
|
||||
_configuration = configuration;
|
||||
_announcementCache = announcementCache;
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// 获取公告信息
|
||||
/// </summary>
|
||||
public async Task<List<AnnouncementLogDto>> GetAsync()
|
||||
{
|
||||
// 使用 GetOrAddAsync 从缓存获取或添加数据,缓存1小时
|
||||
var cacheData = await _announcementCache.GetOrAddAsync(
|
||||
AnnouncementCacheKey,
|
||||
async () => await LoadAnnouncementDataAsync(),
|
||||
() => new DistributedCacheEntryOptions
|
||||
{
|
||||
AbsoluteExpirationRelativeToNow = TimeSpan.FromHours(1)
|
||||
}
|
||||
);
|
||||
|
||||
return cacheData?.Logs ?? new List<AnnouncementLogDto>();
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// 从数据库加载公告数据
|
||||
/// </summary>
|
||||
private async Task<AnnouncementCacheDto> LoadAnnouncementDataAsync()
|
||||
{
|
||||
// 查询所有公告日志,按日期降序排列
|
||||
var logs = await _announcementRepository._DbQueryable
|
||||
.OrderByDescending(x => x.StartTime)
|
||||
.ToListAsync();
|
||||
|
||||
// 转换为 DTO
|
||||
var logDtos = logs.Adapt<List<AnnouncementLogDto>>();
|
||||
return new AnnouncementCacheDto
|
||||
{
|
||||
Logs = logDtos
|
||||
};
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,275 @@
|
||||
using Microsoft.AspNetCore.Authorization;
|
||||
using Microsoft.Extensions.Logging;
|
||||
using Volo.Abp.Application.Services;
|
||||
using Volo.Abp.Users;
|
||||
using Yi.Framework.AiHub.Application.Contracts.Dtos.CardFlip;
|
||||
using Yi.Framework.AiHub.Application.Contracts.IServices;
|
||||
using Yi.Framework.AiHub.Domain.Entities;
|
||||
using Yi.Framework.AiHub.Domain.Extensions;
|
||||
using Yi.Framework.AiHub.Domain.Managers;
|
||||
using Yi.Framework.SqlSugarCore.Abstractions;
|
||||
|
||||
namespace Yi.Framework.AiHub.Application.Services;
|
||||
|
||||
/// <summary>
|
||||
/// 翻牌服务 - 应用层组合服务
|
||||
/// </summary>
|
||||
[Authorize]
|
||||
public class CardFlipService : ApplicationService, ICardFlipService
|
||||
{
|
||||
private readonly CardFlipManager _cardFlipManager;
|
||||
private readonly InviteCodeManager _inviteCodeManager;
|
||||
private readonly ISqlSugarRepository<PremiumPackageAggregateRoot> _premiumPackageRepository;
|
||||
private readonly ILogger<CardFlipService> _logger;
|
||||
|
||||
public CardFlipService(
|
||||
CardFlipManager cardFlipManager,
|
||||
InviteCodeManager inviteCodeManager,
|
||||
ISqlSugarRepository<PremiumPackageAggregateRoot> premiumPackageRepository,
|
||||
ILogger<CardFlipService> logger)
|
||||
{
|
||||
_cardFlipManager = cardFlipManager;
|
||||
_inviteCodeManager = inviteCodeManager;
|
||||
_premiumPackageRepository = premiumPackageRepository;
|
||||
_logger = logger;
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// 获取本周翻牌任务状态
|
||||
/// </summary>
|
||||
public async Task<CardFlipStatusOutput> GetWeeklyTaskStatusAsync()
|
||||
{
|
||||
var userId = CurrentUser.GetId();
|
||||
var weekStart = CardFlipManager.GetWeekStartDate(DateTime.Now);
|
||||
|
||||
// 获取本周任务
|
||||
var task = await _cardFlipManager.GetOrCreateWeeklyTaskAsync(userId, weekStart, createIfNotExists: false);
|
||||
|
||||
// 获取邀请码信息
|
||||
var inviteCode = await _inviteCodeManager.GetUserInviteCodeAsync(userId);
|
||||
|
||||
// 统计本周邀请人数
|
||||
var invitedCount = await _inviteCodeManager.GetWeeklyInvitationCountAsync(userId, weekStart);
|
||||
|
||||
//当前用户是否已填写过邀请码
|
||||
var isFilledInviteCode = await _inviteCodeManager.IsFilledInviteCodeAsync(userId);
|
||||
var output = new CardFlipStatusOutput
|
||||
{
|
||||
TotalFlips = task?.TotalFlips ?? 0,
|
||||
RemainingFreeFlips = CardFlipManager.MAX_FREE_FLIPS - (task?.FreeFlipsUsed ?? 0),
|
||||
RemainingBonusFlips = 0, // 已废弃
|
||||
RemainingInviteFlips = CardFlipManager.MAX_INVITE_FLIPS - (task?.InviteFlipsUsed ?? 0),
|
||||
CanFlip = _cardFlipManager.CanFlipCard(task),
|
||||
MyInviteCode = inviteCode?.Code,
|
||||
InvitedCount = invitedCount,
|
||||
FlipRecords = BuildFlipRecords(task),
|
||||
IsFilledInviteCode = isFilledInviteCode
|
||||
};
|
||||
|
||||
// 生成提示信息
|
||||
output.NextFlipTip = GenerateNextFlipTip(output);
|
||||
|
||||
return output;
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// 翻牌
|
||||
/// </summary>
|
||||
public async Task<FlipCardOutput> FlipCardAsync(FlipCardInput input)
|
||||
{
|
||||
var userId = CurrentUser.GetId();
|
||||
var weekStart = CardFlipManager.GetWeekStartDate(DateTime.Now);
|
||||
|
||||
// 执行翻牌逻辑(由Manager处理验证和翻牌)
|
||||
var result = await _cardFlipManager.ExecuteFlipAsync(userId, input.FlipNumber, weekStart);
|
||||
|
||||
// 如果中奖,发放奖励
|
||||
if (result.IsWin)
|
||||
{
|
||||
await GrantRewardAsync(userId, result.RewardAmount, $"翻牌活动-序号{input.FlipNumber}中奖");
|
||||
}
|
||||
|
||||
// 构建输出
|
||||
var output = new FlipCardOutput
|
||||
{
|
||||
FlipNumber = result.FlipNumber,
|
||||
IsWin = result.IsWin,
|
||||
RewardAmount = result.RewardAmount,
|
||||
RewardDesc = result.RewardDesc,
|
||||
RemainingFlips = CardFlipManager.TOTAL_MAX_FLIPS - input.FlipNumber
|
||||
};
|
||||
|
||||
return output;
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// 使用邀请码解锁翻牌次数
|
||||
/// </summary>
|
||||
public async Task UseInviteCodeAsync(UseInviteCodeInput input)
|
||||
{
|
||||
var userId = CurrentUser.GetId();
|
||||
var weekStart = CardFlipManager.GetWeekStartDate(DateTime.Now);
|
||||
|
||||
// 获取本周任务
|
||||
var task = await _cardFlipManager.GetOrCreateWeeklyTaskAsync(userId, weekStart, createIfNotExists: true);
|
||||
|
||||
// 验证是否已经使用了所有邀请解锁次数
|
||||
if (task.InviteFlipsUsed >= CardFlipManager.MAX_INVITE_FLIPS)
|
||||
{
|
||||
throw new UserFriendlyException("本周邀请解锁次数已用完");
|
||||
}
|
||||
|
||||
// 使用邀请码(由Manager处理验证和邀请逻辑)
|
||||
await _inviteCodeManager.UseInviteCodeAsync(userId, input.InviteCode);
|
||||
|
||||
_logger.LogInformation($"用户 {userId} 使用邀请码 {input.InviteCode} 解锁翻牌次数成功");
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// 获取我的邀请码信息
|
||||
/// </summary>
|
||||
public async Task<InviteCodeOutput> GetMyInviteCodeAsync()
|
||||
{
|
||||
var userId = CurrentUser.GetId();
|
||||
var weekStart = CardFlipManager.GetWeekStartDate(DateTime.Now);
|
||||
|
||||
// 获取我的邀请码
|
||||
var inviteCode = await _inviteCodeManager.GetUserInviteCodeAsync(userId);
|
||||
|
||||
// 统计本周邀请人数
|
||||
var invitedCount = await _inviteCodeManager.GetWeeklyInvitationCountAsync(userId, weekStart);
|
||||
|
||||
// 获取邀请历史
|
||||
var invitationHistory = await _inviteCodeManager.GetInvitationHistoryAsync(userId, 10);
|
||||
|
||||
return new InviteCodeOutput
|
||||
{
|
||||
MyInviteCode = inviteCode?.Code,
|
||||
InvitedCount = invitedCount,
|
||||
InvitationHistory = invitationHistory.Select(x => new InvitationHistoryItem
|
||||
{
|
||||
InvitedUserName = x.InvitedUserName,
|
||||
InvitationTime = x.InvitationTime,
|
||||
WeekDescription = GetWeekDescription(x.InvitationTime)
|
||||
}).ToList()
|
||||
};
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// 生成我的邀请码
|
||||
/// </summary>
|
||||
public async Task<string> GenerateMyInviteCodeAsync()
|
||||
{
|
||||
var userId = CurrentUser.GetId();
|
||||
|
||||
// 生成邀请码(由Manager处理)
|
||||
var code = await _inviteCodeManager.GenerateInviteCodeForUserAsync(userId);
|
||||
|
||||
return code;
|
||||
}
|
||||
|
||||
#region 私有辅助方法
|
||||
|
||||
/// <summary>
|
||||
/// 构建翻牌记录列表
|
||||
/// </summary>
|
||||
private List<CardFlipRecord> BuildFlipRecords(CardFlipTaskAggregateRoot? task)
|
||||
{
|
||||
var records = new List<CardFlipRecord>();
|
||||
|
||||
// 获取已翻牌的顺序
|
||||
var flippedOrder = task != null ? _cardFlipManager.GetFlippedOrder(task) : new List<int>();
|
||||
var flippedNumbers = new HashSet<int>(flippedOrder);
|
||||
|
||||
// 获取中奖记录
|
||||
var winRecords = task?.WinRecords ?? new Dictionary<int, long>();
|
||||
|
||||
// 构建记录,按照原始序号1-10排列
|
||||
for (int i = 1; i <= CardFlipManager.TOTAL_MAX_FLIPS; i++)
|
||||
{
|
||||
var record = new CardFlipRecord
|
||||
{
|
||||
FlipNumber = i,
|
||||
IsFlipped = flippedNumbers.Contains(i),
|
||||
IsWin = false,
|
||||
FlipTypeDesc = CardFlipManager.GetFlipTypeDesc(i),
|
||||
// 设置在翻牌顺序中的位置(0表示未翻,>0表示第几个翻的)
|
||||
FlipOrderIndex = flippedOrder.IndexOf(i) >= 0 ? flippedOrder.IndexOf(i) + 1 : 0
|
||||
};
|
||||
|
||||
// 设置中奖信息
|
||||
// 判断这张卡是第几次翻的
|
||||
if (task != null && flippedNumbers.Contains(i))
|
||||
{
|
||||
var flipOrderIndex = flippedOrder.IndexOf(i) + 1; // 第几次翻的(1-based)
|
||||
|
||||
// 检查这次翻牌是否中奖
|
||||
if (winRecords.TryGetValue(flipOrderIndex, out var rewardAmount))
|
||||
{
|
||||
record.IsWin = true;
|
||||
record.RewardAmount = rewardAmount;
|
||||
}
|
||||
}
|
||||
|
||||
records.Add(record);
|
||||
}
|
||||
|
||||
return records;
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// 生成下次翻牌提示
|
||||
/// </summary>
|
||||
private string GenerateNextFlipTip(CardFlipStatusOutput status)
|
||||
{
|
||||
if (status.TotalFlips >= CardFlipManager.TOTAL_MAX_FLIPS)
|
||||
{
|
||||
return "本周翻牌次数已用完,请下周再来!";
|
||||
}
|
||||
|
||||
if (status.RemainingFreeFlips > 0)
|
||||
{
|
||||
return $"本周您还有{status.RemainingFreeFlips}次免费翻牌机会";
|
||||
}
|
||||
else if (status.RemainingInviteFlips > 0)
|
||||
{
|
||||
if (status.TotalFlips >= 7)
|
||||
{
|
||||
return $"本周使用他人邀请码或他人使用你的邀请码,可解锁{status.RemainingInviteFlips}次翻牌,且必中大奖!每次中奖最大额度将翻倍!";
|
||||
}
|
||||
|
||||
return $"本周使用他人邀请码或他人使用你的邀请码,可解锁{status.RemainingInviteFlips}次翻牌,必中大奖!每次中奖最大额度将翻倍!";
|
||||
}
|
||||
|
||||
return "继续加油!";
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// 发放奖励
|
||||
/// </summary>
|
||||
private async Task GrantRewardAsync(Guid userId, long amount, string description)
|
||||
{
|
||||
var premiumPackage = new PremiumPackageAggregateRoot(userId, amount, description)
|
||||
{
|
||||
PurchaseAmount = 0, // 奖励不需要付费
|
||||
Remark = $"翻牌活动奖励:{amount / 10000}w tokens"
|
||||
};
|
||||
|
||||
await _premiumPackageRepository.InsertAsync(premiumPackage);
|
||||
|
||||
_logger.LogInformation($"用户 {userId} 获得翻牌奖励 {amount / 10000}w tokens");
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// 获取周描述
|
||||
/// </summary>
|
||||
private string GetWeekDescription(DateTime date)
|
||||
{
|
||||
var weekStart = CardFlipManager.GetWeekStartDate(date);
|
||||
var weekEnd = weekStart.AddDays(6);
|
||||
|
||||
return $"{weekStart:MM-dd} 至 {weekEnd:MM-dd}";
|
||||
}
|
||||
|
||||
#endregion
|
||||
}
|
||||
@@ -16,6 +16,7 @@ using Yi.Framework.AiHub.Domain.Entities;
|
||||
using Yi.Framework.AiHub.Domain.Entities.Model;
|
||||
using Yi.Framework.AiHub.Domain.Extensions;
|
||||
using Yi.Framework.AiHub.Domain.Managers;
|
||||
using Yi.Framework.AiHub.Domain.Shared.Consts;
|
||||
using Yi.Framework.AiHub.Domain.Shared.Dtos;
|
||||
using Yi.Framework.AiHub.Domain.Shared.Dtos.OpenAi;
|
||||
using Yi.Framework.AiHub.Domain.Shared.Enums;
|
||||
@@ -35,17 +36,19 @@ public class AiChatService : ApplicationService
|
||||
private readonly AiBlacklistManager _aiBlacklistManager;
|
||||
private readonly ILogger<AiChatService> _logger;
|
||||
private readonly AiGateWayManager _aiGateWayManager;
|
||||
private readonly PremiumPackageManager _premiumPackageManager;
|
||||
|
||||
public AiChatService(IHttpContextAccessor httpContextAccessor,
|
||||
AiBlacklistManager aiBlacklistManager,
|
||||
ISqlSugarRepository<AiModelEntity> aiModelRepository,
|
||||
ILogger<AiChatService> logger, AiGateWayManager aiGateWayManager)
|
||||
ILogger<AiChatService> logger, AiGateWayManager aiGateWayManager, PremiumPackageManager premiumPackageManager)
|
||||
{
|
||||
_httpContextAccessor = httpContextAccessor;
|
||||
_aiBlacklistManager = aiBlacklistManager;
|
||||
_aiModelRepository = aiModelRepository;
|
||||
_logger = logger;
|
||||
_aiGateWayManager = aiGateWayManager;
|
||||
_premiumPackageManager = premiumPackageManager;
|
||||
}
|
||||
|
||||
|
||||
@@ -118,8 +121,56 @@ public class AiChatService : ApplicationService
|
||||
}
|
||||
}
|
||||
|
||||
//如果是尊享包服务,需要校验是是否尊享包足够
|
||||
if (CurrentUser.IsAuthenticated && PremiumPackageConst.ModeIds.Contains(input.Model))
|
||||
{
|
||||
// 检查尊享token包用量
|
||||
var availableTokens = await _premiumPackageManager.GetAvailableTokensAsync(CurrentUser.GetId());
|
||||
if (availableTokens <= 0)
|
||||
{
|
||||
throw new UserFriendlyException("尊享token包用量不足,请先购买尊享token包");
|
||||
}
|
||||
}
|
||||
|
||||
//ai网关代理httpcontext
|
||||
await _aiGateWayManager.CompleteChatStreamForStatisticsAsync(_httpContextAccessor.HttpContext, input,
|
||||
CurrentUser.Id, sessionId, cancellationToken);
|
||||
}
|
||||
|
||||
|
||||
/// <summary>
|
||||
/// 发送消息
|
||||
/// </summary>
|
||||
/// <param name="input"></param>
|
||||
/// <param name="cancellationToken"></param>
|
||||
[HttpPost("ai-chat/FileMaster/send")]
|
||||
public async Task PostFileMasterSendAsync([FromBody] ThorChatCompletionsRequest input,
|
||||
CancellationToken cancellationToken)
|
||||
{
|
||||
if (!string.IsNullOrWhiteSpace(input.Model))
|
||||
{
|
||||
throw new BusinessException("当前接口不支持第三方使用");
|
||||
}
|
||||
|
||||
if (CurrentUser.IsAuthenticated)
|
||||
{
|
||||
await _aiBlacklistManager.VerifiyAiBlacklist(CurrentUser.GetId());
|
||||
if (CurrentUser.IsAiVip())
|
||||
{
|
||||
input.Model = "gpt-5-chat";
|
||||
}
|
||||
else
|
||||
{
|
||||
input.Model = "gpt-4.1-mini";
|
||||
}
|
||||
}
|
||||
else
|
||||
{
|
||||
input.Model = "DeepSeek-R1-0528";
|
||||
}
|
||||
|
||||
//ai网关代理httpcontext
|
||||
await _aiGateWayManager.CompleteChatStreamForStatisticsAsync(_httpContextAccessor.HttpContext, input,
|
||||
CurrentUser.Id, null, cancellationToken);
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,185 @@
|
||||
using Microsoft.AspNetCore.Authorization;
|
||||
using Microsoft.Extensions.Logging;
|
||||
using SqlSugar;
|
||||
using Volo.Abp.Application.Services;
|
||||
using Volo.Abp.Users;
|
||||
using Yi.Framework.AiHub.Application.Contracts.Dtos.DailyTask;
|
||||
using Yi.Framework.AiHub.Domain.Entities;
|
||||
using Yi.Framework.AiHub.Domain.Entities.Chat;
|
||||
using Yi.Framework.AiHub.Domain.Extensions;
|
||||
using Yi.Framework.AiHub.Domain.Managers;
|
||||
using Yi.Framework.AiHub.Domain.Shared.Consts;
|
||||
using Yi.Framework.SqlSugarCore.Abstractions;
|
||||
|
||||
namespace Yi.Framework.AiHub.Application.Services;
|
||||
|
||||
/// <summary>
|
||||
/// 每日任务服务
|
||||
/// </summary>
|
||||
[Authorize]
|
||||
public class DailyTaskService : ApplicationService
|
||||
{
|
||||
private readonly ISqlSugarRepository<DailyTaskRewardRecordAggregateRoot> _dailyTaskRepository;
|
||||
private readonly ISqlSugarRepository<MessageAggregateRoot> _messageRepository;
|
||||
private readonly ISqlSugarRepository<PremiumPackageAggregateRoot> _premiumPackageRepository;
|
||||
private readonly ILogger<DailyTaskService> _logger;
|
||||
|
||||
// 任务配置
|
||||
private readonly Dictionary<int, (long RequiredTokens, long RewardTokens, string Name, string Description)>
|
||||
_taskConfigs = new()
|
||||
{
|
||||
{ 1, (10000000, 1000000, "尊享包1000w token任务", "累积使用尊享包 1000w token") }, // 1000w消耗 -> 100w奖励
|
||||
{ 2, (30000000, 2000000, "尊享包3000w token任务", "累积使用尊享包 3000w token") } // 3000w消耗 -> 200w奖励
|
||||
};
|
||||
|
||||
public DailyTaskService(
|
||||
ISqlSugarRepository<DailyTaskRewardRecordAggregateRoot> dailyTaskRepository,
|
||||
ISqlSugarRepository<MessageAggregateRoot> messageRepository,
|
||||
ISqlSugarRepository<PremiumPackageAggregateRoot> premiumPackageRepository,
|
||||
ILogger<DailyTaskService> logger)
|
||||
{
|
||||
_dailyTaskRepository = dailyTaskRepository;
|
||||
_messageRepository = messageRepository;
|
||||
_premiumPackageRepository = premiumPackageRepository;
|
||||
_logger = logger;
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// 获取今日任务状态
|
||||
/// </summary>
|
||||
/// <returns></returns>
|
||||
public async Task<DailyTaskStatusOutput> GetTodayTaskStatusAsync()
|
||||
{
|
||||
var userId = CurrentUser.GetId();
|
||||
var today = DateTime.Today;
|
||||
|
||||
// 1. 统计今日尊享包Token消耗量
|
||||
var todayConsumed = await GetTodayPremiumTokenConsumptionAsync(userId, today);
|
||||
|
||||
// 2. 查询今日已领取的任务
|
||||
var claimedTasks = await _dailyTaskRepository._DbQueryable
|
||||
.Where(x => x.UserId == userId && x.TaskDate == today)
|
||||
.Select(x => new { x.TaskLevel, x.IsRewarded })
|
||||
.ToListAsync();
|
||||
|
||||
// 3. 构建任务列表
|
||||
var tasks = new List<DailyTaskItem>();
|
||||
foreach (var (level, config) in _taskConfigs)
|
||||
{
|
||||
var claimed = claimedTasks.FirstOrDefault(x => x.TaskLevel == level);
|
||||
int status;
|
||||
|
||||
if (claimed != null && claimed.IsRewarded)
|
||||
{
|
||||
status = 2; // 已领取
|
||||
}
|
||||
else if (todayConsumed >= config.RequiredTokens)
|
||||
{
|
||||
status = 1; // 可领取
|
||||
}
|
||||
else
|
||||
{
|
||||
status = 0; // 未完成
|
||||
}
|
||||
|
||||
var progress = todayConsumed >= config.RequiredTokens
|
||||
? 100
|
||||
: Math.Round((decimal)todayConsumed / config.RequiredTokens * 100, 2);
|
||||
|
||||
tasks.Add(new DailyTaskItem
|
||||
{
|
||||
Level = level,
|
||||
Name = config.Name,
|
||||
Description = config.Description,
|
||||
RequiredTokens = config.RequiredTokens,
|
||||
RewardTokens = config.RewardTokens,
|
||||
Status = status,
|
||||
Progress = progress
|
||||
});
|
||||
}
|
||||
|
||||
return new DailyTaskStatusOutput
|
||||
{
|
||||
TodayConsumedTokens = todayConsumed,
|
||||
Tasks = tasks
|
||||
};
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// 领取任务奖励
|
||||
/// </summary>
|
||||
/// <param name="input"></param>
|
||||
/// <returns></returns>
|
||||
public async Task ClaimTaskRewardAsync(ClaimTaskRewardInput input)
|
||||
{
|
||||
var userId = CurrentUser.GetId();
|
||||
var today = DateTime.Today;
|
||||
|
||||
// 1. 验证任务等级
|
||||
if (!_taskConfigs.TryGetValue(input.TaskLevel, out var taskConfig))
|
||||
{
|
||||
throw new UserFriendlyException($"无效的任务等级: {input.TaskLevel}");
|
||||
}
|
||||
|
||||
// 2. 检查是否已领取
|
||||
var existingRecord = await _dailyTaskRepository._DbQueryable
|
||||
.Where(x => x.UserId == userId && x.TaskDate == today && x.TaskLevel == input.TaskLevel)
|
||||
.FirstAsync();
|
||||
|
||||
if (existingRecord != null)
|
||||
{
|
||||
throw new UserFriendlyException("今日该任务奖励已领取,请明天再来!");
|
||||
}
|
||||
|
||||
// 3. 验证今日Token消耗是否达标
|
||||
var todayConsumed = await GetTodayPremiumTokenConsumptionAsync(userId, today);
|
||||
if (todayConsumed < taskConfig.RequiredTokens)
|
||||
{
|
||||
throw new UserFriendlyException(
|
||||
$"Token消耗未达标!需要 {taskConfig.RequiredTokens / 10000}w,当前 {todayConsumed / 10000}w");
|
||||
}
|
||||
|
||||
// 4. 创建奖励包(使用 PremiumPackageManager)
|
||||
|
||||
var premiumPackage =
|
||||
new PremiumPackageAggregateRoot(userId, taskConfig.RewardTokens, $"每日任务:{taskConfig.Name}")
|
||||
{
|
||||
PurchaseAmount = 0, // 奖励不需要付费
|
||||
Remark = $"{today:yyyy-MM-dd} 每日任务奖励"
|
||||
};
|
||||
|
||||
await _premiumPackageRepository.InsertAsync(premiumPackage);
|
||||
|
||||
// 5. 记录领取记录
|
||||
var record = new DailyTaskRewardRecordAggregateRoot(userId, input.TaskLevel, today, taskConfig.RewardTokens)
|
||||
{
|
||||
Remark = $"完成任务{input.TaskLevel},名称:{taskConfig.Name},消耗 {todayConsumed / 10000}w token"
|
||||
};
|
||||
|
||||
await _dailyTaskRepository.InsertAsync(record);
|
||||
|
||||
_logger.LogInformation(
|
||||
$"用户 {userId} 领取每日任务 {input.TaskLevel} 奖励成功,获得 {taskConfig.RewardTokens / 10000}w tokens");
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// 获取今日尊享包Token消耗量
|
||||
/// </summary>
|
||||
/// <param name="userId">用户ID</param>
|
||||
/// <param name="today">今日日期</param>
|
||||
/// <returns>消耗的Token总数</returns>
|
||||
private async Task<long> GetTodayPremiumTokenConsumptionAsync(Guid userId, DateTime today)
|
||||
{
|
||||
var tomorrow = today.AddDays(1);
|
||||
|
||||
// 查询今日所有使用尊享包模型的消息(role=system 表示消耗)
|
||||
var totalTokens = await _messageRepository._DbQueryable
|
||||
.Where(x => x.UserId == userId)
|
||||
.Where(x => x.Role == "system") // system角色表示实际消耗
|
||||
.Where(x => PremiumPackageConst.ModeIds.Contains(x.ModelId)) // 尊享包模型
|
||||
.Where(x => x.CreationTime >= today && x.CreationTime < tomorrow)
|
||||
.SumAsync(x => x.TokenUsage.TotalTokenCount);
|
||||
|
||||
return totalTokens;
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,88 @@
|
||||
using Microsoft.AspNetCore.Http;
|
||||
using Microsoft.AspNetCore.Mvc;
|
||||
using Volo.Abp.Application.Services;
|
||||
using Volo.Abp.Users;
|
||||
using Yi.Framework.AiHub.Application.Contracts.Dtos.FileMaster;
|
||||
using Yi.Framework.AiHub.Domain.Managers;
|
||||
using Yi.Framework.AiHub.Domain.Shared.Dtos.OpenAi;
|
||||
|
||||
namespace Yi.Framework.AiHub.Application.Services.FileMaster;
|
||||
|
||||
public class FileMasterService : ApplicationService
|
||||
{
|
||||
private readonly IHttpContextAccessor _httpContextAccessor;
|
||||
private readonly AiGateWayManager _aiGateWayManager;
|
||||
private readonly AiBlacklistManager _aiBlacklistManager;
|
||||
|
||||
public FileMasterService(IHttpContextAccessor httpContextAccessor, AiGateWayManager aiGateWayManager,
|
||||
AiBlacklistManager aiBlacklistManager)
|
||||
{
|
||||
_httpContextAccessor = httpContextAccessor;
|
||||
_aiGateWayManager = aiGateWayManager;
|
||||
_aiBlacklistManager = aiBlacklistManager;
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// 校验下一步
|
||||
/// </summary>
|
||||
/// <returns></returns>
|
||||
[HttpPost("FileMaster/VerifyNext")]
|
||||
public Task<string> VerifyNextAsync(VerifyNextInput input)
|
||||
{
|
||||
if (!CurrentUser.IsAuthenticated)
|
||||
{
|
||||
if (input.DirectoryCount + input.FileCount >= 20)
|
||||
{
|
||||
throw new UserFriendlyException("未登录用户,文件夹与文件数量不能大于20个,请登录后解锁全部功能");
|
||||
}
|
||||
}
|
||||
else
|
||||
{
|
||||
if (input.DirectoryCount + input.FileCount >= 100)
|
||||
{
|
||||
throw new UserFriendlyException("为防止无限制暴力使用,当前文件整理大师Vip最多支持100文件与文件夹数量");
|
||||
}
|
||||
}
|
||||
|
||||
return Task.FromResult("success");
|
||||
}
|
||||
|
||||
|
||||
/// <summary>
|
||||
/// 对话
|
||||
/// </summary>
|
||||
/// <param name="input"></param>
|
||||
/// <param name="cancellationToken"></param>
|
||||
[HttpPost("FileMaster/chat/completions")]
|
||||
public async Task ChatCompletionsAsync([FromBody] ThorChatCompletionsRequest input,
|
||||
CancellationToken cancellationToken)
|
||||
{
|
||||
if (CurrentUser.IsAuthenticated)
|
||||
{
|
||||
input.Model = "gpt-5-chat";
|
||||
}
|
||||
else
|
||||
{
|
||||
input.Model = "gpt-5-chat";
|
||||
}
|
||||
|
||||
Guid? userId = CurrentUser.IsAuthenticated ? CurrentUser.GetId() : null;
|
||||
if (userId is not null)
|
||||
{
|
||||
await _aiBlacklistManager.VerifiyAiBlacklist(userId.Value);
|
||||
}
|
||||
|
||||
//ai网关代理httpcontext
|
||||
if (input.Stream == true)
|
||||
{
|
||||
await _aiGateWayManager.CompleteChatStreamForStatisticsAsync(_httpContextAccessor.HttpContext, input,
|
||||
userId, null, cancellationToken);
|
||||
}
|
||||
else
|
||||
{
|
||||
await _aiGateWayManager.CompleteChatForStatisticsAsync(_httpContextAccessor.HttpContext, input, userId,
|
||||
null,
|
||||
cancellationToken);
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,308 @@
|
||||
using System.Text;
|
||||
using System.Xml.Serialization;
|
||||
using Medallion.Threading;
|
||||
using Microsoft.AspNetCore.Http;
|
||||
using Microsoft.AspNetCore.Mvc;
|
||||
using Microsoft.Extensions.Caching.Distributed;
|
||||
using Microsoft.Extensions.Logging;
|
||||
using Volo.Abp.Application.Services;
|
||||
using Volo.Abp.Caching;
|
||||
using Volo.Abp.Users;
|
||||
using Yi.Framework.AiHub.Application.Contracts.Dtos.Fuwuhao;
|
||||
using Yi.Framework.AiHub.Domain.Entities;
|
||||
using Yi.Framework.AiHub.Domain.Managers.Fuwuhao;
|
||||
using Yi.Framework.AiHub.Domain.Shared.Consts;
|
||||
using Yi.Framework.AiHub.Domain.Shared.Enums.Fuwuhao;
|
||||
using Yi.Framework.Rbac.Application.Contracts.Dtos.Account;
|
||||
using Yi.Framework.Rbac.Application.Contracts.IServices;
|
||||
using Yi.Framework.SqlSugarCore.Abstractions;
|
||||
|
||||
namespace Yi.Framework.AiHub.Application.Services.Fuwuhao;
|
||||
|
||||
/// <summary>
|
||||
/// 服务号服务
|
||||
/// </summary>
|
||||
public class FuwuhaoService : ApplicationService
|
||||
{
|
||||
private readonly ILogger<FuwuhaoService> _logger;
|
||||
private readonly IHttpContextAccessor _accessor;
|
||||
private readonly FuwuhaoManager _fuwuhaoManager;
|
||||
private IDistributedCache<SceneCacheDto> _sceneCache;
|
||||
private IDistributedCache<string> _openIdToSceneCache;
|
||||
private ISqlSugarRepository<AiUserExtraInfoEntity> _userRepository;
|
||||
private IAccountService _accountService;
|
||||
private IFileService _fileService;
|
||||
public IDistributedLockProvider DistributedLock => LazyServiceProvider.LazyGetService<IDistributedLockProvider>();
|
||||
|
||||
public FuwuhaoService(ILogger<FuwuhaoService> logger, IHttpContextAccessor accessor, FuwuhaoManager fuwuhaoManager,
|
||||
IDistributedCache<SceneCacheDto> sceneCache, IAccountService accountService, IFileService fileService,
|
||||
IDistributedCache<string> openIdToSceneCache, ISqlSugarRepository<AiUserExtraInfoEntity> userRepositroy)
|
||||
{
|
||||
_logger = logger;
|
||||
_accessor = accessor;
|
||||
_fuwuhaoManager = fuwuhaoManager;
|
||||
_sceneCache = sceneCache;
|
||||
_accountService = accountService;
|
||||
_fileService = fileService;
|
||||
_openIdToSceneCache = openIdToSceneCache;
|
||||
_userRepository = userRepositroy;
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// 服务器号测试回调
|
||||
/// </summary>
|
||||
/// <returns></returns>
|
||||
[HttpGet("fuwuhao/callback")]
|
||||
public async Task<string> GetCallbackAsync([FromQuery] string signature, [FromQuery] string timestamp,
|
||||
[FromQuery] string nonce, [FromQuery] string echostr)
|
||||
{
|
||||
return echostr;
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// 服务号关注回调
|
||||
/// </summary>
|
||||
/// <param name="signature"></param>
|
||||
/// <param name="timestamp"></param>
|
||||
/// <param name="nonce"></param>
|
||||
/// <returns></returns>
|
||||
[HttpPost("fuwuhao/callback")]
|
||||
public async Task<string> PostCallbackAsync([FromQuery] string signature, [FromQuery] string timestamp,
|
||||
[FromQuery] string nonce)
|
||||
{
|
||||
_fuwuhaoManager.ValidateCallback(signature, timestamp, nonce);
|
||||
var request = _accessor.HttpContext.Request;
|
||||
// 1. 读取原始 XML 内容
|
||||
using var reader = new StreamReader(request.Body, Encoding.UTF8);
|
||||
var xmlString = await reader.ReadToEndAsync();
|
||||
|
||||
var serializer = new XmlSerializer(typeof(FuwuhaoCallModel));
|
||||
using var stringReader = new StringReader(xmlString);
|
||||
var body = (FuwuhaoCallModel)serializer.Deserialize(stringReader);
|
||||
|
||||
//获取场景值,后续通过场景值设置缓存状态,前端轮询这个场景值用户是否已操作即可
|
||||
var scene = body.EventKey.Replace("qrscene_", "");
|
||||
if (!(body.Event is "SCAN" or "subscribe"))
|
||||
{
|
||||
throw new UserFriendlyException("当前回调只处理扫码 与 关注");
|
||||
}
|
||||
|
||||
if (scene is null)
|
||||
{
|
||||
throw new UserFriendlyException("服务号返回无场景值");
|
||||
}
|
||||
|
||||
//制作幂等
|
||||
await using (var handle =
|
||||
await DistributedLock.TryAcquireLockAsync($"Yi:fuwuhao:callbacklock:{scene}"))
|
||||
{
|
||||
if (handle == null)
|
||||
{
|
||||
return "success"; // 跳过直接返回成功
|
||||
}
|
||||
|
||||
var cache = await _sceneCache.GetAsync($"{FuwuhaoConst.SceneCacheKey}{scene}");
|
||||
if (cache == null)
|
||||
{
|
||||
return "success"; // 跳过直接返回成功
|
||||
}
|
||||
|
||||
if (cache.SceneResult != SceneResultEnum.Wait)
|
||||
{
|
||||
return "success"; // 跳过直接返回成功
|
||||
}
|
||||
|
||||
//根据操作类型,进行业务处理,返回处理结果,再写入缓存,10s过去,相当于用户10s扫完app后,轮询要在10秒内完成
|
||||
var scenResult =
|
||||
await _fuwuhaoManager.CallBackHandlerAsync(cache.SceneType, body.FromUserName, cache.UserId);
|
||||
cache.SceneResult = scenResult.SceneResult;
|
||||
cache.UserId = scenResult.UserId;
|
||||
await _sceneCache.SetAsync($"{FuwuhaoConst.SceneCacheKey}{scene}", cache,
|
||||
new DistributedCacheEntryOptions() { AbsoluteExpirationRelativeToNow = TimeSpan.FromSeconds(120) });
|
||||
|
||||
//如果是注册,将OpenId与Scene进行绑定,代表用户有30分钟进行注册
|
||||
if (scenResult.SceneResult == SceneResultEnum.Register)
|
||||
{
|
||||
await _openIdToSceneCache.SetAsync($"{FuwuhaoConst.OpenIdToSceneCacheKey}{body.FromUserName}", scene,
|
||||
new DistributedCacheEntryOptions() { AbsoluteExpirationRelativeToNow = TimeSpan.FromMinutes(30) });
|
||||
|
||||
var replyMessage =
|
||||
_fuwuhaoManager.BuildRegisterMessage(body.FromUserName);
|
||||
return replyMessage;
|
||||
}
|
||||
}
|
||||
|
||||
return "success";
|
||||
}
|
||||
|
||||
|
||||
/// <summary>
|
||||
/// 创建带参数的二维码
|
||||
/// </summary>
|
||||
/// <returns>二维码URL</returns>
|
||||
[HttpPost("fuwuhao/qrcode")]
|
||||
public async Task<QrCodeOutput> GetQrCodeAsync([FromQuery] SceneTypeEnum sceneType)
|
||||
{
|
||||
if (sceneType == SceneTypeEnum.Bind && CurrentUser.Id is null)
|
||||
{
|
||||
throw new UserFriendlyException("绑定微信,需登录用户,请重新登录后重试");
|
||||
}
|
||||
|
||||
//生成一个随机场景值
|
||||
var scene = Guid.NewGuid().ToString("N");
|
||||
var qrCodeUrl = await _fuwuhaoManager.CreateQrCodeAsync(scene);
|
||||
await _sceneCache.SetAsync($"{FuwuhaoConst.SceneCacheKey}{scene}", new SceneCacheDto()
|
||||
{
|
||||
UserId = CurrentUser.IsAuthenticated ? CurrentUser.GetId() : null,
|
||||
SceneType = sceneType
|
||||
}, new DistributedCacheEntryOptions() { AbsoluteExpirationRelativeToNow = TimeSpan.FromMinutes(10) });
|
||||
return new QrCodeOutput()
|
||||
{
|
||||
QrCodeUrl = qrCodeUrl,
|
||||
Scene = scene
|
||||
};
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// 扫码登录/注册/绑定,轮询接口
|
||||
/// </summary>
|
||||
/// <param name="scene"></param>
|
||||
/// <returns></returns>
|
||||
[HttpGet("fuwuhao/qrcode/result")]
|
||||
public async Task<QrCodeResultOutput> GetQrCodeResultAsync([FromQuery] string scene)
|
||||
{
|
||||
var output = new QrCodeResultOutput();
|
||||
var cache = await _sceneCache.GetAsync($"{FuwuhaoConst.SceneCacheKey}{scene}");
|
||||
if (cache is null)
|
||||
{
|
||||
output.SceneResult = SceneResultEnum.Expired;
|
||||
return output;
|
||||
}
|
||||
|
||||
output.SceneResult = cache.SceneResult;
|
||||
switch (output.SceneResult)
|
||||
{
|
||||
case SceneResultEnum.Login:
|
||||
if (cache.UserId is null)
|
||||
{
|
||||
throw new ApplicationException("获取用户id异常,请重试");
|
||||
}
|
||||
|
||||
var loginInfo = await _accountService.PostLoginAsync(cache.UserId!.Value);
|
||||
output.Token = loginInfo.Token;
|
||||
output.RefreshToken = loginInfo.RefreshToken;
|
||||
break;
|
||||
}
|
||||
|
||||
return output;
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// 注册账号,需要微信code
|
||||
/// </summary>
|
||||
/// <param name="code"></param>
|
||||
/// <returns></returns>
|
||||
[HttpGet("fuwuhao/register")]
|
||||
public async Task<IActionResult> RegisterByCodeAsync([FromQuery] string code)
|
||||
{
|
||||
var message = await RegisterByCodeForMessageAsync(code);
|
||||
//var message = "恭喜注册";
|
||||
var filePath = Path.Combine("wwwroot", "aihub", "auth.html");
|
||||
var html = await File.ReadAllTextAsync(filePath);
|
||||
var result = new ContentResult
|
||||
{
|
||||
Content = html.Replace("{{message}}", message),
|
||||
ContentType = "text/html",
|
||||
StatusCode = 200
|
||||
};
|
||||
return result;
|
||||
}
|
||||
|
||||
|
||||
private async Task<string> RegisterByCodeForMessageAsync(string code)
|
||||
{
|
||||
//根据code获取到openid、微信用户昵称、头像
|
||||
var userInfo = await _fuwuhaoManager.GetUserInfoByCodeAsync(code);
|
||||
if (userInfo is null)
|
||||
{
|
||||
return "当前注册已经失效,请重新扫码注册!";
|
||||
}
|
||||
|
||||
var scene = await _openIdToSceneCache.GetAsync($"{FuwuhaoConst.OpenIdToSceneCacheKey}{userInfo.OpenId}");
|
||||
if (scene is null)
|
||||
{
|
||||
return "当前注册已经过期,请重新扫码注册!";
|
||||
}
|
||||
|
||||
var files = new FormFileCollection();
|
||||
// 下载头像并添加到系统文件中
|
||||
if (!string.IsNullOrEmpty(userInfo.HeadImgUrl))
|
||||
{
|
||||
using var httpClient = new HttpClient();
|
||||
var imageBytes = await httpClient.GetByteArrayAsync(userInfo.HeadImgUrl);
|
||||
var imageStream = new MemoryStream(imageBytes);
|
||||
|
||||
// 从URL中提取文件扩展名,默认为png
|
||||
var fileName = $"avatar_{userInfo.OpenId}.png";
|
||||
var formFile = new FormFile(imageStream, 0, imageBytes.Length, "avatar", fileName)
|
||||
{
|
||||
Headers = new HeaderDictionary(),
|
||||
ContentType = "image/png"
|
||||
};
|
||||
files.Add(formFile);
|
||||
}
|
||||
|
||||
var result = await _fileService.Post(files);
|
||||
|
||||
//由于存在查询/编辑在同一个事务操作,上锁防止并发
|
||||
await using (await DistributedLock.AcquireLockAsync($"fuwuhao:RegisterLock:{userInfo.OpenId}",
|
||||
TimeSpan.FromMinutes(1)))
|
||||
{
|
||||
if (await _userRepository.IsAnyAsync(x => x.FuwuhaoOpenId == userInfo.OpenId))
|
||||
{
|
||||
return "你已注册过意社区账号!";
|
||||
}
|
||||
|
||||
Guid userId;
|
||||
try
|
||||
{
|
||||
userId = await _accountService.PostSystemRegisterAsync(new RegisterDto
|
||||
{
|
||||
UserName = $"wx{Random.Shared.Next(100000, 999999)}",
|
||||
Password = Guid.NewGuid().ToString("N"),
|
||||
Phone = null,
|
||||
Email = null,
|
||||
Nick = userInfo.Nickname,
|
||||
Icon = result.FirstOrDefault()?.Id.ToString()
|
||||
});
|
||||
}
|
||||
catch (UserFriendlyException e)
|
||||
{
|
||||
return e.Message;
|
||||
}
|
||||
|
||||
|
||||
await _userRepository.InsertAsync(new AiUserExtraInfoEntity(userId, userInfo.OpenId));
|
||||
await _sceneCache.SetAsync($"{FuwuhaoConst.SceneCacheKey}{scene}", new SceneCacheDto
|
||||
{
|
||||
UserId = userId,
|
||||
SceneResult = SceneResultEnum.Login
|
||||
},
|
||||
new DistributedCacheEntryOptions() { AbsoluteExpirationRelativeToNow = TimeSpan.FromSeconds(120) });
|
||||
}
|
||||
|
||||
return "恭喜你成功注册意社区账号!";
|
||||
}
|
||||
}
|
||||
|
||||
[XmlRoot("xml")]
|
||||
public class FuwuhaoCallModel
|
||||
{
|
||||
[XmlElement("ToUserName")] public string ToUserName { get; set; }
|
||||
[XmlElement("FromUserName")] public string FromUserName { get; set; }
|
||||
[XmlElement("CreateTime")] public string CreateTime { get; set; }
|
||||
[XmlElement("MsgType")] public string MsgType { get; set; }
|
||||
[XmlElement("Event")] public string Event { get; set; }
|
||||
[XmlElement("EventKey")] public string EventKey { get; set; }
|
||||
[XmlElement("Ticket")] public string Ticket { get; set; }
|
||||
}
|
||||
@@ -2,13 +2,18 @@
|
||||
using Microsoft.AspNetCore.Mvc;
|
||||
using Microsoft.Extensions.Logging;
|
||||
using Volo.Abp.Application.Services;
|
||||
using Volo.Abp.Users;
|
||||
using Yi.Framework.AiHub.Domain.Entities;
|
||||
using Yi.Framework.AiHub.Domain.Entities.Model;
|
||||
using Yi.Framework.AiHub.Domain.Extensions;
|
||||
using Yi.Framework.AiHub.Domain.Managers;
|
||||
using Yi.Framework.AiHub.Domain.Shared.Consts;
|
||||
using Yi.Framework.AiHub.Domain.Shared.Dtos.Anthropic;
|
||||
using Yi.Framework.AiHub.Domain.Shared.Dtos.OpenAi;
|
||||
using Yi.Framework.AiHub.Domain.Shared.Dtos.OpenAi.Embeddings;
|
||||
using Yi.Framework.AiHub.Domain.Shared.Dtos.OpenAi.Images;
|
||||
using Yi.Framework.AiHub.Domain.Shared.Enums;
|
||||
using Yi.Framework.Rbac.Application.Contracts.IServices;
|
||||
using Yi.Framework.SqlSugarCore.Abstractions;
|
||||
|
||||
namespace Yi.Framework.AiHub.Application.Services;
|
||||
@@ -21,9 +26,13 @@ public class OpenApiService : ApplicationService
|
||||
private readonly AiGateWayManager _aiGateWayManager;
|
||||
private readonly ISqlSugarRepository<AiModelEntity> _aiModelRepository;
|
||||
private readonly AiBlacklistManager _aiBlacklistManager;
|
||||
private readonly IAccountService _accountService;
|
||||
private readonly PremiumPackageManager _premiumPackageManager;
|
||||
|
||||
public OpenApiService(IHttpContextAccessor httpContextAccessor, ILogger<OpenApiService> logger,
|
||||
TokenManager tokenManager, AiGateWayManager aiGateWayManager,
|
||||
ISqlSugarRepository<AiModelEntity> aiModelRepository, AiBlacklistManager aiBlacklistManager)
|
||||
ISqlSugarRepository<AiModelEntity> aiModelRepository, AiBlacklistManager aiBlacklistManager,
|
||||
IAccountService accountService, PremiumPackageManager premiumPackageManager)
|
||||
{
|
||||
_httpContextAccessor = httpContextAccessor;
|
||||
_logger = logger;
|
||||
@@ -31,6 +40,8 @@ public class OpenApiService : ApplicationService
|
||||
_aiGateWayManager = aiGateWayManager;
|
||||
_aiModelRepository = aiModelRepository;
|
||||
_aiBlacklistManager = aiBlacklistManager;
|
||||
_accountService = accountService;
|
||||
_premiumPackageManager = premiumPackageManager;
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
@@ -46,6 +57,18 @@ public class OpenApiService : ApplicationService
|
||||
var httpContext = this._httpContextAccessor.HttpContext;
|
||||
var userId = await _tokenManager.GetUserIdAsync(GetTokenByHttpContext(httpContext));
|
||||
await _aiBlacklistManager.VerifiyAiBlacklist(userId);
|
||||
|
||||
//如果是尊享包服务,需要校验是是否尊享包足够
|
||||
if (PremiumPackageConst.ModeIds.Contains(input.Model))
|
||||
{
|
||||
// 检查尊享token包用量
|
||||
var availableTokens = await _premiumPackageManager.GetAvailableTokensAsync(userId);
|
||||
if (availableTokens <= 0)
|
||||
{
|
||||
throw new UserFriendlyException("尊享token包用量不足,请先购买尊享token包");
|
||||
}
|
||||
}
|
||||
|
||||
//ai网关代理httpcontext
|
||||
if (input.Stream == true)
|
||||
{
|
||||
@@ -69,6 +92,7 @@ public class OpenApiService : ApplicationService
|
||||
public async Task ImagesGenerationsAsync([FromBody] ImageCreateRequest input, CancellationToken cancellationToken)
|
||||
{
|
||||
var httpContext = this._httpContextAccessor.HttpContext;
|
||||
Intercept(httpContext);
|
||||
var userId = await _tokenManager.GetUserIdAsync(GetTokenByHttpContext(httpContext));
|
||||
await _aiBlacklistManager.VerifiyAiBlacklist(userId);
|
||||
await _aiGateWayManager.CreateImageForStatisticsAsync(httpContext, userId, null, input);
|
||||
@@ -83,6 +107,7 @@ public class OpenApiService : ApplicationService
|
||||
public async Task EmbeddingAsync([FromBody] ThorEmbeddingInput input, CancellationToken cancellationToken)
|
||||
{
|
||||
var httpContext = this._httpContextAccessor.HttpContext;
|
||||
Intercept(httpContext);
|
||||
var userId = await _tokenManager.GetUserIdAsync(GetTokenByHttpContext(httpContext));
|
||||
await _aiBlacklistManager.VerifiyAiBlacklist(userId);
|
||||
await _aiGateWayManager.EmbeddingForStatisticsAsync(httpContext, userId, null, input);
|
||||
@@ -114,17 +139,85 @@ public class OpenApiService : ApplicationService
|
||||
};
|
||||
}
|
||||
|
||||
|
||||
/// <summary>
|
||||
/// Anthropic对话(尊享服务专用)
|
||||
/// </summary>
|
||||
/// <param name="input"></param>
|
||||
/// <param name="cancellationToken"></param>
|
||||
[HttpPost("openApi/v1/messages")]
|
||||
public async Task MessagesAsync([FromBody] AnthropicInput input,
|
||||
CancellationToken cancellationToken)
|
||||
{
|
||||
//前面都是校验,后面才是真正的调用
|
||||
var httpContext = this._httpContextAccessor.HttpContext;
|
||||
var userId = await _tokenManager.GetUserIdAsync(GetTokenByHttpContext(httpContext));
|
||||
await _aiBlacklistManager.VerifiyAiBlacklist(userId);
|
||||
|
||||
// 验证用户是否为VIP
|
||||
var userInfo = await _accountService.GetAsync(null, null, userId);
|
||||
if (userInfo == null)
|
||||
{
|
||||
throw new UserFriendlyException("用户信息不存在");
|
||||
}
|
||||
|
||||
// 检查是否为VIP(使用RoleCodes判断)
|
||||
if (!userInfo.RoleCodes.Contains(AiHubConst.VipRole) && userInfo.User.UserName != "cc")
|
||||
{
|
||||
throw new UserFriendlyException("该接口为尊享服务专用,需要VIP权限才能使用");
|
||||
}
|
||||
|
||||
// 检查尊享token包用量
|
||||
var availableTokens = await _premiumPackageManager.GetAvailableTokensAsync(userId);
|
||||
if (availableTokens <= 0)
|
||||
{
|
||||
throw new UserFriendlyException("尊享token包用量不足,请先购买尊享token包");
|
||||
}
|
||||
|
||||
//ai网关代理httpcontext
|
||||
if (input.Stream)
|
||||
{
|
||||
await _aiGateWayManager.AnthropicCompleteChatStreamForStatisticsAsync(_httpContextAccessor.HttpContext, input,
|
||||
userId, null, cancellationToken);
|
||||
}
|
||||
else
|
||||
{
|
||||
await _aiGateWayManager.AnthropicCompleteChatForStatisticsAsync(_httpContextAccessor.HttpContext, input, userId,
|
||||
null,
|
||||
cancellationToken);
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
#region 私有
|
||||
|
||||
private string? GetTokenByHttpContext(HttpContext httpContext)
|
||||
{
|
||||
// 获取Authorization头
|
||||
string authHeader = httpContext.Request.Headers["Authorization"];
|
||||
// 优先从 x-api-key 获取
|
||||
string apiKeyHeader = httpContext.Request.Headers["x-api-key"];
|
||||
if (!string.IsNullOrWhiteSpace(apiKeyHeader))
|
||||
{
|
||||
return apiKeyHeader.Trim();
|
||||
}
|
||||
|
||||
// 检查是否有Bearer token
|
||||
if (authHeader != null && authHeader.StartsWith("Bearer "))
|
||||
// 再检查 Authorization 头
|
||||
string authHeader = httpContext.Request.Headers["Authorization"];
|
||||
if (!string.IsNullOrWhiteSpace(authHeader) && authHeader.StartsWith("Bearer ", StringComparison.OrdinalIgnoreCase))
|
||||
{
|
||||
return authHeader.Substring("Bearer ".Length).Trim();
|
||||
}
|
||||
|
||||
return null;
|
||||
}
|
||||
|
||||
private void Intercept(HttpContext httpContext)
|
||||
{
|
||||
if (httpContext.Request.Host.Value == "yxai.chat")
|
||||
{
|
||||
throw new UserFriendlyException("当前海外站点不支持大流量接口,请使用转发站点:https://ai.ccnetcore.com");
|
||||
}
|
||||
}
|
||||
|
||||
#endregion
|
||||
|
||||
}
|
||||
@@ -14,6 +14,8 @@ using Yi.Framework.AiHub.Domain.Entities.Pay;
|
||||
using Yi.Framework.SqlSugarCore.Abstractions;
|
||||
using System.ComponentModel;
|
||||
using System.Reflection;
|
||||
using Volo.Abp.Users;
|
||||
using Yi.Framework.AiHub.Application.Contracts.Dtos.Recharge;
|
||||
|
||||
namespace Yi.Framework.AiHub.Application.Services;
|
||||
|
||||
@@ -26,16 +28,23 @@ public class PayService : ApplicationService, IPayService
|
||||
private readonly PayManager _payManager;
|
||||
private readonly ILogger<PayService> _logger;
|
||||
private readonly ISqlSugarRepository<PayOrderAggregateRoot, Guid> _payOrderRepository;
|
||||
private readonly IRechargeService _rechargeService;
|
||||
private readonly PremiumPackageManager _premiumPackageManager;
|
||||
|
||||
public PayService(
|
||||
AlipayManager alipayManager,
|
||||
PayManager payManager,
|
||||
ILogger<PayService> logger, ISqlSugarRepository<PayOrderAggregateRoot, Guid> payOrderRepository)
|
||||
ILogger<PayService> logger,
|
||||
ISqlSugarRepository<PayOrderAggregateRoot, Guid> payOrderRepository,
|
||||
IRechargeService rechargeService,
|
||||
PremiumPackageManager premiumPackageManager)
|
||||
{
|
||||
_alipayManager = alipayManager;
|
||||
_payManager = payManager;
|
||||
_logger = logger;
|
||||
_payOrderRepository = payOrderRepository;
|
||||
_rechargeService = rechargeService;
|
||||
_premiumPackageManager = premiumPackageManager;
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
@@ -47,14 +56,15 @@ public class PayService : ApplicationService, IPayService
|
||||
[HttpPost("pay/Order")]
|
||||
public async Task<CreateOrderOutput> CreateOrderAsync(CreateOrderInput input)
|
||||
{
|
||||
// 1. 通过PayManager创建订单
|
||||
// 1. 通过PayManager创建订单(内部会验证VIP资格)
|
||||
var order = await _payManager.CreateOrderAsync(input.GoodsType);
|
||||
|
||||
// 2. 通过AlipayManager发起页面支付
|
||||
var paymentPageHtml = await _alipayManager.PaymentPageAsync(
|
||||
order.GoodsName,
|
||||
order.OutTradeNo,
|
||||
order.TotalAmount);
|
||||
order.TotalAmount,
|
||||
input.ReturnUrl);
|
||||
|
||||
// 3. 返回结果
|
||||
return new CreateOrderOutput
|
||||
@@ -87,9 +97,8 @@ public class PayService : ApplicationService, IPayService
|
||||
// 2. 验证签名
|
||||
await _alipayManager.VerifyNotifyAsync(notifyData);
|
||||
|
||||
|
||||
// 3. 记录支付通知
|
||||
await _payManager.RecordPayNoticeAsync(notifyData,signStr);
|
||||
await _payManager.RecordPayNoticeAsync(notifyData, signStr);
|
||||
|
||||
// 4. 更新订单状态
|
||||
var outTradeNo = notifyData.GetValueOrDefault("out_trade_no", string.Empty);
|
||||
@@ -99,9 +108,51 @@ public class PayService : ApplicationService, IPayService
|
||||
if (!string.IsNullOrEmpty(outTradeNo) && !string.IsNullOrEmpty(tradeStatus))
|
||||
{
|
||||
var status = ParseTradeStatus(tradeStatus);
|
||||
await _payManager.UpdateOrderStatusAsync(outTradeNo, status, tradeNo);
|
||||
var order = await _payManager.UpdateOrderStatusAsync(outTradeNo, status, tradeNo);
|
||||
|
||||
_logger.LogInformation("订单状态更新成功,订单号:{OutTradeNo},状态:{TradeStatus}", outTradeNo, tradeStatus);
|
||||
|
||||
// 验证交易状态,只有交易成功才执行充值逻辑
|
||||
if (status != TradeStatusEnum.TRADE_SUCCESS)
|
||||
{
|
||||
_logger.LogError($"订单 {outTradeNo} 状态为 {tradeStatus},不执行充值逻辑");
|
||||
return "success";
|
||||
}
|
||||
|
||||
// 5. 根据商品类型进行不同的处理
|
||||
if (order.GoodsType.IsPremiumPackage())
|
||||
{
|
||||
// 处理尊享包商品:创建尊享包记录
|
||||
await _premiumPackageManager.CreatePremiumPackageAsync(
|
||||
order.UserId,
|
||||
order.GoodsType,
|
||||
order.TotalAmount,
|
||||
expireMonths: null // 尊享包不设置过期时间,或者可以根据需求设置
|
||||
);
|
||||
|
||||
_logger.LogInformation(
|
||||
$"用户 {order.UserId} 购买尊享包成功,订单号:{outTradeNo},商品:{order.GoodsName}");
|
||||
}
|
||||
else if (order.GoodsType.IsVipService())
|
||||
{
|
||||
// 处理VIP服务商品:充值VIP
|
||||
await _rechargeService.RechargeVipAsync(new RechargeCreateInput
|
||||
{
|
||||
UserId = order.UserId,
|
||||
RechargeAmount = order.TotalAmount,
|
||||
Content = order.GoodsName,
|
||||
Months = order.GoodsType.GetValidMonths(),
|
||||
Remark = "自助充值",
|
||||
ContactInfo = null
|
||||
});
|
||||
|
||||
_logger.LogInformation(
|
||||
$"用户 {order.UserId} 充值VIP成功,订单号:{outTradeNo},月数:{order.GoodsType.GetValidMonths()}");
|
||||
}
|
||||
else
|
||||
{
|
||||
_logger.LogWarning($"未知的商品类型:{order.GoodsType},订单号:{outTradeNo}");
|
||||
}
|
||||
}
|
||||
else
|
||||
{
|
||||
@@ -142,6 +193,85 @@ public class PayService : ApplicationService, IPayService
|
||||
};
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// 获取商品列表
|
||||
/// </summary>
|
||||
/// <param name="input">获取商品列表输入</param>
|
||||
/// <returns>商品列表</returns>
|
||||
[HttpGet("pay/GoodsList")]
|
||||
public async Task<List<GoodsListOutput>> GetGoodsListAsync([FromQuery] GetGoodsListInput input)
|
||||
{
|
||||
var goodsList = new List<GoodsListOutput>();
|
||||
|
||||
// 获取当前用户的累加充值金额(仅已登录用户)
|
||||
decimal totalRechargeAmount = 0m;
|
||||
if (CurrentUser.IsAuthenticated)
|
||||
{
|
||||
totalRechargeAmount = await _payManager.GetUserTotalRechargeAmountAsync(CurrentUser.GetId());
|
||||
}
|
||||
|
||||
// 遍历所有商品枚举
|
||||
foreach (GoodsTypeEnum goodsType in Enum.GetValues(typeof(GoodsTypeEnum)))
|
||||
{
|
||||
// 如果指定了商品类别,则过滤
|
||||
if (input.GoodsCategoryType.HasValue)
|
||||
{
|
||||
var goodsCategory = goodsType.GetGoodsCategory();
|
||||
if (goodsCategory != input.GoodsCategoryType.Value)
|
||||
{
|
||||
continue; // 跳过不匹配的商品
|
||||
}
|
||||
}
|
||||
|
||||
var originalPrice = goodsType.GetTotalAmount();
|
||||
decimal actualPrice = originalPrice;
|
||||
decimal? discountAmount = null;
|
||||
string? discountDescription = null;
|
||||
|
||||
// 如果是尊享包商品,计算折扣
|
||||
if (goodsType.IsPremiumPackage())
|
||||
{
|
||||
|
||||
|
||||
if (CurrentUser.IsAuthenticated)
|
||||
{
|
||||
discountAmount = goodsType.CalculateDiscount(totalRechargeAmount);
|
||||
actualPrice = goodsType.GetDiscountedPrice(totalRechargeAmount);
|
||||
if (discountAmount > 0)
|
||||
{
|
||||
discountDescription = $"根据累积充值已优惠 ¥{discountAmount:F2}";
|
||||
}
|
||||
else
|
||||
{
|
||||
discountDescription = $"累积充值过低,暂无优惠";
|
||||
}
|
||||
}
|
||||
else
|
||||
{
|
||||
discountDescription = $"登录后查看优惠";
|
||||
}
|
||||
}
|
||||
|
||||
var goodsItem = new GoodsListOutput
|
||||
{
|
||||
GoodsName = goodsType.GetChineseName(),
|
||||
OriginalPrice = originalPrice,
|
||||
ReferencePrice = goodsType.GetReferencePrice(),
|
||||
GoodsPrice = actualPrice,
|
||||
GoodsCategory = goodsType.GetGoodsCategory().ToString(),
|
||||
Remark = goodsType.GetRemark(),
|
||||
DiscountAmount = discountAmount,
|
||||
DiscountDescription = discountDescription,
|
||||
GoodsType = goodsType
|
||||
};
|
||||
|
||||
goodsList.Add(goodsItem);
|
||||
}
|
||||
|
||||
return goodsList;
|
||||
}
|
||||
|
||||
|
||||
/// <summary>
|
||||
/// 获取交易状态描述
|
||||
/// </summary>
|
||||
@@ -165,6 +295,7 @@ public class PayService : ApplicationService, IPayService
|
||||
{
|
||||
return result;
|
||||
}
|
||||
|
||||
return TradeStatusEnum.WAIT_TRADE;
|
||||
}
|
||||
}
|
||||
@@ -8,12 +8,13 @@ using Yi.Framework.AiHub.Application.Contracts.IServices;
|
||||
using Yi.Framework.AiHub.Domain.Entities;
|
||||
using Yi.Framework.AiHub.Domain.Managers;
|
||||
using Yi.Framework.AiHub.Domain.Shared.Consts;
|
||||
using Yi.Framework.AiHub.Domain.Shared.Enums;
|
||||
using Yi.Framework.Rbac.Application.Contracts.IServices;
|
||||
using Yi.Framework.SqlSugarCore.Abstractions;
|
||||
|
||||
namespace Yi.Framework.AiHub.Application.Services
|
||||
{
|
||||
public class RechargeService : ApplicationService,IRechargeService
|
||||
public class RechargeService : ApplicationService, IRechargeService
|
||||
{
|
||||
private readonly ISqlSugarRepository<AiRechargeAggregateRoot> _repository;
|
||||
private readonly ICurrentUser _currentUser;
|
||||
@@ -57,15 +58,37 @@ namespace Yi.Framework.AiHub.Application.Services
|
||||
[HttpPost("recharge/vip")]
|
||||
public async Task RechargeVipAsync(RechargeCreateInput input)
|
||||
{
|
||||
DateTime? expireDateTime = null;
|
||||
|
||||
// 如果传入了月数,计算过期时间
|
||||
if (input.Months.HasValue && input.Months.Value > 0)
|
||||
{
|
||||
// 直接查询该用户最大的过期时间
|
||||
var maxExpireTime = await _repository._DbQueryable
|
||||
.Where(x => x.RechargeType == RechargeTypeEnum.Vip)
|
||||
.Where(x => x.UserId == input.UserId && x.ExpireDateTime.HasValue)
|
||||
.MaxAsync(x => x.ExpireDateTime);
|
||||
|
||||
// 如果最大过期时间大于现在时间,从最大过期时间开始计算
|
||||
// 否则从当天开始计算
|
||||
DateTime baseDateTime = maxExpireTime.HasValue && maxExpireTime.Value > DateTime.Now
|
||||
? maxExpireTime.Value
|
||||
: DateTime.Now;
|
||||
// 计算新的过期时间
|
||||
expireDateTime = baseDateTime.AddMonths(input.Months.Value);
|
||||
}
|
||||
// 如果月数为空或0,表示永久VIP,ExpireDateTime保持为null
|
||||
|
||||
// 创建充值记录
|
||||
var rechargeRecord = new AiRechargeAggregateRoot
|
||||
{
|
||||
UserId = input.UserId,
|
||||
RechargeAmount = input.RechargeAmount,
|
||||
Content = input.Content,
|
||||
ExpireDateTime = input.ExpireDateTime,
|
||||
ExpireDateTime = expireDateTime,
|
||||
Remark = input.Remark,
|
||||
ContactInfo = input.ContactInfo
|
||||
ContactInfo = input.ContactInfo,
|
||||
RechargeType = RechargeTypeEnum.Vip
|
||||
};
|
||||
|
||||
// 保存充值记录到数据库
|
||||
|
||||
@@ -1,11 +1,16 @@
|
||||
using Mapster;
|
||||
using Microsoft.AspNetCore.Authorization;
|
||||
using Microsoft.AspNetCore.Mvc;
|
||||
using SqlSugar;
|
||||
using Volo.Abp.Application.Dtos;
|
||||
using Volo.Abp.Application.Services;
|
||||
using Volo.Abp.Users;
|
||||
using Yi.Framework.AiHub.Application.Contracts.Dtos.UsageStatistics;
|
||||
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.Extensions;
|
||||
using Yi.Framework.Ddd.Application.Contracts;
|
||||
using Yi.Framework.SqlSugarCore.Abstractions;
|
||||
|
||||
namespace Yi.Framework.AiHub.Application.Services;
|
||||
@@ -18,13 +23,16 @@ public class UsageStatisticsService : ApplicationService, IUsageStatisticsServic
|
||||
{
|
||||
private readonly ISqlSugarRepository<MessageAggregateRoot> _messageRepository;
|
||||
private readonly ISqlSugarRepository<UsageStatisticsAggregateRoot> _usageStatisticsRepository;
|
||||
private readonly ISqlSugarRepository<PremiumPackageAggregateRoot> _premiumPackageRepository;
|
||||
|
||||
public UsageStatisticsService(
|
||||
ISqlSugarRepository<MessageAggregateRoot> messageRepository,
|
||||
ISqlSugarRepository<UsageStatisticsAggregateRoot> usageStatisticsRepository)
|
||||
ISqlSugarRepository<UsageStatisticsAggregateRoot> usageStatisticsRepository,
|
||||
ISqlSugarRepository<PremiumPackageAggregateRoot> premiumPackageRepository)
|
||||
{
|
||||
_messageRepository = messageRepository;
|
||||
_usageStatisticsRepository = usageStatisticsRepository;
|
||||
_premiumPackageRepository = premiumPackageRepository;
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
@@ -40,6 +48,7 @@ public class UsageStatisticsService : ApplicationService, IUsageStatisticsServic
|
||||
// 从Message表统计近7天的token消耗
|
||||
var dailyUsage = await _messageRepository._DbQueryable
|
||||
.Where(x => x.UserId == userId)
|
||||
.Where(x => x.Role == "assistant" || x.Role == "system")
|
||||
.Where(x => x.CreationTime >= startDate && x.CreationTime < endDate.AddDays(1))
|
||||
.GroupBy(x => x.CreationTime.Date)
|
||||
.Select(g => new
|
||||
@@ -102,4 +111,57 @@ public class UsageStatisticsService : ApplicationService, IUsageStatisticsServic
|
||||
|
||||
return result;
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// 获取当前用户尊享服务Token用量统计
|
||||
/// </summary>
|
||||
/// <returns>尊享服务Token用量统计</returns>
|
||||
public async Task<PremiumTokenUsageDto> GetPremiumTokenUsageAsync()
|
||||
{
|
||||
var userId = CurrentUser.GetId();
|
||||
|
||||
// 获取尊享包Token信息
|
||||
var premiumPackages = await _premiumPackageRepository._DbQueryable
|
||||
.Where(x => x.UserId == userId && x.IsActive)
|
||||
.ToListAsync();
|
||||
|
||||
var result = new PremiumTokenUsageDto();
|
||||
|
||||
if (premiumPackages.Any())
|
||||
{
|
||||
// 过滤掉已过期、禁用的包,不过滤用量负数的包
|
||||
var validPackages = premiumPackages
|
||||
.Where(p => p.IsAvailable(false))
|
||||
.ToList();
|
||||
|
||||
result.PremiumTotalTokens = validPackages.Sum(x => x.TotalTokens);
|
||||
result.PremiumUsedTokens = validPackages.Sum(x => x.UsedTokens);
|
||||
result.PremiumRemainingTokens = validPackages.Sum(x => x.RemainingTokens);
|
||||
}
|
||||
|
||||
return result;
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// 获取当前用户尊享服务token用量统计列表
|
||||
/// </summary>
|
||||
/// <returns></returns>
|
||||
[HttpGet("usage-statistics/premium-token-usage/list")]
|
||||
public async Task<PagedResultDto<PremiumTokenUsageGetListOutput>> GetPremiumTokenUsageListAsync(
|
||||
PremiumTokenUsageGetListInput input)
|
||||
{
|
||||
var userId = CurrentUser.GetId();
|
||||
RefAsync<int> total = 0;
|
||||
// 获取尊享包Token信息
|
||||
var entities = await _premiumPackageRepository._DbQueryable
|
||||
.Where(x => x.UserId == userId)
|
||||
.WhereIF(input.IsFree == false, x => x.PurchaseAmount > 0)
|
||||
.WhereIF(input.IsFree == true, x => x.PurchaseAmount == 0)
|
||||
.WhereIF(input.StartTime is not null && input.EndTime is not null,
|
||||
x => x.CreationTime >= input.StartTime && x.CreationTime <= input.EndTime)
|
||||
.OrderByDescending(x => x.CreationTime)
|
||||
.ToPageListAsync(input.SkipCount, input.MaxResultCount, total);
|
||||
return new PagedResultDto<PremiumTokenUsageGetListOutput>(total,
|
||||
entities.Adapt<List<PremiumTokenUsageGetListOutput>>());
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,7 @@
|
||||
namespace Yi.Framework.AiHub.Domain.Shared.Consts;
|
||||
|
||||
public class FuwuhaoConst
|
||||
{
|
||||
public const string SceneCacheKey = "fuwuhao:scene:";
|
||||
public const string OpenIdToSceneCacheKey = "fuwuhao:OpenIdToScene:";
|
||||
}
|
||||
@@ -0,0 +1,8 @@
|
||||
using Microsoft.AspNetCore.Mvc.ModelBinding.Metadata;
|
||||
|
||||
namespace Yi.Framework.AiHub.Domain.Shared.Consts;
|
||||
|
||||
public class PremiumPackageConst
|
||||
{
|
||||
public static List<string> ModeIds = ["claude-sonnet-4-5-20250929"];
|
||||
}
|
||||
@@ -0,0 +1,9 @@
|
||||
using System.Text.Json.Serialization;
|
||||
|
||||
namespace Yi.Framework.AiHub.Domain.Shared.Dtos.Anthropic;
|
||||
|
||||
public sealed class AnthropicCacheControl
|
||||
{
|
||||
[JsonPropertyName("type")]
|
||||
public string Type { get; set; }
|
||||
}
|
||||
@@ -0,0 +1,190 @@
|
||||
using System.Text.Json.Serialization;
|
||||
using Yi.Framework.AiHub.Domain.Shared.Dtos.OpenAi;
|
||||
|
||||
namespace Yi.Framework.AiHub.Domain.Shared.Dtos.Anthropic;
|
||||
|
||||
public class AnthropicStreamDto
|
||||
{
|
||||
[JsonPropertyName("type")] public string? Type { get; set; }
|
||||
|
||||
[JsonPropertyName("index")] public int? Index { get; set; }
|
||||
|
||||
[JsonPropertyName("content_block")] public AnthropicChatCompletionDtoContentBlock? ContentBlock { get; set; }
|
||||
|
||||
[JsonPropertyName("delta")] public AnthropicChatCompletionDtoDelta? Delta { get; set; }
|
||||
|
||||
[JsonPropertyName("message")] public AnthropicChatCompletionDto? Message { get; set; }
|
||||
|
||||
[JsonPropertyName("usage")] public AnthropicCompletionDtoUsage? Usage { get; set; }
|
||||
|
||||
[JsonPropertyName("error")] public AnthropicStreamErrorDto? Error { get; set; }
|
||||
|
||||
[JsonIgnore]
|
||||
public ThorUsageResponse TokenUsage => new ThorUsageResponse
|
||||
{
|
||||
PromptTokens = Usage?.InputTokens + Usage?.CacheCreationInputTokens + Usage?.CacheReadInputTokens,
|
||||
InputTokens = Usage?.InputTokens + Usage?.CacheCreationInputTokens + Usage?.CacheReadInputTokens,
|
||||
OutputTokens = Usage?.OutputTokens,
|
||||
InputTokensDetails = null,
|
||||
CompletionTokens = Usage?.OutputTokens,
|
||||
TotalTokens = Usage?.InputTokens + Usage?.CacheCreationInputTokens + Usage?.CacheReadInputTokens +
|
||||
Usage?.OutputTokens,
|
||||
PromptTokensDetails = null,
|
||||
CompletionTokensDetails = null
|
||||
};
|
||||
|
||||
|
||||
public void SupplementalMultiplier(double 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
|
||||
{
|
||||
[JsonPropertyName("type")] public string? Type { get; set; }
|
||||
|
||||
[JsonPropertyName("message")] public string? Message { get; set; }
|
||||
}
|
||||
|
||||
public class AnthropicChatCompletionDtoDelta
|
||||
{
|
||||
[JsonPropertyName("type")] public string? Type { get; set; }
|
||||
|
||||
[JsonPropertyName("text")] public string? Text { get; set; }
|
||||
|
||||
[JsonPropertyName("thinking")] public string? Thinking { get; set; }
|
||||
|
||||
[JsonPropertyName("partial_json")] public string? PartialJson { get; set; }
|
||||
|
||||
[JsonPropertyName("stop_reason")] public string? StopReason { get; set; }
|
||||
}
|
||||
|
||||
public class AnthropicChatCompletionDtoContentBlock
|
||||
{
|
||||
[JsonPropertyName("type")] public string? Type { get; set; }
|
||||
|
||||
[JsonPropertyName("thinking")] public string? Thinking { get; set; }
|
||||
|
||||
[JsonPropertyName("signature")] public string? Signature { get; set; }
|
||||
|
||||
[JsonPropertyName("id")] public string? Id { get; set; }
|
||||
|
||||
[JsonPropertyName("name")] public string? Name { get; set; }
|
||||
|
||||
[JsonPropertyName("input")] public object? Input { get; set; }
|
||||
|
||||
[JsonPropertyName("server_name")] public string? ServerName { get; set; }
|
||||
|
||||
[JsonPropertyName("is_error")] public bool? IsError { get; set; }
|
||||
|
||||
[JsonPropertyName("tool_use_id")] public string? ToolUseId { get; set; }
|
||||
|
||||
[JsonPropertyName("content")] public object? Content { get; set; }
|
||||
|
||||
[JsonPropertyName("text")] public string? Text { get; set; }
|
||||
}
|
||||
|
||||
public class AnthropicChatCompletionDto
|
||||
{
|
||||
public string id { get; set; }
|
||||
|
||||
public string type { get; set; }
|
||||
|
||||
public string role { get; set; }
|
||||
|
||||
public AnthropicChatCompletionDtoContent[] content { get; set; }
|
||||
|
||||
public string model { get; set; }
|
||||
|
||||
public string stop_reason { get; set; }
|
||||
|
||||
public object stop_sequence { get; set; }
|
||||
|
||||
public AnthropicCompletionDtoUsage? Usage { get; set; }
|
||||
|
||||
[JsonIgnore]
|
||||
public ThorUsageResponse TokenUsage => new ThorUsageResponse
|
||||
{
|
||||
PromptTokens = Usage?.InputTokens + Usage?.CacheCreationInputTokens + Usage?.CacheReadInputTokens,
|
||||
InputTokens = Usage?.InputTokens + Usage?.CacheCreationInputTokens + Usage?.CacheReadInputTokens,
|
||||
OutputTokens = Usage?.OutputTokens,
|
||||
InputTokensDetails = null,
|
||||
CompletionTokens = Usage?.OutputTokens,
|
||||
TotalTokens = Usage?.InputTokens + Usage?.CacheCreationInputTokens + Usage?.CacheReadInputTokens +
|
||||
Usage?.OutputTokens,
|
||||
PromptTokensDetails = null,
|
||||
CompletionTokensDetails = null
|
||||
};
|
||||
|
||||
public void SupplementalMultiplier(double 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 string type { get; set; }
|
||||
|
||||
public string? text { get; set; }
|
||||
|
||||
public string? id { get; set; }
|
||||
|
||||
public string? name { get; set; }
|
||||
|
||||
public object? input { get; set; }
|
||||
|
||||
[JsonPropertyName("thinking")] public string? Thinking { get; set; }
|
||||
|
||||
[JsonPropertyName("partial_json")] public string? PartialJson { get; set; }
|
||||
|
||||
public string? signature { get; set; }
|
||||
}
|
||||
|
||||
public class AnthropicCompletionDtoUsage
|
||||
{
|
||||
[JsonPropertyName("input_tokens")] public int? InputTokens { get; set; }
|
||||
|
||||
[JsonPropertyName("cache_creation_input_tokens")]
|
||||
public int? CacheCreationInputTokens { get; set; }
|
||||
|
||||
[JsonPropertyName("cache_read_input_tokens")]
|
||||
public int? CacheReadInputTokens { get; set; }
|
||||
|
||||
[JsonPropertyName("output_tokens")] public int? OutputTokens { get; set; }
|
||||
|
||||
[JsonPropertyName("server_tool_use")] public AnthropicServerToolUse? ServerToolUse { get; set; }
|
||||
}
|
||||
|
||||
public class AnthropicServerToolUse
|
||||
{
|
||||
[JsonPropertyName("web_search_requests")]
|
||||
public int? WebSearchRequests { get; set; }
|
||||
}
|
||||
@@ -0,0 +1,160 @@
|
||||
using System.ComponentModel.DataAnnotations;
|
||||
using System.Text.Json;
|
||||
using System.Text.Json.Serialization;
|
||||
|
||||
namespace Yi.Framework.AiHub.Domain.Shared.Dtos.Anthropic;
|
||||
|
||||
public sealed class AnthropicInput
|
||||
{
|
||||
[JsonPropertyName("stream")] public bool Stream { get; set; }
|
||||
|
||||
[JsonPropertyName("model")] public string Model { get; set; }
|
||||
|
||||
[JsonPropertyName("max_tokens")] public int? MaxTokens { get; set; }
|
||||
|
||||
[JsonPropertyName("messages")] public IList<AnthropicMessageInput> Messages { get; set; }
|
||||
|
||||
[JsonPropertyName("tools")] public IList<AnthropicMessageTool>? Tools { get; set; }
|
||||
|
||||
[JsonPropertyName("tool_choice")]
|
||||
public object? ToolChoiceCalculated
|
||||
{
|
||||
get
|
||||
{
|
||||
if (string.IsNullOrEmpty(ToolChoiceString))
|
||||
{
|
||||
return ToolChoiceString;
|
||||
}
|
||||
|
||||
if (ToolChoice?.Type == "function")
|
||||
{
|
||||
return ToolChoice;
|
||||
}
|
||||
|
||||
return ToolChoice?.Type;
|
||||
}
|
||||
set
|
||||
{
|
||||
if (value is JsonElement jsonElement)
|
||||
{
|
||||
if (jsonElement.ValueKind == JsonValueKind.String)
|
||||
{
|
||||
ToolChoiceString = jsonElement.GetString();
|
||||
}
|
||||
else if (jsonElement.ValueKind == JsonValueKind.Object)
|
||||
{
|
||||
ToolChoice = jsonElement.Deserialize<AnthropicTooChoiceInput>(ThorJsonSerializer.DefaultOptions);
|
||||
}
|
||||
}
|
||||
else
|
||||
{
|
||||
ToolChoice = (AnthropicTooChoiceInput)value;
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
[JsonIgnore] public string? ToolChoiceString { get; set; }
|
||||
|
||||
[JsonIgnore] public AnthropicTooChoiceInput? ToolChoice { get; set; }
|
||||
|
||||
[JsonIgnore] public IList<AnthropicMessageContent>? Systems { get; set; }
|
||||
|
||||
[JsonIgnore] public string? System { get; set; }
|
||||
|
||||
[JsonPropertyName("system")]
|
||||
public object? SystemCalculated
|
||||
{
|
||||
get
|
||||
{
|
||||
if (System is not null && Systems is not null)
|
||||
{
|
||||
throw new ValidationException("System 和 Systems 字段不能同时有值");
|
||||
}
|
||||
|
||||
if (System is not null)
|
||||
{
|
||||
return System;
|
||||
}
|
||||
|
||||
return Systems!;
|
||||
}
|
||||
set
|
||||
{
|
||||
if (value is JsonElement str)
|
||||
{
|
||||
if (str.ValueKind == JsonValueKind.String)
|
||||
{
|
||||
System = value?.ToString();
|
||||
}
|
||||
else if (str.ValueKind == JsonValueKind.Array)
|
||||
{
|
||||
Systems = JsonSerializer.Deserialize<IList<AnthropicMessageContent>>(value?.ToString(),
|
||||
ThorJsonSerializer.DefaultOptions);
|
||||
}
|
||||
}
|
||||
else
|
||||
{
|
||||
System = value?.ToString();
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
[JsonPropertyName("thinking")] public AnthropicThinkingInput? Thinking { get; set; }
|
||||
|
||||
[JsonPropertyName("temperature")] public double? Temperature { get; set; }
|
||||
|
||||
[JsonPropertyName("metadata")] public Dictionary<string, object>? Metadata { get; set; }
|
||||
}
|
||||
|
||||
public class AnthropicThinkingInput
|
||||
{
|
||||
[JsonPropertyName("type")] public string? Type { get; set; }
|
||||
[JsonPropertyName("budget_tokens")] public int? BudgetTokens { get; set; }
|
||||
|
||||
[JsonPropertyName("signature")] public string? Signature { get; set; }
|
||||
|
||||
[JsonPropertyName("thinking")] public string? Thinking { get; set; }
|
||||
|
||||
[JsonPropertyName("data")] public string? Data { get; set; }
|
||||
|
||||
[JsonPropertyName("text")] public string? Text { get; set; }
|
||||
}
|
||||
|
||||
public class AnthropicTooChoiceInput
|
||||
{
|
||||
[JsonPropertyName("type")] public string? Type { get; set; }
|
||||
|
||||
[JsonPropertyName("name")] public string? Name { get; set; }
|
||||
}
|
||||
|
||||
public class AnthropicMessageTool
|
||||
{
|
||||
[JsonPropertyName("name")] public string? name { get; set; }
|
||||
|
||||
[JsonPropertyName("description")] public string? Description { get; set; }
|
||||
|
||||
[JsonPropertyName("input_schema")] public Input_schema? 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; }
|
||||
}
|
||||
@@ -0,0 +1,78 @@
|
||||
using System.ComponentModel.DataAnnotations;
|
||||
using System.Text.Json;
|
||||
using System.Text.Json.Serialization;
|
||||
|
||||
namespace Yi.Framework.AiHub.Domain.Shared.Dtos.Anthropic;
|
||||
|
||||
public class AnthropicMessageContent
|
||||
{
|
||||
[JsonPropertyName("cache_control")] public AnthropicCacheControl? CacheControl { get; set; }
|
||||
|
||||
[JsonPropertyName("type")] public string Type { get; set; }
|
||||
|
||||
[JsonPropertyName("text")] public string? Text { get; set; }
|
||||
|
||||
[JsonPropertyName("tool_use_id")] public string? ToolUseId { get; set; }
|
||||
|
||||
[JsonPropertyName("name")] public string? Name { get; set; }
|
||||
|
||||
[JsonPropertyName("id")] public string? Id { get; set; }
|
||||
|
||||
[JsonPropertyName("thinking")] public string? Thinking { get; set; }
|
||||
|
||||
[JsonPropertyName("signature")] public string? Signature { get; set; }
|
||||
|
||||
[JsonPropertyName("input")] public object? Input { get; set; }
|
||||
|
||||
[JsonPropertyName("content")]
|
||||
public object? Content
|
||||
{
|
||||
get
|
||||
{
|
||||
if (_content is not null && _contents is not null)
|
||||
{
|
||||
throw new ValidationException("Messages 中 Content 和 Contents 字段不能同时有值");
|
||||
}
|
||||
|
||||
if (_content is not null)
|
||||
{
|
||||
return _content;
|
||||
}
|
||||
|
||||
return _contents;
|
||||
}
|
||||
set
|
||||
{
|
||||
if (value is JsonElement str)
|
||||
{
|
||||
if (str.ValueKind == JsonValueKind.String)
|
||||
{
|
||||
_content = value?.ToString();
|
||||
}
|
||||
else if (str.ValueKind == JsonValueKind.Array)
|
||||
{
|
||||
_contents = JsonSerializer.Deserialize<List<AnthropicMessageContent>>(value?.ToString());
|
||||
}
|
||||
}
|
||||
else
|
||||
{
|
||||
_content = value?.ToString();
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
private string? _content;
|
||||
|
||||
private List<AnthropicMessageContent>? _contents;
|
||||
|
||||
public class AnthropicMessageContentSource
|
||||
{
|
||||
[JsonPropertyName("type")] public string Type { get; set; }
|
||||
|
||||
[JsonPropertyName("media_type")] public string? MediaType { get; set; }
|
||||
|
||||
[JsonPropertyName("data")] public string? Data { get; set; }
|
||||
}
|
||||
|
||||
[JsonPropertyName("source")] public AnthropicMessageContentSource? Source { get; set; }
|
||||
}
|
||||
@@ -0,0 +1,58 @@
|
||||
using System.ComponentModel.DataAnnotations;
|
||||
using System.Text.Json;
|
||||
using System.Text.Json.Serialization;
|
||||
|
||||
namespace Yi.Framework.AiHub.Domain.Shared.Dtos.Anthropic;
|
||||
|
||||
public class AnthropicMessageInput
|
||||
{
|
||||
[JsonPropertyName("role")]
|
||||
public string Role { get; set; }
|
||||
|
||||
[JsonIgnore]
|
||||
public string? Content;
|
||||
|
||||
[JsonPropertyName("content")]
|
||||
public object? ContentCalculated
|
||||
{
|
||||
get
|
||||
{
|
||||
if (Content is not null && Contents is not null)
|
||||
{
|
||||
throw new ValidationException("Messages 中 Content 和 Contents 字段不能同时有值");
|
||||
}
|
||||
|
||||
if (!string.IsNullOrEmpty(Content))
|
||||
{
|
||||
return Content;
|
||||
}
|
||||
// 如果 Contents 为空或 null,返回空字符串而不是 null
|
||||
if (Contents == null || Contents.Count == 0)
|
||||
{
|
||||
return "_"; // 兼容客户端空值问题
|
||||
}
|
||||
return Contents!;
|
||||
}
|
||||
set
|
||||
{
|
||||
if (value is JsonElement str)
|
||||
{
|
||||
if (str.ValueKind == JsonValueKind.String)
|
||||
{
|
||||
Content = value?.ToString();
|
||||
}
|
||||
else if (str.ValueKind == JsonValueKind.Array)
|
||||
{
|
||||
Contents = JsonSerializer.Deserialize<IList<AnthropicMessageContent>>(value?.ToString(),ThorJsonSerializer.DefaultOptions);
|
||||
}
|
||||
}
|
||||
else
|
||||
{
|
||||
Content = value?.ToString();
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
[JsonIgnore]
|
||||
public IList<AnthropicMessageContent>? Contents;
|
||||
}
|
||||
@@ -0,0 +1,648 @@
|
||||
using System.Text.Json;
|
||||
using Yi.Framework.AiHub.Domain.Shared.Dtos.OpenAi;
|
||||
|
||||
namespace Yi.Framework.AiHub.Domain.Shared.Dtos.Anthropic;
|
||||
|
||||
public static class AnthropicToOpenAi
|
||||
{
|
||||
/// <summary>
|
||||
/// 将AnthropicInput转换为ThorChatCompletionsRequest
|
||||
/// </summary>
|
||||
public static ThorChatCompletionsRequest ConvertAnthropicToOpenAi(AnthropicInput anthropicInput)
|
||||
{
|
||||
var openAiRequest = new ThorChatCompletionsRequest
|
||||
{
|
||||
Model = anthropicInput.Model,
|
||||
MaxTokens = anthropicInput.MaxTokens,
|
||||
Stream = anthropicInput.Stream,
|
||||
Messages = new List<ThorChatMessage>(anthropicInput.Messages.Count)
|
||||
};
|
||||
|
||||
// high medium minimal low
|
||||
if (openAiRequest.Model.EndsWith("-high") ||
|
||||
openAiRequest.Model.EndsWith("-medium") ||
|
||||
openAiRequest.Model.EndsWith("-minimal") ||
|
||||
openAiRequest.Model.EndsWith("-low"))
|
||||
{
|
||||
openAiRequest.ReasoningEffort = openAiRequest.Model switch
|
||||
{
|
||||
var model when model.EndsWith("-high") => "high",
|
||||
var model when model.EndsWith("-medium") => "medium",
|
||||
var model when model.EndsWith("-minimal") => "minimal",
|
||||
var model when model.EndsWith("-low") => "low",
|
||||
_ => "medium"
|
||||
};
|
||||
|
||||
openAiRequest.Model = openAiRequest.Model.Replace("-high", "")
|
||||
.Replace("-medium", "")
|
||||
.Replace("-minimal", "")
|
||||
.Replace("-low", "");
|
||||
}
|
||||
|
||||
if (anthropicInput.Thinking != null &&
|
||||
anthropicInput.Thinking.Type.Equals("enabled", StringComparison.OrdinalIgnoreCase))
|
||||
{
|
||||
openAiRequest.Thinking = new ThorChatClaudeThinking()
|
||||
{
|
||||
BudgetToken = anthropicInput.Thinking.BudgetTokens,
|
||||
Type = "enabled",
|
||||
};
|
||||
openAiRequest.EnableThinking = true;
|
||||
}
|
||||
|
||||
if (openAiRequest.Model.EndsWith("-thinking"))
|
||||
{
|
||||
openAiRequest.EnableThinking = true;
|
||||
openAiRequest.Model = openAiRequest.Model.Replace("-thinking", "");
|
||||
}
|
||||
|
||||
if (openAiRequest.Stream == true)
|
||||
{
|
||||
openAiRequest.StreamOptions = new ThorStreamOptions()
|
||||
{
|
||||
IncludeUsage = true,
|
||||
};
|
||||
}
|
||||
|
||||
if (!string.IsNullOrEmpty(anthropicInput.System))
|
||||
{
|
||||
openAiRequest.Messages.Add(ThorChatMessage.CreateSystemMessage(anthropicInput.System));
|
||||
}
|
||||
|
||||
if (anthropicInput.Systems?.Count > 0)
|
||||
{
|
||||
foreach (var systemContent in anthropicInput.Systems)
|
||||
{
|
||||
openAiRequest.Messages.Add(ThorChatMessage.CreateSystemMessage(systemContent.Text ?? string.Empty));
|
||||
}
|
||||
}
|
||||
|
||||
// 处理messages
|
||||
if (anthropicInput.Messages != null)
|
||||
{
|
||||
foreach (var message in anthropicInput.Messages)
|
||||
{
|
||||
var thorMessages = ConvertAnthropicMessageToThor(message);
|
||||
// 需要过滤 空消息
|
||||
if (thorMessages.Count == 0)
|
||||
{
|
||||
continue;
|
||||
}
|
||||
|
||||
openAiRequest.Messages.AddRange(thorMessages);
|
||||
}
|
||||
|
||||
openAiRequest.Messages = openAiRequest.Messages
|
||||
.Where(m => !string.IsNullOrEmpty(m.Content) || m.Contents?.Count > 0 || m.ToolCalls?.Count > 0 ||
|
||||
!string.IsNullOrEmpty(m.ToolCallId))
|
||||
.ToList();
|
||||
}
|
||||
|
||||
// 处理tools
|
||||
if (anthropicInput.Tools is { Count: > 0 })
|
||||
{
|
||||
openAiRequest.Tools = anthropicInput.Tools.Where(x => x.name != "web_search")
|
||||
.Select(ConvertAnthropicToolToThor).ToList();
|
||||
}
|
||||
|
||||
// 判断是否存在web_search
|
||||
if (anthropicInput.Tools?.Any(x => x.name == "web_search") == true)
|
||||
{
|
||||
openAiRequest.WebSearchOptions = new ThorChatWebSearchOptions()
|
||||
{
|
||||
};
|
||||
}
|
||||
|
||||
// 处理tool_choice
|
||||
if (anthropicInput.ToolChoice != null)
|
||||
{
|
||||
openAiRequest.ToolChoice = ConvertAnthropicToolChoiceToThor(anthropicInput.ToolChoice);
|
||||
}
|
||||
|
||||
return openAiRequest;
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// 根据最后的内容块类型和OpenAI的完成原因确定Claude的停止原因
|
||||
/// </summary>
|
||||
public static string GetStopReasonByLastContentType(string? openAiFinishReason, string lastContentBlockType)
|
||||
{
|
||||
// 如果最后一个内容块是工具调用,优先返回tool_use
|
||||
if (lastContentBlockType == "tool_use")
|
||||
{
|
||||
return "tool_use";
|
||||
}
|
||||
|
||||
// 否则使用标准的转换逻辑
|
||||
return GetClaudeStopReason(openAiFinishReason);
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// 创建message_start事件
|
||||
/// </summary>
|
||||
public static AnthropicStreamDto CreateMessageStartEvent(string messageId, string model)
|
||||
{
|
||||
return new AnthropicStreamDto
|
||||
{
|
||||
Type = "message_start",
|
||||
Message = new AnthropicChatCompletionDto
|
||||
{
|
||||
id = messageId,
|
||||
type = "message",
|
||||
role = "assistant",
|
||||
model = model,
|
||||
content = new AnthropicChatCompletionDtoContent[0],
|
||||
Usage = new AnthropicCompletionDtoUsage
|
||||
{
|
||||
InputTokens = 0,
|
||||
OutputTokens = 0,
|
||||
CacheCreationInputTokens = 0,
|
||||
CacheReadInputTokens = 0
|
||||
}
|
||||
}
|
||||
};
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// 创建content_block_start事件
|
||||
/// </summary>
|
||||
public static AnthropicStreamDto CreateContentBlockStartEvent()
|
||||
{
|
||||
return new AnthropicStreamDto
|
||||
{
|
||||
Type = "content_block_start",
|
||||
Index = 0,
|
||||
ContentBlock = new AnthropicChatCompletionDtoContentBlock
|
||||
{
|
||||
Type = "text",
|
||||
Id = null,
|
||||
Name = null
|
||||
}
|
||||
};
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// 创建thinking block start事件
|
||||
/// </summary>
|
||||
public static AnthropicStreamDto CreateThinkingBlockStartEvent()
|
||||
{
|
||||
return new AnthropicStreamDto
|
||||
{
|
||||
Type = "content_block_start",
|
||||
Index = 0,
|
||||
ContentBlock = new AnthropicChatCompletionDtoContentBlock
|
||||
{
|
||||
Type = "thinking",
|
||||
Id = null,
|
||||
Name = null
|
||||
}
|
||||
};
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// 创建content_block_delta事件
|
||||
/// </summary>
|
||||
public static AnthropicStreamDto CreateContentBlockDeltaEvent(string text)
|
||||
{
|
||||
return new AnthropicStreamDto
|
||||
{
|
||||
Type = "content_block_delta",
|
||||
Index = 0,
|
||||
Delta = new AnthropicChatCompletionDtoDelta
|
||||
{
|
||||
Type = "text_delta",
|
||||
Text = text
|
||||
}
|
||||
};
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// 创建thinking delta事件
|
||||
/// </summary>
|
||||
public static AnthropicStreamDto CreateThinkingBlockDeltaEvent(string thinking)
|
||||
{
|
||||
return new AnthropicStreamDto
|
||||
{
|
||||
Type = "content_block_delta",
|
||||
Index = 0,
|
||||
Delta = new AnthropicChatCompletionDtoDelta
|
||||
{
|
||||
Type = "thinking",
|
||||
Thinking = thinking
|
||||
}
|
||||
};
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// 创建content_block_stop事件
|
||||
/// </summary>
|
||||
public static AnthropicStreamDto CreateContentBlockStopEvent()
|
||||
{
|
||||
return new AnthropicStreamDto
|
||||
{
|
||||
Type = "content_block_stop",
|
||||
Index = 0
|
||||
};
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// 创建message_delta事件
|
||||
/// </summary>
|
||||
public static AnthropicStreamDto CreateMessageDeltaEvent(string finishReason, AnthropicCompletionDtoUsage usage)
|
||||
{
|
||||
return new AnthropicStreamDto
|
||||
{
|
||||
Type = "message_delta",
|
||||
Usage = usage,
|
||||
Delta = new AnthropicChatCompletionDtoDelta
|
||||
{
|
||||
StopReason = finishReason
|
||||
}
|
||||
};
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// 创建message_stop事件
|
||||
/// </summary>
|
||||
public static AnthropicStreamDto CreateMessageStopEvent()
|
||||
{
|
||||
return new AnthropicStreamDto
|
||||
{
|
||||
Type = "message_stop"
|
||||
};
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// 创建tool block start事件
|
||||
/// </summary>
|
||||
public static AnthropicStreamDto CreateToolBlockStartEvent(string? toolId, string? toolName)
|
||||
{
|
||||
return new AnthropicStreamDto
|
||||
{
|
||||
Type = "content_block_start",
|
||||
Index = 0,
|
||||
ContentBlock = new AnthropicChatCompletionDtoContentBlock
|
||||
{
|
||||
Type = "tool_use",
|
||||
Id = toolId,
|
||||
Name = toolName
|
||||
}
|
||||
};
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// 创建tool delta事件
|
||||
/// </summary>
|
||||
public static AnthropicStreamDto CreateToolBlockDeltaEvent(string partialJson)
|
||||
{
|
||||
return new AnthropicStreamDto
|
||||
{
|
||||
Type = "content_block_delta",
|
||||
Index = 0,
|
||||
Delta = new AnthropicChatCompletionDtoDelta
|
||||
{
|
||||
Type = "input_json_delta",
|
||||
PartialJson = partialJson
|
||||
}
|
||||
};
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// 转换Anthropic消息为Thor消息列表
|
||||
/// </summary>
|
||||
public static List<ThorChatMessage> ConvertAnthropicMessageToThor(AnthropicMessageInput anthropicMessage)
|
||||
{
|
||||
var results = new List<ThorChatMessage>();
|
||||
|
||||
// 处理简单的字符串内容
|
||||
if (anthropicMessage.Content != null)
|
||||
{
|
||||
var thorMessage = new ThorChatMessage
|
||||
{
|
||||
Role = anthropicMessage.Role,
|
||||
Content = anthropicMessage.Content
|
||||
};
|
||||
results.Add(thorMessage);
|
||||
return results;
|
||||
}
|
||||
|
||||
// 处理多模态内容
|
||||
if (anthropicMessage.Contents is { Count: > 0 })
|
||||
{
|
||||
var currentContents = new List<ThorChatMessageContent>();
|
||||
var currentToolCalls = new List<ThorToolCall>();
|
||||
|
||||
foreach (var content in anthropicMessage.Contents)
|
||||
{
|
||||
switch (content.Type)
|
||||
{
|
||||
case "text":
|
||||
currentContents.Add(ThorChatMessageContent.CreateTextContent(content.Text ?? string.Empty));
|
||||
break;
|
||||
case "thinking" when !string.IsNullOrEmpty(content.Thinking):
|
||||
results.Add(new ThorChatMessage()
|
||||
{
|
||||
ReasoningContent = content.Thinking
|
||||
});
|
||||
break;
|
||||
case "image":
|
||||
{
|
||||
if (content.Source != null)
|
||||
{
|
||||
var imageUrl = content.Source.Type == "base64"
|
||||
? $"data:{content.Source.MediaType};base64,{content.Source.Data}"
|
||||
: content.Source.Data;
|
||||
currentContents.Add(ThorChatMessageContent.CreateImageUrlContent(imageUrl ?? string.Empty));
|
||||
}
|
||||
|
||||
break;
|
||||
}
|
||||
case "tool_use":
|
||||
{
|
||||
// 如果有普通内容,先创建内容消息
|
||||
if (currentContents.Count > 0)
|
||||
{
|
||||
if (currentContents.Count == 1 && currentContents.Any(x => x.Type == "text"))
|
||||
{
|
||||
var contentMessage = new ThorChatMessage
|
||||
{
|
||||
Role = anthropicMessage.Role,
|
||||
ContentCalculated = currentContents.FirstOrDefault()?.Text ?? string.Empty
|
||||
};
|
||||
results.Add(contentMessage);
|
||||
}
|
||||
else
|
||||
{
|
||||
var contentMessage = new ThorChatMessage
|
||||
{
|
||||
Role = anthropicMessage.Role,
|
||||
Contents = currentContents
|
||||
};
|
||||
results.Add(contentMessage);
|
||||
}
|
||||
|
||||
currentContents = new List<ThorChatMessageContent>();
|
||||
}
|
||||
|
||||
// 收集工具调用
|
||||
var toolCall = new ThorToolCall
|
||||
{
|
||||
Id = content.Id,
|
||||
Type = "function",
|
||||
Function = new ThorChatMessageFunction
|
||||
{
|
||||
Name = content.Name,
|
||||
Arguments = JsonSerializer.Serialize(content.Input)
|
||||
}
|
||||
};
|
||||
currentToolCalls.Add(toolCall);
|
||||
break;
|
||||
}
|
||||
case "tool_result":
|
||||
{
|
||||
// 如果有普通内容,先创建内容消息
|
||||
if (currentContents.Count > 0)
|
||||
{
|
||||
var contentMessage = new ThorChatMessage
|
||||
{
|
||||
Role = anthropicMessage.Role,
|
||||
Contents = currentContents
|
||||
};
|
||||
results.Add(contentMessage);
|
||||
currentContents = [];
|
||||
}
|
||||
|
||||
// 如果有工具调用,先创建工具调用消息
|
||||
if (currentToolCalls.Count > 0)
|
||||
{
|
||||
var toolCallMessage = new ThorChatMessage
|
||||
{
|
||||
Role = anthropicMessage.Role,
|
||||
ToolCalls = currentToolCalls
|
||||
};
|
||||
results.Add(toolCallMessage);
|
||||
currentToolCalls = new List<ThorToolCall>();
|
||||
}
|
||||
|
||||
// 创建工具结果消息
|
||||
var toolMessage = new ThorChatMessage
|
||||
{
|
||||
Role = "tool",
|
||||
ToolCallId = content.ToolUseId,
|
||||
Content = content.Content?.ToString() ?? string.Empty
|
||||
};
|
||||
results.Add(toolMessage);
|
||||
break;
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
// 处理剩余的内容
|
||||
if (currentContents.Count > 0)
|
||||
{
|
||||
var contentMessage = new ThorChatMessage
|
||||
{
|
||||
Role = anthropicMessage.Role,
|
||||
Contents = currentContents
|
||||
};
|
||||
results.Add(contentMessage);
|
||||
}
|
||||
|
||||
// 处理剩余的工具调用
|
||||
if (currentToolCalls.Count > 0)
|
||||
{
|
||||
var toolCallMessage = new ThorChatMessage
|
||||
{
|
||||
Role = anthropicMessage.Role,
|
||||
ToolCalls = currentToolCalls
|
||||
};
|
||||
results.Add(toolCallMessage);
|
||||
}
|
||||
}
|
||||
|
||||
// 如果没有任何内容,返回一个空的消息
|
||||
if (results.Count == 0)
|
||||
{
|
||||
results.Add(new ThorChatMessage
|
||||
{
|
||||
Role = anthropicMessage.Role,
|
||||
Content = string.Empty
|
||||
});
|
||||
}
|
||||
|
||||
// 如果只有一个text则使用content字段
|
||||
if (results is [{ Contents.Count: 1 }] &&
|
||||
results.FirstOrDefault()?.Contents?.FirstOrDefault()?.Type == "text" &&
|
||||
!string.IsNullOrEmpty(results.FirstOrDefault()?.Contents?.FirstOrDefault()?.Text))
|
||||
{
|
||||
return
|
||||
[
|
||||
new ThorChatMessage
|
||||
{
|
||||
Role = results[0].Role,
|
||||
Content = results.FirstOrDefault()?.Contents?.FirstOrDefault()?.Text ?? string.Empty
|
||||
}
|
||||
];
|
||||
}
|
||||
|
||||
return results;
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// 转换Anthropic工具为Thor工具
|
||||
/// </summary>
|
||||
public static ThorToolDefinition ConvertAnthropicToolToThor(AnthropicMessageTool anthropicTool)
|
||||
{
|
||||
IDictionary<string, ThorToolFunctionPropertyDefinition> values =
|
||||
new Dictionary<string, ThorToolFunctionPropertyDefinition>();
|
||||
|
||||
if (anthropicTool.InputSchema?.Properties != null)
|
||||
{
|
||||
foreach (var property in anthropicTool.InputSchema.Properties)
|
||||
{
|
||||
if (property.Value?.description != null)
|
||||
{
|
||||
var definitionType = new ThorToolFunctionPropertyDefinition()
|
||||
{
|
||||
Description = property.Value.description,
|
||||
Type = property.Value.type
|
||||
};
|
||||
if (property.Value?.items?.type != null)
|
||||
{
|
||||
definitionType.Items = new ThorToolFunctionPropertyDefinition()
|
||||
{
|
||||
Type = property.Value.items.type
|
||||
};
|
||||
}
|
||||
|
||||
values.Add(property.Key, definitionType);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
return new ThorToolDefinition
|
||||
{
|
||||
Type = "function",
|
||||
Function = new ThorToolFunctionDefinition
|
||||
{
|
||||
Name = anthropicTool.name,
|
||||
Description = anthropicTool.Description,
|
||||
Parameters = new ThorToolFunctionPropertyDefinition
|
||||
{
|
||||
Type = anthropicTool.InputSchema?.Type ?? "object",
|
||||
Properties = values,
|
||||
Required = anthropicTool.InputSchema?.Required
|
||||
}
|
||||
}
|
||||
};
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// 将OpenAI的完成原因转换为Claude的停止原因
|
||||
/// </summary>
|
||||
public static string GetClaudeStopReason(string? openAIFinishReason)
|
||||
{
|
||||
return openAIFinishReason switch
|
||||
{
|
||||
"stop" => "end_turn",
|
||||
"length" => "max_tokens",
|
||||
"tool_calls" => "tool_use",
|
||||
"content_filter" => "stop_sequence",
|
||||
_ => "end_turn"
|
||||
};
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// 将OpenAI响应转换为Claude响应格式
|
||||
/// </summary>
|
||||
public static AnthropicChatCompletionDto ConvertOpenAIToClaude(ThorChatCompletionsResponse openAIResponse,
|
||||
AnthropicInput originalRequest)
|
||||
{
|
||||
var claudeResponse = new AnthropicChatCompletionDto
|
||||
{
|
||||
id = openAIResponse.Id,
|
||||
type = "message",
|
||||
role = "assistant",
|
||||
model = openAIResponse.Model ?? originalRequest.Model,
|
||||
stop_reason = GetClaudeStopReason(openAIResponse.Choices?.FirstOrDefault()?.FinishReason),
|
||||
stop_sequence = "",
|
||||
content = []
|
||||
};
|
||||
|
||||
if (openAIResponse.Choices is { Count: > 0 })
|
||||
{
|
||||
var choice = openAIResponse.Choices.First();
|
||||
var contents = new List<AnthropicChatCompletionDtoContent>();
|
||||
|
||||
if (!string.IsNullOrEmpty(choice.Message.Content) && !string.IsNullOrEmpty(choice.Message.ReasoningContent))
|
||||
{
|
||||
contents.Add(new AnthropicChatCompletionDtoContent
|
||||
{
|
||||
type = "thinking",
|
||||
Thinking = choice.Message.ReasoningContent
|
||||
});
|
||||
|
||||
contents.Add(new AnthropicChatCompletionDtoContent
|
||||
{
|
||||
type = "text",
|
||||
text = choice.Message.Content
|
||||
});
|
||||
}
|
||||
else
|
||||
{
|
||||
// 处理思维内容
|
||||
if (!string.IsNullOrEmpty(choice.Message.ReasoningContent))
|
||||
contents.Add(new AnthropicChatCompletionDtoContent
|
||||
{
|
||||
type = "thinking",
|
||||
Thinking = choice.Message.ReasoningContent
|
||||
});
|
||||
|
||||
// 处理文本内容
|
||||
if (!string.IsNullOrEmpty(choice.Message.Content))
|
||||
contents.Add(new AnthropicChatCompletionDtoContent
|
||||
{
|
||||
type = "text",
|
||||
text = choice.Message.Content
|
||||
});
|
||||
}
|
||||
|
||||
// 处理工具调用
|
||||
if (choice.Message.ToolCalls is { Count: > 0 })
|
||||
contents.AddRange(choice.Message.ToolCalls.Select(toolCall => new AnthropicChatCompletionDtoContent
|
||||
{
|
||||
type = "tool_use", id = toolCall.Id, name = toolCall.Function?.Name,
|
||||
input = JsonSerializer.Deserialize<object>(toolCall.Function?.Arguments ?? "{}")
|
||||
}));
|
||||
|
||||
claudeResponse.content = contents.ToArray();
|
||||
}
|
||||
|
||||
// 处理使用情况统计 - 确保始终提供Usage信息
|
||||
claudeResponse.Usage = new AnthropicCompletionDtoUsage
|
||||
{
|
||||
InputTokens = openAIResponse.Usage?.PromptTokens ?? 0,
|
||||
OutputTokens = (int?)(openAIResponse.Usage?.CompletionTokens ?? 0),
|
||||
CacheCreationInputTokens = openAIResponse.Usage?.PromptTokensDetails?.CachedTokens ?? 0,
|
||||
CacheReadInputTokens = openAIResponse.Usage?.PromptTokensDetails?.CachedTokens ?? 0
|
||||
};
|
||||
|
||||
return claudeResponse;
|
||||
}
|
||||
|
||||
|
||||
/// <summary>
|
||||
/// 转换Anthropic工具选择为Thor工具选择
|
||||
/// </summary>
|
||||
public static ThorToolChoice ConvertAnthropicToolChoiceToThor(AnthropicTooChoiceInput anthropicToolChoice)
|
||||
{
|
||||
return new ThorToolChoice
|
||||
{
|
||||
Type = anthropicToolChoice.Type ?? "auto",
|
||||
Function = anthropicToolChoice.Name != null
|
||||
? new ThorToolChoiceFunctionTool { Name = anthropicToolChoice.Name }
|
||||
: null
|
||||
};
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,14 @@
|
||||
using System.Text.Json;
|
||||
using System.Text.Json.Serialization;
|
||||
|
||||
namespace Yi.Framework.AiHub.Domain.Shared.Dtos.Anthropic;
|
||||
|
||||
public static class ThorJsonSerializer
|
||||
{
|
||||
public static JsonSerializerOptions DefaultOptions => new()
|
||||
{
|
||||
PropertyNamingPolicy = JsonNamingPolicy.CamelCase,
|
||||
DefaultIgnoreCondition = JsonIgnoreCondition.WhenWritingNull,
|
||||
Encoder = System.Text.Encodings.Web.JavaScriptEncoder.UnsafeRelaxedJsonEscaping,
|
||||
};
|
||||
}
|
||||
@@ -29,63 +29,6 @@ public class ThorChatCompletionsRequest
|
||||
[JsonPropertyName("messages")]
|
||||
public List<ThorChatMessage>? Messages { get; set; }
|
||||
|
||||
/// <summary>
|
||||
/// 兼容-代码补全
|
||||
/// </summary>
|
||||
[JsonPropertyName("suffix")]
|
||||
public string? Suffix { get; set; }
|
||||
|
||||
/// <summary>
|
||||
/// 兼容-代码补全
|
||||
/// </summary>
|
||||
[JsonPropertyName("prompt")]
|
||||
public string? Prompt { get; set; }
|
||||
|
||||
private const string CodeCompletionPrompt = """
|
||||
You are a code modification assistant. Your task is to modify the provided code based on the user's instructions.
|
||||
|
||||
Rules:
|
||||
1. Return only the modified code, with no additional text or explanations.
|
||||
2. The first character of your response must be the first character of the code.
|
||||
3. The last character of your response must be the last character of the code.
|
||||
4. NEVER use triple backticks (```) or any other markdown formatting in your response.
|
||||
5. Do not use any code block indicators, syntax highlighting markers, or any other formatting characters.
|
||||
6. Present the code exactly as it would appear in a plain text editor, preserving all whitespace, indentation, and line breaks.
|
||||
7. Maintain the original code structure and only make changes as specified by the user's instructions.
|
||||
8. Ensure that the modified code is syntactically and semantically correct for the given programming language.
|
||||
9. Use consistent indentation and follow language-specific style guidelines.
|
||||
10. If the user's request cannot be translated into code changes, respond only with the word NULL (without quotes or any formatting).
|
||||
11. Do not include any comments or explanations within the code unless specifically requested.
|
||||
12. Assume that any necessary dependencies or libraries are already imported or available.
|
||||
|
||||
IMPORTANT: Your response must NEVER begin or end with triple backticks, single backticks, or any other formatting characters.
|
||||
|
||||
The relevant context before the current editing content is: {0}.
|
||||
After the current editing content is: {1}.
|
||||
""";
|
||||
|
||||
/// <summary>
|
||||
/// 兼容代码补全
|
||||
/// </summary>
|
||||
public void CompatibleCodeCompletion()
|
||||
{
|
||||
if (Messages is null || !Messages.Any())
|
||||
{
|
||||
//兼容代码补全模式,Prompt为当前代码前内容,Suffix为当前代码后内容
|
||||
Messages = new List<ThorChatMessage>()
|
||||
{
|
||||
new ThorChatMessage
|
||||
{
|
||||
Role = "system",
|
||||
Content = string.Format(CodeCompletionPrompt, Prompt, Suffix)
|
||||
}
|
||||
};
|
||||
}
|
||||
|
||||
Suffix = null;
|
||||
Prompt = null;
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// 模型唯一编码值,如 gpt-4,gpt-3.5-turbo,moonshot-v1-8k,看底层具体平台定义
|
||||
/// </summary>
|
||||
@@ -336,13 +279,10 @@ public class ThorChatCompletionsRequest
|
||||
|
||||
[JsonPropertyName("thinking")] public ThorChatClaudeThinking? Thinking { get; set; }
|
||||
|
||||
/// <summary>
|
||||
/// 参数验证
|
||||
/// </summary>
|
||||
/// <returns></returns>
|
||||
/// <exception cref="NotImplementedException"></exception>
|
||||
public IEnumerable<ValidationResult> Validate()
|
||||
{
|
||||
throw new NotImplementedException();
|
||||
}
|
||||
[JsonPropertyName("enable_thinking")] public bool? EnableThinking { get; set; }
|
||||
|
||||
[JsonPropertyName("web_search_options")]
|
||||
public ThorChatWebSearchOptions? WebSearchOptions { get; set; } = null;
|
||||
|
||||
[JsonPropertyName("reasoning_effort")] public string? ReasoningEffort { get; set; }
|
||||
}
|
||||
@@ -60,4 +60,19 @@ public record ThorChatCompletionsResponse
|
||||
/// </summary>
|
||||
[JsonPropertyName("error")]
|
||||
public ThorError? Error { get; set; }
|
||||
|
||||
public void SupplementalMultiplier(double multiplier)
|
||||
{
|
||||
if (this.Usage is not null)
|
||||
{
|
||||
this.Usage.InputTokens =
|
||||
(int)Math.Round((this.Usage.InputTokens ?? 0) * multiplier);
|
||||
this.Usage.OutputTokens =
|
||||
(int)Math.Round((this.Usage.OutputTokens ?? 0) * multiplier);
|
||||
this.Usage.CompletionTokens =
|
||||
(int)Math.Round((this.Usage.CompletionTokens ?? 0) * multiplier);
|
||||
this.Usage.PromptTokens =
|
||||
(int)Math.Round((this.Usage.PromptTokens ?? 0) * multiplier);
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -51,16 +51,17 @@ public class ThorChatMessage
|
||||
|
||||
/// <summary>
|
||||
/// 发出的消息内容计算,用于json序列号和反序列化,Content 和 Contents 不能同时赋值,只能二选一
|
||||
/// 如果是工具调用,还真可能为空
|
||||
/// </summary>
|
||||
[JsonPropertyName("content")]
|
||||
public object ContentCalculated
|
||||
public object? ContentCalculated
|
||||
{
|
||||
get
|
||||
{
|
||||
if (Content is not null && Contents is not null)
|
||||
{
|
||||
throw new ValidationException("Messages 中 Content 和 Contents 字段不能同时有值");
|
||||
}
|
||||
// if (Content is not null && Contents is not null)
|
||||
// {
|
||||
// throw new ValidationException("Messages 中 Content 和 Contents 字段不能同时有值");
|
||||
// }
|
||||
|
||||
if (Content is not null)
|
||||
{
|
||||
|
||||
@@ -0,0 +1,35 @@
|
||||
using System.Text.Json.Serialization;
|
||||
|
||||
namespace Yi.Framework.AiHub.Domain.Shared.Dtos.OpenAi;
|
||||
|
||||
public class ThorChatWebSearchOptions
|
||||
{
|
||||
[JsonPropertyName("search_context_size")]
|
||||
public string? SearchContextSize { get; set; }
|
||||
|
||||
[JsonPropertyName("user_location")]
|
||||
public ThorUserLocation? UserLocation { get; set; }
|
||||
}
|
||||
|
||||
public sealed class ThorUserLocation
|
||||
{
|
||||
[JsonPropertyName("type")] public required string Type { get; set; }
|
||||
|
||||
[JsonPropertyName("approximate")]
|
||||
public ThorUserLocationApproximate? Approximate { get; set; }
|
||||
}
|
||||
|
||||
public sealed class ThorUserLocationApproximate
|
||||
{
|
||||
[JsonPropertyName("city")]
|
||||
public string? City { get; set; }
|
||||
|
||||
[JsonPropertyName("country")]
|
||||
public string? Country { get; set; }
|
||||
|
||||
[JsonPropertyName("region")]
|
||||
public string? Region { get; set; }
|
||||
|
||||
[JsonPropertyName("timezone")]
|
||||
public string? Timezone { get; set; }
|
||||
}
|
||||
@@ -30,5 +30,5 @@ public class ThorToolFunctionDefinition
|
||||
/// documentation about the format.
|
||||
/// </summary>
|
||||
[JsonPropertyName("parameters")]
|
||||
public ThorToolFunctionPropertyDefinition Parameters { get; set; }
|
||||
public ThorToolFunctionPropertyDefinition? Parameters { get; set; }
|
||||
}
|
||||
@@ -1,4 +1,5 @@
|
||||
using System.Text.Json.Serialization;
|
||||
using System.Text.Json;
|
||||
using System.Text.Json.Serialization;
|
||||
|
||||
namespace Yi.Framework.AiHub.Domain.Shared.Dtos.OpenAi;
|
||||
|
||||
@@ -25,37 +26,77 @@ public class ThorToolFunctionPropertyDefinition
|
||||
/// 表示字符串类型的函数对象
|
||||
/// </summary>
|
||||
String,
|
||||
|
||||
/// <summary>
|
||||
/// 表示整数类型的函数对象
|
||||
/// </summary>
|
||||
Integer,
|
||||
|
||||
/// <summary>
|
||||
/// 表示数字(包括浮点数等)类型的函数对象
|
||||
/// </summary>
|
||||
Number,
|
||||
|
||||
/// <summary>
|
||||
/// 表示对象类型的函数对象
|
||||
/// </summary>
|
||||
Object,
|
||||
|
||||
/// <summary>
|
||||
/// 表示数组类型的函数对象
|
||||
/// </summary>
|
||||
Array,
|
||||
|
||||
/// <summary>
|
||||
/// 表示布尔类型的函数对象
|
||||
/// </summary>
|
||||
Boolean,
|
||||
|
||||
/// <summary>
|
||||
/// 表示空值类型的函数对象
|
||||
/// </summary>
|
||||
Null
|
||||
}
|
||||
|
||||
public string typeStr = "object";
|
||||
|
||||
public string[] Types;
|
||||
|
||||
/// <summary>
|
||||
/// 必填的。函数参数对象类型。默认值为“object”。
|
||||
/// </summary>
|
||||
[JsonPropertyName("type")]
|
||||
public string Type { get; set; } = "object";
|
||||
public object Type
|
||||
{
|
||||
get
|
||||
{
|
||||
if (Types is { Length: > 0 })
|
||||
{
|
||||
return Types;
|
||||
}
|
||||
|
||||
return typeStr;
|
||||
}
|
||||
set
|
||||
{
|
||||
if (value is JsonElement str)
|
||||
{
|
||||
switch (str.ValueKind)
|
||||
{
|
||||
case JsonValueKind.String:
|
||||
typeStr = value?.ToString();
|
||||
break;
|
||||
case JsonValueKind.Array:
|
||||
Types = JsonSerializer.Deserialize<string[]>(value?.ToString());
|
||||
break;
|
||||
}
|
||||
}
|
||||
else
|
||||
{
|
||||
typeStr = value?.ToString();
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// 可选。“函数参数”列表,作为从参数名称映射的字典
|
||||
@@ -68,13 +109,13 @@ public class ThorToolFunctionPropertyDefinition
|
||||
/// 可选。列出必需的“function arguments”列表。
|
||||
/// </summary>
|
||||
[JsonPropertyName("required")]
|
||||
public List<string>? Required { get; set; }
|
||||
public string[]? Required { get; set; }
|
||||
|
||||
/// <summary>
|
||||
/// 可选。是否允许附加属性。默认值为true。
|
||||
/// </summary>
|
||||
[JsonPropertyName("additionalProperties")]
|
||||
public bool? AdditionalProperties { get; set; }
|
||||
public object? AdditionalProperties { get; set; }
|
||||
|
||||
/// <summary>
|
||||
/// 可选。参数描述。
|
||||
@@ -219,11 +260,12 @@ public class ThorToolFunctionPropertyDefinition
|
||||
/// <param name="description"></param>
|
||||
/// <param name="enum"></param>
|
||||
/// <returns></returns>
|
||||
public static ThorToolFunctionPropertyDefinition DefineObject(IDictionary<string, ThorToolFunctionPropertyDefinition>? properties,
|
||||
List<string>? required,
|
||||
bool? additionalProperties,
|
||||
string? description,
|
||||
List<string>? @enum)
|
||||
public static ThorToolFunctionPropertyDefinition DefineObject(
|
||||
IDictionary<string, ThorToolFunctionPropertyDefinition>? properties,
|
||||
string[]? required,
|
||||
object? additionalProperties,
|
||||
string? description,
|
||||
List<string>? @enum)
|
||||
{
|
||||
return new ThorToolFunctionPropertyDefinition
|
||||
{
|
||||
@@ -242,7 +284,6 @@ public class ThorToolFunctionPropertyDefinition
|
||||
/// </summary>
|
||||
/// <param name="type">要转换的类型</param>
|
||||
/// <returns>给定类型的字符串表示形式</returns>
|
||||
|
||||
public static string ConvertTypeToString(FunctionObjectTypes type)
|
||||
{
|
||||
return type switch
|
||||
|
||||
@@ -0,0 +1,7 @@
|
||||
namespace Yi.Framework.AiHub.Domain.Shared.Enums;
|
||||
|
||||
public enum AnnouncementTypeEnum
|
||||
{
|
||||
Activity=1,
|
||||
System=2
|
||||
}
|
||||
@@ -0,0 +1,29 @@
|
||||
namespace Yi.Framework.AiHub.Domain.Shared.Enums.Fuwuhao;
|
||||
|
||||
public enum SceneResultEnum
|
||||
{
|
||||
/// <summary>
|
||||
/// 等待,用户未扫码
|
||||
/// </summary>
|
||||
Wait = 0,
|
||||
|
||||
/// <summary>
|
||||
/// 已扫码完成登录
|
||||
/// </summary>
|
||||
Login = 1,
|
||||
|
||||
/// <summary>
|
||||
/// 已扫码完成注册
|
||||
/// </summary>
|
||||
Register = 2,
|
||||
|
||||
/// <summary>
|
||||
/// 已扫码完成绑定
|
||||
/// </summary>
|
||||
Bind = 3,
|
||||
|
||||
/// <summary>
|
||||
/// 已过期
|
||||
/// </summary>
|
||||
Expired = 10
|
||||
}
|
||||
@@ -0,0 +1,7 @@
|
||||
namespace Yi.Framework.AiHub.Domain.Shared.Enums.Fuwuhao;
|
||||
|
||||
public enum SceneTypeEnum
|
||||
{
|
||||
LoginOrRegister,
|
||||
Bind
|
||||
}
|
||||
@@ -11,9 +11,15 @@ public class PriceAttribute : Attribute
|
||||
{
|
||||
public decimal Price { get; }
|
||||
|
||||
public PriceAttribute(double price)
|
||||
public decimal ReferencePrice { get; }
|
||||
|
||||
public int ValidMonths { get; }
|
||||
|
||||
public PriceAttribute(double price, int validMonths, double referencePrice)
|
||||
{
|
||||
Price = (decimal)price;
|
||||
ValidMonths = validMonths;
|
||||
ReferencePrice = (decimal)referencePrice;
|
||||
}
|
||||
}
|
||||
|
||||
@@ -24,10 +30,60 @@ public class PriceAttribute : Attribute
|
||||
public class DisplayNameAttribute : Attribute
|
||||
{
|
||||
public string DisplayName { get; }
|
||||
public string ChineseName { get; }
|
||||
public string Remark { get; }
|
||||
|
||||
public DisplayNameAttribute(string displayName)
|
||||
public DisplayNameAttribute(string displayName, string chineseName = "", string remark = "")
|
||||
{
|
||||
DisplayName = displayName;
|
||||
ChineseName = chineseName;
|
||||
Remark = remark;
|
||||
}
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// 商品类型特性
|
||||
/// 用于标识商品是VIP服务还是尊享包服务
|
||||
/// </summary>
|
||||
[AttributeUsage(AttributeTargets.Field)]
|
||||
public class GoodsCategoryAttribute : Attribute
|
||||
{
|
||||
public GoodsCategoryType Category { get; }
|
||||
|
||||
public GoodsCategoryAttribute(GoodsCategoryType category)
|
||||
{
|
||||
Category = category;
|
||||
}
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// 商品类别类型
|
||||
/// </summary>
|
||||
public enum GoodsCategoryType
|
||||
{
|
||||
/// <summary>
|
||||
/// VIP服务
|
||||
/// </summary>
|
||||
Vip = 1,
|
||||
|
||||
/// <summary>
|
||||
/// 尊享包服务
|
||||
/// </summary>
|
||||
PremiumPackage = 2
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Token数量特性
|
||||
/// 用于标识尊享包的token数量
|
||||
/// </summary>
|
||||
[AttributeUsage(AttributeTargets.Field)]
|
||||
public class TokenAmountAttribute : Attribute
|
||||
{
|
||||
public long TokenAmount { get; }
|
||||
|
||||
public TokenAmountAttribute(long tokenAmount)
|
||||
{
|
||||
TokenAmount = tokenAmount;
|
||||
}
|
||||
}
|
||||
|
||||
@@ -36,25 +92,33 @@ public class DisplayNameAttribute : Attribute
|
||||
/// </summary>
|
||||
public enum GoodsTypeEnum
|
||||
{
|
||||
[Price(0.01)]
|
||||
[DisplayName("YiXinVip Test")]
|
||||
YiXinVipTest = 0,
|
||||
|
||||
[Price(29.9)]
|
||||
[DisplayName("YiXinVip 1 month")]
|
||||
// VIP服务
|
||||
[Price(29.9, 1, 29.9)] [DisplayName("YiXinVip 1 month", "1个月", "灵活选择")] [GoodsCategory(GoodsCategoryType.Vip)]
|
||||
YiXinVip1 = 1,
|
||||
|
||||
[Price(80.7)]
|
||||
[DisplayName("YiXinVip 3 month")]
|
||||
[Price(83.7, 3, 27.9)] [DisplayName("YiXinVip 3 month", "3个月", "短期体验")] [GoodsCategory(GoodsCategoryType.Vip)]
|
||||
YiXinVip3 = 3,
|
||||
|
||||
[Price(143.9)]
|
||||
[DisplayName("YiXinVip 6 month")]
|
||||
[Price(155.4, 6, 25.9)] [DisplayName("YiXinVip 6 month", "6个月", "年度热销")] [GoodsCategory(GoodsCategoryType.Vip)]
|
||||
YiXinVip6 = 6,
|
||||
|
||||
[Price(199.9)]
|
||||
[DisplayName("YiXinVip 10 month")]
|
||||
YiXinVip10 = 10
|
||||
[Price(183.2, 8, 22.9)]
|
||||
[DisplayName("YiXinVip 8 month", "8个月(推荐)", "限时活动,超高性价比")]
|
||||
[GoodsCategory(GoodsCategoryType.Vip)]
|
||||
YiXinVip8 = 8,
|
||||
|
||||
// 尊享包服务 - 需要VIP资格才能购买
|
||||
[Price(188.9, 0, 1750)]
|
||||
[DisplayName("YiXinPremiumPackage 5000W Tokens", "5000万Tokens", "简单尝试")]
|
||||
[GoodsCategory(GoodsCategoryType.PremiumPackage)]
|
||||
[TokenAmount(50000000)]
|
||||
PremiumPackage5000W = 101,
|
||||
|
||||
[Price(248.9, 0, 3500)]
|
||||
[DisplayName("YiXinPremiumPackage 10000W Tokens", "1亿Tokens(推荐)", "极致性价比")]
|
||||
[GoodsCategory(GoodsCategoryType.PremiumPackage)]
|
||||
[TokenAmount(100000000)]
|
||||
PremiumPackage10000W = 102,
|
||||
}
|
||||
|
||||
public static class GoodsTypeEnumExtensions
|
||||
@@ -93,4 +157,146 @@ public static class GoodsTypeEnumExtensions
|
||||
var displayNameAttribute = fieldInfo?.GetCustomAttribute<DisplayNameAttribute>();
|
||||
return displayNameAttribute?.DisplayName ?? goodsType.ToString();
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// 获取商品有效月份
|
||||
/// </summary>
|
||||
/// <param name="goodsType">商品类型</param>
|
||||
/// <returns>有效月份</returns>
|
||||
public static int GetValidMonths(this GoodsTypeEnum goodsType)
|
||||
{
|
||||
var fieldInfo = goodsType.GetType().GetField(goodsType.ToString());
|
||||
var priceAttribute = fieldInfo?.GetCustomAttribute<PriceAttribute>();
|
||||
return priceAttribute?.ValidMonths ?? 1;
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// 获取商品月均价格
|
||||
/// </summary>
|
||||
/// <param name="goodsType">商品类型</param>
|
||||
/// <returns>月均价格</returns>
|
||||
public static decimal GetMonthlyPrice(this GoodsTypeEnum goodsType)
|
||||
{
|
||||
var totalPrice = goodsType.GetTotalAmount();
|
||||
var validMonths = goodsType.GetValidMonths();
|
||||
return validMonths > 0 ? totalPrice / validMonths : 0m;
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// 获取商品参考价格
|
||||
/// </summary>
|
||||
/// <param name="goodsType">商品类型</param>
|
||||
/// <returns>参考价格</returns>
|
||||
public static decimal GetReferencePrice(this GoodsTypeEnum goodsType)
|
||||
{
|
||||
var fieldInfo = goodsType.GetType().GetField(goodsType.ToString());
|
||||
var priceAttribute = fieldInfo?.GetCustomAttribute<PriceAttribute>();
|
||||
return priceAttribute?.ReferencePrice ?? 0m;
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// 获取商品类别
|
||||
/// </summary>
|
||||
/// <param name="goodsType">商品类型</param>
|
||||
/// <returns>商品类别</returns>
|
||||
public static GoodsCategoryType GetGoodsCategory(this GoodsTypeEnum goodsType)
|
||||
{
|
||||
var fieldInfo = goodsType.GetType().GetField(goodsType.ToString());
|
||||
var categoryAttribute = fieldInfo?.GetCustomAttribute<GoodsCategoryAttribute>();
|
||||
return categoryAttribute?.Category ?? GoodsCategoryType.Vip;
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// 是否为尊享包商品
|
||||
/// </summary>
|
||||
/// <param name="goodsType">商品类型</param>
|
||||
/// <returns>是否为尊享包</returns>
|
||||
public static bool IsPremiumPackage(this GoodsTypeEnum goodsType)
|
||||
{
|
||||
return goodsType.GetGoodsCategory() == GoodsCategoryType.PremiumPackage;
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// 是否为VIP服务商品
|
||||
/// </summary>
|
||||
/// <param name="goodsType">商品类型</param>
|
||||
/// <returns>是否为VIP服务</returns>
|
||||
public static bool IsVipService(this GoodsTypeEnum goodsType)
|
||||
{
|
||||
return goodsType.GetGoodsCategory() == GoodsCategoryType.Vip;
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// 获取尊享包Token数量
|
||||
/// </summary>
|
||||
/// <param name="goodsType">商品类型</param>
|
||||
/// <returns>Token数量</returns>
|
||||
public static long GetTokenAmount(this GoodsTypeEnum goodsType)
|
||||
{
|
||||
var fieldInfo = goodsType.GetType().GetField(goodsType.ToString());
|
||||
var tokenAttribute = fieldInfo?.GetCustomAttribute<TokenAmountAttribute>();
|
||||
return tokenAttribute?.TokenAmount ?? 0;
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// 获取商品中文名称
|
||||
/// </summary>
|
||||
/// <param name="goodsType">商品类型</param>
|
||||
/// <returns>中文名称</returns>
|
||||
public static string GetChineseName(this GoodsTypeEnum goodsType)
|
||||
{
|
||||
var fieldInfo = goodsType.GetType().GetField(goodsType.ToString());
|
||||
var displayNameAttribute = fieldInfo?.GetCustomAttribute<DisplayNameAttribute>();
|
||||
return displayNameAttribute?.ChineseName ?? goodsType.ToString();
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// 获取商品备注
|
||||
/// </summary>
|
||||
/// <param name="goodsType">商品类型</param>
|
||||
/// <returns>备注信息</returns>
|
||||
public static string GetRemark(this GoodsTypeEnum goodsType)
|
||||
{
|
||||
var fieldInfo = goodsType.GetType().GetField(goodsType.ToString());
|
||||
var displayNameAttribute = fieldInfo?.GetCustomAttribute<DisplayNameAttribute>();
|
||||
return displayNameAttribute?.Remark ?? string.Empty;
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// 计算折扣金额(仅用于尊享包)
|
||||
/// 规则:每累加充值10元,减少2.5元,最多减少50元
|
||||
/// </summary>
|
||||
/// <param name="goodsType">商品类型</param>
|
||||
/// <param name="totalRechargeAmount">用户累加充值金额</param>
|
||||
/// <returns>折扣金额</returns>
|
||||
public static decimal CalculateDiscount(this GoodsTypeEnum goodsType, decimal totalRechargeAmount)
|
||||
{
|
||||
// 只有尊享包才有折扣
|
||||
if (!goodsType.IsPremiumPackage())
|
||||
{
|
||||
return 0m;
|
||||
}
|
||||
|
||||
// 每10元减2.5元
|
||||
var discountAmount = Math.Floor(totalRechargeAmount / 2.5m);
|
||||
|
||||
// 最多减少50元
|
||||
return Math.Min(discountAmount, 50m);
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// 获取折扣后的价格(仅用于尊享包)
|
||||
/// </summary>
|
||||
/// <param name="goodsType">商品类型</param>
|
||||
/// <param name="totalRechargeAmount">用户累加充值金额</param>
|
||||
/// <returns>折扣后的价格</returns>
|
||||
public static decimal GetDiscountedPrice(this GoodsTypeEnum goodsType, decimal totalRechargeAmount)
|
||||
{
|
||||
var originalPrice = goodsType.GetTotalAmount();
|
||||
var discount = goodsType.CalculateDiscount(totalRechargeAmount);
|
||||
var discountedPrice = originalPrice - discount;
|
||||
|
||||
// 确保价格不为负数,至少为0.01元
|
||||
return Math.Round(discountedPrice, 2);
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,7 @@
|
||||
namespace Yi.Framework.AiHub.Domain.Shared.Enums;
|
||||
|
||||
public enum ModelApiTypeEnum
|
||||
{
|
||||
OpenAi,
|
||||
Claude
|
||||
}
|
||||
@@ -4,5 +4,6 @@ public enum ModelTypeEnum
|
||||
{
|
||||
Chat = 0,
|
||||
Image = 1,
|
||||
Embedding = 2
|
||||
Embedding = 2,
|
||||
PremiumChat = 3
|
||||
}
|
||||
@@ -0,0 +1,7 @@
|
||||
namespace Yi.Framework.AiHub.Domain.Shared.Enums;
|
||||
|
||||
public enum RechargeTypeEnum
|
||||
{
|
||||
Vip = 10,
|
||||
PremiumPackage = 20
|
||||
}
|
||||
@@ -39,6 +39,12 @@ public static class HttpClientFactory
|
||||
|
||||
private static readonly ConcurrentDictionary<string, Lazy<List<HttpClient>>> HttpClientPool = new();
|
||||
|
||||
/// <summary>
|
||||
/// 高并发下有问题
|
||||
/// </summary>
|
||||
/// <param name="key"></param>
|
||||
/// <returns></returns>
|
||||
[Obsolete]
|
||||
public static HttpClient GetHttpClient(string key)
|
||||
{
|
||||
return HttpClientPool.GetOrAdd(key, k => new Lazy<List<HttpClient>>(() =>
|
||||
|
||||
@@ -0,0 +1,29 @@
|
||||
using Yi.Framework.AiHub.Domain.Shared.Dtos;
|
||||
using Yi.Framework.AiHub.Domain.Shared.Dtos.Anthropic;
|
||||
|
||||
namespace Yi.Framework.AiHub.Domain.AiGateWay;
|
||||
|
||||
public interface IAnthropicChatCompletionService
|
||||
{
|
||||
/// <summary>
|
||||
/// 非流式对话补全
|
||||
/// </summary>
|
||||
/// <param name="request">对话补全请求参数对象</param>
|
||||
/// <param name="aiModelDescribe">平台参数对象</param>
|
||||
/// <param name="cancellationToken">取消令牌</param>
|
||||
/// <returns></returns>
|
||||
Task<AnthropicChatCompletionDto> ChatCompletionsAsync(AiModelDescribe aiModelDescribe,
|
||||
AnthropicInput request,
|
||||
CancellationToken cancellationToken = default);
|
||||
|
||||
/// <summary>
|
||||
/// 流式对话补全
|
||||
/// </summary>
|
||||
/// <param name="request">对话补全请求参数对象</param>
|
||||
/// <param name="aiModelDescribe">平台参数对象</param>
|
||||
/// <param name="cancellationToken">取消令牌</param>
|
||||
/// <returns></returns>
|
||||
IAsyncEnumerable<(string, AnthropicStreamDto?)> StreamChatCompletionsAsync(AiModelDescribe aiModelDescribe,
|
||||
AnthropicInput request,
|
||||
CancellationToken cancellationToken = default);
|
||||
}
|
||||
@@ -1,8 +1,10 @@
|
||||
using Yi.Framework.AiHub.Domain.Shared.Dtos.OpenAi;
|
||||
using Yi.Framework.AiHub.Domain.Shared.Dtos.Anthropic;
|
||||
using Yi.Framework.AiHub.Domain.Shared.Dtos.OpenAi;
|
||||
|
||||
namespace Yi.Framework.AiHub.Domain.AiGateWay;
|
||||
|
||||
public interface ISpecialCompatible
|
||||
{
|
||||
public void Compatible(ThorChatCompletionsRequest request);
|
||||
public void AnthropicCompatible(AnthropicInput request);
|
||||
}
|
||||
@@ -10,7 +10,7 @@ using Yi.Framework.AiHub.Domain.Shared.Dtos.OpenAi;
|
||||
|
||||
namespace Yi.Framework.AiHub.Domain.AiGateWay.Impl.ThorAzureDatabricks.Chats;
|
||||
|
||||
public class AzureDatabricksChatCompletionsService(ILogger<AzureDatabricksChatCompletionsService> logger)
|
||||
public class AzureDatabricksChatCompletionsService(ILogger<AzureDatabricksChatCompletionsService> logger,IHttpClientFactory httpClientFactory)
|
||||
: IChatCompletionService
|
||||
{
|
||||
private string GetAddress(AiModelDescribe? options, string model)
|
||||
@@ -31,7 +31,7 @@ public class AzureDatabricksChatCompletionsService(ILogger<AzureDatabricksChatCo
|
||||
|
||||
chatCompletionCreate.StreamOptions = null;
|
||||
|
||||
var response = await HttpClientFactory.GetHttpClient(address).HttpRequestRaw(
|
||||
var response = await httpClientFactory.CreateClient().HttpRequestRaw(
|
||||
address,
|
||||
chatCompletionCreate, options.ApiKey);
|
||||
|
||||
@@ -149,7 +149,7 @@ public class AzureDatabricksChatCompletionsService(ILogger<AzureDatabricksChatCo
|
||||
using var openai =
|
||||
Activity.Current?.Source.StartActivity("OpenAI 对话补全");
|
||||
|
||||
var response = await HttpClientFactory.GetHttpClient(address).PostJsonAsync(
|
||||
var response = await httpClientFactory.CreateClient().PostJsonAsync(
|
||||
address,
|
||||
chatCompletionCreate, options.ApiKey).ConfigureAwait(false);
|
||||
|
||||
|
||||
@@ -10,7 +10,7 @@ using Yi.Framework.AiHub.Domain.Shared.Dtos.OpenAi;
|
||||
|
||||
namespace Yi.Framework.AiHub.Domain.AiGateWay.Impl.ThorAzureOpenAI.Chats;
|
||||
|
||||
public class AzureOpenAiChatCompletionCompletionsService(ILogger<AzureOpenAiChatCompletionCompletionsService> logger)
|
||||
public class AzureOpenAiChatCompletionCompletionsService(ILogger<AzureOpenAiChatCompletionCompletionsService> logger,IHttpClientFactory httpClientFactory)
|
||||
: IChatCompletionService
|
||||
{
|
||||
public async IAsyncEnumerable<ThorChatCompletionsResponse> CompleteChatStreamAsync(AiModelDescribe options,
|
||||
@@ -21,7 +21,7 @@ public class AzureOpenAiChatCompletionCompletionsService(ILogger<AzureOpenAiChat
|
||||
Activity.Current?.Source.StartActivity("Azure OpenAI 对话流式补全");
|
||||
var url = AzureOpenAIFactory.GetAddress(options, chatCompletionCreate.Model);
|
||||
|
||||
var response = await HttpClientFactory.GetHttpClient(options.Endpoint).HttpRequestRaw(url,
|
||||
var response = await httpClientFactory.CreateClient().HttpRequestRaw(url,
|
||||
chatCompletionCreate, options.ApiKey, "Api-Key");
|
||||
|
||||
openai?.SetTag("Model", chatCompletionCreate.Model);
|
||||
@@ -86,7 +86,7 @@ public class AzureOpenAiChatCompletionCompletionsService(ILogger<AzureOpenAiChat
|
||||
var url = AzureOpenAIFactory.GetAddress(options, chatCompletionCreate.Model);
|
||||
|
||||
var response =
|
||||
await HttpClientFactory.GetHttpClient(options.Endpoint)
|
||||
await httpClientFactory.CreateClient()
|
||||
.PostJsonAsync(url, chatCompletionCreate, options.ApiKey, "Api-Key");
|
||||
|
||||
openai?.SetTag("Model", chatCompletionCreate.Model);
|
||||
|
||||
@@ -5,7 +5,7 @@ using Yi.Framework.AiHub.Domain.Shared.Dtos.OpenAi.Images;
|
||||
|
||||
namespace Yi.Framework.AiHub.Domain.AiGateWay.Impl.ThorAzureOpenAI.Images;
|
||||
|
||||
public class AzureOpenAIServiceImageService : IImageService
|
||||
public class AzureOpenAIServiceImageService(IHttpClientFactory httpClientFactory) : IImageService
|
||||
{
|
||||
public async Task<ImageCreateResponse> CreateImage(ImageCreateRequest imageCreate, AiModelDescribe? options = null,
|
||||
CancellationToken cancellationToken = default(CancellationToken))
|
||||
@@ -13,7 +13,7 @@ public class AzureOpenAIServiceImageService : IImageService
|
||||
var createClient = AzureOpenAIFactory.CreateClient(options);
|
||||
|
||||
var client = createClient.GetImageClient(imageCreate.Model);
|
||||
|
||||
imageCreate.Size??="1024x1024";
|
||||
// 将size字符串拆分为宽度和高度
|
||||
var size = imageCreate.Size.Split('x');
|
||||
if (size.Length != 2)
|
||||
@@ -98,7 +98,7 @@ public class AzureOpenAIServiceImageService : IImageService
|
||||
multipartContent.Add(new ByteArrayContent(imageEditCreateRequest.Image), "image",
|
||||
imageEditCreateRequest.ImageName);
|
||||
|
||||
return await HttpClientFactory.GetHttpClient(url).PostFileAndReadAsAsync<ImageCreateResponse>(
|
||||
return await httpClientFactory.CreateClient().PostFileAndReadAsAsync<ImageCreateResponse>(
|
||||
url,
|
||||
multipartContent, cancellationToken);
|
||||
}
|
||||
|
||||
@@ -0,0 +1,177 @@
|
||||
using System.Diagnostics;
|
||||
using System.Net;
|
||||
using System.Net.Http.Json;
|
||||
using System.Text.Json;
|
||||
using Microsoft.Extensions.Logging;
|
||||
using Yi.Framework.AiHub.Domain.Shared.Dtos;
|
||||
using Yi.Framework.AiHub.Domain.Shared.Dtos.Anthropic;
|
||||
using Yi.Framework.AiHub.Domain.Shared.Dtos.OpenAi;
|
||||
|
||||
namespace Yi.Framework.AiHub.Domain.AiGateWay.Impl.ThorClaude.Chats;
|
||||
|
||||
public class AnthropicChatCompletionsService(
|
||||
IHttpClientFactory httpClientFactory,
|
||||
ILogger<AnthropicChatCompletionsService> logger)
|
||||
: IAnthropicChatCompletionService
|
||||
{
|
||||
public const double ClaudeMultiplier = 1.3d;
|
||||
|
||||
public async Task<AnthropicChatCompletionDto> ChatCompletionsAsync(AiModelDescribe options, AnthropicInput input,
|
||||
CancellationToken cancellationToken = default)
|
||||
{
|
||||
using var openai =
|
||||
Activity.Current?.Source.StartActivity("Claudia 对话补全");
|
||||
|
||||
if (string.IsNullOrEmpty(options.Endpoint))
|
||||
{
|
||||
options.Endpoint = "https://api.anthropic.com/";
|
||||
}
|
||||
|
||||
var client = httpClientFactory.CreateClient();
|
||||
|
||||
var headers = new Dictionary<string, string>
|
||||
{
|
||||
{ "x-api-key", options.ApiKey },
|
||||
{ "authorization", "Bearer " + options.ApiKey },
|
||||
{ "anthropic-version", "2023-06-01" }
|
||||
};
|
||||
|
||||
|
||||
bool isThink = input.Model.EndsWith("-thinking");
|
||||
input.Model = input.Model.Replace("-thinking", string.Empty);
|
||||
|
||||
if (input.MaxTokens is < 2048)
|
||||
{
|
||||
input.MaxTokens = 2048;
|
||||
}
|
||||
|
||||
if (isThink && input.Thinking is null)
|
||||
{
|
||||
input.Thinking = new AnthropicThinkingInput()
|
||||
{
|
||||
Type = "enabled",
|
||||
BudgetTokens = 4000
|
||||
};
|
||||
}
|
||||
|
||||
if (input.Thinking is not null && input.Thinking.BudgetTokens > 0 && input.MaxTokens != null)
|
||||
{
|
||||
if (input.Thinking.BudgetTokens > input.MaxTokens)
|
||||
{
|
||||
input.Thinking.BudgetTokens = input.MaxTokens.Value - 1;
|
||||
if (input.Thinking.BudgetTokens > 63999)
|
||||
{
|
||||
input.Thinking.BudgetTokens = 63999;
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
var response =
|
||||
await client.PostJsonAsync(options.Endpoint.TrimEnd('/') + "/v1/messages", input, string.Empty, headers);
|
||||
|
||||
openai?.SetTag("Model", input.Model);
|
||||
openai?.SetTag("Response", response.StatusCode.ToString());
|
||||
|
||||
// 大于等于400的状态码都认为是异常
|
||||
if (response.StatusCode >= HttpStatusCode.BadRequest)
|
||||
{
|
||||
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 value =
|
||||
await response.Content.ReadFromJsonAsync<AnthropicChatCompletionDto>(ThorJsonSerializer.DefaultOptions,
|
||||
cancellationToken: cancellationToken);
|
||||
value.SupplementalMultiplier(AnthropicChatCompletionsService.ClaudeMultiplier);
|
||||
|
||||
return value;
|
||||
}
|
||||
|
||||
public async IAsyncEnumerable<(string, AnthropicStreamDto?)> StreamChatCompletionsAsync(AiModelDescribe options,
|
||||
AnthropicInput input,
|
||||
CancellationToken cancellationToken = default)
|
||||
{
|
||||
using var openai =
|
||||
Activity.Current?.Source.StartActivity("Claudia 对话补全");
|
||||
|
||||
if (string.IsNullOrEmpty(options.Endpoint))
|
||||
{
|
||||
options.Endpoint = "https://api.anthropic.com/";
|
||||
}
|
||||
|
||||
var client = httpClientFactory.CreateClient();
|
||||
|
||||
var headers = new Dictionary<string, string>
|
||||
{
|
||||
{ "x-api-key", options.ApiKey },
|
||||
{ "authorization", options.ApiKey },
|
||||
{ "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,
|
||||
headers);
|
||||
|
||||
openai?.SetTag("Model", input.Model);
|
||||
openai?.SetTag("Response", response.StatusCode.ToString());
|
||||
|
||||
// 大于等于400的状态码都认为是异常
|
||||
if (response.StatusCode >= HttpStatusCode.BadRequest)
|
||||
{
|
||||
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);
|
||||
}
|
||||
|
||||
using var stream = new StreamReader(await response.Content.ReadAsStreamAsync(cancellationToken));
|
||||
|
||||
using StreamReader reader = new(await response.Content.ReadAsStreamAsync(cancellationToken));
|
||||
string? line = string.Empty;
|
||||
|
||||
string? data = null;
|
||||
string eventType = string.Empty;
|
||||
|
||||
while ((line = await reader.ReadLineAsync(cancellationToken).ConfigureAwait(false)) != null)
|
||||
{
|
||||
line += Environment.NewLine;
|
||||
|
||||
if (line.StartsWith('{'))
|
||||
{
|
||||
logger.LogInformation("OpenAI对话异常 , StatusCode: {StatusCode} Response: {Response}", response.StatusCode,
|
||||
line);
|
||||
|
||||
throw new Exception("OpenAI对话异常" + line);
|
||||
}
|
||||
|
||||
if (string.IsNullOrWhiteSpace(line))
|
||||
{
|
||||
continue;
|
||||
}
|
||||
|
||||
if (line.StartsWith("event:"))
|
||||
{
|
||||
eventType = line;
|
||||
continue;
|
||||
}
|
||||
|
||||
if (!line.StartsWith(OpenAIConstant.Data)) continue;
|
||||
|
||||
data = line[OpenAIConstant.Data.Length..].Trim();
|
||||
|
||||
var result = JsonSerializer.Deserialize<AnthropicStreamDto>(data,
|
||||
ThorJsonSerializer.DefaultOptions);
|
||||
|
||||
result.SupplementalMultiplier(AnthropicChatCompletionsService.ClaudeMultiplier);
|
||||
yield return (eventType, result);
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,879 @@
|
||||
using System.Diagnostics;
|
||||
using System.Net;
|
||||
using System.Net.Http.Json;
|
||||
using System.Text.Json;
|
||||
using Microsoft.Extensions.Logging;
|
||||
using Yi.Framework.AiHub.Domain.Shared.Dtos;
|
||||
using Yi.Framework.AiHub.Domain.Shared.Dtos.Anthropic;
|
||||
using Yi.Framework.AiHub.Domain.Shared.Dtos.OpenAi;
|
||||
|
||||
namespace Yi.Framework.AiHub.Domain.AiGateWay.Impl.ThorClaude.Chats;
|
||||
|
||||
public sealed class ClaudiaChatCompletionsService(
|
||||
IHttpClientFactory httpClientFactory,
|
||||
ILogger<ClaudiaChatCompletionsService> logger)
|
||||
: IChatCompletionService
|
||||
{
|
||||
public List<ThorChatChoiceResponse> CreateResponse(AnthropicChatCompletionDto completionDto)
|
||||
{
|
||||
var response = new ThorChatChoiceResponse();
|
||||
var chatMessage = new ThorChatMessage();
|
||||
if (completionDto == null)
|
||||
{
|
||||
return new List<ThorChatChoiceResponse>();
|
||||
}
|
||||
|
||||
if (completionDto.content.Any(x => x.type.Equals("thinking", StringComparison.OrdinalIgnoreCase)))
|
||||
{
|
||||
// 将推理字段合并到返回对象去
|
||||
chatMessage.ReasoningContent = completionDto.content
|
||||
.First(x => x.type.Equals("thinking", StringComparison.OrdinalIgnoreCase)).Thinking;
|
||||
|
||||
chatMessage.Role = completionDto.role;
|
||||
chatMessage.Content = completionDto.content
|
||||
.First(x => x.type.Equals("text", StringComparison.OrdinalIgnoreCase)).text;
|
||||
}
|
||||
else
|
||||
{
|
||||
chatMessage.Role = completionDto.role;
|
||||
chatMessage.Content = completionDto.content
|
||||
.FirstOrDefault()?.text;
|
||||
}
|
||||
|
||||
response.Delta = chatMessage;
|
||||
response.Message = chatMessage;
|
||||
|
||||
if (completionDto.content.Any(x => x.type.Equals("tool_use", StringComparison.OrdinalIgnoreCase)))
|
||||
{
|
||||
var toolUse = completionDto.content
|
||||
.First(x => x.type.Equals("tool_use", StringComparison.OrdinalIgnoreCase));
|
||||
|
||||
chatMessage.ToolCalls =
|
||||
[
|
||||
new()
|
||||
{
|
||||
Id = toolUse.id,
|
||||
Function = new ThorChatMessageFunction()
|
||||
{
|
||||
Name = toolUse.name,
|
||||
Arguments = JsonSerializer.Serialize(toolUse.input,
|
||||
ThorJsonSerializer.DefaultOptions),
|
||||
},
|
||||
Index = 0,
|
||||
}
|
||||
];
|
||||
|
||||
return
|
||||
[
|
||||
response
|
||||
];
|
||||
}
|
||||
|
||||
return new List<ThorChatChoiceResponse> { response };
|
||||
}
|
||||
|
||||
private object CreateMessage(List<ThorChatMessage> messages, AiModelDescribe options)
|
||||
{
|
||||
var list = new List<object>();
|
||||
|
||||
foreach (var message in messages)
|
||||
{
|
||||
// 如果是图片
|
||||
if (message.ContentCalculated is IList<ThorChatMessageContent> contentCalculated)
|
||||
{
|
||||
list.Add(new
|
||||
{
|
||||
role = message.Role,
|
||||
content = (List<object>)contentCalculated.Select<ThorChatMessageContent, object>(x =>
|
||||
{
|
||||
if (x.Type == "text")
|
||||
{
|
||||
if ("true".Equals(options.ModelExtraInfo, StringComparison.OrdinalIgnoreCase))
|
||||
{
|
||||
return new
|
||||
{
|
||||
type = "text",
|
||||
text = x.Text,
|
||||
cache_control = new
|
||||
{
|
||||
type = "ephemeral"
|
||||
}
|
||||
};
|
||||
}
|
||||
|
||||
return new
|
||||
{
|
||||
type = "text",
|
||||
text = x.Text
|
||||
};
|
||||
}
|
||||
|
||||
var isBase64 = x.ImageUrl?.Url.StartsWith("http") == true;
|
||||
|
||||
if ("true".Equals(options.ModelExtraInfo, StringComparison.OrdinalIgnoreCase))
|
||||
{
|
||||
return new
|
||||
{
|
||||
type = "image",
|
||||
source = new
|
||||
{
|
||||
type = isBase64 ? "base64" : "url",
|
||||
media_type = "image/png",
|
||||
data = x.ImageUrl?.Url,
|
||||
},
|
||||
cache_control = new
|
||||
{
|
||||
type = "ephemeral"
|
||||
}
|
||||
};
|
||||
}
|
||||
|
||||
return new
|
||||
{
|
||||
type = "image",
|
||||
source = new
|
||||
{
|
||||
type = isBase64 ? "base64" : "url",
|
||||
media_type = "image/png",
|
||||
data = x.ImageUrl?.Url,
|
||||
}
|
||||
};
|
||||
})
|
||||
});
|
||||
}
|
||||
else
|
||||
{
|
||||
if ("true".Equals(options.ModelExtraInfo, StringComparison.OrdinalIgnoreCase))
|
||||
{
|
||||
if (message.Role == "system")
|
||||
{
|
||||
list.Add(new
|
||||
{
|
||||
type = "text",
|
||||
text = message.Content,
|
||||
cache_control = new
|
||||
{
|
||||
type = "ephemeral"
|
||||
}
|
||||
});
|
||||
}
|
||||
else
|
||||
{
|
||||
list.Add(new
|
||||
{
|
||||
role = message.Role,
|
||||
content = message.Content
|
||||
});
|
||||
}
|
||||
}
|
||||
else
|
||||
{
|
||||
if (message.Role == "system")
|
||||
{
|
||||
list.Add(new
|
||||
{
|
||||
type = "text",
|
||||
text = message.Content
|
||||
});
|
||||
}
|
||||
else if (message.Role == "tool")
|
||||
{
|
||||
list.Add(new
|
||||
{
|
||||
role = "user",
|
||||
content = new List<object>
|
||||
{
|
||||
new
|
||||
{
|
||||
type = "tool_result",
|
||||
tool_use_id = message.ToolCallId,
|
||||
content = message.Content
|
||||
}
|
||||
}
|
||||
});
|
||||
}
|
||||
else if (message.Role == "assistant")
|
||||
{
|
||||
// {
|
||||
// "role": "assistant",
|
||||
// "content": [
|
||||
// {
|
||||
// "type": "text",
|
||||
// "text": "<thinking>I need to use get_weather, and the user wants SF, which is likely San Francisco, CA.</thinking>"
|
||||
// },
|
||||
// {
|
||||
// "type": "tool_use",
|
||||
// "id": "toolu_01A09q90qw90lq917835lq9",
|
||||
// "name": "get_weather",
|
||||
// "input": {
|
||||
// "location": "San Francisco, CA",
|
||||
// "unit": "celsius"
|
||||
// }
|
||||
// }
|
||||
// ]
|
||||
// },
|
||||
if (message.ToolCalls?.Count > 0)
|
||||
{
|
||||
var content = new List<object>();
|
||||
if (!string.IsNullOrEmpty(message.Content))
|
||||
{
|
||||
content.Add(new
|
||||
{
|
||||
type = "text",
|
||||
text = message.Content
|
||||
});
|
||||
}
|
||||
|
||||
foreach (var toolCall in message.ToolCalls)
|
||||
{
|
||||
content.Add(new
|
||||
{
|
||||
type = "tool_use",
|
||||
id = toolCall.Id,
|
||||
name = toolCall.Function?.Name,
|
||||
input = JsonSerializer.Deserialize<Dictionary<string, object>>(
|
||||
toolCall.Function?.Arguments, ThorJsonSerializer.DefaultOptions)
|
||||
});
|
||||
}
|
||||
|
||||
list.Add(new
|
||||
{
|
||||
role = "assistant",
|
||||
content
|
||||
});
|
||||
}
|
||||
else
|
||||
{
|
||||
list.Add(new
|
||||
{
|
||||
role = "assistant",
|
||||
content = new List<object>
|
||||
{
|
||||
new
|
||||
{
|
||||
type = "text",
|
||||
text = message.Content
|
||||
}
|
||||
}
|
||||
});
|
||||
}
|
||||
}
|
||||
else
|
||||
{
|
||||
list.Add(new
|
||||
{
|
||||
role = message.Role,
|
||||
content = message.Content
|
||||
});
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
return list;
|
||||
}
|
||||
|
||||
|
||||
public async IAsyncEnumerable<ThorChatCompletionsResponse> CompleteChatStreamAsync(AiModelDescribe options,
|
||||
ThorChatCompletionsRequest input,
|
||||
CancellationToken cancellationToken)
|
||||
{
|
||||
using var openai =
|
||||
Activity.Current?.Source.StartActivity("Claudia 对话补全");
|
||||
|
||||
if (string.IsNullOrEmpty(options.Endpoint))
|
||||
{
|
||||
options.Endpoint = "https://api.anthropic.com/";
|
||||
}
|
||||
|
||||
var client = httpClientFactory.CreateClient();
|
||||
|
||||
var headers = new Dictionary<string, string>
|
||||
{
|
||||
{ "x-api-key", options.ApiKey },
|
||||
{ "anthropic-version", "2023-06-01" }
|
||||
};
|
||||
|
||||
var isThinking = input.Model.EndsWith("thinking");
|
||||
input.Model = input.Model.Replace("-thinking", string.Empty);
|
||||
var budgetTokens = 1024;
|
||||
|
||||
if (input.MaxTokens is < 2048)
|
||||
{
|
||||
input.MaxTokens = 2048;
|
||||
}
|
||||
|
||||
if (input.MaxTokens != null && input.MaxTokens / 2 < 1024)
|
||||
{
|
||||
budgetTokens = input.MaxTokens.Value / (4 * 3);
|
||||
}
|
||||
|
||||
// budgetTokens最大4096
|
||||
budgetTokens = Math.Min(budgetTokens, 4096);
|
||||
|
||||
object tool_choice;
|
||||
if (input.ToolChoice is not null && input.ToolChoice.Type == "auto")
|
||||
{
|
||||
tool_choice = new
|
||||
{
|
||||
type = "auto",
|
||||
disable_parallel_tool_use = false,
|
||||
};
|
||||
}
|
||||
else if (input.ToolChoice is not null && input.ToolChoice.Type == "any")
|
||||
{
|
||||
tool_choice = new
|
||||
{
|
||||
type = "any",
|
||||
disable_parallel_tool_use = false,
|
||||
};
|
||||
}
|
||||
else if (input.ToolChoice is not null && input.ToolChoice.Type == "tool")
|
||||
{
|
||||
tool_choice = new
|
||||
{
|
||||
type = "tool",
|
||||
name = input.ToolChoice.Function?.Name,
|
||||
disable_parallel_tool_use = false,
|
||||
};
|
||||
}
|
||||
else
|
||||
{
|
||||
tool_choice = null;
|
||||
}
|
||||
|
||||
var response = await client.HttpRequestRaw(options.Endpoint.TrimEnd('/') + "/v1/messages", new
|
||||
{
|
||||
model = input.Model,
|
||||
max_tokens = input.MaxTokens ?? 2048,
|
||||
stream = true,
|
||||
tool_choice,
|
||||
system = CreateMessage(input.Messages.Where(x => x.Role == "system").ToList(), options),
|
||||
messages = CreateMessage(input.Messages.Where(x => x.Role != "system").ToList(), options),
|
||||
top_p = isThinking ? null : input.TopP,
|
||||
thinking = isThinking
|
||||
? new
|
||||
{
|
||||
type = "enabled",
|
||||
budget_tokens = budgetTokens,
|
||||
}
|
||||
: null,
|
||||
tools = input.Tools?.Select(x => new
|
||||
{
|
||||
name = x.Function?.Name,
|
||||
description = x.Function?.Description,
|
||||
input_schema = new
|
||||
{
|
||||
type = x.Function?.Parameters?.Type,
|
||||
required = x.Function?.Parameters?.Required,
|
||||
properties = x.Function?.Parameters?.Properties?.ToDictionary(y => y.Key, y => new
|
||||
{
|
||||
description = y.Value.Description,
|
||||
type = y.Value.Type,
|
||||
@enum = y.Value.Enum
|
||||
})
|
||||
}
|
||||
}).ToArray(),
|
||||
temperature = isThinking ? null : input.Temperature
|
||||
}, string.Empty, headers);
|
||||
|
||||
openai?.SetTag("Model", input.Model);
|
||||
openai?.SetTag("Response", response.StatusCode.ToString());
|
||||
|
||||
// 大于等于400的状态码都认为是异常
|
||||
if (response.StatusCode >= HttpStatusCode.BadRequest)
|
||||
{
|
||||
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);
|
||||
}
|
||||
|
||||
using var stream = new StreamReader(await response.Content.ReadAsStreamAsync(cancellationToken));
|
||||
|
||||
using StreamReader reader = new(await response.Content.ReadAsStreamAsync(cancellationToken));
|
||||
string? line = string.Empty;
|
||||
var first = true;
|
||||
var isThink = false;
|
||||
|
||||
string? toolId = null;
|
||||
string? toolName = null;
|
||||
while ((line = await reader.ReadLineAsync(cancellationToken).ConfigureAwait(false)) != null)
|
||||
{
|
||||
line += Environment.NewLine;
|
||||
|
||||
if (line.StartsWith('{'))
|
||||
{
|
||||
logger.LogInformation("OpenAI对话异常 , StatusCode: {StatusCode} Response: {Response}", response.StatusCode,
|
||||
line);
|
||||
|
||||
throw new Exception("OpenAI对话异常" + line);
|
||||
}
|
||||
|
||||
if (line.StartsWith(OpenAIConstant.Data))
|
||||
line = line[OpenAIConstant.Data.Length..];
|
||||
|
||||
line = line.Trim();
|
||||
|
||||
if (string.IsNullOrWhiteSpace(line)) continue;
|
||||
|
||||
if (line == OpenAIConstant.Done)
|
||||
{
|
||||
break;
|
||||
}
|
||||
|
||||
if (line.StartsWith(':'))
|
||||
{
|
||||
continue;
|
||||
}
|
||||
|
||||
if (line.StartsWith("event: ", StringComparison.OrdinalIgnoreCase))
|
||||
{
|
||||
continue;
|
||||
}
|
||||
|
||||
var result = JsonSerializer.Deserialize<AnthropicStreamDto>(line,
|
||||
ThorJsonSerializer.DefaultOptions);
|
||||
|
||||
if (result?.Type == "content_block_delta")
|
||||
{
|
||||
if (result.Delta.Type is "text" or "text_delta")
|
||||
{
|
||||
yield return new ThorChatCompletionsResponse()
|
||||
{
|
||||
Choices =
|
||||
[
|
||||
new()
|
||||
{
|
||||
Message = new ThorChatMessage()
|
||||
{
|
||||
Content = result.Delta.Text,
|
||||
Role = "assistant",
|
||||
}
|
||||
}
|
||||
],
|
||||
Model = input.Model,
|
||||
Id = result?.Message?.id,
|
||||
Usage = new ThorUsageResponse()
|
||||
{
|
||||
CompletionTokens = result?.Message?.Usage?.OutputTokens,
|
||||
PromptTokens = result?.Message?.Usage?.InputTokens,
|
||||
}
|
||||
};
|
||||
}
|
||||
else if (result.Delta.Type == "input_json_delta")
|
||||
{
|
||||
yield return new ThorChatCompletionsResponse()
|
||||
{
|
||||
Choices =
|
||||
[
|
||||
new ThorChatChoiceResponse()
|
||||
{
|
||||
Message = new ThorChatMessage()
|
||||
{
|
||||
ToolCalls =
|
||||
[
|
||||
new ThorToolCall()
|
||||
{
|
||||
Id = toolId,
|
||||
Function = new ThorChatMessageFunction()
|
||||
{
|
||||
Name = toolName,
|
||||
Arguments = result.Delta.PartialJson
|
||||
}
|
||||
}
|
||||
],
|
||||
Role = "tool",
|
||||
}
|
||||
}
|
||||
],
|
||||
Model = input.Model,
|
||||
Usage = new ThorUsageResponse()
|
||||
{
|
||||
PromptTokens = result?.Message?.Usage?.InputTokens,
|
||||
}
|
||||
};
|
||||
}
|
||||
else
|
||||
{
|
||||
yield return new ThorChatCompletionsResponse()
|
||||
{
|
||||
Choices = new List<ThorChatChoiceResponse>()
|
||||
{
|
||||
new()
|
||||
{
|
||||
Message = new ThorChatMessage()
|
||||
{
|
||||
ReasoningContent = result.Delta.Thinking,
|
||||
Role = "assistant",
|
||||
}
|
||||
}
|
||||
},
|
||||
Model = input.Model,
|
||||
Id = result?.Message?.id,
|
||||
Usage = new ThorUsageResponse()
|
||||
{
|
||||
CompletionTokens = result?.Message?.Usage?.OutputTokens,
|
||||
PromptTokens = result?.Message?.Usage?.InputTokens
|
||||
}
|
||||
};
|
||||
}
|
||||
|
||||
continue;
|
||||
}
|
||||
|
||||
if (result?.Type == "content_block_start")
|
||||
{
|
||||
if (result?.ContentBlock?.Id is not null)
|
||||
{
|
||||
toolId = result.ContentBlock.Id;
|
||||
}
|
||||
|
||||
if (result?.ContentBlock?.Name is not null)
|
||||
{
|
||||
toolName = result.ContentBlock.Name;
|
||||
}
|
||||
|
||||
if (toolId is null)
|
||||
{
|
||||
continue;
|
||||
}
|
||||
|
||||
yield return new ThorChatCompletionsResponse()
|
||||
{
|
||||
Choices =
|
||||
[
|
||||
new ThorChatChoiceResponse()
|
||||
{
|
||||
Message = new ThorChatMessage()
|
||||
{
|
||||
ToolCalls =
|
||||
[
|
||||
new ThorToolCall()
|
||||
{
|
||||
Id = toolId,
|
||||
Function = new ThorChatMessageFunction()
|
||||
{
|
||||
Name = toolName
|
||||
}
|
||||
}
|
||||
],
|
||||
Role = "tool",
|
||||
}
|
||||
}
|
||||
],
|
||||
Model = input.Model,
|
||||
Usage = new ThorUsageResponse()
|
||||
{
|
||||
PromptTokens = result?.Message?.Usage?.InputTokens,
|
||||
}
|
||||
};
|
||||
}
|
||||
|
||||
if (result.Type == "content_block_delta")
|
||||
{
|
||||
yield return new ThorChatCompletionsResponse()
|
||||
{
|
||||
Choices =
|
||||
[
|
||||
new ThorChatChoiceResponse()
|
||||
{
|
||||
Message = new ThorChatMessage()
|
||||
{
|
||||
ToolCallId = result?.ContentBlock?.Id,
|
||||
FunctionCall = new ThorChatMessageFunction()
|
||||
{
|
||||
Name = result?.ContentBlock?.Name,
|
||||
Arguments = result?.Delta?.PartialJson
|
||||
},
|
||||
Role = "tool",
|
||||
}
|
||||
}
|
||||
],
|
||||
Model = input.Model,
|
||||
Usage = new ThorUsageResponse()
|
||||
{
|
||||
PromptTokens = result?.Message?.Usage?.InputTokens
|
||||
}
|
||||
};
|
||||
continue;
|
||||
}
|
||||
|
||||
if (result.Type == "message_start")
|
||||
{
|
||||
yield return new ThorChatCompletionsResponse()
|
||||
{
|
||||
Choices =
|
||||
[
|
||||
new ThorChatChoiceResponse()
|
||||
{
|
||||
Message = new ThorChatMessage()
|
||||
{
|
||||
Content = result?.Delta?.Text,
|
||||
Role = "assistant",
|
||||
}
|
||||
}
|
||||
],
|
||||
Model = input.Model,
|
||||
Usage = new ThorUsageResponse()
|
||||
{
|
||||
PromptTokens = result?.Message?.Usage?.InputTokens,
|
||||
}
|
||||
};
|
||||
|
||||
continue;
|
||||
}
|
||||
|
||||
if (result.Type == "message_delta")
|
||||
{
|
||||
var deltaOutput = new ThorChatCompletionsResponse()
|
||||
{
|
||||
Choices =
|
||||
[
|
||||
new ThorChatChoiceResponse()
|
||||
{
|
||||
Message = new ThorChatMessage()
|
||||
{
|
||||
Content = result.Delta?.Text,
|
||||
Role = "assistant",
|
||||
}
|
||||
}
|
||||
],
|
||||
Model = input.Model,
|
||||
Usage = new ThorUsageResponse
|
||||
{
|
||||
InputTokens = result.Usage?.InputTokens + result.Usage?.CacheCreationInputTokens +
|
||||
result.Usage?.CacheReadInputTokens,
|
||||
OutputTokens = result.Usage?.OutputTokens,
|
||||
}
|
||||
};
|
||||
|
||||
|
||||
deltaOutput.Usage.PromptTokens = deltaOutput.Usage.InputTokens;
|
||||
deltaOutput.Usage.CompletionTokens = deltaOutput.Usage.OutputTokens;
|
||||
|
||||
deltaOutput.Usage.TotalTokens = deltaOutput.Usage.InputTokens + deltaOutput.Usage.OutputTokens;
|
||||
|
||||
yield return deltaOutput;
|
||||
|
||||
continue;
|
||||
}
|
||||
|
||||
if (result.Message == null)
|
||||
{
|
||||
continue;
|
||||
}
|
||||
|
||||
var chat = CreateResponse(result.Message);
|
||||
|
||||
var content = chat?.FirstOrDefault()?.Delta;
|
||||
|
||||
if (first && string.IsNullOrWhiteSpace(content?.Content) && string.IsNullOrEmpty(content?.ReasoningContent))
|
||||
{
|
||||
continue;
|
||||
}
|
||||
|
||||
if (first && content.Content == OpenAIConstant.ThinkStart)
|
||||
{
|
||||
isThink = true;
|
||||
continue;
|
||||
// 需要将content的内容转换到其他字段
|
||||
}
|
||||
|
||||
if (isThink && content.Content.Contains(OpenAIConstant.ThinkEnd))
|
||||
{
|
||||
isThink = false;
|
||||
// 需要将content的内容转换到其他字段
|
||||
continue;
|
||||
}
|
||||
|
||||
if (isThink)
|
||||
{
|
||||
// 需要将content的内容转换到其他字段
|
||||
foreach (var choice in chat)
|
||||
{
|
||||
choice.Delta.ReasoningContent = choice.Delta.Content;
|
||||
choice.Delta.Content = string.Empty;
|
||||
}
|
||||
}
|
||||
|
||||
first = false;
|
||||
|
||||
var output = new ThorChatCompletionsResponse()
|
||||
{
|
||||
Choices = chat,
|
||||
Model = input.Model,
|
||||
Id = result.Message.id,
|
||||
Usage = new ThorUsageResponse()
|
||||
{
|
||||
InputTokens = result.Message.Usage?.InputTokens + result.Message.Usage?.CacheCreationInputTokens +
|
||||
result.Message.Usage?.CacheReadInputTokens,
|
||||
OutputTokens = result.Message.Usage?.OutputTokens,
|
||||
}
|
||||
};
|
||||
output.Usage.PromptTokens = output.Usage.InputTokens;
|
||||
output.Usage.CompletionTokens = output.Usage.OutputTokens;
|
||||
output.Usage.TotalTokens = output.Usage.InputTokens + output.Usage.OutputTokens;
|
||||
output.SupplementalMultiplier(AnthropicChatCompletionsService.ClaudeMultiplier);
|
||||
yield return output;
|
||||
}
|
||||
}
|
||||
|
||||
public async Task<ThorChatCompletionsResponse> CompleteChatAsync(AiModelDescribe options,
|
||||
ThorChatCompletionsRequest input,
|
||||
CancellationToken cancellationToken)
|
||||
{
|
||||
using var openai =
|
||||
Activity.Current?.Source.StartActivity("Claudia 对话补全");
|
||||
|
||||
if (string.IsNullOrEmpty(options.Endpoint))
|
||||
{
|
||||
options.Endpoint = "https://api.anthropic.com/";
|
||||
}
|
||||
|
||||
var client = httpClientFactory.CreateClient();
|
||||
|
||||
var headers = new Dictionary<string, string>
|
||||
{
|
||||
{ "x-api-key", options.ApiKey },
|
||||
{ "anthropic-version", "2023-06-01" }
|
||||
};
|
||||
|
||||
bool isThink = input.Model.EndsWith("-thinking");
|
||||
input.Model = input.Model.Replace("-thinking", string.Empty);
|
||||
|
||||
var budgetTokens = 1024;
|
||||
if (input.MaxTokens is < 2048)
|
||||
{
|
||||
input.MaxTokens = 2048;
|
||||
}
|
||||
|
||||
if (input.MaxTokens != null && input.MaxTokens / 2 < 1024)
|
||||
{
|
||||
budgetTokens = input.MaxTokens.Value / (4 * 3);
|
||||
}
|
||||
|
||||
object tool_choice;
|
||||
if (input.ToolChoice is not null && input.ToolChoice.Type == "auto")
|
||||
{
|
||||
tool_choice = new
|
||||
{
|
||||
type = "auto",
|
||||
disable_parallel_tool_use = false,
|
||||
};
|
||||
}
|
||||
else if (input.ToolChoice is not null && input.ToolChoice.Type == "any")
|
||||
{
|
||||
tool_choice = new
|
||||
{
|
||||
type = "any",
|
||||
disable_parallel_tool_use = false,
|
||||
};
|
||||
}
|
||||
else if (input.ToolChoice is not null && input.ToolChoice.Type == "tool")
|
||||
{
|
||||
tool_choice = new
|
||||
{
|
||||
type = "tool",
|
||||
name = input.ToolChoice.Function?.Name,
|
||||
disable_parallel_tool_use = false,
|
||||
};
|
||||
}
|
||||
else
|
||||
{
|
||||
tool_choice = null;
|
||||
}
|
||||
|
||||
// budgetTokens最大4096
|
||||
budgetTokens = Math.Min(budgetTokens, 4096);
|
||||
|
||||
var response = await client.PostJsonAsync(options.Endpoint.TrimEnd('/') + "/v1/messages", new
|
||||
{
|
||||
model = input.Model,
|
||||
max_tokens = input.MaxTokens ?? 2000,
|
||||
system = CreateMessage(input.Messages.Where(x => x.Role == "system").ToList(), options),
|
||||
messages = CreateMessage(input.Messages.Where(x => x.Role != "system").ToList(), options),
|
||||
top_p = isThink ? null : input.TopP,
|
||||
tool_choice,
|
||||
thinking = isThink
|
||||
? new
|
||||
{
|
||||
type = "enabled",
|
||||
budget_tokens = budgetTokens,
|
||||
}
|
||||
: null,
|
||||
tools = input.Tools?.Select(x => new
|
||||
{
|
||||
name = x.Function?.Name,
|
||||
description = x.Function?.Description,
|
||||
input_schema = new
|
||||
{
|
||||
type = x.Function?.Parameters?.Type,
|
||||
required = x.Function?.Parameters?.Required,
|
||||
properties = x.Function?.Parameters?.Properties?.ToDictionary(y => y.Key, y => new
|
||||
{
|
||||
description = y.Value.Description,
|
||||
type = y.Value.Type,
|
||||
@enum = y.Value.Enum
|
||||
})
|
||||
}
|
||||
}).ToArray(),
|
||||
temperature = isThink ? null : input.Temperature
|
||||
}, string.Empty, headers);
|
||||
|
||||
openai?.SetTag("Model", input.Model);
|
||||
openai?.SetTag("Response", response.StatusCode.ToString());
|
||||
|
||||
// 大于等于400的状态码都认为是异常
|
||||
if (response.StatusCode >= HttpStatusCode.BadRequest)
|
||||
{
|
||||
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.ToString());
|
||||
}
|
||||
|
||||
var value =
|
||||
await response.Content.ReadFromJsonAsync<AnthropicChatCompletionDto>(ThorJsonSerializer.DefaultOptions,
|
||||
cancellationToken: cancellationToken);
|
||||
|
||||
var thor = new ThorChatCompletionsResponse()
|
||||
{
|
||||
Choices = CreateResponse(value),
|
||||
Model = input.Model,
|
||||
Id = value.id,
|
||||
Usage = new ThorUsageResponse()
|
||||
{
|
||||
CompletionTokens = value.Usage.OutputTokens,
|
||||
PromptTokens = value.Usage.InputTokens
|
||||
}
|
||||
};
|
||||
|
||||
if (value.Usage.CacheReadInputTokens != null)
|
||||
{
|
||||
thor.Usage.PromptTokensDetails ??= new ThorUsageResponsePromptTokensDetails()
|
||||
{
|
||||
CachedTokens = value.Usage.CacheReadInputTokens.Value,
|
||||
};
|
||||
|
||||
if (value.Usage.InputTokens > 0)
|
||||
{
|
||||
thor.Usage.InputTokens = value.Usage.InputTokens;
|
||||
}
|
||||
|
||||
if (value.Usage.OutputTokens > 0)
|
||||
{
|
||||
thor.Usage.CompletionTokens = value.Usage.OutputTokens;
|
||||
thor.Usage.OutputTokens = value.Usage.OutputTokens;
|
||||
}
|
||||
}
|
||||
|
||||
thor.Usage.TotalTokens = thor.Usage.InputTokens + thor.Usage.OutputTokens;
|
||||
thor.SupplementalMultiplier(AnthropicChatCompletionsService.ClaudeMultiplier);
|
||||
return thor;
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,313 @@
|
||||
using Microsoft.Extensions.DependencyInjection;
|
||||
using Microsoft.Extensions.Logging;
|
||||
using Volo.Abp.DependencyInjection;
|
||||
using Yi.Framework.AiHub.Domain.Shared.Dtos;
|
||||
using Yi.Framework.AiHub.Domain.Shared.Dtos.Anthropic;
|
||||
|
||||
namespace Yi.Framework.AiHub.Domain.AiGateWay.Impl.ThorCustomOpenAI.Chats;
|
||||
|
||||
/// <summary>
|
||||
/// OpenAI到Claude适配器服务
|
||||
/// 将Claude格式的请求转换为OpenAI格式,然后将OpenAI的响应转换为Claude格式
|
||||
/// </summary>
|
||||
public class CustomOpenAIAnthropicChatCompletionsService(
|
||||
IAbpLazyServiceProvider serviceProvider,
|
||||
ILogger<CustomOpenAIAnthropicChatCompletionsService> logger)
|
||||
: IAnthropicChatCompletionService
|
||||
{
|
||||
private IChatCompletionService GetChatCompletionService()
|
||||
{
|
||||
return serviceProvider.GetRequiredKeyedService<IChatCompletionService>(nameof(OpenAiChatCompletionsService));
|
||||
}
|
||||
|
||||
public async Task<AnthropicChatCompletionDto> ChatCompletionsAsync(AiModelDescribe aiModelDescribe,
|
||||
AnthropicInput request,
|
||||
CancellationToken cancellationToken = default)
|
||||
{
|
||||
// 转换请求格式:Claude -> OpenAI
|
||||
var openAIRequest = AnthropicToOpenAi.ConvertAnthropicToOpenAi(request);
|
||||
|
||||
if (openAIRequest.Model.StartsWith("gpt-5"))
|
||||
{
|
||||
openAIRequest.MaxCompletionTokens = request.MaxTokens;
|
||||
openAIRequest.MaxTokens = null;
|
||||
}
|
||||
else if (openAIRequest.Model.StartsWith("o3-mini") || openAIRequest.Model.StartsWith("o4-mini"))
|
||||
{
|
||||
openAIRequest.MaxCompletionTokens = request.MaxTokens;
|
||||
openAIRequest.MaxTokens = null;
|
||||
openAIRequest.Temperature = null;
|
||||
}
|
||||
|
||||
// 调用OpenAI服务
|
||||
var openAIResponse =
|
||||
await GetChatCompletionService().CompleteChatAsync(aiModelDescribe,openAIRequest, cancellationToken);
|
||||
|
||||
// 转换响应格式:OpenAI -> Claude
|
||||
var claudeResponse = AnthropicToOpenAi.ConvertOpenAIToClaude(openAIResponse, request);
|
||||
|
||||
return claudeResponse;
|
||||
}
|
||||
|
||||
public async IAsyncEnumerable<(string, AnthropicStreamDto?)> StreamChatCompletionsAsync(AiModelDescribe aiModelDescribe,
|
||||
AnthropicInput request,
|
||||
CancellationToken cancellationToken = default)
|
||||
{
|
||||
var openAIRequest = AnthropicToOpenAi.ConvertAnthropicToOpenAi(request);
|
||||
openAIRequest.Stream = true;
|
||||
|
||||
if (openAIRequest.Model.StartsWith("gpt-5"))
|
||||
{
|
||||
openAIRequest.MaxCompletionTokens = request.MaxTokens;
|
||||
openAIRequest.MaxTokens = null;
|
||||
}
|
||||
else if (openAIRequest.Model.StartsWith("o3-mini") || openAIRequest.Model.StartsWith("o4-mini"))
|
||||
{
|
||||
openAIRequest.MaxCompletionTokens = request.MaxTokens;
|
||||
openAIRequest.MaxTokens = null;
|
||||
openAIRequest.Temperature = null;
|
||||
}
|
||||
|
||||
var messageId = Guid.NewGuid().ToString();
|
||||
var hasStarted = false;
|
||||
var hasTextContentBlockStarted = false;
|
||||
var hasThinkingContentBlockStarted = false;
|
||||
var toolBlocksStarted = new Dictionary<int, bool>(); // 使用索引而不是ID
|
||||
var toolCallIds = new Dictionary<int, string>(); // 存储每个索引对应的ID
|
||||
var toolCallIndexToBlockIndex = new Dictionary<int, int>(); // 工具调用索引到块索引的映射
|
||||
var accumulatedUsage = new AnthropicCompletionDtoUsage();
|
||||
var isFinished = false;
|
||||
var currentContentBlockType = ""; // 跟踪当前内容块类型
|
||||
var currentBlockIndex = 0; // 跟踪当前块索引
|
||||
var lastContentBlockType = ""; // 跟踪最后一个内容块类型,用于确定停止原因
|
||||
|
||||
await foreach (var openAIResponse in GetChatCompletionService().CompleteChatStreamAsync(aiModelDescribe,openAIRequest,
|
||||
cancellationToken))
|
||||
{
|
||||
// 发送message_start事件
|
||||
if (!hasStarted && openAIResponse.Choices?.Count > 0 &&
|
||||
openAIResponse.Choices.Any(x => x.Delta.ToolCalls?.Count > 0) == false)
|
||||
{
|
||||
hasStarted = true;
|
||||
var messageStartEvent = AnthropicToOpenAi.CreateMessageStartEvent(messageId, request.Model);
|
||||
yield return ("message_start", messageStartEvent);
|
||||
}
|
||||
|
||||
// 更新使用情况统计
|
||||
if (openAIResponse.Usage != null)
|
||||
{
|
||||
// 使用最新的token计数(OpenAI通常在最后的响应中提供完整的统计)
|
||||
if (openAIResponse.Usage.PromptTokens.HasValue)
|
||||
{
|
||||
accumulatedUsage.InputTokens = openAIResponse.Usage.PromptTokens.Value;
|
||||
}
|
||||
|
||||
if (openAIResponse.Usage.CompletionTokens.HasValue)
|
||||
{
|
||||
accumulatedUsage.OutputTokens = (int)openAIResponse.Usage.CompletionTokens.Value;
|
||||
}
|
||||
|
||||
if (openAIResponse.Usage.PromptTokensDetails?.CachedTokens.HasValue == true)
|
||||
{
|
||||
accumulatedUsage.CacheReadInputTokens =
|
||||
openAIResponse.Usage.PromptTokensDetails.CachedTokens.Value;
|
||||
}
|
||||
|
||||
// 记录调试信息
|
||||
logger.LogDebug("OpenAI Usage更新: Input={InputTokens}, Output={OutputTokens}, CacheRead={CacheRead}",
|
||||
accumulatedUsage.InputTokens, accumulatedUsage.OutputTokens,
|
||||
accumulatedUsage.CacheReadInputTokens);
|
||||
}
|
||||
|
||||
if (openAIResponse.Choices is { Count: > 0 })
|
||||
{
|
||||
var choice = openAIResponse.Choices.First();
|
||||
|
||||
// 处理内容
|
||||
if (!string.IsNullOrEmpty(choice.Delta?.Content))
|
||||
{
|
||||
// 如果当前有其他类型的内容块在运行,先结束它们
|
||||
if (currentContentBlockType != "text" && !string.IsNullOrEmpty(currentContentBlockType))
|
||||
{
|
||||
var stopEvent = AnthropicToOpenAi.CreateContentBlockStopEvent();
|
||||
stopEvent.Index = currentBlockIndex;
|
||||
yield return ("content_block_stop", stopEvent);
|
||||
currentBlockIndex++; // 切换内容块时增加索引
|
||||
currentContentBlockType = "";
|
||||
}
|
||||
|
||||
// 发送content_block_start事件(仅第一次)
|
||||
if (!hasTextContentBlockStarted || currentContentBlockType != "text")
|
||||
{
|
||||
hasTextContentBlockStarted = true;
|
||||
currentContentBlockType = "text";
|
||||
lastContentBlockType = "text";
|
||||
var contentBlockStartEvent = AnthropicToOpenAi.CreateContentBlockStartEvent();
|
||||
contentBlockStartEvent.Index = currentBlockIndex;
|
||||
yield return ("content_block_start",
|
||||
contentBlockStartEvent);
|
||||
}
|
||||
|
||||
// 发送content_block_delta事件
|
||||
var contentDeltaEvent = AnthropicToOpenAi.CreateContentBlockDeltaEvent(choice.Delta.Content);
|
||||
contentDeltaEvent.Index = currentBlockIndex;
|
||||
yield return ("content_block_delta",
|
||||
contentDeltaEvent);
|
||||
}
|
||||
|
||||
// 处理工具调用
|
||||
if (choice.Delta?.ToolCalls is { Count: > 0 })
|
||||
{
|
||||
foreach (var toolCall in choice.Delta.ToolCalls)
|
||||
{
|
||||
var toolCallIndex = toolCall.Index; // 使用索引来标识工具调用
|
||||
|
||||
// 发送tool_use content_block_start事件
|
||||
if (toolBlocksStarted.TryAdd(toolCallIndex, true))
|
||||
{
|
||||
// 如果当前有文本或thinking内容块在运行,先结束它们
|
||||
if (currentContentBlockType == "text" || currentContentBlockType == "thinking")
|
||||
{
|
||||
var stopEvent = AnthropicToOpenAi.CreateContentBlockStopEvent();
|
||||
stopEvent.Index = currentBlockIndex;
|
||||
yield return ("content_block_stop", stopEvent);
|
||||
currentBlockIndex++; // 增加块索引
|
||||
}
|
||||
// 如果当前有其他工具调用在运行,也需要结束它们
|
||||
else if (currentContentBlockType == "tool_use")
|
||||
{
|
||||
var stopEvent = AnthropicToOpenAi.CreateContentBlockStopEvent();
|
||||
stopEvent.Index = currentBlockIndex;
|
||||
yield return ("content_block_stop", stopEvent);
|
||||
currentBlockIndex++; // 增加块索引
|
||||
}
|
||||
|
||||
currentContentBlockType = "tool_use";
|
||||
lastContentBlockType = "tool_use";
|
||||
|
||||
// 为此工具调用分配一个新的块索引
|
||||
toolCallIndexToBlockIndex[toolCallIndex] = currentBlockIndex;
|
||||
|
||||
// 保存工具调用的ID(如果有的话)
|
||||
if (!string.IsNullOrEmpty(toolCall.Id))
|
||||
{
|
||||
toolCallIds[toolCallIndex] = toolCall.Id;
|
||||
}
|
||||
else if (!toolCallIds.ContainsKey(toolCallIndex))
|
||||
{
|
||||
// 如果没有ID且之前也没有保存过,生成一个新的ID
|
||||
toolCallIds[toolCallIndex] = Guid.NewGuid().ToString();
|
||||
}
|
||||
|
||||
var toolBlockStartEvent = AnthropicToOpenAi.CreateToolBlockStartEvent(
|
||||
toolCallIds[toolCallIndex],
|
||||
toolCall.Function?.Name);
|
||||
toolBlockStartEvent.Index = currentBlockIndex;
|
||||
yield return ("content_block_start",
|
||||
toolBlockStartEvent);
|
||||
}
|
||||
|
||||
// 如果有增量的参数,发送content_block_delta事件
|
||||
if (!string.IsNullOrEmpty(toolCall.Function?.Arguments))
|
||||
{
|
||||
var toolDeltaEvent =
|
||||
AnthropicToOpenAi.CreateToolBlockDeltaEvent(toolCall.Function.Arguments);
|
||||
// 使用该工具调用对应的块索引
|
||||
toolDeltaEvent.Index = toolCallIndexToBlockIndex[toolCallIndex];
|
||||
yield return ("content_block_delta",
|
||||
toolDeltaEvent);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
// 处理推理内容
|
||||
if (!string.IsNullOrEmpty(choice.Delta?.ReasoningContent))
|
||||
{
|
||||
// 如果当前有其他类型的内容块在运行,先结束它们
|
||||
if (currentContentBlockType != "thinking" && !string.IsNullOrEmpty(currentContentBlockType))
|
||||
{
|
||||
var stopEvent = AnthropicToOpenAi.CreateContentBlockStopEvent();
|
||||
stopEvent.Index = currentBlockIndex;
|
||||
yield return ("content_block_stop", stopEvent);
|
||||
currentBlockIndex++; // 增加块索引
|
||||
currentContentBlockType = "";
|
||||
}
|
||||
|
||||
// 对于推理内容,也需要发送对应的事件
|
||||
if (!hasThinkingContentBlockStarted || currentContentBlockType != "thinking")
|
||||
{
|
||||
hasThinkingContentBlockStarted = true;
|
||||
currentContentBlockType = "thinking";
|
||||
lastContentBlockType = "thinking";
|
||||
var thinkingBlockStartEvent = AnthropicToOpenAi.CreateThinkingBlockStartEvent();
|
||||
thinkingBlockStartEvent.Index = currentBlockIndex;
|
||||
yield return ("content_block_start",
|
||||
thinkingBlockStartEvent);
|
||||
}
|
||||
|
||||
var thinkingDeltaEvent =
|
||||
AnthropicToOpenAi.CreateThinkingBlockDeltaEvent(choice.Delta.ReasoningContent);
|
||||
thinkingDeltaEvent.Index = currentBlockIndex;
|
||||
yield return ("content_block_delta",
|
||||
thinkingDeltaEvent);
|
||||
}
|
||||
|
||||
// 处理结束
|
||||
if (!string.IsNullOrEmpty(choice.FinishReason) && !isFinished)
|
||||
{
|
||||
isFinished = true;
|
||||
|
||||
// 发送content_block_stop事件(如果有活跃的内容块)
|
||||
if (!string.IsNullOrEmpty(currentContentBlockType))
|
||||
{
|
||||
var contentBlockStopEvent = AnthropicToOpenAi.CreateContentBlockStopEvent();
|
||||
contentBlockStopEvent.Index = currentBlockIndex;
|
||||
yield return ("content_block_stop",
|
||||
contentBlockStopEvent);
|
||||
}
|
||||
|
||||
// 发送message_delta事件
|
||||
var messageDeltaEvent = AnthropicToOpenAi.CreateMessageDeltaEvent(
|
||||
AnthropicToOpenAi.GetStopReasonByLastContentType(choice.FinishReason, lastContentBlockType),
|
||||
accumulatedUsage);
|
||||
|
||||
// 记录最终Usage统计
|
||||
logger.LogDebug(
|
||||
"流式响应结束,最终Usage: Input={InputTokens}, Output={OutputTokens}, CacheRead={CacheRead}",
|
||||
accumulatedUsage.InputTokens, accumulatedUsage.OutputTokens,
|
||||
accumulatedUsage.CacheReadInputTokens);
|
||||
|
||||
yield return ("message_delta",
|
||||
messageDeltaEvent);
|
||||
|
||||
// 发送message_stop事件
|
||||
var messageStopEvent = AnthropicToOpenAi.CreateMessageStopEvent();
|
||||
yield return ("message_stop",
|
||||
messageStopEvent);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
// 确保流正确结束
|
||||
if (!isFinished)
|
||||
{
|
||||
if (!string.IsNullOrEmpty(currentContentBlockType))
|
||||
{
|
||||
var contentBlockStopEvent = AnthropicToOpenAi.CreateContentBlockStopEvent();
|
||||
contentBlockStopEvent.Index = currentBlockIndex;
|
||||
yield return ("content_block_stop",
|
||||
contentBlockStopEvent);
|
||||
}
|
||||
|
||||
var messageDeltaEvent =
|
||||
AnthropicToOpenAi.CreateMessageDeltaEvent(
|
||||
AnthropicToOpenAi.GetStopReasonByLastContentType("end_turn", lastContentBlockType),
|
||||
accumulatedUsage);
|
||||
yield return ("message_delta", messageDeltaEvent);
|
||||
|
||||
var messageStopEvent = AnthropicToOpenAi.CreateMessageStopEvent();
|
||||
yield return ("message_stop",
|
||||
messageStopEvent);
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,167 @@
|
||||
using System.Diagnostics;
|
||||
using System.Net;
|
||||
using System.Net.Http.Json;
|
||||
using System.Text.Json;
|
||||
using Microsoft.Extensions.Logging;
|
||||
using Yi.Framework.AiHub.Domain.AiGateWay.Exceptions;
|
||||
using Yi.Framework.AiHub.Domain.Shared.Dtos;
|
||||
using Yi.Framework.AiHub.Domain.Shared.Dtos.OpenAi;
|
||||
|
||||
namespace Yi.Framework.AiHub.Domain.AiGateWay.Impl.ThorCustomOpenAI.Chats;
|
||||
|
||||
public sealed class OpenAiChatCompletionsService(ILogger<OpenAiChatCompletionsService> logger,IHttpClientFactory httpClientFactory)
|
||||
: IChatCompletionService
|
||||
{
|
||||
public async IAsyncEnumerable<ThorChatCompletionsResponse> CompleteChatStreamAsync(AiModelDescribe options,
|
||||
ThorChatCompletionsRequest chatCompletionCreate,
|
||||
CancellationToken cancellationToken)
|
||||
{
|
||||
using var openai =
|
||||
Activity.Current?.Source.StartActivity("OpenAI 对话流式补全");
|
||||
|
||||
var response = await httpClientFactory.CreateClient().HttpRequestRaw(
|
||||
options?.Endpoint.TrimEnd('/') + "/chat/completions",
|
||||
chatCompletionCreate, options.ApiKey);
|
||||
|
||||
openai?.SetTag("Model", chatCompletionCreate.Model);
|
||||
openai?.SetTag("Response", response.StatusCode.ToString());
|
||||
|
||||
if (response.StatusCode == HttpStatusCode.Unauthorized)
|
||||
{
|
||||
throw new UnauthorizedAccessException();
|
||||
}
|
||||
|
||||
// 如果限流则抛出限流异常
|
||||
if (response.StatusCode == HttpStatusCode.TooManyRequests)
|
||||
{
|
||||
throw new ThorRateLimitException();
|
||||
}
|
||||
|
||||
// 大于等于400的状态码都认为是异常
|
||||
if (response.StatusCode >= HttpStatusCode.BadRequest)
|
||||
{
|
||||
var error = await response.Content.ReadAsStringAsync();
|
||||
logger.LogError("OpenAI对话异常 , StatusCode: {StatusCode} 错误响应内容:{Content}", response.StatusCode,
|
||||
error);
|
||||
|
||||
throw new BusinessException("OpenAI对话异常:" + error, response.StatusCode.ToString());
|
||||
}
|
||||
|
||||
using var stream = new StreamReader(await response.Content.ReadAsStreamAsync(cancellationToken));
|
||||
|
||||
using StreamReader reader = new(await response.Content.ReadAsStreamAsync(cancellationToken));
|
||||
string? line = string.Empty;
|
||||
var first = true;
|
||||
var isThink = false;
|
||||
while ((line = await reader.ReadLineAsync().ConfigureAwait(false)) != null)
|
||||
{
|
||||
line += Environment.NewLine;
|
||||
|
||||
if (line.StartsWith('{'))
|
||||
{
|
||||
logger.LogInformation("OpenAI对话异常 , StatusCode: {StatusCode} Response: {Response}", response.StatusCode,
|
||||
line);
|
||||
|
||||
throw new BusinessException("OpenAI对话异常", line);
|
||||
}
|
||||
|
||||
if (line.StartsWith(OpenAIConstant.Data))
|
||||
line = line[OpenAIConstant.Data.Length..];
|
||||
|
||||
line = line.Trim();
|
||||
|
||||
if (string.IsNullOrWhiteSpace(line)) continue;
|
||||
|
||||
if (line == OpenAIConstant.Done)
|
||||
{
|
||||
break;
|
||||
}
|
||||
|
||||
if (line.StartsWith(':'))
|
||||
{
|
||||
continue;
|
||||
}
|
||||
|
||||
|
||||
var result = JsonSerializer.Deserialize<ThorChatCompletionsResponse>(line,
|
||||
ThorJsonSerializer.DefaultOptions);
|
||||
|
||||
if (result == null)
|
||||
{
|
||||
continue;
|
||||
}
|
||||
|
||||
var content = result?.Choices?.FirstOrDefault()?.Delta;
|
||||
|
||||
if (first && content?.Content == OpenAIConstant.ThinkStart)
|
||||
{
|
||||
isThink = true;
|
||||
continue;
|
||||
// 需要将content的内容转换到其他字段
|
||||
}
|
||||
|
||||
if (isThink && content?.Content?.Contains(OpenAIConstant.ThinkEnd) == true)
|
||||
{
|
||||
isThink = false;
|
||||
// 需要将content的内容转换到其他字段
|
||||
continue;
|
||||
}
|
||||
|
||||
if (isThink && result?.Choices != null)
|
||||
{
|
||||
// 需要将content的内容转换到其他字段
|
||||
foreach (var choice in result.Choices)
|
||||
{
|
||||
choice.Delta.ReasoningContent = choice.Delta.Content;
|
||||
choice.Delta.Content = string.Empty;
|
||||
}
|
||||
}
|
||||
|
||||
first = false;
|
||||
|
||||
yield return result;
|
||||
}
|
||||
}
|
||||
|
||||
public async Task<ThorChatCompletionsResponse> CompleteChatAsync(AiModelDescribe options,
|
||||
ThorChatCompletionsRequest chatCompletionCreate,
|
||||
CancellationToken cancellationToken)
|
||||
{
|
||||
using var openai =
|
||||
Activity.Current?.Source.StartActivity("OpenAI 对话补全");
|
||||
|
||||
var response = await HttpClientFactory.GetHttpClient(options.Endpoint).PostJsonAsync(
|
||||
options?.Endpoint.TrimEnd('/') + "/chat/completions",
|
||||
chatCompletionCreate, options.ApiKey).ConfigureAwait(false);
|
||||
|
||||
openai?.SetTag("Model", chatCompletionCreate.Model);
|
||||
openai?.SetTag("Response", response.StatusCode.ToString());
|
||||
|
||||
if (response.StatusCode == HttpStatusCode.Unauthorized)
|
||||
{
|
||||
throw new BusinessException("渠道未登录,请联系管理人员", "401");
|
||||
}
|
||||
|
||||
// 如果限流则抛出限流异常
|
||||
if (response.StatusCode == HttpStatusCode.TooManyRequests)
|
||||
{
|
||||
throw new ThorRateLimitException();
|
||||
}
|
||||
|
||||
// 大于等于400的状态码都认为是异常
|
||||
if (response.StatusCode >= HttpStatusCode.BadRequest)
|
||||
{
|
||||
var error = await response.Content.ReadAsStringAsync(cancellationToken).ConfigureAwait(false);
|
||||
logger.LogError("OpenAI对话异常 请求地址:{Address}, StatusCode: {StatusCode} Response: {Response}", options.Endpoint,
|
||||
response.StatusCode, error);
|
||||
|
||||
throw new BusinessException("OpenAI对话异常", response.StatusCode.ToString());
|
||||
}
|
||||
|
||||
var result =
|
||||
await response.Content.ReadFromJsonAsync<ThorChatCompletionsResponse>(
|
||||
cancellationToken: cancellationToken).ConfigureAwait(false);
|
||||
|
||||
return result;
|
||||
}
|
||||
}
|
||||
@@ -9,7 +9,7 @@ using Yi.Framework.AiHub.Domain.Shared.Dtos.OpenAi;
|
||||
|
||||
namespace Yi.Framework.AiHub.Domain.AiGateWay.Impl.ThorDeepSeek.Chats;
|
||||
|
||||
public sealed class DeepSeekChatCompletionsService(ILogger<DeepSeekChatCompletionsService> logger)
|
||||
public sealed class DeepSeekChatCompletionsService(ILogger<DeepSeekChatCompletionsService> logger,IHttpClientFactory httpClientFactory)
|
||||
: IChatCompletionService
|
||||
{
|
||||
public async IAsyncEnumerable<ThorChatCompletionsResponse> CompleteChatStreamAsync(AiModelDescribe options,
|
||||
@@ -24,7 +24,7 @@ public sealed class DeepSeekChatCompletionsService(ILogger<DeepSeekChatCompletio
|
||||
using var openai =
|
||||
Activity.Current?.Source.StartActivity("OpenAI 对话流式补全");
|
||||
|
||||
var response = await HttpClientFactory.GetHttpClient(options.Endpoint).HttpRequestRaw(
|
||||
var response = await httpClientFactory.CreateClient().HttpRequestRaw(
|
||||
options?.Endpoint.TrimEnd('/') + "/chat/completions",
|
||||
chatCompletionCreate, options.ApiKey);
|
||||
|
||||
@@ -142,7 +142,7 @@ public sealed class DeepSeekChatCompletionsService(ILogger<DeepSeekChatCompletio
|
||||
options.Endpoint = "https://api.deepseek.com/v1";
|
||||
}
|
||||
|
||||
var response = await HttpClientFactory.GetHttpClient(options.Endpoint).PostJsonAsync(
|
||||
var response = await httpClientFactory.CreateClient().PostJsonAsync(
|
||||
options?.Endpoint.TrimEnd('/') + "/chat/completions",
|
||||
chatCompletionCreate, options.ApiKey).ConfigureAwait(false);
|
||||
|
||||
|
||||
@@ -4,7 +4,7 @@ using Yi.Framework.AiHub.Domain.Shared.Dtos.OpenAi.Embeddings;
|
||||
|
||||
namespace Yi.Framework.AiHub.Domain.AiGateWay.Impl.ThorSiliconFlow.Embeddings;
|
||||
|
||||
public sealed class SiliconFlowTextEmbeddingService
|
||||
public sealed class SiliconFlowTextEmbeddingService(IHttpClientFactory httpClientFactory)
|
||||
: ITextEmbeddingService
|
||||
{
|
||||
public async Task<EmbeddingCreateResponse> EmbeddingAsync(
|
||||
@@ -12,7 +12,7 @@ public sealed class SiliconFlowTextEmbeddingService
|
||||
AiModelDescribe? options = null,
|
||||
CancellationToken cancellationToken = default)
|
||||
{
|
||||
var response = await HttpClientFactory.GetHttpClient(options.Endpoint).PostJsonAsync(
|
||||
var response = await httpClientFactory.CreateClient().PostJsonAsync(
|
||||
options?.Endpoint.TrimEnd('/') + "/v1/embeddings",
|
||||
createEmbeddingModel, options!.ApiKey);
|
||||
|
||||
|
||||
@@ -1,5 +1,6 @@
|
||||
using Microsoft.Extensions.Options;
|
||||
using Volo.Abp.DependencyInjection;
|
||||
using Yi.Framework.AiHub.Domain.Shared.Dtos.Anthropic;
|
||||
using Yi.Framework.AiHub.Domain.Shared.Dtos.OpenAi;
|
||||
|
||||
namespace Yi.Framework.AiHub.Domain.AiGateWay;
|
||||
@@ -20,4 +21,12 @@ public class SpecialCompatible : ISpecialCompatible,ISingletonDependency
|
||||
handle(request);
|
||||
}
|
||||
}
|
||||
|
||||
public void AnthropicCompatible(AnthropicInput request)
|
||||
{
|
||||
foreach (var handle in _options.Value.AnthropicHandles)
|
||||
{
|
||||
handle(request);
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -1,8 +1,10 @@
|
||||
using Yi.Framework.AiHub.Domain.Shared.Dtos.OpenAi;
|
||||
using Yi.Framework.AiHub.Domain.Shared.Dtos.Anthropic;
|
||||
using Yi.Framework.AiHub.Domain.Shared.Dtos.OpenAi;
|
||||
|
||||
namespace Yi.Framework.AiHub.Domain.AiGateWay;
|
||||
|
||||
public class SpecialCompatibleOptions
|
||||
{
|
||||
public List<Action<ThorChatCompletionsRequest>> Handles { get; set; } = new();
|
||||
public List<Action<AnthropicInput>> AnthropicHandles { get; set; } = new();
|
||||
}
|
||||
@@ -1,6 +1,7 @@
|
||||
using Alipay.EasySDK.Factory;
|
||||
using Alipay.EasySDK.Kernel.Util;
|
||||
using Alipay.EasySDK.Payment.Page.Models;
|
||||
using Microsoft.Extensions.Configuration;
|
||||
using Microsoft.Extensions.Logging;
|
||||
using Volo.Abp.Domain.Services;
|
||||
|
||||
@@ -21,13 +22,13 @@ public class AlipayManager : DomainService
|
||||
/// <returns></returns>
|
||||
/// <exception cref="AlipayException"></exception>
|
||||
public Task<AlipayTradePagePayResponse> PaymentPageAsync(string productName, string orderNumber,
|
||||
decimal totalAmount)
|
||||
decimal totalAmount, string? returnUrl)
|
||||
{
|
||||
try
|
||||
{
|
||||
// 2. 发起API调用(以创建当面付收款二维码为例)
|
||||
var response = Factory.Payment.Page()
|
||||
.Pay(productName, orderNumber, totalAmount.ToString(), "https://ccnetcore.com/pay/sucess");
|
||||
.Pay(productName, orderNumber, totalAmount.ToString(), returnUrl ?? string.Empty);
|
||||
// 3. 处理响应或异常
|
||||
if (ResponseChecker.Success(response))
|
||||
{
|
||||
|
||||
@@ -1,5 +1,6 @@
|
||||
using SqlSugar;
|
||||
using Volo.Abp.Domain.Entities.Auditing;
|
||||
using Yi.Framework.AiHub.Domain.Shared.Enums;
|
||||
|
||||
namespace Yi.Framework.AiHub.Domain.Entities;
|
||||
|
||||
@@ -38,4 +39,9 @@ public class AiRechargeAggregateRoot : FullAuditedAggregateRoot<Guid>
|
||||
/// 联系方式
|
||||
/// </summary>
|
||||
public string? ContactInfo { get; set; }
|
||||
|
||||
/// <summary>
|
||||
/// 订单类型
|
||||
/// </summary>
|
||||
public RechargeTypeEnum RechargeType { get; set; }
|
||||
}
|
||||
@@ -0,0 +1,40 @@
|
||||
using SqlSugar;
|
||||
using Volo.Abp.Auditing;
|
||||
using Volo.Abp.Domain.Entities;
|
||||
|
||||
namespace Yi.Framework.AiHub.Domain.Entities;
|
||||
|
||||
/// <summary>
|
||||
/// ai用户表
|
||||
/// </summary>
|
||||
[SugarTable("Ai_UserExtraInfo")]
|
||||
[SugarIndex($"index_{nameof(UserId)}", nameof(UserId), OrderByType.Asc)]
|
||||
public class AiUserExtraInfoEntity : Entity<Guid>, IHasCreationTime, ISoftDelete
|
||||
{
|
||||
public AiUserExtraInfoEntity()
|
||||
{
|
||||
}
|
||||
|
||||
public AiUserExtraInfoEntity(Guid userId, string fuwuhaoOpenId)
|
||||
{
|
||||
this.UserId = userId;
|
||||
this.FuwuhaoOpenId = fuwuhaoOpenId;
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// 用户id
|
||||
/// </summary>
|
||||
public Guid UserId { get; set; }
|
||||
|
||||
/// <summary>
|
||||
/// 服务号,openid
|
||||
/// </summary>
|
||||
public string FuwuhaoOpenId { get; set; }
|
||||
|
||||
/// <summary>
|
||||
/// 创建时间
|
||||
/// </summary>
|
||||
public DateTime CreationTime { get; set; }
|
||||
|
||||
public bool IsDeleted { get; set; }
|
||||
}
|
||||
@@ -0,0 +1,57 @@
|
||||
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_Announcement")]
|
||||
public class AnnouncementAggregateRoot : FullAuditedAggregateRoot<Guid>
|
||||
{
|
||||
public AnnouncementAggregateRoot()
|
||||
{
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// 标题
|
||||
/// </summary>
|
||||
public string Title { get; set; } = string.Empty;
|
||||
|
||||
/// <summary>
|
||||
/// 内容列表(JSON格式存储)
|
||||
/// </summary>
|
||||
[SugarColumn(IsJson = true, IsNullable = false)]
|
||||
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; }
|
||||
}
|
||||
@@ -0,0 +1,146 @@
|
||||
using SqlSugar;
|
||||
using Volo.Abp.Domain.Entities.Auditing;
|
||||
|
||||
namespace Yi.Framework.AiHub.Domain.Entities;
|
||||
|
||||
/// <summary>
|
||||
/// 翻牌任务记录
|
||||
/// </summary>
|
||||
[SugarTable("Ai_CardFlipTask")]
|
||||
[SugarIndex($"index_{nameof(UserId)}_{nameof(WeekStartDate)}",
|
||||
nameof(UserId), OrderByType.Asc,
|
||||
nameof(WeekStartDate), OrderByType.Desc)]
|
||||
public class CardFlipTaskAggregateRoot : FullAuditedAggregateRoot<Guid>
|
||||
{
|
||||
public CardFlipTaskAggregateRoot()
|
||||
{
|
||||
}
|
||||
|
||||
public CardFlipTaskAggregateRoot(Guid userId, DateTime weekStartDate)
|
||||
{
|
||||
UserId = userId;
|
||||
WeekStartDate = weekStartDate.Date; // 确保只存储日期部分
|
||||
TotalFlips = 0;
|
||||
FreeFlipsUsed = 0;
|
||||
BonusFlipsUsed = 0;
|
||||
InviteFlipsUsed = 0;
|
||||
IsFirstFlipDone = false;
|
||||
FlippedOrder = new List<int>();
|
||||
WinRecords = new Dictionary<int, long>();
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// 用户ID
|
||||
/// </summary>
|
||||
public Guid UserId { get; set; }
|
||||
|
||||
/// <summary>
|
||||
/// 本周开始日期(每周一)
|
||||
/// </summary>
|
||||
public DateTime WeekStartDate { get; set; }
|
||||
|
||||
/// <summary>
|
||||
/// 总共已翻牌次数
|
||||
/// </summary>
|
||||
public int TotalFlips { get; set; }
|
||||
|
||||
/// <summary>
|
||||
/// 已使用的免费次数(最多7次)
|
||||
/// </summary>
|
||||
public int FreeFlipsUsed { get; set; }
|
||||
|
||||
/// <summary>
|
||||
/// 已使用的赠送次数(已废弃,保持为0)
|
||||
/// </summary>
|
||||
public int BonusFlipsUsed { get; set; }
|
||||
|
||||
/// <summary>
|
||||
/// 已使用的邀请解锁次数(最多3次)
|
||||
/// </summary>
|
||||
public int InviteFlipsUsed { get; set; }
|
||||
|
||||
/// <summary>
|
||||
/// 是否已完成首次翻牌(用于判断是否创建任务)
|
||||
/// </summary>
|
||||
public bool IsFirstFlipDone { get; set; }
|
||||
|
||||
/// <summary>
|
||||
/// 中奖记录(以翻牌顺序为key,例如第1次翻牌中奖则key为1,奖励金额为value)
|
||||
/// </summary>
|
||||
[SugarColumn(IsJson = true, IsNullable = true)]
|
||||
public Dictionary<int, long>? WinRecords { get; set; }
|
||||
|
||||
/// <summary>
|
||||
/// 备注信息
|
||||
/// </summary>
|
||||
[SugarColumn(Length = 500, IsNullable = true)]
|
||||
public string? Remark { get; set; }
|
||||
|
||||
/// <summary>
|
||||
/// 已翻牌的顺序(存储用户实际翻牌的序号列表,如[3,7,1,5]表示依次翻了3号、7号、1号、5号牌)
|
||||
/// </summary>
|
||||
[SugarColumn(IsJson = true, IsNullable = true)]
|
||||
public List<int>? FlippedOrder { get; set; }
|
||||
|
||||
/// <summary>
|
||||
/// 增加翻牌次数
|
||||
/// </summary>
|
||||
/// <param name="flipType">翻牌类型</param>
|
||||
public void IncrementFlip(FlipType flipType)
|
||||
{
|
||||
TotalFlips++;
|
||||
|
||||
switch (flipType)
|
||||
{
|
||||
case FlipType.Free:
|
||||
FreeFlipsUsed++;
|
||||
break;
|
||||
case FlipType.Bonus:
|
||||
BonusFlipsUsed++;
|
||||
break;
|
||||
case FlipType.Invite:
|
||||
InviteFlipsUsed++;
|
||||
break;
|
||||
}
|
||||
|
||||
if (!IsFirstFlipDone)
|
||||
{
|
||||
IsFirstFlipDone = true;
|
||||
}
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// 记录中奖
|
||||
/// </summary>
|
||||
/// <param name="flipCount">第几次翻牌(1-10)</param>
|
||||
/// <param name="amount">奖励金额</param>
|
||||
public void SetWinReward(int flipCount, long amount)
|
||||
{
|
||||
if (WinRecords == null)
|
||||
{
|
||||
WinRecords = new Dictionary<int, long>();
|
||||
}
|
||||
WinRecords[flipCount] = amount;
|
||||
}
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// 翻牌类型枚举
|
||||
/// </summary>
|
||||
public enum FlipType
|
||||
{
|
||||
/// <summary>
|
||||
/// 免费翻牌(1-7次)
|
||||
/// </summary>
|
||||
Free = 0,
|
||||
|
||||
/// <summary>
|
||||
/// 赠送翻牌(已废弃)
|
||||
/// </summary>
|
||||
Bonus = 1,
|
||||
|
||||
/// <summary>
|
||||
/// 邀请解锁翻牌(8-10次)
|
||||
/// </summary>
|
||||
Invite = 2
|
||||
}
|
||||
@@ -24,18 +24,26 @@ public class MessageAggregateRoot : FullAuditedAggregateRoot<Guid>
|
||||
{
|
||||
UserId = userId;
|
||||
SessionId = sessionId;
|
||||
Content = content;
|
||||
//如果没有会话,不存储对话内容
|
||||
Content = sessionId is null ? null : content;
|
||||
Role = role;
|
||||
ModelId = modelId;
|
||||
if (tokenUsage is not null)
|
||||
{
|
||||
long inputTokenCount = tokenUsage.PromptTokens
|
||||
?? tokenUsage.InputTokens
|
||||
?? 0;
|
||||
long inputTokenCount =
|
||||
(tokenUsage.PromptTokens.HasValue && tokenUsage.PromptTokens.Value != 0)
|
||||
? tokenUsage.PromptTokens.Value
|
||||
: (tokenUsage.InputTokens.HasValue && tokenUsage.InputTokens.Value != 0)
|
||||
? tokenUsage.InputTokens.Value
|
||||
: 0;
|
||||
|
||||
long outputTokenCount =
|
||||
(tokenUsage.CompletionTokens.HasValue && tokenUsage.CompletionTokens.Value != 0)
|
||||
? tokenUsage.CompletionTokens.Value
|
||||
: (tokenUsage.OutputTokens.HasValue && tokenUsage.OutputTokens.Value != 0)
|
||||
? tokenUsage.OutputTokens.Value
|
||||
: 0;
|
||||
|
||||
long outputTokenCount = tokenUsage.CompletionTokens
|
||||
?? tokenUsage.OutputTokens
|
||||
?? 0;
|
||||
|
||||
this.TokenUsage = new TokenUsageValueObject
|
||||
{
|
||||
|
||||
@@ -0,0 +1,57 @@
|
||||
using SqlSugar;
|
||||
using Volo.Abp.Domain.Entities.Auditing;
|
||||
|
||||
namespace Yi.Framework.AiHub.Domain.Entities;
|
||||
|
||||
/// <summary>
|
||||
/// 每日任务奖励领取记录
|
||||
/// </summary>
|
||||
[SugarTable("Ai_DailyTaskRewardRecord")]
|
||||
[SugarIndex($"index_{nameof(UserId)}_{nameof(TaskDate)}",
|
||||
nameof(UserId), OrderByType.Asc,
|
||||
nameof(TaskDate), OrderByType.Desc)]
|
||||
public class DailyTaskRewardRecordAggregateRoot : FullAuditedAggregateRoot<Guid>
|
||||
{
|
||||
public DailyTaskRewardRecordAggregateRoot()
|
||||
{
|
||||
}
|
||||
|
||||
public DailyTaskRewardRecordAggregateRoot(Guid userId, int taskLevel, DateTime taskDate, long rewardTokens)
|
||||
{
|
||||
UserId = userId;
|
||||
TaskLevel = taskLevel;
|
||||
TaskDate = taskDate.Date; // 确保只存储日期部分
|
||||
RewardTokens = rewardTokens;
|
||||
IsRewarded = true;
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// 用户ID
|
||||
/// </summary>
|
||||
public Guid UserId { get; set; }
|
||||
|
||||
/// <summary>
|
||||
/// 任务等级(1=1000w任务,2=3000w任务)
|
||||
/// </summary>
|
||||
public int TaskLevel { get; set; }
|
||||
|
||||
/// <summary>
|
||||
/// 任务日期(只包含日期,不包含时间)
|
||||
/// </summary>
|
||||
public DateTime TaskDate { get; set; }
|
||||
|
||||
/// <summary>
|
||||
/// 奖励的Token数量
|
||||
/// </summary>
|
||||
public long RewardTokens { get; set; }
|
||||
|
||||
/// <summary>
|
||||
/// 是否已发放奖励
|
||||
/// </summary>
|
||||
public bool IsRewarded { get; set; }
|
||||
|
||||
/// <summary>
|
||||
/// 备注信息
|
||||
/// </summary>
|
||||
public string? Remark { get; set; }
|
||||
}
|
||||
@@ -0,0 +1,76 @@
|
||||
using SqlSugar;
|
||||
using Volo.Abp.Domain.Entities.Auditing;
|
||||
|
||||
namespace Yi.Framework.AiHub.Domain.Entities;
|
||||
|
||||
/// <summary>
|
||||
/// 邀请记录
|
||||
/// </summary>
|
||||
[SugarTable("Ai_InvitationRecord")]
|
||||
[SugarIndex($"index_{nameof(InviterId)}_{nameof(InvitedUserId)}",
|
||||
nameof(InviterId), OrderByType.Asc,
|
||||
nameof(InvitedUserId), OrderByType.Asc)]
|
||||
[SugarIndex($"index_{nameof(InvitedUserId)}", nameof(InvitedUserId), OrderByType.Asc)]
|
||||
public class InvitationRecordAggregateRoot : FullAuditedAggregateRoot<Guid>
|
||||
{
|
||||
public InvitationRecordAggregateRoot()
|
||||
{
|
||||
}
|
||||
|
||||
public InvitationRecordAggregateRoot(Guid inviterId, Guid invitedUserId, string inviteCode)
|
||||
{
|
||||
InviterId = inviterId;
|
||||
InvitedUserId = invitedUserId;
|
||||
InviteCode = inviteCode;
|
||||
InvitationTime = DateTime.Now;
|
||||
Status = InvitationStatus.Valid;
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// 邀请人ID
|
||||
/// </summary>
|
||||
public Guid InviterId { get; set; }
|
||||
|
||||
/// <summary>
|
||||
/// 被邀请人ID
|
||||
/// </summary>
|
||||
public Guid InvitedUserId { get; set; }
|
||||
|
||||
/// <summary>
|
||||
/// 使用的邀请码
|
||||
/// </summary>
|
||||
[SugarColumn(Length = 50)]
|
||||
public string InviteCode { get; set; } = string.Empty;
|
||||
|
||||
/// <summary>
|
||||
/// 邀请时间
|
||||
/// </summary>
|
||||
public DateTime InvitationTime { get; set; }
|
||||
|
||||
/// <summary>
|
||||
/// 邀请状态(0=有效,1=已撤销)
|
||||
/// </summary>
|
||||
public InvitationStatus Status { get; set; }
|
||||
|
||||
/// <summary>
|
||||
/// 备注信息
|
||||
/// </summary>
|
||||
[SugarColumn(Length = 500, IsNullable = true)]
|
||||
public string? Remark { get; set; }
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// 邀请状态枚举
|
||||
/// </summary>
|
||||
public enum InvitationStatus
|
||||
{
|
||||
/// <summary>
|
||||
/// 有效
|
||||
/// </summary>
|
||||
Valid = 0,
|
||||
|
||||
/// <summary>
|
||||
/// 已撤销
|
||||
/// </summary>
|
||||
Revoked = 1
|
||||
}
|
||||
@@ -0,0 +1,47 @@
|
||||
using SqlSugar;
|
||||
using Volo.Abp.Domain.Entities.Auditing;
|
||||
|
||||
namespace Yi.Framework.AiHub.Domain.Entities;
|
||||
|
||||
/// <summary>
|
||||
/// 用户邀请码
|
||||
/// </summary>
|
||||
[SugarTable("Ai_InviteCode")]
|
||||
[SugarIndex($"index_{nameof(UserId)}", nameof(UserId), OrderByType.Asc, true)]
|
||||
[SugarIndex($"index_{nameof(Code)}", nameof(Code), OrderByType.Asc, true)]
|
||||
public class InviteCodeAggregateRoot : FullAuditedAggregateRoot<Guid>
|
||||
{
|
||||
public InviteCodeAggregateRoot()
|
||||
{
|
||||
}
|
||||
|
||||
public InviteCodeAggregateRoot(Guid userId, string code)
|
||||
{
|
||||
UserId = userId;
|
||||
Code = code;
|
||||
UsedCount = 0;
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// 用户ID(邀请码拥有者)
|
||||
/// </summary>
|
||||
public Guid UserId { get; set; }
|
||||
|
||||
/// <summary>
|
||||
/// 邀请码(唯一)
|
||||
/// </summary>
|
||||
[SugarColumn(Length = 50)]
|
||||
public string Code { get; set; } = string.Empty;
|
||||
|
||||
/// <summary>
|
||||
/// 被使用次数(统计用,一个邀请码可以被多人使用)
|
||||
/// </summary>
|
||||
public int UsedCount { get; set; }
|
||||
|
||||
/// <summary>
|
||||
/// 备注信息
|
||||
/// </summary>
|
||||
[SugarColumn(Length = 500, IsNullable = true)]
|
||||
public string? Remark { get; set; }
|
||||
|
||||
}
|
||||
@@ -52,7 +52,12 @@ public class AiModelEntity : Entity<Guid>, IOrderNum, ISoftDelete
|
||||
public string? ExtraInfo { get; set; }
|
||||
|
||||
/// <summary>
|
||||
/// 模型类型
|
||||
/// 模型类型(聊天/图片等)
|
||||
/// </summary>
|
||||
public ModelTypeEnum ModelType { get; set; }
|
||||
|
||||
/// <summary>
|
||||
/// 模型Api类型,现支持同一个模型id,多种接口格式
|
||||
/// </summary>
|
||||
public ModelApiTypeEnum ModelApiType { get; set; }
|
||||
}
|
||||
@@ -0,0 +1,133 @@
|
||||
using SqlSugar;
|
||||
using Volo.Abp.Domain.Entities.Auditing;
|
||||
|
||||
namespace Yi.Framework.AiHub.Domain.Entities;
|
||||
|
||||
/// <summary>
|
||||
/// 尊享包聚合根
|
||||
/// 用于给VIP扩展额外购买尊享token包
|
||||
/// </summary>
|
||||
[SugarTable("Ai_PremiumPackage")]
|
||||
[SugarIndex($"index_{nameof(UserId)}", nameof(UserId), OrderByType.Asc)]
|
||||
public class PremiumPackageAggregateRoot : FullAuditedAggregateRoot<Guid>
|
||||
{
|
||||
public PremiumPackageAggregateRoot()
|
||||
{
|
||||
}
|
||||
|
||||
public PremiumPackageAggregateRoot(Guid userId, long totalTokens, string packageName)
|
||||
{
|
||||
UserId = userId;
|
||||
TotalTokens = totalTokens;
|
||||
RemainingTokens = totalTokens;
|
||||
PackageName = packageName;
|
||||
IsActive = true;
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// 用户ID
|
||||
/// </summary>
|
||||
public Guid UserId { get; set; }
|
||||
|
||||
/// <summary>
|
||||
/// 包名称
|
||||
/// </summary>
|
||||
public string PackageName { get; set; }
|
||||
|
||||
/// <summary>
|
||||
/// 总用量(总token数)
|
||||
/// </summary>
|
||||
public long TotalTokens { get; set; }
|
||||
|
||||
/// <summary>
|
||||
/// 剩余用量(剩余token数)
|
||||
/// </summary>
|
||||
public long RemainingTokens { get; set; }
|
||||
|
||||
/// <summary>
|
||||
/// 已使用token数
|
||||
/// </summary>
|
||||
public long UsedTokens { get; set; }
|
||||
|
||||
/// <summary>
|
||||
/// 到期时间
|
||||
/// </summary>
|
||||
public DateTime? ExpireDateTime { get; set; }
|
||||
|
||||
/// <summary>
|
||||
/// 是否激活
|
||||
/// </summary>
|
||||
public bool IsActive { get; set; }
|
||||
|
||||
/// <summary>
|
||||
/// 购买金额
|
||||
/// </summary>
|
||||
public decimal PurchaseAmount { get; set; }
|
||||
|
||||
/// <summary>
|
||||
/// 备注
|
||||
/// </summary>
|
||||
public string? Remark { get; set; }
|
||||
|
||||
/// <summary>
|
||||
/// 消耗token
|
||||
/// </summary>
|
||||
/// <param name="tokenCount">消耗的token数量</param>
|
||||
/// <returns>是否消耗成功</returns>
|
||||
public bool ConsumeTokens(long tokenCount)
|
||||
{
|
||||
RemainingTokens -= tokenCount;
|
||||
UsedTokens += tokenCount;
|
||||
|
||||
return true;
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// 检查是否可用
|
||||
/// </summary>
|
||||
/// <returns>是否可用</returns>
|
||||
public bool IsAvailable(bool isVerifyRemainingToken=true)
|
||||
{
|
||||
if (!IsActive)
|
||||
{
|
||||
return false;
|
||||
}
|
||||
|
||||
if (isVerifyRemainingToken&&RemainingTokens <= 0)
|
||||
{
|
||||
return false;
|
||||
}
|
||||
|
||||
if (ExpireDateTime.HasValue && ExpireDateTime.Value < DateTime.Now)
|
||||
{
|
||||
return false;
|
||||
}
|
||||
|
||||
return true;
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// 停用尊享包
|
||||
/// </summary>
|
||||
public void Deactivate()
|
||||
{
|
||||
IsActive = false;
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// 激活尊享包
|
||||
/// </summary>
|
||||
public void Activate()
|
||||
{
|
||||
IsActive = true;
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// 设置到期时间
|
||||
/// </summary>
|
||||
/// <param name="expireDateTime">到期时间</param>
|
||||
public void SetExpireDateTime(DateTime expireDateTime)
|
||||
{
|
||||
ExpireDateTime = expireDateTime;
|
||||
}
|
||||
}
|
||||
@@ -12,48 +12,60 @@ using Volo.Abp.Domain.Services;
|
||||
using Yi.Framework.AiHub.Domain.AiGateWay;
|
||||
using Yi.Framework.AiHub.Domain.AiGateWay.Exceptions;
|
||||
using Yi.Framework.AiHub.Domain.Entities.Model;
|
||||
using Yi.Framework.AiHub.Domain.Shared.Consts;
|
||||
using Yi.Framework.AiHub.Domain.Shared.Dtos;
|
||||
using Yi.Framework.AiHub.Domain.Shared.Dtos.Anthropic;
|
||||
using Yi.Framework.AiHub.Domain.Shared.Dtos.OpenAi;
|
||||
using Yi.Framework.AiHub.Domain.Shared.Dtos.OpenAi.Embeddings;
|
||||
using Yi.Framework.AiHub.Domain.Shared.Dtos.OpenAi.Images;
|
||||
using Yi.Framework.AiHub.Domain.Shared.Enums;
|
||||
using Yi.Framework.Core.Extensions;
|
||||
using Yi.Framework.SqlSugarCore.Abstractions;
|
||||
using JsonSerializer = System.Text.Json.JsonSerializer;
|
||||
using ThorJsonSerializer = Yi.Framework.AiHub.Domain.AiGateWay.ThorJsonSerializer;
|
||||
|
||||
namespace Yi.Framework.AiHub.Domain.Managers;
|
||||
|
||||
public class AiGateWayManager : DomainService
|
||||
{
|
||||
private readonly ISqlSugarRepository<AiAppAggregateRoot> _aiAppRepository;
|
||||
private readonly ISqlSugarRepository<AiModelEntity> _aiModelRepository;
|
||||
private readonly ILogger<AiGateWayManager> _logger;
|
||||
private readonly AiMessageManager _aiMessageManager;
|
||||
private readonly UsageStatisticsManager _usageStatisticsManager;
|
||||
private readonly ISpecialCompatible _specialCompatible;
|
||||
private PremiumPackageManager? _premiumPackageManager;
|
||||
|
||||
|
||||
public AiGateWayManager(ISqlSugarRepository<AiAppAggregateRoot> aiAppRepository, ILogger<AiGateWayManager> logger,
|
||||
AiMessageManager aiMessageManager, UsageStatisticsManager usageStatisticsManager,
|
||||
ISpecialCompatible specialCompatible)
|
||||
ISpecialCompatible specialCompatible, ISqlSugarRepository<AiModelEntity> aiModelRepository)
|
||||
{
|
||||
_aiAppRepository = aiAppRepository;
|
||||
_logger = logger;
|
||||
_aiMessageManager = aiMessageManager;
|
||||
_usageStatisticsManager = usageStatisticsManager;
|
||||
_specialCompatible = specialCompatible;
|
||||
_aiModelRepository = aiModelRepository;
|
||||
}
|
||||
|
||||
private PremiumPackageManager PremiumPackageManager =>
|
||||
_premiumPackageManager ??= LazyServiceProvider.LazyGetRequiredService<PremiumPackageManager>();
|
||||
|
||||
/// <summary>
|
||||
/// 获取模型
|
||||
/// </summary>
|
||||
/// <param name="modelApiType"></param>
|
||||
/// <param name="modelId"></param>
|
||||
/// <returns></returns>
|
||||
private async Task<AiModelDescribe> GetModelAsync(string modelId)
|
||||
private async Task<AiModelDescribe> GetModelAsync(ModelApiTypeEnum modelApiType, string modelId)
|
||||
{
|
||||
var allApp = await _aiAppRepository._DbQueryable.Includes(x => x.AiModels).ToListAsync();
|
||||
foreach (var app in allApp)
|
||||
{
|
||||
var model = app.AiModels.FirstOrDefault(x => x.ModelId == modelId);
|
||||
if (model is not null)
|
||||
{
|
||||
return new AiModelDescribe
|
||||
var aiModelDescribe = await _aiModelRepository._DbQueryable
|
||||
.LeftJoin<AiAppAggregateRoot>((model, app) => model.AiAppId == app.Id)
|
||||
.Where((model, app) => model.ModelId == modelId)
|
||||
.Where((model, app) => model.ModelApiType == modelApiType)
|
||||
.Select((model, app) =>
|
||||
new AiModelDescribe
|
||||
{
|
||||
AppId = app.Id,
|
||||
AppName = app.Name,
|
||||
@@ -66,11 +78,14 @@ public class AiGateWayManager : DomainService
|
||||
Description = model.Description,
|
||||
AppExtraUrl = app.ExtraUrl,
|
||||
ModelExtraInfo = model.ExtraInfo
|
||||
};
|
||||
}
|
||||
})
|
||||
.FirstAsync();
|
||||
if (aiModelDescribe is null)
|
||||
{
|
||||
throw new UserFriendlyException($"【{modelId}】模型当前版本【{modelApiType}】格式不支持");
|
||||
}
|
||||
|
||||
throw new UserFriendlyException($"{modelId}模型当前版本不支持");
|
||||
return aiModelDescribe;
|
||||
}
|
||||
|
||||
|
||||
@@ -85,7 +100,7 @@ public class AiGateWayManager : DomainService
|
||||
[EnumeratorCancellation] CancellationToken cancellationToken)
|
||||
{
|
||||
_specialCompatible.Compatible(request);
|
||||
var modelDescribe = await GetModelAsync(request.Model);
|
||||
var modelDescribe = await GetModelAsync(ModelApiTypeEnum.OpenAi, request.Model);
|
||||
var chatService =
|
||||
LazyServiceProvider.GetRequiredKeyedService<IChatCompletionService>(modelDescribe.HandlerName);
|
||||
|
||||
@@ -115,7 +130,7 @@ public class AiGateWayManager : DomainService
|
||||
var response = httpContext.Response;
|
||||
// 设置响应头,声明是 json
|
||||
//response.ContentType = "application/json; charset=UTF-8";
|
||||
var modelDescribe = await GetModelAsync(request.Model);
|
||||
var modelDescribe = await GetModelAsync(ModelApiTypeEnum.OpenAi, request.Model);
|
||||
var chatService =
|
||||
LazyServiceProvider.GetRequiredKeyedService<IChatCompletionService>(modelDescribe.HandlerName);
|
||||
var data = await chatService.CompleteChatAsync(modelDescribe, request, cancellationToken);
|
||||
@@ -124,7 +139,7 @@ public class AiGateWayManager : DomainService
|
||||
await _aiMessageManager.CreateUserMessageAsync(userId.Value, sessionId,
|
||||
new MessageInputDto
|
||||
{
|
||||
Content = request.Messages?.LastOrDefault().Content ?? string.Empty,
|
||||
Content = sessionId is null ? "不予存储" : request.Messages?.LastOrDefault().Content ?? string.Empty,
|
||||
ModelId = request.Model,
|
||||
TokenUsage = data.Usage,
|
||||
});
|
||||
@@ -132,12 +147,23 @@ public class AiGateWayManager : DomainService
|
||||
await _aiMessageManager.CreateSystemMessageAsync(userId.Value, sessionId,
|
||||
new MessageInputDto
|
||||
{
|
||||
Content = data.Choices.FirstOrDefault()?.Delta.Content,
|
||||
Content =
|
||||
sessionId is null ? "不予存储" : data.Choices?.FirstOrDefault()?.Delta.Content ?? string.Empty,
|
||||
ModelId = request.Model,
|
||||
TokenUsage = data.Usage
|
||||
});
|
||||
|
||||
await _usageStatisticsManager.SetUsageAsync(userId.Value, request.Model, data.Usage);
|
||||
|
||||
// 扣减尊享token包用量
|
||||
if (PremiumPackageConst.ModeIds.Contains(request.Model))
|
||||
{
|
||||
var totalTokens = data.Usage?.TotalTokens ?? 0;
|
||||
if (totalTokens > 0)
|
||||
{
|
||||
await PremiumPackageManager.TryConsumeTokensAsync(userId.Value, totalTokens);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
await response.WriteAsJsonAsync(data, cancellationToken);
|
||||
@@ -195,6 +221,11 @@ public class AiGateWayManager : DomainService
|
||||
// 如果没有完成,才等待,已完成,全部输出
|
||||
await Task.Delay(outputInterval, cancellationToken).ConfigureAwait(false);
|
||||
}
|
||||
else
|
||||
{
|
||||
//已经完成了,也等待,但是速度可以放快
|
||||
await Task.Delay(10, cancellationToken).ConfigureAwait(false);
|
||||
}
|
||||
}
|
||||
}, cancellationToken);
|
||||
|
||||
@@ -204,7 +235,7 @@ public class AiGateWayManager : DomainService
|
||||
{
|
||||
await foreach (var data in completeChatResponse)
|
||||
{
|
||||
if (data.Usage is not null)
|
||||
if (data.Usage is not null && (data.Usage.CompletionTokens > 0 || data.Usage.OutputTokens > 0))
|
||||
{
|
||||
tokenUsage = data.Usage;
|
||||
}
|
||||
@@ -251,7 +282,7 @@ public class AiGateWayManager : DomainService
|
||||
await _aiMessageManager.CreateUserMessageAsync(userId, sessionId,
|
||||
new MessageInputDto
|
||||
{
|
||||
Content = request.Messages?.LastOrDefault()?.Content ?? string.Empty,
|
||||
Content = sessionId is null ? "不予存储" : request.Messages?.LastOrDefault()?.Content ?? string.Empty,
|
||||
ModelId = request.Model,
|
||||
TokenUsage = tokenUsage,
|
||||
});
|
||||
@@ -259,12 +290,22 @@ public class AiGateWayManager : DomainService
|
||||
await _aiMessageManager.CreateSystemMessageAsync(userId, sessionId,
|
||||
new MessageInputDto
|
||||
{
|
||||
Content = backupSystemContent.ToString(),
|
||||
Content = sessionId is null ? "不予存储" : backupSystemContent.ToString(),
|
||||
ModelId = request.Model,
|
||||
TokenUsage = tokenUsage
|
||||
});
|
||||
|
||||
await _usageStatisticsManager.SetUsageAsync(userId, request.Model, tokenUsage);
|
||||
|
||||
// 扣减尊享token包用量
|
||||
if (userId is not null && PremiumPackageConst.ModeIds.Contains(request.Model))
|
||||
{
|
||||
var totalTokens = tokenUsage.TotalTokens ?? 0;
|
||||
if (totalTokens > 0)
|
||||
{
|
||||
await PremiumPackageManager.TryConsumeTokensAsync(userId.Value, totalTokens);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
@@ -285,7 +326,7 @@ public class AiGateWayManager : DomainService
|
||||
var model = request.Model;
|
||||
if (string.IsNullOrEmpty(model)) model = "dall-e-2";
|
||||
|
||||
var modelDescribe = await GetModelAsync(model);
|
||||
var modelDescribe = await GetModelAsync(ModelApiTypeEnum.OpenAi, model);
|
||||
|
||||
// 获取渠道指定的实现类型的服务
|
||||
var imageService =
|
||||
@@ -303,7 +344,7 @@ public class AiGateWayManager : DomainService
|
||||
await _aiMessageManager.CreateUserMessageAsync(userId, sessionId,
|
||||
new MessageInputDto
|
||||
{
|
||||
Content = request.Prompt,
|
||||
Content = sessionId is null ? "不予存储" : request.Prompt,
|
||||
ModelId = model,
|
||||
TokenUsage = response.Usage,
|
||||
});
|
||||
@@ -311,12 +352,22 @@ public class AiGateWayManager : DomainService
|
||||
await _aiMessageManager.CreateSystemMessageAsync(userId, sessionId,
|
||||
new MessageInputDto
|
||||
{
|
||||
Content = response.Results?.FirstOrDefault()?.Url,
|
||||
Content = sessionId is null ? "不予存储" : response.Results?.FirstOrDefault()?.Url,
|
||||
ModelId = model,
|
||||
TokenUsage = response.Usage
|
||||
});
|
||||
|
||||
await _usageStatisticsManager.SetUsageAsync(userId, model, response.Usage);
|
||||
|
||||
// 扣减尊享token包用量
|
||||
if (userId is not null && PremiumPackageConst.ModeIds.Contains(request.Model))
|
||||
{
|
||||
var totalTokens = response.Usage.TotalTokens ?? 0;
|
||||
if (totalTokens > 0)
|
||||
{
|
||||
await PremiumPackageManager.TryConsumeTokensAsync(userId.Value, totalTokens);
|
||||
}
|
||||
}
|
||||
}
|
||||
catch (Exception e)
|
||||
{
|
||||
@@ -345,7 +396,7 @@ public class AiGateWayManager : DomainService
|
||||
using var embedding =
|
||||
Activity.Current?.Source.StartActivity("向量模型调用");
|
||||
|
||||
var modelDescribe = await GetModelAsync(input.Model);
|
||||
var modelDescribe = await GetModelAsync(ModelApiTypeEnum.OpenAi, input.Model);
|
||||
|
||||
// 获取渠道指定的实现类型的服务
|
||||
var embeddingService =
|
||||
@@ -389,7 +440,7 @@ public class AiGateWayManager : DomainService
|
||||
|
||||
var usage = new ThorUsageResponse()
|
||||
{
|
||||
PromptTokens = stream.Usage?.PromptTokens??0,
|
||||
PromptTokens = stream.Usage?.PromptTokens ?? 0,
|
||||
InputTokens = stream.Usage?.InputTokens ?? 0,
|
||||
CompletionTokens = 0,
|
||||
TotalTokens = stream.Usage?.InputTokens ?? 0
|
||||
@@ -436,4 +487,210 @@ public class AiGateWayManager : DomainService
|
||||
throw new UserFriendlyException(errorContent);
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
/// <summary>
|
||||
/// Anthropic聊天完成-流式
|
||||
/// </summary>
|
||||
/// <param name="request"></param>
|
||||
/// <param name="cancellationToken"></param>
|
||||
/// <returns></returns>
|
||||
public async IAsyncEnumerable<(string, AnthropicStreamDto?)> AnthropicCompleteChatStreamAsync(
|
||||
AnthropicInput request,
|
||||
[EnumeratorCancellation] CancellationToken cancellationToken)
|
||||
{
|
||||
_specialCompatible.AnthropicCompatible(request);
|
||||
var modelDescribe = await GetModelAsync(ModelApiTypeEnum.Claude, request.Model);
|
||||
var chatService =
|
||||
LazyServiceProvider.GetRequiredKeyedService<IAnthropicChatCompletionService>(modelDescribe.HandlerName);
|
||||
|
||||
await foreach (var result in chatService.StreamChatCompletionsAsync(modelDescribe, request, cancellationToken))
|
||||
{
|
||||
yield return result;
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
/// <summary>
|
||||
/// Anthropic聊天完成-非流式
|
||||
/// </summary>
|
||||
/// <param name="httpContext"></param>
|
||||
/// <param name="request"></param>
|
||||
/// <param name="userId"></param>
|
||||
/// <param name="sessionId"></param>
|
||||
/// <param name="cancellationToken"></param>
|
||||
/// <returns></returns>
|
||||
public async Task AnthropicCompleteChatForStatisticsAsync(HttpContext httpContext,
|
||||
AnthropicInput request,
|
||||
Guid? userId = null,
|
||||
Guid? sessionId = null,
|
||||
CancellationToken cancellationToken = default)
|
||||
{
|
||||
_specialCompatible.AnthropicCompatible(request);
|
||||
var response = httpContext.Response;
|
||||
// 设置响应头,声明是 json
|
||||
//response.ContentType = "application/json; charset=UTF-8";
|
||||
var modelDescribe = await GetModelAsync(ModelApiTypeEnum.Claude, request.Model);
|
||||
var chatService =
|
||||
LazyServiceProvider.GetRequiredKeyedService<IAnthropicChatCompletionService>(modelDescribe.HandlerName);
|
||||
var data = await chatService.ChatCompletionsAsync(modelDescribe, request, cancellationToken);
|
||||
if (userId is not null)
|
||||
{
|
||||
await _aiMessageManager.CreateUserMessageAsync(userId.Value, sessionId,
|
||||
new MessageInputDto
|
||||
{
|
||||
Content = sessionId is null ? "不予存储" : request.Messages?.FirstOrDefault()?.Content ?? string.Empty,
|
||||
ModelId = request.Model,
|
||||
TokenUsage = data.TokenUsage,
|
||||
});
|
||||
|
||||
await _aiMessageManager.CreateSystemMessageAsync(userId.Value, sessionId,
|
||||
new MessageInputDto
|
||||
{
|
||||
Content = sessionId is null ? "不予存储" : data.content?.FirstOrDefault()?.text,
|
||||
ModelId = request.Model,
|
||||
TokenUsage = data.TokenUsage
|
||||
});
|
||||
|
||||
await _usageStatisticsManager.SetUsageAsync(userId.Value, request.Model, data.TokenUsage);
|
||||
|
||||
// 扣减尊享token包用量
|
||||
var totalTokens = data.TokenUsage.TotalTokens ?? 0;
|
||||
if (totalTokens > 0)
|
||||
{
|
||||
await PremiumPackageManager.TryConsumeTokensAsync(userId.Value, totalTokens);
|
||||
}
|
||||
}
|
||||
|
||||
await response.WriteAsJsonAsync(data, cancellationToken);
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Anthropic聊天完成-缓存处理
|
||||
/// </summary>
|
||||
/// <param name="httpContext"></param>
|
||||
/// <param name="request"></param>
|
||||
/// <param name="userId"></param>
|
||||
/// <param name="sessionId"></param>
|
||||
/// <param name="cancellationToken"></param>
|
||||
/// <returns></returns>
|
||||
public async Task AnthropicCompleteChatStreamForStatisticsAsync(
|
||||
HttpContext httpContext,
|
||||
AnthropicInput request,
|
||||
Guid? userId = null,
|
||||
Guid? sessionId = null,
|
||||
CancellationToken cancellationToken = default)
|
||||
{
|
||||
var response = httpContext.Response;
|
||||
// 设置响应头,声明是 SSE 流
|
||||
response.ContentType = "text/event-stream;charset=utf-8;";
|
||||
response.Headers.TryAdd("Cache-Control", "no-cache");
|
||||
response.Headers.TryAdd("Connection", "keep-alive");
|
||||
|
||||
|
||||
var gateWay = LazyServiceProvider.GetRequiredService<AiGateWayManager>();
|
||||
var completeChatResponse = gateWay.AnthropicCompleteChatStreamAsync(request, cancellationToken);
|
||||
ThorUsageResponse? tokenUsage = null;
|
||||
StringBuilder backupSystemContent = new StringBuilder();
|
||||
try
|
||||
{
|
||||
await foreach (var responseResult in completeChatResponse)
|
||||
{
|
||||
//message_start是为了保底机制
|
||||
if (responseResult.Item1.Contains("message_delta") || responseResult.Item1.Contains("message_start"))
|
||||
{
|
||||
tokenUsage = responseResult.Item2?.TokenUsage;
|
||||
}
|
||||
|
||||
backupSystemContent.Append(responseResult.Item2?.Delta?.Text);
|
||||
await WriteAsEventStreamDataAsync(httpContext, responseResult.Item1, responseResult.Item2,
|
||||
cancellationToken);
|
||||
}
|
||||
}
|
||||
catch (Exception e)
|
||||
{
|
||||
_logger.LogError(e, $"Ai对话异常");
|
||||
var errorContent = $"对话Ai异常,异常信息:\n当前Ai模型:{request.Model}\n异常信息:{e.Message}\n异常堆栈:{e}";
|
||||
throw new UserFriendlyException(errorContent);
|
||||
}
|
||||
|
||||
await _aiMessageManager.CreateUserMessageAsync(userId, sessionId,
|
||||
new MessageInputDto
|
||||
{
|
||||
Content = sessionId is null ? "不予存储" : request.Messages?.LastOrDefault()?.Content ?? string.Empty,
|
||||
ModelId = request.Model,
|
||||
TokenUsage = tokenUsage,
|
||||
});
|
||||
|
||||
await _aiMessageManager.CreateSystemMessageAsync(userId, sessionId,
|
||||
new MessageInputDto
|
||||
{
|
||||
Content = sessionId is null ? "不予存储" : backupSystemContent.ToString(),
|
||||
ModelId = request.Model,
|
||||
TokenUsage = tokenUsage
|
||||
});
|
||||
|
||||
await _usageStatisticsManager.SetUsageAsync(userId, request.Model, tokenUsage);
|
||||
|
||||
// 扣减尊享token包用量
|
||||
if (userId.HasValue && tokenUsage is not null)
|
||||
{
|
||||
var totalTokens = tokenUsage.TotalTokens ?? 0;
|
||||
if (tokenUsage.TotalTokens > 0)
|
||||
{
|
||||
await PremiumPackageManager.TryConsumeTokensAsync(userId.Value, totalTokens);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
#region Anthropic格式Http响应
|
||||
|
||||
private static readonly byte[] EventPrefix = "event: "u8.ToArray();
|
||||
private static readonly byte[] DataPrefix = "data: "u8.ToArray();
|
||||
private static readonly byte[] NewLine = "\n"u8.ToArray();
|
||||
private static readonly byte[] DoubleNewLine = "\n\n"u8.ToArray();
|
||||
|
||||
/// <summary>
|
||||
/// 使用 JsonSerializer.SerializeAsync 直接序列化到响应流
|
||||
/// </summary>
|
||||
private static async ValueTask WriteAsEventStreamDataAsync<T>(
|
||||
HttpContext context,
|
||||
string @event,
|
||||
T value,
|
||||
CancellationToken cancellationToken = default)
|
||||
where T : class
|
||||
{
|
||||
var response = context.Response;
|
||||
var bodyStream = response.Body;
|
||||
// 确保 SSE Header 已经设置好
|
||||
// e.g. Content-Type: text/event-stream; charset=utf-8
|
||||
await response.StartAsync(cancellationToken).ConfigureAwait(false);
|
||||
// 写事件类型
|
||||
await bodyStream.WriteAsync(EventPrefix, cancellationToken).ConfigureAwait(false);
|
||||
await WriteUtf8StringAsync(bodyStream, @event.Trim(), cancellationToken).ConfigureAwait(false);
|
||||
await bodyStream.WriteAsync(NewLine, cancellationToken).ConfigureAwait(false);
|
||||
// 写 data: + JSON
|
||||
await bodyStream.WriteAsync(DataPrefix, cancellationToken).ConfigureAwait(false);
|
||||
await JsonSerializer.SerializeAsync(
|
||||
bodyStream,
|
||||
value,
|
||||
ThorJsonSerializer.DefaultOptions,
|
||||
cancellationToken
|
||||
).ConfigureAwait(false);
|
||||
// 事件结束 \n\n
|
||||
await bodyStream.WriteAsync(DoubleNewLine, cancellationToken).ConfigureAwait(false);
|
||||
// 及时把数据发送给客户端
|
||||
await bodyStream.FlushAsync(cancellationToken).ConfigureAwait(false);
|
||||
}
|
||||
|
||||
|
||||
private static async ValueTask WriteUtf8StringAsync(Stream stream, string value, CancellationToken token)
|
||||
{
|
||||
if (string.IsNullOrEmpty(value))
|
||||
return;
|
||||
var buffer = Encoding.UTF8.GetBytes(value);
|
||||
await stream.WriteAsync(buffer, token).ConfigureAwait(false);
|
||||
}
|
||||
|
||||
#endregion
|
||||
}
|
||||
@@ -2,6 +2,7 @@
|
||||
using Volo.Abp.Domain.Services;
|
||||
using Yi.Framework.AiHub.Domain.Entities;
|
||||
using Yi.Framework.AiHub.Domain.Entities.OpenApi;
|
||||
using Yi.Framework.AiHub.Domain.Shared.Enums;
|
||||
using Yi.Framework.SqlSugarCore.Abstractions;
|
||||
|
||||
namespace Yi.Framework.AiHub.Domain.Managers;
|
||||
@@ -28,7 +29,7 @@ public class AiRechargeManager : DomainService
|
||||
var currentTime = DateTime.Now;
|
||||
|
||||
// 查找所有充值记录,按用户分组
|
||||
var allRecharges = await _rechargeRepository._DbQueryable
|
||||
var allRecharges = await _rechargeRepository._DbQueryable.Where(x => x.RechargeType == RechargeTypeEnum.Vip)
|
||||
.ToListAsync();
|
||||
|
||||
if (!allRecharges.Any())
|
||||
|
||||
@@ -0,0 +1,356 @@
|
||||
using Microsoft.Extensions.Logging;
|
||||
using Volo.Abp.Domain.Services;
|
||||
using Yi.Framework.AiHub.Domain.Entities;
|
||||
using Yi.Framework.SqlSugarCore.Abstractions;
|
||||
|
||||
namespace Yi.Framework.AiHub.Domain.Managers;
|
||||
|
||||
/// <summary>
|
||||
/// 翻牌管理器 - 负责翻牌核心业务逻辑
|
||||
/// </summary>
|
||||
public class CardFlipManager : DomainService
|
||||
{
|
||||
private readonly ISqlSugarRepository<CardFlipTaskAggregateRoot> _cardFlipTaskRepository;
|
||||
private readonly ISqlSugarRepository<InvitationRecordAggregateRoot> _invitationRecordRepository;
|
||||
private readonly InviteCodeManager _inviteCodeManager;
|
||||
private readonly ILogger<CardFlipManager> _logger;
|
||||
|
||||
// 翻牌规则配置
|
||||
public const int MAX_FREE_FLIPS = 7; // 免费翻牌次数
|
||||
public const int MAX_INVITE_FLIPS = 3; // 邀请解锁翻牌次数
|
||||
public const int TOTAL_MAX_FLIPS = 10; // 总最大翻牌次数
|
||||
|
||||
private const int EIGHTH_FLIP = 8; // 第8次翻牌
|
||||
private const int NINTH_FLIP = 9; // 第9次翻牌
|
||||
private const int TENTH_FLIP = 10; // 第10次翻牌
|
||||
|
||||
// 前7次免费翻牌奖励配置
|
||||
private const long FREE_MIN_REWARD = 10000; // 前7次最小奖励 1w
|
||||
private const long FREE_MAX_REWARD = 30000; // 前7次最大奖励 3w
|
||||
private const double FREE_WIN_RATE = 0.5; // 前7次中奖概率 50%
|
||||
|
||||
private const long EIGHTH_MIN_REWARD = 1000000; // 第8次最小奖励 100w
|
||||
private const long EIGHTH_MAX_REWARD = 3000000; // 第8次最大奖励 300w
|
||||
private const long NINTH_MIN_REWARD = 1000000; // 第9次最小奖励 100w
|
||||
private const long NINTH_MAX_REWARD = 5000000; // 第9次最大奖励 500w
|
||||
private const long TENTH_MIN_REWARD = 1000000; // 第10次最小奖励 100w
|
||||
private const long TENTH_MAX_REWARD = 10000000; // 第10次最大奖励 1000w
|
||||
|
||||
public CardFlipManager(
|
||||
ISqlSugarRepository<CardFlipTaskAggregateRoot> cardFlipTaskRepository,
|
||||
ISqlSugarRepository<InvitationRecordAggregateRoot> invitationRecordRepository,
|
||||
InviteCodeManager inviteCodeManager,
|
||||
ILogger<CardFlipManager> logger)
|
||||
{
|
||||
_cardFlipTaskRepository = cardFlipTaskRepository;
|
||||
_invitationRecordRepository = invitationRecordRepository;
|
||||
_inviteCodeManager = inviteCodeManager;
|
||||
_logger = logger;
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// 获取或创建本周任务
|
||||
/// </summary>
|
||||
public async Task<CardFlipTaskAggregateRoot?> GetOrCreateWeeklyTaskAsync(
|
||||
Guid userId,
|
||||
DateTime weekStart,
|
||||
bool createIfNotExists)
|
||||
{
|
||||
var task = await _cardFlipTaskRepository._DbQueryable
|
||||
.Where(x => x.UserId == userId && x.WeekStartDate == weekStart)
|
||||
.FirstAsync();
|
||||
|
||||
if (task == null && createIfNotExists)
|
||||
{
|
||||
task = new CardFlipTaskAggregateRoot(userId, weekStart);
|
||||
await _cardFlipTaskRepository.InsertAsync(task);
|
||||
}
|
||||
|
||||
return task;
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// 获取已翻牌的顺序列表
|
||||
/// </summary>
|
||||
public List<int> GetFlippedOrder(CardFlipTaskAggregateRoot task)
|
||||
{
|
||||
return task.FlippedOrder ?? new List<int>();
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// 执行翻牌逻辑
|
||||
/// </summary>
|
||||
/// <param name="userId">用户ID</param>
|
||||
/// <param name="flipNumber">翻牌序号</param>
|
||||
/// <param name="weekStart">本周开始日期</param>
|
||||
/// <returns>翻牌结果</returns>
|
||||
public async Task<FlipResult> ExecuteFlipAsync(Guid userId, int flipNumber, DateTime weekStart)
|
||||
{
|
||||
// 验证翻牌序号
|
||||
if (flipNumber < 1 || flipNumber > TOTAL_MAX_FLIPS)
|
||||
{
|
||||
throw new UserFriendlyException($"翻牌序号必须在1-{TOTAL_MAX_FLIPS}之间");
|
||||
}
|
||||
|
||||
// 获取或创建本周任务
|
||||
var task = await GetOrCreateWeeklyTaskAsync(userId, weekStart, createIfNotExists: true);
|
||||
|
||||
// 验证翻牌次数
|
||||
if (task.TotalFlips >= TOTAL_MAX_FLIPS)
|
||||
{
|
||||
throw new UserFriendlyException("本周翻牌次数已用完,请下周再来!");
|
||||
}
|
||||
|
||||
// 验证该牌是否已经翻过
|
||||
var flippedOrder = GetFlippedOrder(task);
|
||||
if (flippedOrder.Contains(flipNumber))
|
||||
{
|
||||
throw new UserFriendlyException($"第 {flipNumber} 号牌已经翻过了!");
|
||||
}
|
||||
|
||||
// 判断翻牌类型
|
||||
var flipType = DetermineFlipType(task);
|
||||
|
||||
// 验证是否有足够的次数
|
||||
if (!CanUseFlipType(task, flipType))
|
||||
{
|
||||
throw new UserFriendlyException(GetFlipTypeErrorMessage(flipType));
|
||||
}
|
||||
|
||||
// 如果是邀请类型翻牌,必须验证用户本周的邀请记录数量足够(包括填写别人的邀请码和别人填写我的邀请码)
|
||||
if (flipType == FlipType.Invite)
|
||||
{
|
||||
// 查询本周作为邀请人或被邀请人的记录数量(双方都会增加翻牌次数)
|
||||
var weeklyInviteRecordCount = await _invitationRecordRepository._DbQueryable
|
||||
.Where(x => x.InviterId == userId || x.InvitedUserId == userId)
|
||||
.Where(x => x.InvitationTime >= weekStart)
|
||||
.CountAsync();
|
||||
|
||||
// 本周邀请记录数量必须 >= 即将使用的邀请翻牌次数
|
||||
// 例如: 要翻第8次(InviteFlipsUsed=0->1), 需要至少有1条邀请记录(我邀请别人或别人邀请我)
|
||||
// 要翻第9次(InviteFlipsUsed=1->2), 需要至少有2条邀请记录
|
||||
// 要翻第10次(InviteFlipsUsed=2->3), 需要至少有3条邀请记录
|
||||
var requiredInviteRecordCount = task.InviteFlipsUsed + 1;
|
||||
if (weeklyInviteRecordCount < requiredInviteRecordCount)
|
||||
{
|
||||
throw new UserFriendlyException($"需本周累积{requiredInviteRecordCount}次邀请记录(填写别人的邀请码或别人填写你的邀请码)才能解锁第{task.TotalFlips + 1}次翻牌");
|
||||
}
|
||||
}
|
||||
|
||||
// 计算翻牌结果(基于当前是第几次翻牌,而不是卡片序号)
|
||||
var flipCount = task.TotalFlips + 1; // 当前这次翻牌是第几次
|
||||
var result = CalculateFlipResult(flipCount);
|
||||
|
||||
// 将卡片序号信息也返回
|
||||
result.FlipNumber = flipNumber;
|
||||
|
||||
// 更新翻牌次数(必须在记录奖励之前,因为需要先确定是第几次)
|
||||
task.IncrementFlip(flipType);
|
||||
|
||||
// 记录翻牌顺序
|
||||
if (task.FlippedOrder == null)
|
||||
{
|
||||
task.FlippedOrder = new List<int>();
|
||||
}
|
||||
task.FlippedOrder.Add(flipNumber);
|
||||
|
||||
// 如果中奖,记录奖励金额(用于后续查询显示)
|
||||
if (result.IsWin)
|
||||
{
|
||||
task.SetWinReward(flipCount, result.RewardAmount);
|
||||
}
|
||||
|
||||
await _cardFlipTaskRepository.UpdateAsync(task);
|
||||
|
||||
_logger.LogInformation($"用户 {userId} 完成第 {flipNumber} 次翻牌,中奖:{result.IsWin}");
|
||||
|
||||
return result;
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// 判断是否可以翻牌
|
||||
/// </summary>
|
||||
public bool CanFlipCard(CardFlipTaskAggregateRoot? task)
|
||||
{
|
||||
if (task == null) return true; // 没有任务记录,可以开始翻牌
|
||||
|
||||
return task.TotalFlips < TOTAL_MAX_FLIPS;
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// 判断翻牌类型
|
||||
/// </summary>
|
||||
public FlipType DetermineFlipType(CardFlipTaskAggregateRoot task)
|
||||
{
|
||||
if (task.FreeFlipsUsed < MAX_FREE_FLIPS)
|
||||
{
|
||||
return FlipType.Free;
|
||||
}
|
||||
else
|
||||
{
|
||||
return FlipType.Invite;
|
||||
}
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// 判断是否可以使用该翻牌类型
|
||||
/// </summary>
|
||||
public bool CanUseFlipType(CardFlipTaskAggregateRoot task, FlipType flipType)
|
||||
{
|
||||
return flipType switch
|
||||
{
|
||||
FlipType.Free => task.FreeFlipsUsed < MAX_FREE_FLIPS,
|
||||
FlipType.Invite => task.InviteFlipsUsed < MAX_INVITE_FLIPS,
|
||||
_ => false
|
||||
};
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// 计算翻牌结果
|
||||
/// </summary>
|
||||
/// <param name="flipCount">第几次翻牌(1-10)</param>
|
||||
private FlipResult CalculateFlipResult(int flipCount)
|
||||
{
|
||||
var result = new FlipResult
|
||||
{
|
||||
FlipNumber = 0, // 稍后会被设置为实际的卡片序号
|
||||
IsWin = false
|
||||
};
|
||||
|
||||
var random = new Random();
|
||||
|
||||
// 前7次: 50%概率中奖,奖励1w-3w
|
||||
if (flipCount <= 7)
|
||||
{
|
||||
// 50%概率中奖
|
||||
if (random.NextDouble() < FREE_WIN_RATE)
|
||||
{
|
||||
var rewardAmount = GenerateRandomReward(FREE_MIN_REWARD, FREE_MAX_REWARD);
|
||||
result.IsWin = true;
|
||||
result.RewardAmount = rewardAmount;
|
||||
result.RewardDesc = $"恭喜获得尊享包 {rewardAmount / 10000m:0.##}w tokens!";
|
||||
}
|
||||
else
|
||||
{
|
||||
result.IsWin = false;
|
||||
result.RewardDesc = "很遗憾,未中奖";
|
||||
}
|
||||
}
|
||||
// 第8次中奖 (邀请码解锁)
|
||||
else if (flipCount == EIGHTH_FLIP)
|
||||
{
|
||||
var rewardAmount = GenerateRandomReward(EIGHTH_MIN_REWARD, EIGHTH_MAX_REWARD);
|
||||
result.IsWin = true;
|
||||
result.RewardAmount = rewardAmount;
|
||||
result.RewardDesc = $"恭喜获得尊享包 {rewardAmount / 10000}w tokens!";
|
||||
}
|
||||
// 第9次中奖 (邀请码解锁)
|
||||
else if (flipCount == NINTH_FLIP)
|
||||
{
|
||||
var rewardAmount = GenerateRandomReward(NINTH_MIN_REWARD, NINTH_MAX_REWARD);
|
||||
result.IsWin = true;
|
||||
result.RewardAmount = rewardAmount;
|
||||
result.RewardDesc = $"恭喜获得尊享包 {rewardAmount / 10000}w tokens!";
|
||||
}
|
||||
// 第10次中奖 (邀请码解锁)
|
||||
else if (flipCount == TENTH_FLIP)
|
||||
{
|
||||
var rewardAmount = GenerateRandomReward(TENTH_MIN_REWARD, TENTH_MAX_REWARD);
|
||||
result.IsWin = true;
|
||||
result.RewardAmount = rewardAmount;
|
||||
result.RewardDesc = $"恭喜获得尊享包 {rewardAmount / 10000}w tokens!";
|
||||
}
|
||||
|
||||
return result;
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// 获取翻牌类型错误提示
|
||||
/// </summary>
|
||||
private string GetFlipTypeErrorMessage(FlipType flipType)
|
||||
{
|
||||
return flipType switch
|
||||
{
|
||||
FlipType.Free => "免费翻牌次数已用完",
|
||||
FlipType.Invite => "需要使用邀请码解锁更多次数",
|
||||
_ => "无法翻牌"
|
||||
};
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// 生成随机奖励金额
|
||||
/// </summary>
|
||||
private long GenerateRandomReward(long min, long max)
|
||||
{
|
||||
var random = new Random();
|
||||
|
||||
// 根据最小值判断单位
|
||||
// 如果min小于100000,则使用1w(10000)作为单位;否则使用100w(1000000)作为单位
|
||||
long unit = min < 100000 ? 10000 : 1000000;
|
||||
|
||||
// 将min和max转换为单位的倍数
|
||||
long minUnits = min / unit;
|
||||
long maxUnits = max / unit;
|
||||
|
||||
// 在倍数范围内随机
|
||||
long randomUnits = random.Next((int)minUnits, (int)maxUnits + 1);
|
||||
|
||||
// 返回单位的倍数
|
||||
return randomUnits * unit;
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// 获取本周开始日期(周一)
|
||||
/// </summary>
|
||||
public static DateTime GetWeekStartDate(DateTime date)
|
||||
{
|
||||
var dayOfWeek = (int)date.DayOfWeek;
|
||||
// 将周日(0)转换为7
|
||||
if (dayOfWeek == 0) dayOfWeek = 7;
|
||||
|
||||
// 计算本周一的日期
|
||||
var monday = date.Date.AddDays(-(dayOfWeek - 1));
|
||||
return monday;
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// 获取翻牌类型描述
|
||||
/// </summary>
|
||||
public static string GetFlipTypeDesc(int flipNumber)
|
||||
{
|
||||
if (flipNumber <= MAX_FREE_FLIPS)
|
||||
{
|
||||
return "免费";
|
||||
}
|
||||
else
|
||||
{
|
||||
return "邀请解锁";
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// 翻牌结果
|
||||
/// </summary>
|
||||
public class FlipResult
|
||||
{
|
||||
/// <summary>
|
||||
/// 翻牌序号
|
||||
/// </summary>
|
||||
public int FlipNumber { get; set; }
|
||||
|
||||
/// <summary>
|
||||
/// 是否中奖
|
||||
/// </summary>
|
||||
public bool IsWin { get; set; }
|
||||
|
||||
/// <summary>
|
||||
/// 奖励金额
|
||||
/// </summary>
|
||||
public long RewardAmount { get; set; }
|
||||
|
||||
/// <summary>
|
||||
/// 奖励描述
|
||||
/// </summary>
|
||||
public string RewardDesc { get; set; } = string.Empty;
|
||||
}
|
||||
Some files were not shown because too many files have changed in this diff Show More
Reference in New Issue
Block a user