-
Notifications
You must be signed in to change notification settings - Fork 35
Expand file tree
/
Copy pathmain.py
More file actions
201 lines (161 loc) · 5.44 KB
/
Copy pathmain.py
File metadata and controls
201 lines (161 loc) · 5.44 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
"""Command line interface for the Lance-backed knowledge graph."""
from __future__ import annotations
import logging
import sys
from typing import TYPE_CHECKING, Optional, Sequence
from . import extraction as kg_extraction
from .cli.ingest import extract_and_add, preview_extraction
from .cli.interactive import _execute_query, list_datasets, run_interactive
from .cli.parser import build_parser
from .cli.runtime import configure_logging as cli_configure_logging
from .cli.runtime import load_config as cli_load_config
from .cli.runtime import load_service as cli_load_service
from .store import LanceGraphStore
if TYPE_CHECKING:
import argparse
from .config import KnowledgeGraphConfig
from .service import LanceKnowledgeGraph
LOGGER = logging.getLogger(__name__)
def init_graph(config: "KnowledgeGraphConfig") -> None:
"""Initialize the on-disk storage and scaffold the schema file."""
config.ensure_directories()
LanceGraphStore(config).ensure_layout()
schema_path = config.resolved_schema_path()
schema_stub = """# Lance knowledge graph schema
#
# Define node labels and relationship mappings. Example:
# nodes:
# Person:
# id_field: person_id
# relationships:
# WORKS_FOR:
# source: person_id
# target: company_id
# entity_types:
# - PERSON
# - ORGANIZATION
# relationship_types:
# - WORKS_FOR
# - PART_OF
nodes: {}
relationships: {}
entity_types: []
relationship_types: []
"""
if isinstance(schema_path, str):
import pyarrow.fs
try:
fs, path = pyarrow.fs.FileSystem.from_uri(schema_path)
info = fs.get_file_info(path)
if info.type != pyarrow.fs.FileType.NotFound:
print(f"Schema already present at {schema_path}")
return
with fs.open_output_stream(path) as f:
f.write(schema_stub.encode("utf-8"))
print(f"Created schema template at {schema_path}")
return
except Exception as e:
print(f"Failed to initialize schema at {schema_path}: {e}", file=sys.stderr)
return
if schema_path.exists():
print(f"Schema already present at {schema_path}")
return
schema_path.write_text(schema_stub, encoding="utf-8")
print(f"Created schema template at {schema_path}")
def ask_question(
question: str,
service: "LanceKnowledgeGraph",
args: "argparse.Namespace",
) -> None:
"""Answer a natural-language question using the graph via LLM-assisted Cypher."""
from .llm.qa import ask_question as qa_ask
answer = qa_ask(
question,
service,
llm_model=args.llm_model,
llm_temperature=args.llm_temperature,
llm_config_path=args.llm_config,
embedding_model=getattr(args, "embedding_model", None),
)
print(answer)
def _load_config(args: "argparse.Namespace") -> "KnowledgeGraphConfig":
return cli_load_config(args)
def _load_service(config: "KnowledgeGraphConfig"):
return cli_load_service(config)
def _resolve_extractor(args: "argparse.Namespace") -> kg_extraction.BaseExtractor:
from .llm.llm_utils import load_llm_options
options = load_llm_options(args.llm_config)
return kg_extraction.get_extractor(
args.extractor,
llm_model=args.llm_model,
llm_temperature=args.llm_temperature,
llm_options=options,
)
def _resolve_embedding_generator(
args: "argparse.Namespace",
*,
options: Optional[dict] = None,
):
from .llm.llm_utils import resolve_embedding_generator
model = getattr(args, "embedding_model", None)
return resolve_embedding_generator(model_name=model, options=options)
def _configure_logging(level: str) -> None:
cli_configure_logging(level)
def _build_parser() -> "argparse.ArgumentParser":
return build_parser()
def main(argv: Optional[Sequence[str]] = None) -> int:
parser = _build_parser()
args = parser.parse_args(argv)
config = _load_config(args)
_configure_logging(args.log_level)
exclusive_args = any(
[
args.init,
args.extract_preview is not None,
args.extract_and_add is not None,
args.ask is not None,
args.list_datasets,
]
)
if args.query and exclusive_args:
parser.error(
"Query argument cannot be combined with --init/--ask/--extract-* flags."
)
if args.init:
init_graph(config)
return 0
if args.list_datasets:
list_datasets(config)
return 0
if args.extract_preview:
extractor = _resolve_extractor(args)
preview_extraction(args.extract_preview, extractor)
return 0
try:
service = _load_service(config)
except FileNotFoundError as exc:
message = (
f"{exc}. Run `knowledge_graph --init` or provide a schema with --schema."
)
print(message, file=sys.stderr)
return 1
if args.extract_and_add:
extractor = _resolve_extractor(args)
embedding_generator = _resolve_embedding_generator(args)
extract_and_add(
args.extract_and_add,
service,
extractor,
embedding_generator=embedding_generator,
)
return 0
if args.ask:
ask_question(args.ask, service, args)
return 0
if args.query:
_execute_query(service, args.query)
return 0
run_interactive(service)
return 0
if __name__ == "__main__":
raise SystemExit(main())