当前位置: 首页 > 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>

相关文章:

  • 使用kettle做的数据同步案例
  • C/C++ string模拟实现
  • MYSQL execute command denied to user ‘‘@‘%‘ for routine
  • 腾讯《地下城与勇士:起源》手游在部分安卓平台停止更新
  • 微信小程序-上拉加载和下拉刷新
  • C类IP介绍
  • 【Java数据结构】优先级队列详解(二)
  • centos环境上:k8s 简单安装教程
  • 《算法设计与分析》第五六章:回溯法与分支限界法
  • FreeRTOS学习笔记-基于stm32(11)任务通知及相关API函数简介
  • 12306 火车票价格解析 (PHP 解析)
  • 洛谷 P1008 [NOIP1998 普及组] 三连击
  • 被拷打已老实!面试官问我 #{} 和 ${} 的区别是什么?
  • 算法金 | 再见!!!梯度下降(多图)
  • 力扣469A
  • 07.Android之多媒体问题
  •  D - 粉碎叛乱F - 其他起义
  • Java 9 被无情抛弃,Java 8 直接升级到 Java 10!!
  • java2019面试题北京
  • java第三方包学习之lombok
  • PHP的类修饰符与访问修饰符
  • 彻底搞懂浏览器Event-loop
  • 和 || 运算
  • 机器学习中为什么要做归一化normalization
  • 前端性能优化--懒加载和预加载
  • 使用docker-compose进行多节点部署
  • 微信小程序实战练习(仿五洲到家微信版)
  • 我的面试准备过程--容器(更新中)
  • 小程序、APP Store 需要的 SSL 证书是个什么东西?
  • 一个完整Java Web项目背后的密码
  • 中文输入法与React文本输入框的问题与解决方案
  • postgresql行列转换函数
  • 如何在 Intellij IDEA 更高效地将应用部署到容器服务 Kubernetes ...
  • ​如何使用QGIS制作三维建筑
  • ​无人机石油管道巡检方案新亮点:灵活准确又高效
  • #C++ 智能指针 std::unique_ptr 、std::shared_ptr 和 std::weak_ptr
  • #git 撤消对文件的更改
  • (AngularJS)Angular 控制器之间通信初探
  • (done) NLP “bag-of-words“ 方法 (带有二元分类和多元分类两个例子)词袋模型、BoW
  • (vue)el-tabs选中最后一项后更新数据后无法展开
  • (含答案)C++笔试题你可以答对多少?
  • (回溯) LeetCode 40. 组合总和II
  • (微服务实战)预付卡平台支付交易系统卡充值业务流程设计
  • (转)一些感悟
  • (最新)华为 2024 届秋招-硬件技术工程师-单板硬件开发—机试题—(共12套)(每套四十题)
  • *2 echo、printf、mkdir命令的应用
  • .net 开发怎么实现前后端分离_前后端分离:分离式开发和一体式发布
  • .net 连接达梦数据库开发环境部署
  • .net 设置默认首页
  • .NET分布式缓存Memcached从入门到实战
  • ::前边啥也没有
  • [12] 使用 CUDA 进行图像处理
  • [AI]文心一言出圈的同时,NLP处理下的ChatGPT-4.5最新资讯
  • [C++核心编程](四):类和对象——封装
  • [CCF-CSP] 202303-4 星际网络II