https://open.bigmodel.cn/dev/api#glm-4
cn.bigmodel.openapi oapi-java-sdk release-V4-2.0.0
用 制作出来的 AI ChatRobot
package com.codervibe.utils; import com.alibaba.fastjson.JSON; import com.fasterxml.jackson.annotation.JsonInclude; import com.fasterxml.jackson.core.JsonProcessingException; import com.fasterxml.jackson.databind.DeserializationFeature; import com.fasterxml.jackson.databind.ObjectMapper; import com.fasterxml.jackson.databind.PropertyNamingStrategy; import com.zhipu.oapi.ClientV4; import com.zhipu.oapi.Constants; import com.zhipu.oapi.service.v4.image.CreateImageRequest; import com.zhipu.oapi.service.v4.image.ImageApiResponse; import com.zhipu.oapi.service.v4.model.*; import io.reactivex.Flowable; import java.util.ArrayList; import java.util.HashMap; import java.util.List; import java.util.Map; import java.util.concurrent.atomic.AtomicBoolean; public class ChatAPIUtils { private static final String API_KEY = "cb11ad7f3b68ce03ed9be6e13573aa19"; private static final String API_SECRET = "nG7UQrrXqsXtqD1S"; private static final ClientV4 client = new ClientV4.Builder(API_KEY, API_SECRET).build(); private static final ObjectMapper mapper = defaultObjectMapper(); public static ObjectMapper defaultObjectMapper() { ObjectMapper mapper = new ObjectMapper(); mapper.configure(DeserializationFeature.FAIL_ON_UNKNOWN_PROPERTIES, false); mapper.setSerializationInclusion(JsonInclude.Include.NON_NULL); mapper.setPropertyNamingStrategy(PropertyNamingStrategy.SNAKE_CASE); mapper.addMixIn(ChatFunction.class, ChatFunctionMixIn.class); mapper.addMixIn(ChatCompletionRequest.class, ChatCompletionRequestMixIn.class); mapper.addMixIn(ChatFunctionCall.class, ChatFunctionCallMixIn.class); return mapper; } // 请自定义自己的业务id private static final String requestIdTemplate = "mycompany-%d"; /** * 同步调用 */ public static String InvokeApi(String content) throws JsonProcessingException { Listmessages = new ArrayList<>(); ChatMessage chatMessage = new ChatMessage(ChatMessageRole.USER.value(), content); messages.add(chatMessage); String requestId = String.format(requestIdTemplate, System.currentTimeMillis()); // 函数调用参数构建部分 List chatToolList = new ArrayList<>(); ChatTool chatTool = new ChatTool(); chatTool.setType(ChatToolType.FUNCTION.value()); ChatFunctionParameters chatFunctionParameters = new ChatFunctionParameters(); chatFunctionParameters.setType("object"); Map properties = new HashMap<>(); properties.put("location", new HashMap () {{ put("type", "string"); put("description", "城市,如:北京"); }}); properties.put("unit", new HashMap () {{ put("type", "string"); put("enum", new ArrayList () {{ add("celsius"); add("fahrenheit"); }}); }}); chatFunctionParameters.setProperties(properties); ChatFunction chatFunction = ChatFunction.builder() .name("get_weather") .description("Get the current weather of a location") .parameters(chatFunctionParameters) .build(); chatTool.setFunction(chatFunction); chatToolList.add(chatTool); ChatCompletionRequest chatCompletionRequest = ChatCompletionRequest.builder() .model(Constants.ModelChatGLM4) .stream(Boolean.FALSE) .invokeMethod(Constants.invokeMethod) .messages(messages) .requestId(requestId) .tools(chatToolList) .toolChoice("auto") .build(); ModelApiResponse invokeModelApiResp = client.invokeModelApi(chatCompletionRequest); try { // 这里返回出去是一个 json return mapper.writeValueAsString(invokeModelApiResp); } catch (JsonProcessingException e) { e.printStackTrace(); } return mapper.writeValueAsString(new ModelApiResponse()); } public static void CreateImage(String content) { CreateImageRequest createImageRequest = new CreateImageRequest(); createImageRequest.setModel(Constants.ModelCogView); createImageRequest.setPrompt(content); ImageApiResponse imageApiResponse = client.createImage(createImageRequest); System.out.println("imageApiResponse:" + JSON.toJSONString(imageApiResponse)); } }
/** * 同步调用 */ public static ModelData InvokeApi(String content) throwsJsonProcessingException{ Listmessages = new ArrayList<>(); ChatMessage chatMessage = new ChatMessage(ChatMessageRole.USER.value(), content); messages.add(chatMessage); String requestId = String.format(requestIdTemplate, System.currentTimeMillis()); // 函数调用参数构建部分 List chatToolList = new ArrayList<>(); ChatTool chatTool = new ChatTool(); chatTool.setType(ChatToolType.FUNCTION.value()); ChatFunctionParameters chatFunctionParameters = new ChatFunctionParameters(); chatFunctionParameters.setType("object"); Map properties = new HashMap<>(); properties.put("location", new HashMap () {{ put("type", "string"); put("description", "城市,如:北京"); }}); properties.put("unit", new HashMap () {{ put("type", "string"); put("enum", new ArrayList () {{ add("celsius"); add("fahrenheit"); }}); }}); chatFunctionParameters.setProperties(properties); ChatFunction chatFunction = ChatFunction.builder() .name("get_weather") .description("Get the current weather of a location") .parameters(chatFunctionParameters) .build(); chatTool.setFunction(chatFunction); chatToolList.add(chatTool); ChatCompletionRequest chatCompletionRequest = ChatCompletionRequest.builder() .model(Constants.ModelChatGLM4) .stream(Boolean.FALSE) .invokeMethod(Constants.invokeMethod) .messages(messages) .requestId(requestId) .tools(chatToolList) .toolChoice("auto") .build(); ModelApiResponse invokeModelApiResp = client.invokeModelApi(chatCompletionRequest); ModelData data = invokeModelApiResp.getData(); return data;
Listchoices = data.getChoices(); System.out.println("choices.toString() = " + choices.toString()); for (Choice choice : choices) { ChatMessage message = choice.getMessage(); System.out.println("message.getContent() = " + message.getContent()); //本来这里想返回具体的信息类但是发现 上面的的那个ModelApiResponse类 也是一个 统一返回类型 也包含这 请求状态码 之类的定义 return message; } return new ChatMessage(); try { return mapper.writeValueAsString(invokeModelApiResp); } catch (JsonProcessingException e) { e.printStackTrace(); } return mapper.writeValueAsString(new ModelApiResponse());
@PostMapping("/chat") public R chat(@RequestParam("content") String content) throws JsonProcessingException { /** * data 中的 choices 是一个 List类型但是实际上只有一个所以索性直接获取数组下标0的对象 */ logger.info(ChatAPIUtils.InvokeApi(content).getChoices().get(0).getMessage().getContent().toString()); return R.ok().data("content", ChatAPIUtils.InvokeApi(content)); }
package com.codervibe.server.service; import com.zhipu.oapi.service.v4.image.ImageResult; import com.zhipu.oapi.service.v4.model.ModelData; public interface ChatService { /** * AI 对话 */ ModelData AIdialogue(String content); /** * AI 画图 */ ImageResult AIcreateimage(String content); }
package com.codervibe.server.Impl; import com.codervibe.server.service.ChatService; import com.codervibe.utils.ChatAPIUtils; import com.fasterxml.jackson.core.JsonProcessingException; import com.zhipu.oapi.service.v4.image.ImageResult; import com.zhipu.oapi.service.v4.model.ModelData; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import org.springframework.stereotype.Service; @Service("chatService") public class ChatServiceImpl implements ChatService { Logger logger = LoggerFactory.getLogger(ChatServiceImpl.class); /** * AI 对话 * @param content */ @Override public ModelData AIdialogue(String content) { logger.info(ChatAPIUtils.InvokeApi(content).getChoices().get(0).getMessage().getContent().toString()); return ChatAPIUtils.InvokeApi(content); } /** * AI 画图 * * @param content */ @Override public ImageResult AIcreateimage(String content) { logger.info(ChatAPIUtils.CreateImage(content).getData().get(0).getUrl()); return ChatAPIUtils.CreateImage(content); } }
****package com.codervibe.web.controller; import com.codervibe.server.service.ChatService; import com.codervibe.utils.ChatAPIUtils; import com.codervibe.web.common.response.R; import com.fasterxml.jackson.core.JsonProcessingException; import org.springframework.web.bind.annotation.PostMapping; import org.springframework.web.bind.annotation.RequestMapping; import org.springframework.web.bind.annotation.RequestParam; import org.springframework.web.bind.annotation.RestController; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import javax.annotation.Resource; @RestController @RequestMapping("/chat") public class ChatController { Logger logger = LoggerFactory.getLogger(ChatController.class); @Resource private ChatService chatService; @PostMapping("/content") public R chat(@RequestParam("content") String content) { return R.ok().data("content", chatService.AIdialogue(content)); } @PostMapping("/AIcreateimage") public R AIcreateimage(@RequestParam("content") String content){ return R.ok().data("image",chatService.AIcreateimage(content)); } }