-
Notifications
You must be signed in to change notification settings - Fork 353
fix(rag): serve streaming chat completions as text/event-stream (#2837) #2839
New issue
Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.
By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.
Already on GitHub? Sign in to your account
Open
Anai-Guo
wants to merge
3
commits into
containers:main
Choose a base branch
from
Anai-Guo:fix-rag-stream-content-type
base: main
Could not load branches
Branch not found: {{ refName }}
Loading
Could not load tags
Nothing to show
Loading
Are you sure you want to change the base?
Some commits from the old base branch may be removed from the timeline,
and old review comments may become outdated.
+123
−1
Open
Changes from all commits
Commits
Show all changes
3 commits
Select commit
Hold shift + click to select a range
File filter
Filter by extension
Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
There are no files selected for viewing
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -0,0 +1,122 @@ | ||
| import asyncio | ||
| import importlib | ||
| import importlib.util | ||
| import sys | ||
| from importlib.machinery import SourceFileLoader | ||
| from pathlib import Path | ||
| from unittest.mock import MagicMock | ||
|
|
||
| import pytest | ||
|
|
||
| # The RAG proxy is a standalone container script (no ``.py`` extension) that | ||
| # imports a handful of packages which are only installed inside the RAG | ||
| # container image, not in the unit-test environment. We stub the ones that | ||
| # are missing so the module can be imported and its response-construction | ||
| # logic exercised in isolation. | ||
| RAG_FRAMEWORK = Path(__file__).resolve().parents[2] / "container-images" / "scripts" / "rag_framework" | ||
|
|
||
|
|
||
| def _stub_pydantic(): | ||
| module = type(sys)("pydantic") | ||
|
|
||
| class BaseModel: # minimal stand-in; models are never instantiated here | ||
| pass | ||
|
|
||
| def Field(default=None, *args, **kwargs): | ||
| return default | ||
|
|
||
| module.BaseModel = BaseModel | ||
| module.Field = Field | ||
| return module | ||
|
|
||
|
|
||
| def _stub_fastapi(): | ||
| module = type(sys)("fastapi") | ||
|
|
||
| class _App: | ||
| def __init__(self, *args, **kwargs): | ||
| pass | ||
|
|
||
| def _decorator(self, *args, **kwargs): | ||
| def wrap(func): | ||
| return func | ||
|
|
||
| return wrap | ||
|
|
||
| get = post = put = delete = middleware = _decorator | ||
|
|
||
| class HTTPException(Exception): | ||
| def __init__(self, *args, **kwargs): | ||
| super().__init__(kwargs.get("detail", "")) | ||
|
|
||
| module.FastAPI = lambda *a, **k: _App() | ||
| module.HTTPException = HTTPException | ||
| return module | ||
|
|
||
|
|
||
| def _stub_fastapi_responses(): | ||
| module = type(sys)("fastapi.responses") | ||
|
|
||
| class StreamingResponse: | ||
| def __init__(self, content, media_type=None, headers=None, **kwargs): | ||
| self.body_iterator = content | ||
| self.media_type = media_type | ||
| self.headers = headers or {} | ||
|
|
||
| module.StreamingResponse = StreamingResponse | ||
| return module | ||
|
|
||
|
|
||
| def _load_rag_framework(): | ||
| # Optional heavy deps that only ship in the container image. | ||
| for name in ("aiohttp", "openai", "qdrant_client", "uvicorn"): | ||
| if name not in sys.modules: | ||
| try: | ||
| importlib.import_module(name) | ||
| except ImportError: | ||
| sys.modules[name] = MagicMock() | ||
|
|
||
| if "pydantic" not in sys.modules: | ||
| try: | ||
| importlib.import_module("pydantic") | ||
| except ImportError: | ||
| sys.modules["pydantic"] = _stub_pydantic() | ||
|
|
||
| try: | ||
| importlib.import_module("fastapi") | ||
| importlib.import_module("fastapi.responses") | ||
| except ImportError: | ||
| sys.modules["fastapi"] = _stub_fastapi() | ||
| sys.modules["fastapi.responses"] = _stub_fastapi_responses() | ||
|
|
||
| loader = SourceFileLoader("ramalama_rag_framework", str(RAG_FRAMEWORK)) | ||
| spec = importlib.util.spec_from_loader(loader.name, loader) | ||
| module = importlib.util.module_from_spec(spec) | ||
| loader.exec_module(module) | ||
| return module | ||
|
|
||
|
|
||
| @pytest.mark.skipif( | ||
| sys.version_info < (3, 10), | ||
| reason="rag_framework uses PEP 604 unions in class bodies; it only runs in the RAG container image (Python 3.11+)", | ||
| ) | ||
| def test_stream_completion_uses_sse_media_type(): | ||
| """Regression test for #2837: streaming chat completions must advertise | ||
| ``text/event-stream`` so strict OpenAI clients (e.g. Open WebUI) accept | ||
| the SSE body instead of rejecting it as ``text/plain``.""" | ||
| rag_framework = _load_rag_framework() | ||
|
|
||
| # Bypass __init__: it would try to open Qdrant/OpenAI clients. The | ||
| # streaming generator is not iterated, so ``self`` is never dereferenced. | ||
| service = rag_framework.RagService.__new__(rag_framework.RagService) | ||
|
|
||
| response = asyncio.run(service._stream_completion("cmpl-id", 0, MagicMock(), [])) | ||
|
|
||
| assert response.media_type == "text/event-stream" | ||
| # SSE responses must not be cached. | ||
| headers = {key.lower(): value for key, value in dict(response.headers).items()} | ||
| assert headers.get("cache-control") == "no-cache" | ||
|
|
||
|
|
||
| if __name__ == "__main__": | ||
| raise SystemExit(pytest.main([__file__, "-v"])) | ||
Add this suggestion to a batch that can be applied as a single commit.
This suggestion is invalid because no changes were made to the code.
Suggestions cannot be applied while the pull request is closed.
Suggestions cannot be applied while viewing a subset of changes.
Only one suggestion per line can be applied in a batch.
Add this suggestion to a batch that can be applied as a single commit.
Applying suggestions on deleted lines is not supported.
You must change the existing code in this line in order to create a valid suggestion.
Outdated suggestions cannot be applied.
This suggestion has been applied or marked resolved.
Suggestions cannot be applied from pending reviews.
Suggestions cannot be applied on multi-line comments.
Suggestions cannot be applied while the pull request is queued to merge.
Suggestion cannot be applied right now. Please check back later.
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
🩺 Stability & Availability | 🟠 Major | ⚡ Quick win
🧩 Analysis chain
🏁 Script executed:
Repository: containers/ramalama
Length of output: 3857
Move the RAG framework bootstrap behind the version guard.
SourceFileLoader(...).exec_module(module)runs during test collection, so Python 3.9 can hit the PEP 604 syntax inrag_frameworkbeforepytest.mark.skipiftakes effect. Loadrag_frameworkonly insidetest_stream_completion_uses_sse_media_typeafter checkingsys.version_info, or addpytest.skip(..., allow_module_level=True)before the bootstrap code.🤖 Prompt for AI Agents
Source: Coding guidelines