Spring AI(Vertex AI)是否支持自定义微调模型?配置异常求助
Spring AI调用Vertex AI自定义微调模型的解决方案
核心结论
Spring AI支持调用Vertex AI上的自定义微调模型,但不能直接沿用官方预训练Gemini模型的默认配置方式——你遇到的默认 fallback 到gemini-flash-001的问题,是因为默认的预训练模型客户端会校验模型名称,不符合预设列表时就会自动使用默认值。
具体实现方式
要调用自定义微调模型,需要绕过默认的预训练模型封装,可采用以下两种方式:
1. 使用Vertex AI低阶Java客户端直接调用
直接借助Google Cloud提供的Vertex AI Java客户端库,构造针对自定义模型的请求:
import com.google.cloud.vertexai.VertexAI; import com.google.cloud.vertexai.api.GenerateContentResponse; import com.google.cloud.vertexai.generativeai.GenerativeModel; public class CustomVertexAIModelClient { public String callFineTunedModel(String projectId, String location, String customModelId, String prompt) { try (VertexAI vertexAI = new VertexAI(projectId, location)) { // 指定自定义模型的完整资源路径 GenerativeModel model = new GenerativeModel(customModelId, vertexAI); GenerateContentResponse response = model.generateContent(prompt); return response.getCandidates(0).getContent().getParts(0).getText(); } } }
配置时,确保已通过环境变量或服务账号密钥完成Google Cloud的身份认证。
2. 自定义Spring AI的ChatModel实现
如果想沿用Spring AI的ChatModel抽象,让自定义模型适配Spring AI生态,可以实现自己的ChatModel类:
import org.springframework.ai.chat.model.ChatModel; import org.springframework.ai.chat.model.ChatResponse; import org.springframework.ai.chat.prompt.Prompt; import com.google.cloud.vertexai.VertexAI; import com.google.cloud.vertexai.generativeai.GenerativeModel; import java.util.List; public class CustomVertexAIChatModel implements ChatModel { private final GenerativeModel generativeModel; public CustomVertexAIChatModel(String projectId, String location, String customModelId) { VertexAI vertexAI = new VertexAI(projectId, location); this.generativeModel = new GenerativeModel(customModelId, vertexAI); } @Override public ChatResponse call(Prompt prompt) { // 转换Spring AI Prompt格式为Vertex AI要求的格式 String promptText = prompt.getInstructions().getContent(); var response = generativeModel.generateContent(promptText); // 转换Vertex AI响应为Spring AI ChatResponse格式 return new ChatResponse(List.of(new org.springframework.ai.chat.model.ChatResponse.Message( org.springframework.ai.chat.model.ChatResponse.Message.Role.ASSISTANT, response.getCandidates(0).getContent().getParts(0).getText() ))); } }
然后在Spring配置类中注册这个自定义Bean:
import org.springframework.context.annotation.Bean; import org.springframework.context.annotation.Configuration; import org.springframework.ai.chat.model.ChatModel; @Configuration public class VertexAIConfig { @Bean public ChatModel customVertexAIChatModel() { return new CustomVertexAIChatModel( "your-project-id", "your-location", "projects/your-project-id/locations/your-location/models/your-custom-model-id" ); } }
关键注意事项
- 自定义模型的名称需要使用完整的资源路径,格式为
projects/{project-id}/locations/{location}/models/{custom-model-id},而非简单的模型ID - 确保你的服务账号拥有
aiplatform.models.predict权限,能够访问Vertex AI上的自定义模型
内容的提问来源于stack exchange,提问作者Ryan Howell
相关产品推荐
相关产品推荐

