Commit Graph

1421 Commits

Author SHA1 Message Date
Soby Chacko
f5b00a027c Various checkstyle fixes 2024-11-18 19:17:09 -05:00
Christian Tzolov
c038526dd1 refactor(openai): consolidate token usage details and add audio tokens support
The commit restructures OpenAI token usage tracking by:
- Adding audio_tokens support in PromptTokensDetails
- Deprecating individual token getter methods in favor of consolidated records
- Introducing new PromptTokensDetails and CompletionTokenDetails records
- Updating tests to reflect the new structure

Resolves #1369 , #1720
2024-11-18 23:12:30 +01:00
jitokim
fb2e7528d0 Fix Anthropic issue using unsubscribed response body in exception message
Signed-off-by: jitokim <pigberger70@gmail.com>
2024-11-18 16:44:21 -05:00
jitokim
a7a1804fac Rename Cassandra TTL Property for Clarity
Rename `timeToLiveSeconds` to `timeToLive` in
`CassandraChatMemoryProperties` and associated code to prevent
misleading interpretation. This change addresses issue #1728, as
the property previously suggested values in seconds but expected
milliseconds.

Improve readability and ensure accurate configuration by aligning
the name with its behavior. Include updates to test cases to
validate the new property name and verify ISO 8601 format handling.

Fixes #1728

Signed-off-by: Jihoon Kim <pigberger70@gmail.com>
2024-11-18 16:24:08 -05:00
Christian Tzolov
432954dad7 Add Supplier and Consumer function callback support in function calling
Add support for no-argument Supplier and single-argument Consumer function
callbacks in the Spring AI core module. This enhancement allows:
- Registration of Supplier<O> callbacks with no input (Void) type
- Registration of Consumer<I> callbacks with no output (Void) type
- Support for Kotlin Function0 (equivalent to Java Supplier)
- Handle empty properties for Void input types in schema generation
- Enhance FunctionCallback builder to support Supplier/Consumer patterns

Additional changes:
- Add test coverage for both Supplier and Consumer callbacks in various scenarios
- Enhance TypeResolverHelper to support Consumer input type resolution
- Support lambda-style function declarations for improved ergonomics
- Add test cases for void input/output handling in OpenAI chat model
- Include examples of function calls without return values
- Add support for parameterless functions through Supplier interface

Add comprehensive documentation for the FunctionCallback API:
- Overview of the interface and its key methods
- Builder pattern usage with function and method invocation approaches
- Examples for different function types (Function, BiFunction, Supplier, Consumer)
- Best practices and common pitfalls
- Schema generation and customization options

Resolves #1718 , #1277 , #1118, #860
2024-11-18 15:54:21 -05:00
Emmanuel Ferdman
f9a9c02e2b Update Message.java reference
Signed-off-by: Emmanuel Ferdman <emmanuelferdman@gmail.com>
2024-11-18 11:20:05 +01:00
Ilayaperumal Gopinathan
4e3955eee9 Fix typo 2024-11-18 10:14:20 +00:00
coderamittad
24096b04bf Update getting-started.adoc 2024-11-18 07:49:53 +05:30
Christian Tzolov
bc24b4c45d docs: Clarify function calling concepts and usage patterns
Improves function calling documentation with clearer organization and examples:

- Reorganizes content into server-side and client-side registration sections
- Adds detailed examples for both function-invoking and method-invoking approaches
- Enhances tool context documentation with diagrams and usage examples
- Updates function-calling diagrams to reflect current implementation
2024-11-17 17:23:21 +01:00
Christian Tzolov
018257a605 fix: Resolve javadoc and maven confiuration issues 2024-11-16 12:43:27 +01:00
Christian Tzolov
0ca91b2ed9 fix: Resolve various javadoc and checkstyle issues 2024-11-16 11:06:14 +01:00
Christian Tzolov
75e3a08d7d refactor: revise function callback API deprecation messages and documentation
- Update deprecated annotation messages to correctly reference functions() instead of function()
- Add detailed documentation for FunctionCallback.Builder hierarchy
- Deprecate FunctionCallbackWrapper class in favor of Builder pattern
- Fix typos and improve code documentation
2024-11-16 07:28:56 +01:00
Josh Long
944fb996e4 Add extension function for Chatclient.CalLResponseSpec.entity(Class<?>)
- This makes ChatClient easier to use from Kotlin
2024-11-15 17:06:52 -05:00
Christian Tzolov
fb0d99dc37 Revamp function callback builder API
Introduces a simplified, type-safe builder pattern for function callbacks to
improve developer experience and code reliability. The new hierarchical API
separates concerns between direct function invocation and method reflection,
while providing better compile-time safety.

