一、项目背景
近期完成一个医疗 AI 问答类小程序需求,核心是实现用户在线咨询、AI 智能解答、基础对话管理,要求快速交付、接口稳定、内容合规。整体采用Java 后端 + 第三方 AI 大模型接口 + 微信小程序的轻量方案,无需训练模型,开发成本低、上线速度快,非常适合中小项目快速落地。
二、技术选型
- 后端:Java + Spring Boot
- AI 接口:通义千问 / 讯飞星火(免费额度够用,接口完善)
- 前端:微信小程序原生开发
- 数据存储:MySQL(存储对话记录)
- 核心能力:AI 接口封装、敏感词过滤、对话上下文管理、流式响应
三、核心功能实现
1. AI 接口统一封装
把 AI 接口做通用封装,方便后续切换模型、统一异常处理、超时控制。
@RestController @RequestMapping("/api/ai") @Slf4j public class AiChatController { @Autowired private AiApiService aiApiService; @PostMapping("/chat") public Result chat(@RequestBody AiChatDTO dto) { try { // 1. 输入校验 + 敏感词过滤 if (StringUtil.isEmpty(dto.getQuestion()) || SensitiveFilter.filter(dto.getQuestion())) { return Result.fail("输入内容不合法,请重新输入"); } // 2. 构建医疗场景Prompt String prompt = buildMedicalPrompt(dto.getQuestion()); // 3. 调用AI接口 String answer = aiApiService.sendChat(prompt); // 4. 返回结果 return Result.success(answer); } catch (Exception e) { log.error("AI接口调用异常", e); return Result.fail("服务繁忙,请稍后重试"); } } /** * 医疗场景专用Prompt,强制引导合规回答 */ private String buildMedicalPrompt(String question) { return "你是专业医疗咨询助手,回答通俗易懂,不提供诊断、不开药方," + "所有内容仅供参考,身体不适请及时就医。问题:" + question; } }
2. 对话上下文管理
支持多轮对话,保留历史上下文,提升 AI 回答连贯性。
// 上下文缓存(可替换为Redis) private static final ConcurrentHashMap<String, List> USER_CONTEXT = new ConcurrentHashMap<>(); public String sendWithContext(String userId, String question) { List history = USER_CONTEXT.getOrDefault(userId, new ArrayList<>()); history.add(new ChatMessage("user", question)); // 控制上下文长度,避免过长导致响应慢 if (history.size() > 5) { history = history.subList(history.size() - 5, history.size()); } String answer = aiApiService.callAi(history); history.add(new ChatMessage("assistant", answer)); USER_CONTEXT.put(userId, history); return answer; }
3. 小程序前端核心逻辑
// 上下文缓存(可替换为Redis) private static final ConcurrentHashMap<String, List> USER_CONTEXT = new ConcurrentHashMap<>(); public String sendWithContext(String userId, String question) { List history = USER_CONTEXT.getOrDefault(userId, new ArrayList<>()); history.add(new ChatMessage("user", question)); // 控制上下文长度,避免过长导致响应慢 if (history.size() > 5) { history = history.subList(history.size() - 5, history.size()); } String answer = aiApiService.callAi(history); history.add(new ChatMessage("assistant", answer)); USER_CONTEXT.put(userId, history); return answer; }
四、开发必踩坑(避坑总结)
- AI 接口超时原因:高峰期响应慢,导致前端报错解决:设置 10s 超时,重试 2 次,增加友好提示
- 医疗合规风险原因:AI 可能输出违规内容解决:强制加提示语 + 敏感词过滤 + 前端免责声明
- 上下文膨胀原因:对话过长,接口变慢、成本变高解决:只保留最近 5 轮对话,自动清理早期记录
- 跨域 / 小程序合法域名解决:后端配置 CORS,小程序后台配置合法域名
五、项目总结
- 中小 AI 项目不用训练模型,直接对接第三方大模型成本最低、落地最快
- Java 后端封装 AI 接口非常稳定,适合做企业级 / 小程序类项目
- 医疗 / 法律 / 咨询类 AI 问答,合规 > 功能 > 体验
- 这套方案可直接复用在法律 AI、教育 AI、客服 AI 等场景