Skip to content

Commit 29d0fcb

Browse files
committed
fixed formatting issues
1 parent 5b1cb44 commit 29d0fcb

7 files changed

Lines changed: 91 additions & 89 deletions

File tree

src/llm_orchestration_service.py

Lines changed: 6 additions & 6 deletions
Original file line numberDiff line numberDiff line change
@@ -2192,7 +2192,7 @@ def _generate_rag_response(
21922192
},
21932193
output=answer,
21942194
)
2195-
2195+
21962196
retrieval_context: List[Dict[str, Any]] | None = None
21972197
if eval_mode and relevant_chunks:
21982198
max_blocks_used = ResponseGenerationConstants.DEFAULT_MAX_BLOCKS
@@ -2230,16 +2230,16 @@ def _generate_rag_response(
22302230
chunks=None, # No chunks when question is out of scope
22312231
)
22322232
else:
2233-
response = OrchestrationResponse(
2233+
response = OrchestrationResponse(
22342234
chatId=request.chatId,
22352235
llmServiceActive=True, # service OK; insufficient context
22362236
questionOutOfLLMScope=True,
22372237
inputGuardFailed=False,
22382238
content=localized_msg,
22392239
)
2240-
if eval_mode:
2240+
if eval_mode:
22412241
response.retrieval_context = retrieval_context
2242-
return response
2242+
return response
22432243

22442244
# In-scope: return the answer as-is (NO citations)
22452245
logger.info("Returning in-scope answer without citations.")
@@ -2264,14 +2264,14 @@ def _generate_rag_response(
22642264
chunks=self._format_chunks_for_test_response(relevant_chunks),
22652265
)
22662266
else:
2267-
response = OrchestrationResponse(
2267+
response = OrchestrationResponse(
22682268
chatId=request.chatId,
22692269
llmServiceActive=True,
22702270
questionOutOfLLMScope=False,
22712271
inputGuardFailed=False,
22722272
content=content_with_refs,
22732273
)
2274-
if eval_mode:
2274+
if eval_mode:
22752275
response.retrieval_context = retrieval_context
22762276
return response
22772277

src/llm_orchestration_service_api.py

Lines changed: 2 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -1,4 +1,5 @@
11
"""LLM Orchestration Service API - FastAPI application."""
2+
23
import os
34
from contextlib import asynccontextmanager
45
from typing import Any, AsyncGenerator, Dict
@@ -40,7 +41,7 @@
4041
ContextGenerationRequest,
4142
ContextGenerationResponse,
4243
EmbeddingErrorResponse,
43-
DeepEvalTestOrchestrationResponse
44+
DeepEvalTestOrchestrationResponse,
4445
)
4546

4647

src/models/request_models.py

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -278,4 +278,4 @@ class DeepEvalTestOrchestrationResponse(BaseModel):
278278
content: str
279279
retrieval_context: Optional[List[Dict[str, Any]]] = None
280280
refined_questions: Optional[List[str]] = None
281-
expected_output: Optional[str] = None # For DeepEval
281+
expected_output: Optional[str] = None # For DeepEval

tests/conftest.py

Lines changed: 24 additions & 25 deletions
Original file line numberDiff line numberDiff line change
@@ -16,14 +16,11 @@
1616

1717

1818
def download_embeddings_from_azure(
19-
connection_string: str,
20-
container_name: str,
21-
blob_name: str,
22-
local_path: Path
19+
connection_string: str, container_name: str, blob_name: str, local_path: Path
2320
) -> None:
2421
"""
2522
Download pre-computed embeddings from Azure Blob Storage.
26-
23+
2724
Args:
2825
connection_string: Azure Storage connection string
2926
container_name: Name of the blob container
@@ -34,28 +31,29 @@ def download_embeddings_from_azure(
3431
logger.info(f" Container: {container_name}")
3532
logger.info(f" Blob: {blob_name}")
3633
logger.info(f" Local path: {local_path}")
37-
34+
3835
try:
3936
# Create BlobServiceClient
40-
blob_service_client = BlobServiceClient.from_connection_string(connection_string)
41-
37+
blob_service_client = BlobServiceClient.from_connection_string(
38+
connection_string
39+
)
40+
4241
# Get blob client
4342
blob_client = blob_service_client.get_blob_client(
44-
container=container_name,
45-
blob=blob_name
43+
container=container_name, blob=blob_name
4644
)
47-
45+
4846
# Ensure parent directory exists
4947
local_path.parent.mkdir(parents=True, exist_ok=True)
50-
48+
5149
# Download the blob
5250
with open(local_path, "wb") as download_file:
5351
download_stream = blob_client.download_blob()
5452
download_file.write(download_stream.readall())
55-
53+
5654
file_size_kb = local_path.stat().st_size / 1024
5755
logger.info(f"✓ Downloaded embeddings successfully ({file_size_kb:.2f} KB)")
58-
56+
5957
except Exception as e:
6058
logger.error(f"Failed to download embeddings from Azure: {e}")
6159
raise
@@ -144,10 +142,10 @@ def start(self) -> None:
144142
"""Start all test containers and bootstrap Vault"""
145143
logger.info("Starting RAG Stack testcontainers...")
146144
os.environ["EVAL_MODE"] = "true"
147-
145+
148146
# Download embeddings from Azure before starting containers
149147
self._download_embeddings_from_azure()
150-
148+
151149
# Prepare Vault Agent directories
152150
agent_in = self.project_root / "test-vault" / "agents" / "llm"
153151
agent_out = self.project_root / "test-vault" / "agent-out"
@@ -212,33 +210,33 @@ def _download_embeddings_from_azure(self) -> None:
212210
connection_string = os.getenv("AZURE_STORAGE_CONNECTION_STRING")
213211
container_name = os.getenv("AZURE_STORAGE_CONTAINER_NAME", "test-embeddings")
214212
blob_name = os.getenv("AZURE_STORAGE_BLOB_NAME", "test_embeddings.json")
215-
213+
216214
# Local path where embeddings should be saved
217215
embeddings_file = self.project_root / "tests" / "data" / "test_embeddings.json"
218-
216+
219217
# Skip if embeddings already exist locally (for local development)
220-
#if embeddings_file.exists():
218+
# if embeddings_file.exists():
221219
# logger.info("Embeddings file already exists locally, skipping Azure download")
222220
# return
223-
221+
224222
# Require Azure configuration for CI/CD
225223
if not connection_string:
226224
raise ValueError(
227225
"AZURE_STORAGE_CONNECTION_STRING is required to download embeddings. "
228226
"Either set this environment variable or ensure test_embeddings.json "
229227
f"exists at {embeddings_file}"
230228
)
231-
229+
232230
logger.info("=" * 80)
233231
logger.info("DOWNLOADING EMBEDDINGS FROM AZURE BLOB STORAGE")
234232
logger.info("=" * 80)
235-
233+
236234
try:
237235
download_embeddings_from_azure(
238236
connection_string=connection_string,
239237
container_name=container_name,
240238
blob_name=blob_name,
241-
local_path=embeddings_file
239+
local_path=embeddings_file,
242240
)
243241
logger.info("Embeddings download complete")
244242
except Exception as e:
@@ -797,8 +795,9 @@ def orchestration_client(rag_stack: RAGStackTestContainers):
797795
Function-scoped fixture that provides the orchestration service URL.
798796
Tests can use either requests (sync) or httpx (async).
799797
"""
798+
800799
class OrchestrationClient:
801800
def __init__(self, base_url: str):
802801
self.base_url = base_url
803-
804-
return OrchestrationClient(rag_stack.get_orchestration_service_url())
802+
803+
return OrchestrationClient(rag_stack.get_orchestration_service_url())

tests/deepeval_tests/report_generator.py

Lines changed: 1 addition & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -161,13 +161,10 @@ def generate_failure_analysis(results: Dict[str, Any]) -> str:
161161
if len(failure["input"]) > 50
162162
else failure["input"]
163163
)
164-
reason_preview = (
165-
failure["reason"] )
164+
reason_preview = failure["reason"]
166165

