Skip to content

Commit 7236108

Browse files
Run Black & Flake8
1 parent 398d5c6 commit 7236108

File tree

5 files changed

+25
-73
lines changed

5 files changed

+25
-73
lines changed

atomic-examples/fastapi-memory/fastapi_memory/client.py

Lines changed: 10 additions & 22 deletions
Original file line numberDiff line numberDiff line change
@@ -95,10 +95,7 @@ def _delete_session(user_id: str, session_id: str) -> bool:
9595
True if successful, False otherwise
9696
"""
9797
try:
98-
response = httpx.delete(
99-
f"{BASE_URL}/users/{user_id}/sessions/{session_id}",
100-
timeout=REQUEST_TIMEOUT
101-
)
98+
response = httpx.delete(f"{BASE_URL}/users/{user_id}/sessions/{session_id}", timeout=REQUEST_TIMEOUT)
10299
response.raise_for_status()
103100
return True
104101
except httpx.HTTPStatusError as e:
@@ -212,10 +209,7 @@ def _fetch_conversation_history(user_id: str, session_id: str) -> Optional[List[
212209
List of message dicts with 'role', 'content', 'timestamp', or None if request failed
213210
"""
214211
try:
215-
response = httpx.get(
216-
f"{BASE_URL}/users/{user_id}/sessions/{session_id}/history",
217-
timeout=REQUEST_TIMEOUT
218-
)
212+
response = httpx.get(f"{BASE_URL}/users/{user_id}/sessions/{session_id}/history", timeout=REQUEST_TIMEOUT)
219213
response.raise_for_status()
220214
data = response.json()
221215
return data.get("messages", [])
@@ -244,7 +238,7 @@ def _display_conversation_history(messages: List[dict]) -> None:
244238
elif role == "assistant":
245239
console.print(Text("Agent:", style="bold green"), end=" ")
246240
console.print(Text(content, style="green"))
247-
241+
248242
if msg.get("suggested_questions"):
249243
_display_suggested_questions(msg["suggested_questions"])
250244
console.print()
@@ -289,7 +283,7 @@ def chat_non_streaming(user_id: str, session_id: str) -> None:
289283
initial_questions = [
290284
"What can you help me with?",
291285
"Tell me about your capabilities",
292-
"How does this chat system work?"
286+
"How does this chat system work?",
293287
]
294288
_display_suggested_questions(initial_questions)
295289
console.print()
@@ -347,7 +341,7 @@ async def chat_streaming_async(user_id: str, session_id: str) -> None:
347341
initial_questions = [
348342
"What can you help me with?",
349343
"Tell me about your capabilities",
350-
"How does this chat system work?"
344+
"How does this chat system work?",
351345
]
352346
_display_suggested_questions(initial_questions)
353347
console.print()
@@ -380,25 +374,19 @@ async def chat_streaming_async(user_id: str, session_id: str) -> None:
380374
data = json.loads(data_str)
381375

382376
if "error" in data:
383-
console.print(
384-
f"\n[bold red]Error:[/bold red] {data['error']}\n"
385-
)
377+
console.print(f"\n[bold red]Error:[/bold red] {data['error']}\n")
386378
break
387379

388380
if data.get("response"):
389381
current_response = data["response"]
390382
if data.get("suggested_questions"):
391383
current_questions = data["suggested_questions"]
392384

393-
display_text = Text.assemble(
394-
("Agent: ", "bold green"), (current_response, "green")
395-
)
385+
display_text = Text.assemble(("Agent: ", "bold green"), (current_response, "green"))
396386

397387
if current_questions:
398388
display_text.append("\n\n")
399-
display_text.append(
400-
"Suggested questions:\n", style="bold cyan"
401-
)
389+
display_text.append("Suggested questions:\n", style="bold cyan")
402390
for i, question in enumerate(current_questions, 1):
403391
display_text.append(f"{i}. {question}\n", style="cyan")
404392

