java调用通义千问API

前置工作

创建并获取API-KEY

根据官方文档

image-20240402150554690

所以需要先获取API-KEY:

image-20240402150739606

复制并保存创建的API-KEY:

image-20240402150654976

(ps:我这现在如果没复制到API-KEY,可以通过安全验证的方式查看API-KEY,以后可能就不可以这样了,所以还是好好保存吧)

安装DashScope SDK

注意这样要求Java SDK支持java8及以上环境:

image-20240402150815529

maven网站查看DashScope Java SDK版本号,我当前查看的最新版本是2.3.0,所以我在pom.xml文件中添加以下依赖项:



    com.alibaba
    dashscope-sdk-java
    2.1.1

然而,可能是我配置的镜像还没有2.3.0的版本,所以说没找到,所以我加载2.1.1的版本了。
另外,我这里应该是DashScope依赖和项目里的其他依赖冲突了,出现报错,有两份SLF4J

SLF4J: Class path contains multiple SLF4J bindings.
SLF4J: Found binding in [jar:file:/D:/Program%20Files/apache-maven-3.6.1/mvn_repo/ch/qos/logback/logback-classic/1.2.10/logback-classic-1.2.10.jar!/org/slf4j/impl/StaticLoggerBinder.class]
SLF4J: Found binding in [jar:file:/D:/Program%20Files/apache-maven-3.6.1/mvn_repo/org/slf4j/slf4j-simple/1.7.36/slf4j-simple-1.7.36.jar!/org/slf4j/impl/StaticLoggerBinder.class]
SLF4J: See http://www.slf4j.org/codes.html#multiple_bindings for an explanation.
SLF4J: Actual binding is of type [ch.qos.logback.classic.util.ContextSelectorStaticBinder]

查到冲突的包:

image-20240402151041005

对依赖添加排除依赖,然后就不会报依赖包冲突的错了,如下:


    com.alibaba
    dashscope-sdk-java
    
        
            org.slf4j
            slf4j-simple
        
    
    2.1.1

代码部分

通义千问支持http调用,可以参考官方给出的请求和响应实例:

image-20240402151129946

image-20240402151129946

再利用hutool来帮助代码的编写:


    
    cn.hutool   
    hutool-all  
    5.8.16

Controller类:

import cn.hutool.http.HttpRequest;
import cn.hutool.json.JSONUtil;

import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RestController;
//还需要引入下面两个domain类

@RestController
public class ChatController {
    @PostMapping("/chat")//文档要求使用post请求
    public ChatResponse chat(String q){
        String url = "https://dashscope.aliyuncs.com/api/v1/services/aigc/text-generation/generation";//这里看官方文档
        String ApiKey = "sk-xxxxxxxxxx3d7fe";//这里换成你自己的ApiKey

        ChatRequest chatRequest = new ChatRequest(q);
        String json = JSONUtil.toJsonStr(chatRequest);
        //System.out.println(json);//正式发送给api前,查看请求的主要数据情况
        String result = HttpRequest.post(url)
                .header("Authorization","Bearer "+ ApiKey)
                .header("Content-Type","application/json")
                .body(json)
                .execute().body();
        System.out.println(result);
        return JSONUtil.toBean(result, ChatResponse.class);
    }
}

domain类:

//这个是用来处理请求的
import lombok.AllArgsConstructor;
import lombok.Data;
import lombok.NoArgsConstructor;

import java.util.ArrayList;
import java.util.List;

@Data
@AllArgsConstructor
@NoArgsConstructor
public class ChatRequest {
    String model;
    Input input;
    Parameters parameters;

    public ChatRequest(String q){
        model  = "qwen-v1";
        input = new Input(q);
        parameters = new Parameters();
    }
    class Input {
        public List messages;
        Input(String q){
            ArrayList chats = new ArrayList<>();
            chats.add(new Chat("system","你是达摩院的生活助手机器人。"));
            chats.add(new Chat("user",q));
            messages = chats;
        }
    }
    class Chat {
        public String role;
        public String content;
        Chat(String role,String content){
            this.role = role;
            this.content = content;
        }
    }
    class Parameters {
        public String result_format = "text";
    }
}
//这个是用来处理响应的
import lombok.AllArgsConstructor;
import lombok.Data;
import lombok.NoArgsConstructor;

@Data
@AllArgsConstructor
@NoArgsConstructor
public class ChatResponse {
    Output output;
    Usage usage;
    String request_id;
    class Output{
        public String text;
        public String finish_reason;
    }
    class Usage{
        public String output_tokens;
        public String input_tokens;
    }
}

启动项目,访问Knife4j的文档地址http://localhost:8081/api/doc.html,测试后端api/chat端口(这里也可以用postman、apipost、apifox、Swagger等测试端口工具):

image-20230906235936032

响应数据为:

{
  "output": {
    "text": "I am a large language model created by DAMO Academy. I am called QianWen.",
    "finish_reason": "stop"
  },
  "usage": {
    "output_tokens": "20",
    "input_tokens": "30"
  },
  "request_id": "1f92c2ac-ccb9-9498-9870-55fbc04d2e9c"
}

我问中文时候就是回中文,回答的语言可能和问的语言有关吧

小结

可以在上面代码的基础上,根据自己的项目实际情况,进行修改,上面的代码只是对数据进行了基础的处理。

Was this helpful?

0 / 0

发表回复 0

Your email address will not be published.