Commit Graph

500 Commits

Author SHA1 Message Date
Ilayaperumal Gopinathan
3b95dfd87f Fix checkstyle errors 2024-11-19 23:29:36 +00:00
Ilayaperumal Gopinathan
3812d2e6d8 Remove explicit ChatOptions for the models using FunctionCallingOptions
- Since FunctionCallingOptions already extends ChatOptions,
   removing explicit usage of ChatOptions in the Model Options classes
2024-11-19 18:02:54 -05:00
Christian Tzolov
0eacc9193b feat(tools): Add tool call history to ToolContext
- Add TOOL_CALL_HISTORY constant to store tool call history
- Extend ToolContext with getToolConversationHistory method
- Include tool call history in tool context during function execution
- Add test coverage for tool call history verification

Resolves #1202
2024-11-19 22:50:38 +00:00
Soby Chacko
edc70031dc Remove Boot dependency from core anthropic and watson modules
Fixes: #1591
2024-11-19 17:05:41 -05:00
Gareth Evans
a7b5652790 Upgrade azure-openai library to beta.12
- Correct merge utils after lib update
2024-11-19 15:11:23 -05:00
Mark Pollack
aff18bfca9 Fixes for Azure OpenAI ITs 2024-11-19 14:43:22 -05:00
jitokim
1298a28216 add OllamaChatModelTests
Signed-off-by: jitokim <pigberger70@gmail.com>
2024-11-19 16:13:47 +00:00
jitokim
08b0c30c9e Fix duplicate keys in ChatResponseMetadata for OllamaApi.ChatResponse metadata
Fix assertion in contructor of OllamaChatModel

Signed-off-by: jitokim <pigberger70@gmail.com>
2024-11-19 16:13:47 +00:00
jitokim
d8583271c7 fix callback merging in AzureOpenAiChatModel constructor
and minor fixes

Signed-off-by: jitokim <pigberger70@gmail.com>
2024-11-19 09:12:51 +01:00
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
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
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
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
b3e7efd3b9 feat: allow vertex embedding connection settings to be configurable 2024-11-15 12:35:27 +01: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
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
Mark Pollack
1d540a6dd1 CI Actions imporvements 2024-11-12 15:24:23 -05:00
Soby Chacko
4de95b7708 Checkstyle fix 2024-11-11 10:50:31 -05: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
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
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
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
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
Ilayaperumal Gopinathan
35f46e957f Fix javadoc at ResponseFormat class' HTML elements 2024-11-07 20:06:53 +00:00
liugddx
f924502791 Support single object tool_calls in OpenAI vendor APIs
XFY Spark and possibly other vendors implement the OpenAI interface but return
tool_calls as a single object rather than an array. Add @JsonFormat annotation
to handle both array and single object responses in ChatCompletionMessage,
making Spring AI more broadly compatible with OpenAI API implementations.

Only ChatCompletionMessage.java required modification to support this alternate
format while maintaining backward compatibility with the standard OpenAI API
response structure.

Co-authored-by: jito <pigberger70@gmail.com>
2024-11-07 13:13:49 -05:00
Christian Tzolov
83f7164bff Extract ResponseFormat to standalone class
- Extracts ResponseFormat from being a nested record in OpenAiApi to
   a dedicated class with builder pattern support.
 - Resolve the issue with constructor bindings for the Boog property
   binding.
 - Re-enables previously disabled response format integration tests.

 - Add checkstyle changes
 - Add schema field in ResponseFormat and set jsonSchema via the setter for schema,
   this way schema set via a Boot property also sets the correct JsonSchema
 - Add default constructors in ResponseFormat and JsonSchema

 Resolves #1681
2024-11-06 17:50:23 -05:00
Anders Swanson
fb65ed01bd Add OCI GenAI Cohere Chat integration
Adds Oracle Cloud Infrastructure (OCI) Generative AI's Cohere chat model support
to expand Spring AI's cloud provider capabilities. This allows developers to use
OCI's managed Cohere models through both dedicated and on-demand serving modes.

