通义千问调用笔记

如何使用通义千问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>
相关文章:
通义千问调用笔记
如何使用通义千问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.G…...
Linux常见的压缩文件种类与对应的压缩解压方法
天行健,君子以自强不息;地势坤,君子以厚德载物。 每个人都有惰性,但不断学习是好好生活的根本,共勉! 文章均为学习整理笔记,分享记录为主,如有错误请指正,共同学习进步。…...
LNMP网站架构
一、安装nginx服务 1、关闭防火墙和核心防护 systemctl stop firewalld systemctl disable firewalld setenforce 0 2、安装依赖包 yum -y install pcre-devel zlib-devel openssl-devel gcc gcc-c make 3、创建运行用户 useradd -M -s /sbin/nologin nginx 4、编译安装…...
排序算法及源代码
堆排序: 在学习堆之后我们知道了大堆和小堆,对于大堆而言第一个节点就是对大值,对于小堆而言,第一个值就是最小的值。如果我们把第一个值与最后一个值交换再对最后一个值前面的数据重新建堆,如此下去就可以实现建堆排…...
力扣第206题“反转链表”
在本篇文章中,我们将详细解读力扣第206题“反转链表”。通过学习本篇文章,读者将掌握如何使用迭代和递归的方法来解决这一问题,并了解相关的复杂度分析和模拟面试问答。每种方法都将配以详细的解释,以便于理解。 问题描述 力扣第…...
多模态大模型解读
目录 1. CLIP 2. ALBEF 3. BLIP 4. BLIP2 参考文献 (2023年)视觉语言的多模态大模型的目前主流方法是:借助预训练好的LLM和图像编码器,用一个图文特征对齐模块来连接,从而让语言模型理解图像特征并进行深层次的问…...
React是什么?
theme: condensed-night-purple highlight: atelier-cave-light React是什么? 官方的解释是:A JavaScript library for building user interfaces用于构建用户界面的 JavaScript 库 那为什么要选择用React呢? 原生的HTML、CSS、JavaScrip的…...
创新入门 | 病毒循环Viral Loop是什么?为何能实现指数增长
今天,很多高速增长的成功创业公司都在采用”病毒循环“的策略去快速传播、并扩大用户基础。究竟什么是“病毒循环”?初创公司的创始人为何需要重视这个策略?这篇文章中将会一一解答与病毒循环有关的各种问题。 一、什么是病毒循环(…...
鸿蒙HarmonyOS实战:渲染控制、路由案例
条件渲染 简单来说,就是动态控制组件的显示与隐藏,类似于vue中的v-if 但是这里写法就是用if、else、else if看起来更像是原生的感觉 效果 循环渲染 我们实际开发中,数据一般是后端返回来的对象格式,对此我们需要进行遍历&#…...
【Linux】进程控制2——进程等待(waitwaitpid)
1. 进程等待必要性 我们知道,子进程退出,父进程如果不管不顾,就可能造成"僵尸进程”的问题,进而造成内存泄漏。另外,进程一旦变成僵尸状态,那就刀枪不入,“杀人不眨眼”的kill -9 也无能为…...
SpringBoot 统计接口调用耗时的多种方式
在实际开发中,了解项目中接口的响应时间是必不可少的事情。SpringBoot 项目支持监听接口的功能也不止一个,接下来我们分别以 AOP、ApplicationListener、Tomcat 三个方面去实现三种不同的监听接口响应时间的操作。 AOP 首先我们在项目中创建一个类 &am…...
Linux系统安装Ruby语言
Ruby是一种面向对象的脚本语言,由日本的计算机科学家松本行弘设计并开发,Ruby的设计哲学强调程序员的幸福感,致力于简化编程的复杂性,并提供一种既强大又易于使用的工具。其语法简洁优雅,易于阅读和书写,使…...
网络安全练气篇——OWASP TOP 10
1、什么是OWASP? OWASP(开放式Web应用程序安全项目)是一个开放的社区,由非营利组织 OWASP基金会支持的项目。对所有致力于改进应用程序安全的人士开放,旨在提高对应用程序安全性的认识。 其最具权威的就是“10项最严重…...
python实现进度条的方法和实现代码
在Python中,有多种方式可以实现进度条。这里,我将介绍七种常见的方法:使用tqdm(这是一个外部库,非常流行且易于使用)、rich、click、progressbar2等库以及纯Python的print函数与time库来模拟进度条。 目录…...
被拷打已老实!面试官问我 #{} 和 ${} 的区别是什么?
引言:在使用 MyBatis 进行数据库操作时,#{} 和 ${} 的区别是面试中常见的问题,对理解如何在 MyBatis 中安全有效地处理 SQL 语句至关重要。正确使用这两种占位符不仅影响应用的安全性,还涉及到性能优化。 题目 被拷打已老实&…...
C# —— while循环语句
作用 让顺序执行的代码 可以停下来 循环执行某一代码块 // 条件分支语句: 让代码产生分支 进行执行 // 循环语句 : 让代码可以重复执行 语法 while循环 while (bool值) { 循环体(条件满足时执行的代码块) …...
力扣第205题“同构字符串”
在本篇文章中,我们将详细解读力扣第205题“同构字符串”。通过学习本篇文章,读者将掌握如何使用哈希表来解决这一问题,并了解相关的复杂度分析和模拟面试问答。每种方法都将配以详细的解释,以便于理解。 问题描述 力扣第205题“…...
探索RESTful API开发,构建可扩展的Web服务
介绍 当我们浏览网页、使用手机应用或与各种互联网服务交互时,我们经常听到一个术语:“RESTful API”。它听起来很高深,但实际上,它是构建现代网络应用程序所不可或缺的基础。 什么是RESTful API? 让我们将RESTful …...
苹果安卓网页的H5封装成App的应用和原生开发的应用有什么不一样?
H5封装类成App的应用和原生应用有什么不一样?——一对比谈优缺点 1. 开发速度和复用性 H5封装的App优势:一次编写,多平台运行。你只需要使用一种语言编写代码,就可以发布到不同的平台,降低开发成本。 原生应用优势&…...
IO流2.
字符流-->字符流的底层其实就是字节流 public class Stream {public static void main(String[] args) throws IOException {//1.创建对象并关联本地文件FileReader frnew FileReader("abc\\a.txt");//2.读取资源read()int ch;while((chfr.read())!-1){System.out…...
谷歌浏览器插件
项目中有时候会用到插件 sync-cookie-extension1.0.0:开发环境同步测试 cookie 至 localhost,便于本地请求服务携带 cookie 参考地址:https://juejin.cn/post/7139354571712757767 里面有源码下载下来,加在到扩展即可使用FeHelp…...
【kafka】Golang实现分布式Masscan任务调度系统
要求: 输出两个程序,一个命令行程序(命令行参数用flag)和一个服务端程序。 命令行程序支持通过命令行参数配置下发IP或IP段、端口、扫描带宽,然后将消息推送到kafka里面。 服务端程序: 从kafka消费者接收…...
基于FPGA的PID算法学习———实现PID比例控制算法
基于FPGA的PID算法学习 前言一、PID算法分析二、PID仿真分析1. PID代码2.PI代码3.P代码4.顶层5.测试文件6.仿真波形 总结 前言 学习内容:参考网站: PID算法控制 PID即:Proportional(比例)、Integral(积分&…...
PPT|230页| 制造集团企业供应链端到端的数字化解决方案:从需求到结算的全链路业务闭环构建
制造业采购供应链管理是企业运营的核心环节,供应链协同管理在供应链上下游企业之间建立紧密的合作关系,通过信息共享、资源整合、业务协同等方式,实现供应链的全面管理和优化,提高供应链的效率和透明度,降低供应链的成…...
渗透实战PortSwigger靶场-XSS Lab 14:大多数标签和属性被阻止
<script>标签被拦截 我们需要把全部可用的 tag 和 event 进行暴力破解 XSS cheat sheet: https://portswigger.net/web-security/cross-site-scripting/cheat-sheet 通过爆破发现body可以用 再把全部 events 放进去爆破 这些 event 全部可用 <body onres…...
pam_env.so模块配置解析
在PAM(Pluggable Authentication Modules)配置中, /etc/pam.d/su 文件相关配置含义如下: 配置解析 auth required pam_env.so1. 字段分解 字段值说明模块类型auth认证类模块,负责验证用户身份&am…...
JDK 17 新特性
#JDK 17 新特性 /**************** 文本块 *****************/ python/scala中早就支持,不稀奇 String json “”" { “name”: “Java”, “version”: 17 } “”"; /**************** Switch 语句 -> 表达式 *****************/ 挺好的ÿ…...
Unity | AmplifyShaderEditor插件基础(第七集:平面波动shader)
目录 一、👋🏻前言 二、😈sinx波动的基本原理 三、😈波动起来 1.sinx节点介绍 2.vertexPosition 3.集成Vector3 a.节点Append b.连起来 4.波动起来 a.波动的原理 b.时间节点 c.sinx的处理 四、🌊波动优化…...
微软PowerBI考试 PL300-在 Power BI 中清理、转换和加载数据
微软PowerBI考试 PL300-在 Power BI 中清理、转换和加载数据 Power Query 具有大量专门帮助您清理和准备数据以供分析的功能。 您将了解如何简化复杂模型、更改数据类型、重命名对象和透视数据。 您还将了解如何分析列,以便知晓哪些列包含有价值的数据,…...
10-Oracle 23 ai Vector Search 概述和参数
一、Oracle AI Vector Search 概述 企业和个人都在尝试各种AI,使用客户端或是内部自己搭建集成大模型的终端,加速与大型语言模型(LLM)的结合,同时使用检索增强生成(Retrieval Augmented Generation &#…...
