0


Java+SpringBoot调用通义千问的大语言模型的API及前端Vue实现联调

image.png上图中可以明显看见通义千问除了有大语言模型,还有通义千问VL通义千问Audio。因此注意,本文只是针对于通义千问的大语言模型。至于以上两个是做什么的,可自行查看官网。

阿里云官网提供两种提供的快速入门的方法案例:(改进)

在pom.xml文件种导入DashScope SDK的坐标
<!--        通义千问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><exclusions><exclusion><groupId>org.slf4j</groupId><artifactId>slf4j-simple</artifactId></exclusion></exclusions></dependency><dependency><groupId>com.squareup.okhttp3</groupId><artifactId>okhttp</artifactId><version>4.10.0</version></dependency>

通过messages调用(推荐)

编写Controller层
packagecom.he.cms.blog.controller;importcom.alibaba.dashscope.aigc.generation.GenerationResult;importcom.alibaba.dashscope.exception.InputRequiredException;importcom.alibaba.dashscope.exception.NoApiKeyException;importcom.he.cms.blog.service.IBlogAiSGenerateService;importio.swagger.annotations.Api;importio.swagger.annotations.ApiOperation;importlombok.extern.slf4j.Slf4j;importorg.springframework.beans.factory.annotation.Autowired;importorg.springframework.web.bind.annotation.PathVariable;importorg.springframework.web.bind.annotation.RequestMapping;importorg.springframework.web.bind.annotation.RestController;/**
 * @ClassName BlogAiGenerateController
 * @Author Hym
 * @Date 2024/4/13 23:01
 */@Slf4j@RestController//好好学习,走向巅峰!@Api(tags ="博客生成")publicclassBlogAiGenerateController{@AutowiredprivateIBlogAiSGenerateService blogAiSGenerateService;/**
     * 生成博客
     */@RequestMapping("/generateArticle/{content}")@ApiOperation(value ="生成博客", notes ="生成博客"+"调用方式:"+"生成博客"+"传入参数:"+"content")publicGenerationResultgenerateArticle(@PathVariableString content)throwsNoApiKeyException,InputRequiredException{GenerationResult generationResult =blogAiSGenerateService.BlogAiSGenerate(content);
        log.info(generationResult.toString());return generationResult;}}
2.3 Servic层及实现类

接口

packagecom.he.cms.blog.service;importcom.alibaba.dashscope.aigc.generation.GenerationResult;importcom.alibaba.dashscope.exception.InputRequiredException;importcom.alibaba.dashscope.exception.NoApiKeyException;publicinterfaceIBlogAiSGenerateService{/**
 * 生成博客
 *
 * @param title   标题
 * @param content 内容
 * @return 结果
 */GenerationResultBlogAiSGenerate(String content)throwsNoApiKeyException,InputRequiredException;}

实现类

packagecom.he.cms.blog.service.impl;importcom.alibaba.dashscope.aigc.generation.GenerationResult;importcom.alibaba.dashscope.exception.InputRequiredException;importcom.alibaba.dashscope.exception.NoApiKeyException;importcom.he.cms.blog.service.ICmsBlogAiSGenerateService;importcom.he.cms.utils.CmsBlogQianWenGenerateUtils;importorg.springframework.stereotype.Service;importjavax.annotation.Resource;/**
 * @ClassName BlogAiSGenerateServiceImpl
 * @Author Hym
 * @Date 2024/4/13 23:06
 */@Service//好好学习,走向巅峰!publicclassCmsBlogAiSGenerateServiceImplimplementsICmsBlogAiSGenerateService{@ResourceprivateCmsBlogQianWenGenerateUtils cmsBlogQianWenGenerateUtils;@OverridepublicGenerationResultBlogAiSGenerate(String content)throwsNoApiKeyException,InputRequiredException{return  cmsBlogQianWenGenerateUtils.callWithMessage(content);}//    public static void main(String[] args) {//        CmsBlogAiSGenerateServiceImpl blogAiSGenerateService = new CmsBlogAiSGenerateServiceImpl();//        try {//            System.out.println(blogAiSGenerateService.BlogAiSGenerate("给我写一篇java的文章").toString());//        } catch (NoApiKeyException e) {//            e.printStackTrace();//        } catch (InputRequiredException e) {//            e.printStackTrace();//        }//    }}
调用通义千问API的组件

image.png

