java调用通义千问API

准备

1、API-KEY的获取与配置

前往API-KEY管理,可以点击创建后获取

2、开通DashScope

具体看文档

如何获取通义千问API的KEY_模型服务灵积(DashScope)-阿里云帮助中心 (aliyun.com)

开始

1、安装DashScope SDK

需要:已安装Java8及以上版本

导入依赖   【the-latest-version替换成最新版本,版本可以查看Maven

<!-- https://mvnrepository.com/artifact/com.alibaba/dashscope-sdk-java -->
<dependency>
    <groupId>com.alibaba</groupId>
    <artifactId>dashscope-sdk-java</artifactId>
    <version>the-latest-version</version>
</dependency>


<dependency>
    <groupId>com.squareup.okhttp3</groupId>
    <artifactId>okhttp</artifactId>
    <version>4.9.3</version>
</dependency>

2、编写接口

package org.mashang.aidemo.controller;

import com.alibaba.dashscope.aigc.generation.Generation;
import com.alibaba.dashscope.aigc.generation.GenerationResult;
import com.alibaba.dashscope.aigc.generation.models.QwenParam;
import com.alibaba.dashscope.common.Message;
import com.alibaba.dashscope.common.MessageManager;
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.Constants;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RestController;

@RestController
public class Test {

	@PostMapping("/ai")
	  public GenerationResult callWithMessage(String str)
	      throws NoApiKeyException, ApiException, InputRequiredException {
	    Generation gen = new Generation();
	    Constants.apiKey="sk-xxxxxxxxxxxxxxxxxxxxxxxxxx";//这里填写自己申请的APIKEY
	    MessageManager msgManager = new MessageManager(10);
	    Message systemMsg =
	        Message.builder().role(Role.SYSTEM.getValue()).content("You are a helpful assistant.").build();
	    Message userMsg = Message.builder().role(Role.USER.getValue()).content(str).build();//这里填写对话内容
	    msgManager.add(systemMsg);
	    msgManager.add(userMsg);
	    QwenParam param =
	        QwenParam.builder().model(Generation.Models.QWEN_TURBO).messages(msgManager.get())
	            .resultFormat(QwenParam.ResultFormat.MESSAGE)
	            .topP(0.8)
	            .enableSearch(true)
	            .build();
	    GenerationResult result = gen.call(param);
	    return result;
	  }

}

运行

发送:用postman测试

响应:

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值