Commit Graph

91 Commits

Author SHA1 Message Date
Mark Pollack
9392485bd5 Fix VectorStoreChatMemoryAdvisor streaming bug
- Override adviseStream method in VectorStoreChatMemoryAdvisor to properly handle streaming responses
- Add tests to verify the fix works with both normal and problematic streaming scenarios

Fixes #3152

Signed-off-by: Mark Pollack <mark.pollack@broadcom.com>
2025-05-16 09:26:27 -04:00
Mark Pollack
2f5d53fde0 Fix VectorStoreChatMemoryAdvisor streaming bug
- Override adviseStream method in VectorStoreChatMemoryAdvisor to properly handle streaming responses
- Add tests to verify the fix works with both normal and problematic streaming scenarios

Fixes #3152

Signed-off-by: Mark Pollack <mark.pollack@broadcom.com>
2025-05-16 14:08:20 +01:00
Soby Chacko
368be3a04f Fixing miscellaneous checkstyle errors
Enabling checkstyle by default in the project build

Signed-off-by: Soby Chacko <soby.chacko@broadcom.com>
2025-05-16 11:08:33 +01:00
Thomas Vitale
8939148fbc Fixes for memory advisors after recent refactoring
* The defaultConversationId was configurable, but not used. It’s now being used correctly when a custom defaultConversationId is defined.
* The memory advisors were missing the required configuration of a Schedule due to a default value missing. Now as default Scheduler is used, automatically protecting from blocking. It can be customised via “scheduler()”, replacing the old “protectFromBlocking()” method.
* The new defaultTopK options in VectorStoreChatMemoryAdvisor were documented, but not implemented. That is fixed now.
* The memory advisors were not null-safe. Now they are.
* Improved tests to check the null-safe behaviour.
* Updated the documentation accordingly.

Fixes gh-3133

Signed-off-by: Thomas Vitale <ThomasVitale@users.noreply.github.com>
2025-05-13 09:53:24 -04:00
Mark Pollack
848a3fd31f refactor: Simplify chat memory advisor hierarchy and remove deprecated API
- Remove deprecated ChatMemory.get(String conversationId, int lastN) method

- Replace AbstractChatMemoryAdvisor with BaseChatMemoryAdvisor interface in api package
- Make constructors private in all memory advisor implementations to enforce builder usage
- Rename CHAT_MEMORY_CONVERSATION_ID_KEY to CONVERSATION_ID and move to ChatMemory interface
- In VectorStoreChatMemoryAdvisor:
  - Rename DEFAULT_CHAT_MEMORY_RESPONSE_SIZE (100) to DEFAULT_TOP_K (20)
  - Rename builder method chatMemoryRetrieveSize() to topK()
  - Remove systemTextAdvise() builder method
- In PromptChatMemoryAdvisor:
  - Remove systemTextAdvise() builder method
  - Fix bug where only the last user message was stored from prompts with multiple messages
- Enhance logging in memory advisors to aid in debugging
- Add comprehensive tests for all advisor implementations:
  - Unit tests for builder behavior
  - Integration tests for the various chat memory advisors

Signed-off-by: Mark Pollack <mark.pollack@broadcom.com>
2025-05-12 19:41:18 -04:00
Soby Chacko
8f879aae03 GH-1831: Add auto-truncation support strategies when batching documents
Fixes: #1831

- Document auto-truncation configuration with high token limits
- Add integration tests for auto-truncation behavior
- Include Spring Boot and manual configuration examples
- Test large documents and batching scenarios

Enables proper use of embedding model auto-truncation while avoiding batching strategy exceptions.

Signed-off-by: Soby Chacko <soby.chacko@broadcom.com>
2025-05-10 17:57:49 -04:00
Thomas Vitale
4fe74d886e Remove deprecations in ChatClient and Advisors
* Update remaining Advisors and related classes to use the new APIs.
* In AbstractChatMemoryAdvisor, the “doNextWithProtectFromBlockingBefore()” protected method has been changed from accepting AdvisedRequest to ChatClientRequest. It’s a breaking change since the alternative was not part of M8.
* MessageAggregator has a new method to aggregate messages from ChatClientRequest. The previous method aggregating messages from AdvisedRequest has been removed. Warning since it wasn’t marked as deprecated in M8.
* In SimpleLoggerAdvisor, the “requestToString” input argument needs to be updated to use ChatClientRequest. It’s a breaking change since the alternative was not part of M8. Same thing about the constructor.
* The “getTemplateRenderer” method has been removed from BaseAdvisorChain. Each Advisor is encouraged to accept a PromptTemplate to achieve self-contained prompt augmentation operations.
* Remove deprecations in ChatClient and Advisors, and update tests accordingly.
* When building a Prompt from the ChatClient input, the SystemMessage passed via systemText() is placed first in the message list. Before, it was put last, resulting in errors with several model providers.

