Integrating Azure OpenAI with Spring Boot: Complete Guide


This guide will walk you through integrating Azure OpenAI with a Spring Boot application using the spring-ai-azure-openai-spring-boot-starter dependency. You will learn how to configure, develop, and test an end-to-end solution.


Step 1: Set Up Your Azure OpenAI Resource

1.1. Create Azure OpenAI Resource

  1. Log in to Azure Portal.
  2. Navigate to Create a resource and search for Azure OpenAI.
  3. Follow the prompts to create a new Azure OpenAI resource.

1.2. Get Required Values

Once your Azure OpenAI resource is set up, gather the following details:

  • Resource Name:

    • Found in the resource overview.
    • Example: my-openai-resource
  • API Key:

    • Navigate to Keys and Endpoint in the left menu of your OpenAI resource.
    • Copy one of the API keys (e.g., KEY1).
  • Deployment Name:

    • Go to Deployments in the left menu.
    • Deploy a model (e.g., text-davinci-003).
    • Note the Name of your deployment.

Step 2: Create a Spring Boot Project

2.1. Generate Project Using Spring Initializr

  1. Visit Spring Initializr.
  2. Configure the project:
    • Project: Maven
    • Language: Java
    • Spring Boot Version: Latest stable version
    • Dependencies:
      • Spring Web
      • Azure OpenAI
  3. Click Generate to download the project as a .zip file.
  4. Extract the project and open it in your preferred IDE.

2.2. 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>

Run mvn clean install to download the dependency.


Step 3: Configure Application Properties

Add your Azure OpenAI credentials in the application.yml file:

spring:
  ai:
    azure-openai:
      endpoint: "https://my-openai-resource.openai.azure.com/"
      api-key: "1234567890abcdef1234567890abcdef"
      default-deployment: "text-davinci-003-deployment"
server:
  port: 8080

Replace the placeholders with:

  • Endpoint: https://<your-resource-name>.openai.azure.com/
  • API Key: Your API key.
  • Default Deployment: The name of your deployed model.

Step 4: Create Service and Controller

4.1. Create OpenAI Service

Write a service class to handle communication with Azure OpenAI.

OpenAIService.java:

package com.example.service;

import org.springframework.ai.openai.OpenAiTemplate;
import org.springframework.stereotype.Service;

@Service
public class OpenAIService {

    private final OpenAiTemplate openAiTemplate;

    public OpenAIService(OpenAiTemplate openAiTemplate) {
        this.openAiTemplate = openAiTemplate;
    }

    public String generateText(String prompt) {
        return openAiTemplate.chatCompletion()
                .withMessages(prompt)
                .execute()
                .getChoices()
                .get(0)
                .getMessage()
                .getContent();
    }
}

4.2. Create OpenAI Controller

Expose a REST endpoint to accept a prompt and return the AI-generated response.

OpenAIController.java:

package com.example.controller;

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

@RestController
@RequestMapping("/api/openai")
public class OpenAIController {

    private final OpenAIService openAIService;

    public OpenAIController(OpenAIService openAIService) {
        this.openAIService = openAIService;
    }

    @PostMapping("/generate")
    public String generateResponse(@RequestBody String prompt) {
        return openAIService.generateText(prompt);
    }
}

Step 5: Test the Application

5.1. Run the Application

Start the application:

mvn spring-boot:run

5.2. Test the API

Use a tool like Postman or cURL to test the endpoint.

Request:

  • URL: http://localhost:8080/api/openai/generate
  • Method: POST
  • Body: Raw JSON:
    "Write a short story about a robot learning to cook."

Response:

"Once there was a robot named RoboChef who always wanted to learn how to cook..."

Complete Project Structure

src └── main ├── java │ └── com.example │ ├── controller │ │ └── OpenAIController.java │ ├── service │ │ └── OpenAIService.java └── resources ├── application.yml

You’ve successfully integrated Azure OpenAI into a Spring Boot application! This end-to-end solution enables you to interact with Azure's AI models using simple REST API calls. You can now build on this foundation to develop advanced AI-powered applications.

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