Skip to content

Add OpenAI-compatible API endpoint - #55

Merged
pavelanni merged 9 commits into
mainfrom
feature/openai-compatible-api
May 5, 2026
Merged

pavelanni merged 9 commits into
mainfrom
feature/openai-compatible-api

Conversation

@pavelanni

@pavelanni pavelanni commented May 5, 2026 •

Copy link
Copy Markdown
Collaborator

Summary

Adds OpenAI-compatible Chat Completions API so users can connect
existing chat UIs (Open WebUI, LibreChat, TypingMind) to DocsClaw
instead of building a custom web frontend.

  • POST /v1/chat/completions — full chat completions with
    streaming (SSE) and non-streaming modes
  • GET /v1/models — lists DocsClaw as a single model entry
  • GET /v1/skills — lists agent skills from the agent card

How it works

New internal/openaiapi/ package with a thin translation layer that
converts OpenAI-format requests to DocsClaw's internal llm.Message
format, runs the LLM provider (with tool loop in phase 2), and
returns OpenAI-format responses. Routes sit alongside existing A2A
endpoints on port 8000.

Key design decisions

  • Server-side tool execution — clients see only the final answer
    (tool-call visibility is a planned follow-up)
  • Client-side message history — standard stateless OpenAI behavior
  • System prompt merging — DocsClaw's prompt takes priority;
    client system messages are appended
  • Simulated streaming — response is chunked word-by-word over SSE
    (true token streaming is a future enhancement)
  • No auth — handled by infrastructure (OAuth proxy sidecar on
    OpenShift)

Verified with

  • Open WebUI connected to DocsClaw endpoint
  • Multi-turn conversations with markdown rendering
  • curl tests for all endpoints and error cases

Closes #54

Test plan

  • Unit tests for message conversion (OpenAI ↔ llm.Message)
  • Unit tests for SSE streaming (chunk encoding, newline preservation, [DONE])
  • Integration tests for all three handlers (mock provider)
  • Error handling tests (invalid JSON, empty messages)
  • Phase 1 and phase 2 handler paths
  • make test — all tests pass
  • make lint — 0 issues
  • Manual curl verification (all endpoints)
  • Open WebUI end-to-end (model selection, chat, markdown rendering)

Summary by CodeRabbit

Release Notes

  • New Features
    • OpenAI-compatible API endpoints now available: chat completions, model listing, and skills discovery.
    • Support for streaming and non-streaming response modes.
    • Fully integrated with existing system prompts and tool capabilities.

pavelanni added 7 commits May 5, 2026 10:25
Issue #54: Add /v1/chat/completions, /v1/models, and /v1/skills
endpoints so users can connect OpenAI-compatible chat UIs.

Assisted-By: Claude (Anthropic AI) <[email protected]>
Signed-off-by: Pavel Anni <[email protected]>
Assisted-By: Claude (Anthropic AI) <[email protected]>
Signed-off-by: Pavel Anni <[email protected]>
Assisted-By: Claude (Anthropic AI) <[email protected]>
Signed-off-by: Pavel Anni <[email protected]>
Assisted-By: Claude (Anthropic AI) <[email protected]>
Signed-off-by: Pavel Anni <[email protected]>
Adds /v1/chat/completions, /v1/models, and /v1/skills endpoints
alongside existing A2A routes on port 8000.

Assisted-By: Claude (Anthropic AI) <[email protected]>
Signed-off-by: Pavel Anni <[email protected]>
Phase 1 was only sending the last user message via Provider.Complete,
discarding prior conversation turns. Switch to CompleteWithTools with
nil tools to preserve full message history for multi-turn conversations.

Assisted-By: Claude (Anthropic AI) <[email protected]>
Signed-off-by: Pavel Anni <[email protected]>
…ring

strings.Fields() was stripping all whitespace including newlines,
causing markdown to render as a single unformatted block. Split by
lines first, then by words within each line, emitting newline chunks
to preserve document structure.

Assisted-By: Claude (Anthropic AI) <[email protected]>
Signed-off-by: Pavel Anni <[email protected]>
@coderabbitai

coderabbitai Bot commented May 5, 2026 •

Copy link
Copy Markdown

Warning

Rate limit exceeded

@pavelanni has exceeded the limit for the number of commits that can be reviewed per hour. Please wait 30 minutes and 52 seconds before requesting another review.

To keep reviews running without waiting, you can enable usage-based add-on for your organization. This allows additional reviews beyond the hourly cap. Account admins can enable it under billing.

