DEV Community

araf
araf

Posted on

1 1

Part 5: AI Agents with LangChain4j + Tool Integration

🧠 AI with Java & Spring Boot – Part 5: AI Agents with LangChain4j + Tool Integration

Welcome back! πŸ™Œ

In the last parts of this series, we taught our AI app to chat, remember, and understand documents.

Today, we’ll make it act smartly β€” by building an AI agent that can:

  • Interpret your input
  • Decide what to do
  • Call tools (Java methods)
  • Return a final answer

Think of it like a smart chatbot that can also do math, check weather, and more.

Let’s dive in! πŸ§ͺ


πŸ“¦ What We'll Build

An agent that can:

  • Understand prompts like: > β€œWhat’s 25% of 160 if it’s sunny in Tokyo?”
  • Call custom tools (like weather check or calculator)
  • Combine answers and return a natural-language response

βš™οΈ Prerequisites

Make sure you have:

  • Java 17+
  • Spring Boot 3+
  • Maven project
  • OpenAI API key

πŸ“ Project Structure

src/
 └── main/
     β”œβ”€β”€ java/
     β”‚   └── com.example.agent/
     β”‚       β”œβ”€β”€ AgentApplication.java
     β”‚       β”œβ”€β”€ tools/CalculatorTool.java
     β”‚       β”œβ”€β”€ tools/WeatherTool.java
     β”‚       β”œβ”€β”€ service/ReasoningAgent.java
     β”‚       └── controller/AgentController.java
Enter fullscreen mode Exit fullscreen mode

🧱 Step 1: Add Maven Dependencies

<dependencies>
    <!-- LangChain4j core -->
    <dependency>
        <groupId>dev.langchain4j</groupId>
        <artifactId>langchain4j</artifactId>
        <version>0.25.0</version>
    </dependency>
    <!-- LangChain4j OpenAI LLM -->
    <dependency>
        <groupId>dev.langchain4j</groupId>
        <artifactId>langchain4j-openai</artifactId>
        <version>0.25.0</version>
    </dependency>
</dependencies>
Enter fullscreen mode Exit fullscreen mode

πŸš€ Step 2: Create the Spring Boot Main Class

@SpringBootApplication
public class AgentApplication {
    public static void main(String[] args) {
        SpringApplication.run(AgentApplication.class, args);
    }
}
Enter fullscreen mode Exit fullscreen mode

πŸ›  Step 3: Create Tools (Functions for the Agent to Use)

➀ Calculator Tool

package com.example.agent.tools;

import dev.langchain4j.agent.tool.Tool;
import org.springframework.stereotype.Component;

@Component
public class CalculatorTool {

    @Tool
    public String calculatePercentage(String input) {
        try {
            String[] parts = input.split(" of ");
            double percent = Double.parseDouble(parts[0].replace("%", "").trim());
            double value = Double.parseDouble(parts[1].trim());
            double result = (percent / 100) * value;
            return String.format("%.2f", result);
        } catch (Exception e) {
            return "Invalid input for percentage calculation.";
        }
    }
}
Enter fullscreen mode Exit fullscreen mode

➀ Weather Tool (Mocked)

package com.example.agent.tools;

import dev.langchain4j.agent.tool.Tool;
import org.springframework.stereotype.Component;

@Component
public class WeatherTool {

    @Tool
    public String getCurrentWeather(String city) {
        // In real-world, call an API here like OpenWeather
        return "It is sunny in " + city;
    }
}
Enter fullscreen mode Exit fullscreen mode

🧠 Step 4: Create the Reasoning Agent

package com.example.agent.service;

import com.example.agent.tools.CalculatorTool;
import com.example.agent.tools.WeatherTool;
import dev.langchain4j.agent.Agent;
import dev.langchain4j.model.openai.OpenAiChatModel;
import org.springframework.stereotype.Component;

@Component
public class ReasoningAgent {

    private final Agent agent;

    public ReasoningAgent(CalculatorTool calculatorTool, WeatherTool weatherTool) {
        this.agent = Agent.builder()
            .llm(OpenAiChatModel.builder()
                .apiKey("YOUR_OPENAI_API_KEY")
                .modelName("gpt-3.5-turbo")
                .temperature(0.3)
                .build())
            .tools(calculatorTool, weatherTool)
            .build();
    }

    public String ask(String input) {
        return agent.respond(input);
    }
}
Enter fullscreen mode Exit fullscreen mode

πŸ“ Replace "YOUR_OPENAI_API_KEY" with your actual OpenAI key or inject it from properties.


🌐 Step 5: REST Controller

package com.example.agent.controller;

import com.example.agent.service.ReasoningAgent;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.*;

import java.util.Map;

@RestController
@RequestMapping("/api/agent")
public class AgentController {

    private final ReasoningAgent agent;

    public AgentController(ReasoningAgent agent) {
        this.agent = agent;
    }

    @PostMapping("/ask")
    public ResponseEntity<String> askAgent(@RequestBody Map<String, String> request) {
        String prompt = request.get("prompt");
        return ResponseEntity.ok(agent.ask(prompt));
    }
}
Enter fullscreen mode Exit fullscreen mode

πŸ§ͺ Test Your Agent

Run your app, then test using curl or Postman:

curl -X POST http://localhost:8080/api/agent/ask \
-H "Content-Type: application/json" \
-d '{"prompt": "If it is sunny in Tokyo, what is 25% of 160?"}'
Enter fullscreen mode Exit fullscreen mode

βœ… The AI will:

  • Understand your prompt
  • Use getCurrentWeather("Tokyo")
  • Use calculatePercentage("25% of 160")
  • Return a natural response

πŸ”§ Tips for Production

  • Replace WeatherTool with a real weather API like OpenWeatherMap
  • Add more tools (currency, finance, translator, etc.)
  • Secure your endpoints
  • Log tool invocations
  • Add rate limiting

πŸ”š Wrapping Up the Series

You've now built a complete Java AI assistant with:

  • πŸ’¬ Chat capabilities
  • 🧠 Memory
  • πŸ“„ Document understanding
  • 🀹 Tool use
  • πŸ€– Autonomous agents

All in Spring Boot + LangChain4j + OpenAI


πŸ’‘ What’s Next?

Want:

  • A GitHub starter repo?
  • A web UI with React?
  • WhatsApp chatbot integration?

Let me know in the comments β€” or message me.

Happy coding,

β€” RF πŸ‘¨β€πŸ’»

AWS Q Developer image

Build your favorite retro game with Amazon Q Developer CLI in the Challenge & win a T-shirt!

Feeling nostalgic? Build Games Challenge is your chance to recreate your favorite retro arcade style game using Amazon Q Developer’s agentic coding experience in the command line interface, Q Developer CLI.

Participate Now

Top comments (0)

πŸ‘‹ Kindness is contagious

Delve into this thought-provoking piece, celebrated by the DEV Community. Coders from every walk are invited to share their insights and strengthen our collective intelligence.

A heartfelt β€œthank you” can transform someone’s dayβ€”leave yours in the comments!

On DEV, knowledge sharing paves our journey and forges strong connections. Found this helpful? A simple thanks to the author means so much.

Get Started