org.llm4s.toolapi

Members list

Packages

Built-in tools for common agent operations.

Built-in tools for common agent operations.

This package provides production-ready tools that can be used out of the box:

== Core Utilities (No API Keys Required) ==

import org.llm4s.toolapi.builtin.core._

val tools = new ToolRegistry(Seq(
 DateTimeTool.tool,
 CalculatorTool.tool,
 UUIDTool.tool,
 JSONTool.tool
))

== File System Tools ==

import org.llm4s.toolapi.builtin.filesystem._

val fileTools = new ToolRegistry(Seq(
 ReadFileTool.create(FileConfig(
   maxFileSize = 512 * 1024,
   allowedPaths = Some(Seq("/tmp"))
 )),
 ListDirectoryTool.tool,
 FileInfoTool.tool
))

== HTTP Tools ==

import org.llm4s.toolapi.builtin.http._

val httpTools = new ToolRegistry(Seq(
 HTTPTool.create(HttpConfig(
   timeoutMs = 10000,
   allowedDomains = Some(Seq("api.example.com"))
 ))
))

== Shell Tools ==

import org.llm4s.toolapi.builtin.shell._

// Read-only shell (safe commands)
val shellTools = new ToolRegistry(Seq(
 ShellTool.create(ShellConfig.readOnly())
))

// Development shell with common dev tools
val devShellTools = new ToolRegistry(Seq(
 ShellTool.create(ShellConfig.development())
))

== Search Tools ==

import org.llm4s.toolapi.builtin.search._

val searchTools = new ToolRegistry(Seq(
 DuckDuckGoSearchTool.tool
))

== All Built-in Tools ==

import org.llm4s.toolapi.builtin.BuiltinTools

// Get all safe tools (no shell, restricted filesystem)
val tools = BuiltinTools.withHttpSafe()

// Get all tools with custom config
val allTools = BuiltinTools.all(
 fileConfig = FileConfig(allowedPaths = Some(Seq("/tmp")))
)

Attributes

See also

Type members

Classlikes

case class ArraySchema[A](description: String, itemSchema: SchemaDefinition[A], minItems: Option[Int], maxItems: Option[Int], uniqueItems: Boolean) extends SchemaDefinition[Seq[A]]

Array schema with item type and size constraints.

Array schema with item type and size constraints.

Value parameters

description

Human-readable description shown to the LLM

itemSchema

Schema applied to every element of the array

maxItems

Maximum number of elements (inclusive)

minItems

Minimum number of elements (inclusive)

uniqueItems

When true, all elements must be distinct

Attributes

Supertypes
trait Serializable
trait Product
trait Equals
trait SchemaDefinition[Seq[A]]
class Object
trait Matchable
class Any
Show all

Helper class to convert ToolRegistry to Azure OpenAI format

Helper class to convert ToolRegistry to Azure OpenAI format

Attributes

Supertypes
class Object
trait Matchable
class Any
Self type
case class BooleanSchema(description: String) extends SchemaDefinition[Boolean]

Boolean schema.

Boolean schema.

Value parameters

description

Human-readable description shown to the LLM

Attributes

Supertypes
trait Serializable
trait Product
trait Equals
trait SchemaDefinition[Boolean]
class Object
trait Matchable
class Any
Show all
case class IntegerSchema(description: String, minimum: Option[Int], maximum: Option[Int], exclusiveMinimum: Option[Int], exclusiveMaximum: Option[Int], multipleOf: Option[Int]) extends SchemaDefinition[Int]

Integer schema with range and divisibility constraints.

Integer schema with range and divisibility constraints.

Value parameters

description

Human-readable description shown to the LLM

exclusiveMaximum

Exclusive upper bound

exclusiveMinimum

Exclusive lower bound

maximum

Inclusive upper bound

minimum

Inclusive lower bound

multipleOf

Value must be a multiple of this integer

Attributes

Supertypes
trait Serializable
trait Product
trait Equals
trait SchemaDefinition[Int]
class Object
trait Matchable
class Any
Show all
case class NullableSchema[T](underlying: SchemaDefinition[T]) extends SchemaDefinition[Option[T]]

