Prevent callback return value from halting stream

The delta branch in decode_responses_event now explicitly returns
:ok after invoking the callback, so a callback returning {:error, _}
cannot be mistaken for a stream-level error by decode_events.
This commit is contained in:
Claudio Ortolina
2026-04-13 13:14:33 +01:00
parent 846b92fd4c
commit bdc1cd3992
2 changed files with 25 additions and 0 deletions
+1
View File
@@ -125,6 +125,7 @@ defmodule OpenAI.API do
case JSON.decode!(json) do case JSON.decode!(json) do
%{"type" => "response.output_text.delta", "delta" => delta} -> %{"type" => "response.output_text.delta", "delta" => delta} ->
cb.(delta) cb.(delta)
:ok
%{"type" => "error", "error" => %{"message" => message}} -> %{"type" => "error", "error" => %{"message" => message}} ->
{:error, message} {:error, message}
+24
View File
@@ -89,6 +89,30 @@ defmodule OpenAI.APITest do
assert_received {:chunk, " world"} assert_received {:chunk, " world"}
end end
test "callback return value does not affect stream processing" do
Req.Test.stub(__MODULE__, fn conn ->
body =
"data: #{JSON.encode!(%{"type" => "response.output_text.delta", "delta" => "Hello"})}\n\n" <>
"data: #{JSON.encode!(%{"type" => "response.output_text.delta", "delta" => " world"})}\n\n" <>
"data: #{JSON.encode!(%{"type" => "response.completed"})}\n\n"
conn
|> Plug.Conn.put_resp_content_type("text/event-stream")
|> Plug.Conn.send_resp(200, body)
end)
test_pid = self()
cb = fn chunk ->
send(test_pid, {:chunk, chunk})
{:error, "callback error"}
end
assert :ok = API.chat_stream([], "instructions", "gpt-4.1", 0.7, @config, cb)
assert_received {:chunk, "Hello"}
assert_received {:chunk, " world"}
end
@tag :capture_log @tag :capture_log
test "returns error on non-2xx response" do test "returns error on non-2xx response" do
Req.Test.stub(__MODULE__, fn conn -> Req.Test.stub(__MODULE__, fn conn ->