Spaces:
Sleeping
Sleeping
Update app.py
Browse files
app.py
CHANGED
@@ -1,143 +1,117 @@
|
|
1 |
import concurrent.futures
|
2 |
import gradio as gr
|
|
|
3 |
import json
|
4 |
import traceback
|
|
|
|
|
5 |
|
6 |
-
class
|
7 |
def __init__(self):
|
|
|
8 |
self.executor = concurrent.futures.ThreadPoolExecutor(max_workers=1)
|
9 |
-
self.
|
10 |
|
11 |
-
def
|
12 |
-
"""
|
13 |
-
|
14 |
-
function_data = json.loads(json_str)
|
15 |
-
required_fields = ['name', 'description', 'parameters']
|
16 |
-
if not all(field in function_data for field in required_fields):
|
17 |
-
return False, "Missing required fields: name, description, or parameters"
|
18 |
-
|
19 |
-
if not isinstance(function_data['parameters'], dict):
|
20 |
-
return False, "Parameters must be a JSON object"
|
21 |
-
|
22 |
-
return True, function_data
|
23 |
-
except json.JSONDecodeError as e:
|
24 |
-
return False, f"Invalid JSON format: {str(e)}"
|
25 |
-
except Exception as e:
|
26 |
-
return False, f"Validation error: {str(e)}"
|
27 |
|
28 |
-
def add_function(self, function_json):
|
29 |
-
"""Add a new function definition."""
|
30 |
try:
|
31 |
-
|
32 |
-
|
33 |
-
|
34 |
-
|
35 |
-
|
36 |
-
|
37 |
-
|
38 |
-
|
39 |
-
|
|
|
|
|
|
|
|
|
40 |
|
41 |
-
|
42 |
-
|
43 |
-
|
44 |
-
|
45 |
-
|
46 |
-
|
47 |
-
|
48 |
-
for name, func in self.functions.items():
|
49 |
-
output.append(f"\n## {name}")
|
50 |
-
output.append(f"Description: {func['description']}")
|
51 |
-
output.append("\nParameters:")
|
52 |
-
params = func['parameters']
|
53 |
-
if 'properties' in params:
|
54 |
-
for param_name, param_info in params['properties'].items():
|
55 |
-
output.append(f"- {param_name}: {param_info.get('description', 'No description')}")
|
56 |
-
if param_info.get('type'):
|
57 |
-
output.append(f" Type: {param_info['type']}")
|
58 |
-
if param_info.get('required', False):
|
59 |
-
output.append(" Required: Yes")
|
60 |
|
61 |
-
return
|
62 |
except Exception as e:
|
63 |
-
|
|
|
64 |
|
65 |
-
def
|
66 |
-
|
67 |
try:
|
68 |
-
|
69 |
-
|
70 |
-
|
71 |
-
|
72 |
-
function_call = {
|
73 |
-
"name": function_name,
|
74 |
-
"arguments": parameters
|
75 |
-
}
|
76 |
-
|
77 |
-
return True, json.dumps(function_call, indent=2)
|
78 |
except Exception as e:
|
79 |
-
return
|
80 |
|
81 |
def __del__(self):
|
82 |
self.executor.shutdown(wait=False)
|
|
|
|
|
|
|
|
|
|
|
83 |
|
84 |
def create_interface():
|
85 |
-
|
86 |
-
|
87 |
-
|
88 |
-
gr.Markdown("# HuggingChat Function Manager")
|
89 |
-
|
90 |
-
with gr.Tab("Add Function"):
|
91 |
-
function_json = gr.Textbox(
|
92 |
-
label="Function Definition (JSON)",
|
93 |
-
placeholder='''{
|
94 |
-
"name": "example_function",
|
95 |
-
"description": "An example function",
|
96 |
-
"parameters": {
|
97 |
-
"type": "object",
|
98 |
-
"properties": {
|
99 |
-
"param1": {
|
100 |
-
"type": "string",
|
101 |
-
"description": "First parameter"
|
102 |
-
}
|
103 |
-
},
|
104 |
-
"required": ["param1"]
|
105 |
-
}
|
106 |
-
}''',
|
107 |
-
lines=10
|
108 |
-
)
|
109 |
-
add_output = gr.Textbox(label="Result", lines=2)
|
110 |
-
add_btn = gr.Button("Add Function", variant="primary")
|
111 |
-
add_btn.click(
|
112 |
-
manager.add_function,
|
113 |
-
inputs=[function_json],
|
114 |
-
outputs=[add_output]
|
115 |
-
)
|
116 |
|
117 |
-
|
118 |
-
|
119 |
-
|
120 |
-
|
121 |
-
|
122 |
-
|
123 |
-
)
|
124 |
|
125 |
-
|
126 |
-
|
127 |
-
|
128 |
-
|
129 |
-
|
130 |
-
|
131 |
-
|
132 |
-
|
133 |
-
|
134 |
-
|
135 |
-
|
136 |
-
|
137 |
-
|
138 |
-
|
139 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
140 |
|
|
|
|
|
|
|
|
|
|
|
|
|
141 |
return demo
|
142 |
|
143 |
if __name__ == "__main__":
|
|
|
1 |
import concurrent.futures
|
2 |
import gradio as gr
|
3 |
+
from huggingface_hub import InferenceClient
|
4 |
import json
|
5 |
import traceback
|
6 |
+
import tempfile
|
7 |
+
import shutil
|
8 |
|
9 |
+
class HuggingChatExecutor:
|
10 |
def __init__(self):
|
11 |
+
self.temp_dir = tempfile.TemporaryDirectory()
|
12 |
self.executor = concurrent.futures.ThreadPoolExecutor(max_workers=1)
|
13 |
+
self.client = InferenceClient("HuggingFaceH4/zephyr-7b-beta")
|
14 |
|
15 |
+
def _execute_chat(self, message, system_prompt, functions=None):
|
16 |
+
messages = [{"role": "system", "content": system_prompt}]
|
17 |
+
messages.append({"role": "user", "content": message})
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
18 |
|
|
|
|
|
19 |
try:
|
20 |
+
if functions:
|
21 |
+
# Parse functions string as JSON array
|
22 |
+
functions_list = json.loads(functions)
|
23 |
+
response = self.client.chat_completion(
|
24 |
+
messages,
|
25 |
+
functions=functions_list,
|
26 |
+
stream=False
|
27 |
+
)
|
28 |
+
else:
|
29 |
+
response = self.client.chat_completion(
|
30 |
+
messages,
|
31 |
+
stream=False
|
32 |
+
)
|
33 |
|
34 |
+
# Format the output
|
35 |
+
output = {
|
36 |
+
"message": message,
|
37 |
+
"system_prompt": system_prompt,
|
38 |
+
"functions": functions if functions else "No functions provided",
|
39 |
+
"response": response.choices[0].message
|
40 |
+
}
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
41 |
|
42 |
+
return json.dumps(output, indent=2)
|
43 |
except Exception as e:
|
44 |
+
error_trace = traceback.format_exc()
|
45 |
+
return f"Error executing chat:\n{str(e)}\n\nTraceback:\n{error_trace}"
|
46 |
|
47 |
+
def execute(self, message, system_prompt, functions):
|
48 |
+
future = self.executor.submit(self._execute_chat, message, system_prompt, functions)
|
49 |
try:
|
50 |
+
output = future.result(timeout=30)
|
51 |
+
return output
|
52 |
+
except concurrent.futures.TimeoutError:
|
53 |
+
return "Error: Timed out waiting for chat response"
|
|
|
|
|
|
|
|
|
|
|
|
|
54 |
except Exception as e:
|
55 |
+
return f"Error: {str(e)}"
|
56 |
|
57 |
def __del__(self):
|
58 |
self.executor.shutdown(wait=False)
|
59 |
+
shutil.rmtree(self.temp_dir.name)
|
60 |
+
|
61 |
+
def wrapper_execute(message, system_prompt, functions):
|
62 |
+
executor = HuggingChatExecutor()
|
63 |
+
return executor.execute(message, system_prompt, functions)
|
64 |
|
65 |
def create_interface():
|
66 |
+
with gr.Blocks() as demo:
|
67 |
+
gr.Markdown("# HuggingChat Tool Executor")
|
68 |
+
gr.Markdown("Execute chat completions with function calling capabilities")
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
69 |
|
70 |
+
gr.Markdown("### Message")
|
71 |
+
message_input = gr.Textbox(
|
72 |
+
label="User Message",
|
73 |
+
placeholder="Enter your message here...",
|
74 |
+
lines=3
|
75 |
+
)
|
|
|
76 |
|
77 |
+
gr.Markdown("### System Prompt")
|
78 |
+
system_input = gr.Textbox(
|
79 |
+
label="System Prompt",
|
80 |
+
value="You are a helpful AI assistant.",
|
81 |
+
lines=2
|
82 |
+
)
|
83 |
+
|
84 |
+
gr.Markdown("### Functions")
|
85 |
+
functions_input = gr.Textbox(
|
86 |
+
label="Functions (JSON array)",
|
87 |
+
placeholder='''[
|
88 |
+
{
|
89 |
+
"name": "get_weather",
|
90 |
+
"description": "Get the weather in a location",
|
91 |
+
"parameters": {
|
92 |
+
"type": "object",
|
93 |
+
"properties": {
|
94 |
+
"location": {
|
95 |
+
"type": "string",
|
96 |
+
"description": "The city and state, e.g. San Francisco, CA"
|
97 |
+
}
|
98 |
+
},
|
99 |
+
"required": ["location"]
|
100 |
+
}
|
101 |
+
}
|
102 |
+
]''',
|
103 |
+
lines=10
|
104 |
+
)
|
105 |
+
|
106 |
+
gr.Markdown("### Output")
|
107 |
+
output_text = gr.Textbox(label="Response", lines=20)
|
108 |
|
109 |
+
run_button = gr.Button("Run")
|
110 |
+
run_button.click(
|
111 |
+
wrapper_execute,
|
112 |
+
inputs=[message_input, system_input, functions_input],
|
113 |
+
outputs=output_text
|
114 |
+
)
|
115 |
return demo
|
116 |
|
117 |
if __name__ == "__main__":
|