File size: 6,338 Bytes
751e7d4
085880a
d2daf95
f7a9983
 
3b5590f
401ca9f
b98f2e5
99d2505
 
 
085880a
d2daf95
 
 
f7a9983
d2daf95
 
 
d950565
d2daf95
 
 
 
 
 
99d2505
71c83be
5c9a3e1
962509d
b98f2e5
33826e4
5c32781
33826e4
b98f2e5
 
0e2ac66
55dbaf1
99d2505
55dbaf1
0e2ac66
 
131f73e
9aa49ac
131f73e
962509d
ed7f73f
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
962509d
751e7d4
d2daf95
33826e4
d2daf95
5c32781
eacc8e2
99d2505
eacc8e2
b98f2e5
 
 
 
 
5c32781
 
 
 
99d2505
 
 
 
401ca9f
3b5590f
4c74a4e
 
 
 
 
 
 
3b5590f
33826e4
12aabf0
d2daf95
f94eede
9352ef2
f94eede
9352ef2
f94eede
d2daf95
 
 
9352ef2
d2daf95
 
2275821
0f3cefd
acb08b7
5d46926
b98f2e5
33826e4
d2daf95
2275821
b98f2e5
3691388
b98f2e5
 
 
 
6772cf6
5c32781
 
 
 
 
f52ce74
5c32781
e1952ef
d2daf95
6772cf6
a29437c
 
 
 
 
 
6772cf6
 
 
a29437c
 
 
 
6772cf6
 
 
085880a
a3b4442
f52ce74
d2daf95
99d2505
0eab080
d2daf95
9aa49ac
33826e4
d2daf95
0eab080
33826e4
 
 
0eab080
33826e4
7729daa
33826e4
7729daa
33826e4
 
5c32781
33826e4
 
d2daf95
085880a
6159031
33826e4
b98f2e5
5c32781
e1952ef
 
5c9a3e1
085880a
4dd59d6
 
 
 
 
 
 
 
 
 
 
 
d2daf95
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
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
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
import os
import gradio as gr
from gradio.utils import get_space
from huggingface_hub import InferenceClient
from e2b_code_interpreter import Sandbox
from pathlib import Path
from transformers import AutoTokenizer
import json
from openai import OpenAI
from huggingface_hub import HfApi, HfFolder
from jupyter_handler import JupyterNotebook

if not get_space():
    try:
        from dotenv import load_dotenv

        load_dotenv()
    except (ImportError, ModuleNotFoundError):
        pass


from utils import (
    run_interactive_notebook,
)

E2B_API_KEY = os.environ["E2B_API_KEY"]
HF_TOKEN = os.environ["HF_TOKEN"] #HfFolder.get_token() #
DEFAULT_MAX_TOKENS = 512
SANDBOXES = {}
SANDBOX_TIMEOUT = 300
TMP_DIR = './tmp/'
model="Qwen/Qwen3-Coder-480B-A35B-Instruct:cerebras"
init_notebook = JupyterNotebook()

if not os.path.exists(TMP_DIR):
    os.makedirs(TMP_DIR)

with open(TMP_DIR+"jupyter-agent.ipynb", 'w', encoding='utf-8') as f:
    json.dump(JupyterNotebook().data, f, indent=2)

with open("ds-system-prompt.txt", "r") as f:
    DEFAULT_SYSTEM_PROMPT = f.read()
DEFAULT_SYSTEM_PROMPT = """You are a coding agent with access to a Jupyter Kernel. \
When possible break down tasks step-by-step. \
The following files are available (if any):
{}

List of available packages:
# Jupyter server requirements
jupyter-server==2.16.0
ipykernel==6.29.5
ipython==9.2.0

orjson==3.10.18
pandas==2.2.3
matplotlib==3.10.3
pillow==11.3.0

# Latest version for
e2b_charts

# Other packages
aiohttp==3.12.14
beautifulsoup4==4.13.4
bokeh==3.7.3
gensim==4.3.3 # unmaintained, blocking numpy and scipy bump
imageio==2.37.0
joblib==1.5.0
librosa==0.11.0
nltk==3.9.1
numpy==1.26.4 # bump blocked by gensim
numba==0.61.2
opencv-python==4.11.0.86
openpyxl==3.1.5
plotly==6.0.1
kaleido==1.0.0
pytest==8.3.5
python-docx==1.1.2
pytz==2025.2
requests==2.32.4
scikit-image==0.25.2
scikit-learn==1.6.1
scipy==1.13.1 # bump blocked by gensim
seaborn==0.13.2
soundfile==0.13.1
spacy==3.8.2 # doesn't work on 3.13.x
textblob==0.19.0
tornado==6.5.1
urllib3==2.5.0
xarray==2025.4.0
xlrd==2.0.1
sympy==1.14.0

If you need to install additional packages:
1. install uv first with `pip install uv` 
2. then use uv to install the package with `uv pip install PACKAGE_NAME --system`.

"""

