forked from tashifkhan/agentic-browser
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathmain.py
More file actions
231 lines (189 loc) · 6.42 KB
/
Copy pathmain.py
File metadata and controls
231 lines (189 loc) · 6.42 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
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
from contextlib import asynccontextmanager
import anyio
import asyncio
import uvicorn
from dotenv import load_dotenv
from fastapi import FastAPI
from fastapi.middleware.cors import CORSMiddleware
from mcp.server.streamable_http import StreamableHTTPServerTransport
from core.config import get_logger
from mcp_server.server import server as mcp_server
logger = get_logger(__name__)
load_dotenv()
class MCPStreamableHTTPApp:
async def __call__(self, scope, receive, send):
if scope["type"] != "http":
return
transport = StreamableHTTPServerTransport(mcp_session_id=None)
async with anyio.create_task_group() as task_group:
async with transport.connect() as (read_stream, write_stream):
task_group.start_soon(
mcp_server.run,
read_stream,
write_stream,
mcp_server.create_initialization_options(),
False,
True,
)
await transport.handle_request(scope, receive, send)
task_group.cancel_scope.cancel()
@asynccontextmanager
async def lifespan(app: FastAPI):
"""Connect memory stores on startup, disconnect on shutdown."""
from core.clients.neo4j import get_neo4j
from core.clients.opensearch import get_opensearch
from core.db import init_db
logger.info("Initialising memory stores...")
try:
await init_db()
logger.info("Postgres: ready")
except Exception as exc:
logger.warning("Postgres init skipped: %s", exc)
try:
neo4j = get_neo4j()
await neo4j.connect()
await neo4j.create_constraints()
logger.info("Neo4j: connected")
except Exception as exc:
logger.warning("Neo4j init skipped: %s", exc)
try:
os_client = get_opensearch()
os_client.connect()
os_client.ensure_indices()
logger.info("OpenSearch: connected, indices ready")
except Exception as exc:
logger.warning("OpenSearch init skipped: %s", exc)
try:
from core.llm import reload_default_llm
await reload_default_llm()
logger.info("Default LLM resolved (DB override applied if present)")
except Exception as exc:
logger.warning("LLM default resolution skipped: %s", exc)
try:
from services.telegram_bot_runner import run_telegram_bot
bot_task = asyncio.create_task(run_telegram_bot())
app.state.bot_task = bot_task
logger.info("Telegram bot task created.")
except Exception as exc:
logger.warning("Telegram bot init skipped: %s", exc)
try:
from apscheduler.schedulers.asyncio import AsyncIOScheduler
from memory.maintenance.consolidation import ConsolidationRunner
runner = ConsolidationRunner()
scheduler = AsyncIOScheduler()
scheduler.add_job(
runner.hourly,
"interval",
hours=1,
id="memory_hourly",
)
scheduler.add_job(
runner.nightly,
"cron",
hour=3,
id="memory_nightly",
)
scheduler.add_job(
runner.weekly,
"cron",
day_of_week="sun",
hour=4,
id="memory_weekly",
)
scheduler.start()
app.state.scheduler = scheduler
logger.info("Memory maintenance scheduler started")
except Exception as exc:
logger.warning("Scheduler init skipped: %s", exc)
yield
if hasattr(app.state, "scheduler"):
app.state.scheduler.shutdown(wait=False)
if hasattr(app.state, "bot_task"):
app.state.bot_task.cancel()
await asyncio.gather(app.state.bot_task, return_exceptions=True)
try:
neo4j = get_neo4j()
await neo4j.close()
except Exception:
pass
try:
os_client = get_opensearch()
os_client.close()
except Exception:
pass
app = FastAPI(title="Agentic Browser API", version="0.1.0", lifespan=lifespan)
app.add_middleware(
CORSMiddleware,
allow_origins=["*"],
allow_credentials=False,
allow_methods=["*"],
allow_headers=["*"],
)
from memory.api.router import router as memory_router # noqa: E402
from routers import ( # noqa: E402
auth_router,
automation_router,
browser_runtime_router,
calendar_router,
conversations_router,
debug_router,
file_upload_router,
github_router,
gmail_router,
google_search_router,
health_router,
integrations_router,
pyjiit_router,
react_agent_router,
skills_router,
state_router,
voice_router,
website_router,
website_validator_router,
youtube_router,
)
from routers import (
browser_use_router as agent_router,
)
app.include_router(health_router, prefix="/api/genai/health")
app.include_router(github_router, prefix="/api/genai/github")
app.include_router(website_router, prefix="/api/genai/website")
app.include_router(youtube_router, prefix="/api/genai/youtube")
app.include_router(google_search_router, prefix="/api/google-search")
app.include_router(gmail_router, prefix="/api/gmail")
app.include_router(calendar_router, prefix="/api/calendar")
app.include_router(pyjiit_router, prefix="/api/pyjiit")
app.include_router(react_agent_router, prefix="/api/genai/react")
app.include_router(website_validator_router, prefix="/api/validator")
app.include_router(agent_router, prefix="/api/agent")
app.include_router(file_upload_router, prefix="/api/upload")
app.include_router(skills_router, prefix="/api/skills")
app.include_router(auth_router, prefix="/api/auth")
app.include_router(state_router, prefix="/api/state")
app.include_router(conversations_router, prefix="/api")
app.include_router(voice_router, prefix="/api/voice")
app.include_router(memory_router, prefix="/api/memory")
app.include_router(automation_router, prefix="/api/browser/automation")
app.include_router(browser_runtime_router, prefix="/api/browser/runtime")
app.include_router(debug_router, prefix="/api/debug")
app.include_router(integrations_router, prefix="/api/integrations")
app.mount("/mcp", MCPStreamableHTTPApp())
@app.get("/")
def root():
return {
"name": app.title,
"version": app.version,
}
def run(
host: str = "0.0.0.0",
port: int = 5454,
reload: bool = True,
):
uvicorn.run(
"main:app",
host=host,
port=port,
reload=reload,
)
if __name__ == "__main__":
run()