167166
analysis += f"| {failure['test_case']} | {query_preview} | {failure['metric']} | {failure['score']:.2f} | {reason_preview} |\n"
168167

169-
170-
171168
analysis += "\n"
172169
return analysis
173170

tests/deepeval_tests/standard_tests.py

Lines changed: 21 additions & 12 deletions
Original file line numberDiff line numberDiff line change
@@ -113,6 +113,7 @@ def save_results_fixture():
113113
import httpx # Replace requests with httpx
114114
import asyncio
115115

116+
116117
class TestRAGSystem:
117118
"""Test suite for RAG system evaluation using DeepEval metrics via API."""
118119

@@ -177,7 +178,10 @@ async def test_all_metrics(self, test_item: Dict[str, Any], orchestration_client
177178
except httpx.RequestError as e:
178179
result = {"content": f"API Error: {str(e)}", "retrieval_context": []}
179180
except Exception as e:
180-
result = {"content": f"Unexpected error: {str(e)}", "retrieval_context": []}
181+
result = {
182+
"content": f"Unexpected error: {str(e)}",
183+
"retrieval_context": [],
184+
}
181185
if result is None:
182186
result = {"content": "No response received", "retrieval_context": []}
183187
# --- DEBUG LOGGING ---
@@ -186,20 +190,23 @@ async def test_all_metrics(self, test_item: Dict[str, Any], orchestration_client
186190
print("=" * 80)
187191
print(f"Response keys: {list(result.keys())}")
188192
for key, value in result.items():
189-
190193
print(key, value)
191194
print(f"Content length: {len(result.get('content', ''))}")
192195
print(f"Retrieval context: {len(result.get('retrieval_context', []))} chunks")
193-
194-
if result.get('retrieval_context'):
195-
for chunk in result['retrieval_context']:
196+
197+
if result.get("retrieval_context"):
198+
for chunk in result["retrieval_context"]:
196199
print(chunk.keys())
197-
context = chunk.get('content', '') if isinstance(chunk, dict) else str(chunk)
198-
meta = chunk.get('metadata', {}) if isinstance(chunk, dict) else {}
199-
fused_score = meta.get('fused_score', 'N/A')
200-
bm25_score = meta.get('bm25_score', 'N/A')
201-
semantic_score = meta.get('semantic_score', 'N/A')
202-
print(f"Chunk (fused: {fused_score}, bm25: {bm25_score}, semantic: {semantic_score}):\n {context}\n\n")
200+
context = (
201+
chunk.get("content", "") if isinstance(chunk, dict) else str(chunk)
202+
)
203+
meta = chunk.get("metadata", {}) if isinstance(chunk, dict) else {}
204+
fused_score = meta.get("fused_score", "N/A")
205+
bm25_score = meta.get("bm25_score", "N/A")
206+
semantic_score = meta.get("semantic_score", "N/A")
207+
print(
208+
f"Chunk (fused: {fused_score}, bm25: {bm25_score}, semantic: {semantic_score}):\n {context}\n\n"
209+
)
203210
else:
204211
print("WARNING: No retrieval context returned!")
205212
print("=" * 80)
@@ -262,4 +269,6 @@ async def run_metric(metric_name, metric):
262269
# --- Assert ---
263270
failed = [name for name, res in metrics_results.items() if not res["passed"]]
264271
if failed:
265-
pytest.fail(f"Metrics failed: {', '.join(failed)} for input: {test_item['input'][:50]}")
272+
pytest.fail(
273+
f"Metrics failed: {', '.join(failed)} for input: {test_item['input'][:50]}"
274+
)

0 commit comments

Comments
 (0)