Java Agent 入门项目模板(含代码 + 配置 + 说明)

为了帮助你快速入门 Java AI Agent 开发,我们将创建一个基于 Spring BootLangChain4j 的项目模板。此项目将展示如何构建一个能够接收用户输入并调用外部工具(如查询天气)的简单 AI Agent。

项目结构

复制代码
ai-agent-demo/
├── backend/               # Spring Boot 后端
│   ├── pom.xml            # Maven 配置
│   └── src/main/java/com/example/agent
│       ├── annotation/
│       │   └── AgentSkill.java          # 自定义注解
│       ├── model/
│       │   ├── SkillInput.java
│       │   └── SkillOutput.java
│       ├── executor/
│       │   └── SkillExecutorService.java # 核心调度器
│       ├── skills/
│       │   ├── WeatherSkill.java        # 示例技能
│       │   └── SearchSkill.java         # 另一个技能(可选)
│       ├── config/
│       │   └── AppConfig.java           # 配置类
│       └── Application.java             # 主应用类
└── README.md                           # 项目说明文档

1. pom.xml - Maven 配置

xml 复制代码
<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 http://maven.apache.org/xsd/maven-4.0.0.xsd">
    <modelVersion>4.0.0</modelVersion>
    <groupId>com.example.agent</groupId>
    <artifactId>ai-agent-demo</artifactId>
    <version>1.0-SNAPSHOT</version>

    <properties>
        <java.version>17</java.version>
        <spring.boot.version>3.2.0</spring.boot.version>
        <langchain4j.version>0.33.1</langchain4j.version>
    </properties>

    <dependencies>
        <!-- Spring Boot Starter -->
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-web</artifactId>
            <version>${spring.boot.version}</version>
        </dependency>

        <!-- LangChain4j -->
        <dependency>
            <groupId>dev.langchain4j</groupId>
            <artifactId>langchain4j-spring-boot-starter</artifactId>
            <version>${langchain4j.version}</version>
        </dependency>
        <dependency>
            <groupId>dev.langchain4j</groupId>
            <artifactId>langchain4j-qianwen</artifactId>
            <version>${langchain4j.version}</version>
        </dependency>

        <!-- Lombok for cleaner code -->
        <dependency>
            <groupId>org.projectlombok</groupId>
            <artifactId>lombok</artifactId>
            <version>1.18.26</version>
            <scope>provided</scope>
        </dependency>

        <!-- JSON processing -->
        <dependency>
            <groupId>com.fasterxml.jackson.core</groupId>
            <artifactId>jackson-databind</artifactId>
            <version>2.15.2</version>
        </dependency>
    </dependencies>

    <build>
        <plugins>
            <plugin>
                <groupId>org.springframework.boot</groupId>
                <artifactId>spring-boot-maven-plugin</artifactId>
            </plugin>
        </plugins>
    </build>
</project>

2. annotation/AgentSkill.java - 自定义注解

java 复制代码
package com.example.agent.annotation;

import java.lang.annotation.ElementType;
import java.lang.annotation.Retention;
import java.lang.annotation.RetentionPolicy;
import java.lang.annotation.Target;

@Retention(RetentionPolicy.RUNTIME)
@Target(ElementType.TYPE)
public @interface AgentSkill {
    String name();          // 技能名,如 "getWeather"
    String description();   // 描述,用于 LLM 理解
    String[] triggers() default {}; // 触发关键词(可选)
}

3. model/SkillInput.javaSkillOutput.java

java 复制代码
package com.example.agent.model;

import java.util.Map;

public interface SkillInput {
    Map<String, Object> toMap();
}

package com.example.agent.model;

public record SkillOutput(String result, boolean success) {}

4. executor/SkillExecutorService.java - 核心调度器

java 复制代码
package com.example.agent.executor;

import com.example.agent.annotation.AgentSkill;
import com.example.agent.model.SkillInput;
import com.example.agent.model.SkillOutput;
import org.springframework.context.ApplicationContext;
import org.springframework.stereotype.Service;

import java.util.Map;
import java.util.concurrent.ConcurrentHashMap;

@Service
public class SkillExecutorService {

    private final Map<String, BaseSkill> skillRegistry = new ConcurrentHashMap<>();

    public void registerSkills(ApplicationContext context) {
        Map<String, Object> beans = context.getBeansWithAnnotation(AgentSkill.class);
        for (Object bean : beans.values()) {
            AgentSkill ann = bean.getClass().getAnnotation(AgentSkill.class);
            skillRegistry.put(ann.name(), (BaseSkill) bean);
        }
        System.out.println("Registered skills: " + skillRegistry.keySet());
    }

    public SkillOutput execute(String skillName, SkillInput input) {
        BaseSkill skill = skillRegistry.get(skillName);
        if (skill == null) {
            return new SkillOutput("Skill not found: " + skillName, false);
        }

        try {
            return skill.execute(input);
        } catch (Exception e) {
            return new SkillOutput("Skill execution failed: " + e.getMessage(), false);
        }
    }
}

5. skills/WeatherSkill.java - 示例技能

java 复制代码
package com.example.agent.skills;

