yrshi commited on
Commit
84486cb
·
1 Parent(s): ca9a33f

update some space settings

Browse files
Files changed (7) hide show
  1. README.md +6 -4
  2. app.py +224 -45
  3. app.py.bak +0 -249
  4. demo.py +70 -0
  5. install_env.sh +2 -1
  6. requirements.txt +15 -0
  7. setup.sh +1 -1
README.md CHANGED
@@ -1,11 +1,13 @@
1
  ---
2
  title: AutoRefine
3
- emoji: 💬
4
- colorFrom: yellow
5
  colorTo: purple
6
  sdk: gradio
7
- sdk_version: 5.42.0
8
- app_file: app.py
 
 
9
  pinned: false
10
  hf_oauth: true
11
  hf_oauth_scopes:
 
1
  ---
2
  title: AutoRefine
3
+ emoji: 🚀
4
+ colorFrom: blue
5
  colorTo: purple
6
  sdk: gradio
7
+ # sdk_version: 5.42.0
8
+ python_version: 3.10
9
+ models: ["yrshi/AutoRefine-Qwen2.5-3B-Base", "intfloat/e5-base-v2"]
10
+ app_file: demo.py
11
  pinned: false
12
  hf_oauth: true
13
  hf_oauth_scopes:
app.py CHANGED
@@ -1,20 +1,14 @@
 
 
 
 
1
  import gradio as gr
2
- from infer import run_search, question_list
3
 
4
  import subprocess
5
  import time
6
  import atexit
7
- from urllib.parse import urlparse
8
 
9
- # ... (keep all your other imports like transformers, torch, requests, re, gr) ...
10
-
11
- # --- NEW: Server Launch Block ---
12
- # Insert this block *before* you load the model
13
- # -----------------------------------------------------------------
14
- print("Attempting to start retrieval server...")
15
-
16
- # Start the server as a background process
17
- # subprocess.Popen does not block, unlike os.system
18
  try:
19
  server_process = subprocess.Popen(["bash", "retrieval_launch.sh"])
20
  print(f"Server process started with PID: {server_process.pid}")
@@ -27,44 +21,229 @@ try:
27
  print("Server process terminated.")
28
 
29
  atexit.register(cleanup)
30
-
31
  except Exception as e:
32
  print(f"Failed to start retrieval_launch.sh: {e}")
33
  print("WARNING: The retrieval server may not be running.")
34
 
35
- def gradio_answer(question: str) -> str:
36
- print(f"\nReceived question for Gradio: {question}")
37
- try:
38
- # Call the core inference function, passing the pre-loaded assets
39
- trajectory, answer = run_search(question)
40
- answer_string = f"Final answer: {answer.strip()}"
41
- answer_string += f"\n\n====== Trajectory of reasoning steps ======\n{trajectory.strip()}"
42
- return answer_string
43
- except Exception as e:
44
- # Basic error handling for the Gradio interface
45
- return f"An error occurred: {e}. Please check the console for more details."
46
-
47
-
48
- iface = gr.Interface(
49
- fn=gradio_answer,
50
- inputs=gr.Textbox(
51
- lines=3,
52
- label="Enter your question",
53
- placeholder="e.g., Who invented the telephone?"
54
- ),
55
- outputs=gr.Textbox(
56
- label="Answer",
57
- show_copy_button=True, # Allow users to easily copy the answer
58
- elem_id="answer_output" # Optional: for custom CSS/JS targeting
59
- ),
60
- title="Demo of AutoRefine: Question Answering with Search and Refine During Thinking",
61
- description=("Ask a question and this model will use a multi-turn reasoning and search mechanism to find the answer."),
62
- examples=question_list, # Use the list of example questions
63
- live=False, # Set to True if you want real-time updates as user types
64
- allow_flagging="never", # Disable flagging functionality
65
- theme=gr.themes.Soft(), # Apply a clean theme
66
- cache_examples=True, # Cache the examples for faster loading
67
  )
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
68
 
69
- iface.launch(share=True)
 
 
 
 
 
 
 
 
 
70
 
 
 
 
1
+ import transformers
2
+ import torch
3
+ import requests
4
+ import re
5
  import gradio as gr
6
+ from threading import Thread
7
 
8
  import subprocess
9
  import time
10
  import atexit
 
11
 
 
 
 
 
 
 
 
 
 
12
  try:
