diff --git a/include/ai/types/enums.h b/include/ai/types/enums.h index 2fa0219..66ad3e7 100644 --- a/include/ai/types/enums.h +++ b/include/ai/types/enums.h @@ -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 \ No newline at end of file diff --git a/include/ai/types/stream_event.h b/include/ai/types/stream_event.h index 8646af3..444f8e7 100644 --- a/include/ai/types/stream_event.h +++ b/include/ai/types/stream_event.h @@ -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; } @@ -39,6 +49,7 @@ struct StreamEvent { StreamEventType type; std::string text_delta; + std::string reasoning_delta; std::optional error; std::optional usage; std::optional finish_reason; diff --git a/src/providers/anthropic/anthropic_stream.cpp b/src/providers/anthropic/anthropic_stream.cpp index 14078bf..9295658 100644 --- a/src/providers/anthropic/anthropic_stream.cpp +++ b/src/providers/anthropic/anthropic_stream.cpp @@ -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") == diff --git a/src/providers/http_sse_stream.cpp b/src/providers/http_sse_stream.cpp index 292ef80..c4b8e89 100644 --- a/src/providers/http_sse_stream.cpp +++ b/src/providers/http_sse_stream.cpp @@ -2,14 +2,8 @@ #include "ai/logger.h" -#include #include -namespace { -constexpr auto kEventTimeout = static_cast(30); -constexpr auto kSleepInterval = std::chrono::milliseconds(1); -} // namespace - namespace ai { namespace providers { namespace streaming { @@ -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 queue_lock(queue_mutex_); + is_complete_ = false; + } finish_event_pushed_ = false; stream_errored_ = false; line_buffer_.clear(); @@ -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, - "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 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(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 lock(queue_mutex_); + return !event_queue_.empty() || !is_complete_; } void HttpSseStream::stop_stream() { @@ -216,7 +206,11 @@ 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 lock(queue_mutex_); + event_queue_.push_back(std::move(event)); + } + queue_cv_.notify_one(); } StreamEvent HttpSseStream::create_error_event(const std::string& message) { @@ -224,27 +218,38 @@ StreamEvent HttpSseStream::create_error_event(const std::string& message) { return StreamEvent(kStreamEventTypeError, message); } -void HttpSseStream::push_finish_event_if_needed() { +std::optional 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 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() { diff --git a/src/providers/http_sse_stream.h b/src/providers/http_sse_stream.h index 6b9bb7d..62876a5 100644 --- a/src/providers/http_sse_stream.h +++ b/src/providers/http_sse_stream.h @@ -4,8 +4,9 @@ #include "providers/stream_utils.h" #include -#include +#include #include +#include #include #include #include @@ -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 lock(queue_mutex_); + return event_queue_.size(); } #endif @@ -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 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(); @@ -106,11 +109,16 @@ class HttpSseStream : public internal::StreamResultImpl { void consume_chunk(const char* data, std::size_t length); Options options_; - moodycamel::ConcurrentQueue 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 event_queue_; std::thread stream_thread_; std::mutex thread_mutex_; std::string line_buffer_; - std::atomic is_complete_{false}; + bool is_complete_{false}; // Guarded by queue_mutex_. std::atomic should_stop_{false}; std::atomic finish_event_pushed_{false}; std::atomic stream_errored_{false}; diff --git a/src/providers/openai/openai_stream.cpp b/src/providers/openai/openai_stream.cpp index 105e9c8..3d6d8ea 100644 --- a/src/providers/openai/openai_stream.cpp +++ b/src/providers/openai/openai_stream.cpp @@ -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(); - 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())); + } } if (delta.contains("tool_calls") && delta["tool_calls"].is_array()) { diff --git a/tests/unit/anthropic_stream_test.cpp b/tests/unit/anthropic_stream_test.cpp index 747f78c..567eed4 100644 --- a/tests/unit/anthropic_stream_test.cpp +++ b/tests/unit/anthropic_stream_test.cpp @@ -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( diff --git a/tests/unit/openai_stream_test.cpp b/tests/unit/openai_stream_test.cpp index c16ca16..bda6f55 100644 --- a/tests/unit/openai_stream_test.cpp +++ b/tests/unit/openai_stream_test.cpp @@ -6,6 +6,8 @@ #include "ai/types/stream_options.h" #include "ai/types/stream_result.h" +#include + #include #include @@ -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: