Connect Java apps to ChatGPT using OpenAI and Spring Boot
If you've ever wanted to integrate OpenAI's ChatGPT features into your Java programs, you'll be happy to learn that Spring AI has made the process easier than ever.
And it's not just easier to connect Java apps to OpenAI using Spring AI. It provides support for the most popular AI models, including Anthropic, Ollama and models from Microsoft, Amazon and Google.
The ability to integrate text to image, audio transcription and chat completion to your existing Java applications is now easier than ever.
How to connect to OpenAI in Java
To connect a Spring Boot Java app to OpenAI's gpt-4o model, follow these simple steps:
- Create an OpenAI key and set up billing.
- Create a Spring Boot application that uses the OpenAI starter.
- Add your API key to the application.properties file.
- Autowire the OpenAiChatModel into a Spring component.
- Create a Prompt object with text to send to the GPT model.
- Obtain a ChatResponse by passing the Prompt to the chat model.
- Print the response to the client.
Query OpenAI in Java example
The code below shows a Java application querying OpenAI in a runnable, standalone Spring Boot application.
/* Simple Java to ChatGPT/GPT-4o program. */
@SpringBootApplication
public class SpringGpt5Application implements CommandLineRunner {
@Autowired
OpenAiChatModel chatModel;
@Override
public void run(String... args) throws Exception {
Prompt prompt = new Prompt("Tell me a joke that is funny!");
ChatResponse response = chatModel.call(prompt);
System.out.println(response.getResult().getOutput().getContent());
}
public static void main(String[] args) {
SpringApplication.run(SpringGpt5Application.class, args);
}
}
Customizing the GPT model in Spring
At minimum, for this example to work OpenAI API key must be listed in Spring's application.properties file. However, Spring AI provides a variety of properties that can be configured to customize your OpenAI model. The Spring configuration file used in this Java and OpenAI tutorial sets the OpenAI API key and downgrades the model to gpt-3.5-turbo, increases the temperature and limits the max tokens used by a chat.
spring.ai.openai.api-key=sk-proj-NMD_y-m
spring.ai.openai.chat.options.model=gpt-3.5-turbo
spring.ai.openai.chat.options.temperature=0.7
spring.ai.openai.chat.options.maxTokens=100
If you want to get into the AI space and integrate your code with various AI models including OpenAI's GPT, now is the time. The Spring AI tools make it incredibly easy to integrate AI technology into your Java apps.
Cameron McKenzie has been a Java EE software engineer for 20 years. His current specialties include Agile development; DevOps; Spring; and container-based technologies such as Docker, Swarm and Kubernetes.