harborrag-runtime 2.0.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.
- harborrag_runtime/__init__.py +22 -0
- harborrag_runtime/application/README.md +39 -0
- harborrag_runtime/application/__init__.py +39 -0
- harborrag_runtime/application/chat/__init__.py +7 -0
- harborrag_runtime/application/chat/citations.py +149 -0
- harborrag_runtime/application/chat/client.py +201 -0
- harborrag_runtime/application/chat/completion.py +92 -0
- harborrag_runtime/application/chat/completion_request.py +130 -0
- harborrag_runtime/application/chat/evidence.py +202 -0
- harborrag_runtime/application/chat/options.py +43 -0
- harborrag_runtime/application/chat/preparation.py +135 -0
- harborrag_runtime/application/chat/presenters.py +130 -0
- harborrag_runtime/application/chat/prompting.py +127 -0
- harborrag_runtime/application/chat/query_scope.py +146 -0
- harborrag_runtime/application/chat/replay.py +141 -0
- harborrag_runtime/application/chat/request_filters.py +134 -0
- harborrag_runtime/application/chat/retrieval.py +127 -0
- harborrag_runtime/application/chat/service.py +371 -0
- harborrag_runtime/application/composition/__init__.py +1 -0
- harborrag_runtime/application/composition/factories.py +106 -0
- harborrag_runtime/application/composition/resources.py +141 -0
- harborrag_runtime/application/composition/selection.py +65 -0
- harborrag_runtime/application/composition/service.py +550 -0
- harborrag_runtime/application/composition/tenant_models.py +45 -0
- harborrag_runtime/application/control_plane/__init__.py +1 -0
- harborrag_runtime/application/control_plane/active_runs.py +38 -0
- harborrag_runtime/application/control_plane/connection_models.py +109 -0
- harborrag_runtime/application/control_plane/connection_testing.py +91 -0
- harborrag_runtime/application/control_plane/connection_writes.py +227 -0
- harborrag_runtime/application/control_plane/connections.py +749 -0
- harborrag_runtime/application/control_plane/effect_recovery.py +235 -0
- harborrag_runtime/application/control_plane/projects.py +313 -0
- harborrag_runtime/application/control_plane/settings_import.py +239 -0
- harborrag_runtime/application/control_plane/settings_service.py +233 -0
- harborrag_runtime/application/control_plane/tenants.py +55 -0
- harborrag_runtime/application/errors.py +110 -0
- harborrag_runtime/application/ingestion/__init__.py +1 -0
- harborrag_runtime/application/ingestion/client.py +65 -0
- harborrag_runtime/application/ingestion/connection_sources.py +96 -0
- harborrag_runtime/application/ingestion/direct.py +120 -0
- harborrag_runtime/application/ingestion/follower.py +83 -0
- harborrag_runtime/application/ingestion/ports.py +174 -0
- harborrag_runtime/application/ingestion/progress_bridge.py +221 -0
- harborrag_runtime/application/ingestion/retry_selection.py +71 -0
- harborrag_runtime/application/ingestion/service.py +564 -0
- harborrag_runtime/application/ingestion/starter.py +78 -0
- harborrag_runtime/application/memory/__init__.py +21 -0
- harborrag_runtime/application/memory/client.py +114 -0
- harborrag_runtime/application/memory/composition.py +90 -0
- harborrag_runtime/application/memory/context.py +45 -0
- harborrag_runtime/application/memory/sessions.py +117 -0
- harborrag_runtime/application/ports.py +133 -0
- harborrag_runtime/application/retrieval/__init__.py +1 -0
- harborrag_runtime/application/retrieval/access.py +26 -0
- harborrag_runtime/application/scheduling/service.py +58 -0
- harborrag_runtime/application/schemas.py +15 -0
- harborrag_runtime/chat/README.md +40 -0
- harborrag_runtime/chat/__init__.py +18 -0
- harborrag_runtime/chat/composition.py +53 -0
- harborrag_runtime/chat/facade.py +46 -0
- harborrag_runtime/chat/service.py +183 -0
- harborrag_runtime/chat/tenant_clients.py +341 -0
- harborrag_runtime/chat/tenant_config.py +235 -0
- harborrag_runtime/chat/tenant_models.py +22 -0
- harborrag_runtime/composition/__init__.py +5 -0
- harborrag_runtime/composition/config_store.py +53 -0
- harborrag_runtime/composition/connection_removal.py +120 -0
- harborrag_runtime/composition/connection_stores.py +107 -0
- harborrag_runtime/composition/control_plane.py +401 -0
- harborrag_runtime/composition/mcp_auth.py +39 -0
- harborrag_runtime/composition/readers.py +113 -0
- harborrag_runtime/composition/resources.py +336 -0
- harborrag_runtime/composition/storage_providers.py +113 -0
- harborrag_runtime/config/__init__.py +84 -0
- harborrag_runtime/config/checkout.py +212 -0
- harborrag_runtime/config/chunking.py +167 -0
- harborrag_runtime/config/connectors/__init__.py +19 -0
- harborrag_runtime/config/connectors/fingerprints.py +54 -0
- harborrag_runtime/config/connectors/importing.py +611 -0
- harborrag_runtime/config/connectors/loader.py +95 -0
- harborrag_runtime/config/connectors/models/__init__.py +30 -0
- harborrag_runtime/config/connectors/models/atlassian.py +199 -0
- harborrag_runtime/config/connectors/models/builder.py +208 -0
- harborrag_runtime/config/connectors/models/common.py +45 -0
- harborrag_runtime/config/connectors/models/fields.py +134 -0
- harborrag_runtime/config/connectors/models/github.py +143 -0
- harborrag_runtime/config/connectors/models/local_file.py +119 -0
- harborrag_runtime/config/connectors/models/registry.py +149 -0
- harborrag_runtime/config/connectors/models/sharepoint.py +186 -0
- harborrag_runtime/config/connectors/models/spec.py +563 -0
- harborrag_runtime/config/connectors/parsing.py +275 -0
- harborrag_runtime/config/connectors/providers.py +177 -0
- harborrag_runtime/config/connectors/schemas.py +215 -0
- harborrag_runtime/config/errors.py +26 -0
- harborrag_runtime/config/graph_build.py +335 -0
- harborrag_runtime/config/graph_build_loading.py +38 -0
- harborrag_runtime/config/loading.py +245 -0
- harborrag_runtime/config/models.py +95 -0
- harborrag_runtime/config/ontology_loading.py +76 -0
- harborrag_runtime/config/parsers/__init__.py +19 -0
- harborrag_runtime/config/parsers/loader.py +85 -0
- harborrag_runtime/config/parsers/parsing.py +285 -0
- harborrag_runtime/config/parsers/providers.py +305 -0
- harborrag_runtime/config/parsers/schemas.py +614 -0
- harborrag_runtime/config/settings.py +378 -0
- harborrag_runtime/config/settings_document.py +133 -0
- harborrag_runtime/config/temporal.py +331 -0
- harborrag_runtime/config/temporal_loading.py +310 -0
- harborrag_runtime/config_store/__init__.py +5 -0
- harborrag_runtime/config_store/defaults.py +47 -0
- harborrag_runtime/config_store/provider.py +153 -0
- harborrag_runtime/config_store/run_settings.py +72 -0
- harborrag_runtime/connections/__init__.py +27 -0
- harborrag_runtime/connections/secrets.py +348 -0
- harborrag_runtime/contracts.py +237 -0
- harborrag_runtime/document_stage_catalog.py +82 -0
- harborrag_runtime/errors.py +64 -0
- harborrag_runtime/events/__init__.py +3 -0
- harborrag_runtime/events/in_process.py +100 -0
- harborrag_runtime/execution/__init__.py +26 -0
- harborrag_runtime/execution/contracts.py +32 -0
- harborrag_runtime/execution/direct.py +169 -0
- harborrag_runtime/execution/gateway.py +97 -0
- harborrag_runtime/execution/source_conversion.py +61 -0
- harborrag_runtime/execution/source_submission.py +278 -0
- harborrag_runtime/execution/submission.py +64 -0
- harborrag_runtime/execution/task_registry.py +387 -0
- harborrag_runtime/execution/temporal.py +165 -0
- harborrag_runtime/ingestion/README.md +79 -0
- harborrag_runtime/ingestion/__init__.py +59 -0
- harborrag_runtime/ingestion/chunking_profile.py +97 -0
- harborrag_runtime/ingestion/composition.py +279 -0
- harborrag_runtime/ingestion/connection_checks.py +239 -0
- harborrag_runtime/ingestion/connections.py +507 -0
- harborrag_runtime/ingestion/document/__init__.py +1 -0
- harborrag_runtime/ingestion/document/normalization.py +14 -0
- harborrag_runtime/ingestion/document/normalizers/__init__.py +9 -0
- harborrag_runtime/ingestion/document/normalizers/builtins.py +39 -0
- harborrag_runtime/ingestion/document/normalizers/transform.py +30 -0
- harborrag_runtime/ingestion/document/run_tools.py +152 -0
- harborrag_runtime/ingestion/failure_classification.py +82 -0
- harborrag_runtime/ingestion/field_indexes.py +56 -0
- harborrag_runtime/ingestion/maintenance/__init__.py +1 -0
- harborrag_runtime/ingestion/maintenance/connection_removal.py +115 -0
- harborrag_runtime/ingestion/maintenance/projection_admin.py +180 -0
- harborrag_runtime/ingestion/maintenance/relation_repair.py +555 -0
- harborrag_runtime/ingestion/maintenance/retention.py +353 -0
- harborrag_runtime/ingestion/observability.py +3 -0
- harborrag_runtime/ingestion/profiles.py +127 -0
- harborrag_runtime/ingestion/runtime_builder.py +339 -0
- harborrag_runtime/ingestion/source/__init__.py +1 -0
- harborrag_runtime/ingestion/source/descriptor_mapping.py +144 -0
- harborrag_runtime/ingestion/source/discovery.py +290 -0
- harborrag_runtime/ingestion/source/documents.py +184 -0
- harborrag_runtime/ingestion/source/finalization.py +288 -0
- harborrag_runtime/ingestion/source/operations.py +175 -0
- harborrag_runtime/ingestion/source/plan.py +413 -0
- harborrag_runtime/ingestion/source/retry.py +150 -0
- harborrag_runtime/ingestion/source/service.py +470 -0
- harborrag_runtime/ingestion/source/skips.py +172 -0
- harborrag_runtime/ingestion_contracts.py +107 -0
- harborrag_runtime/memory/__init__.py +81 -0
- harborrag_runtime/memory/access.py +47 -0
- harborrag_runtime/memory/administration.py +460 -0
- harborrag_runtime/memory/context/__init__.py +5 -0
- harborrag_runtime/memory/context/result.py +20 -0
- harborrag_runtime/memory/directory.py +166 -0
- harborrag_runtime/memory/erasure.py +122 -0
- harborrag_runtime/memory/locks.py +170 -0
- harborrag_runtime/memory/messages.py +202 -0
- harborrag_runtime/memory/presenters.py +117 -0
- harborrag_runtime/memory/projects.py +38 -0
- harborrag_runtime/memory/tiers/__init__.py +1 -0
- harborrag_runtime/memory/tiers/in_memory.py +491 -0
- harborrag_runtime/memory/titles.py +32 -0
- harborrag_runtime/memory/usage.py +131 -0
- harborrag_runtime/observability/__init__.py +1 -0
- harborrag_runtime/observability/connector_metrics.py +14 -0
- harborrag_runtime/observability/discovery_metrics.py +46 -0
- harborrag_runtime/observability/model.py +410 -0
- harborrag_runtime/observability/observability_types.py +47 -0
- harborrag_runtime/observability/stage_observation.py +96 -0
- harborrag_runtime/observability/tool_audit.py +17 -0
- harborrag_runtime/plugins.py +56 -0
- harborrag_runtime/rate_limiting.py +39 -0
- harborrag_runtime/reader_contracts.py +149 -0
- harborrag_runtime/retrieval/__init__.py +1 -0
- harborrag_runtime/retrieval/composition.py +174 -0
- harborrag_runtime/retrieval/facades.py +224 -0
- harborrag_runtime/scheduling/__init__.py +48 -0
- harborrag_runtime/scheduling/config.py +185 -0
- harborrag_runtime/scheduling/errors.py +37 -0
- harborrag_runtime/scheduling/models.py +146 -0
- harborrag_runtime/scheduling/service.py +297 -0
- harborrag_runtime/scheduling/validation.py +213 -0
- harborrag_runtime/sdk/__init__.py +86 -0
- harborrag_runtime/sdk/configuration.py +44 -0
- harborrag_runtime/sdk/facades.py +47 -0
- harborrag_runtime/sdk/runtime.py +242 -0
- harborrag_runtime/security/__init__.py +1 -0
- harborrag_runtime/security/api_key_operations.py +236 -0
- harborrag_runtime/serialization.py +35 -0
- harborrag_runtime/temporal/__init__.py +19 -0
- harborrag_runtime/temporal/activity_observability.py +313 -0
- harborrag_runtime/temporal/client.py +580 -0
- harborrag_runtime/temporal/connection.py +39 -0
- harborrag_runtime/temporal/conversion.py +147 -0
- harborrag_runtime/temporal/dispatch.py +38 -0
- harborrag_runtime/temporal/document_workflow.py +154 -0
- harborrag_runtime/temporal/failure_handling.py +68 -0
- harborrag_runtime/temporal/gateway.py +121 -0
- harborrag_runtime/temporal/heartbeats.py +67 -0
- harborrag_runtime/temporal/identity.py +14 -0
- harborrag_runtime/temporal/ingestion_activities.py +435 -0
- harborrag_runtime/temporal/maintenance_activities.py +251 -0
- harborrag_runtime/temporal/maintenance_schemas.py +88 -0
- harborrag_runtime/temporal/optional.py +19 -0
- harborrag_runtime/temporal/plan_resolver.py +149 -0
- harborrag_runtime/temporal/policies.py +18 -0
- harborrag_runtime/temporal/reindex_workflow.py +71 -0
- harborrag_runtime/temporal/retry_activities.py +147 -0
- harborrag_runtime/temporal/retry_workflow.py +222 -0
- harborrag_runtime/temporal/sandbox.py +51 -0
- harborrag_runtime/temporal/schedules.py +341 -0
- harborrag_runtime/temporal/schemas.py +482 -0
- harborrag_runtime/temporal/source_activities.py +590 -0
- harborrag_runtime/temporal/source_batch_workflow.py +226 -0
- harborrag_runtime/temporal/source_workflow.py +908 -0
- harborrag_runtime/temporal/submission.py +23 -0
- harborrag_runtime/temporal/worker.py +478 -0
- harborrag_runtime/temporal/worker_registry.py +141 -0
- harborrag_runtime/temporal_models.py +227 -0
- harborrag_runtime/testing/chat_fakes.py +309 -0
- harborrag_runtime/testing/chat_service_double.py +126 -0
- harborrag_runtime/testing/connection_fakes.py +278 -0
- harborrag_runtime/testing/memory_fakes.py +128 -0
- harborrag_runtime/topology/__init__.py +1 -0
- harborrag_runtime/topology/budgeted_extractor.py +110 -0
- harborrag_runtime/topology/chunk_runner.py +41 -0
- harborrag_runtime/topology/composition.py +168 -0
- harborrag_runtime/topology/configuration.py +126 -0
- harborrag_runtime/topology/contextual.py +140 -0
- harborrag_runtime/topology/derived.py +238 -0
- harborrag_runtime/topology/derived_coverage.py +5 -0
- harborrag_runtime/topology/derived_dispatch.py +63 -0
- harborrag_runtime/topology/derived_factory.py +175 -0
- harborrag_runtime/topology/derived_models.py +251 -0
- harborrag_runtime/topology/derived_projection.py +127 -0
- harborrag_runtime/topology/description_factory.py +81 -0
- harborrag_runtime/topology/embedding_profile.py +85 -0
- harborrag_runtime/topology/entity_summary_index.py +304 -0
- harborrag_runtime/topology/maintenance.py +126 -0
- harborrag_runtime/topology/operations.py +277 -0
- harborrag_runtime/topology/parent_materializer.py +167 -0
- harborrag_runtime/topology/run_cost.py +43 -0
- harborrag_runtime/topology/security_operations.py +46 -0
- harborrag_runtime/topology/service.py +349 -0
- harborrag_runtime/topology/summary_factory.py +164 -0
- harborrag_runtime/topology/summary_inputs.py +129 -0
- harborrag_runtime/topology/summary_operations.py +128 -0
- harborrag_runtime/topology/summary_policy.py +39 -0
- harborrag_runtime/topology/summary_products.py +43 -0
- harborrag_runtime/topology/summary_service.py +625 -0
- harborrag_runtime/topology/summary_worker.py +129 -0
- harborrag_runtime/topology/summary_workflow.py +32 -0
- harborrag_runtime/topology/worker.py +101 -0
- harborrag_runtime/topology/workflow.py +32 -0
- harborrag_runtime-2.0.0.dist-info/METADATA +267 -0
- harborrag_runtime-2.0.0.dist-info/RECORD +271 -0
- harborrag_runtime-2.0.0.dist-info/WHEEL +4 -0
- harborrag_runtime-2.0.0.dist-info/licenses/LICENSE +201 -0
|
@@ -0,0 +1,22 @@
|
|
|
1
|
+
from __future__ import annotations
|
|
2
|
+
|
|
3
|
+
from typing import TYPE_CHECKING, Any
|
|
4
|
+
|
|
5
|
+
if TYPE_CHECKING:
|
|
6
|
+
from harborrag_runtime.composition import CompositionRoot
|
|
7
|
+
from harborrag_runtime.sdk import HarborRAG, HarborRAGConfig
|
|
8
|
+
|
|
9
|
+
__all__ = ["CompositionRoot", "HarborRAG", "HarborRAGConfig"]
|
|
10
|
+
|
|
11
|
+
|
|
12
|
+
def __getattr__(name: str) -> Any:
|
|
13
|
+
"""Load the composition root lazily so configuration utilities stay standalone."""
|
|
14
|
+
if name == "CompositionRoot":
|
|
15
|
+
from harborrag_runtime.composition import CompositionRoot
|
|
16
|
+
|
|
17
|
+
return CompositionRoot
|
|
18
|
+
if name in {"HarborRAG", "HarborRAGConfig"}:
|
|
19
|
+
from harborrag_runtime.sdk import HarborRAG, HarborRAGConfig
|
|
20
|
+
|
|
21
|
+
return {"HarborRAG": HarborRAG, "HarborRAGConfig": HarborRAGConfig}[name]
|
|
22
|
+
raise AttributeError(f"module {__name__!r} has no attribute {name!r}")
|
|
@@ -0,0 +1,39 @@
|
|
|
1
|
+
# Application services
|
|
2
|
+
|
|
3
|
+
Find where the application services behind the HTTP API and the CLI live, and what they
|
|
4
|
+
must not do. The `harborrag_runtime.application` package turns a transport's arguments into
|
|
5
|
+
one use case (chat, memory, ingestion or a control-plane read or write) and
|
|
6
|
+
returns one transport-neutral `AppResponse` envelope. Durable ingestion reaches Temporal
|
|
7
|
+
through the runtime client; nothing in this package hands a Temporal object to a caller.
|
|
8
|
+
|
|
9
|
+
The transports live in the `harborrag-app` package: `api/` for HTTP, `cli/` for the command
|
|
10
|
+
line and `operations/` for the port both call. They import this package; this package never
|
|
11
|
+
imports an app or MCP-server module.
|
|
12
|
+
|
|
13
|
+
## Package layout
|
|
14
|
+
|
|
15
|
+
| Path | Owns |
|
|
16
|
+
| --- | --- |
|
|
17
|
+
| `chat/` | Grounded chat completions: scope, retrieval, prompting, citations and the answer events a JSON or streamed response is built from; the completion request's mode and filter refusals; `Idempotency-Key` replay |
|
|
18
|
+
| `memory/` | Conversation sessions, the last three exchanges a chat turn replays, the configured memory plugins, and the service methods that forward to the conversation directory and memory administration; messages, titles, erasure, the conversation directory, administration, usage records, turn locks and presenters live in `harborrag_runtime.memory`, and `MemoryIdentity` in `harborrag_core.domain.identity` |
|
|
19
|
+
| `retrieval/` | The corpus access mode that chat retrieval reads |
|
|
20
|
+
| `ingestion/` | Ingestion ports, recovery, run-progress events and inline execution; presentation and the failure inbox live in `harborrag_engine.ingestion`; starting a run (`starter.py`) and following its events (`follower.py`); durable submission goes through the ingestion application service |
|
|
21
|
+
| `scheduling/` | Reconciling `config/sources/schedules.yaml` into the schedule engine |
|
|
22
|
+
| `control_plane/` | Projects, connections, active runs, runtime settings (the level and role rules, the PATCH refusals, import and export), tenant data checks, and recovery of control-plane side effects |
|
|
23
|
+
| `composition/` | The `AppService` facade, its resource lifecycle, service selection and the `DestinationPolicy` it hands to connection checks |
|
|
24
|
+
| `ports.py`, `schemas.py`, `errors.py` | `BaseAppService`, `AppResponse` and secret-safe error envelopes, shared by the whole package |
|
|
25
|
+
|
|
26
|
+
## Inputs and outputs
|
|
27
|
+
|
|
28
|
+
Transport arguments go in; an `AppResponse` comes out. `get_app_service()` and
|
|
29
|
+
`select_app_service()` in `composition/selection.py` build the service from
|
|
30
|
+
`RuntimeSettings` through the runtime's production composition.
|
|
31
|
+
|
|
32
|
+
## Must not
|
|
33
|
+
|
|
34
|
+
- import an app or MCP-server module;
|
|
35
|
+
- import adapter implementations, apart from the `DestinationPolicy` type that composition, connection tests and connection writes receive from the runtime;
|
|
36
|
+
- implement ingestion business rules;
|
|
37
|
+
- leave a use case's sequencing, existence checks or error translation to a transport:
|
|
38
|
+
an operation calls one service method and maps its result;
|
|
39
|
+
- expose Temporal objects to HTTP or CLI callers.
|
|
@@ -0,0 +1,39 @@
|
|
|
1
|
+
"""Application services behind the HTTP API and the CLI.
|
|
2
|
+
|
|
3
|
+
Runtime-layer use cases that turn a transport's arguments into one transport-neutral
|
|
4
|
+
`AppResponse`. Transports (HTTP, CLI) live in the app package and import this one; nothing
|
|
5
|
+
here imports them, and no Temporal object crosses this boundary.
|
|
6
|
+
|
|
7
|
+
Start from: get_app_service, select_app_service, BaseAppService, AppResponse.
|
|
8
|
+
"""
|
|
9
|
+
|
|
10
|
+
from typing import TYPE_CHECKING, Any
|
|
11
|
+
|
|
12
|
+
from .composition.selection import (
|
|
13
|
+
get_app_service,
|
|
14
|
+
runtime_app_service,
|
|
15
|
+
select_app_service,
|
|
16
|
+
)
|
|
17
|
+
from .ports import BaseAppService
|
|
18
|
+
from .schemas import AppResponse
|
|
19
|
+
|
|
20
|
+
if TYPE_CHECKING:
|
|
21
|
+
from .composition.service import AppService
|
|
22
|
+
|
|
23
|
+
__all__ = [
|
|
24
|
+
"AppResponse",
|
|
25
|
+
"AppService",
|
|
26
|
+
"BaseAppService",
|
|
27
|
+
"get_app_service",
|
|
28
|
+
"runtime_app_service",
|
|
29
|
+
"select_app_service",
|
|
30
|
+
]
|
|
31
|
+
|
|
32
|
+
|
|
33
|
+
def __getattr__(name: str) -> Any:
|
|
34
|
+
"""Keep the runtime client optional until a caller requests a concrete service."""
|
|
35
|
+
if name == "AppService":
|
|
36
|
+
from .composition.service import AppService
|
|
37
|
+
|
|
38
|
+
return AppService
|
|
39
|
+
raise AttributeError(name)
|
|
@@ -0,0 +1,149 @@
|
|
|
1
|
+
"""Number an answer's citations by first appearance and describe each cited passage.
|
|
2
|
+
|
|
3
|
+
The model cites passage ``k`` of its prompt as ``[k]``, or several as ``[k, m]`` or
|
|
4
|
+
``[k-m]``. The caller sees ``[n]``, where ``n`` counts the passages in the order the
|
|
5
|
+
answer first cites them, one number per bracket, so every citation is cited. Only a
|
|
6
|
+
marker whose every number names a passage is rewritten. Every other bracket is left
|
|
7
|
+
as written: a year such as ``[2024]``, a list or range glued to a word such as
|
|
8
|
+
``m[1, 2]``, and anything inside inline code or a fenced code block.
|
|
9
|
+
"""
|
|
10
|
+
|
|
11
|
+
from __future__ import annotations
|
|
12
|
+
|
|
13
|
+
import re
|
|
14
|
+
from collections.abc import Sequence
|
|
15
|
+
|
|
16
|
+
from harborrag_core.domain.retrieval import RetrievalResult
|
|
17
|
+
from harborrag_runtime.memory.messages import CitationRecord
|
|
18
|
+
|
|
19
|
+
from .presenters import citation_uri, display_text
|
|
20
|
+
|
|
21
|
+
SNIPPET_LIMIT = 300
|
|
22
|
+
_MAX_RANGE = 20
|
|
23
|
+
_ITEM = r"\d{1,4}(?:\s*[-–]\s*\d{1,4})?"
|
|
24
|
+
_MARKER = re.compile(rf"\[\s*({_ITEM}(?:\s*,\s*{_ITEM})*)\s*\]")
|
|
25
|
+
_HELD = re.compile(r"(?:\s*\[[\d\s,\-–]{0,40}|\s+|`+)$")
|
|
26
|
+
_CODE_DELIMITER = re.compile(r"`+")
|
|
27
|
+
_LIST_OR_RANGE = re.compile(r"[,\-–]")
|
|
28
|
+
_ELLIPSIS = "…"
|
|
29
|
+
|
|
30
|
+
|
|
31
|
+
class CitationNumbering:
|
|
32
|
+
"""Rewrite one answer's markers as it arrives, in one piece or many.
|
|
33
|
+
|
|
34
|
+
``feed`` returns the text that can be shown so far; a marker or a run of backticks
|
|
35
|
+
split across pieces, and the whitespace before it, is held back until it closes.
|
|
36
|
+
``finish`` returns what is left. The concatenated output is the answer as stored and
|
|
37
|
+
returned.
|
|
38
|
+
|
|
39
|
+
Args:
|
|
40
|
+
passages: The passages of the prompt, in the order the model saw them.
|
|
41
|
+
"""
|
|
42
|
+
|
|
43
|
+
def __init__(self, passages: Sequence[RetrievalResult]) -> None:
|
|
44
|
+
self._passages = tuple(passages)
|
|
45
|
+
self._numbers: dict[int, int] = {}
|
|
46
|
+
self._pending = ""
|
|
47
|
+
self._code_delimiter = ""
|
|
48
|
+
self._previous = ""
|
|
49
|
+
|
|
50
|
+
def feed(self, text: str) -> str:
|
|
51
|
+
"""Return the renumbered text that no later piece can change."""
|
|
52
|
+
buffered = self._pending + text
|
|
53
|
+
held = _HELD.search(buffered)
|
|
54
|
+
cut = held.start() if held else len(buffered)
|
|
55
|
+
self._pending = buffered[cut:]
|
|
56
|
+
return self._rewrite(buffered[:cut])
|
|
57
|
+
|
|
58
|
+
def finish(self) -> str:
|
|
59
|
+
"""Return the held-back rest of the answer."""
|
|
60
|
+
rest, self._pending = self._pending, ""
|
|
61
|
+
return self._rewrite(rest)
|
|
62
|
+
|
|
63
|
+
def citations(self) -> tuple[CitationRecord, ...]:
|
|
64
|
+
"""Return the cited passages, ``n`` ascending."""
|
|
65
|
+
order = sorted(self._numbers.items(), key=lambda item: item[1])
|
|
66
|
+
return tuple(citation_record(n, self._passages[index - 1]) for index, n in order)
|
|
67
|
+
|
|
68
|
+
def _rewrite(self, text: str) -> str:
|
|
69
|
+
"""Renumber the markers of ``text`` that lie outside code, carrying code state on."""
|
|
70
|
+
pieces: list[str] = []
|
|
71
|
+
start = 0
|
|
72
|
+
for delimiter in _CODE_DELIMITER.finditer(text):
|
|
73
|
+
pieces.append(self._rewrite_prose(text[start : delimiter.start()], text, start))
|
|
74
|
+
pieces.append(delimiter.group())
|
|
75
|
+
self._toggle_code(delimiter.group())
|
|
76
|
+
start = delimiter.end()
|
|
77
|
+
pieces.append(self._rewrite_prose(text[start:], text, start))
|
|
78
|
+
self._previous = (self._previous + text)[-1:]
|
|
79
|
+
return "".join(pieces)
|
|
80
|
+
|
|
81
|
+
def _rewrite_prose(self, segment: str, text: str, start: int) -> str:
|
|
82
|
+
"""Renumber ``segment``, which starts at ``start`` in ``text``, unless it is code."""
|
|
83
|
+
if self._code_delimiter:
|
|
84
|
+
return segment
|
|
85
|
+
before = text[start - 1] if start else self._previous
|
|
86
|
+
return _MARKER.sub(self._renumber, before + segment)[len(before) :]
|
|
87
|
+
|
|
88
|
+
def _toggle_code(self, delimiter: str) -> None:
|
|
89
|
+
"""Open code at a backtick run, or close it at a run of the same length."""
|
|
90
|
+
if not self._code_delimiter:
|
|
91
|
+
self._code_delimiter = delimiter
|
|
92
|
+
elif delimiter == self._code_delimiter:
|
|
93
|
+
self._code_delimiter = ""
|
|
94
|
+
|
|
95
|
+
def _renumber(self, marker: re.Match[str]) -> str:
|
|
96
|
+
indexes = None if _is_subscript(marker) else self._indexes(marker.group(1))
|
|
97
|
+
if indexes is None:
|
|
98
|
+
return marker.group(0)
|
|
99
|
+
numbers = [self._numbers.setdefault(index, len(self._numbers) + 1) for index in indexes]
|
|
100
|
+
return "".join(f"[{number}]" for number in dict.fromkeys(numbers))
|
|
101
|
+
|
|
102
|
+
def _indexes(self, items: str) -> list[int] | None:
|
|
103
|
+
"""Return the passage indexes a marker names, in order, or None when one names none."""
|
|
104
|
+
indexes: list[int] = []
|
|
105
|
+
for item in items.split(","):
|
|
106
|
+
first, _, last = item.replace("–", "-").partition("-")
|
|
107
|
+
low = int(first)
|
|
108
|
+
high = int(last) if last.strip() else low
|
|
109
|
+
if not (1 <= low <= high <= len(self._passages) and high - low < _MAX_RANGE):
|
|
110
|
+
return None
|
|
111
|
+
indexes.extend(range(low, high + 1))
|
|
112
|
+
return indexes
|
|
113
|
+
|
|
114
|
+
|
|
115
|
+
def _is_subscript(marker: re.Match[str]) -> bool:
|
|
116
|
+
"""Whether a list or range in brackets is glued to the word before it, as in ``m[1, 2]``.
|
|
117
|
+
|
|
118
|
+
A single number glued to a word, as in ``capital[1]``, is still a citation.
|
|
119
|
+
"""
|
|
120
|
+
before = marker.string[marker.start() - 1 : marker.start()]
|
|
121
|
+
glued = before.isalnum() or before == "_"
|
|
122
|
+
return glued and _LIST_OR_RANGE.search(marker.group(1)) is not None
|
|
123
|
+
|
|
124
|
+
|
|
125
|
+
def citation_record(n: int, result: RetrievalResult) -> CitationRecord:
|
|
126
|
+
"""Describe one cited passage as the explorer ``Citation``."""
|
|
127
|
+
metadata = result.metadata
|
|
128
|
+
document_id = str(metadata.get("document_id", ""))
|
|
129
|
+
locator = metadata.get("citation_locator")
|
|
130
|
+
page = locator.get("page_start") if isinstance(locator, dict) else None
|
|
131
|
+
return CitationRecord(
|
|
132
|
+
n=n,
|
|
133
|
+
chunk_id=result.id,
|
|
134
|
+
document_id=document_id,
|
|
135
|
+
title=display_text(metadata.get("document_title"), 256)
|
|
136
|
+
or display_text(document_id, 128)
|
|
137
|
+
or "Untitled document",
|
|
138
|
+
snippet=snippet(result.text),
|
|
139
|
+
url=citation_uri(locator),
|
|
140
|
+
page=page if isinstance(page, int) and not isinstance(page, bool) else None,
|
|
141
|
+
)
|
|
142
|
+
|
|
143
|
+
|
|
144
|
+
def snippet(text: str) -> str:
|
|
145
|
+
"""Collapse the passage's whitespace and cut it to ``SNIPPET_LIMIT`` characters."""
|
|
146
|
+
collapsed = " ".join(text.split())
|
|
147
|
+
if len(collapsed) <= SNIPPET_LIMIT:
|
|
148
|
+
return collapsed
|
|
149
|
+
return collapsed[: SNIPPET_LIMIT - len(_ELLIPSIS)].rstrip() + _ELLIPSIS
|
|
@@ -0,0 +1,201 @@
|
|
|
1
|
+
"""Chat use-case forwarding shared by application service implementations."""
|
|
2
|
+
|
|
3
|
+
from __future__ import annotations
|
|
4
|
+
|
|
5
|
+
from collections.abc import AsyncGenerator, Callable
|
|
6
|
+
|
|
7
|
+
from harborrag_core.contracts.errors import (
|
|
8
|
+
HarborConnectionError,
|
|
9
|
+
HarborNotFoundError,
|
|
10
|
+
UnknownReferenceError,
|
|
11
|
+
)
|
|
12
|
+
|
|
13
|
+
from ..memory import ConversationSessionService
|
|
14
|
+
from ..schemas import AppResponse
|
|
15
|
+
from .completion import TurnEvent
|
|
16
|
+
from .completion_request import (
|
|
17
|
+
CompletionCaller,
|
|
18
|
+
CompletionOutcome,
|
|
19
|
+
CompletionRequest,
|
|
20
|
+
ReplayKey,
|
|
21
|
+
chat_options,
|
|
22
|
+
)
|
|
23
|
+
from .options import ChatExecutionOptions
|
|
24
|
+
from .replay import CompletionAttempt
|
|
25
|
+
from .service import ChatApplicationService
|
|
26
|
+
|
|
27
|
+
|
|
28
|
+
class ChatClientMixin:
|
|
29
|
+
"""Expose chat operations from a composed chat application service."""
|
|
30
|
+
|
|
31
|
+
_chat: ChatApplicationService
|
|
32
|
+
_sessions: ConversationSessionService
|
|
33
|
+
|
|
34
|
+
async def create_chat_session( # noqa: PLR0913 - one component of the new session per argument
|
|
35
|
+
self,
|
|
36
|
+
*,
|
|
37
|
+
tenant_id: str,
|
|
38
|
+
principal_id: str,
|
|
39
|
+
user_id: str | None = None,
|
|
40
|
+
title: str | None = None,
|
|
41
|
+
project_id: str | None = None,
|
|
42
|
+
) -> AppResponse:
|
|
43
|
+
"""Create a chat session scoped to ``project_id`` for its whole life.
|
|
44
|
+
|
|
45
|
+
``user_id`` owns the new conversation; ``None`` is the shared ``DEFAULT_USER``. The transport
|
|
46
|
+
must pass the same end-user identity it later puts on
|
|
47
|
+
``ChatExecutionOptions``: the session is keyed by it, so creating as
|
|
48
|
+
the credential and completing as the human would make every turn look
|
|
49
|
+
like an unknown session.
|
|
50
|
+
|
|
51
|
+
Raises:
|
|
52
|
+
HarborNotFoundError: ``project_id`` does not exist in ``tenant_id``.
|
|
53
|
+
"""
|
|
54
|
+
await self._chat.validate_project(project_id, tenant_id=tenant_id)
|
|
55
|
+
return await self._sessions.create(
|
|
56
|
+
tenant_id=tenant_id,
|
|
57
|
+
principal_id=principal_id,
|
|
58
|
+
user_id=user_id,
|
|
59
|
+
title=title,
|
|
60
|
+
project_id=project_id,
|
|
61
|
+
)
|
|
62
|
+
|
|
63
|
+
async def start_chat_session(
|
|
64
|
+
self,
|
|
65
|
+
*,
|
|
66
|
+
tenant_id: str,
|
|
67
|
+
principal_id: str,
|
|
68
|
+
user_id: str | None,
|
|
69
|
+
title: str | None,
|
|
70
|
+
project_id: str | None,
|
|
71
|
+
) -> AppResponse:
|
|
72
|
+
"""Create a chat session, a project that does not exist being a reference error.
|
|
73
|
+
|
|
74
|
+
Raises:
|
|
75
|
+
UnknownReferenceError: ``project_id`` does not exist in ``tenant_id`` (field
|
|
76
|
+
``project_id``).
|
|
77
|
+
HarborConnectionError: The chat service did not create the session.
|
|
78
|
+
"""
|
|
79
|
+
try:
|
|
80
|
+
result = await self.create_chat_session(
|
|
81
|
+
tenant_id=tenant_id,
|
|
82
|
+
principal_id=principal_id,
|
|
83
|
+
user_id=user_id,
|
|
84
|
+
title=title,
|
|
85
|
+
project_id=project_id,
|
|
86
|
+
)
|
|
87
|
+
except HarborNotFoundError as exc:
|
|
88
|
+
raise UnknownReferenceError(str(exc), {"field": "project_id"}) from exc
|
|
89
|
+
if not result.ok:
|
|
90
|
+
raise HarborConnectionError("Chat service is unavailable")
|
|
91
|
+
return result
|
|
92
|
+
|
|
93
|
+
async def complete_chat_request(
|
|
94
|
+
self,
|
|
95
|
+
request: CompletionRequest,
|
|
96
|
+
*,
|
|
97
|
+
caller: CompletionCaller,
|
|
98
|
+
replay: ReplayKey,
|
|
99
|
+
validate_body: Callable[[str], object],
|
|
100
|
+
) -> CompletionOutcome:
|
|
101
|
+
"""Answer one completion request once, replaying the stored answer for a repeated key.
|
|
102
|
+
|
|
103
|
+
Every refusal of the request comes before the key is claimed and before any model
|
|
104
|
+
call. A repeated ``replay.key`` with the same body returns the stored completion
|
|
105
|
+
without a model call.
|
|
106
|
+
|
|
107
|
+
Args:
|
|
108
|
+
request: The question and its narrowing.
|
|
109
|
+
caller: Who asks, from verified claims.
|
|
110
|
+
replay: The idempotency key and the hash of the request body.
|
|
111
|
+
validate_body: Checks the completion JSON against the transport's response model
|
|
112
|
+
and raises when it does not fit. It runs before a session stores the exchange,
|
|
113
|
+
so a rejected answer leaves no history; the key is recorded as failed instead
|
|
114
|
+
of completed, and the error propagates.
|
|
115
|
+
|
|
116
|
+
Returns:
|
|
117
|
+
The completion as JSON, and whether it was replayed.
|
|
118
|
+
|
|
119
|
+
Raises:
|
|
120
|
+
ModeUnavailableError: ``request.mode`` is ``advanced`` or ``auto``.
|
|
121
|
+
HarborValidationError: ``request.filters`` cannot be applied, or the key was
|
|
122
|
+
used with another body.
|
|
123
|
+
CompletionInProgressError: The first request with the key is still being answered.
|
|
124
|
+
HarborConflictError: The first request with the key failed.
|
|
125
|
+
HarborConnectionError: The turn ended without its answer.
|
|
126
|
+
"""
|
|
127
|
+
options = chat_options(request, user_id=caller.user_id, acl_subject=caller.acl_subject)
|
|
128
|
+
attempt = CompletionAttempt(
|
|
129
|
+
self._sessions,
|
|
130
|
+
caller.tenant_id,
|
|
131
|
+
caller.user_id or caller.principal_id,
|
|
132
|
+
replay.key,
|
|
133
|
+
replay.request_hash,
|
|
134
|
+
)
|
|
135
|
+
stored = await attempt.claim()
|
|
136
|
+
if stored is not None:
|
|
137
|
+
return CompletionOutcome(stored, replayed=True)
|
|
138
|
+
completion = await attempt.settle(
|
|
139
|
+
self._chat.answer(
|
|
140
|
+
request.message,
|
|
141
|
+
tenant_id=caller.tenant_id,
|
|
142
|
+
principal_id=caller.principal_id,
|
|
143
|
+
options=options,
|
|
144
|
+
validate=lambda answered: validate_body(answered.body()),
|
|
145
|
+
)
|
|
146
|
+
)
|
|
147
|
+
body = completion.body()
|
|
148
|
+
await attempt.finish(body, session_id=completion.session_id)
|
|
149
|
+
return CompletionOutcome(body, replayed=False)
|
|
150
|
+
|
|
151
|
+
async def chat_session_exists(
|
|
152
|
+
self,
|
|
153
|
+
session_id: str,
|
|
154
|
+
*,
|
|
155
|
+
tenant_id: str,
|
|
156
|
+
principal_id: str,
|
|
157
|
+
user_id: str | None = None,
|
|
158
|
+
) -> bool:
|
|
159
|
+
"""Report whether the caller owns the chat session ``session_id``."""
|
|
160
|
+
return await self._sessions.exists(
|
|
161
|
+
session_id,
|
|
162
|
+
tenant_id=tenant_id,
|
|
163
|
+
principal_id=principal_id,
|
|
164
|
+
user_id=user_id,
|
|
165
|
+
)
|
|
166
|
+
|
|
167
|
+
async def chat_completion(
|
|
168
|
+
self,
|
|
169
|
+
query: str,
|
|
170
|
+
*,
|
|
171
|
+
tenant_id: str,
|
|
172
|
+
principal_id: str,
|
|
173
|
+
options: ChatExecutionOptions,
|
|
174
|
+
) -> AppResponse:
|
|
175
|
+
"""Answer one question as the explorer completion body; see ``ChatApplicationService``.
|
|
176
|
+
|
|
177
|
+
Raises:
|
|
178
|
+
HarborError: The turn was refused or failed; see ``ChatApplicationService.answer``.
|
|
179
|
+
"""
|
|
180
|
+
return await self._chat.complete(
|
|
181
|
+
query,
|
|
182
|
+
tenant_id=tenant_id,
|
|
183
|
+
principal_id=principal_id,
|
|
184
|
+
options=options,
|
|
185
|
+
)
|
|
186
|
+
|
|
187
|
+
def chat_answer(
|
|
188
|
+
self,
|
|
189
|
+
query: str,
|
|
190
|
+
*,
|
|
191
|
+
tenant_id: str,
|
|
192
|
+
principal_id: str,
|
|
193
|
+
options: ChatExecutionOptions,
|
|
194
|
+
) -> AsyncGenerator[TurnEvent, None]:
|
|
195
|
+
"""Run one turn as events; see ``ChatApplicationService.answer``."""
|
|
196
|
+
return self._chat.answer(
|
|
197
|
+
query,
|
|
198
|
+
tenant_id=tenant_id,
|
|
199
|
+
principal_id=principal_id,
|
|
200
|
+
options=options,
|
|
201
|
+
)
|
|
@@ -0,0 +1,92 @@
|
|
|
1
|
+
"""One chat turn's answer as the caller receives it, and the events that build it.
|
|
2
|
+
|
|
3
|
+
``ChatApplicationService.answer`` yields, in order: one ``RetrievalFound``, one or more
|
|
4
|
+
``AnswerDelta`` whose texts concatenate to the answer, and one ``TurnCompleted``. The
|
|
5
|
+
JSON route drains them; a stream sends each as it comes.
|
|
6
|
+
|
|
7
|
+
``RetrievalFound`` comes after every read and check the turn makes before its first
|
|
8
|
+
model call, and the next step is that call. A failure before it cost no model call.
|
|
9
|
+
"""
|
|
10
|
+
|
|
11
|
+
from __future__ import annotations
|
|
12
|
+
|
|
13
|
+
import json
|
|
14
|
+
from dataclasses import asdict, dataclass
|
|
15
|
+
|
|
16
|
+
from harborrag_core.domain.retrieval import RetrievalResult
|
|
17
|
+
from harborrag_runtime.memory.messages import ChatMode, CitationRecord
|
|
18
|
+
|
|
19
|
+
|
|
20
|
+
@dataclass(frozen=True, slots=True)
|
|
21
|
+
class CompletionUsage:
|
|
22
|
+
"""What the answer call cost; zero when no answer call was made."""
|
|
23
|
+
|
|
24
|
+
mode: ChatMode
|
|
25
|
+
steps: int
|
|
26
|
+
prompt_tokens: int
|
|
27
|
+
completion_tokens: int
|
|
28
|
+
reasoning_tokens: int
|
|
29
|
+
cost_usd: float | None
|
|
30
|
+
reasoning: str = "off"
|
|
31
|
+
|
|
32
|
+
|
|
33
|
+
@dataclass(frozen=True, slots=True)
|
|
34
|
+
class Completion:
|
|
35
|
+
"""One answered question; ``completion_id`` is the stored assistant message id."""
|
|
36
|
+
|
|
37
|
+
completion_id: str
|
|
38
|
+
session_id: str | None
|
|
39
|
+
trace_id: str
|
|
40
|
+
mode: ChatMode
|
|
41
|
+
answer: str
|
|
42
|
+
citations: tuple[CitationRecord, ...]
|
|
43
|
+
usage: CompletionUsage
|
|
44
|
+
|
|
45
|
+
def data(self) -> dict[str, object]:
|
|
46
|
+
"""Return the explorer completion body, fields in the explorer's order."""
|
|
47
|
+
usage = self.usage
|
|
48
|
+
return {
|
|
49
|
+
"completion_id": self.completion_id,
|
|
50
|
+
"session_id": self.session_id,
|
|
51
|
+
"trace_id": self.trace_id,
|
|
52
|
+
"mode": self.mode,
|
|
53
|
+
"answer": self.answer,
|
|
54
|
+
"citations": [asdict(citation) for citation in self.citations],
|
|
55
|
+
"usage": {
|
|
56
|
+
"mode": usage.mode,
|
|
57
|
+
"reasoning": usage.reasoning,
|
|
58
|
+
"steps": usage.steps,
|
|
59
|
+
"prompt_tokens": usage.prompt_tokens,
|
|
60
|
+
"completion_tokens": usage.completion_tokens,
|
|
61
|
+
"reasoning_tokens": usage.reasoning_tokens,
|
|
62
|
+
"cost_usd": usage.cost_usd,
|
|
63
|
+
},
|
|
64
|
+
}
|
|
65
|
+
|
|
66
|
+
def body(self) -> str:
|
|
67
|
+
"""Return ``data()`` as the compact JSON that is validated, stored and replayed."""
|
|
68
|
+
return json.dumps(self.data(), ensure_ascii=False, separators=(",", ":"))
|
|
69
|
+
|
|
70
|
+
|
|
71
|
+
@dataclass(frozen=True, slots=True)
|
|
72
|
+
class RetrievalFound:
|
|
73
|
+
"""The passages the answer may cite, found before any answer text exists."""
|
|
74
|
+
|
|
75
|
+
results: tuple[RetrievalResult, ...]
|
|
76
|
+
|
|
77
|
+
|
|
78
|
+
@dataclass(frozen=True, slots=True)
|
|
79
|
+
class AnswerDelta:
|
|
80
|
+
"""The next piece of answer text, markers already numbered."""
|
|
81
|
+
|
|
82
|
+
text: str
|
|
83
|
+
|
|
84
|
+
|
|
85
|
+
@dataclass(frozen=True, slots=True)
|
|
86
|
+
class TurnCompleted:
|
|
87
|
+
"""The answer is stored (in a session) and complete."""
|
|
88
|
+
|
|
89
|
+
completion: Completion
|
|
90
|
+
|
|
91
|
+
|
|
92
|
+
type TurnEvent = RetrievalFound | AnswerDelta | TurnCompleted
|
|
@@ -0,0 +1,130 @@
|
|
|
1
|
+
"""One chat completion request as the chat service takes it, and the options it narrows to.
|
|
2
|
+
|
|
3
|
+
Mode and filter refusals and the connection narrowing happen here, before any model call.
|
|
4
|
+
"""
|
|
5
|
+
|
|
6
|
+
from __future__ import annotations
|
|
7
|
+
|
|
8
|
+
from dataclasses import dataclass
|
|
9
|
+
from typing import Literal
|
|
10
|
+
|
|
11
|
+
from harborrag_core.contracts.errors import HarborValidationError, ModeUnavailableError
|
|
12
|
+
from harborrag_runtime.chat import ChatPrompt
|
|
13
|
+
|
|
14
|
+
from .options import ChatExecutionOptions
|
|
15
|
+
from .request_filters import FilterGroup, retrieval_filters
|
|
16
|
+
|
|
17
|
+
RequestedMode = Literal["instant", "classic", "advanced", "auto"]
|
|
18
|
+
|
|
19
|
+
|
|
20
|
+
@dataclass(frozen=True, slots=True)
|
|
21
|
+
class CompletionRequest:
|
|
22
|
+
"""The question of one completion request and how to narrow it.
|
|
23
|
+
|
|
24
|
+
Args:
|
|
25
|
+
message: The question.
|
|
26
|
+
session_id: The session it belongs to; ``None`` asks a one-off question.
|
|
27
|
+
mode: The mode asked for; only ``instant`` and ``classic`` are available.
|
|
28
|
+
filters: Explorer filters to apply, if any.
|
|
29
|
+
project_ids: The projects a one-off question reads.
|
|
30
|
+
connections: Connection refs to narrow to.
|
|
31
|
+
trace_id: Trace id of the request, recorded with the answer.
|
|
32
|
+
"""
|
|
33
|
+
|
|
34
|
+
message: str
|
|
35
|
+
session_id: str | None
|
|
36
|
+
mode: RequestedMode
|
|
37
|
+
filters: FilterGroup | None
|
|
38
|
+
project_ids: tuple[str, ...]
|
|
39
|
+
connections: tuple[str, ...]
|
|
40
|
+
trace_id: str
|
|
41
|
+
|
|
42
|
+
|
|
43
|
+
@dataclass(frozen=True, slots=True)
|
|
44
|
+
class CompletionCaller:
|
|
45
|
+
"""Who asks, from verified claims.
|
|
46
|
+
|
|
47
|
+
Args:
|
|
48
|
+
tenant_id: Tenant the question is asked in.
|
|
49
|
+
principal_id: Subject of the credential.
|
|
50
|
+
user_id: End user who owns the session; the principal when ``None``.
|
|
51
|
+
acl_subject: Subject the document ACL checks, such as an API key's owner.
|
|
52
|
+
"""
|
|
53
|
+
|
|
54
|
+
tenant_id: str
|
|
55
|
+
principal_id: str
|
|
56
|
+
user_id: str | None
|
|
57
|
+
acl_subject: str
|
|
58
|
+
|
|
59
|
+
|
|
60
|
+
@dataclass(frozen=True, slots=True)
|
|
61
|
+
class ReplayKey:
|
|
62
|
+
"""The idempotency key of a request and the hash of its body.
|
|
63
|
+
|
|
64
|
+
Args:
|
|
65
|
+
key: ``Idempotency-Key`` of the request; ``None`` turns replay off.
|
|
66
|
+
request_hash: Hash of the request body, so a key reused with another body is refused.
|
|
67
|
+
"""
|
|
68
|
+
|
|
69
|
+
key: str | None
|
|
70
|
+
request_hash: str
|
|
71
|
+
|
|
72
|
+
|
|
73
|
+
@dataclass(frozen=True, slots=True)
|
|
74
|
+
class CompletionOutcome:
|
|
75
|
+
"""A completion's stored body.
|
|
76
|
+
|
|
77
|
+
Args:
|
|
78
|
+
body: The completion as JSON, as stored for replay.
|
|
79
|
+
replayed: Whether it came from the store without a model call.
|
|
80
|
+
"""
|
|
81
|
+
|
|
82
|
+
body: str
|
|
83
|
+
replayed: bool
|
|
84
|
+
|
|
85
|
+
|
|
86
|
+
def chat_options(
|
|
87
|
+
request: CompletionRequest, *, user_id: str | None, acl_subject: str
|
|
88
|
+
) -> ChatExecutionOptions:
|
|
89
|
+
"""The options of one completion request.
|
|
90
|
+
|
|
91
|
+
Args:
|
|
92
|
+
request: The question and its narrowing.
|
|
93
|
+
user_id: The end user who owns the session.
|
|
94
|
+
acl_subject: Subject the document ACL checks.
|
|
95
|
+
|
|
96
|
+
Returns:
|
|
97
|
+
The chat service's options for the turn.
|
|
98
|
+
|
|
99
|
+
Raises:
|
|
100
|
+
ModeUnavailableError: ``mode`` is ``advanced`` or ``auto`` (until v2.1.0).
|
|
101
|
+
HarborValidationError: ``filters`` cannot be applied, or its ``connection``
|
|
102
|
+
condition excludes every requested connection (field ``filters``).
|
|
103
|
+
"""
|
|
104
|
+
if request.mode not in ("instant", "classic"):
|
|
105
|
+
raise ModeUnavailableError(
|
|
106
|
+
f"mode {request.mode!r} is not available until v2.1.0", {"field": "mode"}
|
|
107
|
+
)
|
|
108
|
+
narrowing = retrieval_filters(request.filters)
|
|
109
|
+
connections = tuple(dict.fromkeys(request.connections))
|
|
110
|
+
if narrowing.connections is not None:
|
|
111
|
+
connections = (
|
|
112
|
+
tuple(ref for ref in connections if ref in narrowing.connections)
|
|
113
|
+
if connections
|
|
114
|
+
else narrowing.connections
|
|
115
|
+
)
|
|
116
|
+
if not connections:
|
|
117
|
+
raise HarborValidationError(
|
|
118
|
+
"the connection filter excludes every requested connection", {"field": "filters"}
|
|
119
|
+
)
|
|
120
|
+
return ChatExecutionOptions(
|
|
121
|
+
session_id=request.session_id,
|
|
122
|
+
system=ChatPrompt.DEFAULT,
|
|
123
|
+
user_id=user_id,
|
|
124
|
+
acl_subject=acl_subject,
|
|
125
|
+
mode=request.mode,
|
|
126
|
+
project_ids=request.project_ids,
|
|
127
|
+
connections=connections,
|
|
128
|
+
filters=narrowing.evidence,
|
|
129
|
+
trace_id=request.trace_id,
|
|
130
|
+
)
|