diff --git a/Makefile b/Makefile index 740f337..27bb4cd 100644 --- a/Makefile +++ b/Makefile @@ -162,6 +162,12 @@ HDRS = include/splinter.h include/splinter_engine.h include/splinter_plugin.h \ src/backend/curl.h src/backend/log.h src/backend/i18n.h src/backend/md.h src/backend/b64.h src/backend/a2aserver.h $(LIBOBJ) $(BINOBJ): $(HDRS) $(PLUGIN): $(HDRS) +# +# The tests too: a test that allocates a struct sp_reply by value and +# links a freshly built library is one header change away from reading +# the fields of a different layout. That failure looks like a broken +# test, not like a stale object, so it costs an hour every time. +$(TESTS): $(HDRS) src/backend/agent.o: include/splinter.h src/backend/buf.o: include/splinter.h diff --git a/include/splinter.h b/include/splinter.h index a7b743c..036934d 100644 --- a/include/splinter.h +++ b/include/splinter.h @@ -171,6 +171,14 @@ struct sp_reply { char judge_cache[8]; char cache_mode[8]; /* X-Junction-Cache: off/5m/1h */ + /* + * What the provider says ended the message: "stop", "length", + * "tool_calls", "max_tokens", "" when it did not say. A tool call + * cut off by the token limit is not the same as a broken one, and + * only this field tells them apart. + */ + char finish[24]; + char *content; /* assistant text, may be "" */ struct sp_toolcall *calls; char *calls_json; /* the provider's own tool_calls array */ diff --git a/src/backend/agent.c b/src/backend/agent.c index 22314ea..35b8552 100644 --- a/src/backend/agent.c +++ b/src/backend/agent.c @@ -419,6 +419,17 @@ limit_retry(struct sp_agent *a, struct sp_buf *err, long status, #define SP_NET_RETRIES 3 #define SP_NET_WAIT_S 5 +/* + * A tool call with broken JSON is a model step gone wrong, not a broken link: + * the same prompt tends to produce the same call. So each retry says what was + * wrong, and it waits like a network retry does -- five attempts in one + * millisecond bought nothing, which is why the operator still saw the error. + * + * After the last attempt the turn does not die: the model is asked for words + * instead ("look, then continue"), because the work in the session is worth + * more than an error message nobody can act on. + */ +#define SP_BAD_TOOL_TRIES 5 /* mark whether anything was streamed before an error: a retry after that * would print the same answer a second time */ @@ -719,6 +730,8 @@ agent_loop(struct sp_agent *a, struct sp_conv *conv, int resume, int decision, struct sp_buf obs; size_t step, i, mark; int rc = -1, limit_tries = 0, bad_tool_tries = 0; + /* the last request asked for words: whatever comes back ends the turn */ + int last_chance = 0; if (sp_buf_init(&obs) != 0) { sp_buf_puts(err, "agent: out of memory"); @@ -917,6 +930,31 @@ agent_loop(struct sp_agent *a, struct sp_conv *conv, int resume, int decision, (size_t)(reply.tokens_in > 0 ? reply.tokens_in : 0), (size_t)(reply.tokens_out > 0 ? reply.tokens_out : 0)); + if (last_chance && reply.ncalls > 0) { + /* + * The model was asked not to call a tool and called one + * anyway. It did not run and it will not: the turn ends on + * the words it wrote, and a call it never explained is + * not silently dropped - it is in the log. + */ + sp_logf("agent", "a call came back after the turn was " + "asked for words; it did not run: %.400s", + reply.calls[0].args != NULL ? + reply.calls[0].args : ""); + if (reply.content == NULL || reply.content[0] == '\0') { + free(reply.content); + reply.content = strdup( + "I could not send a runnable tool call: the " + "arguments were not valid JSON. Nothing ran. " + "The raw call is in the log; tell me how to " + "continue."); + if (reply.content == NULL) { + sp_reply_free(&reply); + goto oom; + } + } + reply.ncalls = 0; + } if (reply.ncalls == 0) { const char *text = reply.content != NULL ? reply.content : ""; @@ -941,15 +979,103 @@ agent_loop(struct sp_agent *a, struct sp_conv *conv, int resume, int decision, size_t bad = 0; if (!tool_args_valid(&reply, &bad)) { + /* + * A call the token limit cut off is not a call the model + * could not write: the same request truncates it again, + * so the correction has to ask for a *smaller* call. + */ + int cut_off = strcmp(reply.finish, "length") == 0 || + strcmp(reply.finish, "max_tokens") == 0; + const char *what = reply.calls[bad].args; + const char *name = reply.calls[bad].name != NULL ? + reply.calls[bad].name : "?"; + struct sp_buf note; + int push_rc; + + bad_tool_tries++; + /* + * The whole call, not 240 bytes of it: "mal gucken" + * means the operator can read what the model did. + */ sp_logf("agent", "malformed tool arguments for " - "%s: %.240s", reply.calls[bad].name, - reply.calls[bad].args != NULL ? - reply.calls[bad].args : ""); + "%s (try %d/%d, %zu bytes, finish=%s%s): %s", + name, bad_tool_tries, SP_BAD_TOOL_TRIES, + what != NULL ? strlen(what) : (size_t)0, + reply.finish[0] != '\0' ? reply.finish : "-", + cut_off ? ", cut off" : "", + what != NULL ? what : ""); sp_buf_clear(err); + if (sp_buf_init(¬e) != 0) + goto oom; + if (bad_tool_tries < SP_BAD_TOOL_TRIES) { + /* + * Asking again with the identical prompt asks + * for the identical call. Say what was wrong + * instead, and say it as a user message: a tool + * result without a call before it is refused by + * the endpoint. + */ + if (cut_off) + sp_buf_printf(¬e, + "That call (%s) was cut off by the " + "output limit, so its arguments are not " + "valid JSON (%s). Send a smaller call - " + "one command, short arguments - or answer " + "without a tool.", name, + what != NULL && what[0] != '\0' ? + what : "empty"); + else + sp_buf_printf(¬e, + "That call (%s) was not run: its arguments " + "are not valid JSON (%s). Send it again as one " + "complete JSON object, or answer without a " + "tool.", name, + what != NULL && what[0] != '\0' ? + what : "empty"); + } else { + /* + * The last word goes to words. The turn keeps + * its session and the operator gets an answer + * they can act on, instead of a turn that died + * on "model sent malformed tool arguments". + */ + sp_logf("agent", "no valid tool call after " + "%d tries: asking for words instead", + SP_BAD_TOOL_TRIES); + sp_buf_printf(¬e, + "Every tool call you sent had arguments that " + "are not valid JSON, so none of them ran. Do " + "not send another call. Answer in plain text: " + "say what you wanted to do, step by step, and " + "what is still open."); + last_chance = 1; + } + push_rc = sp_conv_push(conv, "user", NULL, note.p); + if (push_rc == 0) { + sp_logf("user", "%s", note.p); + if (a->sess != NULL) + (void)sp_session_append(a->sess, + "user", note.p, err); + } + sp_buf_free(¬e); sp_reply_free(&reply); - if (++bad_tool_tries >= 3) { - sp_buf_puts(err, "agent: model sent " - "malformed tool arguments"); + if (push_rc != 0) + goto oom; + if (last_chance) + continue; + if (a->cfg->note != NULL) { + char line[256]; + + snprintf(line, sizeof(line), + "tool call with broken JSON, " + "trying again in %d s (%d/%d)", + retry_wait_ms() / 1000, bad_tool_tries, + SP_BAD_TOOL_TRIES); + a->cfg->note(a->cfg->note_ctx, line); + } + if (!retry_sleep(a, retry_wait_ms())) { + sp_buf_puts(err, + "agent: cancelled by operator"); goto out; } continue; diff --git a/src/backend/openai.c b/src/backend/openai.c index 54105f6..f52623f 100644 --- a/src/backend/openai.c +++ b/src/backend/openai.c @@ -355,6 +355,13 @@ sp_openai_reply(const char *json, struct sp_reply *out, struct sp_buf *err) return -1; } + { + const char *fr = mcp_json_string(mcp_arg(choice, + "finish_reason")); + + if (fr != NULL) + snprintf(out->finish, sizeof(out->finish), "%s", fr); + } content = mcp_arg(message, "content"); out->content = strdup(jstr(content) != NULL ? jstr(content) : ""); if (out->content == NULL) { diff --git a/src/backend/sse.c b/src/backend/sse.c index ffdcfc0..13b945f 100644 --- a/src/backend/sse.c +++ b/src/backend/sse.c @@ -41,6 +41,7 @@ struct sp_sse { long tokens_out; long tokens_cached; double cost; + char finish[24]; /* choices[0].finish_reason, "" if none */ int error_code; /* from a data: {"error":...} event */ }; @@ -345,6 +346,18 @@ sp_sse_line(struct sp_sse *s, const char *line, struct sp_buf *out, return 0; } choice = mcp_array_at(choices, 0); + /* + * The stop reason is what says whether the message ended or was cut + * off. It arrives on the last chunk, which carries no delta, so it + * has to be read before the delta check throws that chunk away. + */ + { + const char *fr = mcp_json_string(mcp_arg(choice, + "finish_reason")); + + if (fr != NULL && *fr != '\0') + snprintf(s->finish, sizeof(s->finish), "%s", fr); + } delta = mcp_arg(choice, "delta"); if (delta == NULL) { mcp_json_free(v); @@ -483,6 +496,7 @@ sp_sse_finish(struct sp_sse *s, struct sp_reply *out, struct sp_buf *err) out->tokens_out = s->tokens_out; out->tokens_cached = s->tokens_cached; out->cost = s->cost; + snprintf(out->finish, sizeof(out->finish), "%s", s->finish); out->content = strdup(s->content.p != NULL ? s->content.p : ""); if (out->content == NULL) return -1; diff --git a/tests/test_agent.c b/tests/test_agent.c index 6cc0b89..62070e1 100644 --- a/tests/test_agent.c +++ b/tests/test_agent.c @@ -89,15 +89,105 @@ flaky_stream(void *ctx, const struct sp_conv *conv, struct sp_reply *out, return 0; } +/* + * The turn that asks for words is the last resort of the malformed-call + * retry: a model that reads it answers, and the turn ends with an answer + * instead of dying on "malformed tool arguments". + */ +static int +asked_for_words(const struct sp_conv *conv) +{ + size_t i; + + if (conv == NULL) + return 0; + for (i = conv->n; i > 0; i--) + if (conv->v[i - 1].content != NULL && + strstr(conv->v[i - 1].content, "Answer in plain text") != NULL) + return 1; + return 0; +} + +/* + * A call the token limit cut off: the arguments stop in the middle, and the + * provider says why ("finish_reason": "length"). That is a different fault + * from a model that cannot write JSON - the same request truncates it again - + * so the correction asks for a smaller call, not for the same one. + */ +static int cut_off_calls; +static struct sp_buf cut_off_second; +static int +cut_off_send(void *ctx, const struct sp_conv *conv, struct sp_reply *out, + struct sp_buf *err) +{ + (void)ctx; + (void)err; + cut_off_calls++; + if (asked_for_words(conv)) { + memset(out, 0, sizeof(*out)); + out->status = 200; + out->content = strdup("the call did not fit"); + return out->content != NULL ? 0 : -1; + } + if (cut_off_calls == 2 && conv != NULL) { + size_t i; + + sp_buf_clear(&cut_off_second); + for (i = 0; i < conv->n; i++) + if (conv->v[i].content != NULL) { + sp_buf_puts(&cut_off_second, conv->v[i].content); + sp_buf_puts(&cut_off_second, "\n"); + } + } + memset(out, 0, sizeof(*out)); + out->status = 200; + out->content = strdup(""); + snprintf(out->finish, sizeof(out->finish), "length"); + out->ncalls = 1; + out->calls = calloc(1, sizeof(*out->calls)); + if (out->content == NULL || out->calls == NULL) + return -1; + out->calls[0].id = strdup("c1"); + out->calls[0].name = strdup("run"); + out->calls[0].args = strdup("{\"command\":\"echo a very long comm"); + out->calls_json = strdup("[{\"id\":\"c1\",\"type\":\"function\"," + "\"function\":{\"name\":\"run\",\"arguments\":" + "\"{\\\"command\\\":\\\"echo a very long comm\"}}]"); + return out->calls[0].id != NULL && out->calls[0].name != NULL && + out->calls[0].args != NULL && out->calls_json != NULL ? 0 : -1; +} + /* a reply whose tool call carries arguments that are not JSON */ static int bad_args_calls; +static struct sp_buf bad_args_second; /* the second request, verbatim */ static int bad_args_send(void *ctx, const struct sp_conv *conv, struct sp_reply *out, struct sp_buf *err) { (void)ctx; - (void)conv; bad_args_calls++; + if (asked_for_words(conv)) { + memset(out, 0, sizeof(*out)); + out->status = 200; + out->content = strdup("nothing ran, here is what I meant"); + return out->content != NULL ? 0 : -1; + } + /* + * The retry has to carry a correction, not the same prompt again: + * the model answers a request it already answered with a broken + * call usually with the same broken call. + */ + if (bad_args_calls == 2 && conv != NULL) { + size_t i; + + sp_buf_clear(&bad_args_second); + for (i = 0; i < conv->n; i++) + if (conv->v[i].content != NULL) { + sp_buf_puts(&bad_args_second, + conv->v[i].content); + sp_buf_puts(&bad_args_second, "\n"); + } + } memset(out, 0, sizeof(*out)); out->status = 200; out->content = strdup(""); @@ -127,9 +217,14 @@ joined_args_send(void *ctx, const struct sp_conv *conv, struct sp_reply *out, struct sp_buf *err) { (void)ctx; - (void)conv; (void)err; joined_args_calls++; + if (asked_for_words(conv)) { + memset(out, 0, sizeof(*out)); + out->status = 200; + out->content = strdup("one call at a time, nothing ran"); + return out->content != NULL ? 0 : -1; + } memset(out, 0, sizeof(*out)); out->status = 200; out->content = strdup(""); @@ -453,13 +548,25 @@ main(void) bad_args_calls = 0; sp_buf_clear(&answer); sp_buf_clear(&err); - CHECK(sp_agent_run(&a, "bad args", &answer, &err) != 0); - CHECK(strstr(err.p, "malformed tool arguments") != NULL); - CHECK(bad_args_calls == 3); + /* + * Five attempts with a correction each, then one request that + * asks for words: the turn ends with an answer, not with an + * error the operator cannot act on. + */ + CHECK(sp_agent_run(&a, "bad args", &answer, &err) == 0); + CHECK(bad_args_calls == 6); + CHECK(strstr(answer.p, "nothing ran") != NULL); CHECK(a.stats.tool_calls == 0); CHECK(a.conv == NULL || a.conv->n == 0 || strstr(a.conv->v[a.conv->n - 1].content != NULL ? a.conv->v[a.conv->n - 1].content : "", "command:bad") == NULL); + /* + * The retry is not the same prompt: it carries the arguments + * the model got wrong and says what was wrong with them. + */ + CHECK(bad_args_second.len > 0); + CHECK(strstr(bad_args_second.p, "{command:bad}") != NULL); + CHECK(strstr(bad_args_second.p, "not valid JSON") != NULL); sp_conv_free(a.conv); } @@ -485,13 +592,52 @@ main(void) joined_args_calls = 0; sp_buf_clear(&answer); sp_buf_clear(&err); - CHECK(sp_agent_run(&a, "joined args", &answer, &err) != 0); - CHECK(strstr(err.p, "malformed tool arguments") != NULL); - CHECK(joined_args_calls == 3); + CHECK(sp_agent_run(&a, "joined args", &answer, &err) == 0); + CHECK(joined_args_calls == 6); + CHECK(strstr(answer.p, "nothing ran") != NULL); CHECK(a.stats.tool_calls == 0); sp_conv_free(a.conv); } + /* + * A call cut off by the token limit ("finish_reason": "length") is not + * a model that cannot write JSON: the same request truncates it again. + * The correction has to ask for a smaller call, and the turn still + * ends with words after five tries. + */ + { + struct sp_agent a; + struct sp_agent_config cfg; + struct sp_transport tr; + + (void)setenv("SPLINTER_RETRY_WAIT_MS", "0", 1); + memset(&a, 0, sizeof(a)); + memset(&cfg, 0, sizeof(cfg)); + memset(&tr, 0, sizeof(tr)); + cfg.max_steps = 8; + cfg.autonomous = 1; + tr.send = cut_off_send; + a.reg = &r; + a.cfg = &cfg; + a.tr = tr; + cut_off_calls = 0; + sp_buf_clear(&answer); + sp_buf_clear(&err); + CHECK(sp_agent_run(&a, "cut off", &answer, &err) == 0); + CHECK(cut_off_calls == 6); + CHECK(strstr(answer.p, "did not fit") != NULL); + /* + * The correction names the limit, not just "invalid JSON": only + * the first sentence tells the model what to do differently. + */ + CHECK(strstr(cut_off_second.p, "cut off by the") != NULL); + CHECK(strstr(cut_off_second.p, "smaller call") != NULL); + CHECK(a.stats.tool_calls == 0); + sp_conv_free(a.conv); + sp_buf_free(&cut_off_second); + (void)unsetenv("SPLINTER_RETRY_WAIT_MS"); + } + /* * A round that fails between its calls still answers every call: * an assistant message with two tool_calls and one result made each