-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathmain.py
More file actions
111 lines (93 loc) · 3.51 KB
/
Copy pathmain.py
File metadata and controls
111 lines (93 loc) · 3.51 KB
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
import os
import subprocess
import json
from fastapi import FastAPI, UploadFile, File, HTTPException, BackgroundTasks
from fastapi.responses import FileResponse, HTMLResponse
from pydantic import BaseModel
app = FastAPI()
WORKSPACE_DIR = os.getenv("WORKSPACE_DIR", "/workspace")
HISTORY_FILE = os.path.join(WORKSPACE_DIR, "chat_history.json")
os.makedirs(WORKSPACE_DIR, exist_ok=True)
class ChatRequest(BaseModel):
prompt: str
model: str
class EditRequest(BaseModel):
filename: str
content: str
def load_history():
if os.path.exists(HISTORY_FILE):
try:
with open(HISTORY_FILE, "r") as f:
return json.load(f)
except:
pass
return [{"role": "opencode", "text": "How can I help you code today?"}]
def save_history(history):
with open(HISTORY_FILE, "w") as f:
json.dump(history, f)
def run_opencode_bg(prompt: str, model: str):
env = os.environ.copy()
if "deepseek" in model.lower():
env["OPENAI_API_BASE"] = "https://openrouter.ai/api/v1"
env["OPENAI_API_KEY"] = env.get("OPENROUTER_API_KEY", "")
# We rely on the full LLM dependency to process the instructions and generate files
cmd = ["opencode", "--prompt", prompt, "--cwd", WORKSPACE_DIR]
try:
result = subprocess.run(cmd, env=env, capture_output=True, text=True, timeout=300)
output = result.stdout if result.returncode == 0 else result.stderr
except Exception as e:
output = f"Error running OpenCode: {str(e)}"
history = load_history()
history.append({"role": "opencode", "text": output})
save_history(history)
@app.get("/api/chat/history")
def get_history():
return {"history": load_history()}
@app.post("/api/chat")
def chat(req: ChatRequest, background_tasks: BackgroundTasks):
history = load_history()
history.append({"role": "user", "text": req.prompt})
save_history(history)
# Background task allows app closure without interrupting the AI
background_tasks.add_task(run_opencode_bg, req.prompt, req.model)
return {"status": "started"}
@app.get("/api/files")
def list_files():
files = [f for f in os.listdir(WORKSPACE_DIR) if f != "chat_history.json"]
return {"files": files}
@app.get("/api/files/download/{filename}")
def download_file(filename: str):
path = os.path.join(WORKSPACE_DIR, filename)
if os.path.exists(path):
return FileResponse(path, filename=filename)
raise HTTPException(status_code=404)
@app.delete("/api/files/{filename}")
def delete_file(filename: str):
path = os.path.join(WORKSPACE_DIR, filename)
if os.path.exists(path):
os.remove(path)
return {"status": "deleted"}
raise HTTPException(status_code=404)
@app.post("/api/files/upload")
async def upload_file(file: UploadFile = File(...)):
path = os.path.join(WORKSPACE_DIR, file.filename)
with open(path, "wb") as f:
f.write(await file.read())
return {"status": "uploaded"}
@app.post("/api/files/edit")
def edit_file(req: EditRequest):
path = os.path.join(WORKSPACE_DIR, req.filename)
with open(path, "w") as f:
f.write(req.content)
return {"status": "saved"}
@app.get("/api/files/read/{filename}")
def read_file(filename: str):
path = os.path.join(WORKSPACE_DIR, filename)
if os.path.exists(path):
with open(path, "r") as f:
return {"content": f.read()}
raise HTTPException(status_code=404)
@app.get("/", response_class=HTMLResponse)
def root():
with open("index.html", "r") as f:
return f.read()