Eteims commited on
Commit
26c6eb4
·
verified ·
1 Parent(s): ccbf880

Create app.py

Browse files
Files changed (1) hide show
  1. app.py +200 -0
app.py ADDED
@@ -0,0 +1,200 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import gradio as gr
2
+ from openai import OpenAI
3
+ import os
4
+ import json
5
+ from novita_sandbox.code_interpreter import Sandbox
6
+
7
+ # Create client
8
+ client = OpenAI(
9
+ base_url="https://api.novita.ai/openai",
10
+ api_key=os.environ["NOVITA_API_KEY"],
11
+ )
12
+
13
+ model = "meta-llama/llama-3.3-70b-instruct"
14
+
15
+ # Initialize sandbox with working directory
16
+ sandbox = Sandbox.create(timeout=1200)
17
+
18
+ # Define tool functions (no JSON serialization now)
19
+ def read_file(path: str):
20
+ print(f"[DEBUG] read_file called with path: {path}")
21
+ try:
22
+ content = sandbox.files.read(path)
23
+ print(f"[DEBUG] read_file result: {content}")
24
+ return content
25
+ except Exception as e:
26
+ print(f"[DEBUG] read_file error: {e}")
27
+ return f"Error reading file: {e}"
28
+
29
+ def write_file(path: str, data: str):
30
+ print(f"[DEBUG] write_file called with path: {path}")
31
+ try:
32
+ sandbox.files.write(path, data)
33
+ msg = f"File created successfully at {path}"
34
+ print(f"[DEBUG] {msg}")
35
+ return msg
36
+ except Exception as e:
37
+ print(f"[DEBUG] write_file error: {e}")
38
+ return f"Error writing file: {e}"
39
+
40
+ def write_files(files: list):
41
+ print(f"[DEBUG] write_files called with {len(files)} files")
42
+ try:
43
+ sandbox.files.write_files(files)
44
+ msg = f"{len(files)} file(s) created successfully"
45
+ print(f"[DEBUG] {msg}")
46
+ return msg
47
+ except Exception as e:
48
+ print(f"[DEBUG] write_files error: {e}")
49
+ return f"Error writing multiple files: {e}"
50
+
51
+ def run_commands(command: str):
52
+ print(f"[DEBUG] run_commands called with command: {command}")
53
+ try:
54
+ result = sandbox.commands.run(command)
55
+ print(f"[DEBUG] run_commands result: {result}")
56
+ return result.stdout
57
+ except Exception as e:
58
+ print(f"[DEBUG] run_commands error: {e}")
59
+ return f"Error running command: {e}"
60
+
61
+ # Register tools
62
+ tools = [
63
+ {
64
+ "type": "function",
65
+ "function": {
66
+ "name": "read_file",
67
+ "description": "Read contents of a file inside the sandbox",
68
+ "parameters": {
69
+ "type": "object",
70
+ "properties": {
71
+ "path": {"type": "string", "description": "File path in the sandbox"}
72
+ },
73
+ "required": ["path"],
74
+ },
75
+ },
76
+ },
77
+ {
78
+ "type": "function",
79
+ "function": {
80
+ "name": "write_file",
81
+ "description": "Write a single file inside the sandbox",
82
+ "parameters": {
83
+ "type": "object",
84
+ "properties": {
85
+ "path": {"type": "string", "description": "File path in the sandbox"},
86
+ "data": {"type": "string", "description": "Content to write"},
87
+ },
88
+ "required": ["path", "data"],
89
+ },
90
+ },
91
+ },
92
+ {
93
+ "type": "function",
94
+ "function": {
95
+ "name": "write_files",
96
+ "description": "Write multiple files inside the sandbox",
97
+ "parameters": {
98
+ "type": "object",
99
+ "properties": {
100
+ "files": {
101
+ "type": "array",
102
+ "items": {
103
+ "type": "object",
104
+ "properties": {
105
+ "path": {"type": "string"},
106
+ "data": {"type": "string"},
107
+ },
108
+ "required": ["path", "data"],
109
+ },
110
+ }
111
+ },
112
+ "required": ["files"],
113
+ },
114
+ },
115
+ },
116
+ {
117
+ "type": "function",
118
+ "function": {
119
+ "name": "run_commands",
120
+ "description": "Run a single shell command inside the sandbox working directory",
121
+ "parameters": {
122
+ "type": "object",
123
+ "properties": {
124
+ "command": {
125
+ "type": "string",
126
+ "description": "The shell command to run, e.g. 'ls' or 'python main.py'",
127
+ }
128
+ },
129
+ "required": ["command"],
130
+ },
131
+ },
132
+ }
133
+ ]
134
+
135
+ # Persistent messages
136
+ messages = []
137
+
138
+ def chat_fn(user_message, history):
139
+ global messages
140
+ messages.append({"role": "user", "content": user_message})
141
+
142
+ # Send to model
143
+ response = client.chat.completions.create(
144
+ model=model,
145
+ messages=messages,
146
+ tools=tools,
147
+ )
148
+
149
+ assistant_msg = response.choices[0].message
150
+ messages.append(assistant_msg)
151
+
152
+ output_text = ""
153
+
154
+ if assistant_msg.tool_calls:
155
+ print(f"[DEBUG] Assistant requested {len(assistant_msg.tool_calls)} tool call(s).")
156
+
157
+ for tool_call in assistant_msg.tool_calls:
158
+ fn_name = tool_call.function.name
159
+ fn_args = json.loads(tool_call.function.arguments)
160
+ print(f"[DEBUG] Tool call detected: {fn_name} with args {fn_args}")
161
+
162
+ if fn_name == "read_file":
163
+ fn_result = read_file(**fn_args)
164
+ elif fn_name == "write_file":
165
+ fn_result = write_file(**fn_args)
166
+ elif fn_name == "write_files":
167
+ fn_result = write_files(**fn_args)
168
+ elif fn_name == "run_commands":
169
+ fn_result = run_commands(**fn_args)
170
+ else:
171
+ fn_result = f"Error: Unknown tool {fn_name}"
172
+ print(f"[DEBUG] Unknown tool requested: {fn_name}")
173
+
174
+ messages.append({
175
+ "tool_call_id": tool_call.id,
176
+ "role": "tool",
177
+ "content": str(fn_result),
178
+ })
179
+
180
+ follow_up = client.chat.completions.create(
181
+ model=model,
182
+ messages=messages,
183
+ )
184
+ final_answer = follow_up.choices[0].message
185
+ messages.append(final_answer)
186
+ output_text = final_answer.content
187
+ else:
188
+ output_text = assistant_msg.content
189
+
190
+ return output_text
191
+
192
+ with gr.Blocks() as demo:
193
+ gr.ChatInterface(chat_fn, title="Sandbox Chat Agent")
194
+
195
+ # Graceful cleanup when the server stops
196
+ import atexit
197
+ atexit.register(lambda: (sandbox.kill(), print("[DEBUG] Sandbox terminated. 👋")))
198
+
199
+ if __name__ == "__main__":
200
+ demo.launch()