diff --git a/README.md b/README.md index 23cca14..6a89e4b 100644 --- a/README.md +++ b/README.md @@ -10,6 +10,7 @@ the same facts, so the build fails when a claim stops being true. | `spring-boot-ai-service` | same post | `@AiService` on Spring Boot 4.1.1 with the 1.22.0-beta32 starter | | `agentic` | Agentic Workflows with LangChain4j: Sequential, Parallel, Loop and Supervisor Agents | the five workflow builders, state passing by key, supervisor JSON, error recovery | | `advanced-rag` | Advanced RAG with LangChain4j: Query Transformation, Routing and Easy RAG | Easy RAG, query compression and expansion, query routing, minScore, content injection, chat-memory cost, `Result.sources()` | +| `local-tool-calling` | Tool Calling with Small Local Models: Which Ollama Models Actually Follow Your Schema? | six small Ollama models on the same MCP-served tool suite, scored for valid calls, schema violations, wrong values and spurious calls | ## Versions (verified on Maven Central, 2026-10-11) @@ -21,7 +22,7 @@ the same facts, so the build fails when a claim stops being true. | JDK | 25 LTS | | | JUnit | 6.1.3 | | -`advanced-rag` is built against LangChain4j **1.23.0** (`langchain4j-easy-rag` and the bundled bge-small embeddings are `1.23.0-beta33`, published to Maven Central on 2026-10-28; neither has a GA release). It overrides the 1.22.0 BOM above for that module only. +`local-tool-calling` is built against LangChain4j **1.24.0** (`langchain4j-mcp` is `1.24.0-beta34`, beta only) and needs a local Ollama for its benchmark (its unit tests run offline). `advanced-rag` is built against LangChain4j **1.23.0** (`langchain4j-easy-rag` and the bundled bge-small embeddings are `1.23.0-beta33`, published to Maven Central on 2026-10-28; neither has a GA release). It overrides the 1.22.0 BOM above for that module only. ## Run diff --git a/local-tool-calling/.gitignore b/local-tool-calling/.gitignore new file mode 100644 index 0000000..5a28a3d --- /dev/null +++ b/local-tool-calling/.gitignore @@ -0,0 +1,2 @@ +results/ +target/ diff --git a/local-tool-calling/README.md b/local-tool-calling/README.md new file mode 100644 index 0000000..1d06a23 --- /dev/null +++ b/local-tool-calling/README.md @@ -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/.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. diff --git a/local-tool-calling/mcp/tool_server.py b/local-tool-calling/mcp/tool_server.py new file mode 100644 index 0000000..89c8084 --- /dev/null +++ b/local-tool-calling/mcp/tool_server.py @@ -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") diff --git a/local-tool-calling/pom.xml b/local-tool-calling/pom.xml new file mode 100644 index 0000000..a3ed466 --- /dev/null +++ b/local-tool-calling/pom.xml @@ -0,0 +1,65 @@ + + + 4.0.0 + + + com.ankurm.langchain4j + langchain4j-demo + 1.0.0 + + + local-tool-calling + + + + 1.24.0 + 1.24.0-beta34 + + + + + + dev.langchain4j + langchain4j-bom + ${lc4j.tools.version} + pom + import + + + + + + + dev.langchain4j + langchain4j + + + dev.langchain4j + langchain4j-ollama + + + + dev.langchain4j + langchain4j-mcp + ${lc4j.tools.beta.version} + + + org.slf4j + slf4j-simple + ${slf4j.version} + + + org.junit.jupiter + junit-jupiter + test + + + org.assertj + assertj-core + ${assertj.version} + test + + + diff --git a/local-tool-calling/scripts/_cp.sh b/local-tool-calling/scripts/_cp.sh new file mode 100755 index 0000000..61e80e9 --- /dev/null +++ b/local-tool-calling/scripts/_cp.sh @@ -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)" diff --git a/local-tool-calling/scripts/benchmark.sh b/local-tool-calling/scripts/benchmark.sh new file mode 100755 index 0000000..8f933c9 --- /dev/null +++ b/local-tool-calling/scripts/benchmark.sh @@ -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' diff --git a/local-tool-calling/scripts/mcp-wiring.sh b/local-tool-calling/scripts/mcp-wiring.sh new file mode 100755 index 0000000..bcaa897 --- /dev/null +++ b/local-tool-calling/scripts/mcp-wiring.sh @@ -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' diff --git a/local-tool-calling/scripts/pull-models.sh b/local-tool-calling/scripts/pull-models.sh new file mode 100755 index 0000000..f2ff377 --- /dev/null +++ b/local-tool-calling/scripts/pull-models.sh @@ -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 diff --git a/local-tool-calling/scripts/summarize.py b/local-tool-calling/scripts/summarize.py new file mode 100755 index 0000000..7a15822 --- /dev/null +++ b/local-tool-calling/scripts/summarize.py @@ -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)) diff --git a/local-tool-calling/src/main/java/com/ankurm/lc4j/localtools/Benchmark.java b/local-tool-calling/src/main/java/com/ankurm/lc4j/localtools/Benchmark.java new file mode 100644 index 0000000..803c9be --- /dev/null +++ b/local-tool-calling/src/main/java/com/ankurm/lc4j/localtools/Benchmark.java @@ -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 o = opts(a); + List 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 tools = mcp.listTools(); + Scorer scorer = new Scorer(tools); + List 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 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 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 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 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 opts(String[] a) { + Map m = new HashMap<>(); + for (int i = 0; i + 1 < a.length; i += 2) m.put(a[i].replaceFirst("^--", ""), a[i + 1]); + return m; + } +} diff --git a/local-tool-calling/src/main/java/com/ankurm/lc4j/localtools/McpTools.java b/local-tool-calling/src/main/java/com/ankurm/lc4j/localtools/McpTools.java new file mode 100644 index 0000000..95ae878 --- /dev/null +++ b/local-tool-calling/src/main/java/com/ankurm/lc4j/localtools/McpTools.java @@ -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(); + } +} diff --git a/local-tool-calling/src/main/java/com/ankurm/lc4j/localtools/McpWiring.java b/local-tool-calling/src/main/java/com/ankurm/lc4j/localtools/McpWiring.java new file mode 100644 index 0000000..fa84a51 --- /dev/null +++ b/local-tool-calling/src/main/java/com/ankurm/lc4j/localtools/McpWiring.java @@ -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 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()); + } + } +} diff --git a/local-tool-calling/src/main/java/com/ankurm/lc4j/localtools/Outcome.java b/local-tool-calling/src/main/java/com/ankurm/lc4j/localtools/Outcome.java new file mode 100644 index 0000000..6a2d403 --- /dev/null +++ b/local-tool-calling/src/main/java/com/ankurm/lc4j/localtools/Outcome.java @@ -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 +} diff --git a/local-tool-calling/src/main/java/com/ankurm/lc4j/localtools/Scorer.java b/local-tool-calling/src/main/java/com/ankurm/lc4j/localtools/Scorer.java new file mode 100644 index 0000000..54db530 --- /dev/null +++ b/local-tool-calling/src/main/java/com/ankurm/lc4j/localtools/Scorer.java @@ -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 registry = new LinkedHashMap<>(); + + public Scorer(List tools) { + tools.forEach(t -> registry.put(t.name(), t)); + } + + public record Result(Outcome outcome, List notes) {} + + public Result score(ToolCase tc, List calls) { + List 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 seen = EnumSet.noneOf(Outcome.class); + List 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 problems = schemaProblems(spec, args); + if (!problems.isEmpty()) { + seen.add(Outcome.SCHEMA_INVALID); + notes.add(call.name() + ": " + String.join("; ", problems)); + continue; + } + Optional 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 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 schemaProblems(ToolSpecification spec, JsonNode args) { + List problems = new ArrayList<>(); + JsonObjectSchema schema = spec.parameters(); + if (args == null || !args.isObject()) { + problems.add("arguments are not a JSON object"); + return problems; + } + Map props = schema == null ? Map.of() : schema.properties(); + List 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 valueProblems(ToolCase.Expected exp, JsonNode args) { + List 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 ? "" : n)); + }); + return out; + } + + private static JsonNode parse(String json) { + try { + return JSON.readTree(json == null || json.isBlank() ? "{}" : json); + } catch (Exception e) { + return null; + } + } +} diff --git a/local-tool-calling/src/main/java/com/ankurm/lc4j/localtools/ToolCase.java b/local-tool-calling/src/main/java/com/ankurm/lc4j/localtools/ToolCase.java new file mode 100644 index 0000000..311a9b0 --- /dev/null +++ b/local-tool-calling/src/main/java/com/ankurm/lc4j/localtools/ToolCase.java @@ -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) { + + /** One expected call: a tool name plus a checker per argument. Arguments not listed are not value-checked. */ + public record Expected(String tool, Map> argChecks) {} + + // ---- argument matchers ---------------------------------------------------------------- + + static Predicate eqIgnoreCase(String s) { + return v -> v instanceof String x && x.trim().equalsIgnoreCase(s); + } + + static Predicate contains(String s) { + return v -> v instanceof String x && x.toLowerCase().contains(s.toLowerCase()); + } + + static Predicate 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> m = new java.util.LinkedHashMap<>(); + for (int i = 0; i < kv.length; i += 2) { + @SuppressWarnings("unchecked") Predicate p = (Predicate) 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 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())); + } +} diff --git a/local-tool-calling/src/test/java/com/ankurm/lc4j/localtools/ScorerTest.java b/local-tool-calling/src/test/java/com/ankurm/lc4j/localtools/ScorerTest.java new file mode 100644 index 0000000..ac51567 --- /dev/null +++ b/local-tool-calling/src/test/java/com/ankurm/lc4j/localtools/ScorerTest.java @@ -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); + } +} diff --git a/pom.xml b/pom.xml index b4f8e5b..9e0ba48 100644 --- a/pom.xml +++ b/pom.xml @@ -14,6 +14,7 @@ spring-boot-ai-service agentic advanced-rag + local-tool-calling