欢迎光临
我们一直在努力

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

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

<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 – 自定义注解

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.java 和 SkillOutput.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 – 核心调度器

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 – 示例技能

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 – 配置类

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 – 主应用类

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 – 项目说明文档

# 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

  • Build the project:

    mvn clean install

  • Run the application:

    mvn spring-boot:run

  • 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

  • 构建项目:

    mvn clean install

  • 运行应用:

    mvn spring-boot:run

  • 测试接口(例如使用 Postman 或 curl):

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


  • 赞(0)
    未经允许不得转载:171主机测评 » Java Agent 入门项目模板(含代码 + 配置 + 说明)
    分享到: 更多 (0)

    评论 抢沙发

    • 昵称 (必填)
    • 邮箱 (必填)
    • 网址