程序调用AI大模型方式(SDK\HTTP\SPRINGAI\LANFCHAIN4J)

一、SDK引入

pom.xml中引入相关依赖

xml 复制代码
<!-- https://mvnrepository.com/artifact/com.alibaba/dashscope-sdk-java -->
<dependency>
    <groupId>com.alibaba</groupId>
    <artifactId>dashscope-sdk-java</artifactId>
    <version>2.19.1</version>
</dependency>

代码

java 复制代码
import java.util.Arrays;
import java.lang.System;

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;
import com.alibaba.dashscope.utils.JsonUtils;

/**
 * 阿里云通义千问官方SDK调用示例
 * 相比原生HTTP,SDK更简洁、更安全、参数更规范
 */
public class SdkAiInvoke {

    /**
     * 调用通义千问AI接口的核心方法
     * @return AI返回的结果对象
     * @throws ApiException API调用异常
     * @throws NoApiKeyException 未提供API Key异常
     * @throws InputRequiredException 缺少必填参数异常
     */
    public static GenerationResult callWithMessage() throws ApiException, NoApiKeyException, InputRequiredException {
        // 1. 创建AI对话生成器对象(SDK核心类)
        Generation gen = new Generation();

        // 2. 构建系统消息:定义AI的角色/行为规则
        Message systemMsg = Message.builder()
                .role(Role.SYSTEM.getValue())  // 角色:system(系统设定)
                .content("You are a helpful assistant.")  // AI的行为指令
                .build();

        // 3. 构建用户消息:实际提问内容
        Message userMsg = Message.builder()
                .role(Role.USER.getValue())  // 角色:user(用户)
                .content("你是谁?")  // 用户提问
                .build();

        // 4. 构建请求参数(SDK封装,无需手动拼JSON)
        GenerationParam param = GenerationParam.builder()
                // 填写你的阿里云API Key
                .apiKey({{这里填充你自己 申请的API_KEY}})
                // 指定使用的AI模型,可在阿里云控制台更换
                .model("qwen-plus")
                // 传入对话消息列表(系统+用户)
                .messages(Arrays.asList(systemMsg, userMsg))
                // 指定返回格式为MESSAGE结构,方便解析
                .resultFormat(GenerationParam.ResultFormat.MESSAGE)
                .build();

        // 5. 发送请求并返回结果
        return gen.call(param);
    }

    /**
     * 程序入口:执行调用并打印结果
     */
    public static void main(String[] args) {
        try {
            // 调用AI接口获取结果
            GenerationResult result = callWithMessage();
            // 将结果转为JSON格式输出控制台
            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);
    }
}

二、HTTP 调用

java 复制代码
import cn.hutool.http.HttpRequest;
import cn.hutool.http.HttpResponse;
import cn.hutool.json.JSONObject;

import java.util.HashMap;
import java.util.Map;

/**
 * Java 调用阿里云通义千问AI接口
 */
public class HttpAiInvoke {
    public static void main(String[] args) {
        // 通义千问API地址
        String url = "https://dashscope.aliyuncs.com/api/v1/services/aigc/text-generation/generation";

        // 请求头:鉴权 + JSON格式
        Map<String, String> headers = new HashMap<>();
        headers.put("Authorization", "Bearer " + {{这里填充你自己 申请的API_KEY}};
        headers.put("Content-Type", "application/json");

        // 构建请求体
        JSONObject requestBody = new JSONObject();
        requestBody.put("model", "qwen-plus"); // 指定AI模型

        // 构造对话消息
        JSONObject input = new JSONObject();
        JSONObject[] messages = new JSONObject[2];

        // 系统角色:定义AI行为
        JSONObject systemMessage = new JSONObject();
        systemMessage.put("role", "system");
        systemMessage.put("content", "You are a helpful assistant.");
        messages[0] = systemMessage;

        // 用户提问
        JSONObject userMessage = new JSONObject();
        userMessage.put("role", "user");
        userMessage.put("content", "你是谁?");
        messages[1] = userMessage;

        input.put("messages", messages);
        requestBody.put("input", input);

        // 响应参数设置
        JSONObject parameters = new JSONObject();
        parameters.put("result_format", "message");
        requestBody.put("parameters", parameters);

        // 发送POST请求
        HttpResponse response = HttpRequest.post(url)
                .addHeaders(headers)
                .body(requestBody.toString())
                .execute();

        // 处理响应结果
        if (response.isOk()) {
            System.out.println("请求成功,响应内容:");
            System.out.println(response.body());
        } else {
            System.out.println("请求失败,状态码:" + response.getStatus());
            System.out.println("响应内容:" + response.body());
        }
    }
}

结果展示

三、SpringAI

引入依赖

xml 复制代码
<dependency>
    <groupId>com.alibaba.cloud.ai</groupId>
    <artifactId>spring-ai-alibaba-starter</artifactId>
    <version>1.0.0-M6.1</version>
</dependency>

配置文件

yaml 复制代码
spring:
  #springAI配置
  application:
    name: spring-ai-alibaba-qwq-chat-client-example
  ai:
    dashscope:
      api-key: {{这里填充你自己 申请的API_KEY}}
      chat:
        options:
          model: qwen-plus
java 复制代码
import org.springframework.boot.CommandLineRunner;
import org.springframework.stereotype.Component;
import jakarta.annotation.Resource;

// 取消注释即可在 SpringBoot 项目启动时执行
@Component
public class SpringAiAiInvoke implements CommandLineRunner {

