程序调用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);
    }
}
相关推荐
yong99902 小时前
基于直方图优化的图像去雾技术MATLAB实现
人工智能·计算机视觉·matlab
熊猫钓鱼>_>2 小时前
GenUI:从“文本对话”到“可操作界面”的范式转移
开发语言·人工智能·agent·sdk·vibecoding·assistant·genui
其实防守也摸鱼2 小时前
部署本地AI大模型--ollma
人工智能·安全·ai·大模型·软件工程·本地大模型
拂晓 AI 编程2 小时前
claude code 加上 PPT Master skill 生成可手改PPT
人工智能·powerpoint
小橙子学AI2 小时前
Rokid AI眼镜皮肤健康检测智能体技术实践
人工智能
Ether IC Verifier2 小时前
PCIe数据链路层详细介绍
网络·网络协议·tcp/ip·计算机网络·dpu
QQ676580082 小时前
智慧工地物料堆积识别 工地钢筋木材图像识别 工地砖块目标检测 建筑物大理石图像识别 建筑物工地材料识别 物料堆积识别10349期
人工智能·目标检测·计算机视觉·工地物料堆积·工地钢筋木材图像识别·工地砖块目标检测·建筑物大理石图像
懂AI的老郑2 小时前
时空智能体技术研究与应用
人工智能
Wild API2 小时前
多模型成本治理怎么落地?从任务分层、日志统计到结构优化的一套实战思路
大数据·网络·人工智能