Relates to gh-2655

Signed-off-by: Thomas Vitale <ThomasVitale@users.noreply.github.com>
2025-05-06 09:58:06 +01:00
Mark Pollack
d45ff8e984 Refactorings
- Avoid overlapping package names
  Changed in spring-ai-commons package from org.sf.ai.model to org.sf.ai.content
  Refactor advisor module name to be spring-ai-advisors-vector-store
    Moved advisors into org.springframework.ai.chat.client.advisor.vectorstore

- Created top level memory directory
- Create new module spring-ai-model-chat-memory-neo4j and moved neo4j memory classes out of the vectorstore module
  Updated neo4j autoconfiguation
2025-04-04 11:44:38 -04:00
CChuYong
c02430ea6b Add PgIdType based schema generation for PgVectorStore
Signed-off-by: CChuYong <yeongmin1061@gmail.com>
2025-04-01 19:27:33 +01:00
CChuYong
268248ba3c Fix PgVectorStore doDelete function as batch
Signed-off-by: CChuYong <yeongmin1061@gmail.com>
2025-03-12 17:51:39 +00:00
Ilayaperumal Gopinathan
ded9facfe5 Remove deprecations from 1.0.0-M6
- Remove deprecations from models, vector stores and usage
- Deprecations from FunctionCallback and ObservationContext/Convention will be in a separate PR

Models updates
  - Remove AbstractToolCallSupport from the models which use ToolCallingManager
  - Remove deprecated constructors and their usage
  - Remove FunctionCallbackResolver and FunctionCallbacks usage in the models

- Add back deprecations for VectorStoreChatMemoryAdvisor until builder is fixed

- Update OpenAiPaymentTransactionIT to use ToolCallbackResolver in config

Signed-off-by: Ilayaperumal Gopinathan <ilayaperumal.gopinathan@broadcom.com>
2025-03-11 10:42:03 -04:00
Soby Chacko
8e23422dc0 Vector store classes checkstyle fix
Signed-off-by: Soby Chacko <soby.chacko@broadcom.com>
2025-02-18 19:40:22 -05:00
Soby Chacko
4d692a542b Add missing integration tests for delete by ID API in vector store implementations.
Extract common vector store delete tests to base class

This commit extracts shared delete operation tests into a reusable BaseVectorStoreTests class.
This reduces code duplication and provides a consistent test suite for delete operations across
different vector store implementations. The base class includes tests for:

Deleting by ID
Deleting by filter expressions
Deleting by string filter expressions

Most of the vector store implementation now extends this base class and inherits these
common tests while maintaining the ability to add vector store specific tests.

Adding javadoc

Signed-off-by: Soby Chacko <soby.chacko@broadcom.com>
2025-02-12 20:09:08 +00:00
Soby Chacko
3f0557b8b3 Vector store impls: code cleanup and checkstyle fixes
Signed-off-by: Soby Chacko <soby.chacko@broadcom.com>
2025-02-11 16:16:57 -05:00
ogbozoyan
cd871eaddc VectorStoreChatMemoryAdvisor constructors cleanup
- Deprecate all constructors except one with all fields
 - Update the build method to include order in the VectorStoreChatMemoryAdvisor's constructor
2025-02-06 17:32:42 +00:00
Soby Chacko
6035516044 GH-2165: Simplify VectorStore delete method to return void
- Change VectorStore.delete() and related implementations to return void instead of Optional<Boolean>
- Remove unnecessary boolean return values and success status checks across all vector store implementations
- Clean up tests by removing redundant assertions
- Implementations continue using runtime exceptions for error signaling

Signed-off-by: Soby Chacko <soby.chacko@broadcom.com>
2025-02-06 15:10:47 +00:00
Ilayaperumal Gopinathan
54f49b5580 Fix PgVectorAutoconfiguration to use PgIDType 2025-02-05 23:39:34 +00:00
jitokim
4dbe73433a Refactor ID handling for different IdType formats
- Add handling for UUID, TEXT, INTEGER, SERIAL, BIGSERIAL formats in `convertIdToPgType` function.
- Implemented type conversion logic based on the IdType value (UUID, TEXT, INTEGER, SERIAL, BIGSERIAL).
- Add unit tests to validate correct conversion for UUID and non-UUID IdType formats.
  - `testToPgTypeWithUuidIdType`: Validates UUID handling.
  - `testToPgTypeWithNonUuidIdType`: Validates handling for non-UUID IdTypes.

