mirror of
https://gitee.com/ccnetcore/Yi
synced 2026-03-19 16:06:36 +08:00
Compare commits
231 Commits
invitation
...
ai-agent
| Author | SHA1 | Date | |
|---|---|---|---|
|
|
67cb142c07 | ||
|
|
f164b7dccc | ||
|
|
6cc14c1e32 | ||
|
|
e992cfc928 | ||
|
|
42edd4c230 | ||
|
|
3892ff1937 | ||
|
|
12878ba022 | ||
|
|
a3259ad36f | ||
|
|
5bb7dfb7cd | ||
|
|
3447e2dc5d | ||
|
|
88fae0cdc2 | ||
|
|
5a7f0ab108 | ||
|
|
be5f57f654 | ||
|
|
a6e7a5e906 | ||
|
|
c4ab176089 | ||
|
|
a50f877964 | ||
|
|
28cdc29369 | ||
|
|
e39cbaf5e7 | ||
|
|
9d1dd72584 | ||
|
|
ea403fcae0 | ||
|
|
91533909c2 | ||
|
|
61d5d40dbb | ||
|
|
38dbd0aca7 | ||
|
|
343347ea11 | ||
|
|
a9e11d161c | ||
|
|
d25ca6dc4a | ||
|
|
ba95d1798f | ||
|
|
436b5b910c | ||
|
|
560a76558a | ||
|
|
a1be2bebf7 | ||
|
|
3f53eb14ab | ||
|
|
e46044e217 | ||
|
|
80dcd76749 | ||
|
|
9c842ab802 | ||
|
|
b8c0f9a212 | ||
|
|
6cc0059691 | ||
|
|
33d28a8cb0 | ||
|
|
e4621d9049 | ||
|
|
953fbc043b | ||
|
|
c649ad31c2 | ||
|
|
50fc8c5f0a | ||
|
|
64bc65114a | ||
|
|
ae9d778ac7 | ||
|
|
77a9a64a41 | ||
|
|
19ea76bd60 | ||
|
|
0c31b97824 | ||
|
|
70ae2fab44 | ||
|
|
411a9058ca | ||
|
|
4b9f845fae | ||
|
|
bdaa53bac8 | ||
|
|
e5b81c08f3 | ||
|
|
1ffab89e97 | ||
|
|
5440b226c4 | ||
|
|
90c6022839 | ||
|
|
184467e482 | ||
|
|
68045d6458 | ||
|
|
d52f17a17b | ||
|
|
047937af4c | ||
|
|
a9267bfc0e | ||
|
|
1019fd685b | ||
|
|
34246d8a62 | ||
|
|
599b6335d5 | ||
|
|
46bc48d1c1 | ||
|
|
17675e702d | ||
|
|
639c683144 | ||
|
|
96a21210b5 | ||
|
|
7495dc86a0 | ||
|
|
ee4cb20eef | ||
|
|
9ca3cd0b1a | ||
|
|
eb6ec06157 | ||
|
|
62940ae25a | ||
|
|
dfc143379f | ||
|
|
bd3a9a5ce8 | ||
|
|
ec4fdc39fe | ||
|
|
3c3e134d2b | ||
|
|
81089cc058 | ||
|
|
681194a517 | ||
|
|
8f515f76c0 | ||
|
|
fcb74eb28c | ||
|
|
44afdaef8e | ||
|
|
41c55d088d | ||
|
|
3b71fe3135 | ||
|
|
4326c41258 | ||
|
|
7f0d57b311 | ||
|
|
75c208dafc | ||
|
|
8021ca9eff | ||
|
|
2cf06a5677 | ||
|
|
2fa42cd8a3 | ||
|
|
a600eb9e7e | ||
|
|
fcf0fd7f70 | ||
|
|
4e421c160c | ||
|
|
340e2016d6 | ||
|
|
5dfaead60e | ||
|
|
c8acb12e4a | ||
|
|
5fbcb8cbd9 | ||
|
|
fd8d4399d3 | ||
|
|
6f1efafd86 | ||
|
|
2714a507d9 | ||
|
|
9a9230786b | ||
|
|
4a8b58a65c | ||
|
|
7d81f88658 | ||
|
|
0ce3c0bbdd | ||
|
|
981235e6e9 | ||
|
|
d0ecb232a1 | ||
|
|
c7a52604e7 | ||
|
|
da81b2d8a3 | ||
|
|
7b14fdd8de | ||
|
|
1fc2734eb7 | ||
|
|
f3bef72ebb | ||
|
|
7e6d2e829b | ||
|
|
944626960b | ||
|
|
c073868989 | ||
|
|
d2981100fa | ||
|
|
ce4f7e5711 | ||
|
|
cc812ba2cb | ||
|
|
8a6e5abf48 | ||
|
|
8b191330b8 | ||
|
|
5ed79c6dd0 | ||
|
|
6e2ca8f1c3 | ||
|
|
a46a552097 | ||
|
|
53e56134d4 | ||
|
|
0d2f2cb826 | ||
|
|
f90105ebb4 | ||
|
|
67ed1ac1e3 | ||
|
|
69b84f6613 | ||
|
|
433d616b9b | ||
|
|
53aa575ad4 | ||
|
|
571df74c43 | ||
|
|
b7847c7e7d | ||
|
|
94eb41996e | ||
|
|
cefde6848d | ||
|
|
381b712b25 | ||
|
|
c319b0b4e4 | ||
|
|
1a32fa9e20 | ||
|
|
909406238c | ||
|
|
54a1d2a66f | ||
|
|
8dcbfcad33 | ||
|
|
f64fd43951 | ||
|
|
551597765c | ||
|
|
bfda33280a | ||
|
|
8d0411f1f4 | ||
|
|
3995d4acab | ||
|
|
6ff5727156 | ||
|
|
f654386dfe | ||
|
|
c03ef82643 | ||
|
|
525545329b | ||
|
|
755cb6f509 | ||
|
|
55469708f0 | ||
|
|
94c52c62fe | ||
|
|
37b4709d76 | ||
|
|
86555af6ce | ||
|
|
ddb00879f4 | ||
|
|
2d0ca08314 | ||
|
|
b78ecf27d5 | ||
|
|
02a5f69958 | ||
|
|
cf5bf746ef | ||
|
|
0a5e40ee25 | ||
|
|
51a266ef58 | ||
|
|
1f0901c90c | ||
|
|
a725c06396 | ||
|
|
54547f0d7c | ||
|
|
afe9c8bcae | ||
|
|
688d93e5c1 | ||
|
|
4c65b2398d | ||
|
|
41435f1aa3 | ||
|
|
20206bbc44 | ||
|
|
f2dc0d1825 | ||
|
|
51b4d1b072 | ||
|
|
9180799e4e | ||
|
|
9788b9182b | ||
|
|
260b9a4795 | ||
|
|
9380e3daa8 | ||
|
|
bb894e14a4 | ||
|
|
b492d82442 | ||
|
|
5eaffe2ec2 | ||
|
|
d7bcad9da7 | ||
|
|
04e11d15e2 | ||
|
|
97e3dc5eed | ||
|
|
695bd56a27 | ||
|
|
7919383be3 | ||
|
|
d6cc3c5d96 | ||
|
|
19f0d05a69 | ||
|
|
3c5e575e9b | ||
|
|
f875617de1 | ||
|
|
9976e8a6e2 | ||
|
|
38e8cbc5ca | ||
|
|
d95c14c903 | ||
|
|
ffb2f2fb4c | ||
|
|
4bd2fc357d | ||
|
|
da23d17af8 | ||
|
|
c1a6046107 | ||
|
|
2ec7b5f4fd | ||
|
|
d21f61646a | ||
|
|
eecdf442fb | ||
|
|
8e8338743d | ||
|
|
1b4c3cbb8d | ||
|
|
b7756e2112 | ||
|
|
cb49059e84 | ||
|
|
690cabfd96 | ||
|
|
4521212a90 | ||
|
|
771ecd9d81 | ||
|
|
94834f45c3 | ||
|
|
a9b2979a21 | ||
|
|
22ac150acd | ||
|
|
17337b8d78 | ||
|
|
09fb43ee14 | ||
|
|
477c0e3f2c | ||
|
|
5beef22269 | ||
|
|
933cbb91d8 | ||
|
|
cf137f6307 | ||
|
|
3e75792e43 | ||
|
|
108ba348f6 | ||
|
|
bcdcec40e0 | ||
|
|
2ce8baea42 | ||
|
|
609de29e71 | ||
|
|
2efed4f4a5 | ||
|
|
1cc5f2a14f | ||
|
|
d9997eeb28 | ||
|
|
06e77aa8fd | ||
|
|
e9e2228f6e | ||
|
|
d516a381d0 | ||
|
|
4e792ba976 | ||
|
|
f90d3871fa | ||
|
|
6005b9329d | ||
|
|
9d4b3e7d0c | ||
|
|
72795382a1 | ||
|
|
35cdff2afa | ||
|
|
dcf547f513 | ||
|
|
8660d45f36 | ||
|
|
63dd55e7a4 | ||
|
|
40cd89f90c |
@@ -1,9 +0,0 @@
|
|||||||
{
|
|
||||||
"permissions": {
|
|
||||||
"allow": [
|
|
||||||
"WebFetch(domain:www.donet5.com)"
|
|
||||||
],
|
|
||||||
"deny": [],
|
|
||||||
"ask": []
|
|
||||||
}
|
|
||||||
}
|
|
||||||
3
.gitignore
vendored
3
.gitignore
vendored
@@ -265,6 +265,7 @@ src/Acme.BookStore.Blazor.Server.Tiered/Logs/*
|
|||||||
**/wwwroot/libs/*
|
**/wwwroot/libs/*
|
||||||
public
|
public
|
||||||
dist
|
dist
|
||||||
|
dist - 副本
|
||||||
.vscode
|
.vscode
|
||||||
/Yi.Abp.Net8/src/Yi.Abp.Web/appsettings.Development.json
|
/Yi.Abp.Net8/src/Yi.Abp.Web/appsettings.Development.json
|
||||||
/Yi.Abp.Net8/src/Yi.Abp.Web/appsettings.Production.json
|
/Yi.Abp.Net8/src/Yi.Abp.Web/appsettings.Production.json
|
||||||
@@ -277,3 +278,5 @@ database_backup
|
|||||||
/Yi.Abp.Net8/src/Yi.Abp.Web/yi-abp-dev.db
|
/Yi.Abp.Net8/src/Yi.Abp.Web/yi-abp-dev.db
|
||||||
|
|
||||||
package-lock.json
|
package-lock.json
|
||||||
|
|
||||||
|
.claude
|
||||||
|
|||||||
10
README.md
10
README.md
@@ -7,6 +7,12 @@
|
|||||||
[](https://gitee.com/ccnetcore/Yi)
|
[](https://gitee.com/ccnetcore/Yi)
|
||||||
[](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) | 简体中文
|
[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) (已上线,欢迎加入)
|
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)
|
||||||
|
|
||||||
## 🍏 支持:
|
## 🍏 支持:
|
||||||
|
|
||||||
|
|||||||
@@ -2,7 +2,8 @@
|
|||||||
"permissions": {
|
"permissions": {
|
||||||
"allow": [
|
"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)",
|
"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/**)"
|
"Read(//e/code/github/Yi/Yi.Ai.Vue3/**)",
|
||||||
|
"Bash(dotnet build:*)"
|
||||||
],
|
],
|
||||||
"deny": [],
|
"deny": [],
|
||||||
"ask": []
|
"ask": []
|
||||||
|
|||||||
129
Yi.Abp.Net8/CLAUDE.md
Normal file
129
Yi.Abp.Net8/CLAUDE.md
Normal file
@@ -0,0 +1,129 @@
|
|||||||
|
# CLAUDE.md
|
||||||
|
|
||||||
|
This file provides guidance to Claude Code (claude.ai/code) when working with code in this repository.
|
||||||
|
|
||||||
|
## Overview
|
||||||
|
|
||||||
|
Yi.Abp.Net8 is a modular, multi-tenant SaaS platform built on ABP Framework 8.3.4 with .NET 8.0. It uses **SqlSugar** (not EF Core) as the ORM and follows Domain-Driven Design (DDD) principles. The platform includes AI/ML features (chat, models, agents, token tracking), RBAC, forum, messaging, and digital collectibles modules.
|
||||||
|
|
||||||
|
## Architecture
|
||||||
|
|
||||||
|
### Solution Structure
|
||||||
|
|
||||||
|
```
|
||||||
|
Yi.Abp.Net8/
|
||||||
|
├── src/ # Main application host
|
||||||
|
│ └── Yi.Abp.Web/ # ASP.NET Core 8.0 Web Host (port 19001)
|
||||||
|
├── framework/ # Framework layer (shared infrastructure)
|
||||||
|
│ ├── Yi.Framework.Core # Core utilities, JSON handling
|
||||||
|
│ ├── Yi.Framework.SqlSugarCore # SqlSugar ORM abstraction (v5.1.4.197-preview22)
|
||||||
|
│ ├── Yi.Framework.SqlSugarCore.Abstractions # Repository interfaces
|
||||||
|
│ ├── Yi.Framework.AspNetCore # ASP.NET Core extensions
|
||||||
|
│ ├── Yi.Framework.AspNetCore.Authentication.OAuth # QQ, Gitee OAuth
|
||||||
|
│ ├── Yi.Framework.Ddd.Application # DDD application base classes
|
||||||
|
│ ├── Yi.Framework.BackgroundWorkers.Hangfire # Job scheduling
|
||||||
|
│ ├── Yi.Framework.Caching.FreeRedis # Redis caching
|
||||||
|
│ └── Yi.Framework.SemanticKernel # AI/ML integration
|
||||||
|
├── module/ # Business modules (each follows 5-layer DDD pattern)
|
||||||
|
│ ├── ai-hub/ # AI services (chat, models, sessions, agents)
|
||||||
|
│ ├── rbac/ # Role-Based Access Control (core auth/authz)
|
||||||
|
│ ├── bbs/ # Forum/community
|
||||||
|
│ ├── chat-hub/ # Real-time messaging
|
||||||
|
│ ├── audit-logging/ # Audit trail tracking
|
||||||
|
│ ├── code-gen/ # Code generation
|
||||||
|
│ ├── tenant-management/ # Multi-tenancy support
|
||||||
|
│ ├── digital-collectibles/ # NFT/digital assets
|
||||||
|
│ └── ai-stock/ # AI-powered stock analysis
|
||||||
|
├── test/ # Unit tests (xUnit + NSubstitute + Shouldly)
|
||||||
|
├── client/ # HTTP API clients
|
||||||
|
└── tool/ # Development utilities
|
||||||
|
```
|
||||||
|
|
||||||
|
### Module Structure (DDD Layers)
|
||||||
|
|
||||||
|
Each module follows this pattern:
|
||||||
|
|
||||||
|
```
|
||||||
|
module/[feature]/
|
||||||
|
├── [Feature].Domain.Shared/ # Constants, enums, shared DTOs
|
||||||
|
├── [Feature].Domain/ # Entities, aggregates, domain services
|
||||||
|
├── [Feature].Application.Contracts/ # Service interfaces, DTOs
|
||||||
|
├── [Feature].Application/ # Application services (implementations)
|
||||||
|
└── [Feature].SqlSugarCore/ # Repository implementations, DbContext
|
||||||
|
```
|
||||||
|
|
||||||
|
**Dependency Flow:** Application → Domain + Application.Contracts → Domain.Shared → Framework
|
||||||
|
|
||||||
|
### Module Registration
|
||||||
|
|
||||||
|
All modules are registered in `src/Yi.Abp.Web/YiAbpWebModule.cs`. When adding a new module:
|
||||||
|
|
||||||
|
1. Add `DependsOn` attribute in `YiAbpWebModule`
|
||||||
|
2. Add conventional controller in `PreConfigureServices`:
|
||||||
|
```csharp
|
||||||
|
options.ConventionalControllers.Create(typeof(YiFramework[Feature]ApplicationModule).Assembly,
|
||||||
|
option => option.RemoteServiceName = "[service-name]");
|
||||||
|
```
|
||||||
|
|
||||||
|
### API Routing
|
||||||
|
|
||||||
|
All API routes use the unified prefix: `/api/app/{service-name}/{controller}/{action}`
|
||||||
|
|
||||||
|
Registered service names:
|
||||||
|
- `default` - Main application services
|
||||||
|
- `rbac` - Authentication, authorization, user/role management
|
||||||
|
- `ai-hub` - AI chat, models, sessions, agents
|
||||||
|
- `bbs` - Forum posts and comments
|
||||||
|
- `chat-hub` - Real-time messaging
|
||||||
|
- `tenant-management` - Multi-tenant configuration
|
||||||
|
- `code-gen` - Code generation utilities
|
||||||
|
- `digital-collectibles` - NFT/digital assets
|
||||||
|
- `ai-stock` - Stock analysis
|
||||||
|
|
||||||
|
## Database
|
||||||
|
|
||||||
|
**ORM:** SqlSugar (NOT Entity Framework Core)
|
||||||
|
|
||||||
|
**Configuration** (`appsettings.json`):
|
||||||
|
```json
|
||||||
|
"DbConnOptions": {
|
||||||
|
"Url": "DataSource=yi-abp-dev.db",
|
||||||
|
"DbType": "Sqlite", // Sqlite, Mysql, Sqlserver, Oracle, PostgreSQL
|
||||||
|
"EnabledCodeFirst": true, // Auto-create tables
|
||||||
|
"EnabledDbSeed": true, // Auto-seed data
|
||||||
|
"EnabledSaasMultiTenancy": true
|
||||||
|
}
|
||||||
|
```
|
||||||
|
|
||||||
|
**Multi-tenancy:** Tenant isolation via `HeaderTenantResolveContributor` (NOT cookie-based). Tenant is resolved from `__tenant` header.
|
||||||
|
|
||||||
|
## Key Technologies
|
||||||
|
|
||||||
|
| Component | Technology |
|
||||||
|
|-----------|-----------|
|
||||||
|
| Framework | ABP 8.3.4 |
|
||||||
|
| .NET Version | .NET 8.0 |
|
||||||
|
| ORM | SqlSugar 5.1.4.197-preview22 |
|
||||||
|
| Authentication | JWT Bearer + Refresh Tokens |
|
||||||
|
| OAuth | QQ, Gitee |
|
||||||
|
| Caching | FreeRedis (optional) |
|
||||||
|
| Background Jobs | Hangfire (in-memory or Redis) |
|
||||||
|
| Logging | Serilog (daily rolling files) |
|
||||||
|
| Testing | xUnit + NSubstitute + Shouldly |
|
||||||
|
| Container | Autofac |
|
||||||
|
|
||||||
|
## Important Notes
|
||||||
|
|
||||||
|
- **JSON Serialization:** Uses Microsoft's `System.Text.Json`, NOT Newtonsoft.Json. Date format handled via `DatetimeJsonConverter`.
|
||||||
|
- **Multi-tenancy:** Tenant resolved from `__tenant` header, NOT cookies.
|
||||||
|
- **Rate Limiting:** Disabled in development, enabled in production (1000 req/60s sliding window).
|
||||||
|
- **Swagger:** Available at `/swagger` in development.
|
||||||
|
- **Hangfire Dashboard:** Available at `/hangfire` (requires JWT authorization).
|
||||||
|
- **Background Workers:** Disabled in development (`AbpBackgroundWorkerOptions.IsEnabled = false`).
|
||||||
|
|
||||||
|
## Development Workflow
|
||||||
|
|
||||||
|
1. **Branch:** Main branch is `abp`, current development branch is `ai-hub`.
|
||||||
|
2. **Commit Convention:** Chinese descriptive messages with prefixes (`feat:`, `fix:`, `style:`).
|
||||||
|
3. **Testing:** Run `dotnet test` before committing.
|
||||||
|
4. **Building:** Use `dotnet build --no-restore` for faster builds after initial restore.
|
||||||
@@ -12,6 +12,7 @@
|
|||||||
</PropertyGroup>
|
</PropertyGroup>
|
||||||
|
|
||||||
<PropertyGroup>
|
<PropertyGroup>
|
||||||
|
<SatelliteResourceLanguages>en;zh-CN</SatelliteResourceLanguages>
|
||||||
<LangVersion>latest</LangVersion>
|
<LangVersion>latest</LangVersion>
|
||||||
<Version>1.0.0</Version>
|
<Version>1.0.0</Version>
|
||||||
<NoWarn>$(NoWarn);CS1591;CS8618;CS1998;CS8604;CS8620;CS8600;CS8602</NoWarn>
|
<NoWarn>$(NoWarn);CS1591;CS8618;CS1998;CS8604;CS8620;CS8600;CS8602</NoWarn>
|
||||||
|
|||||||
@@ -1,4 +1,4 @@
|
|||||||
// MIT 许可证
|
// MIT 许可证
|
||||||
//
|
//
|
||||||
// 版权 © 2020-present 百小僧, 百签科技(广东)有限公司 和所有贡献者
|
// 版权 © 2020-present 百小僧, 百签科技(广东)有限公司 和所有贡献者
|
||||||
//
|
//
|
||||||
@@ -17,25 +17,25 @@ using Microsoft.AspNetCore.Mvc;
|
|||||||
using Microsoft.AspNetCore.Mvc.Filters;
|
using Microsoft.AspNetCore.Mvc.Filters;
|
||||||
using Microsoft.Extensions.DependencyInjection;
|
using Microsoft.Extensions.DependencyInjection;
|
||||||
using Microsoft.Extensions.Logging;
|
using Microsoft.Extensions.Logging;
|
||||||
|
using Newtonsoft.Json;
|
||||||
using Volo.Abp.AspNetCore.Mvc;
|
using Volo.Abp.AspNetCore.Mvc;
|
||||||
using Volo.Abp.DependencyInjection;
|
using Volo.Abp.Validation;
|
||||||
using Yi.Framework.Core.Extensions;
|
using Yi.Framework.Core.Extensions;
|
||||||
|
|
||||||
namespace Yi.Framework.AspNetCore.UnifyResult.Fiters;
|
namespace Yi.Framework.AspNetCore.UnifyResult.Fiters;
|
||||||
|
|
||||||
/// <summary>
|
/// <summary>
|
||||||
/// 友好异常拦截器
|
/// 友好异常拦截器
|
||||||
/// </summary>
|
/// </summary>
|
||||||
public sealed class FriendlyExceptionFilter : IAsyncExceptionFilter
|
public sealed class FriendlyExceptionFilter : IAsyncExceptionFilter
|
||||||
{
|
{
|
||||||
/// <summary>
|
/// <summary>
|
||||||
/// 异常拦截
|
/// 异常拦截
|
||||||
/// </summary>
|
/// </summary>
|
||||||
/// <param name="context"></param>
|
/// <param name="context"></param>
|
||||||
/// <returns></returns>
|
/// <returns></returns>
|
||||||
public async Task OnExceptionAsync(ExceptionContext context)
|
public async Task OnExceptionAsync(ExceptionContext context)
|
||||||
{
|
{
|
||||||
|
|
||||||
// 排除 WebSocket 请求处理
|
// 排除 WebSocket 请求处理
|
||||||
if (context.HttpContext.IsWebSocketRequest()) return;
|
if (context.HttpContext.IsWebSocketRequest()) return;
|
||||||
|
|
||||||
@@ -44,20 +44,23 @@ public sealed class FriendlyExceptionFilter : IAsyncExceptionFilter
|
|||||||
|
|
||||||
// 解析异常信息
|
// 解析异常信息
|
||||||
var exceptionMetadata = GetExceptionMetadata(context);
|
var exceptionMetadata = GetExceptionMetadata(context);
|
||||||
|
var unifyResult = context.GetRequiredService<IUnifyResultProvider>();
|
||||||
IUnifyResultProvider unifyResult = context.GetRequiredService<IUnifyResultProvider>();
|
|
||||||
// 执行规范化异常处理
|
// 执行规范化异常处理
|
||||||
context.Result = unifyResult.OnException(context, exceptionMetadata);
|
context.Result = unifyResult.OnException(context, exceptionMetadata);
|
||||||
|
|
||||||
// 创建日志记录器
|
// 创建日志记录器
|
||||||
var logger = context.HttpContext.RequestServices.GetRequiredService<ILogger<FriendlyExceptionFilter>>();
|
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>
|
||||||
/// 获取异常元数据
|
/// 获取异常元数据
|
||||||
/// </summary>
|
/// </summary>
|
||||||
/// <param name="context"></param>
|
/// <param name="context"></param>
|
||||||
/// <returns></returns>
|
/// <returns></returns>
|
||||||
@@ -74,22 +77,25 @@ public sealed class FriendlyExceptionFilter : IAsyncExceptionFilter
|
|||||||
// 判断是否是 ExceptionContext 或者 ActionExecutedContext
|
// 判断是否是 ExceptionContext 或者 ActionExecutedContext
|
||||||
var exception = context is ExceptionContext exContext
|
var exception = context is ExceptionContext exContext
|
||||||
? exContext.Exception
|
? exContext.Exception
|
||||||
: (
|
: context is ActionExecutedContext edContext
|
||||||
context is ActionExecutedContext edContext
|
? edContext.Exception
|
||||||
? edContext.Exception
|
: default;
|
||||||
: default
|
|
||||||
);
|
if (exception is AbpValidationException validationException)
|
||||||
|
{
|
||||||
|
errors = validationException.ValidationErrors;
|
||||||
|
isValidationException = true;
|
||||||
|
}
|
||||||
|
|
||||||
// 判断是否是友好异常
|
// 判断是否是友好异常
|
||||||
if (exception is UserFriendlyException friendlyException)
|
if (exception is UserFriendlyException friendlyException)
|
||||||
{
|
{
|
||||||
int statusCode2 = 500;
|
var statusCode2 = 500;
|
||||||
int.TryParse(friendlyException.Code, out statusCode2);
|
int.TryParse(friendlyException.Code, out statusCode2);
|
||||||
isFriendlyException = true;
|
isFriendlyException = true;
|
||||||
errorCode = friendlyException.Code;
|
errorCode = friendlyException.Code;
|
||||||
originErrorCode = friendlyException.Code;
|
originErrorCode = friendlyException.Code;
|
||||||
statusCode = statusCode2==0?403:statusCode2;
|
statusCode = statusCode2 == 0 ? 403 : statusCode2;
|
||||||
isValidationException = false;
|
|
||||||
errors = friendlyException.Message;
|
errors = friendlyException.Message;
|
||||||
data = friendlyException.Data;
|
data = friendlyException.Data;
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -2,6 +2,7 @@
|
|||||||
using Microsoft.Extensions.DependencyInjection;
|
using Microsoft.Extensions.DependencyInjection;
|
||||||
using Swashbuckle.AspNetCore.SwaggerGen;
|
using Swashbuckle.AspNetCore.SwaggerGen;
|
||||||
using Volo.Abp.AspNetCore.Mvc.ExceptionHandling;
|
using Volo.Abp.AspNetCore.Mvc.ExceptionHandling;
|
||||||
|
using Volo.Abp.AspNetCore.Mvc.Response;
|
||||||
using Yi.Framework.AspNetCore.UnifyResult.Fiters;
|
using Yi.Framework.AspNetCore.UnifyResult.Fiters;
|
||||||
|
|
||||||
namespace Yi.Framework.AspNetCore.UnifyResult;
|
namespace Yi.Framework.AspNetCore.UnifyResult;
|
||||||
@@ -20,9 +21,10 @@ public static class UnifyResultExtensions
|
|||||||
services.AddTransient<FriendlyExceptionFilter>();
|
services.AddTransient<FriendlyExceptionFilter>();
|
||||||
services.AddMvc(options =>
|
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<SucceededUnifyResultFilter>(99);
|
||||||
options.Filters.AddService<FriendlyExceptionFilter>(100);
|
options.Filters.AddService<FriendlyExceptionFilter>(100);
|
||||||
options.Filters.RemoveAll(x => (x as ServiceFilterAttribute)?.ServiceType == typeof(AbpExceptionFilter));
|
|
||||||
});
|
});
|
||||||
return services;
|
return services;
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -199,11 +199,11 @@ namespace Yi.Framework.Ddd.Application
|
|||||||
/// <summary>
|
/// <summary>
|
||||||
/// 批量删除实体
|
/// 批量删除实体
|
||||||
/// </summary>
|
/// </summary>
|
||||||
/// <param name="ids">实体ID集合</param>
|
/// <param name="id">实体ID集合</param>
|
||||||
[RemoteService(isEnabled: true)]
|
[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>
|
/// <summary>
|
||||||
|
|||||||
@@ -1,7 +1,8 @@
|
|||||||
using Microsoft.Extensions.DependencyInjection;
|
using Microsoft.Extensions.DependencyInjection;
|
||||||
using Volo.Abp.Modularity;
|
using Volo.Abp.Modularity;
|
||||||
using Volo.Abp.ObjectMapping;
|
using Volo.Abp.ObjectMapping;
|
||||||
using Yi.Framework.Core;
|
using Yi.Framework.Core;
|
||||||
|
using Mapster;
|
||||||
|
|
||||||
namespace Yi.Framework.Mapster
|
namespace Yi.Framework.Mapster
|
||||||
{
|
{
|
||||||
@@ -22,7 +23,8 @@ namespace Yi.Framework.Mapster
|
|||||||
public override void ConfigureServices(ServiceConfigurationContext context)
|
public override void ConfigureServices(ServiceConfigurationContext context)
|
||||||
{
|
{
|
||||||
var services = context.Services;
|
var services = context.Services;
|
||||||
|
// 扫描并注册所有映射配置
|
||||||
|
TypeAdapterConfig.GlobalSettings.Scan(AppDomain.CurrentDomain.GetAssemblies());
|
||||||
// 注册Mapster相关服务
|
// 注册Mapster相关服务
|
||||||
services.AddTransient<IAutoObjectMappingProvider, MapsterAutoObjectMappingProvider>();
|
services.AddTransient<IAutoObjectMappingProvider, MapsterAutoObjectMappingProvider>();
|
||||||
services.AddTransient<IObjectMapper, MapsterObjectMapper>();
|
services.AddTransient<IObjectMapper, MapsterObjectMapper>();
|
||||||
|
|||||||
@@ -60,8 +60,8 @@ namespace Yi.Framework.SqlSugarCore.Abstractions
|
|||||||
public bool EnabledSaasMultiTenancy { get; set; } = false;
|
public bool EnabledSaasMultiTenancy { get; set; } = false;
|
||||||
|
|
||||||
/// <summary>
|
/// <summary>
|
||||||
/// 并发乐观锁异常,否则不处理
|
/// 是否开启更新并发乐观锁
|
||||||
/// </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.Linq.Expressions;
|
||||||
using System.Text;
|
|
||||||
using Microsoft.Extensions.Logging;
|
|
||||||
using Microsoft.Extensions.Options;
|
using Microsoft.Extensions.Options;
|
||||||
using Nito.AsyncEx;
|
using Nito.AsyncEx;
|
||||||
using SqlSugar;
|
using SqlSugar;
|
||||||
using Volo.Abp;
|
|
||||||
using Volo.Abp.Auditing;
|
|
||||||
using Volo.Abp.Data;
|
using Volo.Abp.Data;
|
||||||
using Volo.Abp.DependencyInjection;
|
using Volo.Abp.DependencyInjection;
|
||||||
using Volo.Abp.Domain.Entities;
|
using Volo.Abp.Domain.Entities;
|
||||||
@@ -17,18 +12,19 @@ using Yi.Framework.SqlSugarCore.Abstractions;
|
|||||||
|
|
||||||
namespace Yi.Framework.SqlSugarCore.Repositories
|
namespace Yi.Framework.SqlSugarCore.Repositories
|
||||||
{
|
{
|
||||||
public class SqlSugarRepository<TEntity> : ISqlSugarRepository<TEntity>, IRepository<TEntity>
|
public class SqlSugarRepository<TEntity> : ISqlSugarRepository<TEntity>, IRepository<TEntity> where TEntity : class, IEntity, new()
|
||||||
where TEntity : class, IEntity, new()
|
|
||||||
{
|
{
|
||||||
|
[Obsolete("使用GetDbContextAsync()")]
|
||||||
public ISqlSugarClient _Db => AsyncContext.Run(async () => await GetDbContextAsync());
|
public ISqlSugarClient _Db => AsyncContext.Run(async () => await GetDbContextAsync());
|
||||||
|
|
||||||
|
[Obsolete("使用AsQueryable()")]
|
||||||
public ISugarQueryable<TEntity> _DbQueryable => _Db.Queryable<TEntity>();
|
public ISugarQueryable<TEntity> _DbQueryable => _Db.Queryable<TEntity>();
|
||||||
|
|
||||||
private readonly ISugarDbContextProvider<ISqlSugarDbContext> _dbContextProvider;
|
private readonly ISugarDbContextProvider<ISqlSugarDbContext> _dbContextProvider;
|
||||||
|
|
||||||
public IAbpLazyServiceProvider LazyServiceProvider { get; set; }
|
public IAbpLazyServiceProvider LazyServiceProvider { get; set; }
|
||||||
protected DbConnOptions? Options => LazyServiceProvider?.LazyGetService<IOptions<DbConnOptions>>().Value;
|
|
||||||
|
|
||||||
|
protected DbConnOptions? Options => LazyServiceProvider?.LazyGetService<IOptions<DbConnOptions>>().Value;
|
||||||
/// <summary>
|
/// <summary>
|
||||||
/// 异步查询执行器
|
/// 异步查询执行器
|
||||||
/// </summary>
|
/// </summary>
|
||||||
@@ -64,26 +60,22 @@ namespace Yi.Framework.SqlSugarCore.Repositories
|
|||||||
|
|
||||||
#region Abp模块
|
#region Abp模块
|
||||||
|
|
||||||
public virtual async Task<TEntity?> FindAsync(Expression<Func<TEntity, bool>> predicate,
|
public virtual async Task<TEntity?> FindAsync(Expression<Func<TEntity, bool>> predicate, bool includeDetails = true, CancellationToken cancellationToken = default)
|
||||||
bool includeDetails = true, CancellationToken cancellationToken = default)
|
|
||||||
{
|
{
|
||||||
return await GetFirstAsync(predicate);
|
return await GetFirstAsync(predicate);
|
||||||
}
|
}
|
||||||
|
|
||||||
public virtual async Task<TEntity> GetAsync(Expression<Func<TEntity, bool>> predicate,
|
public virtual async Task<TEntity> GetAsync(Expression<Func<TEntity, bool>> predicate, bool includeDetails = true, CancellationToken cancellationToken = default)
|
||||||
bool includeDetails = true, CancellationToken cancellationToken = default)
|
|
||||||
{
|
{
|
||||||
return await GetFirstAsync(predicate);
|
return await GetFirstAsync(predicate);
|
||||||
}
|
}
|
||||||
|
|
||||||
public virtual async Task DeleteAsync(Expression<Func<TEntity, bool>> predicate, bool autoSave = false,
|
public virtual async Task DeleteAsync(Expression<Func<TEntity, bool>> predicate, bool autoSave = false, CancellationToken cancellationToken = default)
|
||||||
CancellationToken cancellationToken = default)
|
|
||||||
{
|
{
|
||||||
await this.DeleteAsync(predicate);
|
await this.DeleteAsync(predicate);
|
||||||
}
|
}
|
||||||
|
|
||||||
public virtual async Task DeleteDirectAsync(Expression<Func<TEntity, bool>> predicate,
|
public virtual async Task DeleteDirectAsync(Expression<Func<TEntity, bool>> predicate, CancellationToken cancellationToken = default)
|
||||||
CancellationToken cancellationToken = default)
|
|
||||||
{
|
{
|
||||||
await this.DeleteAsync(predicate);
|
await this.DeleteAsync(predicate);
|
||||||
}
|
}
|
||||||
@@ -113,71 +105,60 @@ namespace Yi.Framework.SqlSugarCore.Repositories
|
|||||||
throw new NotImplementedException();
|
throw new NotImplementedException();
|
||||||
}
|
}
|
||||||
|
|
||||||
public virtual async Task<List<TEntity>> GetListAsync(Expression<Func<TEntity, bool>> predicate,
|
public virtual async Task<List<TEntity>> GetListAsync(Expression<Func<TEntity, bool>> predicate, bool includeDetails = false, CancellationToken cancellationToken = default)
|
||||||
bool includeDetails = false, CancellationToken cancellationToken = default)
|
|
||||||
{
|
{
|
||||||
return await GetListAsync(predicate);
|
return await GetListAsync(predicate);
|
||||||
}
|
}
|
||||||
|
|
||||||
public virtual async Task<TEntity> InsertAsync(TEntity entity, bool autoSave = false,
|
public virtual async Task<TEntity> InsertAsync(TEntity entity, bool autoSave = false, CancellationToken cancellationToken = default)
|
||||||
CancellationToken cancellationToken = default)
|
|
||||||
{
|
{
|
||||||
return await InsertReturnEntityAsync(entity);
|
return await InsertReturnEntityAsync(entity);
|
||||||
}
|
}
|
||||||
|
|
||||||
public virtual async Task InsertManyAsync(IEnumerable<TEntity> entities, bool autoSave = false,
|
public virtual async Task InsertManyAsync(IEnumerable<TEntity> entities, bool autoSave = false, CancellationToken cancellationToken = default)
|
||||||
CancellationToken cancellationToken = default)
|
|
||||||
{
|
{
|
||||||
await InsertRangeAsync(entities.ToList());
|
await InsertRangeAsync(entities.ToList());
|
||||||
}
|
}
|
||||||
|
|
||||||
public virtual async Task<TEntity> UpdateAsync(TEntity entity, bool autoSave = false,
|
public virtual async Task<TEntity> UpdateAsync(TEntity entity, bool autoSave = false, CancellationToken cancellationToken = default)
|
||||||
CancellationToken cancellationToken = default)
|
|
||||||
{
|
{
|
||||||
await UpdateAsync(entity);
|
await UpdateAsync(entity);
|
||||||
return entity;
|
return entity;
|
||||||
}
|
}
|
||||||
|
|
||||||
public virtual async Task UpdateManyAsync(IEnumerable<TEntity> entities, bool autoSave = false,
|
public virtual async Task UpdateManyAsync(IEnumerable<TEntity> entities, bool autoSave = false, CancellationToken cancellationToken = default)
|
||||||
CancellationToken cancellationToken = default)
|
|
||||||
{
|
{
|
||||||
await UpdateRangeAsync(entities.ToList());
|
await UpdateRangeAsync(entities.ToList());
|
||||||
}
|
}
|
||||||
|
|
||||||
public virtual async Task DeleteAsync(TEntity entity, bool autoSave = false,
|
public virtual async Task DeleteAsync(TEntity entity, bool autoSave = false, CancellationToken cancellationToken = default)
|
||||||
CancellationToken cancellationToken = default)
|
|
||||||
{
|
{
|
||||||
await DeleteAsync(entity);
|
await DeleteAsync(entity);
|
||||||
}
|
}
|
||||||
|
|
||||||
public virtual async Task DeleteManyAsync(IEnumerable<TEntity> entities, bool autoSave = false,
|
public virtual async Task DeleteManyAsync(IEnumerable<TEntity> entities, bool autoSave = false, CancellationToken cancellationToken = default)
|
||||||
CancellationToken cancellationToken = default)
|
|
||||||
{
|
{
|
||||||
await DeleteAsync(entities.ToList());
|
await DeleteAsync(entities.ToList());
|
||||||
}
|
}
|
||||||
|
|
||||||
public virtual async Task<List<TEntity>> GetListAsync(bool includeDetails = false,
|
public virtual async Task<List<TEntity>> GetListAsync(bool includeDetails = false, CancellationToken cancellationToken = default)
|
||||||
CancellationToken cancellationToken = default)
|
|
||||||
{
|
{
|
||||||
return await GetListAsync();
|
return await GetListAsync();
|
||||||
}
|
}
|
||||||
|
|
||||||
public virtual async Task<long> GetCountAsync(CancellationToken cancellationToken = default)
|
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,
|
public virtual async Task<List<TEntity>> GetPagedListAsync(int skipCount, int maxResultCount, string sorting, bool includeDetails = false, CancellationToken cancellationToken = default)
|
||||||
bool includeDetails = false, CancellationToken cancellationToken = default)
|
|
||||||
{
|
{
|
||||||
return await GetPageListAsync(_ => true, skipCount, maxResultCount);
|
return await GetPageListAsync(_ => true, skipCount, maxResultCount);
|
||||||
}
|
}
|
||||||
|
|
||||||
#endregion
|
#endregion
|
||||||
|
|
||||||
|
|
||||||
#region 内置DB快捷操作
|
#region 内置DB快捷操作
|
||||||
|
|
||||||
public virtual async Task<IDeleteable<TEntity>> AsDeleteable()
|
public virtual async Task<IDeleteable<TEntity>> AsDeleteable()
|
||||||
{
|
{
|
||||||
return (await GetDbSimpleClientAsync()).AsDeleteable();
|
return (await GetDbSimpleClientAsync()).AsDeleteable();
|
||||||
@@ -232,11 +213,9 @@ namespace Yi.Framework.SqlSugarCore.Repositories
|
|||||||
{
|
{
|
||||||
return (await GetDbSimpleClientAsync()).AsUpdateable(updateObjs);
|
return (await GetDbSimpleClientAsync()).AsUpdateable(updateObjs);
|
||||||
}
|
}
|
||||||
|
|
||||||
#endregion
|
#endregion
|
||||||
|
|
||||||
#region SimpleClient模块
|
#region SimpleClient模块
|
||||||
|
|
||||||
public virtual async Task<int> CountAsync(Expression<Func<TEntity, bool>> whereExpression)
|
public virtual async Task<int> CountAsync(Expression<Func<TEntity, bool>> whereExpression)
|
||||||
{
|
{
|
||||||
return await (await GetDbSimpleClientAsync()).CountAsync(whereExpression);
|
return await (await GetDbSimpleClientAsync()).CountAsync(whereExpression);
|
||||||
@@ -253,6 +232,7 @@ namespace Yi.Framework.SqlSugarCore.Repositories
|
|||||||
{
|
{
|
||||||
return await (await GetDbSimpleClientAsync()).DeleteAsync(deleteObj);
|
return await (await GetDbSimpleClientAsync()).DeleteAsync(deleteObj);
|
||||||
}
|
}
|
||||||
|
|
||||||
}
|
}
|
||||||
|
|
||||||
public virtual async Task<bool> DeleteAsync(List<TEntity> deleteObjs)
|
public virtual async Task<bool> DeleteAsync(List<TEntity> deleteObjs)
|
||||||
@@ -272,13 +252,13 @@ namespace Yi.Framework.SqlSugarCore.Repositories
|
|||||||
{
|
{
|
||||||
if (typeof(ISoftDelete).IsAssignableFrom(typeof(TEntity)))
|
if (typeof(ISoftDelete).IsAssignableFrom(typeof(TEntity)))
|
||||||
{
|
{
|
||||||
return await (await GetDbSimpleClientAsync()).AsUpdateable()
|
return await (await GetDbSimpleClientAsync()).AsUpdateable().SetColumns(nameof(ISoftDelete.IsDeleted), true).Where(whereExpression).ExecuteCommandAsync() > 0;
|
||||||
.SetColumns(nameof(ISoftDelete.IsDeleted), true).Where(whereExpression).ExecuteCommandAsync() > 0;
|
|
||||||
}
|
}
|
||||||
else
|
else
|
||||||
{
|
{
|
||||||
return await (await GetDbSimpleClientAsync()).DeleteAsync(whereExpression);
|
return await (await GetDbSimpleClientAsync()).DeleteAsync(whereExpression);
|
||||||
}
|
}
|
||||||
|
|
||||||
}
|
}
|
||||||
|
|
||||||
public virtual async Task<bool> DeleteByIdAsync(dynamic id)
|
public virtual async Task<bool> DeleteByIdAsync(dynamic id)
|
||||||
@@ -286,11 +266,7 @@ namespace Yi.Framework.SqlSugarCore.Repositories
|
|||||||
if (typeof(ISoftDelete).IsAssignableFrom(typeof(TEntity)))
|
if (typeof(ISoftDelete).IsAssignableFrom(typeof(TEntity)))
|
||||||
{
|
{
|
||||||
var entity = await GetByIdAsync(id);
|
var entity = await GetByIdAsync(id);
|
||||||
if (entity is null)
|
if (entity == null) return false;
|
||||||
{
|
|
||||||
return false;
|
|
||||||
}
|
|
||||||
|
|
||||||
//反射赋值
|
//反射赋值
|
||||||
ReflexHelper.SetModelValue(nameof(ISoftDelete.IsDeleted), true, entity);
|
ReflexHelper.SetModelValue(nameof(ISoftDelete.IsDeleted), true, entity);
|
||||||
return await UpdateAsync(entity);
|
return await UpdateAsync(entity);
|
||||||
@@ -311,7 +287,6 @@ namespace Yi.Framework.SqlSugarCore.Repositories
|
|||||||
{
|
{
|
||||||
return false;
|
return false;
|
||||||
}
|
}
|
||||||
|
|
||||||
//反射赋值
|
//反射赋值
|
||||||
entities.ForEach(e => ReflexHelper.SetModelValue(nameof(ISoftDelete.IsDeleted), true, e));
|
entities.ForEach(e => ReflexHelper.SetModelValue(nameof(ISoftDelete.IsDeleted), true, e));
|
||||||
return await UpdateRangeAsync(entities);
|
return await UpdateRangeAsync(entities);
|
||||||
@@ -320,6 +295,7 @@ namespace Yi.Framework.SqlSugarCore.Repositories
|
|||||||
{
|
{
|
||||||
return await (await GetDbSimpleClientAsync()).DeleteByIdAsync(ids);
|
return await (await GetDbSimpleClientAsync()).DeleteByIdAsync(ids);
|
||||||
}
|
}
|
||||||
|
|
||||||
}
|
}
|
||||||
|
|
||||||
public virtual async Task<TEntity> GetByIdAsync(dynamic id)
|
public virtual async Task<TEntity> GetByIdAsync(dynamic id)
|
||||||
@@ -328,6 +304,7 @@ namespace Yi.Framework.SqlSugarCore.Repositories
|
|||||||
}
|
}
|
||||||
|
|
||||||
|
|
||||||
|
|
||||||
public virtual async Task<TEntity> GetFirstAsync(Expression<Func<TEntity, bool>> whereExpression)
|
public virtual async Task<TEntity> GetFirstAsync(Expression<Func<TEntity, bool>> whereExpression)
|
||||||
{
|
{
|
||||||
return await (await GetDbSimpleClientAsync()).GetFirstAsync(whereExpression);
|
return await (await GetDbSimpleClientAsync()).GetFirstAsync(whereExpression);
|
||||||
@@ -343,19 +320,14 @@ namespace Yi.Framework.SqlSugarCore.Repositories
|
|||||||
return await (await GetDbSimpleClientAsync()).GetListAsync(whereExpression);
|
return await (await GetDbSimpleClientAsync()).GetListAsync(whereExpression);
|
||||||
}
|
}
|
||||||
|
|
||||||
public virtual async Task<List<TEntity>> GetPageListAsync(Expression<Func<TEntity, bool>> whereExpression,
|
public virtual async Task<List<TEntity>> GetPageListAsync(Expression<Func<TEntity, bool>> whereExpression, int pageNum, int pageSize)
|
||||||
int pageNum, int pageSize)
|
|
||||||
{
|
{
|
||||||
return await (await GetDbSimpleClientAsync()).GetPageListAsync(whereExpression,
|
return await (await AsQueryable()).Where(whereExpression).ToPageListAsync(pageNum, pageSize);
|
||||||
new PageModel() { PageIndex = pageNum, PageSize = pageSize });
|
|
||||||
}
|
}
|
||||||
|
|
||||||
public virtual async Task<List<TEntity>> GetPageListAsync(Expression<Func<TEntity, bool>> whereExpression,
|
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)
|
||||||
int pageNum, int pageSize, Expression<Func<TEntity, object>>? orderByExpression = null,
|
|
||||||
OrderByType orderByType = OrderByType.Asc)
|
|
||||||
{
|
{
|
||||||
return await (await GetDbSimpleClientAsync()).GetPageListAsync(whereExpression,
|
return await (await AsQueryable()).Where(whereExpression) .OrderBy( orderByExpression,orderByType).ToPageListAsync(pageNum, pageSize);
|
||||||
new PageModel { PageIndex = pageNum, PageSize = pageSize }, orderByExpression, orderByType);
|
|
||||||
}
|
}
|
||||||
|
|
||||||
public virtual async Task<TEntity> GetSingleAsync(Expression<Func<TEntity, bool>> whereExpression)
|
public virtual async Task<TEntity> GetSingleAsync(Expression<Func<TEntity, bool>> whereExpression)
|
||||||
@@ -410,9 +382,9 @@ namespace Yi.Framework.SqlSugarCore.Repositories
|
|||||||
|
|
||||||
public virtual async Task<bool> UpdateAsync(TEntity updateObj)
|
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
|
try
|
||||||
{
|
{
|
||||||
@@ -426,24 +398,18 @@ namespace Yi.Framework.SqlSugarCore.Repositories
|
|||||||
$"{ex.Message}[更新失败:ConcurrencyStamp不是最新版本],entityInfo:{updateObj}", ex);
|
$"{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);
|
return await (await GetDbSimpleClientAsync()).UpdateAsync(updateObj);
|
||||||
}
|
}
|
||||||
|
|
||||||
public virtual async Task<bool> UpdateAsync(Expression<Func<TEntity, TEntity>> columns,
|
public virtual async Task<bool> UpdateAsync(Expression<Func<TEntity, TEntity>> columns, Expression<Func<TEntity, bool>> whereExpression)
|
||||||
Expression<Func<TEntity, bool>> whereExpression)
|
|
||||||
{
|
{
|
||||||
return await (await GetDbSimpleClientAsync()).UpdateAsync(columns, whereExpression);
|
return await (await GetDbSimpleClientAsync()).UpdateAsync(columns, whereExpression);
|
||||||
}
|
}
|
||||||
|
|
||||||
|
|
||||||
|
|
||||||
public virtual async Task<bool> UpdateRangeAsync(List<TEntity> updateObjs)
|
public virtual async Task<bool> UpdateRangeAsync(List<TEntity> updateObjs)
|
||||||
{
|
{
|
||||||
return await (await GetDbSimpleClientAsync()).UpdateRangeAsync(updateObjs);
|
return await (await GetDbSimpleClientAsync()).UpdateRangeAsync(updateObjs);
|
||||||
@@ -452,34 +418,28 @@ namespace Yi.Framework.SqlSugarCore.Repositories
|
|||||||
#endregion
|
#endregion
|
||||||
}
|
}
|
||||||
|
|
||||||
public class SqlSugarRepository<TEntity, TKey> : SqlSugarRepository<TEntity>, ISqlSugarRepository<TEntity, TKey>,
|
public class SqlSugarRepository<TEntity, TKey> : SqlSugarRepository<TEntity>, ISqlSugarRepository<TEntity, TKey>, IRepository<TEntity, TKey> where TEntity : class, IEntity<TKey>, new()
|
||||||
IRepository<TEntity, TKey> where TEntity : class, IEntity<TKey>, new()
|
|
||||||
{
|
{
|
||||||
public SqlSugarRepository(ISugarDbContextProvider<ISqlSugarDbContext> dbContextProvider) : base(
|
public SqlSugarRepository(ISugarDbContextProvider<ISqlSugarDbContext> sugarDbContextProvider) : base(sugarDbContextProvider)
|
||||||
dbContextProvider)
|
|
||||||
{
|
{
|
||||||
}
|
}
|
||||||
|
|
||||||
public virtual async Task DeleteAsync(TKey id, bool autoSave = false,
|
public virtual async Task DeleteAsync(TKey id, bool autoSave = false, CancellationToken cancellationToken = default)
|
||||||
CancellationToken cancellationToken = default)
|
|
||||||
{
|
{
|
||||||
await DeleteByIdAsync(id);
|
await DeleteByIdAsync(id);
|
||||||
}
|
}
|
||||||
|
|
||||||
public virtual async Task DeleteManyAsync(IEnumerable<TKey> ids, bool autoSave = false,
|
public virtual async Task DeleteManyAsync(IEnumerable<TKey> ids, bool autoSave = false, CancellationToken cancellationToken = default)
|
||||||
CancellationToken cancellationToken = default)
|
|
||||||
{
|
{
|
||||||
await DeleteByIdsAsync(ids.Select(x => (object)x).ToArray());
|
await DeleteByIdsAsync(ids.Select(x => (object)x).ToArray());
|
||||||
}
|
}
|
||||||
|
|
||||||
public virtual async Task<TEntity?> FindAsync(TKey id, bool includeDetails = true,
|
public virtual async Task<TEntity?> FindAsync(TKey id, bool includeDetails = true, CancellationToken cancellationToken = default)
|
||||||
CancellationToken cancellationToken = default)
|
|
||||||
{
|
{
|
||||||
return await GetByIdAsync(id);
|
return await GetByIdAsync(id);
|
||||||
}
|
}
|
||||||
|
|
||||||
public virtual async Task<TEntity> GetAsync(TKey id, bool includeDetails = true,
|
public virtual async Task<TEntity> GetAsync(TKey id, bool includeDetails = true, CancellationToken cancellationToken = default)
|
||||||
CancellationToken cancellationToken = default)
|
|
||||||
{
|
{
|
||||||
return await GetByIdAsync(id);
|
return await GetByIdAsync(id);
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -0,0 +1,30 @@
|
|||||||
|
using Yi.Framework.AiHub.Domain.Shared.Enums;
|
||||||
|
|
||||||
|
namespace Yi.Framework.AiHub.Application.Contracts.Dtos.ActivationCode;
|
||||||
|
|
||||||
|
/// <summary>
|
||||||
|
/// 批量生成激活码输入
|
||||||
|
/// </summary>
|
||||||
|
public class ActivationCodeCreateInput
|
||||||
|
{
|
||||||
|
/// <summary>
|
||||||
|
/// 商品类型
|
||||||
|
/// </summary>
|
||||||
|
public ActivationCodeGoodsTypeEnum GoodsType { get; set; }
|
||||||
|
|
||||||
|
/// <summary>
|
||||||
|
/// 数量
|
||||||
|
/// </summary>
|
||||||
|
public int Count { get; set; } = 1;
|
||||||
|
}
|
||||||
|
|
||||||
|
/// <summary>
|
||||||
|
/// 批量生成激活码列表输入
|
||||||
|
/// </summary>
|
||||||
|
public class ActivationCodeCreateListInput
|
||||||
|
{
|
||||||
|
/// <summary>
|
||||||
|
/// 生成项列表
|
||||||
|
/// </summary>
|
||||||
|
public List<ActivationCodeCreateInput> Items { get; set; } = new();
|
||||||
|
}
|
||||||
@@ -0,0 +1,35 @@
|
|||||||
|
using Yi.Framework.AiHub.Domain.Shared.Enums;
|
||||||
|
|
||||||
|
namespace Yi.Framework.AiHub.Application.Contracts.Dtos.ActivationCode;
|
||||||
|
|
||||||
|
/// <summary>
|
||||||
|
/// 批量生成激活码输出
|
||||||
|
/// </summary>
|
||||||
|
public class ActivationCodeCreateOutput
|
||||||
|
{
|
||||||
|
/// <summary>
|
||||||
|
/// 商品类型
|
||||||
|
/// </summary>
|
||||||
|
public ActivationCodeGoodsTypeEnum GoodsType { get; set; }
|
||||||
|
|
||||||
|
/// <summary>
|
||||||
|
/// 数量
|
||||||
|
/// </summary>
|
||||||
|
public int Count { get; set; }
|
||||||
|
|
||||||
|
/// <summary>
|
||||||
|
/// 激活码列表
|
||||||
|
/// </summary>
|
||||||
|
public List<string> Codes { get; set; } = new();
|
||||||
|
}
|
||||||
|
|
||||||
|
/// <summary>
|
||||||
|
/// 批量生成激活码列表输出
|
||||||
|
/// </summary>
|
||||||
|
public class ActivationCodeCreateListOutput
|
||||||
|
{
|
||||||
|
/// <summary>
|
||||||
|
/// 分组输出
|
||||||
|
/// </summary>
|
||||||
|
public List<ActivationCodeCreateOutput> Items { get; set; } = new();
|
||||||
|
}
|
||||||
@@ -0,0 +1,12 @@
|
|||||||
|
namespace Yi.Framework.AiHub.Application.Contracts.Dtos.ActivationCode;
|
||||||
|
|
||||||
|
/// <summary>
|
||||||
|
/// 激活码兑换输入
|
||||||
|
/// </summary>
|
||||||
|
public class ActivationCodeRedeemInput
|
||||||
|
{
|
||||||
|
/// <summary>
|
||||||
|
/// 激活码
|
||||||
|
/// </summary>
|
||||||
|
public string Code { get; set; } = string.Empty;
|
||||||
|
}
|
||||||
@@ -0,0 +1,24 @@
|
|||||||
|
using Yi.Framework.AiHub.Domain.Shared.Enums;
|
||||||
|
|
||||||
|
namespace Yi.Framework.AiHub.Application.Contracts.Dtos.ActivationCode;
|
||||||
|
|
||||||
|
/// <summary>
|
||||||
|
/// 激活码兑换输出
|
||||||
|
/// </summary>
|
||||||
|
public class ActivationCodeRedeemOutput
|
||||||
|
{
|
||||||
|
/// <summary>
|
||||||
|
/// 商品类型
|
||||||
|
/// </summary>
|
||||||
|
public ActivationCodeGoodsTypeEnum GoodsType { get; set; }
|
||||||
|
|
||||||
|
/// <summary>
|
||||||
|
/// 商品名称
|
||||||
|
/// </summary>
|
||||||
|
public string PackageName { get; set; } = string.Empty;
|
||||||
|
|
||||||
|
/// <summary>
|
||||||
|
/// 内容描述
|
||||||
|
/// </summary>
|
||||||
|
public string Content { get; set; } = string.Empty;
|
||||||
|
}
|
||||||
@@ -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>();
|
||||||
|
}
|
||||||
@@ -40,11 +40,6 @@ public class CardFlipStatusOutput
|
|||||||
/// </summary>
|
/// </summary>
|
||||||
public int InvitedCount { get; set; }
|
public int InvitedCount { get; set; }
|
||||||
|
|
||||||
/// <summary>
|
|
||||||
/// 是否已被邀请(被邀请后不可再提供邀请码)
|
|
||||||
/// </summary>
|
|
||||||
public bool IsInvited { get; set; }
|
|
||||||
|
|
||||||
/// <summary>
|
/// <summary>
|
||||||
/// 翻牌记录
|
/// 翻牌记录
|
||||||
/// </summary>
|
/// </summary>
|
||||||
@@ -54,6 +49,11 @@ public class CardFlipStatusOutput
|
|||||||
/// 下次可翻牌提示
|
/// 下次可翻牌提示
|
||||||
/// </summary>
|
/// </summary>
|
||||||
public string? NextFlipTip { get; set; }
|
public string? NextFlipTip { get; set; }
|
||||||
|
|
||||||
|
/// <summary>
|
||||||
|
/// 当前用户是否已经填写过邀请码
|
||||||
|
/// </summary>
|
||||||
|
public bool IsFilledInviteCode { get; set; }
|
||||||
}
|
}
|
||||||
|
|
||||||
/// <summary>
|
/// <summary>
|
||||||
|
|||||||
@@ -0,0 +1,42 @@
|
|||||||
|
using System.ComponentModel.DataAnnotations;
|
||||||
|
|
||||||
|
namespace Yi.Framework.AiHub.Application.Contracts.Dtos.Channel;
|
||||||
|
|
||||||
|
/// <summary>
|
||||||
|
/// 创建AI应用输入
|
||||||
|
/// </summary>
|
||||||
|
public class AiAppCreateInput
|
||||||
|
{
|
||||||
|
/// <summary>
|
||||||
|
/// 应用名称
|
||||||
|
/// </summary>
|
||||||
|
[Required(ErrorMessage = "应用名称不能为空")]
|
||||||
|
[StringLength(100, ErrorMessage = "应用名称不能超过100个字符")]
|
||||||
|
public string Name { get; set; }
|
||||||
|
|
||||||
|
/// <summary>
|
||||||
|
/// 应用终结点
|
||||||
|
/// </summary>
|
||||||
|
[Required(ErrorMessage = "应用终结点不能为空")]
|
||||||
|
[StringLength(500, ErrorMessage = "应用终结点不能超过500个字符")]
|
||||||
|
public string Endpoint { get; set; }
|
||||||
|
|
||||||
|
/// <summary>
|
||||||
|
/// 额外URL
|
||||||
|
/// </summary>
|
||||||
|
[StringLength(500, ErrorMessage = "额外URL不能超过500个字符")]
|
||||||
|
public string? ExtraUrl { get; set; }
|
||||||
|
|
||||||
|
/// <summary>
|
||||||
|
/// 应用Key
|
||||||
|
/// </summary>
|
||||||
|
[Required(ErrorMessage = "应用Key不能为空")]
|
||||||
|
[StringLength(500, ErrorMessage = "应用Key不能超过500个字符")]
|
||||||
|
public string ApiKey { get; set; }
|
||||||
|
|
||||||
|
/// <summary>
|
||||||
|
/// 排序
|
||||||
|
/// </summary>
|
||||||
|
[Range(0, int.MaxValue, ErrorMessage = "排序必须大于等于0")]
|
||||||
|
public int OrderNum { get; set; }
|
||||||
|
}
|
||||||
@@ -0,0 +1,42 @@
|
|||||||
|
namespace Yi.Framework.AiHub.Application.Contracts.Dtos.Channel;
|
||||||
|
|
||||||
|
/// <summary>
|
||||||
|
/// AI应用DTO
|
||||||
|
/// </summary>
|
||||||
|
public class AiAppDto
|
||||||
|
{
|
||||||
|
/// <summary>
|
||||||
|
/// 应用ID
|
||||||
|
/// </summary>
|
||||||
|
public Guid Id { get; set; }
|
||||||
|
|
||||||
|
/// <summary>
|
||||||
|
/// 应用名称
|
||||||
|
/// </summary>
|
||||||
|
public string Name { get; set; }
|
||||||
|
|
||||||
|
/// <summary>
|
||||||
|
/// 应用终结点
|
||||||
|
/// </summary>
|
||||||
|
public string Endpoint { get; set; }
|
||||||
|
|
||||||
|
/// <summary>
|
||||||
|
/// 额外URL
|
||||||
|
/// </summary>
|
||||||
|
public string? ExtraUrl { get; set; }
|
||||||
|
|
||||||
|
/// <summary>
|
||||||
|
/// 应用Key
|
||||||
|
/// </summary>
|
||||||
|
public string ApiKey { get; set; }
|
||||||
|
|
||||||
|
/// <summary>
|
||||||
|
/// 排序
|
||||||
|
/// </summary>
|
||||||
|
public int OrderNum { get; set; }
|
||||||
|
|
||||||
|
/// <summary>
|
||||||
|
/// 创建时间
|
||||||
|
/// </summary>
|
||||||
|
public DateTime CreationTime { get; set; }
|
||||||
|
}
|
||||||
@@ -0,0 +1,14 @@
|
|||||||
|
using Yi.Framework.Ddd.Application.Contracts;
|
||||||
|
|
||||||
|
namespace Yi.Framework.AiHub.Application.Contracts.Dtos.Channel;
|
||||||
|
|
||||||
|
/// <summary>
|
||||||
|
/// 获取AI应用列表输入
|
||||||
|
/// </summary>
|
||||||
|
public class AiAppGetListInput : PagedAllResultRequestDto
|
||||||
|
{
|
||||||
|
/// <summary>
|
||||||
|
/// 搜索关键词(搜索应用名称)
|
||||||
|
/// </summary>
|
||||||
|
public string? SearchKey { get; set; }
|
||||||
|
}
|
||||||
@@ -0,0 +1,48 @@
|
|||||||
|
using System.ComponentModel.DataAnnotations;
|
||||||
|
|
||||||
|
namespace Yi.Framework.AiHub.Application.Contracts.Dtos.Channel;
|
||||||
|
|
||||||
|
/// <summary>
|
||||||
|
/// 更新AI应用输入
|
||||||
|
/// </summary>
|
||||||
|
public class AiAppUpdateInput
|
||||||
|
{
|
||||||
|
/// <summary>
|
||||||
|
/// 应用ID
|
||||||
|
/// </summary>
|
||||||
|
[Required(ErrorMessage = "应用ID不能为空")]
|
||||||
|
public Guid Id { get; set; }
|
||||||
|
|
||||||
|
/// <summary>
|
||||||
|
/// 应用名称
|
||||||
|
/// </summary>
|
||||||
|
[Required(ErrorMessage = "应用名称不能为空")]
|
||||||
|
[StringLength(100, ErrorMessage = "应用名称不能超过100个字符")]
|
||||||
|
public string Name { get; set; }
|
||||||
|
|
||||||
|
/// <summary>
|
||||||
|
/// 应用终结点
|
||||||
|
/// </summary>
|
||||||
|
[Required(ErrorMessage = "应用终结点不能为空")]
|
||||||
|
[StringLength(500, ErrorMessage = "应用终结点不能超过500个字符")]
|
||||||
|
public string Endpoint { get; set; }
|
||||||
|
|
||||||
|
/// <summary>
|
||||||
|
/// 额外URL
|
||||||
|
/// </summary>
|
||||||
|
[StringLength(500, ErrorMessage = "额外URL不能超过500个字符")]
|
||||||
|
public string? ExtraUrl { get; set; }
|
||||||
|
|
||||||
|
/// <summary>
|
||||||
|
/// 应用Key
|
||||||
|
/// </summary>
|
||||||
|
[Required(ErrorMessage = "应用Key不能为空")]
|
||||||
|
[StringLength(500, ErrorMessage = "应用Key不能超过500个字符")]
|
||||||
|
public string ApiKey { get; set; }
|
||||||
|
|
||||||
|
/// <summary>
|
||||||
|
/// 排序
|
||||||
|
/// </summary>
|
||||||
|
[Range(0, int.MaxValue, ErrorMessage = "排序必须大于等于0")]
|
||||||
|
public int OrderNum { get; set; }
|
||||||
|
}
|
||||||
@@ -0,0 +1,96 @@
|
|||||||
|
using System.ComponentModel.DataAnnotations;
|
||||||
|
using Yi.Framework.AiHub.Domain.Shared.Enums;
|
||||||
|
|
||||||
|
namespace Yi.Framework.AiHub.Application.Contracts.Dtos.Channel;
|
||||||
|
|
||||||
|
/// <summary>
|
||||||
|
/// 创建AI模型输入
|
||||||
|
/// </summary>
|
||||||
|
public class AiModelCreateInput
|
||||||
|
{
|
||||||
|
/// <summary>
|
||||||
|
/// 处理名
|
||||||
|
/// </summary>
|
||||||
|
[Required(ErrorMessage = "处理名不能为空")]
|
||||||
|
[StringLength(100, ErrorMessage = "处理名不能超过100个字符")]
|
||||||
|
public string HandlerName { get; set; }
|
||||||
|
|
||||||
|
/// <summary>
|
||||||
|
/// 模型ID
|
||||||
|
/// </summary>
|
||||||
|
[Required(ErrorMessage = "模型ID不能为空")]
|
||||||
|
[StringLength(200, ErrorMessage = "模型ID不能超过200个字符")]
|
||||||
|
public string ModelId { get; set; }
|
||||||
|
|
||||||
|
/// <summary>
|
||||||
|
/// 模型名称
|
||||||
|
/// </summary>
|
||||||
|
[Required(ErrorMessage = "模型名称不能为空")]
|
||||||
|
[StringLength(200, ErrorMessage = "模型名称不能超过200个字符")]
|
||||||
|
public string Name { get; set; }
|
||||||
|
|
||||||
|
/// <summary>
|
||||||
|
/// 模型描述
|
||||||
|
/// </summary>
|
||||||
|
[StringLength(1000, ErrorMessage = "模型描述不能超过1000个字符")]
|
||||||
|
public string? Description { get; set; }
|
||||||
|
|
||||||
|
/// <summary>
|
||||||
|
/// 排序
|
||||||
|
/// </summary>
|
||||||
|
[Range(0, int.MaxValue, ErrorMessage = "排序必须大于等于0")]
|
||||||
|
public int OrderNum { get; set; }
|
||||||
|
|
||||||
|
/// <summary>
|
||||||
|
/// AI应用ID
|
||||||
|
/// </summary>
|
||||||
|
[Required(ErrorMessage = "AI应用ID不能为空")]
|
||||||
|
public Guid AiAppId { get; set; }
|
||||||
|
|
||||||
|
/// <summary>
|
||||||
|
/// 额外信息
|
||||||
|
/// </summary>
|
||||||
|
[StringLength(2000, ErrorMessage = "额外信息不能超过2000个字符")]
|
||||||
|
public string? ExtraInfo { get; set; }
|
||||||
|
|
||||||
|
/// <summary>
|
||||||
|
/// 模型类型
|
||||||
|
/// </summary>
|
||||||
|
[Required(ErrorMessage = "模型类型不能为空")]
|
||||||
|
public ModelTypeEnum ModelType { get; set; }
|
||||||
|
|
||||||
|
/// <summary>
|
||||||
|
/// 模型API类型
|
||||||
|
/// </summary>
|
||||||
|
[Required(ErrorMessage = "模型API类型不能为空")]
|
||||||
|
public ModelApiTypeEnum ModelApiType { get; set; }
|
||||||
|
|
||||||
|
/// <summary>
|
||||||
|
/// 模型倍率
|
||||||
|
/// </summary>
|
||||||
|
[Range(0.01, double.MaxValue, ErrorMessage = "模型倍率必须大于0")]
|
||||||
|
public decimal Multiplier { get; set; } = 1;
|
||||||
|
|
||||||
|
/// <summary>
|
||||||
|
/// 模型显示倍率
|
||||||
|
/// </summary>
|
||||||
|
[Range(0.01, double.MaxValue, ErrorMessage = "模型显示倍率必须大于0")]
|
||||||
|
public decimal MultiplierShow { get; set; } = 1;
|
||||||
|
|
||||||
|
/// <summary>
|
||||||
|
/// 供应商分组名称
|
||||||
|
/// </summary>
|
||||||
|
[StringLength(100, ErrorMessage = "供应商分组名称不能超过100个字符")]
|
||||||
|
public string? ProviderName { get; set; }
|
||||||
|
|
||||||
|
/// <summary>
|
||||||
|
/// 模型图标URL
|
||||||
|
/// </summary>
|
||||||
|
[StringLength(500, ErrorMessage = "模型图标URL不能超过500个字符")]
|
||||||
|
public string? IconUrl { get; set; }
|
||||||
|
|
||||||
|
/// <summary>
|
||||||
|
/// 是否为尊享模型
|
||||||
|
/// </summary>
|
||||||
|
public bool IsPremium { get; set; }
|
||||||
|
}
|
||||||
@@ -0,0 +1,84 @@
|
|||||||
|
using Yi.Framework.AiHub.Domain.Shared.Enums;
|
||||||
|
|
||||||
|
namespace Yi.Framework.AiHub.Application.Contracts.Dtos.Channel;
|
||||||
|
|
||||||
|
/// <summary>
|
||||||
|
/// AI模型DTO
|
||||||
|
/// </summary>
|
||||||
|
public class AiModelDto
|
||||||
|
{
|
||||||
|
/// <summary>
|
||||||
|
/// 模型ID
|
||||||
|
/// </summary>
|
||||||
|
public Guid Id { get; set; }
|
||||||
|
|
||||||
|
/// <summary>
|
||||||
|
/// 处理名
|
||||||
|
/// </summary>
|
||||||
|
public string HandlerName { get; set; }
|
||||||
|
|
||||||
|
/// <summary>
|
||||||
|
/// 模型ID
|
||||||
|
/// </summary>
|
||||||
|
public string ModelId { get; set; }
|
||||||
|
|
||||||
|
/// <summary>
|
||||||
|
/// 模型名称
|
||||||
|
/// </summary>
|
||||||
|
public string Name { get; set; }
|
||||||
|
|
||||||
|
/// <summary>
|
||||||
|
/// 模型描述
|
||||||
|
/// </summary>
|
||||||
|
public string? Description { get; set; }
|
||||||
|
|
||||||
|
/// <summary>
|
||||||
|
/// 排序
|
||||||
|
/// </summary>
|
||||||
|
public int OrderNum { get; set; }
|
||||||
|
|
||||||
|
/// <summary>
|
||||||
|
/// AI应用ID
|
||||||
|
/// </summary>
|
||||||
|
public Guid AiAppId { get; set; }
|
||||||
|
|
||||||
|
/// <summary>
|
||||||
|
/// 额外信息
|
||||||
|
/// </summary>
|
||||||
|
public string? ExtraInfo { get; set; }
|
||||||
|
|
||||||
|
/// <summary>
|
||||||
|
/// 模型类型
|
||||||
|
/// </summary>
|
||||||
|
public ModelTypeEnum ModelType { get; set; }
|
||||||
|
|
||||||
|
/// <summary>
|
||||||
|
/// 模型API类型
|
||||||
|
/// </summary>
|
||||||
|
public ModelApiTypeEnum ModelApiType { get; set; }
|
||||||
|
|
||||||
|
/// <summary>
|
||||||
|
/// 模型倍率
|
||||||
|
/// </summary>
|
||||||
|
public decimal Multiplier { get; set; }
|
||||||
|
|
||||||
|
/// <summary>
|
||||||
|
/// 模型显示倍率
|
||||||
|
/// </summary>
|
||||||
|
public decimal MultiplierShow { get; set; }
|
||||||
|
|
||||||
|
/// <summary>
|
||||||
|
/// 供应商分组名称
|
||||||
|
/// </summary>
|
||||||
|
public string? ProviderName { get; set; }
|
||||||
|
|
||||||
|
/// <summary>
|
||||||
|
/// 模型图标URL
|
||||||
|
/// </summary>
|
||||||
|
public string? IconUrl { get; set; }
|
||||||
|
|
||||||
|
/// <summary>
|
||||||
|
/// 是否为尊享模型
|
||||||
|
/// </summary>
|
||||||
|
public bool IsPremium { get; set; }
|
||||||
|
}
|
||||||
@@ -0,0 +1,24 @@
|
|||||||
|
using Yi.Framework.Ddd.Application.Contracts;
|
||||||
|
|
||||||
|
namespace Yi.Framework.AiHub.Application.Contracts.Dtos.Channel;
|
||||||
|
|
||||||
|
/// <summary>
|
||||||
|
/// 获取AI模型列表输入
|
||||||
|
/// </summary>
|
||||||
|
public class AiModelGetListInput : PagedAllResultRequestDto
|
||||||
|
{
|
||||||
|
/// <summary>
|
||||||
|
/// 搜索关键词(搜索模型名称、模型ID)
|
||||||
|
/// </summary>
|
||||||
|
public string? SearchKey { get; set; }
|
||||||
|
|
||||||
|
/// <summary>
|
||||||
|
/// AI应用ID筛选
|
||||||
|
/// </summary>
|
||||||
|
public Guid? AiAppId { get; set; }
|
||||||
|
|
||||||
|
/// <summary>
|
||||||
|
/// 是否只显示尊享模型
|
||||||
|
/// </summary>
|
||||||
|
public bool? IsPremiumOnly { get; set; }
|
||||||
|
}
|
||||||
@@ -0,0 +1,102 @@
|
|||||||
|
using System.ComponentModel.DataAnnotations;
|
||||||
|
using Yi.Framework.AiHub.Domain.Shared.Enums;
|
||||||
|
|
||||||
|
namespace Yi.Framework.AiHub.Application.Contracts.Dtos.Channel;
|
||||||
|
|
||||||
|
/// <summary>
|
||||||
|
/// 更新AI模型输入
|
||||||
|
/// </summary>
|
||||||
|
public class AiModelUpdateInput
|
||||||
|
{
|
||||||
|
/// <summary>
|
||||||
|
/// 模型ID
|
||||||
|
/// </summary>
|
||||||
|
[Required(ErrorMessage = "模型ID不能为空")]
|
||||||
|
public Guid Id { get; set; }
|
||||||
|
|
||||||
|
/// <summary>
|
||||||
|
/// 处理名
|
||||||
|
/// </summary>
|
||||||
|
[Required(ErrorMessage = "处理名不能为空")]
|
||||||
|
[StringLength(100, ErrorMessage = "处理名不能超过100个字符")]
|
||||||
|
public string HandlerName { get; set; }
|
||||||
|
|
||||||
|
/// <summary>
|
||||||
|
/// 模型ID
|
||||||
|
/// </summary>
|
||||||
|
[Required(ErrorMessage = "模型ID不能为空")]
|
||||||
|
[StringLength(200, ErrorMessage = "模型ID不能超过200个字符")]
|
||||||
|
public string ModelId { get; set; }
|
||||||
|
|
||||||
|
/// <summary>
|
||||||
|
/// 模型名称
|
||||||
|
/// </summary>
|
||||||
|
[Required(ErrorMessage = "模型名称不能为空")]
|
||||||
|
[StringLength(200, ErrorMessage = "模型名称不能超过200个字符")]
|
||||||
|
public string Name { get; set; }
|
||||||
|
|
||||||
|
/// <summary>
|
||||||
|
/// 模型描述
|
||||||
|
/// </summary>
|
||||||
|
[StringLength(1000, ErrorMessage = "模型描述不能超过1000个字符")]
|
||||||
|
public string? Description { get; set; }
|
||||||
|
|
||||||
|
/// <summary>
|
||||||
|
/// 排序
|
||||||
|
/// </summary>
|
||||||
|
[Range(0, int.MaxValue, ErrorMessage = "排序必须大于等于0")]
|
||||||
|
public int OrderNum { get; set; }
|
||||||
|
|
||||||
|
/// <summary>
|
||||||
|
/// AI应用ID
|
||||||
|
/// </summary>
|
||||||
|
[Required(ErrorMessage = "AI应用ID不能为空")]
|
||||||
|
public Guid AiAppId { get; set; }
|
||||||
|
|
||||||
|
/// <summary>
|
||||||
|
/// 额外信息
|
||||||
|
/// </summary>
|
||||||
|
[StringLength(2000, ErrorMessage = "额外信息不能超过2000个字符")]
|
||||||
|
public string? ExtraInfo { get; set; }
|
||||||
|
|
||||||
|
/// <summary>
|
||||||
|
/// 模型类型
|
||||||
|
/// </summary>
|
||||||
|
[Required(ErrorMessage = "模型类型不能为空")]
|
||||||
|
public ModelTypeEnum ModelType { get; set; }
|
||||||
|
|
||||||
|
/// <summary>
|
||||||
|
/// 模型API类型
|
||||||
|
/// </summary>
|
||||||
|
[Required(ErrorMessage = "模型API类型不能为空")]
|
||||||
|
public ModelApiTypeEnum ModelApiType { get; set; }
|
||||||
|
|
||||||
|
/// <summary>
|
||||||
|
/// 模型倍率
|
||||||
|
/// </summary>
|
||||||
|
[Range(0.01, double.MaxValue, ErrorMessage = "模型倍率必须大于0")]
|
||||||
|
public decimal Multiplier { get; set; }
|
||||||
|
|
||||||
|
/// <summary>
|
||||||
|
/// 模型显示倍率
|
||||||
|
/// </summary>
|
||||||
|
[Range(0.01, double.MaxValue, ErrorMessage = "模型显示倍率必须大于0")]
|
||||||
|
public decimal MultiplierShow { get; set; }
|
||||||
|
|
||||||
|
/// <summary>
|
||||||
|
/// 供应商分组名称
|
||||||
|
/// </summary>
|
||||||
|
[StringLength(100, ErrorMessage = "供应商分组名称不能超过100个字符")]
|
||||||
|
public string? ProviderName { get; set; }
|
||||||
|
|
||||||
|
/// <summary>
|
||||||
|
/// 模型图标URL
|
||||||
|
/// </summary>
|
||||||
|
[StringLength(500, ErrorMessage = "模型图标URL不能超过500个字符")]
|
||||||
|
public string? IconUrl { get; set; }
|
||||||
|
|
||||||
|
/// <summary>
|
||||||
|
/// 是否为尊享模型
|
||||||
|
/// </summary>
|
||||||
|
public bool IsPremium { get; set; }
|
||||||
|
}
|
||||||
@@ -0,0 +1,65 @@
|
|||||||
|
using System.Reflection;
|
||||||
|
using System.Text.Json.Serialization;
|
||||||
|
|
||||||
|
namespace Yi.Framework.AiHub.Application.Contracts.Dtos.Chat;
|
||||||
|
|
||||||
|
public class AgentResultOutput
|
||||||
|
{
|
||||||
|
/// <summary>
|
||||||
|
/// 类型
|
||||||
|
/// </summary>
|
||||||
|
[JsonIgnore]
|
||||||
|
public AgentResultTypeEnum TypeEnum { get; set; }
|
||||||
|
|
||||||
|
/// <summary>
|
||||||
|
/// 类型
|
||||||
|
/// </summary>
|
||||||
|
public string Type => TypeEnum.GetJsonName();
|
||||||
|
|
||||||
|
/// <summary>
|
||||||
|
/// 内容载体
|
||||||
|
/// </summary>
|
||||||
|
public object Content { get; set; }
|
||||||
|
}
|
||||||
|
|
||||||
|
public enum AgentResultTypeEnum
|
||||||
|
{
|
||||||
|
/// <summary>
|
||||||
|
/// 文本内容
|
||||||
|
/// </summary>
|
||||||
|
[JsonPropertyName("text")]
|
||||||
|
Text,
|
||||||
|
/// <summary>
|
||||||
|
/// 工具调用中
|
||||||
|
/// </summary>
|
||||||
|
[JsonPropertyName("toolCalling")]
|
||||||
|
ToolCalling,
|
||||||
|
|
||||||
|
/// <summary>
|
||||||
|
/// 工具调用完成
|
||||||
|
/// </summary>
|
||||||
|
[JsonPropertyName("toolCalled")]
|
||||||
|
ToolCalled,
|
||||||
|
|
||||||
|
/// <summary>
|
||||||
|
/// 用量
|
||||||
|
/// </summary>
|
||||||
|
[JsonPropertyName("usage")]
|
||||||
|
Usage,
|
||||||
|
|
||||||
|
/// <summary>
|
||||||
|
/// 工具调用用量
|
||||||
|
/// </summary>
|
||||||
|
[JsonPropertyName("toolCallUsage")]
|
||||||
|
ToolCallUsage
|
||||||
|
}
|
||||||
|
|
||||||
|
public static class AgentResultTypeEnumExtensions
|
||||||
|
{
|
||||||
|
public static string GetJsonName(this AgentResultTypeEnum value)
|
||||||
|
{
|
||||||
|
var member = typeof(AgentResultTypeEnum).GetMember(value.ToString()).FirstOrDefault();
|
||||||
|
var attr = member?.GetCustomAttribute<JsonPropertyNameAttribute>();
|
||||||
|
return attr?.Name ?? value.ToString();
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -0,0 +1,29 @@
|
|||||||
|
namespace Yi.Framework.AiHub.Application.Contracts.Dtos.Chat;
|
||||||
|
|
||||||
|
public class AgentSendInput
|
||||||
|
{
|
||||||
|
/// <summary>
|
||||||
|
/// 会话id
|
||||||
|
/// </summary>
|
||||||
|
public Guid SessionId { get; set; }
|
||||||
|
|
||||||
|
/// <summary>
|
||||||
|
/// 用户内容
|
||||||
|
/// </summary>
|
||||||
|
public string Content { get; set; }
|
||||||
|
|
||||||
|
/// <summary>
|
||||||
|
/// api密钥Id
|
||||||
|
/// </summary>
|
||||||
|
public Guid TokenId { get; set; }
|
||||||
|
|
||||||
|
/// <summary>
|
||||||
|
/// 模型id
|
||||||
|
/// </summary>
|
||||||
|
public string ModelId { get; set; }
|
||||||
|
|
||||||
|
/// <summary>
|
||||||
|
/// 已选择工具
|
||||||
|
/// </summary>
|
||||||
|
public List<string> Tools { get; set; }
|
||||||
|
}
|
||||||
@@ -0,0 +1,8 @@
|
|||||||
|
namespace Yi.Framework.AiHub.Application.Contracts.Dtos.Chat;
|
||||||
|
|
||||||
|
public class AgentToolOutput
|
||||||
|
{
|
||||||
|
public string Code { get; set; }
|
||||||
|
|
||||||
|
public string Name { get; set; }
|
||||||
|
}
|
||||||
@@ -0,0 +1,27 @@
|
|||||||
|
namespace Yi.Framework.AiHub.Application.Contracts.Dtos.Chat;
|
||||||
|
|
||||||
|
/// <summary>
|
||||||
|
/// 图片生成输入
|
||||||
|
/// </summary>
|
||||||
|
public class ImageGenerationInput
|
||||||
|
{
|
||||||
|
/// <summary>
|
||||||
|
/// 密钥id
|
||||||
|
/// </summary>
|
||||||
|
public Guid? TokenId { get; set; }
|
||||||
|
|
||||||
|
/// <summary>
|
||||||
|
/// 提示词
|
||||||
|
/// </summary>
|
||||||
|
public string Prompt { get; set; } = string.Empty;
|
||||||
|
|
||||||
|
/// <summary>
|
||||||
|
/// 模型ID
|
||||||
|
/// </summary>
|
||||||
|
public string ModelId { get; set; } = string.Empty;
|
||||||
|
|
||||||
|
/// <summary>
|
||||||
|
/// 参考图PrefixBase64列表(可选,包含前缀如 data:image/png;base64,...)
|
||||||
|
/// </summary>
|
||||||
|
public List<string>? ReferenceImagesPrefixBase64 { get; set; }
|
||||||
|
}
|
||||||
@@ -0,0 +1,26 @@
|
|||||||
|
using Volo.Abp.Application.Dtos;
|
||||||
|
using Yi.Framework.AiHub.Domain.Shared.Enums;
|
||||||
|
using Yi.Framework.Ddd.Application.Contracts;
|
||||||
|
|
||||||
|
namespace Yi.Framework.AiHub.Application.Contracts.Dtos.Chat;
|
||||||
|
|
||||||
|
/// <summary>
|
||||||
|
/// 图片任务分页查询输入
|
||||||
|
/// </summary>
|
||||||
|
public class ImageMyTaskPageInput: PagedAllResultRequestDto
|
||||||
|
{
|
||||||
|
/// <summary>
|
||||||
|
/// 提示词
|
||||||
|
/// </summary>
|
||||||
|
public string? Prompt { get; set; }
|
||||||
|
|
||||||
|
/// <summary>
|
||||||
|
/// 任务状态筛选(可选)
|
||||||
|
/// </summary>
|
||||||
|
public TaskStatusEnum? TaskStatus { get; set; }
|
||||||
|
|
||||||
|
/// <summary>
|
||||||
|
/// 发布状态
|
||||||
|
/// </summary>
|
||||||
|
public PublishStatusEnum? PublishStatus { get; set; }
|
||||||
|
}
|
||||||
@@ -0,0 +1,31 @@
|
|||||||
|
using Volo.Abp.Application.Dtos;
|
||||||
|
using Yi.Framework.AiHub.Domain.Shared.Enums;
|
||||||
|
using Yi.Framework.Ddd.Application.Contracts;
|
||||||
|
|
||||||
|
namespace Yi.Framework.AiHub.Application.Contracts.Dtos.Chat;
|
||||||
|
|
||||||
|
/// <summary>
|
||||||
|
/// 图片任务分页查询输入
|
||||||
|
/// </summary>
|
||||||
|
public class ImagePlazaPageInput: PagedAllResultRequestDto
|
||||||
|
{
|
||||||
|
/// <summary>
|
||||||
|
/// 分类
|
||||||
|
/// </summary>
|
||||||
|
public string? Categories { get; set; }
|
||||||
|
|
||||||
|
/// <summary>
|
||||||
|
/// 提示词
|
||||||
|
/// </summary>
|
||||||
|
public string? Prompt { get; set; }
|
||||||
|
|
||||||
|
/// <summary>
|
||||||
|
/// 任务状态筛选(可选)
|
||||||
|
/// </summary>
|
||||||
|
public TaskStatusEnum? TaskStatus { get; set; }
|
||||||
|
|
||||||
|
/// <summary>
|
||||||
|
/// 用户名
|
||||||
|
/// </summary>
|
||||||
|
public string? UserName{ get; set; }
|
||||||
|
}
|
||||||
@@ -0,0 +1,66 @@
|
|||||||
|
using Yi.Framework.AiHub.Domain.Shared.Enums;
|
||||||
|
|
||||||
|
namespace Yi.Framework.AiHub.Application.Contracts.Dtos.Chat;
|
||||||
|
|
||||||
|
/// <summary>
|
||||||
|
/// 图片任务输出
|
||||||
|
/// </summary>
|
||||||
|
public class ImageTaskOutput
|
||||||
|
{
|
||||||
|
/// <summary>
|
||||||
|
/// 任务ID
|
||||||
|
/// </summary>
|
||||||
|
public Guid Id { get; set; }
|
||||||
|
|
||||||
|
/// <summary>
|
||||||
|
/// 提示词
|
||||||
|
/// </summary>
|
||||||
|
public string Prompt { get; set; } = string.Empty;
|
||||||
|
|
||||||
|
/// <summary>
|
||||||
|
/// 是否匿名
|
||||||
|
/// </summary>
|
||||||
|
public bool IsAnonymous { get; set; }
|
||||||
|
|
||||||
|
/// <summary>
|
||||||
|
/// 生成图片URL
|
||||||
|
/// </summary>
|
||||||
|
public string? StoreUrl { get; set; }
|
||||||
|
|
||||||
|
/// <summary>
|
||||||
|
/// 任务状态
|
||||||
|
/// </summary>
|
||||||
|
public TaskStatusEnum TaskStatus { get; set; }
|
||||||
|
|
||||||
|
/// <summary>
|
||||||
|
/// 发布状态
|
||||||
|
/// </summary>
|
||||||
|
public PublishStatusEnum PublishStatus { get; set; }
|
||||||
|
|
||||||
|
/// <summary>
|
||||||
|
/// 分类标签
|
||||||
|
/// </summary>
|
||||||
|
[SqlSugar.SugarColumn( IsJson = true)]
|
||||||
|
public List<string> Categories { get; set; } = new();
|
||||||
|
|
||||||
|
/// <summary>
|
||||||
|
/// 创建时间
|
||||||
|
/// </summary>
|
||||||
|
public DateTime CreationTime { get; set; }
|
||||||
|
|
||||||
|
/// <summary>
|
||||||
|
/// 错误信息
|
||||||
|
/// </summary>
|
||||||
|
public string? ErrorInfo { get; set; }
|
||||||
|
|
||||||
|
/// <summary>
|
||||||
|
/// 用户名称
|
||||||
|
/// </summary>
|
||||||
|
public string? UserName { get; set; }
|
||||||
|
|
||||||
|
/// <summary>
|
||||||
|
/// 用户名称Id
|
||||||
|
/// </summary>
|
||||||
|
public Guid? UserId { get; set; }
|
||||||
|
|
||||||
|
}
|
||||||
@@ -0,0 +1,22 @@
|
|||||||
|
namespace Yi.Framework.AiHub.Application.Contracts.Dtos.Chat;
|
||||||
|
|
||||||
|
/// <summary>
|
||||||
|
/// 发布图片输入
|
||||||
|
/// </summary>
|
||||||
|
public class PublishImageInput
|
||||||
|
{
|
||||||
|
/// <summary>
|
||||||
|
/// 是否匿名
|
||||||
|
/// </summary>
|
||||||
|
public bool IsAnonymous { get; set; } = false;
|
||||||
|
|
||||||
|
/// <summary>
|
||||||
|
/// 任务ID
|
||||||
|
/// </summary>
|
||||||
|
public Guid TaskId { get; set; }
|
||||||
|
|
||||||
|
/// <summary>
|
||||||
|
/// 分类标签
|
||||||
|
/// </summary>
|
||||||
|
public List<string> Categories { get; set; } = new();
|
||||||
|
}
|
||||||
@@ -0,0 +1,17 @@
|
|||||||
|
namespace Yi.Framework.AiHub.Application.Contracts.Dtos.Model;
|
||||||
|
|
||||||
|
/// <summary>
|
||||||
|
/// API类型选项
|
||||||
|
/// </summary>
|
||||||
|
public class ModelApiTypeOption
|
||||||
|
{
|
||||||
|
/// <summary>
|
||||||
|
/// 显示名称
|
||||||
|
/// </summary>
|
||||||
|
public string Label { get; set; }
|
||||||
|
|
||||||
|
/// <summary>
|
||||||
|
/// 枚举值
|
||||||
|
/// </summary>
|
||||||
|
public int Value { get; set; }
|
||||||
|
}
|
||||||
@@ -0,0 +1,79 @@
|
|||||||
|
using Yi.Framework.AiHub.Domain.Shared.Enums;
|
||||||
|
using Yi.Framework.AiHub.Domain.Shared.Extensions;
|
||||||
|
|
||||||
|
namespace Yi.Framework.AiHub.Application.Contracts.Dtos.Model;
|
||||||
|
|
||||||
|
/// <summary>
|
||||||
|
/// 模型库展示数据
|
||||||
|
/// </summary>
|
||||||
|
public class ModelLibraryDto
|
||||||
|
{
|
||||||
|
/// <summary>
|
||||||
|
/// 模型ID
|
||||||
|
/// </summary>
|
||||||
|
public string ModelId { get; set; }
|
||||||
|
|
||||||
|
/// <summary>
|
||||||
|
/// 模型名称
|
||||||
|
/// </summary>
|
||||||
|
public string Name { get; set; }
|
||||||
|
|
||||||
|
/// <summary>
|
||||||
|
/// 模型描述
|
||||||
|
/// </summary>
|
||||||
|
public string? Description { get; set; }
|
||||||
|
|
||||||
|
/// <summary>
|
||||||
|
/// 模型类型
|
||||||
|
/// </summary>
|
||||||
|
public ModelTypeEnum ModelType { get; set; }
|
||||||
|
|
||||||
|
/// <summary>
|
||||||
|
/// 模型类型名称
|
||||||
|
/// </summary>
|
||||||
|
public string ModelTypeName => ModelType.GetDescription();
|
||||||
|
|
||||||
|
/// <summary>
|
||||||
|
/// 模型支持的API类型
|
||||||
|
/// </summary>
|
||||||
|
public List<ModelApiTypeOutput> ModelApiTypes { get; set; }
|
||||||
|
|
||||||
|
|
||||||
|
/// <summary>
|
||||||
|
/// 模型显示倍率
|
||||||
|
/// </summary>
|
||||||
|
public decimal MultiplierShow { get; set; }
|
||||||
|
|
||||||
|
/// <summary>
|
||||||
|
/// 供应商分组名称
|
||||||
|
/// </summary>
|
||||||
|
public string? ProviderName { get; set; }
|
||||||
|
|
||||||
|
/// <summary>
|
||||||
|
/// 模型图标URL
|
||||||
|
/// </summary>
|
||||||
|
public string? IconUrl { get; set; }
|
||||||
|
|
||||||
|
/// <summary>
|
||||||
|
/// 是否为尊享模型(PremiumChat类型)
|
||||||
|
/// </summary>
|
||||||
|
public bool IsPremium { get; set; }
|
||||||
|
|
||||||
|
/// <summary>
|
||||||
|
/// 排序
|
||||||
|
/// </summary>
|
||||||
|
public int OrderNum { get; set; }
|
||||||
|
}
|
||||||
|
|
||||||
|
public class ModelApiTypeOutput
|
||||||
|
{
|
||||||
|
/// <summary>
|
||||||
|
/// 模型类型
|
||||||
|
/// </summary>
|
||||||
|
public ModelApiTypeEnum ModelApiType { get; set; }
|
||||||
|
|
||||||
|
/// <summary>
|
||||||
|
/// 模型类型名称
|
||||||
|
/// </summary>
|
||||||
|
public string ModelApiTypeName => ModelApiType.GetDescription();
|
||||||
|
}
|
||||||
@@ -0,0 +1,35 @@
|
|||||||
|
using Yi.Framework.AiHub.Domain.Shared.Enums;
|
||||||
|
using Yi.Framework.Ddd.Application.Contracts;
|
||||||
|
|
||||||
|
namespace Yi.Framework.AiHub.Application.Contracts.Dtos.Model;
|
||||||
|
|
||||||
|
/// <summary>
|
||||||
|
/// 获取模型库列表查询参数
|
||||||
|
/// </summary>
|
||||||
|
public class ModelLibraryGetListInput : PagedAllResultRequestDto
|
||||||
|
{
|
||||||
|
/// <summary>
|
||||||
|
/// 搜索关键词(搜索模型名称、模型ID)
|
||||||
|
/// </summary>
|
||||||
|
public string? SearchKey { get; set; }
|
||||||
|
|
||||||
|
/// <summary>
|
||||||
|
/// 供应商名称筛选
|
||||||
|
/// </summary>
|
||||||
|
public List<string>? ProviderNames { get; set; }
|
||||||
|
|
||||||
|
/// <summary>
|
||||||
|
/// 模型类型筛选
|
||||||
|
/// </summary>
|
||||||
|
public List<ModelTypeEnum>? ModelTypes { get; set; }
|
||||||
|
|
||||||
|
/// <summary>
|
||||||
|
/// API类型筛选
|
||||||
|
/// </summary>
|
||||||
|
public List<ModelApiTypeEnum>? ModelApiTypes { get; set; }
|
||||||
|
|
||||||
|
/// <summary>
|
||||||
|
/// 是否只显示尊享模型
|
||||||
|
/// </summary>
|
||||||
|
public bool? IsPremiumOnly { get; set; }
|
||||||
|
}
|
||||||
@@ -0,0 +1,17 @@
|
|||||||
|
namespace Yi.Framework.AiHub.Application.Contracts.Dtos.Model;
|
||||||
|
|
||||||
|
/// <summary>
|
||||||
|
/// 模型类型选项
|
||||||
|
/// </summary>
|
||||||
|
public class ModelTypeOption
|
||||||
|
{
|
||||||
|
/// <summary>
|
||||||
|
/// 显示名称
|
||||||
|
/// </summary>
|
||||||
|
public string Label { get; set; }
|
||||||
|
|
||||||
|
/// <summary>
|
||||||
|
/// 枚举值
|
||||||
|
/// </summary>
|
||||||
|
public int Value { get; set; }
|
||||||
|
}
|
||||||
@@ -7,12 +7,6 @@ public class ModelGetListOutput
|
|||||||
/// </summary>
|
/// </summary>
|
||||||
public Guid Id { get; set; }
|
public Guid Id { get; set; }
|
||||||
|
|
||||||
/// <summary>
|
|
||||||
/// 模型分类
|
|
||||||
/// </summary>
|
|
||||||
public string Category { get; set; }
|
|
||||||
|
|
||||||
|
|
||||||
/// <summary>
|
/// <summary>
|
||||||
/// 模型id
|
/// 模型id
|
||||||
/// </summary>
|
/// </summary>
|
||||||
@@ -28,38 +22,13 @@ public class ModelGetListOutput
|
|||||||
/// </summary>
|
/// </summary>
|
||||||
public string? ModelDescribe { get; set; }
|
public string? ModelDescribe { get; set; }
|
||||||
|
|
||||||
/// <summary>
|
|
||||||
/// 模型价格
|
|
||||||
/// </summary>
|
|
||||||
public double ModelPrice { get; set; }
|
|
||||||
|
|
||||||
/// <summary>
|
|
||||||
/// 模型类型
|
|
||||||
/// </summary>
|
|
||||||
public string ModelType { get; set; }
|
|
||||||
|
|
||||||
/// <summary>
|
|
||||||
/// 模型展示状态
|
|
||||||
/// </summary>
|
|
||||||
public string ModelShow { get; set; }
|
|
||||||
|
|
||||||
/// <summary>
|
|
||||||
/// 系统提示
|
|
||||||
/// </summary>
|
|
||||||
public string SystemPrompt { get; set; }
|
|
||||||
|
|
||||||
/// <summary>
|
|
||||||
/// API 主机地址
|
|
||||||
/// </summary>
|
|
||||||
public string ApiHost { get; set; }
|
|
||||||
|
|
||||||
/// <summary>
|
|
||||||
/// API 密钥
|
|
||||||
/// </summary>
|
|
||||||
public string ApiKey { get; set; }
|
|
||||||
|
|
||||||
/// <summary>
|
/// <summary>
|
||||||
/// 备注信息
|
/// 备注信息
|
||||||
/// </summary>
|
/// </summary>
|
||||||
public string? Remark { get; set; }
|
public string? Remark { get; set; }
|
||||||
|
|
||||||
|
/// <summary>
|
||||||
|
/// 是否为尊享包
|
||||||
|
/// </summary>
|
||||||
|
public bool IsPremiumPackage { get; set; }
|
||||||
}
|
}
|
||||||
@@ -25,11 +25,17 @@ public class RechargeCreateInput
|
|||||||
public string Content { get; set; } = string.Empty;
|
public string Content { get; set; } = string.Empty;
|
||||||
|
|
||||||
/// <summary>
|
/// <summary>
|
||||||
/// VIP月数(为空或0表示永久VIP)
|
/// VIP月数(为空或0表示永久VIP,1个月按31天计算)
|
||||||
/// </summary>
|
/// </summary>
|
||||||
[Range(0, int.MaxValue, ErrorMessage = "月数必须大于等于0")]
|
[Range(0, int.MaxValue, ErrorMessage = "月数必须大于等于0")]
|
||||||
public int? Months { get; set; }
|
public int? Months { get; set; }
|
||||||
|
|
||||||
|
/// <summary>
|
||||||
|
/// VIP天数(为空或0表示不使用天数充值)
|
||||||
|
/// </summary>
|
||||||
|
[Range(0, int.MaxValue, ErrorMessage = "天数必须大于等于0")]
|
||||||
|
public int? Days { get; set; }
|
||||||
|
|
||||||
/// <summary>
|
/// <summary>
|
||||||
/// 备注
|
/// 备注
|
||||||
/// </summary>
|
/// </summary>
|
||||||
|
|||||||
@@ -0,0 +1,26 @@
|
|||||||
|
using System.ComponentModel.DataAnnotations;
|
||||||
|
|
||||||
|
namespace Yi.Framework.AiHub.Application.Contracts.Dtos.Token;
|
||||||
|
|
||||||
|
/// <summary>
|
||||||
|
/// 创建Token输入
|
||||||
|
/// </summary>
|
||||||
|
public class TokenCreateInput
|
||||||
|
{
|
||||||
|
/// <summary>
|
||||||
|
/// 名称(同一用户不能重复)
|
||||||
|
/// </summary>
|
||||||
|
[Required(ErrorMessage = "名称不能为空")]
|
||||||
|
[StringLength(100, ErrorMessage = "名称长度不能超过100个字符")]
|
||||||
|
public string Name { get; set; }
|
||||||
|
|
||||||
|
/// <summary>
|
||||||
|
/// 过期时间(空为永不过期)
|
||||||
|
/// </summary>
|
||||||
|
public DateTime? ExpireTime { get; set; }
|
||||||
|
|
||||||
|
/// <summary>
|
||||||
|
/// 尊享包额度限制(空为不限制)
|
||||||
|
/// </summary>
|
||||||
|
public long? PremiumQuotaLimit { get; set; }
|
||||||
|
}
|
||||||
@@ -0,0 +1,47 @@
|
|||||||
|
namespace Yi.Framework.AiHub.Application.Contracts.Dtos.Token;
|
||||||
|
|
||||||
|
/// <summary>
|
||||||
|
/// Token列表输出
|
||||||
|
/// </summary>
|
||||||
|
public class TokenGetListOutputDto
|
||||||
|
{
|
||||||
|
/// <summary>
|
||||||
|
/// Token Id
|
||||||
|
/// </summary>
|
||||||
|
public Guid Id { get; set; }
|
||||||
|
|
||||||
|
/// <summary>
|
||||||
|
/// 名称
|
||||||
|
/// </summary>
|
||||||
|
public string Name { get; set; }
|
||||||
|
|
||||||
|
/// <summary>
|
||||||
|
/// Token密钥
|
||||||
|
/// </summary>
|
||||||
|
public string ApiKey { get; set; }
|
||||||
|
|
||||||
|
/// <summary>
|
||||||
|
/// 过期时间(空为永不过期)
|
||||||
|
/// </summary>
|
||||||
|
public DateTime? ExpireTime { get; set; }
|
||||||
|
|
||||||
|
/// <summary>
|
||||||
|
/// 尊享包额度限制(空为不限制)
|
||||||
|
/// </summary>
|
||||||
|
public long? PremiumQuotaLimit { get; set; }
|
||||||
|
|
||||||
|
/// <summary>
|
||||||
|
/// 尊享包已使用额度
|
||||||
|
/// </summary>
|
||||||
|
public long PremiumUsedQuota { get; set; }
|
||||||
|
|
||||||
|
/// <summary>
|
||||||
|
/// 是否禁用
|
||||||
|
/// </summary>
|
||||||
|
public bool IsDisabled { get; set; }
|
||||||
|
|
||||||
|
/// <summary>
|
||||||
|
/// 创建时间
|
||||||
|
/// </summary>
|
||||||
|
public DateTime CreationTime { get; set; }
|
||||||
|
}
|
||||||
@@ -0,0 +1,9 @@
|
|||||||
|
namespace Yi.Framework.AiHub.Application.Contracts.Dtos.Token;
|
||||||
|
|
||||||
|
public class TokenSelectListOutputDto
|
||||||
|
{
|
||||||
|
public Guid TokenId { get; set; }
|
||||||
|
public string Name { get; set; }
|
||||||
|
|
||||||
|
public bool IsDisabled { get; set; }
|
||||||
|
}
|
||||||
@@ -0,0 +1,32 @@
|
|||||||
|
using System.ComponentModel.DataAnnotations;
|
||||||
|
|
||||||
|
namespace Yi.Framework.AiHub.Application.Contracts.Dtos.Token;
|
||||||
|
|
||||||
|
/// <summary>
|
||||||
|
/// 编辑Token输入
|
||||||
|
/// </summary>
|
||||||
|
public class TokenUpdateInput
|
||||||
|
{
|
||||||
|
/// <summary>
|
||||||
|
/// Token Id
|
||||||
|
/// </summary>
|
||||||
|
[Required(ErrorMessage = "Id不能为空")]
|
||||||
|
public Guid Id { get; set; }
|
||||||
|
|
||||||
|
/// <summary>
|
||||||
|
/// 名称(同一用户不能重复)
|
||||||
|
/// </summary>
|
||||||
|
[Required(ErrorMessage = "名称不能为空")]
|
||||||
|
[StringLength(100, ErrorMessage = "名称长度不能超过100个字符")]
|
||||||
|
public string Name { get; set; }
|
||||||
|
|
||||||
|
/// <summary>
|
||||||
|
/// 过期时间(空为永不过期)
|
||||||
|
/// </summary>
|
||||||
|
public DateTime? ExpireTime { get; set; }
|
||||||
|
|
||||||
|
/// <summary>
|
||||||
|
/// 尊享包额度限制(空为不限制)
|
||||||
|
/// </summary>
|
||||||
|
public long? PremiumQuotaLimit { 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,27 @@
|
|||||||
|
namespace Yi.Framework.AiHub.Application.Contracts.Dtos.UsageStatistics;
|
||||||
|
|
||||||
|
/// <summary>
|
||||||
|
/// 尊享包不同Token用量占比DTO(饼图)
|
||||||
|
/// </summary>
|
||||||
|
public class TokenPremiumUsageDto
|
||||||
|
{
|
||||||
|
/// <summary>
|
||||||
|
/// Token Id
|
||||||
|
/// </summary>
|
||||||
|
public Guid TokenId { get; set; }
|
||||||
|
|
||||||
|
/// <summary>
|
||||||
|
/// Token名称
|
||||||
|
/// </summary>
|
||||||
|
public string TokenName { get; set; }
|
||||||
|
|
||||||
|
/// <summary>
|
||||||
|
/// Token消耗量
|
||||||
|
/// </summary>
|
||||||
|
public long Tokens { get; set; }
|
||||||
|
|
||||||
|
/// <summary>
|
||||||
|
/// 占比(百分比)
|
||||||
|
/// </summary>
|
||||||
|
public decimal Percentage { get; set; }
|
||||||
|
}
|
||||||
@@ -0,0 +1,9 @@
|
|||||||
|
namespace Yi.Framework.AiHub.Application.Contracts.Dtos.UsageStatistics;
|
||||||
|
|
||||||
|
public class UsageStatisticsGetInput
|
||||||
|
{
|
||||||
|
/// <summary>
|
||||||
|
/// tokenId
|
||||||
|
/// </summary>
|
||||||
|
public Guid? TokenId { get; set; }
|
||||||
|
}
|
||||||
@@ -0,0 +1,20 @@
|
|||||||
|
using Volo.Abp.Application.Services;
|
||||||
|
using Yi.Framework.AiHub.Application.Contracts.Dtos.ActivationCode;
|
||||||
|
|
||||||
|
namespace Yi.Framework.AiHub.Application.Contracts.IServices;
|
||||||
|
|
||||||
|
/// <summary>
|
||||||
|
/// 激活码服务接口
|
||||||
|
/// </summary>
|
||||||
|
public interface IActivationCodeService : IApplicationService
|
||||||
|
{
|
||||||
|
/// <summary>
|
||||||
|
/// 批量生成激活码
|
||||||
|
/// </summary>
|
||||||
|
Task<ActivationCodeCreateListOutput> CreateBatchAsync(ActivationCodeCreateListInput input);
|
||||||
|
|
||||||
|
/// <summary>
|
||||||
|
/// 兑换激活码
|
||||||
|
/// </summary>
|
||||||
|
Task<ActivationCodeRedeemOutput> RedeemAsync(ActivationCodeRedeemInput input);
|
||||||
|
}
|
||||||
@@ -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,86 @@
|
|||||||
|
using Volo.Abp.Application.Dtos;
|
||||||
|
using Yi.Framework.AiHub.Application.Contracts.Dtos.Channel;
|
||||||
|
|
||||||
|
namespace Yi.Framework.AiHub.Application.Contracts.IServices;
|
||||||
|
|
||||||
|
/// <summary>
|
||||||
|
/// 渠道商管理服务接口
|
||||||
|
/// </summary>
|
||||||
|
public interface IChannelService
|
||||||
|
{
|
||||||
|
#region AI应用管理
|
||||||
|
|
||||||
|
/// <summary>
|
||||||
|
/// 获取AI应用列表
|
||||||
|
/// </summary>
|
||||||
|
/// <param name="input">查询参数</param>
|
||||||
|
/// <returns>分页应用列表</returns>
|
||||||
|
Task<PagedResultDto<AiAppDto>> GetAppListAsync(AiAppGetListInput input);
|
||||||
|
|
||||||
|
/// <summary>
|
||||||
|
/// 根据ID获取AI应用
|
||||||
|
/// </summary>
|
||||||
|
/// <param name="id">应用ID</param>
|
||||||
|
/// <returns>应用详情</returns>
|
||||||
|
Task<AiAppDto> GetAppByIdAsync(Guid id);
|
||||||
|
|
||||||
|
/// <summary>
|
||||||
|
/// 创建AI应用
|
||||||
|
/// </summary>
|
||||||
|
/// <param name="input">创建输入</param>
|
||||||
|
/// <returns>创建的应用</returns>
|
||||||
|
Task<AiAppDto> CreateAppAsync(AiAppCreateInput input);
|
||||||
|
|
||||||
|
/// <summary>
|
||||||
|
/// 更新AI应用
|
||||||
|
/// </summary>
|
||||||
|
/// <param name="input">更新输入</param>
|
||||||
|
/// <returns>更新后的应用</returns>
|
||||||
|
Task<AiAppDto> UpdateAppAsync(AiAppUpdateInput input);
|
||||||
|
|
||||||
|
/// <summary>
|
||||||
|
/// 删除AI应用
|
||||||
|
/// </summary>
|
||||||
|
/// <param name="id">应用ID</param>
|
||||||
|
Task DeleteAppAsync(Guid id);
|
||||||
|
|
||||||
|
#endregion
|
||||||
|
|
||||||
|
#region AI模型管理
|
||||||
|
|
||||||
|
/// <summary>
|
||||||
|
/// 获取AI模型列表
|
||||||
|
/// </summary>
|
||||||
|
/// <param name="input">查询参数</param>
|
||||||
|
/// <returns>分页模型列表</returns>
|
||||||
|
Task<PagedResultDto<AiModelDto>> GetModelListAsync(AiModelGetListInput input);
|
||||||
|
|
||||||
|
/// <summary>
|
||||||
|
/// 根据ID获取AI模型
|
||||||
|
/// </summary>
|
||||||
|
/// <param name="id">模型ID</param>
|
||||||
|
/// <returns>模型详情</returns>
|
||||||
|
Task<AiModelDto> GetModelByIdAsync(Guid id);
|
||||||
|
|
||||||
|
/// <summary>
|
||||||
|
/// 创建AI模型
|
||||||
|
/// </summary>
|
||||||
|
/// <param name="input">创建输入</param>
|
||||||
|
/// <returns>创建的模型</returns>
|
||||||
|
Task<AiModelDto> CreateModelAsync(AiModelCreateInput input);
|
||||||
|
|
||||||
|
/// <summary>
|
||||||
|
/// 更新AI模型
|
||||||
|
/// </summary>
|
||||||
|
/// <param name="input">更新输入</param>
|
||||||
|
/// <returns>更新后的模型</returns>
|
||||||
|
Task<AiModelDto> UpdateModelAsync(AiModelUpdateInput input);
|
||||||
|
|
||||||
|
/// <summary>
|
||||||
|
/// 删除AI模型(软删除)
|
||||||
|
/// </summary>
|
||||||
|
/// <param name="id">模型ID</param>
|
||||||
|
Task DeleteModelAsync(Guid id);
|
||||||
|
|
||||||
|
#endregion
|
||||||
|
}
|
||||||
@@ -0,0 +1,35 @@
|
|||||||
|
using Volo.Abp.Application.Dtos;
|
||||||
|
using Yi.Framework.AiHub.Application.Contracts.Dtos.Model;
|
||||||
|
|
||||||
|
namespace Yi.Framework.AiHub.Application.Contracts.IServices;
|
||||||
|
|
||||||
|
/// <summary>
|
||||||
|
/// 模型服务接口
|
||||||
|
/// </summary>
|
||||||
|
public interface IModelService
|
||||||
|
{
|
||||||
|
/// <summary>
|
||||||
|
/// 获取模型库列表(公开接口,无需登录)
|
||||||
|
/// </summary>
|
||||||
|
/// <param name="input">查询参数</param>
|
||||||
|
/// <returns>分页模型列表</returns>
|
||||||
|
Task<PagedResultDto<ModelLibraryDto>> GetListAsync(ModelLibraryGetListInput input);
|
||||||
|
|
||||||
|
/// <summary>
|
||||||
|
/// 获取供应商列表(公开接口,无需登录)
|
||||||
|
/// </summary>
|
||||||
|
/// <returns>供应商列表</returns>
|
||||||
|
Task<List<string>> GetProviderListAsync();
|
||||||
|
|
||||||
|
/// <summary>
|
||||||
|
/// 获取模型类型选项列表(公开接口,无需登录)
|
||||||
|
/// </summary>
|
||||||
|
/// <returns>模型类型选项</returns>
|
||||||
|
Task<List<ModelTypeOption>> GetModelTypeOptionsAsync();
|
||||||
|
|
||||||
|
/// <summary>
|
||||||
|
/// 获取API类型选项列表(公开接口,无需登录)
|
||||||
|
/// </summary>
|
||||||
|
/// <returns>API类型选项</returns>
|
||||||
|
Task<List<ModelApiTypeOption>> GetApiTypeOptionsAsync();
|
||||||
|
}
|
||||||
@@ -11,13 +11,13 @@ public interface IUsageStatisticsService
|
|||||||
/// 获取当前用户近7天的Token消耗统计
|
/// 获取当前用户近7天的Token消耗统计
|
||||||
/// </summary>
|
/// </summary>
|
||||||
/// <returns>每日Token使用量列表</returns>
|
/// <returns>每日Token使用量列表</returns>
|
||||||
Task<List<DailyTokenUsageDto>> GetLast7DaysTokenUsageAsync();
|
Task<List<DailyTokenUsageDto>> GetLast7DaysTokenUsageAsync(UsageStatisticsGetInput input);
|
||||||
|
|
||||||
/// <summary>
|
/// <summary>
|
||||||
/// 获取当前用户各个模型的Token消耗量及占比
|
/// 获取当前用户各个模型的Token消耗量及占比
|
||||||
/// </summary>
|
/// </summary>
|
||||||
/// <returns>模型Token使用量列表</returns>
|
/// <returns>模型Token使用量列表</returns>
|
||||||
Task<List<ModelTokenUsageDto>> GetModelTokenUsageAsync();
|
Task<List<ModelTokenUsageDto>> GetModelTokenUsageAsync(UsageStatisticsGetInput input);
|
||||||
|
|
||||||
/// <summary>
|
/// <summary>
|
||||||
/// 获取当前用户尊享服务Token用量统计
|
/// 获取当前用户尊享服务Token用量统计
|
||||||
|
|||||||
@@ -0,0 +1,123 @@
|
|||||||
|
using System.Text.Json;
|
||||||
|
using Microsoft.Extensions.Logging;
|
||||||
|
using Volo.Abp.BackgroundJobs;
|
||||||
|
using Volo.Abp.DependencyInjection;
|
||||||
|
using Yi.Framework.AiHub.Domain.Entities.Chat;
|
||||||
|
using Yi.Framework.AiHub.Domain.Managers;
|
||||||
|
using Yi.Framework.AiHub.Domain.Shared.Enums;
|
||||||
|
using Yi.Framework.SqlSugarCore.Abstractions;
|
||||||
|
|
||||||
|
namespace Yi.Framework.AiHub.Application.Jobs;
|
||||||
|
|
||||||
|
/// <summary>
|
||||||
|
/// 图片生成后台任务
|
||||||
|
/// </summary>
|
||||||
|
public class ImageGenerationJob : AsyncBackgroundJob<ImageGenerationJobArgs>, ITransientDependency
|
||||||
|
{
|
||||||
|
private readonly ILogger<ImageGenerationJob> _logger;
|
||||||
|
private readonly AiGateWayManager _aiGateWayManager;
|
||||||
|
private readonly ISqlSugarRepository<ImageStoreTaskAggregateRoot> _imageStoreTaskRepository;
|
||||||
|
|
||||||
|
public ImageGenerationJob(
|
||||||
|
ILogger<ImageGenerationJob> logger,
|
||||||
|
AiGateWayManager aiGateWayManager,
|
||||||
|
ISqlSugarRepository<ImageStoreTaskAggregateRoot> imageStoreTaskRepository)
|
||||||
|
{
|
||||||
|
_logger = logger;
|
||||||
|
_aiGateWayManager = aiGateWayManager;
|
||||||
|
_imageStoreTaskRepository = imageStoreTaskRepository;
|
||||||
|
}
|
||||||
|
|
||||||
|
public override async Task ExecuteAsync(ImageGenerationJobArgs args)
|
||||||
|
{
|
||||||
|
var task = await _imageStoreTaskRepository.GetFirstAsync(x => x.Id == args.TaskId);
|
||||||
|
if (task is null)
|
||||||
|
{
|
||||||
|
throw new UserFriendlyException($"{args.TaskId} 图片生成任务不存在");
|
||||||
|
}
|
||||||
|
|
||||||
|
_logger.LogInformation("开始执行图片生成任务,TaskId: {TaskId}, ModelId: {ModelId}, UserId: {UserId}",
|
||||||
|
task.Id, task.ModelId, task.UserId);
|
||||||
|
try
|
||||||
|
{
|
||||||
|
// 构建 Gemini API 请求对象
|
||||||
|
var parts = new List<object>
|
||||||
|
{
|
||||||
|
new { text = task.Prompt }
|
||||||
|
};
|
||||||
|
|
||||||
|
// 添加参考图(如果有)
|
||||||
|
foreach (var prefixBase64 in task.ReferenceImagesPrefixBase64)
|
||||||
|
{
|
||||||
|
var (mimeType, base64Data) = ParsePrefixBase64(prefixBase64);
|
||||||
|
parts.Add(new
|
||||||
|
{
|
||||||
|
inline_data = new
|
||||||
|
{
|
||||||
|
mime_type = mimeType,
|
||||||
|
data = base64Data
|
||||||
|
}
|
||||||
|
});
|
||||||
|
}
|
||||||
|
|
||||||
|
var requestObj = new
|
||||||
|
{
|
||||||
|
contents = new[]
|
||||||
|
{
|
||||||
|
new { role = "user", parts }
|
||||||
|
}
|
||||||
|
};
|
||||||
|
|
||||||
|
var request = JsonSerializer.Deserialize<JsonElement>(
|
||||||
|
JsonSerializer.Serialize(requestObj));
|
||||||
|
|
||||||
|
//里面生成成功已经包含扣款了
|
||||||
|
await _aiGateWayManager.GeminiGenerateContentImageForStatisticsAsync(
|
||||||
|
task.Id,
|
||||||
|
task.ModelId,
|
||||||
|
request,
|
||||||
|
task.UserId,
|
||||||
|
tokenId: task.TokenId);
|
||||||
|
|
||||||
|
|
||||||
|
_logger.LogInformation("图片生成任务完成,TaskId: {TaskId}", args.TaskId);
|
||||||
|
}
|
||||||
|
catch (Exception ex)
|
||||||
|
{
|
||||||
|
var error = $"图片任务失败,TaskId: {args.TaskId},错误信息: {ex.Message},错误堆栈:{ex.StackTrace}";
|
||||||
|
_logger.LogError(ex, error);
|
||||||
|
|
||||||
|
task.TaskStatus = TaskStatusEnum.Fail;
|
||||||
|
task.ErrorInfo = error;
|
||||||
|
|
||||||
|
await _imageStoreTaskRepository.UpdateAsync(task);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
/// <summary>
|
||||||
|
/// 解析带前缀的 Base64 字符串,提取 mimeType 和纯 base64 数据
|
||||||
|
/// </summary>
|
||||||
|
private static (string mimeType, string base64Data) ParsePrefixBase64(string prefixBase64)
|
||||||
|
{
|
||||||
|
// 默认值
|
||||||
|
var mimeType = "image/png";
|
||||||
|
var base64Data = prefixBase64;
|
||||||
|
|
||||||
|
if (prefixBase64.Contains(","))
|
||||||
|
{
|
||||||
|
var parts = prefixBase64.Split(',');
|
||||||
|
if (parts.Length == 2)
|
||||||
|
{
|
||||||
|
var header = parts[0];
|
||||||
|
if (header.Contains(":") && header.Contains(";"))
|
||||||
|
{
|
||||||
|
mimeType = header.Split(':')[1].Split(';')[0];
|
||||||
|
}
|
||||||
|
|
||||||
|
base64Data = parts[1];
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
return (mimeType, base64Data);
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -0,0 +1,12 @@
|
|||||||
|
namespace Yi.Framework.AiHub.Application.Jobs;
|
||||||
|
|
||||||
|
/// <summary>
|
||||||
|
/// 图片生成后台任务参数
|
||||||
|
/// </summary>
|
||||||
|
public class ImageGenerationJobArgs
|
||||||
|
{
|
||||||
|
/// <summary>
|
||||||
|
/// 图片任务ID
|
||||||
|
/// </summary>
|
||||||
|
public Guid TaskId { get; set; }
|
||||||
|
}
|
||||||
@@ -0,0 +1,116 @@
|
|||||||
|
using Medallion.Threading;
|
||||||
|
using Microsoft.AspNetCore.Authorization;
|
||||||
|
using Microsoft.AspNetCore.Mvc;
|
||||||
|
using Volo.Abp;
|
||||||
|
using Volo.Abp.Application.Services;
|
||||||
|
using Volo.Abp.Users;
|
||||||
|
using Yi.Framework.AiHub.Application.Contracts.Dtos.ActivationCode;
|
||||||
|
using Yi.Framework.AiHub.Application.Contracts.Dtos.Recharge;
|
||||||
|
using Yi.Framework.AiHub.Application.Contracts.IServices;
|
||||||
|
using Yi.Framework.AiHub.Domain.Managers;
|
||||||
|
using Yi.Framework.AiHub.Domain.Shared.Enums;
|
||||||
|
|
||||||
|
namespace Yi.Framework.AiHub.Application.Services;
|
||||||
|
|
||||||
|
/// <summary>
|
||||||
|
/// 激活码服务
|
||||||
|
/// </summary>
|
||||||
|
public class ActivationCodeService : ApplicationService, IActivationCodeService
|
||||||
|
{
|
||||||
|
private readonly ActivationCodeManager _activationCodeManager;
|
||||||
|
private readonly IRechargeService _rechargeService;
|
||||||
|
private readonly PremiumPackageManager _premiumPackageManager;
|
||||||
|
private IDistributedLockProvider DistributedLock => LazyServiceProvider.LazyGetRequiredService<IDistributedLockProvider>();
|
||||||
|
public ActivationCodeService(
|
||||||
|
ActivationCodeManager activationCodeManager,
|
||||||
|
IRechargeService rechargeService,
|
||||||
|
PremiumPackageManager premiumPackageManager)
|
||||||
|
{
|
||||||
|
_activationCodeManager = activationCodeManager;
|
||||||
|
_rechargeService = rechargeService;
|
||||||
|
_premiumPackageManager = premiumPackageManager;
|
||||||
|
}
|
||||||
|
|
||||||
|
/// <summary>
|
||||||
|
/// 批量生成激活码
|
||||||
|
/// </summary>
|
||||||
|
[Authorize]
|
||||||
|
[HttpPost("activationCode/Batch")]
|
||||||
|
public async Task<ActivationCodeCreateListOutput> CreateBatchAsync(ActivationCodeCreateListInput input)
|
||||||
|
{
|
||||||
|
if (input.Items == null || input.Items.Count == 0)
|
||||||
|
{
|
||||||
|
throw new UserFriendlyException("生成列表不能为空");
|
||||||
|
}
|
||||||
|
|
||||||
|
var entities = await _activationCodeManager.CreateBatchAsync(
|
||||||
|
input.Items.Select(x => (x.GoodsType, x.Count)).ToList());
|
||||||
|
|
||||||
|
var outputs = entities
|
||||||
|
.GroupBy(x => x.GoodsType)
|
||||||
|
.Select(group => new ActivationCodeCreateOutput
|
||||||
|
{
|
||||||
|
GoodsType = group.Key,
|
||||||
|
Count = group.Count(),
|
||||||
|
Codes = group.Select(x => x.Code).ToList()
|
||||||
|
})
|
||||||
|
.ToList();
|
||||||
|
|
||||||
|
return new ActivationCodeCreateListOutput
|
||||||
|
{
|
||||||
|
Items = outputs
|
||||||
|
};
|
||||||
|
}
|
||||||
|
|
||||||
|
/// <summary>
|
||||||
|
/// 兑换激活码
|
||||||
|
/// </summary>
|
||||||
|
[Authorize]
|
||||||
|
[HttpPost("activationCode/Redeem")]
|
||||||
|
public async Task<ActivationCodeRedeemOutput> RedeemAsync(ActivationCodeRedeemInput input)
|
||||||
|
{
|
||||||
|
//自旋等待,防抖
|
||||||
|
await using var handle =
|
||||||
|
await DistributedLock.AcquireLockAsync($"Yi:AiHub:ActivationCodeLock:{input.Code}");
|
||||||
|
|
||||||
|
var userId = CurrentUser.GetId();
|
||||||
|
var redeemContext = await _activationCodeManager.RedeemAsync(userId, input.Code);
|
||||||
|
var goodsType = redeemContext.ActivationCode.GoodsType;
|
||||||
|
var goods = redeemContext.Goods;
|
||||||
|
var packageName = redeemContext.PackageName;
|
||||||
|
var totalAmount = goods.Price;
|
||||||
|
|
||||||
|
if (goods.TokenAmount > 0)
|
||||||
|
{
|
||||||
|
await _premiumPackageManager.CreatePremiumPackageAsync(
|
||||||
|
userId,
|
||||||
|
goods.TokenAmount,
|
||||||
|
packageName,
|
||||||
|
totalAmount,
|
||||||
|
"激活码兑换",
|
||||||
|
expireMonths: null,
|
||||||
|
isCreateRechargeRecord: !goods.IsCombo);
|
||||||
|
}
|
||||||
|
|
||||||
|
if (goods.VipMonths > 0 || goods.VipDays > 0)
|
||||||
|
{
|
||||||
|
await _rechargeService.RechargeVipAsync(new RechargeCreateInput
|
||||||
|
{
|
||||||
|
UserId = userId,
|
||||||
|
RechargeAmount = totalAmount,
|
||||||
|
Content = packageName,
|
||||||
|
Months = goods.VipMonths,
|
||||||
|
Days = goods.VipDays,
|
||||||
|
Remark = "激活码兑换",
|
||||||
|
ContactInfo = null
|
||||||
|
});
|
||||||
|
}
|
||||||
|
|
||||||
|
return new ActivationCodeRedeemOutput
|
||||||
|
{
|
||||||
|
GoodsType = goodsType,
|
||||||
|
PackageName = packageName,
|
||||||
|
Content = packageName
|
||||||
|
};
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -51,9 +51,8 @@ public class CardFlipService : ApplicationService, ICardFlipService
|
|||||||
// 统计本周邀请人数
|
// 统计本周邀请人数
|
||||||
var invitedCount = await _inviteCodeManager.GetWeeklyInvitationCountAsync(userId, weekStart);
|
var invitedCount = await _inviteCodeManager.GetWeeklyInvitationCountAsync(userId, weekStart);
|
||||||
|
|
||||||
// 检查用户是否已被邀请
|
//当前用户是否已填写过邀请码
|
||||||
var isInvited = await _inviteCodeManager.IsUserInvitedAsync(userId);
|
var isFilledInviteCode = await _inviteCodeManager.IsFilledInviteCodeAsync(userId);
|
||||||
|
|
||||||
var output = new CardFlipStatusOutput
|
var output = new CardFlipStatusOutput
|
||||||
{
|
{
|
||||||
TotalFlips = task?.TotalFlips ?? 0,
|
TotalFlips = task?.TotalFlips ?? 0,
|
||||||
@@ -63,8 +62,8 @@ public class CardFlipService : ApplicationService, ICardFlipService
|
|||||||
CanFlip = _cardFlipManager.CanFlipCard(task),
|
CanFlip = _cardFlipManager.CanFlipCard(task),
|
||||||
MyInviteCode = inviteCode?.Code,
|
MyInviteCode = inviteCode?.Code,
|
||||||
InvitedCount = invitedCount,
|
InvitedCount = invitedCount,
|
||||||
IsInvited = isInvited,
|
FlipRecords = BuildFlipRecords(task),
|
||||||
FlipRecords = BuildFlipRecords(task)
|
IsFilledInviteCode = isFilledInviteCode
|
||||||
};
|
};
|
||||||
|
|
||||||
// 生成提示信息
|
// 生成提示信息
|
||||||
@@ -87,7 +86,7 @@ public class CardFlipService : ApplicationService, ICardFlipService
|
|||||||
// 如果中奖,发放奖励
|
// 如果中奖,发放奖励
|
||||||
if (result.IsWin)
|
if (result.IsWin)
|
||||||
{
|
{
|
||||||
await GrantRewardAsync(userId, result.RewardAmount, $"翻牌活动第{input.FlipNumber}次中奖");
|
await GrantRewardAsync(userId, result.RewardAmount, $"翻牌活动-序号{input.FlipNumber}中奖");
|
||||||
}
|
}
|
||||||
|
|
||||||
// 构建输出
|
// 构建输出
|
||||||
@@ -147,7 +146,6 @@ public class CardFlipService : ApplicationService, ICardFlipService
|
|||||||
{
|
{
|
||||||
MyInviteCode = inviteCode?.Code,
|
MyInviteCode = inviteCode?.Code,
|
||||||
InvitedCount = invitedCount,
|
InvitedCount = invitedCount,
|
||||||
IsInvited = inviteCode?.IsUserInvited ?? false,
|
|
||||||
InvitationHistory = invitationHistory.Select(x => new InvitationHistoryItem
|
InvitationHistory = invitationHistory.Select(x => new InvitationHistoryItem
|
||||||
{
|
{
|
||||||
InvitedUserName = x.InvitedUserName,
|
InvitedUserName = x.InvitedUserName,
|
||||||
@@ -183,6 +181,9 @@ public class CardFlipService : ApplicationService, ICardFlipService
|
|||||||
var flippedOrder = task != null ? _cardFlipManager.GetFlippedOrder(task) : new List<int>();
|
var flippedOrder = task != null ? _cardFlipManager.GetFlippedOrder(task) : new List<int>();
|
||||||
var flippedNumbers = new HashSet<int>(flippedOrder);
|
var flippedNumbers = new HashSet<int>(flippedOrder);
|
||||||
|
|
||||||
|
// 获取中奖记录
|
||||||
|
var winRecords = task?.WinRecords ?? new Dictionary<int, long>();
|
||||||
|
|
||||||
// 构建记录,按照原始序号1-10排列
|
// 构建记录,按照原始序号1-10排列
|
||||||
for (int i = 1; i <= CardFlipManager.TOTAL_MAX_FLIPS; i++)
|
for (int i = 1; i <= CardFlipManager.TOTAL_MAX_FLIPS; i++)
|
||||||
{
|
{
|
||||||
@@ -202,23 +203,11 @@ public class CardFlipService : ApplicationService, ICardFlipService
|
|||||||
{
|
{
|
||||||
var flipOrderIndex = flippedOrder.IndexOf(i) + 1; // 第几次翻的(1-based)
|
var flipOrderIndex = flippedOrder.IndexOf(i) + 1; // 第几次翻的(1-based)
|
||||||
|
|
||||||
// 第8次翻的卡中奖
|
// 检查这次翻牌是否中奖
|
||||||
if (flipOrderIndex == 8)
|
if (winRecords.TryGetValue(flipOrderIndex, out var rewardAmount))
|
||||||
{
|
{
|
||||||
record.IsWin = true;
|
record.IsWin = true;
|
||||||
record.RewardAmount = task.EighthRewardAmount;
|
record.RewardAmount = rewardAmount;
|
||||||
}
|
|
||||||
// 第9次翻的卡中奖
|
|
||||||
else if (flipOrderIndex == 9)
|
|
||||||
{
|
|
||||||
record.IsWin = true;
|
|
||||||
record.RewardAmount = task.NinthRewardAmount;
|
|
||||||
}
|
|
||||||
// 第10次翻的卡中奖
|
|
||||||
else if (flipOrderIndex == 10)
|
|
||||||
{
|
|
||||||
record.IsWin = true;
|
|
||||||
record.RewardAmount = task.TenthRewardAmount;
|
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
@@ -246,10 +235,10 @@ public class CardFlipService : ApplicationService, ICardFlipService
|
|||||||
{
|
{
|
||||||
if (status.TotalFlips >= 7)
|
if (status.TotalFlips >= 7)
|
||||||
{
|
{
|
||||||
return $"本周使用他人邀请码可解锁{status.RemainingInviteFlips}次翻牌,且必中大奖!每次中奖最大额度将翻倍!";
|
return $"本周使用他人邀请码或他人使用你的邀请码,可解锁{status.RemainingInviteFlips}次翻牌,且必中大奖!每次中奖最大额度将翻倍!";
|
||||||
}
|
}
|
||||||
|
|
||||||
return $"本周使用他人邀请码可解锁{status.RemainingInviteFlips}次翻牌,必中大奖!每次中奖最大额度将翻倍!";
|
return $"本周使用他人邀请码或他人使用你的邀请码,可解锁{status.RemainingInviteFlips}次翻牌,必中大奖!每次中奖最大额度将翻倍!";
|
||||||
}
|
}
|
||||||
|
|
||||||
return "继续加油!";
|
return "继续加油!";
|
||||||
@@ -1,3 +1,4 @@
|
|||||||
|
using Medallion.Threading;
|
||||||
using Microsoft.AspNetCore.Authorization;
|
using Microsoft.AspNetCore.Authorization;
|
||||||
using Microsoft.Extensions.Logging;
|
using Microsoft.Extensions.Logging;
|
||||||
using SqlSugar;
|
using SqlSugar;
|
||||||
@@ -6,6 +7,7 @@ using Volo.Abp.Users;
|
|||||||
using Yi.Framework.AiHub.Application.Contracts.Dtos.DailyTask;
|
using Yi.Framework.AiHub.Application.Contracts.Dtos.DailyTask;
|
||||||
using Yi.Framework.AiHub.Domain.Entities;
|
using Yi.Framework.AiHub.Domain.Entities;
|
||||||
using Yi.Framework.AiHub.Domain.Entities.Chat;
|
using Yi.Framework.AiHub.Domain.Entities.Chat;
|
||||||
|
using Yi.Framework.AiHub.Domain.Entities.Model;
|
||||||
using Yi.Framework.AiHub.Domain.Extensions;
|
using Yi.Framework.AiHub.Domain.Extensions;
|
||||||
using Yi.Framework.AiHub.Domain.Managers;
|
using Yi.Framework.AiHub.Domain.Managers;
|
||||||
using Yi.Framework.AiHub.Domain.Shared.Consts;
|
using Yi.Framework.AiHub.Domain.Shared.Consts;
|
||||||
@@ -23,25 +25,27 @@ public class DailyTaskService : ApplicationService
|
|||||||
private readonly ISqlSugarRepository<MessageAggregateRoot> _messageRepository;
|
private readonly ISqlSugarRepository<MessageAggregateRoot> _messageRepository;
|
||||||
private readonly ISqlSugarRepository<PremiumPackageAggregateRoot> _premiumPackageRepository;
|
private readonly ISqlSugarRepository<PremiumPackageAggregateRoot> _premiumPackageRepository;
|
||||||
private readonly ILogger<DailyTaskService> _logger;
|
private readonly ILogger<DailyTaskService> _logger;
|
||||||
|
private IDistributedLockProvider DistributedLock => LazyServiceProvider.LazyGetRequiredService<IDistributedLockProvider>();
|
||||||
|
private readonly ISqlSugarRepository<AiModelEntity> _aiModelRepository;
|
||||||
// 任务配置
|
// 任务配置
|
||||||
private readonly Dictionary<int, (long RequiredTokens, long RewardTokens, string Name, string Description)>
|
private readonly Dictionary<int, (long RequiredTokens, long RewardTokens, string Name, string Description)>
|
||||||
_taskConfigs = new()
|
_taskConfigs = new()
|
||||||
{
|
{
|
||||||
{ 1, (10000000, 2000000, "尊享包1000w token任务", "累积使用尊享包 1000w token") }, // 1000w消耗 -> 200w奖励
|
{ 1, (10000000, 1000000, "尊享包1000w token任务", "累积使用尊享包 1000w token") }, // 1000w消耗 -> 100w奖励
|
||||||
{ 2, (30000000, 4000000, "尊享包3000w token任务", "累积使用尊享包 3000w token") } // 3000w消耗 -> 600w奖励
|
{ 2, (30000000, 2000000, "尊享包3000w token任务", "累积使用尊享包 3000w token") } // 3000w消耗 -> 200w奖励
|
||||||
};
|
};
|
||||||
|
|
||||||
public DailyTaskService(
|
public DailyTaskService(
|
||||||
ISqlSugarRepository<DailyTaskRewardRecordAggregateRoot> dailyTaskRepository,
|
ISqlSugarRepository<DailyTaskRewardRecordAggregateRoot> dailyTaskRepository,
|
||||||
ISqlSugarRepository<MessageAggregateRoot> messageRepository,
|
ISqlSugarRepository<MessageAggregateRoot> messageRepository,
|
||||||
ISqlSugarRepository<PremiumPackageAggregateRoot> premiumPackageRepository,
|
ISqlSugarRepository<PremiumPackageAggregateRoot> premiumPackageRepository,
|
||||||
ILogger<DailyTaskService> logger)
|
ILogger<DailyTaskService> logger, ISqlSugarRepository<AiModelEntity> aiModelRepository)
|
||||||
{
|
{
|
||||||
_dailyTaskRepository = dailyTaskRepository;
|
_dailyTaskRepository = dailyTaskRepository;
|
||||||
_messageRepository = messageRepository;
|
_messageRepository = messageRepository;
|
||||||
_premiumPackageRepository = premiumPackageRepository;
|
_premiumPackageRepository = premiumPackageRepository;
|
||||||
_logger = logger;
|
_logger = logger;
|
||||||
|
_aiModelRepository = aiModelRepository;
|
||||||
}
|
}
|
||||||
|
|
||||||
/// <summary>
|
/// <summary>
|
||||||
@@ -113,6 +117,11 @@ public class DailyTaskService : ApplicationService
|
|||||||
public async Task ClaimTaskRewardAsync(ClaimTaskRewardInput input)
|
public async Task ClaimTaskRewardAsync(ClaimTaskRewardInput input)
|
||||||
{
|
{
|
||||||
var userId = CurrentUser.GetId();
|
var userId = CurrentUser.GetId();
|
||||||
|
//自旋等待,防抖
|
||||||
|
await using var handle =
|
||||||
|
await DistributedLock.AcquireLockAsync($"Yi:AiHub:ClaimTaskRewardLock:{userId}");
|
||||||
|
|
||||||
|
|
||||||
var today = DateTime.Today;
|
var today = DateTime.Today;
|
||||||
|
|
||||||
// 1. 验证任务等级
|
// 1. 验证任务等级
|
||||||
@@ -173,10 +182,16 @@ public class DailyTaskService : ApplicationService
|
|||||||
var tomorrow = today.AddDays(1);
|
var tomorrow = today.AddDays(1);
|
||||||
|
|
||||||
// 查询今日所有使用尊享包模型的消息(role=system 表示消耗)
|
// 查询今日所有使用尊享包模型的消息(role=system 表示消耗)
|
||||||
|
// 先获取所有尊享模型的ModelId列表
|
||||||
|
var premiumModelIds = await _aiModelRepository._DbQueryable
|
||||||
|
.Where(x => x.IsPremium)
|
||||||
|
.Select(x => x.ModelId)
|
||||||
|
.ToListAsync();
|
||||||
|
|
||||||
var totalTokens = await _messageRepository._DbQueryable
|
var totalTokens = await _messageRepository._DbQueryable
|
||||||
.Where(x => x.UserId == userId)
|
.Where(x => x.UserId == userId)
|
||||||
.Where(x => x.Role == "system") // system角色表示实际消耗
|
.Where(x => x.Role == "system") // system角色表示实际消耗
|
||||||
.Where(x => PremiumPackageConst.ModeIds.Contains(x.ModelId)) // 尊享包模型
|
.Where(x => premiumModelIds.Contains(x.ModelId)) // 尊享包模型
|
||||||
.Where(x => x.CreationTime >= today && x.CreationTime < tomorrow)
|
.Where(x => x.CreationTime >= today && x.CreationTime < tomorrow)
|
||||||
.SumAsync(x => x.TokenUsage.TotalTokenCount);
|
.SumAsync(x => x.TokenUsage.TotalTokenCount);
|
||||||
|
|
||||||
@@ -1,10 +1,14 @@
|
|||||||
using Mapster;
|
using Mapster;
|
||||||
using Microsoft.AspNetCore.Authorization;
|
using Microsoft.AspNetCore.Authorization;
|
||||||
using Microsoft.AspNetCore.Mvc;
|
using Microsoft.AspNetCore.Mvc;
|
||||||
|
using SqlSugar;
|
||||||
|
using System.Globalization;
|
||||||
|
using System.Text;
|
||||||
using Volo.Abp.Application.Services;
|
using Volo.Abp.Application.Services;
|
||||||
using Volo.Abp.Users;
|
using Volo.Abp.Users;
|
||||||
using Yi.Framework.AiHub.Application.Contracts.Dtos;
|
using Yi.Framework.AiHub.Application.Contracts.Dtos;
|
||||||
using Yi.Framework.AiHub.Domain.Entities;
|
using Yi.Framework.AiHub.Domain.Entities;
|
||||||
|
using Yi.Framework.AiHub.Domain.Entities.Chat;
|
||||||
using Yi.Framework.Rbac.Application.Contracts.IServices;
|
using Yi.Framework.Rbac.Application.Contracts.IServices;
|
||||||
using Yi.Framework.Rbac.Domain.Shared.Dtos;
|
using Yi.Framework.Rbac.Domain.Shared.Dtos;
|
||||||
using Yi.Framework.SqlSugarCore.Abstractions;
|
using Yi.Framework.SqlSugarCore.Abstractions;
|
||||||
@@ -17,15 +21,19 @@ public class AiAccountService : ApplicationService
|
|||||||
private IAccountService _accountService;
|
private IAccountService _accountService;
|
||||||
private ISqlSugarRepository<AiUserExtraInfoEntity> _userRepository;
|
private ISqlSugarRepository<AiUserExtraInfoEntity> _userRepository;
|
||||||
private ISqlSugarRepository<AiRechargeAggregateRoot> _rechargeRepository;
|
private ISqlSugarRepository<AiRechargeAggregateRoot> _rechargeRepository;
|
||||||
|
private ISqlSugarRepository<PremiumPackageAggregateRoot> _premiumPackageRepository;
|
||||||
|
private ISqlSugarRepository<MessageAggregateRoot> _messageRepository;
|
||||||
public AiAccountService(
|
public AiAccountService(
|
||||||
IAccountService accountService,
|
IAccountService accountService,
|
||||||
ISqlSugarRepository<AiUserExtraInfoEntity> userRepository,
|
ISqlSugarRepository<AiUserExtraInfoEntity> userRepository,
|
||||||
ISqlSugarRepository<AiRechargeAggregateRoot> rechargeRepository)
|
ISqlSugarRepository<AiRechargeAggregateRoot> rechargeRepository,
|
||||||
|
ISqlSugarRepository<PremiumPackageAggregateRoot> premiumPackageRepository, ISqlSugarRepository<MessageAggregateRoot> messageRepository)
|
||||||
{
|
{
|
||||||
_accountService = accountService;
|
_accountService = accountService;
|
||||||
_userRepository = userRepository;
|
_userRepository = userRepository;
|
||||||
_rechargeRepository = rechargeRepository;
|
_rechargeRepository = rechargeRepository;
|
||||||
|
_premiumPackageRepository = premiumPackageRepository;
|
||||||
|
_messageRepository = messageRepository;
|
||||||
}
|
}
|
||||||
|
|
||||||
/// <summary>
|
/// <summary>
|
||||||
@@ -72,4 +80,163 @@ public class AiAccountService : ApplicationService
|
|||||||
|
|
||||||
return output;
|
return output;
|
||||||
}
|
}
|
||||||
|
|
||||||
|
/// <summary>
|
||||||
|
/// 获取利润统计数据
|
||||||
|
/// </summary>
|
||||||
|
/// <param name="currentCost">当前成本(RMB)</param>
|
||||||
|
/// <returns></returns>
|
||||||
|
[Authorize]
|
||||||
|
[HttpGet("account/profit-statistics")]
|
||||||
|
public async Task<string> GetProfitStatisticsAsync([FromQuery] decimal currentCost)
|
||||||
|
{
|
||||||
|
if (CurrentUser.UserName != "Guo" && CurrentUser.UserName != "cc")
|
||||||
|
{
|
||||||
|
throw new UserFriendlyException("您暂无权限访问");
|
||||||
|
}
|
||||||
|
|
||||||
|
// 1. 获取尊享包总消耗和剩余库存
|
||||||
|
var premiumPackages = await _premiumPackageRepository._DbQueryable.ToListAsync();
|
||||||
|
long totalUsedTokens = premiumPackages.Sum(p => p.UsedTokens);
|
||||||
|
long totalRemainingTokens = premiumPackages.Sum(p => p.RemainingTokens);
|
||||||
|
|
||||||
|
// 2. 计算1亿Token成本
|
||||||
|
decimal costPerHundredMillion = totalUsedTokens > 0
|
||||||
|
? currentCost / (totalUsedTokens / 100000000m)
|
||||||
|
: 0;
|
||||||
|
|
||||||
|
// 3. 计算总成本(剩余+已使用的总成本)
|
||||||
|
long totalTokens = totalUsedTokens + totalRemainingTokens;
|
||||||
|
decimal totalCost = totalTokens > 0
|
||||||
|
? (totalTokens / 100000000m) * costPerHundredMillion
|
||||||
|
: 0;
|
||||||
|
|
||||||
|
// 4. 获取总收益(RechargeType=PremiumPackage的充值金额总和)
|
||||||
|
decimal totalRevenue = await _rechargeRepository._DbQueryable
|
||||||
|
.Where(x => x.RechargeType == Domain.Shared.Enums.RechargeTypeEnum.PremiumPackage)
|
||||||
|
.SumAsync(x => x.RechargeAmount);
|
||||||
|
|
||||||
|
// 5. 计算利润率
|
||||||
|
decimal profitRate = totalCost > 0
|
||||||
|
? (totalRevenue / totalCost - 1) * 100
|
||||||
|
: 0;
|
||||||
|
|
||||||
|
// 6. 按200售价计算成本
|
||||||
|
decimal costAt200Price = totalRevenue > 0
|
||||||
|
? (totalCost / totalRevenue) * 200
|
||||||
|
: 0;
|
||||||
|
|
||||||
|
// 7. 格式化输出
|
||||||
|
var today = DateTime.Now;
|
||||||
|
string dayOfWeek = today.ToString("dddd", new System.Globalization.CultureInfo("zh-CN"));
|
||||||
|
string weekDay = dayOfWeek switch
|
||||||
|
{
|
||||||
|
"星期一" => "周1",
|
||||||
|
"星期二" => "周2",
|
||||||
|
"星期三" => "周3",
|
||||||
|
"星期四" => "周4",
|
||||||
|
"星期五" => "周5",
|
||||||
|
"星期六" => "周6",
|
||||||
|
"星期日" => "周日",
|
||||||
|
_ => dayOfWeek
|
||||||
|
};
|
||||||
|
|
||||||
|
var result = $@"{today:M月d日} {weekDay}
|
||||||
|
尊享包已消耗({totalUsedTokens / 100000000m:F2}亿){totalUsedTokens}
|
||||||
|
尊享包剩余库存({totalRemainingTokens / 100000000m:F2}亿){totalRemainingTokens}
|
||||||
|
当前成本:{currentCost:F2}RMB
|
||||||
|
1亿Token成本:{costPerHundredMillion:F2} RMB=1亿 Token
|
||||||
|
总成本:{totalCost:F2} RMB
|
||||||
|
总收益:{totalRevenue:F2}RMB
|
||||||
|
利润率: {profitRate:F1}%
|
||||||
|
按200售价来算,成本在{costAt200Price:F2}";
|
||||||
|
|
||||||
|
return result;
|
||||||
|
}
|
||||||
|
|
||||||
|
public class TokenStatisticsInput
|
||||||
|
{
|
||||||
|
/// <summary>
|
||||||
|
/// 指定日期(当天零点)
|
||||||
|
/// </summary>
|
||||||
|
public DateTime Date { get; set; }
|
||||||
|
|
||||||
|
/// <summary>
|
||||||
|
/// 模型Id -> 1亿Token成本(RMB)
|
||||||
|
/// </summary>
|
||||||
|
public Dictionary<string, decimal> ModelCosts { get; set; } = new();
|
||||||
|
}
|
||||||
|
|
||||||
|
/// <summary>
|
||||||
|
/// 获取指定日期各模型Token统计
|
||||||
|
/// </summary>
|
||||||
|
[Authorize]
|
||||||
|
[HttpPost("account/token-statistics")]
|
||||||
|
public async Task<string> GetTokenStatisticsAsync([FromBody] TokenStatisticsInput input)
|
||||||
|
{
|
||||||
|
if (CurrentUser.UserName != "Guo" && CurrentUser.UserName != "cc")
|
||||||
|
{
|
||||||
|
throw new UserFriendlyException("您暂无权限访问");
|
||||||
|
}
|
||||||
|
|
||||||
|
if (input.ModelCosts is null || input.ModelCosts.Count == 0)
|
||||||
|
{
|
||||||
|
throw new UserFriendlyException("请提供模型成本配置");
|
||||||
|
}
|
||||||
|
|
||||||
|
var day = input.Date.Date;
|
||||||
|
var nextDay = day.AddDays(1);
|
||||||
|
var modelIds = input.ModelCosts.Keys.ToList();
|
||||||
|
|
||||||
|
var modelStats = await _messageRepository._DbQueryable
|
||||||
|
.Where(x => modelIds.Contains(x.ModelId))
|
||||||
|
.Where(x => x.CreationTime >= day && x.CreationTime < nextDay)
|
||||||
|
.Where(x => x.Role == "system")
|
||||||
|
.GroupBy(x => x.ModelId)
|
||||||
|
.Select(x => new
|
||||||
|
{
|
||||||
|
ModelId = x.ModelId,
|
||||||
|
Tokens = SqlFunc.AggregateSum(x.TokenUsage.TotalTokenCount),
|
||||||
|
Count = SqlFunc.AggregateCount(x.Id)
|
||||||
|
})
|
||||||
|
.ToListAsync();
|
||||||
|
|
||||||
|
var modelStatDict = modelStats.ToDictionary(x => x.ModelId, x => x);
|
||||||
|
|
||||||
|
string weekDay = day.ToString("dddd", new CultureInfo("zh-CN")) switch
|
||||||
|
{
|
||||||
|
"星期一" => "周1",
|
||||||
|
"星期二" => "周2",
|
||||||
|
"星期三" => "周3",
|
||||||
|
"星期四" => "周4",
|
||||||
|
"星期五" => "周5",
|
||||||
|
"星期六" => "周6",
|
||||||
|
"星期日" => "周日",
|
||||||
|
_ => day.ToString("dddd", new CultureInfo("zh-CN"))
|
||||||
|
};
|
||||||
|
|
||||||
|
var sb = new StringBuilder();
|
||||||
|
sb.AppendLine($"{day:M月d日} {weekDay}");
|
||||||
|
|
||||||
|
foreach (var kvp in input.ModelCosts)
|
||||||
|
{
|
||||||
|
var modelId = kvp.Key;
|
||||||
|
var cost = kvp.Value;
|
||||||
|
|
||||||
|
modelStatDict.TryGetValue(modelId, out var stat);
|
||||||
|
long tokens = stat?.Tokens ?? 0;
|
||||||
|
long count = stat?.Count ?? 0;
|
||||||
|
|
||||||
|
decimal costPerHundredMillion = tokens > 0
|
||||||
|
? cost / (tokens / 100000000m)
|
||||||
|
: 0;
|
||||||
|
|
||||||
|
decimal tokensInWan = tokens / 10000m;
|
||||||
|
|
||||||
|
sb.AppendLine();
|
||||||
|
sb.AppendLine($"{modelId} 成本:【{cost:F2}RMB】 次数:【{count}次】 token:【{tokensInWan:F0}w】 1亿token成本:【{costPerHundredMillion:F2}RMB】");
|
||||||
|
}
|
||||||
|
|
||||||
|
return sb.ToString().TrimEnd();
|
||||||
|
}
|
||||||
}
|
}
|
||||||
@@ -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,240 @@
|
|||||||
|
using Mapster;
|
||||||
|
using Microsoft.AspNetCore.Authorization;
|
||||||
|
using Microsoft.AspNetCore.Mvc;
|
||||||
|
using SqlSugar;
|
||||||
|
using Volo.Abp.Application.Dtos;
|
||||||
|
using Volo.Abp.Application.Services;
|
||||||
|
using Yi.Framework.AiHub.Application.Contracts.Dtos.Channel;
|
||||||
|
using Yi.Framework.AiHub.Application.Contracts.IServices;
|
||||||
|
using Yi.Framework.AiHub.Domain.Entities.Model;
|
||||||
|
using Yi.Framework.SqlSugarCore.Abstractions;
|
||||||
|
|
||||||
|
namespace Yi.Framework.AiHub.Application.Services;
|
||||||
|
|
||||||
|
/// <summary>
|
||||||
|
/// 渠道商管理服务实现
|
||||||
|
/// </summary>
|
||||||
|
[Authorize(Roles = "admin")]
|
||||||
|
public class ChannelService : ApplicationService, IChannelService
|
||||||
|
{
|
||||||
|
private readonly ISqlSugarRepository<AiAppAggregateRoot, Guid> _appRepository;
|
||||||
|
private readonly ISqlSugarRepository<AiModelEntity, Guid> _modelRepository;
|
||||||
|
|
||||||
|
public ChannelService(
|
||||||
|
ISqlSugarRepository<AiAppAggregateRoot, Guid> appRepository,
|
||||||
|
ISqlSugarRepository<AiModelEntity, Guid> modelRepository)
|
||||||
|
{
|
||||||
|
_appRepository = appRepository;
|
||||||
|
_modelRepository = modelRepository;
|
||||||
|
}
|
||||||
|
|
||||||
|
#region AI应用管理
|
||||||
|
|
||||||
|
/// <summary>
|
||||||
|
/// 获取AI应用列表
|
||||||
|
/// </summary>
|
||||||
|
[HttpGet("channel/app")]
|
||||||
|
public async Task<PagedResultDto<AiAppDto>> GetAppListAsync(AiAppGetListInput input)
|
||||||
|
{
|
||||||
|
RefAsync<int> total = 0;
|
||||||
|
|
||||||
|
var entities = await _appRepository._DbQueryable
|
||||||
|
.WhereIF(!string.IsNullOrWhiteSpace(input.SearchKey), x => x.Name.Contains(input.SearchKey))
|
||||||
|
.OrderByDescending(x => x.OrderNum)
|
||||||
|
.OrderByDescending(x => x.CreationTime)
|
||||||
|
.ToPageListAsync(input.SkipCount, input.MaxResultCount, total);
|
||||||
|
|
||||||
|
var output = entities.Adapt<List<AiAppDto>>();
|
||||||
|
return new PagedResultDto<AiAppDto>(total, output);
|
||||||
|
}
|
||||||
|
|
||||||
|
/// <summary>
|
||||||
|
/// 根据ID获取AI应用
|
||||||
|
/// </summary>
|
||||||
|
[HttpGet("channel/app/{id}")]
|
||||||
|
public async Task<AiAppDto> GetAppByIdAsync([FromRoute]Guid id)
|
||||||
|
{
|
||||||
|
var entity = await _appRepository.GetByIdAsync(id);
|
||||||
|
return entity.Adapt<AiAppDto>();
|
||||||
|
}
|
||||||
|
|
||||||
|
/// <summary>
|
||||||
|
/// 创建AI应用
|
||||||
|
/// </summary>
|
||||||
|
public async Task<AiAppDto> CreateAppAsync(AiAppCreateInput input)
|
||||||
|
{
|
||||||
|
var entity = new AiAppAggregateRoot
|
||||||
|
{
|
||||||
|
Name = input.Name,
|
||||||
|
Endpoint = input.Endpoint,
|
||||||
|
ExtraUrl = input.ExtraUrl,
|
||||||
|
ApiKey = input.ApiKey,
|
||||||
|
OrderNum = input.OrderNum
|
||||||
|
};
|
||||||
|
|
||||||
|
await _appRepository.InsertAsync(entity);
|
||||||
|
return entity.Adapt<AiAppDto>();
|
||||||
|
}
|
||||||
|
|
||||||
|
/// <summary>
|
||||||
|
/// 更新AI应用
|
||||||
|
/// </summary>
|
||||||
|
public async Task<AiAppDto> UpdateAppAsync(AiAppUpdateInput input)
|
||||||
|
{
|
||||||
|
var entity = await _appRepository.GetByIdAsync(input.Id);
|
||||||
|
|
||||||
|
entity.Name = input.Name;
|
||||||
|
entity.Endpoint = input.Endpoint;
|
||||||
|
entity.ExtraUrl = input.ExtraUrl;
|
||||||
|
entity.ApiKey = input.ApiKey;
|
||||||
|
entity.OrderNum = input.OrderNum;
|
||||||
|
|
||||||
|
await _appRepository.UpdateAsync(entity);
|
||||||
|
return entity.Adapt<AiAppDto>();
|
||||||
|
}
|
||||||
|
|
||||||
|
/// <summary>
|
||||||
|
/// 删除AI应用
|
||||||
|
/// </summary>
|
||||||
|
[HttpDelete("channel/app/{id}")]
|
||||||
|
public async Task DeleteAppAsync([FromRoute]Guid id)
|
||||||
|
{
|
||||||
|
// 检查是否有关联的模型
|
||||||
|
var hasModels = await _modelRepository._DbQueryable
|
||||||
|
.Where(x => x.AiAppId == id && !x.IsDeleted)
|
||||||
|
.AnyAsync();
|
||||||
|
|
||||||
|
if (hasModels)
|
||||||
|
{
|
||||||
|
throw new Volo.Abp.UserFriendlyException("该应用下存在模型,无法删除");
|
||||||
|
}
|
||||||
|
|
||||||
|
await _appRepository.DeleteAsync(id);
|
||||||
|
}
|
||||||
|
|
||||||
|
#endregion
|
||||||
|
|
||||||
|
#region AI模型管理
|
||||||
|
|
||||||
|
/// <summary>
|
||||||
|
/// 获取AI模型列表
|
||||||
|
/// </summary>
|
||||||
|
[HttpGet("channel/model")]
|
||||||
|
public async Task<PagedResultDto<AiModelDto>> GetModelListAsync(AiModelGetListInput input)
|
||||||
|
{
|
||||||
|
RefAsync<int> total = 0;
|
||||||
|
|
||||||
|
var query = _modelRepository._DbQueryable
|
||||||
|
.Where(x => !x.IsDeleted)
|
||||||
|
.WhereIF(!string.IsNullOrWhiteSpace(input.SearchKey), x =>
|
||||||
|
x.Name.Contains(input.SearchKey) || x.ModelId.Contains(input.SearchKey))
|
||||||
|
.WhereIF(input.AiAppId.HasValue, x => x.AiAppId == input.AiAppId.Value)
|
||||||
|
.WhereIF(input.IsPremiumOnly == true, x => x.IsPremium);
|
||||||
|
|
||||||
|
var entities = await query
|
||||||
|
.OrderBy(x => x.OrderNum)
|
||||||
|
.OrderByDescending(x => x.Id)
|
||||||
|
.ToPageListAsync(input.SkipCount, input.MaxResultCount, total);
|
||||||
|
|
||||||
|
var output = entities.Adapt<List<AiModelDto>>();
|
||||||
|
return new PagedResultDto<AiModelDto>(total, output);
|
||||||
|
}
|
||||||
|
|
||||||
|
/// <summary>
|
||||||
|
/// 根据ID获取AI模型
|
||||||
|
/// </summary>
|
||||||
|
[HttpGet("channel/model/{id}")]
|
||||||
|
public async Task<AiModelDto> GetModelByIdAsync([FromRoute]Guid id)
|
||||||
|
{
|
||||||
|
var entity = await _modelRepository.GetByIdAsync(id);
|
||||||
|
return entity.Adapt<AiModelDto>();
|
||||||
|
}
|
||||||
|
|
||||||
|
/// <summary>
|
||||||
|
/// 创建AI模型
|
||||||
|
/// </summary>
|
||||||
|
public async Task<AiModelDto> CreateModelAsync(AiModelCreateInput input)
|
||||||
|
{
|
||||||
|
// 验证应用是否存在
|
||||||
|
var appExists = await _appRepository._DbQueryable
|
||||||
|
.Where(x => x.Id == input.AiAppId)
|
||||||
|
.AnyAsync();
|
||||||
|
|
||||||
|
if (!appExists)
|
||||||
|
{
|
||||||
|
throw new Volo.Abp.UserFriendlyException("指定的AI应用不存在");
|
||||||
|
}
|
||||||
|
|
||||||
|
var entity = new AiModelEntity
|
||||||
|
{
|
||||||
|
HandlerName = input.HandlerName,
|
||||||
|
ModelId = input.ModelId,
|
||||||
|
Name = input.Name,
|
||||||
|
Description = input.Description,
|
||||||
|
OrderNum = input.OrderNum,
|
||||||
|
AiAppId = input.AiAppId,
|
||||||
|
ExtraInfo = input.ExtraInfo,
|
||||||
|
ModelType = input.ModelType,
|
||||||
|
ModelApiType = input.ModelApiType,
|
||||||
|
Multiplier = input.Multiplier,
|
||||||
|
MultiplierShow = input.MultiplierShow,
|
||||||
|
ProviderName = input.ProviderName,
|
||||||
|
IconUrl = input.IconUrl,
|
||||||
|
IsPremium = input.IsPremium,
|
||||||
|
IsDeleted = false
|
||||||
|
};
|
||||||
|
|
||||||
|
await _modelRepository.InsertAsync(entity);
|
||||||
|
return entity.Adapt<AiModelDto>();
|
||||||
|
}
|
||||||
|
|
||||||
|
/// <summary>
|
||||||
|
/// 更新AI模型
|
||||||
|
/// </summary>
|
||||||
|
public async Task<AiModelDto> UpdateModelAsync(AiModelUpdateInput input)
|
||||||
|
{
|
||||||
|
var entity = await _modelRepository.GetByIdAsync(input.Id);
|
||||||
|
|
||||||
|
// 验证应用是否存在
|
||||||
|
if (entity.AiAppId != input.AiAppId)
|
||||||
|
{
|
||||||
|
var appExists = await _appRepository._DbQueryable
|
||||||
|
.Where(x => x.Id == input.AiAppId)
|
||||||
|
.AnyAsync();
|
||||||
|
|
||||||
|
if (!appExists)
|
||||||
|
{
|
||||||
|
throw new Volo.Abp.UserFriendlyException("指定的AI应用不存在");
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
entity.HandlerName = input.HandlerName;
|
||||||
|
entity.ModelId = input.ModelId;
|
||||||
|
entity.Name = input.Name;
|
||||||
|
entity.Description = input.Description;
|
||||||
|
entity.OrderNum = input.OrderNum;
|
||||||
|
entity.AiAppId = input.AiAppId;
|
||||||
|
entity.ExtraInfo = input.ExtraInfo;
|
||||||
|
entity.ModelType = input.ModelType;
|
||||||
|
entity.ModelApiType = input.ModelApiType;
|
||||||
|
entity.Multiplier = input.Multiplier;
|
||||||
|
entity.MultiplierShow = input.MultiplierShow;
|
||||||
|
entity.ProviderName = input.ProviderName;
|
||||||
|
entity.IconUrl = input.IconUrl;
|
||||||
|
entity.IsPremium = input.IsPremium;
|
||||||
|
|
||||||
|
await _modelRepository.UpdateAsync(entity);
|
||||||
|
return entity.Adapt<AiModelDto>();
|
||||||
|
}
|
||||||
|
|
||||||
|
/// <summary>
|
||||||
|
/// 删除AI模型(软删除)
|
||||||
|
/// </summary>
|
||||||
|
[HttpDelete("channel/model/{id}")]
|
||||||
|
public async Task DeleteModelAsync(Guid id)
|
||||||
|
{
|
||||||
|
await _modelRepository.DeleteByIdAsync(id);
|
||||||
|
}
|
||||||
|
|
||||||
|
#endregion
|
||||||
|
}
|
||||||
@@ -1,18 +1,26 @@
|
|||||||
using System.Collections.Concurrent;
|
using System.Collections.Concurrent;
|
||||||
|
using System.Reflection;
|
||||||
using System.Text;
|
using System.Text;
|
||||||
|
using System.Text.Encodings.Web;
|
||||||
|
using Dm.util;
|
||||||
using Microsoft.AspNetCore.Authorization;
|
using Microsoft.AspNetCore.Authorization;
|
||||||
using Microsoft.AspNetCore.Http;
|
using Microsoft.AspNetCore.Http;
|
||||||
using Microsoft.AspNetCore.Mvc;
|
using Microsoft.AspNetCore.Mvc;
|
||||||
using Microsoft.Extensions.DependencyInjection;
|
using Microsoft.Extensions.DependencyInjection;
|
||||||
using Microsoft.Extensions.Logging;
|
using Microsoft.Extensions.Logging;
|
||||||
using Microsoft.Extensions.Options;
|
using Microsoft.Extensions.Options;
|
||||||
|
using ModelContextProtocol;
|
||||||
|
using ModelContextProtocol.Server;
|
||||||
using Newtonsoft.Json;
|
using Newtonsoft.Json;
|
||||||
using Newtonsoft.Json.Serialization;
|
using Newtonsoft.Json.Serialization;
|
||||||
using OpenAI.Chat;
|
using OpenAI.Chat;
|
||||||
using Volo.Abp.Application.Services;
|
using Volo.Abp.Application.Services;
|
||||||
using Volo.Abp.Users;
|
using Volo.Abp.Users;
|
||||||
using Yi.Framework.AiHub.Application.Contracts.Dtos;
|
using Yi.Framework.AiHub.Application.Contracts.Dtos;
|
||||||
|
using Yi.Framework.AiHub.Application.Contracts.Dtos.Chat;
|
||||||
|
using Yi.Framework.AiHub.Domain;
|
||||||
using Yi.Framework.AiHub.Domain.Entities;
|
using Yi.Framework.AiHub.Domain.Entities;
|
||||||
|
using Yi.Framework.AiHub.Domain.Entities.Chat;
|
||||||
using Yi.Framework.AiHub.Domain.Entities.Model;
|
using Yi.Framework.AiHub.Domain.Entities.Model;
|
||||||
using Yi.Framework.AiHub.Domain.Extensions;
|
using Yi.Framework.AiHub.Domain.Extensions;
|
||||||
using Yi.Framework.AiHub.Domain.Managers;
|
using Yi.Framework.AiHub.Domain.Managers;
|
||||||
@@ -32,23 +40,37 @@ namespace Yi.Framework.AiHub.Application.Services;
|
|||||||
public class AiChatService : ApplicationService
|
public class AiChatService : ApplicationService
|
||||||
{
|
{
|
||||||
private readonly IHttpContextAccessor _httpContextAccessor;
|
private readonly IHttpContextAccessor _httpContextAccessor;
|
||||||
private readonly ISqlSugarRepository<AiModelEntity> _aiModelRepository;
|
|
||||||
private readonly AiBlacklistManager _aiBlacklistManager;
|
private readonly AiBlacklistManager _aiBlacklistManager;
|
||||||
private readonly ILogger<AiChatService> _logger;
|
private readonly ILogger<AiChatService> _logger;
|
||||||
private readonly AiGateWayManager _aiGateWayManager;
|
private readonly AiGateWayManager _aiGateWayManager;
|
||||||
|
private readonly ModelManager _modelManager;
|
||||||
private readonly PremiumPackageManager _premiumPackageManager;
|
private readonly PremiumPackageManager _premiumPackageManager;
|
||||||
|
private readonly ChatManager _chatManager;
|
||||||
|
private readonly TokenManager _tokenManager;
|
||||||
|
private readonly IAccountService _accountService;
|
||||||
|
private readonly ISqlSugarRepository<AgentStoreAggregateRoot> _agentStoreRepository;
|
||||||
|
private readonly ISqlSugarRepository<AiModelEntity> _aiModelRepository;
|
||||||
|
|
||||||
public AiChatService(IHttpContextAccessor httpContextAccessor,
|
public AiChatService(IHttpContextAccessor httpContextAccessor,
|
||||||
AiBlacklistManager aiBlacklistManager,
|
AiBlacklistManager aiBlacklistManager,
|
||||||
ISqlSugarRepository<AiModelEntity> aiModelRepository,
|
ILogger<AiChatService> logger,
|
||||||
ILogger<AiChatService> logger, AiGateWayManager aiGateWayManager, PremiumPackageManager premiumPackageManager)
|
AiGateWayManager aiGateWayManager,
|
||||||
|
ModelManager modelManager,
|
||||||
|
PremiumPackageManager premiumPackageManager,
|
||||||
|
ChatManager chatManager, TokenManager tokenManager, IAccountService accountService,
|
||||||
|
ISqlSugarRepository<AgentStoreAggregateRoot> agentStoreRepository, ISqlSugarRepository<AiModelEntity> aiModelRepository)
|
||||||
{
|
{
|
||||||
_httpContextAccessor = httpContextAccessor;
|
_httpContextAccessor = httpContextAccessor;
|
||||||
_aiBlacklistManager = aiBlacklistManager;
|
_aiBlacklistManager = aiBlacklistManager;
|
||||||
_aiModelRepository = aiModelRepository;
|
|
||||||
_logger = logger;
|
_logger = logger;
|
||||||
_aiGateWayManager = aiGateWayManager;
|
_aiGateWayManager = aiGateWayManager;
|
||||||
|
_modelManager = modelManager;
|
||||||
_premiumPackageManager = premiumPackageManager;
|
_premiumPackageManager = premiumPackageManager;
|
||||||
|
_chatManager = chatManager;
|
||||||
|
_tokenManager = tokenManager;
|
||||||
|
_accountService = accountService;
|
||||||
|
_agentStoreRepository = agentStoreRepository;
|
||||||
|
_aiModelRepository = aiModelRepository;
|
||||||
}
|
}
|
||||||
|
|
||||||
|
|
||||||
@@ -66,28 +88,23 @@ public class AiChatService : ApplicationService
|
|||||||
}
|
}
|
||||||
|
|
||||||
/// <summary>
|
/// <summary>
|
||||||
/// 获取模型列表
|
/// 获取对话模型列表
|
||||||
/// </summary>
|
/// </summary>
|
||||||
/// <returns></returns>
|
/// <returns></returns>
|
||||||
public async Task<List<ModelGetListOutput>> GetModelAsync()
|
public async Task<List<ModelGetListOutput>> GetModelAsync()
|
||||||
{
|
{
|
||||||
var output = await _aiModelRepository._DbQueryable
|
var output = await _aiModelRepository._DbQueryable
|
||||||
.Where(x => x.ModelType == ModelTypeEnum.Chat)
|
.Where(x => x.ModelType == ModelTypeEnum.Chat)
|
||||||
|
.Where(x => x.ModelApiType == ModelApiTypeEnum.OpenAi)
|
||||||
.OrderByDescending(x => x.OrderNum)
|
.OrderByDescending(x => x.OrderNum)
|
||||||
.Select(x => new ModelGetListOutput
|
.Select(x => new ModelGetListOutput
|
||||||
{
|
{
|
||||||
Id = x.Id,
|
Id = x.Id,
|
||||||
Category = "chat",
|
|
||||||
ModelId = x.ModelId,
|
ModelId = x.ModelId,
|
||||||
ModelName = x.Name,
|
ModelName = x.Name,
|
||||||
ModelDescribe = x.Description,
|
ModelDescribe = x.Description,
|
||||||
ModelPrice = 0,
|
Remark = x.Description,
|
||||||
ModelType = "1",
|
IsPremiumPackage = x.IsPremium
|
||||||
ModelShow = "0",
|
|
||||||
SystemPrompt = null,
|
|
||||||
ApiHost = null,
|
|
||||||
ApiKey = null,
|
|
||||||
Remark = x.Description
|
|
||||||
}).ToListAsync();
|
}).ToListAsync();
|
||||||
return output;
|
return output;
|
||||||
}
|
}
|
||||||
@@ -122,22 +139,26 @@ public class AiChatService : ApplicationService
|
|||||||
}
|
}
|
||||||
|
|
||||||
//如果是尊享包服务,需要校验是是否尊享包足够
|
//如果是尊享包服务,需要校验是是否尊享包足够
|
||||||
if (CurrentUser.IsAuthenticated && PremiumPackageConst.ModeIds.Contains(input.Model))
|
if (CurrentUser.IsAuthenticated)
|
||||||
{
|
{
|
||||||
// 检查尊享token包用量
|
var isPremium = await _modelManager.IsPremiumModelAsync(input.Model);
|
||||||
var availableTokens = await _premiumPackageManager.GetAvailableTokensAsync(CurrentUser.GetId());
|
|
||||||
if (availableTokens <= 0)
|
if (isPremium)
|
||||||
{
|
{
|
||||||
throw new UserFriendlyException("尊享token包用量不足,请先购买尊享token包");
|
// 检查尊享token包用量
|
||||||
|
var availableTokens = await _premiumPackageManager.GetAvailableTokensAsync(CurrentUser.GetId());
|
||||||
|
if (availableTokens <= 0)
|
||||||
|
{
|
||||||
|
throw new UserFriendlyException("尊享token包用量不足,请先购买尊享token包");
|
||||||
|
}
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
//ai网关代理httpcontext
|
//ai网关代理httpcontext
|
||||||
await _aiGateWayManager.CompleteChatStreamForStatisticsAsync(_httpContextAccessor.HttpContext, input,
|
await _aiGateWayManager.CompleteChatStreamForStatisticsAsync(_httpContextAccessor.HttpContext, input,
|
||||||
CurrentUser.Id, sessionId, cancellationToken);
|
CurrentUser.Id, sessionId, null, CancellationToken.None);
|
||||||
}
|
}
|
||||||
|
|
||||||
|
|
||||||
/// <summary>
|
/// <summary>
|
||||||
/// 发送消息
|
/// 发送消息
|
||||||
/// </summary>
|
/// </summary>
|
||||||
@@ -171,6 +192,80 @@ public class AiChatService : ApplicationService
|
|||||||
|
|
||||||
//ai网关代理httpcontext
|
//ai网关代理httpcontext
|
||||||
await _aiGateWayManager.CompleteChatStreamForStatisticsAsync(_httpContextAccessor.HttpContext, input,
|
await _aiGateWayManager.CompleteChatStreamForStatisticsAsync(_httpContextAccessor.HttpContext, input,
|
||||||
CurrentUser.Id, null, cancellationToken);
|
CurrentUser.Id, null, null, CancellationToken.None);
|
||||||
|
}
|
||||||
|
|
||||||
|
|
||||||
|
/// <summary>
|
||||||
|
/// Agent 发送消息
|
||||||
|
/// </summary>
|
||||||
|
[HttpPost("ai-chat/agent/send")]
|
||||||
|
public async Task PostAgentSendAsync([FromBody] AgentSendInput input, CancellationToken cancellationToken)
|
||||||
|
{
|
||||||
|
var tokenValidation = await _tokenManager.ValidateTokenAsync(input.TokenId, input.ModelId);
|
||||||
|
|
||||||
|
await _aiBlacklistManager.VerifiyAiBlacklist(tokenValidation.UserId);
|
||||||
|
// 验证用户是否为VIP
|
||||||
|
var userInfo = await _accountService.GetAsync(null, null, tokenValidation.UserId);
|
||||||
|
if (userInfo == null)
|
||||||
|
{
|
||||||
|
throw new UserFriendlyException("用户信息不存在");
|
||||||
|
}
|
||||||
|
|
||||||
|
// 检查是否为VIP(使用RoleCodes判断)
|
||||||
|
if (!userInfo.RoleCodes.Contains(AiHubConst.VipRole) && userInfo.User.UserName != "cc")
|
||||||
|
{
|
||||||
|
throw new UserFriendlyException("该接口为尊享服务专用,需要VIP权限才能使用");
|
||||||
|
}
|
||||||
|
|
||||||
|
//如果是尊享包服务,需要校验是是否尊享包足够
|
||||||
|
var isPremium = await _modelManager.IsPremiumModelAsync(input.ModelId);
|
||||||
|
|
||||||
|
if (isPremium)
|
||||||
|
{
|
||||||
|
// 检查尊享token包用量
|
||||||
|
var availableTokens = await _premiumPackageManager.GetAvailableTokensAsync(tokenValidation.UserId);
|
||||||
|
if (availableTokens <= 0)
|
||||||
|
{
|
||||||
|
throw new UserFriendlyException("尊享token包用量不足,请先购买尊享token包");
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
await _chatManager.AgentCompleteChatStreamAsync(_httpContextAccessor.HttpContext,
|
||||||
|
input.SessionId,
|
||||||
|
input.Content,
|
||||||
|
tokenValidation.Token,
|
||||||
|
tokenValidation.TokenId,
|
||||||
|
input.ModelId,
|
||||||
|
tokenValidation.UserId,
|
||||||
|
input.Tools,
|
||||||
|
CancellationToken.None);
|
||||||
|
}
|
||||||
|
|
||||||
|
/// <summary>
|
||||||
|
/// 获取 Agent 工具
|
||||||
|
/// </summary>
|
||||||
|
/// <returns></returns>
|
||||||
|
[HttpPost("ai-chat/agent/tool")]
|
||||||
|
public List<AgentToolOutput> GetAgentToolAsync()
|
||||||
|
{
|
||||||
|
var agentTools = _chatManager.GetTools().Select(x => new AgentToolOutput
|
||||||
|
{
|
||||||
|
Code = x.Code,
|
||||||
|
Name = x.Name
|
||||||
|
}).ToList();
|
||||||
|
return agentTools;
|
||||||
|
}
|
||||||
|
|
||||||
|
/// <summary>
|
||||||
|
/// 获取 Agent 上下文
|
||||||
|
/// </summary>
|
||||||
|
/// <returns></returns>
|
||||||
|
[HttpPost("ai-chat/agent/context/{sessionId}")]
|
||||||
|
[Authorize]
|
||||||
|
public async Task<string?> GetAgentContextAsync([FromRoute] Guid sessionId)
|
||||||
|
{
|
||||||
|
var data = await _agentStoreRepository.GetFirstAsync(x => x.SessionId == sessionId);
|
||||||
|
return data?.Store;
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
@@ -0,0 +1,395 @@
|
|||||||
|
using System.Text.Json;
|
||||||
|
using Microsoft.AspNetCore.Authorization;
|
||||||
|
using Microsoft.AspNetCore.Hosting;
|
||||||
|
using Microsoft.AspNetCore.Http;
|
||||||
|
using Microsoft.AspNetCore.Mvc;
|
||||||
|
using SqlSugar;
|
||||||
|
using Volo.Abp;
|
||||||
|
using Volo.Abp.Application.Services;
|
||||||
|
using Volo.Abp.BackgroundJobs;
|
||||||
|
using Volo.Abp.Guids;
|
||||||
|
using Volo.Abp.Users;
|
||||||
|
using Yi.Framework.AiHub.Application.Contracts.Dtos;
|
||||||
|
using Yi.Framework.AiHub.Application.Contracts.Dtos.Chat;
|
||||||
|
using Yi.Framework.AiHub.Application.Jobs;
|
||||||
|
using Yi.Framework.AiHub.Domain.Entities.Chat;
|
||||||
|
using Yi.Framework.AiHub.Domain.Entities.Model;
|
||||||
|
using Yi.Framework.AiHub.Domain.Extensions;
|
||||||
|
using Yi.Framework.AiHub.Domain.Managers;
|
||||||
|
using Yi.Framework.AiHub.Domain.Shared.Consts;
|
||||||
|
using Yi.Framework.AiHub.Domain.Shared.Enums;
|
||||||
|
using Yi.Framework.SqlSugarCore.Abstractions;
|
||||||
|
|
||||||
|
namespace Yi.Framework.AiHub.Application.Services.Chat;
|
||||||
|
|
||||||
|
/// <summary>
|
||||||
|
/// AI图片生成服务
|
||||||
|
/// </summary>
|
||||||
|
[Authorize]
|
||||||
|
public class AiImageService : ApplicationService
|
||||||
|
{
|
||||||
|
private readonly ISqlSugarRepository<ImageStoreTaskAggregateRoot> _imageTaskRepository;
|
||||||
|
private readonly IBackgroundJobManager _backgroundJobManager;
|
||||||
|
private readonly AiBlacklistManager _aiBlacklistManager;
|
||||||
|
private readonly PremiumPackageManager _premiumPackageManager;
|
||||||
|
private readonly ModelManager _modelManager;
|
||||||
|
private readonly IGuidGenerator _guidGenerator;
|
||||||
|
private readonly IWebHostEnvironment _webHostEnvironment;
|
||||||
|
private readonly TokenManager _tokenManager;
|
||||||
|
private readonly ISqlSugarRepository<AiModelEntity> _aiModelRepository;
|
||||||
|
|
||||||
|
public AiImageService(
|
||||||
|
ISqlSugarRepository<ImageStoreTaskAggregateRoot> imageTaskRepository,
|
||||||
|
IBackgroundJobManager backgroundJobManager,
|
||||||
|
AiBlacklistManager aiBlacklistManager,
|
||||||
|
PremiumPackageManager premiumPackageManager,
|
||||||
|
ModelManager modelManager,
|
||||||
|
IGuidGenerator guidGenerator,
|
||||||
|
IWebHostEnvironment webHostEnvironment, TokenManager tokenManager,
|
||||||
|
ISqlSugarRepository<AiModelEntity> aiModelRepository)
|
||||||
|
{
|
||||||
|
_imageTaskRepository = imageTaskRepository;
|
||||||
|
_backgroundJobManager = backgroundJobManager;
|
||||||
|
_aiBlacklistManager = aiBlacklistManager;
|
||||||
|
_premiumPackageManager = premiumPackageManager;
|
||||||
|
_modelManager = modelManager;
|
||||||
|
_guidGenerator = guidGenerator;
|
||||||
|
_webHostEnvironment = webHostEnvironment;
|
||||||
|
_tokenManager = tokenManager;
|
||||||
|
_aiModelRepository = aiModelRepository;
|
||||||
|
}
|
||||||
|
|
||||||
|
/// <summary>
|
||||||
|
/// 生成图片(异步任务)
|
||||||
|
/// </summary>
|
||||||
|
/// <param name="input">图片生成输入参数</param>
|
||||||
|
/// <returns>任务ID</returns>
|
||||||
|
[HttpPost("ai-image/generate")]
|
||||||
|
[Authorize]
|
||||||
|
public async Task<Guid> GenerateAsync([FromBody] ImageGenerationInput input)
|
||||||
|
{
|
||||||
|
var userId = CurrentUser.GetId();
|
||||||
|
|
||||||
|
// 黑名单校验
|
||||||
|
await _aiBlacklistManager.VerifiyAiBlacklist(userId);
|
||||||
|
|
||||||
|
//校验token
|
||||||
|
if (input.TokenId is not null)
|
||||||
|
{
|
||||||
|
await _tokenManager.ValidateTokenAsync(input.TokenId, input.ModelId);
|
||||||
|
}
|
||||||
|
|
||||||
|
|
||||||
|
// VIP校验
|
||||||
|
if (!CurrentUser.IsAiVip())
|
||||||
|
{
|
||||||
|
throw new UserFriendlyException("图片生成功能需要VIP用户才能使用,请购买VIP后重新登录重试");
|
||||||
|
}
|
||||||
|
|
||||||
|
// 尊享包校验 - 使用ModelManager统一判断
|
||||||
|
var isPremium = await _modelManager.IsPremiumModelAsync(input.ModelId);
|
||||||
|
if (isPremium)
|
||||||
|
{
|
||||||
|
var availableTokens = await _premiumPackageManager.GetAvailableTokensAsync(userId);
|
||||||
|
if (availableTokens <= 0)
|
||||||
|
{
|
||||||
|
throw new UserFriendlyException("尊享token包用量不足,请先购买尊享token包");
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
// 创建任务实体
|
||||||
|
var task = new ImageStoreTaskAggregateRoot
|
||||||
|
{
|
||||||
|
Prompt = input.Prompt,
|
||||||
|
ReferenceImagesPrefixBase64 = input.ReferenceImagesPrefixBase64 ?? new List<string>(),
|
||||||
|
ReferenceImagesUrl = new List<string>(),
|
||||||
|
TaskStatus = TaskStatusEnum.Processing,
|
||||||
|
UserId = userId,
|
||||||
|
UserName = CurrentUser.UserName,
|
||||||
|
TokenId = input.TokenId,
|
||||||
|
ModelId = input.ModelId
|
||||||
|
};
|
||||||
|
|
||||||
|
await _imageTaskRepository.InsertAsync(task);
|
||||||
|
// 入队后台任务
|
||||||
|
await _backgroundJobManager.EnqueueAsync(new ImageGenerationJobArgs
|
||||||
|
{
|
||||||
|
TaskId = task.Id,
|
||||||
|
});
|
||||||
|
|
||||||
|
return task.Id;
|
||||||
|
}
|
||||||
|
|
||||||
|
/// <summary>
|
||||||
|
/// 查询任务状态
|
||||||
|
/// </summary>
|
||||||
|
/// <param name="taskId">任务ID</param>
|
||||||
|
/// <returns>任务详情</returns>
|
||||||
|
[HttpGet("ai-image/task/{taskId}")]
|
||||||
|
public async Task<ImageTaskOutput> GetTaskAsync([FromRoute] Guid taskId)
|
||||||
|
{
|
||||||
|
var userId = CurrentUser.GetId();
|
||||||
|
|
||||||
|
var task = await _imageTaskRepository.GetFirstAsync(x => x.Id == taskId && x.UserId == userId);
|
||||||
|
if (task == null)
|
||||||
|
{
|
||||||
|
throw new UserFriendlyException("任务不存在或无权访问");
|
||||||
|
}
|
||||||
|
|
||||||
|
return new ImageTaskOutput
|
||||||
|
{
|
||||||
|
Id = task.Id,
|
||||||
|
Prompt = task.Prompt,
|
||||||
|
// ReferenceImagesBase64 = task.ReferenceImagesBase64,
|
||||||
|
// ReferenceImagesUrl = task.ReferenceImagesUrl,
|
||||||
|
// StoreBase64 = task.StoreBase64,
|
||||||
|
StoreUrl = task.StoreUrl,
|
||||||
|
TaskStatus = task.TaskStatus,
|
||||||
|
PublishStatus = task.PublishStatus,
|
||||||
|
Categories = task.Categories,
|
||||||
|
CreationTime = task.CreationTime,
|
||||||
|
ErrorInfo = task.ErrorInfo,
|
||||||
|
};
|
||||||
|
}
|
||||||
|
|
||||||
|
/// <summary>
|
||||||
|
/// 上传Base64图片转换为URL
|
||||||
|
/// </summary>
|
||||||
|
/// <param name="base64Data">Base64图片数据(包含前缀如 data:image/png;base64,)</param>
|
||||||
|
/// <returns>图片访问URL</returns>
|
||||||
|
[HttpPost("ai-image/upload-base64")]
|
||||||
|
[AllowAnonymous]
|
||||||
|
public async Task<string> UploadBase64ToUrlAsync([FromBody] string base64Data)
|
||||||
|
{
|
||||||
|
if (string.IsNullOrWhiteSpace(base64Data))
|
||||||
|
{
|
||||||
|
throw new UserFriendlyException("Base64数据不能为空");
|
||||||
|
}
|
||||||
|
|
||||||
|
// 解析Base64数据
|
||||||
|
string mimeType = "image/png";
|
||||||
|
string base64Content = base64Data;
|
||||||
|
|
||||||
|
if (base64Data.Contains(","))
|
||||||
|
{
|
||||||
|
var parts = base64Data.Split(',');
|
||||||
|
if (parts.Length == 2)
|
||||||
|
{
|
||||||
|
// 提取MIME类型
|
||||||
|
var header = parts[0];
|
||||||
|
if (header.Contains(":") && header.Contains(";"))
|
||||||
|
{
|
||||||
|
mimeType = header.Split(':')[1].Split(';')[0];
|
||||||
|
}
|
||||||
|
|
||||||
|
base64Content = parts[1];
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
// 获取文件扩展名
|
||||||
|
var extension = mimeType switch
|
||||||
|
{
|
||||||
|
"image/png" => ".png",
|
||||||
|
"image/jpeg" => ".jpg",
|
||||||
|
"image/jpg" => ".jpg",
|
||||||
|
"image/gif" => ".gif",
|
||||||
|
"image/webp" => ".webp",
|
||||||
|
_ => ".png"
|
||||||
|
};
|
||||||
|
|
||||||
|
// 解码Base64
|
||||||
|
byte[] imageBytes;
|
||||||
|
try
|
||||||
|
{
|
||||||
|
imageBytes = Convert.FromBase64String(base64Content);
|
||||||
|
}
|
||||||
|
catch (FormatException)
|
||||||
|
{
|
||||||
|
throw new UserFriendlyException("Base64格式无效");
|
||||||
|
}
|
||||||
|
|
||||||
|
// ==============================
|
||||||
|
// ✅ 按日期创建目录(yyyyMMdd)
|
||||||
|
// ==============================
|
||||||
|
var dateFolder = DateTime.Now.ToString("yyyyMMdd");
|
||||||
|
var uploadPath = Path.Combine(
|
||||||
|
_webHostEnvironment.ContentRootPath,
|
||||||
|
"wwwroot",
|
||||||
|
"ai-images",
|
||||||
|
dateFolder
|
||||||
|
);
|
||||||
|
|
||||||
|
if (!Directory.Exists(uploadPath))
|
||||||
|
{
|
||||||
|
Directory.CreateDirectory(uploadPath);
|
||||||
|
}
|
||||||
|
|
||||||
|
// 保存文件
|
||||||
|
var fileId = _guidGenerator.Create();
|
||||||
|
var fileName = $"{fileId}{extension}";
|
||||||
|
var filePath = Path.Combine(uploadPath, fileName);
|
||||||
|
|
||||||
|
await File.WriteAllBytesAsync(filePath, imageBytes);
|
||||||
|
|
||||||
|
// 返回包含日期目录的访问URL
|
||||||
|
return $"/wwwroot/ai-images/{dateFolder}/{fileName}";
|
||||||
|
}
|
||||||
|
|
||||||
|
/// <summary>
|
||||||
|
/// 分页查询我的任务列表
|
||||||
|
/// </summary>
|
||||||
|
[HttpGet("ai-image/my-tasks")]
|
||||||
|
public async Task<PagedResult<ImageTaskOutput>> GetMyTaskPageAsync([FromQuery] ImageMyTaskPageInput input)
|
||||||
|
{
|
||||||
|
var userId = CurrentUser.GetId();
|
||||||
|
|
||||||
|
RefAsync<int> total = 0;
|
||||||
|
var output = await _imageTaskRepository._DbQueryable
|
||||||
|
.Where(x => x.UserId == userId)
|
||||||
|
.WhereIF(input.TaskStatus is not null, x => x.TaskStatus == input.TaskStatus)
|
||||||
|
.WhereIF(!string.IsNullOrWhiteSpace(input.Prompt), x => x.Prompt.Contains(input.Prompt))
|
||||||
|
.WhereIF(input.PublishStatus is not null, x => x.PublishStatus == input.PublishStatus)
|
||||||
|
.WhereIF(input.StartTime is not null && input.EndTime is not null,
|
||||||
|
x => x.CreationTime >= input.StartTime && x.CreationTime <= input.EndTime)
|
||||||
|
.OrderByDescending(x => x.CreationTime)
|
||||||
|
.Select(x => new ImageTaskOutput
|
||||||
|
{
|
||||||
|
Id = x.Id,
|
||||||
|
Prompt = x.Prompt,
|
||||||
|
StoreUrl = x.StoreUrl,
|
||||||
|
TaskStatus = x.TaskStatus,
|
||||||
|
PublishStatus = x.PublishStatus,
|
||||||
|
Categories = x.Categories,
|
||||||
|
CreationTime = x.CreationTime,
|
||||||
|
ErrorInfo = x.ErrorInfo
|
||||||
|
})
|
||||||
|
.ToPageListAsync(input.SkipCount, input.MaxResultCount, total);
|
||||||
|
|
||||||
|
|
||||||
|
return new PagedResult<ImageTaskOutput>(total, output);
|
||||||
|
}
|
||||||
|
|
||||||
|
/// <summary>
|
||||||
|
/// 分页查询图片广场(已发布的图片)
|
||||||
|
/// </summary>
|
||||||
|
[HttpGet("ai-image/plaza")]
|
||||||
|
[AllowAnonymous]
|
||||||
|
public async Task<PagedResult<ImageTaskOutput>> GetPlazaPageAsync([FromQuery] ImagePlazaPageInput input)
|
||||||
|
{
|
||||||
|
RefAsync<int> total = 0;
|
||||||
|
var output = await _imageTaskRepository._DbQueryable
|
||||||
|
.Where(x => x.PublishStatus == PublishStatusEnum.Published)
|
||||||
|
.Where(x => x.TaskStatus == TaskStatusEnum.Success)
|
||||||
|
.WhereIF(input.TaskStatus is not null, x => x.TaskStatus == input.TaskStatus)
|
||||||
|
.WhereIF(!string.IsNullOrWhiteSpace(input.Prompt), x => x.Prompt.Contains(input.Prompt))
|
||||||
|
.WhereIF(!string.IsNullOrWhiteSpace(input.Categories), x => SqlFunc.JsonLike(x.Categories, input.Categories))
|
||||||
|
.WhereIF(!string.IsNullOrWhiteSpace(input.UserName),x=>x.UserName.Contains(input.UserName) )
|
||||||
|
.WhereIF(input.StartTime is not null && input.EndTime is not null,
|
||||||
|
x => x.CreationTime >= input.StartTime && x.CreationTime <= input.EndTime)
|
||||||
|
.OrderByDescending(x => x.CreationTime)
|
||||||
|
.Select(x => new ImageTaskOutput
|
||||||
|
{
|
||||||
|
Id = x.Id,
|
||||||
|
Prompt = x.Prompt,
|
||||||
|
IsAnonymous = x.IsAnonymous,
|
||||||
|
StoreUrl = x.StoreUrl,
|
||||||
|
TaskStatus = x.TaskStatus,
|
||||||
|
PublishStatus = x.PublishStatus,
|
||||||
|
Categories = x.Categories,
|
||||||
|
CreationTime = x.CreationTime,
|
||||||
|
ErrorInfo = null,
|
||||||
|
UserName = x.UserName,
|
||||||
|
UserId = x.UserId,
|
||||||
|
|
||||||
|
})
|
||||||
|
.ToPageListAsync(input.SkipCount, input.MaxResultCount, total); ;
|
||||||
|
|
||||||
|
|
||||||
|
output.ForEach(x =>
|
||||||
|
{
|
||||||
|
if (x.IsAnonymous)
|
||||||
|
{
|
||||||
|
x.UserName = null;
|
||||||
|
x.UserId = null;
|
||||||
|
}
|
||||||
|
});
|
||||||
|
|
||||||
|
return new PagedResult<ImageTaskOutput>(total, output);
|
||||||
|
}
|
||||||
|
|
||||||
|
/// <summary>
|
||||||
|
/// 发布图片到广场
|
||||||
|
/// </summary>
|
||||||
|
[HttpPost("ai-image/publish")]
|
||||||
|
public async Task PublishAsync([FromBody] PublishImageInput input)
|
||||||
|
{
|
||||||
|
var userId = CurrentUser.GetId();
|
||||||
|
|
||||||
|
var task = await _imageTaskRepository.GetFirstAsync(x => x.Id == input.TaskId && x.UserId == userId);
|
||||||
|
if (task == null)
|
||||||
|
{
|
||||||
|
throw new UserFriendlyException("任务不存在或无权访问");
|
||||||
|
}
|
||||||
|
|
||||||
|
if (task.TaskStatus != TaskStatusEnum.Success)
|
||||||
|
{
|
||||||
|
throw new UserFriendlyException("只有已完成的任务才能发布");
|
||||||
|
}
|
||||||
|
|
||||||
|
if (task.PublishStatus == PublishStatusEnum.Published)
|
||||||
|
{
|
||||||
|
throw new UserFriendlyException("该任务已发布");
|
||||||
|
}
|
||||||
|
|
||||||
|
//设置发布
|
||||||
|
task.SetPublish(input.IsAnonymous,input.Categories);
|
||||||
|
await _imageTaskRepository.UpdateAsync(task);
|
||||||
|
}
|
||||||
|
|
||||||
|
/// <summary>
|
||||||
|
/// 获取图片模型列表
|
||||||
|
/// </summary>
|
||||||
|
/// <returns></returns>
|
||||||
|
[HttpPost("ai-image/model")]
|
||||||
|
[AllowAnonymous]
|
||||||
|
public async Task<List<ModelGetListOutput>> GetModelAsync()
|
||||||
|
{
|
||||||
|
var output = await _aiModelRepository._DbQueryable
|
||||||
|
.Where(x => x.ModelType == ModelTypeEnum.Image)
|
||||||
|
.Where(x => x.ModelApiType == ModelApiTypeEnum.GenerateContent)
|
||||||
|
.OrderByDescending(x => x.OrderNum)
|
||||||
|
.Select(x => new ModelGetListOutput
|
||||||
|
{
|
||||||
|
Id = x.Id,
|
||||||
|
ModelId = x.ModelId,
|
||||||
|
ModelName = x.Name,
|
||||||
|
ModelDescribe = x.Description,
|
||||||
|
Remark = x.Description,
|
||||||
|
IsPremiumPackage = x.IsPremium
|
||||||
|
}).ToListAsync();
|
||||||
|
return output;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
/// <summary>
|
||||||
|
/// 分页结果
|
||||||
|
/// </summary>
|
||||||
|
/// <typeparam name="T">数据类型</typeparam>
|
||||||
|
public class PagedResult<T>
|
||||||
|
{
|
||||||
|
/// <summary>
|
||||||
|
/// 总数
|
||||||
|
/// </summary>
|
||||||
|
public long Total { get; set; }
|
||||||
|
|
||||||
|
/// <summary>
|
||||||
|
/// 数据列表
|
||||||
|
/// </summary>
|
||||||
|
public List<T> Items { get; set; }
|
||||||
|
|
||||||
|
public PagedResult(long total, List<T> items)
|
||||||
|
{
|
||||||
|
Total = total;
|
||||||
|
Items = items;
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -0,0 +1,130 @@
|
|||||||
|
using Mapster;
|
||||||
|
using Microsoft.AspNetCore.Mvc;
|
||||||
|
using SqlSugar;
|
||||||
|
using Volo.Abp.Application.Dtos;
|
||||||
|
using Volo.Abp.Application.Services;
|
||||||
|
using Yi.Framework.AiHub.Application.Contracts.Dtos.Model;
|
||||||
|
using Yi.Framework.AiHub.Application.Contracts.IServices;
|
||||||
|
using Yi.Framework.AiHub.Domain.Entities.Model;
|
||||||
|
using Yi.Framework.AiHub.Domain.Managers;
|
||||||
|
using Yi.Framework.AiHub.Domain.Shared.Consts;
|
||||||
|
using Yi.Framework.AiHub.Domain.Shared.Enums;
|
||||||
|
using Yi.Framework.AiHub.Domain.Shared.Extensions;
|
||||||
|
using Yi.Framework.SqlSugarCore.Abstractions;
|
||||||
|
|
||||||
|
namespace Yi.Framework.AiHub.Application.Services.Chat;
|
||||||
|
|
||||||
|
/// <summary>
|
||||||
|
/// 模型服务
|
||||||
|
/// </summary>
|
||||||
|
public class ModelService : ApplicationService, IModelService
|
||||||
|
{
|
||||||
|
private readonly ISqlSugarRepository<AiModelEntity, Guid> _modelRepository;
|
||||||
|
private readonly ModelManager _modelManager;
|
||||||
|
|
||||||
|
public ModelService(ISqlSugarRepository<AiModelEntity, Guid> modelRepository, ModelManager modelManager)
|
||||||
|
{
|
||||||
|
_modelRepository = modelRepository;
|
||||||
|
_modelManager = modelManager;
|
||||||
|
}
|
||||||
|
|
||||||
|
/// <summary>
|
||||||
|
/// 获取模型库列表(公开接口,无需登录)
|
||||||
|
/// </summary>
|
||||||
|
public async Task<PagedResultDto<ModelLibraryDto>> GetListAsync(ModelLibraryGetListInput input)
|
||||||
|
{
|
||||||
|
RefAsync<int> total = 0;
|
||||||
|
|
||||||
|
// 查询所有未删除的模型,使用WhereIF动态添加筛选条件
|
||||||
|
var modelIds = (await _modelRepository._DbQueryable
|
||||||
|
.WhereIF(!string.IsNullOrWhiteSpace(input.SearchKey), x =>
|
||||||
|
x.Name.Contains(input.SearchKey) || x.ModelId.Contains(input.SearchKey))
|
||||||
|
.WhereIF(input.ProviderNames is not null, x =>
|
||||||
|
input.ProviderNames.Contains(x.ProviderName))
|
||||||
|
.WhereIF(input.ModelTypes is not null, x =>
|
||||||
|
input.ModelTypes.Contains(x.ModelType))
|
||||||
|
.WhereIF(input.ModelApiTypes is not null, x =>
|
||||||
|
input.ModelApiTypes.Contains(x.ModelApiType))
|
||||||
|
.WhereIF(input.IsPremiumOnly == true, x => x.IsPremium)
|
||||||
|
.GroupBy(x => x.ModelId)
|
||||||
|
.Select(x => x.ModelId)
|
||||||
|
.ToPageListAsync(input.SkipCount, input.MaxResultCount, total));
|
||||||
|
|
||||||
|
var entities = await _modelRepository._DbQueryable.Where(x => modelIds.Contains(x.ModelId))
|
||||||
|
.OrderBy(x => x.OrderNum)
|
||||||
|
.OrderBy(x => x.Name).ToListAsync();
|
||||||
|
|
||||||
|
var output= entities.GroupBy(x => x.ModelId).Select(x => new ModelLibraryDto
|
||||||
|
{
|
||||||
|
ModelId = x.First().ModelId,
|
||||||
|
Name = x.First().Name,
|
||||||
|
Description = x.First().Description,
|
||||||
|
ModelType = x.First().ModelType,
|
||||||
|
ModelApiTypes = x.Select(y => new ModelApiTypeOutput { ModelApiType = y.ModelApiType }).ToList(),
|
||||||
|
MultiplierShow = x.First().MultiplierShow,
|
||||||
|
ProviderName = x.First().ProviderName,
|
||||||
|
IconUrl = x.First().IconUrl,
|
||||||
|
IsPremium = x.First().IsPremium,
|
||||||
|
OrderNum = x.First().OrderNum
|
||||||
|
}).ToList();
|
||||||
|
|
||||||
|
return new PagedResultDto<ModelLibraryDto>(total, output);
|
||||||
|
}
|
||||||
|
|
||||||
|
/// <summary>
|
||||||
|
/// 获取供应商列表(公开接口,无需登录)
|
||||||
|
/// </summary>
|
||||||
|
public async Task<List<string>> GetProviderListAsync()
|
||||||
|
{
|
||||||
|
var providers = await _modelRepository._DbQueryable
|
||||||
|
.Where(x => !x.IsDeleted)
|
||||||
|
.Where(x => !string.IsNullOrEmpty(x.ProviderName))
|
||||||
|
.GroupBy(x => x.ProviderName)
|
||||||
|
.OrderBy(x => x.OrderNum)
|
||||||
|
.Select(x => x.ProviderName)
|
||||||
|
.ToListAsync();
|
||||||
|
|
||||||
|
return providers!;
|
||||||
|
}
|
||||||
|
|
||||||
|
/// <summary>
|
||||||
|
/// 获取模型类型选项列表(公开接口,无需登录)
|
||||||
|
/// </summary>
|
||||||
|
public Task<List<ModelTypeOption>> GetModelTypeOptionsAsync()
|
||||||
|
{
|
||||||
|
var options = Enum.GetValues<ModelTypeEnum>()
|
||||||
|
.Select(e => new ModelTypeOption
|
||||||
|
{
|
||||||
|
Label = e.GetDescription(),
|
||||||
|
Value = (int)e
|
||||||
|
})
|
||||||
|
.ToList();
|
||||||
|
|
||||||
|
return Task.FromResult(options);
|
||||||
|
}
|
||||||
|
|
||||||
|
/// <summary>
|
||||||
|
/// 获取API类型选项列表(公开接口,无需登录)
|
||||||
|
/// </summary>
|
||||||
|
public Task<List<ModelApiTypeOption>> GetApiTypeOptionsAsync()
|
||||||
|
{
|
||||||
|
var options = Enum.GetValues<ModelApiTypeEnum>()
|
||||||
|
.Select(e => new ModelApiTypeOption
|
||||||
|
{
|
||||||
|
Label = e.GetDescription(),
|
||||||
|
Value = (int)e
|
||||||
|
})
|
||||||
|
.ToList();
|
||||||
|
|
||||||
|
return Task.FromResult(options);
|
||||||
|
}
|
||||||
|
|
||||||
|
/// <summary>
|
||||||
|
/// 清除尊享模型ID缓存
|
||||||
|
/// </summary>
|
||||||
|
[HttpPost("model/clear-premium-cache")]
|
||||||
|
public async Task ClearPremiumModelCacheAsync()
|
||||||
|
{
|
||||||
|
await _modelManager.ClearPremiumModelIdsCacheAsync();
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -0,0 +1,254 @@
|
|||||||
|
using Dm.util;
|
||||||
|
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.Token;
|
||||||
|
using Yi.Framework.AiHub.Domain.Entities;
|
||||||
|
using Yi.Framework.AiHub.Domain.Entities.Model;
|
||||||
|
using Yi.Framework.AiHub.Domain.Entities.OpenApi;
|
||||||
|
using Yi.Framework.AiHub.Domain.Extensions;
|
||||||
|
using Yi.Framework.AiHub.Domain.Managers;
|
||||||
|
using Yi.Framework.AiHub.Domain.Shared.Consts;
|
||||||
|
using Yi.Framework.Ddd.Application.Contracts;
|
||||||
|
using Yi.Framework.SqlSugarCore.Abstractions;
|
||||||
|
|
||||||
|
namespace Yi.Framework.AiHub.Application.Services;
|
||||||
|
|
||||||
|
/// <summary>
|
||||||
|
/// Token服务
|
||||||
|
/// </summary>
|
||||||
|
[Authorize]
|
||||||
|
public class TokenService : ApplicationService
|
||||||
|
{
|
||||||
|
private readonly ISqlSugarRepository<TokenAggregateRoot> _tokenRepository;
|
||||||
|
private readonly ISqlSugarRepository<UsageStatisticsAggregateRoot> _usageStatisticsRepository;
|
||||||
|
private readonly ModelManager _modelManager;
|
||||||
|
|
||||||
|
public TokenService(
|
||||||
|
ISqlSugarRepository<TokenAggregateRoot> tokenRepository,
|
||||||
|
ISqlSugarRepository<UsageStatisticsAggregateRoot> usageStatisticsRepository,
|
||||||
|
ModelManager modelManager)
|
||||||
|
{
|
||||||
|
_tokenRepository = tokenRepository;
|
||||||
|
_usageStatisticsRepository = usageStatisticsRepository;
|
||||||
|
_modelManager = modelManager;
|
||||||
|
}
|
||||||
|
|
||||||
|
/// <summary>
|
||||||
|
/// 获取当前用户的Token列表
|
||||||
|
/// </summary>
|
||||||
|
[HttpGet("token/list")]
|
||||||
|
public async Task<PagedResultDto<TokenGetListOutputDto>> GetListAsync([FromQuery] PagedAllResultRequestDto input)
|
||||||
|
{
|
||||||
|
RefAsync<int> total = 0;
|
||||||
|
var userId = CurrentUser.GetId();
|
||||||
|
|
||||||
|
var tokens = await _tokenRepository._DbQueryable
|
||||||
|
.Where(x => x.UserId == userId)
|
||||||
|
.OrderByDescending(x => x.CreationTime)
|
||||||
|
.ToPageListAsync(input.SkipCount, input.MaxResultCount, total);
|
||||||
|
|
||||||
|
if (!tokens.Any())
|
||||||
|
{
|
||||||
|
return new PagedResultDto<TokenGetListOutputDto>();
|
||||||
|
}
|
||||||
|
|
||||||
|
// 通过ModelManager获取尊享包模型ID列表
|
||||||
|
var premiumModelIds = await _modelManager.GetPremiumModelIdsAsync();
|
||||||
|
|
||||||
|
// 批量查询所有Token的尊享包已使用额度
|
||||||
|
var tokenIds = tokens.Select(t => t.Id).ToList();
|
||||||
|
var usageStats = await _usageStatisticsRepository._DbQueryable
|
||||||
|
.Where(x => x.UserId == userId && tokenIds.Contains(x.TokenId) && premiumModelIds.Contains(x.ModelId))
|
||||||
|
.GroupBy(x => x.TokenId)
|
||||||
|
.Select(g => new
|
||||||
|
{
|
||||||
|
TokenId = g.TokenId,
|
||||||
|
UsedQuota = SqlFunc.AggregateSum(g.TotalTokenCount)
|
||||||
|
})
|
||||||
|
.ToListAsync();
|
||||||
|
|
||||||
|
var result = tokens.Select(t =>
|
||||||
|
{
|
||||||
|
var usedQuota = usageStats.FirstOrDefault(u => u.TokenId == t.Id)?.UsedQuota ?? 0;
|
||||||
|
return new TokenGetListOutputDto
|
||||||
|
{
|
||||||
|
Id = t.Id,
|
||||||
|
Name = t.Name,
|
||||||
|
ApiKey = t.Token,
|
||||||
|
ExpireTime = t.ExpireTime,
|
||||||
|
PremiumQuotaLimit = t.PremiumQuotaLimit,
|
||||||
|
PremiumUsedQuota = usedQuota,
|
||||||
|
IsDisabled = t.IsDisabled,
|
||||||
|
CreationTime = t.CreationTime
|
||||||
|
};
|
||||||
|
}).ToList();
|
||||||
|
|
||||||
|
return new PagedResultDto<TokenGetListOutputDto>(total, result);
|
||||||
|
}
|
||||||
|
|
||||||
|
[HttpGet("token/select-list")]
|
||||||
|
public async Task<List<TokenSelectListOutputDto>> GetSelectListAsync([FromQuery] bool? includeDefault = true)
|
||||||
|
{
|
||||||
|
var userId = CurrentUser.GetId();
|
||||||
|
var tokens = await _tokenRepository._DbQueryable
|
||||||
|
.Where(x => x.UserId == userId)
|
||||||
|
.OrderBy(x => x.IsDisabled)
|
||||||
|
.OrderByDescending(x => x.CreationTime)
|
||||||
|
.Select(x => new TokenSelectListOutputDto
|
||||||
|
{
|
||||||
|
TokenId = x.Id,
|
||||||
|
Name = x.Name,
|
||||||
|
IsDisabled = x.IsDisabled
|
||||||
|
}).ToListAsync();
|
||||||
|
|
||||||
|
if (includeDefault == true)
|
||||||
|
{
|
||||||
|
tokens.Insert(0, new TokenSelectListOutputDto
|
||||||
|
{
|
||||||
|
TokenId = Guid.Empty,
|
||||||
|
Name = "默认",
|
||||||
|
IsDisabled = false
|
||||||
|
});
|
||||||
|
}
|
||||||
|
|
||||||
|
return tokens;
|
||||||
|
}
|
||||||
|
|
||||||
|
|
||||||
|
/// <summary>
|
||||||
|
/// 创建Token
|
||||||
|
/// </summary>
|
||||||
|
[HttpPost("token")]
|
||||||
|
public async Task<TokenGetListOutputDto> CreateAsync([FromBody] TokenCreateInput input)
|
||||||
|
{
|
||||||
|
var userId = CurrentUser.GetId();
|
||||||
|
|
||||||
|
// 检查用户是否为VIP
|
||||||
|
if (!CurrentUser.IsAiVip())
|
||||||
|
{
|
||||||
|
throw new UserFriendlyException("充值成为Vip,畅享第三方token服务");
|
||||||
|
}
|
||||||
|
|
||||||
|
// 检查名称是否重复
|
||||||
|
var exists = await _tokenRepository._DbQueryable
|
||||||
|
.AnyAsync(x => x.UserId == userId && x.Name == input.Name);
|
||||||
|
if (exists)
|
||||||
|
{
|
||||||
|
throw new UserFriendlyException($"名称【{input.Name}】已存在,请使用其他名称");
|
||||||
|
}
|
||||||
|
|
||||||
|
var token = new TokenAggregateRoot(userId, input.Name)
|
||||||
|
{
|
||||||
|
ExpireTime = input.ExpireTime,
|
||||||
|
PremiumQuotaLimit = input.PremiumQuotaLimit
|
||||||
|
};
|
||||||
|
|
||||||
|
await _tokenRepository.InsertAsync(token);
|
||||||
|
|
||||||
|
return new TokenGetListOutputDto
|
||||||
|
{
|
||||||
|
Id = token.Id,
|
||||||
|
Name = token.Name,
|
||||||
|
ApiKey = token.Token,
|
||||||
|
ExpireTime = token.ExpireTime,
|
||||||
|
PremiumQuotaLimit = token.PremiumQuotaLimit,
|
||||||
|
PremiumUsedQuota = 0,
|
||||||
|
IsDisabled = token.IsDisabled,
|
||||||
|
CreationTime = token.CreationTime
|
||||||
|
};
|
||||||
|
}
|
||||||
|
|
||||||
|
/// <summary>
|
||||||
|
/// 编辑Token
|
||||||
|
/// </summary>
|
||||||
|
[HttpPut("token")]
|
||||||
|
public async Task UpdateAsync([FromBody] TokenUpdateInput input)
|
||||||
|
{
|
||||||
|
var userId = CurrentUser.GetId();
|
||||||
|
|
||||||
|
var token = await _tokenRepository._DbQueryable
|
||||||
|
.FirstAsync(x => x.Id == input.Id && x.UserId == userId);
|
||||||
|
|
||||||
|
if (token is null)
|
||||||
|
{
|
||||||
|
throw new UserFriendlyException("Token不存在或无权限操作");
|
||||||
|
}
|
||||||
|
|
||||||
|
// 检查名称是否重复(排除自己)
|
||||||
|
var exists = await _tokenRepository._DbQueryable
|
||||||
|
.AnyAsync(x => x.UserId == userId && x.Name == input.Name && x.Id != input.Id);
|
||||||
|
if (exists)
|
||||||
|
{
|
||||||
|
throw new UserFriendlyException($"名称【{input.Name}】已存在,请使用其他名称");
|
||||||
|
}
|
||||||
|
|
||||||
|
token.Name = input.Name;
|
||||||
|
token.ExpireTime = input.ExpireTime;
|
||||||
|
token.PremiumQuotaLimit = input.PremiumQuotaLimit;
|
||||||
|
|
||||||
|
await _tokenRepository.UpdateAsync(token);
|
||||||
|
}
|
||||||
|
|
||||||
|
/// <summary>
|
||||||
|
/// 删除Token
|
||||||
|
/// </summary>
|
||||||
|
[HttpDelete("token/{id}")]
|
||||||
|
public async Task DeleteAsync(Guid id)
|
||||||
|
{
|
||||||
|
var userId = CurrentUser.GetId();
|
||||||
|
|
||||||
|
var token = await _tokenRepository._DbQueryable
|
||||||
|
.FirstAsync(x => x.Id == id && x.UserId == userId);
|
||||||
|
|
||||||
|
if (token is null)
|
||||||
|
{
|
||||||
|
throw new UserFriendlyException("Token不存在或无权限操作");
|
||||||
|
}
|
||||||
|
|
||||||
|
await _tokenRepository.DeleteAsync(token);
|
||||||
|
}
|
||||||
|
|
||||||
|
/// <summary>
|
||||||
|
/// 启用Token
|
||||||
|
/// </summary>
|
||||||
|
[HttpPost("token/{id}/enable")]
|
||||||
|
public async Task EnableAsync(Guid id)
|
||||||
|
{
|
||||||
|
var userId = CurrentUser.GetId();
|
||||||
|
|
||||||
|
var token = await _tokenRepository._DbQueryable
|
||||||
|
.FirstAsync(x => x.Id == id && x.UserId == userId);
|
||||||
|
|
||||||
|
if (token is null)
|
||||||
|
{
|
||||||
|
throw new UserFriendlyException("Token不存在或无权限操作");
|
||||||
|
}
|
||||||
|
|
||||||
|
token.Enable();
|
||||||
|
await _tokenRepository.UpdateAsync(token);
|
||||||
|
}
|
||||||
|
|
||||||
|
/// <summary>
|
||||||
|
/// 禁用Token
|
||||||
|
/// </summary>
|
||||||
|
[HttpPost("token/{id}/disable")]
|
||||||
|
public async Task DisableAsync(Guid id)
|
||||||
|
{
|
||||||
|
var userId = CurrentUser.GetId();
|
||||||
|
|
||||||
|
var token = await _tokenRepository._DbQueryable
|
||||||
|
.FirstAsync(x => x.Id == id && x.UserId == userId);
|
||||||
|
|
||||||
|
if (token is null)
|
||||||
|
{
|
||||||
|
throw new UserFriendlyException("Token不存在或无权限操作");
|
||||||
|
}
|
||||||
|
|
||||||
|
token.Disable();
|
||||||
|
await _tokenRepository.UpdateAsync(token);
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -76,12 +76,12 @@ public class FileMasterService : ApplicationService
|
|||||||
if (input.Stream == true)
|
if (input.Stream == true)
|
||||||
{
|
{
|
||||||
await _aiGateWayManager.CompleteChatStreamForStatisticsAsync(_httpContextAccessor.HttpContext, input,
|
await _aiGateWayManager.CompleteChatStreamForStatisticsAsync(_httpContextAccessor.HttpContext, input,
|
||||||
userId, null, cancellationToken);
|
userId, null, null, cancellationToken);
|
||||||
}
|
}
|
||||||
else
|
else
|
||||||
{
|
{
|
||||||
await _aiGateWayManager.CompleteChatForStatisticsAsync(_httpContextAccessor.HttpContext, input, userId,
|
await _aiGateWayManager.CompleteChatForStatisticsAsync(_httpContextAccessor.HttpContext, input, userId,
|
||||||
null,
|
null, null,
|
||||||
cancellationToken);
|
cancellationToken);
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -1,9 +1,11 @@
|
|||||||
using Microsoft.AspNetCore.Http;
|
using System.Text.Json;
|
||||||
|
using Microsoft.AspNetCore.Http;
|
||||||
using Microsoft.AspNetCore.Mvc;
|
using Microsoft.AspNetCore.Mvc;
|
||||||
using Microsoft.Extensions.Logging;
|
using Microsoft.Extensions.Logging;
|
||||||
using Volo.Abp.Application.Services;
|
using Volo.Abp.Application.Services;
|
||||||
using Volo.Abp.Users;
|
using Volo.Abp.Users;
|
||||||
using Yi.Framework.AiHub.Domain.Entities;
|
using Yi.Framework.AiHub.Domain.Entities;
|
||||||
|
using Yi.Framework.AiHub.Domain.Entities.Chat;
|
||||||
using Yi.Framework.AiHub.Domain.Entities.Model;
|
using Yi.Framework.AiHub.Domain.Entities.Model;
|
||||||
using Yi.Framework.AiHub.Domain.Extensions;
|
using Yi.Framework.AiHub.Domain.Extensions;
|
||||||
using Yi.Framework.AiHub.Domain.Managers;
|
using Yi.Framework.AiHub.Domain.Managers;
|
||||||
@@ -12,6 +14,7 @@ using Yi.Framework.AiHub.Domain.Shared.Dtos.Anthropic;
|
|||||||
using Yi.Framework.AiHub.Domain.Shared.Dtos.OpenAi;
|
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.Embeddings;
|
||||||
using Yi.Framework.AiHub.Domain.Shared.Dtos.OpenAi.Images;
|
using Yi.Framework.AiHub.Domain.Shared.Dtos.OpenAi.Images;
|
||||||
|
using Yi.Framework.AiHub.Domain.Shared.Dtos.OpenAi.Responses;
|
||||||
using Yi.Framework.AiHub.Domain.Shared.Enums;
|
using Yi.Framework.AiHub.Domain.Shared.Enums;
|
||||||
using Yi.Framework.Rbac.Application.Contracts.IServices;
|
using Yi.Framework.Rbac.Application.Contracts.IServices;
|
||||||
using Yi.Framework.SqlSugarCore.Abstractions;
|
using Yi.Framework.SqlSugarCore.Abstractions;
|
||||||
@@ -24,24 +27,27 @@ public class OpenApiService : ApplicationService
|
|||||||
private readonly ILogger<OpenApiService> _logger;
|
private readonly ILogger<OpenApiService> _logger;
|
||||||
private readonly TokenManager _tokenManager;
|
private readonly TokenManager _tokenManager;
|
||||||
private readonly AiGateWayManager _aiGateWayManager;
|
private readonly AiGateWayManager _aiGateWayManager;
|
||||||
private readonly ISqlSugarRepository<AiModelEntity> _aiModelRepository;
|
private readonly ModelManager _modelManager;
|
||||||
private readonly AiBlacklistManager _aiBlacklistManager;
|
private readonly AiBlacklistManager _aiBlacklistManager;
|
||||||
private readonly IAccountService _accountService;
|
private readonly IAccountService _accountService;
|
||||||
private readonly PremiumPackageManager _premiumPackageManager;
|
private readonly PremiumPackageManager _premiumPackageManager;
|
||||||
|
private readonly ISqlSugarRepository<ImageStoreTaskAggregateRoot> _imageStoreRepository;
|
||||||
|
private readonly ISqlSugarRepository<AiModelEntity> _aiModelRepository;
|
||||||
public OpenApiService(IHttpContextAccessor httpContextAccessor, ILogger<OpenApiService> logger,
|
public OpenApiService(IHttpContextAccessor httpContextAccessor, ILogger<OpenApiService> logger,
|
||||||
TokenManager tokenManager, AiGateWayManager aiGateWayManager,
|
TokenManager tokenManager, AiGateWayManager aiGateWayManager,
|
||||||
ISqlSugarRepository<AiModelEntity> aiModelRepository, AiBlacklistManager aiBlacklistManager,
|
ModelManager modelManager, AiBlacklistManager aiBlacklistManager,
|
||||||
IAccountService accountService, PremiumPackageManager premiumPackageManager)
|
IAccountService accountService, PremiumPackageManager premiumPackageManager, ISqlSugarRepository<ImageStoreTaskAggregateRoot> imageStoreRepository, ISqlSugarRepository<AiModelEntity> aiModelRepository)
|
||||||
{
|
{
|
||||||
_httpContextAccessor = httpContextAccessor;
|
_httpContextAccessor = httpContextAccessor;
|
||||||
_logger = logger;
|
_logger = logger;
|
||||||
_tokenManager = tokenManager;
|
_tokenManager = tokenManager;
|
||||||
_aiGateWayManager = aiGateWayManager;
|
_aiGateWayManager = aiGateWayManager;
|
||||||
_aiModelRepository = aiModelRepository;
|
_modelManager = modelManager;
|
||||||
_aiBlacklistManager = aiBlacklistManager;
|
_aiBlacklistManager = aiBlacklistManager;
|
||||||
_accountService = accountService;
|
_accountService = accountService;
|
||||||
_premiumPackageManager = premiumPackageManager;
|
_premiumPackageManager = premiumPackageManager;
|
||||||
|
_imageStoreRepository = imageStoreRepository;
|
||||||
|
_aiModelRepository = aiModelRepository;
|
||||||
}
|
}
|
||||||
|
|
||||||
/// <summary>
|
/// <summary>
|
||||||
@@ -55,11 +61,15 @@ public class OpenApiService : ApplicationService
|
|||||||
{
|
{
|
||||||
//前面都是校验,后面才是真正的调用
|
//前面都是校验,后面才是真正的调用
|
||||||
var httpContext = this._httpContextAccessor.HttpContext;
|
var httpContext = this._httpContextAccessor.HttpContext;
|
||||||
var userId = await _tokenManager.GetUserIdAsync(GetTokenByHttpContext(httpContext));
|
var tokenValidation = await _tokenManager.ValidateTokenAsync(GetTokenByHttpContext(httpContext), input.Model);
|
||||||
|
var userId = tokenValidation.UserId;
|
||||||
|
var tokenId = tokenValidation.TokenId;
|
||||||
await _aiBlacklistManager.VerifiyAiBlacklist(userId);
|
await _aiBlacklistManager.VerifiyAiBlacklist(userId);
|
||||||
|
|
||||||
//如果是尊享包服务,需要校验是是否尊享包足够
|
//如果是尊享包服务,需要校验是是否尊享包足够
|
||||||
if (PremiumPackageConst.ModeIds.Contains(input.Model))
|
var isPremium = await _modelManager.IsPremiumModelAsync(input.Model);
|
||||||
|
|
||||||
|
if (isPremium)
|
||||||
{
|
{
|
||||||
// 检查尊享token包用量
|
// 检查尊享token包用量
|
||||||
var availableTokens = await _premiumPackageManager.GetAvailableTokensAsync(userId);
|
var availableTokens = await _premiumPackageManager.GetAvailableTokensAsync(userId);
|
||||||
@@ -73,16 +83,17 @@ public class OpenApiService : ApplicationService
|
|||||||
if (input.Stream == true)
|
if (input.Stream == true)
|
||||||
{
|
{
|
||||||
await _aiGateWayManager.CompleteChatStreamForStatisticsAsync(_httpContextAccessor.HttpContext, input,
|
await _aiGateWayManager.CompleteChatStreamForStatisticsAsync(_httpContextAccessor.HttpContext, input,
|
||||||
userId, null, cancellationToken);
|
userId, null, tokenId,CancellationToken.None);
|
||||||
}
|
}
|
||||||
else
|
else
|
||||||
{
|
{
|
||||||
await _aiGateWayManager.CompleteChatForStatisticsAsync(_httpContextAccessor.HttpContext, input, userId,
|
await _aiGateWayManager.CompleteChatForStatisticsAsync(_httpContextAccessor.HttpContext, input, userId,
|
||||||
null,
|
null, tokenId,
|
||||||
cancellationToken);
|
CancellationToken.None);
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
|
|
||||||
/// <summary>
|
/// <summary>
|
||||||
/// 图片生成
|
/// 图片生成
|
||||||
/// </summary>
|
/// </summary>
|
||||||
@@ -93,11 +104,14 @@ public class OpenApiService : ApplicationService
|
|||||||
{
|
{
|
||||||
var httpContext = this._httpContextAccessor.HttpContext;
|
var httpContext = this._httpContextAccessor.HttpContext;
|
||||||
Intercept(httpContext);
|
Intercept(httpContext);
|
||||||
var userId = await _tokenManager.GetUserIdAsync(GetTokenByHttpContext(httpContext));
|
var tokenValidation = await _tokenManager.ValidateTokenAsync(GetTokenByHttpContext(httpContext), input.Model);
|
||||||
|
var userId = tokenValidation.UserId;
|
||||||
|
var tokenId = tokenValidation.TokenId;
|
||||||
await _aiBlacklistManager.VerifiyAiBlacklist(userId);
|
await _aiBlacklistManager.VerifiyAiBlacklist(userId);
|
||||||
await _aiGateWayManager.CreateImageForStatisticsAsync(httpContext, userId, null, input);
|
await _aiGateWayManager.CreateImageForStatisticsAsync(httpContext, userId, null, input, tokenId);
|
||||||
}
|
}
|
||||||
|
|
||||||
|
|
||||||
/// <summary>
|
/// <summary>
|
||||||
/// 向量生成
|
/// 向量生成
|
||||||
/// </summary>
|
/// </summary>
|
||||||
@@ -108,9 +122,11 @@ public class OpenApiService : ApplicationService
|
|||||||
{
|
{
|
||||||
var httpContext = this._httpContextAccessor.HttpContext;
|
var httpContext = this._httpContextAccessor.HttpContext;
|
||||||
Intercept(httpContext);
|
Intercept(httpContext);
|
||||||
var userId = await _tokenManager.GetUserIdAsync(GetTokenByHttpContext(httpContext));
|
var tokenValidation = await _tokenManager.ValidateTokenAsync(GetTokenByHttpContext(httpContext), input.Model);
|
||||||
|
var userId = tokenValidation.UserId;
|
||||||
|
var tokenId = tokenValidation.TokenId;
|
||||||
await _aiBlacklistManager.VerifiyAiBlacklist(userId);
|
await _aiBlacklistManager.VerifiyAiBlacklist(userId);
|
||||||
await _aiGateWayManager.EmbeddingForStatisticsAsync(httpContext, userId, null, input);
|
await _aiGateWayManager.EmbeddingForStatisticsAsync(httpContext, userId, null, input, tokenId);
|
||||||
}
|
}
|
||||||
|
|
||||||
|
|
||||||
@@ -151,7 +167,9 @@ public class OpenApiService : ApplicationService
|
|||||||
{
|
{
|
||||||
//前面都是校验,后面才是真正的调用
|
//前面都是校验,后面才是真正的调用
|
||||||
var httpContext = this._httpContextAccessor.HttpContext;
|
var httpContext = this._httpContextAccessor.HttpContext;
|
||||||
var userId = await _tokenManager.GetUserIdAsync(GetTokenByHttpContext(httpContext));
|
var tokenValidation = await _tokenManager.ValidateTokenAsync(GetTokenByHttpContext(httpContext), input.Model);
|
||||||
|
var userId = tokenValidation.UserId;
|
||||||
|
var tokenId = tokenValidation.TokenId;
|
||||||
await _aiBlacklistManager.VerifiyAiBlacklist(userId);
|
await _aiBlacklistManager.VerifiyAiBlacklist(userId);
|
||||||
|
|
||||||
// 验证用户是否为VIP
|
// 验证用户是否为VIP
|
||||||
@@ -177,18 +195,131 @@ public class OpenApiService : ApplicationService
|
|||||||
//ai网关代理httpcontext
|
//ai网关代理httpcontext
|
||||||
if (input.Stream)
|
if (input.Stream)
|
||||||
{
|
{
|
||||||
await _aiGateWayManager.AnthropicCompleteChatStreamForStatisticsAsync(_httpContextAccessor.HttpContext, input,
|
await _aiGateWayManager.AnthropicCompleteChatStreamForStatisticsAsync(_httpContextAccessor.HttpContext,
|
||||||
userId, null, cancellationToken);
|
input,
|
||||||
|
userId, null, tokenId, CancellationToken.None);
|
||||||
}
|
}
|
||||||
else
|
else
|
||||||
{
|
{
|
||||||
await _aiGateWayManager.AnthropicCompleteChatForStatisticsAsync(_httpContextAccessor.HttpContext, input, userId,
|
await _aiGateWayManager.AnthropicCompleteChatForStatisticsAsync(_httpContextAccessor.HttpContext, input,
|
||||||
null,
|
userId,
|
||||||
cancellationToken);
|
null, tokenId,
|
||||||
|
CancellationToken.None);
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
|
|
||||||
|
/// <summary>
|
||||||
|
/// 响应-Openai新规范 (尊享服务专用)
|
||||||
|
/// </summary>
|
||||||
|
/// <param name="input"></param>
|
||||||
|
/// <param name="cancellationToken"></param>
|
||||||
|
[HttpPost("openApi/v1/responses")]
|
||||||
|
public async Task ResponsesAsync([FromBody] OpenAiResponsesInput input, CancellationToken cancellationToken)
|
||||||
|
{
|
||||||
|
//前面都是校验,后面才是真正的调用
|
||||||
|
var httpContext = this._httpContextAccessor.HttpContext;
|
||||||
|
var tokenValidation = await _tokenManager.ValidateTokenAsync(GetTokenByHttpContext(httpContext), input.Model);
|
||||||
|
var userId = tokenValidation.UserId;
|
||||||
|
var tokenId = tokenValidation.TokenId;
|
||||||
|
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 == true)
|
||||||
|
{
|
||||||
|
await _aiGateWayManager.OpenAiResponsesStreamForStatisticsAsync(_httpContextAccessor.HttpContext,
|
||||||
|
input,
|
||||||
|
userId, null, tokenId, CancellationToken.None);
|
||||||
|
}
|
||||||
|
else
|
||||||
|
{
|
||||||
|
await _aiGateWayManager.OpenAiResponsesAsyncForStatisticsAsync(_httpContextAccessor.HttpContext, input,
|
||||||
|
userId,
|
||||||
|
null, tokenId,
|
||||||
|
CancellationToken.None);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
|
||||||
|
/// <summary>
|
||||||
|
/// 生成-Gemini (尊享服务专用)
|
||||||
|
/// </summary>
|
||||||
|
/// <param name="input"></param>
|
||||||
|
/// <param name="modelId"></param>
|
||||||
|
/// <param name="alt"></param>
|
||||||
|
/// <param name="cancellationToken"></param>
|
||||||
|
[HttpPost("openApi/v1beta/models/{modelId}:{action:regex(^(generateContent|streamGenerateContent)$)}")]
|
||||||
|
public async Task GenerateContentAsync([FromBody] JsonElement input,
|
||||||
|
[FromRoute] string modelId,
|
||||||
|
[FromQuery] string? alt, CancellationToken cancellationToken)
|
||||||
|
{
|
||||||
|
//前面都是校验,后面才是真正的调用
|
||||||
|
var httpContext = this._httpContextAccessor.HttpContext;
|
||||||
|
var tokenValidation = await _tokenManager.ValidateTokenAsync(GetTokenByHttpContext(httpContext), modelId);
|
||||||
|
var userId = tokenValidation.UserId;
|
||||||
|
var tokenId = tokenValidation.TokenId;
|
||||||
|
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 (alt == "sse")
|
||||||
|
{
|
||||||
|
await _aiGateWayManager.GeminiGenerateContentStreamForStatisticsAsync(_httpContextAccessor.HttpContext,
|
||||||
|
modelId, input,
|
||||||
|
userId,
|
||||||
|
null, tokenId,
|
||||||
|
CancellationToken.None);
|
||||||
|
}
|
||||||
|
else
|
||||||
|
{
|
||||||
|
await _aiGateWayManager.GeminiGenerateContentForStatisticsAsync(_httpContextAccessor.HttpContext,
|
||||||
|
modelId, input,
|
||||||
|
userId,
|
||||||
|
null, tokenId,
|
||||||
|
CancellationToken.None);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
#region 私有
|
#region 私有
|
||||||
|
|
||||||
private string? GetTokenByHttpContext(HttpContext httpContext)
|
private string? GetTokenByHttpContext(HttpContext httpContext)
|
||||||
@@ -200,9 +331,17 @@ public class OpenApiService : ApplicationService
|
|||||||
return apiKeyHeader.Trim();
|
return apiKeyHeader.Trim();
|
||||||
}
|
}
|
||||||
|
|
||||||
|
// 再从 谷歌 获取
|
||||||
|
string googApiKeyHeader = httpContext.Request.Headers["x-goog-api-key"];
|
||||||
|
if (!string.IsNullOrWhiteSpace(googApiKeyHeader))
|
||||||
|
{
|
||||||
|
return googApiKeyHeader.Trim();
|
||||||
|
}
|
||||||
|
|
||||||
// 再检查 Authorization 头
|
// 再检查 Authorization 头
|
||||||
string authHeader = httpContext.Request.Headers["Authorization"];
|
string authHeader = httpContext.Request.Headers["Authorization"];
|
||||||
if (!string.IsNullOrWhiteSpace(authHeader) && authHeader.StartsWith("Bearer ", StringComparison.OrdinalIgnoreCase))
|
if (!string.IsNullOrWhiteSpace(authHeader) &&
|
||||||
|
authHeader.StartsWith("Bearer ", StringComparison.OrdinalIgnoreCase))
|
||||||
{
|
{
|
||||||
return authHeader.Substring("Bearer ".Length).Trim();
|
return authHeader.Substring("Bearer ".Length).Trim();
|
||||||
}
|
}
|
||||||
@@ -219,5 +358,4 @@ public class OpenApiService : ApplicationService
|
|||||||
}
|
}
|
||||||
|
|
||||||
#endregion
|
#endregion
|
||||||
|
|
||||||
}
|
}
|
||||||
@@ -122,11 +122,15 @@ public class PayService : ApplicationService, IPayService
|
|||||||
// 5. 根据商品类型进行不同的处理
|
// 5. 根据商品类型进行不同的处理
|
||||||
if (order.GoodsType.IsPremiumPackage())
|
if (order.GoodsType.IsPremiumPackage())
|
||||||
{
|
{
|
||||||
|
var tokenAmount = order.GoodsType.GetTokenAmount();
|
||||||
|
var packageName = order.GoodsType.GetDisplayName();
|
||||||
// 处理尊享包商品:创建尊享包记录
|
// 处理尊享包商品:创建尊享包记录
|
||||||
await _premiumPackageManager.CreatePremiumPackageAsync(
|
await _premiumPackageManager.CreatePremiumPackageAsync(
|
||||||
order.UserId,
|
order.UserId,
|
||||||
order.GoodsType,
|
tokenAmount,
|
||||||
|
packageName,
|
||||||
order.TotalAmount,
|
order.TotalAmount,
|
||||||
|
"自助充值",
|
||||||
expireMonths: null // 尊享包不设置过期时间,或者可以根据需求设置
|
expireMonths: null // 尊享包不设置过期时间,或者可以根据需求设置
|
||||||
);
|
);
|
||||||
|
|
||||||
|
|||||||
@@ -55,13 +55,24 @@ namespace Yi.Framework.AiHub.Application.Services
|
|||||||
/// </summary>
|
/// </summary>
|
||||||
/// <param name="input">充值输入参数</param>
|
/// <param name="input">充值输入参数</param>
|
||||||
/// <returns></returns>
|
/// <returns></returns>
|
||||||
[HttpPost("recharge/vip")]
|
[RemoteService(isEnabled:false)]
|
||||||
public async Task RechargeVipAsync(RechargeCreateInput input)
|
public async Task RechargeVipAsync(RechargeCreateInput input)
|
||||||
{
|
{
|
||||||
DateTime? expireDateTime = null;
|
DateTime? expireDateTime = null;
|
||||||
|
|
||||||
// 如果传入了月数,计算过期时间
|
// 计算总天数(1个月 = 31天)
|
||||||
|
int totalDays = 0;
|
||||||
if (input.Months.HasValue && input.Months.Value > 0)
|
if (input.Months.HasValue && input.Months.Value > 0)
|
||||||
|
{
|
||||||
|
totalDays += input.Months.Value * 31;
|
||||||
|
}
|
||||||
|
if (input.Days.HasValue && input.Days.Value > 0)
|
||||||
|
{
|
||||||
|
totalDays += input.Days.Value;
|
||||||
|
}
|
||||||
|
|
||||||
|
// 如果有天数,计算过期时间
|
||||||
|
if (totalDays > 0)
|
||||||
{
|
{
|
||||||
// 直接查询该用户最大的过期时间
|
// 直接查询该用户最大的过期时间
|
||||||
var maxExpireTime = await _repository._DbQueryable
|
var maxExpireTime = await _repository._DbQueryable
|
||||||
@@ -75,9 +86,9 @@ namespace Yi.Framework.AiHub.Application.Services
|
|||||||
? maxExpireTime.Value
|
? maxExpireTime.Value
|
||||||
: DateTime.Now;
|
: DateTime.Now;
|
||||||
// 计算新的过期时间
|
// 计算新的过期时间
|
||||||
expireDateTime = baseDateTime.AddMonths(input.Months.Value);
|
expireDateTime = baseDateTime.AddDays(totalDays);
|
||||||
}
|
}
|
||||||
// 如果月数为空或0,表示永久VIP,ExpireDateTime保持为null
|
// 如果总天数为0,表示永久VIP,ExpireDateTime保持为null
|
||||||
|
|
||||||
// 创建充值记录
|
// 创建充值记录
|
||||||
var rechargeRecord = new AiRechargeAggregateRoot
|
var rechargeRecord = new AiRechargeAggregateRoot
|
||||||
|
|||||||
@@ -1,55 +0,0 @@
|
|||||||
using Microsoft.AspNetCore.Authorization;
|
|
||||||
using Volo.Abp.Application.Services;
|
|
||||||
using Volo.Abp.Users;
|
|
||||||
using Yi.Framework.AiHub.Application.Contracts.Dtos.Token;
|
|
||||||
using Yi.Framework.AiHub.Domain.Entities.OpenApi;
|
|
||||||
using Yi.Framework.AiHub.Domain.Extensions;
|
|
||||||
using Yi.Framework.AiHub.Domain.Managers;
|
|
||||||
using Yi.Framework.SqlSugarCore.Abstractions;
|
|
||||||
|
|
||||||
namespace Yi.Framework.AiHub.Application.Services;
|
|
||||||
|
|
||||||
public class TokenService : ApplicationService
|
|
||||||
{
|
|
||||||
private readonly ISqlSugarRepository<TokenAggregateRoot> _tokenRepository;
|
|
||||||
private readonly TokenManager _tokenManager;
|
|
||||||
|
|
||||||
/// <summary>
|
|
||||||
/// 构造函数
|
|
||||||
/// </summary>
|
|
||||||
/// <param name="tokenRepository"></param>
|
|
||||||
/// <param name="tokenManager"></param>
|
|
||||||
public TokenService(ISqlSugarRepository<TokenAggregateRoot> tokenRepository, TokenManager tokenManager)
|
|
||||||
{
|
|
||||||
_tokenRepository = tokenRepository;
|
|
||||||
_tokenManager = tokenManager;
|
|
||||||
}
|
|
||||||
|
|
||||||
/// <summary>
|
|
||||||
/// 获取token
|
|
||||||
/// </summary>
|
|
||||||
/// <returns></returns>
|
|
||||||
[Authorize]
|
|
||||||
public async Task<TokenOutput> GetAsync()
|
|
||||||
{
|
|
||||||
return new TokenOutput
|
|
||||||
{
|
|
||||||
ApiKey = await _tokenManager.GetAsync(CurrentUser.GetId())
|
|
||||||
};
|
|
||||||
}
|
|
||||||
|
|
||||||
/// <summary>
|
|
||||||
/// 创建token
|
|
||||||
/// </summary>
|
|
||||||
/// <exception cref="UserFriendlyException"></exception>
|
|
||||||
[Authorize]
|
|
||||||
public async Task CreateAsync()
|
|
||||||
{
|
|
||||||
if (!CurrentUser.IsAiVip())
|
|
||||||
{
|
|
||||||
throw new UserFriendlyException("充值成为Vip,畅享第三方token服务");
|
|
||||||
}
|
|
||||||
|
|
||||||
await _tokenManager.CreateAsync(CurrentUser.GetId());
|
|
||||||
}
|
|
||||||
}
|
|
||||||
@@ -1,12 +1,20 @@
|
|||||||
|
using Mapster;
|
||||||
using Microsoft.AspNetCore.Authorization;
|
using Microsoft.AspNetCore.Authorization;
|
||||||
|
using Microsoft.AspNetCore.Mvc;
|
||||||
using SqlSugar;
|
using SqlSugar;
|
||||||
|
using Volo.Abp.Application.Dtos;
|
||||||
using Volo.Abp.Application.Services;
|
using Volo.Abp.Application.Services;
|
||||||
using Volo.Abp.Users;
|
using Volo.Abp.Users;
|
||||||
using Yi.Framework.AiHub.Application.Contracts.Dtos.UsageStatistics;
|
using Yi.Framework.AiHub.Application.Contracts.Dtos.UsageStatistics;
|
||||||
using Yi.Framework.AiHub.Application.Contracts.IServices;
|
using Yi.Framework.AiHub.Application.Contracts.IServices;
|
||||||
using Yi.Framework.AiHub.Domain.Entities;
|
using Yi.Framework.AiHub.Domain.Entities;
|
||||||
using Yi.Framework.AiHub.Domain.Entities.Chat;
|
using Yi.Framework.AiHub.Domain.Entities.Chat;
|
||||||
|
using Yi.Framework.AiHub.Domain.Entities.Model;
|
||||||
|
using Yi.Framework.AiHub.Domain.Entities.OpenApi;
|
||||||
using Yi.Framework.AiHub.Domain.Extensions;
|
using Yi.Framework.AiHub.Domain.Extensions;
|
||||||
|
using Yi.Framework.AiHub.Domain.Managers;
|
||||||
|
using Yi.Framework.AiHub.Domain.Shared.Consts;
|
||||||
|
using Yi.Framework.Ddd.Application.Contracts;
|
||||||
using Yi.Framework.SqlSugarCore.Abstractions;
|
using Yi.Framework.SqlSugarCore.Abstractions;
|
||||||
|
|
||||||
namespace Yi.Framework.AiHub.Application.Services;
|
namespace Yi.Framework.AiHub.Application.Services;
|
||||||
@@ -20,22 +28,27 @@ public class UsageStatisticsService : ApplicationService, IUsageStatisticsServic
|
|||||||
private readonly ISqlSugarRepository<MessageAggregateRoot> _messageRepository;
|
private readonly ISqlSugarRepository<MessageAggregateRoot> _messageRepository;
|
||||||
private readonly ISqlSugarRepository<UsageStatisticsAggregateRoot> _usageStatisticsRepository;
|
private readonly ISqlSugarRepository<UsageStatisticsAggregateRoot> _usageStatisticsRepository;
|
||||||
private readonly ISqlSugarRepository<PremiumPackageAggregateRoot> _premiumPackageRepository;
|
private readonly ISqlSugarRepository<PremiumPackageAggregateRoot> _premiumPackageRepository;
|
||||||
|
private readonly ISqlSugarRepository<TokenAggregateRoot> _tokenRepository;
|
||||||
|
private readonly ModelManager _modelManager;
|
||||||
public UsageStatisticsService(
|
public UsageStatisticsService(
|
||||||
ISqlSugarRepository<MessageAggregateRoot> messageRepository,
|
ISqlSugarRepository<MessageAggregateRoot> messageRepository,
|
||||||
ISqlSugarRepository<UsageStatisticsAggregateRoot> usageStatisticsRepository,
|
ISqlSugarRepository<UsageStatisticsAggregateRoot> usageStatisticsRepository,
|
||||||
ISqlSugarRepository<PremiumPackageAggregateRoot> premiumPackageRepository)
|
ISqlSugarRepository<PremiumPackageAggregateRoot> premiumPackageRepository,
|
||||||
|
ISqlSugarRepository<TokenAggregateRoot> tokenRepository,
|
||||||
|
ModelManager modelManager)
|
||||||
{
|
{
|
||||||
_messageRepository = messageRepository;
|
_messageRepository = messageRepository;
|
||||||
_usageStatisticsRepository = usageStatisticsRepository;
|
_usageStatisticsRepository = usageStatisticsRepository;
|
||||||
_premiumPackageRepository = premiumPackageRepository;
|
_premiumPackageRepository = premiumPackageRepository;
|
||||||
|
_tokenRepository = tokenRepository;
|
||||||
|
_modelManager = modelManager;
|
||||||
}
|
}
|
||||||
|
|
||||||
/// <summary>
|
/// <summary>
|
||||||
/// 获取当前用户近7天的Token消耗统计
|
/// 获取当前用户近7天的Token消耗统计
|
||||||
/// </summary>
|
/// </summary>
|
||||||
/// <returns>每日Token使用量列表</returns>
|
/// <returns>每日Token使用量列表</returns>
|
||||||
public async Task<List<DailyTokenUsageDto>> GetLast7DaysTokenUsageAsync()
|
public async Task<List<DailyTokenUsageDto>> GetLast7DaysTokenUsageAsync([FromQuery]UsageStatisticsGetInput input)
|
||||||
{
|
{
|
||||||
var userId = CurrentUser.GetId();
|
var userId = CurrentUser.GetId();
|
||||||
var endDate = DateTime.Today;
|
var endDate = DateTime.Today;
|
||||||
@@ -46,6 +59,7 @@ public class UsageStatisticsService : ApplicationService, IUsageStatisticsServic
|
|||||||
.Where(x => x.UserId == userId)
|
.Where(x => x.UserId == userId)
|
||||||
.Where(x => x.Role == "assistant" || x.Role == "system")
|
.Where(x => x.Role == "assistant" || x.Role == "system")
|
||||||
.Where(x => x.CreationTime >= startDate && x.CreationTime < endDate.AddDays(1))
|
.Where(x => x.CreationTime >= startDate && x.CreationTime < endDate.AddDays(1))
|
||||||
|
.WhereIF(input.TokenId.HasValue,x => x.TokenId == input.TokenId)
|
||||||
.GroupBy(x => x.CreationTime.Date)
|
.GroupBy(x => x.CreationTime.Date)
|
||||||
.Select(g => new
|
.Select(g => new
|
||||||
{
|
{
|
||||||
@@ -75,17 +89,19 @@ public class UsageStatisticsService : ApplicationService, IUsageStatisticsServic
|
|||||||
/// 获取当前用户各个模型的Token消耗量及占比
|
/// 获取当前用户各个模型的Token消耗量及占比
|
||||||
/// </summary>
|
/// </summary>
|
||||||
/// <returns>模型Token使用量列表</returns>
|
/// <returns>模型Token使用量列表</returns>
|
||||||
public async Task<List<ModelTokenUsageDto>> GetModelTokenUsageAsync()
|
public async Task<List<ModelTokenUsageDto>> GetModelTokenUsageAsync([FromQuery]UsageStatisticsGetInput input)
|
||||||
{
|
{
|
||||||
var userId = CurrentUser.GetId();
|
var userId = CurrentUser.GetId();
|
||||||
|
|
||||||
// 从UsageStatistics表获取各模型的token消耗统计
|
// 从UsageStatistics表获取各模型的token消耗统计(按ModelId聚合,因为同一模型可能有多个TokenId的记录)
|
||||||
var modelUsages = await _usageStatisticsRepository._DbQueryable
|
var modelUsages = await _usageStatisticsRepository._DbQueryable
|
||||||
.Where(x => x.UserId == userId)
|
.Where(x => x.UserId == userId)
|
||||||
|
.WhereIF(input.TokenId.HasValue,x => x.TokenId == input.TokenId)
|
||||||
|
.GroupBy(x => x.ModelId)
|
||||||
.Select(x => new
|
.Select(x => new
|
||||||
{
|
{
|
||||||
x.ModelId,
|
ModelId = x.ModelId,
|
||||||
x.TotalTokenCount
|
TotalTokenCount = SqlFunc.AggregateSum(x.TotalTokenCount)
|
||||||
})
|
})
|
||||||
.ToListAsync();
|
.ToListAsync();
|
||||||
|
|
||||||
@@ -125,9 +141,9 @@ public class UsageStatisticsService : ApplicationService, IUsageStatisticsServic
|
|||||||
|
|
||||||
if (premiumPackages.Any())
|
if (premiumPackages.Any())
|
||||||
{
|
{
|
||||||
// 过滤掉已过期的包
|
// 过滤掉已过期、禁用的包,不过滤用量负数的包
|
||||||
var validPackages = premiumPackages
|
var validPackages = premiumPackages
|
||||||
.Where(p => p.IsAvailable())
|
.Where(p => p.IsAvailable(false))
|
||||||
.ToList();
|
.ToList();
|
||||||
|
|
||||||
result.PremiumTotalTokens = validPackages.Sum(x => x.TotalTokens);
|
result.PremiumTotalTokens = validPackages.Sum(x => x.TotalTokens);
|
||||||
@@ -137,4 +153,79 @@ public class UsageStatisticsService : ApplicationService, IUsageStatisticsServic
|
|||||||
|
|
||||||
return result;
|
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>>());
|
||||||
|
}
|
||||||
|
|
||||||
|
/// <summary>
|
||||||
|
/// 获取当前用户尊享包不同Token用量占比(饼图)
|
||||||
|
/// </summary>
|
||||||
|
/// <returns>各Token的尊享模型用量及占比</returns>
|
||||||
|
[HttpGet("usage-statistics/premium-token-usage/by-token")]
|
||||||
|
public async Task<List<TokenPremiumUsageDto>> GetPremiumTokenUsageByTokenAsync()
|
||||||
|
{
|
||||||
|
var userId = CurrentUser.GetId();
|
||||||
|
|
||||||
|
// 通过ModelManager获取所有尊享模型的ModelId列表
|
||||||
|
var premiumModelIds = await _modelManager.GetPremiumModelIdsAsync();
|
||||||
|
|
||||||
|
// 从UsageStatistics表获取尊享模型的token消耗统计(按TokenId聚合)
|
||||||
|
var tokenUsages = await _usageStatisticsRepository._DbQueryable
|
||||||
|
.Where(x => x.UserId == userId && premiumModelIds.Contains(x.ModelId))
|
||||||
|
.GroupBy(x => x.TokenId)
|
||||||
|
.Select(x => new
|
||||||
|
{
|
||||||
|
TokenId = x.TokenId,
|
||||||
|
TotalTokenCount = SqlFunc.AggregateSum(x.TotalTokenCount)
|
||||||
|
})
|
||||||
|
.ToListAsync();
|
||||||
|
|
||||||
|
if (!tokenUsages.Any())
|
||||||
|
{
|
||||||
|
return new List<TokenPremiumUsageDto>();
|
||||||
|
}
|
||||||
|
|
||||||
|
// 获取用户的所有Token信息用于名称映射
|
||||||
|
var tokenIds = tokenUsages.Select(x => x.TokenId).ToList();
|
||||||
|
var tokens = await _tokenRepository._DbQueryable
|
||||||
|
.Where(x => x.UserId == userId && tokenIds.Contains(x.Id))
|
||||||
|
.Select(x => new { x.Id, x.Name })
|
||||||
|
.ToListAsync();
|
||||||
|
|
||||||
|
var tokenNameDict = tokens.ToDictionary(x => x.Id, x => x.Name);
|
||||||
|
|
||||||
|
// 计算总token数
|
||||||
|
var totalTokens = tokenUsages.Sum(x => x.TotalTokenCount);
|
||||||
|
|
||||||
|
// 计算各Token占比
|
||||||
|
var result = tokenUsages.Select(x => new TokenPremiumUsageDto
|
||||||
|
{
|
||||||
|
TokenId = x.TokenId,
|
||||||
|
TokenName = x.TokenId == Guid.Empty ? "默认" : (tokenNameDict.TryGetValue(x.TokenId, out var name) ? name : "其他"),
|
||||||
|
Tokens = x.TotalTokenCount,
|
||||||
|
Percentage = totalTokens > 0 ? Math.Round((decimal)x.TotalTokenCount / totalTokens * 100, 2) : 0
|
||||||
|
}).OrderByDescending(x => x.Tokens).ToList();
|
||||||
|
|
||||||
|
return result;
|
||||||
|
}
|
||||||
}
|
}
|
||||||
@@ -2,6 +2,10 @@
|
|||||||
<Import Project="..\..\..\common.props" />
|
<Import Project="..\..\..\common.props" />
|
||||||
|
|
||||||
|
|
||||||
|
<ItemGroup>
|
||||||
|
<PackageReference Include="Volo.Abp.BackgroundJobs.Abstractions" Version="$(AbpVersion)" />
|
||||||
|
</ItemGroup>
|
||||||
|
|
||||||
<ItemGroup>
|
<ItemGroup>
|
||||||
<ProjectReference Include="..\..\..\framework\Yi.Framework.Ddd.Application\Yi.Framework.Ddd.Application.csproj" />
|
<ProjectReference Include="..\..\..\framework\Yi.Framework.Ddd.Application\Yi.Framework.Ddd.Application.csproj" />
|
||||||
<ProjectReference Include="..\Yi.Framework.AiHub.Application.Contracts\Yi.Framework.AiHub.Application.Contracts.csproj" />
|
<ProjectReference Include="..\Yi.Framework.AiHub.Application.Contracts\Yi.Framework.AiHub.Application.Contracts.csproj" />
|
||||||
|
|||||||
@@ -1,3 +1,7 @@
|
|||||||
|
using System.ComponentModel;
|
||||||
|
using System.Text.Json;
|
||||||
|
using ModelContextProtocol;
|
||||||
|
using ModelContextProtocol.Server;
|
||||||
using Yi.Framework.AiHub.Application.Contracts;
|
using Yi.Framework.AiHub.Application.Contracts;
|
||||||
using Yi.Framework.AiHub.Domain;
|
using Yi.Framework.AiHub.Domain;
|
||||||
using Yi.Framework.Ddd.Application;
|
using Yi.Framework.Ddd.Application;
|
||||||
|
|||||||
@@ -0,0 +1,16 @@
|
|||||||
|
namespace Yi.Framework.AiHub.Domain.Shared.Attributes;
|
||||||
|
|
||||||
|
[AttributeUsage(AttributeTargets.Class|AttributeTargets.Method)]
|
||||||
|
public class YiAgentToolAttribute:Attribute
|
||||||
|
{
|
||||||
|
public YiAgentToolAttribute()
|
||||||
|
{
|
||||||
|
}
|
||||||
|
|
||||||
|
public YiAgentToolAttribute(string name)
|
||||||
|
{
|
||||||
|
Name = name;
|
||||||
|
}
|
||||||
|
|
||||||
|
public string Name { get; set; }
|
||||||
|
}
|
||||||
@@ -4,5 +4,22 @@ namespace Yi.Framework.AiHub.Domain.Shared.Consts;
|
|||||||
|
|
||||||
public class PremiumPackageConst
|
public class PremiumPackageConst
|
||||||
{
|
{
|
||||||
public static List<string> ModeIds = ["claude-sonnet-4-5-20250929"];
|
public static List<string> ModeIds =
|
||||||
|
[
|
||||||
|
"claude-sonnet-4-5-20250929",
|
||||||
|
"claude-haiku-4-5-20251001",
|
||||||
|
"claude-opus-4-5-20251101",
|
||||||
|
"gemini-3-pro-preview",
|
||||||
|
"gpt-5.1-codex-max",
|
||||||
|
"gpt-5.2",
|
||||||
|
"gemini-3-pro-high",
|
||||||
|
"gemini-3-pro-image-preview",
|
||||||
|
"gpt-5.2-codex-xhigh",
|
||||||
|
"gpt-5.2-codex",
|
||||||
|
|
||||||
|
"glm-4.7",
|
||||||
|
"yi-claude-sonnet-4-5-20250929",
|
||||||
|
"yi-claude-haiku-4-5-20251001",
|
||||||
|
"yi-claude-opus-4-5-20251101",
|
||||||
|
];
|
||||||
}
|
}
|
||||||
@@ -56,4 +56,9 @@ public class AiModelDescribe
|
|||||||
/// 模型额外信息
|
/// 模型额外信息
|
||||||
/// </summary>
|
/// </summary>
|
||||||
public string? ModelExtraInfo { get; set; }
|
public string? ModelExtraInfo { get; set; }
|
||||||
|
|
||||||
|
/// <summary>
|
||||||
|
/// 模型倍率
|
||||||
|
/// </summary>
|
||||||
|
public decimal Multiplier { get; set; }
|
||||||
}
|
}
|
||||||
@@ -34,7 +34,7 @@ public class AnthropicStreamDto
|
|||||||
};
|
};
|
||||||
|
|
||||||
|
|
||||||
public void SupplementalMultiplier(double multiplier)
|
public void SupplementalMultiplier(decimal multiplier)
|
||||||
{
|
{
|
||||||
if (this.Usage is not null)
|
if (this.Usage is not null)
|
||||||
{
|
{
|
||||||
@@ -130,7 +130,7 @@ public class AnthropicChatCompletionDto
|
|||||||
CompletionTokensDetails = null
|
CompletionTokensDetails = null
|
||||||
};
|
};
|
||||||
|
|
||||||
public void SupplementalMultiplier(double multiplier)
|
public void SupplementalMultiplier(decimal multiplier)
|
||||||
{
|
{
|
||||||
if (this.Usage is not null)
|
if (this.Usage is not null)
|
||||||
{
|
{
|
||||||
|
|||||||
@@ -109,8 +109,15 @@ public sealed class AnthropicInput
|
|||||||
public class AnthropicThinkingInput
|
public class AnthropicThinkingInput
|
||||||
{
|
{
|
||||||
[JsonPropertyName("type")] public string? Type { get; set; }
|
[JsonPropertyName("type")] public string? Type { get; set; }
|
||||||
|
|
||||||
[JsonPropertyName("budget_tokens")] public int? BudgetTokens { 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
|
public class AnthropicTooChoiceInput
|
||||||
|
|||||||
@@ -20,6 +20,8 @@ public class AnthropicMessageContent
|
|||||||
|
|
||||||
[JsonPropertyName("thinking")] public string? Thinking { get; set; }
|
[JsonPropertyName("thinking")] public string? Thinking { get; set; }
|
||||||
|
|
||||||
|
[JsonPropertyName("signature")] public string? Signature { get; set; }
|
||||||
|
|
||||||
[JsonPropertyName("input")] public object? Input { get; set; }
|
[JsonPropertyName("input")] public object? Input { get; set; }
|
||||||
|
|
||||||
[JsonPropertyName("content")]
|
[JsonPropertyName("content")]
|
||||||
|
|||||||
@@ -22,11 +22,15 @@ public class AnthropicMessageInput
|
|||||||
throw new ValidationException("Messages 中 Content 和 Contents 字段不能同时有值");
|
throw new ValidationException("Messages 中 Content 和 Contents 字段不能同时有值");
|
||||||
}
|
}
|
||||||
|
|
||||||
if (Content is not null)
|
if (!string.IsNullOrEmpty(Content))
|
||||||
{
|
{
|
||||||
return Content;
|
return Content;
|
||||||
}
|
}
|
||||||
|
// 如果 Contents 为空或 null,返回空字符串而不是 null
|
||||||
|
if (Contents == null || Contents.Count == 0)
|
||||||
|
{
|
||||||
|
return "_"; // 兼容客户端空值问题
|
||||||
|
}
|
||||||
return Contents!;
|
return Contents!;
|
||||||
}
|
}
|
||||||
set
|
set
|
||||||
|
|||||||
@@ -1,648 +0,0 @@
|
|||||||
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,77 @@
|
|||||||
|
using System.Text.Json;
|
||||||
|
using Yi.Framework.AiHub.Domain.Shared.Dtos.OpenAi;
|
||||||
|
using Yi.Framework.AiHub.Domain.Shared.Extensions;
|
||||||
|
|
||||||
|
namespace Yi.Framework.AiHub.Domain.Shared.Dtos.Gemini;
|
||||||
|
|
||||||
|
public static class GeminiGenerateContentAcquirer
|
||||||
|
{
|
||||||
|
public static ThorUsageResponse? GetUsage(JsonElement response)
|
||||||
|
{
|
||||||
|
var usage = response.GetPath("usageMetadata");
|
||||||
|
if (!usage.HasValue)
|
||||||
|
{
|
||||||
|
return null;
|
||||||
|
}
|
||||||
|
|
||||||
|
var inputTokens = usage.Value.GetPath("promptTokenCount").GetInt();
|
||||||
|
var outputTokens = usage.Value.GetPath("candidatesTokenCount").GetInt()
|
||||||
|
+ usage.Value.GetPath("cachedContentTokenCount").GetInt()
|
||||||
|
+ usage.Value.GetPath("thoughtsTokenCount").GetInt()
|
||||||
|
+ usage.Value.GetPath("toolUsePromptTokenCount").GetInt();
|
||||||
|
|
||||||
|
return new ThorUsageResponse
|
||||||
|
{
|
||||||
|
PromptTokens = inputTokens,
|
||||||
|
InputTokens = inputTokens,
|
||||||
|
OutputTokens = outputTokens,
|
||||||
|
CompletionTokens = outputTokens,
|
||||||
|
TotalTokens = inputTokens + outputTokens,
|
||||||
|
};
|
||||||
|
}
|
||||||
|
|
||||||
|
/// <summary>
|
||||||
|
/// 获取图片 base64(包含 data:image 前缀)
|
||||||
|
/// 优先从 inlineData.data 中获取,其次从 markdown text 中解析
|
||||||
|
/// </summary>
|
||||||
|
public static string GetImagePrefixBase64(JsonElement response)
|
||||||
|
{
|
||||||
|
// Step 1: 优先尝试从 candidates[0].content.parts[0].inlineData.data 获取
|
||||||
|
var inlineBase64 = response
|
||||||
|
.GetPath("candidates", 0, "content", "parts", 0, "inlineData", "data")
|
||||||
|
.GetString();
|
||||||
|
|
||||||
|
if (!string.IsNullOrEmpty(inlineBase64))
|
||||||
|
{
|
||||||
|
// 默认按 png 格式拼接前缀
|
||||||
|
return $"data:image/png;base64,{inlineBase64}";
|
||||||
|
}
|
||||||
|
|
||||||
|
// Step 2: fallback,从 candidates[0].content.parts[0].text 中解析 markdown 图片
|
||||||
|
var text = response
|
||||||
|
.GetPath("candidates", 0, "content", "parts", 0, "text")
|
||||||
|
.GetString();
|
||||||
|
|
||||||
|
if (string.IsNullOrEmpty(text))
|
||||||
|
{
|
||||||
|
return string.Empty;
|
||||||
|
}
|
||||||
|
|
||||||
|
// markdown 图片格式: 
|
||||||
|
var startMarker = "(data:image/";
|
||||||
|
var startIndex = text.IndexOf(startMarker, StringComparison.Ordinal);
|
||||||
|
if (startIndex < 0)
|
||||||
|
{
|
||||||
|
return string.Empty;
|
||||||
|
}
|
||||||
|
|
||||||
|
startIndex += 1; // 跳过 "("
|
||||||
|
var endIndex = text.IndexOf(')', startIndex);
|
||||||
|
if (endIndex <= startIndex)
|
||||||
|
{
|
||||||
|
return string.Empty;
|
||||||
|
}
|
||||||
|
|
||||||
|
return text.Substring(startIndex, endIndex - startIndex);
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -0,0 +1,47 @@
|
|||||||
|
using System.Text.Json;
|
||||||
|
using System.Text.Json.Serialization;
|
||||||
|
|
||||||
|
namespace Yi.Framework.AiHub.Domain.Shared.Dtos.OpenAi.Responses;
|
||||||
|
|
||||||
|
public class OpenAiResponsesInput
|
||||||
|
{
|
||||||
|
[JsonPropertyName("stream")] public bool? Stream { get; set; }
|
||||||
|
|
||||||
|
[JsonPropertyName("model")] public string Model { get; set; }
|
||||||
|
[JsonPropertyName("input")] public JsonElement Input { get; set; }
|
||||||
|
|
||||||
|
[JsonPropertyName("max_output_tokens")]
|
||||||
|
public int? MaxOutputTokens { get; set; }
|
||||||
|
|
||||||
|
[JsonPropertyName("max_tool_calls")] public JsonElement? MaxToolCalls { get; set; }
|
||||||
|
[JsonPropertyName("instructions")] public string? Instructions { get; set; }
|
||||||
|
[JsonPropertyName("metadata")] public JsonElement? Metadata { get; set; }
|
||||||
|
|
||||||
|
[JsonPropertyName("parallel_tool_calls")]
|
||||||
|
public bool? ParallelToolCalls { get; set; }
|
||||||
|
|
||||||
|
[JsonPropertyName("previous_response_id")]
|
||||||
|
public string? PreviousResponseId { get; set; }
|
||||||
|
|
||||||
|
[JsonPropertyName("prompt")] public JsonElement? Prompt { get; set; }
|
||||||
|
[JsonPropertyName("prompt_cache_key")] public string? PromptCacheKey { get; set; }
|
||||||
|
|
||||||
|
[JsonPropertyName("prompt_cache_retention")]
|
||||||
|
public string? PromptCacheRetention { get; set; }
|
||||||
|
|
||||||
|
[JsonPropertyName("reasoning")] public JsonElement? Reasoning { get; set; }
|
||||||
|
|
||||||
|
[JsonPropertyName("safety_identifier")]
|
||||||
|
public string? SafetyIdentifier { get; set; }
|
||||||
|
|
||||||
|
[JsonPropertyName("service_tier")] public string? ServiceTier { get; set; }
|
||||||
|
[JsonPropertyName("store")] public bool? Store { get; set; }
|
||||||
|
[JsonPropertyName("stream_options")] public JsonElement? StreamOptions { get; set; }
|
||||||
|
[JsonPropertyName("temperature")] public decimal? Temperature { get; set; }
|
||||||
|
[JsonPropertyName("text")] public JsonElement? Text { get; set; }
|
||||||
|
[JsonPropertyName("tool_choice")] public JsonElement? ToolChoice { get; set; }
|
||||||
|
[JsonPropertyName("tools")] public JsonElement? Tools { get; set; }
|
||||||
|
[JsonPropertyName("top_logprobs")] public int? TopLogprobs { get; set; }
|
||||||
|
[JsonPropertyName("top_p")] public decimal? TopP { get; set; }
|
||||||
|
[JsonPropertyName("truncation")] public string? Truncation { get; set; }
|
||||||
|
}
|
||||||
@@ -0,0 +1,91 @@
|
|||||||
|
using System.Text.Json.Serialization;
|
||||||
|
|
||||||
|
namespace Yi.Framework.AiHub.Domain.Shared.Dtos.OpenAi.Responses;
|
||||||
|
|
||||||
|
public class OpenAiResponsesOutput
|
||||||
|
{
|
||||||
|
[JsonPropertyName("id")]
|
||||||
|
public string? Id { get; set; }
|
||||||
|
[JsonPropertyName("object")]
|
||||||
|
public string? Object { get; set; }
|
||||||
|
[JsonPropertyName("created_at")]
|
||||||
|
public long CreatedAt { get; set; }
|
||||||
|
[JsonPropertyName("status")]
|
||||||
|
public string? Status { get; set; }
|
||||||
|
[JsonPropertyName("error")]
|
||||||
|
public dynamic? Error { get; set; }
|
||||||
|
[JsonPropertyName("incomplete_details")]
|
||||||
|
public dynamic? IncompleteDetails { get; set; }
|
||||||
|
[JsonPropertyName("instructions")]
|
||||||
|
public dynamic? Instructions { get; set; }
|
||||||
|
[JsonPropertyName("max_output_tokens")]
|
||||||
|
public dynamic? MaxOutputTokens { get; set; }
|
||||||
|
[JsonPropertyName("model")]
|
||||||
|
public string? Model { get; set; }
|
||||||
|
// output 是复杂对象
|
||||||
|
[JsonPropertyName("output")]
|
||||||
|
public List<dynamic>? Output { get; set; }
|
||||||
|
[JsonPropertyName("parallel_tool_calls")]
|
||||||
|
public bool ParallelToolCalls { get; set; }
|
||||||
|
[JsonPropertyName("previous_response_id")]
|
||||||
|
public dynamic? PreviousResponseId { get; set; }
|
||||||
|
[JsonPropertyName("reasoning")]
|
||||||
|
public dynamic? Reasoning { get; set; }
|
||||||
|
[JsonPropertyName("store")]
|
||||||
|
public bool Store { get; set; }
|
||||||
|
[JsonPropertyName("temperature")]
|
||||||
|
public double Temperature { get; set; }
|
||||||
|
[JsonPropertyName("text")]
|
||||||
|
public dynamic? Text { get; set; }
|
||||||
|
[JsonPropertyName("tool_choice")]
|
||||||
|
public string? ToolChoice { get; set; }
|
||||||
|
[JsonPropertyName("tools")]
|
||||||
|
public List<dynamic>? Tools { get; set; }
|
||||||
|
[JsonPropertyName("top_p")]
|
||||||
|
public double TopP { get; set; }
|
||||||
|
[JsonPropertyName("truncation")]
|
||||||
|
public string? Truncation { get; set; }
|
||||||
|
// usage 为唯一强类型
|
||||||
|
[JsonPropertyName("usage")]
|
||||||
|
public OpenAiResponsesUsageOutput? Usage { get; set; }
|
||||||
|
[JsonPropertyName("user")]
|
||||||
|
public dynamic? User { get; set; }
|
||||||
|
[JsonPropertyName("metadata")]
|
||||||
|
public dynamic? Metadata { get; set; }
|
||||||
|
|
||||||
|
public void SupplementalMultiplier(decimal 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);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
public class OpenAiResponsesUsageOutput
|
||||||
|
{
|
||||||
|
[JsonPropertyName("input_tokens")]
|
||||||
|
public int InputTokens { get; set; }
|
||||||
|
[JsonPropertyName("input_tokens_details")]
|
||||||
|
public OpenAiResponsesInputTokensDetails? InputTokensDetails { get; set; }
|
||||||
|
[JsonPropertyName("output_tokens")]
|
||||||
|
public int OutputTokens { get; set; }
|
||||||
|
[JsonPropertyName("output_tokens_details")]
|
||||||
|
public OpenAiResponsesOutputTokensDetails? OutputTokensDetails { get; set; }
|
||||||
|
[JsonPropertyName("total_tokens")]
|
||||||
|
public int TotalTokens { get; set; }
|
||||||
|
}
|
||||||
|
public class OpenAiResponsesInputTokensDetails
|
||||||
|
{
|
||||||
|
[JsonPropertyName("cached_tokens")]
|
||||||
|
public int CachedTokens { get; set; }
|
||||||
|
}
|
||||||
|
public class OpenAiResponsesOutputTokensDetails
|
||||||
|
{
|
||||||
|
[JsonPropertyName("reasoning_tokens")]
|
||||||
|
public int ReasoningTokens { get; set; }
|
||||||
|
}
|
||||||
@@ -61,7 +61,7 @@ public record ThorChatCompletionsResponse
|
|||||||
[JsonPropertyName("error")]
|
[JsonPropertyName("error")]
|
||||||
public ThorError? Error { get; set; }
|
public ThorError? Error { get; set; }
|
||||||
|
|
||||||
public void SupplementalMultiplier(double multiplier)
|
public void SupplementalMultiplier(decimal multiplier)
|
||||||
{
|
{
|
||||||
if (this.Usage is not null)
|
if (this.Usage is not null)
|
||||||
{
|
{
|
||||||
@@ -73,6 +73,9 @@ public record ThorChatCompletionsResponse
|
|||||||
(int)Math.Round((this.Usage.CompletionTokens ?? 0) * multiplier);
|
(int)Math.Round((this.Usage.CompletionTokens ?? 0) * multiplier);
|
||||||
this.Usage.PromptTokens =
|
this.Usage.PromptTokens =
|
||||||
(int)Math.Round((this.Usage.PromptTokens ?? 0) * multiplier);
|
(int)Math.Round((this.Usage.PromptTokens ?? 0) * multiplier);
|
||||||
|
|
||||||
|
this.Usage.TotalTokens =
|
||||||
|
(int)Math.Round((this.Usage.TotalTokens ?? 0) * multiplier);
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
@@ -90,6 +90,28 @@ public class ThorChatMessage
|
|||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
|
|
||||||
|
/// <summary>
|
||||||
|
/// 用于数据存储
|
||||||
|
/// </summary>
|
||||||
|
[JsonIgnore]
|
||||||
|
public string MessagesStore
|
||||||
|
{
|
||||||
|
get
|
||||||
|
{
|
||||||
|
if (Content is not null)
|
||||||
|
{
|
||||||
|
return Content;
|
||||||
|
}
|
||||||
|
|
||||||
|
if (Contents is not null && Contents.Any())
|
||||||
|
{
|
||||||
|
return JsonSerializer.Serialize(Contents);
|
||||||
|
}
|
||||||
|
return string.Empty;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
/// <summary>
|
/// <summary>
|
||||||
/// 【可选】参与者的可选名称。提供模型信息以区分相同角色的参与者。
|
/// 【可选】参与者的可选名称。提供模型信息以区分相同角色的参与者。
|
||||||
/// </summary>
|
/// </summary>
|
||||||
|
|||||||
@@ -0,0 +1,138 @@
|
|||||||
|
using System;
|
||||||
|
using System.Reflection;
|
||||||
|
|
||||||
|
namespace Yi.Framework.AiHub.Domain.Shared.Enums;
|
||||||
|
|
||||||
|
/// <summary>
|
||||||
|
/// 激活码商品特性
|
||||||
|
/// </summary>
|
||||||
|
[AttributeUsage(AttributeTargets.Field)]
|
||||||
|
public class ActivationCodeGoodsAttribute : Attribute
|
||||||
|
{
|
||||||
|
public decimal Price { get; }
|
||||||
|
public long TokenAmount { get; }
|
||||||
|
public int VipMonths { get; }
|
||||||
|
public int VipDays { get; }
|
||||||
|
public bool IsCombo { get; }
|
||||||
|
public bool IsReusable { get; }
|
||||||
|
public bool IsSameTypeOnce { get; }
|
||||||
|
public string DisplayName { get; }
|
||||||
|
public string Content { get; }
|
||||||
|
|
||||||
|
public ActivationCodeGoodsAttribute(
|
||||||
|
double price,
|
||||||
|
long tokenAmount,
|
||||||
|
int vipMonths,
|
||||||
|
bool isCombo,
|
||||||
|
bool isReusable,
|
||||||
|
bool isSameTypeOnce,
|
||||||
|
string displayName,
|
||||||
|
string content,
|
||||||
|
int vipDays = 0)
|
||||||
|
{
|
||||||
|
Price = (decimal)price;
|
||||||
|
TokenAmount = tokenAmount;
|
||||||
|
VipMonths = vipMonths;
|
||||||
|
VipDays = vipDays;
|
||||||
|
IsCombo = isCombo;
|
||||||
|
IsReusable = isReusable;
|
||||||
|
IsSameTypeOnce = isSameTypeOnce;
|
||||||
|
DisplayName = displayName;
|
||||||
|
Content = content;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
/// <summary>
|
||||||
|
/// 激活码商品类型
|
||||||
|
/// </summary>
|
||||||
|
public enum ActivationCodeGoodsTypeEnum
|
||||||
|
{
|
||||||
|
/// <summary>
|
||||||
|
/// 48.90【意心Ai会员1月+2000w 尊享Token】新人首单组合包(推荐)
|
||||||
|
/// </summary>
|
||||||
|
[ActivationCodeGoods(price: 48.90, tokenAmount: 20000000, vipMonths: 1, isCombo: true, isReusable: false,
|
||||||
|
isSameTypeOnce: true, displayName: "意心Ai会员1月+2000w 尊享Token", content: "新人首单组合包")]
|
||||||
|
Vip1MonthPlus2000W = 1,
|
||||||
|
|
||||||
|
/// <summary>
|
||||||
|
/// 1.00【10w 尊享Token】测试体验包
|
||||||
|
/// </summary>
|
||||||
|
[ActivationCodeGoods(price: 1.00, tokenAmount: 100000, vipMonths: 0, isCombo: false, isReusable: false,
|
||||||
|
isSameTypeOnce: false, displayName: "10w 尊享Token", content: "测试体验包")]
|
||||||
|
Premium10W = 2,
|
||||||
|
|
||||||
|
/// <summary>
|
||||||
|
/// 9.90【1000w 尊享Token】意心会员首单回馈包
|
||||||
|
/// </summary>
|
||||||
|
[ActivationCodeGoods(price: 9.90, tokenAmount: 10000000, vipMonths: 0, isCombo: false, isReusable: false,
|
||||||
|
isSameTypeOnce: true, displayName: "1000w 尊享Token", content: "意心会员首单回馈包")]
|
||||||
|
Premium1000W = 3,
|
||||||
|
|
||||||
|
/// <summary>
|
||||||
|
/// 22.90【意心Ai会员1月】特价包
|
||||||
|
/// </summary>
|
||||||
|
[ActivationCodeGoods(price: 22.90, tokenAmount: 0, vipMonths: 1, isCombo: false, isReusable: false,
|
||||||
|
isSameTypeOnce: false, displayName: "意心Ai会员1月", content: "特价包")]
|
||||||
|
Vip1Month = 4,
|
||||||
|
|
||||||
|
/// <summary>
|
||||||
|
/// 138.90【5000w 尊享Token】特价包
|
||||||
|
/// </summary>
|
||||||
|
[ActivationCodeGoods(price: 138.90, tokenAmount: 50000000, vipMonths: 0, isCombo: false, isReusable: false,
|
||||||
|
isSameTypeOnce: false, displayName: "5000w 尊享Token", content: "特价包")]
|
||||||
|
Premium5000W = 5,
|
||||||
|
|
||||||
|
/// <summary>
|
||||||
|
/// 198.90【1亿 尊享Token】特价包
|
||||||
|
/// </summary>
|
||||||
|
[ActivationCodeGoods(price: 198.90, tokenAmount: 100000000, vipMonths: 0, isCombo: false, isReusable: false,
|
||||||
|
isSameTypeOnce: false, displayName: "1亿 尊享Token", content: "特价包")]
|
||||||
|
Premium1Yi = 6,
|
||||||
|
|
||||||
|
/// <summary>
|
||||||
|
/// 1【意心Ai会员1天+50w 尊享Token】新人试用首单组合包
|
||||||
|
/// </summary>
|
||||||
|
[ActivationCodeGoods(price: 1, tokenAmount: 500000, vipMonths: 0, vipDays: 1, isCombo: true, isReusable: false,
|
||||||
|
isSameTypeOnce: true, displayName: "意心Ai会员1天+50w 尊享Token", content: "新人首单组合包")]
|
||||||
|
Vip1DayTest = 7,
|
||||||
|
|
||||||
|
/// <summary>
|
||||||
|
/// 0【10w 尊享Token】免费包
|
||||||
|
/// </summary>
|
||||||
|
[ActivationCodeGoods(price: 0, tokenAmount: 100000, vipMonths: 0, isCombo: false, isReusable: true,
|
||||||
|
isSameTypeOnce: false, displayName: "10w 尊享Token", content: "免费包")]
|
||||||
|
Premium10WFree = 100,
|
||||||
|
|
||||||
|
|
||||||
|
|
||||||
|
|
||||||
|
/// <summary>
|
||||||
|
/// 0【888w 尊享Token】活动包
|
||||||
|
/// </summary>
|
||||||
|
[ActivationCodeGoods(price: 0, tokenAmount: 8880000, vipMonths: 0, isCombo: false, isReusable: false,
|
||||||
|
isSameTypeOnce: false, displayName: "888w 尊享Token", content: "888w活动赠送福利包")]
|
||||||
|
Premium888WFree = 200,
|
||||||
|
|
||||||
|
/// <summary>
|
||||||
|
/// 0【666w 尊享Token】活动包
|
||||||
|
/// </summary>
|
||||||
|
[ActivationCodeGoods(price: 0, tokenAmount: 6660000, vipMonths: 0, isCombo: false, isReusable: false,
|
||||||
|
isSameTypeOnce: false, displayName: "666w 尊享Token", content: "666w活动赠送福利包")]
|
||||||
|
Premium666WFree = 201,
|
||||||
|
|
||||||
|
/// <summary>
|
||||||
|
/// 0【100w 尊享Token】活动包
|
||||||
|
/// </summary>
|
||||||
|
[ActivationCodeGoods(price: 0, tokenAmount: 1000000, vipMonths: 0, isCombo: false, isReusable: false,
|
||||||
|
isSameTypeOnce: false, displayName: "100w 尊享Token", content: "100w活动赠送福利包")]
|
||||||
|
Premium100WFree = 202,
|
||||||
|
}
|
||||||
|
|
||||||
|
public static class ActivationCodeGoodsTypeEnumExtensions
|
||||||
|
{
|
||||||
|
public static ActivationCodeGoodsAttribute? GetGoods(this ActivationCodeGoodsTypeEnum goodsType)
|
||||||
|
{
|
||||||
|
var fieldInfo = goodsType.GetType().GetField(goodsType.ToString());
|
||||||
|
return fieldInfo?.GetCustomAttribute<ActivationCodeGoodsAttribute>();
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -0,0 +1,7 @@
|
|||||||
|
namespace Yi.Framework.AiHub.Domain.Shared.Enums;
|
||||||
|
|
||||||
|
public enum AnnouncementTypeEnum
|
||||||
|
{
|
||||||
|
Activity=1,
|
||||||
|
System=2
|
||||||
|
}
|
||||||
@@ -102,11 +102,6 @@ public enum GoodsTypeEnum
|
|||||||
[Price(155.4, 6, 25.9)] [DisplayName("YiXinVip 6 month", "6个月", "年度热销")] [GoodsCategory(GoodsCategoryType.Vip)]
|
[Price(155.4, 6, 25.9)] [DisplayName("YiXinVip 6 month", "6个月", "年度热销")] [GoodsCategory(GoodsCategoryType.Vip)]
|
||||||
YiXinVip6 = 6,
|
YiXinVip6 = 6,
|
||||||
|
|
||||||
[Price(183.2, 8, 22.9)]
|
|
||||||
[DisplayName("YiXinVip 8 month", "8个月(推荐)", "限时活动,超高性价比")]
|
|
||||||
[GoodsCategory(GoodsCategoryType.Vip)]
|
|
||||||
YiXinVip8 = 8,
|
|
||||||
|
|
||||||
// 尊享包服务 - 需要VIP资格才能购买
|
// 尊享包服务 - 需要VIP资格才能购买
|
||||||
[Price(188.9, 0, 1750)]
|
[Price(188.9, 0, 1750)]
|
||||||
[DisplayName("YiXinPremiumPackage 5000W Tokens", "5000万Tokens", "简单尝试")]
|
[DisplayName("YiXinPremiumPackage 5000W Tokens", "5000万Tokens", "简单尝试")]
|
||||||
@@ -115,10 +110,23 @@ public enum GoodsTypeEnum
|
|||||||
PremiumPackage5000W = 101,
|
PremiumPackage5000W = 101,
|
||||||
|
|
||||||
[Price(248.9, 0, 3500)]
|
[Price(248.9, 0, 3500)]
|
||||||
[DisplayName("YiXinPremiumPackage 10000W Tokens", "1亿Tokens(推荐)", "极致性价比")]
|
[DisplayName("YiXinPremiumPackage 10000W Tokens", "1亿Tokens", "极致性价比")]
|
||||||
[GoodsCategory(GoodsCategoryType.PremiumPackage)]
|
[GoodsCategory(GoodsCategoryType.PremiumPackage)]
|
||||||
[TokenAmount(100000000)]
|
[TokenAmount(100000000)]
|
||||||
PremiumPackage10000W = 102,
|
PremiumPackage10000W = 102,
|
||||||
|
|
||||||
|
|
||||||
|
[Price(238.9, 0, 3500)]
|
||||||
|
[DisplayName("YiXinPremiumPackage 10000W Tokens", "1亿Tokens(2026元旦限购)", "活动9.5折特价")]
|
||||||
|
[GoodsCategory(GoodsCategoryType.PremiumPackage)]
|
||||||
|
[TokenAmount(100000000)]
|
||||||
|
PremiumPackage10000W_2026 = 103,
|
||||||
|
|
||||||
|
[Price(398.9, 0, 7000)]
|
||||||
|
[DisplayName("YiXinPremiumPackage 20000W Tokens", "2亿Tokens(2026元旦限购)", "史上最低8.8折")]
|
||||||
|
[GoodsCategory(GoodsCategoryType.PremiumPackage)]
|
||||||
|
[TokenAmount(200000000)]
|
||||||
|
PremiumPackage20000W_2026 = 104,
|
||||||
}
|
}
|
||||||
|
|
||||||
public static class GoodsTypeEnumExtensions
|
public static class GoodsTypeEnumExtensions
|
||||||
@@ -264,7 +272,7 @@ public static class GoodsTypeEnumExtensions
|
|||||||
|
|
||||||
/// <summary>
|
/// <summary>
|
||||||
/// 计算折扣金额(仅用于尊享包)
|
/// 计算折扣金额(仅用于尊享包)
|
||||||
/// 规则:每累加充值10元,减少2.5元,最多减少50元
|
/// 规则:每累加充值10元,减少10元,最多减少50元
|
||||||
/// </summary>
|
/// </summary>
|
||||||
/// <param name="goodsType">商品类型</param>
|
/// <param name="goodsType">商品类型</param>
|
||||||
/// <param name="totalRechargeAmount">用户累加充值金额</param>
|
/// <param name="totalRechargeAmount">用户累加充值金额</param>
|
||||||
@@ -276,11 +284,10 @@ public static class GoodsTypeEnumExtensions
|
|||||||
{
|
{
|
||||||
return 0m;
|
return 0m;
|
||||||
}
|
}
|
||||||
|
// 每满 10 元减 10 元
|
||||||
// 每10元减2.5元
|
var discountTimes = Math.Floor(totalRechargeAmount / 10m);
|
||||||
var discountAmount = Math.Floor(totalRechargeAmount / 2.5m);
|
var discountAmount = discountTimes * 10m;
|
||||||
|
// 最多减少 50 元
|
||||||
// 最多减少50元
|
|
||||||
return Math.Min(discountAmount, 50m);
|
return Math.Min(discountAmount, 50m);
|
||||||
}
|
}
|
||||||
|
|
||||||
|
|||||||
@@ -1,7 +1,18 @@
|
|||||||
namespace Yi.Framework.AiHub.Domain.Shared.Enums;
|
using System.ComponentModel;
|
||||||
|
|
||||||
|
namespace Yi.Framework.AiHub.Domain.Shared.Enums;
|
||||||
|
|
||||||
public enum ModelApiTypeEnum
|
public enum ModelApiTypeEnum
|
||||||
{
|
{
|
||||||
|
[Description("OpenAI")]
|
||||||
OpenAi,
|
OpenAi,
|
||||||
Claude
|
|
||||||
|
[Description("Claude")]
|
||||||
|
Claude,
|
||||||
|
|
||||||
|
[Description("Response")]
|
||||||
|
Response,
|
||||||
|
|
||||||
|
[Description("GenerateContent")]
|
||||||
|
GenerateContent
|
||||||
}
|
}
|
||||||
@@ -1,9 +1,15 @@
|
|||||||
namespace Yi.Framework.AiHub.Domain.Shared.Enums;
|
using System.ComponentModel;
|
||||||
|
|
||||||
|
namespace Yi.Framework.AiHub.Domain.Shared.Enums;
|
||||||
|
|
||||||
public enum ModelTypeEnum
|
public enum ModelTypeEnum
|
||||||
{
|
{
|
||||||
|
[Description("聊天")]
|
||||||
Chat = 0,
|
Chat = 0,
|
||||||
|
|
||||||
|
[Description("图片")]
|
||||||
Image = 1,
|
Image = 1,
|
||||||
Embedding = 2,
|
|
||||||
PremiumChat = 3
|
[Description("嵌入")]
|
||||||
|
Embedding = 2
|
||||||
}
|
}
|
||||||
@@ -0,0 +1,17 @@
|
|||||||
|
namespace Yi.Framework.AiHub.Domain.Shared.Enums;
|
||||||
|
|
||||||
|
/// <summary>
|
||||||
|
/// 发布状态枚举
|
||||||
|
/// </summary>
|
||||||
|
public enum PublishStatusEnum
|
||||||
|
{
|
||||||
|
/// <summary>
|
||||||
|
/// 未发布
|
||||||
|
/// </summary>
|
||||||
|
Unpublished = 0,
|
||||||
|
|
||||||
|
/// <summary>
|
||||||
|
/// 已发布
|
||||||
|
/// </summary>
|
||||||
|
Published = 1
|
||||||
|
}
|
||||||
@@ -0,0 +1,8 @@
|
|||||||
|
namespace Yi.Framework.AiHub.Domain.Shared.Enums;
|
||||||
|
|
||||||
|
public enum TaskStatusEnum
|
||||||
|
{
|
||||||
|
Processing,
|
||||||
|
Success,
|
||||||
|
Fail
|
||||||
|
}
|
||||||
@@ -0,0 +1,27 @@
|
|||||||
|
using System.ComponentModel;
|
||||||
|
using System.Reflection;
|
||||||
|
|
||||||
|
namespace Yi.Framework.AiHub.Domain.Shared.Extensions;
|
||||||
|
|
||||||
|
/// <summary>
|
||||||
|
/// 枚举扩展方法
|
||||||
|
/// </summary>
|
||||||
|
public static class EnumExtensions
|
||||||
|
{
|
||||||
|
/// <summary>
|
||||||
|
/// 获取枚举的Description特性值
|
||||||
|
/// </summary>
|
||||||
|
/// <param name="value">枚举值</param>
|
||||||
|
/// <returns>Description特性值,如果没有则返回枚举名称</returns>
|
||||||
|
public static string GetDescription(this Enum value)
|
||||||
|
{
|
||||||
|
var field = value.GetType().GetField(value.ToString());
|
||||||
|
if (field == null)
|
||||||
|
{
|
||||||
|
return value.ToString();
|
||||||
|
}
|
||||||
|
|
||||||
|
var attribute = field.GetCustomAttribute<DescriptionAttribute>();
|
||||||
|
return attribute?.Description ?? value.ToString();
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -0,0 +1,279 @@
|
|||||||
|
using System.Text.Json;
|
||||||
|
|
||||||
|
namespace Yi.Framework.AiHub.Domain.Shared.Extensions;
|
||||||
|
|
||||||
|
public static class JsonElementExtensions
|
||||||
|
{
|
||||||
|
#region 路径访问
|
||||||
|
|
||||||
|
/// <summary>
|
||||||
|
/// 链式获取深层属性,支持对象属性和数组索引
|
||||||
|
/// </summary>
|
||||||
|
/// <example>
|
||||||
|
/// root.GetPath("user", "addresses", 0, "city")
|
||||||
|
/// </example>
|
||||||
|
public static JsonElement? GetPath(this JsonElement element, params object[] path)
|
||||||
|
{
|
||||||
|
JsonElement current = element;
|
||||||
|
|
||||||
|
foreach (var key in path)
|
||||||
|
{
|
||||||
|
switch (key)
|
||||||
|
{
|
||||||
|
case string propertyName:
|
||||||
|
if (current.ValueKind != JsonValueKind.Object ||
|
||||||
|
!current.TryGetProperty(propertyName, out current))
|
||||||
|
return null;
|
||||||
|
break;
|
||||||
|
|
||||||
|
case int index:
|
||||||
|
if (current.ValueKind != JsonValueKind.Array ||
|
||||||
|
index < 0 || index >= current.GetArrayLength())
|
||||||
|
return null;
|
||||||
|
current = current[index];
|
||||||
|
break;
|
||||||
|
|
||||||
|
default:
|
||||||
|
return null;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
return current;
|
||||||
|
}
|
||||||
|
|
||||||
|
/// <summary>
|
||||||
|
/// 安全获取对象属性
|
||||||
|
/// </summary>
|
||||||
|
public static JsonElement? Get(this JsonElement element, string propertyName)
|
||||||
|
{
|
||||||
|
if (element.ValueKind == JsonValueKind.Object &&
|
||||||
|
element.TryGetProperty(propertyName, out var value))
|
||||||
|
return value;
|
||||||
|
return null;
|
||||||
|
}
|
||||||
|
|
||||||
|
/// <summary>
|
||||||
|
/// 安全获取数组元素
|
||||||
|
/// </summary>
|
||||||
|
public static JsonElement? Get(this JsonElement element, int index)
|
||||||
|
{
|
||||||
|
if (element.ValueKind == JsonValueKind.Array &&
|
||||||
|
index >= 0 && index < element.GetArrayLength())
|
||||||
|
return element[index];
|
||||||
|
return null;
|
||||||
|
}
|
||||||
|
|
||||||
|
/// <summary>
|
||||||
|
/// 链式安全获取对象属性
|
||||||
|
/// </summary>
|
||||||
|
public static JsonElement? Get(this JsonElement? element, string propertyName)
|
||||||
|
=> element?.Get(propertyName);
|
||||||
|
|
||||||
|
/// <summary>
|
||||||
|
/// 链式安全获取数组元素
|
||||||
|
/// </summary>
|
||||||
|
public static JsonElement? Get(this JsonElement? element, int index)
|
||||||
|
=> element?.Get(index);
|
||||||
|
|
||||||
|
#endregion
|
||||||
|
|
||||||
|
#region 取值方法(带默认值)
|
||||||
|
|
||||||
|
public static string? GetString(this JsonElement? element, string? defaultValue = null)
|
||||||
|
=> element?.ValueKind == JsonValueKind.String ? element.Value.GetString() : defaultValue;
|
||||||
|
|
||||||
|
public static int GetInt(this JsonElement? element, int defaultValue = 0)
|
||||||
|
=> element?.ValueKind == JsonValueKind.Number ? element.Value.GetInt32() : defaultValue;
|
||||||
|
|
||||||
|
public static long GetLong(this JsonElement? element, long defaultValue = 0)
|
||||||
|
=> element?.ValueKind == JsonValueKind.Number ? element.Value.GetInt64() : defaultValue;
|
||||||
|
|
||||||
|
public static double GetDouble(this JsonElement? element, double defaultValue = 0)
|
||||||
|
=> element?.ValueKind == JsonValueKind.Number ? element.Value.GetDouble() : defaultValue;
|
||||||
|
|
||||||
|
public static decimal GetDecimal(this JsonElement? element, decimal defaultValue = 0)
|
||||||
|
=> element?.ValueKind == JsonValueKind.Number ? element.Value.GetDecimal() : defaultValue;
|
||||||
|
|
||||||
|
public static bool GetBool(this JsonElement? element, bool defaultValue = false)
|
||||||
|
=> element?.ValueKind is JsonValueKind.True or JsonValueKind.False
|
||||||
|
? element.Value.GetBoolean()
|
||||||
|
: defaultValue;
|
||||||
|
|
||||||
|
public static DateTime GetDateTime(this JsonElement? element, DateTime defaultValue = default)
|
||||||
|
=> element?.ValueKind == JsonValueKind.String && element.Value.TryGetDateTime(out var dt)
|
||||||
|
? dt
|
||||||
|
: defaultValue;
|
||||||
|
|
||||||
|
public static Guid GetGuid(this JsonElement? element, Guid defaultValue = default)
|
||||||
|
=> element?.ValueKind == JsonValueKind.String && element.Value.TryGetGuid(out var guid)
|
||||||
|
? guid
|
||||||
|
: defaultValue;
|
||||||
|
|
||||||
|
#endregion
|
||||||
|
|
||||||
|
#region 可空取值方法
|
||||||
|
|
||||||
|
public static int? GetIntOrNull(this JsonElement? element)
|
||||||
|
=> element?.ValueKind == JsonValueKind.Number ? element.Value.GetInt32() : null;
|
||||||
|
|
||||||
|
public static long? GetLongOrNull(this JsonElement? element)
|
||||||
|
=> element?.ValueKind == JsonValueKind.Number ? element.Value.GetInt64() : null;
|
||||||
|
|
||||||
|
public static double? GetDoubleOrNull(this JsonElement? element)
|
||||||
|
=> element?.ValueKind == JsonValueKind.Number ? element.Value.GetDouble() : null;
|
||||||
|
|
||||||
|
public static decimal? GetDecimalOrNull(this JsonElement? element)
|
||||||
|
=> element?.ValueKind == JsonValueKind.Number ? element.Value.GetDecimal() : null;
|
||||||
|
|
||||||
|
public static bool? GetBoolOrNull(this JsonElement? element)
|
||||||
|
=> element?.ValueKind is JsonValueKind.True or JsonValueKind.False
|
||||||
|
? element.Value.GetBoolean()
|
||||||
|
: null;
|
||||||
|
|
||||||
|
public static DateTime? GetDateTimeOrNull(this JsonElement? element)
|
||||||
|
=> element?.ValueKind == JsonValueKind.String && element.Value.TryGetDateTime(out var dt)
|
||||||
|
? dt
|
||||||
|
: null;
|
||||||
|
|
||||||
|
public static Guid? GetGuidOrNull(this JsonElement? element)
|
||||||
|
=> element?.ValueKind == JsonValueKind.String && element.Value.TryGetGuid(out var guid)
|
||||||
|
? guid
|
||||||
|
: null;
|
||||||
|
|
||||||
|
#endregion
|
||||||
|
|
||||||
|
#region 数组操作
|
||||||
|
|
||||||
|
/// <summary>
|
||||||
|
/// 安全获取数组,不存在返回空数组
|
||||||
|
/// </summary>
|
||||||
|
public static IEnumerable<JsonElement> GetArray(this JsonElement? element)
|
||||||
|
{
|
||||||
|
if (element?.ValueKind == JsonValueKind.Array)
|
||||||
|
{
|
||||||
|
foreach (var item in element.Value.EnumerateArray())
|
||||||
|
yield return item;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
/// <summary>
|
||||||
|
/// 获取数组长度
|
||||||
|
/// </summary>
|
||||||
|
public static int GetArrayLength(this JsonElement? element)
|
||||||
|
=> element?.ValueKind == JsonValueKind.Array ? element.Value.GetArrayLength() : 0;
|
||||||
|
|
||||||
|
/// <summary>
|
||||||
|
/// 数组转 List
|
||||||
|
/// </summary>
|
||||||
|
public static List<string?> ToStringList(this JsonElement? element)
|
||||||
|
=> element.GetArray().Select(e => e.GetString()).ToList();
|
||||||
|
|
||||||
|
public static List<int> ToIntList(this JsonElement? element)
|
||||||
|
=> element.GetArray()
|
||||||
|
.Where(e => e.ValueKind == JsonValueKind.Number)
|
||||||
|
.Select(e => e.GetInt32())
|
||||||
|
.ToList();
|
||||||
|
|
||||||
|
#endregion
|
||||||
|
|
||||||
|
#region 对象操作
|
||||||
|
|
||||||
|
/// <summary>
|
||||||
|
/// 安全枚举对象属性
|
||||||
|
/// </summary>
|
||||||
|
public static IEnumerable<JsonProperty> GetProperties(this JsonElement? element)
|
||||||
|
{
|
||||||
|
if (element?.ValueKind == JsonValueKind.Object)
|
||||||
|
{
|
||||||
|
foreach (var prop in element.Value.EnumerateObject())
|
||||||
|
yield return prop;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
/// <summary>
|
||||||
|
/// 获取所有属性名
|
||||||
|
/// </summary>
|
||||||
|
public static IEnumerable<string> GetPropertyNames(this JsonElement? element)
|
||||||
|
=> element.GetProperties().Select(p => p.Name);
|
||||||
|
|
||||||
|
/// <summary>
|
||||||
|
/// 判断是否包含某属性
|
||||||
|
/// </summary>
|
||||||
|
public static bool HasProperty(this JsonElement? element, string propertyName)
|
||||||
|
=> element?.ValueKind == JsonValueKind.Object &&
|
||||||
|
element.Value.TryGetProperty(propertyName, out _);
|
||||||
|
|
||||||
|
#endregion
|
||||||
|
|
||||||
|
#region 类型判断
|
||||||
|
|
||||||
|
public static bool IsNull(this JsonElement? element)
|
||||||
|
=> element == null || element.Value.ValueKind == JsonValueKind.Null;
|
||||||
|
|
||||||
|
public static bool IsNullOrUndefined(this JsonElement? element)
|
||||||
|
=> element == null || element.Value.ValueKind is JsonValueKind.Null or JsonValueKind.Undefined;
|
||||||
|
|
||||||
|
public static bool IsObject(this JsonElement? element)
|
||||||
|
=> element?.ValueKind == JsonValueKind.Object;
|
||||||
|
|
||||||
|
public static bool IsArray(this JsonElement? element)
|
||||||
|
=> element?.ValueKind == JsonValueKind.Array;
|
||||||
|
|
||||||
|
public static bool IsString(this JsonElement? element)
|
||||||
|
=> element?.ValueKind == JsonValueKind.String;
|
||||||
|
|
||||||
|
public static bool IsNumber(this JsonElement? element)
|
||||||
|
=> element?.ValueKind == JsonValueKind.Number;
|
||||||
|
|
||||||
|
public static bool IsBool(this JsonElement? element)
|
||||||
|
=> element?.ValueKind is JsonValueKind.True or JsonValueKind.False;
|
||||||
|
|
||||||
|
public static bool Exists(this JsonElement? element)
|
||||||
|
=> element != null && element.Value.ValueKind != JsonValueKind.Undefined;
|
||||||
|
|
||||||
|
#endregion
|
||||||
|
|
||||||
|
#region 反序列化
|
||||||
|
|
||||||
|
/// <summary>
|
||||||
|
/// 反序列化为指定类型
|
||||||
|
/// </summary>
|
||||||
|
public static T? Deserialize<T>(this JsonElement? element, JsonSerializerOptions? options = null)
|
||||||
|
=> element.HasValue ? element.Value.Deserialize<T>(options) : default;
|
||||||
|
|
||||||
|
/// <summary>
|
||||||
|
/// 反序列化为指定类型,带默认值
|
||||||
|
/// </summary>
|
||||||
|
public static T Deserialize<T>(this JsonElement? element, T defaultValue, JsonSerializerOptions? options = null)
|
||||||
|
=> element.HasValue ? element.Value.Deserialize<T>(options) ?? defaultValue : defaultValue;
|
||||||
|
|
||||||
|
#endregion
|
||||||
|
|
||||||
|
#region 转换为字典/动态类型
|
||||||
|
|
||||||
|
/// <summary>
|
||||||
|
/// 转换为 Dictionary
|
||||||
|
/// </summary>
|
||||||
|
public static Dictionary<string, JsonElement>? ToDictionary(this JsonElement? element)
|
||||||
|
{
|
||||||
|
if (element?.ValueKind != JsonValueKind.Object)
|
||||||
|
return null;
|
||||||
|
|
||||||
|
var dict = new Dictionary<string, JsonElement>();
|
||||||
|
foreach (var prop in element.Value.EnumerateObject())
|
||||||
|
dict[prop.Name] = prop.Value;
|
||||||
|
return dict;
|
||||||
|
}
|
||||||
|
|
||||||
|
#endregion
|
||||||
|
|
||||||
|
#region 原始值
|
||||||
|
|
||||||
|
/// <summary>
|
||||||
|
/// 获取原始 JSON 字符串
|
||||||
|
/// </summary>
|
||||||
|
public static string? GetRawText(this JsonElement? element)
|
||||||
|
=> element?.GetRawText();
|
||||||
|
|
||||||
|
#endregion
|
||||||
|
}
|
||||||
@@ -2,6 +2,7 @@
|
|||||||
<Import Project="..\..\..\common.props" />
|
<Import Project="..\..\..\common.props" />
|
||||||
|
|
||||||
<ItemGroup>
|
<ItemGroup>
|
||||||
|
<PackageReference Include="Microsoft.Extensions.AI.Abstractions" Version="9.5.0" />
|
||||||
<PackageReference Include="Volo.Abp.Ddd.Domain.Shared" Version="$(AbpVersion)" />
|
<PackageReference Include="Volo.Abp.Ddd.Domain.Shared" Version="$(AbpVersion)" />
|
||||||
</ItemGroup>
|
</ItemGroup>
|
||||||
|
|
||||||
|
|||||||
Some files were not shown because too many files have changed in this diff Show More
Reference in New Issue
Block a user