yrshi commited on
Commit
969257a
·
1 Parent(s): 0bdea9d

use demo as app for now

Browse files
Files changed (3) hide show
  1. app.py +34 -244
  2. app.py.bak +249 -0
  3. demo.py +0 -39
app.py CHANGED
@@ -1,249 +1,39 @@
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)
 
 
 
 
 
1
  import gradio as gr
2
+ from infer import run_search, question_list
3
 
4
+ def gradio_answer(question: str) -> str:
5
+ print(f"\nReceived question for Gradio: {question}")
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
6
  try:
7
+ # Call the core inference function, passing the pre-loaded assets
8
+ trajectory, answer = run_search(question)
9
+ answer_string = f"Final answer: {answer.strip()}"
10
+ answer_string += f"\n\n====== Trajectory of reasoning steps ======\n{trajectory.strip()}"
11
+ return answer_string
12
+ except Exception as e:
13
+ # Basic error handling for the Gradio interface
14
+ return f"An error occurred: {e}. Please check the console for more details."
15
+
16
+
17
+ iface = gr.Interface(
18
+ fn=gradio_answer,
19
+ inputs=gr.Textbox(
20
+ lines=3,
21
+ label="Enter your question",
22
+ placeholder="e.g., Who invented the telephone?"
23
+ ),
24
+ outputs=gr.Textbox(
25
+ label="Answer",
26
+ show_copy_button=True, # Allow users to easily copy the answer
27
+ elem_id="answer_output" # Optional: for custom CSS/JS targeting
28
+ ),
29
+ title="Demo of AutoRefine: Question Answering with Search and Refine During Thinking",
30
+ description=("Ask a question and this model will use a multi-turn reasoning and search mechanism to find the answer."),
31
+ examples=question_list, # Use the list of example questions
32
+ live=False, # Set to True if you want real-time updates as user types
33
+ allow_flagging="never", # Disable flagging functionality
34
+ theme=gr.themes.Soft(), # Apply a clean theme
35
+ cache_examples=True, # Cache the examples for faster loading
36
+ )
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
37
 
38
+ iface.launch(share=True)
 
 
 
 
 
 
 
 
 
39
 
 
 
app.py.bak ADDED
@@ -0,0 +1,249 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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 DELETED
@@ -1,39 +0,0 @@
1
- import gradio as gr
2
- from infer import run_search, question_list
3
-
4
- def gradio_answer(question: str) -> str:
5
- print(f"\nReceived question for Gradio: {question}")
6
- try:
7
- # Call the core inference function, passing the pre-loaded assets
8
- trajectory, answer = run_search(question)
9
- answer_string = f"Final answer: {answer.strip()}"
10
- answer_string += f"\n\n====== Trajectory of reasoning steps ======\n{trajectory.strip()}"
11
- return answer_string
12
- except Exception as e:
13
- # Basic error handling for the Gradio interface
14
- return f"An error occurred: {e}. Please check the console for more details."
15
-
16
-
17
- iface = gr.Interface(
18
- fn=gradio_answer,
19
- inputs=gr.Textbox(
20
- lines=3,
21
- label="Enter your question",
22
- placeholder="e.g., Who invented the telephone?"
23
- ),
24
- outputs=gr.Textbox(
25
- label="Answer",
26
- show_copy_button=True, # Allow users to easily copy the answer
27
- elem_id="answer_output" # Optional: for custom CSS/JS targeting
28
- ),
29
- title="Demo of AutoRefine: Question Answering with Search and Refine During Thinking",
30
- description=("Ask a question and this model will use a multi-turn reasoning and search mechanism to find the answer."),
31
- examples=question_list, # Use the list of example questions
32
- live=False, # Set to True if you want real-time updates as user types
33
- allow_flagging="never", # Disable flagging functionality
34
- theme=gr.themes.Soft(), # Apply a clean theme
35
- cache_examples=True, # Cache the examples for faster loading
36
- )
37
-
38
- iface.launch(share=True)
39
-