Nullable schema wrapper that widens an existing schema to also accept null.

Nullable schema wrapper that widens an existing schema to also accept null.

Emits "type": ["<original>", "null"] in the JSON Schema output.

Value parameters

underlying

The non-nullable schema to wrap

Attributes

Supertypes
trait Serializable
trait Product
trait Equals
trait SchemaDefinition[Option[T]]
class Object
trait Matchable
class Any
Show all
case class NumberSchema(description: String, isInteger: Boolean, minimum: Option[Double], maximum: Option[Double], exclusiveMinimum: Option[Double], exclusiveMaximum: Option[Double], multipleOf: Option[Double]) extends SchemaDefinition[Double]

Number schema (floating-point) with range and divisibility constraints.

Number schema (floating-point) with range and divisibility constraints.

Value parameters

description

Human-readable description shown to the LLM

exclusiveMaximum

Exclusive upper bound

exclusiveMinimum

Exclusive lower bound

isInteger

When true the JSON type is "integer" instead of "number"

maximum

Inclusive upper bound

minimum

Inclusive lower bound

multipleOf

Value must be a multiple of this number

Attributes

Supertypes
trait Serializable
trait Product
trait Equals
trait SchemaDefinition[Double]
class Object
trait Matchable
class Any
Show all
case class ObjectSchema[T](description: String, properties: Seq[PropertyDefinition[_]], additionalProperties: Boolean) extends SchemaDefinition[T]

Object schema with a fixed set of typed properties.

Object schema with a fixed set of typed properties.

In strict mode all properties are emitted as required regardless of the individual PropertyDefinition.required flag, matching the behaviour expected by OpenAI strict-mode tool definitions.

Value parameters

additionalProperties

Whether to allow extra keys beyond those listed

description

Human-readable description shown to the LLM

properties

Ordered sequence of property definitions

Attributes

Supertypes
trait Serializable
trait Product
trait Equals
trait SchemaDefinition[T]
class Object
trait Matchable
class Any
Show all
case class PropertyDefinition[T](name: String, schema: SchemaDefinition[T], required: Boolean)

A named property within an ObjectSchema.

A named property within an ObjectSchema.

Value parameters

name

Property key in the JSON object

required

Whether the property is required

schema

Schema applied to the property value

Attributes

Supertypes
trait Serializable
trait Product
trait Equals
class Object
trait Matchable
class Any
Show all
case class SafeParameterExtractor(params: Value)

Safe parameter extraction with type checking and path navigation.

Safe parameter extraction with type checking and path navigation.

This extractor provides two modes of operation:

  1. Simple mode: Returns Either[String, T] for backward compatibility
  2. Enhanced mode: Returns Either[ToolParameterError, T] for structured error reporting

Value parameters

params

The JSON parameters to extract from

Attributes

Companion
object
Supertypes
trait Serializable
trait Product
trait Equals
class Object
trait Matchable
class Any
Show all

Attributes

Companion
class
Supertypes
trait Product
trait Mirror
class Object
trait Matchable
class Any
Self type
object Schema

Schema builder — fluent API for creating JSON Schema SchemaDefinition values.

Schema builder — fluent API for creating JSON Schema SchemaDefinition values.

Attributes

Example
import org.llm4s.toolapi.Schema
val schema = Schema.`object`[Map[String, Any]]("Query parameters")
 .withProperty(Schema.property("q",    Schema.string("Search query")))
 .withProperty(Schema.property("limit", Schema.integer("Max results"), required = false))
Supertypes
class Object
trait Matchable
class Any
Self type
Schema.type
sealed trait SchemaDefinition[T]

Base trait for all JSON Schema definitions used in tool parameter specifications.

Base trait for all JSON Schema definitions used in tool parameter specifications.

Each concrete subclass corresponds to a JSON Schema type and can be converted to a ujson.Value for inclusion in OpenAI-compatible tool definitions via SchemaDefinition.toJsonSchema.

Attributes

