response_generator.cpp

src/core/response_generator.cpp

@file response_generator.cpp @brief Response generation implementation.

Owners: @tvanfossen

build_params_json

std::string entropic::ResponseGenerator::build_params_json(const std::string &tier, const std::string &session_key="", bool force_tool_call=false, const std::string &only_tool="")

Build generation params JSON with tier routing.

src/core/response_generator.cpp:932

Source · 25 lines
std::string ResponseGenerator::build_params_json(
    const std::string& tier, const std::string& session_key,
    bool force_tool_call, const std::string& only_tool) {
    nlohmann::json j = nlohmann::json::object();
    if (!tier.empty()) { j["tier"] = tier; }
    // gh#144 (v2.12.0): only emitted when non-empty, so a handle that never
    // names a session sends a byte-identical params payload.
    if (!session_key.empty()) { j["session"] = session_key; }

    bool offered = true;
    if (inference_.get_tool_prompt != nullptr) {
        char* tools = nullptr;
        int rc = inference_.get_tool_prompt(
            tier.c_str(), &tools, inference_.tool_prompt_data);
        if (rc == 0 && tools != nullptr) {
            j["tools"] = only_tool.empty()
                ? std::string(tools)
                : restrict_tools(tools, only_tool, tier, offered);
            if (inference_.free_fn) { inference_.free_fn(tools); }
        }
    }
    // v2.14.6: forced only when the retry can actually conclude.
    if (force_tool_call && offered) { j["force_tool_call"] = true; }
    return j.dump();
}
Activity · 16 steps
lines 935–935nlohmann::json j = nlohmann::json::object();lines 936–936◇ if (!tier.empty())lines 936–936j["tier"] = tier;lines 939–939◇ if (!session_key.empty())lines 939–939j["session"] = session_key;lines 941–941bool offered = true;lines 942–942◇ if (inference_.get_tool_prompt != nullptr)lines 943–943char* tools = nullptr;lines 944–945int rc = inference_.get_tool_prompt( tier.c_str(), &tools, inference_.tool_prompt_data);lines 946–946◇ if (rc == 0 && tools != nullptr)lines 947–949j["tools"] = only_tool.empty() ? std::string(tools) : restrict_tools(tools, only_tool, tier, offered);lines 950–950◇ if (inference_.free_fn)lines 950–950inference_.free_fn(tools);lines 954–954◇ if (force_tool_call && offered)lines 954–954j["force_tool_call"] = true;lines 955–955return j.dump();

Requirements

REQ-IDEN-001

dispatch_batch_generate

int entropic::ResponseGenerator::dispatch_batch_generate(const std::string &msgs_json, const std::string &params_json, char **result_json)

Dispatch the batch backend call, honoring interrupts.

src/core/response_generator.cpp:540

Show on the map →

Called by generate_batch

Calls generation_cancelled, spawn_cancel_poller

Source · 39 lines
int ResponseGenerator::dispatch_batch_generate(
    const std::string& msgs_json,
    const std::string& params_json,
    char** result_json) {
    // Fall back to the no-cancel entry for backends that predate the
    // generate_cancellable ABI field.
    //
    // gh#110 (v2.9.6): also prefer the no-cancel entry whenever
    // speculative decoding is enabled. `generate_cancellable`'s
    // backing orchestrator call deliberately bypasses
    // run_generate_dispatch (speculative/MTP routing) — batch-with-
    // cancel only ever calls plain decode. The plain `generate` entry
    // point runs run_generate_dispatch and is therefore the only
    // batch path that can reach MTP. v1 tradeoff: a speculative batch
    // turn is not cancellable mid-decode (documented, not silent).
    if (inference_.generate_cancellable == nullptr
        || loop_config_.speculative_enabled) {
        return inference_.generate(
            msgs_json.c_str(), params_json.c_str(),
            result_json, inference_.backend_data);
    }

    // The C-ABI side bridges this int → atomic<bool> for the backend
    // via its own poller; this side mirrors the engine's atomic
    // interrupt_flag_ → the int. Two cheap 10ms-poll hops, but it
    // keeps the C ABI int*-only (no atomic across the .so boundary).
    int cancel_int = generation_cancelled(events_) ? 1 : 0;

    std::atomic<bool> observer_done(false);
    std::thread observer = spawn_cancel_poller(cancel_int, observer_done);

    int rc = inference_.generate_cancellable(
        msgs_json.c_str(), params_json.c_str(),
        result_json, &cancel_int, inference_.backend_data);

    observer_done.store(true, std::memory_order_release);
    if (observer.joinable()) { observer.join(); }
    return rc;
}
Activity · 10 steps
lines 555–556◇ if (inference_.generate_cancellable == nullptr || loop_config_.speculative_enabled)lines 557–559return inference_.generate( msgs_json.c_str(), params_json.c_str(), result_json, inference_.backend_data);lines 566–566int cancel_int = generation_cancelled(events_) ? 1 : 0;lines 568–568std::atomic<bool> observer_done(false);lines 569–569std::thread observer = spawn_cancel_poller(cancel_int, observer_done);lines 571–573int rc = inference_.generate_cancellable( msgs_json.c_str(), params_json.c_str(), result_json, &cancel_int, inference_.backend_data);lines 575–575observer_done.store(true, std::memory_order_release);lines 576–576◇ if (observer.joinable())lines 576–576observer.join();lines 577–577return rc;

Requirements

REQ-LOOP-006

generate_batch

GenerateResult entropic::ResponseGenerator::generate_batch(LoopContext &ctx)

Generate via batch (non-streaming).

src/core/response_generator.cpp:631

Show on the map →

Called by none

Calls apply_terminal_batch_rc, dispatch_batch_generate, prepare_prompts, sanitize_utf8

Source · 43 lines
GenerateResult ResponseGenerator::generate_batch(LoopContext& ctx) {
    if (inference_.generate == nullptr
        && inference_.generate_cancellable == nullptr) {
        logger->error("No generate function available");
        return {"", "[]", "error"};
    }

    auto [msgs_json, params_json] = prepare_prompts(ctx, "batch");
    char* result_json = nullptr;

    // gh#81 (v2.4.2): prefer the cancellable dispatch so an interrupt
    // is honored mid-decode (was ~60s lag pre-fix).
    int rc = dispatch_batch_generate(msgs_json, params_json, &result_json);

    GenerateResult result;
    // Cancellation and the v2.13.0 context refusal are both terminal and
    // both shaped unlike a retryable failure — see apply_terminal_batch_rc.
    if (!apply_terminal_batch_rc(rc, result_json, result)) {
        if (rc == 0 && result_json != nullptr) {
            // Issue #3 (v2.1.1): inbound boundary, batch path. See the
            // streaming branch above for rationale; same policy applies.
            result.content = mcp::sanitize_utf8(result_json);
            result.finish_reason = "stop";
            result.tool_calls_json = "[]";
            // Fire observer once with full content so the non-streaming
            // fallback still reaches registered observers. (2.0.6-rc16)
            if (stream_observer_ != nullptr && !result.content.empty()) {
                stream_observer_(result.content.data(),
                                 result.content.size(),
                                 stream_observer_data_);
            }
        } else {
            result.finish_reason = "error";
            logger->error("Generate failed (rc={})", rc);
        }
    }
    if (result_json != nullptr && inference_.free_fn != nullptr) {
        inference_.free_fn(result_json);
    }
    logger->info("Generate complete (batch): finish={}, {} chars",
                 result.finish_reason, result.content.size());
    return result;
}
Activity · 21 steps
lines 632–633◇ if (inference_.generate == nullptr && inference_.generate_cancellable == nullptr)lines 634–634logger->error("No generate function available");lines 635–635return {"", "[]", "error"};lines 638–638auto [msgs_json, params_json] = prepare_prompts(ctx, "batch");lines 639–639char* result_json = nullptr;lines 643–643int rc = dispatch_batch_generate(msgs_json, params_json, &result_json);lines 645–645GenerateResult result;lines 648–648◇ if (!apply_terminal_batch_rc(rc, result_json, result))lines 649–649◇ if (rc == 0 && result_json != nullptr)lines 652–652result.content = mcp::sanitize_utf8(result_json);lines 653–653result.finish_reason = "stop";lines 654–654result.tool_calls_json = "[]";lines 657–657◇ if (stream_observer_ != nullptr && !result.content.empty())lines 658–660stream_observer_(result.content.data(), result.content.size(), stream_observer_data_);lines 662–662elselines 663–663result.finish_reason = "error";lines 664–664logger->error("Generate failed (rc={})", rc);lines 667–667◇ if (result_json != nullptr && inference_.free_fn != nullptr)lines 668–668inference_.free_fn(result_json);lines 670–671logger->info("Generate complete (batch): finish={}, {} chars", result.finish_reason, result.content.size());lines 672–672return result;

