Spaces:
Running
Running
Create app.py
Browse files
app.py
ADDED
|
@@ -0,0 +1,48 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
from fastapi import FastAPI
|
| 2 |
+
from fastapi.responses import StreamingResponse
|
| 3 |
+
from pydantic import BaseModel
|
| 4 |
+
import subprocess
|
| 5 |
+
import shlex
|
| 6 |
+
|
| 7 |
+
app = FastAPI()
|
| 8 |
+
|
| 9 |
+
class AgentRequest(BaseModel):
|
| 10 |
+
prompt: str
|
| 11 |
+
# Defaulting to one of the built-in free OpenCode Zen models
|
| 12 |
+
model: str = "opencode/minimax-m2.5-free"
|
| 13 |
+
|
| 14 |
+
def stream_opencode_logs(prompt: str, model: str):
|
| 15 |
+
"""
|
| 16 |
+
Executes OpenCode in headless mode and streams the live terminal output.
|
| 17 |
+
"""
|
| 18 |
+
# shlex.quote ensures the prompt doesn't break the shell command
|
| 19 |
+
cmd = f'opencode run --model {shlex.quote(model)} {shlex.quote(prompt)}'
|
| 20 |
+
|
| 21 |
+
# Run OpenCode as a subprocess and capture stdout live
|
| 22 |
+
process = subprocess.Popen(
|
| 23 |
+
cmd,
|
| 24 |
+
shell=True,
|
| 25 |
+
stdout=subprocess.PIPE,
|
| 26 |
+
stderr=subprocess.STDOUT, # Pipe errors to the same log stream
|
| 27 |
+
text=True,
|
| 28 |
+
bufsize=1
|
| 29 |
+
)
|
| 30 |
+
|
| 31 |
+
# Yield logs line-by-line as Server-Sent Events
|
| 32 |
+
for line in process.stdout:
|
| 33 |
+
yield f"data: {line}\n\n"
|
| 34 |
+
|
| 35 |
+
process.stdout.close()
|
| 36 |
+
process.wait()
|
| 37 |
+
yield f"data: [DONE]\n\n"
|
| 38 |
+
|
| 39 |
+
@app.post("/run")
|
| 40 |
+
async def execute_task(req: AgentRequest):
|
| 41 |
+
return StreamingResponse(
|
| 42 |
+
stream_opencode_logs(req.prompt, req.model),
|
| 43 |
+
media_type="text/event-stream"
|
| 44 |
+
)
|
| 45 |
+
|
| 46 |
+
@app.get("/")
|
| 47 |
+
def health_check():
|
| 48 |
+
return {"status": "OpenCode Executor is live and waiting for Super Agent!"}
|