前一篇介紹到如何使用application.properties設定連線,這一篇跟大家介紹pom.xml直接引用的方式~
<dependency>
<groupId>org.springframework.ai</groupId>
<artifactId>spring-ai-openai-spring-boot-starter</artifactId>
<version>0.8.1-SNAPSHOT</version>
</dependency>
spring.ai.openai.api-key=${OPENAI_API_KEY}
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.web.client.RestTemplate;
@Configuration
public class ChatGPTConfig {
@Bean
@Qualifier("openaiRestTemplate")
RestTemplate restTemplate() {
return new RestTemplate();
}
}
@RestController
@RequestMapping("api/v1")
@Slf4j
public class ChatAPIController {
@Autowired
private ChatClient chatClient;
@GetMapping("chat")
public String chat(@RequestParam("prompt") String prompt) {
return chatClient.call(prompt);
}
}
@RestController
@RequestMapping("api/v1")
@Slf4j
public class ChatAPIController {
@Qualifier("openaiRestTemplate")
@Autowired
private RestTemplate restTemplate;
@Autowired
private ImageClient imageClient;
@GetMapping(value = "image", produces = MediaType.IMAGE_JPEG_VALUE)
@ResponseBody
public byte[] getImage(@RequestParam("prompt") String prompt) throws URISyntaxException, IOException {
Image image = imageClient.call(new ImagePrompt(prompt)).getResult().getOutput();
URI uri = new URI(image.getUrl());
ResponseEntity<byte[]> responseEntity = restTemplate.getForEntity(uri, byte[].class);
return responseEntity.getBody();
}
}
不論使用哪種方式,大家都可以去看看相關的Library,就可以用得更熟能生巧!