Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Add spring boot starter for pgvector. #76

Open
wants to merge 7 commits into
base: main
Choose a base branch
from
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
82 changes: 82 additions & 0 deletions langchain4j-pgvector-spring-boot-starter/pom.xml
Original file line number Diff line number Diff line change
@@ -0,0 +1,82 @@
<?xml version="1.0" encoding="UTF-8"?>
<project xmlns="http://maven.apache.org/POM/4.0.0"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
<modelVersion>4.0.0</modelVersion>
<parent>
<groupId>dev.langchain4j</groupId>
<artifactId>langchain4j-spring</artifactId>
<version>0.37.0-SNAPSHOT</version>
<relativePath>../pom.xml</relativePath>
</parent>

<artifactId>langchain4j-pgvector-spring-boot-starter</artifactId>
<name>LangChain4j Spring Boot starter for PgVector</name>
<packaging>jar</packaging>

<dependencies>

<dependency>
<groupId>dev.langchain4j</groupId>
<artifactId>langchain4j-pgvector</artifactId>
</dependency>

<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter</artifactId>
</dependency>

<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-autoconfigure-processor</artifactId>
<optional>true</optional>
</dependency>

<!-- needed to generate automatic metadata about available config properties -->
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-configuration-processor</artifactId>
<optional>true</optional>
</dependency>

<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-test</artifactId>
<scope>test</scope>
</dependency>

<dependency>
<groupId>dev.langchain4j</groupId>
<artifactId>langchain4j-embeddings-all-minilm-l6-v2-q</artifactId>
<scope>test</scope>
</dependency>

<dependency>
<groupId>dev.langchain4j</groupId>
<artifactId>langchain4j-spring-boot-tests</artifactId>
<version>${project.version}</version>
<classifier>tests</classifier>
<type>test-jar</type>
<scope>test</scope>
</dependency>

<dependency>
<groupId>org.testcontainers</groupId>
<artifactId>postgresql</artifactId>
<scope>test</scope>
</dependency>

<dependency>
<groupId>org.tinylog</groupId>
<artifactId>tinylog-impl</artifactId>
<scope>test</scope>
</dependency>

<dependency>
<groupId>org.tinylog</groupId>
<artifactId>slf4j-tinylog</artifactId>
<scope>test</scope>
</dependency>
</dependencies>

</project>
Original file line number Diff line number Diff line change
@@ -0,0 +1,22 @@
package dev.langchain4j.store.embedding.pgvector.spring;

import org.springframework.boot.context.properties.ConfigurationProperties;

@ConfigurationProperties(prefix = PgVectorDataSourceProperties.PREFIX)
public record PgVectorDataSourceProperties(
boolean enabled,
String host,
String user,
String password,
Integer port,
String database
) {
static final String PREFIX = "langchain4j.pgvector.datasource";

/**
* Provide a default constructor that sets the default value of enabled to false.
*/
public PgVectorDataSourceProperties() {
this(false, null, null, null, null, null);
}
}
Original file line number Diff line number Diff line change
@@ -0,0 +1,133 @@
package dev.langchain4j.store.embedding.pgvector.spring;

import dev.langchain4j.model.embedding.EmbeddingModel;
import dev.langchain4j.store.embedding.pgvector.PgVectorEmbeddingStore;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.ObjectProvider;
import org.springframework.boot.autoconfigure.AutoConfiguration;
import org.springframework.boot.autoconfigure.condition.ConditionalOnBean;
import org.springframework.boot.autoconfigure.condition.ConditionalOnMissingBean;
import org.springframework.boot.autoconfigure.condition.ConditionalOnProperty;
import org.springframework.boot.context.properties.EnableConfigurationProperties;
import org.springframework.context.ApplicationContext;
import org.springframework.context.annotation.Bean;
import org.springframework.lang.Nullable;

import javax.sql.DataSource;
import java.sql.Connection;
import java.sql.DatabaseMetaData;
import java.sql.SQLException;
import java.util.Map;
import java.util.Optional;

import static dev.langchain4j.internal.ValidationUtils.*;
import static dev.langchain4j.store.embedding.pgvector.spring.PgVectorEmbeddingStoreProperties.*;
import static org.springframework.util.StringUtils.startsWithIgnoreCase;

