Spring AI: Build AI-Driven Applications with Spring Boot and Azure OpenAI

The flow of interaction:

  • Postman sends a request to the REST API.
  • The REST Controller delegates the request to the AI Service.
  • The AI Service uses the OpenAiClient (provided by Spring AI Azure OpenAI Starter) to call the Azure OpenAI API.
  • The Azure OpenAI API interacts with the underlying AI models to generate a response, which is sent back to the client.

Tools and Technologies Overview

  1. Spring Boot: A Java-based framework for building production-ready applications quickly and efficiently.
  2. Azure OpenAI: A cloud-based AI service providing access to advanced language models such as GPT-3.5 and GPT-4.
  3. Spring AI Azure OpenAI Starter: A Spring Boot starter that simplifies integration with Azure OpenAI services.
  4. Maven: A build automation tool for managing dependencies and building the project.
  5. Postman: A tool for testing REST APIs during development.

Artificial Intelligence (AI) is revolutionizing how applications are built, offering intelligent features like natural language processing, chatbots, and content generation. With Spring Boot, a robust Java framework, and Azure OpenAI, a powerful AI service, you can create scalable and AI-driven applications seamlessly. This guide walks you through building an AI-enabled application from scratch, leveraging Spring Boot's simplicity and Azure OpenAI's advanced models like GPT-4.


1. Setup Your Spring Boot Project

Create a new Spring Boot project using Spring Initializr or your favorite IDE.

  • Add the following dependencies:
    • Spring Web
    • Azure OpenAI

Complete pom.xml:

<?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.4.2</version>
        <relativePath/> <!-- lookup parent from repository -->
    </parent>
    <groupId>com.example</groupId>
    <artifactId>spring-ai-azure-open-ai-demo</artifactId>
    <version>0.0.1-SNAPSHOT</version>
    <name>spring-ai-azure-open-ai-demo</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-M5</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-azure-openai-spring-boot-starter</artifactId>
        </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>

2. Configure Application Properties

Add the required configuration to your application.properties or application.yml file.

For Azure OpenAI, you'll need:

  • Azure OpenAI API key
  • Endpoint URL
  • Model Name (e.g., gpt-4 or gpt-3.5-turbo)

Here’s an example configuration for application.properties:

# Azure OpenAI configuration
spring.ai.azure.openai.api-key=<your-azure-openai-api-key>
spring.ai.azure.openai.endpoint=https://<your-resource-name>.openai.azure.com/
spring.ai.azure.openai.model=gpt-4

3. Find Your Azure OpenAI API Key and Endpoint

  1. Log in to the Azure Portal.
  2. Search for Azure OpenAI in the services and select your resource.
  3. Navigate to the Keys and Endpoint section.
  4. Copy your API key and endpoint URL.

4. Create an AI Service

Create a service class to interact with the Azure OpenAI API using Spring AI.

import org.springframework.ai.openai.OpenAiClient;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;

@Service
public class AIService {

    private final OpenAiClient openAiClient;

    public AIService(OpenAiClient openAiClient) {
        this.openAiClient = openAiClient;
    }

    public String getAIResponse(String prompt) {
        return openAiClient.completion(prompt);
    }
}

5. Build a REST Controller

Expose an endpoint for your application.

import com.example.springai.service.AIService;
import org.springframework.web.bind.annotation.*;

@RestController
@RequestMapping("/api/ai")
public class AIController {

    private final AIService aiService;

    public AIController(AIService aiService) {
        this.aiService = aiService;
    }

    @PostMapping("/ask")
    public String askAI(@RequestBody String prompt) {
        return aiService.getAIResponse(prompt);
    }
}

6. Test the Application

Run your Spring Boot application and test the endpoint.

  • URL: http://localhost:8080/api/ai/ask

  • Method: POST

  • Request Body:

    {
      "prompt": "What is the capital of France?"
    }
  • Response:

    {
      "response": "The capital of France is Paris."
    }

Notes:

  • Replace <your-azure-openai-api-key> and <your-resource-name> with actual values.
  • Ensure your API key is stored securely, e.g., using environment variables or a secrets manager.

To access the source code or download the project, visit the GitHub repository:

🔗 GitHub - Spring AI Demo Project

Feel free to clone or fork the repository to get started quickly!


Get Your Copy of Spring AI in Action Today!

🚀 Don’t miss out on this amazing opportunity to elevate your development skills with AI.
📖 Transform your Spring applications using cutting-edge AI technologies.

🎉 Unlock amazing savings of 34.04% with our exclusive offer!

👉 Click below to save big and shop now!
🔗 Grab Your 34.04% Discount Now!

👉 Click below to save big and shop now!
🔗 Grab Your 34.04% Discount Now!

Popular posts from this blog

Learn Java 8 streams with an example - print odd/even numbers from Array and List

Java Stream API - How to convert List of objects to another List of objects using Java streams?

Registration and Login with Spring Boot + Spring Security + Thymeleaf

Java, Spring Boot Mini Project - Library Management System - Download

ReactJS, Spring Boot JWT Authentication Example

Top 5 Java ORM tools - 2024

Java - Blowfish Encryption and decryption Example

Spring boot video streaming example-HTML5

Google Cloud Storage + Spring Boot - File Upload, Download, and Delete