13
  server_process = subprocess.Popen(["bash", "retrieval_launch.sh"])
14
  print(f"Server process started with PID: {server_process.pid}")
 
21
  print("Server process terminated.")
22
 
23
  atexit.register(cleanup)
 
24
  except Exception as e:
25
  print(f"Failed to start retrieval_launch.sh: {e}")
26
  print("WARNING: The retrieval server may not be running.")
27
 
28
+ # --- Configuration --------------------------------------------------
29
+
30
+ # 1. DEFINE YOUR MODEL
31
+ model_id = "yrshi/AutoRefine-Qwen2.5-3B-Base"
32
+
33
+ # 2. !!! CRITICAL: UPDATE THIS URL !!!
34
+ # Your local 'http://127.0.0.1:8000/retrieve' will NOT work on Hugging Face.
35
+ # You must deploy your retrieval service and provide its public URL here.
36
+ RETRIEVER_URL = "http://127.0.0.1:8000/retrieve" # <-- UPDATE ME
37
+
38
+ # 3. MODEL & SEARCH CONSTANTS
39
+ curr_eos = [151645, 151643] # for Qwen2.5 series models
40
+ curr_search_template = '\n\n{output_text}<documents>{search_results}</documents>\n\n'
41
+ target_sequences = ["</search>", " </search>", "</search>\n", " </search>\n", "</search>\n\n", " </search>\n\n"]
42
+
43
+ # --- Global Model & Tokenizer Loading -------------------------------
44
+ # This happens once when the Space starts.
45
+ # Ensure your Space has a GPU assigned (e.g., T4, A10G).
46
+
47
+ print("Loading model and tokenizer...")
48
+ device = torch.device("cuda" if torch.cuda.is_available() else "cpu")
49
+
50
+ tokenizer = transformers.AutoTokenizer.from_pretrained(model_id)
51
+ model = transformers.AutoModelForCausalLM.from_pretrained(
52
+ model_id,
53
+ torch_dtype=torch.bfloat16,
54
+ device_map="auto"
 
 
 
 
 
55
  )
