Skip to content

Commit 8396a3a

Browse files
committed
feat: add basic schema validation layer for extraction outputs
1 parent ceea4de commit 8396a3a

4 files changed

Lines changed: 38 additions & 2 deletions

File tree

src/llm.py

Lines changed: 7 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -2,6 +2,7 @@
22
import os
33
import requests
44
from api.services.prompt_builder import build_extraction_prompt
5+
from src.validation import validate_extraction
56

67
def safe_extract_value(response: str):
78
if not response:
@@ -160,4 +161,9 @@ def handle_plural_values(self, plural_value):
160161
return values
161162

162163
def get_data(self):
163-
return self._json
164+
validated_data, errors = validate_extraction(self._json)
165+
166+
if errors:
167+
print("[Validation Warning]", errors)
168+
169+
return validated_data

src/main.py

Lines changed: 2 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -2,7 +2,8 @@
22
# from backend import Fill
33
from commonforms import prepare_form
44
from pypdf import PdfReader
5-
from controller import Controller
5+
from typing import Union
6+
from src.controller import Controller
67

78
def input_fields(num_fields: int):
89
fields = []

src/validation.py

Lines changed: 29 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,29 @@
1+
from pydantic import BaseModel, ValidationError
2+
from typing import Optional
3+
4+
5+
class ExtractionSchema(BaseModel):
6+
name: Optional[str]
7+
location: Optional[str]
8+
date: Optional[str]
9+
incident_type: Optional[str]
10+
description: Optional[str]
11+
12+
class Config:
13+
extra = "allow"
14+
15+
16+
def validate_extraction(data: dict):
17+
try:
18+
validated = ExtractionSchema(**data)
19+
return validated.dict(), None
20+
except ValidationError as e:
21+
formatted_errors = []
22+
23+
for err in e.errors():
24+
formatted_errors.append({
25+
"field": err.get("loc", ["unknown"])[0],
26+
"issue": err.get("msg", "Invalid value")
27+
})
28+
29+
return data, formatted_errors

temp_outfile.pdf

72.7 KB
Binary file not shown.

0 commit comments

Comments
 (0)