当前位置: 首页 > news >正文

SpringAI:AI工程应用框架新选择

Spring AI 是一个用于 AI 工程的应用框架

Spring AI 是一个用于 AI 工程的应用框架。其目标是将可移植性和模块化设计等 Spring 生态系统设计原则应用于 AI 领域,并推广使用 POJO 作为应用程序的构建块到 AI 领域。

 Spring AI 的核心是解决 AI 集成的基本挑战:将企业数据和 API 与 AI 模型连接起来。

特征

支持所有主要的 AI 模型提供商,例如 Anthropic、OpenAI、Microsoft、Amazon、Google 和 Ollama。支持的模型类型包括

基于Spring AI与Cassandra整合

以下是基于Spring AI与Cassandra整合的实用示例,涵盖从基础操作到高级应用场景,代码均以Spring Boot为框架。

基础CRUD操作

1. 实体类定义

@Table
public class Product {@PrimaryKeyprivate UUID id;private String name;private double price;// Lombok注解省略
}

2. 插入数据

@Repository
public interface ProductRepository extends CassandraRepository<Product, UUID> {@InsertProduct save(Product product);
}

3. 批量插入

List<Product> products = Arrays.asList(new Product(...));
productRepository.saveAll(products);

4. 按ID查询

Optional<Product> product = productRepository.findById(uuid);

5. 更新数据

product.setPrice(29.99);
productRepository.save(product);


查询与条件操作

6. 自定义查询方法

@Query("SELECT * FROM products WHERE price > ?0 ALLOW FILTERING")
List<Product> findByPriceGreaterThan(double price);

7. 分页查询

Page<Product> page = productRepository.findAll(PageRequest.of(0, 10));

8. 排序查询

Sort sort = Sort.by(Sort.Direction.DESC, "price");
List<Product> products = productRepository.findAll(sort);

9. IN条件查询

@Query("SELECT * FROM products WHERE id IN ?0")
List<Product> findByIds(List<UUID> ids);

10. 使用CassandraTemplate

cassandraTemplate.select("SELECT * FROM products", Product.class);


高级数据建模

11. 使用UDT(用户定义类型)

@UserDefinedType("address")
public class Address {private String city;private String street;
}

12. 集合类型字段

@Table
public class User {private Set<String> tags;private Map<String, String> attributes;
}

13. 时间序列数据建模

@PrimaryKeyClass
public class SensorReadingKey {@PrimaryKeyColumn(type = PrimaryKeyType.PARTITIONED)private String sensorId;@PrimaryKeyColumn(type = PrimaryKeyType.CLUSTERED, ordering = Ordering.DESCENDING)private Instant timestamp;
}


AI集成示例

14. 存储AI模型输出

@Table
public class ModelPrediction {@PrimaryKeyprivate UUID id;private String modelName;private Map<String, Double> probabilities;
}

15. 特征向量存储

@Table
public class FeatureVector {@PrimaryKeyprivate String entityId;private List<Float> vector;  // 用于相似性搜索
}

16. 推荐结果缓存

@Table
public class UserRecommendation {@PrimaryKeyprivate String userId;private List<String> recommendedItems;
}


性能优化

17. 批量异步写入

ListenableFuture<Void> future = cassandraTemplate.insertAsynchron(entities);

18. 轻量级事务

@Insert(ifNotExists = true)
boolean insertIfNotExists(Product product);

19. 物化视图查询

@Table
@MaterializedView("products_by_price")
public class ProductByPrice {@PrimaryKeyprivate double price;private UUID productId;
}


错误处理与监控

20. 重试策略配置

@Retryable(maxAttempts = 3, backoff = @Backoff(delay = 100))
public void saveWithRetry(Product product) {productRepository.save(product);
}

21. 指标监控

@Timed("cassandra.query.time")
public List<Product> findAllProducts() {return productRepository.findAll();
}


分布式场景

22. 多数据中心配置

spring:data:cassandra:keyspace-name: my_keyspacelocal-datacenter: DC1contact-points: host1,host2

23. 跨分区查询

@Query("SELECT * FROM products WHERE token(id) > token(?0) LIMIT 100")
List<Product> findAfterToken(UUID lastId);


测试与调试

24. 单元测试配置