Signed-off-by: jitokim <pigberger70@gmail.com>
2025-02-05 23:39:34 +00:00
Ilayaperumal Gopinathan
2932769883 Switch back to use slf4j logging
- Revert the changes to update to use Apache Commons Logging and re-add the previously used slf4j logging
2025-02-03 15:31:43 -05:00
Soby Chacko
16a596f8b7 Add getNativeClient API to VectorStore interface
Adds getNativeClient API to VectorStore interface allowing access to the underlying native client implementation.

This change:
- Adds getNativeClient() default method to VectorStore interface returning Optional<T>
- Implements getNativeClient() in all vector store implementations exposing their respective native clients
- Adds integration tests verifying native client access for all implementations

Fixes: #2137

Signed-off-by: Soby Chacko <soby.chacko@broadcom.com>
2025-02-03 14:49:36 -05:00
Ilayaperumal Gopinathan
8303a52611 Use Apache Commons Logging
- Remove existing spring-boot-starter-logging
 - Update to use Springframework's LogAccessor to use commons logging

Resolves #2095
2025-01-28 11:00:05 +00:00
Soby Chacko
f588716b41 Add filter-based deletion and string filter API to VectorStore
Add string-based filter deletion alongside the Filter.Expression-based deletion
for vector stores. This provides a more convenient API for simple filter cases
while maintaining the full flexibility of expression-based filtering.

Key changes:
- Add delete(Filter.Expression) and delete(String) methods to VectorStore
- Add default string filter implementation in VectorStore interface
- Implement filter deletion in Chroma/Elasticsearch/PgVector stores
- Add integration tests for both filter APIs across implementations

This extends vector store deletion capabilities while maintaining consistent
behavior across implementations.
2025-01-24 14:15:46 -05:00
jitokim
822576bf91 Fix typo in PgDistanceType enum class
Signed-off-by: jitokim <pigberger70@gmail.com>
2025-01-24 16:59:00 +00:00
Ilayaperumal Gopinathan
224191aea7 Revert "Remove UUID Enforcement for ID Column in PGVectorStore"
This reverts commit bac507c62a.
2025-01-24 12:40:35 +00:00
jitokim
bac507c62a Remove UUID Enforcement for ID Column in PGVectorStore
Signed-off-by: jitokim <pigberger70@gmail.com>
2025-01-24 11:48:09 +00:00
Soby Chacko
9844a18983 Move batching strategy to base vector store builder
Moving BatchingStrategy configuration from individual vector store implementations
to the base AbstractVectorStoreBuilder to reduce code duplication and provide consistent
batching behavior across all vector stores.

The default TokenCountBatchingStrategy is now set in the base builder class.
2025-01-09 12:30:59 +00:00
Soby Chacko
6a5326816c Addressing vector store releated checkstyle issues 2025-01-08 16:55:19 -05:00
Soby Chacko
eff7a80b07 Remove vector store related deprecations introduced in 1.0.0-M5 2025-01-08 09:34:17 +00:00
Ilayaperumal Gopinathan
977500f7a1 Remove deprecated classes and methods in spring-ai-core
* Remove use of Document.getContext method from spring-ai-core, use getText
* Remove deprecated ChatOptionsBuilder class
* Remove deprecated FunctionCallingOptionsBuilder class
2025-01-06 16:57:55 -05:00
Ilayaperumal Gopinathan
7fe3b389c4 Fix checkstyle errors 2025-01-02 13:43:58 +00:00
Mark Pollack
3bb49c3fd6 Update class level javadoc in some vector stores to match builder signatures 2024-12-23 10:41:01 -05:00
Ilayaperumal Gopinathan
a0ef1179c4 Fix PgVectorStoreWithChatMemoryAdvisorIT
- Use the PgVectorStoreBuilder to create the instance of PgVectorStore
2024-12-20 20:38:41 +00:00
Ilayaperumal Gopinathan
2804604933 Refactor SearchRequest builder methods
- Add a new Builder inner class to move all the builder methods and deprecate the existing builder methods
 - Update docs and references
