java对接阿里通义千问

在这里插入图片描述
创建一个应用
在这里插入图片描述
在这里插入图片描述
在这里插入图片描述

pom.xml引入依赖
在这里插入图片描述

<dependency>
    <groupId>com.alibaba</groupId>
    <artifactId>dashscope-sdk-java</artifactId>
    <!-- 请将 'the-latest-version' 替换为查询到的最新版本号:https://mvnrepository.com/artifact/com.alibaba/dashscope-sdk-java -->
    <version>the-latest-version</version>
</dependency>

https://mvnrepository.com/artifact/com.alibaba/dashscope-sdk-java

<!-- https://mvnrepository.com/artifact/com.alibaba/dashscope-sdk-java -->
<dependency>
    <groupId>com.alibaba</groupId>
    <artifactId>dashscope-sdk-java</artifactId>
    <version>2.17.1</version>
</dependency>

在这里插入图片描述
使用发现pom.xml已经引入了dashscope依赖 但是依赖中没有dashscope这个包
在这里插入图片描述
在这里插入图片描述
解决方案清理maven和idea缓存
在这里插入图片描述
然后就解决了
在这里插入图片描述
下面是官方提供的demo

import com.alibaba.dashscope.app.*;
import com.alibaba.dashscope.exception.ApiException;
import com.alibaba.dashscope.exception.InputRequiredException;
import com.alibaba.dashscope.exception.NoApiKeyException;

public class Main {
    public static void callWithSession()
            throws ApiException, NoApiKeyException, InputRequiredException {
        ApplicationParam param = ApplicationParam.builder()
                // 若没有配置环境变量,可用百炼API Key将下行替换为:.apiKey("sk-xxx")。但不建议在生产环境中直接将API Key硬编码到代码中,以减少API Key泄露风险。
                .apiKey(System.getenv("DASHSCOPE_API_KEY"))
                // 替换为实际的应用 ID
                .appId("YOUR_APP_ID")
                .prompt("你是谁?")
                .build();

        Application application = new Application();
        ApplicationResult result = application.call(param);

        param.setSessionId(result.getOutput().getSessionId());
        param.setPrompt("你有什么技能?");
        result = application.call(param);

        System.out.printf("%s\n, session_id: %s\n",
                result.getOutput().getText(), result.getOutput().getSessionId());
    }