def execute_jupyter_agent(
    user_input, files, message_history, request: gr.Request
):

    if request.session_hash not in SANDBOXES:
        SANDBOXES[request.session_hash] = Sandbox(api_key=E2B_API_KEY, timeout=SANDBOX_TIMEOUT)
    sbx = SANDBOXES[request.session_hash]

    save_dir = os.path.join(TMP_DIR, request.session_hash)
    os.makedirs(save_dir, exist_ok=True)
    save_dir = os.path.join(save_dir, 'jupyter-agent.ipynb')

    with open(save_dir, 'w', encoding='utf-8') as f:
        json.dump(init_notebook.data, f, indent=2)
    yield init_notebook.render(), message_history, save_dir

    client = OpenAI(
        base_url="https://router.huggingface.co/v1",
        api_key=HF_TOKEN,
    )

    filenames = []
    if files is not None:
        for filepath in files:
            filpath = Path(filepath)
            with open(filepath, "rb") as file:
                print(f"uploading {filepath}...")
                sbx.files.write(filpath.name, file)
                filenames.append(filpath.name)

    sytem_prompt = DEFAULT_SYSTEM_PROMPT
    # Initialize message_history if it doesn't exist
    if len(message_history) == 0:
        if files is None:
            sytem_prompt = sytem_prompt.format("- None")
        else:
            sytem_prompt = sytem_prompt.format("- " + "\n- ".join(filenames))

        message_history.append(
            {
                "role": "system",
                "content": sytem_prompt,
            }
        )
    message_history.append({"role": "user", "content": user_input})

    #print("history:", message_history)

    for notebook_html, notebook_data, messages in run_interactive_notebook(
        client, model, message_history, sbx,
    ):
        message_history = messages
        
        yield notebook_html, message_history, TMP_DIR+"jupyter-agent.ipynb"
    
    with open(save_dir, 'w', encoding='utf-8') as f:
        json.dump(notebook_data, f, indent=2)
    yield notebook_html, message_history, save_dir

def clear(msg_state, request: gr.Request):
    if request.session_hash in SANDBOXES:
        SANDBOXES[request.session_hash].kill()
        SANDBOXES.pop(request.session_hash)

    msg_state = []
    return init_notebook.render(), msg_state


css = """
#component-0 {
    height: 100vh;
    overflow-y: auto;
    padding: 20px;
}

.gradio-container {
    height: 100vh !important;
}

.contain {
    height: 100vh !important;
}
"""


# Create the interface
with gr.Blocks() as demo:
    msg_state = gr.State(value=[])

    html_output = gr.HTML(value=JupyterNotebook().render())
    
    user_input = gr.Textbox(
        #value="Write code to multiply three numbers: 10048, 32, 19", lines=3, label="User input"
        value="Solve the Lotka-Volterra equation and plot the results. Do it step by step and explain what you are doing and in the end make a super nice and clean plot.", label="Agent task"
    )
    
    with gr.Row():
        generate_btn = gr.Button("Run!")
        clear_btn = gr.Button("Clear Notebook")
    
    with gr.Accordion("Upload files ⬆ | Download notebook⬇", open=False):
        files = gr.File(label="Upload files to use", file_count="multiple")
        file = gr.File(TMP_DIR+"jupyter-agent.ipynb", label="Download Jupyter Notebook")

    powered_html = gr.HTML("""\
        <p align="center">
             <img style="max-height:100px; max-width:100%; height:auto;"src="https://huggingface.co/spaces/lvwerra/jupyter-agent-2/resolve/main/powered-by.png" alt="Powered by" />
        </p>""")
    

    generate_btn.click(
        fn=execute_jupyter_agent,
        inputs=[user_input, files, msg_state],
        outputs=[html_output, msg_state, file],
        show_progress="hidden",
    )

    clear_btn.click(fn=clear, inputs=[msg_state], outputs=[html_output, msg_state])

    demo.load(
        fn=None,
        inputs=None,
        outputs=None,
        js=""" () => {
    if (document.querySelectorAll('.dark').length) {
        document.querySelectorAll('.dark').forEach(el => el.classList.remove('dark'));
    }
}
"""
    )

demo.launch(ssr_mode=False)