@@ -461,11 +449,11 @@ def manage_sessions(user_id: str) -> None:
461449
confirm = Prompt.ask(
462450
f"\n[bold yellow]Delete session {session_to_delete[:8]}...?[/bold yellow]",
463451
choices=["yes", "no"],
464-
default="no"
452+
default="no",
465453
)
466454
if confirm == "yes":
467455
if _delete_session(user_id, session_to_delete):
468-
console.print(f"\n[bold green]✓ Session deleted[/bold green]")
456+
console.print("\n[bold green]✓ Session deleted[/bold green]")
469457
else:
470458
console.print("[bold red]Invalid selection[/bold red]")
471459
except ValueError:

atomic-examples/fastapi-memory/fastapi_memory/lib/config.py

Lines changed: 1 addition & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -36,10 +36,7 @@ def get_api_key() -> str:
3636
except Exception:
3737
continue
3838

39-
raise ValueError(
40-
"OPENAI_API_KEY environment variable is required. "
41-
"Please set it or create a .env file."
42-
)
39+
raise ValueError("OPENAI_API_KEY environment variable is required. " "Please set it or create a .env file.")
4340

4441

4542
# Constants

atomic-examples/fastapi-memory/fastapi_memory/lib/schemas.py

Lines changed: 1 addition & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -11,9 +11,7 @@ class ChatRequest(BaseIOSchema):
1111

1212
message: str = Field(..., description="User message")
1313
user_id: str = Field(..., description="User identifier")
14-
session_id: Optional[str] = Field(
15-
None, description="Session identifier for conversation continuity"
16-
)
14+
session_id: Optional[str] = Field(None, description="Session identifier for conversation continuity")
1715

1816

1917
class ChatResponse(BaseIOSchema):

atomic-examples/fastapi-memory/fastapi_memory/main.py

Lines changed: 9 additions & 30 deletions
Original file line numberDiff line numberDiff line change
@@ -16,7 +16,6 @@
1616
ChatResponse,
1717
ConversationHistory,
1818
ConversationMessage,
19-
SessionCreateRequest,
2019
SessionCreateResponse,
2120
SessionDeleteResponse,
2221
SessionInfo,
@@ -174,8 +173,7 @@ async def chat(request: ChatRequest) -> ChatResponse:
174173
try:
175174
if not request.session_id:
176175
raise HTTPException(
177-
status_code=400,
178-
detail="session_id is required. Create a session first using POST /users/{user_id}/sessions"
176+
status_code=400, detail="session_id is required. Create a session first using POST /users/{user_id}/sessions"
179177
)
180178

181179
# Store user message in history
@@ -225,8 +223,7 @@ async def chat_stream(request: ChatRequest) -> StreamingResponse:
225223
try:
226224
if not request.session_id:
227225
raise HTTPException(
228-
status_code=400,
229-
detail="session_id is required. Create a session first using POST /users/{user_id}/sessions"
226+
status_code=400, detail="session_id is required. Create a session first using POST /users/{user_id}/sessions"
230227
)
231228

232229
# Store user message in history
@@ -239,13 +236,11 @@ async def generate():
239236
full_response = ""
240237
final_suggested_questions = []
241238
try:
242-
async for chunk in agent.run_async_stream(
243-
ChatRequest(message=request.message, user_id=request.user_id)
244-
):
239+
async for chunk in agent.run_async_stream(ChatRequest(message=request.message, user_id=request.user_id)):
245240
chunk_dict = chunk.model_dump() if hasattr(chunk, "model_dump") else {}
246241
response_text = chunk_dict.get("response", "")
247242
full_response = response_text # Keep updating with latest full text
248-
243+
249244
if chunk_dict.get("suggested_questions"):
250245
final_suggested_questions = chunk_dict.get("suggested_questions")
251246

@@ -299,10 +294,7 @@ async def create_session(user_id: str) -> SessionCreateResponse:
299294
session_id = _generate_session_id()
300295
session_metadata[user_id][session_id] = datetime.now().isoformat()
301296