packagecom.he.cms.utils;importcom.alibaba.dashscope.aigc.generation.Generation;importcom.alibaba.dashscope.aigc.generation.GenerationResult;importcom.alibaba.dashscope.aigc.generation.models.QwenParam;importcom.alibaba.dashscope.common.Message;importcom.alibaba.dashscope.common.MessageManager;importcom.alibaba.dashscope.common.Role;importcom.alibaba.dashscope.exception.ApiException;importcom.alibaba.dashscope.exception.InputRequiredException;importcom.alibaba.dashscope.exception.NoApiKeyException;importcom.alibaba.dashscope.utils.Constants;importio.swagger.annotations.ApiOperation;importlombok.extern.slf4j.Slf4j;importorg.springframework.beans.factory.annotation.Value;importorg.springframework.stereotype.Component;/**
 * @ClassName BlogQianWenGenerateUtils
 * @Author Hym
 * @Date 2024/4/13 23:13
 *///好好学习,走向巅峰!@Slf4j@ComponentpublicclassCmsBlogQianWenGenerateUtils{@Value("${tong_yi_cloud.ai_api_Key}")privateString qianWenKeyApiKey;@ApiOperation("千问生成文章"+"调用方式:"+"千问生成文章"+"传入参数:"+"content")publicGenerationResultcallWithMessage(String content)throwsNoApiKeyException,ApiException,InputRequiredException{Constants.apiKey=qianWenKeyApiKey;Generation gen =newGeneration();MessageManager msgManager =newMessageManager(10);Message systemMsg =Message.builder().role(Role.SYSTEM.getValue()).content("你是一个写文章的大师").build();Message userMsg =Message.builder().role(Role.USER.getValue()).content(content).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);
        log.info("千问api回答的话语为:{}",result);return result;}}
返回结果
{"requestId":"358d15cd-c01c-9052-aa8f-c20232a50148","usage":{"inputTokens":25,"outputTokens":400,"totalTokens":425},"output":{"text":null,"finishReason":null,"choices":[{"finishReason":"stop","index":null,"message":{"role":"assistant","content":"标题:职场探索:打造个人品牌,成功求职之道\n\n在人生的道路上,找工作如同开启一段新的旅程,充满期待与挑战。在这个竞争激烈的市场中,找到理想的工作不仅需要实力的展现,更需要策略和技巧的巧妙运用。以下是一些关键步骤和建议,助你在求职之路上走得更稳健。\n\n首先,自我认知是基石。明确你的职业目标和兴趣,了解自己的优势与劣势,这将帮助你定位理想的职位。一份精心撰写的简历和个性化的求职信,能精准地传达你的专业技能和独特价值,让招聘者一眼看出你的潜力。\n\n其次,提升自我。不断学习和积累经验是提升竞争力的关键。无论是专业技能的精进,还是软技能的培养,如团队合作、沟通能力等,都能让你在众多应聘者中脱颖而出。参加行业研讨会、实习项目或者志愿者活动,都是拓宽视野和积累实战经验的好方法。\n\n网络的力量不容忽视。利用社交媒体平台如LinkedIn建立专业形象,定期更新你的职业动态和成就,不仅能吸引潜在雇主的注意,也能扩大你的人脉圈。同时,关注行业内的招聘信息,积极投递并参与线上面试,可以提高你的曝光率。\n\n面试时,充分准备至关重要。研究公司的文化和价值观,理解他们对岗位的期望,用实例说明你是如何满足这些要求的。展示你的热情、诚实和解决问题的能力,让面试官看到你的诚意和决心。\n\n最后,保持耐心和积极态度。找工作并非一蹴而就,可能会经历挫折,但请记住,每一次的拒绝都是向成功的一步。保持开放的心态,持续学习,不断提升自己,总有一天,机会会降临到有准备的你身上。\n\n总的来说,寻找工作是一个全方位的策略性过程,需要你的智慧、努力和时间。相信自己,坚持下去,你一定能在职场上找到属于你的那片天空。祝你好运,职场之路越走越宽广!","toolCalls":null,"toolCallId":null}}]}}

通过prompt调用

改良版本