The integration provides auto-configuration for simple setup while allowing full
customization of model parameters through OCICohereChatOptions. Teams can now
use OCI's Cohere models alongside other providers in Spring AI applications.

This change complements the existing OCI embedding support, offering a complete
set of GenAI capabilities for Oracle Cloud users.

Signed-off-by: Anders Swanson <anders.swanson@oracle.com>
2024-11-06 17:43:48 -05:00
VictorZalevski
cd886437eb Improve usage field to include new properties
OpenAI's API returns additional token usage metrics that provide deeper
insight into API consumption. This adds support for:

- acceptedPredictionTokens: Tokens from accepted model predictions
- audioTokens: Tokens used for audio processing
- rejectedPredictionTokens: Tokens from rejected model predictions

These fields help track resource utilization and costs more accurately
by breaking down token usage by type. Added @JsonIgnoreProperties to
maintain compatibility with future OpenAI API additions.

Fixes warning logging in RetryUtils.SHORT_RETRY_TEMPLATE to reduce noise
in test output.
2024-11-06 14:53:17 -05:00
Mark Pollack
2a6f55a8c5 Use shorter retry intervals in tests
The DEFAULT_RETRY_TEMPLATE uses exponential backoff starting at 2s with max 3min
delay between retries, making tests run unnecessarily long. This change
introduces SHORT_RETRY_TEMPLATE with fixed 100ms backoff to speed up test
execution while preserving the same retry behavior and error handling.
2024-11-06 13:29:37 -05:00
Mark Pollack
0b4f90e8c0 wip 2024-11-06 13:15:16 -05:00
Christian Tzolov
3fbc310ff4 Allow null or empty userText if request contains Tool Response message
- Add a new test case for testing function call with advisor in BedrockConverseChatClientIT
- Add a new test case for testing tool proxy function call in OpenAiChatClientProxyFunctionCallsIT
- Remove unused model property from BedrockConverseProxyChatProperties
2024-11-06 18:20:29 +01:00
Soby Chacko
66f58d2d70 Change default build setting to disable Checkstyle enforcement
- Disable project-wide Checkstyle checks to unblock development
- Add documentation for enabling Checkstyle locally
- Fix remaining checkstyle violations in current codebase

Fixes #1669
2024-11-05 10:43:38 -05:00
Christian Tzolov
d0312ba426 Add @JsonIgnore annotation to jsonSchema field in AI provider APIs
Add @JsonIgnore annotation to the jsonSchema field in Function classes across
multiple AI provider APIs (MiniMax, MistralAI, OpenAI, ZhiPuAI) to exclude
it from JSON serialization.
2024-11-05 12:56:23 +01:00
Christian Tzolov
fd8cac57bb Revert "Revert "Convert API records to POJOs and fix failing autconfig tests""
This reverts commit 3e9a3fd3b0.
2024-11-05 11:52:41 +01:00
Christian Tzolov
3e9a3fd3b0 Revert "Convert API records to POJOs and fix failing autconfig tests"
This reverts commit 4184af5341.
2024-11-05 10:00:57 +01:00
Ilayaperumal Gopinathan
d44a6aff7c GH-924 Remove PaLM API support
https://github.com/spring-projects/spring-ai/pull/1664

  - As a follow up to decommission the PaLM API, the PaLM API support is removed.
  - Remove the model and vector store classes
  - Remove the documentation entries
  - Reference: https://ai.google.dev/palm_docs/deprecation

Resolves #924
2024-11-04 15:22:50 -05:00
jitokim
166e3d5f37 Fix incorrect logger class initialization
Signed-off-by: jitokim <pigberger70@gmail.com>
2024-11-04 12:53:59 +00:00
Ilayaperumal Gopinathan
8becbbba3b Fix javadoc errors at BedrockProxyChatModel
- Removed invalid parameters
2024-11-04 12:08:44 +00:00
Mark Pollack
ff41a1a529 Disable OracleVectorStore and Ollama IT tests 2024-11-03 18:55:09 -05:00
Christian Tzolov
0d2d4b7385 Add Bedrock Converse API chat model support
Introduces support for Amazon Bedrock Converse API through a new BedrockProxyChatModel
implementation. This enables integration with Bedrock's conversation models with features
including:
- Support for sync/async chat completions
- Stream response handling
- Tool/function calling capabilities
- System message support
- Image input support
- Observation and metrics integration
- Configurable model parameters and AWS credentials

