-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathmain.py
More file actions
356 lines (307 loc) · 12.1 KB
/
main.py
File metadata and controls
356 lines (307 loc) · 12.1 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
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
"""
SightCore - Main Application Entry Point
Warden App Compatible + LangChain Cloud API
"""
import os
import asyncio
from concurrent.futures import ThreadPoolExecutor
import logging
from dotenv import load_dotenv
# Load environment variables FIRST — before any other imports read os.getenv()
load_dotenv()
from fastapi import FastAPI, HTTPException
from fastapi.middleware.cors import CORSMiddleware
from fastapi.responses import FileResponse, JSONResponse
from pydantic import BaseModel
import uvicorn
# Import LangGraph API router
from src.api.langgraph_api import router as langgraph_router, ASSISTANT_ID, GRAPH_ID, _threads, _runs
# Setup logging with timestamps
logging.basicConfig(
level=logging.INFO,
format='%(asctime)s | %(levelname)-8s | %(name)s | %(message)s',
datefmt='%Y-%m-%d %H:%M:%S'
)
logger = logging.getLogger(__name__)
# Verify API key
ANTHROPIC_API_KEY = os.getenv("ANTHROPIC_API_KEY", "")
if not ANTHROPIC_API_KEY:
logger.warning("⚠️ ANTHROPIC_API_KEY bulunamadı!")
else:
logger.info("✅ Claude API Key ayarlı")
# ============================================
# FASTAPI APPLICATION
# ============================================
app = FastAPI(
title="SightCore API - Warden App Compatible",
description="LangChain Cloud API + Warden App Compatible - Crypto Technical Analysis Agent",
version="1.0.0",
docs_url="/docs",
redoc_url="/redoc"
)
# CORS (Cloudflare handles security)
app.add_middleware(
CORSMiddleware,
allow_origins=["*"],
allow_credentials=True,
allow_methods=["*"],
allow_headers=["*"],
expose_headers=[
"x-pagination-total",
"x-pagination-next",
"content-location",
"location",
"cache-control"
]
)
# OPTIONS handler for CORS preflight (CRITICAL for Warden App!)
@app.options("/{full_path:path}")
async def options_handler(full_path: str):
"""Handle CORS preflight requests"""
return JSONResponse(
content={"detail": "OK"},
status_code=200,
headers={
"Access-Control-Allow-Origin": "*",
"Access-Control-Allow-Methods": "GET, POST, PUT, DELETE, OPTIONS, PATCH",
"Access-Control-Allow-Headers": "*",
"Access-Control-Max-Age": "3600"
}
)
# Include LangGraph API router
app.include_router(langgraph_router)
# ============================================
# STATIC FILES
# ============================================
@app.get("/")
async def root():
"""Serve main page"""
return FileResponse("index.html")
@app.get("/chat.html")
async def chat_page():
"""Serve chat page"""
return FileResponse("chat.html")
@app.get("/image_cdfd97.jpg")
async def logo():
"""Serve logo"""
return FileResponse("image_cdfd97.jpg")
# ============================================
# INFO & HEALTH ENDPOINTS
# ============================================
@app.get("/info")
async def get_info():
"""Get deployment info (CRITICAL for Warden App!)"""
return {
"version": "1.0.0",
"service": "SightCore",
"deployment_type": "self-hosted",
"api_version": "v1",
"features": {
"streaming": True,
"threads": True,
"assistants": True,
"state_management": True,
"conversation_history": True,
"multimodal": True,
"auto_create_threads": True,
"interrupts": True,
"wait_for_run": True,
"checkpoints": True,
"bulk_operations": True,
"crons": False # Not supported in self-hosted
},
"streaming_modes": ["values", "updates", "messages", "debug", "events"],
"streaming_events": [
"metadata", "values", "updates", "debug",
"messages/partial", "messages/complete",
"done", "end", "error"
],
"endpoints": {
"assistants_list": "GET /assistants",
"assistants_search": "GET|POST /assistants/search",
"assistants_get": "GET /assistants/{id}",
"assistants_runs": "POST /assistants/{id}/runs",
"assistants_crons": "GET /assistants/{id}/crons",
"threads_create": "POST /threads",
"threads_list": "GET /threads",
"threads_search": "GET|POST /threads/search",
"threads_get": "GET /threads/{id}",
"threads_update": "PATCH /threads/{id}",
"threads_delete": "DELETE /threads/{id}",
"threads_history": "GET|POST /threads/{id}/history",
"threads_state": "GET|POST /threads/{id}/state",
"threads_checkpoint": "POST /threads/{id}/state/checkpoint",
"threads_interrupt": "POST /threads/{id}/interrupt",
"threads_runs_create": "POST /threads/{id}/runs",
"threads_runs_stream": "POST /threads/{id}/runs/stream",
"threads_runs_list": "GET /threads/{id}/runs",
"threads_runs_get": "GET /threads/{id}/runs/{run_id}",
"threads_runs_wait": "GET|POST /threads/{id}/runs/{run_id}/wait",
"bulk_state_update": "POST /threads/state/bulk"
},
"default_assistant": {
"assistant_id": ASSISTANT_ID,
"graph_id": GRAPH_ID,
"name": "SightCore",
"description": "AI Crypto Technical Analysis Agent"
},
"metadata": {
"supported_languages": ["en", "tr", "es", "fr", "de"],
"exchanges": ["binance", "okx", "bybit", "gate", "mexc", "kucoin", "huobi", "bitget"],
"capabilities": [
"Technical Analysis",
"Chart Pattern Detection",
"Support/Resistance Levels",
"Divergence Analysis"
]
},
"compatibility": {
"warden_app": True,
"langgraph_cloud_api": True,
"remote_graph": True,
"langchain": True
},
"performance": {
"average_response_time": "5-8s",
"timeout": "5s per exchange call",
"concurrent_exchanges": 16
}
}
@app.get("/health")
async def health_check():
"""Health check endpoint"""
return {
"status": "healthy",
"service": "SightCore",
"version": "1.0.0",
"api_format": "Warden App Compatible + LangChain Cloud",
"assistants": 1,
"threads": len(_threads),
"runs": len(_runs)
}
# ============================================
# BACKWARD COMPATIBILITY - OLD API
# ============================================
class QueryRequest(BaseModel):
query: str
class QueryResponse(BaseModel):
response: str
@app.post("/api/v1/analyze", response_model=QueryResponse)
async def analyze_query(request: QueryRequest):
"""Backward compatible endpoint"""
try:
from langchain_core.messages import HumanMessage
from agent.graph import graph
from src.api.langgraph_api import convert_to_langgraph_output
# Create temporary thread
messages = [HumanMessage(content=request.query)]
# Execute
loop = asyncio.get_running_loop()
with ThreadPoolExecutor(max_workers=1) as executor:
result = await loop.run_in_executor(
executor,
lambda: graph.invoke({"messages": messages})
)
# Extract response
output = convert_to_langgraph_output(result, [])
if output.get("messages"):
assistant_messages = [msg for msg in output["messages"] if msg.get("role") == "assistant"]
if assistant_messages:
return QueryResponse(response=assistant_messages[-1]["content"])
raise HTTPException(status_code=500, detail="No response generated")
except HTTPException:
raise
except Exception as e:
logger.error(f"Old API error: {e}")
raise HTTPException(status_code=500, detail=str(e))
# Import helper functions from tools for backward compatibility
from agent.tools import get_indicators as _get_indicators_tool
from agent.tools import get_patterns as _get_patterns_tool
from agent.tools import get_support_resistance as _get_support_resistance_tool
from agent.tools import get_divergences as _get_divergences_tool
@app.get("/api/v1/indicators", response_model=QueryResponse)
async def get_indicators_endpoint():
"""Backward compatible indicators endpoint"""
try:
loop = asyncio.get_running_loop()
with ThreadPoolExecutor(max_workers=1) as executor:
result = await loop.run_in_executor(executor, lambda: _get_indicators_tool.invoke({}))
return QueryResponse(response=result)
except Exception as e:
raise HTTPException(status_code=500, detail=str(e))
@app.get("/api/v1/patterns", response_model=QueryResponse)
async def get_patterns_endpoint():
"""Backward compatible patterns endpoint"""
try:
loop = asyncio.get_running_loop()
with ThreadPoolExecutor(max_workers=1) as executor:
result = await loop.run_in_executor(executor, lambda: _get_patterns_tool.invoke({}))
return QueryResponse(response=result)
except Exception as e:
raise HTTPException(status_code=500, detail=str(e))
@app.get("/api/v1/support-resistance", response_model=QueryResponse)
async def get_support_resistance_endpoint():
"""Backward compatible support/resistance endpoint"""
try:
loop = asyncio.get_running_loop()
with ThreadPoolExecutor(max_workers=1) as executor:
result = await loop.run_in_executor(executor, lambda: _get_support_resistance_tool.invoke({}))
return QueryResponse(response=result)
except Exception as e:
raise HTTPException(status_code=500, detail=str(e))
@app.get("/api/v1/divergences", response_model=QueryResponse)
async def get_divergences_endpoint():
"""Backward compatible divergences endpoint"""
try:
loop = asyncio.get_running_loop()
with ThreadPoolExecutor(max_workers=1) as executor:
result = await loop.run_in_executor(executor, lambda: _get_divergences_tool.invoke({}))
return QueryResponse(response=result)
except Exception as e:
raise HTTPException(status_code=500, detail=str(e))
# ============================================
# MAIN
# ============================================
if __name__ == "__main__":
logger.info("=" * 70)
logger.info(" SightCore API - Warden App Compatible")
logger.info("=" * 70)
logger.info(f" Host: 0.0.0.0")
logger.info(f" Port: 8000")
logger.info(f" AI Provider: Claude (Anthropic)")
logger.info(f" API Key: {'✅ Ayarlı' if ANTHROPIC_API_KEY else '❌ Eksik'}")
logger.info(f" Assistant ID: {ASSISTANT_ID}")
logger.info("")
logger.info(" Architecture:")
logger.info(" - main.py: Entry point + static files + backward compat")
logger.info(" - src/api/langgraph_api.py: LangGraph Cloud API")
logger.info(" - agent/: LangGraph agent implementation")
logger.info("")
logger.info(" Warden App Compatible Features:")
logger.info(" ✅ Auto-create threads")
logger.info(" ✅ POST method support")
logger.info(" ✅ Direct array returns")
logger.info(" ✅ Thread streaming")
logger.info(" ✅ messages/complete event")
logger.info(" ✅ Conversation history")
logger.info(" ✅ Thread state management")
logger.info(" ✅ Multimodal content")
logger.info("")
logger.info(" LangChain Cloud API Endpoints:")
logger.info(" - GET /assistants")
logger.info(" - POST /assistants/{id}/runs")
logger.info(" - POST /threads")
logger.info(" - POST /threads/{id}/runs")
logger.info(" - POST /threads/{id}/runs/stream ⭐")
logger.info(" - GET /threads/{id}/history")
logger.info(" - GET /threads/{id}/state")
logger.info(" - GET /info ⭐")
logger.info("")
logger.info(" Backward Compatible:")
logger.info(" - POST /api/v1/analyze")
logger.info(" - GET /api/v1/indicators")
logger.info("")
logger.info(" Optimized for: Cloudflare + Warden App")
logger.info("=" * 70)
logger.info("")
uvicorn.run(app, host="0.0.0.0", port=8000, log_level="info")