|
| 1 | +from __future__ import annotations |
| 2 | + |
| 3 | +import json |
| 4 | +from typing import Any |
| 5 | + |
| 6 | +from gateframe.core.contract import ValidationContract, ValidationResult |
| 7 | + |
| 8 | + |
| 9 | +def _require_langchain() -> None: |
| 10 | + try: |
| 11 | + import langchain # noqa: F401 |
| 12 | + except ImportError: |
| 13 | + raise ImportError( |
| 14 | + "langchain is required for this integration. " |
| 15 | + "Install it with: pip install gateframe[langchain]" |
| 16 | + ) from None |
| 17 | + |
| 18 | + |
| 19 | +def extract_text(response: Any, output_key: str = "output") -> str: # noqa: ANN401 |
| 20 | + """Extract text from a LangChain response (str, AIMessage, or dict).""" |
| 21 | + if isinstance(response, str): |
| 22 | + return response |
| 23 | + if isinstance(response, dict): |
| 24 | + if output_key not in response: |
| 25 | + raise ValueError(f"Key '{output_key}' not found in response dict.") |
| 26 | + value = response[output_key] |
| 27 | + if not isinstance(value, str): |
| 28 | + raise ValueError(f"Expected str at key '{output_key}', got {type(value).__name__}.") |
| 29 | + return value |
| 30 | + content = getattr(response, "content", None) |
| 31 | + if content is not None: |
| 32 | + if not isinstance(content, str): |
| 33 | + raise ValueError(f"Expected str content, got {type(content).__name__}.") |
| 34 | + return content |
| 35 | + raise ValueError(f"Cannot extract text from response of type {type(response).__name__}.") |
| 36 | + |
| 37 | + |
| 38 | +def extract_json(response: Any, output_key: str = "output") -> dict[str, Any]: # noqa: ANN401 |
| 39 | + """Extract text, then parse as JSON. Raises ValueError on failure.""" |
| 40 | + text = extract_text(response, output_key=output_key) |
| 41 | + try: |
| 42 | + data = json.loads(text) |
| 43 | + except json.JSONDecodeError as exc: |
| 44 | + raise ValueError( |
| 45 | + f"Failed to parse response as JSON: {exc}. Raw text: {text[:200]}" |
| 46 | + ) from exc |
| 47 | + if not isinstance(data, dict): |
| 48 | + raise ValueError(f"Expected JSON object, got {type(data).__name__}.") |
| 49 | + return data |
| 50 | + |
| 51 | + |
| 52 | +def extract_metadata(response: Any) -> dict[str, Any]: # noqa: ANN401 |
| 53 | + """Extract available metadata from a LangChain response. Omits None values.""" |
| 54 | + meta: dict[str, Any] = {} |
| 55 | + |
| 56 | + if isinstance(response, str): |
| 57 | + return meta |
| 58 | + |
| 59 | + response_metadata = getattr(response, "response_metadata", None) |
| 60 | + if isinstance(response_metadata, dict): |
| 61 | + for k, v in response_metadata.items(): |
| 62 | + if v is not None: |
| 63 | + meta[k] = v |
| 64 | + |
| 65 | + type_val = getattr(response, "type", None) |
| 66 | + if type_val is not None: |
| 67 | + meta["type"] = type_val |
| 68 | + |
| 69 | + source_documents = getattr(response, "source_documents", None) |
| 70 | + if source_documents is not None: |
| 71 | + meta["source_document_count"] = len(source_documents) |
| 72 | + |
| 73 | + return meta |
| 74 | + |
| 75 | + |
| 76 | +class LangChainValidator: |
| 77 | + def __init__( |
| 78 | + self, |
| 79 | + contract: ValidationContract, |
| 80 | + *, |
| 81 | + parse_json: bool = False, |
| 82 | + output_key: str = "output", |
| 83 | + ) -> None: |
| 84 | + self._contract = contract |
| 85 | + self._parse_json = parse_json |
| 86 | + self._output_key = output_key |
| 87 | + |
| 88 | + def validate(self, response: Any, **context: Any) -> ValidationResult: # noqa: ANN401 |
| 89 | + output = ( |
| 90 | + extract_json(response, output_key=self._output_key) |
| 91 | + if self._parse_json |
| 92 | + else extract_text(response, output_key=self._output_key) |
| 93 | + ) |
| 94 | + metadata = extract_metadata(response) |
| 95 | + merged = {**metadata, **context} |
| 96 | + return self._contract.validate(output, **merged) |
0 commit comments