graph-knowledge-doc-parser 0.2.6__py3-none-any.whl → 0.2.9__py3-none-any.whl
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- {graph_knowledge_doc_parser-0.2.6.dist-info → graph_knowledge_doc_parser-0.2.9.dist-info}/METADATA +5 -4
- graph_knowledge_doc_parser-0.2.9.dist-info/RECORD +44 -0
- kg_doc_parser/__init__.py +4 -3
- kg_doc_parser/cast_hinting.py +4 -1
- kg_doc_parser/document_ingester_logger.py +101 -57
- kg_doc_parser/llm_structured_output.py +40 -13
- kg_doc_parser/models.py +40 -39
- kg_doc_parser/ocr.py +120 -62
- kg_doc_parser/pdf2png.py +9 -4
- kg_doc_parser/semantic_document_splitting_layerwise_edits.py +362 -237
- kg_doc_parser/text_processing_utils.py +11 -4
- kg_doc_parser/utils/file_loaders.py +55 -34
- kg_doc_parser/utils/langchain.py +108 -33
- kg_doc_parser/utils/log.py +8 -6
- kg_doc_parser/utils/version_chaining.py +136 -67
- kg_doc_parser/workflow_ingest/__init__.py +6 -0
- kg_doc_parser/workflow_ingest/adapters.py +125 -29
- kg_doc_parser/workflow_ingest/cache.py +22 -10
- kg_doc_parser/workflow_ingest/cli.py +3 -2
- kg_doc_parser/workflow_ingest/clients.py +175 -56
- kg_doc_parser/workflow_ingest/demo_harness.py +49 -13
- kg_doc_parser/workflow_ingest/design.py +27 -1
- kg_doc_parser/workflow_ingest/handlers.py +173 -51
- kg_doc_parser/workflow_ingest/layered_contracts.py +33 -14
- kg_doc_parser/workflow_ingest/layerwise_llm.py +353 -203
- kg_doc_parser/workflow_ingest/models.py +251 -88
- kg_doc_parser/workflow_ingest/ocr_pipeline.py +56 -22
- kg_doc_parser/workflow_ingest/page_index.py +172 -118
- kg_doc_parser/workflow_ingest/parser_core.py +181 -32
- kg_doc_parser/workflow_ingest/parsing.py +94 -12
- kg_doc_parser/workflow_ingest/probe.py +20 -18
- kg_doc_parser/workflow_ingest/providers.py +99 -41
- kg_doc_parser/workflow_ingest/runners.py +44 -26
- kg_doc_parser/workflow_ingest/semantics.py +131 -53
- kg_doc_parser/workflow_ingest/serialization.py +36 -8
- kg_doc_parser/workflow_ingest/service.py +56 -19
- kg_doc_parser/workflow_ingest/strategy.py +33 -14
- graph_knowledge_doc_parser-0.2.6.dist-info/RECORD +0 -44
- {graph_knowledge_doc_parser-0.2.6.dist-info → graph_knowledge_doc_parser-0.2.9.dist-info}/WHEEL +0 -0
- {graph_knowledge_doc_parser-0.2.6.dist-info → graph_knowledge_doc_parser-0.2.9.dist-info}/entry_points.txt +0 -0
{graph_knowledge_doc_parser-0.2.6.dist-info → graph_knowledge_doc_parser-0.2.9.dist-info}/METADATA
RENAMED
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
Metadata-Version: 2.4
|
|
2
2
|
Name: graph-knowledge-doc-parser
|
|
3
|
-
Version: 0.2.
|
|
3
|
+
Version: 0.2.9
|
|
4
4
|
Summary: doc parser using llm driven engine with graph knowledge awareness
|
|
5
5
|
Author: humblemat810
|
|
6
6
|
Author-email: 67593116+humblemat810@users.noreply.github.com
|
|
@@ -21,7 +21,7 @@ Provides-Extra: openai
|
|
|
21
21
|
Provides-Extra: vertex
|
|
22
22
|
Requires-Dist: diskcache (>=5.6,<6.0) ; platform_python_implementation == "PyPy"
|
|
23
23
|
Requires-Dist: joblib (>=1.5.3,<2.0.0) ; platform_python_implementation == "CPython"
|
|
24
|
-
Requires-Dist: kogwistar (==0.6.
|
|
24
|
+
Requires-Dist: kogwistar (==0.6.7)
|
|
25
25
|
Requires-Dist: langchain-core (>=1.2.5,<2.0.0)
|
|
26
26
|
Requires-Dist: langchain-google-genai (>=4.1.2,<5.0.0) ; extra == "gemini" or extra == "cloud"
|
|
27
27
|
Requires-Dist: langchain-google-vertexai (>=3.2.4,<4.0.0) ; extra == "vertex" or extra == "cloud"
|
|
@@ -34,6 +34,7 @@ Requires-Dist: pydantic (>=2.12.5,<3.0.0)
|
|
|
34
34
|
Requires-Dist: pydantic-extension (>=0.0.7,<0.0.8)
|
|
35
35
|
Requires-Dist: pypdf (>=6.5.0,<7.0.0)
|
|
36
36
|
Requires-Dist: rapidfuzz (>=3.14.3,<4.0.0)
|
|
37
|
+
Requires-Dist: typing-extensions (>=4.8.0,<5.0.0)
|
|
37
38
|
Project-URL: Homepage, https://github.com/humblemat810/kg_doc_parser
|
|
38
39
|
Project-URL: Repository, https://github.com/humblemat810/kg_doc_parser
|
|
39
40
|
Description-Content-Type: text/markdown
|
|
@@ -85,8 +86,8 @@ to normal strategy selection. See the
|
|
|
85
86
|
The deterministic and text-only Bonsai fixture evaluation is recorded in the
|
|
86
87
|
[`PageIndex adversarial fixture report`](doc/page_index_adversarial_fixture_report.md).
|
|
87
88
|
The current patch release is documented in the
|
|
88
|
-
[`0.2.
|
|
89
|
-
[`0.2.
|
|
89
|
+
[`0.2.9` release note](doc/release_0.2.9.md); the prior
|
|
90
|
+
[`0.2.7` release note](doc/release_0.2.7.md) remains available for history.
|
|
90
91
|
|
|
91
92
|
For an adoption path that starts with parser-grounded source units and later
|
|
92
93
|
adds LLM-Wiki cross-document maintenance, see
|
|
@@ -0,0 +1,44 @@
|
|
|
1
|
+
kg_doc_parser/__init__.py,sha256=5t4JrxMB8IFgaYzKRTy3VOz3pav-rZ3Kv5H-Rjs2PDc,418
|
|
2
|
+
kg_doc_parser/cast_hinting.py,sha256=_uQNgii_K9EbOAj9aElIKkdO6o5PDIN6ajUiQ6P17sk,587
|
|
3
|
+
kg_doc_parser/document_ingest_log_config.py,sha256=1qSM8rH3pb9TcK7saGimwNXjayQh0iE1-tz4w3172lQ,793
|
|
4
|
+
kg_doc_parser/document_ingester_logger.py,sha256=Ux_5dSEQBm98y-GYZQ3IhzGnSOTN5G9KQadVYUBJK6A,29709
|
|
5
|
+
kg_doc_parser/llm_structured_output.py,sha256=A2zbu5-27IDgldSaL9XuuxXtwD3ZXGL6lNOfixSe5bk,2508
|
|
6
|
+
kg_doc_parser/models.py,sha256=cMAqoOo6UO7Ga62jeIkKwGkMUGh2-oybXuyNNof6dR8,16034
|
|
7
|
+
kg_doc_parser/ocr.py,sha256=bM7RrSTym178dGRGOQjr08b3zVaye-UzeTidUeinfYU,50297
|
|
8
|
+
kg_doc_parser/pdf2png.py,sha256=mwxo510tLk2o0dOw5ctGZW566onvvVwCs3Byomf-9qc,11987
|
|
9
|
+
kg_doc_parser/semantic_document_splitting_layerwise_edits.py,sha256=WsolD9ZOoCM8vo-ZCtBf9Ea8OvV7IBsok5XTQnlPKXc,160842
|
|
10
|
+
kg_doc_parser/text_processing_utils.py,sha256=nWnPmJdwdX9OTgSCZABCY2o-ksa4FbMt0fi7J8WTUtQ,1135
|
|
11
|
+
kg_doc_parser/utils/__init__.py,sha256=47DEQpj8HBSa-_TImW-5JCeuQeRkm5NMpJWZG3hSuFU,0
|
|
12
|
+
kg_doc_parser/utils/bounded_threadpool_executor.py,sha256=gB0pXOZjeAcDw37DbFth_eYFJuHPmANNCy_7Ev1Abt8,1495
|
|
13
|
+
kg_doc_parser/utils/file_loaders.py,sha256=rRT1wJ-j6aUVRsLZtcmCGTsEJhfqbkI7H4KLrqEnlno,19007
|
|
14
|
+
kg_doc_parser/utils/langchain.py,sha256=0cqvfiwHAp-LXQBxyEFFZIiMfJx1rORSQzLITXW8nZY,13037
|
|
15
|
+
kg_doc_parser/utils/log.py,sha256=KWYOS0DrfLJRKqiPADmJ6Q7y7pELqq30KTmYhnJVTC8,4819
|
|
16
|
+
kg_doc_parser/utils/version_chaining.py,sha256=77_nWZpn6eA5EW0StMO1Kh8DeXnaQ7DHC42KOLS4NIs,57374
|
|
17
|
+
kg_doc_parser/workflow_ingest/__init__.py,sha256=vec-csN6JryQJxioecde3qUF8swSBStNY1ujYpVRNlo,6495
|
|
18
|
+
kg_doc_parser/workflow_ingest/_kogwistar.py,sha256=YI4aWToJt2VELxrp5NWUyjp9_n1_COuP4QulSP5FMk4,454
|
|
19
|
+
kg_doc_parser/workflow_ingest/adapters.py,sha256=KVVhhkbg3-4Qkrsrqb63wJxYCZCL3W99oDyp4NCOKS4,13044
|
|
20
|
+
kg_doc_parser/workflow_ingest/cache.py,sha256=oGAyBw8ST8EknGnCgZvKBPimBDvTlbX39uw3gSR9408,2620
|
|
21
|
+
kg_doc_parser/workflow_ingest/cli.py,sha256=8brKCApxa1PvBynmoUOgIsoQMAgMZXrG_0ZfBr34Lfc,15669
|
|
22
|
+
kg_doc_parser/workflow_ingest/clients.py,sha256=yaq1stqy5qTCdfnV1E0ESt_oz4IqKMEs0LFch7m2PPI,23938
|
|
23
|
+
kg_doc_parser/workflow_ingest/demo_harness.py,sha256=LPDxq4a4NRiLgcnclxUtlwTYbh6spQvVU6LE1eTWNso,17957
|
|
24
|
+
kg_doc_parser/workflow_ingest/design.py,sha256=gwzEo22oSzV0U8WtCy153P3lbXKsUgllqLq3B6rq7zs,9628
|
|
25
|
+
kg_doc_parser/workflow_ingest/handlers.py,sha256=6nfeqUSNO42N-Hb_A56U915TprBfAtTBp3Hz7SUJJgo,57653
|
|
26
|
+
kg_doc_parser/workflow_ingest/layered_contracts.py,sha256=V5ln1gNudNzG4kPIKkW0faiQneM_ZVgLJ7yDZlKxyhc,11568
|
|
27
|
+
kg_doc_parser/workflow_ingest/layerwise_llm.py,sha256=CH-wneyqxapaWC5-gEpWkwaviPNJJj4i-Y32butNPIk,134872
|
|
28
|
+
kg_doc_parser/workflow_ingest/models.py,sha256=oR7tlUoDfkQ08SWPqtMPCzIxsTxwTE5t5cauS_jIWR4,38930
|
|
29
|
+
kg_doc_parser/workflow_ingest/ocr_pipeline.py,sha256=3mgVsJIu1dvHH7JwlGZCFm7jG9u-S4YKK_YPz8S-uCU,61112
|
|
30
|
+
kg_doc_parser/workflow_ingest/page_index.py,sha256=eFB024bUaT6K94l3RFhjHeGLTDIrPDT7yBew4dt9ork,123677
|
|
31
|
+
kg_doc_parser/workflow_ingest/parser_core.py,sha256=QnOLVC0Ts-Gk1cg9_mzfDeML7ln4ZjCB7MdmRSJKvqk,64674
|
|
32
|
+
kg_doc_parser/workflow_ingest/parsing.py,sha256=NAnxiny8UiDZ2MGAbTTHiRdqO51qFaMHb0s-HAL0O_o,12329
|
|
33
|
+
kg_doc_parser/workflow_ingest/probe.py,sha256=1vADLX3zVD1EohCPCeH_T2dgM8GZBwDQdc9-HomqApk,6423
|
|
34
|
+
kg_doc_parser/workflow_ingest/providers.py,sha256=XRukZRTnzR3LkU3qzJ8qPiASRe3tW_LqxCVs1G12Wps,45459
|
|
35
|
+
kg_doc_parser/workflow_ingest/runners.py,sha256=fEFXQVJ7RIDXBkmstZiUs5OO0Y6Kqrae5iTQbFMW6Ic,20550
|
|
36
|
+
kg_doc_parser/workflow_ingest/semantics.py,sha256=ieUMJNUHk81xkZmCKsERaqp10m5_axZhAuyHCFzc3yg,17886
|
|
37
|
+
kg_doc_parser/workflow_ingest/serialization.py,sha256=INd_wmPYGIySqCrGDhWUQKj49sJzPH5IfMlXNGnoa7Q,2903
|
|
38
|
+
kg_doc_parser/workflow_ingest/service.py,sha256=OVlHkf4OtHUpJ1WN6Ag3NfmrQFwouQIQDrjm592iWx4,10446
|
|
39
|
+
kg_doc_parser/workflow_ingest/smoke_assets.py,sha256=FA6JSUBAIZFPUz52G3UrQByMLrQhC8N9NinWXYDmXYk,1978
|
|
40
|
+
kg_doc_parser/workflow_ingest/strategy.py,sha256=8_gOKSOdkPH1IyQmN9kG2s4d5ozzz5G9LNXsdeeFh7Q,10134
|
|
41
|
+
graph_knowledge_doc_parser-0.2.9.dist-info/METADATA,sha256=Z7LfXSXI8M18-ksjecGe_xTq2UAVZ11YUxEIqqlOmEQ,17519
|
|
42
|
+
graph_knowledge_doc_parser-0.2.9.dist-info/WHEEL,sha256=L-WvLdSBvJWHXv5zrQxDvNRnIgoBzLUpcbuiw19KCuQ,88
|
|
43
|
+
graph_knowledge_doc_parser-0.2.9.dist-info/entry_points.txt,sha256=AXIuydpwsOveH3S3HRlyJ8gphiKOznJc1c_f2rNZNV0,74
|
|
44
|
+
graph_knowledge_doc_parser-0.2.9.dist-info/RECORD,,
|
kg_doc_parser/__init__.py
CHANGED
|
@@ -1,9 +1,10 @@
|
|
|
1
|
-
from __future__ import annotations
|
|
2
|
-
|
|
3
1
|
"""Public import surface for the document parser package."""
|
|
4
2
|
|
|
3
|
+
from __future__ import annotations
|
|
4
|
+
|
|
5
5
|
from . import workflow_ingest
|
|
6
6
|
from .workflow_ingest import * # noqa: F401,F403
|
|
7
7
|
from .workflow_ingest import __all__ as _workflow_ingest_all
|
|
8
8
|
|
|
9
|
-
|
|
9
|
+
# The parser package intentionally mirrors the workflow package's public API.
|
|
10
|
+
__all__ = ["workflow_ingest", *_workflow_ingest_all] # pyright: ignore[reportUnsupportedDunderAll]
|
kg_doc_parser/cast_hinting.py
CHANGED
|
@@ -88,25 +88,65 @@ import sqlite3
|
|
|
88
88
|
import threading
|
|
89
89
|
import time
|
|
90
90
|
import traceback
|
|
91
|
+
from collections.abc import Mapping
|
|
91
92
|
from contextlib import closing
|
|
92
93
|
from dataclasses import dataclass
|
|
93
94
|
from datetime import datetime, timezone
|
|
94
|
-
from typing import Any, Dict, Optional, Tuple, Callable
|
|
95
95
|
from threading import Lock
|
|
96
|
+
from typing import Protocol
|
|
97
|
+
from uuid import UUID
|
|
98
|
+
|
|
96
99
|
from langchain_core.callbacks.base import BaseCallbackHandler
|
|
100
|
+
from langchain_core.messages import BaseMessage
|
|
97
101
|
from langchain_core.outputs.chat_generation import ChatGeneration
|
|
98
102
|
from langchain_core.outputs.llm_result import LLMResult
|
|
99
|
-
from langchain_core.messages import BaseMessage
|
|
100
|
-
from uuid import UUID
|
|
101
103
|
|
|
102
104
|
from kg_doc_parser.workflow_ingest.serialization import safe_json_dumps
|
|
103
105
|
|
|
106
|
+
|
|
107
|
+
class TextRedactor(Protocol):
|
|
108
|
+
"""Redact one text value before it is written to ingestion telemetry."""
|
|
109
|
+
|
|
110
|
+
def __call__(self, text: str, /) -> str: ...
|
|
111
|
+
|
|
112
|
+
|
|
113
|
+
def _metadata_float(value: object, default: float = 0.0) -> float:
|
|
114
|
+
if isinstance(value, bool):
|
|
115
|
+
return float(value)
|
|
116
|
+
if isinstance(value, (int, float)):
|
|
117
|
+
return float(value)
|
|
118
|
+
if isinstance(value, str):
|
|
119
|
+
try:
|
|
120
|
+
return float(value)
|
|
121
|
+
except ValueError:
|
|
122
|
+
return default
|
|
123
|
+
return default
|
|
124
|
+
|
|
125
|
+
|
|
126
|
+
def _metadata_int_or_none(value: object) -> int | None:
|
|
127
|
+
if isinstance(value, bool):
|
|
128
|
+
return int(value)
|
|
129
|
+
if isinstance(value, int):
|
|
130
|
+
return value
|
|
131
|
+
if isinstance(value, float) and value.is_integer():
|
|
132
|
+
return int(value)
|
|
133
|
+
if isinstance(value, str):
|
|
134
|
+
try:
|
|
135
|
+
return int(value)
|
|
136
|
+
except ValueError:
|
|
137
|
+
return None
|
|
138
|
+
return None
|
|
139
|
+
|
|
140
|
+
|
|
141
|
+
def _metadata_text(value: object) -> str | None:
|
|
142
|
+
return value if isinstance(value, str) else None
|
|
143
|
+
|
|
104
144
|
# ---------------------------
|
|
105
145
|
# Pricing / cost calculation
|
|
106
146
|
# ---------------------------
|
|
107
147
|
|
|
108
148
|
# per-1K token pricing in USD (example values; keep yours here)
|
|
109
|
-
_COST_TABLE:
|
|
149
|
+
_COST_TABLE: dict[str, dict[str, float]] = {
|
|
110
150
|
"gemini-3-flash-preview": {"input": 0.0005, "output": 0.003, "cache": 0.0},
|
|
111
151
|
"gemini-3.0-pro": {"input": 0.002000, "output": 0.0120, "cache": 0.00031},
|
|
112
152
|
"gemini-2.0-flash": {"input": 0.0001, "output": 0.0004, "cache": 0.0},
|
|
@@ -174,13 +214,13 @@ class _IngestEvent:
|
|
|
174
214
|
Internal event embedding queued from callback thread(s) to writer thread.
|
|
175
215
|
"""
|
|
176
216
|
ts_iso: str
|
|
177
|
-
document_id:
|
|
178
|
-
run_id:
|
|
179
|
-
parent_run_id:
|
|
217
|
+
document_id: str | None
|
|
218
|
+
run_id: str | None
|
|
219
|
+
parent_run_id: str | None
|
|
180
220
|
event_name: str
|
|
181
|
-
model_name:
|
|
182
|
-
filename:
|
|
183
|
-
line_number:
|
|
221
|
+
model_name: str | None
|
|
222
|
+
filename: str | None
|
|
223
|
+
line_number: int | None
|
|
184
224
|
token_count: int
|
|
185
225
|
cost_usd: float
|
|
186
226
|
n_try: float
|
|
@@ -226,7 +266,7 @@ class SQLiteIngestEventWriter:
|
|
|
226
266
|
|
|
227
267
|
os.makedirs(os.path.dirname(db_path) or ".", exist_ok=True)
|
|
228
268
|
|
|
229
|
-
self._q:
|
|
269
|
+
self._q: queue.Queue[_IngestEvent] = queue.Queue()
|
|
230
270
|
self._stop = threading.Event()
|
|
231
271
|
self._thread = threading.Thread(target=self._run, name="sqlite_ingest_writer", daemon=True)
|
|
232
272
|
|
|
@@ -370,7 +410,7 @@ class SQLiteIngestEventWriter:
|
|
|
370
410
|
# Helper: error frame info
|
|
371
411
|
# ---------------------------
|
|
372
412
|
|
|
373
|
-
def _best_effort_error_location(exc: BaseException) ->
|
|
413
|
+
def _best_effort_error_location(exc: BaseException) -> tuple[str | None, int | None]:
|
|
374
414
|
"""
|
|
375
415
|
Extract (filename, line_number) from the deepest traceback frame.
|
|
376
416
|
|
|
@@ -400,8 +440,12 @@ def _utc_now_iso() -> str:
|
|
|
400
440
|
# ---------------------------
|
|
401
441
|
# The LangChain callback
|
|
402
442
|
# ---------------------------
|
|
403
|
-
def
|
|
404
|
-
|
|
443
|
+
def _as_mapping(value: object) -> Mapping[str, object]:
|
|
444
|
+
return value if isinstance(value, Mapping) else {}
|
|
445
|
+
|
|
446
|
+
|
|
447
|
+
def _invoked_model_name(kwargs: Mapping[str, object]) -> str | None:
|
|
448
|
+
inv_params = _as_mapping(kwargs.get("invocation_params"))
|
|
405
449
|
m = inv_params.get("model")
|
|
406
450
|
return str(m) if m else None
|
|
407
451
|
class DocumentIngestSQLiteCallback(BaseCallbackHandler):
|
|
@@ -441,7 +485,7 @@ class DocumentIngestSQLiteCallback(BaseCallbackHandler):
|
|
|
441
485
|
log_errors: bool = True,
|
|
442
486
|
include_traceback: bool = True,
|
|
443
487
|
max_text_chars: int = 40_000,
|
|
444
|
-
redact:
|
|
488
|
+
redact: TextRedactor | None = None,
|
|
445
489
|
) -> None:
|
|
446
490
|
super().__init__()
|
|
447
491
|
self._writer = SQLiteIngestEventWriter(db_path=db_path)
|
|
@@ -453,15 +497,15 @@ class DocumentIngestSQLiteCallback(BaseCallbackHandler):
|
|
|
453
497
|
self.include_traceback = include_traceback
|
|
454
498
|
self.max_text_chars = int(max_text_chars)
|
|
455
499
|
self.redact = redact or (lambda s: s)
|
|
456
|
-
self._run_meta: dict[str, dict[str,
|
|
500
|
+
self._run_meta: dict[str, dict[str, object]] = {}
|
|
457
501
|
self._run_meta_lock = Lock()
|
|
458
|
-
def _remember(self, run_id: UUID, metadata: dict[str,
|
|
502
|
+
def _remember(self, run_id: UUID, metadata: dict[str, object] | None, tags: list[str] | None) -> None:
|
|
459
503
|
md = dict(metadata or {})
|
|
460
504
|
md["_tags"] = list(tags or [])
|
|
461
505
|
with self._run_meta_lock:
|
|
462
506
|
self._run_meta[str(run_id)] = md
|
|
463
507
|
|
|
464
|
-
def _recall(self, run_id: UUID, metadata: dict[str,
|
|
508
|
+
def _recall(self, run_id: UUID, metadata: dict[str, object] | None, tags: list[str] | None) -> dict[str, object]:
|
|
465
509
|
# prefer real-time metadata if present; else fallback to remembered
|
|
466
510
|
if metadata:
|
|
467
511
|
return dict(metadata)
|
|
@@ -485,22 +529,22 @@ class DocumentIngestSQLiteCallback(BaseCallbackHandler):
|
|
|
485
529
|
|
|
486
530
|
def on_chat_model_start(
|
|
487
531
|
self,
|
|
488
|
-
serialized:
|
|
532
|
+
serialized: dict[str, object],
|
|
489
533
|
messages: list[list[BaseMessage]],
|
|
490
534
|
*,
|
|
491
|
-
run_id:
|
|
492
|
-
parent_run_id:
|
|
493
|
-
tags:
|
|
494
|
-
metadata:
|
|
495
|
-
**kwargs:
|
|
535
|
+
run_id: UUID,
|
|
536
|
+
parent_run_id: UUID | None = None,
|
|
537
|
+
tags: list[str] | None = None,
|
|
538
|
+
metadata: dict[str, object] | None = None,
|
|
539
|
+
**kwargs: object,
|
|
496
540
|
) -> None:
|
|
497
541
|
self._remember(run_id, metadata, tags)
|
|
498
542
|
md = metadata or {}
|
|
499
543
|
document_id = md.get("document_id")
|
|
500
544
|
filename = md.get("source_filename")
|
|
501
|
-
n_try =
|
|
545
|
+
n_try = _metadata_float(md.get("n_try", 0))
|
|
502
546
|
|
|
503
|
-
payload:
|
|
547
|
+
payload: dict[str, object] = {
|
|
504
548
|
"serialized": serialized,
|
|
505
549
|
"tags": tags or [],
|
|
506
550
|
"metadata": md,
|
|
@@ -534,7 +578,7 @@ class DocumentIngestSQLiteCallback(BaseCallbackHandler):
|
|
|
534
578
|
event_name="chat_model_start",
|
|
535
579
|
model_name=_invoked_model_name(kwargs) or None,
|
|
536
580
|
filename=str(filename) if filename is not None else None,
|
|
537
|
-
line_number=md.get("line_number"),
|
|
581
|
+
line_number=_metadata_int_or_none(md.get("line_number")),
|
|
538
582
|
token_count=0,
|
|
539
583
|
cost_usd=0.0,
|
|
540
584
|
n_try=n_try,
|
|
@@ -543,14 +587,14 @@ class DocumentIngestSQLiteCallback(BaseCallbackHandler):
|
|
|
543
587
|
)
|
|
544
588
|
def on_llm_start(
|
|
545
589
|
self,
|
|
546
|
-
serialized:
|
|
590
|
+
serialized: dict[str, object],
|
|
547
591
|
prompts: list[str],
|
|
548
592
|
*,
|
|
549
593
|
run_id: UUID,
|
|
550
|
-
parent_run_id:
|
|
551
|
-
tags:
|
|
552
|
-
metadata:
|
|
553
|
-
**kwargs:
|
|
594
|
+
parent_run_id: UUID | None = None,
|
|
595
|
+
tags: list[str] | None = None,
|
|
596
|
+
metadata: dict[str, object] | None = None,
|
|
597
|
+
**kwargs: object,
|
|
554
598
|
) -> None:
|
|
555
599
|
|
|
556
600
|
self._remember(run_id, metadata, tags)
|
|
@@ -566,9 +610,9 @@ class DocumentIngestSQLiteCallback(BaseCallbackHandler):
|
|
|
566
610
|
document_id = md.get("document_id")
|
|
567
611
|
filename = md.get("source_filename")
|
|
568
612
|
if model_name is None:
|
|
569
|
-
|
|
570
|
-
|
|
571
|
-
|
|
613
|
+
inv_params = kwargs.get("invocation_params")
|
|
614
|
+
if isinstance(inv_params, Mapping) and inv_params.get("model"):
|
|
615
|
+
model_name = str(inv_params["model"])
|
|
572
616
|
payload = {
|
|
573
617
|
"serialized": serialized,
|
|
574
618
|
"tags": tags or [],
|
|
@@ -579,7 +623,7 @@ class DocumentIngestSQLiteCallback(BaseCallbackHandler):
|
|
|
579
623
|
if self.log_prompts:
|
|
580
624
|
payload["prompts"] = [self._clip(p) for p in prompts]
|
|
581
625
|
if model_name is None:
|
|
582
|
-
mdn
|
|
626
|
+
mdn = _metadata_text(md.get("model_name"))
|
|
583
627
|
if mdn is not None:
|
|
584
628
|
model_name = mdn
|
|
585
629
|
self._writer.enqueue(
|
|
@@ -591,7 +635,7 @@ class DocumentIngestSQLiteCallback(BaseCallbackHandler):
|
|
|
591
635
|
event_name="llm_start",
|
|
592
636
|
model_name=model_name,
|
|
593
637
|
filename=str(filename) if filename is not None else None,
|
|
594
|
-
line_number=md.get("line_number"),
|
|
638
|
+
line_number=_metadata_int_or_none(md.get("line_number")),
|
|
595
639
|
token_count=0,
|
|
596
640
|
cost_usd=0.0,
|
|
597
641
|
n_try = payload.get('n_try', 0),
|
|
@@ -604,10 +648,10 @@ class DocumentIngestSQLiteCallback(BaseCallbackHandler):
|
|
|
604
648
|
response: LLMResult,
|
|
605
649
|
*,
|
|
606
650
|
run_id: UUID,
|
|
607
|
-
parent_run_id:
|
|
608
|
-
tags:
|
|
609
|
-
metadata:
|
|
610
|
-
**kwargs:
|
|
651
|
+
parent_run_id: UUID | None = None,
|
|
652
|
+
tags: list[str] | None = None,
|
|
653
|
+
metadata: dict[str, object] | None = None,
|
|
654
|
+
**kwargs: object,
|
|
611
655
|
) -> None:
|
|
612
656
|
"""
|
|
613
657
|
Called after the LLM returns.
|
|
@@ -623,7 +667,7 @@ class DocumentIngestSQLiteCallback(BaseCallbackHandler):
|
|
|
623
667
|
|
|
624
668
|
# Defaults if we can't find usage
|
|
625
669
|
input_tokens = output_tokens = cached_tokens = reasoning_tokens = 0
|
|
626
|
-
model_name:
|
|
670
|
+
model_name: str | None = None
|
|
627
671
|
|
|
628
672
|
# LangChain response.generations: List[List[Generation]]
|
|
629
673
|
for gen_list in response.generations:
|
|
@@ -648,9 +692,9 @@ class DocumentIngestSQLiteCallback(BaseCallbackHandler):
|
|
|
648
692
|
gi = getattr(gen, "generation_info", None) or {}
|
|
649
693
|
model_name = gi.get("model_name") or model_name
|
|
650
694
|
if model_name is None:
|
|
651
|
-
|
|
652
|
-
|
|
653
|
-
|
|
695
|
+
inv_params = kwargs.get("invocation_params")
|
|
696
|
+
if isinstance(inv_params, Mapping) and inv_params.get("model"):
|
|
697
|
+
model_name = str(inv_params["model"])
|
|
654
698
|
token_count = int(input_tokens + output_tokens)
|
|
655
699
|
cost_usd = 0.0
|
|
656
700
|
if model_name and (input_tokens or output_tokens or cached_tokens):
|
|
@@ -670,10 +714,10 @@ class DocumentIngestSQLiteCallback(BaseCallbackHandler):
|
|
|
670
714
|
"response_llm_output": getattr(response, "llm_output", None),
|
|
671
715
|
}
|
|
672
716
|
if self.log_responses:
|
|
673
|
-
outs: list[dict[str,
|
|
717
|
+
outs: list[dict[str, object]] = []
|
|
674
718
|
for gen_list in response.generations:
|
|
675
719
|
for gen in gen_list:
|
|
676
|
-
item: dict[str,
|
|
720
|
+
item: dict[str, object] = {"type": type(gen).__name__}
|
|
677
721
|
|
|
678
722
|
# Text-y
|
|
679
723
|
if hasattr(gen, "text") and gen.text:
|
|
@@ -695,7 +739,7 @@ class DocumentIngestSQLiteCallback(BaseCallbackHandler):
|
|
|
695
739
|
payload["outputs"] = outs
|
|
696
740
|
|
|
697
741
|
if model_name is None:
|
|
698
|
-
mdn
|
|
742
|
+
mdn = _metadata_text(md.get("model_name"))
|
|
699
743
|
if mdn is not None:
|
|
700
744
|
model_name = mdn
|
|
701
745
|
self._writer.enqueue(
|
|
@@ -707,7 +751,7 @@ class DocumentIngestSQLiteCallback(BaseCallbackHandler):
|
|
|
707
751
|
event_name="llm_end",
|
|
708
752
|
model_name=str(model_name) if model_name is not None else None,
|
|
709
753
|
filename=str(filename) if filename is not None else None,
|
|
710
|
-
line_number=md.get("line_number"),
|
|
754
|
+
line_number=_metadata_int_or_none(md.get("line_number")),
|
|
711
755
|
token_count=token_count,
|
|
712
756
|
cost_usd=float(cost_usd),
|
|
713
757
|
n_try=float(payload.get('n_try', 0)),
|
|
@@ -720,10 +764,10 @@ class DocumentIngestSQLiteCallback(BaseCallbackHandler):
|
|
|
720
764
|
error: BaseException,
|
|
721
765
|
*,
|
|
722
766
|
run_id: UUID,
|
|
723
|
-
parent_run_id:
|
|
724
|
-
tags:
|
|
725
|
-
metadata:
|
|
726
|
-
**kwargs:
|
|
767
|
+
parent_run_id: UUID | None = None,
|
|
768
|
+
tags: list[str] | None = None,
|
|
769
|
+
metadata: dict[str, object] | None = None,
|
|
770
|
+
**kwargs: object,
|
|
727
771
|
) -> None:
|
|
728
772
|
"""
|
|
729
773
|
Called when the LLM call errors.
|
|
@@ -758,11 +802,11 @@ class DocumentIngestSQLiteCallback(BaseCallbackHandler):
|
|
|
758
802
|
else:
|
|
759
803
|
payload["error_type"] = type(error).__name__
|
|
760
804
|
if model_name is None:
|
|
761
|
-
|
|
762
|
-
|
|
763
|
-
|
|
805
|
+
inv_params = kwargs.get("invocation_params")
|
|
806
|
+
if isinstance(inv_params, Mapping) and inv_params.get("model"):
|
|
807
|
+
model_name = str(inv_params["model"])
|
|
764
808
|
if model_name is None:
|
|
765
|
-
mdn
|
|
809
|
+
mdn = _metadata_text(md.get("model_name"))
|
|
766
810
|
if mdn is not None:
|
|
767
811
|
model_name = mdn
|
|
768
812
|
self._writer.enqueue(
|
|
@@ -1,35 +1,56 @@
|
|
|
1
1
|
from __future__ import annotations
|
|
2
2
|
|
|
3
|
-
from typing import Protocol
|
|
3
|
+
from typing import TYPE_CHECKING, Literal, Protocol, Self, TypeAlias, TypedDict, cast
|
|
4
4
|
|
|
5
|
+
from kogwistar.llm_tasks.providers import (
|
|
6
|
+
SupportsStructuredOutput,
|
|
7
|
+
)
|
|
5
8
|
|
|
6
|
-
|
|
7
|
-
|
|
9
|
+
if TYPE_CHECKING:
|
|
10
|
+
from kogwistar.llm_tasks.providers import StructuredModelLike
|
|
11
|
+
else:
|
|
12
|
+
class StructuredModelLike(Protocol):
|
|
13
|
+
"""Compatibility fallback for released Core versions."""
|
|
8
14
|
|
|
9
|
-
|
|
15
|
+
@classmethod
|
|
16
|
+
def model_validate(cls, payload: object, /) -> Self: ...
|
|
17
|
+
|
|
18
|
+
@classmethod
|
|
19
|
+
def model_json_schema(cls) -> dict[str, object]: ...
|
|
20
|
+
|
|
21
|
+
# Keep the historical parser names as aliases, but use the core contracts as
|
|
22
|
+
# the single source of truth for provider/schema compatibility.
|
|
23
|
+
StructuredSchema: TypeAlias = StructuredModelLike
|
|
24
|
+
StructuredOutputModel: TypeAlias = SupportsStructuredOutput
|
|
10
25
|
|
|
11
|
-
def invoke(self, *args: object, **kwargs: object) -> object: ...
|
|
12
26
|
|
|
27
|
+
class _StructuredOutputOptions(TypedDict, total=False):
|
|
28
|
+
include_raw: bool
|
|
29
|
+
method: Literal["function_calling", "json_mode", "json_schema"]
|
|
13
30
|
|
|
14
|
-
class StructuredOutputModel(Protocol):
|
|
15
|
-
"""Minimum model surface required by the parser's structured-output path."""
|
|
16
31
|
|
|
17
|
-
|
|
32
|
+
class StructuredOutputRunnable(Protocol):
|
|
33
|
+
"""Runnable returned by a structured-output model adapter."""
|
|
34
|
+
|
|
35
|
+
steps: list[object]
|
|
36
|
+
|
|
37
|
+
def invoke(
|
|
18
38
|
self,
|
|
19
|
-
|
|
39
|
+
messages: object,
|
|
40
|
+
config: object | None = None,
|
|
20
41
|
**kwargs: object,
|
|
21
|
-
) ->
|
|
42
|
+
) -> dict[str, object]: ...
|
|
22
43
|
|
|
23
44
|
|
|
24
45
|
def build_structured_output_runnable(
|
|
25
46
|
model: StructuredOutputModel,
|
|
26
|
-
schema:
|
|
47
|
+
schema: type[StructuredSchema],
|
|
27
48
|
*,
|
|
28
49
|
include_raw: bool = True,
|
|
29
50
|
prefer_json_schema: bool = True,
|
|
30
51
|
) -> StructuredOutputRunnable:
|
|
31
52
|
"""Build a structured-output runnable with strict-schema-first fallback."""
|
|
32
|
-
attempts: list[
|
|
53
|
+
attempts: list[_StructuredOutputOptions] = []
|
|
33
54
|
if prefer_json_schema:
|
|
34
55
|
attempts.append({"include_raw": include_raw, "method": "json_schema"})
|
|
35
56
|
attempts.append({"include_raw": include_raw, "method": "function_calling"})
|
|
@@ -38,7 +59,13 @@ def build_structured_output_runnable(
|
|
|
38
59
|
last_error: Exception | None = None
|
|
39
60
|
for kwargs in attempts:
|
|
40
61
|
try:
|
|
41
|
-
|
|
62
|
+
# LangChain returns a runnable with ``steps``; the dependency-light
|
|
63
|
+
# core protocol intentionally does not require that implementation
|
|
64
|
+
# detail. Keep the cast at this parser-only compatibility boundary.
|
|
65
|
+
return cast(
|
|
66
|
+
StructuredOutputRunnable,
|
|
67
|
+
model.with_structured_output(schema, **kwargs),
|
|
68
|
+
)
|
|
42
69
|
except (TypeError, ValueError) as exc:
|
|
43
70
|
last_error = exc
|
|
44
71
|
if last_error is not None:
|