56
+ print("Model and tokenizer loaded successfully.")
57
+
58
+ # --- Custom Stopping Criteria Class ---------------------------------
59
+
60
+ class StopOnSequence(transformers.StoppingCriteria):
61
+ def __init__(self, target_sequences, tokenizer):
62
+ self.target_ids = [tokenizer.encode(target_sequence, add_special_tokens=False) for target_sequence in target_sequences]
63
+ self.target_lengths = [len(target_id) for target_id in self.target_ids]
64
+ self._tokenizer = tokenizer
65
+
66
+ def __call__(self, input_ids, scores, **kwargs):
67
+ targets = [torch.as_tensor(target_id, device=input_ids.device) for target_id in self.target_ids]
68
+ if input_ids.shape[1] < min(self.target_lengths):
69
+ return False
70
+ for i, target in enumerate(targets):
71
+ if torch.equal(input_ids[0, -self.target_lengths[i]:], target):
72
+ return True
73
+ return False
74
+
75
+ # Initialize stopping criteria globally
76
+ stopping_criteria = transformers.StoppingCriteriaList([StopOnSequence(target_sequences, tokenizer)])
77
+
78
+ # --- Helper Functions (Search & Parse) ------------------------------
79
+
80
+ def get_query(text):
81
+ pattern = re.compile(r"<search>(.*?)</search>", re.DOTALL)
82
+ matches = pattern.findall(text)
83
+ return matches[-1] if matches else None
84
+
85
+ def search(query: str):
86
+ """
87
+ Calls your deployed retriever service.
88
+ """
89
+ payload = {"queries": [query], "topk": 3, "return_scores": True}
90
+
91
+ if RETRIEVER_URL == "http://127.0.0.1:8000/retrieve":
92
+ print("WARNING: Using default local retriever URL. This will likely fail.")
93
+ print("Please update RETRIEVER_URL in app.py to your deployed service.")
94
+
95
+ try:
96
+ response = requests.post(RETRIEVER_URL, json=payload, timeout=10)
97
+ response.raise_for_status() # Raise an error for bad responses
98
+ results = response.json()['result']
99
+
100
+ format_reference = ''
101
+ for idx, doc_item in enumerate(results[0]):
102
+ content = doc_item['document']['contents']
103
+ title = content.split("\n")[0]
104
+ text = "\n".join(content.split("\n")[1:])
105
+ format_reference += f"Doc {idx+1}(Title: {title}) {text}\n"
106
+ return format_reference
107
+
108
+ except requests.exceptions.RequestException as e:
109
+ print(f"Error calling retriever: {e}")
110
+ return f"Error: Could not retrieve search results for query: {query}"
111
+ except (KeyError, IndexError):
112
+ print("Error parsing retriever response")
113
+ return "Error: Malformed response from retriever."
114
+
115
+ # --- Main Gradio 'respond' Function ---------------------------------
116
+
117
+ def respond(
118
+ message,
119
+ history: list[dict[str, str]],
120
+ system_message, # This is now our base prompt
121
+ max_tokens,
122
+ temperature,
123
+ top_p,
124
+ hf_token: gr.OAuthToken = None, # Not used here, but in template
125
+ ):
126
+ """
127
+ This function implements your local multi-turn search logic as a
128
+ streaming generator for the Gradio interface.
129
+ """
130
+
131
+ question = message.strip()
132
+
133
+ # Use the system_message from the UI as the base prompt
134
+ # Or, if empty, use your default.
135
+ if not system_message:
136
+ system_message = """You are a helpful assistant excel at answering questions with multi-turn search engine calling. \
137
+ To answer questions, you must first reason through the available information using <think> and </think>. \
138
+ If you identify missing knowledge, you may issue a search request using <search> query </search> at any time. The retrieval system will provide you with the three most relevant documents enclosed in <documents> and </documents>. \
139
+ After each search, you need to summarize and refine the existing documents in <refine> and </refine>. \
140
+ You may send multiple search requests if needed. \
141
+ Once you have sufficient information, provide a concise final answer using <answer> and </answer>. For example, <answer> Donald Trump </answer>."""
142
+
143
+ prompt = f"{system_message} Question: {question}\n"
144
+
145
+ if tokenizer.chat_template:
146
+ # Apply chat template if it exists
147
+ # Note: Your logic builds the prompt manually, but this ensures
148
+ # correct special tokens if the model needs them.
149
+ chat_prompt = [{"role": "user", "content": prompt}]
150
+ prompt = tokenizer.apply_chat_template(chat_prompt, add_generation_prompt=True, tokenize=False)
151
+
152
+ # This string will accumulate the full agent trajectory
153
+ full_response_trajectory = ""
154
+
155
+ while True:
156
+ input_ids = tokenizer.encode(prompt, return_tensors='pt').to(device)
157
+ attention_mask = torch.ones_like(input_ids)
158
+
159
+ # Check for context overflow
160
+ if input_ids.shape[1] > model.config.max_position_embeddings - max_tokens:
161
+ print("Context limit reached.")
162
+ full_response_trajectory += "\n\n[Error: Context limit reached. Aborting.]"
163
+ yield full_response_trajectory
164
+ break
165
+
166
+ # Generate text with the stopping criteria
167
+ outputs = model.generate(
168
+ input_ids,
169
+ attention_mask=attention_mask,
170
+ max_new_tokens=max_tokens,
171
+ stopping_criteria=stopping_criteria,
172
+ pad_token_id=tokenizer.eos_token_id,
173
+ do_sample=True,
174
+ temperature=temperature,
175
+ top_p=top_p
176
+ )
177
+
178
+ # Decode the *newly* generated tokens
179
+ generated_token_ids = outputs[0][input_ids.shape[1]:]
180
+ output_text = tokenizer.decode(generated_token_ids, skip_special_tokens=True)
181
+
182
+ # Check if generation ended with an EOS token
183
+ if outputs[0][-1].item() in curr_eos:
184
+ full_response_trajectory += output_text
185
+ yield full_response_trajectory # Yield the final text
186
+ break # Exit the loop
187
+
188
+ # --- Generation stopped at </search> ---
189
+
190
+ # Get the full text (prompt + new generation) to parse the *last* query
191
+ full_generation_text = tokenizer.decode(outputs[0], skip_special_tokens=True)
192
+ query_text = get_query(full_generation_text)
193
+
194
+ if query_text:
195
+ search_results = search(query_text)
196
+ else:
197
+ search_results = 'Error: Stop token found but no <search> query was parsed.'
198
+
199
+ # Construct the text to append to the prompt
200
+ search_text = curr_search_template.format(
201
+ output_text=output_text,
202
+ search_results=search_results
203
+ )
204
+
205
+ # Append to the prompt for the next loop
206
+ prompt += search_text
207
+
208
+ # Append to the trajectory string and yield to the UI
209
+ full_response_trajectory += search_text
210
+ yield full_response_trajectory
211
+
212
+
213
+ # --- Gradio UI (Example) -------------------------------------------
214
+ # This part is just to make the file runnable.
215
+ # You can customize your Gradio UI as needed.
216
+
217
+ with gr.Blocks() as demo:
218
+ gr.Markdown("# Multi-Turn Search Agent")
219
+ gr.Markdown(f"Running model: `{model_id}`")
220
+
221
+ with gr.Accordion("Prompt & Parameters"):
222
+ system_message = gr.Textbox(
223
+ label="System Message",
224
+ value="""You are a helpful assistant... (full prompt from code)""",
225
+ lines=10
226
+ )
227
+ max_tokens = gr.Slider(50, 2048, value=1024, label="Max New Tokens")
228
+ temperature = gr.Slider(0.1, 1.0, value=0.7, label="Temperature")
229
+ top_p = gr.Slider(0.1, 1.0, value=1.0, label="Top-p")
230
+
231
+ chatbot = gr.Chatbot(label="Agent Trajectory")
232
+ msg = gr.Textbox(label="Your Question")
233
+
234
+ def user_turn(user_message, history):
235
+ return "", history + [[user_message, None]]
236
 
