File size: 1,758 Bytes
6e1d8dd
af1ae43
 
304e233
e0d4a07
304e233
af1ae43
 
 
 
 
 
 
 
 
 
 
 
 
 
6e1d8dd
 
 
8c205ef
 
af1ae43
 
e0d4a07
 
8c205ef
af1ae43
 
 
e0d4a07
af1ae43
 
 
 
 
 
 
3593cc3
e0d4a07
af1ae43
 
 
 
 
304e233
 
af1ae43
 
 
 
 
 
 
 
 
 
51747e6
af1ae43
 
 
 
 
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
import os
from contextlib import asynccontextmanager

from cua2_core.services.agent_service import AgentService
from cua2_core.services.sandbox_service import SandboxService
from cua2_core.websocket.websocket_manager import WebSocketManager
from dotenv import load_dotenv
from fastapi import FastAPI
from fastapi.middleware.cors import CORSMiddleware

# Load environment variables
load_dotenv()


@asynccontextmanager
async def lifespan(app: FastAPI):
    """Lifespan context manager for startup and shutdown events"""
    # Startup: Initialize services
    print("Initializing services...")

    if not os.getenv("HF_TOKEN"):
        raise ValueError("HF_TOKEN is not set")

    num_workers = int(os.getenv("NUM_WORKERS", "1"))

    websocket_manager = WebSocketManager()

    sandbox_service = SandboxService()

    agent_service = AgentService(websocket_manager, sandbox_service, num_workers)

    # Store services in app state for access in routes
    app.state.websocket_manager = websocket_manager
    app.state.sandbox_service = sandbox_service
    app.state.agent_service = agent_service

    print("Services initialized successfully")

    yield

    print("Shutting down services...")
    await agent_service.cleanup()
    await sandbox_service.cleanup_sandboxes()
    print("Services shut down successfully")


# Create FastAPI app with lifespan
app = FastAPI(
    title="Computer Use Backend",
    description="Backend API for Computer Use - AI-powered automation interface",
    version="1.0.0",
    docs_url="/docs",
    redoc_url="/redoc",
    lifespan=lifespan,
)

# Configure CORS
app.add_middleware(
    CORSMiddleware,
    allow_origins=[
        "*",
    ],
    allow_credentials=True,
    allow_methods=["*"],
    allow_headers=["*"],
)