-
Notifications
You must be signed in to change notification settings - Fork 424
refactor: extract shared tool execution support #1837
New issue
Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.
By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.
Already on GitHub? Sign in to your account
Merged
igordayen
merged 1 commit into
embabel:main
from
arnabnandy7:chore/shared-tool-execution-support
Jul 31, 2026
Merged
Changes from all commits
Commits
File filter
Filter by extension
Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
There are no files selected for viewing
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
145 changes: 145 additions & 0 deletions
145
embabel-agent-api/src/main/kotlin/com/embabel/agent/spi/loop/support/ToolExecutionSupport.kt
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -0,0 +1,145 @@ | ||
| /* | ||
| * Copyright 2024-2026 Embabel Pty Ltd. | ||
| * | ||
| * Licensed under the Apache License, Version 2.0 (the "License"); | ||
| * you may not use this file except in compliance with the License. | ||
| * You may obtain a copy of the License at | ||
| * | ||
| * http://www.apache.org/licenses/LICENSE-2.0 | ||
| * | ||
| * Unless required by applicable law or agreed to in writing, software | ||
| * distributed under the License is distributed on an "AS IS" BASIS, | ||
| * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. | ||
| * See the License for the specific language governing permissions and | ||
| * limitations under the License. | ||
| */ | ||
| package com.embabel.agent.spi.loop.support | ||
|
|
||
| import com.embabel.agent.api.tool.Tool | ||
| import com.embabel.agent.api.tool.ToolCallContext | ||
| import com.embabel.agent.api.tool.callback.AfterToolCallContext | ||
| import com.embabel.agent.api.tool.callback.BeforeToolCallContext | ||
| import com.embabel.agent.api.tool.callback.ToolCallInspector | ||
| import com.embabel.agent.spi.loop.ToolCallResult | ||
| import com.embabel.agent.spi.loop.ToolInjectionContext | ||
| import com.embabel.agent.spi.loop.ToolInjectionStrategy | ||
| import com.embabel.chat.Message | ||
| import com.embabel.chat.ToolCall | ||
| import org.slf4j.Logger | ||
| import tools.jackson.databind.ObjectMapper | ||
|
|
||
| /** Result of provider-independent tool execution. */ | ||
|
arnabnandy7 marked this conversation as resolved.
|
||
| internal data class ExecutedToolCall( | ||
|
arnabnandy7 marked this conversation as resolved.
|
||
| val result: Tool.Result, | ||
| val content: String, | ||
| ) | ||
|
|
||
| /** Execute a tool and publish its before and after inspection callbacks. */ | ||
| internal fun executeTool( | ||
| tool: Tool, | ||
| toolCall: ToolCall, | ||
| toolCallContext: ToolCallContext, | ||
| toolCallInspectors: List<ToolCallInspector>, | ||
| ): ExecutedToolCall { | ||
| toolCallInspectors.notifyBeforeToolCall(BeforeToolCallContext(toolCall)) | ||
| val started = System.currentTimeMillis() | ||
| val result = tool.call(toolCall.arguments, toolCallContext) | ||
| val content = when (result) { | ||
| is Tool.Result.Text -> result.content | ||
| is Tool.Result.WithArtifact -> result.content | ||
| is Tool.Result.Error -> "Error: ${result.message}" | ||
| } | ||
| toolCallInspectors.notifyAfterToolCall( | ||
| AfterToolCallContext( | ||
| toolCall = toolCall, | ||
| result = result, | ||
| resultAsString = content, | ||
| durationMs = System.currentTimeMillis() - started, | ||
| ) | ||
| ) | ||
| return ExecutedToolCall(result, content) | ||
| } | ||
|
|
||
| /** | ||
| * Evaluate and apply dynamic tool changes after a tool call. | ||
| * | ||
| * Centralizing decoration, deduplication, and tracking keeps injection semantics | ||
| * consistent for every tool-loop implementation. | ||
| */ | ||
| internal fun applyToolInjection( | ||
| toolCall: ToolCall, | ||
| resultContent: String, | ||
| conversationHistory: List<Message>, | ||
| availableTools: MutableList<Tool>, | ||
| iteration: Int, | ||
| injectionStrategy: ToolInjectionStrategy, | ||
| objectMapper: ObjectMapper, | ||
| toolDecorator: ((Tool) -> Tool)?, | ||
| injectedTools: MutableList<Tool>? = null, | ||
| removedTools: MutableList<Tool>? = null, | ||
| logger: Logger? = null, | ||
| ) { | ||
| val injection = injectionStrategy.evaluate( | ||
| ToolInjectionContext( | ||
| conversationHistory = conversationHistory, | ||
| currentTools = availableTools, | ||
| lastToolCall = ToolCallResult( | ||
| toolName = toolCall.name, | ||
| toolInput = toolCall.arguments, | ||
| result = resultContent, | ||
| resultObject = deserializeToolResult(resultContent, objectMapper, logger), | ||
| ), | ||
| iterationCount = iteration, | ||
| ) | ||
| ) | ||
| if (!injection.hasChanges()) return | ||
|
|
||
| val removedNames = injection.toolsToRemove.map { it.definition.name }.toSet() | ||
| availableTools.removeIf { it.definition.name in removedNames } | ||
| removedTools?.addAll(injection.toolsToRemove) | ||
| if (injection.toolsToRemove.isNotEmpty()) { | ||
| logger?.info( | ||
| "Strategy removed {} tools after {}: {}", | ||
| injection.toolsToRemove.size, | ||
| toolCall.name, | ||
| removedNames, | ||
| ) | ||
| } | ||
|
|
||
| val existingNames = availableTools.map { it.definition.name }.toSet() | ||
| val additions = injection.toolsToAdd | ||
| .map { toolDecorator?.invoke(it) ?: it } | ||
| .filter { it.definition.name !in existingNames } | ||
| if (injection.toolsToAdd.isNotEmpty() && additions.isEmpty()) { | ||
| logger?.debug( | ||
| "All {} tools already present after {}, skipping", | ||
| injection.toolsToAdd.size, | ||
| toolCall.name, | ||
| ) | ||
| } | ||
| availableTools.addAll(additions) | ||
| injectedTools?.addAll(additions) | ||
| if (additions.isNotEmpty()) { | ||
| logger?.info( | ||
| "Strategy injected {} tools after {}: {}", | ||
| additions.size, | ||
| toolCall.name, | ||
| additions.map { it.definition.name }, | ||
| ) | ||
| } | ||
| } | ||
|
|
||
| private fun deserializeToolResult( | ||
| content: String, | ||
| objectMapper: ObjectMapper, | ||
| logger: Logger?, | ||
| ): Any? { | ||
| val trimmed = content.trimStart() | ||
| if (!trimmed.startsWith('{') && !trimmed.startsWith('[')) return null | ||
| return try { | ||
| objectMapper.readValue(content, Any::class.java) | ||
| } catch (e: Exception) { | ||
| logger?.debug("Could not deserialize tool result as JSON: {}", e.message) | ||
| null | ||
| } | ||
| } | ||
Oops, something went wrong.
Add this suggestion to a batch that can be applied as a single commit.
This suggestion is invalid because no changes were made to the code.
Suggestions cannot be applied while the pull request is closed.
Suggestions cannot be applied while viewing a subset of changes.
Only one suggestion per line can be applied in a batch.
Add this suggestion to a batch that can be applied as a single commit.
Applying suggestions on deleted lines is not supported.
You must change the existing code in this line in order to create a valid suggestion.
Outdated suggestions cannot be applied.
This suggestion has been applied or marked resolved.
Suggestions cannot be applied from pending reviews.
Suggestions cannot be applied on multi-line comments.
Suggestions cannot be applied while the pull request is queued to merge.
Suggestion cannot be applied right now. Please check back later.
Uh oh!
There was an error while loading. Please reload this page.