Requirements

REQ-INFER-026 REQ-LOOP-003

generate_response

GenerateResult entropic::ResponseGenerator::generate_response(LoopContext &ctx)

Generate model response, routing tier first if needed.

src/core/response_generator.cpp:172

Source · 8 lines
GenerateResult ResponseGenerator::generate_response(LoopContext& ctx) {
    lock_tier_if_needed(ctx);

    if (loop_config_.stream_output) {
        return generate_streaming(ctx);
    }
    return generate_batch(ctx);
}
Activity · 4 steps
lines 173–173lock_tier_if_needed(ctx);lines 175–175◇ if (loop_config_.stream_output)lines 176–176return generate_streaming(ctx);lines 178–178return generate_batch(ctx);

Requirements

REQ-LOOP-003

generate_streaming

GenerateResult entropic::ResponseGenerator::generate_streaming(LoopContext &ctx)

Generate via streaming with interrupt/pause.

src/core/response_generator.cpp:431

Show on the map →

Called by none

Calls prepare_prompts, resolve_stream_finish_reason, sanitize_utf8

Source · 44 lines
GenerateResult ResponseGenerator::generate_streaming(LoopContext& ctx) {
    if (inference_.generate_stream == nullptr) {
        logger->warn("No streaming function, falling back to batch");
        return generate_batch(ctx);
    }

    auto [msgs_json, params_json] = prepare_prompts(ctx, "stream");

    int cancel_flag = 0;
    StreamAccumulator acc;
    acc.callbacks = &callbacks_;
    acc.events = &events_;
    acc.hooks = &hooks_;
    // gh#20 (v2.1.5): give the token callback a path to raise the
    // backend cancel flag when an interrupt is observed. Without
    // this, the previous implementation would early-return out of
    // the token callback without ever telling the backend to stop.
    acc.cancel_flag = &cancel_flag;
    // Wire the persistent stream observer so every token — including
    // batch entropic_run and delegate child-loop generations — reaches
    // any registered observer. (P0-1, 2.0.6-rc16)
    acc.observer = stream_observer_;
    acc.observer_data = stream_observer_data_;

    int rc = inference_.generate_stream(
        msgs_json.c_str(), params_json.c_str(),
        stream_token_callback, &acc,
        &cancel_flag, inference_.backend_data);

    GenerateResult result;
    result.finish_reason = resolve_stream_finish_reason(rc,
                                                        acc.content.size());
    // Issue #3 (v2.1.1): inbound boundary from llama_cpp. Models can emit
    // malformed UTF-8 mid-stream (partial multi-byte runs under XML-tool-call
    // pressure, decoder desyncs). Sanitize ONCE at message-finalization,
    // never per-token — a multi-byte codepoint may split across token
    // boundaries and per-token sanitize would corrupt valid output.
    // See include/entropic/mcp/utf8_sanitize.h for the boundary policy.
    result.content = mcp::sanitize_utf8(acc.content);
    result.tool_calls_json = "[]";
    logger->info("Generate complete (stream): finish={}, {} chars",
                 result.finish_reason, result.content.size());
    return result;
}
Activity · 19 steps
lines 432–432◇ if (inference_.generate_stream == nullptr)lines 433–433logger->warn("No streaming function, falling back to batch");lines 434–434return generate_batch(ctx);lines 437–437auto [msgs_json, params_json] = prepare_prompts(ctx, "stream");lines 439–439int cancel_flag = 0;lines 440–440StreamAccumulator acc;lines 441–441acc.callbacks = &callbacks_;lines 442–442acc.events = &events_;lines 443–443acc.hooks = &hooks_;lines 448–448acc.cancel_flag = &cancel_flag;lines 452–452acc.observer = stream_observer_;lines 453–453acc.observer_data = stream_observer_data_;lines 455–458int rc = inference_.generate_stream( msgs_json.c_str(), params_json.c_str(), stream_token_callback, &acc, &cancel_flag, inference_.backend_data);lines 460–460GenerateResult result;lines 461–462result.finish_reason = resolve_stream_finish_reason(rc, acc.content.size());lines 469–469result.content = mcp::sanitize_utf8(acc.content);lines 470–470result.tool_calls_json = "[]";lines 471–472logger->info("Generate complete (stream): finish={}, {} chars", result.finish_reason, result.content.size());lines 473–473return result;

