thisisam commited on
Commit
3a32d35
Β·
1 Parent(s): 493fc32

updatedd app

Browse files
Files changed (1) hide show
  1. app.py +175 -27
app.py CHANGED
@@ -1,65 +1,213 @@
1
  import gradio as gr
2
  from huggingface_hub import InferenceClient
3
  import os
 
4
 
5
- # Initialize the Inference Client with correct endpoint
6
- client = InferenceClient(
7
- token=os.getenv("HF_TOKEN"),
8
- base_url="https://router.huggingface.co" # Updated endpoint
9
- )
10
 
11
  def chat_with_fara(message, history):
12
  """
13
- Interact with Fara-7B model via updated Hugging Face Inference API
14
  """
15
  try:
16
- # Build the conversation prompt
17
- conversation = ""
 
18
 
19
- # Add conversation history
20
- for user_msg, assistant_msg in history:
21
- conversation += f"User: {user_msg}\nAssistant: {assistant_msg}\n\n"
 
 
22
 
23
- # Add current message
24
- conversation += f"User: {message}\nAssistant:"
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
25
 
26
- # Call the inference API
27
  response = client.text_generation(
28
- prompt=conversation,
29
  model="microsoft/Fara-7B",
30
  max_new_tokens=500,
31
  temperature=0.7,
32
  do_sample=True
33
  )
34
 
 
 
 
 
35
  return response
36
 
37
  except Exception as e:
38
- return f"❌ API Error: {str(e)}"
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
39
 
40
  # Create the Gradio interface
41
  with gr.Blocks(theme=gr.themes.Soft()) as demo:
42
- gr.Markdown("# πŸ€– Fara-7B Chat Interface")
 
 
 
 
 
 
 
 
 
 
 
 
 
43
 
44
- chatbot = gr.Chatbot(height=400)
45
- msg = gr.Textbox(
46
- label="Your Message",
47
- placeholder="Ask me about web automation tasks...",
48
- lines=2
 
 
 
 
 
 
 
 
 
 
49
  )
50
 
51
  with gr.Row():
52
- send_btn = gr.Button("Send")
53
- clear_btn = gr.Button("Clear")
 
 
 
 
 
 
 
 
 
 
 
54
 
55
  def respond(message, chat_history):
56
- bot_response = chat_with_fara(message, chat_history)
57
- chat_history.append((message, bot_response))
58
  return "", chat_history
59
 
 
 
 
 
 
 
 
 
 
60
  msg.submit(respond, [msg, chatbot], [msg, chatbot])
61
  send_btn.click(respond, [msg, chatbot], [msg, chatbot])
62
  clear_btn.click(lambda: ([], ""), outputs=[chatbot, msg])
 
63
 
64
  if __name__ == "__main__":
65
- demo.launch(server_name="0.0.0.0", server_port=7860)
 
 
 
 
 
1
  import gradio as gr
2
  from huggingface_hub import InferenceClient
3
  import os
4
+ import json
5
 
6
+ # Initialize the Inference Client
7
+ client = InferenceClient(token=os.getenv("HF_TOKEN"))
 
 
 
8
 
9
  def chat_with_fara(message, history):
10
  """
11
+ Interact with Fara-7B using the correct format for agent tasks
12
  """
13
  try:
14
+ # Build the prompt in the expected format for Fara-7B
15
+ # Fara-7B is designed for web automation tasks with specific structure
16
+ system_prompt = """You are Fara, a web automation agent. You help users with web-based tasks by providing step-by-step guidance for browser automation."""
17
 
18
+ # Format messages for the model
19
+ messages = [
20
+ {"role": "system", "content": system_prompt},
21
+ {"role": "user", "content": message}
22
+ ]
23
 
24
+ # Use the conversational endpoint which is more appropriate
25
+ response = client.conversational(
26
+ text=message,
27
+ model="microsoft/Fara-7B",
28
+ max_length=500,
29
+ temperature=0.7
30
+ )
31
+
32
+ # Extract the response
33
+ if hasattr(response, 'generated_text'):
34
+ return response.generated_text
35
+ elif isinstance(response, str):
36
+ return response
37
+ else:
38
+ return str(response)
39
+
40
+ except Exception as e:
41
+ error_msg = f"❌ Error: {str(e)}"
42
+
43
+ # Provide specific guidance based on common errors
44
+ if "401" in str(e):
45
+ error_msg += "\n\nπŸ” Authentication failed. Please check:"
46
+ error_msg += "\n- Your HF_TOKEN is set in Space secrets"
47
+ error_msg += "\n- You have requested access to microsoft/Fara-7B"
48
+ error_msg += "\n- Your token has the necessary permissions"
49
+ elif "404" in str(e):
50
+ error_msg += "\n\nπŸ” Model not found. The model might be:"
51
+ error_msg += "\n- Private and requiring access request"
52
+ error_msg += "\n- Temporarily unavailable"
53
+ elif "403" in str(e):
54
+ error_msg += "\n\n🚫 Access forbidden. You need to:"
55
+ error_msg += "\n- Visit https://huggingface.co/microsoft/Fara-7B"
56
+ error_msg += "\n- Click 'Access repository' to request access"
57
+ error_msg += "\n- Wait for approval from Microsoft"
58
+
59
+ return error_msg
60
+
61
+ # Alternative: Use text generation with proper formatting
62
+ def chat_with_fara_text_generation(message, history):
63
+ """
64
+ Alternative approach using text generation with proper prompt formatting
65
+ """
66
+ try:
67
+ # Format prompt for agent tasks
68
+ prompt = f"""<|system|>
69
+ You are Fara, a web automation agent designed to help users with web-based tasks.
70
+
71
+ When responding:
72
+ 1. Break down complex web tasks into steps
73
+ 2. Suggest specific actions that could be automated
74
+ 3. Identify potential challenges in web automation
75
+ 4. Provide practical guidance for browser automation
76
+
77
+ <|user|>
78
+ {message}
79
+ <|assistant|>
80
+ """
81
 
 
82
  response = client.text_generation(
83
+ prompt=prompt,
84
  model="microsoft/Fara-7B",
85
  max_new_tokens=500,
86
  temperature=0.7,
87
  do_sample=True
88
  )
