Add local-tool-calling module: six small Ollama models scored on one MCP-served tool suite

Four tools served over MCP, twelve prompts, LangChain4j 1.24.0 OllamaChatModel, a scorer that validates each call against the tool's own JSON schema, and scripts to run and summarise the benchmark.

Co-Authored-By: Claude Sonnet 5.5 <[email protected]>
Claude-Session: https://claude.ai/code/session_017ic4b3obqqePfZ9m2Jk5Ub
This commit is contained in:
asmhatre
2026-11-26 19:05:53 +05:30
co-authored by Claude Sonnet 5.5
parent ae8fe985b4
commit f4f90b3b30
18 changed files with 667 additions and 1 deletions
+2
View File
@@ -0,0 +1,2 @@
results/
target/
+37
View File
@@ -0,0 +1,37 @@
# local-tool-calling
Companion to the ankurm.com post *Tool Calling with Small Local Models: Which Ollama Models Actually Follow Your Schema?*
The same four tools, the same twelve prompts, run several times against each small Ollama model through
LangChain4j, and every response scored: valid call, schema-invalid arguments, wrong value, hallucinated tool,
spurious call, no call. The tool definitions come from a small MCP server through `langchain4j-mcp`, so the
schema each model sees is what an MCP client hands it.
| Piece | File |
|---|---|
| Tool suite, served over MCP (stdio) | `mcp/tool_server.py` |
| MCP client wiring | `McpTools.java`, `McpWiring.java` |
| The twelve prompts and what a correct answer is | `ToolCase.java` |
| Scoring (schema validation + value checks) | `Scorer.java`, tested by `ScorerTest.java` |
| The benchmark loop | `Benchmark.java` |
## Versions (verified on Maven Central, 2026-11-26)
LangChain4j `langchain4j` and `langchain4j-ollama` **1.24.0** (GA), `langchain4j-mcp` **1.24.0-beta34** (beta only), JDK 25, Python `mcp` 2.x (`MCPServer`; 1.x used `FastMCP`).
This module overrides the parent's 1.22.0 BOM, like `advanced-rag` does.
## Run
```bash
export JAVA_HOME=/path/to/jdk-25
pip install "mcp>=2"
ollama serve & # or the desktop app
scripts/pull-models.sh # six models, roughly 7 GB
scripts/mcp-wiring.sh # MCP only, no model: lists tools, executes one call
scripts/benchmark.sh # writes results/<model>.jsonl, one line per call
scripts/summarize.py --cases # one table from results/*.jsonl
```
`MODELS=llama3.2:3b RUNS=1 scripts/benchmark.sh` runs a single model once. `TEMPERATURE` (default 0.3) and `PYTHON` are also read.
`mvn test -pl local-tool-calling -am` runs the scorer's unit tests; they use hand-written tool requests, not a model, and
say nothing about how any model behaves. Results are machine-specific and are not committed: run it and compare.
+39
View File
@@ -0,0 +1,39 @@
"""The tool suite, served over MCP (stdio). Run by the Java harness; you never start it by hand.
Requires: pip install "mcp>=2" (mcp 2.x renamed FastMCP to MCPServer; the old import raises ModuleNotFoundError)
The four tools are deliberately dull. The benchmark never executes them (it only looks at what
the model ASKS for); McpWiring executes one of them end to end.
"""
from typing import Literal, Optional
from mcp.server.mcpserver import MCPServer
mcp = MCPServer("local-tool-suite")
@mcp.tool()
def get_weather(city: str, unit: Literal["celsius", "fahrenheit"] = "celsius") -> str:
"""Get the current weather for a city."""
temp = 31 if unit == "celsius" else 88
return f"{city}: {temp} degrees {unit}, humid"
@mcp.tool()
def convert_currency(amount: float, from_currency: str, to_currency: str) -> str:
"""Convert an amount of money between two currencies using ISO 4217 codes such as USD or INR."""
return f"{amount} {from_currency} = {round(amount * 83.2, 2)} {to_currency} (fixed demo rate)"
@mcp.tool()
def create_reminder(text: str, minutes_from_now: int) -> str:
"""Create a reminder that fires the given number of minutes from now."""
return f"Reminder set for +{minutes_from_now} min: {text}"
@mcp.tool()
def search_notes(query: str, limit: Optional[int] = None) -> str:
"""Search the user's personal notes. Optionally cap the number of results."""
return f"3 notes match '{query}' (limit={limit})"
if __name__ == "__main__":
mcp.run(transport="stdio")
+65
View File
@@ -0,0 +1,65 @@
<?xml version="1.0" encoding="UTF-8"?>
<project xmlns="http://maven.apache.org/POM/4.0.0"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
<modelVersion>4.0.0</modelVersion>
<parent>
<groupId>com.ankurm.langchain4j</groupId>
<artifactId>langchain4j-demo</artifactId>
<version>1.0.0</version>
</parent>
<artifactId>local-tool-calling</artifactId>
<properties>
<!-- Verified on Maven Central 2026-11-26. Overrides the parent's 1.22.0 for this module only. -->
<lc4j.tools.version>1.24.0</lc4j.tools.version>
<lc4j.tools.beta.version>1.24.0-beta34</lc4j.tools.beta.version>
</properties>
<dependencyManagement>
<dependencies>
<dependency>
<groupId>dev.langchain4j</groupId>
<artifactId>langchain4j-bom</artifactId>
<version>${lc4j.tools.version}</version>
<type>pom</type>
<scope>import</scope>
</dependency>
</dependencies>
</dependencyManagement>
<dependencies>
<dependency>
<groupId>dev.langchain4j</groupId>
<artifactId>langchain4j</artifactId>
</dependency>
<dependency>
<groupId>dev.langchain4j</groupId>
<artifactId>langchain4j-ollama</artifactId>
</dependency>
<!-- MCP client: beta only, no GA exists -->
<dependency>
<groupId>dev.langchain4j</groupId>
<artifactId>langchain4j-mcp</artifactId>
<version>${lc4j.tools.beta.version}</version>
</dependency>
<dependency>
<groupId>org.slf4j</groupId>
<artifactId>slf4j-simple</artifactId>
<version>${slf4j.version}</version>
</dependency>
<dependency>
<groupId>org.junit.jupiter</groupId>
<artifactId>junit-jupiter</artifactId>
<scope>test</scope>
</dependency>
<dependency>
<groupId>org.assertj</groupId>
<artifactId>assertj-core</artifactId>
<version>${assertj.version}</version>
<scope>test</scope>
</dependency>
</dependencies>
</project>
+7
View File
@@ -0,0 +1,7 @@
#!/usr/bin/env bash
# Builds the module and writes its runtime classpath to target/cp.txt (sourced by the other scripts).
set -euo pipefail
cd "$(dirname "$0")/.."
mvn -B -q -f ../pom.xml -pl local-tool-calling -am compile dependency:build-classpath \
-Dmdep.outputFile=target/cp.txt >/dev/null
CP="target/classes:$(cat target/cp.txt)"
+8
View File
@@ -0,0 +1,8 @@
#!/usr/bin/env bash
# The real benchmark. Needs a running Ollama with the models pulled (see README) and: pip install mcp
# scripts/benchmark.sh # the six models from the post, 3 runs each
# MODELS=llama3.2:3b RUNS=1 scripts/benchmark.sh
source "$(dirname "$0")/_cp.sh"
MODELS="${MODELS:-qwen3:0.6b,qwen3:1.7b,llama3.2:1b,llama3.2:3b,qwen2.5:1.5b,granite3.3:2b}"
java -cp "$CP" com.ankurm.lc4j.localtools.Benchmark --models "$MODELS" --runs "${RUNS:-3}" --temp "${TEMPERATURE:-0.3}" \
--out results --python "${PYTHON:-python3}" --server mcp/tool_server.py 2>&1 | grep --line-buffered -v -e '^Picked up' -e '^\[main\] INFO'
+4
View File
@@ -0,0 +1,4 @@
#!/usr/bin/env bash
# MCP wiring only, no model. Needs: pip install mcp
source "$(dirname "$0")/_cp.sh"
java -cp "$CP" com.ankurm.lc4j.localtools.McpWiring "${PYTHON:-python3}" mcp/tool_server.py 2>&1 | grep -v -e '^Picked up' -e '^\[main\] INFO'
+2
View File
@@ -0,0 +1,2 @@
#!/usr/bin/env bash
for m in qwen3:0.6b qwen3:1.7b llama3.2:1b llama3.2:3b qwen2.5:1.5b granite3.3:2b; do ollama pull "$m"; done
+32
View File
@@ -0,0 +1,32 @@
#!/usr/bin/env python3
"""ENVEL = the subset of SCHEMA where the real arguments arrive wrapped in an envelope, under a "parameters" or "arguments" key.
Reads results/*.jsonl (written by Benchmark) and prints one summary table. Pure counting, no model involved."""
import glob, json, collections, sys
ORDER = ["VALID", "HALLUCINATED_TOOL", "SCHEMA_INVALID", "WRONG_TOOL", "WRONG_VALUE", "PARTIAL", "NO_CALL", "SPURIOUS_CALL"]
HEAD = ["VALID", "HALLU", "SCHEMA", "WTOOL", "WVAL", "PART", "NOCALL", "SPUR"]
args = [x for x in sys.argv[1:] if not x.startswith("--")]
files = sorted(glob.glob((args[0] if args else "results") + "/*.jsonl"))
print(f"{'model':<14} {'n':>3} " + " ".join(f"{h:>6}" for h in HEAD) + f" {'ENVEL':>6} {'JSONtx':>6} {'s/call':>7}")
for f in files:
rows = [json.loads(l) for l in open(f)]
c = collections.Counter(r["outcome"] for r in rows)
env = sum(1 for r in rows if r["outcome"] == "SCHEMA_INVALID" and any("unknown argument 'parameters'" in n or "unknown argument 'arguments'" in n for n in r["notes"]))
jt = sum(1 for r in rows if r["jsonInText"])
sec = sum(r["ms"] for r in rows) / len(rows) / 1000
print(f"{rows[0]['model']:<14} {len(rows):>3} " + " ".join(f"{c.get(o, 0):>6}" for o in ORDER) + f" {env:>6} {jt:>6} {sec:>7.1f}")
# Per-case view: how many of the runs were VALID for each prompt.
if "--cases" in sys.argv:
by = collections.defaultdict(collections.Counter)
models = []
for f in files:
rows = [json.loads(l) for l in open(f)]
models.append(rows[0]["model"])
for r in rows:
by[r["case"]][(r["model"], "n")] += 1
by[r["case"]][(r["model"], "ok")] += r["outcome"] == "VALID"
print()
print(f"{'case':<24} " + " ".join(f"{m:>13}" for m in models))
for case in sorted(by):
print(f"{case:<24} " + " ".join(f"{str(by[case][(m, 'ok')]) + '/' + str(by[case][(m, 'n')]):>13}" for m in models))
@@ -0,0 +1,112 @@
package com.ankurm.lc4j.localtools;
import com.fasterxml.jackson.databind.ObjectMapper;
import dev.langchain4j.agent.tool.ToolExecutionRequest;
import dev.langchain4j.agent.tool.ToolSpecification;
import dev.langchain4j.data.message.AiMessage;
import dev.langchain4j.data.message.SystemMessage;
import dev.langchain4j.data.message.UserMessage;
import dev.langchain4j.mcp.client.McpClient;
import dev.langchain4j.model.chat.ChatModel;
import dev.langchain4j.model.chat.request.ChatRequest;
import dev.langchain4j.model.chat.response.ChatResponse;
import dev.langchain4j.model.ollama.OllamaChatModel;
import java.nio.file.*;
import java.time.Duration;
import java.util.*;
/**
* Runs the same twelve prompts, with the same tool suite, against each Ollama model, several times each,
* and counts what came back. The tool definitions are fetched from the MCP server, so the schema the model
* sees is exactly what an MCP client would hand it.
*
* Usage: Benchmark --models qwen3:1.7b,llama3.2:3b [--runs 3] [--temp 0.3] [--out results]
* [--ollama http://localhost:11434] [--python python3] [--server mcp/tool_server.py]
*/
public final class Benchmark {
static final String SYSTEM = "You are an assistant with access to tools. Call a tool when one fits the request; otherwise answer directly.";
static final ObjectMapper JSON = new ObjectMapper();
public static void main(String[] a) throws Exception {
Map<String, String> o = opts(a);
List<String> models = Arrays.asList(o.getOrDefault("models", "qwen3:1.7b").split(","));
int runs = Integer.parseInt(o.getOrDefault("runs", "3"));
double temp = Double.parseDouble(o.getOrDefault("temp", "0.3"));
Path out = Path.of(o.getOrDefault("out", "results"));
Files.createDirectories(out);
try (McpClient mcp = McpTools.connect(o.getOrDefault("python", "python3"), o.getOrDefault("server", "mcp/tool_server.py"))) {
List<ToolSpecification> tools = mcp.listTools();
Scorer scorer = new Scorer(tools);
List<ToolCase> cases = ToolCase.all();
System.out.println("tools from MCP: " + tools.stream().map(ToolSpecification::name).toList());
System.out.printf("%d cases x %d runs, temperature %.1f%n%n", cases.size(), runs, temp);
List<String> summary = new ArrayList<>();
for (String name : models) {
ChatModel model = OllamaChatModel.builder()
.baseUrl(o.getOrDefault("ollama", "http://localhost:11434"))
.modelName(name).temperature(temp).think(false).numPredict(400)
.timeout(Duration.ofMinutes(10)).build();
Map<Outcome, Integer> counts = new EnumMap<>(Outcome.class);
int jsonInText = 0;
long totalMs = 0;
int n = 0;
StringBuilder lines = new StringBuilder();
for (ToolCase tc : cases) {
for (int r = 1; r <= runs; r++) {
long t0 = System.nanoTime();
ChatResponse resp = model.chat(ChatRequest.builder()
.messages(SystemMessage.from(SYSTEM), UserMessage.from(tc.prompt()))
.toolSpecifications(tools).build());
long ms = (System.nanoTime() - t0) / 1_000_000;
AiMessage ai = resp.aiMessage();
List<ToolExecutionRequest> calls = ai.toolExecutionRequests() == null ? List.of() : ai.toolExecutionRequests();
Scorer.Result res = scorer.score(tc, calls);
String text = ai.text() == null ? "" : ai.text();
boolean jit = calls.isEmpty() && text.contains("{") && text.contains("\"name\"");
if (jit) jsonInText++;
counts.merge(res.outcome(), 1, Integer::sum);
totalMs += ms; n++;
Map<String, Object> rec = new LinkedHashMap<>();
rec.put("model", name); rec.put("case", tc.id()); rec.put("run", r);
rec.put("outcome", res.outcome().name());
rec.put("calls", calls.stream().map(c -> c.name() + c.arguments()).toList());
rec.put("notes", res.notes()); rec.put("jsonInText", jit);
rec.put("text", text.length() > 160 ? text.substring(0, 160) + "..." : text);
rec.put("ms", ms);
lines.append(JSON.writeValueAsString(rec)).append('\n');
System.out.printf("%-14s %-24s run %d %-17s %5d ms%n", name, tc.id(), r, res.outcome(), ms);
}
}
Files.writeString(out.resolve(name.replace(':', '_') + ".jsonl"), lines.toString());
StringBuilder row = new StringBuilder(String.format("%-14s %3d", name, n));
for (Outcome oc : Outcome.values()) row.append(String.format(" %6d", counts.getOrDefault(oc, 0)));
row.append(String.format(" %6d %7.1f", jsonInText, totalMs / 1000.0 / n));
summary.add(row.toString());
}
StringBuilder head = new StringBuilder(String.format("%-14s %3s", "model", "n"));
for (Outcome oc : Outcome.values()) head.append(String.format(" %6s", abbrev(oc)));
head.append(String.format(" %6s %7s", "JSONtx", "s/call"));
System.out.println("\n" + head);
summary.forEach(System.out::println);
Files.writeString(out.resolve("summary.txt"), head + "\n" + String.join("\n", summary) + "\n");
}
}
static String abbrev(Outcome o) {
return switch (o) {
case HALLUCINATED_TOOL -> "HALLU"; case SCHEMA_INVALID -> "SCHEMA"; case WRONG_TOOL -> "WTOOL";
case WRONG_VALUE -> "WVAL"; case PARTIAL -> "PART"; case NO_CALL -> "NOCALL";
case SPURIOUS_CALL -> "SPUR"; case VALID -> "VALID";
};
}
static Map<String, String> opts(String[] a) {
Map<String, String> m = new HashMap<>();
for (int i = 0; i + 1 < a.length; i += 2) m.put(a[i].replaceFirst("^--", ""), a[i + 1]);
return m;
}
}
@@ -0,0 +1,24 @@
package com.ankurm.lc4j.localtools;
import dev.langchain4j.mcp.client.DefaultMcpClient;
import dev.langchain4j.mcp.client.McpClient;
import dev.langchain4j.mcp.client.transport.stdio.StdioMcpTransport;
import java.util.List;
/** Starts mcp/tool_server.py as a child process and returns a connected MCP client. */
public final class McpTools {
private McpTools() {}
public static McpClient connect(String pythonExe, String serverScript) {
StdioMcpTransport transport = StdioMcpTransport.builder()
.command(List.of(pythonExe, serverScript))
.logEvents(false)
.build();
return DefaultMcpClient.builder()
.key("local-tool-suite")
.transport(transport)
.build();
}
}
@@ -0,0 +1,25 @@
package com.ankurm.lc4j.localtools;
import dev.langchain4j.agent.tool.ToolExecutionRequest;
import dev.langchain4j.agent.tool.ToolSpecification;
import dev.langchain4j.mcp.client.McpClient;
import dev.langchain4j.service.tool.ToolExecutionResult;
import java.util.List;
/** Shows the MCP wiring alone: connect, list tools, print the schema a model would see, execute one call. No model involved. */
public final class McpWiring {
public static void main(String[] a) throws Exception {
try (McpClient mcp = McpTools.connect(a.length > 0 ? a[0] : "python3", a.length > 1 ? a[1] : "mcp/tool_server.py")) {
List<ToolSpecification> tools = mcp.listTools();
for (ToolSpecification t : tools) {
System.out.println(t.name() + " -> " + t.description());
System.out.println(" schema: " + t.parameters());
}
ToolExecutionResult r = mcp.executeTool(ToolExecutionRequest.builder()
.name("create_reminder").arguments("{\"text\":\"call the vendor\",\"minutes_from_now\":120}").build());
System.out.println("\nexecuteTool(create_reminder) -> " + r.resultText());
}
}
}
@@ -0,0 +1,21 @@
package com.ankurm.lc4j.localtools;
/** What one model response turned out to be. Listed in the priority order used when a response has several problems. */
public enum Outcome {
/** Hallucinated: a tool name that is not in the registry. */
HALLUCINATED_TOOL,
/** Right tool, arguments that violate the tool's own JSON schema (missing required, wrong type, bad enum, unknown key). */
SCHEMA_INVALID,
/** A real tool, but not the one the prompt called for. */
WRONG_TOOL,
/** Right tool, schema-valid arguments, wrong values (for example 2 hours turned into 2 minutes). */
WRONG_VALUE,
/** Multi-call prompt where only some of the expected calls were made. */
PARTIAL,
/** A tool was expected and the model answered in plain text instead. */
NO_CALL,
/** No tool was expected and the model called one anyway. */
SPURIOUS_CALL,
/** Exactly what the prompt called for (including a correct refusal to call anything). */
VALID
}
@@ -0,0 +1,145 @@
package com.ankurm.lc4j.localtools;
import com.fasterxml.jackson.databind.JsonNode;
import com.fasterxml.jackson.databind.ObjectMapper;
import dev.langchain4j.agent.tool.ToolExecutionRequest;
import dev.langchain4j.agent.tool.ToolSpecification;
import dev.langchain4j.model.chat.request.json.*;
import java.util.*;
/**
* Turns "what the model asked for" into one {@link Outcome}. Pure logic, no model involved,
* so it is unit-tested with hand-written requests (see ScorerTest).
*/
public final class Scorer {
private static final ObjectMapper JSON = new ObjectMapper();
private final Map<String, ToolSpecification> registry = new LinkedHashMap<>();
public Scorer(List<ToolSpecification> tools) {
tools.forEach(t -> registry.put(t.name(), t));
}
public record Result(Outcome outcome, List<String> notes) {}
public Result score(ToolCase tc, List<ToolExecutionRequest> calls) {
List<String> notes = new ArrayList<>();
if (calls.isEmpty()) {
return new Result(tc.expected().isEmpty() ? Outcome.VALID : Outcome.NO_CALL, notes);
}
if (tc.expected().isEmpty()) {
boolean ghost = calls.stream().anyMatch(c -> !registry.containsKey(c.name()));
calls.forEach(c -> notes.add("unexpected call " + c.name() + c.arguments()));
return new Result(ghost ? Outcome.HALLUCINATED_TOOL : Outcome.SPURIOUS_CALL, notes);
}
Set<Outcome> seen = EnumSet.noneOf(Outcome.class);
List<ToolCase.Expected> unmatched = new ArrayList<>(tc.expected());
for (ToolExecutionRequest call : calls) {
ToolSpecification spec = registry.get(call.name());
if (spec == null) {
seen.add(Outcome.HALLUCINATED_TOOL);
notes.add("no such tool: " + call.name());
continue;
}
JsonNode args = parse(call.arguments());
List<String> problems = schemaProblems(spec, args);
if (!problems.isEmpty()) {
seen.add(Outcome.SCHEMA_INVALID);
notes.add(call.name() + ": " + String.join("; ", problems));
continue;
}
Optional<ToolCase.Expected> sameTool = unmatched.stream().filter(e -> e.tool().equals(call.name())).findFirst();
if (sameTool.isEmpty()) {
seen.add(Outcome.WRONG_TOOL);
notes.add("called " + call.name() + " but expected " + tc.expected().stream().map(ToolCase.Expected::tool).toList());
continue;
}
List<String> wrong = valueProblems(sameTool.get(), args);
if (wrong.isEmpty()) {
unmatched.remove(sameTool.get());
} else {
seen.add(Outcome.WRONG_VALUE);
notes.add(call.name() + ": " + String.join("; ", wrong));
unmatched.remove(sameTool.get());
}
}
for (Outcome o : Outcome.values()) { // enum order = priority order
if (seen.contains(o)) return new Result(o, notes);
}
if (!unmatched.isEmpty()) {
notes.add("missing: " + unmatched.stream().map(ToolCase.Expected::tool).toList());
return new Result(Outcome.PARTIAL, notes);
}
return new Result(Outcome.VALID, notes);
}
// ---- schema validation (the part a local model most often fails) ---------------------------
static List<String> schemaProblems(ToolSpecification spec, JsonNode args) {
List<String> problems = new ArrayList<>();
JsonObjectSchema schema = spec.parameters();
if (args == null || !args.isObject()) {
problems.add("arguments are not a JSON object");
return problems;
}
Map<String, JsonSchemaElement> props = schema == null ? Map.of() : schema.properties();
List<String> required = schema == null || schema.required() == null ? List.of() : schema.required();
for (String r : required) {
if (!args.has(r) || args.get(r).isNull()) problems.add("missing required '" + r + "'");
}
args.fieldNames().forEachRemaining(name -> {
JsonSchemaElement el = props.get(name);
if (el == null) {
problems.add("unknown argument '" + name + "'");
return;
}
JsonNode v = args.get(name);
if (v.isNull()) return;
String err = typeProblem(el, v);
if (err != null) problems.add("'" + name + "' " + err);
});
return problems;
}
private static String typeProblem(JsonSchemaElement el, JsonNode v) {
if (el instanceof JsonAnyOfSchema any) { // Optional[int] arrives from MCP as anyOf [integer, null]
String last = "matches no anyOf branch";
for (JsonSchemaElement branch : any.anyOf()) {
if (branch instanceof JsonNullSchema) continue;
String err = typeProblem(branch, v);
if (err == null) return null;
last = err;
}
return last;
}
if (el instanceof JsonStringSchema && !v.isTextual()) return "should be a string, got " + v.getNodeType();
if (el instanceof JsonIntegerSchema && !v.isIntegralNumber()) return "should be an integer, got " + v;
if (el instanceof JsonNumberSchema && !v.isNumber()) return "should be a number, got " + v.getNodeType();
if (el instanceof JsonBooleanSchema && !v.isBoolean()) return "should be a boolean, got " + v.getNodeType();
if (el instanceof JsonEnumSchema e && !(v.isTextual() && e.enumValues().contains(v.asText())))
return "should be one of " + e.enumValues() + ", got " + v;
return null;
}
private static List<String> valueProblems(ToolCase.Expected exp, JsonNode args) {
List<String> out = new ArrayList<>();
exp.argChecks().forEach((name, check) -> {
JsonNode n = args.get(name);
Object val = n == null ? null : n.isNumber() ? (Object) n.numberValue() : n.isTextual() ? n.asText() : n.toString();
if (val == null || !check.test(val)) out.add("'" + name + "' = " + (n == null ? "<absent>" : n));
});
return out;
}
private static JsonNode parse(String json) {
try {
return JSON.readTree(json == null || json.isBlank() ? "{}" : json);
} catch (Exception e) {
return null;
}
}
}
@@ -0,0 +1,65 @@
package com.ankurm.lc4j.localtools;
import java.util.List;
import java.util.Map;
import java.util.function.Predicate;
/**
* One benchmark prompt and what a correct response looks like.
* An empty expectation list means "answer in text, call nothing".
*/
public record ToolCase(String id, String prompt, List<Expected> expected) {
/** One expected call: a tool name plus a checker per argument. Arguments not listed are not value-checked. */
public record Expected(String tool, Map<String, Predicate<Object>> argChecks) {}
// ---- argument matchers ----------------------------------------------------------------
static Predicate<Object> eqIgnoreCase(String s) {
return v -> v instanceof String x && x.trim().equalsIgnoreCase(s);
}
static Predicate<Object> contains(String s) {
return v -> v instanceof String x && x.toLowerCase().contains(s.toLowerCase());
}
static Predicate<Object> num(double d) {
return v -> v instanceof Number n && Math.abs(n.doubleValue() - d) < 1e-9;
}
private static Expected call(String tool, Object... kv) {
Map<String, Predicate<Object>> m = new java.util.LinkedHashMap<>();
for (int i = 0; i < kv.length; i += 2) {
@SuppressWarnings("unchecked") Predicate<Object> p = (Predicate<Object>) kv[i + 1];
m.put((String) kv[i], p);
}
return new Expected(tool, m);
}
/** The twelve prompts. Seven single-call, one two-call, three "no tool should be called" traps, one unit-conversion trap. */
public static List<ToolCase> all() {
return List.of(
new ToolCase("01-weather-plain", "What's the weather in Pune right now?",
List.of(call("get_weather", "city", eqIgnoreCase("Pune")))),
new ToolCase("02-weather-unit-enum", "What is the temperature in Chicago? I want it in Fahrenheit.",
List.of(call("get_weather", "city", eqIgnoreCase("Chicago"), "unit", eqIgnoreCase("fahrenheit")))),
new ToolCase("03-currency-codes", "Convert 250 US dollars to Indian rupees.",
List.of(call("convert_currency", "amount", num(250), "from_currency", eqIgnoreCase("USD"), "to_currency", eqIgnoreCase("INR")))),
new ToolCase("04-currency-big-number", "How much is 1200 euros in Japanese yen?",
List.of(call("convert_currency", "amount", num(1200), "from_currency", eqIgnoreCase("EUR"), "to_currency", eqIgnoreCase("JPY")))),
new ToolCase("05-reminder-minutes", "Remind me to submit the timesheet in 45 minutes.",
List.of(call("create_reminder", "text", contains("timesheet"), "minutes_from_now", num(45)))),
new ToolCase("06-reminder-unit-trap", "Set a reminder to call the vendor in 2 hours.",
List.of(call("create_reminder", "text", contains("vendor"), "minutes_from_now", num(120)))),
new ToolCase("07-notes-optional-int", "Search my notes for the Kubernetes upgrade, give me at most 3 results.",
List.of(call("search_notes", "query", contains("kubernetes"), "limit", num(3)))),
new ToolCase("08-notes-no-limit", "Look through my notes for anything about invoice disputes.",
List.of(call("search_notes", "query", contains("invoice")))),
new ToolCase("09-two-calls", "Check the weather in Mumbai and also convert 100 British pounds to Indian rupees.",
List.of(call("get_weather", "city", eqIgnoreCase("Mumbai")),
call("convert_currency", "amount", num(100), "from_currency", eqIgnoreCase("GBP"), "to_currency", eqIgnoreCase("INR")))),
new ToolCase("10-no-tool-knowledge", "What is the capital of France?", List.of()),
new ToolCase("11-no-tool-chat", "Say hello in Marathi.", List.of()),
new ToolCase("12-no-such-tool", "Email the weekly status report to my manager.", List.of()));
}
}
@@ -0,0 +1,76 @@
package com.ankurm.lc4j.localtools;
import dev.langchain4j.agent.tool.ToolExecutionRequest;
import dev.langchain4j.agent.tool.ToolSpecification;
import dev.langchain4j.model.chat.request.json.*;
import org.junit.jupiter.api.Test;
import java.util.List;
import static org.assertj.core.api.Assertions.assertThat;
/**
* Tests the scoring logic only, with hand-written tool requests. No model is involved and nothing here says
* anything about how any real model behaves; those numbers come from Benchmark.
*/
class ScorerTest {
static final ToolSpecification REMINDER = ToolSpecification.builder().name("create_reminder")
.parameters(JsonObjectSchema.builder()
.addStringProperty("text").addIntegerProperty("minutes_from_now")
.required("text", "minutes_from_now").build()).build();
static final ToolSpecification WEATHER = ToolSpecification.builder().name("get_weather")
.parameters(JsonObjectSchema.builder().addStringProperty("city")
.addEnumProperty("unit", List.of("celsius", "fahrenheit")).required("city").build()).build();
final Scorer scorer = new Scorer(List.of(REMINDER, WEATHER));
final ToolCase hours = ToolCase.all().stream().filter(c -> c.id().startsWith("06")).findFirst().orElseThrow();
final ToolCase capital = ToolCase.all().stream().filter(c -> c.id().startsWith("10")).findFirst().orElseThrow();
static ToolExecutionRequest call(String name, String args) {
return ToolExecutionRequest.builder().name(name).arguments(args).build();
}
@Test void validCall() {
assertThat(scorer.score(hours, List.of(call("create_reminder", "{\"text\":\"call the vendor\",\"minutes_from_now\":120}"))).outcome())
.isEqualTo(Outcome.VALID);
}
@Test void hoursBecomingMinutesIsAWrongValueNotASchemaError() {
assertThat(scorer.score(hours, List.of(call("create_reminder", "{\"text\":\"call the vendor\",\"minutes_from_now\":2}"))).outcome())
.isEqualTo(Outcome.WRONG_VALUE);
}
@Test void stringWhereIntegerRequiredIsSchemaInvalid() {
assertThat(scorer.score(hours, List.of(call("create_reminder", "{\"text\":\"call the vendor\",\"minutes_from_now\":\"2 hours\"}"))).outcome())
.isEqualTo(Outcome.SCHEMA_INVALID);
}
@Test void missingRequiredAndUnknownKeysAreSchemaInvalid() {
assertThat(scorer.score(hours, List.of(call("create_reminder", "{\"text\":\"x\"}"))).outcome()).isEqualTo(Outcome.SCHEMA_INVALID);
assertThat(scorer.score(hours, List.of(call("create_reminder", "{\"text\":\"x\",\"minutes_from_now\":120,\"when\":\"later\"}"))).outcome())
.isEqualTo(Outcome.SCHEMA_INVALID);
}
@Test void inventedToolIsHallucinated() {
assertThat(scorer.score(hours, List.of(call("set_timer", "{\"minutes\":120}"))).outcome()).isEqualTo(Outcome.HALLUCINATED_TOOL);
}
@Test void realButWrongToolIsWrongTool() {
assertThat(scorer.score(hours, List.of(call("get_weather", "{\"city\":\"Pune\"}"))).outcome()).isEqualTo(Outcome.WRONG_TOOL);
}
@Test void answeringInTextWhenAToolWasNeededIsNoCall() {
assertThat(scorer.score(hours, List.of()).outcome()).isEqualTo(Outcome.NO_CALL);
}
@Test void callingAToolForAGeneralKnowledgeQuestionIsSpurious() {
assertThat(scorer.score(capital, List.of(call("get_weather", "{\"city\":\"Paris\"}"))).outcome()).isEqualTo(Outcome.SPURIOUS_CALL);
assertThat(scorer.score(capital, List.of()).outcome()).isEqualTo(Outcome.VALID);
}
@Test void enumViolationIsSchemaInvalid() {
ToolCase c = ToolCase.all().get(1);
assertThat(scorer.score(c, List.of(call("get_weather", "{\"city\":\"Chicago\",\"unit\":\"F\"}"))).outcome()).isEqualTo(Outcome.SCHEMA_INVALID);
}
}