THED1 commited on
Commit
59917bd
·
verified ·
1 Parent(s): 5494add

Upload app.py with huggingface_hub

Browse files
Files changed (1) hide show
  1. app.py +54 -136
app.py CHANGED
@@ -2,204 +2,122 @@ import gradio as gr
2
  import subprocess
3
  import os
4
  import json
5
- import tempfile
6
- from datetime import datetime
7
 
8
  # ============================================
9
  # TOOL DEFINITIONS
10
  # ============================================
11
 
12
  def tool_bash(command: str) -> str:
13
- """Execute bash command and return output"""
14
  try:
15
- result = subprocess.run(
16
- command,
17
- shell=True,
18
- capture_output=True,
19
- text=True,
20
- timeout=30
21
- )
22
- output = result.stdout if result.stdout else result.stderr
23
- return output[:5000] if output else "Command executed (no output)"
24
- except subprocess.TimeoutExpired:
25
- return "Error: Command timed out"
26
  except Exception as e:
27
  return f"Error: {str(e)}"
28
 
29
  def tool_write_file(path: str, content: str) -> str:
30
- """Write content to a file"""
31
  try:
32
- os.makedirs(os.path.dirname(path), exist_ok=True) if os.path.dirname(path) else None
33
- with open(path, 'w', encoding='utf-8') as f:
34
  f.write(content)
35
- return f"File written successfully: {path}"
36
  except Exception as e:
37
  return f"Error: {str(e)}"
38
 
39
  def tool_read_file(path: str) -> str:
40
- """Read content from a file"""
41
  try:
42
- with open(path, 'r', encoding='utf-8') as f:
43
- content = f.read()
44
- return content[:10000] if len(content) > 10000 else content
45
  except Exception as e:
46
  return f"Error: {str(e)}"
47
 
48
  def tool_list_files(directory: str = ".") -> str:
49
- """List files in a directory"""
50
  try:
51
- files = os.listdir(directory)
52
- return "\n".join(files[:100])
53
  except Exception as e:
54
  return f"Error: {str(e)}"
55
 
56
- def tool_delete_file(path: str) -> str:
57
- """Delete a file"""
58
- try:
59
- os.remove(path)
60
- return f"File deleted: {path}"
61
- except Exception as e:
62
- return f"Error: {str(e)}"
63
-
64
- # Tool registry
65
  TOOLS = {
66
  "bash": tool_bash,
67
  "write_file": tool_write_file,
68
  "read_file": tool_read_file,
69
  "list_files": tool_list_files,
70
- "delete_file": tool_delete_file,
71
  }
72
 
73
  # ============================================
74
- # AI AGENT LOGIC
75
  # ============================================
76
 
77
  from huggingface_hub import InferenceClient
78
 
79
- # Free inference client
80
  client = InferenceClient(model="Qwen/Qwen2.5-72B-Instruct")
81
 
82
- SYSTEM_PROMPT = """You are AI7, a helpful AI assistant with tool access.
83
-
84
- You can use these tools by responding with JSON:
85
- - bash: Run shell commands
86
- - write_file: Create files (path, content)
87
- - read_file: Read files (path)
88
- - list_files: List directory (directory)
89
- - delete_file: Remove files (path)
90
 
91
- To use a tool, reply with:
92
- TOOL: {"name": "tool_name", "arguments": {"arg": "value"}}
 
 
 
93
 
94
- After the tool result, continue helping the user. Be helpful and friendly."""
 
95
 
96
- def parse_tool_call(text: str):
97
- """Parse tool call from model output"""
98
- import re
99
- match = re.search(r'TOOL:\s*(\{.*?\})', text, re.DOTALL)
100
- if match:
101
- try:
102
- return json.loads(match.group(1))
103
- except:
104
- return None
105
- return None
106
-
107
- def agent_chat(message, history):
108
- """Main chat function"""
109
- # Build messages list for the model
110
- messages = [{"role": "system", "content": SYSTEM_PROMPT}]
111
 
