Kihagyás

Spring AI - Multi Agent

pom.xml

<dependencyManagement>
    <dependencies>
        <dependency>
            <groupId>org.springframework.ai</groupId>
            <artifactId>spring-ai-bom</artifactId>
            <version>2.0.0</version>
            <type>pom</type>
            <scope>import</scope>
        </dependency>
    </dependencies>
</dependencyManagement>

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

Config

@Bean
@Qualifier("researchChatClient")
ChatClient researchChatClient(ChatClient.Builder builder) {
    return builder
        .defaultSystem("""
            You are a thorough research assistant.

            Research the topic supplied in the user message.
            Provide a concise, factual, and well-structured summary.
            Focus only on information relevant to the supplied topic.
            Clearly indicate uncertainty when reliable information is unavailable.
            """)
        .build();
}

@Bean
@Qualifier("plannerChatClient")
ChatClient plannerChatClient(ChatClient.Builder builder, ResearcherAgentTool researcherAgentTool) {
    return builder.defaultSystem("""
        You are a coordinator assistant.
        If the user's question requires factual research, use the research tool.
        Then, summarize the research results for the user in an easy-to-understand way.
        """).defaultTools(researcherAgentTool).build();
}

application.yaml

spring:
  ai:
    openai:
      base-url: https://example.com/
      api-key: shhh
      chat:
        options:
          model: Qwen3.6-35B-A3B-UD-Q4_K_XL.gguf

AgentLikeATool

@Component
public class ResearcherAgentTool {

    private final ChatClient researchClient;

    public ResearcherAgentTool(@Qualifier("researchChatClient") ChatClient researchClient) {
        this.researchClient = researchClient;
    }

    @Tool(
        name = "research",
        description = """
            Researches the supplied topic.

            Use this tool when answering the user requires factual
            investigation or information that is not safely available
            from general reasoning alone.
            """
    )
    public String research(String topic) {
        return researchClient.prompt().user(topic).call().content();
    }
}

ChatController

@RestController
public class ChatController {

    private final ChatClient chatClient;

    public ChatController(@Qualifier("plannerChatClient") ChatClient chatClient) {
        this.chatClient = chatClient;
    }

    @GetMapping("/chat")
    public String chat(@RequestParam String message) {
        return chatClient.prompt().user(message).call().content();
    }
}

Curl

curl --get --data-urlencode "message=What are the main differences between Spring AI and LangChain4j?" localhost:8080/chat