Spring Boot集成免费的阿里云通义千问API

概述

通义千问是阿里云提供的语言模型服务,它能够处理各种自然语言处理任务,如对话、问答、翻译等。本文将介绍如何在Spring Boot应用中集成通义千问API,并实现一个简单的聊天机器人功能。

前提条件

  • 已安装Java 11及以上版本。
  • 已安装Spring Boot 2.x 或更高版本。
  • 注册阿里云账号,并获取通义千问API的访问权限。

步骤

1. 创建Spring Boot项目

如果你还没有Spring Boot项目,可以通过Spring Initializr创建一个新的项目。这里我们使用一个简单的Web应用作为示例。

 

bash

深色版本

1# 在命令行中执行
2mvn archetype:generate -DgroupId=com.example -DartifactId=thousandquestions -DarchetypeArtifactId=maven-archetype-quickstart -DinteractiveMode=false
3cd thousandquestions
4mvn spring-boot:run

2. 添加依赖

我们需要添加HTTP客户端库(如OkHttp)来发起网络请求到通义千问API。这里我们选择使用okhttp3:okhttp库。

pom.xml文件中添加以下依赖:

 

xml

深色版本

1<dependencies>
2    <!-- 其他依赖 -->
3    <dependency>
4        <groupId>com.squareup.okhttp3</groupId>
5        <artifactId>okhttp</artifactId>
6        <version>4.10.0</version>
7    </dependency>
8</dependencies>

3. 获取API密钥

前往阿里云官网,注册并登录账号,然后进入通义千问页面获取你的API Key和Secret Key。

4. 编写代码

创建一个名为ThousandQuestionsClient的服务类,用于封装与通义千问API的交互逻辑。

 

java

深色版本

1import okhttp3.OkHttpClient;
2import okhttp3.Request;
3import okhttp3.Response;
4
5import java.io.IOException;
6
7public class ThousandQuestionsClient {
8
9    private final OkHttpClient client = new OkHttpClient();
10    private final String apiKey;
11    private final String secretKey;
12
13    public ThousandQuestionsClient(String apiKey, String secretKey) {
14        this.apiKey = apiKey;
15        this.secretKey = secretKey;
16    }
17
18    public String getAnswer(String question) throws IOException {
19        // 构建请求URL
20        String url = "https://api.qianwen.aliyun.com/v1/chat/completions";
21
22        // 构建请求头
23        Request.Builder requestBuilder = new Request.Builder()
24                .addHeader("Content-Type", "application/json")
25                .addHeader("Authorization", "Bearer " + apiKey);
26
27        // 构建请求体
28        String requestBody = "{\"model\":\"qwen\",\"messages\":[{\"role\":\"user\",\"content\":\"" + question + "\"}],\"stream\":false}";
29
30        // 发送POST请求
31        Request request = requestBuilder.url(url).post(okhttp3.RequestBody.create(requestBody, okhttp3.MediaType.get("application/json; charset=utf-8"))).build();
32
33        try (Response response = client.newCall(request).execute()) {
34            if (!response.isSuccessful()) throw new IOException("Unexpected code " + response);
35            return response.body().string();
36        }
37    }
38}

5. 控制器

创建一个控制器类来接收前端的请求,并调用ThousandQuestionsClient获取答案。

 

java

深色版本

1import org.springframework.web.bind.annotation.GetMapping;
2import org.springframework.web.bind.annotation.RequestParam;
3import org.springframework.web.bind.annotation.RestController;
4
5@RestController
6public class QuestionController {
7
8    private final ThousandQuestionsClient client;
9
10    public QuestionController(ThousandQuestionsClient client) {
11        this.client = client;
12    }
13
14    @GetMapping("/answer")
15    public String getAnswer(@RequestParam String question) throws IOException {
16        return client.getAnswer(question);
17    }
18}

6. 配置文件

application.properties中配置API密钥。

 

properties

深色版本

1thousand.questions.api.key=your_api_key_here
2thousand.questions.secret.key=your_secret_key_here

7. 启动类

在启动类中注入密钥,并实例化ThousandQuestionsClient

 

java

深色版本

1import org.springframework.beans.factory.annotation.Value;
2import org.springframework.boot.SpringApplication;
3import org.springframework.boot.autoconfigure.SpringBootApplication;
4import org.springframework.context.annotation.Bean;
5
6@SpringBootApplication
7public class ThousandQuestionsApplication {
8
9    @Value("${thousand.questions.api.key}")
10    private String apiKey;
11
12    @Value("${thousand.questions.secret.key}")
13    private String secretKey;
14
15    public static void main(String[] args) {
16        SpringApplication.run(ThousandQuestionsApplication.class, args);
17    }
18
19    @Bean
20    public ThousandQuestionsClient thousandQuestionsClient() {
21        return new ThousandQuestionsClient(apiKey, secretKey);
22    }
23}

8. 测试

运行Spring Boot应用,并通过浏览器或Postman发送请求。

 

bash

深色版本

1http://localhost:8080/answer?question=你好吗?

结论

以上步骤展示了如何在Spring Boot应用中集成通义千问API来实现一个简单的聊天机器人功能。通过这种方式,你可以轻松地为你的应用增加自然语言处理的能力。

  • 3
    点赞
  • 3
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值