⌛ How to resolve this issue?

After the wait time has elapsed, a review can be triggered using the @coderabbitai review command as a PR comment. Alternatively, push new commits to this PR.

We recommend that you space out your commits to avoid hitting the rate limit.

🚦 How do rate limits work?

CodeRabbit enforces hourly rate limits for each developer per organization.

Our paid plans have higher rate limits than the trial, open-source and free plans. In all cases, we re-allow further reviews after a brief timeout.

Please see our FAQ for further information.

ℹ️ Review info
⚙️ Run configuration

Configuration used: Organization UI

Review profile: CHILL

Plan: Enterprise

Run ID: d3fd90e0-cd27-48fc-a428-14b018c31513

📥 Commits

Reviewing files that changed from the base of the PR and between bbb1df8 and 2956c94.

📒 Files selected for processing (5)
  • internal/cmd/serve.go
  • internal/openaiapi/handler.go
  • internal/openaiapi/handler_test.go
  • internal/openaiapi/stream.go
  • internal/openaiapi/stream_test.go
📝 Walkthrough

Walkthrough

This PR implements an OpenAI-compatible HTTP API in DocsClaw with three endpoints (POST /v1/chat/completions, GET /v1/models, GET /v1/skills) that translates OpenAI message format to internal llm.Message structures, optionally executes an agentic tool loop, and returns responses in both streaming (SSE) and non-streaming JSON formats.

Changes

OpenAI-Compatible API Implementation

Layer / File(s) Summary
Data Structures
internal/openaiapi/types.go, internal/openaiapi/types_test.go
Defines OpenAI request/response types (ChatCompletionRequest, ChatCompletionResponse, ChatCompletionChunk), error envelopes, and model/skill objects. Implements ConvertMessages (filters system messages, merges server + client prompts), BuildResponse (formats chat completion responses), and GenerateID (chatcmpl-* identifiers).
SSE Streaming
internal/openaiapi/stream.go, internal/openaiapi/stream_test.go
Implements StreamResponse (emits SSE chunks with assistant role, streams content as word-sized events, terminates with [DONE]), StreamError (sends error events as SSE), and chunking helpers. Tests validate content-type headers, chunk parsing, newline preservation, and termination semantics.
HTTP Handlers
internal/openaiapi/handler.go, internal/openaiapi/handler_test.go
Implements Handler struct with ChatCompletion (1MB request limit, message conversion, provider/tool-loop selection, SSE or JSON responses), Models (single-model list with agent name in description), and Skills (agent card skill listing). Includes request validation, error handling, and phase-1 compatibility (nil registry → direct provider call). Tests cover non-streaming, streaming, invalid JSON, empty messages, model listing, and skill listing scenarios.
Server Integration
internal/cmd/serve.go
Instantiates openaiapi.Handler with LLM provider, merged system prompt + skills summary, tool registry, loop config, and agent metadata. Registers /v1/chat/completions, /v1/models, and /v1/skills routes on the main mux. Adds startup log entry for OpenAI-compatible API enabled.
Specification & Planning
docs/superpowers/specs/2026-05-05-openai-compatible-api-design.md, docs/superpowers/plans/2026-05-05-openai-compatible-api.md
Design spec documents endpoint behavior, request/response mapping, streaming semantics, system prompt merging rules, model selection, tool visibility, error formats, and testing strategy. Implementation plan breaks work into six tasks with concrete file structure, code examples, manual verification steps, and test/lint/build validation.

Sequence Diagram

sequenceDiagram
    actor Client
    participant Handler as HTTP Handler<br/>(/v1/chat/completions)
    participant Converter as Message<br/>Converter
    participant Provider as LLM Provider
    participant ToolLoop as Tool Loop<br/>(if enabled)
    participant SSE as SSE Streamer<br/>(if streaming)

    Client->>Handler: POST /v1/chat/completions<br/>(with messages, stream flag)
    Handler->>Handler: Decode & validate request<br/>(1MB limit, non-empty messages)
    Handler->>Converter: ConvertMessages(client msgs,<br/>server prompt)
    Converter-->>Handler: Internal messages<br/>+ merged system prompt
    
    alt Registry configured
        Handler->>ToolLoop: RunToolLoop(system prompt<br/>+ messages, tools)
        ToolLoop->>Provider: Call LLM with tools
        Provider-->>ToolLoop: Response with<br/>tool calls/content
        ToolLoop-->>Handler: Final content & usage
    else Registry not configured (Phase 1)
        Handler->>Provider: CompleteWithTools(messages)
        Provider-->>Handler: Response with<br/>content & usage
    end

    alt Stream requested
        Handler->>SSE: StreamResponse(content)
        SSE->>Client: text/event-stream headers
        SSE->>Client: Assistant role chunk
        SSE->>Client: Word-sized content chunks
        SSE->>Client: Finish reason chunk
        SSE->>Client: data: [DONE]\n\n
    else Non-streaming
        Handler->>Handler: BuildResponse(id, model,<br/>content, usage)
        Handler->>Client: application/json<br/>ChatCompletionResponse
    end
