Springboot整合文心一言----非流式响应与流式响应(前后端)
    		       		warning:
    		            这篇文章距离上次修改已过427天,其中的内容可能已经有所变动。
    		        
        		                
                在Spring Boot中整合文心一言API,可以创建两种类型的接口:非流式响应和流式响应。
非流式响应通常使用RestTemplate或WebClient来发送HTTP请求到文心一言的API,然后接收响应。
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.client.RestTemplate;
import org.springframework.web.reactive.function.client.WebClient;
 
@RestController
public class WisdomController {
 
    private final RestTemplate restTemplate;
    private final WebClient webClient;
 
    public WisdomController(RestTemplate restTemplate, WebClient webClient) {
        this.restTemplate = restTemplate;
        this.webClient = webClient;
    }
 
    @GetMapping("/wisdom/non-streaming")
    public String getWisdomNonStreaming() {
        // 使用RestTemplate发送请求并获取响应
        String response = restTemplate.getForObject("https://openapi.baidu.com/rest/2.0/solution/...", String.class);
        return response;
    }
 
    @GetMapping("/wisdom/streaming")
    public Mono<String> getWisdomStreaming() {
        // 使用WebClient发送请求并获取响应
        Mono<String> response = webClient.get()
                .uri("https://openapi.baidu.com/rest/2.0/solution/...")
                .retrieve()
                .bodyToMono(String.class);
        return response;
    }
}在这个例子中,getWisdomNonStreaming方法使用RestTemplate以同步的方式获取文心一言的响应。而getWisdomStreaming方法使用WebClient以异步的方式获取文心一言的响应,返回一个Mono<String>对象。
注意:
- 以上代码中的URL应该替换为文心一言API的真实URL。
 - 对于WebClient,需要在类路径中添加
spring-boot-starter-webflux依赖,以支持反应式编程。 - 对于安全性要求较高的生产环境,应该使用更安全的方式来管理API密钥,例如使用Vault或者Credstash。
 
评论已关闭