Skip to content
Merged
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: 3 additions & 1 deletion include/ai/types/enums.h
Original file line number Diff line number Diff line change
Expand Up @@ -24,7 +24,9 @@ enum StreamEventType {
kStreamEventTypeStepFinish,
kStreamEventTypeFinish,
kStreamEventTypeError,
/// A fragment of the model's reasoning (thinking) text, in `reasoning_delta`.
/// It can be empty when the provider does not return the reasoning itself.
kStreamEventTypeReasoningDelta
};

} // namespace ai
} // namespace ai
11 changes: 11 additions & 0 deletions include/ai/types/stream_event.h
Original file line number Diff line number Diff line change
Expand Up @@ -29,8 +29,18 @@ struct StreamEvent {
explicit StreamEvent(ToolCall call)
: type(kStreamEventTypeToolCall), tool_call(std::move(call)) {}

static StreamEvent reasoning(std::string reasoning_text) {
StreamEvent event(kStreamEventTypeReasoningDelta);
event.reasoning_delta = std::move(reasoning_text);
return event;
}

bool is_text_delta() const { return type == kStreamEventTypeTextDelta; }

bool is_reasoning_delta() const {
return type == kStreamEventTypeReasoningDelta;
}

bool is_error() const { return type == kStreamEventTypeError; }

bool is_tool_call() const { return type == kStreamEventTypeToolCall; }
Expand All @@ -39,6 +49,7 @@ struct StreamEvent {

StreamEventType type;
std::string text_delta;
std::string reasoning_delta;
std::optional<std::string> error;
std::optional<Usage> usage;
std::optional<FinishReason> finish_reason;
Expand Down
8 changes: 8 additions & 0 deletions src/providers/anthropic/anthropic_stream.cpp
Original file line number Diff line number Diff line change
Expand Up @@ -119,6 +119,14 @@ void AnthropicStreamImpl::process_sse_event(const std::string& data) {
push_event(StreamEvent(text));

ai::logger::log_debug("Enqueued text delta: '{}'", text);
} else if (json_event.contains("delta") &&
json_event["delta"].is_object() &&
string_or_empty(json_event["delta"], "type") ==
"thinking_delta") {
// Empty unless the request asks for summarized thinking; recent
// models omit the thinking text by default.
push_event(StreamEvent::reasoning(
string_or_empty(json_event["delta"], "thinking")));
} else if (json_event.contains("delta") &&
json_event["delta"].is_object() &&
string_or_empty(json_event["delta"], "type") ==
Expand Down
87 changes: 46 additions & 41 deletions src/providers/http_sse_stream.cpp
Original file line number Diff line number Diff line change
Expand Up @@ -2,14 +2,8 @@

#include "ai/logger.h"

#include <chrono>
#include <utility>

namespace {
constexpr auto kEventTimeout = static_cast<std::chrono::seconds>(30);
constexpr auto kSleepInterval = std::chrono::milliseconds(1);
} // namespace

namespace ai {
namespace providers {
namespace streaming {
Expand Down Expand Up @@ -37,7 +31,10 @@ void HttpSseStream::start_stream(const std::string& url,

// Reset state for new stream
should_stop_ = false;
is_complete_ = false;
{
std::lock_guard<std::mutex> queue_lock(queue_mutex_);
is_complete_ = false;
}
finish_event_pushed_ = false;
stream_errored_ = false;
line_buffer_.clear();
Expand All @@ -54,37 +51,30 @@ void HttpSseStream::start_stream(const std::string& url,
}

StreamEvent HttpSseStream::get_next_event() {
StreamEvent event("");
auto start_time = std::chrono::steady_clock::now();

while (!event_queue_.try_dequeue(event)) {
if (is_complete_ && event_queue_.size_approx() == 0) {
// Stream is complete and queue is empty
ai::logger::log_debug(
"Stream complete and queue empty, returning empty event");
return StreamEvent("");
}

// Check for timeout
if (std::chrono::steady_clock::now() - start_time > kEventTimeout) {
ai::logger::log_error(
"Timeout waiting for next stream event after {} seconds",
kEventTimeout.count());
return StreamEvent(kStreamEventTypeError,
Comment thread
alexey-milovidov marked this conversation as resolved.
Resolved
"Timeout waiting for next event");
}

std::this_thread::sleep_for(kSleepInterval);
// No timeout of its own here: the gaps between events can be long (e.g.
// while a model reasons without streaming its reasoning), and a stalled
// connection makes the stream thread push an error event and complete once
// its HTTP read timeout expires.
std::unique_lock<std::mutex> lock(queue_mutex_);
queue_cv_.wait(lock,
[this] { return !event_queue_.empty() || is_complete_; });

if (event_queue_.empty()) {
ai::logger::log_debug(
"Stream complete and queue empty, returning empty event");
return StreamEvent("");
}

StreamEvent event = std::move(event_queue_.front());
event_queue_.pop_front();
ai::logger::log_debug("Dequeued event type: {}",
static_cast<int>(event.type));
return event;
}

bool HttpSseStream::has_more_events() const {
// No locks needed - these are atomic operations
return event_queue_.size_approx() > 0 || !is_complete_;
std::lock_guard<std::mutex> lock(queue_mutex_);
return !event_queue_.empty() || !is_complete_;
}

void HttpSseStream::stop_stream() {
Expand Down Expand Up @@ -216,35 +206,50 @@ void HttpSseStream::consume_chunk(const char* data, std::size_t length) {
}

void HttpSseStream::push_event(StreamEvent event) {
event_queue_.enqueue(std::move(event));
{
std::lock_guard<std::mutex> lock(queue_mutex_);
event_queue_.push_back(std::move(event));
}
queue_cv_.notify_one();
}

StreamEvent HttpSseStream::create_error_event(const std::string& message) {
ai::logger::log_debug("Creating error event: {}", message);
return StreamEvent(kStreamEventTypeError, message);
}

void HttpSseStream::push_finish_event_if_needed() {
std::optional<StreamEvent> HttpSseStream::take_finish_event() {
bool expected = false;
if (!finish_event_pushed_.compare_exchange_strong(expected, true)) {
ai::logger::log_debug("Finish event already pushed, skipping");
return;
return std::nullopt;
}

ai::logger::log_debug("Pushing finish event to queue");
if (stream_errored_) {
// Do not stamp a failed stream with a clean finish reason or usage.
push_event(StreamEvent(kStreamEventTypeFinish, kFinishReasonError));
} else if (usage_) {
push_event(StreamEvent(kStreamEventTypeFinish, *usage_, finish_reason_));
} else {
push_event(StreamEvent(kStreamEventTypeFinish, finish_reason_));
return StreamEvent(kStreamEventTypeFinish, kFinishReasonError);
}
if (usage_) {
return StreamEvent(kStreamEventTypeFinish, *usage_, finish_reason_);
}
return StreamEvent(kStreamEventTypeFinish, finish_reason_);
}

void HttpSseStream::mark_complete() {
push_finish_event_if_needed();
is_complete_ = true; // Atomic write
auto finish_event = take_finish_event();
{
// Queue the terminal event and mark the stream complete atomically, so a
// consumer that has dequeued the finish event never sees an incomplete
// stream with an empty queue (and waits for, then yields, a spurious
// event after the finish).
std::lock_guard<std::mutex> lock(queue_mutex_);
if (finish_event) {
ai::logger::log_debug("Pushing finish event to queue");
event_queue_.push_back(std::move(*finish_event));
}
is_complete_ = true;
}
queue_cv_.notify_all();
}

void HttpSseStream::flush_all_pending_tool_calls() {
Expand Down
20 changes: 14 additions & 6 deletions src/providers/http_sse_stream.h
Original file line number Diff line number Diff line change
Expand Up @@ -4,8 +4,9 @@
#include "providers/stream_utils.h"

#include <atomic>
#include <concurrentqueue.h>
#include <condition_variable>
#include <cstddef>
#include <deque>
#include <httplib.h>
#include <map>
#include <mutex>
Expand Down Expand Up @@ -53,7 +54,8 @@ class HttpSseStream : public internal::StreamResultImpl {
process_sse_line(line);
}
std::size_t queued_event_count_for_testing() const {
return event_queue_.size_approx();
std::lock_guard<std::mutex> lock(queue_mutex_);
return event_queue_.size();
}
#endif

Expand All @@ -79,8 +81,9 @@ class HttpSseStream : public internal::StreamResultImpl {

void push_event(StreamEvent event);
static StreamEvent create_error_event(const std::string& message);
/// Push the terminal finish event (at most once per stream).
void push_finish_event_if_needed();
/// The terminal finish event, or nullopt if it was already taken (it is
/// emitted at most once per stream).
std::optional<StreamEvent> take_finish_event();
/// Push the terminal finish event if still needed and mark the stream
/// complete so consumers stop waiting for events.
void mark_complete();
Expand All @@ -106,11 +109,16 @@ class HttpSseStream : public internal::StreamResultImpl {
void consume_chunk(const char* data, std::size_t length);

Options options_;
moodycamel::ConcurrentQueue<StreamEvent> event_queue_;
// Events produced by the stream thread. The consumer blocks on
// `queue_cv_` until an event arrives or the stream completes; a stalled
// connection is bounded by the HTTP read timeout of the stream thread.
mutable std::mutex queue_mutex_;
std::condition_variable queue_cv_;
std::deque<StreamEvent> event_queue_;
std::thread stream_thread_;
std::mutex thread_mutex_;
std::string line_buffer_;
std::atomic<bool> is_complete_{false};
bool is_complete_{false}; // Guarded by queue_mutex_.
std::atomic<bool> should_stop_{false};
std::atomic<bool> finish_event_pushed_{false};
std::atomic<bool> stream_errored_{false};
Expand Down
16 changes: 7 additions & 9 deletions src/providers/openai/openai_stream.cpp
Original file line number Diff line number Diff line change
Expand Up @@ -43,15 +43,13 @@ void OpenAIStreamImpl::process_sse_line(std::string_view line) {
push_event(StreamEvent(content));
}

if (delta.contains("reasoning_content") &&
!delta["reasoning_content"].is_null()) {
std::string content = delta["reasoning_content"].get<std::string>();
ai::logger::log_debug("Received reasoning_content chunk - length: {}",
content.length());
// TODO: currently not passing content, needs revamping of StreamEvent
// constructor
push_event(
StreamEvent(StreamEventType::kStreamEventTypeReasoningDelta));
// OpenAI-compatible servers stream reasoning in a field of their own:
// `reasoning_content` (DeepSeek, vLLM, SGLang) or `reasoning`
// (OpenRouter, Ollama).
for (const char* key : {"reasoning_content", "reasoning"}) {
if (delta.contains(key) && delta[key].is_string()) {
push_event(StreamEvent::reasoning(delta[key].get<std::string>()));
}
}

if (delta.contains("tool_calls") && delta["tool_calls"].is_array()) {
Expand Down
25 changes: 25 additions & 0 deletions tests/unit/anthropic_stream_test.cpp
Original file line number Diff line number Diff line change
Expand Up @@ -450,6 +450,31 @@ TEST_F(AnthropicStreamEventTypesTest, MessageStopEvent) {
EXPECT_THAT(event_data, testing::HasSubstr("message_stop"));
}

TEST_F(AnthropicStreamEventTest, EmitsReasoningDeltasForThinking) {
anthropic::AnthropicStreamImpl stream;
stream.process_sse_chunk_for_testing(
R"(data: {"type":"content_block_start","index":0,"content_block":{"type":"thinking","thinking":""}}

data: {"type":"content_block_delta","index":0,"delta":{"type":"thinking_delta","thinking":"Weighing options"}}

data: {"type":"content_block_delta","index":0,"delta":{"type":"signature_delta","signature":"abc"}}

data: {"type":"content_block_stop","index":0}

data: {"type":"content_block_delta","index":1,"delta":{"type":"text_delta","text":"Answer"}}

)");

auto reasoning = stream.get_next_event();
ASSERT_TRUE(reasoning.is_reasoning_delta());
EXPECT_EQ(reasoning.reasoning_delta, "Weighing options");

auto text = stream.get_next_event();
ASSERT_TRUE(text.is_text_delta());
EXPECT_EQ(text.text_delta, "Answer");
EXPECT_EQ(stream.queued_event_count_for_testing(), 0);
}

TEST_F(AnthropicStreamEventTest, MapsRefusalToContentFilter) {
anthropic::AnthropicStreamImpl stream;
stream.process_sse_chunk_for_testing(
Expand Down
53 changes: 53 additions & 0 deletions tests/unit/openai_stream_test.cpp
Original file line number Diff line number Diff line change
Expand Up @@ -6,6 +6,8 @@
#include "ai/types/stream_options.h"
#include "ai/types/stream_result.h"

#include <thread>

#include <gmock/gmock.h>
#include <gtest/gtest.h>

Expand Down Expand Up @@ -129,6 +131,57 @@ TEST_F(StreamEventTest, EmitsOneFinishWithTerminalUsage) {
EXPECT_EQ(finish_event.usage->total_tokens, 7);
}

TEST_F(StreamEventTest, EmitsReasoningDeltas) {
openai::OpenAIStreamImpl stream;
stream.process_sse_line_for_testing(
R"(data: {"choices":[{"delta":{"reasoning_content":"Let me think"}}]})");
stream.process_sse_line_for_testing(
R"(data: {"choices":[{"delta":{"reasoning":" about it"}}]})");
stream.process_sse_line_for_testing(
R"(data: {"choices":[{"delta":{"content":"Done","reasoning_content":null}}]})");

auto first = stream.get_next_event();
ASSERT_TRUE(first.is_reasoning_delta());
EXPECT_EQ(first.reasoning_delta, "Let me think");
EXPECT_TRUE(first.text_delta.empty());

auto second = stream.get_next_event();
ASSERT_TRUE(second.is_reasoning_delta());
EXPECT_EQ(second.reasoning_delta, " about it");

auto text = stream.get_next_event();
ASSERT_TRUE(text.is_text_delta());
EXPECT_EQ(text.text_delta, "Done");
EXPECT_EQ(stream.queued_event_count_for_testing(), 0);
}

TEST_F(StreamEventTest, ConsumerWaitsForEventFromAnotherThread) {
openai::OpenAIStreamImpl stream;
std::thread producer([&stream] {
stream.process_sse_line_for_testing(
R"(data: {"choices":[{"delta":{"content":"late"}}]})");
});

// Blocks until the producer pushes the event; no polling, no timeout.
auto event = stream.get_next_event();
producer.join();
ASSERT_TRUE(event.is_text_delta());
EXPECT_EQ(event.text_delta, "late");
}

TEST_F(StreamEventTest, NoEventsAfterFinish) {
openai::OpenAIStreamImpl stream;
stream.process_sse_line_for_testing(
R"(data: {"choices":[{"delta":{"content":"Hi"},"finish_reason":"stop"}]})");
stream.process_sse_line_for_testing("data: [DONE]");

EXPECT_TRUE(stream.get_next_event().is_text_delta());
ASSERT_TRUE(stream.get_next_event().is_finish());
// The finish event is queued together with the completion flag, so the
// consumer stops here instead of waiting for (and yielding) another event.
EXPECT_FALSE(stream.has_more_events());
}

// Mock Stream Implementation Tests
class MockStreamImpl {
public:
Expand Down
Loading