Loading

Estimated code review effort

🎯 4 (Complex) | ⏱️ ~40 minutes

🚥 Pre-merge checks | ✅ 4 | ❌ 1

❌ Failed checks (1 warning)

Check name Status Explanation Resolution
Docstring Coverage ⚠️ Warning Docstring coverage is 20.00% which is insufficient. The required threshold is 80.00%. Write docstrings for the functions missing them to satisfy the coverage threshold.
✅ Passed checks (4 passed)
Check name Status Explanation
Description Check ✅ Passed Check skipped - CodeRabbit’s high-level summary is enabled.
Title check ✅ Passed The title accurately and concisely describes the main change: adding an OpenAI-compatible API endpoint, which is the primary objective of this PR.
Linked Issues check ✅ Passed The PR fully implements all key objectives from issue #54: /v1/chat/completions endpoint with streaming and non-streaming modes, /v1/models endpoint, message conversion layer, SSE streaming support, server-side tool execution, and coexistence with A2A endpoints.
Out of Scope Changes check ✅ Passed All changes are scoped to implementing the OpenAI-compatible API. The PR adds only the required endpoints, types, handlers, and streaming logic, with no unrelated changes.

✏️ Tip: You can configure your own custom pre-merge checks in the settings.

✨ Finishing Touches
🧪 Generate unit tests (beta)
  • Create PR with unit tests
  • Commit unit tests in branch feature/openai-compatible-api

Thanks for using CodeRabbit! It's free for OSS, and your support helps us grow. If you like it, consider giving us a shout-out.

❤️ Share

Comment @coderabbitai help to get the list of available commands and usage tips.

Adds http.MaxBytesReader to prevent oversized requests from consuming
excessive memory.

Assisted-By: Claude (Anthropic AI) <[email protected]>
Signed-off-by: Pavel Anni <[email protected]>
@pavelanni
pavelanni marked this pull request as ready for review May 5, 2026 15:26

@coderabbitai coderabbitai Bot left a comment

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Actionable comments posted: 3

Caution

Some comments are outside the diff and can’t be posted inline due to platform limitations.

⚠️ Outside diff range comments (1)
internal/cmd/serve.go (1)

457-476: ⚠️ Potential issue | 🟠 Major | ⚡ Quick win

WriteTimeout: 120s will truncate long SSE streams from /v1/chat/completions.

The new /v1/chat/completions streaming path shares the main server's WriteTimeout of 120s (line 475). The agentic tool loop has a default of 10 iterations with no aggregate timeout—only individual LLM calls enforce a 45-second timeout. A multi-iteration loop with tool execution can easily exceed 120 seconds; when WriteTimeout fires, net/http closes the connection mid-SSE, causing clients to lose the response without the final data: [DONE] marker.

Options:

  • Set WriteTimeout: 0 on the main server and rely on ReadTimeout / per-request context cancellation. This is acceptable since individual LLM calls and tool execution already enforce their own timeouts.
  • Or split streaming endpoints to a dedicated http.Server with WriteTimeout: 0.
  • Or use http.TimeoutHandler selectively for non-streaming routes.

If you choose the first option, also confirm that A2A handlers don't depend on WriteTimeout to bound request duration.

🤖 Prompt for AI Agents
Verify each finding against current code. Fix only still-valid issues, skip the
rest with a brief reason, keep changes minimal, and validate.

In `@internal/cmd/serve.go` around lines 457 - 476, The server's WriteTimeout
(WriteTimeout: 120 * time.Second) will truncate long SSE streams from the
streaming endpoint handled by openaiHandler.ChatCompletion
(/v1/chat/completions); change the server setup so streaming responses are not
cut off—either set WriteTimeout to 0 on the main http.Server instance (server
with Addr, Handler mux, ReadTimeout, WriteTimeout) to disable global write
deadlines, or move the streaming route to a separate http.Server with
WriteTimeout: 0 while keeping the current WriteTimeout for non-streaming routes,
and ensure any A2A handlers or other request flows do not rely on WriteTimeout
for bounding request duration.
🧹 Nitpick comments (1)
internal/openaiapi/handler_test.go (1)

