Getting Started with Spring AI Project: Your First Project Setup

Spring AI Project: In the rapidly evolving world of technology, integrating AI capabilities into your projects is becoming increasingly essential.

 

One of the powerful tools available for developers is Spring AI, a framework that simplifies the integration of AI services into Spring-based applications.

In this guide, we’ll walk through what Spring AI is, how to set up your first project using Spring AI, and how to configure it to work with OpenAI.

Spring AI is a specialized extension of the Spring framework, designed to make it easier for developers to incorporate AI into their applications.

It offers a robust and flexible platform to integrate various AI models and services, streamlining the process of adding intelligent features to your applications.

Whether you’re building chatbots, recommendation systems, or any AI-driven feature, Spring AI provides the tools you need.

Getting started with Spring AI is straightforward. Here are the steps you need to follow:

  • Set Up Your Development Environment:
    • Ensure you have the latest version of the Spring Tool Suite (STS) or IntelliJ IDEA installed.
  • Project Structure:
    • Start by creating a new Spring Boot project.
    • Include the necessary dependencies, such as spring-ai-starter and openai-java (if you’re integrating OpenAI).
				
					<?xml version="1.0" encoding="UTF-8"?>
<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
	xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 https://maven.apache.org/xsd/maven-4.0.0.xsd">
	<modelVersion>4.0.0</modelVersion>
	<parent>
		<groupId>org.springframework.boot</groupId>
		<artifactId>spring-boot-starter-parent</artifactId>
		<version>3.3.1</version>
		<relativePath/> <!-- lookup parent from repository -->
	</parent>
	<groupId>com.example</groupId>
	<artifactId>SpringAI</artifactId>
	<version>0.0.1-SNAPSHOT</version>
	<name>SpringAI</name>
	<description>Demo project for Spring Boot</description>
	<url/>
	<licenses>
		<license/>
	</licenses>
	<developers>
		<developer/>
	</developers>
	<scm>
		<connection/>
		<developerConnection/>
		<tag/>
		<url/>
	</scm>
	<properties>
		<java.version>17</java.version>
		<spring-ai.version>1.0.0-M1</spring-ai.version>
	</properties>
	<dependencies>
		<dependency>
			<groupId>org.springframework.boot</groupId>
			<artifactId>spring-boot-starter-web</artifactId>
		</dependency>
		<dependency>
			<groupId>org.springframework.ai</groupId>
			<artifactId>spring-ai-openai-spring-boot-starter</artifactId>
		</dependency>

		<dependency>
			<groupId>org.springframework.boot</groupId>
			<artifactId>spring-boot-devtools</artifactId>
			<scope>runtime</scope>
			<optional>true</optional>
		</dependency>
		<dependency>
			<groupId>org.springframework.boot</groupId>
			<artifactId>spring-boot-configuration-processor</artifactId>
			<optional>true</optional>
		</dependency>
		<dependency>
			<groupId>org.springframework.boot</groupId>
			<artifactId>spring-boot-starter-test</artifactId>
			<scope>test</scope>
		</dependency>
	</dependencies>
	<dependencyManagement>
		<dependencies>
			<dependency>
				<groupId>org.springframework.ai</groupId>
				<artifactId>spring-ai-bom</artifactId>
				<version>${spring-ai.version}</version>
				<type>pom</type>
				<scope>import</scope>
			</dependency>
		</dependencies>
	</dependencyManagement>

	<build>
		<plugins>
			<plugin>
				<groupId>org.springframework.boot</groupId>
				<artifactId>spring-boot-maven-plugin</artifactId>
			</plugin>
		</plugins>
	</build>
	<repositories>
		<repository>
			<id>spring-milestones</id>
			<name>Spring Milestones</name>
			<url>https://repo.spring.io/milestone</url>
			<snapshots>
				<enabled>false</enabled>
			</snapshots>
		</repository>
	</repositories>

