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
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
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>
- 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
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>
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
- 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
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>
- 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
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.
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.
- 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
- Disable project-wide Checkstyle checks to unblock development
- Add documentation for enabling Checkstyle locally
- Fix remaining checkstyle violations in current codebase
Fixes#1669
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.
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
- Remove @NestedConfigurationProperty and @ConstructorBinding annotations from model options classes
- Remove spring-boot dependency from spring-ai-openai module
- Add exclusion for spring-boot-autoconfigure in spring-cloud-function-context dependency
- Move configuration metadata to spring-ai-spring-boot-autoconfigure module
This change decouples the core AI model implementations from Spring Boot,
making the core modules more lightweight and allowing them to be used in
non-Spring Boot applications. Configuration properties are now handled by
the spring-ai-spring-boot-autoconfigure module instead.
Fixes#1540
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.
- Update Claude 3.5 Sonnet model version from 20240620 to 20241022 across:
- AnthropicApi model definitions
- Integration tests
- Sample events JSON
- Documentation pages
- Upgrade Ollama container to 0.3.14 in tests
- Add llama3.2:1b model to Ollama tests
- Convert Ollama functionCallTest to parameterized test
- Add PromptTokensDetails record to track cached tokens in prompt
- Update Usage record to include promptTokensDetails field
- Add getCachedTokens() method to OpenAiUsage
- Add test cases for cached tokens handling
Resolves#1506
- Remove unnecessary spring-web dependencies
- Update third-party library versions
- Refactor API classes to use consistent header handling
- Remove ApiUtils class and inline its functionality
- Adjust RestClient and WebClient builder usage in autoconfiguration
- Replace direct RestClient.Builder injections with ObjectProvider<RestClient.Builder>
and WebClient.Builder injections with ObjectProvider<WebClient.Builder>
- Update ChromaVectorStoreAutoConfiguration to use ObjectProvider
- Rename MongoDbAtlasLocalContainerConnectionDetailsFactoryTest to IT
- Switch spring-ai-chroma-store dependency from spring-web to spring-webflux
- Simplify ChromaApi constructor by using method reference for default headers
- Adjust import order
Resolves#1066Resolves#524
- Replaced `Map<String, Object>` with `ToolContext` in the `FunctionCallback`, `AbstractFunctionCallback`, and related classes.
- Updated all BiFunction definitions to use `ToolContext` as the second parameter,
enhancing the clarity and structure of the tool context management.
- Modified `FunctionCallbackWrapper` and `FunctionCallbackContext` to adapt to the new `ToolContext` parameter.
- Adjusted the handling of tool context in the documentation and test classes.
- Updated relevant test cases to reflect the API changes and modified the function handling logic to ensure consistency.
- Introduce toolContext to ChatClient, DefaultChatClient, and AdvisedRequest
- Add methods to set and manage toolContext via the FunctionCallingOptions
- Update tests to include toolContext in relevant scenarios
- Implement toolContext handling in function calling options