Requirements

REQ-LOOP-006 REQ-LOOP-008

handle_pause

std::string entropic::ResponseGenerator::handle_pause(LoopContext &ctx, const std::string &partial)

Handle pause during streaming generation.

src/core/response_generator.cpp:691

Source · 57 lines
std::string ResponseGenerator::handle_pause(
    LoopContext& ctx,
    const std::string& partial) {
    ctx.state = AgentState::PAUSED;
    if (callbacks_.on_state_change != nullptr) {
        callbacks_.on_state_change(
            static_cast<int>(AgentState::PAUSED),
            callbacks_.user_data);
    }
    // gh#40 fallout (v2.1.10): persistent slot fires alongside the
    // legacy on_state_change so consumers see PAUSED during
    // streaming runs where the legacy callbacks_ struct has been
    // overwritten by run_streaming's set_callbacks() shuffle.
    if (state_observer_ != nullptr) {
        state_observer_(static_cast<int>(AgentState::PAUSED),
                        state_observer_data_);
    }

    char* injection = nullptr;
    if (callbacks_.on_pause_prompt != nullptr) {
        callbacks_.on_pause_prompt(partial.c_str(), &injection,
                                    callbacks_.user_data);
    }

    if (injection == nullptr) {
        // gh#158: "the consumer declined to inject" means abandon THIS turn,
        // so raise this run's own token. Falling through to the handle-wide
        // flag (the pre-2.13.0 behaviour) would abort every concurrent
        // session's turn on one session's pause prompt.
        if (!cancel_current_run() && events_.interrupt != nullptr) {
            events_.interrupt->store(true);
        }
        return partial;
    }

    std::string inj(injection);
    if (inj.empty()) {
        ctx.state = AgentState::EXECUTING;
        return partial;
    }

    // Injection provided: append partial + injection to messages
    if (!partial.empty()) {
        Message partial_msg;
        partial_msg.role = "assistant";
        partial_msg.content = partial + "\n\n[Generation paused by user]";
        ctx.messages.push_back(std::move(partial_msg));
    }
    Message inject_msg;
    inject_msg.role = "user";
    inject_msg.content = "[User interjection]: " + inj
        + "\n\nPlease continue with this in mind.";
    ctx.messages.push_back(std::move(inject_msg));

    ctx.state = AgentState::EXECUTING;
    return "";
}
Activity · 27 steps
lines 694–694ctx.state = AgentState::PAUSED;lines 695–695◇ if (callbacks_.on_state_change != nullptr)lines 696–698callbacks_.on_state_change( static_cast<int>(AgentState::PAUSED), callbacks_.user_data);lines 704–704◇ if (state_observer_ != nullptr)lines 705–706state_observer_(static_cast<int>(AgentState::PAUSED), state_observer_data_);lines 709–709char* injection = nullptr;lines 710–710◇ if (callbacks_.on_pause_prompt != nullptr)lines 711–712callbacks_.on_pause_prompt(partial.c_str(), &injection, callbacks_.user_data);lines 715–715◇ if (injection == nullptr)lines 720–720◇ if (!cancel_current_run() && events_.interrupt != nullptr)lines 721–721events_.interrupt->store(true);lines 723–723return partial;lines 726–726std::string inj(injection);lines 727–727◇ if (inj.empty())lines 728–728ctx.state = AgentState::EXECUTING;lines 729–729return partial;lines 733–733◇ if (!partial.empty())lines 734–734Message partial_msg;lines 735–735partial_msg.role = "assistant";lines 736–736partial_msg.content = partial + "\n\n[Generation paused by user]";lines 737–737ctx.messages.push_back(std::move(partial_msg));lines 739–739Message inject_msg;lines 740–740inject_msg.role = "user";lines 741–742inject_msg.content = "[User interjection]: " + inj + "\n\nPlease continue with this in mind.";lines 743–743ctx.messages.push_back(std::move(inject_msg));lines 745–745ctx.state = AgentState::EXECUTING;lines 746–746return "";

Requirements

REQ-LOOP-006

inject_engine_state_reminder

std::vector< Message > entropic::ResponseGenerator::inject_engine_state_reminder(const std::vector< Message > &messages, const LoopContext &ctx)

