Files
moyi-model-intelligence-hub/control-plane-java/src/main/java/com/moyi/controlplane/gateway/PlaygroundController.java
T

56 lines
2.6 KiB
Java

package com.moyi.controlplane.gateway;
import com.moyi.controlplane.auth.AuthController;
import com.moyi.controlplane.auth.AuthService;
import com.moyi.controlplane.catalog.CatalogService;
import com.moyi.controlplane.common.ApiException;
import com.moyi.controlplane.task.AsyncTaskService;
import jakarta.servlet.http.HttpServletRequest;
import jakarta.servlet.http.HttpServletResponse;
import java.util.Map;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.*;
@RestController
@RequestMapping("/api/playground/keys/{keyId}")
public class PlaygroundController {
private final AuthService auth;
private final CatalogService catalog;
private final GatewayController gateway;
private final AsyncTaskService tasks;
public PlaygroundController(AuthService auth, CatalogService catalog, GatewayController gateway, AsyncTaskService tasks) {
this.auth = auth;
this.catalog = catalog;
this.gateway = gateway;
this.tasks = tasks;
}
@PostMapping(value="/chat/completions", consumes="application/json")
public ResponseEntity<Map<String, Object>> chat(@PathVariable String keyId,
@RequestBody Map<String, Object> input,
@RequestHeader(value="Idempotency-Key", required=false) String idempotencyKey,
HttpServletRequest request, HttpServletResponse response) {
return gateway.executeChat(requireKey(request, keyId), input, idempotencyKey, response);
}
@PostMapping(value="/{type:3d|video|image|audio}/tasks", consumes="application/json")
public ResponseEntity<Map<String, Object>> createTask(@PathVariable String keyId, @PathVariable String type,
@RequestBody Map<String, Object> input, HttpServletRequest request) {
return ResponseEntity.accepted().body(Map.of("task", tasks.createForKey(requireKey(request, keyId), type, input)));
}
@GetMapping("/tasks/{taskId}")
public Map<String, Object> task(@PathVariable String keyId, @PathVariable String taskId, HttpServletRequest request) {
return Map.of("task", tasks.getForKey(requireKey(request, keyId), taskId));
}
private Map<String, Object> requireKey(HttpServletRequest request, String keyId) {
// A custom header prevents cross-site forms from spending a cookie-authenticated wallet.
// Cross-origin scripts must pass the existing explicit CORS origin allowlist.
if (!"playground".equals(request.getHeader("X-Moyi-Source")))
throw new ApiException("PLAYGROUND_REQUEST_REQUIRED", "请通过在线调试页面发起调用", 403);
return catalog.requireOwnedKey(AuthController.sessionToken(request), keyId, auth);
}
}