Skip to content
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
4 changes: 2 additions & 2 deletions .github/script/npu_test/suites/serving.py
Original file line number Diff line number Diff line change
Expand Up @@ -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")
Expand Down
15 changes: 8 additions & 7 deletions docs/docs/instructions/server/reasoning_and_tools.md
Original file line number Diff line number Diff line change
Expand Up @@ -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 |
|---|---|
Expand All @@ -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]
```
Expand Down
9 changes: 9 additions & 0 deletions docs/docs/instructions/server/request_parameters.md
Original file line number Diff line number Diff line change
Expand Up @@ -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)
Expand Down Expand Up @@ -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`)
Expand Down
23 changes: 23 additions & 0 deletions src/server/openai_response_id.hpp
Original file line number Diff line number Diff line change
@@ -0,0 +1,23 @@
/// \file openai_response_id.hpp
/// \brief Opaque hexadecimal identifiers for OpenAI responses
#pragma once

#include <cstddef>
#include <random>
#include <string>

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<unsigned int> 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
91 changes: 34 additions & 57 deletions src/server/protocol_openai_chat.hpp
Original file line number Diff line number Diff line change
Expand Up @@ -10,13 +10,12 @@
#include <ctime>
#include <functional>
#include <iostream>
#include <random>
#include <sstream>
#include <string>
#include <utility>
#include <nlohmann/json.hpp>
#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
Expand All @@ -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
Expand All @@ -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);
}
}

Expand All @@ -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()) {
Expand All @@ -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);
}
Expand Down Expand Up @@ -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<long>(std::chrono::duration_cast<std::chrono::seconds>(
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", {
Expand Down Expand Up @@ -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<long long>(std::time(nullptr))},
{"model", model_name},
Expand Down
Loading
Loading