Ani14 commited on
Commit
e300631
·
verified ·
1 Parent(s): 2496d5a

Upload 2 files

Browse files
Files changed (2) hide show
  1. app.py +39 -7
  2. models.py +1 -1
app.py CHANGED
@@ -1,22 +1,29 @@
1
  import os
2
  import time
 
 
3
  from fastapi import FastAPI, Request, HTTPException, Depends, status
 
 
4
  from fastapi.security import APIKeyHeader
5
- from typing import Dict, Any
6
  from datetime import datetime
7
 
8
  # LangGraph and Model Imports
9
  from langgraph.checkpoint.memory import MemorySaver
10
  from langgraph.checkpoint.base import BaseCheckpointSaver
11
- from agent import create_honeypot_graph, final_callback
12
  from models import (
13
  HoneypotRequest, HoneypotResponse,
14
  AgentState, ExtractedIntelligence, Message, EngagementMetrics
15
  )
16
 
 
 
 
 
17
  # --- Configuration ---
18
  API_KEY_NAME = "x-api-key"
19
- # Default key for testing, should be set via environment variable in production
20
  API_KEY = os.environ.get("HONEYPOT_API_KEY", "sk_test_123456789")
21
  api_key_header = APIKeyHeader(name=API_KEY_NAME, auto_error=False)
22
 
@@ -24,13 +31,39 @@ api_key_header = APIKeyHeader(name=API_KEY_NAME, auto_error=False)
24
  app = FastAPI(
25
  title="Agentic Honey-Pot API",
26
  description="REST API for Scam Detection and Intelligence Extraction (Problem Statement 2).",
27
- version="1.0.0"
28
  )
29
 
30
  # Initialize LangGraph Checkpointer
31
  checkpointer: BaseCheckpointSaver = MemorySaver()
32
  honeypot_app = create_honeypot_graph(checkpointer)
33
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
34
  # --- Dependency for API Key Validation ---
35
  async def get_api_key(api_key_header: str = Depends(api_key_header)):
36
  if api_key_header is None or api_key_header != API_KEY:
