Sorry, your browser cannot access this site
This page requires browser support (enable) JavaScript
Learn more >

程序调用 AI 大模型

SDK 接入

首先需要按照官方文档安装 SDK:安装SDK官方指南

在选择 SDK 版本时,建议在 Maven 仓库查看最新的版本号:Maven 中央仓库版本信息

  • 在 pom.xml 中引入依赖:
1
2
3
4
5
<dependency>
<groupId>com.alibaba</groupId>
<artifactId>dashscope-sdk-java</artifactId>
<version>2.19.1</version>
</dependency>
  • 创建一个接口类​来存储密钥信息(在‎实际生产环境中,应‌使用配置文件或环境变量)

    1
    2
    3
    public interface TestApiKey {
    String API_KEY = "你的 API Key";
    }
  • 复制文档里面的代码进行测试 通过 API 调用通义千问

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
package com.example.superaiagent.demo.invoke;// 建议dashscope SDK的版本 >= 2.12.0import 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;

/*
* 阿里云灵积 AI SDK 调用
* */
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);
}
}

HTTP 接入

  1. 对于 SD⁠K 不支持的编程语言‌或需要更灵活控制的场​景,可以直接使用 H‎TTP 请求调用 A‌I 大模型的 API
  2. 一⁠般来说,如果有官方 SDK 支持,优‌先使用 SDK;只有在不支持 SDK​ 的情况下,再考虑直接 HTTP 调用‎
  3. HTTP 调用的详细说明可参考官方文档:通过 API 调用通义千问
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
package com.example.superaiagent.demo.invoke;  

import cn.hutool.http.HttpRequest;
import cn.hutool.http.HttpResponse;
import cn.hutool.json.JSONArray;
import cn.hutool.json.JSONObject;

/*
* 阿里云灵积 AI Http 调用
* */public class HttpAiInvoke {

public static void main(String[] args) {
// 替换为您的API密钥
String apiKey = TestApiKey.API_KEY;

// 构建请求URL
String url = "https://dashscope.aliyuncs.com/compatible-mode/v1/chat/completions";

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

// 构建messages数组
JSONArray messages = new JSONArray();

// system消息
JSONObject systemMessage = new JSONObject();
systemMessage.put("role", "system");
systemMessage.put("content", "You are a helpful assistant.");
messages.add(systemMessage);

// user消息
JSONObject userMessage = new JSONObject();
userMessage.put("role", "user");
userMessage.put("content", "你是谁?");
messages.add(userMessage);

requestBody.put("messages", messages);

try {
// 发送POST请求
HttpResponse response = HttpRequest.post(url)
.header("Authorization", "Bearer " + apiKey)
.header("Content-Type", "application/json")
.body(requestBody.toString())
.execute();

// 打印响应结果
System.out.println("响应状态码: " + response.getStatus());
System.out.println("响应内容: " + response.body());

} catch (Exception e) {
e.printStackTrace();
}
}
}

Spring A‌I

  • Spring AI 默认没有支持所有的大模型(尤其是国产的),更多的是支持兼容 OpenAI API 的大模型的集成

  • 理论上来说只要兼容 OpenAI API 的大模型都能在这里使用

  • 推荐直接使用阿里自主封装的 Spring AI Alibaba 框架,它不仅能直接继承阿里系大模型,用起来更方便,而且与标准的 Spring AI 保持兼容

  • 引入依赖:

    • 如果只是想使用 ChatClient 开发一个简单的单智能体或者聊天助手,则只需要加入 spring-ai-alibaba-starter-dashscope 依赖
    • 如果需要使用工作流或多智能体,则需要加入 spring-ai-alibaba-graph-core 依赖。
1
2
3
4
5
<dependency>
<groupId>com.alibaba.cloud.ai</groupId>
<artifactId>spring-ai-alibaba-starter</artifactId>
<version>1.0.0.2</version>
</dependency>
  • 编写配置
1
2
3
4
5
6
7
8
9
spring:
application:
name: spring-ai-alibaba-qwq-chat-client-example
ai:
dashscope:
api-key: ${AI_DASHSCOPE_API_KEY}
chat:
options:
model: qwen-plus
  • 运行代码
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
@Component  
public class SpringAiAiInvoke implements CommandLineRunner {

@Resource
private ChatModel chatModel;

@Override
public void run(String... args) throws Exception {
String text = chatModel.call(new Prompt("你好,我是呵帅"))
.getResult()
.getOutput()
.getText();
System.out.println(text);
}
}

评论