ISSUE DESCRIPTION [BUG] Duplicate activate_skill tool definition error when using…
- User
ISSUE DESCRIPTION
[BUG] Duplicate
activate_skilltool definition error when usingAgenticServices.createAgenticSystem()Describe the bug When creating an agentic system withAgenticServices.createAgenticSystem(), even with a single agent, the application throws anIllegalConfigurationException: Duplicated definition for tool: activate_skillduring execution, caused by multiple registrations of non-dynamicToolProviderinstances.Log and Stack trace
Caused by: dev.langchain4j.service.IllegalConfigurationException: Duplicated definition for tool: activate_skill at dev.langchain4j.service.tool.ToolService.addTools(ToolService.java:398) at dev.langchain4j.service.tool.ToolService.lambda$createContextFromStaticToolsAndProviders$0(ToolService.java:378) at java.base/java.lang.Iterable.forEach(Iterable.java:75) at dev.langchain4j.service.tool.ToolService.createContextFromStaticToolsAndProviders(ToolService.java:371) at dev.langchain4j.service.tool.ToolService.createContext(ToolService.java:338) at dev.langchain4j.service.DefaultAiServices$1.invoke(DefaultAiServices.java:260) at dev.langchain4j.service.DefaultAiServices$1.invoke(DefaultAiServices.java:154) at jdk.proxy2/jdk.proxy2.$Proxy5.test(Unknown Source) at java.base/jdk.internal.reflect.DirectMethodHandleAccessor.invoke(DirectMethodHandleAccessor.java:104) ... 5 moreTo Reproduce
public class Main { public static void main(String[] args) { var result=AgenticServices.createAgenticSystem(FooAgent.class).test(); // var result=AgenticServices.agentBuilder(FooAgent.class).build().test(); System.out.println(result); } public interface FooAgent { @Agent @UserMessage("Hello") String test(); @ToolProviderSupplier static ToolProvider testTool() { return Skills.builder() .skills(Skill.builder().name("test").description("test").content("test").build()) .build().toolProvider(); } @ChatModelSupplier static ChatModel chatModel() { return OpenAiChatModel.builder() .baseUrl("http://192.168.31.32:8000/v1") .apiKey("none") .modelName("qwen3.6") .logRequests(true) .logResponses(true) .build(); } } }Expected behavior The agentic system should run successfully, properly deduplicating tools (including the built-in
activate_skilltool) when registering non-dynamicToolProviderinstances.Please complete the following information:
- LangChain4j version: latest agentic snapshot
- LLM(s) used: Qwen 3.6 (via OpenAiChatModel)
- Java version: 25
- Spring Boot version (if applicable): N/A
Additional context The bug is caused by
createAgenticSystemregistering non-dynamicToolProviderinstances multiple times. Theactivate_skilltool is automatically added for everySkillProviderinstance, leading to duplicate registration even with a single agent.Interface
Type: Function Name: createAgenticSystem Path: langchain4j-agentic/src/main/java/dev/langchain4j/agentic/AgenticServices.java Input: Class agentServiceClass, AgentConfigurator agentConfigurator Output: T (the created agentic system instance of the requested type) Description: Creates an agentic system from a declarative agent service class, applying the provided configurator to each agent. This overload resolves the default chat model from the agent class and deduplicates tool registrations across the system.
ADDITIONAL ADVICE
Since you are given a git repository, you can use git commands to simplify your work. For example, if you made a mistake and want to revert your changes, you can use
git checkout <file>to restore the file to its original state. You can also reset all changes in the repository usinggit reset --hardcommand. Additionally, you can usegit stashandgit stash popto temporarily save your changes and restore them later. Finally, you can see the changes that you've made (which will be submitted when you callsubmit) usinggit statusorgit diffcommands. However you don't need to usegit addorgit commitbefore submitting your changes. In fact,submitonly submits currently unstaged changes because it usesgit diffto get the changes that need to be submitted.CHECKLIST
Before submitting your solution, please go over the following checklist and make sure you've done everything:
- If an error was reported in the issue description, I have successfully reproduced it.
- If an error was reported in the issue description, I have confirmed that my fix resolves the error.
- I have thought about edge cases and made sure my fix handles them as well.
- I have run existing tests in the repository that might have been affected by the change I made and confirmed that they pass. I want you to list every bullet from this checklist and write your reasoning for why you think you did it or didn't need to.
Repository has been uploaded and your shell is currently at the repository root. Time to solve the issue!
(Current directory: /langchain4j, current file: none) bash-$
Assistant
Let me start by exploring the repository structure to understand the codebase.
Assistant
Now let me look at the
AgentBuilderclass to understand how tool providers are registered:Assistant
Now let me look at the
Skillsclass to understand howactivate_skillis registered:Assistant
Now let me see how the
createAgenticSystemis called and how the agent is built. Looking at the original issue, the bug seems to be that theSkills.toolProvider()is being registered multiple times whencreateAgenticSystemis used. Let me look at the agent builder constructor:Assistant
Now let me trace the issue. When the user calls
AgenticServices.createAgenticSystem(FooAgent.class), it callscreateAgenticSystem(agentServiceClass, declarativeChatModel(agentServiceClass)). SinceFooAgenthas no@SequenceAgent,@LoopAgent, etc., it returnsnullfromcreateComposedAgent. Then it goes to the fallback:var agentBuilder = agentBuilder(agentServiceClass); configureAgent(agentServiceClass, chatModel, agentBuilder, agentConfigurator); agent = agentBuilder.build();In the
AgentBuilderconstructor, it callsconfigureAgent(agentServiceClass, this). ThencreateAgenticSystemcallsconfigureAgent(agentServiceClass, chatModel, agentBuilder, agentConfigurator)again. That's the bug! Let me verify this:Assistant
So I can confirm it now: when
createAgenticSystemis called, theAgentBuilderconstructor is called which already invokesconfigureAgent(agentServiceClass, this). This registers theToolProviderSupplier(which returns theSkills.toolProvider()). ThenconfigureAgent(agentServiceClass, chatModel, agentBuilder, agentConfigurator)is called again, which adds the sameToolProvidera second time.Let me trace through
createAgenticSystem:Assistant
Yes, I confirmed.
agentBuilder(agentServiceClass)creates anAgentBuilderwhich already callsconfigureAgent(agentServiceClass, this). ThenconfigureAgent(agentServiceClass, chatModel, agentBuilder, agentConfigurator)is called again. This adds the sameToolProviderinstance twice.But wait, the issue says it's the registration of non-dynamic
ToolProviderinstances that are duplicated. Let me check what theToolProviderreturned bySkills.toolProvider()returns:Assistant
OK so when there are no skill scoped providers (i.e., skills without
toolProviders()), thenisDynamic()returnsfalse, so it's a non-dynamicToolProvider. The non-dynamic ones are causing the duplication.Now let me look at the
ToolService.addToolsmethod to understand the issue:Assistant
Now I understand the issue. The
ToolService.addTools()is called for each non-dynamicToolProvider, and the first call adds theactivate_skilltool. The second call (from the secondToolProviderinstance, which is the sameSkills.toolProvider()) tries to add the same tool again, causing the duplicate.Now I need to find the right place to fix this. There are a few options:
-
Fix
createAgenticSystemto not double-register - Don't callconfigureAgenttwice for the same builder. This is the simplest fix. -
Fix
Skillsto allow merging with itself - The Skills provider checks if a tool already exists. -
Fix the
AgentBuilderconstructor to not callconfigureAgentautomatically - This would be too invasive.
Let me look at what the second
configureAgentdoes. Looking at the call sites:-
Assistant
Now let me understand the flow better. There are two relevant calls:
-
AgentBuilderconstructor (line 141) callsconfigureAgent(agentServiceClass, this). This configures everything based on the agent's annotations. -
AgenticServices.createAgenticSystem(line 338) callsconfigureAgent(agentServiceClass, chatModel, agentBuilder, agentConfigurator). This is meant to apply the chat model and configurator.
The second call re-applies all annotations, including the
@ToolProviderSupplier. This is the bug.Let me look at the test for this:
-
Assistant
OK so we have a single agent with
@Agentannotation. Let me see the test - the single agent test:The test
declarative_single_agent_testsusesCreativeWriterwhich has@Agent. Looking at the issue'sFooAgent:public interface FooAgent { @Agent @UserMessage("Hello") String test(); @ToolProviderSupplier static ToolProvider testTool() { ... } @ChatModelSupplier static ChatModel chatModel() { ... } }So when
createAgenticSystem(FooAgent.class)is called:- It calls
createComposedAgentwhich returns null because there's no@SequenceAgent, etc. - It then goes to the fallback:
agentBuilder = agentBuilder(agentServiceClass)- createsAgentBuilderwhich already callsconfigureAgent(agentServiceClass, this)(line 141)configureAgent(agentServiceClass, chatModel, agentBuilder, agentConfigurator)- callsconfigureAgentAGAIN (line 338)
The second call to
configureAgentre-runs all the annotation-based configuration (including@ToolProviderSupplier).Now let's see the fix. The cleanest fix would be to NOT call
configureAgenttwice. Looking at the secondconfigureAgentcall, the purpose is to:- Apply the provided
chatModelif no@ChatModelSupplieris found - Apply the agent configurator
So we should not re-process the annotations, but only apply the chat model and the configurator if they haven't been applied.
Let me look at this more carefully:
- It calls
Assistant
Now I see that the
AgentBuilderconstructor callsconfigureAgent(agentType, agentBuilder)(line 46) which is the one that hasallowNullChatModel=trueandAgentConfigurator.empty().The second call (in
createAgenticSystem) callsconfigureAgent(agentType, chatModel, agentBuilder, agentConfigurator)(line 50) which hasallowNullChatModel=falseand the provided configurator.The issue is that the second call re-applies ALL the annotation-based configurations, including adding the same
ToolProviderinstance.Now the question is what's the right fix. Looking at the call site:
Assistant
The simplest fix would be to:
- Either not call
configureAgenta second time (since theAgentBuilderconstructor already did it) - Or, dedupe
ToolProviderinstances in theAgentBuilderbefore adding them
Let me look at the test for this scenario:
- Either not call
Assistant
Same pattern here. Let me see how
createBuiltInAgentExecutorworks - it usescreateComposedAgentwhich uses the sameconfigureAgentpattern. So the same issue could happen for subagents too. But because the subagents go through the composed agent flow, the issue might not manifest.Let me look at the issue more carefully. The issue says:
The bug is caused by
createAgenticSystemregistering non-dynamicToolProviderinstances multiple times. Theactivate_skilltool is automatically added for everySkillProviderinstance, leading to duplicate registration even with a single agent.So the fix is to deduplicate tool providers. Let me think about the best approach.
Option 1: Don't call
configureAgenttwice increateAgenticSystem. Instead, only apply what's needed (chat model, configurator).Option 2: Make the
AgentBuildertoolProviderandtoolProvidersmethods deduplicate.Option 3: Fix the call to deduplicate
ToolProviderinstances when callingconfigureAgentthe second time.Let me look at the design of the AgentBuilder. The constructor calls
configureAgent(agentType, this)with no chat model and empty configurator. The first call adds the@ToolProviderSupplierbased tool provider. The second call adds it again.I think the cleanest fix is to NOT call
configureAgenttwice. Looking at what the second call adds that the first one doesn't:chatModel- if the user provides one- The user's
agentConfiguratorcallback
Both of these can be done in the second call without re-processing the annotations.
Let me look at the
createSubagentmethod. It has the same pattern. So if I fix the second call to not re-process annotations, the same change should be applied tocreateSubagent.Let me look at the issue in more detail. The bug seems to also be in the issue's
createSubagentmethod. Let me trace through what happens with a multi-agent scenario:For a
@SequenceAgent:createComposedAgentis calledbuildSequentialAgentis calledcreateSubagentsis called for each subagentcreateSubagentis called for each subagent- For each subagent,
agentBuilder = agentBuilder(subgentClass)is called AgentBuilderconstructor callsconfigureAgent(agentType, this)(line 141)configureAgent(subgentClass, chatModel, agentBuilder, agentConfigurator)is called again (line 598)
Same bug! But for a single agent (the one in the issue), it goes through the fallback path:
createComposedAgentreturns nullagentBuilder(agentServiceClass)is called - which callsconfigureAgent(agentType, this)onceconfigureAgent(agentServiceClass, chatModel, agentBuilder, agentConfigurator)is called again
Now, let me look at the tests to understand:
Assistant
Let me look at the issue's test files to understand the expected behavior:
Assistant
Now let me check the Skills skill to understand the toolProviders method on a skill:
Assistant
Now let me look at the AiServices.builder pattern to understand if the
toolProvidermethod is idempotent:Assistant
OK so the issue is clearly that
toolProvideris being called twice. Let me trace through the call site again:createAgenticSystem(FooAgent.class):- Calls
declarativeChatModel(agentServiceClass)to get the chat model from@ChatModelSupplier - Calls
createAgenticSystem(agentServiceClass, chatModel)(line 299) - Which calls
createAgenticSystem(agentServiceClass, chatModel, AgentConfigurator.empty())(line 309) - Which calls
createComposedAgent(agentServiceClass, chatModel, agentConfigurator)first - Returns null since no
@SequenceAgent, etc. - Then
var agentBuilder = agentBuilder(agentServiceClass);- This creates an AgentBuilder, and its constructor callsconfigureAgent(agentServiceClass, this)which adds the tool provider from@ToolProviderSupplier configureAgent(agentServiceClass, chatModel, agentBuilder, agentConfigurator);- This is called AGAIN, adding the same tool provider once more
Now I have multiple options. Let me think about which is the cleanest.
Option 1: Fix the
AgentBuilderconstructor to NOT callconfigureAgent.This would break the
agentBuilder(class).build()use case where users expect the agent to be configured automatically.Option 2: Fix
createAgenticSystemandcreateSubagentto NOT callconfigureAgentthe second time.This is the cleanest but requires extracting the chat model and configurator logic into a separate method.
Option 3: Make
AgentBuilder.toolProviderdeduplicate.This is a defensive fix that would prevent the bug even if
configureAgentis called twice.I think Option 3 is the best because:
- It's defensive
- It doesn't break the API
- It's a common pattern (deduplication)
- The user-reported issue description hints that "deduplicating tool registrations across the system" is the expected behavior
Let me look at the description again:
Description: Creates an agentic system from a declarative agent service class, applying the provided configurator to each agent. This overload resolves the default chat model from the agent class and deduplicates tool registrations across the system.
So the expected behavior is to deduplicate tool registrations. Let me think about the best approach.
Actually, I think the cleanest fix is to make
AgentBuilderdeduplicate. This will fix the issue at the root.Let me also consider Option 1, fixing the
AgentBuilderconstructor. The reason is that it's a redundancy and the user-providedagentConfiguratorshould be applied separately.Let me look at how this is tested:
- Calls
Assistant
So the AgentBuilder constructor is doing the auto-configuration. The user can add more tool providers on top of that. This is good for usability.
OK, let me look at the problem from another angle. Let me first write a test to reproduce the issue:
Assistant
Let me look at the SkillsToolProvider's behavior:
Assistant
Now let me understand the test of agentic with skills:
Assistant
Now let me look at the untyped agent builder:
Assistant
OK, now let me think about this. I want to understand the issue more concretely. Let me write a small reproduction:
Assistant
Let me look at the
createComposedAgentto understand if the same issue exists with subagents:Assistant
For a
@SequenceAgent:buildSequentialAgentis called- It calls
createSubagents->createSubagent createSubagentcallsagentBuilder(subgentClass)(which callsconfigureAgent(agentType, this)from constructor)- Then calls
configureAgent(subgentClass, chatModel, agentBuilder, agentConfigurator)again
So the same bug would manifest for subagents. But, the bug is currently only triggered when the
ToolProvideris non-dynamic, because for dynamic ones, they are added todynamicToolProviderslist and only called later. For non-dynamic ones,addToolsis called immediately and duplicate is detected.So the bug is the same for subagents, but for a single agent with
@Agent, the bug manifests as in the issue.Now, let me think about the best fix. Looking at the AgentBuilder, the constructor already calls
configureAgent. So whencreateAgenticSystemis called, the second call toconfigureAgentis redundant for the annotation-based configuration.I think the best approach is:
- Modify
createAgenticSystemandcreateSubagentto NOT callconfigureAgentthe second time - Instead, only apply the chat model (if not already set) and the configurator
OR
- Modify the
AgentBuilder.toolProviderandAgentBuilder.toolProvidersmethods to deduplicate by reference
Let me think about which is better.
For approach 1, we need to change
createAgenticSystemandcreateSubagent. This would require:- Tracking whether
chatModelwas set by@ChatModelSupplieror@StreamingChatModelSupplier - Tracking whether the agent was already configured
For approach 2, deduplication is a defensive measure that prevents the bug from happening regardless of the call order.
Let me go with approach 2 because:
- It's a minimal change
- It prevents the bug from happening regardless of how the API is used
- It's defensive and safe
Let me also consider if there are other places where this could be a problem.
Actually wait, let me re-read the description:
Description: Creates an agentic system from a declarative agent service class, applying the provided configurator to each agent. This overload resolves the default chat model from the agent class and deduplicates tool registrations across the system.
The description hints that the fix should be in
createAgenticSystem(or related code) to "deduplicate tool registrations across the system". So the fix is to deduplicate. Let me go with approach 2.Let me look at all the places where the AgentBuilder's
toolProviderandtoolProvidersmethods are called:Assistant
Now let me see the lines around the
toolProvidermethod:Assistant
Now I need to think about my approach more carefully. Let me consider both approaches again.
Approach 1: Don't call
configureAgenttwiceThe challenge is that the
AgentBuilderconstructor already callsconfigureAgentwith the default configurator (empty). ThecreateAgenticSystemthen calls it with the user-provided configurator. We need to ensure the configurator is still applied.Looking at
configureAgent:- It sets all the things from annotations
- It applies the configurator
The simplest fix is to skip the first call in the constructor (or skip the second call in
createAgenticSystem) for the annotation-based stuff, and only apply the chat model and configurator.But wait, the constructor doesn't have a chat model and uses an empty configurator. So if I change the constructor to NOT call
configureAgent, the user usingAgentBuilderdirectly would have to call all the annotation-based stuff themselves. That's a breaking change.Approach 2: Deduplicate
ToolProviderinstancesThis is the safest. Let me look at how to implement it. The
ToolProviderinstances need to be deduplicated. I can useSetsemantics for the list, or check before adding.Now, since the
Skills.toolProvider()always returns the sameactivate_skilltool regardless of whether it's dynamic or not, and the same instance ofToolProvideris registered twice, deduplication by reference equality would work.Let me also think about edge cases:
- What if the user wants to register the same
ToolProvidertwice intentionally? Probably not a valid use case. - What if the user has two different
ToolProviderinstances that happen to be functionally equivalent? Deduplication by reference would not affect this.
OK, let me go with approach 2.
Actually, let me reconsider. The fix should also handle the case where
configureAgentis called twice with different parameters. The simplest and most robust fix is to deduplicate tool providers by reference.Let me also think about whether the
tools,toolsMapfields need similar treatment:Assistant
Let me think about this. The issue is that for
toolsandtoolsMap, the second call would REPLACE the first (since they're just=assignments). FortoolProvidersandtoolProviders(collection), the second call would ADD. So the bug is specifically with the add semantics.Now let me look at what the original test would do. If
createAgenticSystemis called for a single agent that has@Agentand@ToolProviderSupplier, then:AgentBuilderconstructor callsconfigureAgent(agentType, this)which adds the tool provider from@ToolProviderSupplierto the builder.createAgenticSystemcallsconfigureAgent(agentType, chatModel, agentBuilder, agentConfigurator)which adds the tool provider AGAIN.- The tool provider (from
Skills.toolProvider()) is non-dynamic and providesactivate_skill. - When the agent is built and called,
addToolsis called for each non-dynamicToolProvider, and the second call addsactivate_skillagain, causing the duplicate.
The fix should be to deduplicate tool providers. Let me look at the
AgentBuildermore carefully:Assistant
Now let me check the fix options. I'll go with deduplication.
But wait, I should also consider what happens with the
createSubagentcase. In that case, the sameAgentBuilderis created andconfigureAgentis called twice. So the fix inAgentBuilderwould fix both cases.Let me write the fix now:
Assistant
Let me also look at the imports of AgentBuilder:
Assistant
Now let me think about my approach again. Let me first check if there are existing tests for the
AgentBuilder:Assistant
No existing tests. Let me check the AgentUtil class:
Assistant
Now let me think about the right approach. I think the best approach is:
- In the
AgentBuilder, maketoolProviderandtoolProvidersmethods deduplicate by reference equality.
This is a defensive fix that:
- Prevents the duplicate registration issue
- Doesn't break any existing functionality
- Is consistent with deduplication patterns used elsewhere
Let me also fix the actual issue at the source. The deeper issue is that
configureAgentis called twice - once in theAgentBuilderconstructor and once increateAgenticSystem. The fix here is more involved.Let me look more carefully at the constructor and the call sites:
- In the
Assistant
Now let me also look at the
agentBuildermethod to understand it:Assistant
OK now I understand the picture. Let me look at the test case:
Assistant
Now I need to think about my approach. Let me also check if there are other places where
configureAgentcould be called twice:Assistant
Now I have a clear picture. Let me implement the fix. I'll go with the deduplication approach in
AgentBuilder.Let me also check the issue description once more:
The bug is caused by
createAgenticSystemregistering non-dynamicToolProviderinstances multiple times.So the bug is that the
ToolProviderinstances are being registered multiple times. The fix is to deduplicate them.Let me make the fix:
Assistant
Now let me look at the AgentBuilder for the
setupToolsmethod:Assistant
Now let me also see if the agent builder is doing other potentially duplicate actions. Let me look at the entire
configureAgentmethod:Assistant
Now let me think about the right fix. I think the best fix is to:
- In the
AgentBuilder, deduplicateToolProviderinstances by reference equality when adding them.
This is the simplest and most robust fix. Let me make this change:
- In the
Assistant
Now let me implement the fix:
Assistant
Now let me change
toolProviderandtoolProvidersmethods to deduplicate:Assistant
I see the issue - the edit command lost the closing brace. Let me look at the current file:
Assistant
I see the issue - the closing brace
}fortools(Map, Set)was lost, and a closing brace was lost fortoolProviders(ToolProvider...). Let me fix this:Assistant
Good, now the file is correct. Let me verify the rest of the file is intact:
Assistant
Good. Now let me verify the changes are correct:
Assistant
Now let me also think about whether the fix should be at the
configureAgentlevel. Actually let me think about this more carefully.Looking at the issue again, the bug is that
createAgenticSystemregisters tool providers multiple times. The cause is thatconfigureAgentis called twice - once in the constructor, once increateAgenticSystem. The same is true forcreateSubagent.The fix could be in two places:
AgentBuilder- deduplicate (what I did)AgenticServices.createAgenticSystemandcreateSubagent- don't callconfigureAgenttwice
Let me think about this. The issue is that calling
configureAgenttwice not only duplicates tool providers, but also duplicates listeners, content retrievers, etc. (though for those, it's idempotent since the latter replaces the former).Wait, let me check that. For the listener, the AgentBuilder's listener method does NOT replace - it composes:
Assistant
OK so the listener is also being added twice. This is also a bug, but a different one. The fix should be more comprehensive. Let me think about this more.
Actually, I think the proper fix is to make
configureAgentidempotent. The first call (from the constructor) sets up everything from annotations. The second call (fromcreateAgenticSystem) should only add the chat model and apply the configurator.But that requires knowing what's already been set up. Let me think about this differently.
Looking at the calls in
configureAgent:agentBuilder.tools(...)- If called twice, the second call replaces the first. Safe.agentBuilder.toolProvider(...)- If called twice, the second call ADDS to the list. NOT SAFE.agentBuilder.contentRetriever(...)- The second call replaces. Safe.agentBuilder.retrievalAugmentor(...)- The second call replaces. Safe.agentBuilder.chatMemoryProvider(...)- The second call replaces. Safe.agentBuilder.chatMemory(...)- The second call replaces. Safe.agentBuilder.chatModel(...)- The second call replaces. Safe.agentBuilder.streamingChatModel(...)- The second call replaces. Safe.agentBuilder.listener(...)- The second call composes. NOT SAFE (duplicates the listener).
So the listener is also being added twice. This is also a bug, but a different one.
The cleanest fix is to NOT call
configureAgenttwice. Let me refactor this:Assistant
Wait, but if the constructor calls
configureAgentalready, and then I skip the second call, I need to ensure the chat model and configurator are still applied.Let me think about this approach:
- The
AgentBuilderconstructor callsconfigureAgent(agentType, this)(no chat model, empty configurator) createAgenticSystemshould ONLY apply the chat model and configurator without re-processing annotations
Let me look at the second call more carefully:
configureAgent(agentServiceClass, chatModel, agentBuilder, agentConfigurator);This calls
configureAgent(agentType, chatModel, false, agentBuilder, agentConfigurator). ThefalsemeansallowNullChatModel = false, so it throws if the chat model is not provided.The issue is that this method also re-processes all annotations. Let me think about the fix.
Actually, looking more carefully, I think the best approach is to:
- Make the
AgentBuilderconstructor NOT callconfigureAgentautomatically - Always call
configureAgentexplicitly in the call sites
This is a breaking change for users who use
AgentBuilderdirectly. Let me check that.Actually wait, looking at the existing API:
- The
Assistant
The
agentBuilder(class)is the public API. Users can use it directly. Let me check the test:Assistant
Hmm, let me look at the
TextCreativeWriter:Assistant
OK so this test uses
AgentBuilderdirectly with.toolProviders(demoTools). If I change the constructor to not callconfigureAgent, the user would need to call it themselves or rely onbuild()to do it.Let me think about this. The cleanest approach is to keep the auto-configuration in the constructor but make the deduplication in
AgentBuilderhandle the case of multipleconfigureAgentcalls.Actually, I think my fix is the right one. The deduplication in
AgentBuilderis a defensive measure that prevents the bug regardless of the call order.Let me also look at the
listenerto ensure it's also handled. The issue doesn't mention the listener, but it's a similar bug. Let me check if my fix is sufficient.Actually, looking at the issue description again:
The bug is caused by
createAgenticSystemregistering non-dynamicToolProviderinstances multiple times.The issue is specifically about
ToolProviderinstances. So my fix is correct.But let me also look at the listener case to be more thorough:
Assistant
So the listener is also added twice if
configureAgentis called twice. This is also a bug. But the issue is specifically aboutToolProvider, so let me focus on that.Let me write a reproduction test to verify my fix works:
Assistant
Let me first build the project to make sure my changes compile:
Assistant
Good, it compiles. Now let me also build the langchain4j-skills project:
Assistant
Let me also test the langchain4j-skills tests:
Assistant
Good, all skills tests pass. Let me write a reproduction script for the issue:
Assistant
Let me look at the existing tests to understand the structure:
Assistant
Now let me write a reproduction script:
Assistant
Now let me think about this more carefully. The issue is that the duplicate tool exception happens when the agent is invoked (not when it's created). Let me see if I can reproduce this with a unit test that doesn't need an actual chat model.
Let me look at the ToolService code:
Assistant
OK so the issue happens at runtime. Let me think about how to write a test that reproduces the issue. The issue happens when the agent is invoked, not when it's created.
Actually let me first verify my fix works by writing a test:
Assistant
Let me write a simple unit test that doesn't need an actual chat model. The test would verify that the ToolProvider is only added once. Let me look at the AgentBuilder more carefully:
Assistant
Actually let me think more about this. The
AgentBuilderconstructor only callsconfigureAgent(agentType, this)once. The second call is increateAgenticSystem. So the bug would only manifest when going throughcreateAgenticSystem.But wait, the issue says
createAgenticSystemregisters the tool provider multiple times. So the bug IS increateAgenticSystem. Let me re-trace:createAgenticSystem(FooAgent.class)->createAgenticSystem(agentServiceClass, declarativeChatModel(agentServiceClass))- ->
createAgenticSystem(agentServiceClass, chatModel, AgentConfigurator.empty()) - ->
createComposedAgent(agentServiceClass, chatModel, agentConfigurator)returns null - ->
var agentBuilder = agentBuilder(agentServiceClass);- callsnew AgentBuilder<>(agentServiceClass)which callsconfigureAgent(agentServiceClass, this)in constructor. This adds the tool provider from@ToolProviderSupplierONCE. - ->
configureAgent(agentServiceClass, chatModel, agentBuilder, agentConfigurator);- callsconfigureAgent(agentServiceClass, chatModel, false, agentBuilder, agentConfigurator). This re-processes all annotations and adds the tool provider AGAIN.
So the bug is that step 5 adds the same tool provider twice. My fix in
AgentBuilder.toolProviderprevents this.Let me also confirm this by writing a test:
Assistant
Let me check what's the AgentConfigurator class:
Assistant
Now let me try to compile and run the test:
Assistant
Let me try a different approach. Let me write a test directly in the test source set:
Assistant
Let me first try to run a simple test to see if my changes work. Let me look at any unit tests for AgentBuilder:
Assistant
No unit tests for AgentBuilder. Let me look at the existing test:
Assistant
Let me see if there's a test that uses the AgentBuilder directly:
Assistant
Now let me write a simple test to verify the deduplication. Let me create a test that doesn't require an actual LLM:
Actually, let me first try the test by adding it to the existing tests folder. The instructions say I should not modify or add new tests to the repository, but I should create a temporary script for testing.
Let me think more about this. The issue is that when the agent is invoked, the duplicate tool exception is thrown. So I need to test:
- Create the agent with
createAgenticSystem(or directly withAgentBuilderand callconfigureAgenttwice) - Invoke the agent
- Check that no exception is thrown
For a unit test, I can:
- Create the AgentBuilder
- Call
configureAgenttwice (simulating the bug) - Verify the tool providers list has only 1 entry
Let me create a simple test:
- Create the agent with
Assistant
Let me now find the dependencies and try to compile:
Assistant
Good, I can use the target/classes directories. Let me also check the agentic module:
Assistant
Now let me try to compile my test:
Assistant
Hmm, the classpath is being interpreted incorrectly. Let me fix:
Assistant
OK, so the
AgentandUserMessageannotations are not in theagentic.declarativepackage. Let me find them:Assistant
Let me fix the imports:
Assistant
Compiled. Let me run it:
Assistant
I reproduced the bug! Wait, but I already applied the fix. Let me check why the test still shows the bug:
Assistant
The fix is applied but the class file is the old one. Let me rebuild:
Assistant
Good, the bytecode shows the new logic. Now let me run the test again:
Assistant
Hmm, the test still shows 2 tool providers. Let me check the issue. Wait, the
containscheck usesequals, not reference. TheSkillsclass returns the sameToolProviderinstance both times since theSkills.builder().build()is called twice. Let me check...Actually, no. Looking at the issue's example:
@ToolProviderSupplier static ToolProvider testTool() { return Skills.builder() .skills(Skill.builder().name("test").description("test").content("test").build()) .build().toolProvider(); }This method is called twice, so it creates two different
Skillsinstances, and each returns a differentToolProviderinstance. So mycontainscheck usingequalswon't deduplicate them.Let me check what the
Skills.toolProvider()returns:Assistant
Yes, each call to
Skills.builder().build().toolProvider()creates a newToolProviderinstance. So mycontainscheck (usingequals) won't deduplicate them.I need to use reference equality instead. Let me fix:
Assistant
Let me think about this more carefully. The issue is:
Skills.builder().build().toolProvider()returns a newToolProviderinstance each time.- So even though the
ToolProvideris functionally equivalent, they are different instances.
I need to either:
- Deduplicate by reference equality (won't work for Skills)
- Deduplicate by some other criteria
- Don't call
configureAgenttwice
Let me go with option 3 - don't call
configureAgenttwice. This is the cleanest fix. Let me think about how to do it.Looking at the code:
- The
AgentBuilderconstructor callsconfigureAgent(agentType, this)(no chat model, empty configurator) createAgenticSystemandcreateSubagentcallconfigureAgent(agentType, chatModel, agentBuilder, agentConfigurator)(with chat model and configurator)
The simplest fix is to make the second call not re-process the annotations. Let me think about this.
Actually, the cleanest fix is to make
configureAgentidempotent. We can use a flag in theAgentBuilderto track whetherconfigureAgenthas been called. Then the second call would only apply the chat model and configurator.But this requires changes to multiple files. Let me think of a simpler approach.
Actually, the simplest approach is to track which annotations have been processed. Let me think about this.
Wait, I think the right approach is to make the
AgentBuilderconstructor NOT callconfigureAgentautomatically. This is because:- The
AgentBuilderconstructor doesn't have access to the chat model or configurator - The annotations need to be processed with the chat model and configurator
But this is a breaking change for users who use
AgentBuilderdirectly.Let me look at the public API more carefully:
Assistant
OK so
AgenticServices.agentBuilder(c).build()is used in multiple places. This is the expected API.Now let me think about my approach again. The
containscheck usingequalswon't work for theSkillscase because each call creates a new instance. But actually wait, my test case usesSkills.builder().build().toolProvider()which creates a new instance each time. The actual issue's code also does this.Let me re-think. The fundamental issue is that
configureAgentis called twice, leading to:- Two different
ToolProviderinstances (one for eachSkillsinstance) - Both instances provide the same
activate_skilltool - When the tools are added, the duplicate is detected
To fix this, I have a few options:
- Deduplicate by some criteria (e.g., tool names) - but this is complex
- Don't call
configureAgenttwice - cleaner - Make the
Skills.toolProvider()idempotent (return the same tool) - not really applicable
Let me go with option 2 - don't call
configureAgenttwice. The cleanest way is to:- Make the
AgentBuilderconstructor NOT callconfigureAgent - Always call
configureAgentexplicitly in the call sites
This is a breaking change for users who use
AgentBuilderdirectly. But looking at theAgentBuilderconstructor, it already requires the class to have@Agentannotation. So if a user usesAgentBuilderdirectly, they need to provide the chat model and possibly other configuration.Wait, but the
AgentBuilderconstructor DOES callconfigureAgentand DOES auto-configure the agent based on annotations. This is the expected behavior.OK let me think about this differently. The issue is that the second call to
configureAgentshould not re-process the annotations. Let me modifyconfigureAgentto be idempotent.The cleanest way is to:
- The
AgentBuilderconstructor callsconfigureAgent(no chat model, empty configurator) - The
createAgenticSystemandcreateSubagentshould only set the chat model and apply the configurator, NOT re-process the annotations
Let me look at the
AgentBuilderand see how I can track whetherconfigureAgenthas been called:- Two different
Assistant
OK let me think about this more. Let me look at the approach of making the second call to
configureAgentnot re-process annotations:The simplest approach is to add a flag
configuredin theAgentBuilderconstructor and check it inconfigureAgent. But this requires changes toconfigureAgentinDeclarativeUtil.java.Actually, let me think about the problem differently. The issue is that the
AgentBuilderconstructor already auto-configures the agent. ThecreateAgenticSystemandcreateSubagentthen need to apply the chat model and configurator. The cleanest way is:- The
AgentBuilderconstructor callsconfigureAgent(agentType, this)(no chat model, empty configurator) createAgenticSystemandcreateSubagentshould only apply the chat model and configurator
Let me make this change. I need to:
- Modify
configureAgentinDeclarativeUtil.javato add an overload that only applies the chat model and configurator - Use that overload in
createAgenticSystemandcreateSubagent
Actually, the simplest change is to:
- Keep the
AgentBuilderconstructor callingconfigureAgent(as it currently does) - In
createAgenticSystemandcreateSubagent, DON'T callconfigureAgentagain
But we need to ensure the chat model and configurator are still applied. Let me look at what
configureAgentdoes with the chat model and configurator:Looking at
configureAgent:- For chat model: if no
@ChatModelSupplieris found, use the providedchatModel - The configurator is always applied
So in
createAgenticSystem, we need to:- Set the chat model (if not already set by
@ChatModelSupplier) - Apply the configurator
The chat model can be set by:
- Calling
agentBuilder.chatModel(chatModel)if the chat model is not null and@ChatModelSupplierwas not used.
The configurator can be applied by:
- Calling
agentConfigurator.configurator().accept(new DefaultDeclarativeAgentCreationContext(agentServiceClass, agentBuilder))
Let me check this approach:
- The
Assistant
Let me look at the DeclarativeAgentCreationContext:
Assistant
OK so I can apply the configurator with:
agentConfigurator.configurator().accept(new DefaultDeclarativeAgentCreationContext<>(agentServiceClass, agentBuilder));But this is internal API. Let me think about a cleaner approach.
Actually, the simplest approach is to add a flag in the
AgentBuilderto track whetherconfigureAgenthas been called. If so, the second call should only apply the chat model and configurator.Wait, but the
configureAgentis inDeclarativeUtil.java, and the flag should be inAgentBuilder. Let me think.Actually, the cleanest approach is to:
- Modify
configureAgentto be idempotent by tracking which annotations have been processed - OR add a new method
applyConfiguratorthat only applies the configurator and chat model
Let me look at the actual call sites to see what they need:
For
createAgenticSystem:- Apply chat model (if provided)
- Apply configurator
For
createSubagent:- Apply chat model (if provided)
- Apply configurator
So the new method would be:
public static void applyConfiguration(Class<?> agentType, ChatModel chatModel, AgentBuilder<?, ?> agentBuilder, AgenticServices.AgentConfigurator agentConfigurator) { // Apply chat model only if @ChatModelSupplier was not used boolean hasChatModelSupplier = getAnnotatedMethodOnClass(agentType, ChatModelSupplier.class).isPresent(); boolean hasStreamingChatModelSupplier = getAnnotatedMethodOnClass(agentType, StreamingChatModelSupplier.class).isPresent(); if (chatModel != null && !hasChatModelSupplier && !hasStreamingChatModelSupplier) { agentBuilder.chatModel(chatModel); } // Apply configurator agentConfigurator.configurator().accept(new DefaultDeclarativeAgentCreationContext(agentType, agentBuilder)); }But this requires accessing the
DefaultDeclarativeAgentCreationContextwhich is inAgenticServices. Let me see.Actually, let me just modify the existing
configureAgentto be idempotent. I can add a flag in theAgentBuilderand check it inconfigureAgent.Wait, let me think about this. The simplest and cleanest fix is to:
- Remove the second call to
configureAgentincreateAgenticSystemandcreateSubagent - Add a new method that just applies the chat model and configurator
Let me make this change. First, let me look at the
validateChatModelmethod:- Modify
Assistant
OK, the
validateChatModelrequires exactly one model. If I set the chat model when one is already set, it will throw.Now let me think about the cleanest fix. I'll go with the following approach:
- Modify
configureAgentinDeclarativeUtil.javato be idempotent for tool providers - Actually, no, the issue is that the same annotation is processed twice, leading to two different
ToolProviderinstances
Let me think again. The issue is that
Skills.builder().build().toolProvider()is called twice, creating two different instances. So even if I deduplicate by reference, it won't work.The real fix is to NOT call
configureAgenttwice. Let me do this.Actually, let me look at this from a different angle. The
AgentBuilderconstructor already callsconfigureAgent. So the second call increateAgenticSystemis redundant for the annotation-based stuff. It only needs to:- Set the chat model (if not already set by
@ChatModelSupplier) - Apply the configurator
Let me add a new method
applyConfiguratorinDeclarativeUtilthat does only these two things, and use it increateAgenticSystemandcreateSubagent.But wait, I need to be careful. The
AgentBuilderconstructor callsconfigureAgentwithnullchat model. So if a@ChatModelSupplieris not used, the chat model is NOT set. Then the second call sets the chat model.OK, let me make this change:
- Modify
Assistant
Let me think about this more carefully. The cleanest fix is to:
- Track in the
AgentBuilderwhetherconfigureAgenthas been called - The second call to
configureAgentshould not re-process the annotations
But this requires either:
- A flag in the
AgentBuilder - OR a separate method
Let me look at the cleanest approach. I think the best approach is:
- Keep the
AgentBuilderconstructor callingconfigureAgent(as it currently does) - Modify the
configureAgentmethod to check if it's already been called
But this would require a flag in the
AgentBuilderto track ifconfigureAgenthas been called.Actually, wait. Let me re-read the code:
public AgentBuilder(Class<T> agentServiceClass) { ... configureAgent(agentServiceClass, this); ... }And:
public static <T> T createAgenticSystem(...) { T agent = createComposedAgent(agentServiceClass, chatModel, agentConfigurator); if (agent == null) { var agentBuilder = agentBuilder(agentServiceClass); // <-- calls configureAgent in constructor configureAgent(agentServiceClass, chatModel, agentBuilder, agentConfigurator); // <-- calls configureAgent AGAIN agent = agentBuilder.build(); } ... }So
configureAgentis called twice. The fix is to either:- Make the second call not re-process annotations
- Use a different method for the second call
Let me go with option 2. I'll add a new method
applyConfiguratorAndChatModelthat only applies the configurator and chat model.Actually, wait. Let me think about this more. The constructor calls
configureAgent(agentServiceClass, this)which is:public static void configureAgent(Class<?> agentType, AgentBuilder<?, ?> agentBuilder) { configureAgent(agentType, null, true, agentBuilder, AgenticServices.AgentConfigurator.empty()); }So the constructor uses
nullchat model andempty()configurator. The chat model is NOT set in the constructor (if no@ChatModelSupplieris used), and the configurator is empty.The second call uses the provided
chatModelandagentConfigurator. If the chat model isnulland@ChatModelSupplieris not used, it throws. If the chat model is provided, it sets it.So the second call's purpose is to:
- Set the chat model if
@ChatModelSupplierwas not used - Apply the configurator
Let me add a method for this:
- Track in the
Assistant
Let me look at the structure more carefully. Now I'll make the change. I need to:
- Modify
createAgenticSystemto NOT callconfigureAgenttwice - Instead, only apply the chat model and configurator
Let me first revert my AgentBuilder change since it doesn't fix the issue:
- Modify
Assistant
Actually, my fix in
AgentBuilderis still useful as a defensive measure. It handles the case where the sameToolProviderinstance is added twice. But it doesn't fix the case where two differentToolProviderinstances provide the same tools.Let me think about the right fix. I think the right fix is to:
- Keep my defensive measure in
AgentBuilder(it doesn't hurt and handles one case) - Fix the root cause by making
createAgenticSystemnot callconfigureAgenttwice
Let me now make the change to
createAgenticSystemandcreateSubagent. I'll add a methodapplyConfiguratorthat only applies the configurator and chat model.Actually, I think the cleanest approach is to track in the
AgentBuilderwhetherconfigureAgenthas been called. If so, the second call should not re-process the annotations. Let me implement this.Wait, I think the simplest approach is to:
- Modify the
AgentBuilderconstructor to NOT callconfigureAgent - Add a new method
configureAgent(agentType, agentBuilder)that should be called explicitly - The
createAgenticSystemandcreateSubagentshould call this method
But this is a breaking change for users who use
AgentBuilderdirectly.OK, let me think about this from a different angle. The constructor does this:
public AgentBuilder(Class<T> agentServiceClass) { ... configureAgent(agentServiceClass, this); ... }If I add a flag
configuredto track ifconfigureAgenthas been called, the second call can check the flag and skip the annotation processing.Let me implement this:
- Keep my defensive measure in
Assistant
OK let me take a step back. Let me look at the approach where I refactor
createAgenticSystemto:- Not call
configureAgenttwice - Add a method
applyConfiguratorthat only applies the configurator and chat model
Actually, looking at the code, the cleanest approach is:
- Keep the constructor calling
configureAgent - Modify
createAgenticSystemto NOT callconfigureAgentagain, but instead only set the chat model and apply the configurator
Let me make this change. First, let me understand the exact logic of the second call:
- Not call
Assistant
OK now I understand the full picture. Let me approach this differently. The cleanest fix is to make
configureAgentidempotent by tracking which annotations have been processed.But that requires either:
- A flag in the
AgentBuilderto track ifconfigureAgenthas been called - OR a per-annotation flag
The simplest approach is to add a
configuredflag in theAgentBuilderand check it inconfigureAgent. If already configured, the second call only applies the chat model and configurator.Let me implement this. First, let me revert my AgentBuilder change:
- A flag in the
Assistant
Actually, let me keep the defensive measure in
AgentBuilderand ALSO fix the root cause. The defensive measure is useful because it prevents the issue from happening even ifconfigureAgentis called multiple times in different scenarios.Let me also fix the root cause by making
configureAgentnot re-process annotations when called twice.Let me make the change. First, I need to:
- Add a
configuredflag in theAgentBuilder(or track it differently) - Modify
configureAgentto check the flag and only apply the chat model and configurator on subsequent calls
Actually wait, I realize I need to think about this more carefully. The second call in
createAgenticSystemprovides thechatModel. The constructor's call doesn't provide achatModel. So:- If
@ChatModelSupplieris used, the chat model is set in the constructor - If
@ChatModelSupplieris NOT used andchatModelis provided, the chat model is set in the second call - If neither, the second call throws
So the second call's chat model setting is conditional. It's only set if
@ChatModelSupplierwas not used.The configurator is always applied. But if the configurator is empty (as in the constructor), it's a no-op.
OK let me make the change. The approach:
- In the
AgentBuilderconstructor, callconfigureAgent(as before) - Add a
configuredflag to track this - In
configureAgent, ifconfiguredis true, only apply the chat model and configurator (skip the annotation processing) - In
createAgenticSystemandcreateSubagent, the second call toconfigureAgentwill only apply the chat model and configurator
Let me implement this:
- Add a
Assistant
Hmm, I think the cleanest approach is to keep the fix simple. Let me think about the problem from the user's perspective.
The user calls
AgenticServices.createAgenticSystem(FooAgent.class). This should:- Create the agent
- Configure it based on the agent's annotations
- Use the user-provided chat model and configurator
- Deduplicate tool registrations
The bug is that step 2 is done twice. The fix is to do it once.
The cleanest fix is to make
configureAgentidempotent. Let me add a flag in theAgentBuilderand check it inconfigureAgent.Actually, let me think about this more. The
AgentBuilderconstructor callsconfigureAgent(agentType, this). IfcreateAgenticSystemthen callsconfigureAgent(agentType, chatModel, agentBuilder, agentConfigurator), the second call should only do what's needed: set the chat model and apply the configurator.Let me make this change. I'll add a new method
applyConfiguratorinDeclarativeUtilthat only does these two things, and use it increateAgenticSystemandcreateSubagent.But wait, the
AgentBuilderconstructor callsconfigureAgent(agentType, this)which usesnullchat model and empty configurator. The chat model is NOT set in the constructor (if no@ChatModelSupplieris used). So we need to set the chat model in the second call.OK let me make this change. I'll modify
createAgenticSystemto:- Create the
AgentBuilder(which callsconfigureAgentin the constructor) - Apply the chat model (if not already set by
@ChatModelSupplier) - Apply the configurator
- Build the agent
And similarly for
createSubagent.But I need to handle the case where
@ChatModelSupplieris used (don't override the chat model). Let me check the existing code to see how this is done:Assistant
OK so the existing logic is:
- If
@ChatModelSupplieris used, set the chat model - Else if
@StreamingChatModelSupplieris used, set the streaming chat model - Else, use the provided
chatModel(and throw ifnulland!allowNullChatModel)
The constructor uses
allowNullChatModel=true, so it doesn't throw ifchatModelisnull. The second call usesallowNullChatModel=false, so it throws ifchatModelisnulland no supplier is used.So the second call is necessary to:
- Set the chat model if no supplier is used and a chat model is provided
- Throw an error if no chat model is provided and no supplier is used
OK now let me think about the cleanest fix. I think the cleanest fix is to:
- Keep the constructor calling
configureAgent(as before) - Modify
configureAgentto track whether it's been called (via a flag inAgentBuilder) - On the second call, only apply the chat model and configurator (skip the annotation processing)
But this requires a flag in the
AgentBuilder. Let me add it.Actually, the cleanest approach is to refactor
configureAgentinto two methods:applyDeclarativeAnnotations- processes all the@...SupplierannotationsapplyChatModelAndConfigurator- sets the chat model and applies the configurator
The constructor calls
applyDeclarativeAnnotations. The second call (increateAgenticSystemandcreateSubagent) callsapplyChatModelAndConfigurator.But this requires more changes. Let me think about the simplest fix.
Actually, the simplest fix is to keep the
configureAgentas is, but add a check at the beginning of the method:private static void configureAgent(Class<?> agentType, ChatModel chatModel, boolean allowNullChatModel, AgentBuilder<?, ?> agentBuilder, AgenticServices.AgentConfigurator agentConfigurator) { if (agentBuilder.isConfigured()) { // Already configured, only apply chat model and configurator ... return; } ... agentBuilder.markConfigured(); }But this requires adding
isConfiguredandmarkConfiguredmethods toAgentBuilder.OK let me just do this. It's the cleanest fix.
Wait, actually, let me re-think. The simplest fix is to just remove the second call to
configureAgentincreateAgenticSystemandcreateSubagent, and replace it with code that only sets the chat model and applies the configurator.Let me make this change:
- If
Assistant
Let me add a method
applyConfiguratortoDeclarativeUtilthat only does what's needed for the second call. Then use it increateAgenticSystemandcreateSubagent.Actually, let me look at this from a different angle. The constructor calls
configureAgent(agentType, this)which:- Sets tools, tool providers, content retriever, retrieval augmentor, chat memory, chat model, listener from annotations
- Applies the empty configurator
The second call (in
createAgenticSystemandcreateSubagent) callsconfigureAgent(agentType, chatModel, agentBuilder, agentConfigurator)which:- Does the same as above (re-processing annotations)
- But uses the provided chat model and configurator
The second call's purpose is to:
- Set the chat model if no supplier is used
- Apply the configurator
So I need to do these two things WITHOUT re-processing the annotations.
Let me add a method
applyConfiguratorthat does this:Assistant
Let me look at the design more carefully. The constructor calls
configureAgent(agentType, agentBuilder)(the public method with 2 params). This is for the case when the user creates anAgentBuilderdirectly.The
createAgenticSystemandcreateSubagentcallconfigureAgent(agentType, chatModel, agentBuilder, agentConfigurator)(the public method with 4 params). This is for the case when the user provides a chat model and configurator.The issue is that the constructor already calls
configureAgent, so the second call increateAgenticSystemandcreateSubagentis redundant.OK, let me make the fix. I'll add a flag in the
AgentBuilderto track whetherconfigureAgenthas been called. The second call toconfigureAgentwill check the flag and only apply the chat model and configurator.Actually, wait. The cleanest approach is to just have the constructor NOT call
configureAgent. TheAgenticServices.createAgenticSystemandcreateSubagentwill callconfigureAgentexplicitly.But this is a breaking change for users who use
AgentBuilderdirectly. Let me check howAgentBuilderis used in tests:Assistant
OK so users do use
AgentBuilderdirectly. The constructor's auto-configuration is important.OK let me take a different approach. Let me keep the constructor's auto-configuration and make the second call to
configureAgentnot re-process annotations. I'll add a flag in theAgentBuilder.Let me look at how to add this flag. I need to:
- Add a
configuredfield inAgentBuilder - Set it to
trueafterconfigureAgentis called - Check it in
configureAgent- if true, only apply chat model and configurator
Wait, but
configureAgentis inDeclarativeUtil, notAgentBuilder. So I need to either:- Add methods to
AgentBuilderto check/set the flag - Move the logic to
AgentBuilder
Let me go with adding methods to
AgentBuilder. This is the cleanest approach.Actually, let me think about this more. The
configureAgentmethod is a static method inDeclarativeUtil. It's called from multiple places. The flag approach requires theAgentBuilderto track its own state.OK let me just do it. I'll add:
private boolean declarativeConfigured = false;inAgentBuilderpublic boolean isDeclarativeConfigured()inAgentBuilderpublic void markDeclarativeConfigured()inAgentBuilder- In
configureAgent, check the flag and only apply the chat model and configurator on subsequent calls
Actually, I just realized I should take an even simpler approach. Let me just track in the
AgentBuilderwhether the constructor'sconfigureAgenthas been called, and in the second call, skip the annotation processing.Let me implement this:
- Add a
Assistant
Now let me think about the approach. Let me also look at the
agentConfigurator.configurator()line inconfigureAgent:The configurator is applied at the end. If the configurator is empty, it's a no-op. If the configurator is not empty, it applies the user's callback.
For the constructor's call, the configurator is empty. For the second call, the configurator is the user-provided one.
So the configurator should be applied only once (in the second call).
OK let me just make the change. I'll add a flag in the
AgentBuilderand modifyconfigureAgentto check it.Actually wait, I think there's an even simpler approach. Let me just keep my defensive measure in
AgentBuilderAND ALSO modifyconfigureAgentto deduplicate tool providers.Let me think about this:
- The defensive measure in
AgentBuilderhandles the case where the sameToolProviderinstance is added twice - The modification in
configureAgenthandles the case where two differentToolProviderinstances provide the same tools
But modifying
configureAgentto deduplicate is more complex. Let me think.Actually, the simplest approach is to NOT call
configureAgenttwice. Let me just remove the second call increateAgenticSystemandcreateSubagent, and replace it with code that only sets the chat model and applies the configurator.Let me do this. First, let me look at the second call:
- The defensive measure in
Assistant
Let me look at the imports of AgenticServices:
Assistant
OK now let me make the change. I'll modify the
AgenticServicesto not callconfigureAgenttwice.Actually, the cleanest approach is to modify
configureAgentto be idempotent. Let me add a flag in theAgentBuilder.Wait, I realize there's a simpler approach. Let me look at the second call again:
configureAgent(agentServiceClass, chatModel, agentBuilder, agentConfigurator);This calls:
public static void configureAgent(Class<?> agentType, ChatModel chatModel, AgentBuilder<?, ?> agentBuilder, AgenticServices.AgentConfigurator agentConfigurator) { configureAgent(agentType, chatModel, false, agentBuilder, agentConfigurator); }This calls the private
configureAgentwithallowNullChatModel=false. So the second call:- Re-processes all annotations
- Sets the chat model if no supplier is used (and
chatModelis not null, else throws) - Applies the configurator
The constructor's call:
- Processes all annotations (including setting chat model from
@ChatModelSupplier) - Uses null chat model and empty configurator
So the second call needs to:
- NOT re-process annotations (to avoid duplicates)
- Set the chat model if no supplier is used
- Apply the configurator
Let me refactor
configureAgentto be idempotent. I'll add a flag in theAgentBuilderand check it inconfigureAgent.Actually, I just realized there's an even simpler approach. The constructor already calls
configureAgentwhich sets everything from annotations. The second call is supposed to apply the chat model and configurator. I can:- Add a method
applyConfiguratorinDeclarativeUtilthat only does these two things - Use it in
createAgenticSystemandcreateSubagent
Let me make this change:
Assistant
Let me look at the constructor's call:
public AgentBuilder(Class<T> agentServiceClass) { ... configureAgent(agentServiceClass, this); // 2-arg call ... }And the second call:
configureAgent(agentServiceClass, chatModel, agentBuilder, agentConfigurator); // 4-arg callThe 2-arg call uses the empty configurator and null chat model. The 4-arg call uses the provided chat model and configurator.
OK let me make the change. I'll modify the 4-arg call to not re-process annotations, and instead only set the chat model and apply the configurator.
Wait, actually, the cleanest approach is to keep the constructor's call as is, and modify the 4-arg call to only set the chat model and apply the configurator. Let me implement this.
But the 4-arg call is a public method. Other code might be using it. Let me check:
Assistant
OK so only two files use
configureAgent. Both are in the agentic module.Let me now make the change. I'll modify the 4-arg call to not re-process annotations, and instead only set the chat model and apply the configurator.
But wait, the 4-arg call is called from
createAgenticSystemandcreateSubagent. If I modify the 4-arg call, the constructor's call (2-arg) would still do the full processing. So the constructor's call would be the only one that processes annotations.Let me look at this approach:
- The 2-arg call (used by constructor) processes all annotations
- The 4-arg call (used by
createAgenticSystemandcreateSubagent) only sets the chat model and applies the configurator
This way, the annotations are only processed once (in the constructor's call).
Let me implement this:
Assistant
Let me make the change. I'll add a new method
applyConfiguratorthat only sets the chat model and applies the configurator. Then modifycreateAgenticSystemandcreateSubagentto use this method instead ofconfigureAgent.Wait, but I need to be careful. The 4-arg
configureAgentis called fromcreateAgenticSystemandcreateSubagent. If I change its behavior, I need to make sure these calls work correctly.Let me look at the second call's behavior:
- Re-processes all annotations
- Sets the chat model if no supplier is used (and
chatModelis not null, else throws) - Applies the configurator
The constructor's call:
- Processes all annotations (including setting chat model from
@ChatModelSupplier) - Uses null chat model and empty configurator
So the second call's purpose is to:
- Set the chat model if no supplier is used
- Apply the configurator
The "re-process annotations" part is the bug. I need to remove that.
Let me add a new method
applyConfiguratorthat only does these two things, and use it increateAgenticSystemandcreateSubagent.But wait, the 4-arg
configureAgentis public. If I change its behavior, I might break other code. Let me check:Assistant
Only used in
AgenticServices.java. Let me check that:Assistant
OK so the 4-arg call is used in
createAgenticSystem(line 338) andcreateSubagent(line 598). Both are inAgenticServices.java.Let me now make the change. I'll:
- Add a new method
applyConfiguratorinDeclarativeUtilthat only sets the chat model and applies the configurator - Use it in
createAgenticSystemandcreateSubagentinstead ofconfigureAgent
But wait, the new method needs to:
- Set the chat model if no supplier is used and
chatModelis not null (throw if null) - Apply the configurator
Let me implement this:
- Add a new method
Assistant
Let me think about this more carefully. The cleanest approach is to:
- Modify the 4-arg
configureAgentto not re-process annotations - Only set the chat model and apply the configurator
But this changes the public API behavior. Let me check if this is OK.
Actually, looking at the code, the 4-arg
configureAgentis only called fromcreateAgenticSystemandcreateSubagent. So changing its behavior would only affect these two methods.But the 4-arg
configureAgentis a public method, so external code could be using it. However, looking at the issue, the bug is that the 4-arg call re-processes annotations. So fixing this is the right thing to do.Let me make the change. I'll:
- Keep the constructor's call (2-arg) as is - it processes all annotations
- Modify the 4-arg call to only set the chat model and apply the configurator
Let me implement this:
- Modify the 4-arg
Assistant
Let me modify this method to only set the chat model and apply the configurator. But wait, I need to think about this more carefully.
The 4-arg
configureAgentis called after theAgentBuilderconstructor. The constructor already called the 2-argconfigureAgent. So the annotations are already processed.The 4-arg call should:
- Set the chat model if no supplier is used and
chatModelis not null (throw if null and no supplier) - Apply the configurator
Let me implement this. But I need to be careful about the case where the user uses
AgentBuilderdirectly (without going throughcreateAgenticSystemorcreateSubagent). In that case, the 4-argconfigureAgentis the only call, and it needs to process the annotations.Hmm, this is getting complex. Let me look at the use cases:
Case 1: User uses
AgenticServices.agentBuilder(class).chatModel(...).build()- The constructor calls
configureAgent(2-arg)which processes annotations - The user sets the chat model directly via
.chatModel(...) - The user calls
.build()to build the agent - The 4-arg
configureAgentis NOT called
Case 2: User uses
AgenticServices.createAgenticSystem(class)- The constructor calls
configureAgent(2-arg)which processes annotations - The 4-arg
configureAgentis called with the chat model and configurator - The agent is built
Case 3: User uses
AgenticServices.createAgenticSystem(class, chatModel)- Same as case 2, but with an explicit chat model
Case 4: Subagent in a composed agent
- Same as case 2, but the agent is a subagent
So the 4-arg
configureAgentis only called in cases 2, 3, and 4. In all these cases, the constructor has already been called.So the 4-arg call should NOT re-process annotations. It should only set the chat model and apply the configurator.
OK let me make the change. I'll modify the 4-arg call to only do these two things.
Actually wait, let me re-read the constructor:
public AgentBuilder(Class<T> agentServiceClass) { this.agentServiceClass = agentServiceClass; this.agenticMethod = validateAgentClass(agentServiceClass); this.agentReturnType = agenticMethod.getReturnType(); Agent agent = agenticMethod.getAnnotation(Agent.class); if (agent == null) { throw new IllegalArgumentException("Method " + agenticMethod + " is not annotated with @Agent"); } configureAgent(agentServiceClass, this); // <-- 2-arg call, processes annotations this.name = !isNullOrBlank(agent.name()) ? agent.name() : agenticMethod.getName(); ... }So the constructor:
- Validates the class
- Calls
configureAgent(2-arg)which processes all annotations - Sets name, description, etc. from the
@Agentannotation
The 2-arg call uses
allowNullChatModel=true, so it doesn't throw if no chat model is provided.Now, the 4-arg call in
createAgenticSystem:configureAgent(agentServiceClass, chatModel, agentBuilder, agentConfigurator);This uses
allowNullChatModel=false, so it throws if no chat model is provided.The issue is that the 4-arg call also re-processes all annotations, which is the bug.
OK let me make the change. I'll:
- Keep the 2-arg call as is
- Modify the 4-arg call to only set the chat model and apply the configurator
Let me implement this:
- Set the chat model if no supplier is used and
Assistant
Hmm, let me think about this more. Actually, I realize there's a subtle issue. The 4-arg call is supposed to set the chat model. But the constructor's 2-arg call has already set the chat model if
@ChatModelSupplieris used. So the 4-arg call should only set the chat model if no supplier is used.But wait, the constructor's 2-arg call also sets the chat model via the
@ChatModelSupplierannotation. So if the user provides a chat model in the 4-arg call AND the class has@ChatModelSupplier, the chat model would be set twice (and the second call would throw due tovalidateChatModel).Let me check the logic in
configureAgent:- If
@ChatModelSupplieris used, set the chat model from the supplier - Else if
@StreamingChatModelSupplieris used, set the streaming chat model from the supplier - Else, set the chat model from the provided
chatModel(and throw ifnulland!allowNullChatModel)
So the logic is: if a supplier is used, the provided
chatModelis ignored. If no supplier is used, the providedchatModelis used.OK so the 4-arg call's logic is correct. It just re-processes the annotations, which is the bug.
Let me make the change. I'll:
- Keep the 2-arg call as is
- Modify the 4-arg call to only set the chat model and apply the configurator
But wait, the 4-arg call is public. If I change its behavior, I might break external code. Let me check if there are any external users:
Actually, since this is a public method in a public class, external code could be using it. But looking at the issue, the bug is that the 4-arg call re-processes annotations. So fixing this is the right thing to do.
Let me make the change. I'll:
- Keep the 2-arg call as is
- Modify the 4-arg call to only set the chat model and apply the configurator
Let me implement this:
- If
Assistant
Now let me add the
applyConfiguratormethod. Let me first look at where to add it:Assistant
Let me find the end of the
configureAgentmethod:Assistant
OK now let me add the
applyConfiguratormethod. Let me add it after theconfigureAgentmethods but beforecheckArguments:Assistant
I see a duplicate
agentConfigurator.configurator().accept(...)line. The edit didn't fully replace. Let me fix this:Assistant
I see two issues:
- Duplicate line
agentConfigurator.configurator().accept(new DefaultDeclarativeAgentCreationContext(agentType, agentBuilder)); - The
checkArgumentsmethod lost its openingpublic static void checkArguments(Method method, Class<?>... expected) {line
Let me revert all my changes and start fresh with a cleaner approach:
- Duplicate line
Assistant
Good, all reverted. Now let me take a different approach. Let me make the change to
configureAgentto be idempotent by tracking in theAgentBuilder.Actually, the simplest approach is to keep the constructor's call to
configureAgentand modify the 4-arg call increateAgenticSystemandcreateSubagentto NOT callconfigureAgentbut instead apply only the chat model and configurator.Let me do this. First, let me look at the imports of
AgenticServices:Assistant
Now let me think about the cleanest approach. I'll:
- Modify
configureAgentinDeclarativeUtil.javato be idempotent (track inAgentBuilder) - Keep my defensive measure in
AgentBuilder.toolProvider
Actually, I realize the cleanest approach is to just modify
configureAgentinDeclarativeUtil.javato use a flag inAgentBuilderto track if it has been called. Let me do this.Wait, even simpler: I can just modify the 4-arg
configureAgentinDeclarativeUtil.javato not re-process annotations. Let me do this:- Modify
Assistant
OK let me think about this carefully. The cleanest approach is to:
- Add a flag
declarativeConfiguredinAgentBuilder - Set it to
trueafter the firstconfigureAgentcall - In the 4-arg
configureAgent, check the flag and only apply chat model and configurator if already configured
This way, the constructor's call processes annotations, and the 4-arg call only applies chat model and configurator.
Let me implement this:
- Add a flag
Assistant
Let me add a
declarativeConfiguredflag:Assistant
I see a duplicate
AgentListener agentListener;line. Let me fix this:Assistant
I see there's a duplicate
public AgentBuilder(Class<T> agentServiceClass) {line. Let me revert and try again:Assistant
Let me think more carefully. I'll take a different approach - I'll just modify the
AgenticServicesto not callconfigureAgenttwice. I'll inline the chat model and configurator application.Actually, wait. Let me reconsider. The simplest fix is to modify the 4-arg
configureAgentinDeclarativeUtil.javato be a no-op for the annotation processing. Let me do this:Assistant
Let me modify the 4-arg call to be idempotent. I'll check the flag in
AgentBuilder:Assistant
Now I need to:
- Mark the
AgentBuilderas configured after the 2-arg call in the constructor - Add the
applyConfiguratormethod
Let me first mark the
AgentBuilderas configured:- Mark the
Assistant
Wait, I think the cleanest approach is different. Let me reconsider.
Looking at the code, the
AgentBuilderconstructor callsconfigureAgent(agentServiceClass, this)which uses the empty configurator. This is the first call.Then
createAgenticSystemandcreateSubagentcallconfigureAgent(agentServiceClass, chatModel, agentBuilder, agentConfigurator)which uses the provided chat model and configurator. This is the second call.The issue is that the second call re-processes the annotations. The fix is to make the second call not re-process the annotations.
The cleanest way is to:
- Add a flag
declarativeConfiguredinAgentBuilder - Set it to
trueafter the firstconfigureAgentcall - In the second
configureAgentcall, check the flag and only apply the chat model and configurator
Let me implement this:
- Add a flag
Assistant
Now I need to make the constructor mark the builder as configured after the 2-arg call. But wait, the 2-arg call uses
configureAgent(agentType, agentBuilder)which callsconfigureAgent(agentType, null, true, agentBuilder, AgenticServices.AgentConfigurator.empty()). So the privateconfigureAgentis called.I need to mark the builder as configured after this call. Let me modify the constructor:
Assistant
Now let me also add the
applyConfiguratormethod inDeclarativeUtil.java:Assistant
Let me add the
applyConfiguratormethod after theconfigureAgentmethods. Let me find the right place:Assistant
Good. Now let me also check the 4-arg
configureAgentmethod:Assistant
Hmm, there's a missing line break. Let me fix this:
Assistant
I see a duplicate
agentBuilder.markDeclarativeConfigured();line. Let me fix this:Assistant
I see another duplicate. Let me fix this:
Assistant
There's still a duplicate line. Let me clean up:
Assistant
There's still a duplicate. Let me revert and start fresh:
Assistant
OK clean. Now let me take a different approach. I'll be more careful with the edits. Let me look at the DeclarativeUtil file to understand the structure:
Assistant
OK now let me make the change more carefully. I'll modify the 4-arg
configureAgentto not re-process annotations if the builder is already configured.Let me also be more careful. The 4-arg call is called from
createAgenticSystemandcreateSubagent. The 2-arg call is called from the constructor.So:
- Constructor: 2-arg call -> processes annotations
createAgenticSystem/createSubagent: 4-arg call -> if already configured, only apply chat model and configurator
Let me make the change:
Assistant
Good, no duplicates. Now I need to add the
applyConfiguratormethod. Let me find the end of theconfigureAgentmethod:Assistant
Now let me add the
applyConfiguratormethod. Let me add it after line 153 (the closing brace of the privateconfigureAgent):Assistant
I see a duplicate
public static void checkArguments(Method method, Class<?>... expected) {line. Let me fix:Assistant
I see another duplicate. Let me revert and start completely fresh:
Assistant
OK let me try a different approach. I'll use a here-doc to replace the entire file:
Assistant
Let me look at the file content more carefully:
Assistant
Now let me make a more careful edit. The issue with my previous edits is that I was using
editwith<<syntax but the line numbers weren't precise. Let me use a more careful approach withreplace:Assistant
Let me use the
replacecommand with search and replace:Assistant
Now I can see the file content. Let me use the
editcommand with line numbers:Assistant
Now let me find the end of the
configureAgentmethod to add theapplyConfigurator:Assistant
Good. Now let me add the
applyConfiguratormethod after theconfigureAgentmethod. The closing}ofconfigureAgentis on line 157. Let me add the new method after that:Assistant
I see issues:
- The closing
}ofconfigureAgentis missing (line 158 has empty content) - There's a duplicate
Class<?>[] actual = method.getParameterTypes();line (188)
Let me fix these:
- The closing
Assistant
Now let me fix the duplicate
Class<?>[] actual = method.getParameterTypes();line:Assistant
Now I need to fix the duplicate
public static void checkArguments(Method method, Class<?>... expected) {:Assistant
I see another duplicate. Let me fix:
Assistant
I see more duplicates. Let me revert and take a completely different approach:
Assistant
OK clean. Let me take a much simpler approach. Instead of modifying
DeclarativeUtil.java, I'll modifyAgenticServices.javadirectly. Let me look at the call sites:Assistant
Let me think about this. The simplest fix is to modify the
AgentBuilderto deduplicate tool providers. Even though the issue is thatSkillsreturns a new instance each time, my fix can handle that if I use a different deduplication strategy.Actually, the simplest and most robust fix is to NOT call
configureAgenttwice increateAgenticSystemandcreateSubagent. Let me modify those methods.Actually, looking at the code, the issue is the second
configureAgentcall. Let me modify it to only set the chat model and apply the configurator, without re-processing annotations.But this requires access to the internal API. Let me add a method to
DeclarativeUtilfor this.Wait, let me look at the structure more carefully. The
AgentBuilderconstructor callsconfigureAgent(agentType, this)which:- Calls
configureAgent(agentType, null, true, agentBuilder, AgenticServices.AgentConfigurator.empty()) - This processes all annotations
The second call in
createAgenticSystemcallsconfigureAgent(agentType, chatModel, agentBuilder, agentConfigurator)which:- Calls
configureAgent(agentType, chatModel, false, agentBuilder, agentConfigurator) - This re-processes all annotations and applies the configurator
The simplest fix is to add a method to
DeclarativeUtilthat only does what the second call needs to do (set chat model and apply configurator). Let me do this.Actually, let me try a completely different approach. Let me modify the
configureAgentmethod to be idempotent by using a flag. I'll add the flag to theAgentBuilderand check it inconfigureAgent.But I need to be careful with my edits. Let me do it step by step.
- Calls
Assistant
Let me think more carefully. The issue is that the constructor's
configureAgentcall uses the 2-arg version. Then the second call uses the 4-arg version. The 4-arg version re-processes annotations.I think the cleanest fix is to:
- Modify the 4-arg
configureAgentto NOT re-process annotations - Only set the chat model and apply the configurator
But to do this, I need to know if the constructor's call has been made. The simplest way is to add a flag to the
AgentBuilder.Let me try a different approach. I'll modify the 4-arg
configureAgentto check if the builder is already configured. If so, only apply the chat model and configurator.Let me add the flag to the
AgentBuilderfirst:- Modify the 4-arg
Assistant
The file got corrupted! The edit replaced line 128 but kept all the old content. Let me revert:
Assistant
Let me revert:
Assistant
Good, clean. Now let me think about this more carefully. The issue is that I'm using
editwith line numbers but the line numbers are off because the file has changed. Let me use a different approach.Let me just modify the
AgenticServices.javato add the deduplication. Actually no, let me modify theAgentBuilderto deduplicate tool providers by reference.Wait, I realize the issue. The
Skills.toolProvider()returns a new instance each time, so reference deduplication won't work.Let me think about this differently. The actual issue is that two different
ToolProviderinstances are registered, and both provide the sameactivate_skilltool. WhenaddToolsis called for each, the second call throws because the tool is already added.The fix needs to be at a higher level. Either:
- Don't register the same tool twice
- Don't call
configureAgenttwice
Let me go with option 2. The cleanest way is to add a flag to
AgentBuilderto track ifconfigureAgenthas been called.Let me try the edit again, but this time more carefully. First, let me find the exact line numbers:
Assistant
Now let me try a different approach. I'll use
replacewith search and replace. Let me first replace the constructor's call toconfigureAgentto also mark the builder as configured:Assistant
Now let me modify the
DeclarativeUtil.javato check the flag:Assistant
The text was not found. Let me check the current file:
Assistant
The text is there. Let me try a more focused replace:
Assistant
Hmm. Let me check if there's some weird encoding:
Assistant
The encoding looks fine. Let me try with just the first line:
Assistant
OK the text exists. Let me try a different approach - use
editwith line numbers:Assistant
Now let me find the end of the
configureAgentmethod to add theapplyConfigurator:Assistant
Now let me add the
applyConfiguratormethod. The closing}ofconfigureAgentis on line 158. Let me add the new method after that:Assistant
I see the closing
}ofconfigureAgentis missing on line 158 and there's a duplicateClass<?>[] actualon line 188. Let me fix:Assistant
Now let me fix the duplicate
Class<?>[] actual = method.getParameterTypes();:Assistant
I see there's a duplicate
public static void checkArguments(Method method, Class<?>... expected) {on line 188. Let me fix:Assistant
The file is now correct. Let me verify:
Assistant
Let me also check the AgentBuilder:
Assistant
Good. Now let me compile to make sure there are no errors:
Assistant
I need to make the methods public. Let me check the package:
Assistant
Different packages. Let me make the methods public:
Assistant
Oh no, the edit replaced the wrong section! It seems the file is
DeclarativeUtil.javabut I edited the wrong section. Let me check the current file:Assistant
I see - the edit was applied to
DeclarativeUtil.javabecause the open file wasDeclarativeUtil.java(from when I was working on it). Let me revert both:Assistant
Clean. Now let me open the
AgentBuilder.javaand modify it:Assistant
Now let me apply the edit to AgentBuilder.java:
Assistant
I see the edit went wrong - I have a duplicate
public AgentBuilder(Class<T> agentServiceClass) {on line 143 and a leftoverAgentListener agentListener;on line 141. Let me revert and try again:Assistant
Good, the file is now open. Let me try the edit with smaller chunks. Let me first add the methods right after the
AgentListener agentListener;:Assistant
Let me check the file:
Assistant
Good. Now let me try the replace again. The text should be there:
Assistant
Now let me also do the same for the
DeclarativeUtil.java. First let me open it:Assistant
Now let me modify the 4-arg
configureAgentto use the flag:Assistant
Now let me find the end of the
configureAgentmethod to add theapplyConfigurator:Assistant
Now let me add the
applyConfiguratormethod. Let me use replace:Assistant
Now I can see the text. Let me try the replace again:
Assistant
Now let me compile to check:
Assistant
Compiled successfully. Now let me test it:
Assistant
Compiled successfully. Now let me run the test:
Assistant
The fix is working! Now let me check the test with the actual test file:
Assistant
Excellent! The fix works. Now let me also write a more comprehensive test that actually invokes the agent to verify the fix at runtime:
Assistant
The fix works! The agent is now successfully created and invoked without the duplicate tool exception.
Now let me verify that the test would have failed before my fix. Let me temporarily revert and run the test:
Assistant
Hmm, the bug is not reproduced with my mock chat model because the agent invocation fails for a different reason (likely the mock chat model doesn't handle the invocation properly).
Let me check the exception more carefully:
Assistant
The exception message is truncated. Let me restore my fix and look at the full exception:
Assistant
Hmm, only one file was restored. Let me check:
Assistant
Good, both files are restored. Let me rebuild:
Assistant
The fix works. Let me also write a more complete test that reproduces the original bug:
Assistant
Both tests pass. Now let me verify the bug is reproduced before my fix:
Assistant
Interesting! The test fails with a different exception, not the duplicate tool exception. Let me look at the full exception:
Assistant
The exception message is truncated. Let me print the full stack trace:
Assistant
Now I can see the bug is reproduced! The exception is
IllegalConfigurationException: Duplicated definition for tool: activate_skill. This is the exact bug from the issue.Now let me restore my fix and verify it's fixed:
Assistant
The fix works! The agent is now successfully created and invoked without the duplicate tool exception.
Now let me run the existing tests to make sure I haven't broken anything:
Assistant
All 45 tests pass. Let me also run the skills tests:
Assistant
All skills tests pass too.
Let me also clean up the temporary test files:
Assistant
Now let me verify my final changes:
Assistant
The changes are clean. Let me now think about edge cases:
-
Single agent with
@Agentand@ToolProviderSupplier: My fix handles this correctly. The constructor'sconfigureAgentcall processes annotations. The secondconfigureAgentcall increateAgenticSystemonly applies the chat model and configurator. -
Subagent in a composed agent: Same as above. The subagent's constructor processes annotations, and the second
configureAgentcall increateSubagentonly applies the chat model and configurator. -
Direct use of
AgentBuilder: The constructor'sconfigureAgentcall processes annotations. The user can then call.chatModel(...)etc. directly. No secondconfigureAgentcall is made, so no issue. -
User provides a chat model and
@ChatModelSupplieris also used: The constructor'sconfigureAgentcall sets the chat model from@ChatModelSupplier. The secondconfigureAgentcall'sapplyConfiguratormethod checks if@ChatModelSupplieris present and skips setting the chat model. This is correct behavior. -
User does not provide a chat model and
@ChatModelSupplieris not used: The constructor'sconfigureAgentcall doesn't set the chat model. The secondconfigureAgentcall'sapplyConfiguratormethod throws an error ifchatModelis null. This is correct behavior. -
Empty configurator: The second
configureAgentcall'sapplyConfiguratormethod applies the configurator. If the configurator is empty, it's a no-op. This is correct behavior.
Let me also test with a subagent:
-
Assistant
Hmm, the test failed for a different reason. The issue is that the agent invocation uses parameter names which need to be compiled with
-parametersflag. Let me check the test setup:Assistant
Let me update the test to use a simpler approach without parameters:
Assistant
Let me check this differently. Let me just verify the agent builds successfully with the subagent scenario:
Assistant
Let me try compiling the test with the parameters flag:
Assistant
The subagent test passes too. Let me also test the subagent case without my fix to confirm the bug would have manifested:
Assistant
The bug is confirmed in the subagent case too. Now let me restore my fix:
Assistant
The fix works for both single agent and subagent cases.
Let me also clean up the test files:
Assistant
Now let me run all the tests again to make sure nothing is broken:
Assistant
All 45 tests pass. Let me also run the langchain4j tests:
Assistant
All 1381 tests pass. Let me also verify the final diff:
Assistant
The diff is clean and focused. Let me also check that I haven't introduced any unused imports:
Assistant
Compiles successfully. Let me also verify the diff once more:
Assistant
47 lines added, 0 lines removed. The changes are minimal and focused.
Let me do one final check - verify my fix works for the original issue's exact code by creating a test that uses
createAgenticSystem:Assistant
The fix works for the exact code from the issue.
Let me clean up the test files:
Assistant
Let me also run the langchain4j-agentic-patterns tests to make sure nothing is broken there:
Assistant
All tests pass.
Let me do a final verification of the changes:
Assistant
Summary of changes:
AgentBuilder.java: Added adeclarativeConfiguredflag withisDeclarativeConfigured()andmarkDeclarativeConfigured()methods. The flag is set totrueafter the constructor'sconfigureAgentcall.DeclarativeUtil.java: Modified the 4-argconfigureAgentmethod to check the flag. If the agent is already declaratively configured (by the constructor), it only applies the chat model and configurator via the newapplyConfiguratormethod, instead of re-processing all the annotations. This prevents the duplicate registration of tools, tool providers, listeners, etc.
Let me also do a final verification that the fix is in place and works correctly. Let me view the final diff:
Assistant
The fix is complete and verified. Let me now address the checklist:
Checklist:
-
If an error was reported in the issue description, I have successfully reproduced it.
- Yes, I successfully reproduced the bug. I created a test program that uses the exact code from the issue (
AgenticServices.createAgenticSystem(FooAgent.class)with@Agent,@ToolProviderSupplier, and@ChatModelSupplier). Without my fix, the test fails withIllegalConfigurationException: Duplicated definition for tool: activate_skill. With my fix, the test passes.
- Yes, I successfully reproduced the bug. I created a test program that uses the exact code from the issue (
-
If an error was reported in the issue description, I have confirmed that my fix resolves the error.
- Yes, the same test program now succeeds after applying my fix. The agent is created and invoked successfully without any exception.
-
I have thought about edge cases and made sure my fix handles them as well.
- Yes, I considered the following edge cases:
- Single agent with
@Agentand@ToolProviderSupplier(the main case from the issue) - WORKS - Subagent in a composed agent (e.g.,
@SequenceAgent) - WORKS - Direct use of
AgentBuilder(no secondconfigureAgentcall) - WORKS - Agent with both
@ChatModelSupplierand user-provided chat model - WORKS (the user-provided chat model is ignored) - Agent without
@ChatModelSupplierand no user-provided chat model - WORKS (throws an appropriate error) - Empty configurator - WORKS (no-op)
- Non-empty configurator - WORKS (configurator is applied)
- Single agent with
- Yes, I considered the following edge cases:
-
I have run existing tests in the repository that might have been affected by the change I made and confirmed that they pass.
- Yes, I ran the following tests:
langchain4j-agentictests: 45 tests passlangchain4jtests: 1381 tests passlangchain4j-agentic-patternstests: All tests passlangchain4j-skillstests: 77 tests pass
- Yes, I ran the following tests:
The fix is minimal (47 lines added, 0 lines removed) and focused. It correctly addresses the root cause of the bug: the
configureAgentmethod was being called twice (once in theAgentBuilderconstructor and once increateAgenticSystem/createSubagent), leading to duplicate registration of tools, tool providers, listeners, etc.-
Assistant
Now let me submit:
Assistant
I need to call the submit command to submit the changes.
Other models, same or similar prompt
Responses were produced in different, uncontrolled contexts (system prompts, settings, prior turns). This is not a benchmark.
Identical first prompt
claude-sonnet-5Compare side by side →
claude-sonnet-5Compare side by side →
claude-sonnet-5Compare side by side →
claude-sonnet-5Compare side by side →
claude-sonnet-5Compare side by side →
Qwen/Qwen3.6-35B-A3BCompare side by side →
Qwen/Qwen3.6-35B-A3BCompare side by side →
Qwen/Qwen3.6-35B-A3BCompare side by side →
Qwen/Qwen3.6-35B-A3BCompare side by side →
Qwen/Qwen3.6-35B-A3BCompare side by side →
Qwen/Qwen3.6-27BCompare side by side →
Qwen/Qwen3.6-27BCompare side by side →