@AutoConfiguration
@EnableConfigurationProperties({PgVectorEmbeddingStoreProperties.class, PgVectorDataSourceProperties.class})
@ConditionalOnProperty(prefix = PREFIX, name = "enabled", havingValue = "true", matchIfMissing = true)
public class PgVectorEmbeddingStoreAutoConfiguration {

private static final Logger log = LoggerFactory.getLogger(PgVectorEmbeddingStoreAutoConfiguration.class);

private final ApplicationContext applicationContext;

public PgVectorEmbeddingStoreAutoConfiguration(ApplicationContext applicationContext) {
this.applicationContext = applicationContext;
}

@Bean
@ConditionalOnMissingBean
@ConditionalOnBean(DataSource.class)
@ConditionalOnProperty(prefix = PgVectorDataSourceProperties.PREFIX, name = "enabled", havingValue = "false")
public PgVectorEmbeddingStore pgVectorEmbeddingStoreWithExistingDataSource(ObjectProvider<DataSource> dataSources, PgVectorEmbeddingStoreProperties properties,
@Nullable EmbeddingModel embeddingModel) {

// The PostgreSQL data source is selected based on the configured dataSourceBeanName or automatically.
DataSource dataSource = dataSources.stream()
.filter(ds -> {
// Preferentially matches the configured dataSourceBeanName.
String beanName = properties.getDataSourceBeanName();
if (beanName != null && !beanName.isEmpty()) {
String actualBeanName = getBeanNameForDataSource(ds);
return beanName.equals(actualBeanName);
}
return false;
})
.findFirst()
// If no dataSourceBeanName is specified, the first PostgreSQL data source is selected.
.orElseGet(() -> dataSources.stream()
.filter(this::isPostgresqlDataSource)
.findFirst()
.orElseThrow(() -> new IllegalStateException("No suitable PostgreSQL DataSource found in the application context. "
+ "Please configure a valid PostgreSQL DataSource.")));

log.info("Using DataSource bean: {}", dataSource.getClass().getSimpleName());

// Check if the context's data source is a Postgres datasource
ensureTrue(isPostgresqlDataSource(dataSource), "The DataSource in Spring Context is not a Postgres datasource, you need to manually specify the Postgres datasource configuration via 'langchain4j.pgvector.datasource'.");

Integer dimension = Optional.ofNullable(properties.getDimension()).orElseGet(() -> embeddingModel == null ? null : embeddingModel.dimension());

return PgVectorEmbeddingStore.datasourceBuilder()
.datasource(dataSource)
.table(properties.getTable())
.createTable(properties.getCreateTable())
.dimension(dimension)
.useIndex(properties.getUseIndex())
.indexListSize(properties.getIndexListSize())
.build();
}

@Bean
@ConditionalOnMissingBean
@ConditionalOnProperty(prefix = PgVectorDataSourceProperties.PREFIX, name = "enabled", havingValue = "true")
public PgVectorEmbeddingStore pgVectorEmbeddingStoreWithCustomDataSource(PgVectorEmbeddingStoreProperties properties, PgVectorDataSourceProperties dataSourceProperties,
misselvexu marked this conversation as resolved.
Show resolved Hide resolved
@Nullable EmbeddingModel embeddingModel) {
Integer dimension = Optional.ofNullable(properties.getDimension()).orElseGet(() -> embeddingModel == null ? null : embeddingModel.dimension());

return PgVectorEmbeddingStore.builder()
.host(dataSourceProperties.host())
.port(dataSourceProperties.port())
.user(dataSourceProperties.user())
.password(dataSourceProperties.password())
.database(dataSourceProperties.database())
.table(properties.getTable())
.createTable(properties.getCreateTable())
.dimension(dimension)
.useIndex(properties.getUseIndex())
.indexListSize(properties.getIndexListSize())
.build();
}

/**
* Check if the datasource is <code>postgresql</code>`.
* @param dataSource instance of {@link DataSource}.
* @return true means it is a postgresql data source, otherwise it is not.
*/
private boolean isPostgresqlDataSource(DataSource dataSource) {
try (Connection connection = dataSource.getConnection()) {
DatabaseMetaData metaData = connection.getMetaData();
return startsWithIgnoreCase(metaData.getURL(), "jdbc:postgresql");
} catch (SQLException e) {
log.warn("Exception checking datasource driver type during PgVector auto-configuration .");
return false;
}
}

/**
* Get the BeanName of the DataSource instance from the ApplicationContext.
* @param dataSource Target DataSource instance.
* @return bean name of target DataSource .
*/
private String getBeanNameForDataSource(DataSource dataSource) {
// Iterate through all DataSource beans to find the bean name that matches the current instance
return applicationContext.getBeansOfType(DataSource.class).entrySet().stream()
.filter(entry -> entry.getValue().equals(dataSource))
.map(Map.Entry::getKey)
.findFirst()
.orElse(null);
}
}
Original file line number Diff line number Diff line change
@@ -0,0 +1,85 @@
package dev.langchain4j.store.embedding.pgvector.spring;

import org.springframework.boot.context.properties.ConfigurationProperties;

@ConfigurationProperties(prefix = PgVectorEmbeddingStoreProperties.PREFIX)
public class PgVectorEmbeddingStoreProperties {

static final String PREFIX = "langchain4j.pgvector";

/**
* The pgvector database table.
*/
private String table;

/**
* The vector dimension.
*/
private Integer dimension;

/**
* Should create table automatically, default value is <code>false</code>.
*/
private Boolean createTable;

/**
* Should use <a href="https://github.com/pgvector/pgvector#ivfflat">IVFFlat</a> index.
*/
private Boolean useIndex;

/**
* The IVFFlat number of lists.
*/
private Integer indexListSize;

private String dataSourceBeanName;


public String getTable() {
return table;
}

public void setTable(String table) {
this.table = table;
}

public Integer getDimension() {
return dimension;
}

public void setDimension(Integer dimension) {
this.dimension = dimension;
}

public Boolean getCreateTable() {
return createTable;
}

public void setCreateTable(Boolean createTable) {
this.createTable = createTable;
}

public Boolean getUseIndex() {
return useIndex;
}

public void setUseIndex(Boolean useIndex) {
this.useIndex = useIndex;
}

public Integer getIndexListSize() {
return indexListSize;
}

public void setIndexListSize(Integer indexListSize) {
this.indexListSize = indexListSize;
}

public String getDataSourceBeanName() {
return dataSourceBeanName;
}

public void setDataSourceBeanName(String dataSourceBeanName) {
this.dataSourceBeanName = dataSourceBeanName;
}
}
Original file line number Diff line number Diff line change
@@ -0,0 +1 @@
dev.langchain4j.store.embedding.pgvector.spring.PgVectorEmbeddingStoreAutoConfiguration
Loading