Append an "[engine] iteration N/MAX..." reminder to the first system message.

src/core/response_generator.cpp:988

Source · 47 lines
std::vector<Message> ResponseGenerator::inject_engine_state_reminder(
    const std::vector<Message>& messages,
    const LoopContext& ctx) {
    int max_iter = ctx.effective_max_iterations >= 0
        ? ctx.effective_max_iterations
        : loop_config_.max_iterations;
    // v2.14.6: the counter shows only near the budget. Sent every turn, the
    // model read it as the user's request ("I see you've provided a status
    // update", test-v2141) — after a native tool response it is the only
    // plain user text left. Where the budget is close it is worth saying.
    std::string reminder;
    if (max_iter - ctx.metrics.iterations < kReminderWindow) {
        reminder = "[engine] iteration "
            + std::to_string(ctx.metrics.iterations)
            + "/" + std::to_string(max_iter)
            + ", tool calls so far: "
            + std::to_string(ctx.metrics.tool_calls) + ".";
    }

    // Demo ask #2 (v2.1.0): if the previous turn was validator-rejected,
    // surface the reason so the model knows WHY it's being asked again.
    // Engine clears pending_validation_feedback after this turn — the
    // line is one-shot.
    if (!ctx.pending_validation_feedback.empty()) {
        reminder += (reminder.empty() ? "" : "\n")
                  + std::string("[engine] previous turn rejected: ")
                  + ctx.pending_validation_feedback;
    }
    // Demo ask #5 (v2.1.0): anti-spiral primitive. ToolExecutor
    // populated this when consecutive_same_tool_calls hit
    // max_consecutive_same_tool. Same one-shot lifecycle as the
    // validation feedback above; engine clears after this turn.
    if (!ctx.pending_anti_spiral_warning.empty()) {
        reminder += (reminder.empty() ? "" : "\n")
                  + std::string("[engine] anti-spiral: ")
                  + ctx.pending_anti_spiral_warning;
    }

    auto result = messages;
    if (!reminder.empty()) {
        Message reminder_msg;
        reminder_msg.role = "user";
        reminder_msg.content = std::move(reminder);
        result.push_back(std::move(reminder_msg));
    }
    return result;
}
Activity · 15 steps
lines 991–993int max_iter = ctx.effective_max_iterations >= 0 ? ctx.effective_max_iterations : loop_config_.max_iterations;lines 998–998std::string reminder;lines 999–999◇ if (max_iter - ctx.metrics.iterations < kReminderWindow)lines 1000–1004reminder = "[engine] iteration " + std::to_string(ctx.metrics.iterations) + "/" + std::to_string(max_iter) + ", tool calls so far: " + std::to_string(ctx.metrics.tool_calls) + ".";lines 1011–1011◇ if (!ctx.pending_validation_feedback.empty())lines 1012–1014reminder += (reminder.empty() ? "" : "\n") + std::string("[engine] previous turn rejected: ") + ctx.pending_validation_feedback;lines 1020–1020◇ if (!ctx.pending_anti_spiral_warning.empty())lines 1021–1023reminder += (reminder.empty() ? "" : "\n") + std::string("[engine] anti-spiral: ") + ctx.pending_anti_spiral_warning;lines 1026–1026auto result = messages;lines 1027–1027◇ if (!reminder.empty())lines 1028–1028Message reminder_msg;lines 1029–1029reminder_msg.role = "user";lines 1030–1030reminder_msg.content = std::move(reminder);lines 1031–1031result.push_back(std::move(reminder_msg));lines 1033–1033return result;

Requirements

REQ-LOOP-007

is_response_complete

bool entropic::ResponseGenerator::is_response_complete(const std::string &content, const std::string &tool_calls_json)

Check if the last response indicates completion.

src/core/response_generator.cpp:189

Source · 10 lines
bool ResponseGenerator::is_response_complete(
    const std::string& content,
    const std::string& tool_calls_json) {
    if (inference_.is_response_complete == nullptr) {
        return !content.empty();
    }
    return inference_.is_response_complete(
        content.c_str(), tool_calls_json.c_str(),
        inference_.adapter_data) != 0;
}
Activity · 3 steps
lines 192–192◇ if (inference_.is_response_complete == nullptr)lines 193–193return !content.empty();lines 195–197return inference_.is_response_complete( content.c_str(), tool_calls_json.c_str(), inference_.adapter_data) != 0;

