gk2410 commited on
Commit
2901bbc
·
verified ·
1 Parent(s): 2a9345e

Update app.py

Browse files
Files changed (1) hide show
  1. app.py +34 -44
app.py CHANGED
@@ -7,7 +7,7 @@ from sentence_transformers import SentenceTransformer
7
  from huggingface_hub import InferenceClient
8
 
9
  # 1. INITIALIZE MODELS
10
- # Embedder runs on CPU; Llama 3.3 runs via the API
11
  embedder = SentenceTransformer('all-MiniLM-L6-v2')
12
  client = InferenceClient("meta-llama/Llama-3.3-70B-Instruct", token=os.getenv("HF_TOKEN"))
13
 
@@ -15,7 +15,8 @@ def fetch_and_index(query):
15
  """Fetches live book data and indexes it in FAISS."""
16
  try:
17
  url = f"https://openlibrary.org/search.json?q={query}&limit=8"
18
- data = requests.get(url, timeout=5).json().get("docs", [])
 
19
 
20
  if not data: return None, None
21
 
@@ -35,7 +36,7 @@ def fetch_and_index(query):
35
  return None, None
36
 
37
  def librarian_logic(message, history, user_state):
38
- # Initialize State
39
  if user_state is None:
40
  user_state = {"step": "ASK_AGE", "age": None, "location": None}
41
 
@@ -44,63 +45,52 @@ def librarian_logic(message, history, user_state):
44
  if message.isdigit():
45
  user_state["age"] = int(message)
46
  user_state["step"] = "ASK_LOCATION"
47
- reply = "Understood. For regional safety compliance, what is your general location (City/Country)?"
48
- history.append((message, reply))
49
- return history, user_state, ""
50
 
51
- reply = "Welcome to the AI Library! Before we start, for safety and compliance: How old are you?"
52
- history.append((message, reply))
53
- return history, user_state, ""
54
 
55
  if user_state["step"] == "ASK_LOCATION":
56
  user_state["location"] = message
57
  user_state["step"] = "SEARCH_READY"
58
- reply = f"System verified for {user_state['location']}. I am now your active Librarian. What books are you looking for?"
59
- history.append((message, reply))
60
- return history, user_state, ""
61
 
62
- # --- PHASE 2: SEARCH ACTION ---
63
  index, catalog = fetch_and_index(message)
64
-
65
- if not index:
66
- reply = "I couldn't find any live records for that. Try another title or author?"
67
- history.append((message, reply))
68
- return history, user_state, ""
69
-
70
- # Semantic Retrieval
71
- query_vec = embedder.encode([message])
72
- _, I = index.search(np.array(query_vec).astype('float32'), k=min(3, len(catalog)))
73
- results = [catalog[i] for i in I[0]]
74
-
75
- # Agent Synthesis
76
- safety_rule = "The user is a child. Strictly recommend age-appropriate titles." if user_state["age"] < 13 else ""
77
- prompt = (
78
- f"Context: {results}\n"
79
- f"User (Age {user_state['age']}, Loc {user_state['location']}) asks: {message}\n"
80
- f"{safety_rule}\n"
81
- "Present the Title and Author of these matches clearly and briefly."
82
- )
83
 
84
- response = client.chat_completion(
85
- [{"role": "system", "content": "You are a professional librarian agent."},
86
- {"role": "user", "content": prompt}],
87
- max_tokens=250
88
- ).choices[0].message.content
 
 
89
 
90
- history.append((message, response))
91
- return history, user_state, ""
 
 
 
 
 
 
 
 
 
92
 
93
- # --- UI SETUP ---
94
  with gr.Blocks(theme=gr.themes.Soft()) as demo:
95
  gr.Markdown("# 📚 AI Librarian Agent\n*Live Web Search + Semantic FAISS Ranking*")
96
 
97
  user_state = gr.State()
98
  chatbot = gr.Chatbot()
99
- msg = gr.Textbox(label="Your Message", placeholder="Type age first, then chat...")
100
- clear = gr.Button("Reset Session")
101
-
102
  msg.submit(librarian_logic, [msg, chatbot, user_state], [chatbot, user_state, msg])
103
- clear.click(lambda: (None, None, ""), None, [chatbot, user_state, msg])
104
 
105
  if __name__ == "__main__":
106
  demo.launch()
 
7
  from huggingface_hub import InferenceClient
8
 
9
  # 1. INITIALIZE MODELS
10
+ # Embedder (CPU) and Llama 3.3 (API)
11
  embedder = SentenceTransformer('all-MiniLM-L6-v2')
12
  client = InferenceClient("meta-llama/Llama-3.3-70B-Instruct", token=os.getenv("HF_TOKEN"))
13
 
 
15
  """Fetches live book data and indexes it in FAISS."""
16
  try:
17
  url = f"https://openlibrary.org/search.json?q={query}&limit=8"
18
+ response = requests.get(url, timeout=5)
19
+ data = response.json().get("docs", [])
20
 
21
  if not data: return None, None
22
 
 
36
  return None, None
37
 
38
  def librarian_logic(message, history, user_state):
39
+ # Initialize State if empty
40
  if user_state is None:
41
  user_state = {"step": "ASK_AGE", "age": None, "location": None}
42
 
 
45
  if message.isdigit():
46
  user_state["age"] = int(message)
47
  user_state["step"] = "ASK_LOCATION"
48
+ reply = "Got it. For regional safety compliance, what is your general location (City/Country)?"
49
+ return history + [[message, reply]], user_state, ""
 
50
 
51
+ reply = "Welcome! I am your AI Librarian. To begin safely, how old are you?"
52
+ return history + [[message, reply]], user_state, ""
 
53
 
54
  if user_state["step"] == "ASK_LOCATION":
55
  user_state["location"] = message
56
  user_state["step"] = "SEARCH_READY"
57
+ reply = f"Verification complete for {user_state['location']}. How can I help you find a book today?"
58
+ return history + [[message, reply]], user_state, ""
 
59
 
60
+ # --- PHASE 2: SEARCH & LLM ACTION ---
61
  index, catalog = fetch_and_index(message)
62
+ context = "\n- ".join(catalog[:3]) if catalog else "No books found in live search."
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
63
 
64
+ # Constructing the DICT for the model (The fix for your error)
65
+ safety_context = "User is under 13; ensure recommendations are child-safe." if user_state["age"] < 13 else ""
66
+
67
+ messages = [
68
+ {"role": "system", "content": "You are a professional librarian. Use the context provided to recommend titles and authors."},
69
+ {"role": "user", "content": f"Context: {context}\nSafety: {safety_context}\nQuery: {message}"}
70
+ ]
71
 
72
+ response = ""
73
+ # Important: Named argument 'messages' is used here
74
+ for msg in client.chat_completion(
75
+ messages=messages,
76
+ max_tokens=300,
77
+ stream=True
78
+ ):
79
+ token = msg.choices[0].delta.content
80
+ if token:
81
+ response += token
82
+ yield history + [[message, response]], user_state, ""
83
 
84
+ # --- GRADIO UI ---
85
  with gr.Blocks(theme=gr.themes.Soft()) as demo:
86
  gr.Markdown("# 📚 AI Librarian Agent\n*Live Web Search + Semantic FAISS Ranking*")
87
 
88
  user_state = gr.State()
89
  chatbot = gr.Chatbot()
90
+ msg = gr.Textbox(label="Your Input", placeholder="Enter age first...")
91
+
92
+ # Logic link
93
  msg.submit(librarian_logic, [msg, chatbot, user_state], [chatbot, user_state, msg])
 
94
 
95
  if __name__ == "__main__":
96
  demo.launch()