findEthics commited on
Commit
e3a1eb8
·
1 Parent(s): f5d3b25

Add interactive terminal client and improve search functionality

Browse files

- Add local_app.py: minimal interactive chat client for Atlas API
- Enable search by default in ChatRequest model
- Add dotenv support for environment variable loading
- Add enhanced logging for search operations

Files changed (3) hide show
  1. app.py +9 -1
  2. local_app.py +91 -0
  3. requirements.txt +1 -0
app.py CHANGED
@@ -4,6 +4,7 @@ from pydantic import BaseModel
4
  import google.generativeai as genai
5
  import httpx
6
  import os
 
7
  from duckduckgo_search import DDGS
8
  from typing import Optional, List, Dict, Any
9
  import logging
@@ -12,6 +13,9 @@ import asyncio
12
  import threading
13
  from functools import wraps
14
 
 
 
 
15
 
16
  import spacy
17
  from rake_nltk import Rake
@@ -50,7 +54,7 @@ app.add_middleware(
50
  class ChatRequest(BaseModel):
51
  prompt: str
52
  max_new_tokens: int = 500
53
- use_search: bool = False
54
  temperature: float = 0.7
55
 
56
  class ChatResponse(BaseModel):
@@ -343,11 +347,15 @@ async def chat_endpoint(request: ChatRequest):
343
  search_results = []
344
  search_context = ""
345
  # Web search processing
 
346
  if request.use_search:
 
347
  search_terms = extract_search_terms(request.prompt.lower())
 
348
  search_query = " ".join(search_terms) or request.prompt
349
  search_results = await search_web_combined(search_query, 10)
350
  search_context = format_search_context(search_results)
 
351
 
352
  logger.info(f"Search Context: {search_context}")
353
 
 
4
  import google.generativeai as genai
5
  import httpx
6
  import os
7
+ from dotenv import load_dotenv
8
  from duckduckgo_search import DDGS
9
  from typing import Optional, List, Dict, Any
10
  import logging
 
13
  import threading
14
  from functools import wraps
15
 
16
+ # Load environment variables from .env file
17
+ load_dotenv()
18
+
19
 
20
  import spacy
21
  from rake_nltk import Rake
 
54
  class ChatRequest(BaseModel):
55
  prompt: str
56
  max_new_tokens: int = 500
57
+ use_search: bool = True
58
  temperature: float = 0.7
59
 
60
  class ChatResponse(BaseModel):
 
347
  search_results = []
348
  search_context = ""
349
  # Web search processing
350
+ logger.info(f"Use Search : {request.use_search}")
351
  if request.use_search:
352
+ logger.info(f"Starting Web search")
353
  search_terms = extract_search_terms(request.prompt.lower())
354
+ logger.info(f"extract_search_terms successful")
355
  search_query = " ".join(search_terms) or request.prompt
356
  search_results = await search_web_combined(search_query, 10)
357
  search_context = format_search_context(search_results)
358
+ logger.info(f"Web search successful")
359
 
360
  logger.info(f"Search Context: {search_context}")
361
 
local_app.py ADDED
@@ -0,0 +1,91 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ #!/usr/bin/env python3
2
+ """
3
+ Local interactive chat client for Atlas API
4
+ Connects to the FastAPI server running on localhost:7860
5
+ """
6
+
7
+ import httpx
8
+ import asyncio
9
+ import sys
10
+ import json
11
+
12
+ API_BASE_URL = "http://localhost:7860"
13
+
14
+ async def send_chat_message(prompt: str, use_search: bool = True) -> dict:
15
+ """Send a chat message to the API and return the response"""
16
+ async with httpx.AsyncClient(timeout=30.0) as client:
17
+ try:
18
+ response = await client.post(
19
+ f"{API_BASE_URL}/chat",
20
+ json={
21
+ "prompt": prompt,
22
+ "max_new_tokens": 500,
23
+ "use_search": use_search,
24
+ "temperature": 0.7
25
+ }
26
+ )
27
+ response.raise_for_status()
28
+ return response.json()
29
+ except httpx.ConnectError:
30
+ return {"error": "Could not connect to API server. Make sure app.py is running on localhost:7860"}
31
+ except httpx.TimeoutException:
32
+ return {"error": "Request timed out. Please try again."}
33
+ except httpx.HTTPStatusError as e:
34
+ return {"error": f"API error: {e.response.status_code} - {e.response.text}"}
35
+ except Exception as e:
36
+ return {"error": f"Unexpected error: {str(e)}"}
37
+
38
+ async def main():
39
+ """Main chat loop"""
40
+ print("Atlas Chat Client")
41
+ print("Type your messages and press Enter. Empty input or Ctrl+C to exit.")
42
+ print("Type 'search:' before your message to enable web search.")
43
+ print("-" * 50)
44
+
45
+ try:
46
+ while True:
47
+ try:
48
+ # Get user input
49
+ user_input = input("\nYou: ").strip()
50
+
51
+ # Exit on empty input
52
+ if not user_input:
53
+ print("Goodbye!")
54
+ break
55
+
56
+ # Check for search prefix
57
+ use_search = True
58
+ if user_input.startswith("search:"):
59
+ use_search = True
60
+ user_input = user_input[7:].strip()
61
+ if not user_input:
62
+ print("Please provide a message after 'search:'")
63
+ continue
64
+
65
+ # Send message to API
66
+ print("AI: ", end="", flush=True)
67
+ response = await send_chat_message(user_input, use_search)
68
+
69
+ # Handle response
70
+ if "error" in response:
71
+ print(f"Error: {response['error']}")
72
+ else:
73
+ print(response.get("response", "No response received"))
74
+
75
+ # Show search results if available
76
+ if response.get("search_results"):
77
+ print(f"\n[Found {len(response['search_results'])} search results]")
78
+
79
+ except KeyboardInterrupt:
80
+ print("\nGoodbye!")
81
+ break
82
+ except EOFError:
83
+ print("\nGoodbye!")
84
+ break
85
+
86
+ except Exception as e:
87
+ print(f"Fatal error: {e}")
88
+ sys.exit(1)
89
+
90
+ if __name__ == "__main__":
91
+ asyncio.run(main())
requirements.txt CHANGED
@@ -5,6 +5,7 @@ google-generativeai
5
  duckduckgo-search
6
  httpx==0.24.1
7
  python-multipart==0.0.6
 
8
  rake_nltk
9
  nltk
10
  spacy
 
5
  duckduckgo-search
6
  httpx==0.24.1
7
  python-multipart==0.0.6
8
+ python-dotenv
9
  rake_nltk
10
  nltk
11
  spacy