在Spring Boot中整合Spring AI来接入ChatGPT,你需要使用Spring AI的OpenAIService来与OpenAI的API进行交互。以下是一个简化的例子,展示了如何在Spring Boot应用程序中实现这一功能。
- 添加依赖到你的pom.xml:
<dependencies>
    <dependency>
        <groupId>org.springframework.boot</groupId>
        <artifactId>spring-boot-starter</artifactId>
    </dependency>
    <dependency>
        <groupId>org.springframework.boot</groupId>
        <artifactId>spring-boot-starter-ai-openai</artifactId>
    </dependency>
</dependencies>
- 配置你的application.properties或application.yml文件,添加OpenAI的API密钥:
spring.ai-openai.api-key=your_openai_api_key
- 创建一个服务来使用OpenAIService:
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.ai.openai.OpenAIService;
 
@Service
public class ChatService {
 
    @Autowired
    private OpenAIService openAIService;
 
    public String getChatResponse(String message) {
        return openAIService.complete(builder -> builder
            .model("gpt-3.5-turbo")
            .messages(message)
            .temperature(0.5)
        ).join().getChoices().get(0).getPlainText();
    }
}
- 创建一个REST控制器来接收用户消息并返回ChatGPT的响应:
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RestController;
 
@RestController
public class ChatController {
 
    @Autowired
    private ChatService chatService;
 
    @PostMapping("/chat")
    public String chat(@RequestBody String message) {
        return chatService.getChatResponse(message);
    }
}
确保你已经在OpenAI官网注册并获取了API密钥,并且你的Spring Boot应用程序已经配置了该密钥。
这个简单的例子展示了如何在Spring Boot应用程序中集成Spring AI和OpenAI的服务。当用户通过/chat端点发送消息时,它会触发ChatService中的getChatResponse方法,并返回ChatGPT的回复。