通义千问调用笔记
如何使用通义千问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>
相关文章:
![](https://img-blog.csdnimg.cn/direct/db58c7d5a0994b759de3046ecfb1f432.png)
通义千问调用笔记
如何使用通义千问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…...
![](https://www.ngui.cc/images/no-images.jpg)
Linux常见的压缩文件种类与对应的压缩解压方法
天行健,君子以自强不息;地势坤,君子以厚德载物。 每个人都有惰性,但不断学习是好好生活的根本,共勉! 文章均为学习整理笔记,分享记录为主,如有错误请指正,共同学习进步。…...
![](https://www.ngui.cc/images/no-images.jpg)
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、编译安装…...
![](https://img-blog.csdnimg.cn/direct/b7b46b13ae24462c831ee05b8107b5de.png)
排序算法及源代码
堆排序: 在学习堆之后我们知道了大堆和小堆,对于大堆而言第一个节点就是对大值,对于小堆而言,第一个值就是最小的值。如果我们把第一个值与最后一个值交换再对最后一个值前面的数据重新建堆,如此下去就可以实现建堆排…...
![](https://www.ngui.cc/images/no-images.jpg)
力扣第206题“反转链表”
在本篇文章中,我们将详细解读力扣第206题“反转链表”。通过学习本篇文章,读者将掌握如何使用迭代和递归的方法来解决这一问题,并了解相关的复杂度分析和模拟面试问答。每种方法都将配以详细的解释,以便于理解。 问题描述 力扣第…...
![](https://img-blog.csdnimg.cn/img_convert/8d13297e8bb8874a9d02dfd8535ec0a3.png)
多模态大模型解读
目录 1. CLIP 2. ALBEF 3. BLIP 4. BLIP2 参考文献 (2023年)视觉语言的多模态大模型的目前主流方法是:借助预训练好的LLM和图像编码器,用一个图文特征对齐模块来连接,从而让语言模型理解图像特征并进行深层次的问…...
![](https://www.ngui.cc/images/no-images.jpg)
React是什么?
theme: condensed-night-purple highlight: atelier-cave-light React是什么? 官方的解释是:A JavaScript library for building user interfaces用于构建用户界面的 JavaScript 库 那为什么要选择用React呢? 原生的HTML、CSS、JavaScrip的…...
![](https://img-blog.csdnimg.cn/img_convert/7cdbc92b0f929770a40d9f449c3384ff.png)
创新入门 | 病毒循环Viral Loop是什么?为何能实现指数增长
今天,很多高速增长的成功创业公司都在采用”病毒循环“的策略去快速传播、并扩大用户基础。究竟什么是“病毒循环”?初创公司的创始人为何需要重视这个策略?这篇文章中将会一一解答与病毒循环有关的各种问题。 一、什么是病毒循环(…...
![](https://img-blog.csdnimg.cn/direct/8939d548a4e14cf79861d11af83ee11b.png)
鸿蒙HarmonyOS实战:渲染控制、路由案例
条件渲染 简单来说,就是动态控制组件的显示与隐藏,类似于vue中的v-if 但是这里写法就是用if、else、else if看起来更像是原生的感觉 效果 循环渲染 我们实际开发中,数据一般是后端返回来的对象格式,对此我们需要进行遍历&#…...
![](https://img-blog.csdnimg.cn/direct/11b135cffe144cdf8ad4c6a84da369b2.png)
【Linux】进程控制2——进程等待(waitwaitpid)
1. 进程等待必要性 我们知道,子进程退出,父进程如果不管不顾,就可能造成"僵尸进程”的问题,进而造成内存泄漏。另外,进程一旦变成僵尸状态,那就刀枪不入,“杀人不眨眼”的kill -9 也无能为…...
![](https://www.ngui.cc/images/no-images.jpg)
SpringBoot 统计接口调用耗时的多种方式
在实际开发中,了解项目中接口的响应时间是必不可少的事情。SpringBoot 项目支持监听接口的功能也不止一个,接下来我们分别以 AOP、ApplicationListener、Tomcat 三个方面去实现三种不同的监听接口响应时间的操作。 AOP 首先我们在项目中创建一个类 &am…...
![](https://img-blog.csdnimg.cn/direct/a1d81ef526374ebab7809969911eebf2.png)
Linux系统安装Ruby语言
Ruby是一种面向对象的脚本语言,由日本的计算机科学家松本行弘设计并开发,Ruby的设计哲学强调程序员的幸福感,致力于简化编程的复杂性,并提供一种既强大又易于使用的工具。其语法简洁优雅,易于阅读和书写,使…...
![](https://www.ngui.cc/images/no-images.jpg)
网络安全练气篇——OWASP TOP 10
1、什么是OWASP? OWASP(开放式Web应用程序安全项目)是一个开放的社区,由非营利组织 OWASP基金会支持的项目。对所有致力于改进应用程序安全的人士开放,旨在提高对应用程序安全性的认识。 其最具权威的就是“10项最严重…...
![](https://www.ngui.cc/images/no-images.jpg)
python实现进度条的方法和实现代码
在Python中,有多种方式可以实现进度条。这里,我将介绍七种常见的方法:使用tqdm(这是一个外部库,非常流行且易于使用)、rich、click、progressbar2等库以及纯Python的print函数与time库来模拟进度条。 目录…...
![](https://img-blog.csdnimg.cn/img_convert/3cc40243128afed46b97485301da9405.png)
被拷打已老实!面试官问我 #{} 和 ${} 的区别是什么?
引言:在使用 MyBatis 进行数据库操作时,#{} 和 ${} 的区别是面试中常见的问题,对理解如何在 MyBatis 中安全有效地处理 SQL 语句至关重要。正确使用这两种占位符不仅影响应用的安全性,还涉及到性能优化。 题目 被拷打已老实&…...
![](https://www.ngui.cc/images/no-images.jpg)
C# —— while循环语句
作用 让顺序执行的代码 可以停下来 循环执行某一代码块 // 条件分支语句: 让代码产生分支 进行执行 // 循环语句 : 让代码可以重复执行 语法 while循环 while (bool值) { 循环体(条件满足时执行的代码块) …...
![](https://www.ngui.cc/images/no-images.jpg)
力扣第205题“同构字符串”
在本篇文章中,我们将详细解读力扣第205题“同构字符串”。通过学习本篇文章,读者将掌握如何使用哈希表来解决这一问题,并了解相关的复杂度分析和模拟面试问答。每种方法都将配以详细的解释,以便于理解。 问题描述 力扣第205题“…...
![](https://www.ngui.cc/images/no-images.jpg)
探索RESTful API开发,构建可扩展的Web服务
介绍 当我们浏览网页、使用手机应用或与各种互联网服务交互时,我们经常听到一个术语:“RESTful API”。它听起来很高深,但实际上,它是构建现代网络应用程序所不可或缺的基础。 什么是RESTful API? 让我们将RESTful …...
![](https://www.ngui.cc/images/no-images.jpg)
苹果安卓网页的H5封装成App的应用和原生开发的应用有什么不一样?
H5封装类成App的应用和原生应用有什么不一样?——一对比谈优缺点 1. 开发速度和复用性 H5封装的App优势:一次编写,多平台运行。你只需要使用一种语言编写代码,就可以发布到不同的平台,降低开发成本。 原生应用优势&…...
![](https://img-blog.csdnimg.cn/direct/6c21d0d12ff847a295045c7fd9884632.png)
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…...
![](https://img-blog.csdnimg.cn/img_convert/d7d17ac7c5a51d445b96467555d18e86.png)
详解MySQL中的PERCENT_RANK函数
目录 1. 引入1. 基本使用2:分组使用3:处理重复值4. 使用优势4.1 手动计算百分等级4.2 使用 PERCENT_RANK 的优势4.3 使用 PERCENT_RANK 5. 总结 在 MySQL 中,PERCENT_RANK 函数用于计算一个值在其分组中的百分等级。 它的返回值范围是从 0 …...
![](https://www.ngui.cc/images/no-images.jpg)
宏任务与微任务
一、宏任务 1、概念 指消息队列中等地被主线程执行的事件 2、种类 script主代码块、setTimeout 、setInterval 、nodejs的setImmediate 、MessageChannel(react的fiber用到)、postMessage、网络I/O、文件I/O、用户交互的回调等事件、UI渲染事件&#x…...
![](https://img-blog.csdnimg.cn/direct/675a9a89743f47e3953f4e87fecabd3c.png)
昇思大模型学习·第一天
mindspore快速入门回顾 导入mindspore包 处理数据集 下载mnist数据集进行数据集预处理 MnistDataset()方法train_dataset.get_col_names() 打印列名信息使用create_tuple_iterator 或create_dict_iterator对数据集进行迭代访问 网络构建 mindspore.nn: 构建所有网络的基类用…...
![](https://www.ngui.cc/images/no-images.jpg)
python调用chatgpt
简单写了一下关于文本生成接口的调用,其余更多的调用方法可在官网查看 import os from dotenv import load_dotenv, find_dotenv from openai import OpenAI import httpxdef gpt_config():# 为了安全起见,将key写到当前项目根目录下的.env文件中# find…...
![](https://csdnimg.cn/release/blog_editor_html/release2.3.6/ckeditor/plugins/CsdnLink/icons/icon-default.png?t=N7T8)
YOLOV8 目标检测:训练自定义数据集
1、下载 yolov8项目:ultralytics/ultralytics:新增 - PyTorch 中的 YOLOv8 🚀 > ONNX > OpenVINO > CoreML > TFLite --- ultralytics/ultralytics: NEW - YOLOv8 🚀 in PyTorch > ONNX > OpenVINO > CoreM…...
![](https://www.ngui.cc/images/no-images.jpg)
动态更新自建的Redis连接池连接数量
/*** 定时更新Redis连接池信息,防止资源让费*/private static final ScheduledThreadPoolExecutor DYNAMICALLY_UPDATE_REDIS_POOL_THREAD new ScheduledThreadPoolExecutor(1, new ThreadFactory() {Overridepublic Thread newThread(Runnable r) {Thread thread …...
![](https://img-blog.csdnimg.cn/img_convert/aee397b06ba36642473154c62e149bf1.jpeg)
浅谈设计师的设计地位
在当今这个创意无限的时代,设计师的地位日益凸显。他们以独特的视角和精湛的技能,为我们的生活带来了无尽的色彩与灵感。然而,随着行业的不断发展,设计师如何在众多同行中脱颖而出,提升自己的设计地位呢?答…...
![](https://img-blog.csdnimg.cn/direct/5dc90995f188426fbf10e52186e26390.png)
C/C++ string模拟实现
1.模拟准备 1.1因为是模拟string,防止与库发生冲突,所以需要命名空间namespace隔离一下,我们来看一下基本内容 namespace yx {class string{private://char _buff[16]; lunix下小于16字节就存buff里char* _str;size_t _size;size_t _capac…...
![](https://www.ngui.cc/images/no-images.jpg)
微信小程序学习(八):behaviors代码复用
小程序的 behaviors 方法是一种代码复用的方式,可以将一些通用的逻辑和方法提取出来,然后在多个组件中复用,从而减少代码冗余,提高代码的可维护性。 如果需要 behavior 复用代码,需要使用 Behavior() 方法,…...
![](https://www.ngui.cc/images/no-images.jpg)
【The design pattern of Attribute-Based Dynamic Routing Pattern (ADRP)】
In ASP.NET Core, routing is one of the core functionalities that maps HTTP requests to the corresponding controller actions. While “Route-Driven Design Pattern” is a coined name for a design pattern, we can construct a routing-centric design pattern base…...
![](/images/no-images.jpg)
基层建设收录网站/seo运营推广
信息安全相关证书 1、CISP-PTE(国家注册渗透测试工程师) PTE属于渗透测试方向的专项考试,是国内首个渗透测试领域权威认证,属于特定领域,深度发展,从事的工作属于安全服务方面 。政府背景给认证做背书,想在政府、国企及…...
![](/images/no-images.jpg)
职业教育网站建设可行性报告/关键词筛选工具
在最上面的导航栏,点击“项目”—>“属性”—>“配置属性”—>“链接器”—>“系统”—>“子系统(在窗口右边有一个下拉图标)”—>下拉框选择“控制台(/SUBSYSTEM:CONSOLE)”—>最后“确定”—>点击右上角"文件…...
![](https://img-blog.csdnimg.cn/img_convert/77d35851fed7f10a7480cd7c4c64d3cb.png)
网站死链接怎么删除/搜狗站长工具
从Unity 2018.3(TextMeshPro1.4)起,添加了Font Fallback和Dynamic SDF System以实现灵活的SDF使用。有了这个新功能后,我们可以实现以下用法:预先为中文字中经常使用的字符生成普通SDF根据需要追加取得使用频率低的文字…...
![](/images/no-images.jpg)
团结湖网站建设/南京seo整站优化技术
静态绑定和动态绑定是C多态性的一种特性。 1、对象的静态类型和动态类型: 对象的静态类型:对象在声明是采用的类型,在编译期确定; 对象的动态类型:当前对象所指的类型,在运行期决定,对象的动态类…...
![](https://img-blog.csdnimg.cn/20210602194554463.jpg?x-oss-process=image/watermark,type_ZmFuZ3poZW5naGVpdGk,shadow_10,text_aHR0cHM6Ly9ibG9nLmNzZG4ubmV0L3FxXzM5ODA1MzYy,size_16,color_FFFFFF,t_70)
做外贸现在一般都通过哪些网站/网络营销方法
最近看完了空间计量经济学的理论部分,因此打算开始学习一下实战,实战所使用的主要是GEODA家族的软件包们,首先还是打算先学习python的pysal包,毕竟还是更喜欢代码,而且相较于GEODA和GEODASPACE,写代码还是会…...
![](/images/no-images.jpg)
linux主机 安装wordpress/深圳网络营销策划公司
同步自:http://www.blogjava.net/AndersLin/archive/2006/06/27/55421.html 上次发了一文《软件企业的绩效管理和内部消耗》讨论很多,"置身珠海,学习与奋斗"cnBlogs让我认识其实我说了那么多都只是绩效的保健性&…...