上一章我们初识了 Spring AI Alibaba 的 helloworld 模块,完成了环境搭建与快速入门,并成功调用了阿里云百炼平台的模型。那么有个疑问,之前私有化部署的时候使用过 ollama、vllm 部署,调用和目前一致吗?本章将带大家深入样例代码,一探究竟!
本章将探究
spring-ai-alibaba-chat-example 模块,该模块提供了常见的大模型平台 dashscope(阿里云百炼)、deepseel、ollama、openai、qwq(阿里云百炼)、vllm(openAI 标准)、zhipuai(智谱)
1. dashscope-chat 我们登录阿里云百炼平台申请 api-key(有免费提供的 token),直接替换 application.yml 里面的 api-key。按照 dashscope-chat.http 脚本里面提供的地址访问 controller 接口,即可和 AI 模型交互。spring ai alibaba 提供了 DashScopeChatOptions 用来初始化 ChatClient 和模型交互。 2. deepseek-chat 我们登录 deepseek,进入 APi 开放平台,充值1元(结合自己实力)生成 apikey 后直接替换 application.yml 里面的 api-key。按照 deepseek-chat.http 脚本里面提供的地址访问 controller 接口,即可和 AI 模型交互。spring ai 提供了 DeepSeekChatModel、DeepSeekChatO #技术分享 #掘金ptions 用来和模型交互。 3. vllm-chat 之前 ollama 私有化部署后续切换成 vllm 部署,因此直接测试 vllm 模型,在此模块遇到么阻塞很久的问题,一直没测试成功 。按照 vllm 部署的参数配置了 application.yml,启动后一直报错
400 - {"object":"error","message":"[{'type': 'missing', 'loc': ('body',), 'msg': 'Field required', 'input': None}]"}
问题原因 :Spring AI 默认使用基于 WebClient 或 RestTemplate 的 HTTP 客户端,以分块编码(chunked) 发送请求体。vLLM 服务端无法解析分块编码的请求体,导致报错。
解决办法 :完全禁用 Spring WebClient 的分块传输编码(chunked transfer encoding),通过底层 Reactor Netty 客户端进行配置。
<dependency>
<groupId>io.projectreactor.netty</groupId>
<artifactId>reactor-netty-http</artifactId>
</dependency>
package com.alibaba.cloud.ai.example.chat.vllm.conf;
import org.springframework.context.annotation.Bean; import org.springframework.context.annotation.Configuration; import org.springframework.http.client.reactive.ReactorClientHttpConnector; import org.springframework.web.reactive.function.client.WebClient;
import reactor.netty.http.client.HttpClient;
@Configuration public class WebClientConfig {
@Bean public WebClient webClient() { HttpClient httpClient = HttpClient.create() .headers(headers -> headers .remove("Transfer-Encoding") .set("Connection", "close") ) .compress(false);
return WebClient.builder() .clientConnector(new ReactorClientHttpConnector(httpClient)) .build(); } }
通过
spring-ai-alibaba-chat-example 模块的实践,我们成功实现了第三方大模型平台的调用集成,并重点解决了 vLLM 私有化部署模型 的常见调用错误问题。