-
Notifications
You must be signed in to change notification settings - Fork 87
Add spring boot starter for pgvector. #76
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
Open
misselvexu
wants to merge
8
commits into
langchain4j:main
Choose a base branch
from
misselvexu:PR/2102
base: main
Could not load branches
Branch not found: {{ refName }}
Loading
Could not load tags
Nothing to show
Loading
Are you sure you want to change the base?
Some commits from the old base branch may be removed from the timeline,
and old review comments may become outdated.
Open
Changes from all commits
Commits
Show all changes
8 commits
Select commit
Hold shift + click to select a range
935eb58
Add spring boot starter for pgvector.
misselvexu 9ec840b
Optimise the configuration options that pgvector exposes to the user,…
misselvexu 7707c07
Optimize pgvector starter data source auto-configuration logic.
misselvexu 8d4045f
Remove redundant parameter legitimacy checks.
misselvexu 875b24a
Optimize support for multiple data sources and add additional test ca…
misselvexu ab0234d
Optimize code format.
misselvexu 833fd71
Merge branch 'main' into PR/2102
misselvexu fad53aa
Merge branch 'main' into PR/2102
misselvexu File filter
Filter by extension
Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
There are no files selected for viewing
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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> |
22 changes: 22 additions & 0 deletions
22
...in/java/dev/langchain4j/store/embedding/pgvector/spring/PgVectorDataSourceProperties.java
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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); | ||
} | ||
} |
133 changes: 133 additions & 0 deletions
133
.../langchain4j/store/embedding/pgvector/spring/PgVectorEmbeddingStoreAutoConfiguration.java
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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, | ||
@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); | ||
} | ||
} |
85 changes: 85 additions & 0 deletions
85
...ava/dev/langchain4j/store/embedding/pgvector/spring/PgVectorEmbeddingStoreProperties.java
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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; | ||
} | ||
} |
1 change: 1 addition & 0 deletions
1
...esources/META-INF/spring/org.springframework.boot.autoconfigure.AutoConfiguration.imports
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1 @@ | ||
dev.langchain4j.store.embedding.pgvector.spring.PgVectorEmbeddingStoreAutoConfiguration |
Oops, something went wrong.
Add this suggestion to a batch that can be applied as a single commit.
This suggestion is invalid because no changes were made to the code.
Suggestions cannot be applied while the pull request is closed.
Suggestions cannot be applied while viewing a subset of changes.
Only one suggestion per line can be applied in a batch.
Add this suggestion to a batch that can be applied as a single commit.
Applying suggestions on deleted lines is not supported.
You must change the existing code in this line in order to create a valid suggestion.
Outdated suggestions cannot be applied.
This suggestion has been applied or marked resolved.
Suggestions cannot be applied from pending reviews.
Suggestions cannot be applied on multi-line comments.
Suggestions cannot be applied while the pull request is queued to merge.
Suggestion cannot be applied right now. Please check back later.
Uh oh!
There was an error while loading. Please reload this page.