Commit Graph

106 Commits

Author SHA1 Message Date
Thomas Vitale
4b123a7516 Use Double instead of Float for portable ChatOptions
This change updates the type of portable chat options from Float to
Double. Affected options include:
- frequencyPenalty
- presencePenalty
- temperature
- topP

The motivation for this change is to simplify coding. In Java, Float
values require an "f" suffix (e.g., 0.5f), while Double values don't
need any suffix. This makes Double easier to type and reduces
potential errors from forgetting the "f" suffix.

APIs, tests, and documentation have been updated to reflect this
change.

Fixes gh-712

Signed-off-by: Thomas Vitale <ThomasVitale@users.noreply.github.com>
2024-09-16 15:35:51 -04:00
Christian Tzolov
28276d14a4 Refactor Advisor Interfaces and add AroundAdvisor support
Refactoring and enhancements to the advisor functionality.

 New Advisor interfaces in the org.springframework.ai.chat.client.advisor.api package:
 - Advisor: Base interface for all advisor types.
 - RequestAdvisor: For advising on request data before execution.
 - ResponseAdvisor: For advising on response data after execution, with enhanced streaming modes.
 - CallAroundAdvisor and StreamAroundAdvisor: For around advice on synchronous and streaming requests respectively.
 - AroundAdvisorChain and DefaultAroundAdvisorChain: To manage chaining of around advisors.

 Advisor Chain and Prompt Generation:
 - Added the DefaultAroundAdvisorChain class to manage the sequence of advisors applied around chat model methods.
 - Adjusted the prompt generation (toPrompt) to integrate with the refactored AdvisedRequest object.

 Refactoring and Updates:
 - Replaced the deprecated RequestResponseAdvisor interface with RequestAdvisor and ResponseAdvisor across the spring-ai-core and test modules.
 - Updated the DefaultChatClient and related classes to use the new Advisor interface, improving modularity and consistency.
 - Refactored DefaultAdvisorSpec and DefaultChatClientRequestSpec to handle the new Advisor type, and revised advisor lists and methods accordingly.
 - Enhanced the handling of streaming responses, introducing StreamResponseMode for better control during streaming scenarios.
2024-09-05 12:35:34 -04:00
Christian Tzolov
bf8dabfb11 Improve stream advisor processing
* Fixes an issue with advisor name resolution
* Streamlines repeating code
* Add a new advisor strategy for ON_FINISH_REASON streaming responses, which is used by the Q&A advisor
* Improve observable instrumentation by passing the parent observation to the advisor observation
2024-09-03 21:41:36 -04:00
Thomas Vitale
036093a42b Enhance vector store observability support
* Consolidate usage of “db.collection.name” attribute to track table name, collection name, index name, document name, or whatever concept a vector database uses to store data. Removed “db.index” that was use sometimes instead of “db.collection.name”. This usage is in line with the OpenTelemetry Semantic Conventions.
* Configure query response content to be included as a “span event” instead of a “span attribute” if the backend system supports that, similar to how we do for the model observations.
* Structure vector store observation attributes in dedicated enums, including one for the Spring AI Kinds to avoid hard-coding the same value in a lot of places. This follows the OpenTelemetry Semantic Conventions as much as possible. Also, adopt Spring usual non-null-by-default strategy as much as possible.
* Align vector store conventions to the chat model ones, and follow alphabetical order for values. This is particularly useful for the convention classes, for which the Micrometer performance of exporting telemetry data improves when key values are added already sorted to the context.
* Fix flaky test in Mistral AI.
* Improve Qdrant integration tests.

Signed-off-by: Thomas Vitale <ThomasVitale@users.noreply.github.com>
2024-08-22 09:38:59 +02:00
Christian Tzolov
3b014db165 Add ChatClient Advisor Observability support
- Add advisor context, convetions and documentation
- Add ObservableRequestResponseAdvisor wrapper.
- Add Tests

Resolves #1258
2024-08-21 14:28:24 -04:00
Mark Pollack
dad30f06d9 Add ChatOptions to PromptTemplate create methods
Enable ChatOptions configuration when creating Prompts from Templates,

