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

蓝雨幕 2024-07-11 08:03:04 阅读 76

image.png

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

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

在pom.xml文件种导入DashScope SDK的坐标

<code><!-- 通义千问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层

package com.he.cms.blog.controller;

import com.alibaba.dashscope.aigc.generation.GenerationResult;

import com.alibaba.dashscope.exception.InputRequiredException;

import com.alibaba.dashscope.exception.NoApiKeyException;

import com.he.cms.blog.service.IBlogAiSGenerateService;

import io.swagger.annotations.Api;

import io.swagger.annotations.ApiOperation;

import lombok.extern.slf4j.Slf4j;

import org.springframework.beans.factory.annotation.Autowired;

import org.springframework.web.bind.annotation.PathVariable;

import org.springframework.web.bind.annotation.RequestMapping;

import org.springframework.web.bind.annotation.RestController;

/**

* @ClassName BlogAiGenerateController

* @Author Hym

* @Date 2024/4/13 23:01

*/

@Slf4j

@RestController

//好好学习,走向巅峰!

@Api(tags = "博客生成")

public class BlogAiGenerateController {

@Autowired

private IBlogAiSGenerateService blogAiSGenerateService;

/**

* 生成博客

*/

@RequestMapping("/generateArticle/{content}")

@ApiOperation(value = "生成博客", notes = "生成博客" + "调用方式:" + "生成博客" + "传入参数:" + "content")

public GenerationResult generateArticle(@PathVariable String content) throws NoApiKeyException, InputRequiredException {

GenerationResult generationResult = blogAiSGenerateService.BlogAiSGenerate(content);

log.info(generationResult.toString());

return generationResult;

}

}

2.3 Servic层及实现类

接口

package com.he.cms.blog.service;

import com.alibaba.dashscope.aigc.generation.GenerationResult;

import com.alibaba.dashscope.exception.InputRequiredException;

import com.alibaba.dashscope.exception.NoApiKeyException;

public interface IBlogAiSGenerateService {

/**

* 生成博客

*

* @param title 标题

* @param content 内容

* @return 结果

*/

GenerationResult BlogAiSGenerate(String content) throws NoApiKeyException, InputRequiredException;

}

实现类

package com.he.cms.blog.service.impl;

import com.alibaba.dashscope.aigc.generation.GenerationResult;

import com.alibaba.dashscope.exception.InputRequiredException;

import com.alibaba.dashscope.exception.NoApiKeyException;

import com.he.cms.blog.service.ICmsBlogAiSGenerateService;

import com.he.cms.utils.CmsBlogQianWenGenerateUtils;

import org.springframework.stereotype.Service;

import javax.annotation.Resource;

/**

* @ClassName BlogAiSGenerateServiceImpl

* @Author Hym

* @Date 2024/4/13 23:06

*/

@Service

//好好学习,走向巅峰!

public class CmsBlogAiSGenerateServiceImpl implements ICmsBlogAiSGenerateService {

@Resource

private CmsBlogQianWenGenerateUtils cmsBlogQianWenGenerateUtils;

@Override

public GenerationResult BlogAiSGenerate(String content) throws NoApiKeyException, 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

<code>package com.he.cms.utils;

import com.alibaba.dashscope.aigc.generation.Generation;

import com.alibaba.dashscope.aigc.generation.GenerationResult;

import com.alibaba.dashscope.aigc.generation.models.QwenParam;

import com.alibaba.dashscope.common.Message;

import com.alibaba.dashscope.common.MessageManager;

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.Constants;

import io.swagger.annotations.ApiOperation;

import lombok.extern.slf4j.Slf4j;

import org.springframework.beans.factory.annotation.Value;

import org.springframework.stereotype.Component;

/**

* @ClassName BlogQianWenGenerateUtils

* @Author Hym

* @Date 2024/4/13 23:13

*/

//好好学习,走向巅峰!

@Slf4j

@Component

public class CmsBlogQianWenGenerateUtils {

@Value("${tong_yi_cloud.ai_api_Key}")

private String qianWenKeyApiKey;

@ApiOperation("千问生成文章" + "调用方式:" + "千问生成文章" + "传入参数:" + "content")

public GenerationResult callWithMessage(String content) throws NoApiKeyException, ApiException, InputRequiredException

{

Constants.apiKey=qianWenKeyApiKey;

Generation gen = new Generation();

MessageManager msgManager = new MessageManager(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调用

改良版本

package test;// Copyright (c) Alibaba, Inc. and its affiliates.

import com.alibaba.dashscope.aigc.conversation.Conversation;

import com.alibaba.dashscope.aigc.conversation.ConversationParam;

import com.alibaba.dashscope.aigc.conversation.ConversationResult;

import com.alibaba.dashscope.exception.ApiException;

import com.alibaba.dashscope.exception.InputRequiredException;

import com.alibaba.dashscope.exception.NoApiKeyException;

import com.alibaba.dashscope.utils.JsonUtils;

public class Main {

public static void quickStart() throws ApiException, NoApiKeyException, InputRequiredException {

Conversation conversation = new Conversation();

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));

}

public static void main(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.

import java.util.concurrent.Semaphore;

import com.alibaba.dashscope.aigc.generation.Generation;

import com.alibaba.dashscope.aigc.generation.GenerationResult;

import com.alibaba.dashscope.aigc.generation.models.QwenParam;

import com.alibaba.dashscope.common.ResultCallback;

import com.alibaba.dashscope.exception.ApiException;

import com.alibaba.dashscope.exception.InputRequiredException;

import com.alibaba.dashscope.exception.NoApiKeyException;

import com.alibaba.dashscope.utils.JsonUtils;

public class Main {

private final static String PROMPT = "就当前的海洋污染的情况,写一份限塑的倡议书提纲,需要有理有据地号召大家克制地使用塑料制品";

public static void qwenQuickStart()

throws NoApiKeyException, ApiException, InputRequiredException {

Generation gen = new Generation();

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));

}

public static void qwenQuickStartCallback()

throws NoApiKeyException, ApiException, InputRequiredException, InterruptedException {

Generation gen = new Generation();

QwenParam param = QwenParam.builder().model(Generation.Models.QWEN_TURBO).prompt(PROMPT)

.topP(0.8).build();

Semaphore semaphore = new Semaphore(0);

gen.call(param, new ResultCallback<GenerationResult>() {

@Override

public void onEvent(GenerationResult message) {

System.out.println(message);

}

@Override

public void onError(Exception ex){

System.out.println(ex.getMessage());

semaphore.release();

}

@Override

public void onComplete(){

System.out.println("onComplete");

semaphore.release();

}

});

semaphore.acquire();

}

public static void main(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

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



声明

本文内容仅代表作者观点,或转载于其他网站,本站不以此文作为商业用途
如有涉及侵权,请联系本站进行删除
转载本站原创文章,请注明来源及作者。