2024-12-20 19:35:17 +00:00
Soby Chacko
1a6e79cbb9 Enhance vector stores with consistent APIs and null safety
- Replace Document.getContent() with getText() across all vector store implementations
- Fix incorrect package declarations in package-info.java files
- Make builder constructors private and implement proper builder patterns
- Add @Nullable annotations for better null safety
- Simplify PineconeVectorStore builder API by requiring essential parameters in factory method
- Make static Map fields final
- Clean up code and improve JavaDoc documentation

The changes focus on making the vector store APIs more consistent,
type-safe, and maintainable while following best practices for
builder patterns and null safety.
2024-12-20 12:19:12 -05:00
Soby Chacko
ee8bf37359 Require essential dependencies in vector store builder constructors
This commit refactors the builder pattern implementation across all VectorStore
implementations to make the EmbeddingModel a required constructor parameter
rather than an optional builder method. Key changes include:

- Move embeddingModel from being a builder method to a required constructor parameter
- Make embeddingModel final in AbstractVectorStoreBuilder
- Remove redundant validate() methods since EmbeddingModel validation now happens
  in constructor
- Update all VectorStore builder instantiations to pass EmbeddingModel in builder
  creation
- Add @Nullable annotations to appropriate methods in VectorStore interface

This change improves the API design by:
1. Enforcing that EmbeddingModel is provided at builder creation time
2. Removing the possibility of forgotten EmbeddingModel configuration
3. Simplifying the builder implementation by moving validation to construction
4. Making the dependency on EmbeddingModel more explicit in the API

Breaking Changes:
- VectorStore builders must now be created with an EmbeddingModel parameter
- The embeddingModel() builder method has been removed from all implementations
2024-12-20 12:15:58 -05:00
Ilayaperumal Gopinathan
26fab03c2c Refactor VectorStoreObservationContext builder methods
This commit deprecates builder methods with the "with" prefix in the VectorStoreObservationContext class
and introduces new methods without the prefix for a cleaner API. For example:

withCollectionName() → collectionName()
withDimensions() → dimensions()
withNamespace() → namespace()

The old methods are marked as deprecated for maintaining backward compatibility.

All vector store implementations have been updated to use the new method names.
2024-12-18 18:15:09 -05:00
Mark Pollack
03a9379bb7 Refactor PgVector to package org.springframework.ai.vectorstore.pgvector 2024-12-14 16:45:06 -05:00
Mark Pollack
677a18e3d4 Update PgVector javadoc 2024-12-14 15:33:45 -05:00
Soby Chacko
257b963da9 PgVectorStore package rename and builder support
- Move PgVectorStore and related classes to org.springframework.ai.pg.vectorstore package
 - Update builder pattern to use more idiomatic method names (e.g. withSchemaName -> schemaName)
 - Deprecate existing constructors and old Builder class in favor of new static builder() method
 - Update tests to reflect the new builder style usage
 - Update docs
2024-12-14 15:24:14 -05:00
Mark Pollack
dfbc394f83 Make Document support single text or media content
The Document class previously allowed multiple media entries while also having a
text field, leading to ambiguity in content handling. This change enforces a
clear separation between text and media documents to prevent content type
confusion and simplify document processing.

A Document now must contain either text content or a single media entry, but
never both. This aligns with the class's primary use in ETL pipelines where
clear content type boundaries are essential for proper embedding generation and
vector database storage.

Additional architectural changes:
- Document now implements a cleaner API by removing deprecated methods
- Removed MediaContent interface implementation from Document class
- Document.getMedia() now returns a single Media object instead of Collection
- Removed EMPTY_TEXT constant in favor of proper null handling
- Constructor signatures simplified and streamlined
- Builder pattern improved to enforce single content type constraint

The breaking changes include:
- Media is now a single entry instead of a collection
- Content field renamed to text for clarity
- Removed support for mixed content types
- Simplified builder API to prevent ambiguous construction

Prefer using text-related methods over deprecated content methods to
better reflect the actual content type being handled and improve API clarity.
2024-12-09 23:25:38 -05:00
Ilayaperumal Gopinathan
ebd29e0959 GH-1826 Fix EmbeddingModel's usage on Document#embedding
- Since the Document object's reference to the `embedding` is deprecated and will be removed, the VectorStore implementations require a way to store the embedding of the corresponding Document objects

     - One way to fix this is, to have the EmbeddingModel#embed to return the embeddings in the same order as that of the Documents passed to it.

       - Since both the Document and embedding collections use the List object, their iteration operation will make sure to keep them in line with the same order.

       - A fix is required to preserve the order when batching strategy is applied.
	  - Updated the Javadoc for BatchingStrategy
          - Fixed the Document List order in TokenCountBatchingStrategy

    - Refactored the vector store implementations to update this change