Supertypes
class Object
trait Matchable
class Any
Known subtypes
class ArraySchema[A]
class NullableSchema[T]
class NumberSchema
class ObjectSchema[T]
class StringSchema
Show all
case class StringSchema(description: String, enumValues: Option[Seq[String]], minLength: Option[Int], maxLength: Option[Int]) extends SchemaDefinition[String]

String schema with validation options.

String schema with validation options.

Value parameters

description

Human-readable description shown to the LLM

enumValues

Restricts valid values to this closed set

maxLength

Maximum allowed string length

minLength

Minimum allowed string length

Attributes

Supertypes
trait Serializable
trait Product
trait Equals
trait SchemaDefinition[String]
class Object
trait Matchable
class Any
Show all
class ToolBuilder[T, R]

Builder for ToolFunction definitions using a fluent API.

Builder for ToolFunction definitions using a fluent API.

Obtained via the companion ToolBuilder object:

ToolBuilder[Map[String, Any], MyResult]("my_tool", "Does something", schema)
 .withHandler(extractor => Right(MyResult(...)))
 .buildSafe()

Value parameters

description

Natural-language description for the LLM

handler

Optional handler; must be set before calling buildSafe

name

Tool name

schema

Parameter schema

Attributes

Companion
object
Supertypes
class Object
trait Matchable
class Any
object ToolBuilder

Attributes

Companion
class
Supertypes
class Object
trait Matchable
class Any
Self type
sealed trait ToolCallError

Enhanced tool call errors with consistent formatting.

Enhanced tool call errors with consistent formatting.

Covers the full lifecycle of a tool invocation: unknown function, null arguments, invalid arguments, handler errors, and execution exceptions.

Attributes

Companion
object
Supertypes
class Object
trait Matchable
class Any
Known subtypes
class HandlerError
class Timeout
Show all
object ToolCallError

Attributes

Companion
trait
Supertypes
trait Sum
trait Mirror
class Object
trait Matchable
class Any
Self type

JSON serialization helpers for structured tool error payloads.

JSON serialization helpers for structured tool error payloads.

Converts ToolCallError and ToolParameterError instances to machine-readable JSON format for ToolMessage.content, enabling LLMs and consumers to programmatically parse validation errors and self-correct tool arguments.

Output schema:

{
 "isError": true,
 "toolName": "<string>",
 "errorType": "<unknown_function|null_arguments|invalid_arguments|handler_error|execution_error>",
 "message": "<human readable summary>",
 "parameterErrors": [   // optional: only present for invalid_arguments
   {
     "parameterName": "<string>",
     "kind": "<missing_parameter|null_parameter|type_mismatch|invalid_nesting>",
     "expectedType": "<string|null>",
     "receivedType": "<string|null>",
     "availableParameters": ["<string>", ...]  // optional hint
   }
 ],
 "error": "<legacy error string for older consumers>"
}

Attributes

Supertypes
class Object
trait Matchable
class Any
Self type
case class ToolCallRequest(functionName: String, arguments: Value)

Carries the name and parsed JSON arguments for a single tool invocation.

Carries the name and parsed JSON arguments for a single tool invocation.

Produced by the agent framework from org.llm4s.llmconnect.model.ToolCall values in the LLM response. arguments is a pre-parsed ujson.Value (not a raw JSON string), so tool implementations receive structured data directly.

Value parameters

arguments

Parsed JSON arguments; typically a JSON object whose fields correspond to the tool's declared Schema.

functionName

Name of the tool to invoke; matched against ToolFunction.name in ToolRegistry.execute.

Attributes

Supertypes
trait Serializable
trait Product
trait Equals
class Object
trait Matchable
class Any
Show all
case class ToolExecutionConfig(timeout: Option[FiniteDuration], retryPolicy: Option[ToolRetryPolicy])

Configuration for tool execution: optional per-tool timeout and retry policy.

Configuration for tool execution: optional per-tool timeout and retry policy.

Default is no timeout and no retry (backward compatible).

Attributes

Supertypes
trait Serializable
trait Product
trait Equals
class Object
trait Matchable
class Any
Show all
sealed trait ToolExecutionStrategy