302-
return SessionCreateResponse(
303-
session_id=session_id,
304-
message=f"Session '{session_id}' created successfully"
305-
)
297+
return SessionCreateResponse(session_id=session_id, message=f"Session '{session_id}' created successfully")
306298

307299
except Exception as e:
308300
raise HTTPException(status_code=500, detail=f"Failed to create session: {str(e)}")
@@ -327,17 +319,10 @@ async def get_user_sessions(user_id: str) -> UserSessionsResponse:
327319

328320
# Build session info list
329321
session_list = [
330-
SessionInfo(
331-
session_id=sid,
332-
created_at=session_metadata.get(user_id, {}).get(sid)
333-
)
334-
for sid in sorted(all_session_ids)
322+
SessionInfo(session_id=sid, created_at=session_metadata.get(user_id, {}).get(sid)) for sid in sorted(all_session_ids)
335323
]
336324

337-
return UserSessionsResponse(
338-
user_id=user_id,
339-
sessions=session_list
340-
)
325+
return UserSessionsResponse(user_id=user_id, sessions=session_list)
341326

342327

343328
@app.get("/users/{user_id}/sessions/{session_id}/history", response_model=ConversationHistory, tags=["Sessions"])
@@ -358,10 +343,7 @@ async def get_conversation_history(user_id: str, session_id: str) -> Conversatio
358343

359344
messages = conversation_history.get(user_id, {}).get(session_id, [])
360345

361-
return ConversationHistory(
362-
session_id=session_id,
363-
messages=[ConversationMessage(**msg) for msg in messages]
364-
)
346+
return ConversationHistory(session_id=session_id, messages=[ConversationMessage(**msg) for msg in messages])
365347

366348

367349
@app.delete("/users/{user_id}/sessions/{session_id}", response_model=SessionDeleteResponse, tags=["Sessions"])
@@ -395,10 +377,7 @@ async def delete_session(user_id: str, session_id: str) -> SessionDeleteResponse
395377
del conversation_history[user_id][session_id]
396378

397379
if not found:
398-
raise HTTPException(
399-
status_code=404,
400-
detail=f"Session '{session_id}' not found for user '{user_id}'"
401-
)
380+
raise HTTPException(status_code=404, detail=f"Session '{session_id}' not found for user '{user_id}'")
402381

403382
return SessionDeleteResponse(message=f"Session '{session_id}' deleted successfully")
404383

atomic-examples/fastapi-memory/test_api.py

Lines changed: 4 additions & 14 deletions
Original file line numberDiff line numberDiff line change
@@ -4,6 +4,7 @@
44

55
BASE_URL = "http://localhost:8000"
66

7+
78
def test_api():
89
"""Test the basic API flow."""
910
print("Testing FastAPI Memory API...\n")
@@ -29,26 +30,14 @@ def test_api():
2930
# 3. Send a chat message
3031
print("3. Sending first chat message...")
3132
response = httpx.post(
32-
f"{BASE_URL}/chat",
33-
json={
34-
"message": "Hello, how are you?",
35-
"user_id": user_id,
36-
"session_id": session_id
37-
}
33+
f"{BASE_URL}/chat", json={"message": "Hello, how are you?", "user_id": user_id, "session_id": session_id}
3834
)
3935
print(f" Status: {response.status_code}")
4036
print(f" Response: {response.json()}\n")
4137

4238
# 3b. Send another message to build conversation
4339
print("3b. Sending second chat message...")
44-
response = httpx.post(
45-
f"{BASE_URL}/chat",
46-
json={
47-
"message": "Tell me a joke",
48-
"user_id": user_id,
49-
"session_id": session_id
50-
}
51-
)
40+
response = httpx.post(f"{BASE_URL}/chat", json={"message": "Tell me a joke", "user_id": user_id, "session_id": session_id})
5241
print(f" Status: {response.status_code}")
5342
print(f" Response: {response.json()}\n")
5443

@@ -100,6 +89,7 @@ def test_api():
10089

10190
print("✅ All tests completed!")
10291

92+
10393
if __name__ == "__main__":
10494
try:
10595
test_api()

0 commit comments

Comments
 (0)