Skip to content
Closed
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: 4 additions & 0 deletions CHANGELOG.md
Original file line number Diff line number Diff line change
@@ -1,5 +1,9 @@
# Changelog

## Unreleased - provider SSE data spacing

- Preserve provider text when an SSE `data:` field omits the optional space after the colon. Non-streaming responses and translated Completions, Messages and Responses streams now accept both forms.

## Unreleased - Autopilot daily earnings floor

- Add a separately funded daily inference-earnings floor only for machines with saved Autopilot consent. Freeze the first-ever opt-in baseline from the exact preceding 168 hours, including sponsored inference; the daily floor is 110% of that seven-day daily average, rounded down once to whole micro-USD. Closed UTC days receive their own shortfall top-up without changing ordinary base rewards.
Expand Down
2 changes: 1 addition & 1 deletion coordinator/api/inference/response/responses_stream.go
Original file line number Diff line number Diff line change
Expand Up @@ -37,7 +37,7 @@ type streamChunkChoice struct {
// parseStreamChunkChoices decodes the choices array from a provider SSE chunk.
// Returns nil for non-JSON lines, [DONE], and chunks without choices.
func parseStreamChunkChoices(chunk string) []streamChunkChoice {
line := strings.TrimSpace(strings.TrimPrefix(chunk, "data: "))
line := strings.TrimSpace(strings.TrimPrefix(chunk, "data:"))
if line == "" || line == "[DONE]" {
return nil
}
Expand Down
2 changes: 1 addition & 1 deletion coordinator/api/inference/response/stream_message.go
Original file line number Diff line number Diff line change
Expand Up @@ -36,7 +36,7 @@ func ExtractMessageWithReasoningPolicy(chunks []string, preferReasoningContent b
acc := newToolCallAccumulator()

for _, chunk := range chunks {
line := strings.TrimPrefix(chunk, "data: ")
line := strings.TrimPrefix(chunk, "data:")
line = strings.TrimSpace(line)
if line == "" || line == "[DONE]" {
continue
Expand Down
160 changes: 160 additions & 0 deletions coordinator/tests/api/inference/contracts/sse_optional_space_test.go
Original file line number Diff line number Diff line change
@@ -0,0 +1,160 @@
package inference_test

import (
"context"
"encoding/json"
"fmt"
"net/http"
"strings"
"testing"
"time"

"github.com/eigeninference/d-inference/coordinator/protocol"
"nhooyr.io/websocket"
)

// The provider's SSE contract makes the space after data: optional. Exercise
// equivalent frames over the encrypted provider WebSocket and real HTTP router,
// including response translation and non-streaming reconstruction.
func TestProviderSSEOptionalSpaceHTTP(t *testing.T) {
for _, endpoint := range []struct{ name, path, fields string }{
{"chat", "/v1/chat/completions", `"messages":[{"role":"user","content":"hi"}],"max_tokens":1000,"stream_options":{"include_usage":true}`},
{"completions", "/v1/completions", `"prompt":"hi","max_tokens":1000`},
{"messages", "/v1/messages", `"messages":[{"role":"user","content":"hi"}],"max_tokens":1000`},
{"responses", "/v1/responses", `"input":"hi","max_output_tokens":1000`},
} {
for _, streaming := range []bool{false, true} {
for _, spaced := range []bool{true, false} {
t.Run(fmt.Sprintf("%s/stream=%t/space=%t", endpoint.name, streaming, spaced), func(t *testing.T) {
_, reg, _, ts := setupTestServer(t)
defer ts.Close()
ctx, cancel := context.WithTimeout(context.Background(), 20*time.Second)
defer cancel()
p := startBurstProvider(t, ctx, ts, reg, func(ctx context.Context, p *burstProvider, req protocol.InferenceRequestMessage) {
for _, frame := range []string{chatContentChunk("Hello "), chatContentChunk("world"), chatFinishChunk("stop"), chatUsageChunk(10, 2), "data: [DONE]\n\n"} {
if !spaced {
frame = strings.Replace(frame, "data: ", "data:", 1)
}
p.writeChunk(t, ctx, req, frame)
}
p.writeComplete(t, ctx, req, protocol.UsageInfo{PromptTokens: 10, CompletionTokens: 2})
})
defer p.conn.Close(websocket.StatusNormalClosure, "")
body := fmt.Sprintf(`{"model":%q,%s,"stream":%t}`, burstTestModel, endpoint.fields, streaming)
status, headers, raw := streamRequest(t, ctx, ts, endpoint.path, body)
if status != http.StatusOK {
t.Fatalf("status=%d body=%s", status, raw)
}
if streaming && headers.Get("Content-Type") != "text/event-stream" {
t.Fatalf("content-type=%q", headers.Get("Content-Type"))
}
got := optionalSpaceHTTPText(t, endpoint.name, streaming, raw)
if got != "Hello world" {
t.Errorf("response lost provider text: got %q, want %q; body=%s", got, "Hello world", raw)
}
})
}
}
}
}

type optionalSpaceHTTPResponse struct {
Type string `json:"type"`
Delta json.RawMessage `json:"delta"`
Error json.RawMessage `json:"error"`
Choices []struct {
Text string `json:"text"`
FinishReason *string `json:"finish_reason"`
Delta struct {
Content string `json:"content"`
} `json:"delta"`
Message struct {
Content string `json:"content"`
} `json:"message"`
} `json:"choices"`
Content []struct {
Text string `json:"text"`
} `json:"content"`
Output []struct {
Content []struct {
Text string `json:"text"`
} `json:"content"`
} `json:"output"`
}

func optionalSpaceHTTPText(t *testing.T, endpoint string, streaming bool, raw []byte) string {
t.Helper()
var text strings.Builder
decode := func(payload []byte) optionalSpaceHTTPResponse {
t.Helper()
var result optionalSpaceHTTPResponse
if err := json.Unmarshal(payload, &result); err != nil {
t.Fatalf("invalid HTTP response: %v; payload=%s", err, payload)
}
if len(result.Error) > 0 && string(result.Error) != "null" {
t.Fatalf("unexpected error: %s", payload)
}
return result
}
if !streaming {
response := decode(raw)
for _, choice := range response.Choices {
text.WriteString(choice.Text)
text.WriteString(choice.Message.Content)
}
for _, block := range response.Content {
text.WriteString(block.Text)
}
for _, item := range response.Output {
for _, block := range item.Content {
text.WriteString(block.Text)
}
}
return text.String()
}
terminals, finishes := 0, 0
for _, line := range strings.Split(string(raw), "\n") {
payload, data := strings.CutPrefix(line, "data:")
if !data {
continue
}
payload = strings.TrimSpace(payload)
if payload == "[DONE]" {
terminals++
continue
}
event := decode([]byte(payload))
for _, choice := range event.Choices {
text.WriteString(choice.Text)
text.WriteString(choice.Delta.Content)
if choice.FinishReason != nil && *choice.FinishReason != "" {
finishes++
}
}
switch event.Type {
case "response.output_text.delta":
var delta string
if err := json.Unmarshal(event.Delta, &delta); err != nil {
t.Fatal(err)
}
text.WriteString(delta)
case "content_block_delta":
var delta struct {
Text string `json:"text"`
}
if err := json.Unmarshal(event.Delta, &delta); err != nil {
t.Fatal(err)
}
text.WriteString(delta.Text)
case "response.completed", "message_stop":
terminals++
}
}
if terminals != 1 {
t.Errorf("terminal count=%d, want1; body=%s", terminals, raw)
}
if (endpoint == "chat" || endpoint == "completions") && finishes != 1 {
t.Errorf("finish count=%d, want1; body=%s", finishes, raw)
}
return text.String()
}
4 changes: 3 additions & 1 deletion docs/consumer/quickstart.md
Original file line number Diff line number Diff line change
@@ -1,6 +1,6 @@
# Quickstart: first request in five steps

> Last updated: 2026-10-05
> Last updated: 2026-10-08

Get an API key from the console, list the models your key can use, and make your first chat completion against `https://api.darkbloom.dev` — first with `curl`, then from the OpenAI and Anthropic SDKs. For developers integrating the API; each step is one action. Route details for everything used here are in [`../reference/api-contracts.md`](../reference/api-contracts.md).

Expand Down Expand Up @@ -77,6 +77,8 @@ curl -N https://api.darkbloom.dev/v1/chat/completions \

You receive `text/event-stream` frames, one `data: {...}` chunk per provider token group, a final frame carrying `usage` and `finish_reason`, then exactly one `data: [DONE]`. There are no keepalive comments; silence means no token has been produced yet (`handleStreamingResponseWithFirstChunkAndError`, `coordinator/internal/inference/relay/consumer_stream.go`).

When parsing a `data:` field, allow the optional space after the colon. Both `data:{...}` and `data: {...}` carry JSON; see the [SSE framing contract](../reference/api-contracts.md#sse-framing).

### 6. Use the OpenAI SDK

The OpenAI clients append `/chat/completions` to the base URL, so point them at `/v1`:
Expand Down
7 changes: 7 additions & 0 deletions docs/reference/api-contracts.md
Original file line number Diff line number Diff line change
Expand Up @@ -953,6 +953,13 @@ root response marked `incomplete` because generation reached its output limit.

Built by `handleStreamingResponseWithFirstChunkAndError` (`coordinator/internal/inference/relay/consumer_stream.go`), `coordinator/api/inference/response/sse_response.go`, and `coordinator/api/inference/response/chat_metadata_stream.go`; ordering guarantees come from the dispatch state machine in `coordinator/api/inference/dispatch.go`.

Provider JSON data fields may include or omit the single space after `data:`.
Both forms preserve text when reconstructing non-streaming responses for all
four inference endpoints (`ExtractMessageWithReasoningPolicy`,
`coordinator/api/inference/response/stream_message.go`) and translating streams
for Completions, Messages and Responses (`parseStreamChunkChoices`,
`coordinator/api/inference/response/responses_stream.go`).

1. **Deferred commit.** No status line, headers, or bytes are written until the first *content* chunk arrives from a provider (`commitFirstContent`). Until then the coordinator can still fail over to another provider or return a JSON error with a real status code (`Recorder.PreContentTerminal`, `coordinator/internal/inference/rejection/terminal.go`). Clients see a delayed 200, never a 200 that turns into an error mid-preamble.
2. **Headers at commit**: `Content-Type: text/event-stream`, `Cache-Control: no-cache`, `Connection: keep-alive`, `X-Inference-Job-ID` (`WriteSSEResponseHeader`), plus `X-Timing` and the `X-Provider-*` headers.
3. **Each provider chunk** is forwarded as one `data: <json>\n\n` event after `NormalizeSSEChunk` (`coordinator/internal/inference/sse/sse_normalize.go`); the coordinator does not re-tokenise or coalesce content. Chunks that arrive before commit are buffered (`chunkBufferSize` = 256).
Expand Down
Loading