konwledge 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.
- konwledge/__init__.py +29 -0
- konwledge/__main__.py +5 -0
- konwledge/api/__init__.py +41 -0
- konwledge/api/app.py +373 -0
- konwledge/api/management.py +113 -0
- konwledge/api/management_models.py +247 -0
- konwledge/api/management_service.py +631 -0
- konwledge/api/models.py +183 -0
- konwledge/api/server.py +111 -0
- konwledge/application.py +482 -0
- konwledge/auto_evaluation/__init__.py +42 -0
- konwledge/auto_evaluation/models.py +130 -0
- konwledge/auto_evaluation/notifications.py +78 -0
- konwledge/auto_evaluation/service.py +669 -0
- konwledge/cli.py +2339 -0
- konwledge/conflicts/__init__.py +17 -0
- konwledge/conflicts/rules.py +189 -0
- konwledge/conflicts/service.py +353 -0
- konwledge/context/__init__.py +37 -0
- konwledge/context/assembly.py +142 -0
- konwledge/context/citations.py +123 -0
- konwledge/context/models.py +233 -0
- konwledge/context/service.py +89 -0
- konwledge/context/tokens.py +75 -0
- konwledge/conversations/__init__.py +51 -0
- konwledge/conversations/extraction.py +139 -0
- konwledge/conversations/service.py +422 -0
- konwledge/database_schema/__init__.py +95 -0
- konwledge/database_schema/collector.py +603 -0
- konwledge/database_schema/models.py +399 -0
- konwledge/database_schema/repository.py +5 -0
- konwledge/database_schema/service.py +460 -0
- konwledge/database_schema/storage.py +5 -0
- konwledge/demo/__init__.py +27 -0
- konwledge/demo/builder.py +218 -0
- konwledge/demo/corpus/deployment-guide.v1.md +30 -0
- konwledge/demo/corpus/deployment-guide.v2.md +32 -0
- konwledge/demo/corpus/deployment-guide.v3.md +32 -0
- konwledge/demo/corpus/oncall-faq.v1.md +9 -0
- konwledge/demo/scenario.py +126 -0
- konwledge/domain/__init__.py +97 -0
- konwledge/domain/conflicts.py +141 -0
- konwledge/domain/conversations.py +317 -0
- konwledge/domain/database_schema.py +57 -0
- konwledge/domain/evaluation.py +153 -0
- konwledge/domain/freshness.py +41 -0
- konwledge/domain/models.py +289 -0
- konwledge/embedding/__init__.py +25 -0
- konwledge/embedding/providers.py +110 -0
- konwledge/embedding/service.py +139 -0
- konwledge/evaluation/__init__.py +64 -0
- konwledge/evaluation/baselines.py +200 -0
- konwledge/evaluation/gates.py +595 -0
- konwledge/evaluation/metrics.py +149 -0
- konwledge/evaluation/models.py +84 -0
- konwledge/evaluation/service.py +225 -0
- konwledge/evaluation/validation.py +167 -0
- konwledge/indexing/__init__.py +49 -0
- konwledge/indexing/base.py +137 -0
- konwledge/indexing/lance.py +242 -0
- konwledge/indexing/memory.py +142 -0
- konwledge/indexing/service.py +224 -0
- konwledge/ingestion/__init__.py +34 -0
- konwledge/ingestion/loaders.py +56 -0
- konwledge/ingestion/normalization.py +19 -0
- konwledge/ingestion/pipeline.py +241 -0
- konwledge/ingestion/service.py +100 -0
- konwledge/ingestion/splitting.py +120 -0
- konwledge/lifecycle/__init__.py +70 -0
- konwledge/lifecycle/diff.py +296 -0
- konwledge/lifecycle/freshness.py +312 -0
- konwledge/lifecycle/revisions.py +142 -0
- konwledge/lifecycle/service.py +462 -0
- konwledge/lifecycle/status.py +168 -0
- konwledge/mcp/__init__.py +1 -0
- konwledge/mcp/approval_cli.py +184 -0
- konwledge/mcp/controlled.py +597 -0
- konwledge/mcp/controlled_models.py +192 -0
- konwledge/mcp/controlled_safety.py +171 -0
- konwledge/mcp/controlled_tables.py +35 -0
- konwledge/mcp/models.py +207 -0
- konwledge/mcp/server.py +410 -0
- konwledge/mcp/service.py +438 -0
- konwledge/mutations/__init__.py +36 -0
- konwledge/mutations/models.py +212 -0
- konwledge/mutations/router.py +216 -0
- konwledge/mutations/safety.py +108 -0
- konwledge/mutations/service.py +729 -0
- konwledge/mutations/tables.py +86 -0
- konwledge/newcli_auto_evaluation.py +274 -0
- konwledge/newcli_database_schema.py +582 -0
- konwledge/newcli_quality.py +259 -0
- konwledge/py.typed +0 -0
- konwledge/quality/__init__.py +6 -0
- konwledge/quality/acceptance.py +334 -0
- konwledge/quality/benchmark_corpus.py +292 -0
- konwledge/quality/models.py +103 -0
- konwledge/quality/service.py +234 -0
- konwledge/replay/__init__.py +6 -0
- konwledge/replay/bundle.py +408 -0
- konwledge/replay/corpus.py +26 -0
- konwledge/replay/files.py +92 -0
- konwledge/replay/producer.py +215 -0
- konwledge/retrieval/__init__.py +16 -0
- konwledge/retrieval/fusion.py +74 -0
- konwledge/retrieval/models.py +61 -0
- konwledge/retrieval/service.py +211 -0
- konwledge/snapshot/__init__.py +44 -0
- konwledge/snapshot/export.py +487 -0
- konwledge/snapshot/models.py +226 -0
- konwledge/snapshot/v1_contract.py +16 -0
- konwledge/storage/__init__.py +49 -0
- konwledge/storage/auto_evaluation.py +283 -0
- konwledge/storage/conflicts.py +101 -0
- konwledge/storage/conversations.py +256 -0
- konwledge/storage/database.py +92 -0
- konwledge/storage/database_schema.py +117 -0
- konwledge/storage/evaluation.py +95 -0
- konwledge/storage/full_text.py +253 -0
- konwledge/storage/repository.py +458 -0
- konwledge/storage/tables.py +383 -0
- konwledge/storage/unit_of_work.py +74 -0
- konwledge-0.1.0.dist-info/METADATA +264 -0
- konwledge-0.1.0.dist-info/RECORD +127 -0
- konwledge-0.1.0.dist-info/WHEEL +4 -0
- konwledge-0.1.0.dist-info/entry_points.txt +4 -0
- konwledge-0.1.0.dist-info/licenses/LICENSE +201 -0
konwledge/__init__.py
ADDED
|
@@ -0,0 +1,29 @@
|
|
|
1
|
+
"""Public package interface for Konwledge."""
|
|
2
|
+
|
|
3
|
+
from __future__ import annotations
|
|
4
|
+
|
|
5
|
+
from typing import TYPE_CHECKING, Any
|
|
6
|
+
|
|
7
|
+
if TYPE_CHECKING:
|
|
8
|
+
from konwledge.application import KnowledgeLibrary
|
|
9
|
+
|
|
10
|
+
__all__ = ["KnowledgeLibrary", "__version__"]
|
|
11
|
+
|
|
12
|
+
__version__ = "0.1.0"
|
|
13
|
+
|
|
14
|
+
|
|
15
|
+
def __getattr__(name: str) -> Any:
|
|
16
|
+
"""Load the application facade only when requested from the package root."""
|
|
17
|
+
|
|
18
|
+
if name == "KnowledgeLibrary":
|
|
19
|
+
from konwledge.application import KnowledgeLibrary
|
|
20
|
+
|
|
21
|
+
globals()[name] = KnowledgeLibrary
|
|
22
|
+
return KnowledgeLibrary
|
|
23
|
+
raise AttributeError(f"module {__name__!r} has no attribute {name!r}")
|
|
24
|
+
|
|
25
|
+
|
|
26
|
+
def __dir__() -> list[str]:
|
|
27
|
+
"""Include lazy public exports in module introspection."""
|
|
28
|
+
|
|
29
|
+
return sorted(set(globals()) | set(__all__))
|
konwledge/__main__.py
ADDED
|
@@ -0,0 +1,41 @@
|
|
|
1
|
+
"""Optional FastAPI transport and its explicit public schemas."""
|
|
2
|
+
|
|
3
|
+
from __future__ import annotations
|
|
4
|
+
|
|
5
|
+
from konwledge.api.app import create_app
|
|
6
|
+
from konwledge.api.models import (
|
|
7
|
+
MODEL_ID,
|
|
8
|
+
APIError,
|
|
9
|
+
APIErrorResponse,
|
|
10
|
+
ChatCompletionChoice,
|
|
11
|
+
ChatCompletionRequest,
|
|
12
|
+
ChatCompletionResponse,
|
|
13
|
+
ChatContext,
|
|
14
|
+
ChatMessage,
|
|
15
|
+
ChatResponseMessage,
|
|
16
|
+
ContextControls,
|
|
17
|
+
ContextRequest,
|
|
18
|
+
HealthResponse,
|
|
19
|
+
ModelInfo,
|
|
20
|
+
ModelListResponse,
|
|
21
|
+
)
|
|
22
|
+
from konwledge.context import ContextPacket
|
|
23
|
+
|
|
24
|
+
__all__ = [
|
|
25
|
+
"MODEL_ID",
|
|
26
|
+
"APIError",
|
|
27
|
+
"APIErrorResponse",
|
|
28
|
+
"ChatCompletionChoice",
|
|
29
|
+
"ChatCompletionRequest",
|
|
30
|
+
"ChatCompletionResponse",
|
|
31
|
+
"ChatContext",
|
|
32
|
+
"ChatMessage",
|
|
33
|
+
"ChatResponseMessage",
|
|
34
|
+
"ContextControls",
|
|
35
|
+
"ContextPacket",
|
|
36
|
+
"ContextRequest",
|
|
37
|
+
"HealthResponse",
|
|
38
|
+
"ModelInfo",
|
|
39
|
+
"ModelListResponse",
|
|
40
|
+
"create_app",
|
|
41
|
+
]
|
konwledge/api/app.py
ADDED
|
@@ -0,0 +1,373 @@
|
|
|
1
|
+
"""FastAPI application factory for the read-only context transport."""
|
|
2
|
+
|
|
3
|
+
from __future__ import annotations
|
|
4
|
+
|
|
5
|
+
import json
|
|
6
|
+
import secrets
|
|
7
|
+
import time
|
|
8
|
+
import uuid
|
|
9
|
+
from collections.abc import Mapping
|
|
10
|
+
from pathlib import Path
|
|
11
|
+
from threading import RLock
|
|
12
|
+
from typing import TYPE_CHECKING, Any, NoReturn
|
|
13
|
+
|
|
14
|
+
from konwledge import __version__
|
|
15
|
+
from konwledge.api.models import (
|
|
16
|
+
MODEL_ID,
|
|
17
|
+
APIErrorResponse,
|
|
18
|
+
ChatCompletionChoice,
|
|
19
|
+
ChatCompletionRequest,
|
|
20
|
+
ChatCompletionResponse,
|
|
21
|
+
ChatResponseMessage,
|
|
22
|
+
ContextControls,
|
|
23
|
+
ContextPacket,
|
|
24
|
+
ContextRequest,
|
|
25
|
+
HealthResponse,
|
|
26
|
+
ModelInfo,
|
|
27
|
+
ModelListResponse,
|
|
28
|
+
)
|
|
29
|
+
from konwledge.retrieval import RetrievalConfigurationError, RetrievalMode
|
|
30
|
+
|
|
31
|
+
if TYPE_CHECKING:
|
|
32
|
+
from fastapi import FastAPI
|
|
33
|
+
|
|
34
|
+
from konwledge.application import KnowledgeLibrary
|
|
35
|
+
|
|
36
|
+
_MODEL_CREATED = 0
|
|
37
|
+
|
|
38
|
+
|
|
39
|
+
def create_app(
|
|
40
|
+
library: KnowledgeLibrary,
|
|
41
|
+
*,
|
|
42
|
+
api_key: str | None = None,
|
|
43
|
+
enable_management: bool = False,
|
|
44
|
+
enable_mutations: bool = False,
|
|
45
|
+
mutation_manifest: Path | None = None,
|
|
46
|
+
mutation_origin: str | None = None,
|
|
47
|
+
mutation_key: str | None = None,
|
|
48
|
+
mutation_actor: str | None = None,
|
|
49
|
+
) -> FastAPI:
|
|
50
|
+
"""Create an API over an existing library whose lifecycle remains caller-owned.
|
|
51
|
+
|
|
52
|
+
FastAPI is imported only when this optional transport is instantiated. The
|
|
53
|
+
factory neither creates storage nor closes the injected library's engine.
|
|
54
|
+
Management routes are an explicit opt-in and require bearer auth even on loopback.
|
|
55
|
+
"""
|
|
56
|
+
|
|
57
|
+
try:
|
|
58
|
+
from fastapi import Depends, FastAPI, HTTPException
|
|
59
|
+
from fastapi.exceptions import RequestValidationError
|
|
60
|
+
from fastapi.responses import JSONResponse
|
|
61
|
+
from fastapi.security import HTTPBearer
|
|
62
|
+
from starlette.exceptions import HTTPException as StarletteHTTPException
|
|
63
|
+
except ImportError:
|
|
64
|
+
raise ImportError(
|
|
65
|
+
"FastAPI is required for the API transport; install the 'api' extra"
|
|
66
|
+
) from None
|
|
67
|
+
|
|
68
|
+
if not isinstance(enable_management, bool):
|
|
69
|
+
raise TypeError("enable_management must be a bool")
|
|
70
|
+
if not isinstance(enable_mutations, bool):
|
|
71
|
+
raise TypeError("enable_mutations must be a bool")
|
|
72
|
+
if api_key is not None and not isinstance(api_key, str):
|
|
73
|
+
raise TypeError("api_key must be a string or None")
|
|
74
|
+
if api_key is not None and not api_key.strip():
|
|
75
|
+
raise ValueError("api_key must not be empty or contain only whitespace")
|
|
76
|
+
if enable_management and api_key is None:
|
|
77
|
+
raise ValueError("enable_management requires a non-empty api_key")
|
|
78
|
+
mutation_scope = None
|
|
79
|
+
mutation_service = None
|
|
80
|
+
mutation_allowed_origin = None
|
|
81
|
+
if enable_mutations:
|
|
82
|
+
from konwledge.mutations.router import validate_actor, validate_origin
|
|
83
|
+
from konwledge.mutations.safety import load_mutation_scope
|
|
84
|
+
from konwledge.mutations.service import MutationService
|
|
85
|
+
|
|
86
|
+
if mutation_manifest is None:
|
|
87
|
+
raise ValueError("enable_mutations requires mutation_manifest")
|
|
88
|
+
if mutation_key is None or not mutation_key.strip():
|
|
89
|
+
raise ValueError("enable_mutations requires a non-empty mutation_key")
|
|
90
|
+
if api_key is not None and secrets.compare_digest(mutation_key, api_key):
|
|
91
|
+
raise ValueError("mutation_key must be independent from api_key")
|
|
92
|
+
database_path = getattr(getattr(library, "_session_factory", None), "kw", {}).get("bind")
|
|
93
|
+
engine_database = getattr(getattr(database_path, "url", None), "database", None)
|
|
94
|
+
if not isinstance(engine_database, str):
|
|
95
|
+
raise ValueError("enable_mutations requires a file-backed library engine")
|
|
96
|
+
mutation_scope = load_mutation_scope(Path(mutation_manifest), Path(engine_database))
|
|
97
|
+
mutation_allowed_origin = validate_origin(mutation_origin)
|
|
98
|
+
mutation_service = MutationService(
|
|
99
|
+
library._session_factory,
|
|
100
|
+
mutation_scope,
|
|
101
|
+
actor_id=validate_actor(mutation_actor),
|
|
102
|
+
)
|
|
103
|
+
|
|
104
|
+
# When authentication is enabled, do not accidentally publish interactive
|
|
105
|
+
# documentation that cannot itself enforce the bearer-key requirement.
|
|
106
|
+
protected_docs = api_key is not None
|
|
107
|
+
app = FastAPI(
|
|
108
|
+
title="Konwledge API",
|
|
109
|
+
version=__version__,
|
|
110
|
+
docs_url=None if protected_docs else "/docs",
|
|
111
|
+
redoc_url=None if protected_docs else "/redoc",
|
|
112
|
+
openapi_url=None if protected_docs else "/openapi.json",
|
|
113
|
+
)
|
|
114
|
+
library_lock = RLock()
|
|
115
|
+
bearer = HTTPBearer(auto_error=False)
|
|
116
|
+
|
|
117
|
+
def api_error(
|
|
118
|
+
status_code: int,
|
|
119
|
+
*,
|
|
120
|
+
message: str,
|
|
121
|
+
error_type: str = "invalid_request_error",
|
|
122
|
+
param: str | None = None,
|
|
123
|
+
code: str | None = None,
|
|
124
|
+
headers: Mapping[str, str] | None = None,
|
|
125
|
+
) -> NoReturn:
|
|
126
|
+
raise HTTPException(
|
|
127
|
+
status_code=status_code,
|
|
128
|
+
detail={
|
|
129
|
+
"error": {
|
|
130
|
+
"message": message,
|
|
131
|
+
"type": error_type,
|
|
132
|
+
"param": param,
|
|
133
|
+
"code": code,
|
|
134
|
+
}
|
|
135
|
+
},
|
|
136
|
+
headers=headers,
|
|
137
|
+
)
|
|
138
|
+
|
|
139
|
+
async def require_api_key(
|
|
140
|
+
credentials: Any = Depends(bearer), # noqa: B008
|
|
141
|
+
) -> None:
|
|
142
|
+
if api_key is None:
|
|
143
|
+
return
|
|
144
|
+
supplied = "" if credentials is None else credentials.credentials
|
|
145
|
+
if not secrets.compare_digest(supplied, api_key):
|
|
146
|
+
api_error(
|
|
147
|
+
401,
|
|
148
|
+
message="Invalid or missing API key.",
|
|
149
|
+
code="invalid_api_key",
|
|
150
|
+
headers={"WWW-Authenticate": "Bearer"},
|
|
151
|
+
)
|
|
152
|
+
|
|
153
|
+
def error_response(
|
|
154
|
+
status_code: int,
|
|
155
|
+
*,
|
|
156
|
+
message: str,
|
|
157
|
+
error_type: str,
|
|
158
|
+
param: str | None,
|
|
159
|
+
code: str | None,
|
|
160
|
+
headers: Mapping[str, str] | None = None,
|
|
161
|
+
) -> JSONResponse:
|
|
162
|
+
body = APIErrorResponse.model_validate(
|
|
163
|
+
{
|
|
164
|
+
"error": {
|
|
165
|
+
"message": message,
|
|
166
|
+
"type": error_type,
|
|
167
|
+
"param": param,
|
|
168
|
+
"code": code,
|
|
169
|
+
}
|
|
170
|
+
}
|
|
171
|
+
)
|
|
172
|
+
return JSONResponse(
|
|
173
|
+
status_code=status_code,
|
|
174
|
+
content=body.model_dump(mode="json"),
|
|
175
|
+
headers=headers,
|
|
176
|
+
)
|
|
177
|
+
|
|
178
|
+
@app.exception_handler(RequestValidationError)
|
|
179
|
+
async def request_validation_error_handler(
|
|
180
|
+
request: Any, exc: RequestValidationError
|
|
181
|
+
) -> JSONResponse:
|
|
182
|
+
errors = exc.errors()
|
|
183
|
+
first = errors[0] if errors else {}
|
|
184
|
+
location = first.get("loc", ())
|
|
185
|
+
fields = [str(part) for part in location if part not in {"body", "query", "path"}]
|
|
186
|
+
param = ".".join(fields) or None
|
|
187
|
+
unsupported = first.get("type") == "extra_forbidden"
|
|
188
|
+
return error_response(
|
|
189
|
+
400,
|
|
190
|
+
message="Unsupported option." if unsupported else "Invalid request.",
|
|
191
|
+
error_type="invalid_request_error",
|
|
192
|
+
param=param,
|
|
193
|
+
code="unsupported_option" if unsupported else "validation_error",
|
|
194
|
+
)
|
|
195
|
+
|
|
196
|
+
@app.exception_handler(StarletteHTTPException)
|
|
197
|
+
async def http_error_handler(request: Any, exc: StarletteHTTPException) -> JSONResponse:
|
|
198
|
+
detail = exc.detail
|
|
199
|
+
if isinstance(detail, dict) and isinstance(detail.get("error"), dict):
|
|
200
|
+
error = detail["error"]
|
|
201
|
+
return error_response(
|
|
202
|
+
exc.status_code,
|
|
203
|
+
message=str(error.get("message", "Request failed.")),
|
|
204
|
+
error_type=str(error.get("type", "invalid_request_error")),
|
|
205
|
+
param=error.get("param") if isinstance(error.get("param"), str) else None,
|
|
206
|
+
code=error.get("code") if isinstance(error.get("code"), str) else None,
|
|
207
|
+
headers=exc.headers,
|
|
208
|
+
)
|
|
209
|
+
return error_response(
|
|
210
|
+
exc.status_code,
|
|
211
|
+
message="Request failed.",
|
|
212
|
+
error_type="invalid_request_error",
|
|
213
|
+
param=None,
|
|
214
|
+
code="http_error",
|
|
215
|
+
headers=exc.headers,
|
|
216
|
+
)
|
|
217
|
+
|
|
218
|
+
@app.exception_handler(Exception)
|
|
219
|
+
async def unexpected_error_handler(request: Any, exc: Exception) -> JSONResponse:
|
|
220
|
+
# Never serialize exception text: provider, SQL, filesystem, and prompt
|
|
221
|
+
# details can all occur in lower-layer exception messages.
|
|
222
|
+
return error_response(
|
|
223
|
+
500,
|
|
224
|
+
message="An internal error occurred.",
|
|
225
|
+
error_type="internal_error",
|
|
226
|
+
param=None,
|
|
227
|
+
code="internal_error",
|
|
228
|
+
)
|
|
229
|
+
|
|
230
|
+
error_docs: dict[int | str, dict[str, Any]] = {
|
|
231
|
+
400: {"model": APIErrorResponse},
|
|
232
|
+
401: {"model": APIErrorResponse},
|
|
233
|
+
503: {"model": APIErrorResponse},
|
|
234
|
+
}
|
|
235
|
+
auth_dependencies = [Depends(require_api_key)] if api_key is not None else []
|
|
236
|
+
|
|
237
|
+
if enable_management:
|
|
238
|
+
management_api_key = api_key
|
|
239
|
+
assert management_api_key is not None
|
|
240
|
+
|
|
241
|
+
@app.middleware("http")
|
|
242
|
+
async def require_management_api_key(request: Any, call_next: Any) -> Any:
|
|
243
|
+
# Management uses the same bearer-token comparison as the dependency above,
|
|
244
|
+
# but as middleware so unauthenticated requests never reach the router or DB.
|
|
245
|
+
if request.url.path.startswith("/v1/management"):
|
|
246
|
+
authorization = request.headers.get("authorization", "")
|
|
247
|
+
scheme, _, token = authorization.partition(" ")
|
|
248
|
+
supplied = token if scheme.lower() == "bearer" and token else ""
|
|
249
|
+
if not secrets.compare_digest(supplied, management_api_key):
|
|
250
|
+
return error_response(
|
|
251
|
+
401,
|
|
252
|
+
message="Invalid or missing API key.",
|
|
253
|
+
error_type="invalid_request_error",
|
|
254
|
+
param=None,
|
|
255
|
+
code="invalid_api_key",
|
|
256
|
+
headers={"WWW-Authenticate": "Bearer"},
|
|
257
|
+
)
|
|
258
|
+
return await call_next(request)
|
|
259
|
+
|
|
260
|
+
@app.get("/health", response_model=HealthResponse)
|
|
261
|
+
def health() -> HealthResponse:
|
|
262
|
+
return HealthResponse(status="ok", version=__version__)
|
|
263
|
+
|
|
264
|
+
@app.get(
|
|
265
|
+
"/v1/models",
|
|
266
|
+
response_model=ModelListResponse,
|
|
267
|
+
responses=error_docs,
|
|
268
|
+
dependencies=auth_dependencies,
|
|
269
|
+
)
|
|
270
|
+
def list_models() -> ModelListResponse:
|
|
271
|
+
return ModelListResponse(data=(ModelInfo(id=MODEL_ID, created=_MODEL_CREATED),))
|
|
272
|
+
|
|
273
|
+
def build_packet(query: str, controls: ContextControls) -> ContextPacket:
|
|
274
|
+
try:
|
|
275
|
+
with library_lock:
|
|
276
|
+
return library.build_context(
|
|
277
|
+
query,
|
|
278
|
+
mode=controls.mode,
|
|
279
|
+
top_k=controls.top_k,
|
|
280
|
+
candidate_limit=controls.candidate_limit,
|
|
281
|
+
rrf_k=controls.rrf_k,
|
|
282
|
+
at=controls.as_of,
|
|
283
|
+
include_stale=controls.include_stale,
|
|
284
|
+
source_id=controls.source_id,
|
|
285
|
+
max_chars=controls.max_chars,
|
|
286
|
+
max_units=controls.max_units,
|
|
287
|
+
)
|
|
288
|
+
except RetrievalConfigurationError:
|
|
289
|
+
api_error(
|
|
290
|
+
400,
|
|
291
|
+
message="The requested retrieval mode is not configured.",
|
|
292
|
+
param="mode",
|
|
293
|
+
code="retrieval_mode_unavailable",
|
|
294
|
+
)
|
|
295
|
+
except ValueError:
|
|
296
|
+
api_error(
|
|
297
|
+
400,
|
|
298
|
+
message="Invalid retrieval request.",
|
|
299
|
+
code="validation_error",
|
|
300
|
+
)
|
|
301
|
+
except Exception:
|
|
302
|
+
if controls.mode is not RetrievalMode.LEXICAL:
|
|
303
|
+
api_error(
|
|
304
|
+
503,
|
|
305
|
+
message="Vector retrieval is temporarily unavailable.",
|
|
306
|
+
param="mode",
|
|
307
|
+
code="vector_retrieval_unavailable",
|
|
308
|
+
)
|
|
309
|
+
raise
|
|
310
|
+
|
|
311
|
+
@app.post(
|
|
312
|
+
"/v1/context",
|
|
313
|
+
response_model=ContextPacket,
|
|
314
|
+
responses=error_docs,
|
|
315
|
+
dependencies=auth_dependencies,
|
|
316
|
+
)
|
|
317
|
+
def context(request: ContextRequest) -> ContextPacket:
|
|
318
|
+
return build_packet(request.query, request)
|
|
319
|
+
|
|
320
|
+
@app.post(
|
|
321
|
+
"/v1/chat/completions",
|
|
322
|
+
response_model=ChatCompletionResponse,
|
|
323
|
+
responses=error_docs,
|
|
324
|
+
dependencies=auth_dependencies,
|
|
325
|
+
)
|
|
326
|
+
def chat_completions(request: ChatCompletionRequest) -> ChatCompletionResponse:
|
|
327
|
+
controls = request.context
|
|
328
|
+
if controls is None:
|
|
329
|
+
# Validate defaults from the same schema used for explicit controls.
|
|
330
|
+
from konwledge.api.models import ChatContext
|
|
331
|
+
|
|
332
|
+
controls = ChatContext()
|
|
333
|
+
packet = build_packet(request.messages[0].content, controls)
|
|
334
|
+
content = json.dumps(
|
|
335
|
+
packet.model_dump(mode="json"),
|
|
336
|
+
ensure_ascii=False,
|
|
337
|
+
separators=(",", ":"),
|
|
338
|
+
)
|
|
339
|
+
return ChatCompletionResponse(
|
|
340
|
+
id=f"chatcmpl-{uuid.uuid4().hex}",
|
|
341
|
+
created=int(time.time()),
|
|
342
|
+
choices=(
|
|
343
|
+
ChatCompletionChoice(
|
|
344
|
+
index=0,
|
|
345
|
+
message=ChatResponseMessage(content=content),
|
|
346
|
+
),
|
|
347
|
+
),
|
|
348
|
+
)
|
|
349
|
+
|
|
350
|
+
if enable_management:
|
|
351
|
+
from konwledge.api.management import build_management_router
|
|
352
|
+
|
|
353
|
+
app.include_router(build_management_router(library), dependencies=auth_dependencies)
|
|
354
|
+
|
|
355
|
+
if enable_mutations:
|
|
356
|
+
from konwledge.mutations.router import build_mutation_router
|
|
357
|
+
|
|
358
|
+
assert mutation_service is not None
|
|
359
|
+
assert mutation_allowed_origin is not None
|
|
360
|
+
assert mutation_key is not None
|
|
361
|
+
app.include_router(
|
|
362
|
+
build_mutation_router(
|
|
363
|
+
mutation_service,
|
|
364
|
+
mutation_key=mutation_key,
|
|
365
|
+
allowed_origin=mutation_allowed_origin,
|
|
366
|
+
read_key=api_key,
|
|
367
|
+
)
|
|
368
|
+
)
|
|
369
|
+
|
|
370
|
+
return app
|
|
371
|
+
|
|
372
|
+
|
|
373
|
+
__all__ = ["create_app"]
|
|
@@ -0,0 +1,113 @@
|
|
|
1
|
+
"""B1 只读管理 router; 认证和 opt-in 开关由 create_app 接线负责。"""
|
|
2
|
+
|
|
3
|
+
from __future__ import annotations
|
|
4
|
+
|
|
5
|
+
from collections.abc import Callable, Coroutine
|
|
6
|
+
from typing import Annotated, Any
|
|
7
|
+
from uuid import UUID
|
|
8
|
+
|
|
9
|
+
from fastapi import APIRouter, Query, Request, Response
|
|
10
|
+
from fastapi.exceptions import RequestValidationError
|
|
11
|
+
from fastapi.responses import JSONResponse
|
|
12
|
+
from fastapi.routing import APIRoute
|
|
13
|
+
|
|
14
|
+
from konwledge.api.management_models import (
|
|
15
|
+
DiffQuery,
|
|
16
|
+
DocumentDiffDTO,
|
|
17
|
+
DocumentDTO,
|
|
18
|
+
EvidenceDTO,
|
|
19
|
+
JobDTO,
|
|
20
|
+
JobsQuery,
|
|
21
|
+
LineageDTO,
|
|
22
|
+
Page,
|
|
23
|
+
PageQuery,
|
|
24
|
+
RevisionDTO,
|
|
25
|
+
UnitDTO,
|
|
26
|
+
)
|
|
27
|
+
from konwledge.api.management_service import ManagementReadError, ManagementService
|
|
28
|
+
from konwledge.api.models import APIErrorResponse
|
|
29
|
+
from konwledge.application import KnowledgeLibrary
|
|
30
|
+
|
|
31
|
+
__all__ = ["build_management_router"]
|
|
32
|
+
|
|
33
|
+
|
|
34
|
+
def _error(status: int, code: str) -> JSONResponse:
|
|
35
|
+
# 统一已有 API error envelope, 不回显 UUID/query、ValidationError.input 或 SQL。
|
|
36
|
+
body = APIErrorResponse.model_validate(
|
|
37
|
+
{
|
|
38
|
+
"error": {
|
|
39
|
+
"message": "Management request failed.",
|
|
40
|
+
"type": "internal_error" if status == 500 else "invalid_request_error",
|
|
41
|
+
"param": None,
|
|
42
|
+
"code": code,
|
|
43
|
+
}
|
|
44
|
+
}
|
|
45
|
+
)
|
|
46
|
+
return JSONResponse(status_code=status, content=body.model_dump(mode="json"))
|
|
47
|
+
|
|
48
|
+
|
|
49
|
+
class _SafeManagementRoute(APIRoute):
|
|
50
|
+
def get_route_handler(self) -> Callable[[Request], Coroutine[Any, Any, Response]]:
|
|
51
|
+
handler = super().get_route_handler()
|
|
52
|
+
|
|
53
|
+
async def safe_handler(request: Request) -> Response:
|
|
54
|
+
try:
|
|
55
|
+
return await handler(request)
|
|
56
|
+
except RequestValidationError:
|
|
57
|
+
# router 局部策略: 普通 context API 仍保留原有 400 协议。
|
|
58
|
+
return _error(422, "management_validation_error")
|
|
59
|
+
except ManagementReadError as exc:
|
|
60
|
+
return _error(exc.status, exc.code)
|
|
61
|
+
except Exception:
|
|
62
|
+
return _error(500, "management_internal_error")
|
|
63
|
+
|
|
64
|
+
return safe_handler
|
|
65
|
+
|
|
66
|
+
|
|
67
|
+
def build_management_router(library: KnowledgeLibrary) -> APIRouter:
|
|
68
|
+
"""返回唯一接线接口, 自带 prefix; 必须在 app 中附加现有 auth dependency。"""
|
|
69
|
+
service = ManagementService(library)
|
|
70
|
+
router = APIRouter(
|
|
71
|
+
prefix="/v1/management",
|
|
72
|
+
tags=["management"],
|
|
73
|
+
route_class=_SafeManagementRoute,
|
|
74
|
+
responses={
|
|
75
|
+
status: {"model": APIErrorResponse} for status in (404, 409, 410, 422, 500, 503)
|
|
76
|
+
},
|
|
77
|
+
)
|
|
78
|
+
|
|
79
|
+
@router.get("/jobs", response_model=Page[JobDTO])
|
|
80
|
+
def jobs(query: Annotated[JobsQuery, Query()]) -> Page[JobDTO]:
|
|
81
|
+
return service.jobs(query)
|
|
82
|
+
|
|
83
|
+
@router.get("/jobs/{job_id}", response_model=JobDTO)
|
|
84
|
+
def job(job_id: UUID) -> JobDTO:
|
|
85
|
+
return service.job(job_id)
|
|
86
|
+
|
|
87
|
+
@router.get("/revisions/{revision_id}", response_model=RevisionDTO)
|
|
88
|
+
def revision(revision_id: UUID) -> RevisionDTO:
|
|
89
|
+
return service.revision(revision_id)
|
|
90
|
+
|
|
91
|
+
@router.get("/lineages/{lineage_id}", response_model=LineageDTO)
|
|
92
|
+
def lineage(lineage_id: UUID, query: Annotated[PageQuery, Query()]) -> LineageDTO:
|
|
93
|
+
return service.lineage(lineage_id, query)
|
|
94
|
+
|
|
95
|
+
@router.get("/documents/{document_id}", response_model=DocumentDTO)
|
|
96
|
+
def document(document_id: UUID, query: Annotated[PageQuery, Query()]) -> DocumentDTO:
|
|
97
|
+
return service.document(document_id, query)
|
|
98
|
+
|
|
99
|
+
@router.get("/documents/{new_document_id}/diff", response_model=DocumentDiffDTO)
|
|
100
|
+
def document_diff(
|
|
101
|
+
new_document_id: UUID, query: Annotated[DiffQuery, Query()]
|
|
102
|
+
) -> DocumentDiffDTO:
|
|
103
|
+
return service.diff(new_document_id, query.old_document_id, query)
|
|
104
|
+
|
|
105
|
+
@router.get("/units/{unit_id}", response_model=UnitDTO)
|
|
106
|
+
def unit(unit_id: UUID) -> UnitDTO:
|
|
107
|
+
return service.unit(unit_id)
|
|
108
|
+
|
|
109
|
+
@router.get("/units/{unit_id}/evidence", response_model=EvidenceDTO)
|
|
110
|
+
def evidence(unit_id: UUID) -> EvidenceDTO:
|
|
111
|
+
return service.evidence(unit_id)
|
|
112
|
+
|
|
113
|
+
return router
|