Spring AI and the free Google Gemini API

When create a new Spring project via start.spring.io, you'll find two dependencies to integrate Google Gemini: Vertex AI Gemini and Vertex AI Embeddings. Both are useful if you use the paid Google Cloud version of Gemini.

But if you like to use the free Gemini APIs for learning, testing and a proof-of-concept, you may like to use the AI Studio version of the Gemini API. But configuring Spring to use the AI Studio Gemini API is a bit unintuitive. So here is what you need to do:

API Key

First, you need your API for Gemini. You can get yours in the AI Studio key section.

Spring dependencies

Instead of a Gemini dependency, you need the OpenAI dependency and some special configuration. So add this dependency to your pom.xml

<dependency>
    <groupId>org.springframework.ai</groupId>
    <artifactId>spring-ai-starter-model-openai</artifactId>
</dependency>

Spring application properties

And the configuration for Spring AI looks like this:

spring.ai.openai.api-key=${GEMINI_API_KEY}
spring.ai.openai.base-url: https://generativelanguage.googleapis.com/v1beta/openai
spring.ai.openai.chat.completions-path: /chat/completions
spring.ai.openai.chat.options.model: gemini-2.0-flash-exp

Don't forget to protect your API key via an environment variable. You can also use another Gemini model, e.g. gemini-2.5-pro-preview-06-05.

Spring ChatClient config

With that, you can create your configuration for the ChatClient bean like that:

import org.springframework.ai.chat.client.ChatClient;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;

@Configuration
public class LLMConfig {

  @Bean
  public ChatClient chatClient(ChatClient.Builder builder) {
    return builder.build();
  }
}

And now you can inject your ChatClient to any service and us it like this:

@Service
public class AIService {
    private final ChatClient ai;
    
    public AIService(ChatClient ai) {
      this.ai = ai;
    }
    
    public void doSomeAi(String promptText) {
      final String aiResult = ai
            .prompt(prompt)
            .call()
            .content();
      
      // do something with your aiResult
    }
}