From 035c46062fa0ddc98b00ae12c802b4460c313f86 Mon Sep 17 00:00:00 2001 From: Dan Goodliffe Date: Fri, 19 Jun 2026 12:38:36 +0100 Subject: Tidy callAPI_chatJSON and improve error handling --- scripts/toy.groovy | 34 +++++++++++++++++++++++++--------- 1 file changed, 25 insertions(+), 9 deletions(-) (limited to 'scripts/toy.groovy') diff --git a/scripts/toy.groovy b/scripts/toy.groovy index 6ee876c..8b21069 100644 --- a/scripts/toy.groovy +++ b/scripts/toy.groovy @@ -391,17 +391,33 @@ return new Object() { } final callAPI_chatJSON = { messages, prompt, jspec -> - messages += [role: "user", content: """ -Write only a JSON object. -${prompt} - { -${jspec.collect{ k, v -> "\"${k}\": ${v}" }.join(",\n")} - }"""]; - return parseJsonString(callAPI("chat/completions", [ + final request = [ model: loadString("toy.chatModel"), stop: "<", - messages: messages - ])?.choices?[0]?.message?.content); + messages: messages + [ + role: "user", content: """ +${prompt} +Write only a JSON object. +{ +${jspec.collect{ k, v -> "\"${k}\": ${v}" }.join(",\n ")} +}"""], + response_format: "json" + ]; + while (true) { + final responseString = callAPI("chat/completions", request)?.choices?[0]?.message?.content?.trim(); + if (responseString.startsWith("{")) { + def response = null; + try { + response = parseJsonString(responseString); + if (jspec.keySet().each{ response[it]; }) { + return response; + } + } + catch (Exception e){ + } + } + show("Asked for JSON with fields [${jspec.keySet().join(", ")}], got back:\n${responseString}\n\nWill ask again..."); + } } final chatInitialMessages = { String ... extra -> -- cgit v1.3