67-81: ⚡ Quick win

Assert usage fields in the non-streaming success test.

mockProvider.CompleteWithTools returns token usage, but this test currently validates only object/choice/message fields. Add explicit checks for resp.Usage.PromptTokens, CompletionTokens, and TotalTokens to lock the response contract.

🤖 Prompt for AI Agents
Verify each finding against current code. Fix only still-valid issues, skip the
rest with a brief reason, keep changes minimal, and validate.

In `@internal/openaiapi/handler_test.go` around lines 67 - 81, The test currently
verifies resp.Object/Choices/Message/FinishReason but omits token usage; update
the non-streaming success test that calls mockProvider.CompleteWithTools to
assert resp.Usage.PromptTokens, resp.Usage.CompletionTokens, and
resp.Usage.TotalTokens match the expected values returned by the mock (add
checks similar to the other t.Errorf/t.Fatalf assertions), so the response
contract includes usage fields alongside object/choice/message validations.
🤖 Prompt for all review comments with AI agents
Verify each finding against current code. Fix only still-valid issues, skip the
rest with a brief reason, keep changes minimal, and validate.

Inline comments:
In `@internal/openaiapi/handler_test.go`:
- Line 49: Replace all usages of httptest.NewRequest in
internal/openaiapi/handler_test.go with
httptest.NewRequestWithContext(context.Background(), ...) (there are 8 instances
flagged) so each test request is created with an explicit context; update the
import list to include "context" if it's not already imported, and ensure each
call site (the httptest.NewRequest(...) calls around lines where req is
constructed) is changed to use NewRequestWithContext(context.Background(),
http.MethodPost, "/v1/chat/completions", bytes.NewReader(b)) or the appropriate
method/URL/body for that test.

In `@internal/openaiapi/handler.go`:
- Around line 28-34: The JSON decode currently treats an http.MaxBytesError as
invalid_json/400; update the ChatCompletionRequest decode block (where r.Body =
http.MaxBytesReader(...) and json.NewDecoder(r.Body).Decode(&req) is called) to
detect a body-size overflow by using errors.As(err, &maxErr) (add "errors" to
imports) and, if it is a *http.MaxBytesError, call writeError with
http.StatusRequestEntityTooLarge (413) and a payload-specific error code/message
(e.g., "payload_too_large" and maxErr.Error()); otherwise keep the existing
invalid_json/400 behavior.

In `@internal/openaiapi/stream.go`:
- Around line 39-76: The stream code in stream.go currently uses strings.Fields
inside the loop which collapses and strips whitespace; change the chunking to
preserve exact whitespace by tokenizing the original line without normalizing
separators (for example iterate over the line's runes/bytes and emit tokens at
word boundaries while keeping intervening spaces/tabs/newlines as separate
tokens, or use a regex that captures both non-whitespace and whitespace runs)
instead of strings.Fields, and keep emitting chunks via
writeChunk/ChatCompletionChunk with Delta.Content set to those preserved tokens;
also update TestStreamResponsePreservesNewlines to include cases like "    code
line\n\thello\nfoo  bar" to assert streaming output exactly matches
BuildResponse.

---

Outside diff comments:
In `@internal/cmd/serve.go`:
- Around line 457-476: The server's WriteTimeout (WriteTimeout: 120 *
time.Second) will truncate long SSE streams from the streaming endpoint handled
by openaiHandler.ChatCompletion (/v1/chat/completions); change the server setup
so streaming responses are not cut off—either set WriteTimeout to 0 on the main
http.Server instance (server with Addr, Handler mux, ReadTimeout, WriteTimeout)
to disable global write deadlines, or move the streaming route to a separate
http.Server with WriteTimeout: 0 while keeping the current WriteTimeout for
non-streaming routes, and ensure any A2A handlers or other request flows do not
rely on WriteTimeout for bounding request duration.

---

Nitpick comments:
In `@internal/openaiapi/handler_test.go`:
- Around line 67-81: The test currently verifies
resp.Object/Choices/Message/FinishReason but omits token usage; update the
non-streaming success test that calls mockProvider.CompleteWithTools to assert
resp.Usage.PromptTokens, resp.Usage.CompletionTokens, and resp.Usage.TotalTokens
match the expected values returned by the mock (add checks similar to the other
t.Errorf/t.Fatalf assertions), so the response contract includes usage fields
alongside object/choice/message validations.
🪄 Autofix (Beta)