Adds core support classes:
- BedrockUsage: Implements Usage interface for token tracking
- ConverseApiUtils: Utility class for handling Bedrock API responses including:
  - Tool use event aggregation and processing
  - Chat response transformation from stream outputs
  - Model options conversion
  - Support for metadata aggregation
- URLValidator: Utility for URL validation and normalization with support for:
  - Basic and strict URL validation
  - URL normalization
  - Multimodal input handling
- Enhanced FunctionCallingOptionsBuilder with merge capabilities for both ChatOptions
  and FunctionCallingOptions
- Added BEDROCK_CONVERSE to AiProvider enum for metrics tracking
- Extended AWS credentials support with session token capability
- Added configurable session token property to BedrockAwsConnectionProperties

Adds new auto-configuration support:
- BedrockConverseProxyChatAutoConfiguration for automatic setup of the Bedrock Converse chat model
- BedrockConverseProxyChatProperties for configuration including:
  - Model selection (defaults to Claude 3 Sonnet)
  - Timeout settings (defaults to 5 minutes)
  - Temperature and token control
  - Top-K and Top-P sampling parameters
- Integration with existing BedrockAwsConnectionConfiguration for AWS credentials

Updates to testing infrastructure:
- Adds comprehensive test suite for Bedrock Converse properties and auto-configuration
- Integration tests for chat completion and streaming scenarios
- Property validation tests for configuration options
- Temporarily disabled other Bedrock tests due to AWS quota limitations
- Added ObjectMapper configuration for proper JSON handling

Added new spring-ai-bedrock-converse-spring-boot-starter module

Updates module configuration in parent POM and BOM to include new bedrock-converse
modules and starters. Adds necessary auto-configuration imports for seamless integration
with Spring Boot applications.

Unrelated changes:
- Disabled several Bedrock model tests (Jurassic2, Llama, Titan) due to AWS quota limitations
- Disabled PaLM2 tests due to API decommissioning by Google

Resolves #809, #802

Add docs and fix configs

- Move timeout configuration from chat properties to connection properties
- Add comprehensive documentation for Bedrock Converse API usage and configuration
- Update tests to reflect configuration changes

Co-authored-by: maxjiang153 <maxjiang153@users.noreply.github.com>

Standardize AWS credential handling in integration tests

- Improve how we manage AWS credentials across our integration test
suite and ensures consistent test configuration. We're replacing individual
environment variable checks with @RequiresAwsCredentials
annotation and standardizing the use of BedrockTestUtils for context creation
in tests

We also align all AWS regions to US_EAST_1 for consistency and add missing
dependency versioning for Oracle Free.

These changes make our AWS tests more easier to maintain.

Key changes:
- Replace @EnabledIfEnvironmentVariable with @RequiresAwsCredentials
- Standardize context creation via BedrockTestUtils
- Set AWS region to US_EAST_1
- Add Oracle Free dependency version in pom.xml
2024-11-03 17:10:24 -05:00
Mark Pollack
0c07edc2e7 Revert back to previous OpenAiApi implementation and disable config prop tests 2024-11-02 16:16:22 -04:00
Soby Chacko
4184af5341 Convert API records to POJOs and fix failing autconfig tests
Following removal of Spring Boot's ConstructorBinding, convert record types
to regular POJOs to maintain JSON serialization. Update API classes:

- Convert FunctionTool and Function records to standard Java classes with
 getters/setters
- Update test assertions to use getter methods instead of record accessors
- Fix failing tests in MiniMax, OpenAi and ZhiPu API implementations

This keeps core API models independent of Spring Boot while ensuring proper
serialization through standard Java beans.

- MistralAIApi FunctionTool ConstructorBinding removal changes
2024-11-02 15:04:06 -04:00
Soby Chacko
254239cfe0 More checkstyle fixes 2024-11-01 12:25:19 -04:00