Requirements

REQ-IDEN-003

lock_tier_if_needed

void entropic::ResponseGenerator::lock_tier_if_needed(LoopContext &ctx)

Route and lock tier before first generation.

src/core/response_generator.cpp:206

Source · 34 lines
void ResponseGenerator::lock_tier_if_needed(LoopContext& ctx) {
    if (!ctx.locked_tier.empty()) {
        if (callbacks_.on_tier_selected != nullptr) {
            callbacks_.on_tier_selected(ctx.locked_tier.c_str(),
                                        callbacks_.user_data);
        }
        return;
    }

    if (inference_.route == nullptr) {
        ctx.locked_tier = "default";
        return;
    }

    auto msgs_json = serialize_messages(ctx.messages);
    char* result_json = nullptr;
    int rc = inference_.route(msgs_json.c_str(), &result_json,
                              inference_.orchestrator_data);
    if (rc == 0 && result_json != nullptr) {
        ctx.locked_tier = result_json;
        if (inference_.free_fn != nullptr) {
            inference_.free_fn(result_json);
        }
    } else {
        ctx.locked_tier = "default";
        logger->warn("Routing failed (rc={}), using default tier", rc);
    }

    logger->info("Locked tier: {}", ctx.locked_tier);
    if (callbacks_.on_tier_selected != nullptr) {
        callbacks_.on_tier_selected(ctx.locked_tier.c_str(),
                                    callbacks_.user_data);
    }
}
Activity · 20 steps
lines 207–207◇ if (!ctx.locked_tier.empty())lines 208–208◇ if (callbacks_.on_tier_selected != nullptr)lines 209–210callbacks_.on_tier_selected(ctx.locked_tier.c_str(), callbacks_.user_data);lines 212–212return;lines 215–215◇ if (inference_.route == nullptr)lines 216–216ctx.locked_tier = "default";lines 217–217return;lines 220–220auto msgs_json = serialize_messages(ctx.messages);lines 221–221char* result_json = nullptr;lines 222–223int rc = inference_.route(msgs_json.c_str(), &result_json, inference_.orchestrator_data);lines 224–224◇ if (rc == 0 && result_json != nullptr)lines 225–225ctx.locked_tier = result_json;lines 226–226◇ if (inference_.free_fn != nullptr)lines 227–227inference_.free_fn(result_json);lines 229–229elselines 230–230ctx.locked_tier = "default";lines 231–231logger->warn("Routing failed (rc={}), using default tier", rc);lines 234–234logger->info("Locked tier: {}", ctx.locked_tier);lines 235–235◇ if (callbacks_.on_tier_selected != nullptr)lines 236–237callbacks_.on_tier_selected(ctx.locked_tier.c_str(), callbacks_.user_data);

Requirements

REQ-IDEN-001

prepare_prompts

std::pair< std::string, std::string > entropic::ResponseGenerator::prepare_prompts(LoopContext &ctx, const char *mode)

Inject prompts + serialize messages/params for a turn.

src/core/response_generator.cpp:401

Source · 21 lines
std::pair<std::string, std::string> ResponseGenerator::prepare_prompts(
    LoopContext& ctx, const char* mode) {
    // gh#87 (v2.7.0): tool defs no longer string-injected into the system
    // message — they flow as structured JSON via build_params_json →
    // params.tools, and common_chat renders them in the model's native
    // format. Only the runtime engine-state reminder is injected here.
    auto messages = inject_engine_state_reminder(ctx.messages, ctx);
    logger->info("Generate ({}): tier={}, {} messages",
                 mode, ctx.locked_tier, messages.size());
    log_prompt(messages, ctx.locked_tier);
    // v2.14.6: "1" forces any tool call; "complete" (the nudged turn already
    // answered in prose) forces the call AND offers entropic.complete only.
    auto force = ctx.metadata.find("force_tool_call");
    const std::string mode_value =
        force != ctx.metadata.end() ? force->second : "";
    return {serialize_messages(messages),
            build_params_json(ctx.locked_tier, ctx.session_key,
                              !mode_value.empty(),
                              mode_value == "complete" ? "entropic.complete"
                                                       : "")};
}
Activity · 6 steps
lines 407–407auto messages = inject_engine_state_reminder(ctx.messages, ctx);lines 408–409logger->info("Generate ({}): tier={}, {} messages", mode, ctx.locked_tier, messages.size());lines 410–410log_prompt(messages, ctx.locked_tier);lines 413–413auto force = ctx.metadata.find("force_tool_call");lines 414–415const std::string mode_value = force != ctx.metadata.end() ? force->second : "";lines 416–420return {serialize_messages(messages), build_params_json(ctx.locked_tier, ctx.session_key, !mode_value.empty(), mode_value == "complete" ? "entropic.complete" : "")};

