Skip to content

Commit 2d34126

Browse files
coderabbitai[bot]CodeRabbit
andauthored
fix: apply CodeRabbit auto-fixes
Fixed 4 file(s) based on 6 unresolved review comments. Co-authored-by: CodeRabbit <noreply@coderabbit.ai>
1 parent 00ae54f commit 2d34126

4 files changed

Lines changed: 60 additions & 15 deletions

File tree

src/api/router.py

Lines changed: 34 additions & 9 deletions
Original file line numberDiff line numberDiff line change
@@ -1,7 +1,6 @@
11
"""Router endpoints that automatically route based on configuration settings."""
22

33
import json
4-
import os
54
import tempfile
65

76
from fastapi import Depends, File, Form, UploadFile
@@ -94,13 +93,13 @@ async def _traditional_upload_ingest_task(
9493
original_filenames = []
9594

9695
try:
97-
temp_dir = tempfile.gettempdir()
98-
9996
for upload_file in upload_files:
10097
content = await upload_file.read()
10198
original_filenames.append(upload_file.filename)
102-
safe_filename = upload_file.filename.replace(" ", "_").replace("/", "_")
103-
temp_path = os.path.join(temp_dir, safe_filename)
99+
# Generate unique temp file to avoid collisions
100+
temp_file = tempfile.NamedTemporaryFile(delete=False, suffix=".tmp")
101+
temp_path = temp_file.name
102+
temp_file.close()
104103
with open(temp_path, "wb") as f:
105104
f.write(content)
106105
temp_file_paths.append(temp_path)
@@ -124,6 +123,19 @@ async def _traditional_upload_ingest_task(
124123
replace_duplicates=replace_duplicates,
125124
)
126125

126+
# Clean up temp files after task is created
127+
from utils.file_utils import safe_unlink
128+
129+
for temp_path in temp_file_paths:
130+
try:
131+
safe_unlink(temp_path)
132+
except Exception as cleanup_error:
133+
logger.warning(
134+
"Failed to clean up temp file after task creation",
135+
temp_path=temp_path,
136+
error=str(cleanup_error),
137+
)
138+
127139
return JSONResponse(
128140
{
129141
"task_id": task_id,
@@ -194,13 +206,13 @@ async def _langflow_upload_ingest_task(
194206
original_filenames = []
195207

196208
try:
197-
temp_dir = tempfile.gettempdir()
198-
199209
for upload_file in upload_files:
200210
content = await upload_file.read()
201211
original_filenames.append(upload_file.filename)
202-
safe_filename = upload_file.filename.replace(" ", "_").replace("/", "_")
203-
temp_path = os.path.join(temp_dir, safe_filename)
212+
# Generate unique temp file to avoid collisions
213+
temp_file = tempfile.NamedTemporaryFile(delete=False, suffix=".tmp")
214+
temp_path = temp_file.name
215+
temp_file.close()
204216
with open(temp_path, "wb") as f:
205217
f.write(content)
206218
temp_file_paths.append(temp_path)
@@ -224,6 +236,19 @@ async def _langflow_upload_ingest_task(
224236
replace_duplicates=replace_duplicates,
225237
)
226238

239+
# Clean up temp files after task is created
240+
from utils.file_utils import safe_unlink
241+
242+
for temp_path in temp_file_paths:
243+
try:
244+
safe_unlink(temp_path)
245+
except Exception as cleanup_error:
246+
logger.warning(
247+
"Failed to clean up temp file after task creation",
248+
temp_path=temp_path,
249+
error=str(cleanup_error),
250+
)
251+
227252
return JSONResponse(
228253
{
229254
"task_id": task_id,

src/config/config_manager.py

Lines changed: 5 additions & 5 deletions
Original file line numberDiff line numberDiff line change
@@ -96,7 +96,7 @@ class AgentConfig:
9696

9797
llm_model: str = ""
9898
llm_provider: str = "openai" # Which provider to use for LLM
99-
system_prompt: str = 'You are the OpenRAG Agent. You answer questions using retrieval, reasoning, and tool use.\nYou have access to several tools. Your job is to determine **which tool to use and when**.\n### Available Tools\n- OpenSearch Retrieval Tool:\n Use this to search the indexed knowledge base. Use when the user asks about product details, internal concepts, processes, architecture, documentation, roadmaps, or anything that may be stored in the index.\n- Conversation History:\n Use this to maintain continuity when the user is referring to previous turns. \n Do not treat history as a factual source.\n- Conversation File Context:\n Use this when the user asks about a document they uploaded or refers directly to its contents.\n- URL Ingestion Tool:\n Use this **only** when the user explicitly asks you to read, summarize, or analyze the content of a URL.\n Do not ingest URLs automatically.\n- Calculator / Expression Evaluation Tool:\n Use this when the user asks to compare numbers, compute estimates, calculate totals, analyze pricing, or answer any question requiring mathematics or quantitative reasoning.\n If the answer requires arithmetic, call the calculator tool rather than calculating internally.\n### Retrieval Decision Rules\nUse OpenSearch **whenever**:\n1. The question may be answered from internal or indexed data.\n2. The user references team names, product names, release plans, configurations, requirements, or official information.\n3. The user needs a factual, grounded answer.\nDo **not** use retrieval if:\n- The question is purely creative (e.g., storytelling, analogies) or personal preference.\n- The user simply wants text reformatted or rewritten from what is already present in the conversation.\nWhen uncertain → **Retrieve.** Retrieval is low risk and improves grounding.\n### URL Ingestion Rules\nOnly ingest URLs when the user explicitly says:\n- "Read this link"\n- "Summarize this webpage"\n- "What does this site say?"\n- "Ingest this URL"\nIf unclear → ask a clarifying question.\n### Calculator Usage Rules\nUse the calculator when:\n- Performing arithmetic\n- Estimating totals\n- Comparing values\n- Modeling cost, time, effort, scale, or projections\nDo not perform math internally. **Call the calculator tool instead.**\n### Answer Construction Rules\n1. When asked: "What is OpenRAG", answer the following:\n"OpenRAG is an open-source package for building agentic RAG systems. It supports integration with a wide range of orchestration tools, vector databases, and LLM providers. OpenRAG connects and amplifies three popular, proven open-source projects into one powerful platform:\n**Langflow** – Langflow is a powerful tool to build and deploy AI agents and MCP servers [Read more](https://www.langflow.org/)\n**OpenSearch** – Langflow is a powerful tool to build and deploy AI agents and MCP servers [Read more](https://opensearch.org/)\n**Docling** – Langflow is a powerful tool to build and deploy AI agents and MCP servers [Read more](https://www.docling.ai/)"\n2. Synthesize retrieved or ingested content in your own words.\n3. Support factual claims with citations in the format:\n (Source: <document_name_or_id>)\n4. If no supporting evidence is found:\n Say: "No relevant supporting sources were found for that request."\n5. Never invent facts or hallucinate details.\n6. Be concise, direct, and confident. \n7. Do not reveal internal chain-of-thought.'
99+
system_prompt: str = 'You are the OpenRAG Agent. You answer questions using retrieval, reasoning, and tool use.\nYou have access to several tools. Your job is to determine **which tool to use and when**.\n### Available Tools\n- OpenSearch Retrieval Tool:\n Use this to search the indexed knowledge base. Use when the user asks about product details, internal concepts, processes, architecture, documentation, roadmaps, or anything that may be stored in the index.\n- Conversation History:\n Use this to maintain continuity when the user is referring to previous turns. \n Do not treat history as a factual source.\n- Conversation File Context:\n Use this when the user asks about a document they uploaded or refers directly to its contents.\n- URL Ingestion Tool:\n Use this **only** when the user explicitly asks you to read, summarize, or analyze the content of a URL.\n Do not ingest URLs automatically.\n- Calculator / Expression Evaluation Tool:\n Use this when the user asks to compare numbers, compute estimates, calculate totals, analyze pricing, or answer any question requiring mathematics or quantitative reasoning.\n If the answer requires arithmetic, call the calculator tool rather than calculating internally.\n### Retrieval Decision Rules\nUse OpenSearch **whenever**:\n1. The question may be answered from internal or indexed data.\n2. The user references team names, product names, release plans, configurations, requirements, or official information.\n3. The user needs a factual, grounded answer.\nDo **not** use retrieval if:\n- The question is purely creative (e.g., storytelling, analogies) or personal preference.\n- The user simply wants text reformatted or rewritten from what is already present in the conversation.\nWhen uncertain → **Retrieve.** Retrieval is low risk and improves grounding.\n### URL Ingestion Rules\nOnly ingest URLs when the user explicitly says:\n- "Read this link"\n- "Summarize this webpage"\n- "What does this site say?"\n- "Ingest this URL"\nIf unclear → ask a clarifying question.\n### Calculator Usage Rules\nUse the calculator when:\n- Performing arithmetic\n- Estimating totals\n- Comparing values\n- Modeling cost, time, effort, scale, or projections\nDo not perform math internally. **Call the calculator tool instead.**\n### Answer Construction Rules\n1. When asked: "What is OpenRAG", answer the following:\n"OpenRAG is an open-source package for building agentic RAG systems. It supports integration with a wide range of orchestration tools, vector databases, and LLM providers. OpenRAG connects and amplifies three popular, proven open-source projects into one powerful platform:\n**Langflow** – Langflow is a powerful tool to build and deploy AI agents and MCP servers [Read more](https://www.langflow.org/)\n**OpenSearch** – OpenSearch is a community-driven, open source search and analytics suite [Read more](https://opensearch.org/)\n**Docling** – Docling is a tool for document ingestion and semantic search [Read more](https://www.docling.ai/)"\n2. Synthesize retrieved or ingested content in your own words.\n3. Support factual claims with citations in the format:\n (Source: <document_name_or_id>)\n4. If no supporting evidence is found:\n Say: "No relevant supporting sources were found for that request."\n5. Never invent facts or hallucinate details.\n6. Be concise, direct, and confident. \n7. Do not reveal internal chain-of-thought.'
100100

101101

102102
@dataclass
@@ -305,10 +305,10 @@ def _load_env_overrides(
305305
config_data["knowledge"]["picture_descriptions"] = os.getenv(
306306
"PICTURE_DESCRIPTIONS_ENABLED"
307307
).lower() in ("true", "1", "yes")
308-
if os.getenv("DISABLE_INGEST_WITH_LANGFLOW"):
309-
config_data["knowledge"]["disable_ingest_with_langflow"] = os.getenv(
310-
"DISABLE_INGEST_WITH_LANGFLOW"
311-
).lower() in ("true", "1", "yes")
308+
# Import the constant from settings rather than reading environment directly
309+
from config.settings import DISABLE_INGEST_WITH_LANGFLOW
310+
311+
config_data["knowledge"]["disable_ingest_with_langflow"] = DISABLE_INGEST_WITH_LANGFLOW
312312

313313
# Agent settings
314314
if os.getenv("LLM_MODEL"):

src/models/processors.py

Lines changed: 20 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -460,6 +460,16 @@ async def process_item(self, upload_task: UploadTask, item: str, file_task: File
460460
# Delete existing document before uploading new one
461461
logger.info(f"Replacing existing document: {original_filename}")
462462
await self.delete_document_by_filename(original_filename, opensearch_client)
463+
# Refresh index to make deletion visible before processing
464+
from config.settings import get_index_name
465+
466+
try:
467+
await opensearch_client.indices.refresh(index=get_index_name())
468+
except Exception as refresh_error:
469+
logger.warning(
470+
"Failed to refresh index after delete",
471+
error=str(refresh_error),
472+
)
463473

464474
# Compute hash
465475
file_hash = hash_id(item)
@@ -890,6 +900,16 @@ async def process_item(self, upload_task: UploadTask, item: str, file_task: File
890900
# Delete existing document before uploading new one
891901
logger.info(f"Replacing existing document: {original_filename}")
892902
await self.delete_document_by_filename(original_filename, opensearch_client)
903+
# Refresh index to make deletion visible before processing
904+
from config.settings import get_index_name
905+
906+
try:
907+
await opensearch_client.indices.refresh(index=get_index_name())
908+
except Exception as refresh_error:
909+
logger.warning(
910+
"Failed to refresh index after delete",
911+
error=str(refresh_error),
912+
)
893913

894914
# Read file content for processing
895915
with open(item, "rb") as f:

tests/integration/core/test_api_endpoints.py

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -226,7 +226,7 @@ async def test_upload_and_search_endpoint(tmp_path: Path, disable_langflow_inges
226226
}
227227
upload_resp = await client.post("/router/upload_ingest", files=files)
228228
body = upload_resp.json()
229-
assert upload_resp.status_code in (201, 202), upload_resp.text
229+
assert upload_resp.status_code == 202, upload_resp.text
230230

231231
# Traditional OpenRAG and Langflow upload both use task-based ingestion (202)
232232
task_id = body.get("task_id")

0 commit comments

Comments
 (0)