desiree commited on
Commit
63ab561
·
verified ·
1 Parent(s): a05579f

Update app.py

Browse files
Files changed (1) hide show
  1. app.py +90 -116
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 FunctionManager:
7
  def __init__(self):
 
8
  self.executor = concurrent.futures.ThreadPoolExecutor(max_workers=1)
9
- self.functions = {}
10
 
11
- def validate_function_json(self, json_str):
12
- """Validate function JSON format."""
13
- try:
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
- is_valid, result = self.validate_function_json(function_json)
32
- if not is_valid:
33
- return f"Error: {result}"
34
-
35
- function_name = result['name']
36
- self.functions[function_name] = result
37
- return f"Successfully added function: {function_name}"
38
- except Exception as e:
39
- return f"Error adding function: {str(e)}\n{traceback.format_exc()}"
 
 
 
 
40
 
41
- def list_functions(self):
42
- """List all registered functions."""
43
- try:
44
- if not self.functions:
45
- return "No functions registered."
46
-
47
- output = ["# Registered Functions"]
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 "\n".join(output)
62
  except Exception as e:
63
- return f"Error listing functions: {str(e)}\n{traceback.format_exc()}"
 
64
 
65
- def format_function_call(self, function_name, parameters):
66
- """Format a function call into the HuggingChat format."""
67
  try:
68
- if function_name not in self.functions:
69
- return False, f"Function '{function_name}' not found"
70
-
71
- function_def = self.functions[function_name]
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 False, f"Error formatting function call: {str(e)}"
80
 
81
  def __del__(self):
82
  self.executor.shutdown(wait=False)
 
 
 
 
 
83
 
84
  def create_interface():
85
- manager = FunctionManager()
86
-
87
- with gr.Blocks(theme=gr.themes.Soft()) as demo:
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
- with gr.Tab("List Functions"):
118
- list_output = gr.Markdown(label="Registered Functions")
119
- list_btn = gr.Button("List Functions")
120
- list_btn.click(
121
- manager.list_functions,
122
- outputs=[list_output]
123
- )
124
 
125
- with gr.Tab("Format Function Call"):
126
- with gr.Row():
127
- call_name = gr.Textbox(label="Function Name", lines=1)
128
- call_params = gr.Textbox(
129
- label="Parameters (JSON)",
130
- placeholder='{"param1": "value1"}',
131
- lines=5
132
- )
133
- format_output = gr.Textbox(label="Formatted Call", lines=5)
134
- format_btn = gr.Button("Format Call")
135
- format_btn.click(
136
- lambda n, p: manager.format_function_call(n, json.loads(p))[1],
137
- inputs=[call_name, call_params],
138
- outputs=[format_output]
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__":