欢迎光临
我们一直在努力

Java 程序员第 40 阶段05:从零搭建 Java 大模型完整项目,接口层设计与API开发

概述

本文介绍Java大模型项目的接口层设计与API开发,涵盖RESTful API设计规范、对话接口实现(同步+流式SSE)、知识库问答接口、文件上传与处理接口,以及API文档Swagger集成。

1 RESTful API设计规范

1.1 API设计原则

– **资源导向**:以名词而非动词命名 endpoint

– **HTTP方法对应**:GET(查询)、POST(创建)、PUT(更新)、DELETE(删除)

– **版本控制**:通过URL路径 /api/v1/ 进行版本管理

– **统一响应格式**:所有接口返回统一JSON结构

1.2 统一响应格式

public class ApiResponse<T> {
    private int code;
    private String message;
    private T data;
    private long timestamp;

    public static <T> ApiResponse<T> success(T data) {
        return new ApiResponse<>(200, "success", data, System.currentTimeMillis());
    }

    public static <T> ApiResponse<T> error(int code, String message) {
        return new ApiResponse<>(code, message, null, System.currentTimeMillis());
    }
}

1.3 接口路径规范

| 模块 | 前缀 | 示例 |

|——|——|——|

| 对话 | /api/v1/chat | POST /api/v1/chat/stream |

| 知识库 | /api/v1/knowledge | POST /api/v1/knowledge/query |

| 文件 | /api/v1/file | POST /api/v1/file/upload |

| 用户 | /api/v1/user | GET /api/v1/user/profile |

2 对话接口实现

2.1 同步对话接口

@RestController
@RequestMapping("/api/v1/chat")
@RequiredArgsConstructor
public class ChatController {

    private final ChatService chatService;

    @PostMapping("/sync")
    public ApiResponse<ChatResponse> syncChat(@RequestBody ChatRequest request) {
        return ApiResponse.success(chatService.chat(request));
    }
}

2.2 流式对话接口(SSE)

SSE(Server-Sent Events)实现流式输出:

@GetMapping(value = "/stream", produces = MediaType.TEXT_EVENT_STREAM_VALUE)
public Flux<String> streamChat(@RequestParam String message) {
    return chatService.streamChat(message)
        .map(chunk -> "data: " + chunk + "\\n\\n")
        .concatWith(Flux.just("data: [DONE]\\n\\n"));
}

2.3 前端调用示例

const eventSource = new EventSource(`/api/v1/chat/stream?message=${encodeURIComponent(input)}`);
eventSource.onmessage = (event) => {
    if (event.data === '[DONE]') {
        eventSource.close();
    } else {
        appendToChat(event.data);
    }
};

3 知识库问答接口

3.1 接口设计

@PostMapping("/query")
public ApiResponse<KnowledgeResponse> query(
    @RequestBody KnowledgeQueryRequest request) {

    // 1. 向量相似度检索
    List<Document> documents = knowledgeService.search(
        request.getQuery(),
        request.getTopK()
    );

    // 2. 构建提示词
    String prompt = buildPrompt(documents, request.getQuery());

    // 3. 调用大模型生成答案
    String answer = llmService.chat(prompt);

    return ApiResponse.success(new KnowledgeResponse(answer, documents));
}

3.2 检索增强生成(RAG)

用户查询向量检索 → TopK相关文档构建提示词 → LLM生成返回答案

4 文件上传与处理接口

4.1 文件上传Controller

@PostMapping("/upload")
public ApiResponse<FileUploadResponse> upload(
    @RequestParam("file") MultipartFile file,
    @RequestParam(value = "type", defaultValue = "document") String type) {

    // 1. 文件校验
    validateFile(file);

    // 2. 保存文件
    String fileId = fileService.store(file, type);

    // 3. 异步处理(文本提取、向量化)
    asyncProcess(fileId);

    return ApiResponse.success(new FileUploadResponse(fileId, file.getOriginalFilename()));
}

4.2 支持的文件类型

| 类型 | 扩展名 | 处理方式 |

|——|——–|———-|

| 文本 | txt, md, json | 直接解析 |

| Word | docx, doc | Apache POI |

| PDF | pdf | PDFBox解析 |

| 表格 | xlsx, csv | EasyExcel |

5 API文档Swagger集成

5.1 SpringDoc配置

springdoc:
  api-docs:
    path: /api-docs
  swagger-ui:
    path: /swagger-ui.html
    enabled: true

5.2 接口注解示例

@Operation(
    summary = "
流式对话接口",
    description = "
支持SSE流式输出的对话接口,适用于需要实时响应的场景"
)
@ApiResponse(
    responseCode = "200",
    description = "
成功",
    content = @Content(mediaType = "text/event-stream")
)
@GetMapping(value = "/stream", produces = MediaType.TEXT_EVENT_STREAM_VALUE)
public Flux<String> streamChat(@RequestParam String message) {
    // …
}

5.3 访问地址

– Swagger UI: http://localhost:8080/swagger-ui.html

– API Docs: http://localhost:8080/api-docs

6 接口安全设计

6.1 认证机制

采用JWT Token认证:

@Bean
public SecurityFilterChain filterChain(HttpSecurity http) throws Exception {
    http
        .csrf(AbstractHttpConfigurer::disable)
        .authorizeHttpRequests(auth -> auth
            .requestMatchers("/api/v1/auth/**").permitAll()
            .requestMatchers("/swagger-ui/**", "/api-docs/**").permitAll()
            .anyRequest().authenticated()
        )
        .addFilterBefore(jwtAuthFilter, UsernamePasswordAuthenticationFilter.class);
    return http.build();
}

6.2 限流策略

使用Redis实现接口限流:

@Aspect
@Component
public class RateLimitAspect {

    @Autowired
    private RedisTemplate<String, String> redisTemplate;

    @Around("@annotation(rateLimit)")
    public Object rateLimit(ProceedingJoinPoint point, RateLimit rateLimit) throws Throwable {
        String key = getKey(point);
        Long count = redisTemplate.opsForValue().increment(key);

        if (count != null && count > rateLimit.maxRequests()) {
            throw new BizException("请求过于频繁,请稍后重试");
        }
        return point.proceed();
    }
}

7 总结

本文介绍了Java大模型项目的接口层设计与实现,涵盖了:

– RESTful API设计规范和统一响应格式

– 同步与流式(SSE)对话接口实现

– 知识库问答接口的RAG架构

– 文件上传与处理接口

– Swagger API文档集成

– 接口安全认证与限流策略

这些接口设计为上层应用提供了完整的与大模型交互的能力。

赞(0)
未经允许不得转载:171主机测评 » Java 程序员第 40 阶段05:从零搭建 Java 大模型完整项目,接口层设计与API开发
分享到: 更多 (0)

评论 抢沙发

  • 昵称 (必填)
  • 邮箱 (必填)
  • 网址