Resolves #GH-1826
2024-12-05 21:37:27 +01:00
Thomas Vitale
fe58fd30eb Support similarity scores in Document API
Document
* Introduced “score” attribute in Document API. It stores the similarity score.
* Consolidate “distance” metadata for Documents. It stores the distance measurement.
* Adopted prefix-less naming convention in Document.Builder and deprecated old methods.
* Deprecated the many overloaded Document constructors in favour of Document.Builder.

Vector Stores
* Every vector store implementation now configures a “score” attribute with the similarity score of the Document embedding. It also includes the “distance” metadata with the distance measurement.
* Fixed error in Elasticsearch where distance and similarity were mixed up.
* Added missing integration tests for SimpleVectorStore.
* The Azure Vector Store and HanaDB Vector Store do not include those measurements because the product documentation do not include information about how the similarity score is returned, and without access to the cloud products I could not verify that via debugging.
* Improved tests to actually assert the result of the similarity search based on the returned score.

Signed-off-by: Thomas Vitale <ThomasVitale@users.noreply.github.com>
2024-12-02 14:54:28 -05:00
Christian Tzolov
0ca91b2ed9 fix: Resolve various javadoc and checkstyle issues 2024-11-16 11:06:14 +01:00
Thomas Vitale
cca430428e Support case with missing system text in VectorStoreChatMemoryAdvisor
The system text advise prompt is only joined with the value of the system text if it's non-null and non-empty.

Signed-off-by: Thomas Vitale <ThomasVitale@users.noreply.github.com>
2024-11-03 11:54:45 +01:00
Soby Chacko
e72ab6ba25 Addressing more checkstyle violations
- Enable checkstyle on more modules and adressing violations
review
2024-10-31 01:04:41 -04:00
Sébastien Deleuze
081840eef2 Skip tests requiring OpenAI API key
Adds @EnabledIfEnvironmentVariable annotation to integration tests that
use OpenAI embeddings. Tests will be skipped if OPENAI_API_KEY is not set,
making the build process more reliable for contributors who don't have
access to OpenAI services.
2024-10-29 12:15:44 -04:00
Soby Chacko
8e758dbd00 Introduce checkstyle plugin
- Based on https://github.com/spring-io/spring-javaformat
- In this iteration, checkstyles are only enabled for spring-ai-core
2024-10-24 16:43:59 -04:00
Sébastien Deleuze
f21b8a42b5 Refine Jackson ObjectMapper handling
ObjectMapper instantiation is costly, so unless its usage
is one-shot, it is better to create a reusable instance
for upcoming usage.

Also, before this commit, serialization of most Kotlin
classes was not supported due to the lack of proper
Jackson KotlinModule detection.

This commit:
 - Avoids per invocation ObjectMapper instantiation when
   relevant
 - Automatically detects and enables well-known Jackson
   modules including the Kotlin one
 - Removes org.springframework.ai.vectorstore.JsonUtils
   which looks not needed anymore

More optimizations are possible like reusing more
ObjectMapper instances, but this could introduce more breaking
changes so this commit intends to be a good first step.

Kotlin tests will be provided in a follow-up commit.

Additional changes:
 - Update ModelOptionsUtils to use JacksonUtils.instantiateAvailableModules()
 - Add missing license headers
 - Add missing author Javadoc comments
2024-10-24 09:20:47 +02:00
Thomas Vitale
012f07c97b Optimize Testcontainers config for VectorStores
* Unify image definition for vector stores in vector-store modules

* Unify image definition for vector stores in spring-ai-testcontainers module

Signed-off-by: Thomas Vitale <ThomasVitale@users.noreply.github.com>
2024-10-06 19:18:05 +02:00
Thomas Vitale
50e11e3f46 Improve optional values handling in vector store observations
Vector store observations support several key-value pairs, coming from the Spring AI abstractions. Currently, whenever a value is not available (either because not configured by the user or not supported by the vector store provider), span/metrics attributes are generated anyway with value none.

That causes several issues, including an unneeded increase in time series, challenges in alerting/monitoring (especially for integer/double attributes that suddenly are populated with a string), and non-compliance with the OpenTelemetry Semantic Conventions (according to which, attributes should be excluded altogether if there's no value).

This pull request changes the conventions for vector store observations to exclude the generation of span/metrics attributes for optional values which don't have any value.

Signed-off-by: Thomas Vitale <ThomasVitale@users.noreply.github.com>
2024-10-06 15:36:18 +02:00