    public static void main(String[] args) {
        try {
            callWithSession();
        } catch (ApiException | NoApiKeyException | InputRequiredException e) {
            System.out.printf("Exception: %s", e.getMessage());
            System.out.println("请参考文档:https://help.aliyun.com/zh/model-studio/developer-reference/error-code");
        }
        System.exit(0);
    }
}
非常好的题!如果你的电商系统是基于 Java(尤其是 Spring Boot),并且希望**快速对接通义大模型(Qwen)**,下面是一个 **从零开始、生产可用、5 分钟可跑通** 的完整实现方案。 我们将使用 **Spring Boot + Spring AI 核心抽象 + 阿里DashScope API** 实现: - 快速调用 Qwen 大模型 - 支持文本生成(如商品描述、客服回复) - 可扩展为 RAG、智能推荐等场景 - 代码简洁、结构清晰、易于维护 --- ### ✅ 第一步:准备前提条件 #### 1. 获取阿里云 API Key 前往 [https://dashscope.console.aliyun.com/](https://dashscope.console.aliyun.com/) - 登录阿里云账号 - 创建 API Key(在「密钥管理」中) - 记下你的 `DASHSCOPE_API_KEY` > 💡 新用户有免费额度(约 100 万 tokens),足够测试使用。 #### 2. 确定要使用的模型 常用通义系列模型: | 模型名 | 特点 | 推荐用途 | |--------------|--------------------------|------------------| | `qwen-turbo` | 响应快、成本低 | 客服答、摘要 | | `qwen-plus` | 性能均衡 | 商品文案生成 | | `qwen-max` | 强推理能力,接近 GPT-4 | 复杂任务、决策 | 我们以 `qwen-turbo` 为例。 --- ### ✅ 第二步:添加 Maven 依赖 ```xml <!-- Spring Boot Web --> <dependency> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-starter-web</artifactId> </dependency> <!-- Spring AI Core --> <dependency> <groupId>org.springframework.ai</groupId> <artifactId>spring-ai-core</artifactId> <version>0.8.1</version> </dependency> <!-- JSON 处理 --> <dependency> <groupId>com.fasterxml.jackson.core</groupId> <artifactId>jackson-databind</artifactId> </dependency> ``` > ⚠️ 注意版本兼容性。建议使用 Spring Boot 3.1+ 和 Spring AI 0.8.x。 --- ### ✅ 第三步:封装 QwenChatClient(核心) ```java import org.springframework.ai.chat.ChatClient; import org.springframework.ai.chat.ChatResponse; import org.springframework.ai.chat.Generation; import org.springframework.ai.chat.messages.Message; import org.springframework.ai.chat.messages.UserMessage; import org.springframework.ai.chat.prompt.Prompt; import org.springframework.beans.factory.annotation.Value; import org.springframework.stereotype.Component; import org.springframework.web.client.RestTemplate; import org.springframework.http.*; import java.util.Collections; @Component public class QwenChatClient implements ChatClient { private final RestTemplate restTemplate = new RestTemplate(); @Value("${dashscope.api.key}") private String apiKey; private static final String ENDPOINT = "https://dashscope.aliyuncs.com/api/v1/services/aigc/text-generation/generation"; @Override public ChatResponse call(Prompt prompt) { // 提取用户消息 String userMessage = extractUserMessage(prompt); // 构建请求体 RequestBody request = new RequestBody(); request.setModel("qwen-turbo"); // 可配置 request.setInput(new Input(Collections.singletonList( new Input.Message("user", userMessage) ))); request.setParameter(new Parameter()); // 设置 Header HttpHeaders headers = new HttpHeaders(); headers.setContentType(MediaType.APPLICATION_JSON); headers.set("Authorization", "Bearer " + apiKey); HttpEntity<RequestBody> entity = new HttpEntity<>(request, headers); try { ResponseEntity<ResponseData> responseEntity = restTemplate.exchange( ENDPOINT, HttpMethod.POST, entity, ResponseData.class); String content = responseEntity.getBody().getOutput().getText(); return new ChatResponse(new Generation(content)); } catch (Exception e) { throw new RuntimeException("Error calling Qwen API: " + e.getMessage(), e); } } private String extractUserMessage(Prompt prompt) { return prompt.getInstructions().stream() .filter(m -> m instanceof UserMessage) .map(Message::getContent) .findFirst() .orElseThrow(() -> new IllegalArgumentException("No user message provided")); } // --- DTOs --- static class RequestBody { private String model; private Input input; private Parameter parameter; // getter/setter public String getModel() { return model; } public void setModel(String model) { this.model = model; } public Input getInput() { return input; } public void setInput(Input input) { this.input = input; } public Parameter getParameter() { return parameter; } public void setParameter(Parameter parameter) { this.parameter = parameter; } } static class Input { private java.util.List<Message> messages; public Input(java.util.List<Message> messages) { this.messages = messages; } static class Message { private String role; private String content; public Message(String role, String content) { this.role = role; this.content = content; } // getter/setter public String getRole() { return role; } public void setRole(String role) { this.role = role; } public String getContent() { return content; } public void setContent(String content) { this.content = content; } } public java.util.List<Message> getMessages() { return messages; } } static class Parameter { private double temperature = 0.7; private int max_tokens = 512; // 默认即可,也可通过 @Value 注入 } static class ResponseData { private Output output; public Output getOutput() { return output; } static class Output { private String text; public String getText() { return text; } public void setText(String text) { this.text = text; } } } } ``` --- ### ✅ 第四步:配置文件(application.yml) ```yaml server: port: 8080 dashscope: api: key: YOUR_DASHSCOPE_API_KEY_HERE # 替换为你自己的 KEY ``` --- ### ✅ 第五步:提供一个电商应用场景接口 比如:**自动生成商品营销文案** ```java import org.springframework.ai.chat.ChatClient; import org.springframework.ai.chat.messages.UserMessage; import org.springframework.ai.chat.prompt.Prompt; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.web.bind.annotation.GetMapping; import org.springframework.web.bind.annotation.RequestParam; import org.springframework.web.bind.annotation.RestController; @RestController public class ProductCopywritingController { @Autowired private ChatClient chatClient; // 自动注入 QwenChatClient /** * 根据商品名称和特点生成营销文案 */ @GetMapping("/ai/product-copy") public String generateCopy( @RequestParam String productName, @RequestParam String features) { String promptText = String.format( "你是一个电商文案专家,请为以下商品写一段吸引人的中文营销文案(不超过100字):" + "商品名:%s,特点:%s", productName, features); Prompt prompt = new Prompt(new UserMessage(promptText)); return chatClient.call(prompt).getResult().getOutput().getContent(); } } ``` --- ### ✅ 第六步:启动并测试 1. 启动 Spring Boot 应用 2. 调用接口: ```bash GET http://localhost:8080/ai/product-copy?productName=无线蓝牙耳机&features=降噪,续航30小时,高清音质 ``` 返回示例: > “沉浸式音乐体验!这款无线蓝牙耳机支持主动降噪,续航长达30小时,高清音质还原每一个细节,通勤旅行必备之选。” ✅ 成功! --- ### ✅ 扩展建议(后续优化方向) | 功能 | 如何实现 | |------|----------| | 支持流式输出 | 实现 `StreamingChatClient`,处理 SSE | | 多轮对话 | 使用 `MessageHistory` 保存上下文 | | 模板化提示词 | 使用 `PromptTemplate` | | 切换模型更方便 | 加入 `@Value("${ai.model:qwen-turbo}")` 配置 | | 错误重试机制 | 添加 `@Retryable` 注解 | | 监控调用量 | 记录 token 数量、响应时间 | --- ### ✅ 总结:为什么这个方案“快”? | 优势 | 说明 | |------|------| | 不依赖非官方库 | 拒绝 `jmanus` 这类不明来源包 | | 基于标准 Spring AI 抽象 | 未来可无缝切换 OpenAI / 文心一言 | | 结构清晰 | 易读、易维护、易测试 | | 直接对接官方 API | 稳定、安全、可商用 | | 适用于电商场景 | 可用于文案生成、客服机器人、搜索增强等 | ---
评论 3
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值