org.bsc.langgraph4j.langchain4j.tool.ToolNode Maven / Gradle / Ivy
Show all versions of langgraph4j-langchain4j Show documentation
package org.bsc.langgraph4j.langchain4j.tool;
import dev.langchain4j.agent.tool.Tool;
import dev.langchain4j.agent.tool.ToolExecutionRequest;
import dev.langchain4j.agent.tool.ToolSpecification;
import dev.langchain4j.data.message.ToolExecutionResultMessage;
import dev.langchain4j.service.tool.DefaultToolExecutor;
import dev.langchain4j.service.tool.ToolExecutor;
import static dev.langchain4j.agent.tool.ToolSpecifications.toolSpecificationFrom;
import lombok.NonNull;
import lombok.Value;
import lombok.experimental.Accessors;
import lombok.extern.slf4j.Slf4j;
import java.lang.reflect.Method;
import java.util.*;
import java.util.stream.Collectors;
/**
* A node in the graph that executes a tool
*
* This class is just a simple wrapper around a list of {@link Specification} that can be used to build a node
* in a graph that can execute a tool with the given id.
*
*
The node will execute the first tool that has the given id.
*
* @see Specification
*/
@Slf4j
public final class ToolNode {
@Value(staticConstructor = "of")
@Accessors( fluent = true)
public static class Specification {
@NonNull
ToolSpecification value;
@NonNull
ToolExecutor executor;
}
public static class Builder {
private final List toolSpecifications = new ArrayList<>();
public Builder specification(ToolSpecification spec, ToolExecutor executor) {
return this.specification( Specification.of(spec, executor));
}
public Builder specification(Specification toolSpecifications) {
this.toolSpecifications.add(toolSpecifications);
return this;
}
public Builder specification( Object objectWithTool ) {
for (Method method : objectWithTool.getClass().getDeclaredMethods()) {
if (method.isAnnotationPresent(Tool.class)) {
final ToolExecutor toolExecutor = new DefaultToolExecutor(objectWithTool, method);
toolSpecifications.add(new Specification(toolSpecificationFrom(method), toolExecutor));
}
}
return this;
}
public ToolNode build() {
return new ToolNode(toolSpecifications);
}
}
public static Builder builder() {
return new Builder();
}
/**
* Builds a ToolNode out of a collection of objects that have tools attached or a tool specification
*
* @param objectsWithToolsOrSpecification a list of objects with tools
* @return a ToolNode
* @deprecated use {@link #builder()}
*/
@Deprecated
public static ToolNode of( Collection