java 对接阿里千问大模型接口【实操版】

时间:2024-10-14 20:30:18
package com.university.demo; import java.util.Arrays; import com.alibaba.dashscope.aigc.generation.Generation; import com.alibaba.dashscope.aigc.generation.GenerationParam; import com.alibaba.dashscope.aigc.generation.GenerationResult; import com.alibaba.dashscope.common.Message; import com.alibaba.dashscope.common.Role; import com.alibaba.dashscope.exception.ApiException; import com.alibaba.dashscope.exception.InputRequiredException; import com.alibaba.dashscope.exception.NoApiKeyException; public class Main { public static GenerationResult callWithMessage() throws ApiException, NoApiKeyException, InputRequiredException { Generation gen = new Generation(); Message userMsg = Message.builder() .role(Role.USER.getValue()) .content("卢森堡的历史?他们从某种意义上说是德国人吗?") .build(); GenerationParam param = GenerationParam.builder() .model("qwen-turbo") .messages(Arrays.asList( userMsg)) .resultFormat(GenerationParam.ResultFormat.MESSAGE) .build(); return gen.call(param); } public static void main(String[] args) { try { GenerationResult result = callWithMessage(); System.out.println(result.getOutput().getChoices().get(0).getMessage().getContent()); } catch (ApiException | NoApiKeyException | InputRequiredException e) { // 使用日志框架记录异常信息 System.err.println("An error occurred while calling the generation service: " + e.getMessage()); } System.exit(0); } }