kgeval 0.1.0__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.
- kgeval/__init__.py +153 -0
- kgeval/_yaml.py +34 -0
- kgeval/cli.py +481 -0
- kgeval/errors.py +27 -0
- kgeval/evaluation.py +72 -0
- kgeval/graph/__init__.py +44 -0
- kgeval/graph/layout.py +195 -0
- kgeval/graph/model.py +268 -0
- kgeval/graph/names.py +93 -0
- kgeval/graph/view.py +258 -0
- kgeval/ground_truth.py +87 -0
- kgeval/judges/__init__.py +15 -0
- kgeval/judges/base.py +42 -0
- kgeval/judges/cache.py +76 -0
- kgeval/judges/openai.py +137 -0
- kgeval/judges/providers.py +157 -0
- kgeval/metrics/__init__.py +102 -0
- kgeval/metrics/_vocabulary.py +92 -0
- kgeval/metrics/base.py +268 -0
- kgeval/metrics/catalog.py +177 -0
- kgeval/metrics/intrinsic/__init__.py +24 -0
- kgeval/metrics/intrinsic/entities.py +163 -0
- kgeval/metrics/intrinsic/facts.py +54 -0
- kgeval/metrics/intrinsic/properties.py +150 -0
- kgeval/metrics/intrinsic/provenance.py +122 -0
- kgeval/metrics/intrinsic/vocabulary.py +59 -0
- kgeval/metrics/judged/__init__.py +39 -0
- kgeval/metrics/judged/_prompts.py +104 -0
- kgeval/metrics/judged/base.py +223 -0
- kgeval/metrics/judged/entities.py +421 -0
- kgeval/metrics/judged/extraction.py +149 -0
- kgeval/metrics/judged/facts.py +112 -0
- kgeval/metrics/judged/vocabulary.py +353 -0
- kgeval/metrics/reference/__init__.py +23 -0
- kgeval/metrics/reference/competency.py +59 -0
- kgeval/metrics/reference/ground_truth.py +248 -0
- kgeval/metrics/retrieval/__init__.py +6 -0
- kgeval/metrics/retrieval/base.py +96 -0
- kgeval/metrics/retrieval/context.py +138 -0
- kgeval/metrics/schema/__init__.py +13 -0
- kgeval/metrics/schema/base.py +33 -0
- kgeval/metrics/schema/completeness.py +137 -0
- kgeval/metrics/schema/conformance.py +276 -0
- kgeval/py.typed +0 -0
- kgeval/questions.py +193 -0
- kgeval/reference.py +156 -0
- kgeval/report/__init__.py +14 -0
- kgeval/report/comparison.py +270 -0
- kgeval/report/markdown.py +301 -0
- kgeval/report/model.py +166 -0
- kgeval/retrieval.py +97 -0
- kgeval/schema/__init__.py +23 -0
- kgeval/schema/inference.py +121 -0
- kgeval/schema/model.py +259 -0
- kgeval/sources/__init__.py +5 -0
- kgeval/sources/neo4j.py +175 -0
- kgeval-0.1.0.dist-info/METADATA +100 -0
- kgeval-0.1.0.dist-info/RECORD +61 -0
- kgeval-0.1.0.dist-info/WHEEL +4 -0
- kgeval-0.1.0.dist-info/entry_points.txt +3 -0
- kgeval-0.1.0.dist-info/licenses/LICENSE +202 -0
kgeval/__init__.py
ADDED
|
@@ -0,0 +1,153 @@
|
|
|
1
|
+
"""Evaluate knowledge graphs."""
|
|
2
|
+
|
|
3
|
+
from importlib.metadata import version
|
|
4
|
+
|
|
5
|
+
from kgeval.errors import InputError, JudgeError, KgevalError, SourceError, VerdictError
|
|
6
|
+
from kgeval.evaluation import evaluate
|
|
7
|
+
from kgeval.graph import (
|
|
8
|
+
Duration,
|
|
9
|
+
Graph,
|
|
10
|
+
GraphView,
|
|
11
|
+
Layout,
|
|
12
|
+
Node,
|
|
13
|
+
Point,
|
|
14
|
+
PropertyValue,
|
|
15
|
+
Relationship,
|
|
16
|
+
Role,
|
|
17
|
+
value_type,
|
|
18
|
+
)
|
|
19
|
+
from kgeval.ground_truth import GroundTruth, load_ground_truth
|
|
20
|
+
from kgeval.judges import CachedJudge, Judge, OpenAIJudge, create_judge
|
|
21
|
+
from kgeval.metrics import (
|
|
22
|
+
BUILTIN_METRICS,
|
|
23
|
+
Competency,
|
|
24
|
+
EmbeddingConsistency,
|
|
25
|
+
EntityConformance,
|
|
26
|
+
EntityConnectivity,
|
|
27
|
+
EntityDisambiguation,
|
|
28
|
+
EntityF1,
|
|
29
|
+
EntityNaming,
|
|
30
|
+
EntityPrecision,
|
|
31
|
+
EntityProvenance,
|
|
32
|
+
EntityRecall,
|
|
33
|
+
EntityResolution,
|
|
34
|
+
EntityUniqueness,
|
|
35
|
+
ExtractionCompleteness,
|
|
36
|
+
ExtractionCoverage,
|
|
37
|
+
FactAccuracy,
|
|
38
|
+
FactConformance,
|
|
39
|
+
FactF1,
|
|
40
|
+
FactPrecision,
|
|
41
|
+
FactProvenance,
|
|
42
|
+
FactRecall,
|
|
43
|
+
FactUniqueness,
|
|
44
|
+
Finding,
|
|
45
|
+
GroundTruthMetric,
|
|
46
|
+
JudgedMetric,
|
|
47
|
+
Metric,
|
|
48
|
+
MetricCategory,
|
|
49
|
+
MetricResult,
|
|
50
|
+
NodeTypeAccuracy,
|
|
51
|
+
PropertyCompleteness,
|
|
52
|
+
PropertyTypeConsistency,
|
|
53
|
+
RetrievalMetric,
|
|
54
|
+
RetrievalPrecision,
|
|
55
|
+
RetrievalRecall,
|
|
56
|
+
SampledMetric,
|
|
57
|
+
SchemaCompleteness,
|
|
58
|
+
SchemaMetric,
|
|
59
|
+
VocabularyResolution,
|
|
60
|
+
VocabularyUniqueness,
|
|
61
|
+
default_metrics,
|
|
62
|
+
)
|
|
63
|
+
from kgeval.questions import Question, QuestionSet, load_questions
|
|
64
|
+
from kgeval.report import Comparison, GraphSummary, MetricChange, Report, Trend, compare
|
|
65
|
+
from kgeval.retrieval import Retrievals, Retriever, load_retrievals, retrieve
|
|
66
|
+
from kgeval.schema import GraphSchema, infer_schema, load_schema
|
|
67
|
+
from kgeval.sources import Neo4jSource
|
|
68
|
+
|
|
69
|
+
__version__ = version(__name__)
|
|
70
|
+
"""The installed kgeval version."""
|
|
71
|
+
|
|
72
|
+
__all__ = [
|
|
73
|
+
"BUILTIN_METRICS",
|
|
74
|
+
"CachedJudge",
|
|
75
|
+
"Comparison",
|
|
76
|
+
"Competency",
|
|
77
|
+
"Duration",
|
|
78
|
+
"EmbeddingConsistency",
|
|
79
|
+
"EntityConformance",
|
|
80
|
+
"EntityConnectivity",
|
|
81
|
+
"EntityDisambiguation",
|
|
82
|
+
"EntityF1",
|
|
83
|
+
"EntityNaming",
|
|
84
|
+
"EntityPrecision",
|
|
85
|
+
"EntityProvenance",
|
|
86
|
+
"EntityRecall",
|
|
87
|
+
"EntityResolution",
|
|
88
|
+
"EntityUniqueness",
|
|
89
|
+
"ExtractionCompleteness",
|
|
90
|
+
"ExtractionCoverage",
|
|
91
|
+
"FactAccuracy",
|
|
92
|
+
"FactConformance",
|
|
93
|
+
"FactF1",
|
|
94
|
+
"FactPrecision",
|
|
95
|
+
"FactProvenance",
|
|
96
|
+
"FactRecall",
|
|
97
|
+
"FactUniqueness",
|
|
98
|
+
"Finding",
|
|
99
|
+
"Graph",
|
|
100
|
+
"GraphSchema",
|
|
101
|
+
"GraphSummary",
|
|
102
|
+
"GraphView",
|
|
103
|
+
"GroundTruth",
|
|
104
|
+
"GroundTruthMetric",
|
|
105
|
+
"InputError",
|
|
106
|
+
"Judge",
|
|
107
|
+
"JudgeError",
|
|
108
|
+
"JudgedMetric",
|
|
109
|
+
"KgevalError",
|
|
110
|
+
"Layout",
|
|
111
|
+
"Metric",
|
|
112
|
+
"MetricCategory",
|
|
113
|
+
"MetricChange",
|
|
114
|
+
"MetricResult",
|
|
115
|
+
"Neo4jSource",
|
|
116
|
+
"Node",
|
|
117
|
+
"NodeTypeAccuracy",
|
|
118
|
+
"OpenAIJudge",
|
|
119
|
+
"Point",
|
|
120
|
+
"PropertyCompleteness",
|
|
121
|
+
"PropertyTypeConsistency",
|
|
122
|
+
"PropertyValue",
|
|
123
|
+
"Question",
|
|
124
|
+
"QuestionSet",
|
|
125
|
+
"Relationship",
|
|
126
|
+
"Report",
|
|
127
|
+
"RetrievalMetric",
|
|
128
|
+
"RetrievalPrecision",
|
|
129
|
+
"RetrievalRecall",
|
|
130
|
+
"Retrievals",
|
|
131
|
+
"Retriever",
|
|
132
|
+
"Role",
|
|
133
|
+
"SampledMetric",
|
|
134
|
+
"SchemaCompleteness",
|
|
135
|
+
"SchemaMetric",
|
|
136
|
+
"SourceError",
|
|
137
|
+
"Trend",
|
|
138
|
+
"VerdictError",
|
|
139
|
+
"VocabularyResolution",
|
|
140
|
+
"VocabularyUniqueness",
|
|
141
|
+
"__version__",
|
|
142
|
+
"compare",
|
|
143
|
+
"create_judge",
|
|
144
|
+
"default_metrics",
|
|
145
|
+
"evaluate",
|
|
146
|
+
"infer_schema",
|
|
147
|
+
"load_ground_truth",
|
|
148
|
+
"load_questions",
|
|
149
|
+
"load_retrievals",
|
|
150
|
+
"load_schema",
|
|
151
|
+
"retrieve",
|
|
152
|
+
"value_type",
|
|
153
|
+
]
|
kgeval/_yaml.py
ADDED
|
@@ -0,0 +1,34 @@
|
|
|
1
|
+
"""Load YAML and JSON files into validated models."""
|
|
2
|
+
|
|
3
|
+
from __future__ import annotations
|
|
4
|
+
|
|
5
|
+
from pathlib import Path
|
|
6
|
+
from typing import TypeVar
|
|
7
|
+
|
|
8
|
+
import yaml
|
|
9
|
+
from pydantic import TypeAdapter, ValidationError
|
|
10
|
+
|
|
11
|
+
from kgeval.errors import InputError
|
|
12
|
+
|
|
13
|
+
__all__ = ["load_yaml"]
|
|
14
|
+
|
|
15
|
+
_T = TypeVar("_T")
|
|
16
|
+
|
|
17
|
+
|
|
18
|
+
def load_yaml(path: str | Path, adapter: TypeAdapter[_T]) -> _T:
|
|
19
|
+
"""Read a YAML file, which may also be JSON, and validate its content.
|
|
20
|
+
|
|
21
|
+
Args:
|
|
22
|
+
path: The file to read.
|
|
23
|
+
adapter: Validates the parsed content.
|
|
24
|
+
|
|
25
|
+
Returns:
|
|
26
|
+
The validated content.
|
|
27
|
+
|
|
28
|
+
Raises:
|
|
29
|
+
InputError: If the file cannot be read, parsed or validated.
|
|
30
|
+
"""
|
|
31
|
+
try:
|
|
32
|
+
return adapter.validate_python(yaml.safe_load(Path(path).read_text(encoding="utf-8")))
|
|
33
|
+
except (OSError, yaml.YAMLError, ValidationError) as error:
|
|
34
|
+
raise InputError(f"invalid file {path}: {error}") from error
|
kgeval/cli.py
ADDED
|
@@ -0,0 +1,481 @@
|
|
|
1
|
+
"""Provide the ``kgeval`` command-line interface."""
|
|
2
|
+
|
|
3
|
+
from __future__ import annotations
|
|
4
|
+
|
|
5
|
+
import inspect
|
|
6
|
+
import logging
|
|
7
|
+
import sys
|
|
8
|
+
from collections.abc import Iterator
|
|
9
|
+
from contextlib import contextmanager
|
|
10
|
+
from enum import StrEnum
|
|
11
|
+
from importlib.metadata import version
|
|
12
|
+
from pathlib import Path
|
|
13
|
+
from typing import Annotated, NoReturn
|
|
14
|
+
|
|
15
|
+
import typer
|
|
16
|
+
from neo4j import Driver, GraphDatabase
|
|
17
|
+
from neo4j.exceptions import DriverError
|
|
18
|
+
from pydantic import TypeAdapter, ValidationError
|
|
19
|
+
from rich.console import Console
|
|
20
|
+
from rich.markdown import Markdown
|
|
21
|
+
|
|
22
|
+
from kgeval._yaml import load_yaml
|
|
23
|
+
from kgeval.errors import InputError, KgevalError, SourceError
|
|
24
|
+
from kgeval.evaluation import evaluate
|
|
25
|
+
from kgeval.graph import GraphView, Layout
|
|
26
|
+
from kgeval.ground_truth import load_ground_truth
|
|
27
|
+
from kgeval.judges import PROVIDERS, CachedJudge, Judge, create_judge
|
|
28
|
+
from kgeval.metrics import (
|
|
29
|
+
BUILTIN_METRICS,
|
|
30
|
+
GROUND_TRUTH_METRICS,
|
|
31
|
+
JUDGED_METRICS,
|
|
32
|
+
RETRIEVAL_METRICS,
|
|
33
|
+
SCHEMA_METRICS,
|
|
34
|
+
Competency,
|
|
35
|
+
Metric,
|
|
36
|
+
MetricCategory,
|
|
37
|
+
default_metrics,
|
|
38
|
+
)
|
|
39
|
+
from kgeval.questions import load_questions
|
|
40
|
+
from kgeval.report import Report, compare
|
|
41
|
+
from kgeval.retrieval import load_retrievals
|
|
42
|
+
from kgeval.schema import infer_schema, load_schema
|
|
43
|
+
from kgeval.sources import Neo4jSource
|
|
44
|
+
|
|
45
|
+
__all__ = ["app"]
|
|
46
|
+
|
|
47
|
+
app = typer.Typer(
|
|
48
|
+
help="Evaluate knowledge graphs.",
|
|
49
|
+
no_args_is_help=True,
|
|
50
|
+
add_completion=False,
|
|
51
|
+
)
|
|
52
|
+
|
|
53
|
+
|
|
54
|
+
def _print_version(show: bool) -> None:
|
|
55
|
+
if show:
|
|
56
|
+
typer.echo(f"kgeval {version('kgeval')}")
|
|
57
|
+
raise typer.Exit
|
|
58
|
+
|
|
59
|
+
|
|
60
|
+
@app.callback()
|
|
61
|
+
def _main(
|
|
62
|
+
show_version: Annotated[
|
|
63
|
+
bool,
|
|
64
|
+
typer.Option(
|
|
65
|
+
"--version",
|
|
66
|
+
help="Print the installed kgeval version and exit.",
|
|
67
|
+
is_eager=True,
|
|
68
|
+
callback=_print_version,
|
|
69
|
+
),
|
|
70
|
+
] = False,
|
|
71
|
+
) -> None:
|
|
72
|
+
pass
|
|
73
|
+
|
|
74
|
+
|
|
75
|
+
_ENABLED_BY = {
|
|
76
|
+
**{metric_type.name: "--schema" for metric_type in SCHEMA_METRICS},
|
|
77
|
+
**{metric_type.name: "--ground" for metric_type in GROUND_TRUTH_METRICS},
|
|
78
|
+
Competency.name: "--questions",
|
|
79
|
+
**{metric_type.name: "--judge" for metric_type in JUDGED_METRICS},
|
|
80
|
+
**{metric_type.name: "--questions and --retrievals" for metric_type in RETRIEVAL_METRICS},
|
|
81
|
+
}
|
|
82
|
+
|
|
83
|
+
|
|
84
|
+
class OutputFormat(StrEnum):
|
|
85
|
+
"""Name the formats a report can be written in."""
|
|
86
|
+
|
|
87
|
+
MARKDOWN = "markdown"
|
|
88
|
+
JSON = "json"
|
|
89
|
+
|
|
90
|
+
|
|
91
|
+
Uri = Annotated[
|
|
92
|
+
str | None,
|
|
93
|
+
typer.Option(
|
|
94
|
+
envvar="NEO4J_URI",
|
|
95
|
+
help="Neo4j connection URI (default neo4j://localhost:7687); prompted for in a terminal.",
|
|
96
|
+
),
|
|
97
|
+
]
|
|
98
|
+
Username = Annotated[
|
|
99
|
+
str | None,
|
|
100
|
+
typer.Option(
|
|
101
|
+
envvar="NEO4J_USERNAME", help="Neo4j user (default neo4j); prompted for in a terminal."
|
|
102
|
+
),
|
|
103
|
+
]
|
|
104
|
+
Password = Annotated[
|
|
105
|
+
str | None,
|
|
106
|
+
typer.Option(
|
|
107
|
+
envvar="NEO4J_PASSWORD",
|
|
108
|
+
help="Neo4j password; prompted for in a terminal; connects without auth if empty.",
|
|
109
|
+
),
|
|
110
|
+
]
|
|
111
|
+
Database = Annotated[
|
|
112
|
+
str | None,
|
|
113
|
+
typer.Option(envvar="NEO4J_DATABASE", help="Database to read; the server default if unset."),
|
|
114
|
+
]
|
|
115
|
+
LayoutFile = Annotated[
|
|
116
|
+
Path | None,
|
|
117
|
+
typer.Option(
|
|
118
|
+
"--layout",
|
|
119
|
+
help="YAML file of layout fields that replace the detected ones.",
|
|
120
|
+
exists=True,
|
|
121
|
+
dir_okay=False,
|
|
122
|
+
),
|
|
123
|
+
]
|
|
124
|
+
Output = Annotated[
|
|
125
|
+
Path | None, typer.Option("--output", "-o", help="Write to this file, not standard output.")
|
|
126
|
+
]
|
|
127
|
+
MaxFindings = Annotated[int, typer.Option(min=0, help="Findings listed per metric in Markdown.")]
|
|
128
|
+
ReportFile = Annotated[
|
|
129
|
+
Path,
|
|
130
|
+
typer.Argument(
|
|
131
|
+
help="A report that `kgeval run --format json` wrote.", exists=True, dir_okay=False
|
|
132
|
+
),
|
|
133
|
+
]
|
|
134
|
+
Verbose = Annotated[bool, typer.Option("--verbose", "-v", help="Log progress to standard error.")]
|
|
135
|
+
|
|
136
|
+
|
|
137
|
+
@app.command()
|
|
138
|
+
def run(
|
|
139
|
+
uri: Uri = None,
|
|
140
|
+
username: Username = None,
|
|
141
|
+
password: Password = None,
|
|
142
|
+
database: Database = None,
|
|
143
|
+
schema: Annotated[
|
|
144
|
+
Path | None,
|
|
145
|
+
typer.Option(
|
|
146
|
+
help="Graph schema in neo4j-graphrag format (YAML or JSON); adds the schema metrics.",
|
|
147
|
+
exists=True,
|
|
148
|
+
dir_okay=False,
|
|
149
|
+
),
|
|
150
|
+
] = None,
|
|
151
|
+
ground_truth: Annotated[
|
|
152
|
+
Path | None,
|
|
153
|
+
typer.Option(
|
|
154
|
+
"--ground",
|
|
155
|
+
help="Ground truth facts (YAML or JSON); adds precision, recall, and F1.",
|
|
156
|
+
exists=True,
|
|
157
|
+
dir_okay=False,
|
|
158
|
+
),
|
|
159
|
+
] = None,
|
|
160
|
+
questions: Annotated[
|
|
161
|
+
Path | None,
|
|
162
|
+
typer.Option(
|
|
163
|
+
help="Test questions with their supporting facts (YAML or JSON); adds competency.",
|
|
164
|
+
exists=True,
|
|
165
|
+
dir_okay=False,
|
|
166
|
+
),
|
|
167
|
+
] = None,
|
|
168
|
+
retrievals: Annotated[
|
|
169
|
+
Path | None,
|
|
170
|
+
typer.Option(
|
|
171
|
+
help="Element IDs a retriever returned per question (YAML or JSON); "
|
|
172
|
+
"adds the retrieval metrics. Needs --questions.",
|
|
173
|
+
exists=True,
|
|
174
|
+
dir_okay=False,
|
|
175
|
+
),
|
|
176
|
+
] = None,
|
|
177
|
+
judge_model: Annotated[
|
|
178
|
+
str | None,
|
|
179
|
+
typer.Option(
|
|
180
|
+
"--judge",
|
|
181
|
+
help="Model to judge with: an OpenAI model, or PROVIDER:MODEL for "
|
|
182
|
+
f"{', '.join(provider for provider in PROVIDERS if provider != 'openai')}; "
|
|
183
|
+
"adds the judged metrics. Needs the provider's API key.",
|
|
184
|
+
),
|
|
185
|
+
] = None,
|
|
186
|
+
judge_base_url: Annotated[
|
|
187
|
+
str | None,
|
|
188
|
+
typer.Option(help="Base URL that replaces the provider's, such as another server's."),
|
|
189
|
+
] = None,
|
|
190
|
+
judge_cache: Annotated[
|
|
191
|
+
Path | None,
|
|
192
|
+
typer.Option(
|
|
193
|
+
help="SQLite file that stores verdicts, so reruns reuse them.", dir_okay=False
|
|
194
|
+
),
|
|
195
|
+
] = None,
|
|
196
|
+
sample_size: Annotated[
|
|
197
|
+
int, typer.Option(min=1, help="Most units each sampled judged metric judges.")
|
|
198
|
+
] = 100,
|
|
199
|
+
seed: Annotated[int, typer.Option(help="Seed that selects which units are sampled.")] = 0,
|
|
200
|
+
top_k: Annotated[
|
|
201
|
+
int | None,
|
|
202
|
+
typer.Option(
|
|
203
|
+
min=1, help="Top-ranked element IDs of each retrieval to evaluate; all if unset."
|
|
204
|
+
),
|
|
205
|
+
] = None,
|
|
206
|
+
metric: Annotated[
|
|
207
|
+
list[str] | None,
|
|
208
|
+
typer.Option("--metric", "-m", help="Run only this metric; repeat for several."),
|
|
209
|
+
] = None,
|
|
210
|
+
threshold: Annotated[
|
|
211
|
+
list[str] | None,
|
|
212
|
+
typer.Option(
|
|
213
|
+
"--threshold",
|
|
214
|
+
"-t",
|
|
215
|
+
help="Minimum score as METRIC=VALUE, VALUE from 0 to 1; repeat for several.",
|
|
216
|
+
),
|
|
217
|
+
] = None,
|
|
218
|
+
metadata: Annotated[
|
|
219
|
+
list[str] | None,
|
|
220
|
+
typer.Option(
|
|
221
|
+
help="Run description as KEY=VALUE, such as model=gpt-5-mini; repeat for several.",
|
|
222
|
+
),
|
|
223
|
+
] = None,
|
|
224
|
+
layout: LayoutFile = None,
|
|
225
|
+
output_format: Annotated[
|
|
226
|
+
OutputFormat, typer.Option("--format", "-f", help="Report format.")
|
|
227
|
+
] = OutputFormat.MARKDOWN,
|
|
228
|
+
output: Output = None,
|
|
229
|
+
max_findings: MaxFindings = 10,
|
|
230
|
+
verbose: Verbose = False,
|
|
231
|
+
) -> None:
|
|
232
|
+
"""Evaluate a Neo4j knowledge graph and report scores and findings.
|
|
233
|
+
|
|
234
|
+
Exits with status 1 when a metric scores below its threshold and 2 on errors.
|
|
235
|
+
"""
|
|
236
|
+
_configure_logging(verbose)
|
|
237
|
+
thresholds = _parse_thresholds(threshold or [])
|
|
238
|
+
run_metadata = _parse_metadata(metadata or [])
|
|
239
|
+
for option, value in (("--judge-base-url", judge_base_url), ("--judge-cache", judge_cache)):
|
|
240
|
+
if value is not None and judge_model is None:
|
|
241
|
+
raise typer.BadParameter("needs --judge", param_hint=option)
|
|
242
|
+
if retrievals is not None and questions is None:
|
|
243
|
+
raise typer.BadParameter("needs --questions", param_hint="--retrievals")
|
|
244
|
+
if top_k is not None and retrievals is None:
|
|
245
|
+
raise typer.BadParameter("needs --retrievals", param_hint="--top-k")
|
|
246
|
+
try:
|
|
247
|
+
layout_overrides = _load_layout(layout)
|
|
248
|
+
judge: Judge | None = None
|
|
249
|
+
if judge_model is not None:
|
|
250
|
+
judge = create_judge(judge_model, base_url=judge_base_url)
|
|
251
|
+
if judge_cache is not None:
|
|
252
|
+
judge = CachedJudge(judge, judge_cache)
|
|
253
|
+
metrics = default_metrics(
|
|
254
|
+
schema=None if schema is None else load_schema(schema),
|
|
255
|
+
ground_truth=None if ground_truth is None else load_ground_truth(ground_truth),
|
|
256
|
+
questions=None if questions is None else load_questions(questions),
|
|
257
|
+
retrievals=None if retrievals is None else load_retrievals(retrievals),
|
|
258
|
+
judge=judge,
|
|
259
|
+
sample_size=sample_size,
|
|
260
|
+
seed=seed,
|
|
261
|
+
top_k=top_k,
|
|
262
|
+
)
|
|
263
|
+
metrics = _select(metrics, metric or [], thresholds)
|
|
264
|
+
with _connect(uri, username, password) as driver:
|
|
265
|
+
graph = Neo4jSource(driver, database).load()
|
|
266
|
+
report = evaluate(
|
|
267
|
+
graph,
|
|
268
|
+
metrics,
|
|
269
|
+
layout=Layout.detect(graph, layout_overrides),
|
|
270
|
+
metadata=run_metadata,
|
|
271
|
+
)
|
|
272
|
+
except KgevalError as error:
|
|
273
|
+
_fail(str(error))
|
|
274
|
+
if output_format is OutputFormat.JSON:
|
|
275
|
+
_write(report.model_dump_json(indent=2) + "\n", output)
|
|
276
|
+
else:
|
|
277
|
+
_write(report.to_markdown(max_findings), output, render_markdown=True)
|
|
278
|
+
if not report.passed:
|
|
279
|
+
raise typer.Exit(1)
|
|
280
|
+
|
|
281
|
+
|
|
282
|
+
@app.command("compare")
|
|
283
|
+
def compare_command(
|
|
284
|
+
base: ReportFile,
|
|
285
|
+
head: ReportFile,
|
|
286
|
+
max_drop: Annotated[
|
|
287
|
+
float,
|
|
288
|
+
typer.Option(
|
|
289
|
+
min=0, max=1, help="Largest score drop, from 0 to 1, that is not a regression."
|
|
290
|
+
),
|
|
291
|
+
] = 0.0,
|
|
292
|
+
output: Output = None,
|
|
293
|
+
max_findings: MaxFindings = 10,
|
|
294
|
+
) -> None:
|
|
295
|
+
"""Compare the report HEAD with the report BASE, such as a baseline, metric by metric.
|
|
296
|
+
|
|
297
|
+
Exits with status 1 when a metric regressed, because HEAD scores it lower than BASE
|
|
298
|
+
by more than --max-drop and sampling explains, or no longer scores a metric that
|
|
299
|
+
BASE scored, and 2 on errors.
|
|
300
|
+
"""
|
|
301
|
+
try:
|
|
302
|
+
comparison = compare(_load_report(base), _load_report(head), max_drop=max_drop)
|
|
303
|
+
except KgevalError as error:
|
|
304
|
+
_fail(str(error))
|
|
305
|
+
_write(comparison.to_markdown(max_findings), output, render_markdown=True)
|
|
306
|
+
if comparison.regressed:
|
|
307
|
+
raise typer.Exit(1)
|
|
308
|
+
|
|
309
|
+
|
|
310
|
+
@app.command("infer-schema")
|
|
311
|
+
def infer_schema_command(
|
|
312
|
+
uri: Uri = None,
|
|
313
|
+
username: Username = None,
|
|
314
|
+
password: Password = None,
|
|
315
|
+
database: Database = None,
|
|
316
|
+
layout: LayoutFile = None,
|
|
317
|
+
output: Output = None,
|
|
318
|
+
verbose: Verbose = False,
|
|
319
|
+
) -> None:
|
|
320
|
+
"""Write the schema the graph follows today, as YAML to review and pass to --schema."""
|
|
321
|
+
_configure_logging(verbose)
|
|
322
|
+
try:
|
|
323
|
+
layout_overrides = _load_layout(layout)
|
|
324
|
+
with _connect(uri, username, password) as driver:
|
|
325
|
+
graph = Neo4jSource(driver, database).load()
|
|
326
|
+
schema = infer_schema(GraphView(graph, Layout.detect(graph, layout_overrides)))
|
|
327
|
+
except KgevalError as error:
|
|
328
|
+
_fail(str(error))
|
|
329
|
+
_write(schema.to_yaml(), output)
|
|
330
|
+
|
|
331
|
+
|
|
332
|
+
@app.command("metrics")
|
|
333
|
+
def metrics_command() -> None:
|
|
334
|
+
"""List every built-in metric by category, with what each category needs."""
|
|
335
|
+
lines = ["# kgeval metrics"]
|
|
336
|
+
for category in MetricCategory:
|
|
337
|
+
metric_types = [
|
|
338
|
+
metric_type for metric_type in BUILTIN_METRICS if metric_type.category is category
|
|
339
|
+
]
|
|
340
|
+
options = " or ".join(
|
|
341
|
+
dict.fromkeys(
|
|
342
|
+
_ENABLED_BY[metric_type.name]
|
|
343
|
+
for metric_type in metric_types
|
|
344
|
+
if metric_type.name in _ENABLED_BY
|
|
345
|
+
)
|
|
346
|
+
)
|
|
347
|
+
lines += [
|
|
348
|
+
"",
|
|
349
|
+
f"## {category.value} ({f'needs {options}' if options else 'runs by default'})",
|
|
350
|
+
"",
|
|
351
|
+
"| Metric | Description |",
|
|
352
|
+
"| --- | --- |",
|
|
353
|
+
]
|
|
354
|
+
lines += [
|
|
355
|
+
f"| {metric_type.name} | {_summary(metric_type)} |" for metric_type in metric_types
|
|
356
|
+
]
|
|
357
|
+
_write("\n".join(lines) + "\n", None, render_markdown=True)
|
|
358
|
+
|
|
359
|
+
|
|
360
|
+
def _summary(metric_type: type[Metric]) -> str:
|
|
361
|
+
return (inspect.getdoc(metric_type) or "").splitlines()[0]
|
|
362
|
+
|
|
363
|
+
|
|
364
|
+
def _configure_logging(verbose: bool) -> None:
|
|
365
|
+
logging.basicConfig(
|
|
366
|
+
level=logging.INFO if verbose else logging.WARNING,
|
|
367
|
+
format="%(levelname)s %(name)s: %(message)s",
|
|
368
|
+
)
|
|
369
|
+
|
|
370
|
+
|
|
371
|
+
def _ask(value: str | None, text: str, default: str, *, hide_input: bool = False) -> str:
|
|
372
|
+
if value is not None:
|
|
373
|
+
return value
|
|
374
|
+
# Prompt only in a terminal, so pipelines fall back to the default instead of blocking.
|
|
375
|
+
if not sys.stdin.isatty():
|
|
376
|
+
return default
|
|
377
|
+
# Write prompts to stderr, so they stay visible when the report is redirected.
|
|
378
|
+
return str(
|
|
379
|
+
typer.prompt(
|
|
380
|
+
text, default=default, hide_input=hide_input, show_default=not hide_input, err=True
|
|
381
|
+
)
|
|
382
|
+
)
|
|
383
|
+
|
|
384
|
+
|
|
385
|
+
@contextmanager
|
|
386
|
+
def _connect(uri: str | None, username: str | None, password: str | None) -> Iterator[Driver]:
|
|
387
|
+
uri = _ask(uri, "Neo4j URI", "neo4j://localhost:7687")
|
|
388
|
+
username = _ask(username, "Neo4j username", "neo4j")
|
|
389
|
+
password = _ask(password, "Neo4j password (empty for none)", "", hide_input=True)
|
|
390
|
+
auth = (username, password) if password else None
|
|
391
|
+
try:
|
|
392
|
+
driver = GraphDatabase.driver(uri, auth=auth)
|
|
393
|
+
except (ValueError, DriverError) as error:
|
|
394
|
+
raise SourceError(f"cannot connect to {uri}: {error}") from error
|
|
395
|
+
with driver:
|
|
396
|
+
yield driver
|
|
397
|
+
|
|
398
|
+
|
|
399
|
+
def _parse_thresholds(values: list[str]) -> dict[str, float]:
|
|
400
|
+
thresholds: dict[str, float] = {}
|
|
401
|
+
for value in values:
|
|
402
|
+
name, separator, number = value.partition("=")
|
|
403
|
+
try:
|
|
404
|
+
score = float(number)
|
|
405
|
+
except ValueError:
|
|
406
|
+
score = float("nan")
|
|
407
|
+
# Rely on NaN failing every comparison, so "nan" and unparsable values are rejected.
|
|
408
|
+
if not (separator and name.strip() and 0 <= score <= 1):
|
|
409
|
+
raise typer.BadParameter(
|
|
410
|
+
f"expected METRIC=VALUE with VALUE from 0 to 1, got {value!r}",
|
|
411
|
+
param_hint="--threshold",
|
|
412
|
+
)
|
|
413
|
+
thresholds[name.strip()] = score
|
|
414
|
+
return thresholds
|
|
415
|
+
|
|
416
|
+
|
|
417
|
+
def _parse_metadata(values: list[str]) -> dict[str, str]:
|
|
418
|
+
metadata: dict[str, str] = {}
|
|
419
|
+
for value in values:
|
|
420
|
+
key, separator, text = value.partition("=")
|
|
421
|
+
key, text = key.strip(), text.strip()
|
|
422
|
+
if not (separator and key and text):
|
|
423
|
+
raise typer.BadParameter(f"expected KEY=VALUE, got {value!r}", param_hint="--metadata")
|
|
424
|
+
if key in metadata:
|
|
425
|
+
raise typer.BadParameter(f"repeats the key {key!r}", param_hint="--metadata")
|
|
426
|
+
metadata[key] = text
|
|
427
|
+
return metadata
|
|
428
|
+
|
|
429
|
+
|
|
430
|
+
def _select(metrics: list[Metric], names: list[str], thresholds: dict[str, float]) -> list[Metric]:
|
|
431
|
+
enabled = [metric.name for metric in metrics]
|
|
432
|
+
missing = sorted((set(names) | set(thresholds)) - set(enabled))
|
|
433
|
+
problems = [f"{name} needs {_ENABLED_BY[name]}" for name in missing if name in _ENABLED_BY]
|
|
434
|
+
unknown = [name for name in missing if name not in _ENABLED_BY]
|
|
435
|
+
if unknown:
|
|
436
|
+
noun = "metric" if len(unknown) == 1 else "metrics"
|
|
437
|
+
problems.append(f"unknown {noun} {', '.join(unknown)}; choose from {', '.join(enabled)}")
|
|
438
|
+
unselected = sorted(set(thresholds) - set(names)) if names else []
|
|
439
|
+
if unselected:
|
|
440
|
+
problems.append(f"--threshold names {', '.join(unselected)}, which --metric excludes")
|
|
441
|
+
if problems:
|
|
442
|
+
raise typer.BadParameter("; ".join(problems))
|
|
443
|
+
return [
|
|
444
|
+
# Rely on _parse_thresholds for the range check, because model_copy does not validate.
|
|
445
|
+
metric.model_copy(update={"threshold": thresholds[metric.name]})
|
|
446
|
+
if metric.name in thresholds
|
|
447
|
+
else metric
|
|
448
|
+
for metric in metrics
|
|
449
|
+
if not names or metric.name in names
|
|
450
|
+
]
|
|
451
|
+
|
|
452
|
+
|
|
453
|
+
def _load_report(path: Path) -> Report:
|
|
454
|
+
try:
|
|
455
|
+
return Report.model_validate_json(path.read_text(encoding="utf-8"))
|
|
456
|
+
except (OSError, ValidationError) as error:
|
|
457
|
+
raise InputError(f"invalid report {path}: {error}") from error
|
|
458
|
+
|
|
459
|
+
|
|
460
|
+
def _load_layout(path: Path | None) -> Layout | None:
|
|
461
|
+
return None if path is None else load_yaml(path, TypeAdapter(Layout))
|
|
462
|
+
|
|
463
|
+
|
|
464
|
+
def _write(text: str, path: Path | None, *, render_markdown: bool = False) -> None:
|
|
465
|
+
if path is not None:
|
|
466
|
+
try:
|
|
467
|
+
path.write_text(text, encoding="utf-8")
|
|
468
|
+
except OSError as error:
|
|
469
|
+
_fail(f"cannot write {path}: {error}")
|
|
470
|
+
elif render_markdown and sys.stdout.isatty():
|
|
471
|
+
Console().print(Markdown(text))
|
|
472
|
+
else:
|
|
473
|
+
# Write UTF-8 bytes, since graph text can hold characters the console code page lacks.
|
|
474
|
+
sys.stdout.flush()
|
|
475
|
+
sys.stdout.buffer.write(text.encode("utf-8"))
|
|
476
|
+
sys.stdout.buffer.flush()
|
|
477
|
+
|
|
478
|
+
|
|
479
|
+
def _fail(message: str) -> NoReturn:
|
|
480
|
+
typer.echo(f"Error: {message}", err=True)
|
|
481
|
+
raise typer.Exit(2)
|
kgeval/errors.py
ADDED
|
@@ -0,0 +1,27 @@
|
|
|
1
|
+
"""Define the exceptions that kgeval raises."""
|
|
2
|
+
|
|
3
|
+
__all__ = ["InputError", "JudgeError", "KgevalError", "SourceError", "VerdictError"]
|
|
4
|
+
|
|
5
|
+
|
|
6
|
+
class KgevalError(Exception):
|
|
7
|
+
"""Signal any failure raised by kgeval itself."""
|
|
8
|
+
|
|
9
|
+
|
|
10
|
+
class SourceError(KgevalError):
|
|
11
|
+
"""Signal that a graph source could not load the graph or run a query."""
|
|
12
|
+
|
|
13
|
+
|
|
14
|
+
class InputError(KgevalError):
|
|
15
|
+
"""Signal that a user-supplied file or argument is invalid."""
|
|
16
|
+
|
|
17
|
+
|
|
18
|
+
class JudgeError(KgevalError):
|
|
19
|
+
"""Signal that an LLM judge cannot be set up or fails to return a usable verdict."""
|
|
20
|
+
|
|
21
|
+
|
|
22
|
+
class VerdictError(JudgeError):
|
|
23
|
+
"""Signal that a judge gave no usable verdict for one prompt, though it can judge others.
|
|
24
|
+
|
|
25
|
+
Judged metrics retry such a prompt once, then leave its unit out as unjudged, while
|
|
26
|
+
any other ``JudgeError``, such as a rejected API key, fails the metric.
|
|
27
|
+
"""
|