This change deprecates the older FunctionCallbackWrapper in favor of a more
intuitive FunctionCallback.Builder that better handles generic types via
ParameterizedTypeReference. It also adds automatic function description
generation as a fallback when none is provided, though explicit descriptions
are still recommended.

The update standardizes function callback handling across all AI model
implementations (OpenAI, Ollama, Minimax, etc.) and improves response
handling with configurable converters.

Core API Enhancements:

- New Builder Interface: Replaced FunctionCallbackWrapper.builder() with
   FunctionCallback.builder(), introducing a hierarchical approach that improves
   customization and type safety.
- Specialized Builders: Introduced FunctionInvokerBuilder for direct Function/BiFunction
   implementations and MethodInvokerBuilder for reflection-based invocations.
- Generic Type Support: Added ParameterizedTypeReference for better handling of generic parameters.
- Unified Method Definition: Merged method() and argumentTypes() into a single method() call
   for simplicity and type safety.
- Automatic Descriptions: Implemented auto-generation of function descriptions, with warnings
   to encourage explicit descriptions.
- Configurable Response Converters: Enhanced response handling with support for custom
   converters, reducing unnecessary JSON conversions.

Architecture Improvements:

- Established common Builder interface for shared properties
- Separated function object handling from constructor
- Added method-specific configuration (name, arg types, target)
- Added JSON schema generation support for ResolvableType
- Moved to standardized schema types across AI providers
- Set OPEN_API_SCHEMA as default for Vertex AI Gemini

Builder Pattern Standardization:

- Standardized builder method ordering across implementations
- Moved function() call after description() for consistency
- Improved function callback configuration with unified patterns
- Enhanced error handling and validation in DefaultFunctionCallbackBuilder

Deprecations:

- FunctionCallbackWrapper.Builder replaced by DefaultFunctionCallbackBuilder
- Removed CustomizedTypeReference in favor of ParameterizedTypeReference
- Deprecated older ChatClient API methods for function handling

Testing & Documentation:

- Updated all AI model implementations (OpenAI, Ollama, Minimax, Moonshot, ZhiPuAI)
- Added comprehensive integration tests for static/instance methods
- Added integration tests for auto-generated descriptions
- Updated documentation to reflect new builder pattern usage
- Added Kotlin extension for inputType() support

Co-authored-by: Sébastien Deleuze <sebastien.deleuze@broadcom.com>
2024-11-15 15:32:59 -05:00
Ilayaperumal Gopinathan
72c84fe8b8 Remove deprecated code from 1.0 M2 and before
- Remove deprecated types,methods and references
 - Remove usage of "Generation(String text)" and replace with
  "Generation(AssistantMessage)"
 - Remove MiniMaxApi,MootShotApi,OpenAiApi,ZhiPuAiApi
   ChatCompletionFinishReason's FUNCTION_CALL
 - Remove OllamaApi's deprecated types
 - Remove deprecated constructors from PostgresMlEmbeddingModel
 - Remove deprecated constructor from Media
 - Remove tokenNames usage from antlr4 FiltersLexer and FiltersParser
 - Remove deprecated methods from CassandraVectorStoreProperties
 - Remove deprecated constructor and static config class from QdrantVectorStore
 - Minor cleanups on removing deprecated models and versions
 - Remove old name for mixtral models