237
+ msg.submit(
238
+ user_turn,
239
+ [msg, chatbot],
240
+ [msg, chatbot],
241
+ queue=False
242
+ ).then(
243
+ respond,
244
+ [msg, chatbot, system_message, max_tokens, temperature, top_p],
245
+ chatbot
246
+ )
247
 
248
+ if __name__ == "__main__":
249
+ demo.queue().launch(debug=True)
app.py.bak DELETED
@@ -1,249 +0,0 @@
1
- import transformers
2
- import torch
3
- import requests
4
- import re
5
- import gradio as gr
6
- from threading import Thread
7
-
8
- import subprocess
9
- import time
10
- import atexit
11
-
12
- try:
13
- server_process = subprocess.Popen(["bash", "retrieval_launch.sh"])
14
- print(f"Server process started with PID: {server_process.pid}")
15
-
16
- # Register a function to kill the server when app.py exits
17
- def cleanup():
18
- print("Shutting down retrieval server...")
19
- server_process.terminate()
20
- server_process.wait()
21
- print("Server process terminated.")
22
-
23
- atexit.register(cleanup)
24
- except Exception as e:
25
- print(f"Failed to start retrieval_launch.sh: {e}")
26
- print("WARNING: The retrieval server may not be running.")
27
-
28
- # --- Configuration --------------------------------------------------
29
-
30
- # 1. DEFINE YOUR MODEL
31
- model_id = "yrshi/AutoRefine-Qwen2.5-3B-Base"
32
-
33
- # 2. !!! CRITICAL: UPDATE THIS URL !!!
34
- # Your local 'http://127.0.0.1:8000/retrieve' will NOT work on Hugging Face.
35
- # You must deploy your retrieval service and provide its public URL here.
36
- RETRIEVER_URL = "http://127.0.0.1:8000/retrieve" # <-- UPDATE ME
37
-
38
- # 3. MODEL & SEARCH CONSTANTS
39
- curr_eos = [151645, 151643] # for Qwen2.5 series models
40
- curr_search_template = '\n\n{output_text}<documents>{search_results}</documents>\n\n'
41
- target_sequences = ["</search>", " </search>", "</search>\n", " </search>\n", "</search>\n\n", " </search>\n\n"]
42
-
43
- # --- Global Model & Tokenizer Loading -------------------------------
44
- # This happens once when the Space starts.
45
- # Ensure your Space has a GPU assigned (e.g., T4, A10G).
46
-
47
- print("Loading model and tokenizer...")
48
- device = torch.device("cuda" if torch.cuda.is_available() else "cpu")
49
-
50
- tokenizer = transformers.AutoTokenizer.from_pretrained(model_id)
51
- model = transformers.AutoModelForCausalLM.from_pretrained(
52
- model_id,
53
- torch_dtype=torch.bfloat16,
54
- device_map="auto"
55
- )
56
- print("Model and tokenizer loaded successfully.")
57
-
58
- # --- Custom Stopping Criteria Class ---------------------------------
59
-
60
- class StopOnSequence(transformers.StoppingCriteria):
61
- def __init__(self, target_sequences, tokenizer):
62
- self.target_ids = [tokenizer.encode(target_sequence, add_special_tokens=False) for target_sequence in target_sequences]
63
- self.target_lengths = [len(target_id) for target_id in self.target_ids]
64
- self._tokenizer = tokenizer
65
-
66
- def __call__(self, input_ids, scores, **kwargs):
67
- targets = [torch.as_tensor(target_id, device=input_ids.device) for target_id in self.target_ids]
68
- if input_ids.shape[1] < min(self.target_lengths):
69
- return False
70
- for i, target in enumerate(targets):
71
- if torch.equal(input_ids[0, -self.target_lengths[i]:], target):
72
- return True
73
- return False
74
-
75
- # Initialize stopping criteria globally
76
- stopping_criteria = transformers.StoppingCriteriaList([StopOnSequence(target_sequences, tokenizer)])
77
-
78
- # --- Helper Functions (Search & Parse) ------------------------------
79
-
80
- def get_query(text):
81
- pattern = re.compile(r"<search>(.*?)</search>", re.DOTALL)
82
- matches = pattern.findall(text)
83
- return matches[-1] if matches else None
84
-
85
- def search(query: str):
86
- """
87
- Calls your deployed retriever service.
88
- """
89
- payload = {"queries": [query], "topk": 3, "return_scores": True}
90
-
91
- if RETRIEVER_URL == "http://127.0.0.1:8000/retrieve":
92
- print("WARNING: Using default local retriever URL. This will likely fail.")
93
- print("Please update RETRIEVER_URL in app.py to your deployed service.")
94
-
95
- try:
96
- response = requests.post(RETRIEVER_URL, json=payload, timeout=10)
97
- response.raise_for_status() # Raise an error for bad responses
98
- results = response.json()['result']
99
-
100
- format_reference = ''
101
- for idx, doc_item in enumerate(results[0]):
102
- content = doc_item['document']['contents']
103
- title = content.split("\n")[0]
104
- text = "\n".join(content.split("\n")[1:])
105
- format_reference += f"Doc {idx+1}(Title: {title}) {text}\n"
106
- return format_reference
107
-
108
- except requests.exceptions.RequestException as e:
109
- print(f"Error calling retriever: {e}")
110
- return f"Error: Could not retrieve search results for query: {query}"
111
- except (KeyError, IndexError):
112
- print("Error parsing retriever response")
113
- return "Error: Malformed response from retriever."
114
-
115
- # --- Main Gradio 'respond' Function ---------------------------------
116
-
117
- def respond(
118
- message,
119
- history: list[dict[str, str]],
120
- system_message, # This is now our base prompt
121
- max_tokens,
122
- temperature,
123
- top_p,
124
- hf_token: gr.OAuthToken = None, # Not used here, but in template
125
- ):
126
- """
127
- This function implements your local multi-turn search logic as a
128
- streaming generator for the Gradio interface.
129
- """
130
-
131
- question = message.strip()
132
-
133
- # Use the system_message from the UI as the base prompt
134
- # Or, if empty, use your default.
135
- if not system_message:
136
- system_message = """You are a helpful assistant excel at answering questions with multi-turn search engine calling. \
137
- To answer questions, you must first reason through the available information using <think> and </think>. \
138
- If you identify missing knowledge, you may issue a search request using <search> query </search> at any time. The retrieval system will provide you with the three most relevant documents enclosed in <documents> and </documents>. \
139
- After each search, you need to summarize and refine the existing documents in <refine> and </refine>. \
140
- You may send multiple search requests if needed. \
141
- Once you have sufficient information, provide a concise final answer using <answer> and </answer>. For example, <answer> Donald Trump </answer>."""
142
-
143
- prompt = f"{system_message} Question: {question}\n"
144
-
145
- if tokenizer.chat_template:
146
- # Apply chat template if it exists
147
- # Note: Your logic builds the prompt manually, but this ensures
148
- # correct special tokens if the model needs them.
149
- chat_prompt = [{"role": "user", "content": prompt}]
150
- prompt = tokenizer.apply_chat_template(chat_prompt, add_generation_prompt=True, tokenize=False)
151
-
152
- # This string will accumulate the full agent trajectory
153
- full_response_trajectory = ""
154
-
155
- while True:
156
- input_ids = tokenizer.encode(prompt, return_tensors='pt').to(device)
157
- attention_mask = torch.ones_like(input_ids)
158
-
159
- # Check for context overflow
160
- if input_ids.shape[1] > model.config.max_position_embeddings - max_tokens:
161
- print("Context limit reached.")
162
- full_response_trajectory += "\n\n[Error: Context limit reached. Aborting.]"
163
- yield full_response_trajectory
164
- break
165
-
166
- # Generate text with the stopping criteria
167
- outputs = model.generate(
168
- input_ids,
169
- attention_mask=attention_mask,
170
- max_new_tokens=max_tokens,
171
- stopping_criteria=stopping_criteria,
172
- pad_token_id=tokenizer.eos_token_id,
173
- do_sample=True,
174
- temperature=temperature,
175
- top_p=top_p
176
- )
177
-
178
- # Decode the *newly* generated tokens
179
- generated_token_ids = outputs[0][input_ids.shape[1]:]
180
- output_text = tokenizer.decode(generated_token_ids, skip_special_tokens=True)
181
-
182
- # Check if generation ended with an EOS token
183
- if outputs[0][-1].item() in curr_eos:
184
- full_response_trajectory += output_text
185
- yield full_response_trajectory # Yield the final text
186
- break # Exit the loop
187
-
188
- # --- Generation stopped at </search> ---
189
-
190
- # Get the full text (prompt + new generation) to parse the *last* query
191
- full_generation_text = tokenizer.decode(outputs[0], skip_special_tokens=True)
192
- query_text = get_query(full_generation_text)
193
-
194
- if query_text:
195
- search_results = search(query_text)
196
- else:
197
- search_results = 'Error: Stop token found but no <search> query was parsed.'
198
-
199
- # Construct the text to append to the prompt
200
- search_text = curr_search_template.format(
201
- output_text=output_text,
202
- search_results=search_results
203
- )
204
-
205
- # Append to the prompt for the next loop
206
- prompt += search_text
207
-
208
- # Append to the trajectory string and yield to the UI
209
- full_response_trajectory += search_text
210
- yield full_response_trajectory
211
-
212
-
213
- # --- Gradio UI (Example) -------------------------------------------
214
- # This part is just to make the file runnable.
215
- # You can customize your Gradio UI as needed.
216
-
217
- with gr.Blocks() as demo:
218
- gr.Markdown("# Multi-Turn Search Agent")
219
- gr.Markdown(f"Running model: `{model_id}`")
220
-
221
- with gr.Accordion("Prompt & Parameters"):
222
- system_message = gr.Textbox(
223
- label="System Message",
224
- value="""You are a helpful assistant... (full prompt from code)""",
225
- lines=10
226
- )
227
- max_tokens = gr.Slider(50, 2048, value=1024, label="Max New Tokens")
228
- temperature = gr.Slider(0.1, 1.0, value=0.7, label="Temperature")
229
- top_p = gr.Slider(0.1, 1.0, value=1.0, label="Top-p")
230
-
231
- chatbot = gr.Chatbot(label="Agent Trajectory")
232
- msg = gr.Textbox(label="Your Question")
233
-
234
- def user_turn(user_message, history):
235
- return "", history + [[user_message, None]]
236
-
237
- msg.submit(
238
- user_turn,
239
- [msg, chatbot],
240
- [msg, chatbot],
241
- queue=False
242
- ).then(
243
- respond,
244
- [msg, chatbot, system_message, max_tokens, temperature, top_p],
245
- chatbot
246
- )
247
-
248
- if __name__ == "__main__":
249
- demo.queue().launch(debug=True)
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
demo.py ADDED
@@ -0,0 +1,70 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import gradio as gr
2
+ from infer import run_search, question_list
3
+
4
+ import subprocess
5
+ import time
6
+ import atexit
7
+ from urllib.parse import urlparse
8
+
9
+ # ... (keep all your other imports like transformers, torch, requests, re, gr) ...
10
+
11
+ # --- NEW: Server Launch Block ---
12
+ # Insert this block *before* you load the model
13
+ # -----------------------------------------------------------------
14
+ print("Attempting to start retrieval server...")
15
+
16
+ # Start the server as a background process
17
+ # subprocess.Popen does not block, unlike os.system
18
+ try:
19
+ server_process = subprocess.Popen(["bash", "retrieval_launch.sh"])
20
+ print(f"Server process started with PID: {server_process.pid}")
21
+
22
+ # Register a function to kill the server when app.py exits
23
+ def cleanup():
24
+ print("Shutting down retrieval server...")
25
+ server_process.terminate()
26
+ server_process.wait()
27
+ print("Server process terminated.")
28
+
29
+ atexit.register(cleanup)
30
+
31
+ except Exception as e:
32
+ print(f"Failed to start retrieval_launch.sh: {e}")
33
+ print("WARNING: The retrieval server may not be running.")
34
+
35
+ def gradio_answer(question: str) -> str:
36
+ print(f"\nReceived question for Gradio: {question}")
37
+ try:
38
+ # Call the core inference function, passing the pre-loaded assets
39
+ trajectory, answer = run_search(question)
40
+ answer_string = f"Final answer: {answer.strip()}"
41
+ answer_string += f"\n\n====== Trajectory of reasoning steps ======\n{trajectory.strip()}"
42
+ return answer_string
43
+ except Exception as e:
44
+ # Basic error handling for the Gradio interface
45
+ return f"An error occurred: {e}. Please check the console for more details."
46
+
47
+
48
+ iface = gr.Interface(
49
+ fn=gradio_answer,
50
+ inputs=gr.Textbox(
51
+ lines=3,
52
+ label="Enter your question",
53
+ placeholder="e.g., Who invented the telephone?"
54
+ ),
55
+ outputs=gr.Textbox(
56
+ label="Answer",
57
+ show_copy_button=True, # Allow users to easily copy the answer
58
+ elem_id="answer_output" # Optional: for custom CSS/JS targeting
59
+ ),
60
+ title="Demo of AutoRefine: Question Answering with Search and Refine During Thinking",
61
+ description=("Ask a question and this model will use a multi-turn reasoning and search mechanism to find the answer."),
62
+ examples=question_list, # Use the list of example questions
63
+ live=False, # Set to True if you want real-time updates as user types
64
+ allow_flagging="never", # Disable flagging functionality
65
+ theme=gr.themes.Soft(), # Apply a clean theme
66
+ cache_examples=True, # Cache the examples for faster loading
67
+ )
68
+
69
+ iface.launch(share=True)
70
+
install_env.sh CHANGED
@@ -1,5 +1,6 @@
1
  # Run this code manually
