Spring AI Starter Project: A Complete Guide with Examples

SpringAI

Introduction to Spring AI

Artificial Intelligence (AI) has become a core component of modern software applications, and integrating AI into Java-based applications is now easier with Spring AI. The Spring AI Starter Project simplifies AI model interactions, offering built-in support for LLMs (Large Language Models), embeddings, vector databases, and image generation models.

In this guide, we will explore how to set up a Spring AI Starter project, run queries, and leverage AI-powered functionalities. Whether you’re new to AI or an experienced developer, this guide will provide step-by-step instructions, sample code, and best practices for building AI applications using Spring AI.

What is Spring AI?

Spring AI is a project developed by Spring.io that provides integrations for various AI models and frameworks, making it easier to work with AI in Java applications. It allows developers to:

  • Access LLMs (Large Language Models)
  • Perform text generation and embeddings
  • Utilize vector databases
  • Generate images with AI models

Spring AI follows a modular design, allowing developers to choose and configure AI components as needed.

Key Features of Spring AI

  • Support for multiple AI providers (e.g., OpenAI, Hugging Face, Local LLMs)
  • Easy integration with Spring Boot applications
  • Simplified API for interacting with LLMs
  • Embeddings and vector database support
  • Built-in image generation capabilities
  • Configurable and extendable

Setting Up a Spring AI Starter Project

1. Prerequisites

Before starting, ensure you have:

  • Java 17+ installed
  • Spring Boot 3+
  • Maven or Gradle
  • An API key for an AI provider (e.g., OpenAI)

2. Creating a Spring Boot Project

To create a Spring Boot project, use Spring Initializr:

Using Spring Initializr (Manual Setup)

  1. Go to Spring Initializr
  2. Select Spring Boot 3.x
  3. Add dependencies:
    • spring-ai-openai-starter
    • spring-boot-starter-web
  4. Generate the project and extract it.

Using Spring Boot CLI

spring init --dependencies=web,ai-openai my-spring-ai-app

3. Adding Spring AI Dependencies

Add the following dependency to pom.xml (if using Maven):

<dependency>
    <groupId>org.springframework.ai</groupId>
    <artifactId>spring-ai-openai-spring-boot-starter</artifactId>
    <version>0.5.0</version>
</dependency>

For Gradle users, add this to build.gradle:

dependencies {
    implementation 'org.springframework.ai:spring-ai-openai-spring-boot-starter:0.5.0'
}

4. Configuring Spring AI

Add your OpenAI API Key in application.properties:

spring.ai.openai.api-key=your-api-key-here

Implementing AI Queries

Now that we have set up the project, let’s implement AI-powered queries using Spring AI.

1. Creating a Simple AI Service

Create a ChatService class to interact with OpenAI’s LLM:

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

@Service
public class ChatService {
    @Autowired
    private ChatClient chatClient;
    
    public String getResponse(String prompt) {
        return chatClient.call(prompt);
    }
}

2. Creating a REST API Controller

Now, let’s expose the AI service through a REST API:

import org.springframework.web.bind.annotation.*;
import org.springframework.beans.factory.annotation.Autowired;

@RestController
@RequestMapping("/chat")
public class ChatController {
    @Autowired
    private ChatService chatService;
    
    @GetMapping("/ask")
    public String ask(@RequestParam String prompt) {
        return chatService.getResponse(prompt);
    }
}

3. Running the Application

Run your Spring Boot application:

mvn spring-boot:run

Now, test it by sending a GET request:

curl "http://localhost:8080/chat/ask?prompt=Hello! How are you?"

Advanced Features

1. Using Embeddings and Vector Databases

Spring AI supports embeddings that help store and retrieve AI-generated vectors efficiently.

Add the dependency:

<dependency>
    <groupId>org.springframework.ai</groupId>
    <artifactId>spring-ai-embedding-spring-boot-starter</artifactId>
    <version>0.5.0</version>
</dependency>

2. Implementing Image Generation

Use OpenAI’s DALL·E to generate images. Add this to your service:

import org.springframework.ai.image.ImageClient;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

@Service
public class ImageService {
    @Autowired
    private ImageClient imageClient;
    
    public String generateImage(String prompt) {
        return imageClient.call(prompt);
    }
}

Expose it via a REST API:

@RestController
@RequestMapping("/image")
public class ImageController {
    @Autowired
    private ImageService imageService;
    
    @GetMapping("/generate")
    public String generate(@RequestParam String prompt) {
        return imageService.generateImage(prompt);
    }
}

Conclusion

Spring AI provides a seamless way to integrate AI functionalities into Java applications. By following this guide, you can set up a Spring AI Starter Project, interact with LLMs, implement embeddings, and generate images. With the growing adoption of AI, mastering Spring AI will give developers a competitive edge in building smart applications.

Leave a Reply

Your email address will not be published. Required fields are marked *