Spring Boot 整合 Spring AI 实现项目接入ChatGPT(OpenAl的调用)
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RestController;
import com.openai.api.AskCompletionResponse;
import com.openai.api.Completions;
import com.openai.api.EngineApi;
import com.openai.api.ModelApi;
import com.openai.api.OpenaiService;
@RestController
public class ChatController {
private final OpenaiService openaiService;
public ChatController(OpenaiService openaiService) {
this.openaiService = openaiService;
}
@PostMapping("/completions")
public AskCompletionResponse generateCompletion(@RequestBody CompletionRequest completionRequest) {
Completions completions = Completions.builder()
.model(completionRequest.getModel())
.prompt(completionRequest.getPrompt())
.maxTokens(completionRequest.getMaxTokens())
.temperature(completionRequest.getTemperature())
.build();
return openaiService.completions().create(completions);
}
}
// 请求体类
class CompletionRequest {
private String model;
private String prompt;
private Integer maxTokens;
private Double temperature;
// getter和setter方法
}
这个代码示例展示了如何在Spring Boot应用程序中创建一个REST控制器,它接收一个包含提示和模型信息的CompletionRequest
对象,并使用OpenAI的API生成文本。这个控制器方法使用OpenAI的服务来发送完成请求并返回响应。
评论已关闭