Repository navigation
Add OpenAI-compatible API endpoint - #55
Conversation
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]>
|
Warning Rate limit exceeded
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 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 configurationConfiguration used: Organization UI Review profile: CHILL Plan: Enterprise Run ID: 📒 Files selected for processing (5)
📝 WalkthroughWalkthroughThis PR implements an OpenAI-compatible HTTP API in DocsClaw with three endpoints ( ChangesOpenAI-Compatible API Implementation
Sequence DiagramsequenceDiagram
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
Estimated code review effort🎯 4 (Complex) | ⏱️ ~40 minutes 🚥 Pre-merge checks | ✅ 4 | ❌ 1❌ Failed checks (1 warning)
✅ Passed checks (4 passed)
✏️ Tip: You can configure your own custom pre-merge checks in the settings. ✨ Finishing Touches🧪 Generate unit tests (beta)
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. Comment |
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]>
There was a problem hiding this comment.
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: 120swill truncate long SSE streams from/v1/chat/completions.The new
/v1/chat/completionsstreaming path shares the main server'sWriteTimeoutof 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; whenWriteTimeoutfires,net/httpcloses the connection mid-SSE, causing clients to lose the response without the finaldata: [DONE]marker.Options:
- Set
WriteTimeout: 0on the main server and rely onReadTimeout/ 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.ServerwithWriteTimeout: 0.- Or use
http.TimeoutHandlerselectively for non-streaming routes.If you choose the first option, also confirm that A2A handlers don't depend on
WriteTimeoutto 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 winAssert
usagefields in the non-streaming success test.
mockProvider.CompleteWithToolsreturns token usage, but this test currently validates only object/choice/message fields. Add explicit checks forresp.Usage.PromptTokens,CompletionTokens, andTotalTokensto 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
📒 Files selected for processing (9)
docs/superpowers/plans/2026-05-05-openai-compatible-api.mddocs/superpowers/specs/2026-05-05-openai-compatible-api-design.mdinternal/cmd/serve.gointernal/openaiapi/handler.gointernal/openaiapi/handler_test.gointernal/openaiapi/stream.gointernal/openaiapi/stream_test.gointernal/openaiapi/types.gointernal/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)) |
There was a problem hiding this comment.
🧩 Analysis chain
🏁 Script executed:
#!/bin/bash
# Verify remaining noctx patterns in tests
rg -nP '\bhttptest\.NewRequest\s*\(' --type=goRepository: 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.
- 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]>
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 withstreaming (SSE) and non-streaming modes
GET /v1/models— lists DocsClaw as a single model entryGET /v1/skills— lists agent skills from the agent cardHow it works
New
internal/openaiapi/package with a thin translation layer thatconverts OpenAI-format requests to DocsClaw's internal
llm.Messageformat, 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
(tool-call visibility is a planned follow-up)
client system messages are appended
(true token streaming is a future enhancement)
OpenShift)
Verified with
Closes #54
Test plan
make test— all tests passmake lint— 0 issuesSummary by CodeRabbit
Release Notes