Add Chat Completions wrapper with reasoning conversion

Implements Phase 5: OpenAI Chat Completions compatibility layer

Features:
- Wraps Responses API for single source of truth
- Automatically enables reasoning generation
- Converts reasoning items to <think> tags for Open WebUI
- Maintains OpenAI-compatible chat completion format
- Supports both streaming and non-streaming modes
- Pipeline prefix preservation for model names
- System message handling

Architecture:
- Service layer calls Responses API internally
- Streams word-by-word for smooth UX
- Reasoning displayed in thought bubbles (Open WebUI)
- Main response shown separately from thinking

Error Handling:
- Enhanced exception types (RateLimitError, ContextLengthError)
- OpenAI-compatible error format
- Graceful error propagation from Responses API

Testing:
- 6 unit tests for chat router functionality
- 6 unit tests for streaming wrapper behavior
- Total: 12 tests with comprehensive coverage

🤖 Generated with [Claude Code](https://claude.com/claude-code)

Co-Authored-By: Claude <noreply@anthropic.com>
This commit is contained in:
2025-12-06 19:38:35 +01:00
co-authored by Claude
parent ff6c3cf1b5
commit 5e40704d91
4 changed files with 509 additions and 46 deletions
+160 -44
View File
@@ -1,12 +1,15 @@
"""
Chat completion service.
Currently returns mock responses with lorem ipsum.
TODO: Integrate with Ollama/PydanticAI in future.
Wrapper around Responses API that converts to Chat Completions format.
Embeds reasoning in <think> tags for Open WebUI compatibility.
"""
import asyncio
import time
import uuid
from typing import AsyncGenerator
from src.agents.registry import ModelRegistry
from src.chat import constants
from src.chat.schemas import (
ChatCompletionChunk,
@@ -20,29 +23,67 @@ from src.chat.schemas import (
)
# Mock lorem ipsum response
MOCK_RESPONSE = (
"Lorem ipsum dolor sit amet, consectetur adipiscing elit. "
"Sed do eiusmod tempor incididunt ut labore et dolore magna aliqua. "
"Ut enim ad minim veniam, quis nostrud exercitation ullamco laboris."
)
async def create_chat_completion(
request: ChatCompletionRequest,
) -> ChatCompletionResponse:
"""
Create chat completion (mock implementation).
Create chat completion by wrapping Responses API.
Converts Responses API output to Chat Completions format with
reasoning embedded in <think> tags for Open WebUI.
Args:
request: Chat completion request
Returns:
Mock chat completion response with lorem ipsum
Chat completion response with reasoning as <think> tags
"""
completion_id = f"chatcmpl-{uuid.uuid4().hex[:24]}"
created_at = int(time.time())
# Strip pipeline prefix if present
model_id = request.model
if "." in model_id:
model_id = model_id.split(".", 1)[1]
# Get agent and generate response
agent = ModelRegistry.get_agent(model_id)
# Convert Chat messages to Responses format
input_messages = [
{"role": msg.role, "content": msg.content}
for msg in request.messages
]
# Collect output items from agent (with reasoning enabled)
output_items = []
async for item in agent.generate_response(
messages=input_messages,
reasoning={"effort": "medium", "summary": "auto"}, # Enable reasoning
temperature=request.temperature or 1.0,
max_tokens=request.max_tokens,
stop=request.stop if isinstance(request.stop, list) else ([request.stop] if request.stop else None),
):
output_items.append(item)
# Build content with <think> tags
content_parts = []
# Add reasoning as <think> blocks
for item in output_items:
if item.type == "reasoning":
reasoning_text = "\n".join(item.data.get("summary", []))
content_parts.append(f"<think>\n{reasoning_text}\n</think>\n\n")
elif item.type == "message":
content_parts.append(item.data["content"][0]["text"])
content = "".join(content_parts)
# Calculate token usage (approximate)
prompt_text = " ".join(m.content for m in request.messages)
prompt_tokens = len(prompt_text) // 4
completion_tokens = len(content) // 4
return ChatCompletionResponse(
id=completion_id,
object=constants.CHAT_COMPLETION_OBJECT,
@@ -53,16 +94,15 @@ async def create_chat_completion(
index=0,
message=ChatMessage(
role=constants.ROLE_ASSISTANT,
content=MOCK_RESPONSE,
content=content,
),
finish_reason=constants.FINISH_REASON_STOP,
)
],
usage=ChatCompletionUsage(
prompt_tokens=len(" ".join(m.content for m in request.messages).split()),
completion_tokens=len(MOCK_RESPONSE.split()),
total_tokens=len(" ".join(m.content for m in request.messages).split())
+ len(MOCK_RESPONSE.split()),
prompt_tokens=prompt_tokens,
completion_tokens=completion_tokens,
total_tokens=prompt_tokens + completion_tokens,
),
)
@@ -71,20 +111,33 @@ async def create_chat_completion_stream(
request: ChatCompletionRequest,
) -> AsyncGenerator[ChatCompletionChunk, None]:
"""
Create streaming chat completion (mock implementation).
Create streaming chat completion by wrapping Responses API.
Streams reasoning in <think> tags followed by message content.
Args:
request: Chat completion request with stream=True
Yields:
Mock chat completion chunks with lorem ipsum
Chat completion chunks with reasoning as <think> tags
"""
completion_id = f"chatcmpl-{uuid.uuid4().hex[:24]}"
created_at = int(time.time())
# Split response into words for streaming simulation
words = MOCK_RESPONSE.split()
# Strip pipeline prefix if present
model_id = request.model
if "." in model_id:
model_id = model_id.split(".", 1)[1]
# Get agent
agent = ModelRegistry.get_agent(model_id)
# Convert Chat messages to Responses format
input_messages = [
{"role": msg.role, "content": msg.content}
for msg in request.messages
]
# First chunk with role
yield ChatCompletionChunk(
id=completion_id,
@@ -99,23 +152,86 @@ async def create_chat_completion_stream(
)
],
)
# Stream words
for word in words:
yield ChatCompletionChunk(
id=completion_id,
object=constants.CHAT_COMPLETION_CHUNK_OBJECT,
created=created_at,
model=request.model,
choices=[
ChatCompletionChunkChoice(
index=0,
delta=ChatCompletionChunkDelta(content=f"{word} "),
finish_reason=None,
# Stream from agent with reasoning enabled
in_reasoning = False
async for item in agent.generate_response(
messages=input_messages,
reasoning={"effort": "medium", "summary": "auto"}, # Enable reasoning
temperature=request.temperature or 1.0,
max_tokens=request.max_tokens,
stop=request.stop if isinstance(request.stop, list) else ([request.stop] if request.stop else None),
):
if item.type == "reasoning":
# Start <think> block
if not in_reasoning:
yield ChatCompletionChunk(
id=completion_id,
object=constants.CHAT_COMPLETION_CHUNK_OBJECT,
created=created_at,
model=request.model,
choices=[
ChatCompletionChunkChoice(
index=0,
delta=ChatCompletionChunkDelta(content="<think>\n"),
finish_reason=None,
)
],
)
],
)
in_reasoning = True
# Stream reasoning summary steps
for step in item.data.get("summary", []):
yield ChatCompletionChunk(
id=completion_id,
object=constants.CHAT_COMPLETION_CHUNK_OBJECT,
created=created_at,
model=request.model,
choices=[
ChatCompletionChunkChoice(
index=0,
delta=ChatCompletionChunkDelta(content=f"{step}\n"),
finish_reason=None,
)
],
)
await asyncio.sleep(0.05) # Simulate typing
# Close <think> block
yield ChatCompletionChunk(
id=completion_id,
object=constants.CHAT_COMPLETION_CHUNK_OBJECT,
created=created_at,
model=request.model,
choices=[
ChatCompletionChunkChoice(
index=0,
delta=ChatCompletionChunkDelta(content="</think>\n\n"),
finish_reason=None,
)
],
)
in_reasoning = False
elif item.type == "message":
# Stream message content word by word
text = item.data["content"][0]["text"]
for word in text.split():
yield ChatCompletionChunk(
id=completion_id,
object=constants.CHAT_COMPLETION_CHUNK_OBJECT,
created=created_at,
model=request.model,
choices=[
ChatCompletionChunkChoice(
index=0,
delta=ChatCompletionChunkDelta(content=f"{word} "),
finish_reason=None,
)
],
)
await asyncio.sleep(0.05) # Simulate typing
# Final chunk with finish_reason
yield ChatCompletionChunk(
id=completion_id,
+22 -1
View File
@@ -47,6 +47,27 @@ class ModelNotFoundError(AppException):
class ValidationError(AppException):
"""Raised for validation errors."""
def __init__(self, message: str, details: dict[str, Any] | None = None):
super().__init__(message=message, status_code=422, details=details)
class RateLimitError(AppException):
"""Raised when rate limit is exceeded."""
def __init__(self, message: str = "Rate limit exceeded"):
super().__init__(message=message, status_code=429)
class ContextLengthError(AppException):
"""Raised when context length exceeds model limits."""
def __init__(self, message: str = "Context length exceeded"):
super().__init__(message=message, status_code=400)
class APIError(AppException):
"""Generic API error."""
def __init__(self, message: str, status_code: int = 500):
super().__init__(message=message, status_code=status_code)