Requirements

REQ-LOOP-007

restrict_tools

static std::string entropic::restrict_tools(const std::string &tools_json, const std::string &only_tool, const std::string &tier, bool &offered)

Narrow a tier's tool defs to the one named tool (v2.14.6).

src/core/response_generator.cpp:886

Source · 27 lines
static std::string restrict_tools(const std::string& tools_json,
                                  const std::string& only_tool,
                                  const std::string& tier,
                                  bool& offered) {
    auto all = nlohmann::json::parse(tools_json, nullptr, false);
    auto kept = nlohmann::json::array();
    if (all.is_array()) {
        for (const auto& t : all) {
            if (t.is_object() && t.value("name", "") == only_tool) {
                kept.push_back(t);
            }
        }
    }
    std::string out = tools_json;
    offered = !kept.empty();
    if (!offered) {
        logger->error("[tools] tier '{}': forced retry may only call '{}', "
                      "but the tier is not offered it; keeping its tools {} "
                      "and NOT forcing the retry",
                      tier, only_tool, tools_json);
    } else {
        logger->info("[tools] tier '{}': forced retry offers only '{}'",
                     tier, only_tool);
        out = kept.dump();
    }
    return out;
}
Activity · 14 steps
lines 890–890auto all = nlohmann::json::parse(tools_json, nullptr, false);lines 891–891auto kept = nlohmann::json::array();lines 892–892◇ if (all.is_array())lines 893–893◇ for (const auto& t : all)lines 894–894◇ if (t.is_object() && t.value("name", "") == only_tool)lines 895–895kept.push_back(t);lines 899–899std::string out = tools_json;lines 900–900offered = !kept.empty();lines 901–901◇ if (!offered)lines 902–905logger->error("[tools] tier '{}': forced retry may only call '{}', " "but the tier is not offered it; keeping its tools {} " "and NOT forcing the retry", tier, only_tool, tools_json);lines 906–906elselines 907–908logger->info("[tools] tier '{}': forced retry offers only '{}'", tier, only_tool);lines 909–909out = kept.dump();lines 911–911return out;

Requirements

REQ-LOOP-004

spawn_cancel_poller

std::thread entropic::ResponseGenerator::spawn_cancel_poller(int &cancel_int, std::atomic< bool > &done) const

Start the poller that mirrors the stop flags into the C int.

src/core/response_generator.cpp:509

Source · 19 lines
std::thread ResponseGenerator::spawn_cancel_poller(
    int& cancel_int, std::atomic<bool>& done) const {
    const std::atomic<bool>* handle_flag = events_.interrupt;
    const std::atomic<bool>* run_token = current_run_cancel();
    if (handle_flag == nullptr && run_token == nullptr) {
        return {};
    }
    return std::thread(
        [&cancel_int, &done, handle_flag, run_token]() {
            while (!done.load(std::memory_order_acquire)) {
                if (flag_raised(handle_flag) || flag_raised(run_token)) {
                    cancel_int = 1;
                    return;
                }
                std::this_thread::sleep_for(
                    std::chrono::milliseconds(10));
            }
        });
}
Activity · 5 steps
lines 511–511const std::atomic<bool>* handle_flag = events_.interrupt;lines 512–512const std::atomic<bool>* run_token = current_run_cancel();lines 513–513◇ if (handle_flag == nullptr && run_token == nullptr)lines 514–514return {};lines 516–526return std::thread( [&cancel_int, &done, handle_flag, run_token]() { while (!done.load(std::memory_order_acquire)) { if (flag_raised(handle_flag) || flag_raised(run_token)) { cancel_int = 1; return; } std::this_thread::sleep_for( std::chrono::milliseconds(10)); } });

Requirements

REQ-LOOP-006

stream_token_callback

static void entropic::stream_token_callback(const char *token, size_t len, void *user_data)

Token callback for streaming generation.

src/core/response_generator.cpp:281