89
 
90
+ # Clean the response
91
+ if "<|assistant|>" in response:
92
+ response = response.split("<|assistant|>")[-1].strip()
93
+
94
  return response
95
 
96
  except Exception as e:
97
+ return f"❌ Text generation error: {str(e)}"
98
+
99
+ # Fallback function for when Fara-7B is not accessible
100
+ def fallback_chat(message, history):
101
+ """
102
+ Fallback when Fara-7B is not accessible
103
+ """
104
+ fallback_responses = {
105
+ "web automation": "For web automation tasks like the NSW grants search, you would typically:\n\n1. Navigate to https://www.nsw.gov.au/grants-and-funding\n2. Use search functionality to filter for 'healthcare' grants\n3. Extract the list of available funding opportunities\n4. Provide summaries with eligibility criteria and deadlines",
106
+
107
+ "general": "I'd be happy to help with web automation tasks! For tasks like finding grants on government websites, the process involves:\n- Website navigation\n- Search and filtering\n- Data extraction\n- Result organization"
108
+ }
109
+
110
+ # Simple keyword-based fallback
111
+ message_lower = message.lower()
112
+ if any(keyword in message_lower for keyword in ['grant', 'funding', 'nsw', 'healthcare']):
113
+ return fallback_responses["web automation"]
114
+ else:
115
+ return fallback_responses["general"]
116
+
117
+ def smart_chat_handler(message, history):
118
+ """
119
+ Smart handler that tries multiple approaches
120
+ """
121
+ # First try the conversational API
122
+ try:
123
+ response = chat_with_fara(message, history)
124
+ if "Error" not in response and "error" not in response.lower():
125
+ return response
126
+ except:
127
+ pass
128
+
129
+ # Then try text generation
130
+ try:
131
+ response = chat_with_fara_text_generation(message, history)
132
+ if "Error" not in response and "error" not in response.lower():
133
+ return response
134
+ except:
135
+ pass
136
+
137
+ # Finally use fallback
138
+ return fallback_chat(message, history)
139
 
140
  # Create the Gradio interface
141
  with gr.Blocks(theme=gr.themes.Soft()) as demo:
142
+ gr.Markdown(
143
+ """
144
+ # πŸ€– Fara-7B Web Automation Assistant
145
+
146
+ **Microsoft's specialized agent for web automation tasks**
147
+
148
+ This interface connects to the Fara-7B model designed for:
149
+ - Web navigation and automation
150
+ - Task planning for browser actions
151
+ - Step-by-step guidance for web tasks
152
+
153
+ ⚠️ **Note**: Access to Fara-7B requires permission from Microsoft.
154
+ """
155
+ )
156
 
157
+ # Add access information
158
+ with gr.Accordion("πŸ” Access Requirements", open=False):
159
+ gr.Markdown("""
160
+ To use Fara-7B, you need:
161
+ 1. **Access Request**: Visit [the model page](https://huggingface.co/microsoft/Fara-7B) and click "Access repository"
162
+ 2. **HF_TOKEN**: Add your Hugging Face token in Space secrets
163
+ 3. **Wait for Approval**: Microsoft needs to approve your access request
164
+
165
+ If you don't have access yet, this demo will show how Fara-7B would respond to web automation tasks.
166
+ """)
167
+
168
+ chatbot = gr.Chatbot(
169
+ height=500,
170
+ label="Web Automation Chat",
171
+ show_label=True
172
  )
173
 
174
  with gr.Row():
175
+ msg = gr.Textbox(
176
+ label="Web Task Description",
177
+ placeholder="Example: Go to NSW grants website and find healthcare funding...",
178
+ lines=2,
179
+ scale=4
180
+ )
181
+ send_btn = gr.Button("Execute Task", scale=1, variant="primary")
182
+
183
+ with gr.Row():
184
+ clear_btn = gr.Button("Clear Chat")
185
+ method_btn = gr.Button("Check Access Status")
186
+
187
+ output_status = gr.Textbox(label="Status", visible=False)
188
 
189
  def respond(message, chat_history):
190
+ response = smart_chat_handler(message, chat_history)
191
+ chat_history.append((message, response))
192
  return "", chat_history
193
 
194
+ def check_access():
195
+ try:
196
+ # Simple test to check if model is accessible
197
+ test_client = InferenceClient(token=os.getenv("HF_TOKEN"))
198
+ test_response = test_client.model_status("microsoft/Fara-7B")
199
+ return "βœ… Fara-7B is accessible!"
200
+ except Exception as e:
201
+ return f"❌ Access issue: {str(e)}"
202
+
203
  msg.submit(respond, [msg, chatbot], [msg, chatbot])
204
  send_btn.click(respond, [msg, chatbot], [msg, chatbot])
205
  clear_btn.click(lambda: ([], ""), outputs=[chatbot, msg])
206
+ method_btn.click(check_access, outputs=output_status)
207
 
208
  if __name__ == "__main__":
209
+ demo.launch(
210
+ server_name="0.0.0.0",
211
+ server_port=7860,
212
+ share=False
213
+ )