112
- # Add conversation history (tuple format: (user, assistant))
113
- for user_msg, assistant_msg in history:
114
- if user_msg:
115
- messages.append({"role": "user", "content": user_msg})
116
- if assistant_msg:
117
- messages.append({"role": "assistant", "content": assistant_msg})
118
 
119
  messages.append({"role": "user", "content": message})
120
 
121
  try:
122
- # Get response from model
123
- response = client.chat_completion(
124
- messages=messages,
125
- max_tokens=1024,
126
- temperature=0.7
127
- )
128
- assistant_message = response.choices[0].message.content
129
-
130
- # Check for tool calls and execute
131
- tool_call = parse_tool_call(assistant_message)
132
- max_iterations = 5
133
 
134
- while tool_call and max_iterations > 0:
135
- tool_name = tool_call.get("name")
136
- args = tool_call.get("arguments", {})
137
-
138
- if tool_name in TOOLS:
139
- try:
140
- result = TOOLS[tool_name](**args)
141
- except Exception as e:
142
- result = f"Error: {str(e)}"
 
 
 
 
 
 
143
 
144
- # Continue conversation with tool result
145
- messages.append({"role": "assistant", "content": assistant_message})
146
  messages.append({"role": "user", "content": f"Tool result:\n{result}"})
147
-
148
- response = client.chat_completion(
149
- messages=messages,
150
- max_tokens=1024,
151
- temperature=0.7
152
- )
153
- assistant_message = response.choices[0].message.content
154
- tool_call = parse_tool_call(assistant_message)
155
- else:
156
- break
157
-
158
- max_iterations -= 1
159
 
160
- return assistant_message
161
 
162
  except Exception as e:
163
- return f"Error: {str(e)}\n\nNote: Using free Hugging Face inference. May have rate limits."
164
 
165
  # ============================================
166
- # GRADIO INTERFACE
167
  # ============================================
168
 
169
- with gr.Blocks(title="AI7 Agent") as demo:
170
- gr.Markdown("""
171
- # AI7 - AI Agent with Tools
172
-
173
- An AI agent that can execute commands, read/write files, and help with tasks.
174
-
175
- **Tools:** bash, write_file, read_file, list_files, delete_file
176
-
177
- **Examples:**
178
- - "Create a hello.py file"
179
- - "List files in current directory"
180
- - "What is 2+2?"
181
- """)
182
-
183
- chatbot = gr.Chatbot(height=500)
184
 
185
  with gr.Row():
186
- msg = gr.Textbox(
187
- placeholder="Type your message...",
188
- show_label=False,
189
- scale=9
190
- )
191
- submit = gr.Button("Send", scale=1, variant="primary")
192
-
193
- clear = gr.Button("Clear Chat")
194
 
195
- def respond(message, chat_history):
196
- bot_message = agent_chat(message, chat_history)
197
- chat_history.append((message, bot_message))
198
- return "", chat_history
199
 
200
- msg.submit(respond, [msg, chatbot], [msg, chatbot])
201
- submit.click(respond, [msg, chatbot], [msg, chatbot])
202
- clear.click(lambda: [], None, chatbot, queue=False)
203
 
204
  if __name__ == "__main__":
205
  demo.launch(server_name="0.0.0.0", server_port=7860)
 
2
  import subprocess
3
  import os
4
  import json
 
 
5
 
6
  # ============================================
7
  # TOOL DEFINITIONS
8
  # ============================================
9
 
10
  def tool_bash(command: str) -> str:
 
11
  try:
12
+ result = subprocess.run(command, shell=True, capture_output=True, text=True, timeout=30)
13
+ return result.stdout[:3000] if result.stdout else result.stderr[:3000] or "Done"
 
 
 
 
 
 
 
 
 
14
  except Exception as e:
15
  return f"Error: {str(e)}"
16
 
17
  def tool_write_file(path: str, content: str) -> str:
 
18
  try:
19
+ with open(path, 'w') as f:
 
20
  f.write(content)
21
+ return f"Written to {path}"
22
  except Exception as e:
23
  return f"Error: {str(e)}"
24
 
25
  def tool_read_file(path: str) -> str:
 
26
  try:
27
+ with open(path, 'r') as f:
28
+ return f.read()[:5000]
 
