diff --git a/.github/script/npu_test/suites/serving.py b/.github/script/npu_test/suites/serving.py index f01b14bc7..bd2c03fb5 100644 --- a/.github/script/npu_test/suites/serving.py +++ b/.github/script/npu_test/suites/serving.py @@ -310,8 +310,8 @@ def _api_cancel(ctx, client, model: str, case) -> None: expect(reply.get("cancelled") is True, f"/api/cancel answered {reply}") expect(not stream.is_alive(), f"the stream was still open {STREAM_DEADLINE:.0f}s after the cancel") expect(stream.error is None, f"the stream failed: {stream.error}") - expect(stream.finish_reason == "cancel", - f"finish_reason {stream.finish_reason!r} after the cancel, expected 'cancel'") + expect(stream.finish_reason == "stop", + f"finish_reason {stream.finish_reason!r} after the cancel, expected 'stop'") expect(end_seconds <= RELEASE_TIMEOUT, f"the stream took {end_seconds}s to end after the cancel") expect(_wait_idle(client, RELEASE_TIMEOUT), "NPU still busy after the cancelled stream ended") diff --git a/docs/docs/instructions/server/reasoning_and_tools.md b/docs/docs/instructions/server/reasoning_and_tools.md index 8ccdf6fe0..356c6e862 100644 --- a/docs/docs/instructions/server/reasoning_and_tools.md +++ b/docs/docs/instructions/server/reasoning_and_tools.md @@ -143,7 +143,8 @@ How to read it: With `stream=True` the same message arrives in small deltas. FLM runs the **same parser** for both modes. When the stream ends, the deltas add up to exactly the message a non-streaming request would have returned. -Each chunk's `delta` carries **one** of these: +The first chunk's `delta` carries `"role": "assistant"`. Later chunks omit `role`. +A delta can carry one of these payloads: | Delta | Meaning | |---|---| @@ -154,15 +155,15 @@ Each chunk's `delta` carries **one** of these: Then a final chunk with `"delta": {"content": null}` and the `finish_reason`, then `data: [DONE]`. -Here is a real stream from `qwen3:0.6b` (abridged) that calls `get_weather` twice: +This abridged stream shows two `get_weather` calls: ```text data: {"choices":[{"delta":{"role":"assistant","tool_calls":[{"index":0,"id":"call_803aPw…","type":"function","function":{"name":"get_weather","arguments":""}}]}, …}]} -data: {"choices":[{"delta":{"role":"assistant","tool_calls":[{"index":0,"function":{"arguments":"{\""}}]}, …}]} -data: {"choices":[{"delta":{"role":"assistant","tool_calls":[{"index":0,"function":{"arguments":"city"}}]}, …}]} -data: {"choices":[{"delta":{"role":"assistant","tool_calls":[{"index":0,"function":{"arguments":"\": \"Paris\"}"}}]}, …}]} -data: {"choices":[{"delta":{"role":"assistant","tool_calls":[{"index":1,"id":"call_gDVP0q…","type":"function","function":{"name":"get_weather","arguments":""}}]}, …}]} -data: {"choices":[{"delta":{"role":"assistant","tool_calls":[{"index":1,"function":{"arguments":"{\"city\": \"Tokyo\"}"}}]}, …}]} +data: {"choices":[{"delta":{"tool_calls":[{"index":0,"function":{"arguments":"{\""}}]}, …}]} +data: {"choices":[{"delta":{"tool_calls":[{"index":0,"function":{"arguments":"city"}}]}, …}]} +data: {"choices":[{"delta":{"tool_calls":[{"index":0,"function":{"arguments":"\": \"Paris\"}"}}]}, …}]} +data: {"choices":[{"delta":{"tool_calls":[{"index":1,"id":"call_gDVP0q…","type":"function","function":{"name":"get_weather","arguments":""}}]}, …}]} +data: {"choices":[{"delta":{"tool_calls":[{"index":1,"function":{"arguments":"{\"city\": \"Tokyo\"}"}}]}, …}]} data: {"choices":[{"delta":{"content":null},"finish_reason":"tool_calls"}], …} data: [DONE] ``` diff --git a/docs/docs/instructions/server/request_parameters.md b/docs/docs/instructions/server/request_parameters.md index d47d201dd..5b74db55b 100644 --- a/docs/docs/instructions/server/request_parameters.md +++ b/docs/docs/instructions/server/request_parameters.md @@ -20,6 +20,7 @@ This page says what FLM does with the fields of a `/v1/chat/completions` or `/v1 - [The Penalty Window](#-the-penalty-window) - [`seed` and Repeatable Output](#-seed-and-repeatable-output) - [Reasoning in `reasoning_content`](#-reasoning-in-reasoning_content) +- [Completion response shape](#completion-response-shape) - [Continuing an Assistant Message (`continue_final_message`)](#-continuing-an-assistant-message-continue_final_message) - [Fields FLM Doesn't Know](#-fields-flm-doesnt-know) - [Long Prompts: Prefill Chunking](#-long-prompts-prefill-chunking) @@ -184,6 +185,14 @@ Reasoning tokens count toward `max_tokens` and `completion_tokens`, and they ent Turning thinking on and off, streaming examples and the full message format: [Reasoning, Tool Calls & Streaming](https://fastflowlm.com/docs/instructions/server/reasoning_and_tools/). +## Completion response shape + +- Chat Completions use `chatcmpl-` IDs. Text Completions use `cmpl-` IDs. Each response gets its own ID, and all chunks in a stream share that ID. +- For Chat Completions, only the first chunk carries `delta.role: "assistant"`. If generation produces no delta, the server sends an empty assistant opener before the finish chunk. +- For Text Completions, the finish choice has `text: ""`, `index: 0`, and `logprobs: null`. +- A cancelled generation that sends a finish reason uses `stop`. A generation failure sends a JSON error before streaming starts, or an SSE error followed by `[DONE]` if a chunk has already been sent. +- Chat Completions `usage` does not include `completion_tokens_details`. FLM reports total completion tokens but does not count reasoning tokens separately. + --- ## ⏩ Continuing an Assistant Message (`continue_final_message`) diff --git a/src/server/openai_response_id.hpp b/src/server/openai_response_id.hpp new file mode 100644 index 000000000..d7ee981e9 --- /dev/null +++ b/src/server/openai_response_id.hpp @@ -0,0 +1,23 @@ +/// \file openai_response_id.hpp +/// \brief Opaque hexadecimal identifiers for OpenAI responses +#pragma once + +#include +#include +#include + +namespace flm::openai { +inline std::string random_id(const char* prefix, std::size_t hex_digits) { + static thread_local auto generator = [] { + std::random_device random; + std::seed_seq seed{random(), random(), random(), random()}; + return std::mt19937(seed); + }(); + std::uniform_int_distribution digit(0, 15); + std::string id(prefix); + for (std::size_t i = 0; i < hex_digits; ++i) { + id += "0123456789abcdef"[digit(generator)]; + } + return id; +} +} // namespace flm::openai diff --git a/src/server/protocol_openai_chat.hpp b/src/server/protocol_openai_chat.hpp index 2baaedec9..0baf1466f 100644 --- a/src/server/protocol_openai_chat.hpp +++ b/src/server/protocol_openai_chat.hpp @@ -10,13 +10,12 @@ #include #include #include -#include -#include #include #include #include #include "chat_core.hpp" #include "error_model.hpp" +#include "openai_response_id.hpp" #include "prefix_cache_usage.hpp" /// \brief An error as OpenAI's error object; its code is the HTTP status @@ -33,13 +32,10 @@ inline nlohmann::ordered_json openai_error_json(const chat_error& error) { /// \brief finish_reason of a chat completion inline const char* openai_finish_reason(chat_finish finish) { switch (finish) { - case chat_finish::STOP: return "stop"; case chat_finish::LENGTH: return "length"; - case chat_finish::CANCEL: return "cancel"; - case chat_finish::FAILED: return "error"; case chat_finish::TOOL_CALLS: return "tool_calls"; + default: return "stop"; } - return "UNKNOWN"; } /// \brief Writes a chat turn to a /v1/chat/completions client @@ -63,10 +59,9 @@ class openai_chat_sink : public chat_sink { model_name = begin.model; stream = begin.stream; if (stream) { - // Generate a unique ID for this stream - generate_stream_id(); + stream_id = flm::openai::random_id("chatcmpl-", 24); generate_created(); - generate_system_fingerprint(); + system_fingerprint = flm::openai::random_id("fp_", 16); } } @@ -75,7 +70,8 @@ class openai_chat_sink : public chat_sink { } void on_delta(const chat_msg_delta& d) override { - json delta = {{"role", "assistant"}}; + json delta = json::object(); + if (!stream_started) delta["role"] = "assistant"; // only content has logprobs; reasoning and tool calls go out with null json choice_logprobs = nullptr; if (d.is_tool_call()) { @@ -101,28 +97,14 @@ class openai_chat_sink : public chat_sink { } } - json choice = { - {"index", 0}, - {"delta", delta} - }; - if (content_logprobs) { - choice["logprobs"] = choice_logprobs; - } - choice["finish_reason"] = nullptr; - json response = { - {"id", stream_id}, - {"object", "chat.completion.chunk"}, - {"created", created}, - {"model", model_name}, - {"choices", json::array({choice})} - }; - if (include_usage) { - response["usage"] = nullptr; - } - send_event("data: " + flm::error_model::dump_json(response) + "\n\n", false); + send_delta(delta, choice_logprobs); } void on_end(const chat_turn_end& end) override { + if (end.finish == chat_finish::FAILED) { + on_error({500, "server_error", "Generation failed", "", std::nullopt}); + return; + } if (stream) { send_final_chunks(end); } @@ -154,47 +136,42 @@ class openai_chat_sink : public chat_sink { } private: - ///@brief Generate a unique stream ID - void generate_stream_id() { - std::random_device rd; - std::mt19937 gen(rd()); - std::uniform_int_distribution<> dis(0, 15); - - std::stringstream ss; - ss << "chatcmpl-"; - for (int i = 0; i < 24; ++i) { - ss << std::hex << dis(gen); - } - stream_id = ss.str(); - } - void generate_created() { created = static_cast(std::chrono::duration_cast( std::chrono::system_clock::now().time_since_epoch() ).count()); } - void generate_system_fingerprint() { - std::random_device rd; - std::mt19937 gen(rd()); - std::uniform_int_distribution<> dis(0, 15); - - std::stringstream ss; - ss << "fp_"; - for (int i = 0; i < 16; ++i) { - ss << std::hex << dis(gen); - } - system_fingerprint = ss.str(); - } - ///@brief Send one server-sent event of the stream void send_event(const std::string& data, bool is_final) { stream_started = true; send_streaming_response(json(data), is_final); } + void send_delta(const json& delta, const json& choice_logprobs) { + json choice = {{"index", 0}, {"delta", delta}}; + if (content_logprobs) { + choice["logprobs"] = choice_logprobs; + } + choice["finish_reason"] = nullptr; + json response = { + {"id", stream_id}, + {"object", "chat.completion.chunk"}, + {"created", created}, + {"model", model_name}, + {"choices", json::array({choice})} + }; + if (include_usage) { + response["usage"] = nullptr; + } + send_event("data: " + flm::error_model::dump_json(response) + "\n\n", false); + } + ///@brief The end of a streamed turn: the finish reason, the usage when asked for, [DONE] void send_final_chunks(const chat_turn_end& end) { + if (!stream_started) { + send_delta({{"role", "assistant"}, {"content", ""}}, nullptr); + } json final_choice = { {"index", 0}, {"delta", { @@ -302,7 +279,7 @@ class openai_chat_sink : public chat_sink { } }); json response = { - {"id", "fastflowlm-chat-completion"}, + {"id", flm::openai::random_id("chatcmpl-", 24)}, {"object", "chat.completion"}, {"created", static_cast(std::time(nullptr))}, {"model", model_name}, diff --git a/src/server/rest_handler.cpp b/src/server/rest_handler.cpp index 385d14337..693f0279e 100644 --- a/src/server/rest_handler.cpp +++ b/src/server/rest_handler.cpp @@ -10,6 +10,7 @@ #include "error_model.hpp" #include "http_guard.hpp" #include "openai_generation_params.hpp" +#include "openai_response_id.hpp" #include "wstream_buf.hpp" #include "streaming_ostream.hpp" #include "streaming_ostream_openai.hpp" @@ -1420,7 +1421,7 @@ void RestHandler::handle_openai_chat_completion(json request, send_response(*invalid); return; } - run_chat_turn(request, sink, cancellation_token, effort_param); + run_chat_turn(request, sink, cancellation_token, /*discard_failed_stream_tail=*/true, effort_param); } /// \brief Validate and resolve `reasoning_effort` for a Chat Completions request. @@ -1462,7 +1463,8 @@ void RestHandler::handle_openai_responses(const json& request, std::shared_ptr cancellation_token) { flm::responses::sink sink(request, std::move(send_response), std::move(send_streaming_response)); try { - run_chat_turn(flm::responses::to_chat_request(request), sink, cancellation_token); + run_chat_turn(flm::responses::to_chat_request(request), sink, cancellation_token, + /*discard_failed_stream_tail=*/false); } catch (const flm::responses::request_error& e) { sink.on_error({400, "invalid_request_error", e.what(), e.param, std::nullopt}); } @@ -1475,8 +1477,10 @@ void RestHandler::handle_openai_responses(const json& request, ///@param request the request, in the Chat Completions shape ///@param sink receives the turn: its start, its deltas when streamed, its end, or an error ///@param cancellation_token set when the client goes away +///@param discard_failed_stream_tail leave buffered output unsent on a reported generation failure void RestHandler::run_chat_turn(const json& request, chat_sink& sink, - std::shared_ptr cancellation_token, const std::string& effort_param) { + std::shared_ptr cancellation_token, + bool discard_failed_stream_tail, const std::string& effort_param) { auto bad_request = [&sink](const std::string& message, const std::string& param = std::string()) { sink.on_error({400, "invalid_request_error", message, param, std::nullopt}); }; @@ -1835,7 +1839,13 @@ void RestHandler::run_chat_turn(const json& request, chat_sink& sink, } try { - sink.on_end(turn_end(ostream.finish(), true)); + if (discard_failed_stream_tail && meta_info.stop_reason == ERROR_DETECTED) { + // Finalizing can emit buffered text and commit SSE headers before the error. + const chat_msg no_message; + sink.on_end(turn_end(no_message, true)); + } else { + sink.on_end(turn_end(ostream.finish(), true)); + } } catch (const std::exception& e) { header_print("ERROR", std::string("Finishing the stream failed: ") + e.what()); sink.on_error(engine_exception_error(e)); @@ -2140,6 +2150,27 @@ void RestHandler::handle_openai_completion(const json& request, uniformed_input.requested_max_new_tokens = budget; header_print("FLM", "Start generating..."); + const auto finish_reason = [&] { + return meta_info.stop_reason == MAX_LENGTH_REACHED ? "length" : "stop"; + }; + const auto completion_usage = [&] { + json usage = { + {"prompt_tokens", meta_info.prompt_tokens}, + {"prompt_tokens_details", {{"cached_tokens", meta_info.cached_prompt_tokens}}}, + {"completion_tokens", meta_info.generated_tokens}, + {"total_tokens", meta_info.prompt_tokens + meta_info.generated_tokens} + }; + if (meta_info.prefix_cache.valid) usage["flm_prefix_cache"] = prefix_cache_usage_json(meta_info.prefix_cache); + return usage; + }; + const auto generate = [&](std::ostream& out) { + auto_chat_engine->generate(meta_info, length_limit, out, + [&] { return cancellation_token && cancellation_token->cancelled(); }); + if (meta_info.stop_reason == ERROR_DETECTED) { + throw std::runtime_error("Generation failed"); + } + }; + if (stream) { // Create a wrapper callback that passes the pre-formatted SSE string directly bool stream_started = false; @@ -2148,7 +2179,11 @@ void RestHandler::handle_openai_completion(const json& request, json data_json = data; send_streaming_response(data_json, is_final); }; - streaming_ostream_openai ostream(model, openai_stream_callback, stream_include_usage(request)); // streaming in completion format + const bool include_usage = stream_include_usage(request); + streaming_ostream_openai ostream(model, openai_stream_callback, include_usage); + const auto finalize = [&] { + ostream.finalize(finish_reason(), include_usage ? completion_usage() : json()); + }; // Once a chunk is out the headers are sent, so an error can only go // out as one more event, and the stream still has to be ended or the // client waits on it until its own timeout @@ -2171,7 +2206,7 @@ void RestHandler::handle_openai_completion(const json& request, if (meta_info.stop_reason == CANCEL_DETECTED || (cancellation_token && cancellation_token->cancelled())) { meta_info.stop_reason = CANCEL_DETECTED; header_print("❌ ", "Prefill Cancelled!"); - ostream.finalize(meta_info); + finalize(); this->auto_chat_engine->clear_context(); return; } @@ -2185,7 +2220,7 @@ void RestHandler::handle_openai_completion(const json& request, return; } try { - auto_chat_engine->generate(meta_info, length_limit, ostream, [&] { return cancellation_token && cancellation_token->cancelled(); }); + generate(ostream); } catch (const ModelRequestError& error) { send_stream_error(ModelErrorResponse(error)); return; @@ -2195,7 +2230,7 @@ void RestHandler::handle_openai_completion(const json& request, return; } try { - ostream.finalize(meta_info); + finalize(); } catch (const std::exception& e) { header_print("ERROR", std::string("Finishing the stream failed: ") + e.what()); send_stream_error(EngineExceptionResponse(e)); @@ -2229,7 +2264,7 @@ void RestHandler::handle_openai_completion(const json& request, return; } try { - auto_chat_engine->generate(meta_info, length_limit, ostream, [&] { return cancellation_token && cancellation_token->cancelled(); }); + generate(ostream); } catch (const std::exception& e) { json error_response = EngineExceptionResponse(e); send_response(error_response); @@ -2240,7 +2275,7 @@ void RestHandler::handle_openai_completion(const json& request, auto history = this->auto_chat_engine->get_history(); json response = { - {"id", "fastflowlm-chat-completion"}, + {"id", flm::openai::random_id("cmpl-", 24)}, {"object", "text_completion"}, {"created", (int)std::time(nullptr)}, {"model", model}, @@ -2249,17 +2284,11 @@ void RestHandler::handle_openai_completion(const json& request, {"text", response_text}, {"index", 0}, {"logprobs", nullptr}, - {"finish_reason", stop_reason_to_string(meta_info.stop_reason)} + {"finish_reason", finish_reason()} } })}, - {"usage", { - {"prompt_tokens", meta_info.prompt_tokens}, - {"prompt_tokens_details", {{"cached_tokens", meta_info.cached_prompt_tokens}}}, - {"completion_tokens", meta_info.generated_tokens}, - {"total_tokens", meta_info.prompt_tokens + meta_info.generated_tokens} - }} + {"usage", completion_usage()} }; - if (meta_info.prefix_cache.valid) response["usage"]["flm_prefix_cache"] = prefix_cache_usage_json(meta_info.prefix_cache); log_request_summary(meta_info, this->auto_chat_engine->get_current_context_length(), this->auto_chat_engine->get_max_length()); send_response(response); } diff --git a/src/server/rest_handler.hpp b/src/server/rest_handler.hpp index cb550a26d..755c1f721 100644 --- a/src/server/rest_handler.hpp +++ b/src/server/rest_handler.hpp @@ -138,7 +138,8 @@ class RestHandler { const std::optional& reasoning_effort = std::nullopt); /// \brief Run one chat turn, whatever protocol asked for it, and report it to the sink void run_chat_turn(const json& request, chat_sink& sink, - std::shared_ptr cancellation_token, const std::string& effort_param = "reasoning_effort"); + std::shared_ptr cancellation_token, bool discard_failed_stream_tail, + const std::string& effort_param = "reasoning_effort"); flm_rt::device* npu_device_inst; diff --git a/src/server/streaming_ostream_openai.hpp b/src/server/streaming_ostream_openai.hpp index a7c872280..08ea188d6 100644 --- a/src/server/streaming_ostream_openai.hpp +++ b/src/server/streaming_ostream_openai.hpp @@ -8,30 +8,21 @@ */ #pragma once +#include +#include #include #include -#include #include -#include -#include -#include -#include +#include #include -#include "prefix_cache_usage.hpp" -#include "AutoModel/automodel.hpp" +#include "openai_response_id.hpp" #include "wstream_buf.hpp" using json = nlohmann::ordered_json; -class AutoModel; - // v1/completions ///@brief Custom streambuf that captures tokens and sends them immediately -///@param model the model -///@param callback the callback -///@param is_chat_format the is chat format -///@return the streaming buf ///@note The packet is sent every std::flush, but only when UTF-8 sequences are complete class streaming_buf_openai : public std::streambuf { public: @@ -42,12 +33,11 @@ class streaming_buf_openai : public std::streambuf { ///@param callback receives each server-sent event ///@param include_usage stream_options.include_usage: send usage in its own chunk before [DONE] streaming_buf_openai(const std::string& model, StreamCallback callback, bool include_usage) - : model_name(model), stream_callback(callback), include_usage(include_usage), first_chunk(true) { - // Generate a unique ID for this stream - generate_stream_id(); - generate_created(); - generate_system_fingerprint(); - } + : model_name(model), stream_callback(std::move(callback)), include_usage(include_usage), + stream_id(flm::openai::random_id("cmpl-", 24)), + created(std::chrono::duration_cast( + std::chrono::system_clock::now().time_since_epoch()).count()), + system_fingerprint(flm::openai::random_id("fp_", 16)) {} protected: ///@brief Called when buffer is full or flush is requested @@ -63,58 +53,30 @@ class streaming_buf_openai : public std::streambuf { ///@brief Called when stream is flushed ///@return 0 int sync() override { - flush_complete_utf8_sequences(false); + flush_complete_utf8_sequences(); return 0; } public: ///@brief Call this when generation is complete - void finalize(chat_meta_info_t& meta_info) { + void finalize(const char* finish_reason, const json& usage) { // Send the remaining content but not an incomplete UTF-8 sequence at // its end: a generation cut off by the length limit or a cancel can // stop partway through a multi-byte character, the missing bytes will // never come, and invalid UTF-8 makes json::dump() throw - flush_complete_utf8_sequences(false); + flush_complete_utf8_sequences(); buffer.clear(); - send_final_response(meta_info); + send_choice("", finish_reason); + if (include_usage) { + send_chunk(json::array(), usage); + } + stream_callback("data: [DONE]\n\n", true); } private: - ///@brief Generate a unique stream ID - void generate_stream_id() { - std::random_device rd; - std::mt19937 gen(rd()); - std::uniform_int_distribution<> dis(0, 15); - - std::stringstream ss; - ss << "chatcmpl-"; - for (int i = 0; i < 24; ++i) { - ss << std::hex << dis(gen); - } - stream_id = ss.str(); - } - void generate_created() { - created = std::chrono::duration_cast( - std::chrono::system_clock::now().time_since_epoch() - ).count(); - } - void generate_system_fingerprint() { - std::random_device rd; - std::mt19937 gen(rd()); - std::uniform_int_distribution<> dis(0, 15); - - std::stringstream ss; - ss << "fp_"; - for (int i = 0; i < 16; ++i) { - ss << std::hex << dis(gen); - } - system_fingerprint = ss.str(); - } - ///@brief Flush only complete UTF-8 sequences - ///@param is_final the is final - void flush_complete_utf8_sequences(bool is_final) { + void flush_complete_utf8_sequences() { if (buffer.empty()) return; std::string complete_content; @@ -142,7 +104,7 @@ class streaming_buf_openai : public std::streambuf { // Send complete sequences if any if (!complete_content.empty()) { - send_response(complete_content, is_final); + send_choice(complete_content, nullptr); } // Remove processed bytes from buffer @@ -151,77 +113,29 @@ class streaming_buf_openai : public std::streambuf { } } - ///@brief Send the response - ///@param content the content - ///@param is_final the is final - void send_response(const std::string& content, bool is_final) { - json response; - - // Content chunk - response = { - {"id", stream_id}, - {"object", "text_completion"}, - {"created", created}, - {"system_fingerprint", system_fingerprint}, - {"model", model_name}, - {"choices", json::array({ - { - {"text", content}, - {"index", 0}, - {"logprobs", nullptr}, - {"finish_reason", nullptr} - } - })} - }; - if (include_usage) { - response["usage"] = nullptr; - } - - stream_callback("data: " + response.dump() + "\n\n", is_final); - + void send_choice(const std::string& text, const json& finish_reason) { + send_chunk(json::array({{ + {"text", text}, + {"index", 0}, + {"logprobs", nullptr}, + {"finish_reason", finish_reason} + }}), nullptr); } - ///@brief Send the chat final response - void send_final_response(chat_meta_info_t& meta_info) { - // Send final chunk with finish_reason only (no empty delta) - json final_response = { + void send_chunk(json choices, const json& usage) { + json response = { {"id", stream_id}, {"object", "text_completion"}, {"created", created}, {"system_fingerprint", system_fingerprint}, {"model", model_name}, - {"choices", json::array({ - { - {"finish_reason", stop_reason_to_string(meta_info.stop_reason)}, - } - })} + {"choices", std::move(choices)} }; if (include_usage) { - // OpenAI: every chunk carries a null usage, then one extra chunk - // with no choices carries the usage of the whole request - final_response["usage"] = nullptr; + response["usage"] = usage; } - stream_callback("data: " + final_response.dump() + "\n\n", false); - if (include_usage) { - json usage_response = { - {"id", stream_id}, - {"object", "text_completion"}, - {"created", created}, - {"system_fingerprint", system_fingerprint}, - {"model", model_name}, - {"choices", json::array()}, - {"usage", { - {"prompt_tokens", meta_info.prompt_tokens}, - {"prompt_tokens_details", {{"cached_tokens", meta_info.cached_prompt_tokens}}}, - {"completion_tokens", meta_info.generated_tokens}, - {"total_tokens", meta_info.prompt_tokens + meta_info.generated_tokens} - }} - }; - if (meta_info.prefix_cache.valid) usage_response["usage"]["flm_prefix_cache"] = prefix_cache_usage_json(meta_info.prefix_cache); - stream_callback("data: " + usage_response.dump() + "\n\n", false); - } - // Send the [DONE] message - stream_callback("data: [DONE]\n\n", true); + + stream_callback("data: " + response.dump() + "\n\n", false); } @@ -235,25 +149,22 @@ class streaming_buf_openai : public std::streambuf { bool include_usage; ///@brief Stream ID std::string stream_id; - long created; + std::chrono::seconds::rep created; std::string system_fingerprint; - ///@brief First chunk flag - bool first_chunk; }; ///@brief Custom ostream for streaming ///@param model the model ///@param callback the callback -///@param is_chat_format the is chat format ///@return the streaming ostream class streaming_ostream_openai : public std::ostream { public: streaming_ostream_openai(const std::string& model, streaming_buf_openai::StreamCallback callback, bool include_usage) - : std::ostream(&buf), buf(model, callback, include_usage) {} + : std::ostream(&buf), buf(model, std::move(callback), include_usage) {} - ///@brief Finalize the chat - void finalize(chat_meta_info_t& meta_info) { - buf.finalize(meta_info); + ///@brief Finalize the completion + void finalize(const char* finish_reason, const json& usage) { + buf.finalize(finish_reason, usage); } private: diff --git a/src/test/chat_protocols/golden/chat_completions.txt b/src/test/chat_protocols/golden/chat_completions.txt index e450c1c45..d9cde129a 100644 --- a/src/test/chat_protocols/golden/chat_completions.txt +++ b/src/test/chat_protocols/golden/chat_completions.txt @@ -1,16 +1,16 @@ ### text [nstream] -response: {"id":"fastflowlm-chat-completion","object":"chat.completion","created":0,"model":"model-faker","choices":[{"index":0,"message":{"role":"assistant","content":"Hello world!"},"logprobs":null,"finish_reason":"stop"}],"usage":{"prompt_tokens":40,"prompt_tokens_details":{"cached_tokens":8},"completion_tokens":5,"total_tokens":45,"kv_token_occupancy_rate_percentage":3.0029296875,"load_duration":0,"prefill_duration_ttft":0.25,"decoding_duration":0.5,"prefill_speed_tps":128.0,"decoding_speed_tps":10.0},"service_tier":"default"} +response: {"id":"chatcmpl-ID","object":"chat.completion","created":0,"model":"model-faker","choices":[{"index":0,"message":{"role":"assistant","content":"Hello world!"},"logprobs":null,"finish_reason":"stop"}],"usage":{"prompt_tokens":40,"prompt_tokens_details":{"cached_tokens":8},"completion_tokens":5,"total_tokens":45,"kv_token_occupancy_rate_percentage":3.0029296875,"load_duration":0,"prefill_duration_ttft":0.25,"decoding_duration":0.5,"prefill_speed_tps":128.0,"decoding_speed_tps":10.0},"service_tier":"default"} ### text [stream] chunk: data: {"id":"chatcmpl-ID","object":"chat.completion.chunk","created":0,"model":"model-faker","choices":[{"index":0,"delta":{"role":"assistant","content":"Hel"},"finish_reason":null}]} -chunk: data: {"id":"chatcmpl-ID","object":"chat.completion.chunk","created":0,"model":"model-faker","choices":[{"index":0,"delta":{"role":"assistant","content":"lo"},"finish_reason":null}]} +chunk: data: {"id":"chatcmpl-ID","object":"chat.completion.chunk","created":0,"model":"model-faker","choices":[{"index":0,"delta":{"content":"lo"},"finish_reason":null}]} -chunk: data: {"id":"chatcmpl-ID","object":"chat.completion.chunk","created":0,"model":"model-faker","choices":[{"index":0,"delta":{"role":"assistant","content":" wor"},"finish_reason":null}]} +chunk: data: {"id":"chatcmpl-ID","object":"chat.completion.chunk","created":0,"model":"model-faker","choices":[{"index":0,"delta":{"content":" wor"},"finish_reason":null}]} -chunk: data: {"id":"chatcmpl-ID","object":"chat.completion.chunk","created":0,"model":"model-faker","choices":[{"index":0,"delta":{"role":"assistant","content":"ld"},"finish_reason":null}]} +chunk: data: {"id":"chatcmpl-ID","object":"chat.completion.chunk","created":0,"model":"model-faker","choices":[{"index":0,"delta":{"content":"ld"},"finish_reason":null}]} -chunk: data: {"id":"chatcmpl-ID","object":"chat.completion.chunk","created":0,"model":"model-faker","choices":[{"index":0,"delta":{"role":"assistant","content":"!"},"finish_reason":null}]} +chunk: data: {"id":"chatcmpl-ID","object":"chat.completion.chunk","created":0,"model":"model-faker","choices":[{"index":0,"delta":{"content":"!"},"finish_reason":null}]} chunk: data: {"id":"chatcmpl-ID","object":"chat.completion.chunk","created":0,"model":"model-faker","system_fingerprint":"fp_ID","choices":[{"index":0,"delta":{"content":null},"finish_reason":"stop"}]} @@ -20,13 +20,13 @@ final: data: [DONE] ### text [stream+usage] chunk: data: {"id":"chatcmpl-ID","object":"chat.completion.chunk","created":0,"model":"model-faker","choices":[{"index":0,"delta":{"role":"assistant","content":"Hel"},"finish_reason":null}],"usage":null} -chunk: data: {"id":"chatcmpl-ID","object":"chat.completion.chunk","created":0,"model":"model-faker","choices":[{"index":0,"delta":{"role":"assistant","content":"lo"},"finish_reason":null}],"usage":null} +chunk: data: {"id":"chatcmpl-ID","object":"chat.completion.chunk","created":0,"model":"model-faker","choices":[{"index":0,"delta":{"content":"lo"},"finish_reason":null}],"usage":null} -chunk: data: {"id":"chatcmpl-ID","object":"chat.completion.chunk","created":0,"model":"model-faker","choices":[{"index":0,"delta":{"role":"assistant","content":" wor"},"finish_reason":null}],"usage":null} +chunk: data: {"id":"chatcmpl-ID","object":"chat.completion.chunk","created":0,"model":"model-faker","choices":[{"index":0,"delta":{"content":" wor"},"finish_reason":null}],"usage":null} -chunk: data: {"id":"chatcmpl-ID","object":"chat.completion.chunk","created":0,"model":"model-faker","choices":[{"index":0,"delta":{"role":"assistant","content":"ld"},"finish_reason":null}],"usage":null} +chunk: data: {"id":"chatcmpl-ID","object":"chat.completion.chunk","created":0,"model":"model-faker","choices":[{"index":0,"delta":{"content":"ld"},"finish_reason":null}],"usage":null} -chunk: data: {"id":"chatcmpl-ID","object":"chat.completion.chunk","created":0,"model":"model-faker","choices":[{"index":0,"delta":{"role":"assistant","content":"!"},"finish_reason":null}],"usage":null} +chunk: data: {"id":"chatcmpl-ID","object":"chat.completion.chunk","created":0,"model":"model-faker","choices":[{"index":0,"delta":{"content":"!"},"finish_reason":null}],"usage":null} chunk: data: {"id":"chatcmpl-ID","object":"chat.completion.chunk","created":0,"model":"model-faker","system_fingerprint":"fp_ID","choices":[{"index":0,"delta":{"content":null},"finish_reason":"stop"}],"usage":null} @@ -36,16 +36,16 @@ final: data: [DONE] ### reasoning_text [nstream] -response: {"id":"fastflowlm-chat-completion","object":"chat.completion","created":0,"model":"model-faker","choices":[{"index":0,"message":{"role":"assistant","reasoning_content":"Let me think.","content":"The answer is 4."},"logprobs":null,"finish_reason":"stop"}],"usage":{"prompt_tokens":40,"prompt_tokens_details":{"cached_tokens":8},"completion_tokens":7,"total_tokens":47,"kv_token_occupancy_rate_percentage":3.0029296875,"load_duration":0,"prefill_duration_ttft":0.25,"decoding_duration":0.5,"prefill_speed_tps":128.0,"decoding_speed_tps":14.0},"service_tier":"default"} +response: {"id":"chatcmpl-ID","object":"chat.completion","created":0,"model":"model-faker","choices":[{"index":0,"message":{"role":"assistant","reasoning_content":"Let me think.","content":"The answer is 4."},"logprobs":null,"finish_reason":"stop"}],"usage":{"prompt_tokens":40,"prompt_tokens_details":{"cached_tokens":8},"completion_tokens":7,"total_tokens":47,"kv_token_occupancy_rate_percentage":3.0029296875,"load_duration":0,"prefill_duration_ttft":0.25,"decoding_duration":0.5,"prefill_speed_tps":128.0,"decoding_speed_tps":14.0},"service_tier":"default"} ### reasoning_text [stream] chunk: data: {"id":"chatcmpl-ID","object":"chat.completion.chunk","created":0,"model":"model-faker","choices":[{"index":0,"delta":{"role":"assistant","reasoning_content":"Let me"},"finish_reason":null}]} -chunk: data: {"id":"chatcmpl-ID","object":"chat.completion.chunk","created":0,"model":"model-faker","choices":[{"index":0,"delta":{"role":"assistant","reasoning_content":" think."},"finish_reason":null}]} +chunk: data: {"id":"chatcmpl-ID","object":"chat.completion.chunk","created":0,"model":"model-faker","choices":[{"index":0,"delta":{"reasoning_content":" think."},"finish_reason":null}]} -chunk: data: {"id":"chatcmpl-ID","object":"chat.completion.chunk","created":0,"model":"model-faker","choices":[{"index":0,"delta":{"role":"assistant","content":"The answer"},"finish_reason":null}]} +chunk: data: {"id":"chatcmpl-ID","object":"chat.completion.chunk","created":0,"model":"model-faker","choices":[{"index":0,"delta":{"content":"The answer"},"finish_reason":null}]} -chunk: data: {"id":"chatcmpl-ID","object":"chat.completion.chunk","created":0,"model":"model-faker","choices":[{"index":0,"delta":{"role":"assistant","content":" is 4."},"finish_reason":null}]} +chunk: data: {"id":"chatcmpl-ID","object":"chat.completion.chunk","created":0,"model":"model-faker","choices":[{"index":0,"delta":{"content":" is 4."},"finish_reason":null}]} chunk: data: {"id":"chatcmpl-ID","object":"chat.completion.chunk","created":0,"model":"model-faker","system_fingerprint":"fp_ID","choices":[{"index":0,"delta":{"content":null},"finish_reason":"stop"}]} @@ -55,11 +55,11 @@ final: data: [DONE] ### reasoning_text [stream+usage] chunk: data: {"id":"chatcmpl-ID","object":"chat.completion.chunk","created":0,"model":"model-faker","choices":[{"index":0,"delta":{"role":"assistant","reasoning_content":"Let me"},"finish_reason":null}],"usage":null} -chunk: data: {"id":"chatcmpl-ID","object":"chat.completion.chunk","created":0,"model":"model-faker","choices":[{"index":0,"delta":{"role":"assistant","reasoning_content":" think."},"finish_reason":null}],"usage":null} +chunk: data: {"id":"chatcmpl-ID","object":"chat.completion.chunk","created":0,"model":"model-faker","choices":[{"index":0,"delta":{"reasoning_content":" think."},"finish_reason":null}],"usage":null} -chunk: data: {"id":"chatcmpl-ID","object":"chat.completion.chunk","created":0,"model":"model-faker","choices":[{"index":0,"delta":{"role":"assistant","content":"The answer"},"finish_reason":null}],"usage":null} +chunk: data: {"id":"chatcmpl-ID","object":"chat.completion.chunk","created":0,"model":"model-faker","choices":[{"index":0,"delta":{"content":"The answer"},"finish_reason":null}],"usage":null} -chunk: data: {"id":"chatcmpl-ID","object":"chat.completion.chunk","created":0,"model":"model-faker","choices":[{"index":0,"delta":{"role":"assistant","content":" is 4."},"finish_reason":null}],"usage":null} +chunk: data: {"id":"chatcmpl-ID","object":"chat.completion.chunk","created":0,"model":"model-faker","choices":[{"index":0,"delta":{"content":" is 4."},"finish_reason":null}],"usage":null} chunk: data: {"id":"chatcmpl-ID","object":"chat.completion.chunk","created":0,"model":"model-faker","system_fingerprint":"fp_ID","choices":[{"index":0,"delta":{"content":null},"finish_reason":"stop"}],"usage":null} @@ -69,12 +69,12 @@ final: data: [DONE] ### tool_call [nstream] -response: {"id":"fastflowlm-chat-completion","object":"chat.completion","created":0,"model":"model-faker","choices":[{"index":0,"message":{"role":"assistant","tool_calls":[{"index":0,"id":"call_ID","type":"function","function":{"name":"get_weather","arguments":"{\"city\": \"Paris\"}"}}],"content":null},"logprobs":null,"finish_reason":"tool_calls"}],"usage":{"prompt_tokens":40,"prompt_tokens_details":{"cached_tokens":8},"completion_tokens":5,"total_tokens":45,"kv_token_occupancy_rate_percentage":3.0029296875,"load_duration":0,"prefill_duration_ttft":0.25,"decoding_duration":0.5,"prefill_speed_tps":128.0,"decoding_speed_tps":10.0},"service_tier":"default"} +response: {"id":"chatcmpl-ID","object":"chat.completion","created":0,"model":"model-faker","choices":[{"index":0,"message":{"role":"assistant","tool_calls":[{"index":0,"id":"call_ID","type":"function","function":{"name":"get_weather","arguments":"{\"city\": \"Paris\"}"}}],"content":null},"logprobs":null,"finish_reason":"tool_calls"}],"usage":{"prompt_tokens":40,"prompt_tokens_details":{"cached_tokens":8},"completion_tokens":5,"total_tokens":45,"kv_token_occupancy_rate_percentage":3.0029296875,"load_duration":0,"prefill_duration_ttft":0.25,"decoding_duration":0.5,"prefill_speed_tps":128.0,"decoding_speed_tps":10.0},"service_tier":"default"} ### tool_call [stream] chunk: data: {"id":"chatcmpl-ID","object":"chat.completion.chunk","created":0,"model":"model-faker","choices":[{"index":0,"delta":{"role":"assistant","tool_calls":[{"index":0,"id":"call_ID","type":"function","function":{"name":"get_weather","arguments":"{\"city\":"}}]},"finish_reason":null}]} -chunk: data: {"id":"chatcmpl-ID","object":"chat.completion.chunk","created":0,"model":"model-faker","choices":[{"index":0,"delta":{"role":"assistant","tool_calls":[{"index":0,"function":{"arguments":" \"Paris\"}"}}]},"finish_reason":null}]} +chunk: data: {"id":"chatcmpl-ID","object":"chat.completion.chunk","created":0,"model":"model-faker","choices":[{"index":0,"delta":{"tool_calls":[{"index":0,"function":{"arguments":" \"Paris\"}"}}]},"finish_reason":null}]} chunk: data: {"id":"chatcmpl-ID","object":"chat.completion.chunk","created":0,"model":"model-faker","system_fingerprint":"fp_ID","choices":[{"index":0,"delta":{"content":null},"finish_reason":"tool_calls"}]} @@ -84,7 +84,7 @@ final: data: [DONE] ### tool_call [stream+usage] chunk: data: {"id":"chatcmpl-ID","object":"chat.completion.chunk","created":0,"model":"model-faker","choices":[{"index":0,"delta":{"role":"assistant","tool_calls":[{"index":0,"id":"call_ID","type":"function","function":{"name":"get_weather","arguments":"{\"city\":"}}]},"finish_reason":null}],"usage":null} -chunk: data: {"id":"chatcmpl-ID","object":"chat.completion.chunk","created":0,"model":"model-faker","choices":[{"index":0,"delta":{"role":"assistant","tool_calls":[{"index":0,"function":{"arguments":" \"Paris\"}"}}]},"finish_reason":null}],"usage":null} +chunk: data: {"id":"chatcmpl-ID","object":"chat.completion.chunk","created":0,"model":"model-faker","choices":[{"index":0,"delta":{"tool_calls":[{"index":0,"function":{"arguments":" \"Paris\"}"}}]},"finish_reason":null}],"usage":null} chunk: data: {"id":"chatcmpl-ID","object":"chat.completion.chunk","created":0,"model":"model-faker","system_fingerprint":"fp_ID","choices":[{"index":0,"delta":{"content":null},"finish_reason":"tool_calls"}],"usage":null} @@ -94,16 +94,16 @@ final: data: [DONE] ### two_tool_calls [nstream] -response: {"id":"fastflowlm-chat-completion","object":"chat.completion","created":0,"model":"model-faker","choices":[{"index":0,"message":{"role":"assistant","tool_calls":[{"index":0,"id":"call_ID","type":"function","function":{"name":"get_weather","arguments":"{\"city\": \"Paris\"}"}},{"index":1,"id":"call_ID","type":"function","function":{"name":"get_weather","arguments":"{\"city\": \"Rome\"}"}}],"content":"I will look."},"logprobs":null,"finish_reason":"tool_calls"}],"usage":{"prompt_tokens":40,"prompt_tokens_details":{"cached_tokens":8},"completion_tokens":4,"total_tokens":44,"kv_token_occupancy_rate_percentage":3.0029296875,"load_duration":0,"prefill_duration_ttft":0.25,"decoding_duration":0.5,"prefill_speed_tps":128.0,"decoding_speed_tps":8.0},"service_tier":"default"} +response: {"id":"chatcmpl-ID","object":"chat.completion","created":0,"model":"model-faker","choices":[{"index":0,"message":{"role":"assistant","tool_calls":[{"index":0,"id":"call_ID","type":"function","function":{"name":"get_weather","arguments":"{\"city\": \"Paris\"}"}},{"index":1,"id":"call_ID","type":"function","function":{"name":"get_weather","arguments":"{\"city\": \"Rome\"}"}}],"content":"I will look."},"logprobs":null,"finish_reason":"tool_calls"}],"usage":{"prompt_tokens":40,"prompt_tokens_details":{"cached_tokens":8},"completion_tokens":4,"total_tokens":44,"kv_token_occupancy_rate_percentage":3.0029296875,"load_duration":0,"prefill_duration_ttft":0.25,"decoding_duration":0.5,"prefill_speed_tps":128.0,"decoding_speed_tps":8.0},"service_tier":"default"} ### two_tool_calls [stream] chunk: data: {"id":"chatcmpl-ID","object":"chat.completion.chunk","created":0,"model":"model-faker","choices":[{"index":0,"delta":{"role":"assistant","content":"I will look."},"finish_reason":null}]} -chunk: data: {"id":"chatcmpl-ID","object":"chat.completion.chunk","created":0,"model":"model-faker","choices":[{"index":0,"delta":{"role":"assistant","tool_calls":[{"index":0,"id":"call_ID","type":"function","function":{"name":"get_weather","arguments":"{\"city\": \"Paris\"}"}}]},"finish_reason":null}]} +chunk: data: {"id":"chatcmpl-ID","object":"chat.completion.chunk","created":0,"model":"model-faker","choices":[{"index":0,"delta":{"tool_calls":[{"index":0,"id":"call_ID","type":"function","function":{"name":"get_weather","arguments":"{\"city\": \"Paris\"}"}}]},"finish_reason":null}]} -chunk: data: {"id":"chatcmpl-ID","object":"chat.completion.chunk","created":0,"model":"model-faker","choices":[{"index":0,"delta":{"role":"assistant","tool_calls":[{"index":1,"id":"call_ID","type":"function","function":{"name":"get_weather","arguments":""}}]},"finish_reason":null}]} +chunk: data: {"id":"chatcmpl-ID","object":"chat.completion.chunk","created":0,"model":"model-faker","choices":[{"index":0,"delta":{"tool_calls":[{"index":1,"id":"call_ID","type":"function","function":{"name":"get_weather","arguments":""}}]},"finish_reason":null}]} -chunk: data: {"id":"chatcmpl-ID","object":"chat.completion.chunk","created":0,"model":"model-faker","choices":[{"index":0,"delta":{"role":"assistant","tool_calls":[{"index":1,"function":{"arguments":"{\"city\": \"Rome\"}"}}]},"finish_reason":null}]} +chunk: data: {"id":"chatcmpl-ID","object":"chat.completion.chunk","created":0,"model":"model-faker","choices":[{"index":0,"delta":{"tool_calls":[{"index":1,"function":{"arguments":"{\"city\": \"Rome\"}"}}]},"finish_reason":null}]} chunk: data: {"id":"chatcmpl-ID","object":"chat.completion.chunk","created":0,"model":"model-faker","system_fingerprint":"fp_ID","choices":[{"index":0,"delta":{"content":null},"finish_reason":"tool_calls"}]} @@ -113,11 +113,11 @@ final: data: [DONE] ### two_tool_calls [stream+usage] chunk: data: {"id":"chatcmpl-ID","object":"chat.completion.chunk","created":0,"model":"model-faker","choices":[{"index":0,"delta":{"role":"assistant","content":"I will look."},"finish_reason":null}],"usage":null} -chunk: data: {"id":"chatcmpl-ID","object":"chat.completion.chunk","created":0,"model":"model-faker","choices":[{"index":0,"delta":{"role":"assistant","tool_calls":[{"index":0,"id":"call_ID","type":"function","function":{"name":"get_weather","arguments":"{\"city\": \"Paris\"}"}}]},"finish_reason":null}],"usage":null} +chunk: data: {"id":"chatcmpl-ID","object":"chat.completion.chunk","created":0,"model":"model-faker","choices":[{"index":0,"delta":{"tool_calls":[{"index":0,"id":"call_ID","type":"function","function":{"name":"get_weather","arguments":"{\"city\": \"Paris\"}"}}]},"finish_reason":null}],"usage":null} -chunk: data: {"id":"chatcmpl-ID","object":"chat.completion.chunk","created":0,"model":"model-faker","choices":[{"index":0,"delta":{"role":"assistant","tool_calls":[{"index":1,"id":"call_ID","type":"function","function":{"name":"get_weather","arguments":""}}]},"finish_reason":null}],"usage":null} +chunk: data: {"id":"chatcmpl-ID","object":"chat.completion.chunk","created":0,"model":"model-faker","choices":[{"index":0,"delta":{"tool_calls":[{"index":1,"id":"call_ID","type":"function","function":{"name":"get_weather","arguments":""}}]},"finish_reason":null}],"usage":null} -chunk: data: {"id":"chatcmpl-ID","object":"chat.completion.chunk","created":0,"model":"model-faker","choices":[{"index":0,"delta":{"role":"assistant","tool_calls":[{"index":1,"function":{"arguments":"{\"city\": \"Rome\"}"}}]},"finish_reason":null}],"usage":null} +chunk: data: {"id":"chatcmpl-ID","object":"chat.completion.chunk","created":0,"model":"model-faker","choices":[{"index":0,"delta":{"tool_calls":[{"index":1,"function":{"arguments":"{\"city\": \"Rome\"}"}}]},"finish_reason":null}],"usage":null} chunk: data: {"id":"chatcmpl-ID","object":"chat.completion.chunk","created":0,"model":"model-faker","system_fingerprint":"fp_ID","choices":[{"index":0,"delta":{"content":null},"finish_reason":"tool_calls"}],"usage":null} @@ -127,14 +127,14 @@ final: data: [DONE] ### utf8_split [nstream] -response: {"id":"fastflowlm-chat-completion","object":"chat.completion","created":0,"model":"model-faker","choices":[{"index":0,"message":{"role":"assistant","content":"café €"},"logprobs":null,"finish_reason":"stop"}],"usage":{"prompt_tokens":40,"prompt_tokens_details":{"cached_tokens":8},"completion_tokens":6,"total_tokens":46,"kv_token_occupancy_rate_percentage":3.0029296875,"load_duration":0,"prefill_duration_ttft":0.25,"decoding_duration":0.5,"prefill_speed_tps":128.0,"decoding_speed_tps":12.0},"service_tier":"default"} +response: {"id":"chatcmpl-ID","object":"chat.completion","created":0,"model":"model-faker","choices":[{"index":0,"message":{"role":"assistant","content":"café €"},"logprobs":null,"finish_reason":"stop"}],"usage":{"prompt_tokens":40,"prompt_tokens_details":{"cached_tokens":8},"completion_tokens":6,"total_tokens":46,"kv_token_occupancy_rate_percentage":3.0029296875,"load_duration":0,"prefill_duration_ttft":0.25,"decoding_duration":0.5,"prefill_speed_tps":128.0,"decoding_speed_tps":12.0},"service_tier":"default"} ### utf8_split [stream] chunk: data: {"id":"chatcmpl-ID","object":"chat.completion.chunk","created":0,"model":"model-faker","choices":[{"index":0,"delta":{"role":"assistant","content":"caf"},"finish_reason":null}]} -chunk: data: {"id":"chatcmpl-ID","object":"chat.completion.chunk","created":0,"model":"model-faker","choices":[{"index":0,"delta":{"role":"assistant","content":"é"},"finish_reason":null}]} +chunk: data: {"id":"chatcmpl-ID","object":"chat.completion.chunk","created":0,"model":"model-faker","choices":[{"index":0,"delta":{"content":"é"},"finish_reason":null}]} -chunk: data: {"id":"chatcmpl-ID","object":"chat.completion.chunk","created":0,"model":"model-faker","choices":[{"index":0,"delta":{"role":"assistant","content":" €"},"finish_reason":null}]} +chunk: data: {"id":"chatcmpl-ID","object":"chat.completion.chunk","created":0,"model":"model-faker","choices":[{"index":0,"delta":{"content":" €"},"finish_reason":null}]} chunk: data: {"id":"chatcmpl-ID","object":"chat.completion.chunk","created":0,"model":"model-faker","system_fingerprint":"fp_ID","choices":[{"index":0,"delta":{"content":null},"finish_reason":"stop"}]} @@ -144,9 +144,9 @@ final: data: [DONE] ### utf8_split [stream+usage] chunk: data: {"id":"chatcmpl-ID","object":"chat.completion.chunk","created":0,"model":"model-faker","choices":[{"index":0,"delta":{"role":"assistant","content":"caf"},"finish_reason":null}],"usage":null} -chunk: data: {"id":"chatcmpl-ID","object":"chat.completion.chunk","created":0,"model":"model-faker","choices":[{"index":0,"delta":{"role":"assistant","content":"é"},"finish_reason":null}],"usage":null} +chunk: data: {"id":"chatcmpl-ID","object":"chat.completion.chunk","created":0,"model":"model-faker","choices":[{"index":0,"delta":{"content":"é"},"finish_reason":null}],"usage":null} -chunk: data: {"id":"chatcmpl-ID","object":"chat.completion.chunk","created":0,"model":"model-faker","choices":[{"index":0,"delta":{"role":"assistant","content":" €"},"finish_reason":null}],"usage":null} +chunk: data: {"id":"chatcmpl-ID","object":"chat.completion.chunk","created":0,"model":"model-faker","choices":[{"index":0,"delta":{"content":" €"},"finish_reason":null}],"usage":null} chunk: data: {"id":"chatcmpl-ID","object":"chat.completion.chunk","created":0,"model":"model-faker","system_fingerprint":"fp_ID","choices":[{"index":0,"delta":{"content":null},"finish_reason":"stop"}],"usage":null} @@ -156,12 +156,12 @@ final: data: [DONE] ### length [nstream] -response: {"id":"fastflowlm-chat-completion","object":"chat.completion","created":0,"model":"model-faker","choices":[{"index":0,"message":{"role":"assistant","content":"Hello"},"logprobs":null,"finish_reason":"length"}],"usage":{"prompt_tokens":40,"prompt_tokens_details":{"cached_tokens":8},"completion_tokens":2,"total_tokens":42,"kv_token_occupancy_rate_percentage":3.0029296875,"load_duration":0,"prefill_duration_ttft":0.25,"decoding_duration":0.5,"prefill_speed_tps":128.0,"decoding_speed_tps":4.0},"service_tier":"default"} +response: {"id":"chatcmpl-ID","object":"chat.completion","created":0,"model":"model-faker","choices":[{"index":0,"message":{"role":"assistant","content":"Hello"},"logprobs":null,"finish_reason":"length"}],"usage":{"prompt_tokens":40,"prompt_tokens_details":{"cached_tokens":8},"completion_tokens":2,"total_tokens":42,"kv_token_occupancy_rate_percentage":3.0029296875,"load_duration":0,"prefill_duration_ttft":0.25,"decoding_duration":0.5,"prefill_speed_tps":128.0,"decoding_speed_tps":4.0},"service_tier":"default"} ### length [stream] chunk: data: {"id":"chatcmpl-ID","object":"chat.completion.chunk","created":0,"model":"model-faker","choices":[{"index":0,"delta":{"role":"assistant","content":"Hel"},"finish_reason":null}]} -chunk: data: {"id":"chatcmpl-ID","object":"chat.completion.chunk","created":0,"model":"model-faker","choices":[{"index":0,"delta":{"role":"assistant","content":"lo"},"finish_reason":null}]} +chunk: data: {"id":"chatcmpl-ID","object":"chat.completion.chunk","created":0,"model":"model-faker","choices":[{"index":0,"delta":{"content":"lo"},"finish_reason":null}]} chunk: data: {"id":"chatcmpl-ID","object":"chat.completion.chunk","created":0,"model":"model-faker","system_fingerprint":"fp_ID","choices":[{"index":0,"delta":{"content":null},"finish_reason":"length"}]} @@ -171,7 +171,7 @@ final: data: [DONE] ### length [stream+usage] chunk: data: {"id":"chatcmpl-ID","object":"chat.completion.chunk","created":0,"model":"model-faker","choices":[{"index":0,"delta":{"role":"assistant","content":"Hel"},"finish_reason":null}],"usage":null} -chunk: data: {"id":"chatcmpl-ID","object":"chat.completion.chunk","created":0,"model":"model-faker","choices":[{"index":0,"delta":{"role":"assistant","content":"lo"},"finish_reason":null}],"usage":null} +chunk: data: {"id":"chatcmpl-ID","object":"chat.completion.chunk","created":0,"model":"model-faker","choices":[{"index":0,"delta":{"content":"lo"},"finish_reason":null}],"usage":null} chunk: data: {"id":"chatcmpl-ID","object":"chat.completion.chunk","created":0,"model":"model-faker","system_fingerprint":"fp_ID","choices":[{"index":0,"delta":{"content":null},"finish_reason":"length"}],"usage":null} @@ -181,7 +181,7 @@ final: data: [DONE] ### tool_call_length [nstream] -response: {"id":"fastflowlm-chat-completion","object":"chat.completion","created":0,"model":"model-faker","choices":[{"index":0,"message":{"role":"assistant","tool_calls":[{"index":0,"id":"call_ID","type":"function","function":{"name":"get_weather","arguments":"{\"city\": \"Paris\"}"}}],"content":null},"logprobs":null,"finish_reason":"length"}],"usage":{"prompt_tokens":40,"prompt_tokens_details":{"cached_tokens":8},"completion_tokens":1,"total_tokens":41,"kv_token_occupancy_rate_percentage":3.0029296875,"load_duration":0,"prefill_duration_ttft":0.25,"decoding_duration":0.5,"prefill_speed_tps":128.0,"decoding_speed_tps":2.0},"service_tier":"default"} +response: {"id":"chatcmpl-ID","object":"chat.completion","created":0,"model":"model-faker","choices":[{"index":0,"message":{"role":"assistant","tool_calls":[{"index":0,"id":"call_ID","type":"function","function":{"name":"get_weather","arguments":"{\"city\": \"Paris\"}"}}],"content":null},"logprobs":null,"finish_reason":"length"}],"usage":{"prompt_tokens":40,"prompt_tokens_details":{"cached_tokens":8},"completion_tokens":1,"total_tokens":41,"kv_token_occupancy_rate_percentage":3.0029296875,"load_duration":0,"prefill_duration_ttft":0.25,"decoding_duration":0.5,"prefill_speed_tps":128.0,"decoding_speed_tps":2.0},"service_tier":"default"} ### tool_call_length [stream] chunk: data: {"id":"chatcmpl-ID","object":"chat.completion.chunk","created":0,"model":"model-faker","choices":[{"index":0,"delta":{"role":"assistant","tool_calls":[{"index":0,"id":"call_ID","type":"function","function":{"name":"get_weather","arguments":"{\"city\": \"Paris\"}"}}]},"finish_reason":null}]} @@ -202,14 +202,14 @@ final: data: [DONE] ### cancel_in_generation [nstream] -response: {"id":"fastflowlm-chat-completion","object":"chat.completion","created":0,"model":"model-faker","choices":[{"index":0,"message":{"role":"assistant","content":"Hello"},"logprobs":null,"finish_reason":"cancel"}],"usage":{"prompt_tokens":40,"prompt_tokens_details":{"cached_tokens":8},"completion_tokens":2,"total_tokens":42,"kv_token_occupancy_rate_percentage":3.0029296875,"load_duration":0,"prefill_duration_ttft":0.25,"decoding_duration":0.5,"prefill_speed_tps":128.0,"decoding_speed_tps":4.0},"service_tier":"default"} +response: {"id":"chatcmpl-ID","object":"chat.completion","created":0,"model":"model-faker","choices":[{"index":0,"message":{"role":"assistant","content":"Hello"},"logprobs":null,"finish_reason":"stop"}],"usage":{"prompt_tokens":40,"prompt_tokens_details":{"cached_tokens":8},"completion_tokens":2,"total_tokens":42,"kv_token_occupancy_rate_percentage":3.0029296875,"load_duration":0,"prefill_duration_ttft":0.25,"decoding_duration":0.5,"prefill_speed_tps":128.0,"decoding_speed_tps":4.0},"service_tier":"default"} ### cancel_in_generation [stream] chunk: data: {"id":"chatcmpl-ID","object":"chat.completion.chunk","created":0,"model":"model-faker","choices":[{"index":0,"delta":{"role":"assistant","content":"Hel"},"finish_reason":null}]} -chunk: data: {"id":"chatcmpl-ID","object":"chat.completion.chunk","created":0,"model":"model-faker","choices":[{"index":0,"delta":{"role":"assistant","content":"lo"},"finish_reason":null}]} +chunk: data: {"id":"chatcmpl-ID","object":"chat.completion.chunk","created":0,"model":"model-faker","choices":[{"index":0,"delta":{"content":"lo"},"finish_reason":null}]} -chunk: data: {"id":"chatcmpl-ID","object":"chat.completion.chunk","created":0,"model":"model-faker","system_fingerprint":"fp_ID","choices":[{"index":0,"delta":{"content":null},"finish_reason":"cancel"}]} +chunk: data: {"id":"chatcmpl-ID","object":"chat.completion.chunk","created":0,"model":"model-faker","system_fingerprint":"fp_ID","choices":[{"index":0,"delta":{"content":null},"finish_reason":"stop"}]} final: data: [DONE] @@ -217,9 +217,9 @@ final: data: [DONE] ### cancel_in_generation [stream+usage] chunk: data: {"id":"chatcmpl-ID","object":"chat.completion.chunk","created":0,"model":"model-faker","choices":[{"index":0,"delta":{"role":"assistant","content":"Hel"},"finish_reason":null}],"usage":null} -chunk: data: {"id":"chatcmpl-ID","object":"chat.completion.chunk","created":0,"model":"model-faker","choices":[{"index":0,"delta":{"role":"assistant","content":"lo"},"finish_reason":null}],"usage":null} +chunk: data: {"id":"chatcmpl-ID","object":"chat.completion.chunk","created":0,"model":"model-faker","choices":[{"index":0,"delta":{"content":"lo"},"finish_reason":null}],"usage":null} -chunk: data: {"id":"chatcmpl-ID","object":"chat.completion.chunk","created":0,"model":"model-faker","system_fingerprint":"fp_ID","choices":[{"index":0,"delta":{"content":null},"finish_reason":"cancel"}],"usage":null} +chunk: data: {"id":"chatcmpl-ID","object":"chat.completion.chunk","created":0,"model":"model-faker","system_fingerprint":"fp_ID","choices":[{"index":0,"delta":{"content":null},"finish_reason":"stop"}],"usage":null} chunk: data: {"id":"chatcmpl-ID","object":"chat.completion.chunk","created":0,"model":"model-faker","system_fingerprint":"fp_ID","choices":[],"usage":{"prompt_tokens":40,"prompt_tokens_details":{"cached_tokens":8},"completion_tokens":2,"total_tokens":42,"active_kv_tokens":123,"max_kv_token_capacity":4096,"kv_token_occupancy_rate_percentage":3.0029296875,"load_duration":0,"prefill_duration_ttft":0.25,"decoding_duration":0.5,"prefill_speed_tps":128.0,"decoding_speed_tps":4.0}} @@ -227,12 +227,12 @@ final: data: [DONE] ### prefix_cache [nstream] -response: {"id":"fastflowlm-chat-completion","object":"chat.completion","created":0,"model":"model-faker","choices":[{"index":0,"message":{"role":"assistant","content":"Hello"},"logprobs":null,"finish_reason":"stop"}],"usage":{"prompt_tokens":40,"prompt_tokens_details":{"cached_tokens":8},"completion_tokens":2,"total_tokens":42,"kv_token_occupancy_rate_percentage":3.0029296875,"load_duration":0,"prefill_duration_ttft":0.25,"decoding_duration":0.5,"prefill_speed_tps":128.0,"decoding_speed_tps":4.0,"flm_prefix_cache":{"lookup":"hit","prompt_tokens":37,"slot":3,"slot_type":"end","matched_tokens":8,"saved":[{"slot":4,"slot_type":"end","tokens":40,"kv_from":8,"bytes":4096}],"dropped":0,"slots_used":2,"slots_max":8,"bytes_used":8192,"bytes_budget":1048576}},"service_tier":"default"} +response: {"id":"chatcmpl-ID","object":"chat.completion","created":0,"model":"model-faker","choices":[{"index":0,"message":{"role":"assistant","content":"Hello"},"logprobs":null,"finish_reason":"stop"}],"usage":{"prompt_tokens":40,"prompt_tokens_details":{"cached_tokens":8},"completion_tokens":2,"total_tokens":42,"kv_token_occupancy_rate_percentage":3.0029296875,"load_duration":0,"prefill_duration_ttft":0.25,"decoding_duration":0.5,"prefill_speed_tps":128.0,"decoding_speed_tps":4.0,"flm_prefix_cache":{"lookup":"hit","prompt_tokens":37,"slot":3,"slot_type":"end","matched_tokens":8,"saved":[{"slot":4,"slot_type":"end","tokens":40,"kv_from":8,"bytes":4096}],"dropped":0,"slots_used":2,"slots_max":8,"bytes_used":8192,"bytes_budget":1048576}},"service_tier":"default"} ### prefix_cache [stream] chunk: data: {"id":"chatcmpl-ID","object":"chat.completion.chunk","created":0,"model":"model-faker","choices":[{"index":0,"delta":{"role":"assistant","content":"Hel"},"finish_reason":null}]} -chunk: data: {"id":"chatcmpl-ID","object":"chat.completion.chunk","created":0,"model":"model-faker","choices":[{"index":0,"delta":{"role":"assistant","content":"lo"},"finish_reason":null}]} +chunk: data: {"id":"chatcmpl-ID","object":"chat.completion.chunk","created":0,"model":"model-faker","choices":[{"index":0,"delta":{"content":"lo"},"finish_reason":null}]} chunk: data: {"id":"chatcmpl-ID","object":"chat.completion.chunk","created":0,"model":"model-faker","system_fingerprint":"fp_ID","choices":[{"index":0,"delta":{"content":null},"finish_reason":"stop"}]} @@ -242,7 +242,7 @@ final: data: [DONE] ### prefix_cache [stream+usage] chunk: data: {"id":"chatcmpl-ID","object":"chat.completion.chunk","created":0,"model":"model-faker","choices":[{"index":0,"delta":{"role":"assistant","content":"Hel"},"finish_reason":null}],"usage":null} -chunk: data: {"id":"chatcmpl-ID","object":"chat.completion.chunk","created":0,"model":"model-faker","choices":[{"index":0,"delta":{"role":"assistant","content":"lo"},"finish_reason":null}],"usage":null} +chunk: data: {"id":"chatcmpl-ID","object":"chat.completion.chunk","created":0,"model":"model-faker","choices":[{"index":0,"delta":{"content":"lo"},"finish_reason":null}],"usage":null} chunk: data: {"id":"chatcmpl-ID","object":"chat.completion.chunk","created":0,"model":"model-faker","system_fingerprint":"fp_ID","choices":[{"index":0,"delta":{"content":null},"finish_reason":"stop"}],"usage":null} @@ -252,14 +252,14 @@ final: data: [DONE] ### logprobs [nstream] -response: {"id":"fastflowlm-chat-completion","object":"chat.completion","created":0,"model":"model-faker","choices":[{"index":0,"message":{"role":"assistant","reasoning_content":"hm","content":"Hello"},"logprobs":{"content":[{"token":"Hel","logprob":-1.0,"bytes":[72,101,108],"top_logprobs":[]},{"token":"lo","logprob":-1.25,"bytes":[108,111],"top_logprobs":[]}],"refusal":null},"finish_reason":"stop"}],"usage":{"prompt_tokens":40,"prompt_tokens_details":{"cached_tokens":8},"completion_tokens":5,"total_tokens":45,"kv_token_occupancy_rate_percentage":3.0029296875,"load_duration":0,"prefill_duration_ttft":0.25,"decoding_duration":0.5,"prefill_speed_tps":128.0,"decoding_speed_tps":10.0},"service_tier":"default"} +response: {"id":"chatcmpl-ID","object":"chat.completion","created":0,"model":"model-faker","choices":[{"index":0,"message":{"role":"assistant","reasoning_content":"hm","content":"Hello"},"logprobs":{"content":[{"token":"Hel","logprob":-1.0,"bytes":[72,101,108],"top_logprobs":[]},{"token":"lo","logprob":-1.25,"bytes":[108,111],"top_logprobs":[]}],"refusal":null},"finish_reason":"stop"}],"usage":{"prompt_tokens":40,"prompt_tokens_details":{"cached_tokens":8},"completion_tokens":5,"total_tokens":45,"kv_token_occupancy_rate_percentage":3.0029296875,"load_duration":0,"prefill_duration_ttft":0.25,"decoding_duration":0.5,"prefill_speed_tps":128.0,"decoding_speed_tps":10.0},"service_tier":"default"} ### logprobs [stream] chunk: data: {"id":"chatcmpl-ID","object":"chat.completion.chunk","created":0,"model":"model-faker","choices":[{"index":0,"delta":{"role":"assistant","reasoning_content":"hm"},"logprobs":null,"finish_reason":null}]} -chunk: data: {"id":"chatcmpl-ID","object":"chat.completion.chunk","created":0,"model":"model-faker","choices":[{"index":0,"delta":{"role":"assistant","content":"Hel"},"logprobs":{"content":[{"token":"Hel","logprob":-1.0,"bytes":[72,101,108],"top_logprobs":[]}],"refusal":null},"finish_reason":null}]} +chunk: data: {"id":"chatcmpl-ID","object":"chat.completion.chunk","created":0,"model":"model-faker","choices":[{"index":0,"delta":{"content":"Hel"},"logprobs":{"content":[{"token":"Hel","logprob":-1.0,"bytes":[72,101,108],"top_logprobs":[]}],"refusal":null},"finish_reason":null}]} -chunk: data: {"id":"chatcmpl-ID","object":"chat.completion.chunk","created":0,"model":"model-faker","choices":[{"index":0,"delta":{"role":"assistant","content":"lo"},"logprobs":{"content":[{"token":"lo","logprob":-1.25,"bytes":[108,111],"top_logprobs":[]}],"refusal":null},"finish_reason":null}]} +chunk: data: {"id":"chatcmpl-ID","object":"chat.completion.chunk","created":0,"model":"model-faker","choices":[{"index":0,"delta":{"content":"lo"},"logprobs":{"content":[{"token":"lo","logprob":-1.25,"bytes":[108,111],"top_logprobs":[]}],"refusal":null},"finish_reason":null}]} chunk: data: {"id":"chatcmpl-ID","object":"chat.completion.chunk","created":0,"model":"model-faker","system_fingerprint":"fp_ID","choices":[{"index":0,"delta":{"content":null},"logprobs":null,"finish_reason":"stop"}]} @@ -269,9 +269,9 @@ final: data: [DONE] ### logprobs [stream+usage] chunk: data: {"id":"chatcmpl-ID","object":"chat.completion.chunk","created":0,"model":"model-faker","choices":[{"index":0,"delta":{"role":"assistant","reasoning_content":"hm"},"logprobs":null,"finish_reason":null}],"usage":null} -chunk: data: {"id":"chatcmpl-ID","object":"chat.completion.chunk","created":0,"model":"model-faker","choices":[{"index":0,"delta":{"role":"assistant","content":"Hel"},"logprobs":{"content":[{"token":"Hel","logprob":-1.0,"bytes":[72,101,108],"top_logprobs":[]}],"refusal":null},"finish_reason":null}],"usage":null} +chunk: data: {"id":"chatcmpl-ID","object":"chat.completion.chunk","created":0,"model":"model-faker","choices":[{"index":0,"delta":{"content":"Hel"},"logprobs":{"content":[{"token":"Hel","logprob":-1.0,"bytes":[72,101,108],"top_logprobs":[]}],"refusal":null},"finish_reason":null}],"usage":null} -chunk: data: {"id":"chatcmpl-ID","object":"chat.completion.chunk","created":0,"model":"model-faker","choices":[{"index":0,"delta":{"role":"assistant","content":"lo"},"logprobs":{"content":[{"token":"lo","logprob":-1.25,"bytes":[108,111],"top_logprobs":[]}],"refusal":null},"finish_reason":null}],"usage":null} +chunk: data: {"id":"chatcmpl-ID","object":"chat.completion.chunk","created":0,"model":"model-faker","choices":[{"index":0,"delta":{"content":"lo"},"logprobs":{"content":[{"token":"lo","logprob":-1.25,"bytes":[108,111],"top_logprobs":[]}],"refusal":null},"finish_reason":null}],"usage":null} chunk: data: {"id":"chatcmpl-ID","object":"chat.completion.chunk","created":0,"model":"model-faker","system_fingerprint":"fp_ID","choices":[{"index":0,"delta":{"content":null},"logprobs":null,"finish_reason":"stop"}],"usage":null} @@ -281,7 +281,7 @@ final: data: [DONE] ### tools_not_offered [nstream] -response: {"id":"fastflowlm-chat-completion","object":"chat.completion","created":0,"model":"model-faker","choices":[{"index":0,"message":{"role":"assistant","content":"\n{\"name\": \"get_weather\", \"arguments\": {\"city\": \"Paris\"}}\n"},"logprobs":null,"finish_reason":"stop"}],"usage":{"prompt_tokens":40,"prompt_tokens_details":{"cached_tokens":8},"completion_tokens":1,"total_tokens":41,"kv_token_occupancy_rate_percentage":3.0029296875,"load_duration":0,"prefill_duration_ttft":0.25,"decoding_duration":0.5,"prefill_speed_tps":128.0,"decoding_speed_tps":2.0},"service_tier":"default"} +response: {"id":"chatcmpl-ID","object":"chat.completion","created":0,"model":"model-faker","choices":[{"index":0,"message":{"role":"assistant","content":"\n{\"name\": \"get_weather\", \"arguments\": {\"city\": \"Paris\"}}\n"},"logprobs":null,"finish_reason":"stop"}],"usage":{"prompt_tokens":40,"prompt_tokens_details":{"cached_tokens":8},"completion_tokens":1,"total_tokens":41,"kv_token_occupancy_rate_percentage":3.0029296875,"load_duration":0,"prefill_duration_ttft":0.25,"decoding_duration":0.5,"prefill_speed_tps":128.0,"decoding_speed_tps":2.0},"service_tier":"default"} ### tools_not_offered [stream] chunk: data: {"id":"chatcmpl-ID","object":"chat.completion.chunk","created":0,"model":"model-faker","choices":[{"index":0,"delta":{"role":"assistant","content":"\n{\"name\": \"get_weather\", \"arguments\": {\"city\": \"Paris\"}}\n"},"finish_reason":null}]} @@ -305,13 +305,17 @@ final: data: [DONE] response: null ### cancel_in_prefill [stream] -chunk: data: {"id":"chatcmpl-ID","object":"chat.completion.chunk","created":0,"model":"model-faker","system_fingerprint":"fp_ID","choices":[{"index":0,"delta":{"content":null},"finish_reason":"cancel"}]} +chunk: data: {"id":"chatcmpl-ID","object":"chat.completion.chunk","created":0,"model":"model-faker","choices":[{"index":0,"delta":{"role":"assistant","content":""},"finish_reason":null}]} + +chunk: data: {"id":"chatcmpl-ID","object":"chat.completion.chunk","created":0,"model":"model-faker","system_fingerprint":"fp_ID","choices":[{"index":0,"delta":{"content":null},"finish_reason":"stop"}]} final: data: [DONE] ### cancel_in_prefill [stream+usage] -chunk: data: {"id":"chatcmpl-ID","object":"chat.completion.chunk","created":0,"model":"model-faker","system_fingerprint":"fp_ID","choices":[{"index":0,"delta":{"content":null},"finish_reason":"cancel"}],"usage":null} +chunk: data: {"id":"chatcmpl-ID","object":"chat.completion.chunk","created":0,"model":"model-faker","choices":[{"index":0,"delta":{"role":"assistant","content":""},"finish_reason":null}],"usage":null} + +chunk: data: {"id":"chatcmpl-ID","object":"chat.completion.chunk","created":0,"model":"model-faker","system_fingerprint":"fp_ID","choices":[{"index":0,"delta":{"content":null},"finish_reason":"stop"}],"usage":null} chunk: data: {"id":"chatcmpl-ID","object":"chat.completion.chunk","created":0,"model":"model-faker","system_fingerprint":"fp_ID","choices":[],"usage":{"prompt_tokens":0,"prompt_tokens_details":{"cached_tokens":0},"completion_tokens":0,"total_tokens":0,"active_kv_tokens":123,"max_kv_token_capacity":4096,"kv_token_occupancy_rate_percentage":3.0029296875,"load_duration":0,"prefill_duration_ttft":0.0,"decoding_duration":0.0,"prefill_speed_tps":null,"decoding_speed_tps":null}} @@ -333,7 +337,7 @@ response: {"error":{"message":"the scripted model threw","type":"server_error"," ### generate_throw_mid [stream] chunk: data: {"id":"chatcmpl-ID","object":"chat.completion.chunk","created":0,"model":"model-faker","choices":[{"index":0,"delta":{"role":"assistant","content":"Hel"},"finish_reason":null}]} -chunk: data: {"id":"chatcmpl-ID","object":"chat.completion.chunk","created":0,"model":"model-faker","choices":[{"index":0,"delta":{"role":"assistant","content":"lo"},"finish_reason":null}]} +chunk: data: {"id":"chatcmpl-ID","object":"chat.completion.chunk","created":0,"model":"model-faker","choices":[{"index":0,"delta":{"content":"lo"},"finish_reason":null}]} chunk: data: {"error":{"message":"the scripted model threw","type":"server_error","param":null,"code":500}} @@ -343,7 +347,7 @@ final: data: [DONE] ### generate_throw_mid [stream+usage] chunk: data: {"id":"chatcmpl-ID","object":"chat.completion.chunk","created":0,"model":"model-faker","choices":[{"index":0,"delta":{"role":"assistant","content":"Hel"},"finish_reason":null}],"usage":null} -chunk: data: {"id":"chatcmpl-ID","object":"chat.completion.chunk","created":0,"model":"model-faker","choices":[{"index":0,"delta":{"role":"assistant","content":"lo"},"finish_reason":null}],"usage":null} +chunk: data: {"id":"chatcmpl-ID","object":"chat.completion.chunk","created":0,"model":"model-faker","choices":[{"index":0,"delta":{"content":"lo"},"finish_reason":null}],"usage":null} chunk: data: {"error":{"message":"the scripted model threw","type":"server_error","param":null,"code":500}} @@ -356,7 +360,7 @@ response: {"error":{"message":"the scripted model failed","type":"service_unavai ### generate_model_error_mid [stream] chunk: data: {"id":"chatcmpl-ID","object":"chat.completion.chunk","created":0,"model":"model-faker","choices":[{"index":0,"delta":{"role":"assistant","content":"Hel"},"finish_reason":null}]} -chunk: data: {"id":"chatcmpl-ID","object":"chat.completion.chunk","created":0,"model":"model-faker","choices":[{"index":0,"delta":{"role":"assistant","content":"lo"},"finish_reason":null}]} +chunk: data: {"id":"chatcmpl-ID","object":"chat.completion.chunk","created":0,"model":"model-faker","choices":[{"index":0,"delta":{"content":"lo"},"finish_reason":null}]} chunk: data: {"error":{"message":"the scripted model failed","type":"service_unavailable_error","param":null,"code":503,"session_cleared":true}} @@ -366,7 +370,7 @@ final: data: [DONE] ### generate_model_error_mid [stream+usage] chunk: data: {"id":"chatcmpl-ID","object":"chat.completion.chunk","created":0,"model":"model-faker","choices":[{"index":0,"delta":{"role":"assistant","content":"Hel"},"finish_reason":null}],"usage":null} -chunk: data: {"id":"chatcmpl-ID","object":"chat.completion.chunk","created":0,"model":"model-faker","choices":[{"index":0,"delta":{"role":"assistant","content":"lo"},"finish_reason":null}],"usage":null} +chunk: data: {"id":"chatcmpl-ID","object":"chat.completion.chunk","created":0,"model":"model-faker","choices":[{"index":0,"delta":{"content":"lo"},"finish_reason":null}],"usage":null} chunk: data: {"error":{"message":"the scripted model failed","type":"service_unavailable_error","param":null,"code":503,"session_cleared":true}} diff --git a/src/test/chat_protocols/test_chat_protocols.cpp b/src/test/chat_protocols/test_chat_protocols.cpp index fbc8fc5fa..e8043374e 100644 --- a/src/test/chat_protocols/test_chat_protocols.cpp +++ b/src/test/chat_protocols/test_chat_protocols.cpp @@ -8,15 +8,18 @@ #include "chat_core.hpp" #include "protocol_openai_chat.hpp" #include "protocol_responses.hpp" +#include "streaming_ostream_openai.hpp" #include #include #include #include #include +#include #include #include #include +#include #include #include @@ -116,13 +119,27 @@ std::vector cases() { } /// \brief One case through the sink, the way RestHandler::run_chat_turn drives it; every send becomes a line -std::string run(const case_t& c, bool stream, bool include_usage) { +std::string run(const case_t& c, bool stream, bool include_usage, std::set& ids, int& failures) { std::ostringstream out; + std::string response_id; + auto check_id = [&](const json& response) { + if (!response.contains("id")) return; // errors and cancelled non-streaming prefill + static const std::regex shape("chatcmpl-[0-9a-f]{24}"); + const auto id = response.at("id").get(); + if (!std::regex_match(id, shape) || + (response_id.empty() ? !ids.insert(id).second : id != response_id)) { + std::printf(" FAIL %s: invalid, reused or inconsistent response id: %s\n", c.name.c_str(), id.c_str()); + ++failures; + } + response_id = id; + }; auto send_response = [&](const json& response) { + check_id(response); out << "response: " << normalize(response.dump()) << "\n"; }; auto send_streaming_response = [&](const json& data, bool is_final) { const std::string text = data.get(); + if (!is_final) check_id(json::parse(text.substr(6))); out << (is_final ? "final: " : "chunk: ") << normalize(text); if (text.empty() || text.back() != '\n') out << "\n"; }; @@ -269,6 +286,7 @@ int error_routing() { }; const chat_error first{500, "server_error", "first", "", std::nullopt}; const chat_error second{500, "server_error", "second", "", std::nullopt}; + const std::string failed_body = R"({"error":{"message":"Generation failed","type":"server_error","param":null,"code":500}})"; const std::string first_event = "chunk data: " + openai_error_json(first).dump() + "\nfinal data: [DONE]\n"; const std::string second_object = "response " + openai_error_json(second).dump() + "\n"; chat_msg_delta hi; @@ -287,13 +305,42 @@ int error_routing() { sink.on_error(first); failures += check("error before any chunk", out, "response " + openai_error_json(first).dump() + "\n"); } + // An engine may report a failed turn without throwing. + { + chat_turn_end aborted = end; + aborted.finish = chat_finish::FAILED; + for (const bool stream : {false, true}) { + out.clear(); + openai_chat_sink sink(send_response, send_streaming_response, true); + sink.on_begin({"m", stream}); + sink.on_end(aborted); + failures += check("failed turn before any chunk", out, "response " + failed_body + "\n"); + } + out.clear(); + openai_chat_sink sink(send_response, send_streaming_response, true); + sink.on_begin({"m", true}); + sink.on_delta(hi); + const size_t streamed = out.size(); + sink.on_end(aborted); + failures += check("failed turn after a chunk", out.substr(streamed), + "chunk data: " + failed_body + "\nfinal data: [DONE]\n"); + } // the stream was ended and cleaning up failed: one more event and [DONE], as before { out.clear(); openai_chat_sink sink(send_response, send_streaming_response, false); sink.on_begin({"m", true}); - sink.on_start({}); + // The empty opener carries no token logprobs, even if requested. + chat_turn_start start; + start.content_logprobs = [](const std::string&) -> json { + throw std::runtime_error("empty opener requested token logprobs"); + }; + sink.on_start(start); sink.on_end(end); + const size_t first_line = out.find('\n'); + const json opener = json::parse(out.substr(12, first_line - 12))["choices"][0]; + failures += check("empty stream opener", opener.dump(), + R"({"index":0,"delta":{"role":"assistant","content":""},"logprobs":null,"finish_reason":null})"); const size_t ended = out.size(); sink.on_error(first); failures += check("error after the stream ended", out.substr(ended), first_event); @@ -330,6 +377,38 @@ int error_routing() { return failures; } +int text_completion_stream() { + std::string wire; + std::vector chunks; + streaming_ostream_openai stream("m", [&](const std::string& s, bool final) { + if (final) wire = s; + else chunks.push_back(json::parse(s.substr(6))); + }, true); + stream << "Hi\xE2" << std::flush; // the last character never completes + const json usage = {{"prompt_tokens", 3}, {"completion_tokens", 1}, {"total_tokens", 4}}; + stream.finalize("length", usage); + if (chunks.size() != 3) return check("text completion chunk count", std::to_string(chunks.size()), "3"); + int failures = 0; + const auto id = chunks[0].at("id").get(); + if (!std::regex_match(id, std::regex("cmpl-[0-9a-f]{24}"))) { + std::printf(" FAIL text completion id: %s\n", id.c_str()); + ++failures; + } + for (const auto& chunk : chunks) { + failures += check("text completion stream id", chunk.at("id").get(), id); + failures += check("text completion object", chunk.at("object").get(), "text_completion"); + } + failures += check("text completion content usage", chunks[0].at("usage").dump(), "null"); + failures += check("text completion finish usage", chunks[1].at("usage").dump(), "null"); + failures += check("text completion content", chunks[0]["choices"][0]["text"].dump(), R"("Hi")"); + failures += check("text completion finish choice", chunks[1]["choices"][0].dump(), + R"({"text":"","index":0,"logprobs":null,"finish_reason":"length"})"); + failures += check("text completion usage choices", chunks[2]["choices"].dump(), "[]"); + failures += check("text completion usage", chunks[2]["usage"].dump(), usage.dump()); + failures += check("text completion terminator", wire, "data: [DONE]\n\n"); + return failures; +} + /// \brief The flush hook sees each flush's bytes, the incomplete ones too, before the parser does int flush_hook() { struct log_sink : chat_sink { @@ -371,10 +450,13 @@ int main(int argc, char* argv[]) { try { const auto golden = blocks(read_file(golden_path)); std::vector> actual; + std::set ids; for (const case_t& c : cases()) { - actual.push_back({"### " + c.name + " [nstream]", "### " + c.name + " [nstream]\n" + run(c, false, false) + "\n"}); - actual.push_back({"### " + c.name + " [stream]", "### " + c.name + " [stream]\n" + run(c, true, false) + "\n"}); - actual.push_back({"### " + c.name + " [stream+usage]", "### " + c.name + " [stream+usage]\n" + run(c, true, true) + "\n"}); + for (const auto& [mode, stream, include_usage] : + {std::tuple{"nstream", false, false}, std::tuple{"stream", true, false}, std::tuple{"stream+usage", true, true}}) { + const std::string name = "### " + c.name + " [" + mode + "]"; + actual.push_back({name, name + "\n" + run(c, stream, include_usage, ids, failures) + "\n"}); + } } if (golden.size() != actual.size()) { std::printf(" FAIL: the recording has %zu blocks, the test wrote %zu\n", golden.size(), actual.size()); @@ -414,6 +496,7 @@ int main(int argc, char* argv[]) { } } failures += error_routing(); + failures += text_completion_stream(); failures += flush_hook(); // Feed the same ordered text and tool fragments to the streaming sink, then diff --git a/src/test/openai_api_test/flm_api.py b/src/test/openai_api_test/flm_api.py index 30f32213e..7f9e00d3e 100644 --- a/src/test/openai_api_test/flm_api.py +++ b/src/test/openai_api_test/flm_api.py @@ -348,6 +348,9 @@ def check_stream_contract(s: Stream, *, include_usage: bool) -> Folded: expect(len(s.chunks) > 0, "stream has no chunks") ids = {c.get("id") for c in s.chunks} expect(len(ids) == 1, f"chunks carry different ids: {ids}") + response_id = s.chunks[0].get("id") + expect(isinstance(response_id, str) and response_id.startswith("chatcmpl-"), + f"expected a chatcmpl- id, got {response_id!r}") seen_tool_ids: dict[int, str] = {} finish_chunks = 0 for n, chunk in enumerate(s.chunks): @@ -365,11 +368,17 @@ def check_stream_contract(s: Stream, *, include_usage: bool) -> Folded: continue choice = choices[0] delta = choice.get("delta") or {} + if n == 0: + expect(delta.get("role") == "assistant", f"first chunk has no assistant role: {delta}") + else: + expect("role" not in delta, f"chunk {n} repeats role: {delta}") if choice.get("finish_reason") is not None: finish_chunks += 1 continue parts = [k for k in ("reasoning_content", "content", "tool_calls") if delta.get(k)] - expect(len(parts) == 1, f"chunk {n}: a delta must carry exactly one part, got {parts}: {delta}") + empty_opener = n == 0 and delta == {"role": "assistant", "content": ""} + expect(len(parts) == 1 or empty_opener, + f"chunk {n}: a delta must carry exactly one part, got {parts}: {delta}") for tc in delta.get("tool_calls") or []: index = tc.get("index") expect(isinstance(index, int), f"chunk {n}: tool call delta without an index") @@ -383,6 +392,8 @@ def check_stream_contract(s: Stream, *, include_usage: bool) -> Folded: f"chunk {n}: a later delta of call {index} repeats its id or name: {tc}") expect(finish_chunks == 1, f"expected one chunk with a finish_reason, got {finish_chunks}") folded = fold_stream(s.chunks) + expect(folded.finish_reason in ("stop", "length", "tool_calls", "content_filter"), + f"unexpected streamed finish_reason {folded.finish_reason!r}") assert_no_markers(folded.content, "streamed content") assert_no_markers(folded.reasoning, "streamed reasoning_content") if include_usage: diff --git a/src/test/openai_api_test/test_response_shape.py b/src/test/openai_api_test/test_response_shape.py index 687a4d3f0..d7413cdf2 100644 --- a/src/test/openai_api_test/test_response_shape.py +++ b/src/test/openai_api_test/test_response_shape.py @@ -1,12 +1,12 @@ #!/usr/bin/env python3 -"""Response shape of /v1/chat/completions, streamed and not. +"""Response shape of /v1/chat/completions and /v1/completions, streamed and not. Checks the contract every client relies on, whatever the model: * a non-streaming message has the OpenAI fields, no raw template markup, and a finish_reason that agrees with its tool calls; -* every stream chunk carries exactly one kind of delta, one stream id, - one finish chunk, then ``data: [DONE]``; +* only the first chat stream chunk carries the role. The stream has one id + and one finish chunk, then ``data: [DONE]``; * usage is only streamed when ``stream_options.include_usage`` asks, as one last chunk with no choices; * streaming and non-streaming produce the same message: the server @@ -39,6 +39,9 @@ def nonstream_message(api: Api) -> None: resp = api.post(api.body(user(PROMPT), max_tokens=64)) expect(resp.status == 200, f"HTTP {resp.status}: {resp.error_message()}") expect(resp.body.get("object") == "chat.completion", f"object is {resp.body.get('object')!r}") + response_id = resp.body.get("id") + expect(isinstance(response_id, str) and response_id.startswith("chatcmpl-"), + f"expected a chatcmpl- id, got {response_id!r}") choice = resp.body["choices"][0] msg = flm_api.check_message_contract(choice) expect(msg["content"].strip() != "", "content is empty") @@ -81,6 +84,40 @@ def length_finish(api: Api) -> None: expect(folded.finish_reason == "length", f"stream finish_reason is {folded.finish_reason!r}") +@case +def text_completion_shape(api: Api) -> None: + """Legacy text completions use cmpl IDs and full choices, including the finish chunk.""" + url = api.completions_url() + body = api.body([], max_tokens=16) + del body["messages"] + body["prompt"] = "The capital of France is" + plain = api.post(body, url=url) + expect(plain.status == 200, f"HTTP {plain.status}: {plain.error_message()}") + expect(plain.body.get("object") == "text_completion", f"not a text completion: {plain.body}") + plain_id = plain.body.get("id") + expect(isinstance(plain_id, str) and plain_id.startswith("cmpl-"), f"plain id is {plain_id!r}") + plain_choice = plain.body["choices"][0] + expect(plain_choice["finish_reason"] in ("stop", "length"), f"unexpected choice: {plain_choice}") + + streamed = api.stream(dict(body, stream_options={"include_usage": True}), url=url) + expect(streamed.status == 200 and streamed.done and len(streamed.chunks) >= 2, + f"expected a completed text stream with usage: {streamed}") + stream_id = streamed.chunks[0].get("id") + expect(isinstance(stream_id, str) and stream_id.startswith("cmpl-"), f"stream id is {stream_id!r}") + expect(stream_id != plain_id, f"text completions reused id {plain_id!r}") + for chunk in streamed.chunks: + expect(chunk.get("object") == "text_completion" and chunk.get("id") == stream_id, + f"unexpected envelope: {chunk}") + finish = streamed.chunks[-2]["choices"][0] + expect(finish.get("text") == "" and finish.get("index") == 0 + and "logprobs" in finish and finish["logprobs"] is None + and finish.get("finish_reason") in ("stop", "length") and "delta" not in finish, + f"incomplete finish choice: {finish}") + usage = streamed.chunks[-1] + expect(usage["choices"] == [] and isinstance(usage.get("usage"), dict), + f"expected a final choice-less usage chunk: {usage}") + + @case def stream_matches_nonstream(api: Api) -> None: """Greedy streaming and non-streaming answers are the same text."""