2
- # conda create -n faiss_env python=3.10 && conda activate faiss_env
 
3
 
4
  conda install pytorch==2.4.0 torchvision==0.19.0 torchaudio==2.4.0 pytorch-cuda=12.1 -c pytorch -c nvidia -y
5
  pip install transformers datasets pyserini
 
1
  # Run this code manually
2
+ conda tos accept --override-channels --channel https://repo.anaconda.com/pkgs/main
3
+ conda tos accept --override-channels --channel https://repo.anaconda.com/pkgs/r
4
 
5
  conda install pytorch==2.4.0 torchvision==0.19.0 torchaudio==2.4.0 pytorch-cuda=12.1 -c pytorch -c nvidia -y
6
  pip install transformers datasets pyserini
requirements.txt ADDED
@@ -0,0 +1,15 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # Run this code manually
2
+ torch==2.4.0
3
+ torchvision==0.19.0
4
+ torchaudio==2.4.0
5
+ transformers
6
+ datasets
7
+ pyserini
8
+ faiss-gpu=1.8.0
9
+ uvicorn
10
+ fastapi
11
+ huggingface_hub
12
+ pydantic
13
+ hf_transfer
14
+ accelerate
15
+ gradio
setup.sh CHANGED
@@ -11,5 +11,5 @@ python download_model.py
11
  bash retrieval_launch.sh
12
  # sanity check
13
  python infer.py
14
- GRADIO_SERVER_PORT=7890 python demo.py
15
  ```
 
11
  bash retrieval_launch.sh
12
  # sanity check
13
  python infer.py
14
+ GRADIO_SERVER_PORT=7890 python app.py
15
  ```