diff --git a/robot-docs/extensions.md b/robot-docs/extensions.md index 415dcac9b..12948e7cd 100644 --- a/robot-docs/extensions.md +++ b/robot-docs/extensions.md @@ -92,7 +92,7 @@ Initial session opening tolerates failed bundles and reports their warnings. Exp Host routes receive `host.Context(store, session, searches)` and the request string. The runtime captures eligible search providers from the loaded active composition; handlers do not read the registry to bypass session selection. Native discovery and composition revision calculation live in `harness/runtime/catalog`; HTTP encoders stay in the daemon. -`ModelsPlugin` supplies catalogued model facts and provider model lists. `ModelProviderPlugin` declares its models.dev namespace and resolves a tagged saved profile into an `Upstream`: a `stream` function over albedo's request, event, and turn types, plus the endpoint, replay protocol, and an `explain` for failures. A provider with its own wire format encodes an `openai_api.Exchange` and passes it with its own `stream.Reducer` to `openai_api.exchange`, which keeps HTTP, SSE framing, limits, and callbacks shared; `antigravity` does this. `LoginPlugin` supplies a browser sign-in that the daemon runs for every client; see [model authentication](auth.md#sign-in-api). +`ModelsPlugin` supplies catalogued model facts and provider model lists. `ModelProviderPlugin` declares its models.dev namespace and resolves a tagged saved profile into an `Upstream`: a `stream` function over albedo's request, event, and turn types, plus the endpoint, replay protocol, and an `explain` for failures. A provider with its own wire format encodes an `openai_api.Exchange` and passes it with its own `stream.Reducer` to `openai_api.exchange`, which keeps HTTP, SSE framing, limits, and callbacks shared; `antigravity` does this. A wire with its own framing supplies a `stream_http.Wire` to `stream_http.exchange` instead, which keeps the same HTTP, deadline, and callback rules shared and leaves only framing, payloads, and its end-of-body rules to the provider; Bedrock's Converse adapter is this, over AWS binary EventStream frames instead of SSE. `LoginPlugin` supplies a browser sign-in that the daemon runs for every client; see [model authentication](auth.md#sign-in-api). `ServicePlugin(Service(admission, handle))` serves HTTP while its extension is enabled globally. Sessions do not select services. `admission(path, method)` diff --git a/robot-docs/provider-requests.md b/robot-docs/provider-requests.md index 5f1656005..953679ced 100644 --- a/robot-docs/provider-requests.md +++ b/robot-docs/provider-requests.md @@ -73,7 +73,7 @@ for fields and bounds. `openai_api` speaks HTTP/1.1 itself (`albedo_openai_transport.erl`) over a socket the process streaming the call owns: plain TCP for `http`, and for `https` TLS verified against the OTP system CAs with HTTPS hostname matching, SNI for named hosts, and ALPN offering only `http/1.1`. Each packet wakes only that process; no connection process sits between the socket and the reducer. The socket closes when its owner exits, and a host header the caller passes (Bedrock signs its own) replaces the one the transport would add. -An exchange's `timeout_ms` bounds connecting and each wait for data. A provider that sets `first_event_timeout_ms` gives its headers and first SSE event a shared deadline instead, counted from when the request went out; keepalive comments do not move it, and `timeout_ms` bounds the waits after the first event. Only Antigravity sets one: 300 s for both, as oh-my-pi allows Cloud Code Assist, because argon streams no thought parts, so its thinking is a silent socket. Everyone else keeps one per-wait budget (60 s for the OpenAI clients, 120 s for Claude, Bedrock, Vertex). `ALBEDO_PROVIDER_TIMEOUT_MS` holds every budget to at most that many ms, so tests can reach a timeout in seconds. +An exchange's `timeout_ms` bounds connecting and each wait for data. A provider that sets `first_event_timeout_ms` gives its headers and first streamed event a shared deadline instead, counted from when the request went out; keepalive comments do not move it, and `timeout_ms` bounds the waits after the first event. Only Antigravity sets one: 300 s for both, as oh-my-pi allows Cloud Code Assist, because argon streams no thought parts, so its thinking is a silent socket. Everyone else keeps one per-wait budget (60 s for the OpenAI clients, 120 s for Claude, Bedrock, Vertex). `ALBEDO_PROVIDER_TIMEOUT_MS` holds every budget to at most that many ms, so tests can reach a timeout in seconds. Connections are kept alive. When an exchange returns `Ok`, its connection goes to `albedo_openai_pool`, one process started on first use, which reads whatever the exchange left unread (a stream ends at its terminal event, often before the chunked terminator; at most 64 KiB within 5 s) and then keeps it idle for the next request to the same scheme, host, and port: up to 60 s, at most 8 per host, newest reused first. A request that arrives while the only connections to its host are still reading that rest waits up to 50 ms for one instead of opening its own. A failed or cancelled exchange closes its socket, so the server stops generating. HTTP/1.0 responses, `connection: close`, and close-delimited bodies are never kept, and an idle connection that closes or sends anything is dropped. A request whose pooled connection fails to send, or closes before any response byte, goes out once more on a new connection; any later failure is a transport failure for the retries above. Reuse saves the TCP and TLS handshakes, about 45 ms per request to `api.openai.com` from a nearby network. diff --git a/src/albedo/harness/extensions/bedrock/converse_http.gleam b/src/albedo/harness/extensions/bedrock/converse_http.gleam index d8e4a7937..03fe776af 100644 --- a/src/albedo/harness/extensions/bedrock/converse_http.gleam +++ b/src/albedo/harness/extensions/bedrock/converse_http.gleam @@ -1,97 +1,61 @@ -//// Bedrock ConverseStream over the shared owned HTTP connection. Unlike SSE, -//// AWS binary framing and the reducer must both finish at HTTP EOF before a -//// completed turn (and its tool proposals) can leave this module. +//// Bedrock Converse over the shared streaming pump. Unlike SSE, AWS binary +//// framing and the reducer must both finish at HTTP EOF before a completed +//// turn (and its tool proposals) can leave this module. -import albedo/clock import albedo/harness/extensions/bedrock/converse_stream import albedo/harness/extensions/bedrock/eventstream import albedo/openai_api import albedo/openai_api/stream -import albedo/openai_api/transport +import albedo/openai_api/stream_http import albedo/openai_api/types -import gleam/bit_array import gleam/dynamic/decode import gleam/int import gleam/json import gleam/list -import gleam/option.{type Option, None, Some} +import gleam/option.{None, Some} import gleam/result import gleam/string const max_frame_bytes = 8_388_608 -const max_error_bytes = 65_536 - -type Wait { - Wait(idle_ms: Int, first_event: Option(#(Int, Int))) -} - -/// This binary pump always requires application/vnd.amazon.eventstream on a -/// successful response. Exchange.require_event_stream is an SSE-only option. pub fn exchange( exchange: openai_api.Exchange, reducer: stream.Reducer, on_event: fn(types.Event) -> types.Control, ) -> Result(types.Turn, types.Error) { use _ <- result.try(validate(exchange)) - let exchange = capped(exchange, transport.budget_cap()) - let sent = clock.monotonic_ms() - let wait = - Wait( - exchange.timeout_ms, - option.map(exchange.first_event_timeout_ms, fn(budget) { - #(sent + budget, budget) - }), - ) - use connection <- result.try( - transport.open( - exchange.url, - exchange.headers, - exchange.body, - exchange.timeout_ms, - ) - |> result.map_error(transport_error( - _, - types.Connecting, - exchange.timeout_ms, - )), - ) - use <- transport.with_connection_discard_errors(connection) - use first <- result.try(receive(connection, wait, types.AwaitingHeaders)) - case first { - transport.Headers(status, headers, final) -> { - use _ <- result.try(notify([types.Responded(status)], on_event)) - case status >= 200 && status < 300 { - False -> http_error(connection, wait, status, final, [], 0) - True -> { - use _ <- result.try(case binary_stream(headers) { - True -> Ok(Nil) - False -> - Error(types.InvalidEvent( - "expected application/vnd.amazon.eventstream response", - )) - }) - case final { - True -> Error(types.UnexpectedEnd) - False -> - pump( - connection, - wait, - types.AwaitingFirstEvent, - eventstream.new_with_limit(int.min( - exchange.max_event_bytes, - max_frame_bytes, - )), - reducer, - Thinking(0, sent, None), - on_event, - ) - } - } + stream_http.exchange(openai_api.to_pump(exchange), wire(), reducer, on_event) +} + +fn wire() -> stream_http.Wire(eventstream.Decoder, eventstream.Message) { + stream_http.Wire( + start: fn(max_bytes) { + eventstream.new_with_limit(int.min(max_bytes, max_frame_bytes)) + }, + feed: fn(decoder, bytes) { + eventstream.feed(decoder, bytes) |> result.map_error(frame_error) + }, + finish: fn(decoder) { + eventstream.finish(decoder) + |> result.map_error(frame_error) + |> result.map(fn(_) { [] }) + }, + payload: event_payload, + body: fn(headers) { + case binary_stream(headers) { + True -> stream_http.Pump + False -> + stream_http.Refuse( + "expected application/vnd.amazon.eventstream response", + ) } - } - _ -> Error(types.InvalidEvent("HTTP data arrived before headers")) - } + }, + // Converse defers tool validation and publication to finish, so a reducer + // that completed early would pool a response with unread metadata, errors, + // or broken frames. + settle: stream_http.OnlyAtEnd("Converse reducer completed before HTTP EOF"), + discard_on_error: True, + ) } fn validate(exchange: openai_api.Exchange) -> Result(Nil, types.Error) { @@ -107,21 +71,6 @@ fn validate(exchange: openai_api.Exchange) -> Result(Nil, types.Error) { } } -fn capped(exchange: openai_api.Exchange, cap: Int) -> openai_api.Exchange { - case cap > 0 { - False -> exchange - True -> - openai_api.Exchange( - ..exchange, - timeout_ms: int.min(exchange.timeout_ms, cap), - first_event_timeout_ms: option.map( - exchange.first_event_timeout_ms, - int.min(_, cap), - ), - ) - } -} - fn binary_stream(headers: List(#(String, String))) -> Bool { list.any(headers, fn(header) { string.lowercase(header.0) == "content-type" @@ -137,79 +86,41 @@ fn binary_stream(headers: List(#(String, String))) -> Bool { }) } -fn pump( - connection: transport.Connection, - wait: Wait, - phase: types.TimeoutPhase, - decoder: eventstream.Decoder, - reducer: stream.Reducer, - thinking: Thinking, +/// One nonstreaming Converse POST. Production model loops use exchange; this +/// helper shares the request/turn wire contract without event framing. +pub fn exchange_sync( + exchange: openai_api.Exchange, + model: String, on_event: fn(types.Event) -> types.Control, ) -> Result(types.Turn, types.Error) { - use message <- result.try(receive(connection, wait, phase)) - case message { - transport.Data(bytes, final) -> { - let now = clock.monotonic_ms() - use #(decoder, messages) <- result.try( - eventstream.feed(decoder, bytes) |> result.map_error(frame_error), - ) - use #(reducer, thinking) <- result.try(deliver( - reducer, - thinking, - now, - messages, - on_event, + use _ <- result.try(validate(exchange)) + stream_http.with_body( + openai_api.to_pump(exchange), + int.min(exchange.max_event_bytes, max_frame_bytes), + True, + on_event, + fn(body) { + use turn <- result.try(converse_stream.decode_response_for_model( + model, + body, )) - case final { - True -> { - use _ <- result.try( - eventstream.finish(decoder) |> result.map_error(frame_error), - ) - reducer.finish() |> result.map(timed(_, thinking, now)) - } - False -> - pump( - connection, - wait, - case messages { - [] -> phase - _ -> types.Streaming - }, - decoder, - reducer, - thinking, - on_event, - ) - } - } - _ -> Error(types.InvalidEvent("unexpected HTTP headers inside stream")) - } + use _ <- result.try(meter(turn, on_event)) + Ok(turn) + }, + ) } -fn deliver( - reducer: stream.Reducer, - thinking: Thinking, - now: Int, - messages: List(eventstream.Message), +fn meter( + turn: types.Turn, on_event: fn(types.Event) -> types.Control, -) -> Result(#(stream.Reducer, Thinking), types.Error) { - case messages { - [] -> Ok(#(reducer, thinking)) - [message, ..rest] -> { - use payload <- result.try(event_payload(message)) - use #(reducer, updates, turn) <- result.try(reducer.feed(payload)) - // Converse's reducer has to defer tool validation and publication to - // finish. Reject an accidentally terminal reducer rather than pooling - // a response that still has unread metadata, errors, or broken frames. - use _ <- result.try(case turn { - None -> Ok(Nil) - Some(_) -> - Error(types.InvalidEvent("Converse reducer completed before HTTP EOF")) - }) - use _ <- result.try(notify(updates, on_event)) - let thinking = list.fold(updates, thinking, fn(t, e) { think(t, e, now) }) - deliver(reducer, thinking, now, rest, on_event) - } +) -> Result(Nil, types.Error) { + case turn.usage { + Some(usage) -> + stream_http.notify( + [types.Metered(usage, Some(usage.input_tokens + usage.output_tokens))], + on_event, + ) + None -> Ok(Nil) } } @@ -303,241 +214,3 @@ fn frame_error(message: String) -> types.Error { False -> types.InvalidEvent(message) } } - -fn notify( - events: List(types.Event), - on_event: fn(types.Event) -> types.Control, -) -> Result(Nil, types.Error) { - list.try_each(events, fn(event) { - case on_event(event) { - types.Continue -> Ok(Nil) - types.Stop -> Error(types.Cancelled) - } - }) -} - -type Thinking { - Thinking(total: Int, last: Int, since: Option(Int)) -} - -fn think(thinking: Thinking, event: types.Event, now: Int) -> Thinking { - case event, thinking.since { - types.ThinkingDelta(_), None -> - Thinking(..thinking, since: Some(thinking.last)) - types.ThinkingDelta(_), Some(_) -> thinking - _, Some(_) -> Thinking(elapsed(thinking, now), now, None) - _, None -> Thinking(..thinking, last: now) - } -} - -fn timed(turn: types.Turn, thinking: Thinking, now: Int) -> types.Turn { - case elapsed(thinking, now) { - 0 -> turn - total -> types.Turn(..turn, thought_ms: Some(total)) - } -} - -fn elapsed(thinking: Thinking, now: Int) -> Int { - case thinking.since { - Some(since) -> thinking.total + now - since - None -> thinking.total - } -} - -fn receive( - connection: transport.Connection, - wait: Wait, - phase: types.TimeoutPhase, -) -> Result(transport.Message, types.Error) { - case wait.first_event, phase { - Some(#(deadline, total)), types.AwaitingHeaders - | Some(#(deadline, total)), types.AwaitingFirstEvent - -> - transport.receive_until(connection, deadline) - |> result.map_error(transport_error(_, phase, total)) - _, types.Streaming -> - transport.receive(connection) - |> result.map_error(transport_error(_, phase, wait.idle_ms)) - _, _ -> - transport.receive_within(connection, wait.idle_ms) - |> result.map_error(transport_error(_, phase, wait.idle_ms)) - } -} - -fn transport_error( - error: transport.Error, - phase: types.TimeoutPhase, - waited_ms: Int, -) -> types.Error { - case error { - transport.InvalidUrl -> types.InvalidRequest("invalid HTTP endpoint") - transport.RequestRefused(message) -> types.InvalidRequest(message) - transport.TransportError(message) -> types.ConnectionError(message) - transport.TimedOut -> types.Timeout(phase, waited_ms) - } -} - -fn http_error( - connection: transport.Connection, - wait: Wait, - status: Int, - final: Bool, - chunks: List(BitArray), - size: Int, -) -> Result(a, types.Error) { - case final || size >= max_error_bytes { - True -> { - let body = - chunks - |> list.reverse - |> bit_array.concat - |> bit_array.to_string - |> result.unwrap("") - Error(types.HttpError(status, body)) - } - False -> { - use message <- result.try(receive( - connection, - wait, - types.AwaitingFirstEvent, - )) - case message { - transport.Data(bytes, final) -> { - let remaining = max_error_bytes - size - let bytes = case bit_array.byte_size(bytes) > remaining { - True -> bit_array.slice(bytes, 0, remaining) |> result.unwrap(<<>>) - False -> bytes - } - http_error( - connection, - wait, - status, - final, - [bytes, ..chunks], - size + bit_array.byte_size(bytes), - ) - } - _ -> Error(types.HttpError(status, "unexpected response framing")) - } - } - } -} - -/// One nonstreaming Converse POST. Production model loops use exchange; -/// this helper shares the request/turn wire contract without SSE framing. -pub fn exchange_sync( - exchange: openai_api.Exchange, - model: String, - on_event: fn(types.Event) -> types.Control, -) -> Result(types.Turn, types.Error) { - use _ <- result.try(validate(exchange)) - let exchange = capped(exchange, transport.budget_cap()) - let sent = clock.monotonic_ms() - let wait = - Wait( - exchange.timeout_ms, - option.map(exchange.first_event_timeout_ms, fn(budget) { - #(sent + budget, budget) - }), - ) - use connection <- result.try( - transport.open( - exchange.url, - exchange.headers, - exchange.body, - exchange.timeout_ms, - ) - |> result.map_error(transport_error( - _, - types.Connecting, - exchange.timeout_ms, - )), - ) - use <- transport.with_connection_discard_errors(connection) - use message <- result.try(receive(connection, wait, types.AwaitingHeaders)) - case message { - transport.Headers(status, _, final) -> { - use _ <- result.try(notify([types.Responded(status)], on_event)) - case status >= 200 && status < 300 { - False -> http_error(connection, wait, status, final, [], 0) - True -> { - use bytes <- result.try(collect_json( - connection, - wait, - types.AwaitingFirstEvent, - final, - [], - 0, - int.min(exchange.max_event_bytes, max_frame_bytes), - )) - use body <- result.try( - bit_array.to_string(bytes) - |> result.replace_error(types.InvalidEvent( - "Converse response is not UTF-8", - )), - ) - use turn <- result.try(converse_stream.decode_response_for_model( - model, - body, - )) - use _ <- result.try(notify( - case turn.usage { - Some(usage) -> [ - types.Metered( - usage, - Some(usage.input_tokens + usage.output_tokens), - ), - ] - None -> [] - }, - on_event, - )) - Ok(turn) - } - } - } - _ -> Error(types.InvalidEvent("HTTP data arrived before headers")) - } -} - -fn collect_json( - connection: transport.Connection, - wait: Wait, - phase: types.TimeoutPhase, - final: Bool, - chunks: List(BitArray), - size: Int, - limit: Int, -) -> Result(BitArray, types.Error) { - case final { - True -> Ok(chunks |> list.reverse |> bit_array.concat) - False -> { - use message <- result.try(receive(connection, wait, phase)) - case message { - transport.Data(bytes, final) -> { - let size = size + bit_array.byte_size(bytes) - case size > limit { - True -> Error(types.EventTooLarge) - False -> - collect_json( - connection, - wait, - case bytes { - <<>> -> phase - _ -> types.Streaming - }, - final, - [bytes, ..chunks], - size, - limit, - ) - } - } - _ -> - Error(types.InvalidEvent( - "unexpected HTTP headers inside Converse response", - )) - } - } - } -} diff --git a/src/albedo/openai_api.gleam b/src/albedo/openai_api.gleam index 562a6a32e..f35d29f45 100644 --- a/src/albedo/openai_api.gleam +++ b/src/albedo/openai_api.gleam @@ -22,20 +22,16 @@ //// verified TLS for https, and kept alive between requests to the same host. //// Requests stay as iodata. -import albedo/clock - import albedo/openai_api/request import albedo/openai_api/sse import albedo/openai_api/stream as reducer -import albedo/openai_api/transport +import albedo/openai_api/stream_http import albedo/openai_api/types.{ type Client, type Control, type Error, type Event, type Input, type Protocol, - type Request, type Turn, ChatCompletions, Continue, Responses, Stop, + type Request, type Turn, ChatCompletions, Responses, } -import gleam/bit_array -import gleam/int import gleam/list -import gleam/option.{type Option, None, Some} +import gleam/option.{type Option, None} import gleam/result import gleam/string import gleam/string_tree.{type StringTree} @@ -224,83 +220,6 @@ pub type Exchange { ) } -/// The budgets one exchange waits under; `first_event` is the deadline its -/// headers and first event must meet, and the budget that deadline came from. -type Wait { - Wait(idle_ms: Int, first_event: Option(#(Int, Int))) -} - -pub fn exchange( - exchange: Exchange, - reducer: reducer.Reducer, - on_event: fn(Event) -> Control, -) -> Result(Turn, Error) { - let exchange = capped(exchange, transport.budget_cap()) - let sent = clock.monotonic_ms() - let wait = - Wait( - exchange.timeout_ms, - option.map(exchange.first_event_timeout_ms, fn(budget) { - #(sent + budget, budget) - }), - ) - use connection <- result.try( - transport.open( - exchange.url, - exchange.headers, - exchange.body, - exchange.timeout_ms, - ) - |> result.map_error(transport_error( - _, - types.Connecting, - exchange.timeout_ms, - )), - ) - use <- transport.with_connection(connection) - use first <- result.try(receive(connection, wait, types.AwaitingHeaders)) - case first { - transport.Headers(status, headers, final) -> { - use _ <- result.try(notify([types.Responded(status)], on_event)) - case status >= 200 && status < 300 { - False -> http_error(connection, wait, status, final, [], 0) - True -> - case event_stream(headers) || !exchange.require_event_stream, final { - False, _ -> http_error(connection, wait, status, final, [], 0) - True, True -> Error(types.UnexpectedEnd) - True, False -> - pump( - connection, - wait, - types.AwaitingFirstEvent, - sse.new(exchange.max_event_bytes), - reducer, - Thinking(0, sent, None), - on_event, - ) - } - } - } - _ -> Error(types.InvalidEvent("HTTP data arrived before headers")) - } -} - -/// `exchange` with every budget held to `cap` ms, when `cap` is positive. -fn capped(exchange: Exchange, cap: Int) -> Exchange { - case cap > 0 { - False -> exchange - True -> - Exchange( - ..exchange, - timeout_ms: int.min(exchange.timeout_ms, cap), - first_event_timeout_ms: option.map( - exchange.first_event_timeout_ms, - int.min(_, cap), - ), - ) - } -} - fn validate_client(client: Client) -> Result(Nil, Error) { case client.timeout_ms <= 0 || client.max_event_bytes <= 0, @@ -361,6 +280,48 @@ fn unsafe_header(value: String) -> Bool { string.contains(value, "\r") || string.contains(value, "\n") } +/// Stream one turn, settling it only once the response is complete. +pub fn exchange( + exchange: Exchange, + reducer: reducer.Reducer, + on_event: fn(Event) -> Control, +) -> Result(Turn, Error) { + stream_http.exchange(to_pump(exchange), wire(exchange), reducer, on_event) +} + +/// The pump's view of `exchange`: where the request goes and its budgets. +pub fn to_pump(exchange: Exchange) -> stream_http.Exchange { + stream_http.Exchange( + exchange.url, + exchange.headers, + exchange.body, + exchange.timeout_ms, + exchange.first_event_timeout_ms, + exchange.max_event_bytes, + ) +} + +/// SSE framing: the body carries `data` payloads, and a response without the +/// event-stream content type is only an error body when nothing requires one. +fn wire(exchange: Exchange) -> stream_http.Wire(sse.Parser, sse.Event) { + stream_http.Wire( + start: sse.new, + feed: fn(parser, chunk) { + sse.feed(parser, chunk) |> result.map_error(sse_error) + }, + finish: fn(parser) { sse.finish(parser) |> result.map_error(sse_error) }, + payload: fn(event: sse.Event) { Ok(event.data) }, + body: fn(headers) { + case event_stream(headers) || !exchange.require_event_stream { + True -> stream_http.Pump + False -> stream_http.HttpError + } + }, + settle: stream_http.BeforeEnd, + discard_on_error: False, + ) +} + fn event_stream(headers: List(#(String, String))) -> Bool { list.any(headers, fn(header) { let #(name, value) = header @@ -377,167 +338,6 @@ fn event_stream(headers: List(#(String, String))) -> Bool { }) } -fn pump( - connection: transport.Connection, - wait: Wait, - phase: types.TimeoutPhase, - parser: sse.Parser, - state: reducer.Reducer, - thinking: Thinking, - on_event: fn(Event) -> Control, -) -> Result(Turn, Error) { - use message <- result.try(receive(connection, wait, phase)) - case message { - transport.Data(bytes, final) -> { - let now = clock.monotonic_ms() - use #(parser, events) <- result.try( - sse.feed(parser, bytes) |> result.map_error(sse_error), - ) - let phase = case events { - [] -> phase - _ -> types.Streaming - } - use #(state, thinking, turn) <- result.try(deliver( - state, - thinking, - now, - events, - on_event, - )) - case turn, final { - Some(turn), _ -> Ok(timed(turn, thinking, now)) - None, True -> { - use events <- result.try( - sse.finish(parser) |> result.map_error(sse_error), - ) - use #(state, thinking, turn) <- result.try(deliver( - state, - thinking, - now, - events, - on_event, - )) - case turn { - Some(turn) -> Ok(turn) - None -> state.finish() - } - |> result.map(timed(_, thinking, now)) - } - None, False -> - pump(connection, wait, phase, parser, state, thinking, on_event) - } - } - _ -> Error(types.InvalidEvent("unexpected HTTP headers inside stream")) - } -} - -fn deliver( - state: reducer.Reducer, - thinking: Thinking, - now: Int, - events: List(sse.Event), - on_event: fn(Event) -> Control, -) -> Result(#(reducer.Reducer, Thinking, Option(Turn)), Error) { - case events { - [] -> Ok(#(state, thinking, None)) - [event, ..rest] -> { - use #(state, updates, turn) <- result.try(state.feed(event.data)) - use _ <- result.try(notify(updates, on_event)) - let thinking = list.fold(updates, thinking, fn(t, e) { think(t, e, now) }) - case turn { - Some(_) -> Ok(#(state, thinking, turn)) - None -> deliver(state, thinking, now, rest, on_event) - } - } - } -} - -fn notify( - events: List(Event), - on_event: fn(Event) -> Control, -) -> Result(Nil, Error) { - list.try_each(events, fn(event) { - case on_event(event) { - Continue -> Ok(Nil) - Stop -> Error(types.Cancelled) - } - }) -} - -/// Time spent thinking so far, when the last other event came (the request -/// itself, at first), and when the spell under way began. -type Thinking { - Thinking(total: Int, last: Int, since: Option(Int)) -} - -/// A spell runs from the event before its first thinking delta to the next -/// other event: summarized thinking streams only once it is written, so the -/// thought began before its first delta did. -fn think(thinking: Thinking, event: Event, now: Int) -> Thinking { - case event, thinking.since { - types.ThinkingDelta(_), None -> - Thinking(..thinking, since: Some(thinking.last)) - types.ThinkingDelta(_), Some(_) -> thinking - _, Some(_) -> Thinking(elapsed(thinking, now), now, None) - _, None -> Thinking(..thinking, last: now) - } -} - -/// A turn that ends while it is still thinking thought until its end. -fn timed(turn: Turn, thinking: Thinking, now: Int) -> Turn { - case elapsed(thinking, now) { - 0 -> turn - total -> types.Turn(..turn, thought_ms: Some(total)) - } -} - -/// Thinking time so far, closing the spell under way if there is one. -fn elapsed(thinking: Thinking, now: Int) -> Int { - case thinking.since { - Some(since) -> thinking.total + now - since - None -> thinking.total - } -} - -/// The next message, within what is left of the first-event deadline while -/// one runs, else within the idle budget until the first event. Once events -/// flow, a body chunk waits while the connection is alive. -fn receive( - connection: transport.Connection, - wait: Wait, - phase: types.TimeoutPhase, -) -> Result(transport.Message, Error) { - case wait.first_event, phase { - Some(#(deadline, total)), types.AwaitingHeaders - | Some(#(deadline, total)), types.AwaitingFirstEvent - -> - transport.receive_within( - connection, - int.max(1, deadline - clock.monotonic_ms()), - ) - |> result.map_error(transport_error(_, phase, total)) - _, types.Streaming -> - transport.receive(connection) - |> result.map_error(transport_error(_, phase, wait.idle_ms)) - _, _ -> - transport.receive_within(connection, wait.idle_ms) - |> result.map_error(transport_error(_, phase, wait.idle_ms)) - } -} - -fn transport_error( - error: transport.Error, - phase: types.TimeoutPhase, - waited_ms: Int, -) -> Error { - case error { - transport.InvalidUrl -> types.InvalidRequest("invalid HTTP endpoint") - transport.RequestRefused(message) -> types.InvalidRequest(message) - transport.TransportError(message) -> types.ConnectionError(message) - transport.TimedOut -> types.Timeout(phase, waited_ms) - } -} - fn sse_error(error: sse.Error) -> Error { case error { sse.EventTooLarge -> types.EventTooLarge @@ -545,49 +345,3 @@ fn sse_error(error: sse.Error) -> Error { sse.Malformed(message) -> types.InvalidEvent(message) } } - -fn http_error( - connection: transport.Connection, - wait: Wait, - status: Int, - final: Bool, - chunks: List(BitArray), - size: Int, -) -> Result(a, Error) { - case final || size >= 65_536 { - True -> { - let body = - chunks - |> list.reverse - |> bit_array.concat - |> bit_array.to_string - |> result.unwrap("") - Error(types.HttpError(status, body)) - } - False -> { - use message <- result.try(receive( - connection, - wait, - types.AwaitingFirstEvent, - )) - case message { - transport.Data(bytes, final) -> { - let remaining = 65_536 - size - let bytes = case bit_array.byte_size(bytes) > remaining { - True -> bit_array.slice(bytes, 0, remaining) |> result.unwrap(<<>>) - False -> bytes - } - http_error( - connection, - wait, - status, - final, - [bytes, ..chunks], - size + bit_array.byte_size(bytes), - ) - } - _ -> Error(types.HttpError(status, "unexpected response framing")) - } - } - } -} diff --git a/src/albedo/openai_api/stream_http.gleam b/src/albedo/openai_api/stream_http.gleam new file mode 100644 index 000000000..67df26ee4 --- /dev/null +++ b/src/albedo/openai_api/stream_http.gleam @@ -0,0 +1,490 @@ +//// The streaming HTTP pump every provider wire shares: open the exchange, read +//// its headers, feed body frames to a reducer, and settle a turn only once the +//// response is complete. +//// +//// A wire supplies only what makes it different: how a chunk becomes frames, +//// what payload a frame carries, when a body is its stream, and whether its +//// reducer may settle a turn before the body ends. + +import albedo/clock +import albedo/openai_api/stream +import albedo/openai_api/transport +import albedo/openai_api/types +import gleam/bit_array +import gleam/int +import gleam/list +import gleam/option.{type Option, None, Some} +import gleam/result +import gleam/string_tree.{type StringTree} + +const max_error_bytes = 65_536 + +/// One exchange as the pump needs it: where the request goes and the budgets +/// it runs under. A wire converts its own exchange to this. +pub type Exchange { + Exchange( + url: String, + headers: List(#(String, String)), + body: StringTree, + timeout_ms: Int, + first_event_timeout_ms: Option(Int), + max_event_bytes: Int, + ) +} + +/// What a response whose body is not this wire's stream means. +pub type Body { + /// Feed the body to the reducer as frames. + Pump + /// Read the body and report it as the HTTP error its status carries. + HttpError + /// Refuse with this message instead of reading the body. + Refuse(String) +} + +/// Whether a reducer may settle the turn before the body ends. A wire that +/// validates a whole document at EOF refuses an early turn instead. +pub type Settle { + BeforeEnd + OnlyAtEnd(String) +} + +/// One wire's framing and its rules for a response. +pub type Wire(parser, frame) { + Wire( + /// The frame parser, given the exchange's event byte limit. + start: fn(Int) -> parser, + feed: fn(parser, BitArray) -> Result(#(parser, List(frame)), types.Error), + /// Frames completed by a flush when the body ends. + finish: fn(parser) -> Result(List(frame), types.Error), + /// The reducer payload one frame carries. + payload: fn(frame) -> Result(String, types.Error), + body: fn(List(#(String, String))) -> Body, + settle: Settle, + /// Discard the socket after any error instead of pooling it. + discard_on_error: Bool, + ) +} + +pub fn exchange( + exchange: Exchange, + wire: Wire(parser, frame), + reducer: stream.Reducer, + on_event: fn(types.Event) -> types.Control, +) -> Result(types.Turn, types.Error) { + let exchange = capped(exchange, transport.budget_cap()) + let sent = clock.monotonic_ms() + let wait = + Wait( + exchange.timeout_ms, + option.map(exchange.first_event_timeout_ms, fn(budget) { + #(sent + budget, budget) + }), + ) + use connection <- result.try( + transport.open( + exchange.url, + exchange.headers, + exchange.body, + exchange.timeout_ms, + ) + |> result.map_error(transport_error( + _, + types.Connecting, + exchange.timeout_ms, + )), + ) + use <- with_connection(connection, wire.discard_on_error) + use first <- result.try(receive(connection, wait, types.AwaitingHeaders)) + case first { + transport.Headers(status, headers, final) -> { + use _ <- result.try(notify([types.Responded(status)], on_event)) + case status >= 200 && status < 300 { + False -> http_error(connection, wait, status, final, [], 0) + True -> + case wire.body(headers) { + HttpError -> http_error(connection, wait, status, final, [], 0) + Refuse(message) -> Error(types.InvalidEvent(message)) + Pump -> + case final { + True -> Error(types.UnexpectedEnd) + False -> + pump( + connection, + wait, + types.AwaitingFirstEvent, + wire.start(exchange.max_event_bytes), + wire, + reducer, + Thinking(0, sent, None), + on_event, + ) + } + } + } + } + _ -> Error(types.InvalidEvent("HTTP data arrived before headers")) + } +} + +fn pump( + connection: transport.Connection, + wait: Wait, + phase: types.TimeoutPhase, + parser: parser, + wire: Wire(parser, frame), + reducer: stream.Reducer, + thinking: Thinking, + on_event: fn(types.Event) -> types.Control, +) -> Result(types.Turn, types.Error) { + use message <- result.try(receive(connection, wait, phase)) + case message { + transport.Data(bytes, final) -> { + let now = clock.monotonic_ms() + use #(parser, frames) <- result.try(wire.feed(parser, bytes)) + let phase = case frames { + [] -> phase + _ -> types.Streaming + } + use #(reducer, thinking, done) <- result.try(deliver( + wire, + reducer, + thinking, + now, + frames, + on_event, + )) + case done, final { + Some(turn), _ -> Ok(timed(turn, thinking, now)) + None, True -> { + use frames <- result.try(wire.finish(parser)) + use #(reducer, thinking, done) <- result.try(deliver( + wire, + reducer, + thinking, + now, + frames, + on_event, + )) + case done { + Some(turn) -> Ok(turn) + None -> reducer.finish() + } + |> result.map(timed(_, thinking, now)) + } + None, False -> + pump( + connection, + wait, + phase, + parser, + wire, + reducer, + thinking, + on_event, + ) + } + } + _ -> Error(types.InvalidEvent("unexpected HTTP headers inside stream")) + } +} + +fn deliver( + wire: Wire(parser, frame), + reducer: stream.Reducer, + thinking: Thinking, + now: Int, + frames: List(frame), + on_event: fn(types.Event) -> types.Control, +) -> Result(#(stream.Reducer, Thinking, Option(types.Turn)), types.Error) { + case frames { + [] -> Ok(#(reducer, thinking, None)) + [frame, ..rest] -> { + use payload <- result.try(wire.payload(frame)) + use #(reducer, updates, turn) <- result.try(reducer.feed(payload)) + use _ <- result.try(settle(wire.settle, turn)) + use _ <- result.try(notify(updates, on_event)) + let thinking = + list.fold(updates, thinking, fn(t, event) { think(t, event, now) }) + case turn { + Some(_) -> Ok(#(reducer, thinking, turn)) + None -> deliver(wire, reducer, thinking, now, rest, on_event) + } + } + } +} + +fn settle( + policy: Settle, + turn: Option(types.Turn), +) -> Result(Nil, types.Error) { + case policy, turn { + BeforeEnd, _ -> Ok(Nil) + OnlyAtEnd(message), Some(_) -> Error(types.InvalidEvent(message)) + OnlyAtEnd(_), None -> Ok(Nil) + } +} + +fn with_connection( + connection: transport.Connection, + discard_on_error: Bool, + run: fn() -> value, +) -> value { + case discard_on_error { + True -> transport.with_connection_discard_errors(connection, run) + False -> transport.with_connection(connection, run) + } +} + +/// `exchange` with every budget held to `cap` ms, when `cap` is positive. +fn capped(exchange: Exchange, cap: Int) -> Exchange { + case cap > 0 { + False -> exchange + True -> + Exchange( + ..exchange, + timeout_ms: int.min(exchange.timeout_ms, cap), + first_event_timeout_ms: option.map( + exchange.first_event_timeout_ms, + int.min(_, cap), + ), + ) + } +} + +/// Time spent thinking so far, when the last other event came (the request +/// itself, at first), and when the spell under way began. +type Thinking { + Thinking(total: Int, last: Int, since: Option(Int)) +} + +/// A spell runs from the event before its first thinking delta to the next +/// other event: summarized thinking streams only once it is written, so the +/// thought began before its first delta did. +fn think(thinking: Thinking, event: types.Event, now: Int) -> Thinking { + case event, thinking.since { + types.ThinkingDelta(_), None -> + Thinking(..thinking, since: Some(thinking.last)) + types.ThinkingDelta(_), Some(_) -> thinking + _, Some(_) -> Thinking(elapsed(thinking, now), now, None) + _, None -> Thinking(..thinking, last: now) + } +} + +/// A turn that ends while it is still thinking thought until its end. +fn timed(turn: types.Turn, thinking: Thinking, now: Int) -> types.Turn { + case elapsed(thinking, now) { + 0 -> turn + total -> types.Turn(..turn, thought_ms: Some(total)) + } +} + +/// Thinking time so far, closing the spell under way if there is one. +fn elapsed(thinking: Thinking, now: Int) -> Int { + case thinking.since { + Some(since) -> thinking.total + now - since + None -> thinking.total + } +} + +/// The budgets one exchange waits under; `first_event` is the deadline its +/// headers and first event must meet, and the budget that deadline came from. +type Wait { + Wait(idle_ms: Int, first_event: Option(#(Int, Int))) +} + +/// The next message, within what is left of the first-event deadline while +/// one runs, else within the idle budget until the first event. Once events +/// flow, a body chunk waits while the connection is alive. +fn receive( + connection: transport.Connection, + wait: Wait, + phase: types.TimeoutPhase, +) -> Result(transport.Message, types.Error) { + case wait.first_event, phase { + Some(#(deadline, total)), types.AwaitingHeaders + | Some(#(deadline, total)), types.AwaitingFirstEvent + -> + transport.receive_until(connection, deadline) + |> result.map_error(transport_error(_, phase, total)) + _, types.Streaming -> + transport.receive(connection) + |> result.map_error(transport_error(_, phase, wait.idle_ms)) + _, _ -> + transport.receive_within(connection, wait.idle_ms) + |> result.map_error(transport_error(_, phase, wait.idle_ms)) + } +} + +fn transport_error( + error: transport.Error, + phase: types.TimeoutPhase, + waited_ms: Int, +) -> types.Error { + case error { + transport.InvalidUrl -> types.InvalidRequest("invalid HTTP endpoint") + transport.RequestRefused(message) -> types.InvalidRequest(message) + transport.TransportError(message) -> types.ConnectionError(message) + transport.TimedOut -> types.Timeout(phase, waited_ms) + } +} + +fn http_error( + connection: transport.Connection, + wait: Wait, + status: Int, + final: Bool, + chunks: List(BitArray), + size: Int, +) -> Result(a, types.Error) { + case final || size >= max_error_bytes { + True -> { + let body = + chunks + |> list.reverse + |> bit_array.concat + |> bit_array.to_string + |> result.unwrap("") + Error(types.HttpError(status, body)) + } + False -> { + use message <- result.try(receive( + connection, + wait, + types.AwaitingFirstEvent, + )) + case message { + transport.Data(bytes, final) -> { + let remaining = max_error_bytes - size + let bytes = case bit_array.byte_size(bytes) > remaining { + True -> bit_array.slice(bytes, 0, remaining) |> result.unwrap(<<>>) + False -> bytes + } + http_error( + connection, + wait, + status, + final, + [bytes, ..chunks], + size + bit_array.byte_size(bytes), + ) + } + _ -> Error(types.HttpError(status, "unexpected response framing")) + } + } + } +} + +/// One request whose response is a whole body rather than a stream. `run` gets +/// it before the connection is pooled (or discarded, if any step failed). +pub fn with_body( + exchange: Exchange, + limit: Int, + discard_on_error: Bool, + on_event: fn(types.Event) -> types.Control, + run: fn(String) -> Result(a, types.Error), +) -> Result(a, types.Error) { + let exchange = capped(exchange, transport.budget_cap()) + let sent = clock.monotonic_ms() + let wait = + Wait( + exchange.timeout_ms, + option.map(exchange.first_event_timeout_ms, fn(budget) { + #(sent + budget, budget) + }), + ) + use connection <- result.try( + transport.open( + exchange.url, + exchange.headers, + exchange.body, + exchange.timeout_ms, + ) + |> result.map_error(transport_error( + _, + types.Connecting, + exchange.timeout_ms, + )), + ) + use <- with_connection(connection, discard_on_error) + use first <- result.try(receive(connection, wait, types.AwaitingHeaders)) + case first { + transport.Headers(status, _, final) -> { + use _ <- result.try(notify([types.Responded(status)], on_event)) + case status >= 200 && status < 300 { + False -> http_error(connection, wait, status, final, [], 0) + True -> { + use bytes <- result.try(collect( + connection, + wait, + types.AwaitingFirstEvent, + final, + [], + 0, + limit, + )) + use body <- result.try( + bit_array.to_string(bytes) + |> result.replace_error(types.InvalidEvent( + "response body is not UTF-8", + )), + ) + run(body) + } + } + } + _ -> Error(types.InvalidEvent("HTTP data arrived before headers")) + } +} + +fn collect( + connection: transport.Connection, + wait: Wait, + phase: types.TimeoutPhase, + final: Bool, + chunks: List(BitArray), + size: Int, + limit: Int, +) -> Result(BitArray, types.Error) { + case final { + True -> Ok(chunks |> list.reverse |> bit_array.concat) + False -> { + use message <- result.try(receive(connection, wait, phase)) + case message { + transport.Data(bytes, final) -> { + let size = size + bit_array.byte_size(bytes) + case size > limit { + True -> Error(types.EventTooLarge) + False -> + collect( + connection, + wait, + case bytes { + <<>> -> phase + _ -> types.Streaming + }, + final, + [bytes, ..chunks], + size, + limit, + ) + } + } + _ -> Error(types.InvalidEvent("unexpected HTTP headers inside body")) + } + } + } +} + +/// Deliver events to the caller's callback; Stop cancels the exchange. +pub fn notify( + events: List(types.Event), + on_event: fn(types.Event) -> types.Control, +) -> Result(Nil, types.Error) { + list.try_each(events, fn(event) { + case on_event(event) { + types.Continue -> Ok(Nil) + types.Stop -> Error(types.Cancelled) + } + }) +}