点击上方“IT那活儿”公众号--专注于企业全栈运维技术分享,不管IT什么活儿,干就完了!!!
技术背景
- Spring Boot 3.x(后端框架) - OpenAI GPT-4 API(大语言模型) - OkHttp(HTTP 请求库) - Lombok + Jackson(简化代码开发) - Maven(构建工具)
使用步骤
<!--pom.xml -->
<dependencies>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-web</artifactId>
</dependency>
<dependency>
<groupId>com.squareup.okhttp3</groupId>
<artifactId>okhttp</artifactId>
<version>4.11.0</version>
</dependency>
<dependency>
<groupId>com.fasterxml.jackson.core</groupId>
<artifactId>jackson-databind</artifactId>
</dependency>
<dependency>
<groupId>org.projectlombok</groupId>
<artifactId>lombok</artifactId>
<optional>true</optional>
</dependency>
</dependencies>
openai:
api-key: sk-xxxxxx
model: gpt-4
url: api.openai.com/v1/chat/completions
@Configuration
@ConfigurationProperties(prefix = "openai")
@Data
public class OpenAiConfig {
privateStringapiKey;
privateStringurl;
privateStringmodel;
}
@Data
@NoArgsConstructor
@AllArgsConstructor
public classChatMessage {
private String role; // "user", "assistant", "system"
private String content;
}
@Data
public class ChatRequest {
private String model;
private List<ChatMessage> messages;
private double temperature = 0.7;
}
@Service
@RequiredArgsConstructor
publicclassOpenAiService{
privatefinal OpenAiConfig config;
privatefinal ObjectMapper objectMapper = new ObjectMapper();
public String chat(String userMessage)throws IOException {
OkHttpClient client = new OkHttpClient();
List<ChatMessage> messages = List.of(new ChatMessage("user", userMessage));
ChatRequest request = new ChatRequest(config.getModel(), messages, 0.7);
RequestBody body = RequestBody.create(
objectMapper.writeValueAsString(request),
MediaType.get("application/json")
);
Request httpRequest = new Request.Builder()
.url(config.getUrl())
.header("Authorization", "Bearer " + config.getApiKey())
.post(body)
.build();
try (Response response = client.newCall(httpRequest).execute()) {
if (!response.isSuccessful()) {
thrownew IOException("Unexpected code " + response);
}
String responseBody = response.body().string();
JsonNode root = objectMapper.readTree(responseBody);
return root.path("choices").get(0).path("message").path("content").asText();
}
}
}
@RestController
@RequestMapping("/chat")
@RequiredArgsConstructor
publicclass ChatController {
private final OpenAiService openAiService;
@PostMapping
public ResponseEntity<String> chat(@RequestBody Map<String, String> request) {
String question = request.get("question");
try {
String answer = openAiService.chat(question);
return ResponseEntity.ok(answer);
} catch (Exception e) {
return ResponseEntity.status(HttpStatus.INTERNAL_SERVER_ERROR).body("错误:" + e.getMessage());
}
}
}
接口调用示例

本文作者:刘首江(上海新炬中北团队)
本文来源:“IT那活儿”公众号

文章转载自IT那活儿,如果涉嫌侵权,请发送邮件至:contact@modb.pro进行举报,并提供相关证据,一经查实,墨天轮将立刻删除相关内容。




