Skip to content

Commit 1a37476

Browse files
Made Changes to repo asper change req
made changes to the repo asper bug 2386
1 parent 07d7e12 commit 1a37476

20 files changed

Lines changed: 2395 additions & 81 deletions

CogniwareIms/backend/app/core/config.py

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -5,7 +5,7 @@
55

66
import os
77
from functools import lru_cache
8-
from typing import List, Optional
8+
from typing import List
99

1010
from pydantic_settings import BaseSettings
1111

CogniwareIms/backend/app/init_knowledge_base.py

Lines changed: 4 additions & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -14,10 +14,10 @@
1414
# Add parent directory to path
1515
sys.path.insert(0, str(Path(__file__).parent.parent))
1616

17-
from app.services.csv_processor import csv_processor
18-
from app.services.embedding_service import embedding_service
19-
from app.services.knowledge_manager import knowledge_manager
20-
from app.services.retrieval_service import retrieval_service
17+
from app.services.csv_processor import csv_processor # noqa: E402
18+
from app.services.embedding_service import embedding_service # noqa: E402
19+
from app.services.knowledge_manager import knowledge_manager # noqa: E402
20+
from app.services.retrieval_service import retrieval_service # noqa: E402
2121

2222
logging.basicConfig(
2323
level=logging.INFO, format="%(asctime)s - %(name)s - %(levelname)s - %(message)s"

CogniwareIms/backend/app/main.py

Lines changed: 1 addition & 5 deletions
Original file line numberDiff line numberDiff line change
@@ -9,11 +9,8 @@
99
import logging
1010
import os
1111
from datetime import datetime
12-
from pathlib import Path
1312
from typing import Any, Dict, List, Optional
1413

15-
import httpx
16-
from app.services.csv_processor import csv_processor
1714
from app.services.dbqna_service import dbqna_service
1815
from app.services.doc_summarization import doc_summarization
1916

@@ -26,7 +23,6 @@
2623
from app.services.llm_service import llm_service
2724
from app.services.retrieval_service import retrieval_service
2825
from fastapi import (
29-
Depends,
3026
FastAPI,
3127
File,
3228
HTTPException,
@@ -618,7 +614,7 @@ async def broadcast(self, message: dict):
618614
for connection in self.active_connections:
619615
try:
620616
await connection.send_json(message)
621-
except:
617+
except Exception:
622618
pass
623619

624620

CogniwareIms/backend/app/services/dbqna_service.py

Lines changed: 3 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -6,11 +6,11 @@
66
Converts natural language to SQL and executes against inventory database
77
"""
88

9+
import json
910
import logging
1011
import os
11-
from typing import Any, Dict, List, Optional
12+
from typing import Any, Dict
1213

13-
import sqlalchemy
1414
from sqlalchemy import create_engine, text
1515

1616
from .llm_service import llm_service
@@ -224,7 +224,7 @@ async def health_check(self) -> bool:
224224
with engine.connect() as conn:
225225
conn.execute(text("SELECT 1"))
226226
return True
227-
except:
227+
except Exception:
228228
return False
229229

230230

CogniwareIms/backend/app/services/embedding_service.py

Lines changed: 2 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -100,7 +100,7 @@ async def embed_batch(
100100
try:
101101
emb = await self.embed_text(text)
102102
embeddings.append(emb)
103-
except:
103+
except Exception:
104104
embeddings.append([0.0] * 768) # Zero vector as last resort
105105

106106
return embeddings
@@ -167,7 +167,7 @@ async def health_check(self) -> bool:
167167
async with httpx.AsyncClient(timeout=httpx.Timeout(5.0)) as client:
168168
response = await client.get(f"{self.base_url}/v1/health_check")
169169
return response.status_code == 200
170-
except:
170+
except Exception:
171171
return False
172172

173173

CogniwareIms/backend/app/services/file_upload_service.py

Lines changed: 0 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -29,9 +29,7 @@
2929
except ImportError:
3030
Document = None
3131

32-
from .embedding_service import embedding_service
3332
from .knowledge_manager import knowledge_manager
34-
from .retrieval_service import retrieval_service
3533

3634
logger = logging.getLogger(__name__)
3735

CogniwareIms/backend/app/services/interactive_agent.py

Lines changed: 17 additions & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -126,7 +126,10 @@ async def chat(
126126
return {
127127
"success": False,
128128
"error": str(e),
129-
"response": "I apologize, but I encountered an error processing your request. Please try rephrasing your question.",
129+
"response": (
130+
"I apologize, but I encountered an error processing your request. "
131+
"Please try rephrasing your question."
132+
),
130133
}
131134

132135
async def _is_database_query(self, message: str) -> bool:
@@ -197,9 +200,19 @@ def _build_chat_messages(
197200

198201
# System prompt based on user role
199202
role_prompts = {
200-
"Consumer": "You are a helpful AI assistant for product research and PC building. Help users find products and make informed decisions.",
201-
"Inventory Manager": "You are an AI assistant for inventory management. Help with stock queries, warehouse operations, and data analysis. Be precise with numbers and locations.",
202-
"Super Admin": "You are an AI assistant for system administration. Provide comprehensive insights and administrative support.",
203+
"Consumer": (
204+
"You are a helpful AI assistant for product research and PC building. "
205+
"Help users find products and make informed decisions."
206+
),
207+
"Inventory Manager": (
208+
"You are an AI assistant for inventory management. "
209+
"Help with stock queries, warehouse operations, and data analysis. "
210+
"Be precise with numbers and locations."
211+
),
212+
"Super Admin": (
213+
"You are an AI assistant for system administration. "
214+
"Provide comprehensive insights and administrative support."
215+
),
203216
}
204217

205218
system_content = role_prompts.get(user_role, "You are a helpful AI assistant.")

CogniwareIms/backend/app/services/llm_service.py

Lines changed: 15 additions & 5 deletions
Original file line numberDiff line numberDiff line change
@@ -107,7 +107,9 @@ async def generate_sql_query(
107107
"""
108108
schema_str = json.dumps(schema, indent=2)
109109

110-
system_prompt = f"""You are an expert SQL generator. Given a database schema and a natural language question, generate a valid SQL query.
110+
system_prompt = (
111+
f"""You are an expert SQL generator. Given a database schema and a """
112+
f"""natural language question, generate a valid SQL query.
111113
112114
Database Schema:
113115
{schema_str}
@@ -137,7 +139,9 @@ async def generate_sql_query(
137139

138140
async def summarize_text(self, text: str, max_length: int = 150) -> str:
139141
"""Summarize long text using OPEA DocSummarization pattern."""
140-
prompt = f"""Summarize the following text in {max_length} words or less. Focus on key points and important details:
142+
prompt = (
143+
f"""Summarize the following text in {max_length} words or less. """
144+
f"""Focus on key points and important details:
141145
142146
Text:
143147
{text}
@@ -148,7 +152,9 @@ async def summarize_text(self, text: str, max_length: int = 150) -> str:
148152

149153
async def extract_entities(self, text: str) -> List[Dict[str, str]]:
150154
"""Extract named entities from text Useful for inventory data extraction."""
151-
prompt = f"""Extract all product names, SKUs, quantities, and locations from the following text. Return as JSON list.
155+
prompt = (
156+
f"""Extract all product names, SKUs, quantities, and locations """
157+
f"""from the following text. Return as JSON list.
152158
153159
Text: {text}
154160
@@ -206,7 +212,11 @@ async def answer_inventory_question(
206212

207213
context = "\n".join(context_parts)
208214

209-
system_prompt = """You are an AI assistant for inventory management. Answer questions accurately based on the provided inventory data. Be concise and specific."""
215+
system_prompt = (
216+
"You are an AI assistant for inventory management. "
217+
"Answer questions accurately based on the provided inventory data. "
218+
"Be concise and specific."
219+
)
210220

211221
return await self.query_with_context(question, context, system_prompt)
212222

@@ -248,7 +258,7 @@ async def health_check(self) -> bool:
248258
async with httpx.AsyncClient(timeout=httpx.Timeout(5.0)) as client:
249259
response = await client.get(f"{self.base_url}/v1/health_check")
250260
return response.status_code == 200
251-
except:
261+
except Exception:
252262
return False
253263

254264

CogniwareIms/backend/app/services/opea_client.py

Lines changed: 10 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -8,6 +8,7 @@
88
from typing import Any, Dict, List, Optional
99

1010
import httpx
11+
from fastapi import HTTPException
1112

1213
logger = logging.getLogger(__name__)
1314

@@ -121,6 +122,15 @@ async def health_check_all(self) -> Dict[str, str]:
121122
"dbqna": self.dbqna_url,
122123
}
123124

125+
async def check_service(url: str) -> bool:
126+
"""Check if a service is available."""
127+
try:
128+
async with httpx.AsyncClient(timeout=httpx.Timeout(5.0)) as client:
129+
response = await client.get(f"{url}/v1/health_check")
130+
return response.status_code == 200
131+
except Exception:
132+
return False
133+
124134
status = {}
125135
for name, url in services.items():
126136
status[name] = await check_service(url)

CogniwareIms/backend/app/services/retrieval_service.py

Lines changed: 2 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -253,7 +253,7 @@ async def health_check(self) -> Dict[str, Any]:
253253
async with httpx.AsyncClient(timeout=httpx.Timeout(5.0)) as client:
254254
response = await client.get(f"{self.base_url}/v1/health_check")
255255
status["opea_service"] = response.status_code == 200
256-
except:
256+
except Exception:
257257
pass
258258

259259
# Check Redis
@@ -262,7 +262,7 @@ async def health_check(self) -> Dict[str, Any]:
262262
await client.ping()
263263
status["redis"] = True
264264
status["document_count"] = await self.count_documents()
265-
except:
265+
except Exception:
266266
pass
267267

268268
return status

0 commit comments

Comments
 (0)