Show on the map →

Called by none

Calls emit_to_current_run_stream, generation_cancelled

Source · 68 lines
static void stream_token_callback(
    const char* token,
    size_t len,
    void* user_data) {
    auto* acc = static_cast<StreamAccumulator*>(user_data);

    // gh#20 (v2.1.5): two coupled bugs lived here.
    //
    // (A) The previous implementation set `acc->interrupted = true`
    //     and returned early WITHOUT propagating the interrupt to the
    //     backend. The backend's cancel_flag stayed 0, so llama_cpp
    //     ran to natural EOS — up to 60s of wasted decode after the
    //     user pressed Ctrl-C.
    //
    // (B) The early return also dropped every post-interrupt token
    //     from `acc->content`. When the backend finally finished
    //     cleanly, the response_generator built the iter result from
    //     this truncated buffer (e.g. 7 chars instead of the 107
    //     decoded tokens forming a valid tool call), throwing away
    //     fully-formed output.
    //
    // The fix raises the cancel flag for the backend AND keeps
    // appending the token so the content buffer is complete up to
    // the cancel point. The backend stops on its next loop iteration
    // (<= 1 token wall-time); whatever made it through is preserved.
    bool just_interrupted = acc->events != nullptr
        && generation_cancelled(*acc->events)
        && !acc->interrupted;
    if (just_interrupted) {
        acc->interrupted = true;
        // gh#49 (v2.1.12): log the cancel-flag raise so a session
        // log can confirm the per-token interrupt poll observed the
        // engine-level flag. Pre-v2.1.12 the bissell-llm-studio
        // repro saw the "Engine interrupted" line on 0->1 transition
        // but no evidence the per-token poll ever fired — this log
        // is the first observable receipt of the propagation.
        logger->info("Stream interrupt observed at token {}; "
                     "raising backend cancel_flag",
                     acc->token_index);
        if (acc->cancel_flag != nullptr) {
            *acc->cancel_flag = 1;
        }
    }

    acc->content.append(token, len);
    // gh#208 (v2.14.2): a streaming run's own sink first — published to
    // this (the run's) thread. The handle-wide slot is only for a caller
    // that registered one outside any streaming run.
    if (!emit_to_current_run_stream(token, len)
        && acc->callbacks->on_stream_chunk != nullptr) {
        acc->callbacks->on_stream_chunk(token, len,
                                         acc->callbacks->user_data);
    }

    // Global observer — fires on every token regardless of whether
    // the caller registered on_stream_chunk. (2.0.6-rc16)
    if (acc->observer != nullptr) {
        acc->observer(token, len, acc->observer_data);
    }

    // Hook: ON_STREAM_TOKEN (v1.9.1)
    if (acc->hooks != nullptr && acc->hooks->fire_info != nullptr) {
        std::string json = "{\"token_index\":"
            + std::to_string(acc->token_index++) + "}";
        acc->hooks->fire_info(acc->hooks->registry,
            ENTROPIC_HOOK_ON_STREAM_TOKEN, json.c_str());
    }
}
Activity · 15 steps
lines 285–285auto* acc = static_cast<StreamAccumulator*>(user_data);lines 306–308bool just_interrupted = acc->events != nullptr && generation_cancelled(*acc->events) && !acc->interrupted;lines 309–309◇ if (just_interrupted)lines 310–310acc->interrupted = true;lines 317–319logger->info("Stream interrupt observed at token {}; " "raising backend cancel_flag", acc->token_index);lines 320–320◇ if (acc->cancel_flag != nullptr)lines 321–321*acc->cancel_flag = 1;lines 325–325acc->content.append(token, len);lines 329–330◇ if (!emit_to_current_run_stream(token, len) && acc->callbacks->on_stream_chunk != nullptr)lines 331–332acc->callbacks->on_stream_chunk(token, len, acc->callbacks->user_data);lines 337–337◇ if (acc->observer != nullptr)lines 338–338acc->observer(token, len, acc->observer_data);lines 342–342◇ if (acc->hooks != nullptr && acc->hooks->fire_info != nullptr)lines 343–344std::string json = "{\"token_index\":" + std::to_string(acc->token_index++) + "}";lines 345–346acc->hooks->fire_info(acc->hooks->registry, ENTROPIC_HOOK_ON_STREAM_TOKEN, json.c_str());

Requirements

REQ-LOOP-008