Spring AI - Chat Model
ChatModel is the core model of the Spring AI project. It provides a simple and flexible way to create chatbots and conversational interfaces. The model is designed to be easy to use and extend, allowing developers to quickly build and deploy chatbots for a wide range of applications.
Maven Dependency
1 | <properties> |
Configuration
OpenAI Chat Properties are explained here https://docs.spring.io/spring-ai/reference/api/chat/openai-chat.html. use spring.ai.openai.api-key to define the OpenAI API key and spring.ai.openai.chat.options.model to define the model to use.
You can select between models such as: gpt-4o, gpt-4o-mini, gpt-4-turbo, gpt-3.5-turbo, and more. See the models page for more information.
1 | spring.ai.openai.api-key=YOUR_API_KEY |
API access cost a small fee. You can get a API key by signing up at https://platform.openai.com.
Usage
Spring will automatically create a ChatModel bean for you. You can inject this bean into your service or controller and use it to generate responses to user prompts.
You can use call method of ChatModel to call the OpenAI API and get the response.
1 |
|
At run-time, you can override the default options by adding request-specific options to the Prompt call.
1 | public String getResponse(String prompt) { |
PromptTemplate
You can use PromptTemplate to define a template for prompts. The template can include placeholders that will be replaced with values at run-time. This can be useful for generating prompts that are based on dynamic data.
1 | public String getNovelsToRead(String genre) { |