Junit4遇上chatGPT
这是一篇适合Java工程师体质的AI开发教程。
本教程会教你写一个简单的junit4的Rule,该Rule在基于junit4的测试方法失败后,自动向GPT发送错误信息并通过GPT分析得出代码修改建议。
首先向AI问好
简单的通过AI,让它基于json格式生成相应的类文件,这样方便我们在代码中使用,而不用显示写json字符串。
package com.jd.jr.parrot.llm;
import lombok.Data;
/**
* created on 2023/7/25 20:07
*
* @author Dragonchu
*/
@Data
public class Choice {
private String finish_reason;
private int index;
private Message message;
}
package com.jd.jr.parrot.llm;
import lombok.Data;
/**
* created on 2023/7/25 20:07
*
* @author Dragonchu
*/
@Data
public class Message {
private String role;
private String content;
}
package com.jd.jr.parrot.llm;
import lombok.Data;
/**
* created on 2023/7/25 20:06
*
* @author Dragonchu
*/
@Data
public class Usage {
private int completion_tokens;
private int prompt_tokens;
private int total_tokens;
}
package com.jd.jr.parrot.llm;
import java.util.List;
import lombok.Data;
/**
* created on 2023/7/25 20:17
*
* @author Dragonchu
*/
@Data
public class OpenAiRequest {
private String erp;
private List<Message> messages;
private String model;
}
package com.jd.jr.parrot.llm;
import java.util.List;
import lombok.Data;
/**
* created on 2023/7/25 20:04
*
* @author Dragonchu
*/
@Data
public class OpenAiResponse {
private long created;
private Usage usage;
private String model;
private String id;
private List<Choice> choices;
private String object;
}
封装一个简单的工具,以供使用GPT
package com.jd.jr.parrot.llm;
import com.google.gson.Gson;
import java.util.Arrays;
import lombok.extern.slf4j.Slf4j;
import org.apache.http.client.methods.CloseableHttpResponse;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.entity.StringEntity;
import org.apache.http.impl.client.CloseableHttpClient;
import org.apache.http.impl.client.HttpClients;
import org.apache.http.util.EntityUtils;
import java.io.IOException;
import java.nio.charset.Charset;
/**
* created on 2023/7/25 20:07
*
* @author Dragonchu
*/
@Slf4j
public class LLMUtil {
private static String url = "Your url";
private static String apiKey = "Your key";
public static String sendMsg(String msg){
OpenAiRequest request =