</project>

				
			
  • Configuration with OpenAI:
    • To utilize OpenAI within your Spring AI project, you’ll need to configure your API keys.

  • Key Configuration Steps:
    • Creating a Secret API Key in OpenAI:
      • Sign in to your OpenAI account or create a new account if you don’t have one.
      • Navigate to the API section of your OpenAI dashboard.
      • Click on “Create New Secret Key.” A pop-up will appear with your new API key.
      • Important: Copy this key immediately, as you won’t be able to see it again. This key is what you’ll use to authenticate your Spring AI project with OpenAI.
  • Adding Balance to Your OpenAI Account:
      • OpenAI’s API services are not free, so you’ll need to add balance to your account to start using them.
      • Go to the Billing section of your OpenAI dashboard.
      • Choose a payment method and add funds to your account. You can select from various payment options like credit cards or PayPal.
      • Monitor your usage and balance regularly to avoid interruptions in service.
  • API Key Setup
    • In your application.properties, add the line: openai.api.key=your-api-key-here.
				
					spring.application.name=SpringAI
spring.ai.openai.api-key=api-key
spring.ai.openai.chat.options.model=gpt-4o-mini
				
			
  • Bean Configuration:
    • Create a configuration class to define the beans necessary for interacting with OpenAI’s API.
    • We will create a chatbot. Create a bean of ChatClient.
    • Here’s an configuration class:
				
					package com.example.demo.config;

import org.springframework.ai.chat.client.ChatClient;
import org.springframework.ai.openai.api.OpenAiApi;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;

@Configuration
public class SpringAIConfig {

	@Value("${spring.ai.openai.api-key}")
    private String apiKey;
	
	@Bean
	OpenAiApi openAiApi() {
		return new OpenAiApi(apiKey);
	}
	
	@Bean
    ChatClient chatClient(ChatClient.Builder builder) {
        return builder.build();
    }
	
}

				
			
  • Service Class :
    • Here’s an service class that interacts with OpenAI’s API using the Spring AI framework:
				
					package com.example.demo.service;

import java.util.Map;

import org.springframework.ai.chat.client.ChatClient;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

@Service
public class SpringAIService {

	@Autowired
	ChatClient chatClient;

	public Map<String, String> getdummyChatResponse(String message) {
		return Map.of("completion", chatClient.prompt().user(message).call().content());
	}

}

				
			

Controller Class: Here’s a controller class to handle requests and interact with the AI service:

				
					package com.example.demo.controller;

import java.util.Map;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.HttpStatus;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;

import com.example.demo.service.SpringAIService;

@RestController
public class SpringAIController {

	@Autowired
	SpringAIService aiService;

	@GetMapping("/ai")
	ResponseEntity<Map<String, String>> completion(
			@RequestParam(value = "message", defaultValue = "Tell me a joke") String message) {

		return new ResponseEntity<Map<String, String>>(aiService.getdummyChatResponse(message), HttpStatus.OK);
	}
}

				
			
  • Starting Your Application and Testing with Postman
    • Now that your project setup is ready, it’s time to start your Spring Boot application and test the AI integration.
    • To start your project right click on project select run as spring boot app.
  • Testing with Postman or any API Testing Tool:
    • Open Postman (or your preferred API testing tool).
    • Create a new GET request with the following URL:
				
					http://localhost:8080/ai?message=Your prompt here
				
			
    • Replace Your prompt here with any text you’d like to use as input for the AI model.
    • Click Send to execute the request.
    • The response should return the AI-generated text based on your input prompt.

Conclusion

Congratulations! You’ve successfully set up your first Spring AI project and integrated it with OpenAI.

By following this guide, you’ve not only configured your development environment and added essential dependencies but also learned how to secure your application with an API key and ensure it’s ready for production use.

Testing your application with Postman or another API testing tool has shown that you’re on the right track, and you now have a solid foundation to build upon.

Keep experimenting, refining your skills, and pushing the boundaries of what your application can do. With the power of AI at your fingertips, you’re not just building software—you’re creating the future.

Leave a Comment