π§ 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
π§± 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>
π Step 2: Create the Spring Boot Main Class
@SpringBootApplication
public class AgentApplication {
public static void main(String[] args) {
SpringApplication.run(AgentApplication.class, args);
}
}
π 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.";
}
}
}
β€ 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;
}
}
π§ 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);
}
}
π 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));
}
}
π§ͺ 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?"}'
β 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 π¨βπ»
Top comments (0)