    // 注入阿里云通义千问 AI 模型(Spring AI 自动装配)
    @Resource
    private ChatModel dashscopeChatModel;

    /**
     * SpringBoot 项目启动后自动执行的方法
     */
    @Override
    public void run(String... args) throws Exception {
        // 向 AI 发送提问:你好
        // call():调用 AI 接口;getResult():获取响应结果;getOutput():获取 AI 回复消息
        AssistantMessage output = dashscopeChatModel.call(new Prompt("你好"))
                .getResult()
                .getOutput();
        
        // 打印 AI 返回的回答内容
        System.out.println(output.getText());
    }
}

四、langchain4j

首先引入依赖

xml 复制代码
<!-- https://mvnrepository.com/artifact/dev.langchain4j/langchain4j-community-dashscope -->
<dependency>
    <groupId>dev.langchain4j</groupId>
    <artifactId>langchain4j-community-dashscope</artifactId>
    <version>1.0.0-beta2</version>
</dependency>
java 复制代码
import dev.langchain4j.community.model.dashscope.QwenChatModel;
import dev.langchain4j.model.chat.ChatLanguageModel;

public class LangChainAiInvoke {

    public static void main(String[] args) {
        ChatLanguageModel qwenModel = QwenChatModel.builder()
                .apiKey({{这里填充你自己 申请的API_KEY}})
                .modelName("qwen-max")
                .build();
        String answer = qwenModel.chat("我是程序员");
        System.out.println(answer);
    }
}
相关推荐
IPdodo_3 分钟前
跨境 API 调用不稳定怎么办:出口、超时重试与链路监控的实践
网络·python·网络协议
红海云10 分钟前
Kimi 双端接入 CloudBase 的工程价值
人工智能·语言模型
计算机编程-吉哥1 小时前
YOLO26 vs YOLO11 vs YOLOv8:深度学习咖啡果实成熟度分割系统【计算机毕业设计选题推荐】
人工智能·python·深度学习·yolo·django·毕业设计
冬奇Lab1 小时前
一年前没启动 AI 提效的团队,今年在付什么钱?
人工智能
NeoGressAI外贸数字化2 小时前
IOR新规9月18日生效:Form 5106六项资料自查清单
人工智能
根目录下的猫2 小时前
RK3588适配的轻量级AI模型推荐
人工智能·后端·python·目标检测
weixin_6682 小时前
Cursor 插件使用说明:Linear 与 Figma
人工智能·cursor
wshzd3 小时前
LLM之Agent(六十八)|PI(七)构建测试与开发流程
人工智能
H0311169853 小时前
App竞品数据平台功能梳理:月狐数据、七麦数据、点点数据
人工智能
YOLO数据集集合3 小时前
高铁轨道紧固件损坏检测数据集 | 高铁巡检 紧固件缺陷 轨道安全9093期
人工智能·目标检测·计算机视觉·目标跟踪·轨道·铁轨紧固件·铁轨