Skip to content

Commit a8c79d1

Browse files
committed
add working assistant
1 parent a221385 commit a8c79d1

File tree

8 files changed

+46
-72
lines changed

8 files changed

+46
-72
lines changed

.vscode/launch.json

Lines changed: 4 additions & 6 deletions
Original file line numberDiff line numberDiff line change
@@ -5,14 +5,12 @@
55
"version": "0.2.0",
66
"configurations": [
77
{
8-
"name": "Python Debugger: Flask",
8+
"name": "Python: Debug Atlas server ",
99
"type": "debugpy",
1010
"request": "launch",
11-
"module": "flask",
12-
"env": { "FLASK_APP": "server/api.py", "FLASK_DEBUG": "1" },
13-
"args": ["run", "--no-debugger", "--no-reload", "--port", "8000"],
14-
"jinja": true,
15-
"autoStartBrowser": false
11+
"program": "${workspaceFolder}/server/api.py",
12+
"console": "integratedTerminal",
13+
"args": ["--port", "8000", "--dev", "true"]
1614
}
1715
]
1816
}

Dockerfile

Lines changed: 0 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -17,7 +17,6 @@ RUN mkdir ./api
1717
COPY server ./api
1818
RUN pip install --upgrade pip
1919
RUN pip install -r ./api/requirements.txt
20-
RUN pip install gunicorn eventlet
2120
ENV FLASK_ENV production
2221

2322
EXPOSE 80

