This commit is contained in:
commit
db82325ed7
216 files changed
+33718
No files matched your search
@@ -0,0 +1,263 @@
|
||||
package run.webup.platform;
|
||||
|
||||
import jakarta.servlet.http.HttpServletRequest;
|
||||
import jakarta.validation.Valid;
|
||||
import jakarta.validation.constraints.*;
|
||||
import java.math.BigDecimal;
|
||||
import java.util.*;
|
||||
import org.springframework.jdbc.core.JdbcTemplate;
|
||||
import org.springframework.security.access.prepost.PreAuthorize;
|
||||
import org.springframework.security.core.annotation.AuthenticationPrincipal;
|
||||
import org.springframework.transaction.annotation.Transactional;
|
||||
import org.springframework.web.bind.annotation.*;
|
||||
|
||||
@RestController
|
||||
@RequestMapping("/api")
|
||||
public class ModelController {
|
||||
private final JdbcTemplate db;
|
||||
private final SecretVault vault;
|
||||
private final ProviderTransport transport;
|
||||
|
||||
public ModelController(JdbcTemplate db, SecretVault vault, ProviderTransport transport) {
|
||||
this.db = db;
|
||||
this.vault = vault;
|
||||
this.transport = transport;
|
||||
}
|
||||
|
||||
void audit(UUID actor, String action, String target, String ip) {
|
||||
db.update(
|
||||
"INSERT INTO admin_operation_logs(id,actor_id,action,target,ip,details) VALUES"
|
||||
+ " (?,?,?,?,?,?)",
|
||||
UUID.randomUUID(),
|
||||
actor,
|
||||
action,
|
||||
target,
|
||||
ip,
|
||||
"模型配置操作;凭证不写入审计");
|
||||
}
|
||||
|
||||
public record Provider(
|
||||
@NotBlank @Size(max = 100) String name,
|
||||
@NotBlank @Size(max = 1000) String baseUrl,
|
||||
@Pattern(regexp = "OPENAI|ANTHROPIC|GEMINI") @NotNull String apiType,
|
||||
@Size(max = 2000) String apiKey,
|
||||
boolean enabled,
|
||||
@Min(5) @Max(180) int timeoutSeconds,
|
||||
@Pattern(regexp = "BEARER|API_KEY|X_API_KEY") String authMode) {}
|
||||
|
||||
public record Model(
|
||||
@NotNull UUID providerId,
|
||||
@NotBlank @Size(max = 100) String name,
|
||||
@NotBlank @Pattern(regexp = "[A-Za-z0-9_.:@/-]{1,200}") String modelId,
|
||||
@Min(256) @Max(4000000) int contextLength,
|
||||
@Min(1) @Max(1000000) int maxOutput,
|
||||
boolean toolsEnabled,
|
||||
boolean visionEnabled,
|
||||
boolean enabled,
|
||||
@NotNull @DecimalMin("0") @Digits(integer = 12, fraction = 8) BigDecimal inputPrice,
|
||||
@NotNull @DecimalMin("0") @Digits(integer = 12, fraction = 8) BigDecimal outputPrice,
|
||||
@NotNull @DecimalMin("0") @Digits(integer = 12, fraction = 8) BigDecimal cacheReadPrice,
|
||||
@NotNull @DecimalMin("0") @Digits(integer = 12, fraction = 8) BigDecimal cacheWritePrice) {}
|
||||
|
||||
@GetMapping("/admin/providers")
|
||||
@PreAuthorize("hasAuthority('models:write')")
|
||||
public List<Map<String, Object>> providers() {
|
||||
return db.queryForList(
|
||||
"SELECT"
|
||||
+ " id,name,base_url,api_type,enabled,timeout_seconds,connection_status,last_error,created_at,updated_at,auth_mode"
|
||||
+ " FROM ai_providers ORDER BY created_at DESC");
|
||||
}
|
||||
|
||||
@PostMapping("/admin/providers")
|
||||
@PreAuthorize("hasAuthority('models:write')")
|
||||
@Transactional
|
||||
public Map<String, UUID> create(
|
||||
@AuthenticationPrincipal SecurityConfig.Identity who,
|
||||
@Valid @RequestBody Provider p,
|
||||
HttpServletRequest req) {
|
||||
transport.validate(p.baseUrl());
|
||||
if (p.apiKey() == null || p.apiKey().isBlank())
|
||||
throw new ApiError.Failure(400, "首次添加供应商需要 API Key");
|
||||
UUID id = UUID.randomUUID();
|
||||
db.update(
|
||||
"INSERT INTO"
|
||||
+ " ai_providers(id,name,base_url,api_type,encrypted_key,enabled,timeout_seconds,auth_mode)"
|
||||
+ " VALUES (?,?,?,?,?,?,?,?)",
|
||||
id,
|
||||
p.name(),
|
||||
p.baseUrl(),
|
||||
p.apiType(),
|
||||
vault.encrypt(p.apiKey()),
|
||||
p.enabled(),
|
||||
p.timeoutSeconds(),
|
||||
p.authMode() == null ? "BEARER" : p.authMode());
|
||||
audit(who.id(), "PROVIDER_CREATE", id.toString(), AuthController.ip(req));
|
||||
return Map.of("id", id);
|
||||
}
|
||||
|
||||
@PutMapping("/admin/providers/{id}")
|
||||
@PreAuthorize("hasAuthority('models:write')")
|
||||
@Transactional
|
||||
public Map<String, String> update(
|
||||
@AuthenticationPrincipal SecurityConfig.Identity who,
|
||||
@PathVariable UUID id,
|
||||
@Valid @RequestBody Provider p,
|
||||
HttpServletRequest req) {
|
||||
transport.validate(p.baseUrl());
|
||||
var rows =
|
||||
db.queryForList(
|
||||
"SELECT encrypted_key,base_url,api_type FROM ai_providers WHERE id=? FOR UPDATE", id);
|
||||
if (rows.isEmpty()) throw new ApiError.Failure(404, "供应商不存在");
|
||||
if ((!rows.getFirst().get("base_url").equals(p.baseUrl())
|
||||
|| !rows.getFirst().get("api_type").equals(p.apiType()))
|
||||
&& db.queryForObject(
|
||||
"SELECT COUNT(*) FROM ai_models WHERE provider_id=?", Integer.class, id)
|
||||
> 0) throw new ApiError.Failure(409, "已有模型引用此供应商,变更地址或协议请创建新供应商,避免历史任务凭证发送到错误地址");
|
||||
String key =
|
||||
p.apiKey() == null || p.apiKey().isBlank()
|
||||
? rows.getFirst().get("encrypted_key").toString()
|
||||
: vault.encrypt(p.apiKey());
|
||||
db.update(
|
||||
"UPDATE ai_providers SET"
|
||||
+ " name=?,base_url=?,api_type=?,encrypted_key=?,enabled=?,timeout_seconds=?,auth_mode=?,connection_status='UNTESTED',last_error='',updated_at=CURRENT_TIMESTAMP"
|
||||
+ " WHERE id=?",
|
||||
p.name(),
|
||||
p.baseUrl(),
|
||||
p.apiType(),
|
||||
key,
|
||||
p.enabled(),
|
||||
p.timeoutSeconds(),
|
||||
p.authMode() == null ? "BEARER" : p.authMode(),
|
||||
id);
|
||||
audit(who.id(), "PROVIDER_UPDATE", id.toString(), AuthController.ip(req));
|
||||
return Map.of("message", "供应商已更新,留空密钥保持原值");
|
||||
}
|
||||
|
||||
@PostMapping("/admin/providers/{id}/test")
|
||||
@PreAuthorize("hasAuthority('models:write')")
|
||||
public Map<String, String> test(
|
||||
@AuthenticationPrincipal SecurityConfig.Identity who,
|
||||
@PathVariable UUID id,
|
||||
HttpServletRequest req) {
|
||||
var rows = db.queryForList("SELECT * FROM ai_providers WHERE id=?", id);
|
||||
if (rows.isEmpty()) throw new ApiError.Failure(404, "供应商不存在");
|
||||
var p = rows.getFirst();
|
||||
try {
|
||||
transport.requestAuthenticated(
|
||||
p.get("base_url").toString(),
|
||||
"/models",
|
||||
vault.decrypt(p.get("encrypted_key").toString()),
|
||||
p.get("api_type").toString(),
|
||||
(Integer) p.get("timeout_seconds"),
|
||||
null,
|
||||
p.get("auth_mode").toString());
|
||||
db.update(
|
||||
"UPDATE ai_providers SET connection_status='CONNECTED',last_error='' WHERE id=?", id);
|
||||
audit(who.id(), "PROVIDER_TEST_OK", id.toString(), AuthController.ip(req));
|
||||
return Map.of("message", "已实际连接供应商的模型列表接口(不代表工具能力已验证)");
|
||||
} catch (ApiError.Failure f) {
|
||||
db.update(
|
||||
"UPDATE ai_providers SET connection_status='ERROR',last_error=? WHERE id=?",
|
||||
f.getMessage(),
|
||||
id);
|
||||
audit(who.id(), "PROVIDER_TEST_FAILED", id.toString(), AuthController.ip(req));
|
||||
throw f;
|
||||
}
|
||||
}
|
||||
|
||||
@GetMapping("/models")
|
||||
public List<Map<String, Object>> available() {
|
||||
return models(false);
|
||||
}
|
||||
|
||||
@GetMapping("/admin/models")
|
||||
@PreAuthorize("hasAuthority('models:write')")
|
||||
public List<Map<String, Object>> all() {
|
||||
return models(true);
|
||||
}
|
||||
|
||||
private List<Map<String, Object>> models(boolean all) {
|
||||
return db.queryForList(
|
||||
"SELECT m.*,p.name AS provider_name,p.api_type,v.id AS"
|
||||
+ " price_version_id,v.input_price,v.output_price,v.cache_read_price,v.cache_write_price"
|
||||
+ " FROM ai_models m JOIN ai_providers p ON p.id=m.provider_id JOIN"
|
||||
+ " ai_model_price_versions v ON v.id=m.current_price_version "
|
||||
+ (all ? "" : "WHERE m.enabled=TRUE AND p.enabled=TRUE ")
|
||||
+ " ORDER BY m.created_at DESC");
|
||||
}
|
||||
|
||||
@PostMapping("/admin/models")
|
||||
@PreAuthorize("hasAuthority('models:write')")
|
||||
@Transactional
|
||||
public Map<String, UUID> createModel(
|
||||
@AuthenticationPrincipal SecurityConfig.Identity who,
|
||||
@Valid @RequestBody Model m,
|
||||
HttpServletRequest req) {
|
||||
if (m.maxOutput() > m.contextLength()) throw new ApiError.Failure(400, "最大输出不能超过上下文长度");
|
||||
UUID id = UUID.randomUUID();
|
||||
db.update(
|
||||
"INSERT INTO"
|
||||
+ " ai_models(id,provider_id,name,model_id,context_length,max_output,tools_enabled,vision_enabled,enabled)"
|
||||
+ " VALUES (?,?,?,?,?,?,?,?,?)",
|
||||
id,
|
||||
m.providerId(),
|
||||
m.name(),
|
||||
m.modelId(),
|
||||
m.contextLength(),
|
||||
m.maxOutput(),
|
||||
m.toolsEnabled(),
|
||||
m.visionEnabled(),
|
||||
m.enabled());
|
||||
price(id, m);
|
||||
audit(who.id(), "MODEL_CREATE", id.toString(), AuthController.ip(req));
|
||||
return Map.of("id", id);
|
||||
}
|
||||
|
||||
void price(UUID id, Model m) {
|
||||
UUID version = UUID.randomUUID();
|
||||
db.update(
|
||||
"INSERT INTO"
|
||||
+ " ai_model_price_versions(id,model_id,input_price,output_price,cache_read_price,cache_write_price)"
|
||||
+ " VALUES (?,?,?,?,?,?)",
|
||||
version,
|
||||
id,
|
||||
m.inputPrice(),
|
||||
m.outputPrice(),
|
||||
m.cacheReadPrice(),
|
||||
m.cacheWritePrice());
|
||||
db.update("UPDATE ai_models SET current_price_version=? WHERE id=?", version, id);
|
||||
}
|
||||
|
||||
@PutMapping("/admin/models/{id}")
|
||||
@PreAuthorize("hasAuthority('models:write')")
|
||||
@Transactional
|
||||
public Map<String, String> updateModel(
|
||||
@AuthenticationPrincipal SecurityConfig.Identity who,
|
||||
@PathVariable UUID id,
|
||||
@Valid @RequestBody Model m,
|
||||
HttpServletRequest req) {
|
||||
if (m.maxOutput() > m.contextLength()) throw new ApiError.Failure(400, "最大输出不能超过上下文长度");
|
||||
// Once used by a task, a model's upstream identity is immutable; create a new model to change
|
||||
// it.
|
||||
var existing =
|
||||
db.queryForList("SELECT provider_id,model_id FROM ai_models WHERE id=? FOR UPDATE", id);
|
||||
if (existing.isEmpty()) throw new ApiError.Failure(404, "模型不存在");
|
||||
if (!existing.getFirst().get("provider_id").toString().equals(m.providerId().toString())
|
||||
|| !existing.getFirst().get("model_id").equals(m.modelId()))
|
||||
throw new ApiError.Failure(409, "实际模型和供应商不可修改,请新建配置");
|
||||
db.update(
|
||||
"UPDATE ai_models SET"
|
||||
+ " name=?,context_length=?,max_output=?,tools_enabled=?,vision_enabled=?,enabled=?,updated_at=CURRENT_TIMESTAMP"
|
||||
+ " WHERE id=?",
|
||||
m.name(),
|
||||
m.contextLength(),
|
||||
m.maxOutput(),
|
||||
m.toolsEnabled(),
|
||||
m.visionEnabled(),
|
||||
m.enabled(),
|
||||
id);
|
||||
price(id, m);
|
||||
audit(who.id(), "MODEL_UPDATE", id.toString(), AuthController.ip(req));
|
||||
return Map.of("message", "已保存新价格版本,已有任务的价格快照保持不变");
|
||||
}
|
||||
}
|
||||
Reference in new issue
Block a user