diff --git a/docs/api/llm.md b/docs/api/llm.md new file mode 100644 index 00000000..59de22f3 --- /dev/null +++ b/docs/api/llm.md @@ -0,0 +1,52 @@ +# 通用 LLM 对话接口 + +`POST /api/v1/open/llm/chat/completions` + +独立固定 Bearer Token 鉴权,不需要登录 JWT 或设备签名。接口返回项目统一 `Result`,不是 OpenAI 响应格式的直接透传。 +当前接入 DeepSeek,支持文本、多轮历史和非流式输出;调用方在每次请求中传入历史消息,服务端不保存会话。 + +## 配置 + +```text +LLM_API_TOKEN=<自行设置的固定访问令牌> +DEEPSEEK_API_KEY=<模型供应商密钥> +DEEPSEEK_MODEL=deepseek-flash +``` + +访问令牌与模型密钥用途不同,不应使用同一值。通过环境变量或 Kubernetes Secret 注入,不写入源码。 +未配置访问令牌或模型密钥时接口返回 HTTP 503。现有设备 AI 指令接口保持独立。 + +生产固定令牌保存于服务器 `/opt/youlai-boot/llm.env`(root 所有,权限 `600`), +通过 namespace `youlai` 的 Secret `youlai-llm` 注入。DeepSeek 配置仍使用 `youlai-deepseek`。 +修改文件后需同步更新 Secret 并重启: + +```bash +kubectl -n youlai create secret generic youlai-llm \ + --from-env-file=/opt/youlai-boot/llm.env --dry-run=client -o yaml | kubectl apply -f - +kubectl -n youlai rollout restart deployment/youlai-boot +``` + +## 调用示例 + +```bash +curl -X POST 'https://api.ttstd.com/api/v1/open/llm/chat/completions' \ + -H "Authorization: Bearer $LLM_API_TOKEN" \ + -H 'Content-Type: application/json' \ + -d '{"messages":[{"role":"system","content":"请用中文简短回答"},{"role":"user","content":"你好"}],"maxTokens":1024,"temperature":0.7}' +``` + +成功响应示例(用量以实际返回为准): + +```json +{"code":"00000","msg":"一切ok","data":{"model":"deepseek-flash","content":"你好!","finishReason":"stop","usage":{"promptTokens":20,"completionTokens":3,"totalTokens":23}}} +``` + +消息角色限 `system`、`user`、`assistant`,消息数 1~50,每条内容 1~8000 字符且不能全为空白,总长度不超过 32000 字符。 +`maxTokens` 默认 1024、范围 1~4096;`temperature` 默认 0.7、范围 0~2。 +模型由服务端配置,本接口关闭 thinking;不支持流式、工具调用和图片。 +`finishReason=length` 表示输出被 token 上限截断,调用方应据此提示或继续请求。 + +HTTP 状态:401 令牌无效;400 请求参数错误;429 单实例并发超过 4;502 上游错误或响应异常;503 未配置或请求中断;504 上游请求超过 60 秒。 +接口不会向调用方透传供应商错误正文或密钥。生产发布时将 `LLM_API_TOKEN` 加入后端容器 Secret 并重启后生效。 + +协议参考:https://api-docs.deepseek.com/api/create-chat-completion/ diff --git a/src/main/java/com/youlai/boot/open/llm/config/LlmSecurityConfig.java b/src/main/java/com/youlai/boot/open/llm/config/LlmSecurityConfig.java new file mode 100644 index 00000000..bb6ecfb7 --- /dev/null +++ b/src/main/java/com/youlai/boot/open/llm/config/LlmSecurityConfig.java @@ -0,0 +1,25 @@ +package com.youlai.boot.open.llm.config; + +import org.springframework.beans.factory.annotation.Value; +import org.springframework.context.annotation.Bean; +import org.springframework.context.annotation.Configuration; +import org.springframework.core.annotation.Order; +import org.springframework.security.config.annotation.web.builders.HttpSecurity; +import org.springframework.security.config.annotation.web.configurers.AbstractHttpConfigurer; +import org.springframework.security.config.http.SessionCreationPolicy; +import org.springframework.security.web.SecurityFilterChain; +import org.springframework.security.web.authentication.UsernamePasswordAuthenticationFilter; + +@Configuration +public class LlmSecurityConfig { + @Bean + @Order(1) + SecurityFilterChain llmSecurityChain(HttpSecurity http, @Value("${LLM_API_TOKEN:}") String token) throws Exception { + return http.securityMatcher("/api/v1/open/llm/**") + .csrf(AbstractHttpConfigurer::disable) + .sessionManagement(s -> s.sessionCreationPolicy(SessionCreationPolicy.STATELESS)) + .authorizeHttpRequests(a -> a.anyRequest().permitAll()) + .addFilterBefore(new LlmTokenFilter(token), UsernamePasswordAuthenticationFilter.class) + .build(); + } +} diff --git a/src/main/java/com/youlai/boot/open/llm/config/LlmTokenFilter.java b/src/main/java/com/youlai/boot/open/llm/config/LlmTokenFilter.java new file mode 100644 index 00000000..d3711cd4 --- /dev/null +++ b/src/main/java/com/youlai/boot/open/llm/config/LlmTokenFilter.java @@ -0,0 +1,37 @@ +package com.youlai.boot.open.llm.config; + +import cn.hutool.json.JSONUtil; +import com.youlai.boot.common.result.Result; +import jakarta.servlet.*; +import jakarta.servlet.http.*; +import org.springframework.web.filter.OncePerRequestFilter; +import java.io.IOException; +import java.nio.charset.StandardCharsets; +import java.security.MessageDigest; + +/** Scoped to the LLM chain; never registered as a global servlet filter. */ +public class LlmTokenFilter extends OncePerRequestFilter { + private final String token; + public LlmTokenFilter(String token) { this.token = token; } + + @Override protected void doFilterInternal(HttpServletRequest request, HttpServletResponse response, + FilterChain chain) throws ServletException, IOException { + String auth = request.getHeader("Authorization"); + if (token == null || token.isBlank()) { + reject(response, 503, "LLM 接口尚未配置访问令牌"); + return; + } + if (auth == null || !auth.startsWith("Bearer ") || !MessageDigest.isEqual( + token.getBytes(StandardCharsets.UTF_8), auth.substring(7).getBytes(StandardCharsets.UTF_8))) { + reject(response, 401, "LLM 访问令牌无效"); + return; + } + chain.doFilter(request, response); + } + + private void reject(HttpServletResponse response, int status, String message) throws IOException { + response.setStatus(status); + response.setContentType("application/json;charset=UTF-8"); + response.getWriter().write(JSONUtil.toJsonStr(Result.failed(message))); + } +} diff --git a/src/main/java/com/youlai/boot/open/llm/controller/LlmChatController.java b/src/main/java/com/youlai/boot/open/llm/controller/LlmChatController.java new file mode 100644 index 00000000..7f916b50 --- /dev/null +++ b/src/main/java/com/youlai/boot/open/llm/controller/LlmChatController.java @@ -0,0 +1,30 @@ +package com.youlai.boot.open.llm.controller; + +import com.youlai.boot.common.result.Result; +import com.youlai.boot.open.llm.model.*; +import com.youlai.boot.open.llm.service.LlmChatService; +import io.swagger.v3.oas.annotations.Operation; +import io.swagger.v3.oas.annotations.tags.Tag; +import jakarta.validation.Valid; +import lombok.RequiredArgsConstructor; +import org.springframework.http.ResponseEntity; +import org.springframework.web.bind.annotation.*; +import org.springframework.web.server.ResponseStatusException; + +@RestController +@RequestMapping("/api/v1/open/llm") +@RequiredArgsConstructor +@Tag(name = "通用 LLM 对话") +public class LlmChatController { + private final LlmChatService service; + + @PostMapping("/chat/completions") + @Operation(summary = "固定 Bearer Token 鉴权的多轮非流式对话") + public ResponseEntity> chat(@Valid @RequestBody LlmChatRequest request) { + try { + return ResponseEntity.ok(Result.success(service.chat(request))); + } catch (ResponseStatusException e) { + return ResponseEntity.status(e.getStatusCode()).body(Result.failed(e.getReason())); + } + } +} diff --git a/src/main/java/com/youlai/boot/open/llm/model/LlmChatRequest.java b/src/main/java/com/youlai/boot/open/llm/model/LlmChatRequest.java new file mode 100644 index 00000000..d5b5f596 --- /dev/null +++ b/src/main/java/com/youlai/boot/open/llm/model/LlmChatRequest.java @@ -0,0 +1,13 @@ +package com.youlai.boot.open.llm.model; + +import jakarta.validation.Valid; +import jakarta.validation.constraints.*; +import java.util.List; + +public record LlmChatRequest( + @NotEmpty @Size(max = 50) List<@NotNull @Valid Message> messages, + @Min(1) @Max(4096) Integer maxTokens, + @DecimalMin("0.0") @DecimalMax("2.0") Double temperature) { + public record Message(@NotNull @Pattern(regexp = "system|user|assistant") String role, + @NotBlank @Size(max = 8000) String content) {} +} diff --git a/src/main/java/com/youlai/boot/open/llm/model/LlmChatResponse.java b/src/main/java/com/youlai/boot/open/llm/model/LlmChatResponse.java new file mode 100644 index 00000000..43caa25a --- /dev/null +++ b/src/main/java/com/youlai/boot/open/llm/model/LlmChatResponse.java @@ -0,0 +1,5 @@ +package com.youlai.boot.open.llm.model; + +public record LlmChatResponse(String model, String content, String finishReason, Usage usage) { + public record Usage(Integer promptTokens, Integer completionTokens, Integer totalTokens) {} +} diff --git a/src/main/java/com/youlai/boot/open/llm/service/LlmChatService.java b/src/main/java/com/youlai/boot/open/llm/service/LlmChatService.java new file mode 100644 index 00000000..e7e58310 --- /dev/null +++ b/src/main/java/com/youlai/boot/open/llm/service/LlmChatService.java @@ -0,0 +1,78 @@ +package com.youlai.boot.open.llm.service; + +import cn.hutool.json.JSONObject; +import cn.hutool.json.JSONUtil; +import com.youlai.boot.open.llm.model.*; +import org.springframework.beans.factory.annotation.Autowired; +import org.springframework.beans.factory.annotation.Value; +import org.springframework.http.HttpStatus; +import org.springframework.stereotype.Service; +import org.springframework.web.server.ResponseStatusException; +import java.net.URI; +import java.net.http.*; +import java.time.Duration; +import java.util.*; +import java.util.concurrent.Semaphore; + +@Service +public class LlmChatService { + private final String key; + private final String model; + private final URI endpoint; + private final HttpClient client; + private final Semaphore slots = new Semaphore(4); + + @Autowired + public LlmChatService(@Value("${DEEPSEEK_API_KEY:}") String key, + @Value("${DEEPSEEK_MODEL:deepseek-flash}") String model) { + this(key, model, URI.create("https://api.deepseek.com/chat/completions")); + } + + LlmChatService(String key, String model, URI endpoint) { + this.key = key; + this.model = model; + this.endpoint = endpoint; + client = HttpClient.newBuilder().connectTimeout(Duration.ofSeconds(5)).build(); + } + + public LlmChatResponse chat(LlmChatRequest request) { + if (key.isBlank()) throw new ResponseStatusException(HttpStatus.SERVICE_UNAVAILABLE, "LLM 模型密钥尚未配置"); + if (request.messages().stream().mapToInt(m -> m.content().length()).sum() > 32000) { + throw new ResponseStatusException(HttpStatus.BAD_REQUEST, "消息总长度不能超过 32000 字符"); + } + if (!slots.tryAcquire()) throw new ResponseStatusException(HttpStatus.TOO_MANY_REQUESTS, "LLM 请求繁忙,请稍后重试"); + try { + Map payload = new LinkedHashMap<>(); + payload.put("model", model); + payload.put("stream", false); + payload.put("thinking", Map.of("type", "disabled")); + payload.put("max_tokens", request.maxTokens() == null ? 1024 : request.maxTokens()); + payload.put("temperature", request.temperature() == null ? 0.7 : request.temperature()); + payload.put("messages", request.messages().stream().map(m -> Map.of("role", m.role(), "content", m.content())).toList()); + HttpRequest upstream = HttpRequest.newBuilder(endpoint).timeout(Duration.ofSeconds(60)) + .header("Authorization", "Bearer " + key).header("Content-Type", "application/json") + .POST(HttpRequest.BodyPublishers.ofString(JSONUtil.toJsonStr(payload))).build(); + HttpResponse response = client.send(upstream, HttpResponse.BodyHandlers.ofString()); + if (response.statusCode() != 200 || response.body().length() > 1024 * 1024) { + throw new IllegalArgumentException("invalid upstream response"); + } + JSONObject root = JSONUtil.parseObj(response.body()); + JSONObject choice = root.getJSONArray("choices").getJSONObject(0); + String content = choice.getJSONObject("message").getStr("content"); + if (content == null || content.isBlank()) throw new IllegalArgumentException("empty content"); + JSONObject usage = root.getJSONObject("usage"); + return new LlmChatResponse(root.getStr("model"), content, choice.getStr("finish_reason"), usage == null ? null + : new LlmChatResponse.Usage(usage.getInt("prompt_tokens"), usage.getInt("completion_tokens"), usage.getInt("total_tokens"))); + } catch (InterruptedException e) { + Thread.currentThread().interrupt(); + throw new ResponseStatusException(HttpStatus.SERVICE_UNAVAILABLE, "LLM 请求已中断"); + } catch (HttpTimeoutException e) { + throw new ResponseStatusException(HttpStatus.GATEWAY_TIMEOUT, "LLM 请求超时"); + } catch (Exception e) { + // Do not expose upstream bodies, messages, or credentials. + throw new ResponseStatusException(HttpStatus.BAD_GATEWAY, "LLM 服务暂不可用"); + } finally { + slots.release(); + } + } +} diff --git a/src/test/java/com/youlai/boot/open/llm/config/LlmSecurityConfigTest.java b/src/test/java/com/youlai/boot/open/llm/config/LlmSecurityConfigTest.java new file mode 100644 index 00000000..7d251a45 --- /dev/null +++ b/src/test/java/com/youlai/boot/open/llm/config/LlmSecurityConfigTest.java @@ -0,0 +1,41 @@ +package com.youlai.boot.open.llm.config; + +import jakarta.servlet.Filter; +import org.junit.jupiter.api.Test; +import org.springframework.context.annotation.*; +import org.springframework.mock.web.*; +import org.springframework.security.config.annotation.web.configuration.EnableWebSecurity; +import org.springframework.web.context.support.AnnotationConfigWebApplicationContext; +import java.util.Map; +import java.util.concurrent.atomic.AtomicBoolean; +import org.springframework.core.env.MapPropertySource; +import static org.junit.jupiter.api.Assertions.*; + +class LlmSecurityConfigTest { + @Configuration + @EnableWebSecurity + @Import(LlmSecurityConfig.class) + static class Config {} + + @Test void dedicatedChainAcceptsFixedTokenWithoutJwtAuthentication() throws Exception { + try (var context = new AnnotationConfigWebApplicationContext()) { + context.setServletContext(new MockServletContext()); + context.getEnvironment().getPropertySources().addFirst(new MapPropertySource("test", + Map.of("LLM_API_TOKEN", "fixed-test-token"))); + context.register(Config.class); + context.refresh(); + Filter filter = context.getBean("springSecurityFilterChain", Filter.class); + for (String token : new String[]{"fixed-test-token", "wrong"}) { + String path = "/api/v1/open/llm/chat/completions"; + var request = new MockHttpServletRequest("POST", path); + request.setServletPath(path); + request.addHeader("Authorization", "Bearer " + token); + var response = new MockHttpServletResponse(); + AtomicBoolean reached = new AtomicBoolean(); + filter.doFilter(request, response, (req, res) -> reached.set(true)); + assertEquals(token.equals("fixed-test-token"), reached.get()); + if (!reached.get()) assertEquals(401, response.getStatus()); + } + } + } +} diff --git a/src/test/java/com/youlai/boot/open/llm/config/LlmTokenFilterTest.java b/src/test/java/com/youlai/boot/open/llm/config/LlmTokenFilterTest.java new file mode 100644 index 00000000..21d79971 --- /dev/null +++ b/src/test/java/com/youlai/boot/open/llm/config/LlmTokenFilterTest.java @@ -0,0 +1,28 @@ +package com.youlai.boot.open.llm.config; + +import org.junit.jupiter.api.Test; +import org.springframework.mock.web.*; +import java.util.concurrent.atomic.AtomicBoolean; +import static org.junit.jupiter.api.Assertions.*; + +class LlmTokenFilterTest { + @Test void acceptsOnlyConfiguredBearerToken() throws Exception { + for (String value : new String[]{"Bearer fixed-test-token", "Bearer wrong", "Basic fixed-test-token", ""}) { + var request = new MockHttpServletRequest("POST", "/api/v1/open/llm/chat/completions"); + if (!value.isEmpty()) request.addHeader("Authorization", value); + var response = new MockHttpServletResponse(); + AtomicBoolean called = new AtomicBoolean(); + new LlmTokenFilter("fixed-test-token").doFilter(request, response, (req, res) -> called.set(true)); + assertEquals(value.equals("Bearer fixed-test-token"), called.get()); + if (!called.get()) assertEquals(401, response.getStatus()); + } + } + + @Test void missingConfigurationFailsClosed() throws Exception { + var request = new MockHttpServletRequest(); + request.addHeader("Authorization", "Bearer anything"); + var response = new MockHttpServletResponse(); + new LlmTokenFilter("").doFilter(request, response, (req, res) -> fail("must not pass")); + assertEquals(503, response.getStatus()); + } +} diff --git a/src/test/java/com/youlai/boot/open/llm/service/LlmChatServiceTest.java b/src/test/java/com/youlai/boot/open/llm/service/LlmChatServiceTest.java new file mode 100644 index 00000000..1382f3ce --- /dev/null +++ b/src/test/java/com/youlai/boot/open/llm/service/LlmChatServiceTest.java @@ -0,0 +1,72 @@ +package com.youlai.boot.open.llm.service; + +import cn.hutool.json.JSONUtil; +import com.sun.net.httpserver.HttpServer; +import com.youlai.boot.open.llm.model.LlmChatRequest; +import org.junit.jupiter.api.*; +import org.springframework.web.server.ResponseStatusException; +import java.net.*; +import java.nio.charset.StandardCharsets; +import java.util.List; +import java.util.concurrent.atomic.AtomicReference; +import static org.junit.jupiter.api.Assertions.*; + +class LlmChatServiceTest { + private HttpServer server; + private URI uri; + @BeforeEach void start() throws Exception { + server = HttpServer.create(new InetSocketAddress("127.0.0.1", 0), 0); + uri = URI.create("http://127.0.0.1:" + server.getAddress().getPort() + "/chat"); + server.start(); + } + @AfterEach void stop() { server.stop(0); } + private LlmChatRequest request() { + return new LlmChatRequest(List.of(new LlmChatRequest.Message("system", "简短回答"), + new LlmChatRequest.Message("user", "你好")), null, null); + } + + @Test void forwardsHistoryAndReturnsContentAndUsage() { + AtomicReference body = new AtomicReference<>(); + AtomicReference auth = new AtomicReference<>(); + server.createContext("/chat", exchange -> { + body.set(new String(exchange.getRequestBody().readAllBytes(), StandardCharsets.UTF_8)); + auth.set(exchange.getRequestHeaders().getFirst("Authorization")); + byte[] reply = ("{\"model\":\"test-model\",\"choices\":[{\"message\":{\"content\":\"你好!\"}," + + "\"finish_reason\":\"stop\"}],\"usage\":{\"prompt_tokens\":5,\"completion_tokens\":3,\"total_tokens\":8}}") + .getBytes(StandardCharsets.UTF_8); + exchange.getResponseHeaders().set("Content-Type", "application/json; charset=utf-8"); + exchange.sendResponseHeaders(200, reply.length); + exchange.getResponseBody().write(reply); + exchange.close(); + }); + var result = new LlmChatService("upstream-test-key", "test-model", uri).chat(request()); + assertEquals("你好!", result.content()); + assertEquals(8, result.usage().totalTokens()); + assertEquals("Bearer upstream-test-key", auth.get()); + var json = JSONUtil.parseObj(body.get()); + assertEquals(2, json.getJSONArray("messages").size()); + assertEquals(1024, json.getInt("max_tokens")); + assertEquals("disabled", json.getJSONObject("thinking").getStr("type")); + assertFalse(json.getBool("stream")); + } + + @Test void upstreamFailureDoesNotLeakProviderBody() { + server.createContext("/chat", e -> { + byte[] reply = "secret-provider-detail".getBytes(StandardCharsets.UTF_8); + e.sendResponseHeaders(401, reply.length); e.getResponseBody().write(reply); e.close(); + }); + var error = assertThrows(ResponseStatusException.class, + () -> new LlmChatService("test", "test", uri).chat(request())); + assertEquals(502, error.getStatusCode().value()); + assertFalse(error.getMessage().contains("secret-provider-detail")); + } + + @Test void missingKeyAndOversizedHistoryFailBeforeNetwork() { + assertEquals(503, assertThrows(ResponseStatusException.class, + () -> new LlmChatService("", "test", uri).chat(request())).getStatusCode().value()); + var large = new LlmChatRequest(java.util.Collections.nCopies(5, + new LlmChatRequest.Message("user", "a".repeat(8000))), null, null); + assertEquals(400, assertThrows(ResponseStatusException.class, + () -> new LlmChatService("test", "test", uri).chat(large)).getStatusCode().value()); + } +}