Spring AI Alibaba示例代码(其他平台模型及vllm-chat 400错误解决)

上一章我们初识了 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、DeepSeekChatOptions用来和模型交互。 3. vllm-chat 之前ollama私有化部署后续切换成vllm部署,因此直接测试vllm模型,在此模块遇到么阻塞很久的问题,一直没测试成功

按照vllm部署的参数配置了application.yml,启动后一直报错

less 复制代码
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 客户端进行配置。

xml 复制代码
<dependency>
    <groupId>io.projectreactor.netty</groupId>
    <artifactId>reactor-netty-http</artifactId>
</dependency>
kotlin 复制代码
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() {
        // 创建并配置 Netty 的 HttpClient
        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 私有化部署模型 的常见调用错误问题。

相关推荐
不浪brown9 小时前
cursor!还钱!
ai编程·cursor·trae
waynaqua12 小时前
Claude Code 最新版已经支持 Windows 安装使用!
ai编程·claude
用户66769403763013 小时前
生产力升级:将ERNIE 4.5-VL模型封装为可随时调用的API服务
ai编程
mortimer16 小时前
当AI配音遇上视频:实现音画同步的自动化工程实践
python·ffmpeg·ai编程
大模型真好玩18 小时前
深入浅出LangChain AI Agent智能体开发教程(二)—LangChain接入大模型
人工智能·python·ai编程
特立独行的猫a18 小时前
AI编程神器 Claude Code 安装及使用体验
ide·ai编程·claude·ai ide·claude code
葫芦和十三21 小时前
SuperClaude 硬核指南:将你的 AI 助手锻造成专业开发战友
后端·ai编程·claude
极客密码21 小时前
Kiro AI IDE上手初体验!亚马逊出品,能否撼动Cursor的王座?
aigc·ai编程·cursor
张拭心1 天前
亚马逊 AI IDE Kiro “狙击”Cursor?实测心得
前端·ai编程