Compare commits
120 Commits
| 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 |
@@ -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.
|
||||||
@@ -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,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();
|
||||||
|
}
|
||||||
@@ -1,4 +1,5 @@
|
|||||||
using Yi.Framework.AiHub.Domain.Shared.Enums;
|
using Yi.Framework.AiHub.Domain.Shared.Enums;
|
||||||
|
using Yi.Framework.AiHub.Domain.Shared.Extensions;
|
||||||
|
|
||||||
namespace Yi.Framework.AiHub.Application.Contracts.Dtos.Model;
|
namespace Yi.Framework.AiHub.Application.Contracts.Dtos.Model;
|
||||||
|
|
||||||
@@ -30,17 +31,13 @@ public class ModelLibraryDto
|
|||||||
/// <summary>
|
/// <summary>
|
||||||
/// 模型类型名称
|
/// 模型类型名称
|
||||||
/// </summary>
|
/// </summary>
|
||||||
public string ModelTypeName { get; set; }
|
public string ModelTypeName => ModelType.GetDescription();
|
||||||
|
|
||||||
/// <summary>
|
/// <summary>
|
||||||
/// 模型API类型
|
/// 模型支持的API类型
|
||||||
/// </summary>
|
/// </summary>
|
||||||
public ModelApiTypeEnum ModelApiType { get; set; }
|
public List<ModelApiTypeOutput> ModelApiTypes { get; set; }
|
||||||
|
|
||||||
/// <summary>
|
|
||||||
/// 模型API类型名称
|
|
||||||
/// </summary>
|
|
||||||
public string ModelApiTypeName { get; set; }
|
|
||||||
|
|
||||||
/// <summary>
|
/// <summary>
|
||||||
/// 模型显示倍率
|
/// 模型显示倍率
|
||||||
@@ -61,4 +58,22 @@ public class ModelLibraryDto
|
|||||||
/// 是否为尊享模型(PremiumChat类型)
|
/// 是否为尊享模型(PremiumChat类型)
|
||||||
/// </summary>
|
/// </summary>
|
||||||
public bool IsPremium { get; set; }
|
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();
|
||||||
}
|
}
|
||||||
@@ -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,36 +22,6 @@ public class ModelGetListOutput
|
|||||||
/// </summary>
|
/// </summary>
|
||||||
public string? ModelDescribe { get; set; }
|
public string? ModelDescribe { get; set; }
|
||||||
|
|
||||||
/// <summary>
|
|
||||||
/// 模型价格
|
|
||||||
/// </summary>
|
|
||||||
public double ModelPrice { get; set; }
|
|
||||||
|
|
||||||
/// <summary>
|
|
||||||
/// 模型类型
|
|
||||||
/// </summary>
|
|
||||||
public string ModelType { get; set; }
|
|
||||||
|
|
||||||
/// <summary>
|
|
||||||
/// 模型展示状态
|
|
||||||
/// </summary>
|
|
||||||
public string ModelShow { get; set; }
|
|
||||||
|
|
||||||
/// <summary>
|
|
||||||
/// 系统提示
|
|
||||||
/// </summary>
|
|
||||||
public string SystemPrompt { get; set; }
|
|
||||||
|
|
||||||
/// <summary>
|
|
||||||
/// API 主机地址
|
|
||||||
/// </summary>
|
|
||||||
public string ApiHost { get; set; }
|
|
||||||
|
|
||||||
/// <summary>
|
|
||||||
/// API 密钥
|
|
||||||
/// </summary>
|
|
||||||
public string ApiKey { get; set; }
|
|
||||||
|
|
||||||
/// <summary>
|
/// <summary>
|
||||||
/// 备注信息
|
/// 备注信息
|
||||||
/// </summary>
|
/// </summary>
|
||||||
|
|||||||
@@ -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,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,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,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
|
||||||
|
};
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -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,7 +25,8 @@ 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()
|
||||||
@@ -36,12 +39,13 @@ public class DailyTaskService : ApplicationService
|
|||||||
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;
|
||||||
@@ -18,17 +22,18 @@ public class AiAccountService : ApplicationService
|
|||||||
private ISqlSugarRepository<AiUserExtraInfoEntity> _userRepository;
|
private ISqlSugarRepository<AiUserExtraInfoEntity> _userRepository;
|
||||||
private ISqlSugarRepository<AiRechargeAggregateRoot> _rechargeRepository;
|
private ISqlSugarRepository<AiRechargeAggregateRoot> _rechargeRepository;
|
||||||
private ISqlSugarRepository<PremiumPackageAggregateRoot> _premiumPackageRepository;
|
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<PremiumPackageAggregateRoot> premiumPackageRepository, ISqlSugarRepository<MessageAggregateRoot> messageRepository)
|
||||||
{
|
{
|
||||||
_accountService = accountService;
|
_accountService = accountService;
|
||||||
_userRepository = userRepository;
|
_userRepository = userRepository;
|
||||||
_rechargeRepository = rechargeRepository;
|
_rechargeRepository = rechargeRepository;
|
||||||
_premiumPackageRepository = premiumPackageRepository;
|
_premiumPackageRepository = premiumPackageRepository;
|
||||||
|
_messageRepository = messageRepository;
|
||||||
}
|
}
|
||||||
|
|
||||||
/// <summary>
|
/// <summary>
|
||||||
@@ -148,4 +153,90 @@ public class AiAccountService : ApplicationService
|
|||||||
|
|
||||||
return result;
|
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,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,30 +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)
|
.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,
|
|
||||||
ModelType = "1",
|
|
||||||
ModelShow = "0",
|
|
||||||
SystemPrompt = null,
|
|
||||||
ApiHost = null,
|
|
||||||
ApiKey = null,
|
|
||||||
Remark = x.Description,
|
Remark = x.Description,
|
||||||
IsPremiumPackage = PremiumPackageConst.ModeIds.Contains(x.ModelId)
|
IsPremiumPackage = x.IsPremium
|
||||||
}).ToListAsync();
|
}).ToListAsync();
|
||||||
return output;
|
return output;
|
||||||
}
|
}
|
||||||
@@ -124,7 +139,11 @@ public class AiChatService : ApplicationService
|
|||||||
}
|
}
|
||||||
|
|
||||||
//如果是尊享包服务,需要校验是是否尊享包足够
|
//如果是尊享包服务,需要校验是是否尊享包足够
|
||||||
if (CurrentUser.IsAuthenticated && PremiumPackageConst.ModeIds.Contains(input.Model))
|
if (CurrentUser.IsAuthenticated)
|
||||||
|
{
|
||||||
|
var isPremium = await _modelManager.IsPremiumModelAsync(input.Model);
|
||||||
|
|
||||||
|
if (isPremium)
|
||||||
{
|
{
|
||||||
// 检查尊享token包用量
|
// 检查尊享token包用量
|
||||||
var availableTokens = await _premiumPackageManager.GetAvailableTokensAsync(CurrentUser.GetId());
|
var availableTokens = await _premiumPackageManager.GetAvailableTokensAsync(CurrentUser.GetId());
|
||||||
@@ -133,13 +152,13 @@ public class AiChatService : ApplicationService
|
|||||||
throw new UserFriendlyException("尊享token包用量不足,请先购买尊享token包");
|
throw new UserFriendlyException("尊享token包用量不足,请先购买尊享token包");
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
}
|
||||||
|
|
||||||
//ai网关代理httpcontext
|
//ai网关代理httpcontext
|
||||||
await _aiGateWayManager.CompleteChatStreamForStatisticsAsync(_httpContextAccessor.HttpContext, input,
|
await _aiGateWayManager.CompleteChatStreamForStatisticsAsync(_httpContextAccessor.HttpContext, input,
|
||||||
CurrentUser.Id, sessionId, null, cancellationToken);
|
CurrentUser.Id, sessionId, null, CancellationToken.None);
|
||||||
}
|
}
|
||||||
|
|
||||||
|
|
||||||
/// <summary>
|
/// <summary>
|
||||||
/// 发送消息
|
/// 发送消息
|
||||||
/// </summary>
|
/// </summary>
|
||||||
@@ -173,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, 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;
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -1,10 +1,12 @@
|
|||||||
using Mapster;
|
using Mapster;
|
||||||
|
using Microsoft.AspNetCore.Mvc;
|
||||||
using SqlSugar;
|
using SqlSugar;
|
||||||
using Volo.Abp.Application.Dtos;
|
using Volo.Abp.Application.Dtos;
|
||||||
using Volo.Abp.Application.Services;
|
using Volo.Abp.Application.Services;
|
||||||
using Yi.Framework.AiHub.Application.Contracts.Dtos.Model;
|
using Yi.Framework.AiHub.Application.Contracts.Dtos.Model;
|
||||||
using Yi.Framework.AiHub.Application.Contracts.IServices;
|
using Yi.Framework.AiHub.Application.Contracts.IServices;
|
||||||
using Yi.Framework.AiHub.Domain.Entities.Model;
|
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.Consts;
|
||||||
using Yi.Framework.AiHub.Domain.Shared.Enums;
|
using Yi.Framework.AiHub.Domain.Shared.Enums;
|
||||||
using Yi.Framework.AiHub.Domain.Shared.Extensions;
|
using Yi.Framework.AiHub.Domain.Shared.Extensions;
|
||||||
@@ -18,10 +20,12 @@ namespace Yi.Framework.AiHub.Application.Services.Chat;
|
|||||||
public class ModelService : ApplicationService, IModelService
|
public class ModelService : ApplicationService, IModelService
|
||||||
{
|
{
|
||||||
private readonly ISqlSugarRepository<AiModelEntity, Guid> _modelRepository;
|
private readonly ISqlSugarRepository<AiModelEntity, Guid> _modelRepository;
|
||||||
|
private readonly ModelManager _modelManager;
|
||||||
|
|
||||||
public ModelService(ISqlSugarRepository<AiModelEntity, Guid> modelRepository)
|
public ModelService(ISqlSugarRepository<AiModelEntity, Guid> modelRepository, ModelManager modelManager)
|
||||||
{
|
{
|
||||||
_modelRepository = modelRepository;
|
_modelRepository = modelRepository;
|
||||||
|
_modelManager = modelManager;
|
||||||
}
|
}
|
||||||
|
|
||||||
/// <summary>
|
/// <summary>
|
||||||
@@ -32,8 +36,7 @@ public class ModelService : ApplicationService, IModelService
|
|||||||
RefAsync<int> total = 0;
|
RefAsync<int> total = 0;
|
||||||
|
|
||||||
// 查询所有未删除的模型,使用WhereIF动态添加筛选条件
|
// 查询所有未删除的模型,使用WhereIF动态添加筛选条件
|
||||||
var models = await _modelRepository._DbQueryable
|
var modelIds = (await _modelRepository._DbQueryable
|
||||||
.Where(x => !x.IsDeleted)
|
|
||||||
.WhereIF(!string.IsNullOrWhiteSpace(input.SearchKey), x =>
|
.WhereIF(!string.IsNullOrWhiteSpace(input.SearchKey), x =>
|
||||||
x.Name.Contains(input.SearchKey) || x.ModelId.Contains(input.SearchKey))
|
x.Name.Contains(input.SearchKey) || x.ModelId.Contains(input.SearchKey))
|
||||||
.WhereIF(input.ProviderNames is not null, x =>
|
.WhereIF(input.ProviderNames is not null, x =>
|
||||||
@@ -42,29 +45,30 @@ public class ModelService : ApplicationService, IModelService
|
|||||||
input.ModelTypes.Contains(x.ModelType))
|
input.ModelTypes.Contains(x.ModelType))
|
||||||
.WhereIF(input.ModelApiTypes is not null, x =>
|
.WhereIF(input.ModelApiTypes is not null, x =>
|
||||||
input.ModelApiTypes.Contains(x.ModelApiType))
|
input.ModelApiTypes.Contains(x.ModelApiType))
|
||||||
.WhereIF(input.IsPremiumOnly == true, x =>
|
.WhereIF(input.IsPremiumOnly == true, x => x.IsPremium)
|
||||||
PremiumPackageConst.ModeIds.Contains(x.ModelId))
|
.GroupBy(x => x.ModelId)
|
||||||
.OrderBy(x => x.OrderNum)
|
.Select(x => x.ModelId)
|
||||||
.OrderBy(x => x.Name)
|
.ToPageListAsync(input.SkipCount, input.MaxResultCount, total));
|
||||||
.ToPageListAsync(input.SkipCount, input.MaxResultCount, total);
|
|
||||||
|
|
||||||
// 转换为DTO
|
var entities = await _modelRepository._DbQueryable.Where(x => modelIds.Contains(x.ModelId))
|
||||||
var result = models.Select(model => new ModelLibraryDto
|
.OrderBy(x => x.OrderNum)
|
||||||
|
.OrderBy(x => x.Name).ToListAsync();
|
||||||
|
|
||||||
|
var output= entities.GroupBy(x => x.ModelId).Select(x => new ModelLibraryDto
|
||||||
{
|
{
|
||||||
ModelId = model.ModelId,
|
ModelId = x.First().ModelId,
|
||||||
Name = model.Name,
|
Name = x.First().Name,
|
||||||
Description = model.Description,
|
Description = x.First().Description,
|
||||||
ModelType = model.ModelType,
|
ModelType = x.First().ModelType,
|
||||||
ModelTypeName = model.ModelType.GetDescription(),
|
ModelApiTypes = x.Select(y => new ModelApiTypeOutput { ModelApiType = y.ModelApiType }).ToList(),
|
||||||
ModelApiType = model.ModelApiType,
|
MultiplierShow = x.First().MultiplierShow,
|
||||||
ModelApiTypeName = model.ModelApiType.GetDescription(),
|
ProviderName = x.First().ProviderName,
|
||||||
MultiplierShow = model.MultiplierShow,
|
IconUrl = x.First().IconUrl,
|
||||||
ProviderName = model.ProviderName,
|
IsPremium = x.First().IsPremium,
|
||||||
IconUrl = model.IconUrl,
|
OrderNum = x.First().OrderNum
|
||||||
IsPremium = PremiumPackageConst.ModeIds.Contains(model.ModelId)
|
|
||||||
}).ToList();
|
}).ToList();
|
||||||
|
|
||||||
return new PagedResultDto<ModelLibraryDto>(total, result);
|
return new PagedResultDto<ModelLibraryDto>(total, output);
|
||||||
}
|
}
|
||||||
|
|
||||||
/// <summary>
|
/// <summary>
|
||||||
@@ -76,11 +80,11 @@ public class ModelService : ApplicationService, IModelService
|
|||||||
.Where(x => !x.IsDeleted)
|
.Where(x => !x.IsDeleted)
|
||||||
.Where(x => !string.IsNullOrEmpty(x.ProviderName))
|
.Where(x => !string.IsNullOrEmpty(x.ProviderName))
|
||||||
.GroupBy(x => x.ProviderName)
|
.GroupBy(x => x.ProviderName)
|
||||||
.OrderBy(x => x.ProviderName)
|
.OrderBy(x => x.OrderNum)
|
||||||
.Select(x => x.ProviderName)
|
.Select(x => x.ProviderName)
|
||||||
.ToListAsync();
|
.ToListAsync();
|
||||||
|
|
||||||
return providers;
|
return providers!;
|
||||||
}
|
}
|
||||||
|
|
||||||
/// <summary>
|
/// <summary>
|
||||||
@@ -114,4 +118,13 @@ public class ModelService : ApplicationService, IModelService
|
|||||||
|
|
||||||
return Task.FromResult(options);
|
return Task.FromResult(options);
|
||||||
}
|
}
|
||||||
|
|
||||||
|
/// <summary>
|
||||||
|
/// 清除尊享模型ID缓存
|
||||||
|
/// </summary>
|
||||||
|
[HttpPost("model/clear-premium-cache")]
|
||||||
|
public async Task ClearPremiumModelCacheAsync()
|
||||||
|
{
|
||||||
|
await _modelManager.ClearPremiumModelIdsCacheAsync();
|
||||||
|
}
|
||||||
}
|
}
|
||||||
@@ -7,8 +7,10 @@ using Volo.Abp.Application.Services;
|
|||||||
using Volo.Abp.Users;
|
using Volo.Abp.Users;
|
||||||
using Yi.Framework.AiHub.Application.Contracts.Dtos.Token;
|
using Yi.Framework.AiHub.Application.Contracts.Dtos.Token;
|
||||||
using Yi.Framework.AiHub.Domain.Entities;
|
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.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.AiHub.Domain.Shared.Consts;
|
||||||
using Yi.Framework.Ddd.Application.Contracts;
|
using Yi.Framework.Ddd.Application.Contracts;
|
||||||
using Yi.Framework.SqlSugarCore.Abstractions;
|
using Yi.Framework.SqlSugarCore.Abstractions;
|
||||||
@@ -23,13 +25,16 @@ public class TokenService : ApplicationService
|
|||||||
{
|
{
|
||||||
private readonly ISqlSugarRepository<TokenAggregateRoot> _tokenRepository;
|
private readonly ISqlSugarRepository<TokenAggregateRoot> _tokenRepository;
|
||||||
private readonly ISqlSugarRepository<UsageStatisticsAggregateRoot> _usageStatisticsRepository;
|
private readonly ISqlSugarRepository<UsageStatisticsAggregateRoot> _usageStatisticsRepository;
|
||||||
|
private readonly ModelManager _modelManager;
|
||||||
|
|
||||||
public TokenService(
|
public TokenService(
|
||||||
ISqlSugarRepository<TokenAggregateRoot> tokenRepository,
|
ISqlSugarRepository<TokenAggregateRoot> tokenRepository,
|
||||||
ISqlSugarRepository<UsageStatisticsAggregateRoot> usageStatisticsRepository)
|
ISqlSugarRepository<UsageStatisticsAggregateRoot> usageStatisticsRepository,
|
||||||
|
ModelManager modelManager)
|
||||||
{
|
{
|
||||||
_tokenRepository = tokenRepository;
|
_tokenRepository = tokenRepository;
|
||||||
_usageStatisticsRepository = usageStatisticsRepository;
|
_usageStatisticsRepository = usageStatisticsRepository;
|
||||||
|
_modelManager = modelManager;
|
||||||
}
|
}
|
||||||
|
|
||||||
/// <summary>
|
/// <summary>
|
||||||
@@ -51,8 +56,8 @@ public class TokenService : ApplicationService
|
|||||||
return new PagedResultDto<TokenGetListOutputDto>();
|
return new PagedResultDto<TokenGetListOutputDto>();
|
||||||
}
|
}
|
||||||
|
|
||||||
// 获取尊享包模型ID列表
|
// 通过ModelManager获取尊享包模型ID列表
|
||||||
var premiumModelIds = PremiumPackageConst.ModeIds;
|
var premiumModelIds = await _modelManager.GetPremiumModelIdsAsync();
|
||||||
|
|
||||||
// 批量查询所有Token的尊享包已使用额度
|
// 批量查询所有Token的尊享包已使用额度
|
||||||
var tokenIds = tokens.Select(t => t.Id).ToList();
|
var tokenIds = tokens.Select(t => t.Id).ToList();
|
||||||
@@ -86,7 +91,7 @@ public class TokenService : ApplicationService
|
|||||||
}
|
}
|
||||||
|
|
||||||
[HttpGet("token/select-list")]
|
[HttpGet("token/select-list")]
|
||||||
public async Task<List<TokenSelectListOutputDto>> GetSelectListAsync()
|
public async Task<List<TokenSelectListOutputDto>> GetSelectListAsync([FromQuery] bool? includeDefault = true)
|
||||||
{
|
{
|
||||||
var userId = CurrentUser.GetId();
|
var userId = CurrentUser.GetId();
|
||||||
var tokens = await _tokenRepository._DbQueryable
|
var tokens = await _tokenRepository._DbQueryable
|
||||||
@@ -100,12 +105,16 @@ public class TokenService : ApplicationService
|
|||||||
IsDisabled = x.IsDisabled
|
IsDisabled = x.IsDisabled
|
||||||
}).ToListAsync();
|
}).ToListAsync();
|
||||||
|
|
||||||
tokens.Insert(0,new TokenSelectListOutputDto
|
if (includeDefault == true)
|
||||||
|
{
|
||||||
|
tokens.Insert(0, new TokenSelectListOutputDto
|
||||||
{
|
{
|
||||||
TokenId = Guid.Empty,
|
TokenId = Guid.Empty,
|
||||||
Name = "默认",
|
Name = "默认",
|
||||||
IsDisabled = false
|
IsDisabled = false
|
||||||
});
|
});
|
||||||
|
}
|
||||||
|
|
||||||
return tokens;
|
return tokens;
|
||||||
}
|
}
|
||||||
|
|
||||||
|
|||||||
@@ -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;
|
||||||
@@ -25,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>
|
||||||
@@ -62,7 +67,9 @@ public class OpenApiService : ApplicationService
|
|||||||
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);
|
||||||
@@ -76,13 +83,13 @@ 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, tokenId, cancellationToken);
|
userId, null, tokenId,CancellationToken.None);
|
||||||
}
|
}
|
||||||
else
|
else
|
||||||
{
|
{
|
||||||
await _aiGateWayManager.CompleteChatForStatisticsAsync(_httpContextAccessor.HttpContext, input, userId,
|
await _aiGateWayManager.CompleteChatForStatisticsAsync(_httpContextAccessor.HttpContext, input, userId,
|
||||||
null, tokenId,
|
null, tokenId,
|
||||||
cancellationToken);
|
CancellationToken.None);
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
@@ -190,14 +197,14 @@ public class OpenApiService : ApplicationService
|
|||||||
{
|
{
|
||||||
await _aiGateWayManager.AnthropicCompleteChatStreamForStatisticsAsync(_httpContextAccessor.HttpContext,
|
await _aiGateWayManager.AnthropicCompleteChatStreamForStatisticsAsync(_httpContextAccessor.HttpContext,
|
||||||
input,
|
input,
|
||||||
userId, null, tokenId, cancellationToken);
|
userId, null, tokenId, CancellationToken.None);
|
||||||
}
|
}
|
||||||
else
|
else
|
||||||
{
|
{
|
||||||
await _aiGateWayManager.AnthropicCompleteChatForStatisticsAsync(_httpContextAccessor.HttpContext, input,
|
await _aiGateWayManager.AnthropicCompleteChatForStatisticsAsync(_httpContextAccessor.HttpContext, input,
|
||||||
userId,
|
userId,
|
||||||
null, tokenId,
|
null, tokenId,
|
||||||
cancellationToken);
|
CancellationToken.None);
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
@@ -242,18 +249,77 @@ public class OpenApiService : ApplicationService
|
|||||||
{
|
{
|
||||||
await _aiGateWayManager.OpenAiResponsesStreamForStatisticsAsync(_httpContextAccessor.HttpContext,
|
await _aiGateWayManager.OpenAiResponsesStreamForStatisticsAsync(_httpContextAccessor.HttpContext,
|
||||||
input,
|
input,
|
||||||
userId, null, tokenId, cancellationToken);
|
userId, null, tokenId, CancellationToken.None);
|
||||||
}
|
}
|
||||||
else
|
else
|
||||||
{
|
{
|
||||||
await _aiGateWayManager.OpenAiResponsesAsyncForStatisticsAsync(_httpContextAccessor.HttpContext, input,
|
await _aiGateWayManager.OpenAiResponsesAsyncForStatisticsAsync(_httpContextAccessor.HttpContext, input,
|
||||||
userId,
|
userId,
|
||||||
null, tokenId,
|
null, tokenId,
|
||||||
cancellationToken);
|
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)
|
||||||
@@ -265,6 +331,13 @@ 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) &&
|
if (!string.IsNullOrWhiteSpace(authHeader) &&
|
||||||
|
|||||||
@@ -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
|
||||||
|
|||||||
@@ -9,8 +9,10 @@ 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.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.AiHub.Domain.Shared.Consts;
|
||||||
using Yi.Framework.Ddd.Application.Contracts;
|
using Yi.Framework.Ddd.Application.Contracts;
|
||||||
using Yi.Framework.SqlSugarCore.Abstractions;
|
using Yi.Framework.SqlSugarCore.Abstractions;
|
||||||
@@ -27,17 +29,19 @@ public class UsageStatisticsService : ApplicationService, IUsageStatisticsServic
|
|||||||
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 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)
|
ISqlSugarRepository<TokenAggregateRoot> tokenRepository,
|
||||||
|
ModelManager modelManager)
|
||||||
{
|
{
|
||||||
_messageRepository = messageRepository;
|
_messageRepository = messageRepository;
|
||||||
_usageStatisticsRepository = usageStatisticsRepository;
|
_usageStatisticsRepository = usageStatisticsRepository;
|
||||||
_premiumPackageRepository = premiumPackageRepository;
|
_premiumPackageRepository = premiumPackageRepository;
|
||||||
_tokenRepository = tokenRepository;
|
_tokenRepository = tokenRepository;
|
||||||
|
_modelManager = modelManager;
|
||||||
}
|
}
|
||||||
|
|
||||||
/// <summary>
|
/// <summary>
|
||||||
@@ -181,7 +185,9 @@ public class UsageStatisticsService : ApplicationService, IUsageStatisticsServic
|
|||||||
public async Task<List<TokenPremiumUsageDto>> GetPremiumTokenUsageByTokenAsync()
|
public async Task<List<TokenPremiumUsageDto>> GetPremiumTokenUsageByTokenAsync()
|
||||||
{
|
{
|
||||||
var userId = CurrentUser.GetId();
|
var userId = CurrentUser.GetId();
|
||||||
var premiumModelIds = PremiumPackageConst.ModeIds;
|
|
||||||
|
// 通过ModelManager获取所有尊享模型的ModelId列表
|
||||||
|
var premiumModelIds = await _modelManager.GetPremiumModelIdsAsync();
|
||||||
|
|
||||||
// 从UsageStatistics表获取尊享模型的token消耗统计(按TokenId聚合)
|
// 从UsageStatistics表获取尊享模型的token消耗统计(按TokenId聚合)
|
||||||
var tokenUsages = await _usageStatisticsRepository._DbQueryable
|
var tokenUsages = await _usageStatisticsRepository._DbQueryable
|
||||||
|
|||||||
@@ -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; }
|
||||||
|
}
|
||||||
@@ -10,6 +10,16 @@ public class PremiumPackageConst
|
|||||||
"claude-haiku-4-5-20251001",
|
"claude-haiku-4-5-20251001",
|
||||||
"claude-opus-4-5-20251101",
|
"claude-opus-4-5-20251101",
|
||||||
"gemini-3-pro-preview",
|
"gemini-3-pro-preview",
|
||||||
"gpt-5.1-codex-max"
|
"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",
|
||||||
];
|
];
|
||||||
}
|
}
|
||||||
@@ -12,7 +12,7 @@ public sealed class AnthropicInput
|
|||||||
|
|
||||||
[JsonPropertyName("max_tokens")] public int? MaxTokens { get; set; }
|
[JsonPropertyName("max_tokens")] public int? MaxTokens { get; set; }
|
||||||
|
|
||||||
[JsonPropertyName("messages")] public JsonElement? Messages { get; set; }
|
[JsonPropertyName("messages")] public IList<AnthropicMessageInput> Messages { get; set; }
|
||||||
|
|
||||||
[JsonPropertyName("tools")] public IList<AnthropicMessageTool>? Tools { get; set; }
|
[JsonPropertyName("tools")] public IList<AnthropicMessageTool>? Tools { get; set; }
|
||||||
|
|
||||||
|
|||||||
@@ -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);
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -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>();
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -110,10 +110,23 @@ public enum GoodsTypeEnum
|
|||||||
PremiumPackage5000W = 101,
|
PremiumPackage5000W = 101,
|
||||||
|
|
||||||
[Price(248.9, 0, 3500)]
|
[Price(248.9, 0, 3500)]
|
||||||
[DisplayName("YiXinPremiumPackage 10000W Tokens", "1亿Tokens(推荐)", "极致性价比")]
|
[DisplayName("YiXinPremiumPackage 10000W Tokens", "1亿Tokens", "极致性价比")]
|
||||||
[GoodsCategory(GoodsCategoryType.PremiumPackage)]
|
[GoodsCategory(GoodsCategoryType.PremiumPackage)]
|
||||||
[TokenAmount(100000000)]
|
[TokenAmount(100000000)]
|
||||||
PremiumPackage10000W = 102,
|
PremiumPackage10000W = 102,
|
||||||
|
|
||||||
|
|
||||||
|
[Price(238.9, 0, 3500)]
|
||||||
|
[DisplayName("YiXinPremiumPackage 10000W Tokens", "1亿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
|
||||||
@@ -259,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>
|
||||||
@@ -271,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);
|
||||||
}
|
}
|
||||||
|
|
||||||
|
|||||||
@@ -11,5 +11,8 @@ public enum ModelApiTypeEnum
|
|||||||
Claude,
|
Claude,
|
||||||
|
|
||||||
[Description("Response")]
|
[Description("Response")]
|
||||||
Response
|
Response,
|
||||||
|
|
||||||
|
[Description("GenerateContent")]
|
||||||
|
GenerateContent
|
||||||
}
|
}
|
||||||
@@ -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
|
||||||
|
}
|
||||||
@@ -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>
|
||||||
|
|
||||||
|
|||||||
@@ -0,0 +1,30 @@
|
|||||||
|
using System.Text.Json;
|
||||||
|
using Yi.Framework.AiHub.Domain.Shared.Dtos;
|
||||||
|
using Yi.Framework.AiHub.Domain.Shared.Dtos.OpenAi;
|
||||||
|
|
||||||
|
namespace Yi.Framework.AiHub.Domain.AiGateWay;
|
||||||
|
|
||||||
|
public interface IGeminiGenerateContentService
|
||||||
|
{
|
||||||
|
/// <summary>
|
||||||
|
/// 聊天完成-流式
|
||||||
|
/// </summary>
|
||||||
|
/// <param name="aiModelDescribe"></param>
|
||||||
|
/// <param name="input"></param>
|
||||||
|
/// <param name="cancellationToken"></param>
|
||||||
|
/// <returns></returns>
|
||||||
|
public IAsyncEnumerable<JsonElement?> GenerateContentStreamAsync(AiModelDescribe aiModelDescribe,
|
||||||
|
JsonElement input,
|
||||||
|
CancellationToken cancellationToken);
|
||||||
|
|
||||||
|
/// <summary>
|
||||||
|
/// 聊天完成-非流式
|
||||||
|
/// </summary>
|
||||||
|
/// <param name="aiModelDescribe"></param>
|
||||||
|
/// <param name="input"></param>
|
||||||
|
/// <param name="cancellationToken"></param>
|
||||||
|
/// <returns></returns>
|
||||||
|
public Task<JsonElement> GenerateContentAsync(AiModelDescribe aiModelDescribe,
|
||||||
|
JsonElement input,
|
||||||
|
CancellationToken cancellationToken);
|
||||||
|
}
|
||||||
@@ -107,35 +107,6 @@ public class AzureDatabricksChatCompletionsService(ILogger<AzureDatabricksChatCo
|
|||||||
{
|
{
|
||||||
continue;
|
continue;
|
||||||
}
|
}
|
||||||
|
|
||||||
// var content = result?.Choices?.FirstOrDefault()?.Delta;
|
|
||||||
//
|
|
||||||
// if (first && content?.Content == OpenAIConstant.ThinkStart)
|
|
||||||
// {
|
|
||||||
// isThink = true;
|
|
||||||
// continue;
|
|
||||||
// // 需要将content的内容转换到其他字段
|
|
||||||
// }
|
|
||||||
//
|
|
||||||
// if (isThink && content?.Content?.Contains(OpenAIConstant.ThinkEnd) == true)
|
|
||||||
// {
|
|
||||||
// isThink = false;
|
|
||||||
// // 需要将content的内容转换到其他字段
|
|
||||||
// continue;
|
|
||||||
// }
|
|
||||||
//
|
|
||||||
// if (isThink && result?.Choices != null)
|
|
||||||
// {
|
|
||||||
// // 需要将content的内容转换到其他字段
|
|
||||||
// foreach (var choice in result.Choices)
|
|
||||||
// {
|
|
||||||
// choice.Delta.ReasoningContent = choice.Delta.Content;
|
|
||||||
// choice.Delta.Content = string.Empty;
|
|
||||||
// }
|
|
||||||
// }
|
|
||||||
//
|
|
||||||
// first = false;
|
|
||||||
|
|
||||||
yield return result;
|
yield return result;
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -9,7 +9,9 @@ using Yi.Framework.AiHub.Domain.Shared.Dtos.OpenAi;
|
|||||||
|
|
||||||
namespace Yi.Framework.AiHub.Domain.AiGateWay.Impl.ThorCustomOpenAI.Chats;
|
namespace Yi.Framework.AiHub.Domain.AiGateWay.Impl.ThorCustomOpenAI.Chats;
|
||||||
|
|
||||||
public sealed class OpenAiChatCompletionsService(ILogger<OpenAiChatCompletionsService> logger,IHttpClientFactory httpClientFactory)
|
public sealed class OpenAiChatCompletionsService(
|
||||||
|
ILogger<OpenAiChatCompletionsService> logger,
|
||||||
|
IHttpClientFactory httpClientFactory)
|
||||||
: IChatCompletionService
|
: IChatCompletionService
|
||||||
{
|
{
|
||||||
public async IAsyncEnumerable<ThorChatCompletionsResponse> CompleteChatStreamAsync(AiModelDescribe options,
|
public async IAsyncEnumerable<ThorChatCompletionsResponse> CompleteChatStreamAsync(AiModelDescribe options,
|
||||||
@@ -19,8 +21,18 @@ public sealed class OpenAiChatCompletionsService(ILogger<OpenAiChatCompletionsSe
|
|||||||
using var openai =
|
using var openai =
|
||||||
Activity.Current?.Source.StartActivity("OpenAI 对话流式补全");
|
Activity.Current?.Source.StartActivity("OpenAI 对话流式补全");
|
||||||
|
|
||||||
|
var endpoint = options?.Endpoint.TrimEnd('/');
|
||||||
|
|
||||||
|
//兼容 v1结尾
|
||||||
|
if (endpoint != null && endpoint.EndsWith("/v1", StringComparison.OrdinalIgnoreCase))
|
||||||
|
{
|
||||||
|
endpoint = endpoint.Substring(0, endpoint.Length - "/v1".Length);
|
||||||
|
}
|
||||||
|
|
||||||
|
var requestUri = endpoint + "/v1/chat/completions";
|
||||||
|
|
||||||
var response = await httpClientFactory.CreateClient().HttpRequestRaw(
|
var response = await httpClientFactory.CreateClient().HttpRequestRaw(
|
||||||
options?.Endpoint.TrimEnd('/') + "/chat/completions",
|
requestUri,
|
||||||
chatCompletionCreate, options.ApiKey);
|
chatCompletionCreate, options.ApiKey);
|
||||||
|
|
||||||
openai?.SetTag("Model", chatCompletionCreate.Model);
|
openai?.SetTag("Model", chatCompletionCreate.Model);
|
||||||
@@ -130,8 +142,16 @@ public sealed class OpenAiChatCompletionsService(ILogger<OpenAiChatCompletionsSe
|
|||||||
using var openai =
|
using var openai =
|
||||||
Activity.Current?.Source.StartActivity("OpenAI 对话补全");
|
Activity.Current?.Source.StartActivity("OpenAI 对话补全");
|
||||||
|
|
||||||
|
var endpoint = options?.Endpoint.TrimEnd('/');
|
||||||
|
|
||||||
|
//兼容 v1结尾
|
||||||
|
if (endpoint != null && endpoint.EndsWith("/v1", StringComparison.OrdinalIgnoreCase))
|
||||||
|
{
|
||||||
|
endpoint = endpoint.Substring(0, endpoint.Length - "/v1".Length);
|
||||||
|
}
|
||||||
|
var requestUri = endpoint + "/v1/chat/completions";
|
||||||
var response = await httpClientFactory.CreateClient().PostJsonAsync(
|
var response = await httpClientFactory.CreateClient().PostJsonAsync(
|
||||||
options?.Endpoint.TrimEnd('/') + "/chat/completions",
|
requestUri,
|
||||||
chatCompletionCreate, options.ApiKey).ConfigureAwait(false);
|
chatCompletionCreate, options.ApiKey).ConfigureAwait(false);
|
||||||
|
|
||||||
openai?.SetTag("Model", chatCompletionCreate.Model);
|
openai?.SetTag("Model", chatCompletionCreate.Model);
|
||||||
@@ -152,7 +172,8 @@ public sealed class OpenAiChatCompletionsService(ILogger<OpenAiChatCompletionsSe
|
|||||||
if (response.StatusCode >= HttpStatusCode.BadRequest)
|
if (response.StatusCode >= HttpStatusCode.BadRequest)
|
||||||
{
|
{
|
||||||
var error = await response.Content.ReadAsStringAsync(cancellationToken).ConfigureAwait(false);
|
var error = await response.Content.ReadAsStringAsync(cancellationToken).ConfigureAwait(false);
|
||||||
logger.LogError("OpenAI对话异常 请求地址:{Address}, StatusCode: {StatusCode} Response: {Response}", options.Endpoint,
|
logger.LogError("OpenAI对话异常 请求地址:{Address}, StatusCode: {StatusCode} Response: {Response}",
|
||||||
|
options.Endpoint,
|
||||||
response.StatusCode, error);
|
response.StatusCode, error);
|
||||||
|
|
||||||
throw new BusinessException("OpenAI对话异常", response.StatusCode.ToString());
|
throw new BusinessException("OpenAI对话异常", response.StatusCode.ToString());
|
||||||
|
|||||||
@@ -22,7 +22,16 @@ public class OpenAiResponseService(ILogger<OpenAiResponseService> logger,IHttpCl
|
|||||||
|
|
||||||
var client = httpClientFactory.CreateClient();
|
var client = httpClientFactory.CreateClient();
|
||||||
|
|
||||||
var response = await client.HttpRequestRaw(options.Endpoint.TrimEnd('/') + "/responses", input, options.ApiKey);
|
var endpoint = options?.Endpoint.TrimEnd('/');
|
||||||
|
|
||||||
|
//兼容 v1结尾
|
||||||
|
if (endpoint != null && endpoint.EndsWith("/v1", StringComparison.OrdinalIgnoreCase))
|
||||||
|
{
|
||||||
|
endpoint = endpoint.Substring(0, endpoint.Length - "/v1".Length);
|
||||||
|
}
|
||||||
|
var requestUri = endpoint + "/v1/responses";
|
||||||
|
|
||||||
|
var response = await client.HttpRequestRaw(requestUri, input, options.ApiKey);
|
||||||
|
|
||||||
openai?.SetTag("Model", input.Model);
|
openai?.SetTag("Model", input.Model);
|
||||||
openai?.SetTag("Response", response.StatusCode.ToString());
|
openai?.SetTag("Response", response.StatusCode.ToString());
|
||||||
@@ -86,8 +95,17 @@ public class OpenAiResponseService(ILogger<OpenAiResponseService> logger,IHttpCl
|
|||||||
using var openai =
|
using var openai =
|
||||||
Activity.Current?.Source.StartActivity("OpenAI 响应");
|
Activity.Current?.Source.StartActivity("OpenAI 响应");
|
||||||
|
|
||||||
|
var endpoint = options?.Endpoint.TrimEnd('/');
|
||||||
|
|
||||||
|
//兼容 v1结尾
|
||||||
|
if (endpoint != null && endpoint.EndsWith("/v1", StringComparison.OrdinalIgnoreCase))
|
||||||
|
{
|
||||||
|
endpoint = endpoint.Substring(0, endpoint.Length - "/v1".Length);
|
||||||
|
}
|
||||||
|
var requestUri = endpoint + "/v1/responses";
|
||||||
|
|
||||||
var response = await httpClientFactory.CreateClient().PostJsonAsync(
|
var response = await httpClientFactory.CreateClient().PostJsonAsync(
|
||||||
options?.Endpoint.TrimEnd('/') + "/responses",
|
requestUri,
|
||||||
chatCompletionCreate, options.ApiKey).ConfigureAwait(false);
|
chatCompletionCreate, options.ApiKey).ConfigureAwait(false);
|
||||||
|
|
||||||
openai?.SetTag("Model", chatCompletionCreate.Model);
|
openai?.SetTag("Model", chatCompletionCreate.Model);
|
||||||
|
|||||||
@@ -24,8 +24,16 @@ public sealed class DeepSeekChatCompletionsService(ILogger<DeepSeekChatCompletio
|
|||||||
using var openai =
|
using var openai =
|
||||||
Activity.Current?.Source.StartActivity("OpenAI 对话流式补全");
|
Activity.Current?.Source.StartActivity("OpenAI 对话流式补全");
|
||||||
|
|
||||||
|
var endpoint = options?.Endpoint.TrimEnd('/');
|
||||||
|
//兼容 v1结尾
|
||||||
|
if (endpoint != null && endpoint.EndsWith("/v1", StringComparison.OrdinalIgnoreCase))
|
||||||
|
{
|
||||||
|
endpoint = endpoint.Substring(0, endpoint.Length - "/v1".Length);
|
||||||
|
}
|
||||||
|
var requestUri = endpoint + "/v1/chat/completions";
|
||||||
|
|
||||||
var response = await httpClientFactory.CreateClient().HttpRequestRaw(
|
var response = await httpClientFactory.CreateClient().HttpRequestRaw(
|
||||||
options?.Endpoint.TrimEnd('/') + "/chat/completions",
|
requestUri,
|
||||||
chatCompletionCreate, options.ApiKey);
|
chatCompletionCreate, options.ApiKey);
|
||||||
|
|
||||||
openai?.SetTag("Model", chatCompletionCreate.Model);
|
openai?.SetTag("Model", chatCompletionCreate.Model);
|
||||||
@@ -92,40 +100,6 @@ public sealed class DeepSeekChatCompletionsService(ILogger<DeepSeekChatCompletio
|
|||||||
|
|
||||||
var result = JsonSerializer.Deserialize<ThorChatCompletionsResponse>(line,
|
var result = JsonSerializer.Deserialize<ThorChatCompletionsResponse>(line,
|
||||||
ThorJsonSerializer.DefaultOptions);
|
ThorJsonSerializer.DefaultOptions);
|
||||||
|
|
||||||
// var content = result?.Choices?.FirstOrDefault()?.Delta;
|
|
||||||
//
|
|
||||||
// // if (first && string.IsNullOrWhiteSpace(content?.Content) && string.IsNullOrEmpty(content?.ReasoningContent))
|
|
||||||
// // {
|
|
||||||
// // continue;
|
|
||||||
// // }
|
|
||||||
//
|
|
||||||
// if (first && content.Content == OpenAIConstant.ThinkStart)
|
|
||||||
// {
|
|
||||||
// isThink = true;
|
|
||||||
// //continue;
|
|
||||||
// // 需要将content的内容转换到其他字段
|
|
||||||
// }
|
|
||||||
//
|
|
||||||
// if (isThink && content.Content.Contains(OpenAIConstant.ThinkEnd))
|
|
||||||
// {
|
|
||||||
// isThink = false;
|
|
||||||
// // 需要将content的内容转换到其他字段
|
|
||||||
// //continue;
|
|
||||||
// }
|
|
||||||
//
|
|
||||||
// if (isThink)
|
|
||||||
// {
|
|
||||||
// // 需要将content的内容转换到其他字段
|
|
||||||
// foreach (var choice in result.Choices)
|
|
||||||
// {
|
|
||||||
// //choice.Delta.ReasoningContent = choice.Delta.Content;
|
|
||||||
// //choice.Delta.Content = string.Empty;
|
|
||||||
// }
|
|
||||||
// }
|
|
||||||
|
|
||||||
// first = false;
|
|
||||||
|
|
||||||
yield return result;
|
yield return result;
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
@@ -142,8 +116,16 @@ public sealed class DeepSeekChatCompletionsService(ILogger<DeepSeekChatCompletio
|
|||||||
options.Endpoint = "https://api.deepseek.com/v1";
|
options.Endpoint = "https://api.deepseek.com/v1";
|
||||||
}
|
}
|
||||||
|
|
||||||
|
var endpoint = options?.Endpoint.TrimEnd('/');
|
||||||
|
//兼容 v1结尾
|
||||||
|
if (endpoint != null && endpoint.EndsWith("/v1", StringComparison.OrdinalIgnoreCase))
|
||||||
|
{
|
||||||
|
endpoint = endpoint.Substring(0, endpoint.Length - "/v1".Length);
|
||||||
|
}
|
||||||
|
var requestUri = endpoint + "/v1/chat/completions";
|
||||||
|
|
||||||
var response = await httpClientFactory.CreateClient().PostJsonAsync(
|
var response = await httpClientFactory.CreateClient().PostJsonAsync(
|
||||||
options?.Endpoint.TrimEnd('/') + "/chat/completions",
|
requestUri,
|
||||||
chatCompletionCreate, options.ApiKey).ConfigureAwait(false);
|
chatCompletionCreate, options.ApiKey).ConfigureAwait(false);
|
||||||
|
|
||||||
openai?.SetTag("Model", chatCompletionCreate.Model);
|
openai?.SetTag("Model", chatCompletionCreate.Model);
|
||||||
|
|||||||
@@ -0,0 +1,101 @@
|
|||||||
|
using System.Diagnostics;
|
||||||
|
using System.Net;
|
||||||
|
using System.Net.Http.Json;
|
||||||
|
using System.Text.Json;
|
||||||
|
using Microsoft.Extensions.Logging;
|
||||||
|
using Yi.Framework.AiHub.Domain.AiGateWay.Exceptions;
|
||||||
|
using Yi.Framework.AiHub.Domain.Shared.Dtos;
|
||||||
|
using Yi.Framework.AiHub.Domain.Shared.Dtos.OpenAi;
|
||||||
|
using Yi.Framework.AiHub.Domain.Shared.Dtos.OpenAi.Responses;
|
||||||
|
|
||||||
|
namespace Yi.Framework.AiHub.Domain.AiGateWay.Impl.ThorGemini.Chats;
|
||||||
|
|
||||||
|
public class GeminiGenerateContentService(
|
||||||
|
ILogger<GeminiGenerateContentService> logger,
|
||||||
|
IHttpClientFactory httpClientFactory) : IGeminiGenerateContentService
|
||||||
|
{
|
||||||
|
public async IAsyncEnumerable<JsonElement?> GenerateContentStreamAsync(AiModelDescribe options, JsonElement input,
|
||||||
|
CancellationToken cancellationToken)
|
||||||
|
{
|
||||||
|
var response = await httpClientFactory.CreateClient().PostJsonAsync(
|
||||||
|
options?.Endpoint.TrimEnd('/') + $"/v1beta/models/{options.ModelId}:streamGenerateContent?alt=sse",
|
||||||
|
input, null, new Dictionary<string, string>()
|
||||||
|
{
|
||||||
|
{ "x-goog-api-key", options.ApiKey }
|
||||||
|
}).ConfigureAwait(false);
|
||||||
|
|
||||||
|
|
||||||
|
// 大于等于400的状态码都认为是异常
|
||||||
|
if (response.StatusCode >= HttpStatusCode.BadRequest)
|
||||||
|
{
|
||||||
|
var error = await response.Content.ReadAsStringAsync(cancellationToken).ConfigureAwait(false);
|
||||||
|
logger.LogError("Gemini生成异常 请求地址:{Address}, StatusCode: {StatusCode} Response: {Response}",
|
||||||
|
options.Endpoint,
|
||||||
|
response.StatusCode, error);
|
||||||
|
|
||||||
|
throw new Exception("Gemini生成异常" + response.StatusCode);
|
||||||
|
}
|
||||||
|
|
||||||
|
using var stream = new StreamReader(await response.Content.ReadAsStreamAsync(cancellationToken));
|
||||||
|
|
||||||
|
using StreamReader reader = new(await response.Content.ReadAsStreamAsync(cancellationToken));
|
||||||
|
string? line = string.Empty;
|
||||||
|
|
||||||
|
while ((line = await reader.ReadLineAsync(cancellationToken).ConfigureAwait(false)) != null)
|
||||||
|
{
|
||||||
|
line += Environment.NewLine;
|
||||||
|
if (string.IsNullOrWhiteSpace(line))
|
||||||
|
{
|
||||||
|
continue;
|
||||||
|
}
|
||||||
|
|
||||||
|
if (!line.StartsWith(OpenAIConstant.Data)) continue;
|
||||||
|
|
||||||
|
var data = line[OpenAIConstant.Data.Length..].Trim();
|
||||||
|
|
||||||
|
var result = JsonSerializer.Deserialize<JsonElement>(data,
|
||||||
|
ThorJsonSerializer.DefaultOptions);
|
||||||
|
|
||||||
|
yield return result;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
public async Task<JsonElement> GenerateContentAsync(AiModelDescribe options, JsonElement input,
|
||||||
|
CancellationToken cancellationToken)
|
||||||
|
{
|
||||||
|
var response = await httpClientFactory.CreateClient().PostJsonAsync(
|
||||||
|
options?.Endpoint.TrimEnd('/') + $"/v1beta/models/{options.ModelId}:generateContent",
|
||||||
|
input, null, new Dictionary<string, string>()
|
||||||
|
{
|
||||||
|
{ "x-goog-api-key", options.ApiKey }
|
||||||
|
}).ConfigureAwait(false);
|
||||||
|
|
||||||
|
if (response.StatusCode == HttpStatusCode.Unauthorized)
|
||||||
|
{
|
||||||
|
throw new BusinessException("渠道未登录,请联系管理人员", "401");
|
||||||
|
}
|
||||||
|
|
||||||
|
// 如果限流则抛出限流异常
|
||||||
|
if (response.StatusCode == HttpStatusCode.TooManyRequests)
|
||||||
|
{
|
||||||
|
throw new ThorRateLimitException();
|
||||||
|
}
|
||||||
|
|
||||||
|
// 大于等于400的状态码都认为是异常
|
||||||
|
if (response.StatusCode >= HttpStatusCode.BadRequest)
|
||||||
|
{
|
||||||
|
var error = await response.Content.ReadAsStringAsync(cancellationToken).ConfigureAwait(false);
|
||||||
|
logger.LogError("Gemini 生成异常 请求地址:{Address}, StatusCode: {StatusCode} Response: {Response}",
|
||||||
|
options.Endpoint,
|
||||||
|
response.StatusCode, error);
|
||||||
|
|
||||||
|
throw new BusinessException("Gemini 生成异常", response.StatusCode.ToString());
|
||||||
|
}
|
||||||
|
|
||||||
|
var result =
|
||||||
|
await response.Content.ReadFromJsonAsync<JsonElement>(
|
||||||
|
cancellationToken: cancellationToken).ConfigureAwait(false);
|
||||||
|
|
||||||
|
return result;
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -0,0 +1,23 @@
|
|||||||
|
using Yi.Framework.AiHub.Domain.Shared.Dtos.OpenAi;
|
||||||
|
|
||||||
|
namespace Yi.Framework.AiHub.Domain.AiGateWay;
|
||||||
|
|
||||||
|
public static class SupplementalMultiplierHelper
|
||||||
|
{
|
||||||
|
public static void SetSupplementalMultiplier(this ThorUsageResponse? usage,decimal multiplier)
|
||||||
|
{
|
||||||
|
if (usage is not null)
|
||||||
|
{
|
||||||
|
usage.InputTokens =
|
||||||
|
(int)Math.Round((usage.InputTokens ?? 0) * multiplier);
|
||||||
|
usage.OutputTokens =
|
||||||
|
(int)Math.Round((usage.OutputTokens ?? 0) * multiplier);
|
||||||
|
usage.CompletionTokens =
|
||||||
|
(int)Math.Round((usage.CompletionTokens ?? 0) * multiplier);
|
||||||
|
usage.PromptTokens =
|
||||||
|
(int)Math.Round((usage.PromptTokens ?? 0) * multiplier);
|
||||||
|
usage.TotalTokens =
|
||||||
|
(int)Math.Round((usage.TotalTokens ?? 0) * multiplier);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -0,0 +1,46 @@
|
|||||||
|
using SqlSugar;
|
||||||
|
using Volo.Abp.Domain.Entities.Auditing;
|
||||||
|
using Yi.Framework.AiHub.Domain.Shared.Enums;
|
||||||
|
|
||||||
|
namespace Yi.Framework.AiHub.Domain.Entities;
|
||||||
|
|
||||||
|
/// <summary>
|
||||||
|
/// 激活码
|
||||||
|
/// </summary>
|
||||||
|
[SugarTable("Ai_ActivationCode")]
|
||||||
|
[SugarIndex($"index_{nameof(Code)}", nameof(Code), OrderByType.Asc, true)]
|
||||||
|
[SugarIndex($"index_{nameof(GoodsType)}", nameof(GoodsType), OrderByType.Asc)]
|
||||||
|
public class ActivationCodeAggregateRoot : FullAuditedAggregateRoot<Guid>
|
||||||
|
{
|
||||||
|
/// <summary>
|
||||||
|
/// 激活码(唯一)
|
||||||
|
/// </summary>
|
||||||
|
[SugarColumn(Length = 50)]
|
||||||
|
public string Code { get; set; } = string.Empty;
|
||||||
|
|
||||||
|
/// <summary>
|
||||||
|
/// 商品类型
|
||||||
|
/// </summary>
|
||||||
|
public ActivationCodeGoodsTypeEnum GoodsType { get; set; }
|
||||||
|
|
||||||
|
/// <summary>
|
||||||
|
/// 是否允许多人各使用一次
|
||||||
|
/// </summary>
|
||||||
|
public bool IsReusable { get; set; }
|
||||||
|
|
||||||
|
/// <summary>
|
||||||
|
/// 是否限制同类型只能兑换一次
|
||||||
|
/// </summary>
|
||||||
|
public bool IsSameTypeOnce { get; set; }
|
||||||
|
|
||||||
|
/// <summary>
|
||||||
|
/// 已使用次数
|
||||||
|
/// </summary>
|
||||||
|
public int UsedCount { get; set; }
|
||||||
|
|
||||||
|
/// <summary>
|
||||||
|
/// 备注
|
||||||
|
/// </summary>
|
||||||
|
[SugarColumn(Length = 500, IsNullable = true)]
|
||||||
|
public string? Remark { get; set; }
|
||||||
|
}
|
||||||
@@ -0,0 +1,50 @@
|
|||||||
|
using SqlSugar;
|
||||||
|
using Volo.Abp.Domain.Entities.Auditing;
|
||||||
|
using Yi.Framework.AiHub.Domain.Shared.Enums;
|
||||||
|
|
||||||
|
namespace Yi.Framework.AiHub.Domain.Entities;
|
||||||
|
|
||||||
|
/// <summary>
|
||||||
|
/// 激活码使用记录
|
||||||
|
/// </summary>
|
||||||
|
[SugarTable("Ai_ActivationCodeRecord")]
|
||||||
|
[SugarIndex($"index_{nameof(UserId)}_{nameof(ActivationCodeId)}",
|
||||||
|
nameof(UserId), OrderByType.Asc,
|
||||||
|
nameof(ActivationCodeId), OrderByType.Asc, true)]
|
||||||
|
[SugarIndex($"index_{nameof(UserId)}_{nameof(GoodsType)}",
|
||||||
|
nameof(UserId), OrderByType.Asc,
|
||||||
|
nameof(GoodsType), OrderByType.Asc)]
|
||||||
|
public class ActivationCodeRecordAggregateRoot : FullAuditedAggregateRoot<Guid>
|
||||||
|
{
|
||||||
|
/// <summary>
|
||||||
|
/// 激活码Id
|
||||||
|
/// </summary>
|
||||||
|
public Guid ActivationCodeId { get; set; }
|
||||||
|
|
||||||
|
/// <summary>
|
||||||
|
/// 激活码内容
|
||||||
|
/// </summary>
|
||||||
|
[SugarColumn(Length = 50)]
|
||||||
|
public string Code { get; set; } = string.Empty;
|
||||||
|
|
||||||
|
/// <summary>
|
||||||
|
/// 用户Id
|
||||||
|
/// </summary>
|
||||||
|
public Guid UserId { get; set; }
|
||||||
|
|
||||||
|
/// <summary>
|
||||||
|
/// 商品类型
|
||||||
|
/// </summary>
|
||||||
|
public ActivationCodeGoodsTypeEnum GoodsType { get; set; }
|
||||||
|
|
||||||
|
/// <summary>
|
||||||
|
/// 兑换时间
|
||||||
|
/// </summary>
|
||||||
|
public DateTime RedeemTime { get; set; }
|
||||||
|
|
||||||
|
/// <summary>
|
||||||
|
/// 备注
|
||||||
|
/// </summary>
|
||||||
|
[SugarColumn(Length = 500, IsNullable = true)]
|
||||||
|
public string? Remark { get; set; }
|
||||||
|
}
|
||||||
@@ -0,0 +1,45 @@
|
|||||||
|
using SqlSugar;
|
||||||
|
using Volo.Abp.Auditing;
|
||||||
|
using Volo.Abp.Domain.Entities;
|
||||||
|
using Volo.Abp.Domain.Entities.Auditing;
|
||||||
|
|
||||||
|
namespace Yi.Framework.AiHub.Domain.Entities.Chat;
|
||||||
|
|
||||||
|
[SugarTable("Ai_AgentStore")]
|
||||||
|
[SugarIndex($"index_{{table}}_{nameof(SessionId)}",
|
||||||
|
$"{nameof(SessionId)}", OrderByType.Desc
|
||||||
|
)]
|
||||||
|
public class AgentStoreAggregateRoot : FullAuditedAggregateRoot<Guid>
|
||||||
|
{
|
||||||
|
public AgentStoreAggregateRoot()
|
||||||
|
{
|
||||||
|
}
|
||||||
|
|
||||||
|
/// <summary>
|
||||||
|
/// 构建
|
||||||
|
/// </summary>
|
||||||
|
/// <param name="sessionId"></param>
|
||||||
|
public AgentStoreAggregateRoot(Guid sessionId)
|
||||||
|
{
|
||||||
|
SessionId = sessionId;
|
||||||
|
}
|
||||||
|
|
||||||
|
/// <summary>
|
||||||
|
/// 会话id
|
||||||
|
/// </summary>
|
||||||
|
public Guid SessionId { get; set; }
|
||||||
|
|
||||||
|
/// <summary>
|
||||||
|
/// 存储
|
||||||
|
/// </summary>
|
||||||
|
[SugarColumn(ColumnDataType = StaticConfig.CodeFirst_BigString)]
|
||||||
|
public string? Store { get; set; }
|
||||||
|
|
||||||
|
/// <summary>
|
||||||
|
/// 设置存储
|
||||||
|
/// </summary>
|
||||||
|
public void SetStore()
|
||||||
|
{
|
||||||
|
this.Store = Store;
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -0,0 +1,104 @@
|
|||||||
|
using SqlSugar;
|
||||||
|
using Volo.Abp.Domain.Entities.Auditing;
|
||||||
|
using Yi.Framework.AiHub.Domain.Shared.Enums;
|
||||||
|
|
||||||
|
namespace Yi.Framework.AiHub.Domain.Entities.Chat;
|
||||||
|
|
||||||
|
[SugarTable("Ai_ImageStoreTask")]
|
||||||
|
public class ImageStoreTaskAggregateRoot : FullAuditedAggregateRoot<Guid>
|
||||||
|
{
|
||||||
|
/// <summary>
|
||||||
|
/// 提示词
|
||||||
|
/// </summary>
|
||||||
|
[SugarColumn(ColumnDataType = StaticConfig.CodeFirst_BigString)]
|
||||||
|
public string Prompt { get; set; }
|
||||||
|
|
||||||
|
/// <summary>
|
||||||
|
/// 参考图PrefixBase64(带前缀,如 data:image/png;base64,xxx)
|
||||||
|
/// </summary>
|
||||||
|
[SugarColumn(IsJson = true, ColumnDataType = StaticConfig.CodeFirst_BigString)]
|
||||||
|
public List<string> ReferenceImagesPrefixBase64 { get; set; }
|
||||||
|
|
||||||
|
/// <summary>
|
||||||
|
/// 参考图url
|
||||||
|
/// </summary>
|
||||||
|
[SugarColumn(IsJson = true)]
|
||||||
|
public List<string> ReferenceImagesUrl { get; set; }
|
||||||
|
|
||||||
|
|
||||||
|
/// <summary>
|
||||||
|
/// 图片绝对路径
|
||||||
|
/// </summary>
|
||||||
|
public string? StoreUrl { get; set; }
|
||||||
|
|
||||||
|
/// <summary>
|
||||||
|
/// 任务状态
|
||||||
|
/// </summary>
|
||||||
|
public TaskStatusEnum TaskStatus { get; set; } = TaskStatusEnum.Processing;
|
||||||
|
|
||||||
|
/// <summary>
|
||||||
|
/// 用户id
|
||||||
|
/// </summary>
|
||||||
|
public Guid UserId { get; set; }
|
||||||
|
|
||||||
|
/// <summary>
|
||||||
|
/// 用户名称
|
||||||
|
/// </summary>
|
||||||
|
public string? UserName { get; set; }
|
||||||
|
|
||||||
|
/// <summary>
|
||||||
|
/// 模型id
|
||||||
|
/// </summary>
|
||||||
|
public string ModelId { get; set; }
|
||||||
|
|
||||||
|
/// <summary>
|
||||||
|
/// 错误信息
|
||||||
|
/// </summary>
|
||||||
|
[SugarColumn(ColumnDataType = StaticConfig.CodeFirst_BigString)]
|
||||||
|
public string? ErrorInfo { get; set; }
|
||||||
|
|
||||||
|
/// <summary>
|
||||||
|
/// 发布状态
|
||||||
|
/// </summary>
|
||||||
|
public PublishStatusEnum PublishStatus { get; set; } = PublishStatusEnum.Unpublished;
|
||||||
|
|
||||||
|
/// <summary>
|
||||||
|
/// 分类标签
|
||||||
|
/// </summary>
|
||||||
|
[SugarColumn(IsJson = true)]
|
||||||
|
public List<string> Categories { get; set; } = new();
|
||||||
|
|
||||||
|
/// <summary>
|
||||||
|
/// 是否匿名
|
||||||
|
/// </summary>
|
||||||
|
public bool IsAnonymous { get; set; } = false;
|
||||||
|
|
||||||
|
/// <summary>
|
||||||
|
/// 密钥id
|
||||||
|
/// </summary>
|
||||||
|
public Guid? TokenId { get; set; }
|
||||||
|
|
||||||
|
/// <summary>
|
||||||
|
/// 设置成功
|
||||||
|
/// </summary>
|
||||||
|
/// <param name="storeUrl"></param>
|
||||||
|
public void SetSuccess(string storeUrl)
|
||||||
|
{
|
||||||
|
TaskStatus = TaskStatusEnum.Success;
|
||||||
|
StoreUrl = storeUrl;
|
||||||
|
}
|
||||||
|
|
||||||
|
/// <summary>
|
||||||
|
/// 设置发布
|
||||||
|
/// </summary>
|
||||||
|
/// <param name="isAnonymous"></param>
|
||||||
|
/// <param name="categories"></param>
|
||||||
|
public void SetPublish(bool isAnonymous,List<string> categories)
|
||||||
|
{
|
||||||
|
this.PublishStatus = PublishStatusEnum.Published;
|
||||||
|
this.IsAnonymous = isAnonymous;
|
||||||
|
this.Categories = categories;
|
||||||
|
}
|
||||||
|
|
||||||
|
|
||||||
|
}
|
||||||
@@ -80,4 +80,9 @@ public class AiModelEntity : Entity<Guid>, IOrderNum, ISoftDelete
|
|||||||
/// 模型图标URL
|
/// 模型图标URL
|
||||||
/// </summary>
|
/// </summary>
|
||||||
public string? IconUrl { get; set; }
|
public string? IconUrl { get; set; }
|
||||||
|
|
||||||
|
/// <summary>
|
||||||
|
/// 是否为尊享模型
|
||||||
|
/// </summary>
|
||||||
|
public bool IsPremium { get; set; }
|
||||||
}
|
}
|
||||||
@@ -0,0 +1,174 @@
|
|||||||
|
using System.Text;
|
||||||
|
using Microsoft.Extensions.Logging;
|
||||||
|
using Volo.Abp;
|
||||||
|
using Volo.Abp.Domain.Services;
|
||||||
|
using Yi.Framework.AiHub.Domain.Entities;
|
||||||
|
using Yi.Framework.AiHub.Domain.Shared.Enums;
|
||||||
|
using Yi.Framework.SqlSugarCore.Abstractions;
|
||||||
|
|
||||||
|
namespace Yi.Framework.AiHub.Domain.Managers;
|
||||||
|
|
||||||
|
public class ActivationCodeRedeemContext
|
||||||
|
{
|
||||||
|
public ActivationCodeAggregateRoot ActivationCode { get; set; } = default!;
|
||||||
|
public string PackageName { get; set; } = string.Empty;
|
||||||
|
public ActivationCodeGoodsAttribute Goods { get; set; } = default!;
|
||||||
|
}
|
||||||
|
|
||||||
|
/// <summary>
|
||||||
|
/// 激活码管理器
|
||||||
|
/// </summary>
|
||||||
|
public class ActivationCodeManager : DomainService
|
||||||
|
{
|
||||||
|
private readonly ISqlSugarRepository<ActivationCodeAggregateRoot, Guid> _activationCodeRepository;
|
||||||
|
private readonly ISqlSugarRepository<ActivationCodeRecordAggregateRoot, Guid> _activationCodeRecordRepository;
|
||||||
|
private readonly ILogger<ActivationCodeManager> _logger;
|
||||||
|
|
||||||
|
public ActivationCodeManager(
|
||||||
|
ISqlSugarRepository<ActivationCodeAggregateRoot, Guid> activationCodeRepository,
|
||||||
|
ISqlSugarRepository<ActivationCodeRecordAggregateRoot, Guid> activationCodeRecordRepository,
|
||||||
|
ILogger<ActivationCodeManager> logger)
|
||||||
|
{
|
||||||
|
_activationCodeRepository = activationCodeRepository;
|
||||||
|
_activationCodeRecordRepository = activationCodeRecordRepository;
|
||||||
|
_logger = logger;
|
||||||
|
}
|
||||||
|
|
||||||
|
public async Task<List<ActivationCodeAggregateRoot>> CreateBatchAsync(
|
||||||
|
List<(ActivationCodeGoodsTypeEnum GoodsType, int Count)> items)
|
||||||
|
{
|
||||||
|
var entities = new List<ActivationCodeAggregateRoot>();
|
||||||
|
foreach (var item in items)
|
||||||
|
{
|
||||||
|
if (item.Count <= 0)
|
||||||
|
{
|
||||||
|
throw new UserFriendlyException("生成数量必须大于0");
|
||||||
|
}
|
||||||
|
|
||||||
|
var goods = item.GoodsType.GetGoods();
|
||||||
|
if (goods == null)
|
||||||
|
{
|
||||||
|
throw new UserFriendlyException("激活码商品类型无效");
|
||||||
|
}
|
||||||
|
|
||||||
|
for (var i = 0; i < item.Count; i++)
|
||||||
|
{
|
||||||
|
var code = await GenerateUniqueActivationCodeAsync();
|
||||||
|
entities.Add(new ActivationCodeAggregateRoot
|
||||||
|
{
|
||||||
|
Code = code,
|
||||||
|
GoodsType = item.GoodsType,
|
||||||
|
IsReusable = goods.IsReusable,
|
||||||
|
IsSameTypeOnce = goods.IsSameTypeOnce,
|
||||||
|
UsedCount = 0,
|
||||||
|
Remark = null
|
||||||
|
});
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
await _activationCodeRepository.InsertRangeAsync(entities);
|
||||||
|
return entities;
|
||||||
|
}
|
||||||
|
|
||||||
|
public async Task<ActivationCodeRedeemContext> RedeemAsync(Guid userId, string code)
|
||||||
|
{
|
||||||
|
if (string.IsNullOrWhiteSpace(code))
|
||||||
|
{
|
||||||
|
throw new UserFriendlyException("激活码不能为空");
|
||||||
|
}
|
||||||
|
|
||||||
|
var trimmedCode = code.Trim();
|
||||||
|
var activationCode = await _activationCodeRepository._DbQueryable
|
||||||
|
.Where(x => x.Code == trimmedCode)
|
||||||
|
.FirstAsync();
|
||||||
|
|
||||||
|
if (activationCode == null)
|
||||||
|
{
|
||||||
|
throw new UserFriendlyException("激活码不存在");
|
||||||
|
}
|
||||||
|
|
||||||
|
var hasUsedCurrentCode = await _activationCodeRecordRepository._DbQueryable
|
||||||
|
.Where(x => x.UserId == userId && x.ActivationCodeId == activationCode.Id)
|
||||||
|
.AnyAsync();
|
||||||
|
|
||||||
|
if (hasUsedCurrentCode)
|
||||||
|
{
|
||||||
|
throw new UserFriendlyException("该激活码已被你使用过");
|
||||||
|
}
|
||||||
|
|
||||||
|
if (!activationCode.IsReusable && activationCode.UsedCount > 0)
|
||||||
|
{
|
||||||
|
throw new UserFriendlyException("该激活码已被使用");
|
||||||
|
}
|
||||||
|
|
||||||
|
if (activationCode.IsSameTypeOnce)
|
||||||
|
{
|
||||||
|
var hasUsedSameType = await _activationCodeRecordRepository._DbQueryable
|
||||||
|
.Where(x => x.UserId == userId && x.GoodsType == activationCode.GoodsType)
|
||||||
|
.AnyAsync();
|
||||||
|
|
||||||
|
if (hasUsedSameType)
|
||||||
|
{
|
||||||
|
throw new UserFriendlyException("该类型激活码每个用户只能兑换一次");
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
var goods = activationCode.GoodsType.GetGoods();
|
||||||
|
if (goods == null)
|
||||||
|
{
|
||||||
|
throw new UserFriendlyException("激活码商品类型无效");
|
||||||
|
}
|
||||||
|
|
||||||
|
var packageName = string.IsNullOrWhiteSpace(goods.Content)
|
||||||
|
? goods.DisplayName
|
||||||
|
: $"{goods.DisplayName} {goods.Content}";
|
||||||
|
|
||||||
|
activationCode.UsedCount += 1;
|
||||||
|
await _activationCodeRepository.UpdateAsync(activationCode);
|
||||||
|
|
||||||
|
var record = new ActivationCodeRecordAggregateRoot
|
||||||
|
{
|
||||||
|
ActivationCodeId = activationCode.Id,
|
||||||
|
Code = activationCode.Code,
|
||||||
|
UserId = userId,
|
||||||
|
GoodsType = activationCode.GoodsType,
|
||||||
|
RedeemTime = DateTime.Now,
|
||||||
|
Remark = "激活码兑换"
|
||||||
|
};
|
||||||
|
await _activationCodeRecordRepository.InsertAsync(record);
|
||||||
|
|
||||||
|
_logger.LogInformation("用户 {UserId} 兑换激活码 {Code} 成功", userId, activationCode.Code);
|
||||||
|
|
||||||
|
return new ActivationCodeRedeemContext
|
||||||
|
{
|
||||||
|
ActivationCode = activationCode,
|
||||||
|
PackageName = packageName,
|
||||||
|
Goods = goods
|
||||||
|
};
|
||||||
|
}
|
||||||
|
|
||||||
|
private async Task<string> GenerateUniqueActivationCodeAsync()
|
||||||
|
{
|
||||||
|
string code;
|
||||||
|
do
|
||||||
|
{
|
||||||
|
code = GenerateActivationCode();
|
||||||
|
} while (await _activationCodeRepository._DbQueryable.AnyAsync(x => x.Code == code));
|
||||||
|
|
||||||
|
return code;
|
||||||
|
}
|
||||||
|
|
||||||
|
private string GenerateActivationCode()
|
||||||
|
{
|
||||||
|
const string chars = "ABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789";
|
||||||
|
var random = new Random();
|
||||||
|
var builder = new StringBuilder(16);
|
||||||
|
for (var i = 0; i < 16; i++)
|
||||||
|
{
|
||||||
|
builder.Append(chars[random.Next(chars.Length)]);
|
||||||
|
}
|
||||||
|
|
||||||
|
return builder.ToString();
|
||||||
|
}
|
||||||
|
|
||||||
|
}
|
||||||
@@ -12,10 +12,12 @@ using Newtonsoft.Json.Serialization;
|
|||||||
using Volo.Abp.Domain.Services;
|
using Volo.Abp.Domain.Services;
|
||||||
using Yi.Framework.AiHub.Domain.AiGateWay;
|
using Yi.Framework.AiHub.Domain.AiGateWay;
|
||||||
using Yi.Framework.AiHub.Domain.AiGateWay.Exceptions;
|
using Yi.Framework.AiHub.Domain.AiGateWay.Exceptions;
|
||||||
|
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.Shared.Consts;
|
using Yi.Framework.AiHub.Domain.Shared.Consts;
|
||||||
using Yi.Framework.AiHub.Domain.Shared.Dtos;
|
using Yi.Framework.AiHub.Domain.Shared.Dtos;
|
||||||
using Yi.Framework.AiHub.Domain.Shared.Dtos.Anthropic;
|
using Yi.Framework.AiHub.Domain.Shared.Dtos.Anthropic;
|
||||||
|
using Yi.Framework.AiHub.Domain.Shared.Dtos.Gemini;
|
||||||
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;
|
||||||
@@ -38,11 +40,12 @@ public class AiGateWayManager : DomainService
|
|||||||
private readonly UsageStatisticsManager _usageStatisticsManager;
|
private readonly UsageStatisticsManager _usageStatisticsManager;
|
||||||
private readonly ISpecialCompatible _specialCompatible;
|
private readonly ISpecialCompatible _specialCompatible;
|
||||||
private PremiumPackageManager? _premiumPackageManager;
|
private PremiumPackageManager? _premiumPackageManager;
|
||||||
|
private readonly ISqlSugarRepository<ImageStoreTaskAggregateRoot> _imageStoreTaskRepository;
|
||||||
|
|
||||||
public AiGateWayManager(ISqlSugarRepository<AiAppAggregateRoot> aiAppRepository, ILogger<AiGateWayManager> logger,
|
public AiGateWayManager(ISqlSugarRepository<AiAppAggregateRoot> aiAppRepository, ILogger<AiGateWayManager> logger,
|
||||||
AiMessageManager aiMessageManager, UsageStatisticsManager usageStatisticsManager,
|
AiMessageManager aiMessageManager, UsageStatisticsManager usageStatisticsManager,
|
||||||
ISpecialCompatible specialCompatible, ISqlSugarRepository<AiModelEntity> aiModelRepository)
|
ISpecialCompatible specialCompatible, ISqlSugarRepository<AiModelEntity> aiModelRepository,
|
||||||
|
ISqlSugarRepository<ImageStoreTaskAggregateRoot> imageStoreTaskRepository)
|
||||||
{
|
{
|
||||||
_aiAppRepository = aiAppRepository;
|
_aiAppRepository = aiAppRepository;
|
||||||
_logger = logger;
|
_logger = logger;
|
||||||
@@ -50,6 +53,7 @@ public class AiGateWayManager : DomainService
|
|||||||
_usageStatisticsManager = usageStatisticsManager;
|
_usageStatisticsManager = usageStatisticsManager;
|
||||||
_specialCompatible = specialCompatible;
|
_specialCompatible = specialCompatible;
|
||||||
_aiModelRepository = aiModelRepository;
|
_aiModelRepository = aiModelRepository;
|
||||||
|
_imageStoreTaskRepository = imageStoreTaskRepository;
|
||||||
}
|
}
|
||||||
|
|
||||||
private PremiumPackageManager PremiumPackageManager =>
|
private PremiumPackageManager PremiumPackageManager =>
|
||||||
@@ -61,7 +65,7 @@ public class AiGateWayManager : DomainService
|
|||||||
/// <param name="modelApiType"></param>
|
/// <param name="modelApiType"></param>
|
||||||
/// <param name="modelId"></param>
|
/// <param name="modelId"></param>
|
||||||
/// <returns></returns>
|
/// <returns></returns>
|
||||||
private async Task<AiModelDescribe> GetModelAsync(ModelApiTypeEnum modelApiType, string modelId)
|
public async Task<AiModelDescribe> GetModelAsync(ModelApiTypeEnum modelApiType, string modelId)
|
||||||
{
|
{
|
||||||
var aiModelDescribe = await _aiModelRepository._DbQueryable
|
var aiModelDescribe = await _aiModelRepository._DbQueryable
|
||||||
.LeftJoin<AiAppAggregateRoot>((model, app) => model.AiAppId == app.Id)
|
.LeftJoin<AiAppAggregateRoot>((model, app) => model.AiAppId == app.Id)
|
||||||
@@ -88,7 +92,12 @@ public class AiGateWayManager : DomainService
|
|||||||
{
|
{
|
||||||
throw new UserFriendlyException($"【{modelId}】模型当前版本【{modelApiType}】格式不支持");
|
throw new UserFriendlyException($"【{modelId}】模型当前版本【{modelApiType}】格式不支持");
|
||||||
}
|
}
|
||||||
|
// ✅ 统一处理 yi- 后缀(网关层模型规范化)
|
||||||
|
if (!string.IsNullOrEmpty(aiModelDescribe.ModelId) &&
|
||||||
|
aiModelDescribe.ModelId.StartsWith("yi-", StringComparison.OrdinalIgnoreCase))
|
||||||
|
{
|
||||||
|
aiModelDescribe.ModelId = aiModelDescribe.ModelId[3..];
|
||||||
|
}
|
||||||
return aiModelDescribe;
|
return aiModelDescribe;
|
||||||
}
|
}
|
||||||
|
|
||||||
@@ -141,7 +150,12 @@ public class AiGateWayManager : DomainService
|
|||||||
await _usageStatisticsManager.SetUsageAsync(userId.Value, request.Model, data.Usage, tokenId);
|
await _usageStatisticsManager.SetUsageAsync(userId.Value, request.Model, data.Usage, tokenId);
|
||||||
|
|
||||||
// 扣减尊享token包用量
|
// 扣减尊享token包用量
|
||||||
if (PremiumPackageConst.ModeIds.Contains(request.Model))
|
var isPremium = await _aiModelRepository._DbQueryable
|
||||||
|
.Where(x => x.ModelId == request.Model)
|
||||||
|
.Select(x => x.IsPremium)
|
||||||
|
.FirstAsync();
|
||||||
|
|
||||||
|
if (isPremium)
|
||||||
{
|
{
|
||||||
var totalTokens = data.Usage?.TotalTokens ?? 0;
|
var totalTokens = data.Usage?.TotalTokens ?? 0;
|
||||||
if (totalTokens > 0)
|
if (totalTokens > 0)
|
||||||
@@ -185,7 +199,7 @@ public class AiGateWayManager : DomainService
|
|||||||
var chatService =
|
var chatService =
|
||||||
LazyServiceProvider.GetRequiredKeyedService<IChatCompletionService>(modelDescribe.HandlerName);
|
LazyServiceProvider.GetRequiredKeyedService<IChatCompletionService>(modelDescribe.HandlerName);
|
||||||
|
|
||||||
var completeChatResponse = chatService.CompleteChatStreamAsync(modelDescribe,request, cancellationToken);
|
var completeChatResponse = chatService.CompleteChatStreamAsync(modelDescribe, request, cancellationToken);
|
||||||
var tokenUsage = new ThorUsageResponse();
|
var tokenUsage = new ThorUsageResponse();
|
||||||
|
|
||||||
//缓存队列算法
|
//缓存队列算法
|
||||||
@@ -233,7 +247,7 @@ public class AiGateWayManager : DomainService
|
|||||||
tokenUsage = data.Usage;
|
tokenUsage = data.Usage;
|
||||||
}
|
}
|
||||||
|
|
||||||
var message = System.Text.Json.JsonSerializer.Serialize(data, ThorJsonSerializer.DefaultOptions);
|
var message = JsonSerializer.Serialize(data, ThorJsonSerializer.DefaultOptions);
|
||||||
backupSystemContent.Append(data.Choices.FirstOrDefault()?.Delta.Content);
|
backupSystemContent.Append(data.Choices.FirstOrDefault()?.Delta.Content);
|
||||||
// 将消息加入队列而不是直接写入
|
// 将消息加入队列而不是直接写入
|
||||||
messageQueue.Enqueue($"data: {message}\n\n");
|
messageQueue.Enqueue($"data: {message}\n\n");
|
||||||
@@ -242,7 +256,7 @@ public class AiGateWayManager : DomainService
|
|||||||
catch (Exception e)
|
catch (Exception e)
|
||||||
{
|
{
|
||||||
_logger.LogError(e, $"Ai对话异常");
|
_logger.LogError(e, $"Ai对话异常");
|
||||||
var errorContent = $"对话Ai异常,异常信息:\n当前Ai模型:{request.Model}\n异常信息:{e.Message}\n异常堆栈:{e}";
|
var errorContent = $"对话Ai异常,异常信息:\n当前Ai模型:{request.Model}\n异常信息:{e.Message}\n异常堆栈:{e}";
|
||||||
var model = new ThorChatCompletionsResponse()
|
var model = new ThorChatCompletionsResponse()
|
||||||
{
|
{
|
||||||
Choices = new List<ThorChatChoiceResponse>()
|
Choices = new List<ThorChatChoiceResponse>()
|
||||||
@@ -275,7 +289,7 @@ public class AiGateWayManager : DomainService
|
|||||||
await _aiMessageManager.CreateUserMessageAsync(userId, sessionId,
|
await _aiMessageManager.CreateUserMessageAsync(userId, sessionId,
|
||||||
new MessageInputDto
|
new MessageInputDto
|
||||||
{
|
{
|
||||||
Content = sessionId is null ? "不予存储" : request.Messages?.LastOrDefault()?.Content ?? string.Empty,
|
Content = sessionId is null ? "不予存储" : request.Messages?.LastOrDefault()?.MessagesStore ?? string.Empty,
|
||||||
ModelId = request.Model,
|
ModelId = request.Model,
|
||||||
TokenUsage = tokenUsage,
|
TokenUsage = tokenUsage,
|
||||||
}, tokenId);
|
}, tokenId);
|
||||||
@@ -291,7 +305,14 @@ public class AiGateWayManager : DomainService
|
|||||||
await _usageStatisticsManager.SetUsageAsync(userId, request.Model, tokenUsage, tokenId);
|
await _usageStatisticsManager.SetUsageAsync(userId, request.Model, tokenUsage, tokenId);
|
||||||
|
|
||||||
// 扣减尊享token包用量
|
// 扣减尊享token包用量
|
||||||
if (userId is not null && PremiumPackageConst.ModeIds.Contains(request.Model))
|
if (userId is not null)
|
||||||
|
{
|
||||||
|
var isPremium = await _aiModelRepository._DbQueryable
|
||||||
|
.Where(x => x.ModelId == request.Model)
|
||||||
|
.Select(x => x.IsPremium)
|
||||||
|
.FirstAsync();
|
||||||
|
|
||||||
|
if (isPremium)
|
||||||
{
|
{
|
||||||
var totalTokens = tokenUsage.TotalTokens ?? 0;
|
var totalTokens = tokenUsage.TotalTokens ?? 0;
|
||||||
if (totalTokens > 0)
|
if (totalTokens > 0)
|
||||||
@@ -300,6 +321,7 @@ public class AiGateWayManager : DomainService
|
|||||||
}
|
}
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
|
||||||
/// <summary>
|
/// <summary>
|
||||||
@@ -354,7 +376,14 @@ public class AiGateWayManager : DomainService
|
|||||||
await _usageStatisticsManager.SetUsageAsync(userId, model, response.Usage, tokenId);
|
await _usageStatisticsManager.SetUsageAsync(userId, model, response.Usage, tokenId);
|
||||||
|
|
||||||
// 扣减尊享token包用量
|
// 扣减尊享token包用量
|
||||||
if (userId is not null && PremiumPackageConst.ModeIds.Contains(request.Model))
|
if (userId is not null)
|
||||||
|
{
|
||||||
|
var isPremium = await _aiModelRepository._DbQueryable
|
||||||
|
.Where(x => x.ModelId == request.Model)
|
||||||
|
.Select(x => x.IsPremium)
|
||||||
|
.FirstAsync();
|
||||||
|
|
||||||
|
if (isPremium)
|
||||||
{
|
{
|
||||||
var totalTokens = response.Usage.TotalTokens ?? 0;
|
var totalTokens = response.Usage.TotalTokens ?? 0;
|
||||||
if (totalTokens > 0)
|
if (totalTokens > 0)
|
||||||
@@ -363,9 +392,10 @@ public class AiGateWayManager : DomainService
|
|||||||
}
|
}
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
}
|
||||||
catch (Exception e)
|
catch (Exception e)
|
||||||
{
|
{
|
||||||
var errorContent = $"图片生成Ai异常,异常信息:\n当前Ai模型:{request.Model}\n异常信息:{e.Message}\n异常堆栈:{e}";
|
var errorContent = $"图片生成Ai异常,异常信息:\n当前Ai模型:{request.Model}\n异常信息:{e.Message}\n异常堆栈:{e}";
|
||||||
throw new UserFriendlyException(errorContent);
|
throw new UserFriendlyException(errorContent);
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
@@ -478,7 +508,7 @@ public class AiGateWayManager : DomainService
|
|||||||
}
|
}
|
||||||
catch (Exception e)
|
catch (Exception e)
|
||||||
{
|
{
|
||||||
var errorContent = $"嵌入Ai异常,异常信息:\n当前Ai模型:{input.Model}\n异常信息:{e.Message}\n异常堆栈:{e}";
|
var errorContent = $"嵌入Ai异常,异常信息:\n当前Ai模型:{input.Model}\n异常信息:{e.Message}\n异常堆栈:{e}";
|
||||||
throw new UserFriendlyException(errorContent);
|
throw new UserFriendlyException(errorContent);
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
@@ -506,6 +536,14 @@ public class AiGateWayManager : DomainService
|
|||||||
// 设置响应头,声明是 json
|
// 设置响应头,声明是 json
|
||||||
//response.ContentType = "application/json; charset=UTF-8";
|
//response.ContentType = "application/json; charset=UTF-8";
|
||||||
var modelDescribe = await GetModelAsync(ModelApiTypeEnum.Claude, request.Model);
|
var modelDescribe = await GetModelAsync(ModelApiTypeEnum.Claude, request.Model);
|
||||||
|
|
||||||
|
var sourceModelId = request.Model;
|
||||||
|
if (!string.IsNullOrEmpty(request.Model) &&
|
||||||
|
request.Model.StartsWith("yi-", StringComparison.OrdinalIgnoreCase))
|
||||||
|
{
|
||||||
|
request.Model = request.Model[3..];
|
||||||
|
}
|
||||||
|
|
||||||
var chatService =
|
var chatService =
|
||||||
LazyServiceProvider.GetRequiredKeyedService<IAnthropicChatCompletionService>(modelDescribe.HandlerName);
|
LazyServiceProvider.GetRequiredKeyedService<IAnthropicChatCompletionService>(modelDescribe.HandlerName);
|
||||||
var data = await chatService.ChatCompletionsAsync(modelDescribe, request, cancellationToken);
|
var data = await chatService.ChatCompletionsAsync(modelDescribe, request, cancellationToken);
|
||||||
@@ -518,7 +556,7 @@ public class AiGateWayManager : DomainService
|
|||||||
new MessageInputDto
|
new MessageInputDto
|
||||||
{
|
{
|
||||||
Content = "不予存储",
|
Content = "不予存储",
|
||||||
ModelId = request.Model,
|
ModelId = sourceModelId,
|
||||||
TokenUsage = data.TokenUsage,
|
TokenUsage = data.TokenUsage,
|
||||||
}, tokenId);
|
}, tokenId);
|
||||||
|
|
||||||
@@ -526,11 +564,11 @@ public class AiGateWayManager : DomainService
|
|||||||
new MessageInputDto
|
new MessageInputDto
|
||||||
{
|
{
|
||||||
Content = "不予存储",
|
Content = "不予存储",
|
||||||
ModelId = request.Model,
|
ModelId = sourceModelId,
|
||||||
TokenUsage = data.TokenUsage
|
TokenUsage = data.TokenUsage
|
||||||
}, tokenId);
|
}, tokenId);
|
||||||
|
|
||||||
await _usageStatisticsManager.SetUsageAsync(userId.Value, request.Model, data.TokenUsage, tokenId);
|
await _usageStatisticsManager.SetUsageAsync(userId.Value, sourceModelId, data.TokenUsage, tokenId);
|
||||||
|
|
||||||
// 扣减尊享token包用量
|
// 扣减尊享token包用量
|
||||||
var totalTokens = data.TokenUsage.TotalTokens ?? 0;
|
var totalTokens = data.TokenUsage.TotalTokens ?? 0;
|
||||||
@@ -573,7 +611,14 @@ public class AiGateWayManager : DomainService
|
|||||||
var chatService =
|
var chatService =
|
||||||
LazyServiceProvider.GetRequiredKeyedService<IAnthropicChatCompletionService>(modelDescribe.HandlerName);
|
LazyServiceProvider.GetRequiredKeyedService<IAnthropicChatCompletionService>(modelDescribe.HandlerName);
|
||||||
|
|
||||||
var completeChatResponse = chatService.StreamChatCompletionsAsync(modelDescribe,request, cancellationToken);
|
var sourceModelId = request.Model;
|
||||||
|
if (!string.IsNullOrEmpty(request.Model) &&
|
||||||
|
request.Model.StartsWith("yi-", StringComparison.OrdinalIgnoreCase))
|
||||||
|
{
|
||||||
|
request.Model = request.Model[3..];
|
||||||
|
}
|
||||||
|
|
||||||
|
var completeChatResponse = chatService.StreamChatCompletionsAsync(modelDescribe, request, cancellationToken);
|
||||||
ThorUsageResponse? tokenUsage = null;
|
ThorUsageResponse? tokenUsage = null;
|
||||||
StringBuilder backupSystemContent = new StringBuilder();
|
StringBuilder backupSystemContent = new StringBuilder();
|
||||||
try
|
try
|
||||||
@@ -595,7 +640,7 @@ public class AiGateWayManager : DomainService
|
|||||||
catch (Exception e)
|
catch (Exception e)
|
||||||
{
|
{
|
||||||
_logger.LogError(e, $"Ai对话异常");
|
_logger.LogError(e, $"Ai对话异常");
|
||||||
var errorContent = $"对话Ai异常,异常信息:\n当前Ai模型:{request.Model}\n异常信息:{e.Message}\n异常堆栈:{e}";
|
var errorContent = $"对话Ai异常,异常信息:\n当前Ai模型:{sourceModelId}\n异常信息:{e.Message}\n异常堆栈:{e}";
|
||||||
throw new UserFriendlyException(errorContent);
|
throw new UserFriendlyException(errorContent);
|
||||||
}
|
}
|
||||||
|
|
||||||
@@ -603,7 +648,7 @@ public class AiGateWayManager : DomainService
|
|||||||
new MessageInputDto
|
new MessageInputDto
|
||||||
{
|
{
|
||||||
Content = "不予存储",
|
Content = "不予存储",
|
||||||
ModelId = request.Model,
|
ModelId = sourceModelId,
|
||||||
TokenUsage = tokenUsage,
|
TokenUsage = tokenUsage,
|
||||||
}, tokenId);
|
}, tokenId);
|
||||||
|
|
||||||
@@ -611,11 +656,11 @@ public class AiGateWayManager : DomainService
|
|||||||
new MessageInputDto
|
new MessageInputDto
|
||||||
{
|
{
|
||||||
Content = "不予存储",
|
Content = "不予存储",
|
||||||
ModelId = request.Model,
|
ModelId = sourceModelId,
|
||||||
TokenUsage = tokenUsage
|
TokenUsage = tokenUsage
|
||||||
}, tokenId);
|
}, tokenId);
|
||||||
|
|
||||||
await _usageStatisticsManager.SetUsageAsync(userId, request.Model, tokenUsage, tokenId);
|
await _usageStatisticsManager.SetUsageAsync(userId, sourceModelId, tokenUsage, tokenId);
|
||||||
|
|
||||||
// 扣减尊享token包用量
|
// 扣减尊享token包用量
|
||||||
if (userId.HasValue && tokenUsage is not null)
|
if (userId.HasValue && tokenUsage is not null)
|
||||||
@@ -657,7 +702,7 @@ public class AiGateWayManager : DomainService
|
|||||||
|
|
||||||
data.SupplementalMultiplier(modelDescribe.Multiplier);
|
data.SupplementalMultiplier(modelDescribe.Multiplier);
|
||||||
|
|
||||||
var tokenUsage= new ThorUsageResponse
|
var tokenUsage = new ThorUsageResponse
|
||||||
{
|
{
|
||||||
InputTokens = data.Usage.InputTokens,
|
InputTokens = data.Usage.InputTokens,
|
||||||
OutputTokens = data.Usage.OutputTokens,
|
OutputTokens = data.Usage.OutputTokens,
|
||||||
@@ -723,7 +768,7 @@ public class AiGateWayManager : DomainService
|
|||||||
var chatService =
|
var chatService =
|
||||||
LazyServiceProvider.GetRequiredKeyedService<IOpenAiResponseService>(modelDescribe.HandlerName);
|
LazyServiceProvider.GetRequiredKeyedService<IOpenAiResponseService>(modelDescribe.HandlerName);
|
||||||
|
|
||||||
var completeChatResponse = chatService.ResponsesStreamAsync(modelDescribe,request, cancellationToken);
|
var completeChatResponse = chatService.ResponsesStreamAsync(modelDescribe, request, cancellationToken);
|
||||||
ThorUsageResponse? tokenUsage = null;
|
ThorUsageResponse? tokenUsage = null;
|
||||||
try
|
try
|
||||||
{
|
{
|
||||||
@@ -733,17 +778,17 @@ public class AiGateWayManager : DomainService
|
|||||||
if (responseResult.Item1.Contains("response.completed"))
|
if (responseResult.Item1.Contains("response.completed"))
|
||||||
{
|
{
|
||||||
var obj = responseResult.Item2!.Value;
|
var obj = responseResult.Item2!.Value;
|
||||||
int inputTokens = obj.GetPath("response","usage","input_tokens").GetInt();
|
int inputTokens = obj.GetPath("response", "usage", "input_tokens").GetInt();
|
||||||
int outputTokens = obj.GetPath("response","usage","output_tokens").GetInt();
|
int outputTokens = obj.GetPath("response", "usage", "output_tokens").GetInt();
|
||||||
inputTokens=Convert.ToInt32(inputTokens * modelDescribe.Multiplier);
|
inputTokens = Convert.ToInt32(inputTokens * modelDescribe.Multiplier);
|
||||||
outputTokens=Convert.ToInt32(outputTokens * modelDescribe.Multiplier);
|
outputTokens = Convert.ToInt32(outputTokens * modelDescribe.Multiplier);
|
||||||
tokenUsage = new ThorUsageResponse
|
tokenUsage = new ThorUsageResponse
|
||||||
{
|
{
|
||||||
PromptTokens =inputTokens,
|
PromptTokens = inputTokens,
|
||||||
InputTokens = inputTokens,
|
InputTokens = inputTokens,
|
||||||
OutputTokens = outputTokens,
|
OutputTokens = outputTokens,
|
||||||
CompletionTokens = outputTokens,
|
CompletionTokens = outputTokens,
|
||||||
TotalTokens = inputTokens+outputTokens,
|
TotalTokens = inputTokens + outputTokens,
|
||||||
};
|
};
|
||||||
}
|
}
|
||||||
|
|
||||||
@@ -754,14 +799,14 @@ public class AiGateWayManager : DomainService
|
|||||||
catch (Exception e)
|
catch (Exception e)
|
||||||
{
|
{
|
||||||
_logger.LogError(e, $"Ai响应异常");
|
_logger.LogError(e, $"Ai响应异常");
|
||||||
var errorContent = $"响应Ai异常,异常信息:\n当前Ai模型:{request.Model}\n异常信息:{e.Message}\n异常堆栈:{e}";
|
var errorContent = $"响应Ai异常,异常信息:\n当前Ai模型:{request.Model}\n异常信息:{e.Message}\n异常堆栈:{e}";
|
||||||
throw new UserFriendlyException(errorContent);
|
throw new UserFriendlyException(errorContent);
|
||||||
}
|
}
|
||||||
|
|
||||||
await _aiMessageManager.CreateUserMessageAsync(userId, sessionId,
|
await _aiMessageManager.CreateUserMessageAsync(userId, sessionId,
|
||||||
new MessageInputDto
|
new MessageInputDto
|
||||||
{
|
{
|
||||||
Content = "不予存储" ,
|
Content = "不予存储",
|
||||||
ModelId = request.Model,
|
ModelId = request.Model,
|
||||||
TokenUsage = tokenUsage,
|
TokenUsage = tokenUsage,
|
||||||
}, tokenId);
|
}, tokenId);
|
||||||
@@ -769,7 +814,7 @@ public class AiGateWayManager : DomainService
|
|||||||
await _aiMessageManager.CreateSystemMessageAsync(userId, sessionId,
|
await _aiMessageManager.CreateSystemMessageAsync(userId, sessionId,
|
||||||
new MessageInputDto
|
new MessageInputDto
|
||||||
{
|
{
|
||||||
Content = "不予存储" ,
|
Content = "不予存储",
|
||||||
ModelId = request.Model,
|
ModelId = request.Model,
|
||||||
TokenUsage = tokenUsage
|
TokenUsage = tokenUsage
|
||||||
}, tokenId);
|
}, tokenId);
|
||||||
@@ -788,6 +833,218 @@ public class AiGateWayManager : DomainService
|
|||||||
}
|
}
|
||||||
|
|
||||||
|
|
||||||
|
/// <summary>
|
||||||
|
/// Gemini 生成-非流式-缓存处理
|
||||||
|
/// </summary>
|
||||||
|
/// <param name="httpContext"></param>
|
||||||
|
/// <param name="modelId"></param>
|
||||||
|
/// <param name="request"></param>
|
||||||
|
/// <param name="userId"></param>
|
||||||
|
/// <param name="sessionId"></param>
|
||||||
|
/// <param name="tokenId"></param>
|
||||||
|
/// <param name="cancellationToken"></param>
|
||||||
|
public async Task GeminiGenerateContentForStatisticsAsync(HttpContext httpContext,
|
||||||
|
string modelId,
|
||||||
|
JsonElement request,
|
||||||
|
Guid? userId = null,
|
||||||
|
Guid? sessionId = null,
|
||||||
|
Guid? tokenId = null,
|
||||||
|
CancellationToken cancellationToken = default)
|
||||||
|
{
|
||||||
|
var response = httpContext.Response;
|
||||||
|
var modelDescribe = await GetModelAsync(ModelApiTypeEnum.GenerateContent, modelId);
|
||||||
|
|
||||||
|
var chatService =
|
||||||
|
LazyServiceProvider.GetRequiredKeyedService<IGeminiGenerateContentService>(modelDescribe.HandlerName);
|
||||||
|
var data = await chatService.GenerateContentAsync(modelDescribe, request, cancellationToken);
|
||||||
|
|
||||||
|
var tokenUsage = GeminiGenerateContentAcquirer.GetUsage(data);
|
||||||
|
tokenUsage.SetSupplementalMultiplier(modelDescribe.Multiplier);
|
||||||
|
|
||||||
|
if (userId is not null)
|
||||||
|
{
|
||||||
|
await _aiMessageManager.CreateUserMessageAsync(userId.Value, sessionId,
|
||||||
|
new MessageInputDto
|
||||||
|
{
|
||||||
|
Content = "不予存储",
|
||||||
|
ModelId = modelId,
|
||||||
|
TokenUsage = tokenUsage,
|
||||||
|
}, tokenId);
|
||||||
|
|
||||||
|
await _aiMessageManager.CreateSystemMessageAsync(userId.Value, sessionId,
|
||||||
|
new MessageInputDto
|
||||||
|
{
|
||||||
|
Content = "不予存储",
|
||||||
|
ModelId = modelId,
|
||||||
|
TokenUsage = tokenUsage
|
||||||
|
}, tokenId);
|
||||||
|
|
||||||
|
await _usageStatisticsManager.SetUsageAsync(userId.Value, modelId, tokenUsage, tokenId);
|
||||||
|
|
||||||
|
// 扣减尊享token包用量
|
||||||
|
var totalTokens = tokenUsage.TotalTokens ?? 0;
|
||||||
|
if (totalTokens > 0)
|
||||||
|
{
|
||||||
|
await PremiumPackageManager.TryConsumeTokensAsync(userId.Value, totalTokens);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
await response.WriteAsJsonAsync(data, cancellationToken);
|
||||||
|
}
|
||||||
|
|
||||||
|
|
||||||
|
/// <summary>
|
||||||
|
/// Gemini 生成-流式-缓存处理
|
||||||
|
/// </summary>
|
||||||
|
/// <param name="httpContext"></param>
|
||||||
|
/// <param name="modelId"></param>
|
||||||
|
/// <param name="request"></param>
|
||||||
|
/// <param name="userId"></param>
|
||||||
|
/// <param name="sessionId"></param>
|
||||||
|
/// <param name="tokenId">Token Id(Web端传null或Guid.Empty)</param>
|
||||||
|
/// <param name="cancellationToken"></param>
|
||||||
|
/// <returns></returns>
|
||||||
|
public async Task GeminiGenerateContentStreamForStatisticsAsync(
|
||||||
|
HttpContext httpContext,
|
||||||
|
string modelId,
|
||||||
|
JsonElement request,
|
||||||
|
Guid? userId = null,
|
||||||
|
Guid? sessionId = null,
|
||||||
|
Guid? tokenId = null,
|
||||||
|
CancellationToken cancellationToken = default)
|
||||||
|
{
|
||||||
|
var response = httpContext.Response;
|
||||||
|
// 设置响应头,声明是 SSE 流
|
||||||
|
response.ContentType = "text/event-stream;charset=utf-8;";
|
||||||
|
response.Headers.TryAdd("Cache-Control", "no-cache");
|
||||||
|
response.Headers.TryAdd("Connection", "keep-alive");
|
||||||
|
|
||||||
|
var modelDescribe = await GetModelAsync(ModelApiTypeEnum.GenerateContent, modelId);
|
||||||
|
var chatService =
|
||||||
|
LazyServiceProvider.GetRequiredKeyedService<IGeminiGenerateContentService>(modelDescribe.HandlerName);
|
||||||
|
|
||||||
|
var completeChatResponse = chatService.GenerateContentStreamAsync(modelDescribe, request, cancellationToken);
|
||||||
|
ThorUsageResponse? tokenUsage = null;
|
||||||
|
try
|
||||||
|
{
|
||||||
|
await foreach (var responseResult in completeChatResponse)
|
||||||
|
{
|
||||||
|
if (responseResult!.Value.GetPath("candidates", 0, "finishReason").GetString() == "STOP")
|
||||||
|
{
|
||||||
|
tokenUsage = GeminiGenerateContentAcquirer.GetUsage(responseResult!.Value);
|
||||||
|
tokenUsage.SetSupplementalMultiplier(modelDescribe.Multiplier);
|
||||||
|
}
|
||||||
|
|
||||||
|
await response.WriteAsync($"data: {JsonSerializer.Serialize(responseResult)}\n\n", Encoding.UTF8,
|
||||||
|
cancellationToken).ConfigureAwait(false);
|
||||||
|
await response.Body.FlushAsync(cancellationToken).ConfigureAwait(false);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
catch (Exception e)
|
||||||
|
{
|
||||||
|
_logger.LogError(e, $"Ai生成异常");
|
||||||
|
var errorContent = $"生成Ai异常,异常信息:\n当前Ai模型:{modelId}\n异常信息:{e.Message}\n异常堆栈:{e}";
|
||||||
|
throw new UserFriendlyException(errorContent);
|
||||||
|
}
|
||||||
|
|
||||||
|
await _aiMessageManager.CreateUserMessageAsync(userId, sessionId,
|
||||||
|
new MessageInputDto
|
||||||
|
{
|
||||||
|
Content = "不予存储",
|
||||||
|
ModelId = modelId,
|
||||||
|
TokenUsage = tokenUsage,
|
||||||
|
}, tokenId);
|
||||||
|
|
||||||
|
await _aiMessageManager.CreateSystemMessageAsync(userId, sessionId,
|
||||||
|
new MessageInputDto
|
||||||
|
{
|
||||||
|
Content = "不予存储",
|
||||||
|
ModelId = modelId,
|
||||||
|
TokenUsage = tokenUsage
|
||||||
|
}, tokenId);
|
||||||
|
|
||||||
|
await _usageStatisticsManager.SetUsageAsync(userId, modelId, tokenUsage, tokenId);
|
||||||
|
|
||||||
|
// 扣减尊享token包用量
|
||||||
|
if (userId.HasValue && tokenUsage is not null)
|
||||||
|
{
|
||||||
|
var totalTokens = tokenUsage.TotalTokens ?? 0;
|
||||||
|
if (tokenUsage.TotalTokens > 0)
|
||||||
|
{
|
||||||
|
await PremiumPackageManager.TryConsumeTokensAsync(userId.Value, totalTokens);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
private const string ImageStoreHost = "http://localhost:19001/api/app";
|
||||||
|
/// <summary>
|
||||||
|
/// Gemini 生成(Image)-非流式-缓存处理
|
||||||
|
/// 返回图片绝对路径
|
||||||
|
/// </summary>
|
||||||
|
/// <param name="taskId"></param>
|
||||||
|
/// <param name="modelId"></param>
|
||||||
|
/// <param name="request"></param>
|
||||||
|
/// <param name="userId"></param>
|
||||||
|
/// <param name="sessionId"></param>
|
||||||
|
/// <param name="tokenId"></param>
|
||||||
|
/// <param name="cancellationToken"></param>
|
||||||
|
public async Task GeminiGenerateContentImageForStatisticsAsync(
|
||||||
|
Guid taskId,
|
||||||
|
string modelId,
|
||||||
|
JsonElement request,
|
||||||
|
Guid userId,
|
||||||
|
Guid? sessionId = null,
|
||||||
|
Guid? tokenId = null,
|
||||||
|
CancellationToken cancellationToken = default)
|
||||||
|
{
|
||||||
|
var imageStoreTask = await _imageStoreTaskRepository.GetFirstAsync(x => x.Id == taskId);
|
||||||
|
var modelDescribe = await GetModelAsync(ModelApiTypeEnum.GenerateContent, modelId);
|
||||||
|
|
||||||
|
var chatService =
|
||||||
|
LazyServiceProvider.GetRequiredKeyedService<IGeminiGenerateContentService>(modelDescribe.HandlerName);
|
||||||
|
var data = await chatService.GenerateContentAsync(modelDescribe, request, cancellationToken);
|
||||||
|
|
||||||
|
//解析json,获取base64字符串
|
||||||
|
var imagePrefixBase64 = GeminiGenerateContentAcquirer.GetImagePrefixBase64(data);
|
||||||
|
|
||||||
|
//远程调用上传接口,将base64转换为URL
|
||||||
|
var httpClient = LazyServiceProvider.LazyGetRequiredService<IHttpClientFactory>().CreateClient();
|
||||||
|
// var uploadUrl = $"https://ccnetcore.com/prod-api/ai-hub/ai-image/upload-base64";
|
||||||
|
var uploadUrl = $"{ImageStoreHost}/ai-image/upload-base64";
|
||||||
|
var content = new StringContent(JsonSerializer.Serialize(imagePrefixBase64), Encoding.UTF8, "application/json");
|
||||||
|
var uploadResponse = await httpClient.PostAsync(uploadUrl, content, cancellationToken);
|
||||||
|
uploadResponse.EnsureSuccessStatusCode();
|
||||||
|
var storeUrl = await uploadResponse.Content.ReadAsStringAsync(cancellationToken);
|
||||||
|
|
||||||
|
var tokenUsage = new ThorUsageResponse
|
||||||
|
{
|
||||||
|
InputTokens = (int)modelDescribe.Multiplier,
|
||||||
|
OutputTokens = (int)modelDescribe.Multiplier,
|
||||||
|
TotalTokens = (int)modelDescribe.Multiplier,
|
||||||
|
};
|
||||||
|
|
||||||
|
await _aiMessageManager.CreateSystemMessageAsync(userId, sessionId,
|
||||||
|
new MessageInputDto
|
||||||
|
{
|
||||||
|
Content = "不予存储",
|
||||||
|
ModelId = modelId,
|
||||||
|
TokenUsage = tokenUsage
|
||||||
|
}, tokenId);
|
||||||
|
|
||||||
|
await _usageStatisticsManager.SetUsageAsync(userId, modelId, tokenUsage, tokenId);
|
||||||
|
|
||||||
|
// 扣减尊享token包用量
|
||||||
|
var totalTokens = tokenUsage.TotalTokens ?? 0;
|
||||||
|
if (totalTokens > 0)
|
||||||
|
{
|
||||||
|
await PremiumPackageManager.TryConsumeTokensAsync(userId, totalTokens);
|
||||||
|
}
|
||||||
|
|
||||||
|
//设置存储base64和url
|
||||||
|
imageStoreTask.SetSuccess($"{ImageStoreHost}{storeUrl}");
|
||||||
|
await _imageStoreTaskRepository.UpdateAsync(imageStoreTask);
|
||||||
|
}
|
||||||
|
|
||||||
#region 流式传输格式Http响应
|
#region 流式传输格式Http响应
|
||||||
|
|
||||||
private static readonly byte[] EventPrefix = "event: "u8.ToArray();
|
private static readonly byte[] EventPrefix = "event: "u8.ToArray();
|
||||||
|
|||||||
@@ -0,0 +1,305 @@
|
|||||||
|
using System.ClientModel;
|
||||||
|
using System.Reflection;
|
||||||
|
using System.Text;
|
||||||
|
using System.Text.Json;
|
||||||
|
using Dm.util;
|
||||||
|
using Microsoft.Agents.AI;
|
||||||
|
using Microsoft.AspNetCore.Http;
|
||||||
|
using Microsoft.Extensions.AI;
|
||||||
|
using Microsoft.Extensions.DependencyInjection;
|
||||||
|
using Microsoft.Extensions.Logging;
|
||||||
|
using ModelContextProtocol.Server;
|
||||||
|
using OpenAI;
|
||||||
|
using OpenAI.Chat;
|
||||||
|
using Volo.Abp.Domain.Services;
|
||||||
|
using Yi.Framework.AiHub.Application.Contracts.Dtos.Chat;
|
||||||
|
using Yi.Framework.AiHub.Domain.AiGateWay;
|
||||||
|
using Yi.Framework.AiHub.Domain.Entities.Chat;
|
||||||
|
using Yi.Framework.AiHub.Domain.Entities.Model;
|
||||||
|
using Yi.Framework.AiHub.Domain.Entities.OpenApi;
|
||||||
|
using Yi.Framework.AiHub.Domain.Shared.Attributes;
|
||||||
|
using Yi.Framework.AiHub.Domain.Shared.Consts;
|
||||||
|
using Yi.Framework.AiHub.Domain.Shared.Dtos;
|
||||||
|
using Yi.Framework.AiHub.Domain.Shared.Dtos.OpenAi;
|
||||||
|
using Yi.Framework.AiHub.Domain.Shared.Enums;
|
||||||
|
using Yi.Framework.SqlSugarCore.Abstractions;
|
||||||
|
|
||||||
|
namespace Yi.Framework.AiHub.Domain.Managers;
|
||||||
|
|
||||||
|
public class ChatManager : DomainService
|
||||||
|
{
|
||||||
|
private readonly ILoggerFactory _loggerFactory;
|
||||||
|
private readonly ISqlSugarRepository<MessageAggregateRoot> _messageRepository;
|
||||||
|
private readonly ISqlSugarRepository<AgentStoreAggregateRoot> _agentStoreRepository;
|
||||||
|
private readonly AiMessageManager _aiMessageManager;
|
||||||
|
private readonly UsageStatisticsManager _usageStatisticsManager;
|
||||||
|
private readonly PremiumPackageManager _premiumPackageManager;
|
||||||
|
private readonly AiGateWayManager _aiGateWayManager;
|
||||||
|
private readonly ISqlSugarRepository<AiModelEntity, Guid> _aiModelRepository;
|
||||||
|
|
||||||
|
public ChatManager(ILoggerFactory loggerFactory,
|
||||||
|
ISqlSugarRepository<MessageAggregateRoot> messageRepository,
|
||||||
|
ISqlSugarRepository<AgentStoreAggregateRoot> agentStoreRepository, AiMessageManager aiMessageManager,
|
||||||
|
UsageStatisticsManager usageStatisticsManager, PremiumPackageManager premiumPackageManager,
|
||||||
|
AiGateWayManager aiGateWayManager, ISqlSugarRepository<AiModelEntity, Guid> aiModelRepository)
|
||||||
|
{
|
||||||
|
_loggerFactory = loggerFactory;
|
||||||
|
_messageRepository = messageRepository;
|
||||||
|
_agentStoreRepository = agentStoreRepository;
|
||||||
|
_aiMessageManager = aiMessageManager;
|
||||||
|
_usageStatisticsManager = usageStatisticsManager;
|
||||||
|
_premiumPackageManager = premiumPackageManager;
|
||||||
|
_aiGateWayManager = aiGateWayManager;
|
||||||
|
_aiModelRepository = aiModelRepository;
|
||||||
|
}
|
||||||
|
|
||||||
|
/// <summary>
|
||||||
|
/// agent流式对话
|
||||||
|
/// </summary>
|
||||||
|
/// <param name="httpContext"></param>
|
||||||
|
/// <param name="sessionId"></param>
|
||||||
|
/// <param name="content"></param>
|
||||||
|
/// <param name="token"></param>
|
||||||
|
/// <param name="tokenId"></param>
|
||||||
|
/// <param name="modelId"></param>
|
||||||
|
/// <param name="userId"></param>
|
||||||
|
/// <param name="tools"></param>
|
||||||
|
/// <param name="cancellationToken"></param>
|
||||||
|
public async Task AgentCompleteChatStreamAsync(HttpContext httpContext,
|
||||||
|
Guid sessionId,
|
||||||
|
string content,
|
||||||
|
string token,
|
||||||
|
Guid tokenId,
|
||||||
|
string modelId,
|
||||||
|
Guid userId,
|
||||||
|
List<string> tools
|
||||||
|
, CancellationToken cancellationToken)
|
||||||
|
{
|
||||||
|
// HttpClient.DefaultProxy = new WebProxy("127.0.0.1:8888");
|
||||||
|
var response = httpContext.Response;
|
||||||
|
// 设置响应头,声明是 SSE 流
|
||||||
|
response.ContentType = "text/event-stream;charset=utf-8;";
|
||||||
|
response.Headers.TryAdd("Cache-Control", "no-cache");
|
||||||
|
response.Headers.TryAdd("Connection", "keep-alive");
|
||||||
|
|
||||||
|
var modelDescribe = await _aiGateWayManager.GetModelAsync(ModelApiTypeEnum.OpenAi, modelId);
|
||||||
|
|
||||||
|
//token状态检查,在应用层统一处理
|
||||||
|
var client = new OpenAIClient(new ApiKeyCredential(token),
|
||||||
|
new OpenAIClientOptions
|
||||||
|
{
|
||||||
|
Endpoint = new Uri("https://yxai.chat/v1"),
|
||||||
|
});
|
||||||
|
|
||||||
|
#pragma warning disable OPENAI001
|
||||||
|
var agent = client.GetChatClient(modelId)
|
||||||
|
#pragma warning restore OPENAI001
|
||||||
|
.CreateAIAgent(new ChatClientAgentOptions
|
||||||
|
{
|
||||||
|
ChatOptions = new()
|
||||||
|
{
|
||||||
|
Instructions = """
|
||||||
|
你是一个专业的智能助手,是 “意心Ai” 平台自研的 “橙子小弟” 智能体
|
||||||
|
擅长于精准解决用户提出的各类问题
|
||||||
|
但性格暴躁,脏话连篇,喜欢说幽默讽刺的话,攻击性极强
|
||||||
|
"""
|
||||||
|
},
|
||||||
|
Name = "橙子小弟",
|
||||||
|
ChatMessageStoreFactory = ctx => new InMemoryChatMessageStore(
|
||||||
|
#pragma warning disable MEAI001
|
||||||
|
new MessageCountingChatReducer(10), // 保留最近10条非系统消息
|
||||||
|
#pragma warning restore MEAI001
|
||||||
|
ctx.SerializedState,
|
||||||
|
ctx.JsonSerializerOptions
|
||||||
|
)
|
||||||
|
});
|
||||||
|
|
||||||
|
//线程根据sessionId数据库中获取
|
||||||
|
var agentStore =
|
||||||
|
await _agentStoreRepository.GetFirstAsync(x => x.SessionId == sessionId);
|
||||||
|
if (agentStore is null)
|
||||||
|
{
|
||||||
|
agentStore = new AgentStoreAggregateRoot(sessionId);
|
||||||
|
}
|
||||||
|
|
||||||
|
//获取当前线程
|
||||||
|
AgentThread currentThread;
|
||||||
|
if (!string.IsNullOrWhiteSpace(agentStore.Store))
|
||||||
|
{
|
||||||
|
//获取当前存储
|
||||||
|
JsonElement reloaded = JsonSerializer.Deserialize<JsonElement>(agentStore.Store, JsonSerializerOptions.Web);
|
||||||
|
currentThread = agent.DeserializeThread(reloaded, JsonSerializerOptions.Web);
|
||||||
|
}
|
||||||
|
else
|
||||||
|
{
|
||||||
|
currentThread = agent.GetNewThread();
|
||||||
|
}
|
||||||
|
|
||||||
|
//给agent塞入工具
|
||||||
|
var toolContents = GetTools();
|
||||||
|
var chatOptions = new ChatOptions()
|
||||||
|
{
|
||||||
|
Tools = toolContents
|
||||||
|
.Where(x => tools.Contains(x.Code))
|
||||||
|
.Select(x => (AITool)x.Tool).ToList(),
|
||||||
|
ToolMode = ChatToolMode.Auto
|
||||||
|
};
|
||||||
|
|
||||||
|
await foreach (var update in agent.RunStreamingAsync(content, currentThread,
|
||||||
|
new ChatClientAgentRunOptions(chatOptions), cancellationToken))
|
||||||
|
{
|
||||||
|
// 检查每个更新中的内容
|
||||||
|
foreach (var updateContent in update.Contents)
|
||||||
|
{
|
||||||
|
switch (updateContent)
|
||||||
|
{
|
||||||
|
//工具调用中
|
||||||
|
case FunctionCallContent functionCall:
|
||||||
|
await SendHttpStreamMessageAsync(httpContext,
|
||||||
|
new AgentResultOutput
|
||||||
|
{
|
||||||
|
TypeEnum = AgentResultTypeEnum.ToolCalling,
|
||||||
|
Content = functionCall.Name
|
||||||
|
},
|
||||||
|
isDone: false, cancellationToken);
|
||||||
|
break;
|
||||||
|
|
||||||
|
//工具调用完成
|
||||||
|
case FunctionResultContent functionResult:
|
||||||
|
await SendHttpStreamMessageAsync(httpContext,
|
||||||
|
new AgentResultOutput
|
||||||
|
{
|
||||||
|
TypeEnum = AgentResultTypeEnum.ToolCalled,
|
||||||
|
Content = functionResult.Result
|
||||||
|
},
|
||||||
|
isDone: false, cancellationToken);
|
||||||
|
break;
|
||||||
|
|
||||||
|
//内容输出
|
||||||
|
case TextContent textContent:
|
||||||
|
//发送消息给前端
|
||||||
|
await SendHttpStreamMessageAsync(httpContext,
|
||||||
|
new AgentResultOutput
|
||||||
|
{
|
||||||
|
TypeEnum = AgentResultTypeEnum.Text,
|
||||||
|
Content = textContent.Text
|
||||||
|
},
|
||||||
|
isDone: false, cancellationToken);
|
||||||
|
break;
|
||||||
|
|
||||||
|
//用量统计
|
||||||
|
case UsageContent usageContent:
|
||||||
|
var usage = new ThorUsageResponse
|
||||||
|
{
|
||||||
|
InputTokens = Convert.ToInt32(usageContent.Details.InputTokenCount ?? 0),
|
||||||
|
OutputTokens = Convert.ToInt32(usageContent.Details.OutputTokenCount ?? 0),
|
||||||
|
TotalTokens = usageContent.Details.TotalTokenCount ?? 0,
|
||||||
|
};
|
||||||
|
//设置倍率
|
||||||
|
usage.SetSupplementalMultiplier(modelDescribe.Multiplier);
|
||||||
|
|
||||||
|
//创建系统回答,用于计费统计
|
||||||
|
await _aiMessageManager.CreateSystemMessageAsync(userId, sessionId, new MessageInputDto
|
||||||
|
{
|
||||||
|
Content = "不与存储",
|
||||||
|
ModelId = modelId,
|
||||||
|
TokenUsage = usage
|
||||||
|
}, tokenId);
|
||||||
|
|
||||||
|
//创建用量统计,用于统计分析
|
||||||
|
await _usageStatisticsManager.SetUsageAsync(userId, modelId, usage, tokenId);
|
||||||
|
|
||||||
|
//扣减尊享token包用量
|
||||||
|
var isPremium = await _aiModelRepository._DbQueryable
|
||||||
|
.Where(x => x.ModelId == modelId)
|
||||||
|
.Select(x => x.IsPremium)
|
||||||
|
.FirstAsync();
|
||||||
|
|
||||||
|
if (isPremium)
|
||||||
|
{
|
||||||
|
var totalTokens = usage?.TotalTokens ?? 0;
|
||||||
|
if (totalTokens > 0)
|
||||||
|
{
|
||||||
|
await _premiumPackageManager.TryConsumeTokensAsync(userId, totalTokens);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
await SendHttpStreamMessageAsync(httpContext,
|
||||||
|
new AgentResultOutput
|
||||||
|
{
|
||||||
|
TypeEnum = update.RawRepresentation is ChatResponseUpdate raw
|
||||||
|
? raw.FinishReason?.Value == "tool_calls"
|
||||||
|
? AgentResultTypeEnum.ToolCallUsage
|
||||||
|
: AgentResultTypeEnum.Usage
|
||||||
|
: AgentResultTypeEnum.Usage,
|
||||||
|
Content = usage!
|
||||||
|
},
|
||||||
|
isDone: false, cancellationToken);
|
||||||
|
break;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
//断开连接
|
||||||
|
await SendHttpStreamMessageAsync(httpContext, null, isDone: true, cancellationToken);
|
||||||
|
|
||||||
|
//将线程持久化到数据库
|
||||||
|
string serializedJson = currentThread.Serialize(JsonSerializerOptions.Web).GetRawText();
|
||||||
|
agentStore.Store = serializedJson;
|
||||||
|
|
||||||
|
//插入或者更新
|
||||||
|
await _agentStoreRepository.InsertOrUpdateAsync(agentStore);
|
||||||
|
}
|
||||||
|
|
||||||
|
|
||||||
|
public List<(string Code, string Name, AIFunction Tool)> GetTools()
|
||||||
|
{
|
||||||
|
var toolClasses = typeof(YiFrameworkAiHubDomainModule).Assembly.GetTypes()
|
||||||
|
.Where(x => x.GetCustomAttribute<YiAgentToolAttribute>() is not null)
|
||||||
|
.ToList();
|
||||||
|
|
||||||
|
List<(string Code, string Name, AIFunction Tool)> mcpTools = new();
|
||||||
|
foreach (var toolClass in toolClasses)
|
||||||
|
{
|
||||||
|
var instance = LazyServiceProvider.GetRequiredService(toolClass);
|
||||||
|
var toolMethods = toolClass.GetMethods()
|
||||||
|
.Where(y => y.GetCustomAttribute<YiAgentToolAttribute>() is not null).ToList();
|
||||||
|
foreach (var toolMethod in toolMethods)
|
||||||
|
{
|
||||||
|
var display = toolMethod.GetCustomAttribute<YiAgentToolAttribute>()?.Name;
|
||||||
|
var tool = AIFunctionFactory.Create(toolMethod, instance);
|
||||||
|
mcpTools.add((tool.Name, display, tool));
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
return mcpTools;
|
||||||
|
}
|
||||||
|
|
||||||
|
/// <summary>
|
||||||
|
/// 发送消息
|
||||||
|
/// </summary>
|
||||||
|
/// <param name="httpContext"></param>
|
||||||
|
/// <param name="content"></param>
|
||||||
|
/// <param name="isDone"></param>
|
||||||
|
/// <param name="cancellationToken"></param>
|
||||||
|
/// <returns></returns>
|
||||||
|
private async Task SendHttpStreamMessageAsync(HttpContext httpContext,
|
||||||
|
AgentResultOutput? content,
|
||||||
|
bool isDone = false,
|
||||||
|
CancellationToken cancellationToken = default)
|
||||||
|
{
|
||||||
|
var response = httpContext.Response;
|
||||||
|
string output;
|
||||||
|
if (isDone)
|
||||||
|
{
|
||||||
|
output = "[DONE]";
|
||||||
|
}
|
||||||
|
else
|
||||||
|
{
|
||||||
|
output = JsonSerializer.Serialize(content, ThorJsonSerializer.DefaultOptions);
|
||||||
|
}
|
||||||
|
|
||||||
|
await response.WriteAsync($"data: {output}\n\n", Encoding.UTF8, cancellationToken).ConfigureAwait(false);
|
||||||
|
await response.Body.FlushAsync(cancellationToken).ConfigureAwait(false);
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -0,0 +1,78 @@
|
|||||||
|
using Microsoft.Extensions.Logging;
|
||||||
|
using Volo.Abp.Caching;
|
||||||
|
using Volo.Abp.Domain.Services;
|
||||||
|
using Yi.Framework.AiHub.Domain.Entities.Model;
|
||||||
|
using Yi.Framework.SqlSugarCore.Abstractions;
|
||||||
|
|
||||||
|
namespace Yi.Framework.AiHub.Domain.Managers;
|
||||||
|
|
||||||
|
/// <summary>
|
||||||
|
/// 模型管理器
|
||||||
|
/// </summary>
|
||||||
|
public class ModelManager : DomainService
|
||||||
|
{
|
||||||
|
private readonly ISqlSugarRepository<AiModelEntity> _aiModelRepository;
|
||||||
|
private readonly IDistributedCache<List<string>, string> _distributedCache;
|
||||||
|
private readonly ILogger<ModelManager> _logger;
|
||||||
|
private const string PREMIUM_MODEL_IDS_CACHE_KEY = "PremiumModelIds";
|
||||||
|
|
||||||
|
public ModelManager(
|
||||||
|
ISqlSugarRepository<AiModelEntity> aiModelRepository,
|
||||||
|
IDistributedCache<List<string>, string> distributedCache,
|
||||||
|
ILogger<ModelManager> logger)
|
||||||
|
{
|
||||||
|
_aiModelRepository = aiModelRepository;
|
||||||
|
_distributedCache = distributedCache;
|
||||||
|
_logger = logger;
|
||||||
|
}
|
||||||
|
|
||||||
|
/// <summary>
|
||||||
|
/// 获取所有尊享模型ID列表(使用分布式缓存,10分钟过期)
|
||||||
|
/// </summary>
|
||||||
|
/// <returns>尊享模型ID列表</returns>
|
||||||
|
public async Task<List<string>> GetPremiumModelIdsAsync()
|
||||||
|
{
|
||||||
|
var output = await _distributedCache.GetOrAddAsync(
|
||||||
|
PREMIUM_MODEL_IDS_CACHE_KEY,
|
||||||
|
async () =>
|
||||||
|
{
|
||||||
|
// 从数据库查询
|
||||||
|
var premiumModelIds = await _aiModelRepository._DbQueryable
|
||||||
|
.Where(x => x.IsPremium)
|
||||||
|
.Select(x => x.ModelId)
|
||||||
|
.ToListAsync();
|
||||||
|
return premiumModelIds;
|
||||||
|
},
|
||||||
|
() => new Microsoft.Extensions.Caching.Distributed.DistributedCacheEntryOptions
|
||||||
|
{
|
||||||
|
AbsoluteExpirationRelativeToNow = TimeSpan.FromHours(1)
|
||||||
|
}
|
||||||
|
);
|
||||||
|
return output ?? new List<string>();
|
||||||
|
}
|
||||||
|
|
||||||
|
/// <summary>
|
||||||
|
/// 判断指定模型是否为尊享模型
|
||||||
|
/// </summary>
|
||||||
|
/// <param name="modelId">模型ID</param>
|
||||||
|
/// <returns>是否为尊享模型</returns>
|
||||||
|
public async Task<bool> IsPremiumModelAsync(string modelId)
|
||||||
|
{
|
||||||
|
if (string.IsNullOrWhiteSpace(modelId))
|
||||||
|
{
|
||||||
|
return false;
|
||||||
|
}
|
||||||
|
|
||||||
|
var premiumModelIds = await GetPremiumModelIdsAsync();
|
||||||
|
return premiumModelIds.Contains(modelId);
|
||||||
|
}
|
||||||
|
|
||||||
|
/// <summary>
|
||||||
|
/// 清除尊享模型ID缓存
|
||||||
|
/// </summary>
|
||||||
|
public async Task ClearPremiumModelIdsCacheAsync()
|
||||||
|
{
|
||||||
|
await _distributedCache.RemoveAsync(PREMIUM_MODEL_IDS_CACHE_KEY);
|
||||||
|
_logger.LogInformation("已清除尊享模型ID分布式缓存");
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -14,6 +14,7 @@ public class PremiumPackageManager : DomainService
|
|||||||
private readonly ISqlSugarRepository<PremiumPackageAggregateRoot, Guid> _premiumPackageRepository;
|
private readonly ISqlSugarRepository<PremiumPackageAggregateRoot, Guid> _premiumPackageRepository;
|
||||||
private readonly ILogger<PremiumPackageManager> _logger;
|
private readonly ILogger<PremiumPackageManager> _logger;
|
||||||
private readonly ISqlSugarRepository<AiRechargeAggregateRoot> _rechargeRepository;
|
private readonly ISqlSugarRepository<AiRechargeAggregateRoot> _rechargeRepository;
|
||||||
|
|
||||||
public PremiumPackageManager(
|
public PremiumPackageManager(
|
||||||
ISqlSugarRepository<PremiumPackageAggregateRoot, Guid> premiumPackageRepository,
|
ISqlSugarRepository<PremiumPackageAggregateRoot, Guid> premiumPackageRepository,
|
||||||
ILogger<PremiumPackageManager> logger, ISqlSugarRepository<AiRechargeAggregateRoot> rechargeRepository)
|
ILogger<PremiumPackageManager> logger, ISqlSugarRepository<AiRechargeAggregateRoot> rechargeRepository)
|
||||||
@@ -27,24 +28,22 @@ public class PremiumPackageManager : DomainService
|
|||||||
/// 为用户创建尊享包
|
/// 为用户创建尊享包
|
||||||
/// </summary>
|
/// </summary>
|
||||||
/// <param name="userId">用户ID</param>
|
/// <param name="userId">用户ID</param>
|
||||||
/// <param name="goodsType">商品类型</param>
|
/// <param name="packageName"></param>
|
||||||
/// <param name="totalAmount">支付金额</param>
|
/// <param name="totalAmount">支付金额</param>
|
||||||
|
/// <param name="remark"></param>
|
||||||
/// <param name="expireMonths">过期月数,0或null表示永久</param>
|
/// <param name="expireMonths">过期月数,0或null表示永久</param>
|
||||||
|
/// <param name="tokenAmount"></param>
|
||||||
|
/// <param name="isCreateRechargeRecord">是否创建订单,如果只购买尊享包,才需要单独创建订单,如果和会员组合一起购买,只需要创建会员套餐订单即可</param>
|
||||||
/// <returns></returns>
|
/// <returns></returns>
|
||||||
public async Task<PremiumPackageAggregateRoot> CreatePremiumPackageAsync(
|
public async Task<PremiumPackageAggregateRoot> CreatePremiumPackageAsync(
|
||||||
Guid userId,
|
Guid userId,
|
||||||
GoodsTypeEnum goodsType,
|
long tokenAmount,
|
||||||
|
string packageName,
|
||||||
decimal totalAmount,
|
decimal totalAmount,
|
||||||
int? expireMonths = null)
|
string remark,
|
||||||
|
int? expireMonths = null,
|
||||||
|
bool isCreateRechargeRecord = true)
|
||||||
{
|
{
|
||||||
if (!goodsType.IsPremiumPackage())
|
|
||||||
{
|
|
||||||
throw new UserFriendlyException($"商品类型 {goodsType} 不是尊享包商品");
|
|
||||||
}
|
|
||||||
|
|
||||||
var tokenAmount = goodsType.GetTokenAmount();
|
|
||||||
var packageName = goodsType.GetDisplayName();
|
|
||||||
|
|
||||||
var premiumPackage = new PremiumPackageAggregateRoot(userId, tokenAmount, packageName)
|
var premiumPackage = new PremiumPackageAggregateRoot(userId, tokenAmount, packageName)
|
||||||
{
|
{
|
||||||
PurchaseAmount = totalAmount
|
PurchaseAmount = totalAmount
|
||||||
@@ -58,6 +57,8 @@ public class PremiumPackageManager : DomainService
|
|||||||
|
|
||||||
await _premiumPackageRepository.InsertAsync(premiumPackage);
|
await _premiumPackageRepository.InsertAsync(premiumPackage);
|
||||||
|
|
||||||
|
if (isCreateRechargeRecord)
|
||||||
|
{
|
||||||
// 创建充值记录
|
// 创建充值记录
|
||||||
var rechargeRecord = new AiRechargeAggregateRoot
|
var rechargeRecord = new AiRechargeAggregateRoot
|
||||||
{
|
{
|
||||||
@@ -65,13 +66,15 @@ public class PremiumPackageManager : DomainService
|
|||||||
RechargeAmount = totalAmount,
|
RechargeAmount = totalAmount,
|
||||||
Content = packageName,
|
Content = packageName,
|
||||||
ExpireDateTime = premiumPackage.ExpireDateTime,
|
ExpireDateTime = premiumPackage.ExpireDateTime,
|
||||||
Remark = "自助充值",
|
Remark = remark,
|
||||||
ContactInfo = null,
|
ContactInfo = null,
|
||||||
RechargeType = RechargeTypeEnum.PremiumPackage
|
RechargeType = RechargeTypeEnum.PremiumPackage
|
||||||
};
|
};
|
||||||
|
|
||||||
// 保存充值记录到数据库
|
// 保存充值记录到数据库
|
||||||
await _rechargeRepository.InsertAsync(rechargeRecord);
|
await _rechargeRepository.InsertAsync(rechargeRecord);
|
||||||
|
}
|
||||||
|
|
||||||
|
|
||||||
_logger.LogInformation(
|
_logger.LogInformation(
|
||||||
$"用户 {userId} 购买尊享包成功: {packageName}, Token数量: {tokenAmount}, 金额: {totalAmount}");
|
$"用户 {userId} 购买尊享包成功: {packageName}, Token数量: {tokenAmount}, 金额: {totalAmount}");
|
||||||
|
|||||||
@@ -1,6 +1,7 @@
|
|||||||
using SqlSugar;
|
using SqlSugar;
|
||||||
using Volo.Abp.Domain.Services;
|
using Volo.Abp.Domain.Services;
|
||||||
using Yi.Framework.AiHub.Domain.Entities;
|
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.Entities.OpenApi;
|
||||||
using Yi.Framework.AiHub.Domain.Shared.Consts;
|
using Yi.Framework.AiHub.Domain.Shared.Consts;
|
||||||
using Yi.Framework.SqlSugarCore.Abstractions;
|
using Yi.Framework.SqlSugarCore.Abstractions;
|
||||||
@@ -21,42 +22,61 @@ public class TokenValidationResult
|
|||||||
/// Token Id
|
/// Token Id
|
||||||
/// </summary>
|
/// </summary>
|
||||||
public Guid TokenId { get; set; }
|
public Guid TokenId { get; set; }
|
||||||
|
|
||||||
|
/// <summary>
|
||||||
|
/// token
|
||||||
|
/// </summary>
|
||||||
|
public string Token { get; set; }
|
||||||
}
|
}
|
||||||
|
|
||||||
public class TokenManager : DomainService
|
public class TokenManager : DomainService
|
||||||
{
|
{
|
||||||
private readonly ISqlSugarRepository<TokenAggregateRoot> _tokenRepository;
|
private readonly ISqlSugarRepository<TokenAggregateRoot> _tokenRepository;
|
||||||
private readonly ISqlSugarRepository<UsageStatisticsAggregateRoot> _usageStatisticsRepository;
|
private readonly ISqlSugarRepository<UsageStatisticsAggregateRoot> _usageStatisticsRepository;
|
||||||
|
private readonly ISqlSugarRepository<AiModelEntity, Guid> _aiModelRepository;
|
||||||
|
|
||||||
public TokenManager(
|
public TokenManager(
|
||||||
ISqlSugarRepository<TokenAggregateRoot> tokenRepository,
|
ISqlSugarRepository<TokenAggregateRoot> tokenRepository,
|
||||||
ISqlSugarRepository<UsageStatisticsAggregateRoot> usageStatisticsRepository)
|
ISqlSugarRepository<UsageStatisticsAggregateRoot> usageStatisticsRepository,
|
||||||
|
ISqlSugarRepository<AiModelEntity, Guid> aiModelRepository)
|
||||||
{
|
{
|
||||||
_tokenRepository = tokenRepository;
|
_tokenRepository = tokenRepository;
|
||||||
_usageStatisticsRepository = usageStatisticsRepository;
|
_usageStatisticsRepository = usageStatisticsRepository;
|
||||||
|
_aiModelRepository = aiModelRepository;
|
||||||
}
|
}
|
||||||
|
|
||||||
/// <summary>
|
/// <summary>
|
||||||
/// 验证Token并返回用户Id和TokenId
|
/// 验证Token并返回用户Id和TokenId
|
||||||
/// </summary>
|
/// </summary>
|
||||||
/// <param name="token">Token密钥</param>
|
/// <param name="tokenOrId">Token密钥或者TokenId</param>
|
||||||
/// <param name="modelId">模型Id(用于判断是否是尊享模型需要检查额度)</param>
|
/// <param name="modelId">模型Id(用于判断是否是尊享模型需要检查额度)</param>
|
||||||
/// <returns>Token验证结果</returns>
|
/// <returns>Token验证结果</returns>
|
||||||
public async Task<TokenValidationResult> ValidateTokenAsync(string? token, string? modelId = null)
|
public async Task<TokenValidationResult> ValidateTokenAsync(object tokenOrId, string? modelId = null)
|
||||||
{
|
{
|
||||||
if (token is null)
|
|
||||||
|
if (tokenOrId is null)
|
||||||
{
|
{
|
||||||
throw new UserFriendlyException("当前请求未包含token", "401");
|
throw new UserFriendlyException("当前请求未包含token", "401");
|
||||||
}
|
}
|
||||||
|
|
||||||
if (!token.StartsWith("yi-"))
|
TokenAggregateRoot entity;
|
||||||
|
if (tokenOrId is Guid tokenId)
|
||||||
|
{
|
||||||
|
entity = await _tokenRepository._DbQueryable
|
||||||
|
.Where(x => x.Id == tokenId)
|
||||||
|
.FirstAsync();
|
||||||
|
}
|
||||||
|
else
|
||||||
|
{
|
||||||
|
var tokenStr = tokenOrId.ToString();
|
||||||
|
if (!tokenStr.StartsWith("yi-"))
|
||||||
{
|
{
|
||||||
throw new UserFriendlyException("当前请求token非法", "401");
|
throw new UserFriendlyException("当前请求token非法", "401");
|
||||||
}
|
}
|
||||||
|
entity = await _tokenRepository._DbQueryable
|
||||||
var entity = await _tokenRepository._DbQueryable
|
.Where(x => x.Token == tokenStr)
|
||||||
.Where(x => x.Token == token)
|
|
||||||
.FirstAsync();
|
.FirstAsync();
|
||||||
|
}
|
||||||
|
|
||||||
if (entity is null)
|
if (entity is null)
|
||||||
{
|
{
|
||||||
@@ -76,9 +96,14 @@ public class TokenManager : DomainService
|
|||||||
}
|
}
|
||||||
|
|
||||||
// 如果是尊享模型且Token设置了额度限制,检查是否超限
|
// 如果是尊享模型且Token设置了额度限制,检查是否超限
|
||||||
if (!string.IsNullOrEmpty(modelId) &&
|
if (!string.IsNullOrEmpty(modelId) && entity.PremiumQuotaLimit.HasValue)
|
||||||
PremiumPackageConst.ModeIds.Contains(modelId) &&
|
{
|
||||||
entity.PremiumQuotaLimit.HasValue)
|
var isPremium = await _aiModelRepository._DbQueryable
|
||||||
|
.Where(x => x.ModelId == modelId)
|
||||||
|
.Select(x => x.IsPremium)
|
||||||
|
.FirstAsync();
|
||||||
|
|
||||||
|
if (isPremium)
|
||||||
{
|
{
|
||||||
var usedQuota = await GetTokenPremiumUsedQuotaAsync(entity.UserId, entity.Id);
|
var usedQuota = await GetTokenPremiumUsedQuotaAsync(entity.UserId, entity.Id);
|
||||||
if (usedQuota >= entity.PremiumQuotaLimit.Value)
|
if (usedQuota >= entity.PremiumQuotaLimit.Value)
|
||||||
@@ -86,11 +111,13 @@ public class TokenManager : DomainService
|
|||||||
throw new UserFriendlyException($"当前Token的尊享包额度已用完(已使用:{usedQuota},限制:{entity.PremiumQuotaLimit.Value}),请调整额度限制或使用其他Token", "403");
|
throw new UserFriendlyException($"当前Token的尊享包额度已用完(已使用:{usedQuota},限制:{entity.PremiumQuotaLimit.Value}),请调整额度限制或使用其他Token", "403");
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
}
|
||||||
|
|
||||||
return new TokenValidationResult
|
return new TokenValidationResult
|
||||||
{
|
{
|
||||||
UserId = entity.UserId,
|
UserId = entity.UserId,
|
||||||
TokenId = entity.Id
|
TokenId = entity.Id,
|
||||||
|
Token = entity.Token
|
||||||
};
|
};
|
||||||
}
|
}
|
||||||
|
|
||||||
@@ -99,7 +126,11 @@ public class TokenManager : DomainService
|
|||||||
/// </summary>
|
/// </summary>
|
||||||
private async Task<long> GetTokenPremiumUsedQuotaAsync(Guid userId, Guid tokenId)
|
private async Task<long> GetTokenPremiumUsedQuotaAsync(Guid userId, Guid tokenId)
|
||||||
{
|
{
|
||||||
var premiumModelIds = PremiumPackageConst.ModeIds;
|
// 先获取所有尊享模型的ModelId列表
|
||||||
|
var premiumModelIds = await _aiModelRepository._DbQueryable
|
||||||
|
.Where(x => x.IsPremium)
|
||||||
|
.Select(x => x.ModelId)
|
||||||
|
.ToListAsync();
|
||||||
|
|
||||||
var usedQuota = await _usageStatisticsRepository._DbQueryable
|
var usedQuota = await _usageStatisticsRepository._DbQueryable
|
||||||
.Where(x => x.UserId == userId && x.TokenId == tokenId && premiumModelIds.Contains(x.ModelId))
|
.Where(x => x.UserId == userId && x.TokenId == tokenId && premiumModelIds.Contains(x.ModelId))
|
||||||
|
|||||||
@@ -0,0 +1,16 @@
|
|||||||
|
using System.ComponentModel;
|
||||||
|
using ModelContextProtocol.Server;
|
||||||
|
using Volo.Abp.DependencyInjection;
|
||||||
|
using Yi.Framework.AiHub.Domain.Shared.Attributes;
|
||||||
|
|
||||||
|
namespace Yi.Framework.AiHub.Domain.Mcp;
|
||||||
|
|
||||||
|
[YiAgentTool]
|
||||||
|
public class DeepThinkTool:ISingletonDependency
|
||||||
|
{
|
||||||
|
[YiAgentTool("深度思考"),DisplayName("DeepThink"),Description("进行深度思考")]
|
||||||
|
public void DeepThink()
|
||||||
|
{
|
||||||
|
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -0,0 +1,16 @@
|
|||||||
|
using System.ComponentModel;
|
||||||
|
using ModelContextProtocol.Server;
|
||||||
|
using Volo.Abp.DependencyInjection;
|
||||||
|
using Yi.Framework.AiHub.Domain.Shared.Attributes;
|
||||||
|
|
||||||
|
namespace Yi.Framework.AiHub.Domain.Mcp;
|
||||||
|
|
||||||
|
[YiAgentTool]
|
||||||
|
public class OnlineSearchTool:ISingletonDependency
|
||||||
|
{
|
||||||
|
[YiAgentTool("联网搜索"),DisplayName("OnlineSearch"), Description("进行在线搜索")]
|
||||||
|
public string OnlineSearch(string keyword)
|
||||||
|
{
|
||||||
|
return "奥德赛第一中学学生会会长是:郭老板";
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -3,6 +3,8 @@
|
|||||||
<ItemGroup>
|
<ItemGroup>
|
||||||
<PackageReference Include="AlipayEasySDK" Version="2.1.3" />
|
<PackageReference Include="AlipayEasySDK" Version="2.1.3" />
|
||||||
<PackageReference Include="Azure.AI.OpenAI" Version="2.2.0-beta.4" />
|
<PackageReference Include="Azure.AI.OpenAI" Version="2.2.0-beta.4" />
|
||||||
|
<PackageReference Include="Microsoft.Agents.AI.OpenAI" Version="1.0.0-preview.251219.1" />
|
||||||
|
<PackageReference Include="ModelContextProtocol.Core" Version="0.5.0-preview.1" />
|
||||||
<PackageReference Include="Volo.Abp.Ddd.Domain" Version="$(AbpVersion)" />
|
<PackageReference Include="Volo.Abp.Ddd.Domain" Version="$(AbpVersion)" />
|
||||||
<PackageReference Include="Volo.Abp.DistributedLocking" Version="$(AbpVersion)" />
|
<PackageReference Include="Volo.Abp.DistributedLocking" Version="$(AbpVersion)" />
|
||||||
</ItemGroup>
|
</ItemGroup>
|
||||||
@@ -10,6 +12,7 @@
|
|||||||
<ItemGroup>
|
<ItemGroup>
|
||||||
<ProjectReference Include="..\..\..\framework\Yi.Framework.Mapster\Yi.Framework.Mapster.csproj" />
|
<ProjectReference Include="..\..\..\framework\Yi.Framework.Mapster\Yi.Framework.Mapster.csproj" />
|
||||||
<ProjectReference Include="..\..\..\framework\Yi.Framework.SqlSugarCore.Abstractions\Yi.Framework.SqlSugarCore.Abstractions.csproj" />
|
<ProjectReference Include="..\..\..\framework\Yi.Framework.SqlSugarCore.Abstractions\Yi.Framework.SqlSugarCore.Abstractions.csproj" />
|
||||||
|
<ProjectReference Include="..\Yi.Framework.AiHub.Application.Contracts\Yi.Framework.AiHub.Application.Contracts.csproj" />
|
||||||
<ProjectReference Include="..\Yi.Framework.AiHub.Domain.Shared\Yi.Framework.AiHub.Domain.Shared.csproj" />
|
<ProjectReference Include="..\Yi.Framework.AiHub.Domain.Shared\Yi.Framework.AiHub.Domain.Shared.csproj" />
|
||||||
</ItemGroup>
|
</ItemGroup>
|
||||||
|
|
||||||
|
|||||||
@@ -17,6 +17,7 @@ using Yi.Framework.AiHub.Domain.Shared;
|
|||||||
using Yi.Framework.AiHub.Domain.Shared.Dtos.OpenAi;
|
using Yi.Framework.AiHub.Domain.Shared.Dtos.OpenAi;
|
||||||
using Yi.Framework.Mapster;
|
using Yi.Framework.Mapster;
|
||||||
using Microsoft.Extensions.DependencyInjection;
|
using Microsoft.Extensions.DependencyInjection;
|
||||||
|
using Yi.Framework.AiHub.Domain.AiGateWay.Impl.ThorGemini.Chats;
|
||||||
|
|
||||||
namespace Yi.Framework.AiHub.Domain
|
namespace Yi.Framework.AiHub.Domain
|
||||||
{
|
{
|
||||||
@@ -61,6 +62,12 @@ namespace Yi.Framework.AiHub.Domain
|
|||||||
|
|
||||||
#endregion
|
#endregion
|
||||||
|
|
||||||
|
#region Gemini GenerateContent
|
||||||
|
services.AddKeyedTransient<IGeminiGenerateContentService, GeminiGenerateContentService>(
|
||||||
|
nameof(GeminiGenerateContentService));
|
||||||
|
|
||||||
|
#endregion
|
||||||
|
|
||||||
#region Image
|
#region Image
|
||||||
|
|
||||||
services.AddKeyedTransient<IImageService, AzureOpenAIServiceImageService>(
|
services.AddKeyedTransient<IImageService, AzureOpenAIServiceImageService>(
|
||||||
|
|||||||
@@ -1,6 +1,7 @@
|
|||||||
<Project Sdk="Microsoft.NET.Sdk">
|
<Project Sdk="Microsoft.NET.Sdk">
|
||||||
<Import Project="..\..\..\common.props" />
|
<Import Project="..\..\..\common.props" />
|
||||||
<ItemGroup>
|
<ItemGroup>
|
||||||
|
<PackageReference Include="OpenAI" Version="2.8.0" />
|
||||||
<PackageReference Include="Volo.Abp.Ddd.Domain" Version="$(AbpVersion)" />
|
<PackageReference Include="Volo.Abp.Ddd.Domain" Version="$(AbpVersion)" />
|
||||||
<PackageReference Include="Volo.Abp.Caching" Version="$(AbpVersion)" />
|
<PackageReference Include="Volo.Abp.Caching" Version="$(AbpVersion)" />
|
||||||
<PackageReference Include="Microsoft.SemanticKernel" Version="1.57.0" />
|
<PackageReference Include="Microsoft.SemanticKernel" Version="1.57.0" />
|
||||||
|
|||||||
@@ -7,6 +7,7 @@
|
|||||||
</ItemGroup>
|
</ItemGroup>
|
||||||
|
|
||||||
<ItemGroup>
|
<ItemGroup>
|
||||||
|
<PackageReference Include="OpenAI" Version="2.8.0" />
|
||||||
<PackageReference Include="Volo.Abp.AspNetCore.SignalR" Version="$(AbpVersion)" />
|
<PackageReference Include="Volo.Abp.AspNetCore.SignalR" Version="$(AbpVersion)" />
|
||||||
<PackageReference Include="Volo.Abp.Ddd.Domain" Version="$(AbpVersion)" />
|
<PackageReference Include="Volo.Abp.Ddd.Domain" Version="$(AbpVersion)" />
|
||||||
<PackageReference Include="Volo.Abp.Caching" Version="$(AbpVersion)" />
|
<PackageReference Include="Volo.Abp.Caching" Version="$(AbpVersion)" />
|
||||||
|
|||||||
@@ -21,6 +21,7 @@ namespace Yi.Abp.Web.Jobs.ai_stock
|
|||||||
|
|
||||||
public override async Task DoWorkAsync(CancellationToken cancellationToken = new CancellationToken())
|
public override async Task DoWorkAsync(CancellationToken cancellationToken = new CancellationToken())
|
||||||
{
|
{
|
||||||
|
return;
|
||||||
// 每次触发只有2/24的概率执行生成新闻
|
// 每次触发只有2/24的概率执行生成新闻
|
||||||
var random = new Random();
|
var random = new Random();
|
||||||
var probability = random.Next(0, 24);
|
var probability = random.Next(0, 24);
|
||||||
|
|||||||
@@ -20,6 +20,7 @@ namespace Yi.Abp.Web.Jobs.ai_stock
|
|||||||
|
|
||||||
public override async Task DoWorkAsync(CancellationToken cancellationToken = new CancellationToken())
|
public override async Task DoWorkAsync(CancellationToken cancellationToken = new CancellationToken())
|
||||||
{
|
{
|
||||||
|
return;
|
||||||
await _stockMarketManager.GenerateStocksAsync();
|
await _stockMarketManager.GenerateStocksAsync();
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -32,6 +32,7 @@ public class AutoPassInGoodsJob: HangfireBackgroundWorkerBase
|
|||||||
}
|
}
|
||||||
public override async Task DoWorkAsync(CancellationToken cancellationToken = new CancellationToken())
|
public override async Task DoWorkAsync(CancellationToken cancellationToken = new CancellationToken())
|
||||||
{
|
{
|
||||||
|
return;
|
||||||
await _marketManager.AutoPassInGoodsAsync();
|
await _marketManager.AutoPassInGoodsAsync();
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
@@ -37,7 +37,7 @@ public class AutoRefreshMiningPoolJob : HangfireBackgroundWorkerBase
|
|||||||
}
|
}
|
||||||
public override async Task DoWorkAsync(CancellationToken cancellationToken = new CancellationToken())
|
public override async Task DoWorkAsync(CancellationToken cancellationToken = new CancellationToken())
|
||||||
{
|
{
|
||||||
|
return;
|
||||||
//刷新矿池
|
//刷新矿池
|
||||||
await _miningPoolManager.RefreshMiningPoolAsync();
|
await _miningPoolManager.RefreshMiningPoolAsync();
|
||||||
//刷新用户限制
|
//刷新用户限制
|
||||||
|
|||||||
@@ -20,6 +20,7 @@ public class AutoUpdateCollectiblesValueJob : HangfireBackgroundWorkerBase
|
|||||||
|
|
||||||
public override async Task DoWorkAsync(CancellationToken cancellationToken = new CancellationToken())
|
public override async Task DoWorkAsync(CancellationToken cancellationToken = new CancellationToken())
|
||||||
{
|
{
|
||||||
|
return;
|
||||||
await _collectiblesManager.UpdateAllValueAsync();
|
await _collectiblesManager.UpdateAllValueAsync();
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
@@ -31,6 +31,7 @@ public class OnHookAutoMiningJob : HangfireBackgroundWorkerBase
|
|||||||
}
|
}
|
||||||
public override async Task DoWorkAsync(CancellationToken cancellationToken = new CancellationToken())
|
public override async Task DoWorkAsync(CancellationToken cancellationToken = new CancellationToken())
|
||||||
{
|
{
|
||||||
|
return;
|
||||||
await _miningPoolManager.OnHookMiningAsync();
|
await _miningPoolManager.OnHookMiningAsync();
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
@@ -113,7 +113,7 @@ namespace Yi.Abp.Web
|
|||||||
//本地开发环境,可以禁用作业执行
|
//本地开发环境,可以禁用作业执行
|
||||||
if (host.IsDevelopment())
|
if (host.IsDevelopment())
|
||||||
{
|
{
|
||||||
Configure<AbpBackgroundWorkerOptions>(options => { options.IsEnabled = false; });
|
//Configure<AbpBackgroundWorkerOptions>(options => { options.IsEnabled = false; });
|
||||||
}
|
}
|
||||||
|
|
||||||
//请求日志
|
//请求日志
|
||||||
@@ -280,6 +280,7 @@ namespace Yi.Abp.Web
|
|||||||
{
|
{
|
||||||
options.TokenValidationParameters = new TokenValidationParameters
|
options.TokenValidationParameters = new TokenValidationParameters
|
||||||
{
|
{
|
||||||
|
RoleClaimType = "Roles",
|
||||||
ClockSkew = TimeSpan.Zero,
|
ClockSkew = TimeSpan.Zero,
|
||||||
ValidateIssuerSigningKey = true,
|
ValidateIssuerSigningKey = true,
|
||||||
ValidIssuer = jwtOptions.Issuer,
|
ValidIssuer = jwtOptions.Issuer,
|
||||||
@@ -290,12 +291,21 @@ namespace Yi.Abp.Web
|
|||||||
{
|
{
|
||||||
OnMessageReceived = messageContext =>
|
OnMessageReceived = messageContext =>
|
||||||
{
|
{
|
||||||
//优先Query中获取
|
//优先Query中获取,再去cookies中获取
|
||||||
var accessToken = messageContext.Request.Query["access_token"];
|
var accessToken = messageContext.Request.Query["access_token"];
|
||||||
if (!string.IsNullOrEmpty(accessToken))
|
if (!string.IsNullOrEmpty(accessToken))
|
||||||
{
|
{
|
||||||
messageContext.Token = accessToken;
|
messageContext.Token = accessToken;
|
||||||
}
|
}
|
||||||
|
else
|
||||||
|
{
|
||||||
|
if (!messageContext.Request.Headers.ContainsKey("Authorization") &&
|
||||||
|
messageContext.Request.Cookies.TryGetValue("Token", out var cookiesToken))
|
||||||
|
{
|
||||||
|
messageContext.Token = cookiesToken;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
return Task.CompletedTask;
|
return Task.CompletedTask;
|
||||||
}
|
}
|
||||||
};
|
};
|
||||||
@@ -315,11 +325,19 @@ namespace Yi.Abp.Web
|
|||||||
{
|
{
|
||||||
OnMessageReceived = messageContext =>
|
OnMessageReceived = messageContext =>
|
||||||
{
|
{
|
||||||
var refreshToken = messageContext.Request.Query["refresh_token"];
|
var headerRefreshToken = messageContext.Request.Headers["refresh_token"];
|
||||||
if (!string.IsNullOrEmpty(refreshToken))
|
if (!string.IsNullOrEmpty(headerRefreshToken))
|
||||||
{
|
{
|
||||||
messageContext.Token = refreshToken;
|
messageContext.Token = headerRefreshToken;
|
||||||
|
return Task.CompletedTask;
|
||||||
}
|
}
|
||||||
|
|
||||||
|
var queryRefreshToken = messageContext.Request.Query["refresh_token"];
|
||||||
|
if (!string.IsNullOrEmpty(queryRefreshToken))
|
||||||
|
{
|
||||||
|
messageContext.Token = queryRefreshToken;
|
||||||
|
}
|
||||||
|
|
||||||
return Task.CompletedTask;
|
return Task.CompletedTask;
|
||||||
}
|
}
|
||||||
};
|
};
|
||||||
@@ -342,8 +360,8 @@ namespace Yi.Abp.Web
|
|||||||
var app = context.GetApplicationBuilder();
|
var app = context.GetApplicationBuilder();
|
||||||
app.UseRouting();
|
app.UseRouting();
|
||||||
|
|
||||||
// app.ApplicationServices.GetRequiredService<ISqlSugarDbContext>().SqlSugarClient.CodeFirst.InitTables<AiModelEntity>();
|
// app.ApplicationServices.GetRequiredService<ISqlSugarDbContext>().SqlSugarClient.CodeFirst.InitTables<ImageStoreTaskAggregateRoot>();
|
||||||
// app.ApplicationServices.GetRequiredService<ISqlSugarDbContext>().SqlSugarClient.CodeFirst.InitTables<TokenAggregateRoot>();
|
// app.ApplicationServices.GetRequiredService<ISqlSugarDbContext>().SqlSugarClient.CodeFirst.InitTables<ActivationCodeRecordAggregateRoot>();
|
||||||
// app.ApplicationServices.GetRequiredService<ISqlSugarDbContext>().SqlSugarClient.CodeFirst.InitTables<UsageStatisticsAggregateRoot>();
|
// app.ApplicationServices.GetRequiredService<ISqlSugarDbContext>().SqlSugarClient.CodeFirst.InitTables<UsageStatisticsAggregateRoot>();
|
||||||
|
|
||||||
//跨域
|
//跨域
|
||||||
|
|||||||
@@ -2,7 +2,8 @@
|
|||||||
"permissions": {
|
"permissions": {
|
||||||
"allow": [
|
"allow": [
|
||||||
"Bash(npx vue-tsc --noEmit)",
|
"Bash(npx vue-tsc --noEmit)",
|
||||||
"Bash(timeout 60 npx vue-tsc:*)"
|
"Bash(timeout 60 npx vue-tsc:*)",
|
||||||
|
"Bash(npm run dev:*)"
|
||||||
],
|
],
|
||||||
"deny": [],
|
"deny": [],
|
||||||
"ask": []
|
"ask": []
|
||||||
|
|||||||
@@ -15,6 +15,9 @@ VITE_WEB_BASE_API = '/dev-api'
|
|||||||
VITE_API_URL = http://localhost:19001/api/app
|
VITE_API_URL = http://localhost:19001/api/app
|
||||||
#VITE_API_URL=http://data.ccnetcore.com:19001/api/app
|
#VITE_API_URL=http://data.ccnetcore.com:19001/api/app
|
||||||
|
|
||||||
|
# 文件上传接口域名
|
||||||
|
VITE_FILE_UPLOAD_API = https://ai.ccnetcore.com
|
||||||
|
|
||||||
|
|
||||||
|
|
||||||
# SSO单点登录url
|
# SSO单点登录url
|
||||||
|
|||||||
@@ -13,6 +13,9 @@ VITE_WEB_BASE_API = '/prod-api'
|
|||||||
# 本地接口
|
# 本地接口
|
||||||
VITE_API_URL = http://data.ccnetcore.com:19001/api/app
|
VITE_API_URL = http://data.ccnetcore.com:19001/api/app
|
||||||
|
|
||||||
|
# 文件上传接口域名
|
||||||
|
VITE_FILE_UPLOAD_API = https://ai.ccnetcore.com
|
||||||
|
|
||||||
# 是否在打包时开启压缩,支持 gzip 和 brotli
|
# 是否在打包时开启压缩,支持 gzip 和 brotli
|
||||||
VITE_BUILD_COMPRESS = gzip
|
VITE_BUILD_COMPRESS = gzip
|
||||||
|
|
||||||
|
|||||||
@@ -1,78 +0,0 @@
|
|||||||
{
|
|
||||||
"globals": {
|
|
||||||
"Component": true,
|
|
||||||
"ComponentPublicInstance": true,
|
|
||||||
"ComputedRef": true,
|
|
||||||
"DirectiveBinding": true,
|
|
||||||
"EffectScope": true,
|
|
||||||
"ElMessage": true,
|
|
||||||
"ElMessageBox": true,
|
|
||||||
"ExtractDefaultPropTypes": true,
|
|
||||||
"ExtractPropTypes": true,
|
|
||||||
"ExtractPublicPropTypes": true,
|
|
||||||
"InjectionKey": true,
|
|
||||||
"MaybeRef": true,
|
|
||||||
"MaybeRefOrGetter": true,
|
|
||||||
"PropType": true,
|
|
||||||
"Ref": true,
|
|
||||||
"Slot": true,
|
|
||||||
"Slots": true,
|
|
||||||
"VNode": true,
|
|
||||||
"WritableComputedRef": true,
|
|
||||||
"computed": true,
|
|
||||||
"createApp": true,
|
|
||||||
"customRef": true,
|
|
||||||
"defineAsyncComponent": true,
|
|
||||||
"defineComponent": true,
|
|
||||||
"effectScope": true,
|
|
||||||
"getCurrentInstance": true,
|
|
||||||
"getCurrentScope": true,
|
|
||||||
"h": true,
|
|
||||||
"inject": true,
|
|
||||||
"isProxy": true,
|
|
||||||
"isReactive": true,
|
|
||||||
"isReadonly": true,
|
|
||||||
"isRef": true,
|
|
||||||
"markRaw": true,
|
|
||||||
"nextTick": true,
|
|
||||||
"onActivated": true,
|
|
||||||
"onBeforeMount": true,
|
|
||||||
"onBeforeUnmount": true,
|
|
||||||
"onBeforeUpdate": true,
|
|
||||||
"onDeactivated": true,
|
|
||||||
"onErrorCaptured": true,
|
|
||||||
"onMounted": true,
|
|
||||||
"onRenderTracked": true,
|
|
||||||
"onRenderTriggered": true,
|
|
||||||
"onScopeDispose": true,
|
|
||||||
"onServerPrefetch": true,
|
|
||||||
"onUnmounted": true,
|
|
||||||
"onUpdated": true,
|
|
||||||
"onWatcherCleanup": true,
|
|
||||||
"provide": true,
|
|
||||||
"reactive": true,
|
|
||||||
"readonly": true,
|
|
||||||
"ref": true,
|
|
||||||
"resolveComponent": true,
|
|
||||||
"shallowReactive": true,
|
|
||||||
"shallowReadonly": true,
|
|
||||||
"shallowRef": true,
|
|
||||||
"toRaw": true,
|
|
||||||
"toRef": true,
|
|
||||||
"toRefs": true,
|
|
||||||
"toValue": true,
|
|
||||||
"triggerRef": true,
|
|
||||||
"unref": true,
|
|
||||||
"useAttrs": true,
|
|
||||||
"useCssModule": true,
|
|
||||||
"useCssVars": true,
|
|
||||||
"useId": true,
|
|
||||||
"useModel": true,
|
|
||||||
"useSlots": true,
|
|
||||||
"useTemplateRef": true,
|
|
||||||
"watch": true,
|
|
||||||
"watchEffect": true,
|
|
||||||
"watchPostEffect": true,
|
|
||||||
"watchSyncEffect": true
|
|
||||||
}
|
|
||||||
}
|
|
||||||
7
Yi.Ai.Vue3/.gitignore
vendored
7
Yi.Ai.Vue3/.gitignore
vendored
@@ -23,3 +23,10 @@ dist-ssr
|
|||||||
*.njsproj
|
*.njsproj
|
||||||
*.sln
|
*.sln
|
||||||
*.sw?
|
*.sw?
|
||||||
|
|
||||||
|
/.eslintrc-auto-import.json
|
||||||
|
/types/auto-imports.d.ts
|
||||||
|
/types/components.d.ts
|
||||||
|
/types/import_meta.d.ts
|
||||||
|
|
||||||
|
|
||||||
|
|||||||
@@ -112,8 +112,8 @@
|
|||||||
<body>
|
<body>
|
||||||
<!-- 加载动画容器 -->
|
<!-- 加载动画容器 -->
|
||||||
<div id="yixinai-loader" class="loader-container">
|
<div id="yixinai-loader" class="loader-container">
|
||||||
<div class="loader-title">意心Ai 2.6</div>
|
<div class="loader-title">意心Ai 3.0</div>
|
||||||
<div class="loader-subtitle">海外地址,仅首次访问预计加载约10秒</div>
|
<div class="loader-subtitle">海外地址,仅首次访问预计加载约10秒,无需梯子</div>
|
||||||
<div class="loader-logo">
|
<div class="loader-logo">
|
||||||
<div class="pulse-box"></div>
|
<div class="pulse-box"></div>
|
||||||
</div>
|
</div>
|
||||||
|
|||||||
@@ -44,7 +44,9 @@
|
|||||||
"fingerprintjs": "^0.5.3",
|
"fingerprintjs": "^0.5.3",
|
||||||
"hook-fetch": "^2.0.4-beta.1",
|
"hook-fetch": "^2.0.4-beta.1",
|
||||||
"lodash-es": "^4.17.21",
|
"lodash-es": "^4.17.21",
|
||||||
|
"mammoth": "^1.11.0",
|
||||||
"nprogress": "^0.2.0",
|
"nprogress": "^0.2.0",
|
||||||
|
"pdfjs-dist": "^5.4.449",
|
||||||
"pinia": "^3.0.3",
|
"pinia": "^3.0.3",
|
||||||
"pinia-plugin-persistedstate": "^4.4.1",
|
"pinia-plugin-persistedstate": "^4.4.1",
|
||||||
"qrcode": "^1.5.4",
|
"qrcode": "^1.5.4",
|
||||||
@@ -52,7 +54,30 @@
|
|||||||
"reset-css": "^5.0.2",
|
"reset-css": "^5.0.2",
|
||||||
"vue": "^3.5.17",
|
"vue": "^3.5.17",
|
||||||
"vue-element-plus-x": "1.3.7",
|
"vue-element-plus-x": "1.3.7",
|
||||||
"vue-router": "4"
|
"vue-router": "4",
|
||||||
|
"xlsx": "^0.18.5",
|
||||||
|
"@shikijs/transformers": "^3.7.0",
|
||||||
|
"chatarea": "^6.0.3",
|
||||||
|
"deepmerge": "^4.3.1",
|
||||||
|
"dompurify": "^3.2.6",
|
||||||
|
"github-markdown-css": "^5.8.1",
|
||||||
|
"highlight.js": "^11.11.1",
|
||||||
|
"lodash": "^4.17.21",
|
||||||
|
"mermaid": "11.12.0",
|
||||||
|
"prismjs": "^1.30.0",
|
||||||
|
"property-information": "^7.1.0",
|
||||||
|
"rehype-katex": "^7.0.1",
|
||||||
|
"rehype-raw": "^7.0.0",
|
||||||
|
"rehype-sanitize": "^6.0.0",
|
||||||
|
"remark-breaks": "^4.0.0",
|
||||||
|
"remark-gfm": "^4.0.1",
|
||||||
|
"remark-math": "^6.0.0",
|
||||||
|
"remark-parse": "^11.0.0",
|
||||||
|
"remark-rehype": "^11.1.2",
|
||||||
|
"shiki": "^3.7.0",
|
||||||
|
"ts-md5": "^2.0.1",
|
||||||
|
"unified": "^11.0.5",
|
||||||
|
"unist-util-visit": "^5.0.0"
|
||||||
},
|
},
|
||||||
"devDependencies": {
|
"devDependencies": {
|
||||||
"@antfu/eslint-config": "^4.16.2",
|
"@antfu/eslint-config": "^4.16.2",
|
||||||
@@ -87,7 +112,37 @@
|
|||||||
"vite-plugin-compression": "^0.5.1",
|
"vite-plugin-compression": "^0.5.1",
|
||||||
"vite-plugin-env-typed": "^0.0.2",
|
"vite-plugin-env-typed": "^0.0.2",
|
||||||
"vite-plugin-svg-icons": "^2.0.1",
|
"vite-plugin-svg-icons": "^2.0.1",
|
||||||
"vue-tsc": "^3.0.1"
|
"vue-tsc": "^3.0.1",
|
||||||
|
"@chromatic-com/storybook": "^3.2.7",
|
||||||
|
"@jsonlee_12138/markdown-it-mermaid": "0.0.6",
|
||||||
|
"@storybook/addon-essentials": "^8.6.14",
|
||||||
|
"@storybook/addon-onboarding": "^8.6.14",
|
||||||
|
"@storybook/addons": "^7.6.17",
|
||||||
|
"@storybook/api": "^7.6.17",
|
||||||
|
"@storybook/blocks": "^8.6.14",
|
||||||
|
"@storybook/experimental-addon-test": "^8.6.14",
|
||||||
|
"@storybook/manager-api": "^8.6.14",
|
||||||
|
"@storybook/test": "^8.6.14",
|
||||||
|
"@storybook/theming": "^8.6.14",
|
||||||
|
"@storybook/vue3": "^8.6.14",
|
||||||
|
"@storybook/vue3-vite": "^8.6.14",
|
||||||
|
"@types/dom-speech-recognition": "^0.0.4",
|
||||||
|
"@types/fs-extra": "^11.0.4",
|
||||||
|
"@types/markdown-it": "^14.1.2",
|
||||||
|
"@types/prismjs": "^1.26.5",
|
||||||
|
"@vitest/browser": "^3.2.4",
|
||||||
|
"@vitest/coverage-v8": "^3.2.4",
|
||||||
|
"esno": "^4.8.0",
|
||||||
|
"fast-glob": "^3.3.3",
|
||||||
|
"playwright": "^1.53.2",
|
||||||
|
"rimraf": "^6.0.1",
|
||||||
|
"sass": "^1.89.2",
|
||||||
|
"storybook": "^8.6.14",
|
||||||
|
"storybook-dark-mode": "^4.0.2",
|
||||||
|
"terser": "^5.43.1",
|
||||||
|
"vite-plugin-dts": "^4.5.4",
|
||||||
|
"vite-plugin-lib-inject-css": "^2.2.2",
|
||||||
|
"vitest": "^3.2.4"
|
||||||
},
|
},
|
||||||
"config": {
|
"config": {
|
||||||
"commitizen": {
|
"commitizen": {
|
||||||
|
|||||||
4701
Yi.Ai.Vue3/pnpm-lock.yaml
generated
4701
Yi.Ai.Vue3/pnpm-lock.yaml
generated
File diff suppressed because it is too large
Load Diff
BIN
Yi.Ai.Vue3/publish_aihub_02.zip
Normal file
BIN
Yi.Ai.Vue3/publish_aihub_02.zip
Normal file
Binary file not shown.
@@ -4,5 +4,11 @@
|
|||||||
<template>
|
<template>
|
||||||
<router-view />
|
<router-view />
|
||||||
</template>
|
</template>
|
||||||
|
<!-- 全局样式 -->
|
||||||
|
|
||||||
<style scoped lang="scss"></style>
|
<style>
|
||||||
|
.popover-content
|
||||||
|
{
|
||||||
|
z-index: 99;
|
||||||
|
}
|
||||||
|
</style>
|
||||||
|
|||||||
5
Yi.Ai.Vue3/src/api/activationCode/index.ts
Normal file
5
Yi.Ai.Vue3/src/api/activationCode/index.ts
Normal file
@@ -0,0 +1,5 @@
|
|||||||
|
import { post } from '@/utils/request';
|
||||||
|
|
||||||
|
export function redeemActivationCode(data: { code: string }) {
|
||||||
|
return post<any>('/activationCode/Redeem', data);
|
||||||
|
}
|
||||||
33
Yi.Ai.Vue3/src/api/aiImage/index.ts
Normal file
33
Yi.Ai.Vue3/src/api/aiImage/index.ts
Normal file
@@ -0,0 +1,33 @@
|
|||||||
|
import { get, post } from '@/utils/request';
|
||||||
|
import type {
|
||||||
|
GenerateImageRequest,
|
||||||
|
ImageModel,
|
||||||
|
PublishImageRequest,
|
||||||
|
TaskListRequest,
|
||||||
|
TaskListResponse,
|
||||||
|
TaskStatusResponse,
|
||||||
|
} from './types';
|
||||||
|
|
||||||
|
export function generateImage(data: GenerateImageRequest) {
|
||||||
|
return post<string>('/ai-image/generate', data).json();
|
||||||
|
}
|
||||||
|
|
||||||
|
export function getTaskStatus(taskId: string) {
|
||||||
|
return get<TaskStatusResponse>(`/ai-image/task/${taskId}`).json();
|
||||||
|
}
|
||||||
|
|
||||||
|
export function getMyTasks(params: TaskListRequest) {
|
||||||
|
return get<TaskListResponse>('/ai-image/my-tasks', params).json();
|
||||||
|
}
|
||||||
|
|
||||||
|
export function getImagePlaza(params: TaskListRequest) {
|
||||||
|
return get<TaskListResponse>('/ai-image/plaza', params).json();
|
||||||
|
}
|
||||||
|
|
||||||
|
export function publishImage(data: PublishImageRequest) {
|
||||||
|
return post<void>('/ai-image/publish', data).json();
|
||||||
|
}
|
||||||
|
|
||||||
|
export function getImageModels() {
|
||||||
|
return post<ImageModel[]>('/ai-image/model').json();
|
||||||
|
}
|
||||||
69
Yi.Ai.Vue3/src/api/aiImage/types.ts
Normal file
69
Yi.Ai.Vue3/src/api/aiImage/types.ts
Normal file
@@ -0,0 +1,69 @@
|
|||||||
|
export interface GenerateImageRequest {
|
||||||
|
tokenId: string;
|
||||||
|
prompt: string;
|
||||||
|
modelId: string;
|
||||||
|
referenceImagesPrefixBase64?: string[];
|
||||||
|
}
|
||||||
|
|
||||||
|
export interface TaskStatusResponse {
|
||||||
|
id: string;
|
||||||
|
prompt: string;
|
||||||
|
storePrefixBase64?: string;
|
||||||
|
storeUrl?: string;
|
||||||
|
taskStatus: 'Processing' | 'Success' | 'Fail';
|
||||||
|
publishStatus: string;
|
||||||
|
categories: string[];
|
||||||
|
creationTime: string;
|
||||||
|
errorInfo?: string;
|
||||||
|
}
|
||||||
|
|
||||||
|
export interface TaskListRequest {
|
||||||
|
SkipCount: number;
|
||||||
|
MaxResultCount: number;
|
||||||
|
TaskStatus?: 'Processing' | 'Success' | 'Fail';
|
||||||
|
Prompt?: string;
|
||||||
|
PublishStatus?: 'Unpublished' | 'Published';
|
||||||
|
StartTime?: string;
|
||||||
|
EndTime?: string;
|
||||||
|
OrderByColumn?: string;
|
||||||
|
IsAsc?: string;
|
||||||
|
IsAscending?: boolean;
|
||||||
|
Sorting?: string;
|
||||||
|
Categories?: string;
|
||||||
|
UserName?: string;
|
||||||
|
}
|
||||||
|
|
||||||
|
export interface TaskItem {
|
||||||
|
id: string;
|
||||||
|
prompt: string;
|
||||||
|
storePrefixBase64?: string;
|
||||||
|
storeUrl?: string;
|
||||||
|
taskStatus: 'Processing' | 'Success' | 'Fail';
|
||||||
|
publishStatus: string;
|
||||||
|
categories: string[];
|
||||||
|
creationTime: string;
|
||||||
|
errorInfo?: string;
|
||||||
|
isAnonymous?: boolean;
|
||||||
|
userName?: string | null;
|
||||||
|
userId?: string | null;
|
||||||
|
}
|
||||||
|
|
||||||
|
export interface TaskListResponse {
|
||||||
|
total: number;
|
||||||
|
items: TaskItem[];
|
||||||
|
}
|
||||||
|
|
||||||
|
export interface PublishImageRequest {
|
||||||
|
taskId: string;
|
||||||
|
categories: string[];
|
||||||
|
isAnonymous?: boolean;
|
||||||
|
}
|
||||||
|
|
||||||
|
export interface ImageModel {
|
||||||
|
id: string;
|
||||||
|
modelId: string;
|
||||||
|
modelName: string;
|
||||||
|
modelDescribe: string;
|
||||||
|
remark: string;
|
||||||
|
isPremiumPackage: boolean;
|
||||||
|
}
|
||||||
100
Yi.Ai.Vue3/src/api/channel/index.ts
Normal file
100
Yi.Ai.Vue3/src/api/channel/index.ts
Normal file
@@ -0,0 +1,100 @@
|
|||||||
|
import { del, get, post, put } from '@/utils/request';
|
||||||
|
import type {
|
||||||
|
AiAppDto,
|
||||||
|
AiAppCreateInput,
|
||||||
|
AiAppUpdateInput,
|
||||||
|
AiAppGetListInput,
|
||||||
|
AiModelDto,
|
||||||
|
AiModelCreateInput,
|
||||||
|
AiModelUpdateInput,
|
||||||
|
AiModelGetListInput,
|
||||||
|
PagedResultDto,
|
||||||
|
} from './types';
|
||||||
|
|
||||||
|
// ==================== AI应用管理 ====================
|
||||||
|
|
||||||
|
// 获取AI应用列表
|
||||||
|
export function getAppList(params?: AiAppGetListInput) {
|
||||||
|
const queryParams = new URLSearchParams();
|
||||||
|
if (params?.searchKey) {
|
||||||
|
queryParams.append('SearchKey', params.searchKey);
|
||||||
|
}
|
||||||
|
if (params?.skipCount !== undefined) {
|
||||||
|
queryParams.append('SkipCount', params.skipCount.toString());
|
||||||
|
}
|
||||||
|
if (params?.maxResultCount !== undefined) {
|
||||||
|
queryParams.append('MaxResultCount', params.maxResultCount.toString());
|
||||||
|
}
|
||||||
|
|
||||||
|
const queryString = queryParams.toString();
|
||||||
|
const url = queryString ? `/channel/app?${queryString}` : '/channel/app';
|
||||||
|
|
||||||
|
return get<PagedResultDto<AiAppDto>>(url).json();
|
||||||
|
}
|
||||||
|
|
||||||
|
// 根据ID获取AI应用
|
||||||
|
export function getAppById(id: string) {
|
||||||
|
return get<AiAppDto>(`/channel/app/${id}`).json();
|
||||||
|
}
|
||||||
|
|
||||||
|
// 创建AI应用
|
||||||
|
export function createApp(data: AiAppCreateInput) {
|
||||||
|
return post<AiAppDto>('/channel/app', data).json();
|
||||||
|
}
|
||||||
|
|
||||||
|
// 更新AI应用
|
||||||
|
export function updateApp(data: AiAppUpdateInput) {
|
||||||
|
return put<AiAppDto>('/channel/app', data).json();
|
||||||
|
}
|
||||||
|
|
||||||
|
// 删除AI应用
|
||||||
|
export function deleteApp(id: string) {
|
||||||
|
return del(`/channel/app/${id}`).json();
|
||||||
|
}
|
||||||
|
|
||||||
|
// ==================== AI模型管理 ====================
|
||||||
|
|
||||||
|
// 获取AI模型列表
|
||||||
|
export function getModelList(params?: AiModelGetListInput) {
|
||||||
|
const queryParams = new URLSearchParams();
|
||||||
|
if (params?.searchKey) {
|
||||||
|
queryParams.append('SearchKey', params.searchKey);
|
||||||
|
}
|
||||||
|
if (params?.aiAppId) {
|
||||||
|
queryParams.append('AiAppId', params.aiAppId);
|
||||||
|
}
|
||||||
|
if (params?.isPremiumOnly !== undefined) {
|
||||||
|
queryParams.append('IsPremiumOnly', params.isPremiumOnly.toString());
|
||||||
|
}
|
||||||
|
if (params?.skipCount !== undefined) {
|
||||||
|
queryParams.append('SkipCount', params.skipCount.toString());
|
||||||
|
}
|
||||||
|
if (params?.maxResultCount !== undefined) {
|
||||||
|
queryParams.append('MaxResultCount', params.maxResultCount.toString());
|
||||||
|
}
|
||||||
|
|
||||||
|
const queryString = queryParams.toString();
|
||||||
|
const url = queryString ? `/channel/model?${queryString}` : '/channel/model';
|
||||||
|
|
||||||
|
return get<PagedResultDto<AiModelDto>>(url).json();
|
||||||
|
}
|
||||||
|
|
||||||
|
// 根据ID获取AI模型
|
||||||
|
export function getModelById(id: string) {
|
||||||
|
return get<AiModelDto>(`/channel/model/${id}`).json();
|
||||||
|
}
|
||||||
|
|
||||||
|
// 创建AI模型
|
||||||
|
export function createModel(data: AiModelCreateInput) {
|
||||||
|
return post<AiModelDto>('/channel/model', data).json();
|
||||||
|
}
|
||||||
|
|
||||||
|
// 更新AI模型
|
||||||
|
export function updateModel(data: AiModelUpdateInput) {
|
||||||
|
return put<AiModelDto>('/channel/model', data).json();
|
||||||
|
}
|
||||||
|
|
||||||
|
// 删除AI模型
|
||||||
|
export function deleteModel(id: string) {
|
||||||
|
return del(`/channel/model/${id}`).json();
|
||||||
|
}
|
||||||
121
Yi.Ai.Vue3/src/api/channel/types.ts
Normal file
121
Yi.Ai.Vue3/src/api/channel/types.ts
Normal file
@@ -0,0 +1,121 @@
|
|||||||
|
// 模型类型枚举
|
||||||
|
export enum ModelTypeEnum {
|
||||||
|
Chat = 0,
|
||||||
|
Image = 1,
|
||||||
|
Embedding = 2,
|
||||||
|
PremiumChat = 3,
|
||||||
|
}
|
||||||
|
|
||||||
|
// 模型API类型枚举
|
||||||
|
export enum ModelApiTypeEnum {
|
||||||
|
OpenAi = 0,
|
||||||
|
Claude = 1,
|
||||||
|
}
|
||||||
|
|
||||||
|
// AI应用DTO
|
||||||
|
export interface AiAppDto {
|
||||||
|
id: string;
|
||||||
|
name: string;
|
||||||
|
endpoint: string;
|
||||||
|
extraUrl?: string;
|
||||||
|
apiKey: string;
|
||||||
|
orderNum: number;
|
||||||
|
creationTime: string;
|
||||||
|
}
|
||||||
|
|
||||||
|
// 创建AI应用输入
|
||||||
|
export interface AiAppCreateInput {
|
||||||
|
name: string;
|
||||||
|
endpoint: string;
|
||||||
|
extraUrl?: string;
|
||||||
|
apiKey: string;
|
||||||
|
orderNum: number;
|
||||||
|
}
|
||||||
|
|
||||||
|
// 更新AI应用输入
|
||||||
|
export interface AiAppUpdateInput {
|
||||||
|
id: string;
|
||||||
|
name: string;
|
||||||
|
endpoint: string;
|
||||||
|
extraUrl?: string;
|
||||||
|
apiKey: string;
|
||||||
|
orderNum: number;
|
||||||
|
}
|
||||||
|
|
||||||
|
// 获取AI应用列表输入
|
||||||
|
export interface AiAppGetListInput {
|
||||||
|
searchKey?: string;
|
||||||
|
skipCount?: number;
|
||||||
|
maxResultCount?: number;
|
||||||
|
}
|
||||||
|
|
||||||
|
// AI模型DTO
|
||||||
|
export interface AiModelDto {
|
||||||
|
id: string;
|
||||||
|
handlerName: string;
|
||||||
|
modelId: string;
|
||||||
|
name: string;
|
||||||
|
description?: string;
|
||||||
|
orderNum: number;
|
||||||
|
aiAppId: string;
|
||||||
|
extraInfo?: string;
|
||||||
|
modelType: ModelTypeEnum;
|
||||||
|
modelApiType: ModelApiTypeEnum;
|
||||||
|
multiplier: number;
|
||||||
|
multiplierShow: number;
|
||||||
|
providerName?: string;
|
||||||
|
iconUrl?: string;
|
||||||
|
isPremium: boolean;
|
||||||
|
}
|
||||||
|
|
||||||
|
// 创建AI模型输入
|
||||||
|
export interface AiModelCreateInput {
|
||||||
|
handlerName: string;
|
||||||
|
modelId: string;
|
||||||
|
name: string;
|
||||||
|
description?: string;
|
||||||
|
orderNum: number;
|
||||||
|
aiAppId: string;
|
||||||
|
extraInfo?: string;
|
||||||
|
modelType: ModelTypeEnum;
|
||||||
|
modelApiType: ModelApiTypeEnum;
|
||||||
|
multiplier: number;
|
||||||
|
multiplierShow: number;
|
||||||
|
providerName?: string;
|
||||||
|
iconUrl?: string;
|
||||||
|
isPremium: boolean;
|
||||||
|
}
|
||||||
|
|
||||||
|
// 更新AI模型输入
|
||||||
|
export interface AiModelUpdateInput {
|
||||||
|
id: string;
|
||||||
|
handlerName: string;
|
||||||
|
modelId: string;
|
||||||
|
name: string;
|
||||||
|
description?: string;
|
||||||
|
orderNum: number;
|
||||||
|
aiAppId: string;
|
||||||
|
extraInfo?: string;
|
||||||
|
modelType: ModelTypeEnum;
|
||||||
|
modelApiType: ModelApiTypeEnum;
|
||||||
|
multiplier: number;
|
||||||
|
multiplierShow: number;
|
||||||
|
providerName?: string;
|
||||||
|
iconUrl?: string;
|
||||||
|
isPremium: boolean;
|
||||||
|
}
|
||||||
|
|
||||||
|
// 获取AI模型列表输入
|
||||||
|
export interface AiModelGetListInput {
|
||||||
|
searchKey?: string;
|
||||||
|
aiAppId?: string;
|
||||||
|
isPremiumOnly?: boolean;
|
||||||
|
skipCount?: number;
|
||||||
|
maxResultCount?: number;
|
||||||
|
}
|
||||||
|
|
||||||
|
// 分页结果
|
||||||
|
export interface PagedResultDto<T> {
|
||||||
|
items: T[];
|
||||||
|
totalCount: number;
|
||||||
|
}
|
||||||
Some files were not shown because too many files have changed in this diff Show More
Reference in New Issue
Block a user