client/src/pages/Login/Galaxy.tsx

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -20,7 +20,7 @@ const Galaxy = ({ loggingIn }: { loggingIn?: boolean }) => {
2020

2121
useEffect(() => {
2222
const starDensity = 0.216
23-
const speedCoeff = 0.05
23+
const speedCoeff = 0.03
2424
const giantColor = '180,184,240'
2525
const starColor = '226,225,142'
2626
const cometColor = '226,225,224'

client/src/pages/Login/stars-render.ts

Lines changed: 4 additions & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -23,8 +23,8 @@ export class Star {
2323

2424
reset() {
2525
const { getRandInterval, getProbability } = this.constructor as typeof Star
26-
this.giant = getProbability(3)
27-
this.comet = this.giant || this.first ? false : getProbability(10)
26+
this.giant = getProbability(5)
27+
this.comet = this.giant || this.first ? false : getProbability(3)
2828
this.x = getRandInterval(0, this.width - 10)
2929
this.y = getRandInterval(0, this.height)
3030
this.r = getRandInterval(1.1, 2.6)
@@ -67,10 +67,10 @@ export class Star {
6767

6868
if (this.giant) {
6969
universe.fillStyle = `rgba(${this.colors.giantColor},${this.opacity})`
70-
universe.arc(this.x, this.y, 2, 0, 2 * Math.PI, false)
70+
universe.arc(this.x, this.y, 3, 0, 2 * Math.PI, false)
7171
} else if (this.comet) {
7272
universe.fillStyle = `rgba(${this.colors.cometColor},${this.opacity})`
73-
universe.arc(this.x, this.y, 1.5, 0, 2 * Math.PI, false)
73+
universe.arc(this.x, this.y, 2.5, 0, 2 * Math.PI, false)
7474

7575
for (let i = 0; i < 30; i++) {
7676
universe.fillStyle = `rgba(${this.colors.cometColor},${this.opacity - (this.opacity / 20) * i})`

server/api.py

Lines changed: 3 additions & 25 deletions
Original file line numberDiff line numberDiff line change
@@ -4,7 +4,6 @@
44
import os
55
from sanic import Sanic, response
66
from sanic.request import Request
7-
from sanic_jwt import Initialize
87
from sanic_cors import CORS
98
import socketio
109
from config.app_config import AppConfig
@@ -32,27 +31,6 @@ async def attach_db(_app, _loop):
3231
await init_db()
3332

3433

35-
# Define JWT authentication
36-
async def authenticate(request):
37-
"""
38-
Authenticate the user.
39-
"""
40-
email = request.json.get("email", None)
41-
print(email)
42-
if email:
43-
user = await login_user(email)
44-
return user
45-
return None
46-
47-
48-
Initialize(app, authenticate=authenticate)
49-
50-
# # Define API resources
51-
# app.add_route(GetFeatures.as_view(), "/api/features")
52-
# app.add_route(RunAssistant.as_view(), "/api/run_assistant")
53-
54-
55-
# TODO: add login rate limiter
5634
@app.route("/api/login", methods=["POST"])
5735
async def login(request: Request):
5836
"""
@@ -82,7 +60,7 @@ async def run_assistant_endpoint(request: Request):
8260
Handles the POST request for running the assistant.
8361
"""
8462
if request.method == "POST":
85-
file = request.form.get("file")
63+
file = request.files.get("file")
8664
sid = request.form.get("sid")
8765
return await run_assistant(sid=sid, file=file, sio=sio)
8866

@@ -136,11 +114,11 @@ def parse_args():
136114
"-p", "--port", help="Port for the server.", type=int, default=80
137115
)
138116
parser.add_argument(
139-
"-d", "--debug", help="Debug mode on or off.", type=bool, default=False
117+
"-d", "--dev", help="Dev mode on or off.", type=bool, default=False
140118
)
141119
return parser.parse_args()
142120

143121

144122
if __name__ == "__main__":
145123
args = parse_args()
146-
app.run(host="0.0.0.0", port=args.port, debug=args.debug)
124+
app.run(host="0.0.0.0", port=args.port, dev=args.dev)

server/assistant.py

Lines changed: 22 additions & 14 deletions
Original file line numberDiff line numberDiff line change
@@ -8,6 +8,8 @@
88
from typing import Dict, List, Union
99
from openai import OpenAI
1010
from dotenv import load_dotenv
11+
from sanic.request.form import File
12+
import socketio
1113

1214
load_dotenv()
1315

@@ -221,7 +223,7 @@ def build_feature_functions(
221223
return experiments_function_call
222224

223225

224-
def upload_file_to_vector_store(client: OpenAI, file_path: str) -> str:
226+
def upload_file_to_vector_store(client: OpenAI, file: File, sid: str) -> str:
225227
"""
226228
Uploads a file to the vector store.
227229
@@ -232,6 +234,12 @@ def upload_file_to_vector_store(client: OpenAI, file_path: str) -> str:
232234
- URL to the uploaded file.
233235
"""
234236

237+
file_path = f"paper/{sid}{file.name}"
238+
239+
with open(file_path, "wb") as f:
240+
f.write(file.body)
241+
f.close()
242+
235243
file_info = client.files.create(file=open(file_path, "rb"), purpose="assistants")
236244

237245
now = datetime.now()
@@ -311,44 +319,44 @@ def create_temporary_assistant(client: OpenAI):
311319
return my_temporary_assistant
312320

313321

314-
def call_asssistant_api(file_path: str, sid: str, sio):
322+
async def call_asssistant_api(file: File, sid: str, sio: socketio.AsyncServer):
315323

316324
client = OpenAI()
317325

318326
try:
319-
sio.emit(
327+
await sio.emit(
320328
"status",
321329
{"status": "Fetching all features...", "progress": 0},
322330
to=sid,
323331
namespace="/home",
324332
)
325333
feature_list = get_all_features()
326334

327-
sio.emit(
335+
await sio.emit(
328336
"status",
329337
{"status": "Building feature functions...", "progress": 5},
330338
to=sid,
331339
namespace="/home",
332340
)
333341
functions = build_feature_functions(feature_list)
334342

335-
sio.emit(
343+
await sio.emit(
336344
"status",
337345
{"status": "Uploading file to vector store...", "progress": 10},
338346
to=sid,
339347
namespace="/home",
340348
)
341-
vector_store = upload_file_to_vector_store(client, file_path)
349+
vector_store = upload_file_to_vector_store(client=client, file=file, sid=sid)
342350

343-
sio.emit(
351+
await sio.emit(
344352
"status",
345353
{"status": "Creating an assistant for your task...", "progress": 12},
346354
to=sid,
347355
namespace="/home",
348356
)
349357
my_temporary_assistant = create_temporary_assistant(client)
350358

351-
sio.emit(
359+
await sio.emit(
352360
"status",
353361
{"status": "Updating assistant...", "progress": 15},
354362
to=sid,
@@ -358,7 +366,7 @@ def call_asssistant_api(file_path: str, sid: str, sio):
358366
client, my_temporary_assistant.id, vector_store, functions
359367
)
360368

361-
sio.emit(
369+
await sio.emit(
362370
"status",
363371
{"status": "Creating thread message...", "progress": 30},
364372
to=sid,
@@ -368,12 +376,12 @@ def call_asssistant_api(file_path: str, sid: str, sio):
368376
messages=[
369377
{
370378
"role": "user",
371-
"content": "define_experiments_conditions_and_behaviors",
379+
"content": "run function define_experiments_conditions_and_behaviors",
372380
}
373381
],
374382
)
375383

376-
sio.emit(
384+
await sio.emit(
377385
"status",
378386
{"status": "Running assistant...", "progress": 40},
379387
to=sid,
@@ -384,7 +392,7 @@ def call_asssistant_api(file_path: str, sid: str, sio):
384392
thread_id=thread_message.id, assistant_id=updated_assistant.id
385393
)
386394

387-
sio.emit(
395+
await sio.emit(
388396
"status",
389397
{"status": "Getting tool outputs...", "progress": 50},
390398
to=sid,
@@ -395,7 +403,7 @@ def call_asssistant_api(file_path: str, sid: str, sio):
395403
run.required_action.submit_tool_outputs.tool_calls[0].function.arguments
396404
)
397405

398-
sio.emit(
406+
await sio.emit(
399407
"status",
400408
{"status": "Checking output format...", "progress": 60},
401409
to=sid,
@@ -413,7 +421,7 @@ def call_asssistant_api(file_path: str, sid: str, sio):
413421
print(e)
414422
raise AssistantException("Assistant run failed") from e
415423
finally:
416-
sio.emit(
424+
await sio.emit(
417425
"status",
418426
{"status": "Cleaning up resources...", "progress": 70},
419427
to=sid,

server/config/app_config.py

Lines changed: 3 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -21,7 +21,9 @@ class AppConfig(Config):
2121
JWT_EXP_DELTA_SECONDS (int): The expiration time for JWT tokens in seconds.
2222
"""
2323

24-
BASE_URL = os.getenv("BASE_URL")
24+
BASE_URL = os.getenv(
25+
"FLASK_ENV" == "development" and "BASE_URL_DEV" or "BASE_URL_PROD"
26+
)
2527
SECRET = os.getenv("SOCKET_SECRET")
2628
JWT_SECRET = os.getenv("JWT_SECRET")
2729
JWT_ALGORITHM = "HS256"

server/controllers/assisstant.py

Lines changed: 9 additions & 20 deletions
Original file line numberDiff line numberDiff line change
@@ -4,9 +4,9 @@
44

55
import os
66
from sanic import json as json_response
7+
from sanic.request.form import File
78
import socketio
89

9-
1010
from assistant import AssistantException, call_asssistant_api
1111

1212

@@ -16,41 +16,30 @@
1616
os.makedirs(UPLOAD_DIRECTORY)
1717

1818

19-
def run_assistant(sid, file, sio: socketio.AsyncServer):
19+
async def run_assistant(sid: str, file: File, sio: socketio.AsyncServer):
2020
"""
2121
Run the assistant with the uploaded file
2222
"""
23+
24+
print("Running assistant", sid, file.name)
2325
if file:
24-
file_path = os.path.join(UPLOAD_DIRECTORY, file.filename)
25-
file.save(file_path)
2626
try:
27-
result = call_asssistant_api(file_path, sid, sio)
28-
29-
# print("result : ", json.dumps(result))
30-
sio.emit(
31-
"status",
32-
{"status": "Fetching all features...", "progress": 0},
33-
to=sid,
34-
)
27+
result = await call_asssistant_api(file=file, sid=sid, sio=sio)
3528

3629
response_data = {
3730
"message": "File successfully uploaded",
38-
"file_name": file.filename,
31+
"file_name": file.name,
3932
"experiments": result["experiments"],
4033
}
4134

42-
# Delete the uploaded
43-
if os.path.isfile(file_path):
44-
os.remove(file_path)
35+
if os.path.isfile(f"paper/{sid}{file.name}"):
36+
os.remove(f"paper/{sid}{file.name}")
4537
print("File removed from local storage successfully")
4638
else:
4739
# If it fails, inform the user.
48-
print(f"Error: {file_path} file not found")
40+
print(f"Error: {f"paper/{sid}{file.name}"} file not found")
4941

5042
return json_response(body=response_data, status=200)
5143
except AssistantException as e:
5244
response_data = {"error": str(e)}
5345
return json_response(body=response_data, status=500)
54-
else:
55-
response_data = {"error": "File upload failed"}
56-
return json_response(body=response_data, status=400)

0 commit comments

Comments
 (0)