29
  except Exception as e:
30
  return f"Error: {str(e)}"
31
 
32
  def tool_list_files(directory: str = ".") -> str:
 
33
  try:
34
+ return "\n".join(os.listdir(directory)[:50])
 
35
  except Exception as e:
36
  return f"Error: {str(e)}"
37
 
 
 
 
 
 
 
 
 
 
38
  TOOLS = {
39
  "bash": tool_bash,
40
  "write_file": tool_write_file,
41
  "read_file": tool_read_file,
42
  "list_files": tool_list_files,
 
43
  }
44
 
45
  # ============================================
46
+ # AI LOGIC
47
  # ============================================
48
 
49
  from huggingface_hub import InferenceClient
50
 
 
51
  client = InferenceClient(model="Qwen/Qwen2.5-72B-Instruct")
52
 
53
+ SYSTEM = """You are AI7, a helpful AI assistant.
 
 
 
 
 
 
 
54
 
55
+ Tools available (use JSON format to call):
56
+ - bash: {"tool": "bash", "command": "ls"}
57
+ - write_file: {"tool": "write_file", "path": "file.txt", "content": "text"}
58
+ - read_file: {"tool": "read_file", "path": "file.txt"}
59
+ - list_files: {"tool": "list_files", "dir": "."}
60
 
61
+ When you need to use a tool, respond with ONLY the JSON, nothing else.
62
+ Otherwise, respond normally to help the user."""
63
 
64
+ def chat(message, history):
65
+ messages = [{"role": "system", "content": SYSTEM}]
 
 
 
 
 
 
 
 
 
 
 
 
 
66
 
67
+ for user, bot in history:
68
+ messages.append({"role": "user", "content": user})
69
+ messages.append({"role": "assistant", "content": bot})
 
 
 
70
 
71
  messages.append({"role": "user", "content": message})
72
 
73
  try:
74
+ response = client.chat_completion(messages=messages, max_tokens=1024)
75
+ reply = response.choices[0].message.content
 
 
 
 
 
 
 
 
 
76
 
77
+ # Check for tool call
78
+ try:
79
+ tool_data = json.loads(reply.strip())
80
+ if "tool" in tool_data:
81
+ tool_name = tool_data["tool"]
82
+ if tool_name == "bash":
83
+ result = tool_bash(tool_data.get("command", ""))
84
+ elif tool_name == "write_file":
85
+ result = tool_write_file(tool_data.get("path", ""), tool_data.get("content", ""))
86
+ elif tool_name == "read_file":
87
+ result = tool_read_file(tool_data.get("path", ""))
88
+ elif tool_name == "list_files":
89
+ result = tool_list_files(tool_data.get("dir", "."))
90
+ else:
91
+ result = "Unknown tool"
92
 
93
+ # Get final response with tool result
94
+ messages.append({"role": "assistant", "content": reply})
95
  messages.append({"role": "user", "content": f"Tool result:\n{result}"})
96
+ response = client.chat_completion(messages=messages, max_tokens=1024)
97
+ return response.choices[0].message.content
98
+ except:
99
+ pass
 
 
 
 
 
 
 
 
100
 
101
+ return reply
102
 
103
  except Exception as e:
104
+ return f"Error: {str(e)}"
105
 
106
  # ============================================
107
+ # INTERFACE
108
  # ============================================
109
 
110
+ with gr.Blocks(title="AI7") as demo:
111
+ gr.Markdown("# AI7 - AI Agent\n\nAsk me anything. I can run commands and manage files.")
 
 
 
 
 
 
 
 
 
 
 
 
 
112
 
113
  with gr.Row():
114
+ inp = gr.Textbox(label="Message", scale=4)
115
+ btn = gr.Button("Send", variant="primary")
 
 
 
 
 
 
116
 
117
+ out = gr.Textbox(label="Response", lines=10)
 
 
 
118
 
119
+ btn.click(chat, [inp, gr.State([])], out)
120
+ inp.submit(chat, [inp, gr.State([])], out)
 
121
 
122
  if __name__ == "__main__":
123
  demo.launch(server_name="0.0.0.0", server_port=7860)