Co-authored-by: zhangqian9158 <zhangqian9158@users.noreply.github.com>
2024-08-20 18:19:14 -04:00
Vivek Alpeshbhai Sonani
528dc0438a Unit tests for Generation class 2024-08-20 15:37:43 -04:00
rivkode
1d6cce2419 Add JSON array handling to JsonReader
Enhance JsonReader to detect and process both JSON objects and arrays at
the root level. This update introduces type checking for the JSON root node
using JsonNode and leverages the Stream API to handle JSON arrays.

- Refactor parsing logic to support both JSON arrays and objects
- Rename variable: resourceArray to arrayResource for clarity
- Convert for-loop to Stream API for processing JSON keys
- Add additional tests to ensure proper array handling
2024-08-20 15:06:19 -04:00
Soby Chacko
949f1ed4e8 Add Batching strategy for embedding documents
- When embedding documents, allow batching the documents using some criteria.
 - `BatchingStrategy` interface with a `TokenCountBatchingStrategy` implementation that uses
   the openai max input token size of 8191 as the default.
 - Add a default method in EmbeddingModel to embed document using this new batching strategy.
 - Change `MilvusVectorStore` to make use of this new batching API.
 - Adding unit tests for `TokenCountBatchingStrategy`.
 - Adding openai integration test to call the embed API that uses batching.

Resolves https://github.com/spring-projects/spring-ai/issues/1214

Other vector stores will be updated seperately
2024-08-20 14:08:06 -04:00
Thomas Vitale
3b7522b6c0 Model observability for Anthropic
Signed-off-by: Thomas Vitale <ThomasVitale@users.noreply.github.com>
2024-08-20 01:13:43 -04:00
Thomas Vitale
3fa102e78f Prompt content and completion as span events
Signed-off-by: Thomas Vitale <ThomasVitale@users.noreply.github.com>
2024-08-20 00:59:43 -04:00
Christian Tzolov
bc3f9acb86 Add observability support to VectorStore
Implementation:
- Introduce AbstractObservationVectorStore with instrumentation for add, delete, and similaritySearch methods
- Create VectorStoreObservationContext to capture operation details
- Implement DefaultVectorStoreObservationConvention for naming and tagging
- Add VectorStoreObservationDocumentation for defining observation keys
- Create VectorStoreObservationAutoConfiguration for auto-configuring observations
- Add VectorStoreObservationProperties to control optional observation content filters
- Update VectorStore interface with getName() method
- Modify PgVectorStore and SimpleVectorStore to extend AbstractObservationVectorStore
- Add vector_store Spring AI kind

Filters:
- Implement VectorStoreQueryResponseObservationFilter
- Add VectorStoreDeleteRequestContentObservationFilter and VectorStoreAddRequestContentObservationFilter

Enhancements:
- Update PgVectorStoreAutoConfiguration to support observations
- Add observation support to PgVectorStore's Builder
- Add VectorStoreObservationContext.Operation enum with ADD, DELETE, and QUERY options

Tests:
- Add tests for VectorStore context, convention, and filters
- Add VectorStoreObservationAutoConfiguration tests
- Add PgVectorObservationIT

Resolves #1205
2024-08-16 10:33:50 -04:00
Christian Tzolov
d538e00643 Replace the Embedding format from List<Double> to float[]
- Adjust all affected classes including the Document.
 - Update docs.

Related to #405
2024-08-13 11:53:08 -04:00
Christian Tzolov
66e4b8868f Add ObservationRegistry support to ChatClient
- Implement observable chat responses in DefaultChatClient
 - Add ChatClientObservationContext and related classes for metrics
 - Update ChatClient and builder methods to support ObservationRegistry
 - Enhance RequestResponseAdvisor with getName() method
 - Add ChatClient streaming observability support
 - Introduce ChatClientObservationDocumentation for metric key names
 - Create DefaultChatClientObservationConvention for implementing conventions
 - Add ChatClientInputContentObservationFilter for optional input content logging
 - Update ChatClientAutoConfiguration to include new observation components
 - Extend ChatClientBuilderProperties with observation configuration options
 - Add unit tests for new observation classes and configurations
 - Update AiOperationType and AiProvider enums with new values
 - Implement safeguards and warnings for sensitive data in observations

 Resolves #1206
