Spaces:
Sleeping
Sleeping
Update api.py
Browse files
api.py
CHANGED
@@ -1,4 +1,4 @@
|
|
1 |
-
from fastapi import FastAPI, HTTPException, Request
|
2 |
from fastapi.middleware.cors import CORSMiddleware
|
3 |
from typing import Dict, List, Optional, Union, Any
|
4 |
from pydantic import BaseModel, Field
|
@@ -16,11 +16,6 @@ from fastapi.responses import StreamingResponse
|
|
16 |
from fastapi.responses import JSONResponse
|
17 |
from response_formatter import ResponseFormatter
|
18 |
import traceback
|
19 |
-
from fastapi.security.api_key import APIKeyHeader, APIKey
|
20 |
-
from fastapi.staticfiles import StaticFiles
|
21 |
-
from fastapi.openapi.docs import get_swagger_ui_html
|
22 |
-
from fastapi.responses import HTMLResponse
|
23 |
-
from fastapi.openapi.utils import get_openapi
|
24 |
|
25 |
# Load environment variables
|
26 |
load_dotenv()
|
@@ -32,11 +27,6 @@ logging.basicConfig(
|
|
32 |
)
|
33 |
logger = logging.getLogger(__name__)
|
34 |
|
35 |
-
# Add these constants near the top of the file after imports
|
36 |
-
API_KEY_NAME = "X-API-Key"
|
37 |
-
API_KEY = os.getenv("CLIENT_API_KEY") # Add this to your .env file
|
38 |
-
api_key_header = APIKeyHeader(name=API_KEY_NAME, auto_error=True)
|
39 |
-
|
40 |
class AgentOutput(BaseModel):
|
41 |
"""Structured output from agent processing"""
|
42 |
thought_content: str
|
@@ -304,13 +294,7 @@ class AgentProcessor:
|
|
304 |
return None
|
305 |
|
306 |
# Initialize FastAPI app
|
307 |
-
app = FastAPI(
|
308 |
-
title="Agent API",
|
309 |
-
description="API requiring X-API-Key authentication",
|
310 |
-
version="1.0.0",
|
311 |
-
docs_url=None, # Disable default docs
|
312 |
-
openapi_tags=[{"name": "agent", "description": "Agent endpoints"}],
|
313 |
-
)
|
314 |
agent_processor = None
|
315 |
|
316 |
# Add CORS middleware
|
@@ -322,21 +306,6 @@ app.add_middleware(
|
|
322 |
allow_headers=["*"],
|
323 |
)
|
324 |
|
325 |
-
# Add security scheme
|
326 |
-
app.add_security_requirement({"ApiKeyAuth": []})
|
327 |
-
app.openapi_schema = None # Reset OpenAPI schema
|
328 |
-
|
329 |
-
# Define the security scheme
|
330 |
-
security_scheme = {
|
331 |
-
"ApiKeyAuth": {
|
332 |
-
"type": "apiKey",
|
333 |
-
"in": "header",
|
334 |
-
"name": "X-API-Key",
|
335 |
-
"description": "API key required for authentication"
|
336 |
-
}
|
337 |
-
}
|
338 |
-
app.openapi_components = {"securitySchemes": security_scheme}
|
339 |
-
|
340 |
@app.on_event("startup")
|
341 |
async def startup_event():
|
342 |
global agent_processor
|
@@ -349,41 +318,12 @@ async def shutdown_event():
|
|
349 |
if agent_processor:
|
350 |
await agent_processor.cleanup()
|
351 |
|
352 |
-
|
353 |
-
async def
|
354 |
-
api_key_header: str = Security(api_key_header)
|
355 |
-
) -> APIKey:
|
356 |
-
"""Validate API key from header."""
|
357 |
-
if not API_KEY:
|
358 |
-
raise HTTPException(
|
359 |
-
status_code=500,
|
360 |
-
detail="API key configuration is missing on server"
|
361 |
-
)
|
362 |
-
if api_key_header == API_KEY:
|
363 |
-
return api_key_header
|
364 |
-
raise HTTPException(
|
365 |
-
status_code=403,
|
366 |
-
detail="Invalid or missing API key"
|
367 |
-
)
|
368 |
-
|
369 |
-
# Update your route to require API key
|
370 |
-
@app.post(
|
371 |
-
"/v1/agent",
|
372 |
-
tags=["agent"],
|
373 |
-
summary="Process agent request",
|
374 |
-
response_class=StreamingResponse,
|
375 |
-
responses={
|
376 |
-
403: {"description": "Invalid or missing API key"},
|
377 |
-
500: {"description": "Internal server error"}
|
378 |
-
}
|
379 |
-
)
|
380 |
-
async def process_agent_request(
|
381 |
-
request: AgentRequest,
|
382 |
-
api_key: APIKey = Security(api_key_header, scopes=[])
|
383 |
-
):
|
384 |
try:
|
385 |
logger.info(f"Processing agent request: {request.query}")
|
386 |
return await agent_processor.process_stream(request)
|
|
|
387 |
except Exception as e:
|
388 |
logger.error(f"Error in agent request processing: {e}", exc_info=True)
|
389 |
raise HTTPException(status_code=500, detail=str(e))
|
@@ -409,173 +349,4 @@ if __name__ == "__main__":
|
|
409 |
host="0.0.0.0",
|
410 |
port=port,
|
411 |
reload=True
|
412 |
-
)
|
413 |
-
|
414 |
-
# Add custom docs endpoint
|
415 |
-
@app.get("/docs", include_in_schema=False)
|
416 |
-
async def custom_swagger_ui_html():
|
417 |
-
return get_swagger_ui_html(
|
418 |
-
openapi_url=app.openapi_url,
|
419 |
-
title=app.title + " - Swagger UI",
|
420 |
-
oauth2_redirect_url=app.swagger_ui_oauth2_redirect_url,
|
421 |
-
swagger_js_url="https://unpkg.com/[email protected]/swagger-ui-bundle.js",
|
422 |
-
swagger_css_url="https://unpkg.com/[email protected]/swagger-ui.css",
|
423 |
-
swagger_favicon_url="https://fastapi.tiangolo.com/img/favicon.png",
|
424 |
-
extra_html="""
|
425 |
-
<style>
|
426 |
-
/* Dark theme with cool colors */
|
427 |
-
:root {
|
428 |
-
--primary-color: #00b4d8;
|
429 |
-
--secondary-color: #90e0ef;
|
430 |
-
--background-color: #0d1117;
|
431 |
-
--text-color: #e6edf3;
|
432 |
-
--border-color: #30363d;
|
433 |
-
}
|
434 |
-
|
435 |
-
body {
|
436 |
-
background-color: var(--background-color);
|
437 |
-
color: var(--text-color);
|
438 |
-
}
|
439 |
-
|
440 |
-
.swagger-ui {
|
441 |
-
background-color: var(--background-color);
|
442 |
-
color: var(--text-color);
|
443 |
-
}
|
444 |
-
|
445 |
-
/* Headers and text */
|
446 |
-
.swagger-ui .info .title,
|
447 |
-
.swagger-ui .info .base-url,
|
448 |
-
.swagger-ui .info li,
|
449 |
-
.swagger-ui .info p,
|
450 |
-
.swagger-ui .info table {
|
451 |
-
color: var(--text-color);
|
452 |
-
}
|
453 |
-
|
454 |
-
/* Operation buttons */
|
455 |
-
.swagger-ui .opblock.opblock-post {
|
456 |
-
background: rgba(0, 180, 216, 0.1);
|
457 |
-
border-color: var(--primary-color);
|
458 |
-
}
|
459 |
-
|
460 |
-
.swagger-ui .opblock.opblock-post .opblock-summary-method {
|
461 |
-
background: var(--primary-color);
|
462 |
-
}
|
463 |
-
|
464 |
-
/* Authorize button */
|
465 |
-
.swagger-ui .btn.authorize {
|
466 |
-
background: var(--primary-color);
|
467 |
-
border-color: var(--primary-color);
|
468 |
-
color: white;
|
469 |
-
}
|
470 |
-
|
471 |
-
.swagger-ui .btn.authorize svg {
|
472 |
-
fill: white;
|
473 |
-
}
|
474 |
-
|
475 |
-
/* Schema sections */
|
476 |
-
.swagger-ui .model-box {
|
477 |
-
background: rgba(48, 54, 61, 0.4);
|
478 |
-
}
|
479 |
-
|
480 |
-
.swagger-ui .model {
|
481 |
-
color: var(--text-color);
|
482 |
-
}
|
483 |
-
|
484 |
-
/* Try it out section */
|
485 |
-
.swagger-ui textarea,
|
486 |
-
.swagger-ui input[type=text] {
|
487 |
-
background: var(--background-color);
|
488 |
-
color: var(--text-color);
|
489 |
-
border-color: var(--border-color);
|
490 |
-
}
|
491 |
-
|
492 |
-
/* Response section */
|
493 |
-
.swagger-ui .responses-table th,
|
494 |
-
.swagger-ui .responses-table td {
|
495 |
-
color: var(--text-color);
|
496 |
-
border-color: var(--border-color);
|
497 |
-
}
|
498 |
-
|
499 |
-
/* Scrollbar */
|
500 |
-
::-webkit-scrollbar {
|
501 |
-
width: 8px;
|
502 |
-
height: 8px;
|
503 |
-
}
|
504 |
-
|
505 |
-
::-webkit-scrollbar-track {
|
506 |
-
background: var(--background-color);
|
507 |
-
}
|
508 |
-
|
509 |
-
::-webkit-scrollbar-thumb {
|
510 |
-
background: var(--primary-color);
|
511 |
-
border-radius: 4px;
|
512 |
-
}
|
513 |
-
|
514 |
-
/* Code blocks */
|
515 |
-
.swagger-ui .highlight-code {
|
516 |
-
background-color: #1b1f24;
|
517 |
-
}
|
518 |
-
|
519 |
-
/* Modal dialogs */
|
520 |
-
.swagger-ui .dialog-ux .modal-ux {
|
521 |
-
background: var(--background-color);
|
522 |
-
border-color: var(--border-color);
|
523 |
-
}
|
524 |
-
|
525 |
-
.swagger-ui .dialog-ux .modal-ux-header h3 {
|
526 |
-
color: var(--text-color);
|
527 |
-
}
|
528 |
-
|
529 |
-
/* Tables */
|
530 |
-
.swagger-ui table thead tr td,
|
531 |
-
.swagger-ui table thead tr th {
|
532 |
-
color: var(--text-color);
|
533 |
-
border-color: var(--border-color);
|
534 |
-
}
|
535 |
-
|
536 |
-
/* Links */
|
537 |
-
.swagger-ui a {
|
538 |
-
color: var(--primary-color);
|
539 |
-
}
|
540 |
-
|
541 |
-
/* Schema dropdowns */
|
542 |
-
.swagger-ui select {
|
543 |
-
background: var(--background-color);
|
544 |
-
color: var(--text-color);
|
545 |
-
border-color: var(--border-color);
|
546 |
-
}
|
547 |
-
</style>
|
548 |
-
"""
|
549 |
-
)
|
550 |
-
|
551 |
-
def custom_openapi():
|
552 |
-
if app.openapi_schema:
|
553 |
-
return app.openapi_schema
|
554 |
-
|
555 |
-
openapi_schema = get_openapi(
|
556 |
-
title=app.title,
|
557 |
-
version=app.version,
|
558 |
-
description=app.description,
|
559 |
-
routes=app.routes,
|
560 |
-
)
|
561 |
-
|
562 |
-
# Add security scheme to components
|
563 |
-
openapi_schema["components"] = {
|
564 |
-
"securitySchemes": {
|
565 |
-
"ApiKeyAuth": {
|
566 |
-
"type": "apiKey",
|
567 |
-
"in": "header",
|
568 |
-
"name": "X-API-Key",
|
569 |
-
"description": "API key required for authentication"
|
570 |
-
}
|
571 |
-
}
|
572 |
-
}
|
573 |
-
|
574 |
-
# Add global security requirement
|
575 |
-
openapi_schema["security"] = [{"ApiKeyAuth": []}]
|
576 |
-
|
577 |
-
app.openapi_schema = openapi_schema
|
578 |
-
return app.openapi_schema
|
579 |
-
|
580 |
-
# Set the custom OpenAPI schema
|
581 |
-
app.openapi = custom_openapi
|
|
|
1 |
+
from fastapi import FastAPI, HTTPException, Request
|
2 |
from fastapi.middleware.cors import CORSMiddleware
|
3 |
from typing import Dict, List, Optional, Union, Any
|
4 |
from pydantic import BaseModel, Field
|
|
|
16 |
from fastapi.responses import JSONResponse
|
17 |
from response_formatter import ResponseFormatter
|
18 |
import traceback
|
|
|
|
|
|
|
|
|
|
|
19 |
|
20 |
# Load environment variables
|
21 |
load_dotenv()
|
|
|
27 |
)
|
28 |
logger = logging.getLogger(__name__)
|
29 |
|
|
|
|
|
|
|
|
|
|
|
30 |
class AgentOutput(BaseModel):
|
31 |
"""Structured output from agent processing"""
|
32 |
thought_content: str
|
|
|
294 |
return None
|
295 |
|
296 |
# Initialize FastAPI app
|
297 |
+
app = FastAPI(docs_url="/", redoc_url=None)
|
|
|
|
|
|
|
|
|
|
|
|
|
298 |
agent_processor = None
|
299 |
|
300 |
# Add CORS middleware
|
|
|
306 |
allow_headers=["*"],
|
307 |
)
|
308 |
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
309 |
@app.on_event("startup")
|
310 |
async def startup_event():
|
311 |
global agent_processor
|
|
|
318 |
if agent_processor:
|
319 |
await agent_processor.cleanup()
|
320 |
|
321 |
+
@app.post("/v1/agent")
|
322 |
+
async def process_agent_request(request: AgentRequest):
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
323 |
try:
|
324 |
logger.info(f"Processing agent request: {request.query}")
|
325 |
return await agent_processor.process_stream(request)
|
326 |
+
|
327 |
except Exception as e:
|
328 |
logger.error(f"Error in agent request processing: {e}", exc_info=True)
|
329 |
raise HTTPException(status_code=500, detail=str(e))
|
|
|
349 |
host="0.0.0.0",
|
350 |
port=port,
|
351 |
reload=True
|
352 |
+
)
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|