@@ -59,7 +92,6 @@ async def honeypot_detection(
59
 
60
  if checkpoint and checkpoint.values:
61
  current_state_dict = checkpoint.values
62
- # Ensure all required fields exist
63
  current_state_dict.setdefault("callbackSent", False)
64
  current_state_dict.setdefault("agentNotes", "")
65
  current_state_dict.setdefault("extractedIntelligence", ExtractedIntelligence())
@@ -92,7 +124,7 @@ async def honeypot_detection(
92
 
93
  engagement_duration = int(time.time() - start_time)
94
 
95
- # Prepare response strictly matching PDF page 10/11
96
  return {
97
  "status": "success",
98
  "scamDetected": final_state["scamDetected"],
@@ -105,7 +137,7 @@ async def honeypot_detection(
105
  }
106
 
107
  except Exception as e:
108
- print(f"Error in Honey-Pot: {e}")
109
  raise HTTPException(
110
  status_code=status.HTTP_500_INTERNAL_SERVER_ERROR,
111
  detail=f"Internal server error: {str(e)}",
 
1
  import os
2
  import time
3
+ import logging
4
+ import json
5
  from fastapi import FastAPI, Request, HTTPException, Depends, status
6
+ from fastapi.exceptions import RequestValidationError
7
+ from fastapi.responses import JSONResponse
8
  from fastapi.security import APIKeyHeader
9
+ from typing import Dict, Any, Optional
10
  from datetime import datetime
11
 
12
  # LangGraph and Model Imports
13
  from langgraph.checkpoint.memory import MemorySaver
14
  from langgraph.checkpoint.base import BaseCheckpointSaver
15
+ from agent import create_honeypot_graph
16
  from models import (
17
  HoneypotRequest, HoneypotResponse,
18
  AgentState, ExtractedIntelligence, Message, EngagementMetrics
19
  )
20
 
21
+ # --- Logging Configuration ---
22
+ logging.basicConfig(level=logging.INFO)
23
+ logger = logging.getLogger(__name__)
24
+
25
  # --- Configuration ---
26
  API_KEY_NAME = "x-api-key"
 
27
  API_KEY = os.environ.get("HONEYPOT_API_KEY", "sk_test_123456789")
28
  api_key_header = APIKeyHeader(name=API_KEY_NAME, auto_error=False)
29
 
 
31
  app = FastAPI(
32
  title="Agentic Honey-Pot API",
33
  description="REST API for Scam Detection and Intelligence Extraction (Problem Statement 2).",
34
+ version="1.2.0"
35
  )
36
 
37
  # Initialize LangGraph Checkpointer
38
  checkpointer: BaseCheckpointSaver = MemorySaver()
39
  honeypot_app = create_honeypot_graph(checkpointer)
40
 
41
+ # --- Exception Handler for Diagnostic Logging ---
42
+ @app.exception_handler(RequestValidationError)
43
+ async def validation_exception_handler(request: Request, exc: RequestValidationError):
44
+ """
45
+ Captures and logs the exact payload that caused a 422 Unprocessable Entity error.
46
+ This is crucial for diagnosing why the tester is failing.
47
+ """
48
+ body = await request.body()
49
+ try:
50
+ payload = json.loads(body)
51
+ except:
52
+ payload = body.decode()
53
+
54
+ logger.error(f"422 Unprocessable Entity Error!")
55
+ logger.error(f"Payload received: {payload}")
56
+ logger.error(f"Validation errors: {exc.errors()}")
57
+
58
+ return JSONResponse(
59
+ status_code=status.HTTP_422_UNPROCESSABLE_ENTITY,
60
+ content={
61
+ "detail": exc.errors(),
62
+ "body": payload,
63
+ "message": "The request body does not match the Problem Statement 2 schema. Check logs for details."
64
+ }
65
+ )
66
+
67
  # --- Dependency for API Key Validation ---
68
  async def get_api_key(api_key_header: str = Depends(api_key_header)):
69
  if api_key_header is None or api_key_header != API_KEY:
 
92
 
93
  if checkpoint and checkpoint.values:
94
  current_state_dict = checkpoint.values
 
95
  current_state_dict.setdefault("callbackSent", False)
96
  current_state_dict.setdefault("agentNotes", "")
97
  current_state_dict.setdefault("extractedIntelligence", ExtractedIntelligence())
 
124
 
125
  engagement_duration = int(time.time() - start_time)
126
 
127
+ # Prepare response strictly matching PDF
128
  return {
129
  "status": "success",
130
  "scamDetected": final_state["scamDetected"],
 
137
  }
138
 
139
  except Exception as e:
140
+ logger.error(f"Internal Error: {e}")
141
  raise HTTPException(
142
  status_code=status.HTTP_500_INTERNAL_SERVER_ERROR,
143
  detail=f"Internal server error: {str(e)}",
models.py CHANGED
@@ -26,7 +26,7 @@ class HoneypotRequest(BaseModel):
26
  class ExtractedIntelligence(BaseModel):
27
  """Structured data to be extracted from the conversation."""
28
  bankAccounts: List[str] = Field(default_factory=list)
29
- upilds: List[str] = Field(default_factory=list)
30
  phishingLinks: List[str] = Field(default_factory=list)
31
  phoneNumbers: List[str] = Field(default_factory=list)
32
  suspiciousKeywords: List[str] = Field(default_factory=list)
 
26
  class ExtractedIntelligence(BaseModel):
27
  """Structured data to be extracted from the conversation."""
28
  bankAccounts: List[str] = Field(default_factory=list)
29
+ upilds: List[str] = Field(default_factory=list) # Strictly 'upilds' as per PDF
30
  phishingLinks: List[str] = Field(default_factory=list)
31
  phoneNumbers: List[str] = Field(default_factory=list)
32
  suspiciousKeywords: List[str] = Field(default_factory=list)