packagetest;// Copyright (c) Alibaba, Inc. and its affiliates.importcom.alibaba.dashscope.aigc.conversation.Conversation;importcom.alibaba.dashscope.aigc.conversation.ConversationParam;importcom.alibaba.dashscope.aigc.conversation.ConversationResult;importcom.alibaba.dashscope.exception.ApiException;importcom.alibaba.dashscope.exception.InputRequiredException;importcom.alibaba.dashscope.exception.NoApiKeyException;importcom.alibaba.dashscope.utils.JsonUtils;publicclassMain{publicstaticvoidquickStart()throwsApiException,NoApiKeyException,InputRequiredException{Conversation conversation =newConversation();String prompt ="用萝卜、土豆、茄子做饭,给我个菜谱。";ConversationParam param =ConversationParam.builder().model(Conversation.Models.QWEN_TURBO).prompt(prompt).apiKey("你的apiKey").build();ConversationResult result = conversation.call(param);System.out.println(JsonUtils.toJson(result));}publicstaticvoidmain(String[] args){try{quickStart();}catch(ApiException|NoApiKeyException|InputRequiredException e){System.out.println(e.getMessage());}System.exit(0);}}
返回结果
{"requestId":"b384e189-4d38-9f2e-9773-8350c1934f1a","usage":{"input_tokens":32,"output_tokens":433,"total_tokens":465},"output":{"text":"当然可以,这里有一个简单而美味的三蔬菜炖煮菜品谱,名为\"红烧三蔬(萝卜、土豆、茄子)\":\n\n**材料:**\n1. 萝卜1根\n2. 土豆2个\n3. 茄子2个\n4. 大葱1根\n5. 生姜2片\n6. 大蒜3瓣\n7. 食用油适量\n8. 料酒1汤匙\n9. 生抽酱油2汤匙\n10. 红糖2茶匙\n11. 清水适量\n12. 盐适量\n13. 胡椒粉适量\n14. 水淀粉(可选,用于勾芡)\n\n**步骤:**\n1. 萝卜、土豆和茄子分别洗净去皮,切成滚刀块。大葱切段,生姜和大蒜切末备用。\n2. 锅中加入适量食用油,放入红糖小火慢慢炒化,炒至红色泡沫状。\n3. 加入切好的姜蒜末,翻炒出香味。\n4. 倒入切好的萝卜块,翻煎均匀,让每一块都裹上糖色。\n5. 加入土豆块,继续翻煎至表面微黄。\n6. 将茄子块加入锅中,翻煎至所有蔬菜都略微软化。\n7. 倒入料酒,翻炒均匀后加入生抽酱油,翻炒均匀使蔬菜充分吸收调料。\n8. 加入足够的清水,水量以刚好没过蔬菜为宜。盖上锅盖,转中小火慢炖约15-20分钟,直到蔬菜熟软。\n9. 期间可根据口味加入适量的盐和胡椒粉调味。\n10. 如果喜欢汤汁浓稠,可在最后加入少量水淀粉,快速搅拌均匀即可。\n\n这道菜色泽诱人,营养丰富,是家常便饭的好选择。你可以根据个人口味调整食材份量和调料。Enjoy your meal!","finish_reason":"stop"}}

官方提供的版本

// Copyright (c) Alibaba, Inc. and its affiliates.importjava.util.concurrent.Semaphore;importcom.alibaba.dashscope.aigc.generation.Generation;importcom.alibaba.dashscope.aigc.generation.GenerationResult;importcom.alibaba.dashscope.aigc.generation.models.QwenParam;importcom.alibaba.dashscope.common.ResultCallback;importcom.alibaba.dashscope.exception.ApiException;importcom.alibaba.dashscope.exception.InputRequiredException;importcom.alibaba.dashscope.exception.NoApiKeyException;importcom.alibaba.dashscope.utils.JsonUtils;publicclassMain{privatefinalstaticStringPROMPT="就当前的海洋污染的情况,写一份限塑的倡议书提纲,需要有理有据地号召大家克制地使用塑料制品";publicstaticvoidqwenQuickStart()throwsNoApiKeyException,ApiException,InputRequiredException{Generation gen =newGeneration();QwenParam param =QwenParam.builder().model(Generation.Models.QWEN_TURBO).prompt(PROMPT).topP(0.8).build();GenerationResult result = gen.call(param);System.out.println(JsonUtils.toJson(result));}publicstaticvoidqwenQuickStartCallback()throwsNoApiKeyException,ApiException,InputRequiredException,InterruptedException{Generation gen =newGeneration();QwenParam param =QwenParam.builder().model(Generation.Models.QWEN_TURBO).prompt(PROMPT).topP(0.8).build();Semaphore semaphore =newSemaphore(0);
    gen.call(param,newResultCallback<GenerationResult>(){@OverridepublicvoidonEvent(GenerationResult message){System.out.println(message);}@OverridepublicvoidonError(Exception ex){System.out.println(ex.getMessage());
        semaphore.release();}@OverridepublicvoidonComplete(){System.out.println("onComplete");
        semaphore.release();}});
    semaphore.acquire();}publicstaticvoidmain(String[] args){try{qwenQuickStart();qwenQuickStartCallback();}catch(ApiException|NoApiKeyException|InputRequiredException|InterruptedException e){System.out.println(String.format("Exception %s", e.getMessage()));}System.exit(0);}}

前端最终实现效果图

image.png

后端使用通义千问SDK调用后,控制台的输出

image.png
最后附上该文章的语雀地址:博主语雀

标签: java 前端 spring boot

本文转载自: https://blog.csdn.net/m0_56416743/article/details/138917416
版权归原作者 活的实在 所有, 如有侵权,请联系我们删除。

“Java+SpringBoot调用通义千问的大语言模型的API及前端Vue实现联调”的评论:

还没有评论