2024-08-11 18:26:53 +02:00
Thomas Vitale
bf84d5945e Streamline ChatOptions
* Surface more configuration APIs to ChatOptions
* Use abstraction in Observations directly instead of dedicated implementation
* Simplify metadata config in observations for defined models
* Improve merging of runtime and default options in OpenAI
* Fix missing option in Mistral AI

Relates to gh-1148

Signed-off-by: Thomas Vitale <ThomasVitale@users.noreply.github.com>
2024-08-10 14:48:05 +02:00
Christian Tzolov
91afed5ae5 OpenAi: Add support for structured outputs and JSON schema
- Added support for OpenAI's structured outputs feature, which allows specifying a JSON schema for the model to match
- Introduced new record to configure the desired response format
- Added support for configuring the response format via application properties or the chat options builder
- Extend teh BeanOutputConverter to help generate JSON schema from a target domain object and convert the response.
- Added comprehensive tests to cover the new response format functionality

Resolves #1196
2024-08-08 17:00:18 -04:00
Thomas Vitale
08ccc10a16 Streamline EmbeddingOptions
* Add model and dimensions to option abstraction
* Use abstraction in Observations directly instead of dedicated implementation
* Clean-up the merge of runtime and default embedding options in OpenAI

Relates to #gh-1148

Signed-off-by: Thomas Vitale <ThomasVitale@users.noreply.github.com>
2024-08-08 11:35:08 +02:00
Thomas Vitale
17ba1fc3ba Streamline ImageOptions
* Add style to option abstraction
* Use abstraction in Observations directly instead of dedicated implementation
* Clean-up the merge of runtime and default image options in OpenAI and Stability AI

Related to #1148

Signed-off-by: Thomas Vitale <ThomasVitale@users.noreply.github.com>
2024-08-07 10:19:08 +02:00
Thomas Vitale
8784dee16f Update convention for chat finish reason in LLM observations
Signed-off-by: Thomas Vitale <ThomasVitale@users.noreply.github.com>
2024-08-07 09:25:06 +02:00
Thomas Vitale
6bdb395686 Initial observability for Spring AI
* Observation APIs for chat, embedding and image models
* Conventions based on OpenTelemetry Semantic Conventions for GenAI
* Instrumentation for OpenAI chat, embedding, and image models
* Autoconfiguration for observability for OpenAI

Fixes gh-953

Signed-off-by: Thomas Vitale <ThomasVitale@users.noreply.github.com>
2024-08-01 22:25:43 +02:00
Mark Pollack
5aafea872d Improve Message object hierarchy
- SystemMessage no longer has Media
- Add MediaContent interface
- Clear redundant code
2024-07-19 23:05:46 +02:00
Veerendra Vellanki
60308eab77 register available modules with the object mapper
add tests
2024-07-19 13:05:20 +02:00
Christian Tzolov
edf943ec97 Adjust tests 2024-07-18 19:39:43 +02:00
Mark Pollack
97f443d615 Update to ResponseMetadata design
* Remove inheritance from HashMap
* No more subclasses per model provider
* Builder class for ChatResponse
* Fix the AbstractResponseMetadata#AI_METADATA_STRING parameter order
* ChatResponseMetadata ignore Null values.
2024-07-18 12:48:28 +02:00
Eddú Meléndez
0a42bf01f3 Fix assertions 2024-07-17 11:01:37 +02:00
Christian Tzolov
c70c20b79d Add VertexAI Embedding Model support
- add new spring-ai-vertex-ai-embedding project.
 - add VertexAiTextEmbeddingModel and VertexAiMultimodalEmbeddingMode with related options configuration classes.
 - add ITs
 - add auto-configuraiton and boot starters.
 - register to BOM.
 - add documentation.
 - add multimodal embedding documentation
 - extend the Embedding metdata so that it can keep references to the source document's data, Id, mediatype

 Resolves #1013
 Related to #1009
