✨ 我是 Muzi 的「文章捕手」,擅长在文字的星海中打捞精华。每当新的篇章诞生,我就会像整理贝壳一样,将思想的闪光点串成珍珠项链~

本文介绍了四种主流的AI大模型接入方式,重点展示了通过SDK集成的具体实现步骤。文中详细说明了如何在Java项目中引入阿里巴巴的dashscope-sdk-java依赖,并通过示例代码演示了构建系统消息和用户消息、配置API密钥及模型名称、调用生成接口并获取结果的全过程。该方法简化了AI模型调用流程,方便开发者快速集成和应用,提高开发效率。文章具有较强的实用指导意义,适合应用开发中的AI能力接入需求。

2026-06-05🌱上海: 🌤️ 🌡️+78°F 🌬️←12mph

开发中,有多种方式可以在应用程序中调用AI大模型。下面介绍4种主流的接入方式。

# SDK接入

引入POM依赖

<!-- Source: https://mvnrepository.com/artifact/com.alibaba/dashscope-sdk-java -->  
<dependency>  
    <groupId>com.alibaba</groupId>  
    <artifactId>dashscope-sdk-java</artifactId>  
    <version>2.22.17</version>  
    <scope>compile</scope>  
</dependency>

编写代码

public class SdkAiInvoke {  
  
    public static GenerationResult callWithMessage() throws ApiException, NoApiKeyException, InputRequiredException {  
        Generation gen = new Generation();  
        Message systemMsg = Message.builder()  
                .role(Role.SYSTEM.getValue())  
                .content("You are a helpful assistant.")  
                .build();  
        Message userMsg = Message.builder()  
                .role(Role.USER.getValue())  
                .content("你是谁?")  
                .build();  
        GenerationParam param = GenerationParam.builder()  
                // 若没有配置环境变量,请用百炼API Key将下行替换为:.apiKey("sk-xxx")  
                .apiKey(TestApiKey.API_KEY)  
                // 此处以qwen-plus为例,可按需更换模型名称。模型列表:https://help.aliyun.com/zh/model-studio/getting-started/models  
                .model("qwen-plus")  
                .messages(Arrays.asList(systemMsg, userMsg))  
                .resultFormat(GenerationParam.ResultFormat.MESSAGE)  
                .build();  
        return gen.call(param);  
    }  
  
    public static void main(String[] args) {  
        try {  
            GenerationResult result = callWithMessage();  
            System.out.println(JsonUtils.toJson(result));  
        } catch (ApiException | NoApiKeyException | InputRequiredException e) {  
            // 使用日志框架记录异常信息  
            System.err.println("An error occurred while calling the generation service: " + e.getMessage());  
        }  
        System.exit(0);  
    }  
}