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:
co-authored by
Claude Sonnet 5.5
parent
ae8fe985b4
commit
49ae6530f4
@@ -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);
|
||||
}
|
||||
}
|
||||
Reference in New Issue
Block a user