2024-07-10 15:36:13 -04:00
jiwoo
3bec210b80 Add additional tests for Document metadata and TextSplitter 2024-07-02 11:37:10 -04:00
Nicholas Zhan
5417d19d9a Fix prompt template validation if a variable name contains hyphen 2024-07-02 11:13:54 -04:00
Christian Tzolov
dfa3ceb1ab GH-912: Add customizable logger advisor (#913)
* Add customizable logger advisor
* Address review comments
* Use the OutputCaptureExtension to verify the output text

 Resolves #912
2024-06-21 10:26:18 -04:00
Craig Walls
5cf41f5215 Fix FILTER_EXPRESSION typo 2024-06-20 19:54:32 +02:00
Christian Tzolov
3cbda5acd8 Enable dynamic filter expressions for QuestionAnswerAdvisor
- Add FILTER_EXPRESSION advisor context parameter to update filter expressions per call/stream
 - Implement dynamic filter expression handling in QuestionAnswerAdvisor
 - Add unit tests for dynamic filter expression functionality
 - Update documentation with usage examples

 Resolves #887
2024-06-18 14:32:38 +02:00
Christian Tzolov
476164b6e3 Move the vector expression converters from core to their projects 2024-06-15 20:24:29 +02:00
Christian Tzolov
d6a0dffd3e Add ChatClient support for returning ResponseEntity<ChatResponse, T>
ChatClient already provides the .chatResponse() method to return the entire ChatResponse instance.
 It also provides a set of overloaded .entity(Type) methods to provide Type-converted responses.
 The new .responseEntity(Type) method returns a ResponseEntity<ChatResponse, T> instance, encapsulating
 both the ChatResponse and the requested Type-converted response entity.

 This change allows for more flexibility when handling different response types and facilitates
 easier integration with other components that expect ResponseEntity instances.
2024-06-04 14:36:21 +02:00
Mark Pollack
574138a26a Remove chat.service package and related classes
* This functionality is now provided using the advisors feature in ChatClient
2024-05-27 15:36:30 -04:00
Christian Tzolov
c4784a070f Add ChatClient plugable advisors support
- Add RequestResponseAdvisor interface with adviseReqeust and adviseResponse methods.
    The adviseRequest method takes and returns AdvisedRequest.
    The adviseResponse method takes and returns ChatRequest.
  - Add ChatClient#ChatClientRequets advisor(...) methods to register advisros.
    ChatClient call the registered advisors in order before sealing the ChatClientRequest into a Prompt and call the model
    and after the model response.
  - Implement PromptChatMemoryAdvisor that uses the ChatMemory and the systemem prompt.
  - Implement MessageChatMemoryAdvisor that usees the ChatMemory and the prompt messages.
  - Implement VectorStoreChatMemoryAdvisor that uses VecrStore for long term message history.
  - Add tests.
  - Add shared context to the RequestResponseAdvisor's flow, Context is shared between the request and the  response
  - Add advisor parameters that are passed through the context
2024-05-26 23:23:52 -04:00
Christian Tzolov
cd3b374dab Extend ChatClient API
- add support for custom StructuredOutputConverters usng entity(outputConverterInstance)
  - add mutate() method that returns ChatClient.Builder to create a new ChatClient whose
    settings are replicated from the ChatClient's default settings.
  - add prompt().mutate() method that returns ChatClient.Builder to create a new ChatClient
    whose settings are replicated from the current default and prompt settings.
2024-05-24 14:33:26 +02:00
Mark Pollack
4a2ad60059 Package refactoring
* Move ChatClient and related classes into the chat.client package
* Move ChatModel and related class into the chat.model package
* Smaller refactorings to remove DSM cycles
* Update README.md
2024-05-23 17:52:27 -04:00
Christian Tzolov
0571aac44c Add ChatClient.Builder auto-configuraiton support
- add ChatClinetCustomizer support.
  - add enable/disable property - enabled by default.
  - add ITs.

* Update README.md
2024-05-23 17:01:48 -04:00
Christian Tzolov
5f887b3eb6 Rename ChatClient.ChatClientBuilder to ChatClient.Builder 2024-05-23 16:33:33 +02:00
Christian Tzolov
d04f0694ed fix test 2024-05-23 15:39:34 +02:00
Christian Tzolov
6c9c766da6 Improve PrompTemplate paramters handling 2024-05-23 14:55:29 +02:00
Christian Tzolov
47c9fcea27 Add overload Resourse constructors for fluent API.
Fix issue with PromptTemplate failing on trailing parameters not used in the system/user text.
2024-05-23 11:18:15 +02:00
Josh Long
fbfc87e814 Refactoring of ChatClient to add fluent API and introduce Model as dependent object
* Rename the ModelClient class hierarchy into Model:
  - Rename ModelClient into Model. Update all code and doc references.
  - Rename ChatClient to ChatModel. Update all ChatClient suffixes and chatClient fields and variables in code and doc.
  - Rename EmbeddingClient into EmbeddingModel. Update the XxxEmbeddingClient class and variable suffixes and embeddingClient variables and fields in code and docs.
  - Rename ImageClient into ImageModel.
  - Rename SpeechClient into SpeechModel.
  - Rename TranscriptionClient into TranscriptionModel.
  - Update all javadocs and antora pages. Update the related diagrams.

* Create fluent API in ChatClient interface that now includes streaming support
* Add OpenAI FunctionCallbackWrapper2IT auto-config tests.
* Add ChatClientTest mockito testing.
* Add ChatModel#getDefaultOptions(), and remove @FunctionalInterface

* ChatModel enums extend the new ModelDescription interface.
* Implement fromOptions copy method in every ChatOptions implementation.
* Extend ChatClient to use the model default options if not provided explicitly.

* Update readme to provide guidance on how to adapt to breaking changes.

Co-authored-by: Christian Tzolov <ctzolov@vmware.com>
Co-authored-by: Mark Pollack <mpollack@vmware.com>
2024-05-22 16:07:12 -04:00
Christian Tzolov
517df45cd8 Merge ParametrizedTypeReferenceBeanOutputConverter into BeanOutputConverter
Add ParametrizedTypeReference constructoers along the Clas<T> such.
  Convert the Class into ParametrizedTypeReference internally.
  Update tests and docs.
2024-05-18 04:50:20 +02:00
Christian Tzolov
654e22be9d Add TypeReference StructuredOutputConverter
A ParameterizedTypeReference alternative of BeanOutputConverter that can cover list of beans as well.
  Based on suggestion: https://twitter.com/kisco_/status/1788862522998546440
2024-05-17 15:28:20 +02:00
Christian Tzolov
227f0703ec Fix: function calling not able to resolve input types
Resolves #726
2024-05-16 09:41:09 +02:00
Mark Pollack
867154c082 Changed ChatBot to ChatService with other related name changes
* PromptContext -> ChatServiceContext
* Added PromptChange to ChatServiceContext to capture PromptTransformer changes
* DefaultChatBot -> PromptTransformingChatService
* DefaultStreamingChatBot -> StreamingPromptTransformingChatService
* package name changes, chatbot->service and history->memory
* Added fluent builders to a few PromptTransformer implementations
* Add license headers
2024-05-15 14:01:48 +02:00
Mark Pollack
ad527303ed Rename Agent classes to use ChatBot 2024-05-08 15:43:00 -04:00
Mark Pollack
dfb8bf6a44 Add a new abstraction to simplify implementation of common ChatBot use cases
* Add ChatBot and basic DefaultChatBot
* Add streaming ChatBot support.
* Add Evaluator interface and RelevancyEvaluator implementation
* Add Content data type abstraction for Document and Message
* Renaming and package refactoring
* update .gitignore to allow node package name
* Add List<Media> to node and move ai.transformer package to ai.prompt.transformer
* Add Short/Long term memory support.
* Add mixing transformers support

Docs TBD
2024-05-08 15:14:50 -04:00
Christian Tzolov
a49a2d213f Replace the OutputParser by a StructuredOutputConverter API
- Old OutputParser, BeanOutputParser, ListOutputParser and MapOutputParser classes are depredated
   in favour of the new StructuredOutputConverter, BeanOutputConverter, ListOutputConverter and
   MapOutputConverter implementations.
   Later are drop-in replacements for the former ones, and provide the same functionality.
 - Keep the existing parser package and classes for backward compatibility.
 - Adjust the PromptTemplate for backward compatibility
 - Update all existing tests to use the new Structured Output API.
 - Improve the documentation for structured outputs.
2024-05-08 12:02:24 -04:00