import com.example.agent.annotation.AgentSkill;
import com.example.agent.model.SkillInput;
import com.example.agent.model.SkillOutput;
import org.springframework.stereotype.Component;

@Component
@AgentSkill(
    name = "getWeather",
    description = "获取指定城市的当前天气,参数:city(字符串)"
)
public class WeatherSkill implements BaseSkill {

    @Override
    public SkillOutput execute(SkillInput input) {
        Map<String, Object> args = input.toMap();
        
        if (!args.containsKey("city")) {
            throw new IllegalArgumentException("Missing 'city' parameter");
        }
        
        String city = (String) args.get("city");
        
        // 模拟调用天气 API(实际可用 OpenWeatherMap)
        String weather = "【模拟】" + city + " 天气晴,25°C";
        
        return new SkillOutput(weather, true);
    }
}

6. config/AppConfig.java - 配置类

java 复制代码
package com.example.agent.config;

import com.example.agent.executor.SkillExecutorService;
import org.springframework.context.ApplicationListener;
import org.springframework.context.event.ContextRefreshedEvent;
import org.springframework.stereotype.Component;

@Component
public class AppConfig implements ApplicationListener<ContextRefreshedEvent> {

    private final SkillExecutorService skillExecutorService;

    public AppConfig(SkillExecutorService skillExecutorService) {
        this.skillExecutorService = skillExecutorService;
    }

    @Override
    public void onApplicationEvent(ContextRefreshedEvent event) {
        skillExecutorService.registerSkills(event.getApplicationContext());
    }
}

7. Application.java - 主应用类

java 复制代码
package com.example.agent;

import dev.langchain4j.service.AiServices;
import dev.langchain4j.model.qwen.QwenChatModel;
import dev.langchain4j.model.qwen.QwenModelName;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;

@SpringBootApplication
public class Application {

    public static void main(String[] args) {
        SpringApplication.run(Application.class, args);

        // 示例:如何集成 LangChain4j
        /*
        ChatLanguageModel model = QwenChatModel.builder()
            .apiKey("your-dashscope-api-key")
            .modelName(QwenModelName.QWEN_MAX)
            .build();

        AiServices.create(Agent.class).chatLanguageModel(model).tools(new WeatherTool()).build();
        */
    }
}

8. README.md - 项目说明文档

markdown 复制代码
# AI Agent Demo Project

## Overview
This is a basic Java-based AI Agent project that demonstrates how to create an agent capable of interacting with users and executing specific tasks using external tools.

## Technologies Used
- **Spring Boot 3.2+**
- **LangChain4j**: For integrating with large language models (LLMs) like Qwen.
- **Qwen (通义千问)**: The LLM used in this example.

## Setup Instructions

### Prerequisites
- JDK 17+
- Maven

### Steps to Run
1. Clone the repository:
   ```bash
   git clone https://github.com/your-repo/ai-agent-demo.git
   cd ai-agent-demo/backend
  1. Build the project:

    bash 复制代码
    mvn clean install
  2. Run the application:

    bash 复制代码
    mvn spring-boot:run
  3. Test the API (e.g., using Postman):

    复制代码
    POST /api/chat
    Content-Type: application/json
    
    {
      "message": "北京天气怎么样?"
    }

Components

  • WeatherSkill: A simple tool that simulates fetching weather information.
  • SkillExecutorService: Manages registration and execution of skills.

Next Steps

  • Add more skills (e.g., search knowledge base).
  • Integrate real APIs instead of mock data.
  • Implement memory and multi-turn conversation capabilities.

Enjoy building your AI Agent!

复制代码
---

### 快速启动指南

1. **克隆仓库**:
   ```bash
   git clone https://github.com/your-repo/ai-agent-demo.git
   cd ai-agent-demo/backend
  1. 构建项目

    bash 复制代码
    mvn clean install
  2. 运行应用

    bash 复制代码
    mvn spring-boot:run
  3. 测试接口(例如使用 Postman 或 curl):

    bash 复制代码
    curl -X POST http://localhost:8080/api/chat \
    -H "Content-Type: application/json" \
    -d '{"message":"北京天气怎么样?"}'

相关推荐
海南java第二人2 小时前
SpringBoot循环依赖全解:从根源到解决方案的深度剖析
java·spring
枫叶丹42 小时前
【Qt开发】Qt系统(八)-> Qt UDP Socket
c语言·开发语言·c++·qt·udp
duansamve2 小时前
VSCode中如何搭建JAVA+MAVEN开发环境?
java·vscode·maven
Elias不吃糖2 小时前
Java Collection 体系与使用场景整理
java·学习笔记·map·collection
一颗青果2 小时前
c++的异常机制
java·jvm·c++
一晌小贪欢2 小时前
用 PyQt5 做一个「批量目录重命名」工具,并打包成带图标的 EXE
开发语言·驱动开发·python·python基础·python小白
小豪GO!2 小时前
操作系统-八股
java
爱吃山竹的大肚肚2 小时前
达梦(DM)数据库中设置表空间
java·数据库·sql·mysql·spring·spring cloud·oracle
阿蒙Amon2 小时前
C#每日面试题-简述类成员
开发语言·c#