Repository navigation
Refa: restore openai-compatible chat completions api - #14380
Conversation
📝 WalkthroughWalkthroughA new OpenAI-compatible chat completion endpoint is added at Changes
Sequence Diagram(s)sequenceDiagram
participant Client
participant Auth
participant OpenAI_API
participant ChatService
participant LLM
participant ReferenceBuilder
Client->>Auth: POST /openai/{chat_id}/chat/completions
Auth->>OpenAI_API: authenticated request
OpenAI_API->>OpenAI_API: validate payload (messages, schema)
OpenAI_API->>ChatService: verify chat ownership & resolve model
ChatService-->>OpenAI_API: chat metadata / effective model
alt Streaming
OpenAI_API->>LLM: stream request (model, messages, filters)
LLM-->>OpenAI_API: incremental tokens / chunks
OpenAI_API->>ReferenceBuilder: assemble reference chunks (optional)
OpenAI_API-->>Client: SSE chat.completion.chunk events
OpenAI_API-->>Client: SSE final usage/reference + data:[DONE]
else Non-Streaming
OpenAI_API->>LLM: request (model, messages, filters)
LLM-->>OpenAI_API: full completion
OpenAI_API->>ReferenceBuilder: assemble reference chunks (optional)
OpenAI_API-->>Client: JSON chat.completion with usage/reference
end
Estimated code review effort🎯 4 (Complex) | ⏱️ ~50 minutes Suggested labels
Poem
🚥 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. 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 |
There was a problem hiding this comment.
Actionable comments posted: 4
🧹 Nitpick comments (6)
test/testcases/test_http_api/test_chat_assistant_management/test_chat_sdk_routes_unit.py (2)
1049-1064: Optional: extract the(_ for _ in ()).throw(...)raise-in-lambda idiom into a helper.It’s used four times across the two new tests and is harder to scan than a tiny helper. Pure cleanup; no behavioral change.
♻️ Example helper
+def _raise(exc): + def _f(*_a, **_kw): + raise exc + return _f @@ - monkeypatch.setattr( - module, - "get_tenant_default_model_by_type", - lambda *_args, **_kwargs: (_ for _ in ()).throw(LookupError("Tenant not found!")), - ) + monkeypatch.setattr( + module, + "get_tenant_default_model_by_type", + _raise(LookupError("Tenant not found!")), + )🤖 Prompt for AI Agents
Verify each finding against the current code and only fix it if needed. In `@test/testcases/test_http_api/test_chat_assistant_management/test_chat_sdk_routes_unit.py` around lines 1049 - 1064, Extract the repeated raise-in-lambda idiom "(_ for _ in ()).throw(...)" into a small helper function (e.g., a local helper named raise_in_lambda or make_raiser) and use it in the tests instead of inline lambdas; replace occurrences used when monkeypatching get_tenant_default_model_by_type in the tests that call module.transcription.__wrapped__(), and update the four monkeypatch.setattr invocations to pass a lambda that calls the helper (or the helper itself) so the intent is clearer while keeping behavior identical for _run, _set_request, _DummyUploadFile and transcription references.
1134-1138: Nit:return []inside a generator is misleading.
_TTSOk.ttscontainsyield, so it’s a generator and the[]value passed toreturnis discarded. Either drop the sentinel or convert this to a regular function returning an iterable.♻️ Suggested tweak
class _TTSOk: def tts(self, txt): if not txt: - return [] + return yield f"chunk-{txt}".encode("utf-8")🤖 Prompt for AI Agents
Verify each finding against the current code and only fix it if needed. In `@test/testcases/test_http_api/test_chat_assistant_management/test_chat_sdk_routes_unit.py` around lines 1134 - 1138, The generator method _TTSOk.tts currently uses both yield and "return []", which is confusing because a value returned from a generator is discarded; fix by either turning tts into a normal function that returns an iterable (e.g., return [b"chunk-..."] when txt falsy or a list of chunks) or remove the "return []" sentinel and simply use an empty generator for the falsy case (e.g., if not txt: return followed by no value or replace with "if not txt: return" and keep yields for non-empty txt); update the _TTSOk.tts implementation accordingly.test/benchmark/chat.py (1)
83-83: Add lightweight logging for the new OpenAI benchmark route.Line 83 switches to a new flow, but there’s no request-level trace for diagnostics when benchmark runs fail intermittently.
Proposed patch
import json +import logging import time from typing import Any, Dict, List, Optional from .http_client import HttpClient from .metrics import ChatSample +logger = logging.getLogger(__name__) + @@ def stream_chat_completion( @@ ) -> ChatSample: payload: Dict[str, Any] = {"model": model, "messages": messages, "stream": True} if extra_body: payload["extra_body"] = extra_body + logger.debug( + "Benchmarking OpenAI chat completions route", + extra={"chat_id": chat_id, "stream": True, "has_extra_body": bool(extra_body)}, + ) t0 = time.perf_counter() response = client.request( "POST", f"/openai/{chat_id}/chat/completions",As per coding guidelines,
**/*.py: Add logging for new flows.🤖 Prompt for AI Agents
Verify each finding against the current code and only fix it if needed. In `@test/benchmark/chat.py` at line 83, Add lightweight request-level logging around the new OpenAI benchmark route that builds "/openai/{chat_id}/chat/completions": import and use the module logger in test/benchmark/chat.py and log the outgoing request URL and chat_id (at INFO or DEBUG) before the call, and log the response status (and short body or error) after the call; also catch and log exceptions thrown during the request with contextual fields (chat_id, route) to aid intermittent-failure diagnostics.test/testcases/test_http_api/common.py (1)
339-340: Add debug logs around the migrated helper endpoints.Both updated request paths introduce/restore flow changes, but there is no helper-level logging to aid endpoint migration debugging in API tests.
Proposed patch
from pathlib import Path +import logging import requests from configs import HOST_ADDRESS, VERSION from requests_toolbelt import MultipartEncoder from utils.file_utils import create_txt_file +logger = logging.getLogger(__name__) + @@ def related_questions(auth, payload=None, *, headers=HEADERS): url = f"{HOST_ADDRESS}/api/{VERSION}/searchbots/related_questions" + logger.debug("POST related_questions", extra={"url": url, "has_payload": payload is not None}) res = requests.post(url=url, headers=headers, auth=auth, json=payload) return res.json() @@ def chat_completions_openai(auth, chat_id, payload=None, *, headers=HEADERS): @@ url = f"{HOST_ADDRESS}/api/{VERSION}/openai/{chat_id}/chat/completions" payload = dict(payload or {}) + logger.debug( + "POST chat_completions_openai", + extra={"url": url, "chat_id": chat_id, "stream": bool(payload.get("stream", False))}, + ) res = requests.post(url=url, headers=headers, auth=auth, json=payload) return res.json()As per coding guidelines,
**/*.py: Add logging for new flows.Also applies to: 433-434
🤖 Prompt for AI Agents
Verify each finding against the current code and only fix it if needed. In `@test/testcases/test_http_api/common.py` around lines 339 - 340, Add debug logging around the migrated helper endpoint call that builds url = f"{HOST_ADDRESS}/api/{VERSION}/searchbots/related_questions" and the subsequent requests.post (res variable) so test-level traces capture the request URL, payload, headers/auth and the response status/body; do the same for the other occurrence around the lines using the same endpoint (the variables url, payload, headers, auth, and res identify the spots). Use the project logging pattern (get a logger via logging.getLogger(__name__) or the existing test logger) and emit logger.debug before the post with url and payload and after with res.status_code and a short res.text/JSON extract to aid migration debugging.api/apps/restful_apis/openai_api.py (1)
137-146: Minor: tenant scope inconsistency between_validate_llm_idandget_api_key.
_validate_llm_id(requested_model, current_user.id, …)validates againstcurrent_user.id, but the very next API-key check usesdia.tenant_id. Today both resolve to the same tenant becausediawas just queried withtenant_id=current_user.id, but mixing the two scopes here invites future bugs if the dialog query (orcurrent_user) is ever generalized to cross-tenant access. Passdia.tenant_idto_validate_llm_idas well so the two checks remain in lockstep.- llm_id_error = _validate_llm_id(requested_model, current_user.id, {"model_type": "chat"}) + llm_id_error = _validate_llm_id(requested_model, dia.tenant_id, {"model_type": "chat"})🤖 Prompt for AI Agents
Verify each finding against the current code and only fix it if needed. In `@api/apps/restful_apis/openai_api.py` around lines 137 - 146, The tenant scope is inconsistent: _validate_llm_id(requested_model, current_user.id, {"model_type": "chat"}) uses current_user.id while the subsequent TenantLLMService.get_api_key uses dia.tenant_id; change the _validate_llm_id call to pass dia.tenant_id (i.e. _validate_llm_id(requested_model, dia.tenant_id, {"model_type": "chat"})) so validation and the API-key lookup use the same tenant, keeping dia.llm_id and requested_model assignment logic unchanged.test/testcases/test_http_api/test_session_management/test_session_sdk_routes_unit.py (1)
684-687: Optional: redundantquartstub may shadow fields needed by lazy imports.
_load_session_modulealready installs a richerquartstub (withrequest,current_app,has_app_context). Re-registeringquarthere with onlyResponseandjsonifyworks today only because every consumer already cached itsfrom quart import …references during the earlier load. If any module imported transitively byopenai_api.py(now or later) performs a freshfrom quart import request, this loader will silently break. Consider extending the existing stub instead of replacing it, e.g.:♻️ Suggested adjustment
- quart_mod = ModuleType("quart") - quart_mod.Response = _StubResponse - quart_mod.jsonify = lambda payload: payload - monkeypatch.setitem(sys.modules, "quart", quart_mod) + quart_mod = sys.modules["quart"] + quart_mod.Response = _StubResponse + quart_mod.jsonify = lambda payload: payload🤖 Prompt for AI Agents
Verify each finding against the current code and only fix it if needed. In `@test/testcases/test_http_api/test_session_management/test_session_sdk_routes_unit.py` around lines 684 - 687, The test replaces the "quart" entry in sys.modules with a minimal stub (quart_mod) containing only Response and jsonify which can shadow the richer stub installed by _load_session_module and break future lazy imports; modify the test to locate the existing stub in sys.modules (installed by _load_session_module) and extend it by adding/overriding Response and jsonify instead of replacing the whole module, i.e., if sys.modules.get("quart") exists use that module object and set attributes (Response = _StubResponse, jsonify = lambda payload: payload) otherwise set the new stub as before, keeping monkeypatch.setitem(sys.modules, "quart", ...) only for the new-or-extended module so transitive imports (e.g., from quart import request/current_app/has_app_context) remain available.
🤖 Prompt for all review comments with AI agents
Verify each finding against the current code and only fix it if needed.
Inline comments:
In `@api/apps/restful_apis/openai_api.py`:
- Around line 17-31: Import the logging module and add structured logging for
the new flow: at the entry point of the handler (log chat_id, requested_model,
and stream_mode using logging.info) and inside the streaming generator's
exception handler replace or supplement embedding str(e) into the SSE body by
calling logging.exception(e) so the full traceback is recorded; specifically
modify the streaming generator's except Exception as e: branch (the streamed
exception handler) to call logging.exception(e) and preserve the SSE error
payload, and ensure import logging is added at top of openai_api.py to match
patterns used in api/apps/sdk/session.py.
- Around line 280-289: The usage block incorrectly populates
completion_tokens_details.reasoning_tokens with prompt-side tokens via
context_token_used (which is the total of message contents) causing misreported
reasoning tokens; remove the completion_tokens_details object entirely from the
usage payload (or wire it to a true model-generated reasoning counter if you
have one) and instead only report prompt_tokens, completion_tokens, and
total_tokens; while editing, compute num_tokens_from_string(prompt) and
num_tokens_from_string(content) once into local variables and reuse them to
avoid repeated tokenizer calls (refer to the variables/context_token_used,
completion_tokens_details, num_tokens_from_string, prompt, and content).
- Around line 266-274: After the async_chat consumption, guard against answer
being None: after the async for loop that assigns to answer (the block using
async_chat(dia, msg, False, **chat_kwargs)), check if answer is None and either
raise a clear exception (e.g., RuntimeError or ValueError with a descriptive
message like "async_chat produced no response") or return an explicit error
response before accessing answer["answer"]; update the code around the
answer/content extraction to use this defensive check so accessing content =
answer["answer"] cannot raise a TypeError.
In `@docs/references/python_api_reference.md`:
- Around line 76-78: The documented base_url for the OpenAI client is incorrect
and will produce a 404 because the SDK appends "/chat/completions" to base_url
when calling client.chat.completions.create; change the example so base_url ends
at the chat_id (e.g., base_url="http://ragflow_address/api/v1/openai/<chat_id>")
instead of including "/chat" so that the final request path matches the
registered route POST /api/v1/openai/<chat_id>/chat/completions.
---
Nitpick comments:
In `@api/apps/restful_apis/openai_api.py`:
- Around line 137-146: The tenant scope is inconsistent:
_validate_llm_id(requested_model, current_user.id, {"model_type": "chat"}) uses
current_user.id while the subsequent TenantLLMService.get_api_key uses
dia.tenant_id; change the _validate_llm_id call to pass dia.tenant_id (i.e.
_validate_llm_id(requested_model, dia.tenant_id, {"model_type": "chat"})) so
validation and the API-key lookup use the same tenant, keeping dia.llm_id and
requested_model assignment logic unchanged.
In `@test/benchmark/chat.py`:
- Line 83: Add lightweight request-level logging around the new OpenAI benchmark
route that builds "/openai/{chat_id}/chat/completions": import and use the
module logger in test/benchmark/chat.py and log the outgoing request URL and
chat_id (at INFO or DEBUG) before the call, and log the response status (and
short body or error) after the call; also catch and log exceptions thrown during
the request with contextual fields (chat_id, route) to aid intermittent-failure
diagnostics.
In `@test/testcases/test_http_api/common.py`:
- Around line 339-340: Add debug logging around the migrated helper endpoint
call that builds url =
f"{HOST_ADDRESS}/api/{VERSION}/searchbots/related_questions" and the subsequent
requests.post (res variable) so test-level traces capture the request URL,
payload, headers/auth and the response status/body; do the same for the other
occurrence around the lines using the same endpoint (the variables url, payload,
headers, auth, and res identify the spots). Use the project logging pattern (get
a logger via logging.getLogger(__name__) or the existing test logger) and emit
logger.debug before the post with url and payload and after with res.status_code
and a short res.text/JSON extract to aid migration debugging.
In
`@test/testcases/test_http_api/test_chat_assistant_management/test_chat_sdk_routes_unit.py`:
- Around line 1049-1064: Extract the repeated raise-in-lambda idiom "(_ for _ in
()).throw(...)" into a small helper function (e.g., a local helper named
raise_in_lambda or make_raiser) and use it in the tests instead of inline
lambdas; replace occurrences used when monkeypatching
get_tenant_default_model_by_type in the tests that call
module.transcription.__wrapped__(), and update the four monkeypatch.setattr
invocations to pass a lambda that calls the helper (or the helper itself) so the
intent is clearer while keeping behavior identical for _run, _set_request,
_DummyUploadFile and transcription references.
- Around line 1134-1138: The generator method _TTSOk.tts currently uses both
yield and "return []", which is confusing because a value returned from a
generator is discarded; fix by either turning tts into a normal function that
returns an iterable (e.g., return [b"chunk-..."] when txt falsy or a list of
chunks) or remove the "return []" sentinel and simply use an empty generator for
the falsy case (e.g., if not txt: return followed by no value or replace with
"if not txt: return" and keep yields for non-empty txt); update the _TTSOk.tts
implementation accordingly.
In
`@test/testcases/test_http_api/test_session_management/test_session_sdk_routes_unit.py`:
- Around line 684-687: The test replaces the "quart" entry in sys.modules with a
minimal stub (quart_mod) containing only Response and jsonify which can shadow
the richer stub installed by _load_session_module and break future lazy imports;
modify the test to locate the existing stub in sys.modules (installed by
_load_session_module) and extend it by adding/overriding Response and jsonify
instead of replacing the whole module, i.e., if sys.modules.get("quart") exists
use that module object and set attributes (Response = _StubResponse, jsonify =
lambda payload: payload) otherwise set the new stub as before, keeping
monkeypatch.setitem(sys.modules, "quart", ...) only for the new-or-extended
module so transitive imports (e.g., from quart import
request/current_app/has_app_context) remain available.
🪄 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: Pro
Run ID: 7bcd8086-2f09-4461-a008-97b97bd5e80c
📒 Files selected for processing (9)
api/apps/restful_apis/openai_api.pyapi/apps/sdk/session.pydocs/references/http_api_reference.mddocs/references/python_api_reference.mdtest/benchmark/chat.pytest/testcases/test_http_api/common.pytest/testcases/test_http_api/test_chat_assistant_management/test_chat_sdk_routes_unit.pytest/testcases/test_http_api/test_session_management/test_chat_completions_openai.pytest/testcases/test_http_api/test_session_management/test_session_sdk_routes_unit.py
| import json | ||
| import time | ||
|
|
||
| from quart import Response, jsonify | ||
|
|
||
| from api.apps import current_user, login_required | ||
| from api.db.services.dialog_service import DialogService, async_chat | ||
| from api.db.services.doc_metadata_service import DocMetadataService | ||
| from api.db.services.tenant_llm_service import TenantLLMService | ||
| from api.utils.api_utils import get_error_data_result, get_request_json, validate_request | ||
| from common.constants import RetCode, StatusEnum | ||
| from common.metadata_utils import convert_conditions, meta_filter | ||
| from common.token_utils import num_tokens_from_string | ||
| from rag.prompts.generator import chunks_format | ||
|
|
There was a problem hiding this comment.
Add logging for the new flow, especially around the streamed exception handler.
This new module has no import logging and no log statements, but it owns multiple new flows (request validation, model resolution, metadata filtering, and a streaming generator that catches every Exception). The streaming except Exception as e: branch (lines 240–242) currently only embeds str(e) into the SSE body — the traceback is lost, which makes incidents in the stream pipeline very hard to debug. Sibling modules such as api/apps/sdk/session.py consistently use logging.exception(e) in equivalent handlers.
🪵 Proposed fix
import json
+import logging
import time
@@
except Exception as e:
+ logging.exception("openai_chat_completions stream failed for chat_id=%s", chat_id)
response["choices"][0]["delta"]["content"] = "**ERROR**: " + str(e)
yield f"data:{json.dumps(response, ensure_ascii=False)}\n\n"Consider also a logging.info at entry that records chat_id, requested_model, and stream_mode to give the new endpoint observability parity with the rest of the API surface.
As per coding guidelines: "Add logging for new flows".
Also applies to: 240-242
🤖 Prompt for AI Agents
Verify each finding against the current code and only fix it if needed.
In `@api/apps/restful_apis/openai_api.py` around lines 17 - 31, Import the logging
module and add structured logging for the new flow: at the entry point of the
handler (log chat_id, requested_model, and stream_mode using logging.info) and
inside the streaming generator's exception handler replace or supplement
embedding str(e) into the SSE body by calling logging.exception(e) so the full
traceback is recorded; specifically modify the streaming generator's except
Exception as e: branch (the streamed exception handler) to call
logging.exception(e) and preserve the SSE error payload, and ensure import
logging is added at top of openai_api.py to match patterns used in
api/apps/sdk/session.py.
| answer = None | ||
| chat_kwargs = {"toolcall_session": toolcall_session, "tools": tools, "quote": need_reference} | ||
| if doc_ids_str: | ||
| chat_kwargs["doc_ids"] = doc_ids_str | ||
| async for ans in async_chat(dia, msg, False, **chat_kwargs): | ||
| answer = ans | ||
| break | ||
|
|
||
| content = answer["answer"] |
There was a problem hiding this comment.
Defensive: answer can be None if async_chat produces no items.
answer is initialized implicitly via the loop (line 266 sets it to None), and the loop exits via break after the first yield. If async_chat ever completes without yielding (e.g., upstream short-circuit, empty pipeline, an early return), line 274 raises TypeError: 'NoneType' object is not subscriptable and the user sees a 500 with no useful message. A short-circuit + explicit error is cheaper than the alternative.
🛡️ Proposed fix
answer = None
chat_kwargs = {"toolcall_session": toolcall_session, "tools": tools, "quote": need_reference}
if doc_ids_str:
chat_kwargs["doc_ids"] = doc_ids_str
async for ans in async_chat(dia, msg, False, **chat_kwargs):
answer = ans
break
- content = answer["answer"]
+ if answer is None:
+ return get_error_data_result(message="No response generated.")
+ content = answer.get("answer", "") or ""🤖 Prompt for AI Agents
Verify each finding against the current code and only fix it if needed.
In `@api/apps/restful_apis/openai_api.py` around lines 266 - 274, After the
async_chat consumption, guard against answer being None: after the async for
loop that assigns to answer (the block using async_chat(dia, msg, False,
**chat_kwargs)), check if answer is None and either raise a clear exception
(e.g., RuntimeError or ValueError with a descriptive message like "async_chat
produced no response") or return an explicit error response before accessing
answer["answer"]; update the code around the answer/content extraction to use
this defensive check so accessing content = answer["answer"] cannot raise a
TypeError.
| "usage": { | ||
| "prompt_tokens": num_tokens_from_string(prompt), | ||
| "completion_tokens": num_tokens_from_string(content), | ||
| "total_tokens": num_tokens_from_string(prompt) + num_tokens_from_string(content), | ||
| "completion_tokens_details": { | ||
| "reasoning_tokens": context_token_used, | ||
| "accepted_prediction_tokens": num_tokens_from_string(content), | ||
| "rejected_prediction_tokens": 0, | ||
| }, | ||
| }, |
There was a problem hiding this comment.
completion_tokens_details.reasoning_tokens is being populated with prompt/context tokens.
context_token_used (line 128) is the total token count of every message's content — i.e., prompt-side tokens. The OpenAI spec defines completion_tokens_details.reasoning_tokens as tokens the model generated for internal reasoning (a subset of completion tokens). Reporting prompt tokens in this field will misrepresent usage to any client that aggregates usage.completion_tokens_details.reasoning_tokens (billing dashboards, eval pipelines, etc.) and may produce nonsensical values like reasoning_tokens > completion_tokens.
Either drop completion_tokens_details (the streaming path doesn't emit it either, so removing it keeps the shape consistent), or wire it to a real reasoning-token counter from the model. Stop-gap:
🐛 Proposed fix
- "completion_tokens_details": {
- "reasoning_tokens": context_token_used,
- "accepted_prediction_tokens": num_tokens_from_string(content),
- "rejected_prediction_tokens": 0,
- },
+ "completion_tokens_details": {
+ "reasoning_tokens": 0,
+ "accepted_prediction_tokens": num_tokens_from_string(content),
+ "rejected_prediction_tokens": 0,
+ },While here, num_tokens_from_string(prompt) and num_tokens_from_string(content) are each computed multiple times — caching them in locals would save a couple of tokenizer calls on the hot path.
📝 Committable suggestion
‼️ IMPORTANT
Carefully review the code before committing. Ensure that it accurately replaces the highlighted code, contains no missing lines, and has no issues with indentation. Thoroughly test & benchmark the code to ensure it meets the requirements.
| "usage": { | |
| "prompt_tokens": num_tokens_from_string(prompt), | |
| "completion_tokens": num_tokens_from_string(content), | |
| "total_tokens": num_tokens_from_string(prompt) + num_tokens_from_string(content), | |
| "completion_tokens_details": { | |
| "reasoning_tokens": context_token_used, | |
| "accepted_prediction_tokens": num_tokens_from_string(content), | |
| "rejected_prediction_tokens": 0, | |
| }, | |
| }, | |
| "usage": { | |
| "prompt_tokens": num_tokens_from_string(prompt), | |
| "completion_tokens": num_tokens_from_string(content), | |
| "total_tokens": num_tokens_from_string(prompt) + num_tokens_from_string(content), | |
| "completion_tokens_details": { | |
| "reasoning_tokens": 0, | |
| "accepted_prediction_tokens": num_tokens_from_string(content), | |
| "rejected_prediction_tokens": 0, | |
| }, | |
| }, |
🤖 Prompt for AI Agents
Verify each finding against the current code and only fix it if needed.
In `@api/apps/restful_apis/openai_api.py` around lines 280 - 289, The usage block
incorrectly populates completion_tokens_details.reasoning_tokens with
prompt-side tokens via context_token_used (which is the total of message
contents) causing misreported reasoning tokens; remove the
completion_tokens_details object entirely from the usage payload (or wire it to
a true model-generated reasoning counter if you have one) and instead only
report prompt_tokens, completion_tokens, and total_tokens; while editing,
compute num_tokens_from_string(prompt) and num_tokens_from_string(content) once
into local variables and reuse them to avoid repeated tokenizer calls (refer to
the variables/context_token_used, completion_tokens_details,
num_tokens_from_string, prompt, and content).
| model = "glm-4-flash@ZHIPU-AI" | ||
| client = OpenAI(api_key="ragflow-api-key", base_url="http://ragflow_address/api/v1/openai/<chat_id>/chat") | ||
|
|
There was a problem hiding this comment.
🧩 Analysis chain
🏁 Script executed:
#!/bin/bash
# Find any other docs/tests/code that wire the OpenAI client with a base_url
# ending in /chat to ensure the same fix is applied wherever it appears.
rg -nP -C2 'openai/<?[^/]+>?/chat["\047]' --type md
rg -nP -C2 'base_url\s*=\s*["\047][^"\047]*openai/[^/"\047]+/chat["\047]'Repository: infiniflow/ragflow
Length of output: 800
🏁 Script executed:
#!/bin/bash
# Find the route definition in openai_api.py around line 102
find . -name "openai_api.py" -type f | head -5Repository: infiniflow/ragflow
Length of output: 100
🏁 Script executed:
#!/bin/bash
# Search for other docs that might have the same base_url pattern
rg 'base_url.*openai.*chat' --type md --type py -C 2Repository: infiniflow/ragflow
Length of output: 416
🏁 Script executed:
#!/bin/bash
# Look for all occurrences of chat endpoint definitions
rg '/openai/.*chat/completions' --type py -C 2Repository: infiniflow/ragflow
Length of output: 1114
🏁 Script executed:
#!/bin/bash
# Search for any other code examples or configs with the incorrect base_url pattern
rg 'base_url.*api/v1/openai' --type py --type md -B2 -A2Repository: infiniflow/ragflow
Length of output: 416
🏁 Script executed:
#!/bin/bash
# Check if there are any README or other doc files with examples
find . -name "README*" -o -name "*example*" -o -name "*tutorial*" | grep -E "\.(md|py)$" | head -10Repository: infiniflow/ragflow
Length of output: 213
🏁 Script executed:
#!/bin/bash
# Check for any HTTP API reference or other docs mentioning the OpenAI endpoint
find . -path ./node_modules -prune -o -name "*http*" -o -name "*api*reference*" | grep -E "\.(md|rst)$"Repository: infiniflow/ragflow
Length of output: 198
🌐 Web query:
OpenAI Python SDK chat.completions.create base_url behavior append path
💡 Result:
The OpenAI Python SDK's client.chat.completions.create method appends the "/chat/completions" path to the base_url provided when initializing the OpenAI client. The base_url is automatically normalized to ensure it has a trailing slash via _enforce_trailing_slash in BaseClient.init. When constructing the full request URL in _prepare_url, if the path is relative (as "/chat/completions" is), it merges by concatenating base_url.raw_path (which ends with "/") + the relative path with its leading "/" stripped: merge_raw_path = self.base_url.raw_path + merge_url.raw_path.lstrip(b"/"). This produces a clean path without double slashes (e.g., "https://api.example.com/v1/" + "chat/completions" → "https://api.example.com/v1/chat/completions"). Example: Setting base_url="https://api.example.com/v1" (no trailing slash) results in the client using "https://api.example.com/v1/" internally, and the final URL becomes "https://api.example.com/v1/chat/completions". There is no built-in parameter to customize or override the appended path like "/chat/completions"; it's hardcoded in the resource method. For custom paths (e.g., third-party providers), use an httpx event hook to rewrite the path after construction, as recommended in the official GitHub issue discussion.
Citations:
- 1: https://github.com/openai/openai-python/blob/main/src/openai/_base_client.py
- 2: Add ability to customize "/chat/completions" path after base url openai/openai-python#1344
- 3: https://developers.openai.com/api/reference/python
- 4: Inconsistent base_url behavior with module client and OpenAIClient openai/openai-python#1373
- 5: Make the trailing / optional at openai.base_url setting openai/openai-python#780
🏁 Script executed:
#!/bin/bash
# Check if http_api_reference.md has any OpenAI base_url examples
rg 'base_url|openai.*chat' ./docs/references/http_api_reference.md -C3Repository: infiniflow/ragflow
Length of output: 1632
🏁 Script executed:
#!/bin/bash
# Also check the agent HTTP component for any similar examples
rg 'base_url|openai.*chat' ./docs/guides/agent/agent_component_reference/http.md -C3Repository: infiniflow/ragflow
Length of output: 44
🏁 Script executed:
#!/bin/bash
# Final verification: count total occurrences of the incorrect pattern
rg 'base_url.*api/v1/openai.*chat["\047]' --count-matchesRepository: infiniflow/ragflow
Length of output: 297
🏁 Script executed:
#!/bin/bash
# Final verification with corrected regex
rg 'base_url.*openai.*chat' --countRepository: infiniflow/ragflow
Length of output: 104
Critical: documented base_url mismatches the server route; example will 404.
The OpenAI Python SDK appends /chat/completions to base_url when calling client.chat.completions.create. With base_url="http://ragflow_address/api/v1/openai/<chat_id>/chat", the SDK will request …/api/v1/openai/<chat_id>/chat/chat/completions, which does not match the registered route POST /api/v1/openai/<chat_id>/chat/completions. The base URL must end at <chat_id> instead of /chat.
Proposed fix
-client = OpenAI(api_key="ragflow-api-key", base_url="http://ragflow_address/api/v1/openai/<chat_id>/chat")
+client = OpenAI(api_key="ragflow-api-key", base_url="http://ragflow_address/api/v1/openai/<chat_id>")🤖 Prompt for AI Agents
Verify each finding against the current code and only fix it if needed.
In `@docs/references/python_api_reference.md` around lines 76 - 78, The documented
base_url for the OpenAI client is incorrect and will produce a 404 because the
SDK appends "/chat/completions" to base_url when calling
client.chat.completions.create; change the example so base_url ends at the
chat_id (e.g., base_url="http://ragflow_address/api/v1/openai/<chat_id>")
instead of including "/chat" so that the final request path matches the
registered route POST /api/v1/openai/<chat_id>/chat/completions.
Codecov Report✅ All modified and coverable lines are covered by tests. Additional details and impacted files@@ Coverage Diff @@
## main #14380 +/- ##
=======================================
Coverage 95.30% 95.30%
=======================================
Files 10 10
Lines 703 703
Branches 112 112
=======================================
Hits 670 670
Misses 16 16
Partials 17 17 ☔ View full report in Codecov by Sentry. 🚀 New features to boost your workflow:
|
There was a problem hiding this comment.
🧹 Nitpick comments (1)
test/testcases/test_http_api/test_session_management/test_session_sdk_routes_unit.py (1)
670-695: Heavy duplication with_load_agent_api_module.The
api.appsregistration (lines 674–678) and the trailing dynamic-import boilerplate (lines 689–695) are near-identical to_load_agent_api_module(lines 553–557, 661–667). Consider extracting a small helper like_load_module_from_path(monkeypatch, rel_path, test_module_name)(and a shared_register_api_apps_namespace) to keep these loaders DRY as morerestful_apismodules get unit-tested.🤖 Prompt for AI Agents
Verify each finding against the current code and only fix it if needed. In `@test/testcases/test_http_api/test_session_management/test_session_sdk_routes_unit.py` around lines 670 - 695, The duplicated registration and dynamic-import boilerplate in _load_openai_api_module (api.apps setup and the spec/exec block) should be extracted and reused: create a helper _register_api_apps_namespace(monkeypatch) to register api.apps and api.apps.restful_apis and quart/test stubs, and a helper _load_module_from_path(monkeypatch, rel_path, test_module_name) that builds module_path, creates spec via importlib.util.spec_from_file_location, module via importlib.util.module_from_spec, sets module.manager = _DummyManager() (or accepts a manager arg), inserts the module into sys.modules and calls spec.loader.exec_module(module); then replace the duplicated code in _load_openai_api_module and _load_agent_api_module to call these helpers (keeping the existing monkeypatch usage and test module names).
🤖 Prompt for all review comments with AI agents
Verify each finding against the current code and only fix it if needed.
Nitpick comments:
In
`@test/testcases/test_http_api/test_session_management/test_session_sdk_routes_unit.py`:
- Around line 670-695: The duplicated registration and dynamic-import
boilerplate in _load_openai_api_module (api.apps setup and the spec/exec block)
should be extracted and reused: create a helper
_register_api_apps_namespace(monkeypatch) to register api.apps and
api.apps.restful_apis and quart/test stubs, and a helper
_load_module_from_path(monkeypatch, rel_path, test_module_name) that builds
module_path, creates spec via importlib.util.spec_from_file_location, module via
importlib.util.module_from_spec, sets module.manager = _DummyManager() (or
accepts a manager arg), inserts the module into sys.modules and calls
spec.loader.exec_module(module); then replace the duplicated code in
_load_openai_api_module and _load_agent_api_module to call these helpers
(keeping the existing monkeypatch usage and test module names).
ℹ️ Review info
⚙️ Run configuration
Configuration used: Organization UI
Review profile: CHILL
Plan: Pro
Run ID: 74d4b226-2a4c-4929-b868-30323d26cb5e
📒 Files selected for processing (2)
test/testcases/test_http_api/test_session_management/test_related_questions.pytest/testcases/test_http_api/test_session_management/test_session_sdk_routes_unit.py
What problem does this PR solve?
restore openai-compatible chat completions api
Type of change