Fix all unresolved CodeRabbit comments on this PR:

  • Push a commit to this branch (recommended)
  • Create a new PR with the fixes

ℹ️ Review info
⚙️ Run configuration

Configuration used: Organization UI

Review profile: CHILL

Plan: Enterprise

Run ID: b2e0d42a-7daf-458c-b1f6-cd1e8acfe83c

📥 Commits

Reviewing files that changed from the base of the PR and between 897c35b and bbb1df8.

📒 Files selected for processing (9)
  • docs/superpowers/plans/2026-05-05-openai-compatible-api.md
  • docs/superpowers/specs/2026-05-05-openai-compatible-api-design.md
  • internal/cmd/serve.go
  • internal/openaiapi/handler.go
  • internal/openaiapi/handler_test.go
  • internal/openaiapi/stream.go
  • internal/openaiapi/stream_test.go
  • internal/openaiapi/types.go
  • internal/openaiapi/types_test.go

Messages: []ChatMessage{{Role: "user", Content: "Hi"}},
}
b, _ := json.Marshal(body)
req := httptest.NewRequest(http.MethodPost, "/v1/chat/completions", bytes.NewReader(b))

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

⚠️ Potential issue | 🟠 Major | ⚡ Quick win

🧩 Analysis chain

🏁 Script executed:

#!/bin/bash
# Verify remaining noctx patterns in tests
rg -nP '\bhttptest\.NewRequest\s*\(' --type=go

Repository: redhat-et/docsclaw

Length of output: 986


Replace httptest.NewRequest with httptest.NewRequestWithContext across this file.

The noctx linter flags all 8 instances in this test file and will block CI. Use httptest.NewRequestWithContext(context.Background(), ...) for request construction.

Affected lines and suggested patch
-req := httptest.NewRequest(http.MethodPost, "/v1/chat/completions", bytes.NewReader(b))
+req := httptest.NewRequestWithContext(context.Background(), http.MethodPost, "/v1/chat/completions", bytes.NewReader(b))

-req := httptest.NewRequest(http.MethodPost, "/v1/chat/completions", bytes.NewReader(b))
+req := httptest.NewRequestWithContext(context.Background(), http.MethodPost, "/v1/chat/completions", bytes.NewReader(b))

-req := httptest.NewRequest(http.MethodPost, "/v1/chat/completions",
+req := httptest.NewRequestWithContext(context.Background(), http.MethodPost, "/v1/chat/completions",
 	strings.NewReader("{invalid json"))

Lines: 49, 97, 127, 162, 190, 233, 268, 305

🧰 Tools
🪛 golangci-lint (2.12.1)

[error] 49-49: net/http/httptest.NewRequest must not be called. use net/http/httptest.NewRequestWithContext

(noctx)

🤖 Prompt for AI Agents
Verify each finding against current code. Fix only still-valid issues, skip the
rest with a brief reason, keep changes minimal, and validate.

In `@internal/openaiapi/handler_test.go` at line 49, Replace all usages of
httptest.NewRequest in internal/openaiapi/handler_test.go with
httptest.NewRequestWithContext(context.Background(), ...) (there are 8 instances
flagged) so each test request is created with an explicit context; update the
import list to include "context" if it's not already imported, and ensure each
call site (the httptest.NewRequest(...) calls around lines where req is
constructed) is changed to use NewRequestWithContext(context.Background(),
http.MethodPost, "/v1/chat/completions", bytes.NewReader(b)) or the appropriate
method/URL/body for that test.

Comment thread internal/openaiapi/handler.go Resolved
Comment thread internal/openaiapi/stream.go Resolved
- Distinguish MaxBytesError (413) from invalid JSON (400)
- Preserve exact whitespace in SSE streaming (indentation, tabs,
  multiple spaces) by tokenizing into whitespace/non-whitespace runs
  instead of using strings.Fields
- Remove WriteTimeout on main server to avoid truncating SSE streams
  and long-running agentic tool loops
- Add usage token assertions to handler test

Assisted-By: Claude (Anthropic AI) <[email protected]>
Signed-off-by: Pavel Anni <[email protected]>
@pavelanni
pavelanni merged commit f2c6e85 into main May 5, 2026
3 checks passed
@pavelanni
pavelanni deleted the feature/openai-compatible-api branch May 5, 2026 16:01
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

Add OpenAI-compatible API endpoint

1 participant