Resolves #1599
2024-11-15 14:28:21 -05:00
Gareth Evans
ea1871041c docs: document how to programatically configure vertex embeddings to use a service account 2024-11-15 17:49:10 +01:00
Sébastien Deleuze
f9734a35aa Add support for @Component to TypeResolverHelper 2024-11-15 17:21:20 +01:00
Gareth Evans
01fa511339 docs: correct code in vertex chat functions doc 2024-11-15 13:22:23 +00:00
Gareth Evans
b3e7efd3b9 feat: allow vertex embedding connection settings to be configurable 2024-11-15 12:35:27 +01:00
zhaojy01
382fbaca48 Set embedding field as retrievable in Azure Vector Store
Resolves #1628

In Azure Vector Store, the embedding field needs to be retrievable
for proper functionality. While SearchField class doesn't have a
'retrievable' property, the 'hidden' field serves the same purpose.

The fix sets hidden=false on the embedding field to make it retrievable.

Link: https://github.com/spring-projects/spring-ai/issues/1628
2024-11-14 17:53:27 -05:00
Ilayaperumal Gopinathan
a2e2696c04 Fix checkstyle errors 2024-11-14 21:57:57 +00:00
jitokim
3c14fa633a GH-1727 fix huggingface generate text
- Update GenerateResponse content schema type to array at openapi.json
   - Use CompatGenerateRequest instead of GenerateRequest for the TextGenerationInference API Request

Signed-off-by: jitokim <pigberger70@gmail.com>
2024-11-14 21:15:50 +00:00
Christian Tzolov
7474852b58 Move the advisor name to low cardinality key values
- Adviser name is moved from hight to low cardinality key values.
- Updated tests in  to reflect these changes, ensuring the new low cardinality key is correctly captured.

