OpenAI 集成
大约 6 分钟
第五章:集成OpenAI
5.1 OpenAI API概览
OpenAI是AI领域的领导者,提供了多个强大的模型和服务。
5.1.1 OpenAI模型家族
OpenAI提供了多个模型,每个都有其特定的用途:
GPT系列:文本生成和对话
- gpt-4:最强大的模型
- gpt-4-turbo:高速版本
- gpt-3.5-turbo:经济型选择
DALL-E系列:图像生成
- DALL-E 3:最新图像生成模型
Embeddings:文本嵌入
- text-embedding-ada-002:通用嵌入模型
5.1.2 API功能
- Chat Completions:对话生成
- Completions:文本补全
- Images:图像生成
- Embeddings:文本嵌入
- Audio:语音处理
- Fine-tuning:模型微调
5.2 配置OpenAI客户端
5.2.1 添加依赖
在pom.xml中添加OpenAI依赖:
<dependency>
<groupId>org.springframework.ai</groupId>
<artifactId>spring-ai-openai-spring-boot-starter</artifactId>
</dependency>5.2.2 配置API密钥
在application.properties中配置OpenAI API密钥:
# OpenAI配置
spring.ai.openai.api-key=your-openai-api-key
spring.ai.openai.chat.options.model=gpt-4
spring.ai.openai.chat.options.temperature=0.7
spring.ai.openai.chat.options.max-tokens=10005.2.3 编程配置
@Configuration
public class OpenAiConfig {
@Bean
public ChatClient openAiChatClient(ChatClient.Builder builder) {
return builder
.defaultSystem("You are a helpful assistant")
.defaultOptions(OpenAiChatOptions.builder()
.withModel("gpt-4-turbo")
.withTemperature(0.8f)
.withMaxTokens(2000)
.build())
.build();
}
}5.3 ChatGPT应用开发
5.3.1 基础对话
@RestController
public class OpenAiController {
private final ChatClient openAiChatClient;
public OpenAiController(ChatClient openAiChatClient) {
this.openAiChatClient = openAiChatClient;
}
@GetMapping("/openai/chat")
public String chat(@RequestParam String message) {
return openAiChatClient.prompt()
.user(message)
.call()
.content();
}
}5.3.2 系统提示和角色设定
@GetMapping("/openai/role-play")
public String rolePlay(
@RequestParam String role,
@RequestParam String message) {
return openAiChatClient.prompt()
.system("You are " + role)
.user(message)
.call()
.content();
}5.3.3 多轮对话管理
@RestController
public class ConversationController {
private final ChatClient openAiChatClient;
public ConversationController(ChatClient openAiChatClient) {
this.openAiChatClient = openAiChatClient;
}
@PostMapping("/openai/conversation")
public ConversationResponse conversation(@RequestBody ConversationRequest request) {
ChatPrompt chatPrompt = new ChatPrompt();
// 添加系统提示
chatPrompt.add(new SystemMessage(request.getSystemPrompt()));
// 添加历史消息
for (Message message : request.getHistory()) {
chatPrompt.add(message);
}
// 添加当前消息
chatPrompt.add(new UserMessage(request.getCurrentMessage()));
ChatResponse response = openAiChatClient.prompt(chatPrompt).call();
return new ConversationResponse(
response.getContent(),
response.getResults().get(0).getGenerationMetadata()
);
}
}5.4 DALL-E图像生成
5.4.1 基础图像生成
@RestController
public class DalleController {
private final ImageClient imageClient;
public DalleController(ImageClient imageClient) {
this.imageClient = imageClient;
}
@GetMapping("/openai/image")
public String generateImage(@RequestParam String prompt) {
ImagePrompt imagePrompt = new ImagePrompt(prompt);
ImageResponse response = imageClient.generate(imagePrompt);
return response.getResult().getOutput().getUrl();
}
}5.4.2 高级图像生成选项
@GetMapping("/openai/advanced-image")
public String generateAdvancedImage(
@RequestParam String prompt,
@RequestParam(defaultValue = "1024x1024") String size,
@RequestParam(defaultValue = "1") int n) {
ImagePrompt imagePrompt = new ImagePrompt(prompt);
ImageOptions imageOptions = ImageOptions.builder()
.withModel("dall-e-3")
.withN(n)
.withSize(size)
.build();
ImageResponse response = imageClient.generate(imagePrompt, imageOptions);
return response.getResult().getOutput().getUrl();
}5.4.3 图像编辑
@PostMapping("/openai/edit-image")
public String editImage(
@RequestParam MultipartFile image,
@RequestParam String prompt) {
ImagePrompt imagePrompt = new ImagePrompt(image, prompt);
ImageResponse response = imageClient.generate(imagePrompt);
return response.getResult().getOutput().getUrl();
}5.5 高级功能
5.5.1 函数调用
OpenAI的函数调用功能非常强大:
@RestController
public class OpenAiFunctionController {
private final ChatClient openAiChatClient;
public OpenAiFunctionController(ChatClient openAiChatClient) {
this.openAiChatClient = openAiChatClient;
}
@GetMapping("/openai/function")
public String functionCall(@RequestParam String question) {
FunctionCallback weatherFunction = new FunctionCallback(
"getWeather",
"Get current weather for a location",
new Schema(SchemaType.OBJECT)
.addProperty("location", SchemaProperty.of(SchemaType.STRING, "City name"))
.addRequired("location"),
this::getWeather
);
FunctionCallback calculatorFunction = new FunctionCallback(
"calculate",
"Perform mathematical calculations",
new Schema(SchemaType.OBJECT)
.addProperty("expression", SchemaProperty.of(SchemaType.STRING, "Mathematical expression"))
.addRequired("expression"),
this::calculate
);
return openAiChatClient.prompt()
.user(question)
.functions(weatherFunction, calculatorFunction)
.call()
.content();
}
private String getWeather(Map<String, Object> arguments) {
String location = (String) arguments.get("location");
return "The current weather in " + location + " is 25°C and sunny";
}
private String calculate(Map<String, Object> arguments) {
String expression = (String) arguments.get("expression");
return "Result: " + evaluateExpression(expression);
}
}5.5.2 嵌入向量
@RestController
public class EmbeddingController {
private final EmbeddingClient embeddingClient;
public EmbeddingController(EmbeddingClient embeddingClient) {
this.embeddingClient = embeddingClient;
}
@GetMapping("/openai/embedding")
public List<Float> getEmbedding(@RequestParam String text) {
EmbeddingResponse embeddingResponse = embeddingClient.call(
new EmbeddingRequest(List.of(text))
);
return embeddingResponse.getResults().get(0).getOutput();
}
}5.5.3 语音转文本
@RestController
public class SpeechToTextController {
private final AudioClient audioClient;
public SpeechToTextController(AudioClient audioClient) {
this.audioClient = audioClient;
}
@PostMapping("/openai/speech-to-text")
public String speechToText(@RequestParam MultipartFile audio) {
AudioRequest audioRequest = new AudioRequest(audio);
AudioResponse response = audioClient.generate(audioRequest);
return response.getResult().getOutput();
}
}5.6 实际应用示例
5.6.1 智能写作助手
@Service
public class WritingAssistant {
private final ChatClient openAiChatClient;
public WritingAssistant(ChatClient openAiChatClient) {
this.openAiChatClient = openAiChatClient;
}
public WritingResponse improveWriting(String text, String style) {
return openAiChatClient.prompt()
.system("You are a professional writer specializing in " + style + " writing")
.user("Improve the following text: " + text)
.call()
.entity(WritingResponse.class);
}
}
public class WritingResponse {
private String improvedText;
private List<String> suggestions;
private double score;
// getters and setters
}5.6.2 代码审查工具
@RestController
public class CodeReviewController {
private final ChatClient openAiChatClient;
public CodeReviewController(ChatClient openAiChatClient) {
this.openAiChatClient = openAiChatClient;
}
@PostMapping("/openai/code-review")
public CodeReviewResult reviewCode(@RequestBody CodeReviewRequest request) {
String prompt = "Review the following code and provide suggestions:\n" + request.getCode();
return openAiChatClient.prompt()
.user(prompt)
.call()
.entity(CodeReviewResult.class);
}
}
public class CodeReviewResult {
private List<String> issues;
private List<String> suggestions;
private String overallRating;
// getters and setters
}5.7 性能优化
5.7.1 缓存策略
@Configuration
@EnableCaching
public class OpenAiCacheConfig {
@Bean
public CacheManager cacheManager() {
SimpleCacheManager cacheManager = new SimpleCacheManager();
cacheManager.setCaches(Arrays.asList(
new ConcurrentMapCache("openai-responses"),
new ConcurrentMapCache("openai-embeddings")
));
return cacheManager;
}
}5.7.2 异步处理
@RestController
public class AsyncOpenAiController {
private final ChatClient openAiChatClient;
public AsyncOpenAiController(ChatClient openAiChatClient) {
this.openAiChatClient = openAiChatClient;
}
@GetMapping("/openai/async")
public CompletableFuture<String> asyncChat(@RequestParam String message) {
return openAiChatClient.prompt()
.user(message)
.callAsync()
.thenApply(ChatResponse::getContent);
}
}5.8 错误处理
5.8.1 异常处理
@RestControllerAdvice
public class OpenAiExceptionHandler {
@ExceptionHandler(OpenAiApiException.class)
public ResponseEntity<ErrorResponse> handleOpenAiError(OpenAiApiException ex) {
ErrorResponse error = new ErrorResponse(
"OPENAI_API_ERROR",
"OpenAI API调用失败: " + ex.getMessage()
);
return new ResponseEntity<>(error, HttpStatus.SERVICE_UNAVAILABLE);
}
}5.8.2 速率限制处理
@Configuration
public class OpenAiRateLimitConfig {
@Bean
public ChatClient rateLimitedChatClient(ChatClient chatClient) {
return new ChatClient() {
@Override
public ChatResponse call(Prompt prompt) {
try {
return chatClient.call(prompt);
} catch (OpenAiRateLimitException ex) {
// 处理速率限制
try {
Thread.sleep(1000); // 等待1秒后重试
return chatClient.call(prompt);
} catch (InterruptedException e) {
Thread.currentThread().interrupt();
throw new RuntimeException("Rate limit retry failed", e);
}
}
}
// 实现其他方法...
};
}
}5.9 监控与日志
5.9.1 指标监控
@RestController
public class OpenAiMetricsController {
private final MeterRegistry meterRegistry;
public OpenAiMetricsController(MeterRegistry meterRegistry) {
this.meterRegistry = meterRegistry;
}
@GetMapping("/openai/metrics")
public Map<String, Object> getMetrics() {
return Map.of(
"totalCalls", meterRegistry.counter("openai.total.calls").count(),
"averageDuration", meterRegistry.timer("openai.duration").mean(),
"errorRate", meterRegistry.counter("openai.errors").count() /
(meterRegistry.counter("openai.total.calls").count() + 1.0)
);
}
}5.9.2 请求日志
@Configuration
public class OpenAiLogging {
@Bean
public ChatClient loggingChatClient(ChatClient chatClient) {
return new ChatClient() {
@Override
public ChatResponse call(Prompt prompt) {
long startTime = System.currentTimeMillis();
try {
ChatResponse response = chatClient.call(prompt);
long duration = System.currentTimeMillis() - startTime;
log.info("OpenAI调用 - 耗时: {}ms, Prompt: {}", duration, prompt);
return response;
} catch (Exception ex) {
log.error("OpenAI调用失败", ex);
throw ex;
}
}
// 实现其他方法...
};
}
}5.10 小结
本章详细介绍了OpenAI模型的集成和使用:
- API概览:了解OpenAI的模型家族和功能
- 客户端配置:掌握OpenAI客户端的配置方法
- ChatGPT应用:学习对话生成和多轮对话管理
- 图像生成:掌握DALL-E图像生成和编辑
- 高级功能:了解函数调用、嵌入向量等高级特性
- 实际应用:学习智能写作、代码审查等实际应用场景
- 性能优化:掌握缓存、异步等优化技术
- 错误处理:了解异常处理和速率限制处理
- 监控日志:掌握指标监控和请求日志
在下一章中,我们将学习文本处理与生成的高级技术。 点击这里👇🏻获取:100万QPS短链系统、复杂的商城微服务系统、智能翻译助手AI Agent、SaaS点餐系统、刷题吧小程序、商城系统、秒杀系统、AI项目、代码生成神器、苏三demo项目、智能天气播报AI Agent、智能代码审查AI Agent等 10 个项目的:项目源代码、开发教程和技术答疑
