SpringBoot整合零一万物模型API进行多轮对话

时间:2024-04-19 11:26:32
package com.hao.controller; import cn.hutool.json.JSONUtil; import lombok.Data; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.http.HttpEntity; import org.springframework.http.HttpHeaders; import org.springframework.http.MediaType; import org.springframework.http.ResponseEntity; import org.springframework.web.bind.annotation.GetMapping; import org.springframework.web.bind.annotation.RestController; import org.springframework.web.client.RestTemplate; import java.util.ArrayList; import java.util.List; import java.util.Map; import java.util.Scanner; @RestController public class TestController { @Autowired RestTemplate restTemplate; @GetMapping("/admin/test") public Object test(String[] args) { HttpHeaders headers = new HttpHeaders(); headers.setContentType(MediaType.APPLICATION_JSON); headers.setBearerAuth("{your-own-key}"); Input input = new Input(); input.setModel("yi-34b-chat-0205"); input.setTemperature(0.7); List<Message> messages = new ArrayList<>(); Scanner sc = new Scanner(System.in); while (true) { System.out.println("You:请输入...(exit退出)"); String question = sc.next(); if ("exit".equals(question)) { break; } if (messages.size() == 7) { messages.remove(0); } Message message = new Message(); message.setContent(question); message.setRole("user"); messages.add(message); input.setMessages(messages); HttpEntity<Input> httpEntity = new HttpEntity<>(input,headers); ResponseEntity<Object> obj = restTemplate.postForEntity("https://api.lingyiwanwu.com/v1/chat/completions", httpEntity, Object.class); // 添加assistant返回到messages列表,user/assistant消息必须交替出现 if (messages.size() == 7) { messages.remove(0); } // System.out.println(obj.getBody()); String content = JSONUtil.parseObj(obj.getBody()).getByPath("choices.0.message.content", String.class); Message message1 = new Message(); message1.setContent(content); message1.setRole("assistant"); messages.add(message1); System.out.println("Assistant: " + content); } return "OK"; } } @Data class Input{ private String model; private Double temperature; private List<Message> messages; } @Data class Message{ private String content; private String role; }