Skip to content

Commit 458eb79

Browse files
style: ruff autofix (auto)
1 parent 54193e6 commit 458eb79

4 files changed

Lines changed: 27 additions & 40 deletions

File tree

src/agent.py

Lines changed: 2 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -112,6 +112,7 @@ def _stream_error_chunk(message: str, response_id: str | None = None) -> bytes:
112112
payload["response_id"] = response_id
113113
return (json.dumps(payload) + "\n").encode("utf-8")
114114

115+
115116
async def get_user_conversations(user_id: str):
116117
"""Get conversation metadata for a user from persistent storage."""
117118
return await conversation_persistence.get_user_conversations(user_id)
@@ -163,9 +164,7 @@ async def store_conversation_thread(user_id: str, response_id: str, conversation
163164
content = first_user_msg.get("content", "")
164165
title = content[:50] + "..." if len(content) > 50 else content
165166

166-
user_assistant_messages = [
167-
msg for msg in messages if msg.get("role") in ["user", "assistant"]
168-
]
167+
user_assistant_messages = [msg for msg in messages if msg.get("role") in ["user", "assistant"]]
169168
metadata_only = {
170169
"response_id": response_id,
171170
"title": title,

src/api/chat.py

Lines changed: 21 additions & 25 deletions
Original file line numberDiff line numberDiff line change
@@ -1,17 +1,17 @@
1-
from typing import Optional, Any, Dict
1+
from typing import Any, Dict, Optional
22

33
from fastapi import Depends, HTTPException
4-
from pydantic import BaseModel
54
from fastapi.responses import JSONResponse, StreamingResponse
6-
from utils.logging_config import get_logger
5+
from pydantic import BaseModel
76

87
from dependencies import (
98
get_chat_service,
10-
get_session_manager,
119
get_current_user,
10+
get_session_manager,
1211
require_permission,
1312
)
1413
from session_manager import User
14+
from utils.logging_config import get_logger
1515

1616
logger = get_logger(__name__)
1717

@@ -20,7 +20,7 @@ def _openrag_user_id(user: User) -> str:
2020
return getattr(user, "db_user_id", None) or user.user_id
2121

2222

23-
async def _assert_owns(session_id: Optional[str], user_id: str) -> None:
23+
async def _assert_owns(session_id: str | None, user_id: str) -> None:
2424
"""Raise 403 if `session_id` is set but not owned by `user_id`.
2525
2626
No-op when `session_id` is None (new conversation, nothing to check).
@@ -30,6 +30,7 @@ async def _assert_owns(session_id: Optional[str], user_id: str) -> None:
3030
if not session_id:
3131
return
3232
from services.session_ownership_service import session_ownership_service
33+
3334
owner = await session_ownership_service.get_session_owner(session_id)
3435
if owner is None:
3536
raise HTTPException(status_code=404, detail={"error": "session_not_found"})
@@ -39,15 +40,15 @@ async def _assert_owns(session_id: Optional[str], user_id: str) -> None:
3940

4041
class ChatBody(BaseModel):
4142
prompt: str
42-
previous_response_id: Optional[str] = None
43+
previous_response_id: str | None = None
4344
# OpenRAG sidebar/thread id. Distinct from previous_response_id so a retry
4445
# after an error can stay in the same chat while starting a fresh Langflow session.
45-
conversation_id: Optional[str] = None
46+
conversation_id: str | None = None
4647
stream: bool = False
47-
filters: Optional[Dict[str, Any]] = None
48+
filters: dict[str, Any] | None = None
4849
limit: int = 10
4950
scoreThreshold: float = 0
50-
filter_id: Optional[str] = None
51+
filter_id: str | None = None
5152

5253

5354
async def chat_endpoint(
@@ -67,9 +68,11 @@ async def chat_endpoint(
6768

6869
if body.filters:
6970
from auth_context import set_search_filters
71+
7072
set_search_filters(body.filters)
7173

72-
from auth_context import set_search_limit, set_score_threshold
74+
from auth_context import set_score_threshold, set_search_limit
75+
7376
set_search_limit(body.limit)
7477
set_score_threshold(body.scoreThreshold)
7578

@@ -123,9 +126,11 @@ async def langflow_endpoint(
123126

124127
if body.filters:
125128
from auth_context import set_search_filters
129+
126130
set_search_filters(body.filters)
127131

128-
from auth_context import set_search_limit, set_score_threshold
132+
from auth_context import set_score_threshold, set_search_limit
133+
129134
set_search_limit(body.limit)
130135
set_score_threshold(body.scoreThreshold)
131136

@@ -171,9 +176,7 @@ async def langflow_endpoint(
171176

172177
except Exception as e:
173178
logger.exception("[CHAT] Langflow request failed")
174-
return JSONResponse(
175-
{"error": f"Langflow request failed: {str(e)}"}, status_code=500
176-
)
179+
return JSONResponse({"error": f"Langflow request failed: {str(e)}"}, status_code=500)
177180

178181

179182
async def chat_history_endpoint(
@@ -186,9 +189,7 @@ async def chat_history_endpoint(
186189
return JSONResponse(history)
187190
except Exception as e:
188191
logger.exception("[CHAT] Failed to get chat history")
189-
return JSONResponse(
190-
{"error": f"Failed to get chat history: {str(e)}"}, status_code=500
191-
)
192+
return JSONResponse({"error": f"Failed to get chat history: {str(e)}"}, status_code=500)
192193

193194

194195
async def langflow_history_endpoint(
@@ -201,9 +202,7 @@ async def langflow_history_endpoint(
201202
return JSONResponse(history)
202203
except Exception as e:
203204
logger.exception("[CHAT] Failed to get langflow history")
204-
return JSONResponse(
205-
{"error": f"Failed to get langflow history: {str(e)}"}, status_code=500
206-
)
205+
return JSONResponse({"error": f"Failed to get langflow history: {str(e)}"}, status_code=500)
207206

208207

209208
async def delete_session_endpoint(
@@ -221,11 +220,8 @@ async def delete_session_endpoint(
221220
return JSONResponse({"message": "Session deleted successfully"})
222221
else:
223222
return JSONResponse(
224-
{"error": result.get("error", "Failed to delete session")},
225-
status_code=500
223+
{"error": result.get("error", "Failed to delete session")}, status_code=500
226224
)
227225
except Exception as e:
228226
logger.error(f"Error deleting session: {e}")
229-
return JSONResponse(
230-
{"error": f"Failed to delete session: {str(e)}"}, status_code=500
231-
)
227+
return JSONResponse({"error": f"Failed to delete session: {str(e)}"}, status_code=500)

src/services/chat_service.py

Lines changed: 2 additions & 6 deletions
Original file line numberDiff line numberDiff line change
@@ -843,9 +843,7 @@ async def get_langflow_history(self, user_id: str):
843843
]
844844

845845
if response_id in listed_ids:
846-
existing = next(
847-
c for c in all_conversations if c["response_id"] == response_id
848-
)
846+
existing = next(c for c in all_conversations if c["response_id"] == response_id)
849847
if len(messages) > len(existing.get("messages") or []):
850848
existing["messages"] = messages
851849
existing["total_messages"] = len(messages)
@@ -864,9 +862,7 @@ async def get_langflow_history(self, user_id: str):
864862
else "New Chat"
865863
)
866864
created_at = metadata.get("created_at") or conversation_state.get("created_at")
867-
last_activity = metadata.get("last_activity") or conversation_state.get(
868-
"last_activity"
869-
)
865+
last_activity = metadata.get("last_activity") or conversation_state.get("last_activity")
870866
all_conversations.append(
871867
{
872868
"response_id": response_id,

tests/unit/test_langflow_stream_provider_errors.py

Lines changed: 2 additions & 6 deletions
Original file line numberDiff line numberDiff line change
@@ -206,9 +206,7 @@ async def raise_provider_error(*_args, **_kwargs) -> AsyncIterator[bytes]:
206206

207207

208208
@pytest.mark.asyncio
209-
async def test_langflow_follow_up_after_error_reuses_store_id(
210-
monkeypatch, store_in_memory
211-
):
209+
async def test_langflow_follow_up_after_error_reuses_store_id(monkeypatch, store_in_memory):
212210
"""Retrying in the same chat must not create a second sidebar conversation."""
213211
provider_message = "Rate limit exceeded for watsonx.ai."
214212
stream_calls: list[dict] = []
@@ -263,9 +261,7 @@ async def raise_provider_error(*_args, **kwargs) -> AsyncIterator[bytes]:
263261

264262

265263
@pytest.mark.asyncio
266-
async def test_langflow_follow_up_ignores_broken_previous_response_id(
267-
monkeypatch, store_in_memory
268-
):
264+
async def test_langflow_follow_up_ignores_broken_previous_response_id(monkeypatch, store_in_memory):
269265
"""Even if the client still sends a failed Langflow session id, do not chain it."""
270266
provider_message = "Invalid API key for Anthropic. Check your credentials."
271267
stream_calls: list[dict] = []

0 commit comments

Comments
 (0)