当前位置: 首页 > news >正文

通义千问调用笔记

如何使用通义千问API_模型服务灵积(DashScope)-阿里云帮助中心

package com.ruoyi.webapp.utils;import com.alibaba.dashscope.aigc.generation.Generation;
import com.alibaba.dashscope.aigc.generation.GenerationOutput;
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.ResultCallback;
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;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;
import java.util.concurrent.Semaphore;/*** @author hrui* @date 2024/4/25 10:11*/
public class TYQWUtils {private static final Logger logger = LoggerFactory.getLogger(TYQWUtils.class);public static String callWithMessage(String userContent) throws ApiException, NoApiKeyException, InputRequiredException {Generation gen = new Generation(); // 这里假设Generation可以这样使用API密钥Message systemMsg = Message.builder().role(Role.SYSTEM.getValue()).content("You are a helpful assistant.").build();Message userMsg = Message.builder().role(Role.USER.getValue()).content(userContent).build();GenerationParam param = GenerationParam.builder().model("qwen-turbo").messages(Arrays.asList(systemMsg, userMsg)).resultFormat(GenerationParam.ResultFormat.MESSAGE).topP(0.8).build();GenerationResult result = gen.call(param);List<GenerationOutput.Choice> choices = result.getOutput().getChoices();String content = choices.get(0).getMessage().getContent();return content; // 或者根据实际需求格式化结果}public static void main(String[] args) {List<String> list=new ArrayList<>();}private static void handleGenerationResult(GenerationResult message, StringBuilder fullContent) {fullContent.append(message.getOutput().getChoices().get(0).getMessage().getContent());logger.info("Received message: {}", JsonUtils.toJson(message));}//以流的方式public static String streamCallWithCallback(Generation gen, Message userMsg)throws NoApiKeyException, ApiException, InputRequiredException, InterruptedException {GenerationParam param = buildGenerationParam(userMsg);Semaphore semaphore = new Semaphore(0);StringBuilder fullContent = new StringBuilder();gen.streamCall(param, new ResultCallback<GenerationResult>() {@Overridepublic void onEvent(GenerationResult message) {handleGenerationResult(message, fullContent);}@Overridepublic void onError(Exception err) {logger.error("Exception occurred: {}", err.getMessage());semaphore.release();}@Overridepublic void onComplete() {logger.info("Completed");semaphore.release();}});semaphore.acquire();return fullContent.toString();}private static GenerationParam buildGenerationParam(Message userMsg) {return GenerationParam.builder().model("qwen-turbo").messages(Arrays.asList(userMsg)).resultFormat(GenerationParam.ResultFormat.MESSAGE).topP(0.8).incrementalOutput(true).build();}}
@RestController
@RequestMapping("/app")
public class MessageGenerator extends BaseController {@Value("${api.key}")private String apiKey;final Generation gen = new Generation();@PostConstructpublic void test(){Constants.apiKey=apiKey;}//@PostMapping("/generatetext")
//    @GetMapping("/generatetext")
//    public AjaxResult generateResponse(@RequestParam String userContent) {
//        try {
//            //getLoginUser();
//            System.out.println("提问==================");
//            String str = "xxxx," + userContent + ",xxxx";
//            //String response = TYQWUtils.callWithMessage(str); // Adapt Main.callWithMessage method
//            String response = TYQWUtils.streamCallWithCallback(gen,Message.builder().role(Role.USER.getValue()).content(str).build());
//            System.out.println(response);
//            return success((Object)response);
//        } catch (ApiException | NoApiKeyException | InputRequiredException | InterruptedException e) {
//            //return ResponseEntity.internalServerError().body("An error occurred: " + e.getMessage());
//            return success((Object)"AI出了点小问题,请重新开始你的提问");
//        }
//    }private static void handleGenerationResult(GenerationResult message, StringBuilder fullContent) {fullContent.append(message.getOutput().getChoices().get(0).getMessage().getContent());System.out.println("Received message: " + JsonUtils.toJson(message));}// 以流的方式调用public static Flux<String> streamCallWithCallback(Generation gen, Message userMsg) throws NoApiKeyException, ApiException, InputRequiredException {GenerationParam param = buildGenerationParam(userMsg);StringBuilder fullContent = new StringBuilder();return Flux.create(sink -> {try {gen.streamCall(param, new ResultCallback<GenerationResult>() {@Overridepublic void onEvent(GenerationResult message) {handleGenerationResult(message, fullContent);sink.next(message.getOutput().getChoices().get(0).getMessage().getContent());}@Overridepublic void onError(Exception err) {System.err.println("Exception occurred: " + err.getMessage());sink.error(err);}@Overridepublic void onComplete() {System.out.println("Completed");sink.complete();}});} catch (NoApiKeyException e) {e.printStackTrace();} catch (InputRequiredException e) {e.printStackTrace();}});}private static GenerationParam buildGenerationParam(Message userMsg) {return GenerationParam.builder().model("qwen-turbo").messages(Arrays.asList(userMsg)).resultFormat(GenerationParam.ResultFormat.MESSAGE).topP(0.8).incrementalOutput(true).build();}@GetMapping(value = "/generatetext",produces = "text/html;charset=UTF-8")public Flux<String> generateResponse(@RequestParam String userContent) {try {getLoginUser();String str = "xxxx," + userContent + ",xxxx";return streamCallWithCallback(gen, Message.builder().role(Role.USER.getValue()).content(str).build());} catch (ApiException | NoApiKeyException | InputRequiredException e) {return Flux.just("AI出了点小问题,请重新开始你的提问");}}
}
<!--通义千问SDK--><!-- https://mvnrepository.com/artifact/com.alibaba/dashscope-sdk-java --><dependency><groupId>com.alibaba</groupId><artifactId>dashscope-sdk-java</artifactId><version>2.13.0</version></dependency>

http://www.lryc.cn/news/377082.html

相关文章:

  • Linux常见的压缩文件种类与对应的压缩解压方法
  • LNMP网站架构
  • 排序算法及源代码
  • 力扣第206题“反转链表”
  • 多模态大模型解读
  • React是什么?
  • 创新入门 | 病毒循环Viral Loop是什么?为何能实现指数增长
  • 鸿蒙HarmonyOS实战:渲染控制、路由案例
  • 【Linux】进程控制2——进程等待(waitwaitpid)
  • SpringBoot 统计接口调用耗时的多种方式
  • Linux系统安装Ruby语言
  • 网络安全练气篇——OWASP TOP 10
  • python实现进度条的方法和实现代码
  • 被拷打已老实!面试官问我 #{} 和 ${} 的区别是什么?
  • C# —— while循环语句
  • 力扣第205题“同构字符串”
  • 探索RESTful API开发,构建可扩展的Web服务
  • 苹果安卓网页的H5封装成App的应用和原生开发的应用有什么不一样?
  • IO流2.
  • 详解MySQL中的PERCENT_RANK函数
  • 宏任务与微任务
  • 昇思大模型学习·第一天
  • python调用chatgpt
  • YOLOV8 目标检测:训练自定义数据集
  • 动态更新自建的Redis连接池连接数量
  • 浅谈设计师的设计地位
  • C/C++ string模拟实现
  • 微信小程序学习(八):behaviors代码复用
  • 【The design pattern of Attribute-Based Dynamic Routing Pattern (ADRP)】
  • 2713. 矩阵中严格递增的单元格数