Spring Boot集成OpenAI文本向量化指南

360影视 动漫周边 2025-05-18 19:00 2

摘要:double dot = 0.0, norm1 = 0.0, norm2 = 0.0;

以下是使用 Spring Boot 集成 OpenAI Embedding 实现文本向量化的分步指南:

1. 创建 Spring Boot 项目

使用 Spring Initializr 创建一个新项目,添加以下依赖:

Spring WebLombok(可选)

xml

com.theokanning.openai-gpt3-java

service

0.18.2

3. 配置 OpenAI API 密钥

application.properties 中配置:

properties

openai.api.key=sk-your-api-key-here

openai.api.model=text-embedding-3-small # 推荐模型

使用 @ConfigurationProperties 读取配置:

java

@Configuration

@ConfigurationProperties(prefix = "openai.api")

public class OpenAIConfig {

private String key;

private String model;

// Getters & Setters

}

4. 实现 Embedding 服务

创建服务类处理向量化逻辑:

java

@Service

@RequiredArgsConstructor

public class EmbeddingService {

private final OpenAIConfig config;

public List createEmbedding(String text) {

OpenAiService service = new OpenAiService(config.getKey, Duration.ofSeconds(30));

EmbeddingRequest request = EmbeddingRequest.builder

.model(config.getModel)

.input(Collections.singletonList(text))

.build;

try {

EmbeddingResult result = service.createEmbeddings(request);

return result.getData.get(0).getEmbedding;

} catch (OpenAiHttpException e) {

throw new RuntimeException("OpenAI API error: " + e.getMessage);

}

}

}

5. 创建 REST 控制器

java

@RestController

@RequestMapping("/api/embeddings")

@RequiredArgsConstructor

public class EmbeddingController {

private final EmbeddingService embeddingService;

@PostMapping

public ResponseEntity getEmbedding(@RequestBody TextRequest request) {

try {

List embedding = embeddingService.createEmbedding(request.getText);

return ResponseEntity.ok(new EmbeddingResponse(embedding));

} catch (Exception e) {

return ResponseEntity.internalServerError.body(e.getMessage);

}

}

// DTOs

@Data

static class TextRequest { private String text; }

@Data

@AllArgsConstructor

static class EmbeddingResponse { private List vector; }

}

6. 测试 API

使用 curl 测试:

bash

curl -X POST http://localhost:8080/api/embeddings \

-H "Content-Type: application/json" \

-d '{"text": "Spring Boot整合OpenAI示例"}'

响应示例:

json

{

"vector": [

-0.006929283495992422,

0.031357022792100906,

... // 1536 elements for text-embedding-3-small

]

}

关键注意事项:

API 成本控制:OpenAI 按 token 计费,需监控使用量性能优化:使用 @Async 实现异步处理添加缓存(如 Redis)存储常用文本的向量错误处理:添加重试机制(使用 Spring Retry)处理速率限制(429 错误)模型选择text-embedding-3-small:性价比高text-embedding-3-large:更高维度(3072)

扩展功能建议

java

// 批量处理示例

public Map> batchEmbed(List texts) {

return texts.stream

.collect(Collectors.toMap(

Function.identity,

this::createEmbedding

));

}

// 相似度计算(使用余弦相似度)

public double similarity(List vec1, List vec2) {

double dot = 0.0, norm1 = 0.0, norm2 = 0.0;

for (int i = 0; i

dot += vec1.get(i) * vec2.get(i);

norm1 += Math.pow(vec1.get(i), 2);

norm2 += Math.pow(vec2.get(i), 2);

}

return dot / (Math.sqrt(norm1) * Math.sqrt(norm2));

}

完整技术栈建议

组件推荐选择向量数据库Pinecone, Milvus, PGVector缓存Redis异步处理Spring @Async, Kafka监控Micrometer + Prometheus

参考 OpenAI 官方文档:Embeddings Guide

来源:老客数据一点号

相关推荐