Strategy for executing multiple tool calls.

Strategy for executing multiple tool calls.

When an LLM requests multiple tool calls, they can be executed either sequentially (one at a time) or in parallel (simultaneously).

Attributes

Example
// Execute tools in parallel
agent.runWithStrategy(
 query = "Get weather in London, Paris, and Tokyo",
 tools = weatherTools,
 toolExecutionStrategy = ToolExecutionStrategy.Parallel
)
// Limit concurrency to 2 at a time
agent.runWithStrategy(
 query = "Search 10 different topics",
 tools = searchTools,
 toolExecutionStrategy = ToolExecutionStrategy.ParallelWithLimit(2)
)
Companion
object
Supertypes
class Object
trait Matchable
class Any
Known subtypes
object Parallel
object Sequential

Attributes

Companion
trait
Supertypes
trait Sum
trait Mirror
class Object
trait Matchable
class Any
Self type
case class ToolFunction[T, R](name: String, description: String, schema: SchemaDefinition[T], handler: SafeParameterExtractor => Either[String, R])(implicit evidence$1: ReadWriter[R])

A fully-defined, executable tool that can be invoked by an LLM.

A fully-defined, executable tool that can be invoked by an LLM.

Bundles together a name, a natural-language description (shown to the model), a SchemaDefinition that describes the expected JSON parameters, and a handler function that performs the actual work.

Prefer constructing instances via ToolBuilder rather than directly.

Type parameters

R

Return type, must have a uPickle ReadWriter

T

Phantom type for the parameter schema (unused at runtime)

Value parameters

description

Natural-language description of what the tool does and when to use it

handler

Business logic; receives a SafeParameterExtractor and returns Right(result) or Left(errorMessage)

name

Unique tool identifier used by the LLM when calling the tool

schema

Parameter schema describing the expected JSON arguments

Attributes

Supertypes
trait Serializable
trait Product
trait Equals
class Object
trait Matchable
class Any
Show all
sealed trait ToolParameterError

Structured error information for tool parameter validation.

Structured error information for tool parameter validation.

Represents specific validation failures when parsing tool call arguments, including missing parameters, type mismatches, null values, and invalid nesting.

Attributes

Companion
object
Supertypes
class Object
trait Matchable
class Any
Known subtypes

Attributes

Companion
trait
Supertypes
trait Sum
trait Mirror
class Object
trait Matchable
class Any
Self type
class ToolRegistry(initialTools: Seq[ToolFunction[_, _]])

Registry for tool functions with execution capabilities.

Registry for tool functions with execution capabilities.

Acts as the single point of truth for tools available to an agent. Supports synchronous, asynchronous, and batched execution with configurable concurrency strategies (see ToolExecutionStrategy):

  • execute() — synchronous, blocking execution
  • executeAsync() — asynchronous, non-blocking execution
  • executeAll() — batch execution with a configurable ToolExecutionStrategy

Create a registry by passing an initial set of ToolFunction instances:

val registry = new ToolRegistry(Seq(myTool, anotherTool))
// or use the convenience factories:
ToolRegistry.empty
BuiltinTools.coreSafe.map(new ToolRegistry(_))

Value parameters

initialTools

The tools available in this registry

Attributes

Companion
object
Supertypes
class Object
trait Matchable
class Any
Known subtypes
object ToolRegistry

Attributes

Companion
class
Supertypes
class Object
trait Matchable
class Any
Self type
case class ToolRetryPolicy(maxAttempts: Int, baseDelay: FiniteDuration, backoffFactor: Double)

Simple retry policy with exponential backoff.

Simple retry policy with exponential backoff.

Value parameters

backoffFactor

Multiplier for each subsequent delay (e.g. 2.0 => baseDelay, 2baseDelay, 4baseDelay).

baseDelay

Delay after first failure before first retry.

maxAttempts

Total attempts (first try + retries); must be >= 1.

Attributes

Supertypes
trait Serializable
trait Product
trait Equals
class Object
trait Matchable
class Any
Show all