@TestConfiguration
@EmbeddedCassandra
static class TestConfig {@BeanCassandraTemplate testTemplate() {return new CassandraTemplate(session);}
}

25. 查询日志打印

logging:level:org.springframework.data.cassandra.core.CassandraTemplate: DEBUG

以上示例覆盖了Spring Data Cassandra的核心功能,结合AI场景的特性存储需求,可根据实际业务扩展修改。注意生产环境中需优化分区键设计、添加适当的索引策略。

基于Spring和Azure Vector Search的实例

以下是一些基于Spring和Azure Vector Search的实例示例,涵盖不同场景和使用方法:

基础配置与初始化

application.propertiesapplication.yml中配置Azure Vector Search的连接信息:

azure.search.endpoint=https://{your-service-name}.search.windows.net
azure.search.api-key={your-api-key}
azure.search.index-name={your-index-name}

在Spring Boot中注入SearchClient

@Bean
public SearchClient searchClient(@Value("${azure.search.endpoint}") String endpoint,@Value("${azure.search.api-key}") String apiKey,@Value("${azure.search.index-name}") String indexName) {return new SearchClientBuilder().endpoint(endpoint).credential(new AzureKeyCredential(apiKey)).indexName(indexName).buildClient();
}


向量搜索基础示例

使用预生成的向量进行相似性搜索:

public List<SearchResult> searchByVector(float[] vector, int k) {SearchOptions options = new SearchOptions().setVector(new SearchQueryVector().setValue(vector).setKNearestNeighborsCount(k));return searchClient.search(null, options, Context.NONE).stream().collect(Collectors.toList());
}


文本嵌入与搜索

结合Azure OpenAI生成文本嵌入后搜索:

public List<SearchResult> searchByText(String query, int k) {float[] embedding = openAIClient.generateEmbedding(query); // 假设已配置OpenAI客户端return searchByVector(embedding, k);
}


混合搜索(向量+关键词)

同时使用向量和关键词进行搜索:

public List<SearchResult> hybridSearch(String query, float[] vector, int k) {SearchOptions options = new SearchOptions().setVector(new SearchQueryVector().setValue(vector).setKNearestNeighborsCount(k)).setSearchText(query);return searchClient.search(null, options, Context.NONE).stream().collect(
http://www.dtcms.com/a/307307.html

相关文章:

  • 转码刷 LeetCode 笔记[1]:3.无重复字符的最长子串(python)
  • 一对一交友小程序 / APP 系统架构分析
  • n8n为什么建议在数组的每个item中添加json键?
  • python的异步、并发开发
  • 聊下多线程查询数据库
  • YOLO---01目标检测基础
  • C++从入门到起飞之——智能指针!
  • day 40 打卡-装饰器
  • Vulnhub Thales靶机复现详解
  • 02 基于sklearn的机械学习-KNN算法、模型选择与调优(交叉验证、朴素贝叶斯算法、拉普拉斯平滑)、决策树(信息增益、基尼指数)、随机森林
  • 【JEECG】JVxeTable表格拖拽排序功能
  • C语言:逆序输出0到9的数组元素
  • LeetCode Hot 100 搜索旋转排序数组
  • 腾讯云市场排名
  • 借助 Wisdom SSH 的 AI 助手构建 Linux 开发环境
  • 2419.按位与最大的最长子数组
  • duiLib 自定义资源目录
  • 限流算法详解:固定窗口、滑动窗口、令牌桶与漏桶算法全面对比
  • P1036 [NOIP 2002 普及组] 选数
  • 结合C++红黑树与AI人工智能的应用
  • Linux 系统日志管理与时钟同步实用指南
  • TCP和UDP编程的主要区别
  • 当人生低谷无人帮助时,如何独自奏响人生乐章
  • Linux系统编程Day1-- Linux系统的概念,主要内容
  • 查看遥控器6通道(以及其他通道)的实际PWM值
  • 洛谷 P1601 A+B Problem(高精)普及-
  • Datawhale AI夏令营 大模型技术task3 稍稍提分
  • 密码学安全性简介
  • LLM—— 基于 MCP 协议(Stdio 模式)的工具调用实践
  • 从一开始的网络攻防(十三):WAF入门到上手