Resolves #1716
2024-11-14 11:47:28 -05:00
Mark Pollack
420bf5ed78 Remove files accidentally added to main 2024-11-13 17:58:20 -05:00
Ilayaperumal Gopinathan
a98c042960 Fix Chroma delete operation status check
Due to changes in Chroma v0.5.13 (chroma-core/chroma#2880), the delete
operation no longer returns values. This impacts our ChromaVectorStore's delete
functionality.

Now we need to check the HTTP status code instead to properly verify if the
delete operation succeeded.

Test suite has been updated.

Resolves #1529
2024-11-13 16:32:19 -05:00
Thomas Vitale
263fe2fba7 Modular RAG - Query Analysis
Query Analysis
* Introduce Query Analysis Module
* Define QueryTransformer API and TranslationQueryTransformer implementation
* Define QueryExpander API and MultiQueryExpander implementation
* Support QueryTransformer in RetrievalAugmentationAdvisor (support for QueryExpander will be in the next PR together with the needed DocumentFuser API).

Improvements
* Refine Retrieval and Augmentation Modules for increased robustness
* Expand test coverage for both modules
* Define clone() method for ChatClient.Builder

Tests
* Introduce “spring-ai-integration-tests” for full-fledged integration tests
* Add integration tests for RAG modules
* Add integration tests for RAG advisor

Query Analysis
* Introduce Query Analysis Module
* Define QueryTransformer API and TranslationQueryTransformer implementation
* Define QueryExpander API and MultiQueryExpander implementation
* Support QueryTransformer in RetrievalAugmentationAdvisor (support for QueryExpander will be in the next PR together with the needed DocumentFuser API).

Improvements
* Refine Retrieval and Augmentation Modules for increased robustness
* Expand test coverage for both modules
* Define clone() method for ChatClient.Builder

Tests
* Introduce “spring-ai-integration-tests” for full-fledged integration tests
* Add integration tests for RAG modules
* Add integration tests for RAG advisor

Relates to #gh-1603

Signed-off-by: Thomas Vitale <ThomasVitale@users.noreply.github.com>
2024-11-13 15:58:36 -05:00
Ilayaperumal Gopinathan
b4e0a4598e Update documentation for Milvus vector store
- Add custom field name properties
2024-11-13 12:04:34 +00:00
Mark Pollack
21fb6293ba Update readme to point to https://github.com/danvega/awesome-spring-ai for general project resources 2024-11-12 19:18:07 -05:00
Soby Chacko
c8a9b1640a Add builder pattern to ChromaVectorStore for better initialization control
The change addresses initialization issues when ChromaVectorStore is used outside
Spring context, particularly in scenarios where collections are created manually
before store instantiation. Previously, collection ID wasn't properly populated
when afterPropertiesSet() wasn't called by Spring container.

- Add builder pattern to ChromaVectorStore for better initialization control
- Add initialization flag to prevent multiple collection creation calls
- Add integration tests for builder pattern usage scenarios
- Add spring-ai-transformers dependency for testing
- Remove unused constants (SIMILARITY_THRESHOLD_ALL, DEFAULT_TOP_K)

Collection ID is now properly set regardless of whether the store is managed by
Spring or created manually, solving the 404 Not Found errors during document
insertion.

Fixes: #1240
2024-11-12 17:17:18 -05:00
Mark Pollack
a815d6e8ab Fix CI job 'docker-compose and testcontainers' to only run those modules IT tests 2024-11-12 17:08:34 -05:00
Mark Pollack
1d540a6dd1 CI Actions imporvements 2024-11-12 15:24:23 -05:00
Mark Pollack
6acd202c12 Comment out second tc/docker-compose job in CI 2024-11-12 07:09:10 -05:00
Mark Pollack
fce52cd9b2 Disable Ollama tests in CI 2024-11-11 16:34:18 -05:00
Mark Pollack
a98af02f62 Minimize time to run main CI build action
- Add maven properties for all vector stores such as
skip.vectorstore.azure-cosmos-db to control IT test execution
- Chroma and PGVector IT tests are enabled by default
- Docker Compose and Testcontainers module ITs are skipped by default
- Add parallel job to run docker-compose and testcontainers ITs
2024-11-11 16:19:08 -05:00
Soby Chacko
4de95b7708 Checkstyle fix 2024-11-11 10:50:31 -05:00
dafriz
5e86583679 Bump org.apache.tika to 3.0.0 2024-11-11 11:32:39 +00:00
Christian Tzolov
5f6b892eda Add function calling support to invoke methods with dynamic arguments and return values
This change enables more flexible integration between Spring AI and LLM function
calling capabilities while maintaining type safety and ease of use.

- Add new MethodFunctionCallback class to support method invocation via reflection
 - Supports both static and non-static method calls
 - Handles multiple parameter types including primitives, objects, collections
 - Supports empty parameters and empty response
 - Auto-generates JSON schema from method parameters
 - Special handling for ToolContext parameters
 - Builder pattern for easy configuration

- Add comprehensive unit tests for MethodFunctionCallback
- Add integration tests for MethodFunctionCallback with both Anthropic and OpenAI clients
- Add jackson-module-jsonSchema dependency
- Modify FunctionCallback to check for empty tool context

Testing coverage includes:
- Static method invocation scenarios
- Non-static method calls with various parameter types
- Void return type methods
- Complex parameter types (enums, records, lists)
- Tool context handling
- Error cases and validation

Add MethodFunctionCallback reference docs
2024-11-10 22:58:40 -05:00
Christian Tzolov
c24ef4e79a docs: enhance Bedrock Converse API documentation
- Add migration note recommending transition from InvokeModel to Converse API
- Update model configuration to remove default model ID
- Add AWS session token configuration for temporary credentials
- Improve documentation links and descriptions
2024-11-10 15:42:03 +01:00
Soby Chacko
5e1f681da2 Fix Ollama Kotlin function callback integration tests
- Add default values to KotlinRequest data class to fix Jackson deserialization
- Replace hardcoded model name with OllamaModel.LLAMA3_2 for consistency
- Extract common test setup into companion objects for Ollama tests
- Replace var with val using when expression in weather service
- Clean up imports and remove unused annotations
- Standardize property access using Kotlin conventions
2024-11-08 21:24:28 -05:00
Mark Pollack
634ac2019b Change env var OLLAMA_SKIP_CONTAINER to OLLAMA_WITH_REUSE in BaseOllamaIT 2024-11-08 15:58:44 -05:00
Mark Pollack
11d8591d84 Remove old @DisabledIf on KotlinIT Ollama tests 2024-11-08 15:54:19 -05:00
Mark Pollack
538e2860d1 Disable running Ollama IT tests 2024-11-08 14:54:42 -05:00
Mark Pollack
21fc653464 Improve Ollama test container management
This change simplifies how we manage Ollama containers in tests by moving
from manual toggles to environment variables for better control. Instead of
scattered container configuration, we now have:

- OLLAMA_WITH_REUSE: Toggle reuse of existing containers between tests
- OLLAMA_TESTS_ENABLED: Control test execution globally

The motivation is to make tests more reliable and easier to maintain.
Previously, developers had to modify code to run tests locally vs CI. Now
they can control this via environment variables.

We also introduce thread-safe API access and consistent default settings
across all test classes, removing duplicated configuration and potential
resource leaks.

This makes the test infrastructure more maintainable and provides clearer
separation between local development and CI environments.

Checkstyle fixes.

Make buildOllamaApiWithModel in BaseOllamaIT public and the related test changes.
2024-11-08 12:59:50 -05:00
Sébastien Deleuze
c3c95a82c1 Add Kotlin support and documentation
- Add support for proper Kotlin functions handling by adapting
  `kotlin.jvm.functions.Function1` to `java.util.function.Function` and
  `kotlin.jvm.functions.Function2` to `java.util.function.BiFunction`.
- Removes the dependency on Spring Cloud Function and
  `net.jodah:typetools` which are replaced by leveraging
  Spring Framework `ResolvableType` capabilities.
- Add a Kotlin extension function for
  `FunctionCallbackWrapper.Builder.withInputType` allowing to
  specify `withInputType<T>()` instead of `withInputType(T::class.java)`.
- Add Kotlin documentation.
2024-11-08 18:32:47 +01:00
d050150
78a2a2788b GH-1689 Handle StringIndexOutOfBoundsException in PagePdfDocumentReader
- Add test coverage to TextLine
    - Use char[] instead of String for TextLine
    - Optimise index handling when reading text lines

Resolves #1689
2024-11-08 17:28:32 +00:00
Soby Chacko
865d429451 Checkstyle changes 2024-11-08 15:18:35 +00:00
Ilayaperumal Gopinathan
c1fc687730 Update OpenAiChatModelResponseFormatIT with JSON order usecase
- Verify that the BeanOutputConverter converts with the right order as specified in the JSON schema

Update the BeanOutputConverterTest's test case to tweak the order for validation
2024-11-08 13:50:53 +00:00
Soby Chacko
79266be970 GH-1335: Add JSON schema property order support
Fixes: #1335

https://github.com/spring-projects/spring-ai/issues/1335

Add support for maintaining JSON property order in generated schemas using
@JsonPropertyOrder. Users can now control the order of properties in their
JSON schemas by annotating their classes/records with @JsonPropertyOrder.

- Add JacksonOption.RESPECT_JSONPROPERTY_ORDER to BeanOutputConverter
- Add test to verify schema property ordering
- Update documentation with property ordering example
2024-11-08 13:41:48 +00:00
Christian Tzolov
9fa89a2fd6 fix: Improve error resilience of the Bedrock stream handling
The changes include:

- Refactor the emitting of next, error, and complete events in the Bedrock stream handling to use a default EmitFailureHandler that retries for 10 seconds before failing.
  This helps improve the error resilience of the stream processing.
- Disable a couple of integration tests related to the COHERE_COMMAND_V14 model, as that model version is no longer supported.
- Adjust some configuration options in the Jurassic2 chat model integration test.

Also resolves #1679
2024-11-08 13:40:57 +00:00
Christian Tzolov
7895875ca2 Update README.md
Add a community driven spring-ai-examples entry to the README' code examples list.
2024-11-08 11:07:53 +01:00