Compare commits
66
Commits
| Author | SHA1 | Date | |
|---|---|---|---|
|
|
76f9b286c6
|
||
|
|
9b4708fafc | ||
|
|
15938e07e1
|
||
|
|
b2c97d1000 | ||
|
|
ae8e394a7b | ||
|
|
1bae6e26ba
|
||
|
|
80d529e741
|
||
|
|
b50bc4a5c7
|
||
|
|
6a1bac6a9e | ||
|
|
9c3af04a91
|
||
|
|
0bfa4e4d01 | ||
|
|
3d288ddfe9
|
||
|
|
6d6b4696a5 | ||
|
|
ba8e7a6562
|
||
|
|
c751fc055c
|
||
|
|
50898a927d
|
||
|
|
f60009f595
|
||
|
|
ffa7e25bf4
|
||
|
|
00861af42c
|
||
|
|
3b56c93da7 | ||
|
|
a5c38d74a8
|
||
|
|
e8beb7444a
|
||
|
|
fdf8d72367
|
||
|
|
8aac6cf92d
|
||
|
|
6c36917beb
|
||
|
|
befb90a48a | ||
|
|
bca3ea9d83 | ||
|
|
8655ea21d4
|
||
|
|
4b7b955a1f | ||
|
|
ceeb134c90
|
||
|
|
b49e4f4ee0 | ||
|
|
a15d66ecc7 | ||
|
|
886ee06cc4
|
||
|
|
1020c3b324
|
||
|
|
73b58d7391 | ||
|
|
64268e63d0
|
||
|
|
7081debe5f
|
||
|
|
b0b80ead3d
|
||
|
|
c40eebd3cd
|
||
|
|
ff84e35fb3 | ||
|
|
f7faf0a8c0
|
||
|
|
8fab9a856e
|
||
|
|
a7a4648dd1 | ||
|
|
6e7438a2da
|
||
|
|
467c2199dc
|
||
|
|
01309ddfe9 | ||
|
|
de04965cd7
|
||
|
|
61e6f809f1
|
||
|
|
8e8a5c59cd | ||
|
|
45593d2e79
|
||
|
|
87835961f4
|
||
|
|
c3a828c1c3
|
||
|
|
de215f8ff9
|
||
|
|
9e1bda8dae
|
||
|
|
907d943f8d
|
||
|
|
5e1c213fd6 | ||
|
|
1a65aa2257 | ||
|
|
17c376c5b1
|
||
|
|
2e90fbdc5d
|
||
|
|
6a26a7d4fa
|
||
|
|
1d66154bd2 | ||
|
|
1947688c34
|
||
|
|
c487c87051
|
||
|
|
292277908b
|
||
|
|
77bd8df7a2
|
||
|
|
f6edea4b7b
|
No files matched your search
@@ -1,7 +1,7 @@
|
||||
version: 2.1
|
||||
|
||||
orbs:
|
||||
qqq-orb: kingsrook/qqq-orb@0.6.8
|
||||
qqq-orb: kingsrook/qqq-orb@0.6.9
|
||||
|
||||
commands:
|
||||
configure-package-install:
|
||||
|
||||
@@ -29,6 +29,8 @@ Always use the wrapper: Maven 3.10 cannot read the parent POM. The committed def
|
||||
|
||||
## Modules
|
||||
|
||||
- `qbit-assistant-provider-api`: standalone provider SPI/value types and `ModelPricing`, all exclusively in `com.kingsrook.qbits.assistant.spi`; only Jackson annotations in production. Provider validation takes unresolved `ProviderSettings`, not an entity.
|
||||
|
||||
- `qbit-assistant` (`com.kingsrook.qbits.assistant`):
|
||||
- `AssistantQBitProducer`, `AssistantQBitConfig` (with `AssistantModelRouting` and `AssistantBudgets`), `AssistantRuntime`, `AssistantSecurity`.
|
||||
- `metadata/`: tables, owner key type, the Assistant app (home + main tables in the nav), the retention process, the settings customizer (key-reference checks, masked key status), and the `assistant.admin` custom permission checker.
|
||||
@@ -37,7 +39,7 @@ Always use the wrapper: Maven 3.10 cannot read the parent POM. The committed def
|
||||
- `persistence/AssistantStore`: the **only** code that calls QQQ data actions, and only on the QBit's own tables, under the user's session.
|
||||
- `engine/`: `TurnEngine` (the loop), `ContextBuilder` (cache-prefix order), `SystemPrompt`, `PolicyService` (policy row, budgets), `RateLimiter`, the `TurnEvent` / `TurnEventLog` stream, and `MessageParts`.
|
||||
- `api/`: `AssistantApi` (transport-free) and `AssistantRouteProvider` (Javalin, SSE).
|
||||
- `provider/`: the provider-neutral SPI, plus `fake/ScriptedModelProvider` for tests, evals and demos.
|
||||
- `provider/`: runtime-backed `RegistryModelProvider`, plus `fake/ScriptedModelProvider` for tests, evals and demos. The SPI lives in `qbit-assistant-provider-api`.
|
||||
- `developer/`: the record Developer-screen panel, on the core developer-panel contract.
|
||||
- `processes/`: `AssistantRetentionStep` and `TestConnectionProcess` (record action on `assistant_provider`).
|
||||
- `engine/ProviderService` (active provider from `assistant_provider` rows, key references, prices), `UsageRecorder` (one `assistant_usage` row per model call), `ConnectionTest`.
|
||||
@@ -46,6 +48,8 @@ Always use the wrapper: Maven 3.10 cannot read the parent POM. The committed def
|
||||
- `qbit-assistant-provider-bedrock`: Claude through the Anthropic Bedrock backend, AWS default credentials and SigV4; IRSA/web-identity hosts supply STS.
|
||||
- `qbit-assistant-provider-vertex`: Claude through the Anthropic Vertex backend and Gemini through OpenAI-compatible Chat Completions, with refreshed Google ADC tokens.
|
||||
|
||||
- `qbit-assistant-rag-pgvector`: JDBC vector storage; depends on the runtime RAG interfaces (`VectorStore`, `ChunkVector`).
|
||||
|
||||
## Invariants (do not break)
|
||||
|
||||
- **Sessions:**
|
||||
@@ -93,4 +97,4 @@ QQQ style:
|
||||
- `develop` publishes SNAPSHOTs.
|
||||
- `release/*` publishes RCs; the orb bumps `<revision>` in the root POM.
|
||||
- `v*` tags publish releases.
|
||||
- All five modules and the parent POM publish. The flatten plugin resolves `${revision}`.
|
||||
- All seven modules and the parent POM publish. The flatten plugin resolves `${revision}`.
|
||||
+117
-1
@@ -1,5 +1,116 @@
|
||||
# Changelog
|
||||
|
||||
## Unreleased - In-app help
|
||||
|
||||
- Ship the host-neutral Assistant help bundle through QQQ's native registry, replacing the temporary loader.
|
||||
- Cover Assistant tables, fields, actions, widgets and selectors; retain live metadata references and add a bundle coverage gate.
|
||||
- Document HOST bundle overrides and remove deployment-specific provider, classification, retention and backup guidance.
|
||||
|
||||
## Unreleased - Transcript redaction
|
||||
|
||||
- Tokenize classified PII/PHI in stored messages, tool inputs/results, replay events, pending actions and derived summaries using QQQ secured-data tokens. Preserve eligible model requests and live SSE.
|
||||
- Stage content until turn completion, redact split deltas and classify criteria even when no records match; protect assistant logs with a scoped core redactor.
|
||||
- Reject proposals whose parameters were redacted; prevent confirmation before turn completion.
|
||||
- Read core table-level classification metadata and add secured-data canary tests for storage, audits, logs and in-memory model access.
|
||||
- Preserve durable-turn watchdog, supersede, shutdown and restart recovery with turn-scoped transcript redaction; widen token-bearing columns and entity limits, with H2-safe upgrade SQL.
|
||||
- Require QQQ 4.1.0-RC.7 (qqq#1182); retain the default audit-history opt-in and avoid duplicated routing headers against current core. RC.7 is released.
|
||||
## Unreleased - Foreign keys
|
||||
|
||||
- Reference DDL: add the missing foreign keys (conversation tree, usage, data audit,
|
||||
budget accounting, profile skills) with orphan quarantine and their indexes; make
|
||||
`assistant_model.provider_id` `ON DELETE CASCADE`. A Postgres guardrail test fails
|
||||
any declared relation without a foreign key.
|
||||
|
||||
## Unreleased - Durable turns
|
||||
|
||||
- Renew user-owned run leases with heartbeats, poll cross-replica Stop, enforce
|
||||
hard deadlines, and finalize active runs during graceful shutdown. Recover
|
||||
abandoned runs on replay, active discovery, or the next question.
|
||||
- Default to superseding a prior answer in the same conversation. Accept explicit
|
||||
concurrent questions; the per-user cap supersedes the oldest run instead of
|
||||
refusing another question. Per-minute limits and budgets still apply.
|
||||
- Add `GET /qqq/v1/assistant/turns/active`, `turn.phase` progress and `startedAt`
|
||||
on `message.start`. Cancel is idempotent and returns HTTP 200.
|
||||
- Add the optional `AssistantRunTracker` Jobs tray SPI (no-op by default),
|
||||
pending QQQ core job tracking (#1210).
|
||||
- Add the durable-turn schema upgrade; apply it before deploying this runtime.
|
||||
A partial unique index fences duplicate terminal events from concurrent reapers.
|
||||
- UI API extension `assistant` 1.2.0 (additive): `turns/active`, the optional
|
||||
`concurrency` on a new turn, 503 `SHUTTING_DOWN`, `turn.phase`,
|
||||
`message.start.startedAt`, cancelReason `SUPERSEDED`. The 429 response stays
|
||||
documented for budgets and per-minute limits; the "answer already in progress"
|
||||
refusal is no longer returned. Cancel keeps 202 documented for older replicas.
|
||||
|
||||
## Unreleased - Starter defaults
|
||||
|
||||
- Every seed changeset's rollback is empty: a seeded row cannot be told apart from a host's own row with the same name, and Liquibase also rolls back changesets it marked ran, so a name-based undo would delete host data.
|
||||
|
||||
- Fix the defaults changelog: every precondition is a portable `sql-check` (the formatted-SQL `table-exists` form failed to parse); the policy, budget and prices are seeded only into empty tables and the profile only when no default exists, so an existing host never changes on deploy. The test now runs the changelog through Liquibase 4.33, including an already configured host and a missing table.
|
||||
- The Setup card prices the default model the way calls are costed (registry, price rows, configured prices); "Add rows for every table" reads fresh data-access rows.
|
||||
|
||||
- Ship `db/liquibase/qbit-assistant/assistant-defaults.changelog.sql`: insert-only starter rows for the policy, a default profile, four starter skills offered through it, a monthly instance budget (warn, downgrade, stop), current Anthropic prices and a disabled example scheduled task.
|
||||
- Add the Setup card to the Assistant home: every configuration table with its state (set up, needs setup, using defaults, optional) and the next step.
|
||||
- Add the `assistant_data_access` table action "Add rows for every table", which writes the default access out as editable rows.
|
||||
- Add `help/qbit-assistant.yaml` (QQQ help-bundle format) for the app and every assistant table, saying what each table is for and how its rows get created; applied by `AssistantHelp` until core help bundles ship in a release.
|
||||
- Guardrail tests: every table is used at runtime, seeded or explained, and has empty-state help; the changelog seeds a fresh schema and the seeded rows change the assistant's behavior.
|
||||
|
||||
## Unreleased - X1/Y1
|
||||
|
||||
- Add default-off `withRecordHistory(true)` host opt-in: remove only `audit*` on RC.6, or invoke core #1193 audit-read/write-deny support when available. Preserve user permissions and all other channel denials; kof22 does not opt in.
|
||||
|
||||
- Register explicit assistant-channel denials on every assistant table, process,
|
||||
report and widget, preserving core security patterns; fail runtime startup
|
||||
when an assistant object is exposed.
|
||||
- Bump the assistant UI API extension to 1.1.0 for optional owned-turn attribution
|
||||
on explain-access, and regenerate its OpenAPI contract.
|
||||
- Preserve turn attribution in knowledge discovery, RAG reads and explain-access
|
||||
calls; confirm actions retain the original turn and scheduled runs retain the task.
|
||||
- Build audit links with the presentation filter-link builder, filtering by
|
||||
record, table and channel, including deletes; widen audit link storage to TEXT.
|
||||
Document the host audit migration and the QBit column widening.
|
||||
- Verify the admin denial matrix through the real invoker and Next UI, startup
|
||||
failures, and confirmed-write human/channel attribution with decoded audit links.
|
||||
## Unreleased - Email
|
||||
|
||||
### Changed
|
||||
|
||||
- Switch scheduled-result email delivery to qbit-email 0.1.0-RC.2's published `com.kingsrook.qbits.email.api` package, preserving templates, categories, idempotency keys, linked records and status mapping.
|
||||
- Add optional qbit-email 0.1.0-RC.1 delivery of a scheduled task's result (`AssistantEmail.sendScheduledResult`): template `assistant_scheduled_result`, link-only secure message for results above PUBLIC using core's `DataClassification`, owner-recipient hook, opt-in and `emailExternalApproved` gates. Scheduled-task wiring remains a separate integration step.
|
||||
|
||||
## Unreleased - Provider API extraction (#30)
|
||||
|
||||
- **BREAKING:** move all 23 provider API types, including `ModelPricing`, to `com.kingsrook.qbits.assistant.spi`. Recompile consumers with the new imports; see UPGRADE.md. Enforce exclusive package ownership and API dependency boundaries with ArchUnit.
|
||||
|
||||
- Extract provider SPI/value types and `ModelPricing` into `qbit-assistant-provider-api`, now exclusively in `com.kingsrook.qbits.assistant.spi`. Its only production dependency is Jackson annotations.
|
||||
- Move Anthropic, OpenAI, Bedrock and Vertex main dependencies to the API; retain runtime fixtures in test scope. Pgvector still needs runtime RAG interfaces.
|
||||
- Provider-specific validation now takes unresolved `ProviderSettings` instead of `AssistantProvider`; add an ArchUnit boundary and standalone coverage gates.
|
||||
## Unreleased - P-g
|
||||
|
||||
- Add admin Scheduled tasks, owner-locked run history, Quartz cron/timezones,
|
||||
and a 60-second QQQ scheduled process using the host's scheduler context.
|
||||
- Log in through the loopback UI API with a separately allow-listed credential
|
||||
environment reference; verify the designated user before starting a normal turn.
|
||||
- Add Review/Result Approve write mode, Revoke write mode and Run now actions.
|
||||
Approval binds the task definition; scheduled writes always await confirmation.
|
||||
- Attribute scheduled UI API requests and tool logs, apply per-run STOP caps,
|
||||
and send optional Alerts notifications to the designated user. HIPAA summaries
|
||||
contain only `see conversation`.
|
||||
- Add unique schedule-slot claims, fixed-clock fixture integration tests and
|
||||
additive Postgres DDL. No API routes or provider modules change.
|
||||
|
||||
## Unreleased - P-f
|
||||
|
||||
- Add OpenAI-compatible embeddings (including Azure), explicit CHAT/EMBEDDING
|
||||
model kinds, editable discovery hints, and budgeted EMBED usage.
|
||||
- Add admin Knowledge sources with streamed Review/Result Index now and Clear
|
||||
index actions. Indexing uses the clicking admin's UI API session, chunks text,
|
||||
skips unchanged hashes and reconciles disappeared records.
|
||||
- Add content-free in-memory and optional JDBC pgvector stores, per-instance
|
||||
schemas, HNSW cosine search and transactional record replacement.
|
||||
- Add permission-filtered `search_knowledge`, fresh UI API reads, existing
|
||||
masking/redaction, PHI embedding guards, classification propagation and citations.
|
||||
- Add embedding HTTP contracts, real UI API RAG security/golden tests and
|
||||
always-on JDBC contracts; the pgvector container test skips without Docker.
|
||||
## Unreleased - Answer presentation
|
||||
|
||||
- Add `present_results`: server-formatted metrics, tables, computed percentages,
|
||||
@@ -34,7 +145,7 @@
|
||||
- Add HIPAA mode, eligible-provider enforcement, AES-256-GCM conversation storage,
|
||||
provider diagnostic redaction, and independent PHI conversation retention.
|
||||
- Add owner-locked, admin read-only data routing audits and HIPAA status on the home.
|
||||
- Keep QQQ RC.4 compatibility with a classification stand-in and core #1142 adapter seam.
|
||||
- Classification levels are core's `DataClassification` (the qbit stand-in is removed); the default source reads core AI metadata merged with configuration.
|
||||
|
||||
All notable changes to this project are documented here. The format follows Keep a Changelog, and versions follow semantic versioning.
|
||||
|
||||
@@ -52,6 +163,11 @@ Phase 0/1 of the QQQ Assistant: read-only Q&A and navigation. Requires QQQ 4.1 w
|
||||
- the AI tool kernel (`qqq-backend-core` `actions.ai`, QRun-IO/qqq#1078)
|
||||
- the developer-panel contract (QRun-IO/qqq#1076).
|
||||
|
||||
### Changed (0.1.0-RC.7, needs QQQ with QRun-IO/qqq#1128)
|
||||
- The assistant's endpoints are spec'd `/qqq/v1` operations (UI API extension `assistant` 1.0.0, prefix `/assistant`): same URLs, bodies and statuses, now in the served OpenAPI; turns and events are `text/event-stream`. The raw routes are gone.
|
||||
- Tools call core's `UiApiInvoker` with the caller's own request credentials (`UiApiCredentials`); the loopback stand-in is removed. The assistant's own operations are never invocable by its tools.
|
||||
- The OpenAPI fragment is committed (`openapi/qqq-v1/assistant.yaml`) and contract-tested.
|
||||
|
||||
### Changed (0.1.0-RC.6): tools go through the UI API (owner decision 2026-10-13)
|
||||
- **Every data tool runs a spec'd `/qqq/v1` operation with the user's own session** (`UiApiGateway`, loopback HTTP with the `sessionUUID` cookie): the same authentication, permissions, record locks, validation, audit and errors as the UI. A user without a permission gets the identical denial through the assistant. `navigate` and `search_help` (no records) stay on the core kernel. `LoopbackUiApiGateway` is a stand-in for core's `UiApiInvoker` (QRun-IO/qqq#1128).
|
||||
- Tools: `list_tables`, `describe_table`, `query_records`, `count_records`, `get_record`, `search_records`, `render_widget`, `get_record_history`, and new **`create_record`, `update_record`, `delete_record`**.
|
||||
|
||||
@@ -29,6 +29,8 @@ Always use the wrapper: Maven 3.10 cannot read the parent POM. The committed def
|
||||
|
||||
## Modules
|
||||
|
||||
- `qbit-assistant-provider-api`: standalone provider SPI/value types and `ModelPricing`, all exclusively in `com.kingsrook.qbits.assistant.spi`; only Jackson annotations in production. Provider validation takes unresolved `ProviderSettings`, not an entity.
|
||||
|
||||
- `qbit-assistant` (`com.kingsrook.qbits.assistant`):
|
||||
- `AssistantQBitProducer`, `AssistantQBitConfig` (with `AssistantModelRouting` and `AssistantBudgets`), `AssistantRuntime`, `AssistantSecurity`.
|
||||
- `metadata/`: tables, owner key type, the Assistant app (home + main tables in the nav), the retention process, the settings customizer (key-reference checks, masked key status), and the `assistant.admin` custom permission checker.
|
||||
@@ -37,7 +39,7 @@ Always use the wrapper: Maven 3.10 cannot read the parent POM. The committed def
|
||||
- `persistence/AssistantStore`: the **only** code that calls QQQ data actions, and only on the QBit's own tables, under the user's session.
|
||||
- `engine/`: `TurnEngine` (the loop), `ContextBuilder` (cache-prefix order), `SystemPrompt`, `PolicyService` (policy row, budgets), `RateLimiter`, the `TurnEvent` / `TurnEventLog` stream, and `MessageParts`.
|
||||
- `api/`: `AssistantApi` (transport-free) and `AssistantRouteProvider` (Javalin, SSE).
|
||||
- `provider/`: the provider-neutral SPI, plus `fake/ScriptedModelProvider` for tests, evals and demos.
|
||||
- `provider/`: runtime-backed `RegistryModelProvider`, plus `fake/ScriptedModelProvider` for tests, evals and demos. The SPI lives in `qbit-assistant-provider-api`.
|
||||
- `developer/`: the record Developer-screen panel, on the core developer-panel contract.
|
||||
- `processes/`: `AssistantRetentionStep` and `TestConnectionProcess` (record action on `assistant_provider`).
|
||||
- `engine/ProviderService` (active provider from `assistant_provider` rows, key references, prices), `UsageRecorder` (one `assistant_usage` row per model call), `ConnectionTest`.
|
||||
@@ -46,13 +48,20 @@ Always use the wrapper: Maven 3.10 cannot read the parent POM. The committed def
|
||||
- `qbit-assistant-provider-bedrock`: Claude through the Anthropic Bedrock backend, AWS default credentials and SigV4; IRSA/web-identity hosts supply STS.
|
||||
- `qbit-assistant-provider-vertex`: Claude through the Anthropic Vertex backend and Gemini through OpenAI-compatible Chat Completions, with refreshed Google ADC tokens.
|
||||
|
||||
- `qbit-assistant-rag-pgvector`: optional host-supplied JDBC vector store, isolated by instance schema; depends on runtime RAG interfaces (`VectorStore`, `ChunkVector`), with no QQQ RDBMS internals.
|
||||
|
||||
## Invariants (do not break)
|
||||
|
||||
- **Transcript redaction:** stored transcripts never contain raw PII/PHI values; tokens via `ClassifiedValueTokens`. Redact storage copies before truncation/encryption; eligible model inputs and live SSE remain unchanged.
|
||||
|
||||
- **Sessions:**
|
||||
- Scheduled runs log in as the designated user through `POST /qqq/v1/manageSession`; resolve only its returned UUID, verify the user id, and never construct or elevate a session. The QQQ-supplied scheduler context touches only assistant bookkeeping.
|
||||
- Never use `QSystemUserSession` or construct a `QSession` in main code (ArchUnit).
|
||||
- Every route uses `ExecutorSessionUtils.setupSession` (the user's own session).
|
||||
- `AssistantSecurity` only ever adds the user's OWN id key, or the all-access key for `assistant.admin` holders.
|
||||
- **Channel wall:** every `assistant_*` object (table, process, report and widget) is denied to the `assistant` channel; startup fails otherwise. Requests carry `assistant/<turnId>` or `assistant/scheduled/<taskId>`; administration uses `next-ui`.
|
||||
- **Data access:**
|
||||
- The vector index stores no record content: only source/table/key/field/chunk, content hash and embedding. Retrieval re-reads every hit through the UI API as the asking user, then applies the existing get_record exposure/masking path.
|
||||
- Only `persistence/` calls QueryAction, InsertAction and the other data actions (ArchUnit).
|
||||
- Data tools run only through `UiApiToolbox` → `UiApiGateway` (spec'd `/qqq/v1` operations with the user's `sessionUUID`); never core data actions for user data. Only `navigate` and `search_help` use `AiToolKernel.execute`.
|
||||
- Data access (`DataAccessService`) and the policy only ever narrow what the UI API allows; a table whose AI exposure is NONE stays NONE.
|
||||
@@ -64,6 +73,8 @@ Always use the wrapper: Maven 3.10 cannot read the parent POM. The committed def
|
||||
- Errors (DENIED, NOT_FOUND, INVALID_INPUT, ERROR) are `is_error` results.
|
||||
- Unknown tools and over-limit calls also get error results.
|
||||
- **Keys:** never stored in a table. `assistant_provider.apiKeyEnvName` holds only an allowed environment variable NAME; `apiKeyStatus` is computed on read (last 4 at most) and stripped on save.
|
||||
- Scheduled task `credentialEnvName` is a separately allow-listed environment variable NAME. Tokens never enter rows, model context or logs. `credentialStatus` is computed and stripped on save.
|
||||
- Scheduled write approval is invalidated by changes to prompt, run-as user, credential reference, profile or write request. Scheduled writes always require the designated user's panel confirmation.
|
||||
- **Logging:** never log message content, prompts, tool results or keys. Structured end-of-turn log only.
|
||||
- **Thinking:** thinking is never streamed or stored. The Anthropic adapter keeps the raw assistant message (with signatures) only in memory, as `providerState`, for the tool loop.
|
||||
- **Links:** only `/app` or `/app/...` hrefs are emitted (`TurnEngine.isAppHref`).
|
||||
@@ -99,4 +110,4 @@ QQQ style:
|
||||
- `develop` publishes SNAPSHOTs.
|
||||
- `release/*` publishes RCs; the orb bumps `<revision>` in the root POM.
|
||||
- `v*` tags publish releases.
|
||||
- All five modules and the parent POM publish. The flatten plugin resolves `${revision}`.
|
||||
- All seven modules and the parent POM publish. The flatten plugin resolves `${revision}`.
|
||||
@@ -4,11 +4,142 @@ An in-app AI assistant for any QQQ application. The user asks a question in a ch
|
||||
|
||||
Design spec: `QRun-IO/qqq` `docs/specs/2026-10-11-qqq-assistant-qbit-design.md`.
|
||||
|
||||
## Modules
|
||||
|
||||
| Artifact | What it is |
|
||||
|---|---|
|
||||
| `com.kingsrook.qbits:qbit-assistant` | The QBit: conversation tables, turn engine, `/qqq/v1/assistant` routes (JSON + Server-Sent Events), budgets, kill switch, the provider SPI, and a scripted provider for tests and demos. |
|
||||
| `com.kingsrook.qbits:qbit-assistant-provider-api` | Provider SPI, connection settings, messages, usage and pricing types; only Jackson annotations at runtime. |
|
||||
| `com.kingsrook.qbits:qbit-assistant` | The QBit: conversation tables, turn engine, `/qqq/v1/assistant` routes (JSON + Server-Sent Events), budgets, kill switch, the provider registry, and a scripted provider for tests and demos. |
|
||||
| `com.kingsrook.qbits:qbit-assistant-provider-anthropic` | The Claude provider (`com.anthropic:anthropic-java`). Add it to use Claude. The core QBit has no LLM SDK dependency. |
|
||||
| `com.kingsrook.qbits:qbit-assistant-provider-openai` | OpenAI-compatible chat and embedding providers. |
|
||||
| `com.kingsrook.qbits:qbit-assistant-provider-bedrock` | Claude through AWS Bedrock. |
|
||||
| `com.kingsrook.qbits:qbit-assistant-provider-vertex` | Claude and Gemini through Google Vertex AI. |
|
||||
| `com.kingsrook.qbits:qbit-assistant-rag-pgvector` | JDBC vector store; retains the runtime dependency for `VectorStore` and `ChunkVector`. |
|
||||
|
||||
### Implementing a provider outside qbit-assistant
|
||||
|
||||
Depend on `com.kingsrook.qbits:qbit-assistant-provider-api` at the same version as
|
||||
QBit Assistant, and implement `AssistantModelProvider` and optionally
|
||||
`AssistantProviderType`. No assistant runtime dependency is needed. All API types, including
|
||||
`ModelPricing`, live exclusively in `com.kingsrook.qbits.assistant.spi`. External
|
||||
consumers such as qbit-marketing allow that package in their G1 guardrails;
|
||||
qbit-bom will add it to the G1 defaults. See [migration imports](UPGRADE.md#provider-api-extraction-30).
|
||||
`AssistantProviderType.validate(ProviderSettings)` receives unresolved settings
|
||||
(including `apiKeyEnvName`), without a database entity or resolved credentials.
|
||||
Hosts register providers through `AssistantQBitConfig` in `qbit-assistant`.
|
||||
|
||||
Data tools use the QQQ UI API (`/qqq/v1`) with the signed-in user's session. The UI API enforces permissions and record locks; assistant data-access policy and field exposure can only narrow access. Only record-free navigation and help use the core AI tool kernel. Every tool result reaches the model wrapped as untrusted data.
|
||||
|
||||
## Transcript privacy
|
||||
|
||||
QQQ **4.1.0-RC.7** supplies the secured-data tokens and log hook (`qqq#1182`).
|
||||
Stored transcripts never contain the raw PII/PHI values read by a turn or supplied
|
||||
in classified tool criteria/fields. Messages, tool logs, replay events, knowledge
|
||||
snippets and pending payloads store `ClassifiedValueTokens` tokens; scheduled
|
||||
summaries use the redacted message. The model and live user stream retain the
|
||||
values permitted by PHI routing. History and replay show tokens instead.
|
||||
|
||||
Content is finalized at turn completion; interrupted servers leave value-free
|
||||
placeholders. Proposals requiring redacted parameters are rejected and must be
|
||||
completed in the application. Existing transcripts are not migrated. See
|
||||
[transcript redaction](docs/DESIGN.md#transcript-redaction-secured-data-15).
|
||||
The dependency upgrade stays draft until RC.7 is published; local verification:
|
||||
|
||||
```powershell
|
||||
.\mvnw.cmd -q verify "-Dqqq.snapshot.version=4.1.0-RC7PRE-SNAPSHOT"
|
||||
```
|
||||
|
||||
## Host audit attribution (X1/Y1)
|
||||
|
||||
Use QQQ **4.1.0-RC.6 or later**. The QBit explicitly denies every assistant
|
||||
configuration table, process, report and widget to the `assistant` channel;
|
||||
runtime initialization fails if an assistant object is exposed. The same human
|
||||
can still administer it through Next UI (`next-ui`). Core's security-surface
|
||||
deny patterns remain in place.
|
||||
|
||||
Enable the audit client field in the host's core audit provider **after adding
|
||||
the backing column**:
|
||||
|
||||
```java
|
||||
new AuditsMetaDataProvider().withClientChannelField(true)
|
||||
.defineAll(qInstance, backendName, null);
|
||||
```
|
||||
|
||||
Add nullable `audit.client_channel VARCHAR(100)` using the host's migration and
|
||||
column-naming conventions. For kof22 this requires a feature-named changeset
|
||||
under `changesets/features/`; this QBit does not migrate the host's audit table.
|
||||
The actor remains the signed-in human; `clientChannel` distinguishes
|
||||
`assistant/<turnId>`, `assistant/scheduled/<taskId>` and `next-ui`.
|
||||
|
||||
Apply the X1/Y1 DDL in [UPGRADE.md](UPGRADE.md) to widen the existing
|
||||
`assistant_tool_call.audit_href` column to TEXT for encoded filters.
|
||||
Successful record writes store `assistant_tool_call.auditHref` as an `/app/audit`
|
||||
filter link over `recordId`, `auditTable.name` and `clientChannel`. The human
|
||||
opens this link with their UI permissions; the assistant cannot read audits by
|
||||
default. Without the audit channel field, the QBit leaves `auditHref` empty.
|
||||
Confirmed scheduled actions use their original turn id when the human approves.
|
||||
|
||||
|
||||
## RAG setup
|
||||
|
||||
Knowledge retrieval is optional. The vector index stores **no record content**:
|
||||
only source/table/key/field/chunk identifiers, SHA-256 hashes and embeddings.
|
||||
Indexing reads through the UI API as the clicking administrator. Retrieval
|
||||
re-reads each hit through that same API as the asking user, silently filters
|
||||
403/404 results, applies `get_record` field exposure/masking/redaction and returns
|
||||
fresh snippets with `/app/...` citations. `search_knowledge` follows `allowedTools`
|
||||
and is offered only with an enabled source the user may read in the UI.
|
||||
|
||||
1. Register the OpenAI-compatible provider module and configure the embedding
|
||||
endpoint through the existing provider settings/URL allowlist. Discover or add
|
||||
a model, set **Model kind = EMBEDDING** and its dimensions. Known discovery
|
||||
defaults are `bge-m3` (1024) and `nomic-embed-text` (768); these remain editable.
|
||||
CHAT models cannot be selected for embedding, and EMBEDDING models cannot answer
|
||||
chat turns. Each embedding batch contains at most 64 inputs.
|
||||
2. Use the default `InMemoryVectorStore` for tests/small hosts, or add
|
||||
`com.kingsrook.qbits:qbit-assistant-rag-pgvector` at the QBit's version for
|
||||
persistence. The host supplies its JDBC driver and DataSource; this module
|
||||
does not depend on QQQ RDBMS internals.
|
||||
3. For pgvector, have the DBA install the extension once in the chosen database:
|
||||
`CREATE EXTENSION IF NOT EXISTS vector`. Give the application a distinct schema
|
||||
per QQQ instance. Configure the store before producing the QBit:
|
||||
|
||||
```java
|
||||
PgVectorStore vectors = new PgVectorStore(dataSource, 1024)
|
||||
.withSchema("assistant_rag_my_instance");
|
||||
vectors.ensureSchema();
|
||||
config.withVectorStore(vectors);
|
||||
config.withUiApiBaseUrl("http://127.0.0.1:8000");
|
||||
```
|
||||
|
||||
The UI API URL is this server's own listening address. Configure it explicitly
|
||||
so Index now works before any chat request has taught the runtime its local
|
||||
port. The store creates a content-free `assistant_rag_chunk` table and an HNSW
|
||||
cosine index. Its fixed dimension must match every source using the store;
|
||||
different models are searched separately. No credentials go in source rows.
|
||||
See the [pgvector installation/index documentation](https://github.com/pgvector/pgvector)
|
||||
and the reference DDL in [schema-postgres.sql](docs/schema-postgres.sql).
|
||||
4. Open **Assistant → Knowledge sources** as an `assistant.admin`. Add the table,
|
||||
comma-separated text fields, optional title field and QQQ query-filter JSON,
|
||||
embedding model, and chunk size/overlap (defaults 1500/200). Tables with AI data
|
||||
access NONE, `assistant_*` tables, and fields with NONE/METADATA_ONLY exposure
|
||||
are refused. MASKED fields are masked before embedding and in snippets.
|
||||
5. Select **Index now**. Review makes no embedding calls; Result reports records
|
||||
seen, chunks embedded, unchanged, removed and errors. Re-running unchanged
|
||||
content sends no embeddings. A complete successful scan removes disappeared
|
||||
records; failed scans preserve unvisited entries. **Clear index** removes only
|
||||
that source's vectors. Changes after indexing are read fresh, but semantic
|
||||
ranking becomes current only after re-indexing.
|
||||
|
||||
Embedding usage has purpose `EMBED`, counts toward budgets, and observes the kill
|
||||
switch and provider concurrency limits. PHI sources and queries in PHI
|
||||
conversations require an eligible embedding provider; the eligibility flag is an
|
||||
operator assertion, as for chat. Automatic budget downgrades cannot change an
|
||||
embedding model's vector space, so an incompatible downgrade stops the call.
|
||||
|
||||
Scheduling is deferred to P-g. Its designated-user runner can call
|
||||
`RagService.index` within that user's authenticated context; P-f creates no system
|
||||
session, stored admin credentials, scheduler or background content crawler.
|
||||
Data tools call the QQQ UI API through `UiApiToolbox` and `UiApiGateway` with the signed-in user's session. The UI enforces permissions and record security; the assistant further narrows access and caps and redacts returned values. Data tool results reach the model wrapped as untrusted data. Only record-free navigation and help use the core AI tool kernel.
|
||||
|
||||
## Requirements
|
||||
@@ -61,6 +192,15 @@ The key never goes in config, tables or logs. It lives in the application's secr
|
||||
|
||||
The provider's `toString` never contains the key. Its errors carry only the HTTP status and the API error type.
|
||||
|
||||
### Starter defaults
|
||||
|
||||
Include `db/liquibase/qbit-assistant/assistant-defaults.changelog.sql` (shipped in
|
||||
the jar) after your assistant DDL. A new installation then has a policy row, a
|
||||
default profile with four starter skills, a $50/month instance budget, current
|
||||
Anthropic prices and a disabled example scheduled task. Every row is insert-only,
|
||||
so administrators can edit them freely. The home's **Setup** card shows what is
|
||||
set up and the next step for the rest (usually: add a provider).
|
||||
|
||||
## Provider settings (the Providers table)
|
||||
|
||||
Admins set up providers on the **Providers** screen (`assistant_provider`), a standard QQQ table:
|
||||
@@ -126,6 +266,8 @@ The nav lists the home and the main tables: **Providers**, **Conversations**, **
|
||||
| `providerTestTimeoutSeconds` | 30 | How long Test connection waits for the model. |
|
||||
| `homeMaxRows` | 20000 | Rows per table the app home reads for its period; it says when totals are partial. |
|
||||
| `tablePathPrefix` | `/app` | The front of the links the app home makes to tables and records. |
|
||||
| `emailExternalApproved` | `false` | Stands in for the EXTERNAL approval rule (not built yet): scheduled-task result email is sent only when `true`. |
|
||||
| `emailRecipientResolver` | owner id if it is an address | Hook: task owner user id to email address. |
|
||||
|
||||
At runtime, an admin can override the kill switch, the main model and effort, and the budgets in the single **`assistant_policy`** row.
|
||||
|
||||
@@ -384,12 +526,30 @@ engine/tool golden turns. No cloud credentials or live endpoints are required.
|
||||
Apache 2.0.
|
||||
|
||||
|
||||
## Email through qbit-email
|
||||
|
||||
When the optional [qbit-email](https://github.com/QRun-IO/qbit-email) is on the classpath **and** produced in the instance, a finished scheduled-task run can be emailed to its owner. Without it nothing changes: `AssistantEmail.sendScheduledResult` returns `NOT_AVAILABLE`. The dependency is `optional`; every reference to it is in `AssistantEmailSender`.
|
||||
|
||||
This integration uses qbit-email **0.1.0-RC.2** through its published `com.kingsrook.qbits.email.api` package. Scheduled tasks (P-g) are available, but the runner does not yet wire email delivery. Hosts can call `AssistantEmail.sendScheduledResult(qInstance, config, new ScheduledResultNotice(...))` after a run, supplying its owner, classification, absolute run link and explicit opt-in as `emailResult`. Persisting a task-level email opt-in and wiring the runner remain a separate integration step.
|
||||
|
||||
Gates, in order (each returns a status and queues nothing):
|
||||
1. the task opted in (`NOT_REQUESTED`);
|
||||
2. qbit-email is installed (`NOT_AVAILABLE`);
|
||||
3. `emailExternalApproved` is `true` (`NOT_APPROVED`). The EXTERNAL approval rule exists only in the spec, so this explicit flag gates it until the rule is built;
|
||||
4. a recipient resolves (`NO_RECIPIENT`): `emailRecipientResolver` maps the owner's user id to an address; by default an owner id that already is an address is used.
|
||||
|
||||
What is sent, one message per recipient, idempotency key `assistant:scheduled:<run id>`, linked record the run:
|
||||
- result classified PUBLIC (or none): template `assistant_scheduled_result` (NOTIFICATION, Markdown, registered on first send and never overwritten) with the task name, run time, a summary cut to 280 characters and a link to the run. The full model output is never emailed;
|
||||
- result classified above PUBLIC (core's `DataClassification`): only the link, through qbit-email's `email_secure_message` pattern. No task name, summary or output.
|
||||
|
||||
The outbox result maps to `QUEUED`, `DUPLICATE`, `SUPPRESSED` or `REFUSED` (for example a link that is not absolute http(s)). Addresses and bodies are never logged.
|
||||
|
||||
## Data classification and HIPAA mode
|
||||
|
||||
On QQQ 4.1.0-RC.5, classify application tables/fields in the host configuration:
|
||||
Classify application tables and fields in core's AI metadata (`AiTableMetaData` / `AiFieldMetaData`, QQQ 4.1.0-RC.6), or in the host configuration (a configured value wins when both are set):
|
||||
|
||||
```java
|
||||
import com.kingsrook.qbits.assistant.classification.DataClassification;
|
||||
import com.kingsrook.qqq.backend.core.actions.ai.DataClassification;
|
||||
|
||||
AssistantQBitConfig config = new AssistantQBitConfig()
|
||||
.withDataClassification("patient", DataClassification.PHI)
|
||||
@@ -407,8 +567,8 @@ The existing server-side `withSecretResolver` hook also resolves this reference.
|
||||
Startup validates the key. HIPAA mode defaults off; encryption can also be enabled
|
||||
with the key reference while HIPAA mode is off.
|
||||
|
||||
The qbit `DataClassification` enum is a stand-in for core QRun-IO/qqq#1142, with
|
||||
PUBLIC < CONFIDENTIAL < PII < PHI. Unconfigured tables default to PUBLIC; a field
|
||||
The levels are core's `DataClassification` (PUBLIC < CONFIDENTIAL < PII < PHI); the
|
||||
qbit's former stand-in enum is gone. Unconfigured tables default to PUBLIC; a field
|
||||
falls back to its table unless explicitly overridden. A field subset uses its
|
||||
selected fields; unrestricted reads and record page contexts use the highest
|
||||
classification across the table and its fields. Returned columns and record-label
|
||||
@@ -417,10 +577,9 @@ explicitly if the host considers it safe for that subset. Cross-table results wi
|
||||
tables use the highest classification anywhere. Metadata-only tools remain PUBLIC.
|
||||
The assistant's own tables remain denied to tools.
|
||||
|
||||
Hosts can supply `withClassificationSource(ClassificationSource)` instead. When
|
||||
upgrading to an RC containing core #1142, implement that interface with
|
||||
`AiDataClassifications`/`AiTableMetaData`/`AiFieldMetaData` (map enum names), then
|
||||
replace the stand-in once the qbit's minimum core version includes it.
|
||||
The default `ClassificationSource` reads core's metadata (`AiDataClassifications`,
|
||||
`AiTableMetaData`, `AiFieldMetaData`) merged with the configured map; configuration
|
||||
wins when both are set. Hosts can still supply `withClassificationSource(ClassificationSource)`.
|
||||
|
||||
PHI is sent only to a persisted provider row explicitly marked `hipaaEligible`.
|
||||
Every model dispatch rechecks eligibility, including calls after tools and strict
|
||||
@@ -489,6 +648,45 @@ health is probed when unknown/stale with a two-second timeout. Provider cards sh
|
||||
health and down-until, failures show fallback totals, and turn records show the
|
||||
route and final destination. See [UPGRADE.md](UPGRADE.md) for the additive schema.
|
||||
|
||||
## Scheduled tasks
|
||||
|
||||
Administrators configure recurring prompts in **Assistant → Scheduled tasks**.
|
||||
Tasks use Quartz cron syntax (for example `0 0 8 * * ?`) and an IANA timezone
|
||||
(for example `America/Chicago`; default `UTC`). Tasks start disabled.
|
||||
|
||||
```java
|
||||
config.withUiApiBaseUrl("http://127.0.0.1:8000")
|
||||
.withScheduledTasksSchedulerName("hostScheduler")
|
||||
.withAllowedScheduledCredentialEnvNames(Set.of("ASSISTANT_SCHEDULED_TOKEN"));
|
||||
```
|
||||
|
||||
Provide a long-lived access token accepted by the host's authentication provider
|
||||
in that environment variable. Store only its **name** on the task and set
|
||||
`runAsUserId` to the corresponding QQQ user id. The runner posts the token to
|
||||
`/qqq/v1/manageSession`, reads its session cookie and verifies the returned
|
||||
session's user before starting a new conversation. No system session reads user
|
||||
data. Configure the loopback URL at startup; a scheduled job cannot rely on a
|
||||
browser having visited first.
|
||||
|
||||
For kof22, provision a designated Authentik account with the intended application
|
||||
permissions, obtain a token that kof22's QQQ authentication provider accepts as an
|
||||
`accessToken`, and inject it through the existing secret-manager/ExternalSecret
|
||||
pipeline. An Authentik management API token is suitable only if the host's auth
|
||||
adapter explicitly accepts it. Rotate the token in the secret manager, never in
|
||||
the task table. This feature does not provision an account or token.
|
||||
|
||||
**Run now**, **Approve write mode** and **Revoke write mode** are Review/Result
|
||||
record actions. Write approval names the designated user and displays the exact
|
||||
prompt SHA-256. Changing prompt, user, credential reference, profile or write-mode
|
||||
request clears approval. Scheduled writes always wait for that user's panel
|
||||
confirmation, even if normal policy disables confirmation.
|
||||
|
||||
Each run keeps an owner-locked audit row and a normal conversation. RECORD adds
|
||||
no notification; NOTIFICATION and BOTH also notify the designated user through
|
||||
the optional Alerts QBit SPI. Without Alerts, notification delivery is log-only.
|
||||
HIPAA summaries are always `see conversation`. Cost caps stop at dispatch
|
||||
boundaries, so the last completed call can cross the cap; no further call starts.
|
||||
Apply the [P-g migration](UPGRADE.md#p-g-scheduled-tasks) before enabling jobs.
|
||||
### Answer presentation
|
||||
|
||||
The always-available `present_results` tool turns retrieved results into metrics,
|
||||
@@ -501,3 +699,44 @@ skills can extend the built-in presentation instructions. See the
|
||||
The image-breakdown golden task also runs in the existing opt-in live provider suite:
|
||||
`./mvnw verify -Dassistant.live=true -Dtest.excludedGroups= -Dgroups=live -Djacoco.skip=true -pl qbit-assistant-provider-anthropic -am`
|
||||
(with `ANTHROPIC_API_KEY` set). Live calls are excluded from normal verification.
|
||||
|
||||
### Record history and the assistant channel
|
||||
|
||||
Core's default `ClientChannelsMetaData` denies `audit*` to the `assistant`
|
||||
channel. Accordingly, `get_record_history` is offered only when all three audit
|
||||
tables it queries (`auditTable`, `audit`, and `auditDetail`) exist and are not
|
||||
channel-denied, including their effective permission rules. A host that intends
|
||||
to expose record history can opt in during instance configuration:
|
||||
|
||||
```java
|
||||
new AssistantQBitConfig()
|
||||
.withRecordHistory(true);
|
||||
```
|
||||
|
||||
This is an owner decision and a hard wall: record history defaults to disabled;
|
||||
**kof22 does not opt in**. On QQQ RC.6, the opt-in removes exactly `audit*`
|
||||
from the assistant's denied patterns (the former manual configuration step).
|
||||
RC.6 does not add a separate channel write denial for audits. On later RCs that
|
||||
include QRun-IO/qqq#1193, it calls `withAssistantAuditReads()`, which allows audit
|
||||
reads but denies audit writes. The user's own audit permissions still apply.
|
||||
Other patterns, including `worm_audit_*`, `assistant_*`, and security surfaces,
|
||||
remain untouched, as do explicit object and permission-rule denials.
|
||||
|
||||
History visibility uses core's `isDenied` read/all-operation check. RC.6 has no
|
||||
operation argument; the later write-only deny patterns must remain separate
|
||||
from that check so they do not hide the read tool.
|
||||
|
||||
## In-app help
|
||||
|
||||
The QBit registers [`help/qbit-assistant.yaml`](qbit-assistant/src/main/resources/help/qbit-assistant.yaml)
|
||||
with QQQ's help-bundle registry during production. Hosts with help content storage use QQQ's
|
||||
startup bundle sync; registration is harmless when the host has no `helpContent` table.
|
||||
|
||||
To customize the wording, register a separate bundle with `layer: HOST` using
|
||||
`HelpBundles.register(qInstance, "help/my-application.yaml")`. Entries with the same key and
|
||||
role override this QBIT bundle. User-edited help remains protected by core's sync.
|
||||
Keep live `{{...}}` references so labels and metadata values follow the host's configuration.
|
||||
|
||||
`AssistantTablesGuardrailTest.everyOwnedTargetHasBundleHelp` checks coverage and live references
|
||||
against the produced test instance with `HelpBundleAssertions`; it runs in the normal Maven build.
|
||||
Update the bundle's literal version alongside the artifact version when releasing.
|
||||
+213
@@ -1,5 +1,218 @@
|
||||
# Upgrading qbit-assistant
|
||||
|
||||
## Transcript redaction (Unreleased)
|
||||
|
||||
Apply the transcript-redaction column widening block in `docs/schema-postgres.sql`
|
||||
to existing databases. Stop reasons, request IDs, tool-call IDs, feedback/data-audit/
|
||||
budget-override reasons and scheduled-run summaries/errors now use `TEXT`; token
|
||||
expansion must not fail a write or truncate secured-data tokens. The corresponding
|
||||
entity field limits are removed, including pending-action and tool-result summaries.
|
||||
|
||||
## Foreign keys (2026-10-14)
|
||||
|
||||
Recommended: apply the "Foreign keys" block at the end of
|
||||
`docs/schema-postgres.sql` (after the index audit). It is guarded and safe to re-run.
|
||||
- Adds the missing foreign keys across the conversation tables, usage, data audit,
|
||||
budget accounting and profile skills, with the indexes they need.
|
||||
- Detail rows of a conversation `CASCADE`; the message/turn cycle, usage and the data
|
||||
audit use `SET NULL`, so usage keeps its cost rows when a conversation is deleted.
|
||||
- Usage, budget accounting and the data audit hold their provider (`NO ACTION`):
|
||||
disable a provider with history instead of deleting it.
|
||||
- `assistant_model.provider_id` changes from `NO ACTION` to `CASCADE`
|
||||
(constraint renamed `fk_assistant_model_provider`).
|
||||
- Rows that point at a missing parent are first copied to `qqq_fk_quarantine`
|
||||
(created if absent), then nulled, or deleted for the `NOT NULL` profile-skill
|
||||
links. Check that table after the upgrade.
|
||||
|
||||
No code change.
|
||||
|
||||
## Index audit (2026-10-14)
|
||||
|
||||
Recommended, not required: apply the "Index audit" block at the end of
|
||||
`docs/schema-postgres.sql`. It adds six indexes, every one `IF NOT EXISTS`:
|
||||
- usage by turn (read on each scheduled run)
|
||||
- the three retention date filters (turn events, tool calls, inactive conversations)
|
||||
- the two `ON DELETE SET NULL` foreign keys on `assistant_scheduled_run`
|
||||
|
||||
No code change.
|
||||
|
||||
## Durable turns (Unreleased)
|
||||
|
||||
Apply the **Durable turns** block at the end of `docs/schema-postgres.sql` before
|
||||
starting the new runtime. It adds nullable `heartbeat_at`, `lease_owner`,
|
||||
`cancel_requested_at`, `phase`, `concurrency_mode` and the `(user_id, status)`
|
||||
index. A partial unique index on terminal events also prevents two replicas from
|
||||
inserting separate `message.end` frames for the same turn. Check for historical
|
||||
duplicate terminal frames before applying it (resolve any duplicates through your
|
||||
normal migration process). Fresh installs run the full schema, including ALTERs.
|
||||
Existing rows with no heartbeat use `started_at` for lease expiry. During the
|
||||
first upgrade from a runtime without heartbeats, drain old replicas' turns first:
|
||||
a new replica cannot distinguish an old live turn from a dead owner after 45 s.
|
||||
|
||||
Defaults: heartbeat 5 s, lease 45 s, hard duration 300 s, force-finalization grace
|
||||
20 s, shutdown grace 8 s. Configure these through the corresponding
|
||||
`AssistantQBitConfig` withers. Heartbeat must be shorter than the lease. The JVM
|
||||
shutdown hook is enabled by default; tests disable `registerShutdownHook` and
|
||||
managed hosts may call `runtime.shutdown(Duration)` themselves. Give the process
|
||||
termination budget enough time for the configured shutdown grace and persistence.
|
||||
|
||||
`POST /conversations/{id}/turns` accepts `concurrency: "supersede" | "concurrent"`
|
||||
(case-insensitive). Default `SUPERSEDE` stops prior runs in that conversation;
|
||||
`CONCURRENT` permits them. The default per-user cap is now 3; reaching it stops
|
||||
the oldest run instead of returning the old in-progress 429. Per-minute and
|
||||
budget 429 responses still apply. Superseded turns record `cancelReason=SUPERSEDED`.
|
||||
|
||||
Cancel now returns HTTP **200**, including for terminal turns, with the current
|
||||
`status`. The OpenAPI fragment retains the old 202 response for mixed-version
|
||||
rollouts. Active runs are discoverable through `GET /qqq/v1/assistant/turns/active`;
|
||||
reattach through the existing events route. Consumers should recognize
|
||||
`turn.phase` and `message.start.startedAt`. Starts during shutdown return
|
||||
503 `SHUTTING_DOWN`; clients may retry against a ready replica.
|
||||
|
||||
Hosts may wire `AssistantRunTracker` for Jobs tray publication, progress, Stop,
|
||||
and terminal notification. It is a no-op by default and all callbacks are
|
||||
isolated from turn execution. Tracking ids are local to the owning runtime;
|
||||
reaping an already dead owner does not invent another tracking job. Hosts should
|
||||
associate their durable tracking row with the supplied turn id. The SPI is a
|
||||
stand-in for QQQ #1210.
|
||||
|
||||
## Starter defaults, setup card and table help
|
||||
|
||||
The jar now ships `db/liquibase/qbit-assistant/assistant-defaults.changelog.sql`.
|
||||
Include it from the host's master changelog **after** the changesets that create
|
||||
the `assistant_*` tables:
|
||||
|
||||
```yaml
|
||||
- include: { file: db/liquibase/qbit-assistant/assistant-defaults.changelog.sql }
|
||||
```
|
||||
|
||||
It is insert-only and never changes a host that already configured the
|
||||
assistant: the policy, the **$50/month instance budget** (warn 80%, downgrade
|
||||
100%, stop 120%) and the Anthropic list prices are seeded only into empty tables,
|
||||
and the `default` profile only when no default profile exists. Price rows take
|
||||
precedence over `AssistantQBitConfig.withPricing`, which is why they are seeded
|
||||
only when there are none. The four starter skills and a disabled example
|
||||
scheduled task are always added (by name); on a host with its own default
|
||||
profile the skills are not linked to it, and the Setup card says so. Requires
|
||||
Liquibase 4.x or later (preconditions are `sql-check`s).
|
||||
|
||||
No DDL changes. New: the Assistant home's Setup card, the `assistant_data_access`
|
||||
table action **Add rows for every table** (`assistantDataAccessAddDefaults`,
|
||||
admin only) and bundle help on every assistant table (`help/qbit-assistant.yaml`).
|
||||
|
||||
## X1/Y1: channel wall and audit attribution
|
||||
|
||||
Requires QQQ 4.1.0-RC.6. Every assistant table, process, report and widget is
|
||||
explicitly denied to channel `assistant`; startup rejects an exposed object.
|
||||
Host customizations must preserve these denials. Administration uses `next-ui`.
|
||||
|
||||
Before enabling `AuditsMetaDataProvider.withClientChannelField(true)`, add the
|
||||
nullable `audit.client_channel VARCHAR(100)` column using the host migration
|
||||
conventions. kof22 needs a feature changeset under `changesets/features/` (for
|
||||
example `2026-10-14-audit-client-channel.sql`); no host migration is applied here.
|
||||
Existing audit rows remain null. The test fixture enables the field.
|
||||
|
||||
The existing `assistant_tool_call.auditHref` column now points to audit rows
|
||||
filtered by record, table and client channel, including for deletes. It is empty
|
||||
when the host has not enabled the audit channel field. Apply the X1/Y1 DDL in
|
||||
`docs/schema-postgres.sql` to widen the existing `assistant_tool_call.audit_href`
|
||||
column to TEXT: encoded filters with long table names or string record ids can
|
||||
exceed the old 500-character limit. No new QBit column is required. `GET /assistant/access` accepts an optional owned `turnId` for attribution.
|
||||
|
||||
## Provider API extraction (#30)
|
||||
|
||||
**BREAKING:** every provider API type now lives in the exclusive package
|
||||
`com.kingsrook.qbits.assistant.spi`. Update imports and recompile consumers.
|
||||
Hosts still receive `qbit-assistant-provider-api` transitively from `qbit-assistant`.
|
||||
No schema migration is needed.
|
||||
|
||||
| Old import | New import |
|
||||
|---|---|
|
||||
| `com.kingsrook.qbits.assistant.provider.X` (API types) | `com.kingsrook.qbits.assistant.spi.X` |
|
||||
| `com.kingsrook.qbits.assistant.engine.ModelPricing` | `com.kingsrook.qbits.assistant.spi.ModelPricing` |
|
||||
|
||||
Internal classes such as `provider.RegistryModelProvider` and
|
||||
`provider.fake.ScriptedModelProvider` stay in the runtime and are not API types.
|
||||
External consumers such as qbit-marketing depend only on
|
||||
`com.kingsrook.qbits:qbit-assistant-provider-api` for these contracts and allow
|
||||
package `com.kingsrook.qbits.assistant.spi` in their guardrails. qbit-bom will add
|
||||
this package to the G1 defaults.
|
||||
|
||||
External providers and applications using only provider/pricing types should
|
||||
replace their `qbit-assistant` dependency with
|
||||
`com.kingsrook.qbits:qbit-assistant-provider-api` at the same version. This removes
|
||||
the assistant runtime and QQQ from that dependency path; only Jackson annotations
|
||||
are required by the API. Anthropic, OpenAI, Bedrock and Vertex adapters use this
|
||||
split; pgvector retains `qbit-assistant` for its runtime RAG interfaces.
|
||||
|
||||
Recompile custom provider types that override `validate(AssistantProvider)` and
|
||||
change the signature to `validate(ProviderSettings)`. The settings carry the
|
||||
configured kind, URL, API version, region, project, CA bundle name, timeouts and
|
||||
`apiKeyEnvName`; the key and bearer-token supplier are not resolved for validation.
|
||||
Providers using the default validator need only the import migration. Keep the runtime and
|
||||
provider artifacts on the same version; old validator overrides must be rebuilt.
|
||||
## P-g: scheduled tasks
|
||||
|
||||
Apply the **P-g** DDL in [docs/schema-postgres.sql](docs/schema-postgres.sql)
|
||||
before deploying. The unique `(task_id, scheduled_for)` constraint is required
|
||||
for multi-replica safety; retain run rows as schedule-slot claim history.
|
||||
Existing conversations default to channel `panel`. Tasks start disabled.
|
||||
|
||||
Set `withScheduledTasksSchedulerName(...)` to an existing QQQ scheduler and
|
||||
configure `withUiApiBaseUrl(...)` with this replica's own listener URL. The runner
|
||||
polls every 60 seconds. QQQ must supply a scheduler session able to manage the
|
||||
assistant tables; this QBit never creates that session. The configured backend
|
||||
must enforce unique keys atomically (Postgres does).
|
||||
|
||||
Allow only designated credential references with
|
||||
`withAllowedScheduledCredentialEnvNames(Set.of("ASSISTANT_SCHEDULED_TOKEN"))`.
|
||||
Provide that variable through the host's secret manager. It must hold a token
|
||||
accepted by the host's `manageSession` authentication provider for `runAsUserId`.
|
||||
The runner fails closed on missing/disallowed credentials or an identity mismatch.
|
||||
See [scheduled-task setup](README.md#scheduled-tasks) for kof22 provisioning.
|
||||
|
||||
QQQ RC.5 has no conditional UpdateInput. The runner uses a database-unique
|
||||
schedule-slot insertion as its optimistic claim, then advances `nextRunAt`
|
||||
before starting work. Crashes can skip a slot; they never retry it. No ArchUnit
|
||||
exception or fabricated session is introduced. Core RC.6 enforces client-channel denials; scheduled requests carry
|
||||
`assistant/scheduled/<taskId>`.
|
||||
|
||||
Notifications use the optional Alerts QBit notification SPI with a single-user
|
||||
audience. Without it, delivery logs run id/status only. All output modes retain
|
||||
the owner-locked audit row and conversation. HIPAA run summaries never copy the
|
||||
answer; they contain only `see conversation`.
|
||||
|
||||
## P-f: knowledge retrieval
|
||||
|
||||
Apply the **P-f** assistant-table DDL in
|
||||
[docs/schema-postgres.sql](docs/schema-postgres.sql) before deployment. It adds
|
||||
`assistant_model.model_kind` (existing rows default to CHAT),
|
||||
`embedding_dimensions`, and the admin-only `assistant_rag_source` table.
|
||||
No sources are seeded. Existing chat selections remain unchanged; explicitly
|
||||
EMBEDDING models are excluded from chat, classifier, fallback and downgrade
|
||||
selection. Correct discovery's kind/dimensions if a model name is ambiguous.
|
||||
|
||||
For persistent vectors, add `qbit-assistant-rag-pgvector` at the same version as
|
||||
the QBit, supply the host's JDBC DataSource/driver, and install pgvector in the
|
||||
database. A DBA runs `CREATE EXTENSION IF NOT EXISTS vector`; the application
|
||||
role needs schema creation rights for initial setup (or a DBA-created schema),
|
||||
then normal DML rights. `ensureSchema()` checks for an existing extension first
|
||||
and does not require extension installation privileges when it is already present.
|
||||
The optional pgvector DDL is a **commented reference block**, separate from the
|
||||
assistant-table migration. See [RAG setup](README.md#rag-setup).
|
||||
|
||||
Use a distinct validated schema for each QQQ instance. `vector(N)` fixes dimensions
|
||||
for that store; changing dimensions requires a new schema and re-indexing.
|
||||
Sources can use different models with that dimension; ranking is restricted to
|
||||
sources using the query's model. If the weights behind an unchanged model id
|
||||
change, clear and rebuild its sources. Editing source chunk/filter/model settings
|
||||
or registry model identity/dimensions automatically clears affected vectors.
|
||||
|
||||
Every indexing batch produces EMBED usage and updates existing budget rollups.
|
||||
PHI source content and PHI conversation queries require a HIPAA-eligible embedding
|
||||
provider. No background runner or designated credentials are installed in P-f.
|
||||
The default in-memory store is lost on restart and must be indexed again.
|
||||
|
||||
## P-e: profile routing and provider fallback
|
||||
|
||||
Apply the additive **P-e** ALTER TABLE statements at the end of
|
||||
|
||||
+193
-6
@@ -16,6 +16,13 @@ All of it is in standard QQQ tables with full record screens (D6), prefixed `ass
|
||||
|
||||
`assistant_turn` keeps the per-turn totals and `assistant_usage_daily` the budget rollups, as before. `assistant_usage` adds the per-call detail the home needs: the provider, the failures and latency.
|
||||
|
||||
## Provider SPI boundary
|
||||
|
||||
All provider contracts and value types, including `ModelPricing`, belong exclusively
|
||||
to `com.kingsrook.qbits.assistant.spi` in `qbit-assistant-provider-api`. Consumers
|
||||
can depend on this artifact alone and allow its package in G1. Runtime provider
|
||||
registry and fake implementations remain in their existing internal packages.
|
||||
|
||||
## API keys
|
||||
|
||||
Decision: **reference, not storage.** A provider row holds the NAME of an environment variable (`apiKeyEnvName`); `ProviderService` resolves it through `config.getSecretResolver()` (default `System::getenv`) when it builds a client.
|
||||
@@ -59,7 +66,7 @@ The result goes on the row (`lastTest*`) and into `assistant_usage` (`TEST`), so
|
||||
|
||||
## Cost
|
||||
|
||||
`cost = input × in + output × out + cacheRead × read + cacheWrite5m × w5 + cacheWrite1h × w1`, in micro-dollars, rounded up (`ModelPricing.costMicros`).
|
||||
`cost = input × in + output × out + cacheRead × read + cacheWrite5m × w5 + cacheWrite1h × w1`, in micro-dollars, rounded up (`com.kingsrook.qbits.assistant.spi.ModelPricing.costMicros`).
|
||||
|
||||
Prices come from the `assistant_model_price` row for (type, model). Empty cache prices are 0.1x, 1.25x and 2x the input price. A model without a row uses the `pricing` config map, else costs 0. A price change affects later calls only; each usage row keeps the cost it was recorded with.
|
||||
|
||||
@@ -143,7 +150,7 @@ Owner: *"the agent should have to go through the same API that the UIUX does. th
|
||||
- A request to the server's own port runs the identical pipeline by construction. It costs one local hop, which is milliseconds next to a model call.
|
||||
|
||||
This matches core's design (`docs/UI-API-EXTENSIONS.md` §5, `UiApiInvoker`, QRun-IO/qqq#1128).
|
||||
- `LoopbackUiApiGateway` is the stand-in until a QQQ release has the invoker. Then an adapter over `UiApiInvoker.forServer(server)` replaces it (or a host injects one with `withUiApiGateway`), and nothing else changes.
|
||||
- `CoreUiApiGateway` adapts core's `UiApiInvoker` (the loopback stand-in is deleted). It labels calls with the client channel `assistant`, plus the turn id as detail (`assistant/<turnId>`). Form params go to the invoker's `withFormParam`; extra headers (the bulk-load tools' `X-QQQ-AI-Route`) go through `HeaderedUiApiInvoker`, a small subclass in core's package because core's request has no `withHeader` yet. A host can still inject its own gateway with `withUiApiGateway`.
|
||||
- The base URL is `uiApiBaseUrl` if configured. Otherwise it is `127.0.0.1` plus the local port the first assistant request arrived on, so in a multi-replica deployment the call stays on the replica that holds the session's process state.
|
||||
|
||||
### The tools
|
||||
@@ -228,6 +235,18 @@ The golden and red-team evals now run through the UI API too.
|
||||
- Choosing *another* user would need that user's permissions without their session. QQQ core has no API to evaluate another user's permissions, and the assistant never builds or borrows a session. That part waits for a core API, so the report is always computed with the requester's own session.
|
||||
- **Recent denials:** the home's "Recent denials" card lists the newest tool calls the UI API, data access or the policy refused, with who, the table, the operation and the HTTP status, or the assistant setting that refused it.
|
||||
|
||||
## Spec'd assistant endpoints and the core invoker (phase d, QQQ 4.1.0-RC.6)
|
||||
|
||||
- **The endpoints are spec'd `/qqq/v1` operations.** `api/specs/AssistantSpecs` registers the UI API extension `assistant` (semver 1.0.0, established prefix `/assistant`) through `MiddlewareSpecExtensionsMetaData`.
|
||||
- The URLs, bodies and statuses stay the same (201 create, 202 cancel, 204 delete and feedback, and the assistant's `{"error","code"}` errors), so Next needs no change.
|
||||
- They appear in the served `/qqq/v1/openapi.yaml`. The turn and events streams are declared as `text/event-stream`, with `AssistantTurnEventV1` describing the events.
|
||||
- The fragment is committed as `qbit-assistant/src/main/resources/openapi/qqq-v1/assistant.yaml`. `AssistantSpecsContractTest` checks it against the code, and the release baseline in test resources, with core's `UiApiContract`.
|
||||
- **No raw routes.** `AssistantRouteProvider` keeps only a before-handler that learns the server's local port from the first `/qqq/v1` request.
|
||||
- **Tools call core's `UiApiInvoker`** (`CoreUiApiGateway`), and the loopback stand-in is removed.
|
||||
- The request's credentials (`UiApiCredentials.fromContext`: session cookies, Authorization, API key, exactly as they came in) are captured by the spec that starts the turn, confirms an action or explains access. They are passed to the tools, so OAuth2, table auth and API-key sessions all work. They are never logged.
|
||||
- The gateway also refuses the assistant's own operations, so a turn can never start a turn.
|
||||
- QQQ 4.1.0-RC.6 (the default `qqq.snapshot.version`) contains #1128, so no local build is needed.
|
||||
|
||||
## Owner decisions (2026-10-13), continued: write mode, the hard wall, audit attribution, providers
|
||||
|
||||
These were added on the same day. All recommendations below are accepted; we adjust once they can be seen working.
|
||||
@@ -275,6 +294,14 @@ AI exposure NONE is not enough, because the assistant acts as the user and an ad
|
||||
- **Tests:** an assistant write produces audit rows with the human actor and `via=assistant/<turnId>`; the same write from the UI produces `via=next-ui`.
|
||||
- kof22 needs a feature-named changeset (`changesets/features/...`) for the audit column.
|
||||
|
||||
### X1/Y1 as built
|
||||
- Record history is an explicit, default-off host opt-in (`withRecordHistory(true)`); kof22 does not opt in. RC.6 removes only `audit*`; later core #1193 support allows audit reads with a write-only denial. Other walls and user audit permissions remain intact.
|
||||
- RC.6's invoker fixes the `assistant` channel server-side and ignores spoofed client headers. Turn context survives knowledge discovery, RAG reads, confirm actions and owned-turn explain-access; scheduled calls retain `scheduled/<taskId>`.
|
||||
- The producer enumerates assistant tables, processes, reports and widgets (including source-QBit metadata), adds explicit denied-client rules without replacing user permissions, and registers `assistant_*` idempotently. Runtime construction independently validates the wall with core's `isDenied` and fails on exposed objects.
|
||||
- The fixture enables core's audit channel field. Hosts must migrate the nullable audit column before enabling it; kof22 needs its own feature changeset.
|
||||
- Successful insert/update/delete tool calls link to `/app/audit` with `recordId`, `auditTable.name` and `clientChannel` criteria, using the same encoder as `present_results`. Hosts without the channel field get no audit link. Existing audit link storage widens to TEXT for long encoded filters.
|
||||
- HTTP tests enumerate the configuration denial matrix for an admin, contrast Next UI access, reject broken startup metadata, and verify confirmed-write actor/channel plus the decoded audit filter.
|
||||
|
||||
### P. Providers, local models, HIPAA routing, budgets
|
||||
1. **Providers and models as data, any number, each with an enabled toggle.**
|
||||
- Kinds:
|
||||
@@ -354,10 +381,8 @@ AI exposure NONE is not enough, because the assistant acts as the user and an ad
|
||||
|
||||
### P-c as built
|
||||
|
||||
- The qbit classification enum is a stand-in for core #1142 until a released RC
|
||||
includes it. Configured table/field overrides are the default; hosts can supply
|
||||
a `ClassificationSource` over core metadata, mapping enum names, then replace
|
||||
the stand-in when the minimum QQQ version advances.
|
||||
- The qbit classification stand-in is gone: the levels are core's `actions.ai.DataClassification` (QQQ 4.1.0-RC.6, core #1142).
|
||||
The default `ClassificationSource` reads core metadata (`AiDataClassifications`, `AiTableMetaData`, `AiFieldMetaData`) merged with the configured table/field map; configuration wins when both are set. Hosts can still supply their own source with `withClassificationSource`.
|
||||
- Turn/page/tool classification is monotonic, persisted on the turn and retained
|
||||
on the conversation. Field subsets use overrides; unknown cross-table results
|
||||
conservatively use the highest configured level. Metadata tools stay PUBLIC.
|
||||
@@ -422,6 +447,139 @@ AI exposure NONE is not enough, because the assistant acts as the user and an ad
|
||||
- Admin record screens, additive Postgres DDL and the flow-layout home expose these
|
||||
settings and counters without granting AI access to assistant configuration.
|
||||
|
||||
### P-f as built
|
||||
|
||||
- `AssistantModelProvider.embed` is optional and unsupported by default. The
|
||||
OpenAI-compatible implementation shares chat's JDK HTTP authentication, TLS,
|
||||
Azure deployment paths, timeout and sanitized error mapping. A request accepts
|
||||
1–64 inputs; `EmbeddingService` batches larger jobs and records each call as
|
||||
EMBED, including daily rollups and provider/model budget accounting.
|
||||
- Registry rows have CHAT/EMBEDDING kinds and embedding dimensions. Legacy rows
|
||||
remain CHAT. Discovery suggests EMBEDDING for ids containing embed, bge, e5,
|
||||
gte or nomic; administrators can correct it. Chat routing/fallback/downgrades
|
||||
cannot select an embedding model. Embedding resolution is explicit and checks
|
||||
fresh provider enablement and HIPAA eligibility before dispatch.
|
||||
- `assistant_rag_source` is an admin-only navigation table. Its text fields must
|
||||
exist and allow VALUES/MASKED exposure; application data access must allow READ.
|
||||
Index now and Clear index are standard streamed ETL record actions with Review
|
||||
and Result, never navigation entries. Indexing pages the UI API as the clicking
|
||||
admin, reuses get_record's masking path, chunks deterministically and compares
|
||||
hashes. Complete scans alone prune disappeared records; per-record replacement
|
||||
also removes obsolete field chunks. Configuration/model identity changes clear
|
||||
stale vectors. No source text is saved on a source or vector row.
|
||||
- `VectorStore` supplies upsert/delete/search/count plus content-free chunk
|
||||
reconciliation and atomic record replacement. The in-memory implementation uses
|
||||
exact cosine; the optional pgvector module uses host JDBC, a validated instance
|
||||
schema, bound values and an HNSW cosine index. Sources from other embedding
|
||||
models are excluded before ranking. The DBA installs pgvector; existing
|
||||
installations do not require extension-installation privileges on startup.
|
||||
- `KnowledgeTool` is separate from the unchanged `UiApiToolbox`. A small
|
||||
ContextBuilder hook adds it only for an enabled source, policy permission and
|
||||
UI-readable source table. Search embeds the question, requests 4× the result
|
||||
limit, then re-reads each hit through get_record with the asking user's session.
|
||||
403/404 hits contribute only to the filtered count. Safe current values produce
|
||||
snippets and `/app` citations; record refs propagate touched tables into P-c
|
||||
classification and the normal tool-call log. The citation instruction is in
|
||||
the static rules block. The result limit is capped at eight.
|
||||
- PHI source content and PHI conversation queries only reach eligible embedding
|
||||
providers. Embedding budgets, kill switch and provider concurrency checks apply
|
||||
to each batch. A budget downgrade into another vector space stops embedding.
|
||||
- Tests exercise real fixture UI API reads, denials, record locks, field masking,
|
||||
PHI refusal, classification, reconciliation, embedding wire contracts and a
|
||||
golden cited answer. JDBC shape/transaction tests always run; a pgvector:pg16
|
||||
Testcontainers test skips on hosts without Docker.
|
||||
- P-g may invoke the manual service within a designated user's authenticated
|
||||
context. P-f supplies no scheduled runner or stored/elevated session. Multiple
|
||||
replicas should serialize manual re-indexing of a source at the host level;
|
||||
per-record pgvector replacement is transactional, while scan reconciliation is
|
||||
not a snapshot of concurrently changing application data.
|
||||
|
||||
### P-g as built
|
||||
|
||||
- `assistant_scheduled_task` is admin-only, AI exposure NONE, and appears as
|
||||
Scheduled tasks. The owner-locked, read-only `assistant_scheduled_run` child
|
||||
list retains run status, accounting and a bounded summary. Conversations gain
|
||||
read-only `scheduledTaskId` and `channel` (`panel` or `assistant/scheduled`).
|
||||
Task and run timestamps use the runtime clock; cron uses Quartz and a validated
|
||||
ZoneId, including DST. Enablement and schedule edits recompute `nextRunAt`.
|
||||
- Credentials are references, never stored tokens. `credentialEnvName` must
|
||||
match `[A-Z_][A-Z0-9_]*` and the dedicated
|
||||
`allowedScheduledCredentialEnvNames` allowlist. The existing secret resolver
|
||||
supplies its value. Read-only `credentialStatus` reports presence without
|
||||
exposing token characters and is stripped on every save.
|
||||
- A run sends JSON `{accessToken: ...}` to the same loopback base URL's
|
||||
`POST /qqq/v1/manageSession`. RC.5 with HTTP-only cookies returns the UUID in
|
||||
`Set-Cookie: sessionUUID`; legacy JSON `uuid` is also accepted. Only then does
|
||||
the runner resolve that UUID through the host authentication module, exactly
|
||||
the UUID lookup used by the UI request pipeline. No direct token authentication,
|
||||
automated-user session or constructed QSession exists in assistant code.
|
||||
The resolved user id must equal `runAsUserId` before any model call. MOCK in
|
||||
the integration fixture maps test tokens to the existing user-prefix sessions;
|
||||
that token adapter is test code only.
|
||||
- kof22 provisions an Authentik designated account with normal QQQ permissions
|
||||
and injects an accepted long-lived token through its secret manager and
|
||||
ExternalSecret into an allow-listed environment variable. The task holds the
|
||||
variable name and QQQ user id. Host authentication must accept that token type
|
||||
as `accessToken`; an Authentik management API token is not automatically an
|
||||
application access token. Neither account nor credential is provisioned here.
|
||||
- `assistantScheduledTasksRunner` registers a 60-second QScheduleMetaData when
|
||||
`scheduledTasksSchedulerName` names a host scheduler. QQQ supplies its normal
|
||||
scheduler context for assistant-table bookkeeping; no ArchUnit exception is
|
||||
necessary. Configure `uiApiBaseUrl` at startup. No browser visit is required.
|
||||
- **Claim compatibility:** RC.5 UpdateInput cannot express a conditional
|
||||
`WHERE next_run_at = expected`. AssistantStore therefore claims the expected
|
||||
schedule slot using the database-enforced unique `(taskId, scheduledFor)` run
|
||||
key and advances `nextRunAt` before login/dispatch. This is a unique-insert
|
||||
optimistic claim rather than a conditional update. The memory fixture also
|
||||
serializes claim operations on its instance. The database constraint, not
|
||||
that monitor, prevents cross-replica duplicate execution. Do not remove claim
|
||||
history or deploy to a backend without atomic unique keys. A crash can lose a
|
||||
run; it never retries a claimed slot. A later tick advances an already-claimed
|
||||
slot left behind by a crash between claim and schedule update.
|
||||
- The unchanged AssistantApi starts a new normal turn under the logged-in
|
||||
designated user, preserving start gates, rate limiting, P-c classification,
|
||||
P-d budgets and P-e routing/fallback. An internal context supplies the task's
|
||||
selected profile and additional cost cap. Cost includes chat, classifier,
|
||||
failed calls and knowledge-query embeddings. STOP is checked at dispatch
|
||||
boundaries; an in-flight call can exceed the cap, and no next call is sent.
|
||||
- Every scheduled UI API request, including metadata and knowledge retrieval,
|
||||
carries `X-QQQ-Client: assistant/scheduled/<taskId>`. The only uiapi change is
|
||||
additive `LoopbackUiApiGateway.invokeWithClient`; custom gateways currently
|
||||
fail closed for scheduled requests because their channel contract is unknown.
|
||||
Tool-call rows also record `clientChannel`. Core channel deny enforcement
|
||||
remains pending the client-channel RC; existing AI exposure/data-access
|
||||
restrictions continue to apply on RC.5.
|
||||
- Approve write mode, Revoke write mode and Run now are admin record actions
|
||||
using standard streamed ETL Review/Result. Review shows the exact prompt's
|
||||
SHA-256 and run-as user. Result rereads and compares the complete reviewed
|
||||
definition before recording the actual administrator's user id and time.
|
||||
A persisted approval hash additionally binds prompt, run-as user, credential
|
||||
reference, profile and requested mode. Editing any of these clears approval;
|
||||
ordinary saves cannot set approval or computed bookkeeping fields.
|
||||
- This base has create/update/delete tools, but no W1 conversation mode/policy
|
||||
switch. Scheduled runs explicitly narrow the existing tool policy: write tools
|
||||
require both request and matching approval, a READ_WRITE table and the policy's
|
||||
allowed-tools list. All scheduled writes require panel confirmation, including
|
||||
when normal policy allows immediate writes. A pending proposal adds a waiting
|
||||
notice to the run summary; the scheduler never confirms it.
|
||||
- RECORD keeps the run and conversation; NOTIFICATION and BOTH also submit an
|
||||
Alerts notification with `NotificationAudience.user(runAsUserId)` and an
|
||||
`/app/...` conversation link. Reflection targets the installed Alerts QBit's
|
||||
RC.5 notification SPI/sink, following WebhooksAlerts' optional-dependency
|
||||
pattern. Without it, a log contains run id and status only. Notification text
|
||||
contains no answer data. In HIPAA mode run summaries contain exactly
|
||||
`see conversation`; conversation payloads retain the existing encryption.
|
||||
The existing record URL is an admin-screen link. Non-admin owners can read
|
||||
their scheduled conversations in the panel's conversation list; opening a
|
||||
particular existing conversation from a notification still needs a frontend
|
||||
deep-link contract (the current panel only supports open/new-prompt links).
|
||||
This phase does not broaden existing conversation record-screen permissions.
|
||||
- Failures close the run as FAILED or BLOCKED with sanitized errors and wait
|
||||
until the next schedule. All output modes retain their audit record. Tests
|
||||
exercise real manageSession and UI API requests with a fixed clock, designated
|
||||
permissions and owner locks, headers, competing runners, approval invalidation,
|
||||
notification modes, PHI refusal, encrypted HIPAA storage and cost STOP.
|
||||
|
||||
### Phases (each a green PR)
|
||||
| | Scope | Depends on |
|
||||
|---|---|---|
|
||||
@@ -479,3 +637,32 @@ The shared golden task asks "How many images do I have by type?": five UI count
|
||||
calls establish 81 JPEG, 20 PNG and zero other configured types, then a presentation
|
||||
with two rows, 80.2%/19.8% shares, two pie points and working MIME filter links.
|
||||
The same task is included in the opt-in `live` Anthropic eval suite.
|
||||
|
||||
|
||||
## Transcript redaction (secured data §15)
|
||||
|
||||
`TranscriptRedactor` collects classified values from tools using `ClassificationSource`,
|
||||
including core table/field metadata. Stored record fields use
|
||||
`ClassifiedValueTokens.forRecordField`; criteria/proposals without a record use
|
||||
`forContext`. Core selects `shred:v1`, `hmac:v1`, or `changed:v1`. Knowledge snippets
|
||||
retain their source field's token. Matching is case-sensitive and includes canonical,
|
||||
displayed, escaped, encoded and explicitly truncated variants.
|
||||
|
||||
`AssistantStore` stages content in turn memory and writes placeholders until
|
||||
finalization, protecting backend writes and their audits. It redacts before truncation
|
||||
and encryption. This covers messages, tool/bulk logs, replay events, pending payloads
|
||||
and audit reasons; scheduled summaries derive from redacted messages. Model requests
|
||||
and live SSE remain unchanged under PHI routing. Persisted text deltas are joined
|
||||
before redaction, with the text in the first delta and remaining deltas empty;
|
||||
sequence numbers remain stable.
|
||||
|
||||
Crashes or unfinished tools at timeout leave placeholders. Proposals remain
|
||||
non-executable (`PREPARING`) until finalization; redacted proposals are rejected and
|
||||
must be completed in the application. A core `LogRedactorInterface` hook covers all
|
||||
threads until the turn and its tool workers finish, then releases the raw values.
|
||||
|
||||
History stays redacted; later turns re-read records. Existing transcripts are not
|
||||
migrated, and arbitrary text is not inferred to be classified without a matching
|
||||
observed value or classified criterion/field. Canary tests scan every assistant table,
|
||||
core audits and captured logs, while proving eligible models receive original values.
|
||||
Requires QQQ 4.1.0-RC.7 (`qqq#1182`); keep the PR draft until publication.
|
||||
+244
-8
@@ -49,7 +49,7 @@ CREATE TABLE assistant_turn
|
||||
status VARCHAR(16),
|
||||
classification VARCHAR(16),
|
||||
classification_tables VARCHAR(500),
|
||||
stop_reason VARCHAR(64),
|
||||
stop_reason TEXT,
|
||||
error_code VARCHAR(32),
|
||||
cancel_reason VARCHAR(64),
|
||||
model VARCHAR(200),
|
||||
@@ -88,7 +88,7 @@ CREATE TABLE assistant_tool_call
|
||||
turn_id INTEGER,
|
||||
conversation_id INTEGER,
|
||||
user_id VARCHAR(255),
|
||||
tool_call_id VARCHAR(128),
|
||||
tool_call_id TEXT,
|
||||
tool_name VARCHAR(64),
|
||||
input_json TEXT,
|
||||
outcome VARCHAR(16),
|
||||
@@ -103,7 +103,7 @@ CREATE TABLE assistant_tool_call
|
||||
redactions_json TEXT,
|
||||
ui_api_operation VARCHAR(255),
|
||||
http_status INTEGER,
|
||||
audit_href VARCHAR(500),
|
||||
audit_href TEXT,
|
||||
pending_action_id INTEGER,
|
||||
create_date TIMESTAMP WITH TIME ZONE
|
||||
);
|
||||
@@ -118,7 +118,7 @@ CREATE TABLE assistant_feedback
|
||||
conversation_id INTEGER,
|
||||
user_id VARCHAR(255),
|
||||
rating INTEGER,
|
||||
reason VARCHAR(64),
|
||||
reason TEXT,
|
||||
comment TEXT,
|
||||
create_date TIMESTAMP WITH TIME ZONE
|
||||
);
|
||||
@@ -267,7 +267,7 @@ CREATE TABLE assistant_usage
|
||||
cache_read_tokens BIGINT,
|
||||
cache_write_tokens BIGINT,
|
||||
cost_micros BIGINT,
|
||||
request_id VARCHAR(100),
|
||||
request_id TEXT,
|
||||
create_date TIMESTAMP WITH TIME ZONE
|
||||
);
|
||||
CREATE INDEX assistant_usage_create_date ON assistant_usage (create_date);
|
||||
@@ -310,7 +310,7 @@ CREATE TABLE assistant_pending_action
|
||||
conversation_id INTEGER,
|
||||
turn_id INTEGER,
|
||||
user_id VARCHAR(255),
|
||||
tool_call_id VARCHAR(128),
|
||||
tool_call_id TEXT,
|
||||
tool_name VARCHAR(64),
|
||||
ui_api_operation VARCHAR(255),
|
||||
table_name VARCHAR(128),
|
||||
@@ -382,7 +382,7 @@ CREATE TABLE assistant_data_audit
|
||||
classification VARCHAR(16),
|
||||
tables VARCHAR(500),
|
||||
decision VARCHAR(16),
|
||||
reason VARCHAR(1000),
|
||||
reason TEXT,
|
||||
create_date TIMESTAMP WITH TIME ZONE
|
||||
);
|
||||
CREATE INDEX assistant_data_audit_user_id ON assistant_data_audit (user_id);
|
||||
@@ -415,7 +415,7 @@ CREATE TABLE assistant_budget_override
|
||||
scope_value VARCHAR(200),
|
||||
extra_value NUMERIC,
|
||||
unlimited_until TIMESTAMP WITH TIME ZONE,
|
||||
reason VARCHAR(1000) NOT NULL,
|
||||
reason TEXT NOT NULL,
|
||||
granted_by VARCHAR(200),
|
||||
expires_at TIMESTAMP WITH TIME ZONE NOT NULL,
|
||||
create_date TIMESTAMP WITH TIME ZONE,
|
||||
@@ -477,3 +477,239 @@ ALTER TABLE assistant_turn ADD COLUMN route_decision VARCHAR(16);
|
||||
ALTER TABLE assistant_turn ADD COLUMN route_source VARCHAR(16);
|
||||
ALTER TABLE assistant_turn ADD COLUMN fallback_count INTEGER DEFAULT 0;
|
||||
ALTER TABLE assistant_turn ADD COLUMN provider_id INTEGER REFERENCES assistant_provider(id);
|
||||
|
||||
|
||||
-- P-f: embedding registry and admin-only knowledge-source configuration.
|
||||
ALTER TABLE assistant_model ADD COLUMN model_kind VARCHAR(16) DEFAULT 'CHAT'
|
||||
CHECK (model_kind IN ('CHAT', 'EMBEDDING'));
|
||||
ALTER TABLE assistant_model ADD COLUMN embedding_dimensions INTEGER
|
||||
CHECK (embedding_dimensions > 0);
|
||||
|
||||
CREATE TABLE assistant_rag_source (
|
||||
id SERIAL PRIMARY KEY,
|
||||
name VARCHAR(200) NOT NULL,
|
||||
enabled BOOLEAN DEFAULT TRUE,
|
||||
table_name VARCHAR(200) NOT NULL,
|
||||
field_names VARCHAR(500) NOT NULL,
|
||||
title_field_name VARCHAR(200),
|
||||
filter_json TEXT,
|
||||
embedding_model_id INTEGER NOT NULL REFERENCES assistant_model(id),
|
||||
chunk_chars INTEGER DEFAULT 1500 CHECK (chunk_chars BETWEEN 100 AND 16000),
|
||||
chunk_overlap_chars INTEGER DEFAULT 200 CHECK (chunk_overlap_chars >= 0 AND chunk_overlap_chars < chunk_chars),
|
||||
last_indexed_at TIMESTAMPTZ,
|
||||
last_index_status VARCHAR(200),
|
||||
last_index_error VARCHAR(500),
|
||||
indexed_record_count INTEGER,
|
||||
indexed_chunk_count INTEGER,
|
||||
create_date TIMESTAMPTZ,
|
||||
modify_date TIMESTAMPTZ
|
||||
);
|
||||
|
||||
-- Optional pgvector part: reference only. Run the extension step as a DBA.
|
||||
-- PgVectorStore.ensureSchema() performs the remainder for the host's schema/N.
|
||||
-- Use a distinct schema per QQQ instance; match N to the embedding model.
|
||||
-- CREATE EXTENSION IF NOT EXISTS vector;
|
||||
-- CREATE SCHEMA IF NOT EXISTS assistant_rag;
|
||||
-- CREATE TABLE IF NOT EXISTS assistant_rag.assistant_rag_chunk (
|
||||
-- id BIGSERIAL PRIMARY KEY,
|
||||
-- source_id INT NOT NULL,
|
||||
-- table_name TEXT NOT NULL,
|
||||
-- record_pk TEXT NOT NULL,
|
||||
-- field_name TEXT NOT NULL,
|
||||
-- chunk_index INT NOT NULL,
|
||||
-- content_hash CHAR(64) NOT NULL,
|
||||
-- embedding vector(1024) NOT NULL,
|
||||
-- indexed_at TIMESTAMPTZ NOT NULL DEFAULT CURRENT_TIMESTAMP,
|
||||
-- UNIQUE(source_id, table_name, record_pk, field_name, chunk_index)
|
||||
-- );
|
||||
-- CREATE INDEX IF NOT EXISTS assistant_rag_chunk_cosine
|
||||
-- ON assistant_rag.assistant_rag_chunk USING hnsw (embedding vector_cosine_ops);
|
||||
|
||||
-- P-g: designated-user scheduled assistant tasks. Install before enabling jobs.
|
||||
CREATE TABLE assistant_scheduled_task (
|
||||
id SERIAL PRIMARY KEY,
|
||||
name VARCHAR(200) NOT NULL,
|
||||
enabled BOOLEAN NOT NULL DEFAULT FALSE,
|
||||
prompt TEXT NOT NULL CHECK (char_length(prompt) BETWEEN 1 AND 4000),
|
||||
run_as_user_id VARCHAR(200) NOT NULL,
|
||||
credential_env_name VARCHAR(200) NOT NULL,
|
||||
credential_status VARCHAR(200), -- computed; always NULL in stored rows
|
||||
profile_id INTEGER REFERENCES assistant_profile(id),
|
||||
cron_expression VARCHAR(200) NOT NULL,
|
||||
timezone VARCHAR(100) NOT NULL DEFAULT 'UTC',
|
||||
next_run_at TIMESTAMPTZ,
|
||||
output_mode VARCHAR(20) NOT NULL DEFAULT 'RECORD' CHECK (output_mode IN ('RECORD', 'NOTIFICATION', 'BOTH')),
|
||||
write_mode_requested BOOLEAN NOT NULL DEFAULT FALSE,
|
||||
write_mode_approved_by VARCHAR(200),
|
||||
write_mode_approved_at TIMESTAMPTZ,
|
||||
write_mode_approval_hash VARCHAR(64),
|
||||
max_cost_usd_per_run NUMERIC(18,6) CHECK (max_cost_usd_per_run >= 0),
|
||||
last_run_at TIMESTAMPTZ,
|
||||
last_run_status VARCHAR(20),
|
||||
last_run_error VARCHAR(500),
|
||||
create_date TIMESTAMPTZ,
|
||||
modify_date TIMESTAMPTZ
|
||||
);
|
||||
CREATE INDEX assistant_scheduled_task_due ON assistant_scheduled_task(next_run_at) WHERE enabled;
|
||||
|
||||
ALTER TABLE assistant_conversation ADD COLUMN scheduled_task_id INTEGER REFERENCES assistant_scheduled_task(id);
|
||||
ALTER TABLE assistant_conversation ADD COLUMN channel VARCHAR(64) NOT NULL DEFAULT 'panel';
|
||||
ALTER TABLE assistant_tool_call ADD COLUMN client_channel VARCHAR(64);
|
||||
|
||||
CREATE TABLE assistant_scheduled_run (
|
||||
id SERIAL PRIMARY KEY,
|
||||
task_id INTEGER NOT NULL REFERENCES assistant_scheduled_task(id),
|
||||
user_id VARCHAR(200) NOT NULL,
|
||||
scheduled_for TIMESTAMPTZ NOT NULL,
|
||||
started_at TIMESTAMPTZ,
|
||||
ended_at TIMESTAMPTZ,
|
||||
status VARCHAR(20) NOT NULL CHECK (status IN ('RUNNING', 'OK', 'FAILED', 'SKIPPED', 'BLOCKED')),
|
||||
conversation_id INTEGER REFERENCES assistant_conversation(id) ON DELETE SET NULL,
|
||||
turn_id INTEGER REFERENCES assistant_turn(id) ON DELETE SET NULL,
|
||||
summary TEXT,
|
||||
cost_micros BIGINT,
|
||||
error TEXT,
|
||||
create_date TIMESTAMPTZ,
|
||||
modify_date TIMESTAMPTZ,
|
||||
UNIQUE (task_id, scheduled_for)
|
||||
);
|
||||
CREATE INDEX assistant_scheduled_run_owner ON assistant_scheduled_run(user_id, started_at);
|
||||
|
||||
-- X1/Y1: encoded audit filters can exceed the old 500-character record links.
|
||||
ALTER TABLE assistant_tool_call ALTER COLUMN audit_href TYPE TEXT;
|
||||
|
||||
|
||||
-- Durable turns: apply this additive block before deploying the new runtime.
|
||||
-- Like earlier additions, fresh installs run the CREATEs followed by ALTERs.
|
||||
ALTER TABLE assistant_turn ADD COLUMN heartbeat_at TIMESTAMP;
|
||||
ALTER TABLE assistant_turn ADD COLUMN lease_owner VARCHAR(100);
|
||||
ALTER TABLE assistant_turn ADD COLUMN cancel_requested_at TIMESTAMP;
|
||||
ALTER TABLE assistant_turn ADD COLUMN phase VARCHAR(64);
|
||||
ALTER TABLE assistant_turn ADD COLUMN concurrency_mode VARCHAR(16);
|
||||
CREATE INDEX assistant_turn_user_status ON assistant_turn (user_id, status);
|
||||
|
||||
-- Fence concurrent orphan reapers at the database boundary. A turn ends once.
|
||||
-- Check for pre-existing duplicate message.end rows before applying this index.
|
||||
CREATE UNIQUE INDEX assistant_turn_event_terminal ON assistant_turn_event (turn_id)
|
||||
WHERE event_type = 'message.end';
|
||||
|
||||
-- Index audit (2026-10-14): lookup, retention and FK paths with no leading index.
|
||||
-- ScheduledTurn.cost reads usage by turn on every scheduled run.
|
||||
CREATE INDEX IF NOT EXISTS assistant_usage_turn ON assistant_usage (turn_id);
|
||||
-- Retention: deleteTurnEventsBefore, clearToolResultsBefore and listConversationsInactiveSince filter by date.
|
||||
CREATE INDEX IF NOT EXISTS assistant_turn_event_create_date ON assistant_turn_event (create_date);
|
||||
CREATE INDEX IF NOT EXISTS assistant_tool_call_create_date ON assistant_tool_call (create_date);
|
||||
CREATE INDEX IF NOT EXISTS assistant_conversation_modify_date ON assistant_conversation (modify_date);
|
||||
-- ON DELETE SET NULL children: deleting a conversation or turn would scan scheduled runs without these.
|
||||
CREATE INDEX IF NOT EXISTS assistant_scheduled_run_conversation ON assistant_scheduled_run (conversation_id);
|
||||
CREATE INDEX IF NOT EXISTS assistant_scheduled_run_turn ON assistant_scheduled_run (turn_id);
|
||||
|
||||
-- Foreign keys (2026-10-14). Run on new and existing databases; every step is guarded
|
||||
-- and re-runnable. The rules follow how the qbit deletes:
|
||||
-- * AssistantStore.deleteConversation (also the retention purge) deletes turn events,
|
||||
-- tool calls, feedback, messages, turns, data audit and pending actions, then the
|
||||
-- conversation. The conversation's own detail rows CASCADE, so an admin delete of a
|
||||
-- conversation cleans up the same way.
|
||||
-- * The message <-> turn cycle (turn.user_message_id / assistant_message_id and
|
||||
-- message.turn_id) and the other optional pointers are SET NULL. Rows are inserted
|
||||
-- parent first, so nothing is deferred.
|
||||
-- * assistant_usage keeps its cost rows when a conversation goes (SET NULL), and the
|
||||
-- data audit trail is never cascaded into (SET NULL).
|
||||
-- * Provider references from usage, budget accounting and the data audit are NO ACTION
|
||||
-- (like assistant_turn.provider_id): disable a provider with history, do not delete
|
||||
-- it. A provider's model rows are its own (CASCADE).
|
||||
-- * assistant_budget_usage.usage_id has no foreign key on purpose: the projection
|
||||
-- outlives its usage row so budgets keep counting the spend.
|
||||
-- Rows that already point at a missing parent are recorded in qqq_fk_quarantine first,
|
||||
-- then nulled (nullable columns) or deleted with the full row recorded (NOT NULL).
|
||||
CREATE INDEX IF NOT EXISTS assistant_message_parent_message ON assistant_message (parent_message_id);
|
||||
CREATE INDEX IF NOT EXISTS assistant_message_turn ON assistant_message (turn_id);
|
||||
CREATE INDEX IF NOT EXISTS assistant_turn_user_message ON assistant_turn (user_message_id);
|
||||
CREATE INDEX IF NOT EXISTS assistant_turn_assistant_message ON assistant_turn (assistant_message_id);
|
||||
CREATE INDEX IF NOT EXISTS assistant_turn_provider ON assistant_turn (provider_id);
|
||||
CREATE INDEX IF NOT EXISTS assistant_tool_call_pending_action ON assistant_tool_call (pending_action_id);
|
||||
CREATE INDEX IF NOT EXISTS assistant_feedback_message ON assistant_feedback (message_id);
|
||||
CREATE INDEX IF NOT EXISTS assistant_pending_action_turn ON assistant_pending_action (turn_id);
|
||||
CREATE INDEX IF NOT EXISTS assistant_data_audit_provider ON assistant_data_audit (provider_id);
|
||||
CREATE INDEX IF NOT EXISTS assistant_budget_usage_provider ON assistant_budget_usage (provider_id);
|
||||
CREATE INDEX IF NOT EXISTS assistant_profile_skill_skill ON assistant_profile_skill (skill_id);
|
||||
CREATE INDEX IF NOT EXISTS assistant_budget_downgrade_model ON assistant_budget (downgrade_model_id);
|
||||
CREATE INDEX IF NOT EXISTS assistant_conversation_scheduled_task ON assistant_conversation (scheduled_task_id);
|
||||
CREATE INDEX IF NOT EXISTS assistant_model_fallback_model ON assistant_model (fallback_model_id);
|
||||
CREATE INDEX IF NOT EXISTS assistant_profile_simple_model ON assistant_profile (simple_model_id);
|
||||
CREATE INDEX IF NOT EXISTS assistant_profile_complex_model ON assistant_profile (complex_model_id);
|
||||
CREATE INDEX IF NOT EXISTS assistant_profile_classifier_model ON assistant_profile (classifier_model_id);
|
||||
CREATE INDEX IF NOT EXISTS assistant_rag_source_embedding_model ON assistant_rag_source (embedding_model_id);
|
||||
CREATE INDEX IF NOT EXISTS assistant_scheduled_task_profile ON assistant_scheduled_task (profile_id);
|
||||
|
||||
CREATE TABLE IF NOT EXISTS qqq_fk_quarantine (id BIGINT GENERATED BY DEFAULT AS IDENTITY PRIMARY KEY, table_name VARCHAR(100) NOT NULL, column_name VARCHAR(100) NOT NULL, row_id VARCHAR(100), missing_parent_id VARCHAR(100), action VARCHAR(20) NOT NULL, row_data TEXT, changeset VARCHAR(200), quarantined_at TIMESTAMP DEFAULT CURRENT_TIMESTAMP);
|
||||
|
||||
DO $$
|
||||
DECLARE
|
||||
r RECORD;
|
||||
old TEXT;
|
||||
BEGIN
|
||||
FOR r IN SELECT * FROM (VALUES
|
||||
('assistant_message', 'conversation_id', 'assistant_conversation', 'CASCADE', TRUE),
|
||||
('assistant_message', 'parent_message_id', 'assistant_message', 'SET NULL', TRUE),
|
||||
('assistant_message', 'turn_id', 'assistant_turn', 'SET NULL', TRUE),
|
||||
('assistant_turn', 'conversation_id', 'assistant_conversation', 'CASCADE', TRUE),
|
||||
('assistant_turn', 'user_message_id', 'assistant_message', 'SET NULL', TRUE),
|
||||
('assistant_turn', 'assistant_message_id', 'assistant_message', 'SET NULL', TRUE),
|
||||
('assistant_turn_event', 'turn_id', 'assistant_turn', 'CASCADE', TRUE),
|
||||
('assistant_tool_call', 'conversation_id', 'assistant_conversation', 'CASCADE', TRUE),
|
||||
('assistant_tool_call', 'turn_id', 'assistant_turn', 'CASCADE', TRUE),
|
||||
('assistant_tool_call', 'pending_action_id', 'assistant_pending_action', 'SET NULL', TRUE),
|
||||
('assistant_feedback', 'conversation_id', 'assistant_conversation', 'CASCADE', TRUE),
|
||||
('assistant_feedback', 'message_id', 'assistant_message', 'CASCADE', TRUE),
|
||||
('assistant_pending_action', 'conversation_id', 'assistant_conversation', 'CASCADE', TRUE),
|
||||
('assistant_pending_action', 'turn_id', 'assistant_turn', 'SET NULL', TRUE),
|
||||
('assistant_data_audit', 'conversation_id', 'assistant_conversation', 'SET NULL', TRUE),
|
||||
('assistant_data_audit', 'turn_id', 'assistant_turn', 'SET NULL', TRUE),
|
||||
('assistant_usage', 'conversation_id', 'assistant_conversation', 'SET NULL', TRUE),
|
||||
('assistant_usage', 'turn_id', 'assistant_turn', 'SET NULL', TRUE),
|
||||
('assistant_usage', 'provider_id', 'assistant_provider', 'NO ACTION', TRUE),
|
||||
('assistant_data_audit', 'provider_id', 'assistant_provider', 'NO ACTION', TRUE),
|
||||
('assistant_budget_usage', 'provider_id', 'assistant_provider', 'NO ACTION', TRUE),
|
||||
('assistant_profile_skill', 'profile_id', 'assistant_profile', 'CASCADE', FALSE),
|
||||
('assistant_profile_skill', 'skill_id', 'assistant_skill', 'CASCADE', FALSE)
|
||||
) AS v(child, col, parent, rule, nullable)
|
||||
LOOP
|
||||
IF NOT EXISTS (SELECT 1 FROM information_schema.table_constraints WHERE constraint_schema = current_schema() AND LOWER(constraint_name) = 'fk_' || r.child || '_' || r.col) THEN
|
||||
IF r.nullable THEN
|
||||
EXECUTE format('INSERT INTO qqq_fk_quarantine (table_name, column_name, row_id, missing_parent_id, action, changeset) '
|
||||
|| 'SELECT %L, %L, c.id::text, c.%I::text, ''NULLED'', ''qbit-assistant 2026-10-14 foreign keys'' FROM %I c '
|
||||
|| 'WHERE c.%I IS NOT NULL AND NOT EXISTS (SELECT 1 FROM %I p WHERE p.id = c.%I)', r.child, r.col, r.col, r.child, r.col, r.parent, r.col);
|
||||
EXECUTE format('UPDATE %I c SET %I = NULL WHERE c.%I IS NOT NULL AND NOT EXISTS (SELECT 1 FROM %I p WHERE p.id = c.%I)', r.child, r.col, r.col, r.parent, r.col);
|
||||
ELSE
|
||||
EXECUTE format('INSERT INTO qqq_fk_quarantine (table_name, column_name, row_id, missing_parent_id, action, row_data, changeset) '
|
||||
|| 'SELECT %L, %L, c.id::text, c.%I::text, ''DELETED'', row_to_json(c)::text, ''qbit-assistant 2026-10-14 foreign keys'' FROM %I c '
|
||||
|| 'WHERE NOT EXISTS (SELECT 1 FROM %I p WHERE p.id = c.%I)', r.child, r.col, r.col, r.child, r.parent, r.col);
|
||||
EXECUTE format('DELETE FROM %I c WHERE NOT EXISTS (SELECT 1 FROM %I p WHERE p.id = c.%I)', r.child, r.parent, r.col);
|
||||
END IF;
|
||||
EXECUTE format('ALTER TABLE %I ADD CONSTRAINT %I FOREIGN KEY (%I) REFERENCES %I (id) ON DELETE %s', r.child, 'fk_' || r.child || '_' || r.col, r.col, r.parent, r.rule);
|
||||
END IF;
|
||||
END LOOP;
|
||||
|
||||
-- assistant_model.provider_id: the inline NO ACTION key becomes CASCADE, named as on kof22.
|
||||
IF NOT EXISTS (SELECT 1 FROM information_schema.table_constraints WHERE constraint_schema = current_schema() AND LOWER(constraint_name) = 'fk_assistant_model_provider') THEN
|
||||
FOR old IN SELECT conname FROM pg_constraint
|
||||
WHERE contype = 'f' AND conrelid = 'assistant_model'::regclass AND confrelid = 'assistant_provider'::regclass
|
||||
LOOP
|
||||
EXECUTE format('ALTER TABLE assistant_model DROP CONSTRAINT %I', old);
|
||||
END LOOP;
|
||||
ALTER TABLE assistant_model ADD CONSTRAINT fk_assistant_model_provider FOREIGN KEY (provider_id) REFERENCES assistant_provider (id) ON DELETE CASCADE;
|
||||
END IF;
|
||||
END $$;
|
||||
|
||||
-- Transcript redaction: tokens can expand beyond the original payload bounds.
|
||||
-- Apply to existing databases as well; SET DATA TYPE is also valid in H2.
|
||||
ALTER TABLE assistant_turn ALTER COLUMN stop_reason SET DATA TYPE TEXT;
|
||||
ALTER TABLE assistant_tool_call ALTER COLUMN tool_call_id SET DATA TYPE TEXT;
|
||||
ALTER TABLE assistant_feedback ALTER COLUMN reason SET DATA TYPE TEXT;
|
||||
ALTER TABLE assistant_usage ALTER COLUMN request_id SET DATA TYPE TEXT;
|
||||
ALTER TABLE assistant_pending_action ALTER COLUMN tool_call_id SET DATA TYPE TEXT;
|
||||
ALTER TABLE assistant_data_audit ALTER COLUMN reason SET DATA TYPE TEXT;
|
||||
ALTER TABLE assistant_budget_override ALTER COLUMN reason SET DATA TYPE TEXT;
|
||||
ALTER TABLE assistant_scheduled_run ALTER COLUMN summary SET DATA TYPE TEXT;
|
||||
ALTER TABLE assistant_scheduled_run ALTER COLUMN error SET DATA TYPE TEXT;
|
||||
@@ -35,3 +35,8 @@ Light and dark, 390 and 1440 px:
|
||||
- `p-provider-local-*`: Local GPU (Ollama), keyless LOCAL settings, discovery/test results and discovered models.
|
||||
- `p-model-*`: a discovered model's capabilities, compute prices and connection-test result.
|
||||
- `p-home-providers-*`: the home's provider summary and usage from the executed demo calls, including disabled OpenRouter with its key Not set.
|
||||
|
||||
Answer presentation (owner priority, 2026-10-13), taken against `OpenAiDemoServer` with the Next UI build of QRun-IO/qqq-frontend-next#111 (`next dev` proxied to the demo). The demo's OpenAI-compatible mock answers "How many images do I have by type?" the way a model would through the real adapter: five `count_records` calls through the UI API, then `present_results`.
|
||||
|
||||
Light and dark, 390 and 1440 px:
|
||||
- `panel-presentation-*`: the summary line, an Images metric, the "Media by type" table (counts and the server-computed 80.2% and 19.8%, each row a filtered-list link), the pie chart, two filter links (Open JPEG media, Open PNG media) and a follow-up action.
|
||||
Binary file not shown.
|
After Width: | Height: | Size: 124 KiB |
Binary file not shown.
|
After Width: | Height: | Size: 44 KiB |
Binary file not shown.
|
After Width: | Height: | Size: 126 KiB |
Binary file not shown.
|
After Width: | Height: | Size: 42 KiB |
@@ -28,6 +28,8 @@
|
||||
<anthropic.version>2.71.0</anthropic.version>
|
||||
<archunit.version>1.5.1</archunit.version>
|
||||
<jackson.version>2.21.7</jackson.version>
|
||||
<!-- optional email delivery; qbit-email from Maven Central -->
|
||||
<qbit-email.version>0.1.0-RC.2</qbit-email.version>
|
||||
<!-- live evals call the real API; run them with -Dtest.excludedGroups= -Dgroups=live -->
|
||||
<test.excludedGroups>live</test.excludedGroups>
|
||||
</properties>
|
||||
@@ -35,7 +37,7 @@
|
||||
<parent>
|
||||
<groupId>com.kingsrook</groupId>
|
||||
<artifactId>qbit-build-parent</artifactId>
|
||||
<version>2.0.0</version>
|
||||
<version>2.1.1</version>
|
||||
</parent>
|
||||
|
||||
<groupId>com.kingsrook.qbits</groupId>
|
||||
@@ -50,11 +52,13 @@
|
||||
<modelVersion>4.0.0</modelVersion>
|
||||
|
||||
<modules>
|
||||
<module>qbit-assistant-provider-api</module>
|
||||
<module>qbit-assistant</module>
|
||||
<module>qbit-assistant-provider-anthropic</module>
|
||||
<module>qbit-assistant-provider-openai</module>
|
||||
<module>qbit-assistant-provider-bedrock</module>
|
||||
<module>qbit-assistant-provider-vertex</module>
|
||||
<module>qbit-assistant-rag-pgvector</module>
|
||||
</modules>
|
||||
|
||||
<licenses>
|
||||
@@ -84,6 +88,11 @@
|
||||
|
||||
<dependencyManagement>
|
||||
<dependencies>
|
||||
<dependency>
|
||||
<groupId>com.kingsrook.qbits</groupId>
|
||||
<artifactId>qbit-assistant-provider-api</artifactId>
|
||||
<version>${revision}</version>
|
||||
</dependency>
|
||||
<dependency>
|
||||
<groupId>com.kingsrook.qbits</groupId>
|
||||
<artifactId>qbit-assistant-provider-anthropic</artifactId>
|
||||
@@ -193,8 +202,9 @@
|
||||
</build>
|
||||
|
||||
<profiles>
|
||||
<!-- The assistant needs QQQ 4.1.0-RC.5: the AI tool kernel (package -->
|
||||
<!-- actions.ai, qqq#1078) and the developer panels (qqq#1076). Until -->
|
||||
<!-- The assistant needs QQQ 4.1.0-RC.7: the AI tool kernel (qqq#1078), the -->
|
||||
<!-- developer panels (qqq#1076) and the UI API extension point, invoker -->
|
||||
<!-- and credentials (qqq#1128). Until -->
|
||||
<!-- qbit-build-parent imports the 4.1 BOM, this -->
|
||||
<!-- profile is active by default and imports qqq-bom-pom ahead of the -->
|
||||
<!-- parent's 4.0.0 BOM, as in qbit-quick-search (ADR-0007). Override with -->
|
||||
@@ -205,7 +215,8 @@
|
||||
<activeByDefault>true</activeByDefault>
|
||||
</activation>
|
||||
<properties>
|
||||
<qqq.snapshot.version>4.1.0-RC.5</qqq.snapshot.version>
|
||||
<!-- RC.7 provides classified-value tokens, log redaction and native help bundles. -->
|
||||
<qqq.snapshot.version>4.1.0-RC.7</qqq.snapshot.version>
|
||||
</properties>
|
||||
<dependencyManagement>
|
||||
<dependencies>
|
||||
|
||||
@@ -32,9 +32,14 @@
|
||||
<url>https://github.com/QRun-IO/qbit-assistant</url>
|
||||
|
||||
<dependencies>
|
||||
<dependency>
|
||||
<groupId>com.kingsrook.qbits</groupId>
|
||||
<artifactId>qbit-assistant-provider-api</artifactId>
|
||||
</dependency>
|
||||
<dependency>
|
||||
<groupId>com.kingsrook.qbits</groupId>
|
||||
<artifactId>qbit-assistant</artifactId>
|
||||
<scope>test</scope>
|
||||
</dependency>
|
||||
<dependency>
|
||||
<groupId>com.kingsrook.qqq</groupId>
|
||||
|
||||
+9
-9
@@ -40,15 +40,15 @@ import com.anthropic.models.messages.ToolUseBlock;
|
||||
import com.anthropic.models.messages.ToolUseBlockParam;
|
||||
import com.anthropic.models.messages.Usage;
|
||||
import com.fasterxml.jackson.core.type.TypeReference;
|
||||
import com.kingsrook.qbits.assistant.provider.CacheHint;
|
||||
import com.kingsrook.qbits.assistant.provider.ModelMessage;
|
||||
import com.kingsrook.qbits.assistant.provider.ModelPart;
|
||||
import com.kingsrook.qbits.assistant.provider.ModelProviderException;
|
||||
import com.kingsrook.qbits.assistant.provider.ModelRequest;
|
||||
import com.kingsrook.qbits.assistant.provider.ModelResponse;
|
||||
import com.kingsrook.qbits.assistant.provider.ModelToolDefinition;
|
||||
import com.kingsrook.qbits.assistant.provider.ModelUsage;
|
||||
import com.kingsrook.qbits.assistant.provider.SystemBlock;
|
||||
import com.kingsrook.qbits.assistant.spi.CacheHint;
|
||||
import com.kingsrook.qbits.assistant.spi.ModelMessage;
|
||||
import com.kingsrook.qbits.assistant.spi.ModelPart;
|
||||
import com.kingsrook.qbits.assistant.spi.ModelProviderException;
|
||||
import com.kingsrook.qbits.assistant.spi.ModelRequest;
|
||||
import com.kingsrook.qbits.assistant.spi.ModelResponse;
|
||||
import com.kingsrook.qbits.assistant.spi.ModelToolDefinition;
|
||||
import com.kingsrook.qbits.assistant.spi.ModelUsage;
|
||||
import com.kingsrook.qbits.assistant.spi.SystemBlock;
|
||||
|
||||
|
||||
/*******************************************************************************
|
||||
|
||||
+8
-8
@@ -29,14 +29,14 @@ import com.anthropic.core.http.StreamResponse;
|
||||
import com.anthropic.helpers.MessageAccumulator;
|
||||
import com.anthropic.models.messages.MessageCreateParams;
|
||||
import com.anthropic.models.messages.RawMessageStreamEvent;
|
||||
import com.kingsrook.qbits.assistant.provider.AssistantModelProvider;
|
||||
import com.kingsrook.qbits.assistant.provider.CompletableStreamHandle;
|
||||
import com.kingsrook.qbits.assistant.provider.ModelCapabilities;
|
||||
import com.kingsrook.qbits.assistant.provider.ModelEventListener;
|
||||
import com.kingsrook.qbits.assistant.provider.ModelProviderException;
|
||||
import com.kingsrook.qbits.assistant.provider.ModelRequest;
|
||||
import com.kingsrook.qbits.assistant.provider.ModelUsage;
|
||||
import com.kingsrook.qbits.assistant.provider.StreamHandle;
|
||||
import com.kingsrook.qbits.assistant.spi.AssistantModelProvider;
|
||||
import com.kingsrook.qbits.assistant.spi.CompletableStreamHandle;
|
||||
import com.kingsrook.qbits.assistant.spi.ModelCapabilities;
|
||||
import com.kingsrook.qbits.assistant.spi.ModelEventListener;
|
||||
import com.kingsrook.qbits.assistant.spi.ModelProviderException;
|
||||
import com.kingsrook.qbits.assistant.spi.ModelRequest;
|
||||
import com.kingsrook.qbits.assistant.spi.ModelUsage;
|
||||
import com.kingsrook.qbits.assistant.spi.StreamHandle;
|
||||
import com.kingsrook.qqq.backend.core.logging.QLogger;
|
||||
import com.kingsrook.qqq.backend.core.utils.StringUtils;
|
||||
import static com.kingsrook.qqq.backend.core.logging.LogUtils.logPair;
|
||||
|
||||
+2
-2
@@ -18,8 +18,8 @@ package com.kingsrook.qbits.assistant.provider.anthropic;
|
||||
|
||||
|
||||
import java.util.List;
|
||||
import com.kingsrook.qbits.assistant.provider.AssistantModelProvider;
|
||||
import com.kingsrook.qbits.assistant.provider.AssistantProviderType;
|
||||
import com.kingsrook.qbits.assistant.spi.AssistantModelProvider;
|
||||
import com.kingsrook.qbits.assistant.spi.AssistantProviderType;
|
||||
|
||||
|
||||
/*******************************************************************************
|
||||
|
||||
+10
-10
@@ -24,16 +24,16 @@ import java.util.LinkedHashMap;
|
||||
import java.util.List;
|
||||
import java.util.Map;
|
||||
import com.fasterxml.jackson.core.type.TypeReference;
|
||||
import com.kingsrook.qbits.assistant.provider.CacheHint;
|
||||
import com.kingsrook.qbits.assistant.provider.ModelEventListener;
|
||||
import com.kingsrook.qbits.assistant.provider.ModelMessage;
|
||||
import com.kingsrook.qbits.assistant.provider.ModelPart;
|
||||
import com.kingsrook.qbits.assistant.provider.ModelProviderException;
|
||||
import com.kingsrook.qbits.assistant.provider.ModelRequest;
|
||||
import com.kingsrook.qbits.assistant.provider.ModelResponse;
|
||||
import com.kingsrook.qbits.assistant.provider.ModelToolDefinition;
|
||||
import com.kingsrook.qbits.assistant.provider.StreamHandle;
|
||||
import com.kingsrook.qbits.assistant.provider.SystemBlock;
|
||||
import com.kingsrook.qbits.assistant.spi.CacheHint;
|
||||
import com.kingsrook.qbits.assistant.spi.ModelEventListener;
|
||||
import com.kingsrook.qbits.assistant.spi.ModelMessage;
|
||||
import com.kingsrook.qbits.assistant.spi.ModelPart;
|
||||
import com.kingsrook.qbits.assistant.spi.ModelProviderException;
|
||||
import com.kingsrook.qbits.assistant.spi.ModelRequest;
|
||||
import com.kingsrook.qbits.assistant.spi.ModelResponse;
|
||||
import com.kingsrook.qbits.assistant.spi.ModelToolDefinition;
|
||||
import com.kingsrook.qbits.assistant.spi.StreamHandle;
|
||||
import com.kingsrook.qbits.assistant.spi.SystemBlock;
|
||||
import com.kingsrook.qqq.backend.core.utils.JsonUtils;
|
||||
import org.junit.jupiter.api.AfterEach;
|
||||
import org.junit.jupiter.api.BeforeEach;
|
||||
|
||||
+3
-3
@@ -26,10 +26,10 @@ import java.util.Set;
|
||||
import com.anthropic.core.ObjectMappers;
|
||||
import com.fasterxml.jackson.core.type.TypeReference;
|
||||
import com.kingsrook.qbits.assistant.AssistantQBitConfig;
|
||||
import com.kingsrook.qbits.assistant.provider.ModelProviderException;
|
||||
import com.kingsrook.qbits.assistant.provider.ModelRequest;
|
||||
import com.kingsrook.qbits.assistant.provider.ModelToolDefinition;
|
||||
import com.kingsrook.qbits.assistant.provider.fake.ScriptedModelProvider;
|
||||
import com.kingsrook.qbits.assistant.spi.ModelProviderException;
|
||||
import com.kingsrook.qbits.assistant.spi.ModelRequest;
|
||||
import com.kingsrook.qbits.assistant.spi.ModelToolDefinition;
|
||||
import com.kingsrook.qbits.assistant.testing.AssistantTestFixture;
|
||||
import com.kingsrook.qbits.assistant.testing.TurnRunner;
|
||||
import com.kingsrook.qqq.backend.core.context.QContext;
|
||||
|
||||
+5
@@ -24,6 +24,7 @@ import com.kingsrook.qbits.assistant.testing.GoldenTasks;
|
||||
import com.kingsrook.qbits.assistant.testing.TurnRunner;
|
||||
import com.kingsrook.qqq.backend.core.context.QContext;
|
||||
import com.kingsrook.qqq.backend.core.model.metadata.QInstance;
|
||||
import com.kingsrook.qqq.backend.core.model.metadata.permissions.ClientChannelsMetaData;
|
||||
import org.junit.jupiter.api.AfterEach;
|
||||
import org.junit.jupiter.api.BeforeEach;
|
||||
import org.junit.jupiter.api.Tag;
|
||||
@@ -102,6 +103,10 @@ class LiveGoldenEvalTest
|
||||
@MethodSource("tasks")
|
||||
void live(GoldenTasks.Task task) throws Exception
|
||||
{
|
||||
if("D-page-12-this-week".equals(task.id()))
|
||||
{
|
||||
ClientChannelsMetaData.ofOrWithNew(qInstance).getDeniedPatterns().get("assistant").remove("audit*");
|
||||
}
|
||||
TurnRunner.Outcome outcome = new TurnRunner(qInstance, config).run(task.userId(), task.prompt());
|
||||
assertThat(outcome.errorCode()).as("error").isNull();
|
||||
task.liveCheck().accept(outcome);
|
||||
|
||||
+1
-1
@@ -24,7 +24,6 @@ import java.util.Map;
|
||||
import java.util.Set;
|
||||
import com.kingsrook.qbits.assistant.AssistantQBitConfig;
|
||||
import com.kingsrook.qbits.assistant.engine.ConnectionTest;
|
||||
import com.kingsrook.qbits.assistant.engine.ModelPricing;
|
||||
import com.kingsrook.qbits.assistant.metadata.AssistantMetaDataBuilder;
|
||||
import com.kingsrook.qbits.assistant.model.AssistantModelPrice;
|
||||
import com.kingsrook.qbits.assistant.model.AssistantProvider;
|
||||
@@ -32,6 +31,7 @@ import com.kingsrook.qbits.assistant.provider.anthropic.AnthropicModelProvider;
|
||||
import com.kingsrook.qbits.assistant.provider.anthropic.AnthropicProviderType;
|
||||
import com.kingsrook.qbits.assistant.provider.anthropic.RecordedAnthropicServer;
|
||||
import com.kingsrook.qbits.assistant.provider.fake.ScriptedModelProvider;
|
||||
import com.kingsrook.qbits.assistant.spi.ModelPricing;
|
||||
import com.kingsrook.qbits.assistant.testing.AssistantTestFixture;
|
||||
import com.kingsrook.qbits.assistant.testing.TurnRunner;
|
||||
import com.kingsrook.qqq.backend.core.actions.tables.InsertAction;
|
||||
|
||||
@@ -0,0 +1,116 @@
|
||||
<?xml version="1.0" encoding="UTF-8"?>
|
||||
<!--
|
||||
~ Copyright 2026 Kingsrook, LLC
|
||||
~
|
||||
~ Licensed under the Apache License, Version 2.0 (the "License");
|
||||
~ you may not use this file except in compliance with the License.
|
||||
~ You may obtain a copy of the License at
|
||||
~
|
||||
~ http://www.apache.org/licenses/LICENSE-2.0
|
||||
~
|
||||
~ Unless required by applicable law or agreed to in writing, software
|
||||
~ distributed under the License is distributed on an "AS IS" BASIS,
|
||||
~ WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
|
||||
~ See the License for the specific language governing permissions and
|
||||
~ limitations under the License.
|
||||
-->
|
||||
|
||||
<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
|
||||
<modelVersion>4.0.0</modelVersion>
|
||||
|
||||
<parent>
|
||||
<groupId>com.kingsrook.qbits</groupId>
|
||||
<artifactId>qbit-assistant-parent</artifactId>
|
||||
<version>${revision}</version>
|
||||
</parent>
|
||||
|
||||
<artifactId>qbit-assistant-provider-api</artifactId>
|
||||
<packaging>jar</packaging>
|
||||
|
||||
<name>QBit Assistant - Provider API</name>
|
||||
<description>Provider SPI and pricing value types, independent of the assistant runtime</description>
|
||||
<url>https://github.com/QRun-IO/qbit-assistant</url>
|
||||
|
||||
<dependencies>
|
||||
<dependency>
|
||||
<groupId>com.fasterxml.jackson.core</groupId>
|
||||
<artifactId>jackson-annotations</artifactId>
|
||||
</dependency>
|
||||
<dependency>
|
||||
<groupId>com.fasterxml.jackson.core</groupId>
|
||||
<artifactId>jackson-databind</artifactId>
|
||||
<scope>test</scope>
|
||||
</dependency>
|
||||
<dependency>
|
||||
<groupId>org.junit.jupiter</groupId>
|
||||
<artifactId>junit-jupiter</artifactId>
|
||||
<scope>test</scope>
|
||||
</dependency>
|
||||
<dependency>
|
||||
<groupId>org.assertj</groupId>
|
||||
<artifactId>assertj-core</artifactId>
|
||||
<scope>test</scope>
|
||||
</dependency>
|
||||
<dependency>
|
||||
<groupId>com.tngtech.archunit</groupId>
|
||||
<artifactId>archunit-junit5</artifactId>
|
||||
<scope>test</scope>
|
||||
</dependency>
|
||||
</dependencies>
|
||||
|
||||
<build>
|
||||
<plugins>
|
||||
<plugin>
|
||||
<groupId>org.apache.maven.plugins</groupId>
|
||||
<artifactId>maven-surefire-plugin</artifactId>
|
||||
<configuration>
|
||||
<redirectTestOutputToFile>true</redirectTestOutputToFile>
|
||||
</configuration>
|
||||
</plugin>
|
||||
<plugin>
|
||||
<groupId>org.jacoco</groupId>
|
||||
<artifactId>jacoco-maven-plugin</artifactId>
|
||||
<executions>
|
||||
<execution>
|
||||
<id>prepare-agent</id>
|
||||
<goals>
|
||||
<goal>prepare-agent</goal>
|
||||
</goals>
|
||||
</execution>
|
||||
<execution>
|
||||
<id>report</id>
|
||||
<phase>verify</phase>
|
||||
<goals>
|
||||
<goal>report</goal>
|
||||
</goals>
|
||||
</execution>
|
||||
<execution>
|
||||
<id>check</id>
|
||||
<goals>
|
||||
<goal>check</goal>
|
||||
</goals>
|
||||
<configuration>
|
||||
<rules>
|
||||
<rule>
|
||||
<element>BUNDLE</element>
|
||||
<limits>
|
||||
<limit>
|
||||
<counter>INSTRUCTION</counter>
|
||||
<value>COVEREDRATIO</value>
|
||||
<minimum>0.70</minimum>
|
||||
</limit>
|
||||
<limit>
|
||||
<counter>CLASS</counter>
|
||||
<value>COVEREDRATIO</value>
|
||||
<minimum>0.90</minimum>
|
||||
</limit>
|
||||
</limits>
|
||||
</rule>
|
||||
</rules>
|
||||
</configuration>
|
||||
</execution>
|
||||
</executions>
|
||||
</plugin>
|
||||
</plugins>
|
||||
</build>
|
||||
</project>
|
||||
+11
-1
@@ -14,7 +14,7 @@
|
||||
* limitations under the License.
|
||||
*/
|
||||
|
||||
package com.kingsrook.qbits.assistant.provider;
|
||||
package com.kingsrook.qbits.assistant.spi;
|
||||
|
||||
|
||||
/*******************************************************************************
|
||||
@@ -58,4 +58,14 @@ public interface AssistantModelProvider
|
||||
return (null);
|
||||
}
|
||||
|
||||
|
||||
|
||||
/*******************************************************************************
|
||||
** Optional embedding capability. Unsupported adapters fail before transport.
|
||||
*******************************************************************************/
|
||||
default EmbeddingResponse embed(EmbeddingRequest request) throws ModelProviderException
|
||||
{
|
||||
throw (new ModelProviderException(ModelProviderException.Kind.INVALID_REQUEST, null, "Embeddings are unsupported by this provider."));
|
||||
}
|
||||
|
||||
}
|
||||
+4
-3
@@ -14,11 +14,10 @@
|
||||
* limitations under the License.
|
||||
*/
|
||||
|
||||
package com.kingsrook.qbits.assistant.provider;
|
||||
package com.kingsrook.qbits.assistant.spi;
|
||||
|
||||
|
||||
import java.util.List;
|
||||
import com.kingsrook.qbits.assistant.model.AssistantProvider;
|
||||
|
||||
|
||||
/*******************************************************************************
|
||||
@@ -140,8 +139,10 @@ public interface AssistantProviderType
|
||||
|
||||
/*******************************************************************************
|
||||
** Additional settings errors, without resolving credentials or doing I/O.
|
||||
** Settings contain configured values and apiKeyEnvName; apiKey, the bearer
|
||||
** token supplier and SSLContext are not resolved for validation.
|
||||
*******************************************************************************/
|
||||
default List<String> validate(AssistantProvider row)
|
||||
default List<String> validate(ProviderSettings settings)
|
||||
{
|
||||
return (List.of());
|
||||
}
|
||||
+1
-1
@@ -14,7 +14,7 @@
|
||||
* limitations under the License.
|
||||
*/
|
||||
|
||||
package com.kingsrook.qbits.assistant.provider;
|
||||
package com.kingsrook.qbits.assistant.spi;
|
||||
|
||||
|
||||
/*******************************************************************************
|
||||
+1
-1
@@ -14,7 +14,7 @@
|
||||
* limitations under the License.
|
||||
*/
|
||||
|
||||
package com.kingsrook.qbits.assistant.provider;
|
||||
package com.kingsrook.qbits.assistant.spi;
|
||||
|
||||
|
||||
import java.time.Duration;
|
||||
+1
-1
@@ -14,7 +14,7 @@
|
||||
* limitations under the License.
|
||||
*/
|
||||
|
||||
package com.kingsrook.qbits.assistant.provider;
|
||||
package com.kingsrook.qbits.assistant.spi;
|
||||
|
||||
|
||||
/*******************************************************************************
|
||||
+39
@@ -0,0 +1,39 @@
|
||||
/*
|
||||
* Copyright 2026 Kingsrook, LLC
|
||||
*
|
||||
* Licensed under the Apache License, Version 2.0 (the "License");
|
||||
* you may not use this file except in compliance with the License.
|
||||
* You may obtain a copy of the License at
|
||||
*
|
||||
* http://www.apache.org/licenses/LICENSE-2.0
|
||||
*
|
||||
* Unless required by applicable law or agreed to in writing, software
|
||||
* distributed under the License is distributed on an "AS IS" BASIS,
|
||||
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
|
||||
* See the License for the specific language governing permissions and
|
||||
* limitations under the License.
|
||||
*/
|
||||
|
||||
package com.kingsrook.qbits.assistant.spi;
|
||||
|
||||
|
||||
import java.util.List;
|
||||
|
||||
|
||||
/*******************************************************************************
|
||||
** One embedding batch. Providers accept at most 64 inputs per request.
|
||||
*******************************************************************************/
|
||||
public record EmbeddingRequest(String model, List<String> input)
|
||||
{
|
||||
/*******************************************************************************
|
||||
** Snapshot the inputs and reject empty or oversized batches before transport.
|
||||
*******************************************************************************/
|
||||
public EmbeddingRequest
|
||||
{
|
||||
input = List.copyOf(input);
|
||||
if(model == null || model.isBlank() || input.isEmpty() || input.size() > 64)
|
||||
{
|
||||
throw (new IllegalArgumentException("An embedding request needs a model and 1 to 64 inputs."));
|
||||
}
|
||||
}
|
||||
}
|
||||
+28
@@ -0,0 +1,28 @@
|
||||
/*
|
||||
* Copyright 2026 Kingsrook, LLC
|
||||
*
|
||||
* Licensed under the Apache License, Version 2.0 (the "License");
|
||||
* you may not use this file except in compliance with the License.
|
||||
* You may obtain a copy of the License at
|
||||
*
|
||||
* http://www.apache.org/licenses/LICENSE-2.0
|
||||
*
|
||||
* Unless required by applicable law or agreed to in writing, software
|
||||
* distributed under the License is distributed on an "AS IS" BASIS,
|
||||
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
|
||||
* See the License for the specific language governing permissions and
|
||||
* limitations under the License.
|
||||
*/
|
||||
|
||||
package com.kingsrook.qbits.assistant.spi;
|
||||
|
||||
|
||||
import java.util.List;
|
||||
|
||||
|
||||
/*******************************************************************************
|
||||
** Ordered vectors and billable usage. No input text is retained in the response.
|
||||
*******************************************************************************/
|
||||
public record EmbeddingResponse(List<float[]> vectors, ModelUsage usage, String requestId)
|
||||
{
|
||||
}
|
||||
+1
-1
@@ -14,7 +14,7 @@
|
||||
* limitations under the License.
|
||||
*/
|
||||
|
||||
package com.kingsrook.qbits.assistant.provider;
|
||||
package com.kingsrook.qbits.assistant.spi;
|
||||
|
||||
|
||||
/*******************************************************************************
|
||||
+1
-1
@@ -14,7 +14,7 @@
|
||||
* limitations under the License.
|
||||
*/
|
||||
|
||||
package com.kingsrook.qbits.assistant.provider;
|
||||
package com.kingsrook.qbits.assistant.spi;
|
||||
|
||||
|
||||
/*******************************************************************************
|
||||
+1
-1
@@ -14,7 +14,7 @@
|
||||
* limitations under the License.
|
||||
*/
|
||||
|
||||
package com.kingsrook.qbits.assistant.provider;
|
||||
package com.kingsrook.qbits.assistant.spi;
|
||||
|
||||
|
||||
/*******************************************************************************
|
||||
+1
-1
@@ -14,7 +14,7 @@
|
||||
* limitations under the License.
|
||||
*/
|
||||
|
||||
package com.kingsrook.qbits.assistant.provider;
|
||||
package com.kingsrook.qbits.assistant.spi;
|
||||
|
||||
|
||||
import java.util.ArrayList;
|
||||
+1
-1
@@ -14,7 +14,7 @@
|
||||
* limitations under the License.
|
||||
*/
|
||||
|
||||
package com.kingsrook.qbits.assistant.provider;
|
||||
package com.kingsrook.qbits.assistant.spi;
|
||||
|
||||
|
||||
import java.util.LinkedHashMap;
|
||||
+4
-6
@@ -14,14 +14,12 @@
|
||||
* limitations under the License.
|
||||
*/
|
||||
|
||||
package com.kingsrook.qbits.assistant.engine;
|
||||
package com.kingsrook.qbits.assistant.spi;
|
||||
|
||||
|
||||
import java.io.Serializable;
|
||||
import java.util.LinkedHashMap;
|
||||
import java.util.Map;
|
||||
import com.kingsrook.qbits.assistant.AssistantModelRouting;
|
||||
import com.kingsrook.qbits.assistant.provider.ModelUsage;
|
||||
|
||||
|
||||
/*******************************************************************************
|
||||
@@ -63,9 +61,9 @@ public class ModelPricing implements Serializable
|
||||
public static Map<String, ModelPricing> defaults()
|
||||
{
|
||||
Map<String, ModelPricing> map = new LinkedHashMap<>();
|
||||
map.put(AssistantModelRouting.SONNET_5_5, of(2.0, 10.0, 0.1));
|
||||
map.put(AssistantModelRouting.OPUS_5_5, of(4.0, 20.0, 0.05));
|
||||
map.put(AssistantModelRouting.HAIKU_5_5, of(0.10, 0.50, 0.1));
|
||||
map.put("claude-sonnet-5-5", of(2.0, 10.0, 0.1));
|
||||
map.put("claude-opus-5-5", of(4.0, 20.0, 0.05));
|
||||
map.put("claude-haiku-5-5", of(0.10, 0.50, 0.1));
|
||||
map.put("claude-fable-5-1", of(10.0, 50.0, 0.025));
|
||||
map.put("claude-fable-5", of(10.0, 50.0, 0.1));
|
||||
map.put("claude-opus-5", of(5.0, 25.0, 0.1));
|
||||
+1
-1
@@ -14,7 +14,7 @@
|
||||
* limitations under the License.
|
||||
*/
|
||||
|
||||
package com.kingsrook.qbits.assistant.provider;
|
||||
package com.kingsrook.qbits.assistant.spi;
|
||||
|
||||
|
||||
/*******************************************************************************
|
||||
+1
-1
@@ -14,7 +14,7 @@
|
||||
* limitations under the License.
|
||||
*/
|
||||
|
||||
package com.kingsrook.qbits.assistant.provider;
|
||||
package com.kingsrook.qbits.assistant.spi;
|
||||
|
||||
|
||||
import java.util.ArrayList;
|
||||
+1
-1
@@ -14,7 +14,7 @@
|
||||
* limitations under the License.
|
||||
*/
|
||||
|
||||
package com.kingsrook.qbits.assistant.provider;
|
||||
package com.kingsrook.qbits.assistant.spi;
|
||||
|
||||
|
||||
import java.util.ArrayList;
|
||||
+1
-1
@@ -14,7 +14,7 @@
|
||||
* limitations under the License.
|
||||
*/
|
||||
|
||||
package com.kingsrook.qbits.assistant.provider;
|
||||
package com.kingsrook.qbits.assistant.spi;
|
||||
|
||||
|
||||
import java.util.Map;
|
||||
+1
-1
@@ -14,7 +14,7 @@
|
||||
* limitations under the License.
|
||||
*/
|
||||
|
||||
package com.kingsrook.qbits.assistant.provider;
|
||||
package com.kingsrook.qbits.assistant.spi;
|
||||
|
||||
|
||||
/*******************************************************************************
|
||||
+34
-2
@@ -14,12 +14,12 @@
|
||||
* limitations under the License.
|
||||
*/
|
||||
|
||||
package com.kingsrook.qbits.assistant.provider;
|
||||
package com.kingsrook.qbits.assistant.spi;
|
||||
|
||||
|
||||
import java.util.function.Supplier;
|
||||
import javax.net.ssl.SSLContext;
|
||||
import com.fasterxml.jackson.annotation.JsonIgnore;
|
||||
import javax.net.ssl.SSLContext;
|
||||
|
||||
|
||||
/*******************************************************************************
|
||||
@@ -36,6 +36,7 @@ public class ProviderSettings
|
||||
private String tlsCaBundle;
|
||||
@JsonIgnore
|
||||
private transient SSLContext sslContext;
|
||||
private String apiKeyEnvName;
|
||||
private String kind;
|
||||
private String apiKey;
|
||||
private String baseUrl;
|
||||
@@ -397,4 +398,35 @@ public class ProviderSettings
|
||||
this.bearerTokenSupplier = bearerTokenSupplier;
|
||||
return (this);
|
||||
}
|
||||
|
||||
|
||||
|
||||
/*******************************************************************************
|
||||
** The configured environment variable name, never its secret value.
|
||||
*******************************************************************************/
|
||||
public String getApiKeyEnvName()
|
||||
{
|
||||
return (this.apiKeyEnvName);
|
||||
}
|
||||
|
||||
|
||||
|
||||
/*******************************************************************************
|
||||
** Setter for apiKeyEnvName
|
||||
*******************************************************************************/
|
||||
public void setApiKeyEnvName(String apiKeyEnvName)
|
||||
{
|
||||
this.apiKeyEnvName = apiKeyEnvName;
|
||||
}
|
||||
|
||||
|
||||
|
||||
/*******************************************************************************
|
||||
** Fluent setter for apiKeyEnvName
|
||||
*******************************************************************************/
|
||||
public ProviderSettings withApiKeyEnvName(String apiKeyEnvName)
|
||||
{
|
||||
this.apiKeyEnvName = apiKeyEnvName;
|
||||
return (this);
|
||||
}
|
||||
}
|
||||
+1
-1
@@ -14,7 +14,7 @@
|
||||
* limitations under the License.
|
||||
*/
|
||||
|
||||
package com.kingsrook.qbits.assistant.provider;
|
||||
package com.kingsrook.qbits.assistant.spi;
|
||||
|
||||
|
||||
import java.time.Duration;
|
||||
+1
-1
@@ -14,7 +14,7 @@
|
||||
* limitations under the License.
|
||||
*/
|
||||
|
||||
package com.kingsrook.qbits.assistant.provider;
|
||||
package com.kingsrook.qbits.assistant.spi;
|
||||
|
||||
|
||||
/*******************************************************************************
|
||||
+1
-1
@@ -14,7 +14,7 @@
|
||||
* limitations under the License.
|
||||
*/
|
||||
|
||||
package com.kingsrook.qbits.assistant.provider;
|
||||
package com.kingsrook.qbits.assistant.spi;
|
||||
|
||||
|
||||
/*******************************************************************************
|
||||
+1
-1
@@ -14,7 +14,7 @@
|
||||
* limitations under the License.
|
||||
*/
|
||||
|
||||
package com.kingsrook.qbits.assistant.provider;
|
||||
package com.kingsrook.qbits.assistant.spi;
|
||||
|
||||
|
||||
import java.io.ByteArrayInputStream;
|
||||
+46
@@ -0,0 +1,46 @@
|
||||
/*
|
||||
* Copyright 2026 Kingsrook, LLC
|
||||
*
|
||||
* Licensed under the Apache License, Version 2.0 (the "License");
|
||||
* you may not use this file except in compliance with the License.
|
||||
* You may obtain a copy of the License at
|
||||
*
|
||||
* http://www.apache.org/licenses/LICENSE-2.0
|
||||
*
|
||||
* Unless required by applicable law or agreed to in writing, software
|
||||
* distributed under the License is distributed on an "AS IS" BASIS,
|
||||
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
|
||||
* See the License for the specific language governing permissions and
|
||||
* limitations under the License.
|
||||
*/
|
||||
|
||||
package com.kingsrook.qbits.assistant.spi;
|
||||
|
||||
|
||||
import com.tngtech.archunit.core.domain.JavaClasses;
|
||||
import com.tngtech.archunit.core.importer.ClassFileImporter;
|
||||
import org.junit.jupiter.api.Test;
|
||||
import static com.tngtech.archunit.core.domain.JavaClass.Predicates.resideInAPackage;
|
||||
import static com.tngtech.archunit.core.domain.JavaClass.Predicates.resideOutsideOfPackage;
|
||||
import static com.tngtech.archunit.lang.syntax.ArchRuleDefinition.classes;
|
||||
import static com.tngtech.archunit.lang.syntax.ArchRuleDefinition.noClasses;
|
||||
|
||||
|
||||
/*******************************************************************************
|
||||
** Keep external provider consumers independent of the assistant runtime and QQQ.
|
||||
*******************************************************************************/
|
||||
class ProviderApiArchitectureTest
|
||||
{
|
||||
/*******************************************************************************
|
||||
** Import the entire artifact so an accidental package outside spi also fails.
|
||||
*******************************************************************************/
|
||||
@Test
|
||||
void dependsOnlyOnApiTypes()
|
||||
{
|
||||
String spiPackage = "com.kingsrook.qbits.assistant.spi";
|
||||
JavaClasses imported = new ClassFileImporter().importUrl(AssistantModelProvider.class.getProtectionDomain().getCodeSource().getLocation());
|
||||
classes().should().resideInAPackage(spiPackage).check(imported);
|
||||
noClasses().should().dependOnClassesThat(resideInAPackage("com.kingsrook.qbits..").and(resideOutsideOfPackage(spiPackage))).check(imported);
|
||||
noClasses().should().dependOnClassesThat().resideInAnyPackage("com.kingsrook.qqq..").check(imported);
|
||||
}
|
||||
}
|
||||
+213
@@ -0,0 +1,213 @@
|
||||
/*
|
||||
* Copyright 2026 Kingsrook, LLC
|
||||
*
|
||||
* Licensed under the Apache License, Version 2.0 (the "License");
|
||||
* you may not use this file except in compliance with the License.
|
||||
* You may obtain a copy of the License at
|
||||
*
|
||||
* http://www.apache.org/licenses/LICENSE-2.0
|
||||
*
|
||||
* Unless required by applicable law or agreed to in writing, software
|
||||
* distributed under the License is distributed on an "AS IS" BASIS,
|
||||
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
|
||||
* See the License for the specific language governing permissions and
|
||||
* limitations under the License.
|
||||
*/
|
||||
|
||||
package com.kingsrook.qbits.assistant.spi;
|
||||
|
||||
|
||||
import java.time.Duration;
|
||||
import java.util.ArrayList;
|
||||
import java.util.Collections;
|
||||
import java.util.List;
|
||||
import java.util.Map;
|
||||
import java.util.concurrent.atomic.AtomicInteger;
|
||||
import com.fasterxml.jackson.databind.DeserializationFeature;
|
||||
import com.fasterxml.jackson.databind.JsonNode;
|
||||
import com.fasterxml.jackson.databind.ObjectMapper;
|
||||
import javax.net.ssl.SSLContext;
|
||||
import org.junit.jupiter.api.Test;
|
||||
import static org.assertj.core.api.Assertions.assertThat;
|
||||
import static org.assertj.core.api.Assertions.assertThatThrownBy;
|
||||
|
||||
|
||||
/*******************************************************************************
|
||||
** Provider contracts work on a classpath with no assistant runtime or QQQ.
|
||||
*******************************************************************************/
|
||||
class ProviderApiTest
|
||||
{
|
||||
private final ObjectMapper mapper = new ObjectMapper().disable(DeserializationFeature.FAIL_ON_UNKNOWN_PROPERTIES);
|
||||
|
||||
|
||||
|
||||
/*******************************************************************************
|
||||
** Preserve provider-neutral requests and tool order through JSON; signed
|
||||
** provider state remains in memory only.
|
||||
*******************************************************************************/
|
||||
@Test
|
||||
void requestRoundTripAndCopy() throws Exception
|
||||
{
|
||||
ModelCapabilities capabilities = new ModelCapabilities().withTools(true).withParallelToolCalls(true)
|
||||
.withPromptCaching(true).withThinking(false).withMaxContextTokens(32000)
|
||||
.withVision(false).withStreaming(true).withReasoningEffort(true);
|
||||
ModelToolDefinition tool = new ModelToolDefinition().withName("lookup").withDescription("Look up a record")
|
||||
.withInputSchema(Map.of("type", "object")).withStrict(true);
|
||||
ModelMessage user = ModelMessage.user("Find it").withCacheHint(CacheHint.SHORT);
|
||||
ModelMessage assistant = ModelMessage.assistant("Looking").withPart(ModelPart.toolUse("call-1", "lookup", null))
|
||||
.withProviderState("private-signature");
|
||||
ModelMessage result = new ModelMessage().withRole(ModelMessage.Role.USER)
|
||||
.withParts(List.of(ModelPart.toolResult("call-1", "denied", true)));
|
||||
ModelRequest request = new ModelRequest().withModel("example").withEffort("low").withMaxTokens(100)
|
||||
.withParallelToolCalls(true).withStreaming(false).withCapabilities(capabilities)
|
||||
.withSystem(List.of(new SystemBlock("rules", CacheHint.LONG), new SystemBlock().withText("user context").withCacheHint(CacheHint.SHORT)))
|
||||
.withTools(List.of(tool)).withMessages(new ArrayList<>(List.of(user, assistant, result)));
|
||||
String json = mapper.writeValueAsString(request);
|
||||
assertThat(json).doesNotContain("private-signature", "providerState");
|
||||
ModelRequest restored = mapper.readValue(json, ModelRequest.class);
|
||||
assertThat(mapper.<JsonNode>valueToTree(restored)).isEqualTo(mapper.valueToTree(request));
|
||||
assertThat(restored.getMessages().get(1).getProviderState()).isNull();
|
||||
assertThat(restored.getMessages().get(2).getParts().get(0).getIsError()).isTrue();
|
||||
ModelRequest copy = request.copy();
|
||||
assertThat(mapper.<JsonNode>valueToTree(copy)).isEqualTo(mapper.valueToTree(request));
|
||||
copy.getMessages().clear();
|
||||
assertThat(request.getMessages()).hasSize(3);
|
||||
}
|
||||
|
||||
|
||||
|
||||
/*******************************************************************************
|
||||
** Response helpers retain tool ordering, text, usage and safe metadata.
|
||||
*******************************************************************************/
|
||||
@Test
|
||||
void responseAndPricingRoundTrip() throws Exception
|
||||
{
|
||||
ModelUsage usage = new ModelUsage().withInputTokens(2L).withOutputTokens(3L)
|
||||
.withCacheReadTokens(4L).withCacheWriteTokens(5L).withCacheWrite1hTokens(1L);
|
||||
ModelPart first = ModelPart.toolUse("first", "lookup", Map.of("id", 1));
|
||||
ModelPart second = ModelPart.toolUse("second", "lookup", Map.of("id", 2));
|
||||
ModelResponse response = new ModelResponse().withParts(List.of(ModelPart.text("a"), first, ModelPart.text("b"), second))
|
||||
.withModel("example").withStopReason(ModelResponse.STOP_TOOL_USE).withRequestId("request-1")
|
||||
.withUsage(usage).withProviderState("signature");
|
||||
assertThat(response.getText()).isEqualTo("ab");
|
||||
assertThat(response.getToolUses()).containsExactly(first, second);
|
||||
String json = mapper.writeValueAsString(response);
|
||||
assertThat(json).doesNotContain("signature", "providerState");
|
||||
ModelResponse restored = mapper.readValue(json, ModelResponse.class);
|
||||
assertThat(mapper.<JsonNode>valueToTree(restored)).isEqualTo(mapper.valueToTree(response));
|
||||
assertThat(restored.getProviderState()).isNull();
|
||||
assertThat(response.getProviderState()).isEqualTo("signature");
|
||||
ModelPricing pricing = ModelPricing.of(0.1, 0.5, 0.1);
|
||||
ModelPricing restoredPricing = mapper.readValue(mapper.writeValueAsString(pricing), ModelPricing.class);
|
||||
assertThat(restoredPricing.costMicros(usage)).isEqualTo(3);
|
||||
assertThat(new ModelUsage().withInputTokens(null).add(usage).add(null).billableTokens()).isEqualTo(10);
|
||||
TokenCount tokens = mapper.readValue(mapper.writeValueAsString(new TokenCount().withInputTokens(12L)), TokenCount.class);
|
||||
assertThat(tokens.getInputTokens()).isEqualTo(12L);
|
||||
}
|
||||
|
||||
|
||||
|
||||
/*******************************************************************************
|
||||
** Plain validation settings require no credentials or entity classes, and
|
||||
** live token suppliers/TLS contexts cannot be serialized into diagnostics.
|
||||
*******************************************************************************/
|
||||
@Test
|
||||
void settingsRoundTrip() throws Exception
|
||||
{
|
||||
ProviderSettings settings = new ProviderSettings().withKind("EXAMPLE").withApiKeyEnvName("EXAMPLE_KEY")
|
||||
.withApiKey("test-only-key").withBaseUrl("https://example.invalid").withApiVersion("v1")
|
||||
.withRegion("region").withCloudProject("project").withTlsCaBundle("corporate")
|
||||
.withConnectTimeoutSeconds(5).withRequestTimeoutSeconds(30)
|
||||
.withBearerTokenSupplier(() -> "ephemeral-token").withSslContext(SSLContext.getDefault());
|
||||
String json = mapper.writeValueAsString(settings);
|
||||
assertThat(json).doesNotContain("ephemeral-token", "bearerTokenSupplier", "sslContext");
|
||||
ProviderSettings restored = mapper.readValue(json, ProviderSettings.class);
|
||||
assertThat(mapper.<JsonNode>valueToTree(restored)).isEqualTo(mapper.valueToTree(settings));
|
||||
assertThat(settings.getBearerTokenSupplier().get()).isEqualTo("ephemeral-token");
|
||||
assertThat(settings.getSslContext()).isNotNull();
|
||||
assertThat(restored.getBearerTokenSupplier()).isNull();
|
||||
assertThat(restored.getSslContext()).isNull();
|
||||
}
|
||||
|
||||
|
||||
|
||||
/*******************************************************************************
|
||||
** Embedding batches snapshot input and enforce the transport size contract.
|
||||
*******************************************************************************/
|
||||
@Test
|
||||
void embeddingContracts()
|
||||
{
|
||||
List<String> input = new ArrayList<>(List.of("first", "second"));
|
||||
EmbeddingRequest request = new EmbeddingRequest("embed", input);
|
||||
input.clear();
|
||||
assertThat(request.input()).containsExactly("first", "second");
|
||||
assertThatThrownBy(() -> request.input().add("third")).isInstanceOf(UnsupportedOperationException.class);
|
||||
assertThatThrownBy(() -> new EmbeddingRequest(" ", List.of("text"))).isInstanceOf(IllegalArgumentException.class);
|
||||
assertThatThrownBy(() -> new EmbeddingRequest(null, List.of("text"))).isInstanceOf(IllegalArgumentException.class);
|
||||
assertThatThrownBy(() -> new EmbeddingRequest("embed", List.of())).isInstanceOf(IllegalArgumentException.class);
|
||||
assertThatThrownBy(() -> new EmbeddingRequest("embed", Collections.nCopies(65, "text"))).isInstanceOf(IllegalArgumentException.class);
|
||||
assertThat(new EmbeddingRequest("embed", Collections.nCopies(64, "text")).input()).hasSize(64);
|
||||
float[] vector = new float[] { 0.25F, 0.75F };
|
||||
EmbeddingResponse response = new EmbeddingResponse(List.of(vector), new ModelUsage().withInputTokens(2L), "request");
|
||||
assertThat(response.vectors().getFirst()).containsExactly(0.25F, 0.75F);
|
||||
assertThat(response.usage().getInputTokens()).isEqualTo(2L);
|
||||
assertThat(response.requestId()).isEqualTo("request");
|
||||
}
|
||||
|
||||
|
||||
|
||||
/*******************************************************************************
|
||||
** Cancellation is idempotent, preserves accrued usage, and wins over late
|
||||
** completion. Timeout also cancels the underlying transport.
|
||||
*******************************************************************************/
|
||||
@Test
|
||||
void cancellationAndTimeout() throws Exception
|
||||
{
|
||||
AtomicInteger cancellations = new AtomicInteger();
|
||||
ModelUsage usage = new ModelUsage().withInputTokens(10L);
|
||||
CompletableStreamHandle handle = new CompletableStreamHandle();
|
||||
handle.setPartialUsage(() -> usage);
|
||||
handle.setOnCancel(cancellations::incrementAndGet);
|
||||
handle.cancel();
|
||||
handle.cancel();
|
||||
handle.complete(new ModelResponse().withStopReason(ModelResponse.STOP_END_TURN));
|
||||
handle.fail(new ModelProviderException(ModelProviderException.Kind.SERVER, 500, "late failure"));
|
||||
assertThat(handle.isCancelled()).isTrue();
|
||||
assertThat(cancellations.get()).isEqualTo(1);
|
||||
assertThat(handle.await(Duration.ofSeconds(1)).getUsage()).isSameAs(usage);
|
||||
CompletableStreamHandle timeout = new CompletableStreamHandle();
|
||||
timeout.setPartialUsage(() -> usage);
|
||||
assertThatThrownBy(() -> timeout.await(Duration.ofMillis(1))).isInstanceOfSatisfying(ModelProviderException.class, error ->
|
||||
{
|
||||
assertThat(error.getKind()).isEqualTo(ModelProviderException.Kind.TIMEOUT);
|
||||
assertThat(error.getPartialUsage()).isSameAs(usage);
|
||||
});
|
||||
assertThat(timeout.isCancelled()).isTrue();
|
||||
handle.setPartialUsage(() ->
|
||||
{
|
||||
throw (new IllegalStateException("closed"));
|
||||
});
|
||||
assertThat(handle.partialUsage()).isNull();
|
||||
}
|
||||
|
||||
|
||||
|
||||
/*******************************************************************************
|
||||
** Error metadata is bounded and redacted independently of error classification.
|
||||
*******************************************************************************/
|
||||
@Test
|
||||
void errorDetails()
|
||||
{
|
||||
ModelProviderException error = new ModelProviderException(ModelProviderException.Kind.INVALID_REQUEST, 400, "Invalid schema")
|
||||
.withStrictSchemaRejected(true).withProviderDetails("invalid_request", "bad key sk-abcdefghijk\ntry again", "req-123");
|
||||
assertThat(error.isStrictSchemaRejected()).isTrue();
|
||||
assertThat(error.getProviderErrorType()).isEqualTo("invalid_request");
|
||||
assertThat(error.getProviderMessage()).isEqualTo("bad key [redacted] try again");
|
||||
assertThat(error.getRequestId()).isEqualTo("req-123");
|
||||
assertThat(error.isRetryable()).isFalse();
|
||||
assertThat(ModelProviderException.sanitizeProviderMessage(" ", 10)).isNull();
|
||||
assertThat(ModelProviderException.sanitizeProviderMessage(null, 10)).isNull();
|
||||
assertThat(ModelProviderException.sanitizeProviderMessage("word ".repeat(100), 20)).hasSize(20);
|
||||
assertThat(ModelProviderException.sanitizeProviderMessage("a".repeat(50), 100)).isEqualTo("[redacted]");
|
||||
}
|
||||
}
|
||||
+79
@@ -0,0 +1,79 @@
|
||||
/*
|
||||
* Copyright 2026 Kingsrook, LLC
|
||||
*
|
||||
* Licensed under the Apache License, Version 2.0 (the "License");
|
||||
* you may not use this file except in compliance with the License.
|
||||
* You may obtain a copy of the License at
|
||||
*
|
||||
* http://www.apache.org/licenses/LICENSE-2.0
|
||||
*
|
||||
* Unless required by applicable law or agreed to in writing, software
|
||||
* distributed under the License is distributed on an "AS IS" BASIS,
|
||||
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
|
||||
* See the License for the specific language governing permissions and
|
||||
* limitations under the License.
|
||||
*/
|
||||
|
||||
package com.kingsrook.qbits.assistant.spi;
|
||||
|
||||
|
||||
import java.time.Duration;
|
||||
import org.junit.jupiter.api.Test;
|
||||
import static org.assertj.core.api.Assertions.assertThat;
|
||||
import static org.assertj.core.api.Assertions.assertThatThrownBy;
|
||||
|
||||
|
||||
/*******************************************************************************
|
||||
** Standalone contracts moved from the runtime's component tests.
|
||||
*******************************************************************************/
|
||||
class ProviderComponentsTest
|
||||
{
|
||||
/*******************************************************************************
|
||||
**
|
||||
*******************************************************************************/
|
||||
@Test
|
||||
void testPricing()
|
||||
{
|
||||
ModelPricing sonnet = ModelPricing.defaults().get("claude-sonnet-5-5");
|
||||
ModelUsage usage = new ModelUsage().withInputTokens(6000L).withOutputTokens(800L).withCacheReadTokens(12_000L).withCacheWriteTokens(1000L).withCacheWrite1hTokens(400L);
|
||||
//////////////////////////////////////////////////////////////////////////////////
|
||||
// 6000*2 + 800*10 + 12000*0.2 + 600*2.5 + 400*4 = 12000+8000+2400+1500+1600 //
|
||||
//////////////////////////////////////////////////////////////////////////////////
|
||||
assertThat(sonnet.costMicros(usage)).isEqualTo(25_500);
|
||||
assertThat(sonnet.costMicros(null)).isZero();
|
||||
assertThat(new ModelPricing().costMicros(usage)).isZero();
|
||||
assertThat(ModelPricing.defaults().get("claude-opus-5-5").getCacheReadUsdPerMTok()).isEqualTo(0.2);
|
||||
assertThat(usage.billableTokens()).isEqualTo(7800);
|
||||
assertThat(new ModelUsage().add(usage).add(null).getCacheReadTokens()).isEqualTo(12_000);
|
||||
}
|
||||
|
||||
|
||||
/*******************************************************************************
|
||||
**
|
||||
*******************************************************************************/
|
||||
@Test
|
||||
void testStreamHandle() throws Exception
|
||||
{
|
||||
CompletableStreamHandle handle = new CompletableStreamHandle();
|
||||
handle.complete(new ModelResponse().withStopReason("end_turn"));
|
||||
assertThat(handle.await(Duration.ofSeconds(1)).getStopReason()).isEqualTo("end_turn");
|
||||
|
||||
CompletableStreamHandle failing = new CompletableStreamHandle();
|
||||
failing.fail(new ModelProviderException(ModelProviderException.Kind.RATE_LIMITED, 429, "slow down"));
|
||||
assertThatThrownBy(() -> failing.await(Duration.ofSeconds(1))).isInstanceOfSatisfying(ModelProviderException.class, e ->
|
||||
{
|
||||
assertThat(e.isRetryable()).isTrue();
|
||||
assertThat(e.getHttpStatus()).isEqualTo(429);
|
||||
});
|
||||
|
||||
CompletableStreamHandle cancelled = new CompletableStreamHandle();
|
||||
cancelled.setOnCancel(() ->
|
||||
{
|
||||
throw (new IllegalStateException("closing"));
|
||||
});
|
||||
cancelled.cancel();
|
||||
cancelled.cancel();
|
||||
assertThat(cancelled.await(Duration.ofSeconds(1)).getStopReason()).isEqualTo(ModelResponse.STOP_CANCELLED);
|
||||
assertThat(new ModelProviderException(ModelProviderException.Kind.INVALID_REQUEST, 400, "x").isRetryable()).isFalse();
|
||||
}
|
||||
}
|
||||
+164
@@ -0,0 +1,164 @@
|
||||
/*
|
||||
* Copyright 2026 Kingsrook, LLC
|
||||
*
|
||||
* Licensed under the Apache License, Version 2.0 (the "License");
|
||||
* you may not use this file except in compliance with the License.
|
||||
* You may obtain a copy of the License at
|
||||
*
|
||||
* http://www.apache.org/licenses/LICENSE-2.0
|
||||
*
|
||||
* Unless required by applicable law or agreed to in writing, software
|
||||
* distributed under the License is distributed on an "AS IS" BASIS,
|
||||
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
|
||||
* See the License for the specific language governing permissions and
|
||||
* limitations under the License.
|
||||
*/
|
||||
|
||||
package com.kingsrook.qbits.assistant.spi;
|
||||
|
||||
|
||||
import java.util.List;
|
||||
import org.junit.jupiter.api.Test;
|
||||
import static org.assertj.core.api.Assertions.assertThat;
|
||||
import static org.assertj.core.api.Assertions.assertThatThrownBy;
|
||||
|
||||
|
||||
/*******************************************************************************
|
||||
** A minimal external provider compiles and uses SPI defaults without the runtime.
|
||||
*******************************************************************************/
|
||||
class ProviderDefaultsTest
|
||||
{
|
||||
/*******************************************************************************
|
||||
** Legacy two-argument factories and static model lists remain supported.
|
||||
*******************************************************************************/
|
||||
@Test
|
||||
void minimalProviderDefaults() throws Exception
|
||||
{
|
||||
ExampleProvider provider = new ExampleProvider();
|
||||
ProviderSettings settings = new ProviderSettings().withApiKey("test-key").withBaseUrl("https://example.invalid");
|
||||
assertThat(provider.create(settings)).isSameAs(provider);
|
||||
assertThat(provider.settings.getApiKey()).isEqualTo("test-key");
|
||||
assertThat(provider.settings.getBaseUrl()).isEqualTo("https://example.invalid");
|
||||
assertThat(provider.getKinds()).containsExactly("EXAMPLE_PROVIDER");
|
||||
assertThat(provider.getDefaultBaseUrl("EXAMPLE_PROVIDER")).isNull();
|
||||
assertThat(provider.getDefaultApiKeyEnvName("EXAMPLE_PROVIDER")).isEqualTo("EXAMPLE_KEY");
|
||||
assertThat(provider.getDefaultLocation("EXAMPLE_PROVIDER")).isEqualTo("CLOUD");
|
||||
assertThat(provider.requiresBaseUrl("EXAMPLE_PROVIDER")).isTrue();
|
||||
assertThat(provider.validate(settings)).isEmpty();
|
||||
assertThat(provider.discoverModels(settings)).containsExactly(new DiscoveredModel("example", "example", null, null));
|
||||
assertThat(provider.checkHealth(settings).healthy()).isNull();
|
||||
assertThat(provider.checkHealth(settings).message()).isEqualTo("Health check not supported");
|
||||
assertThat(new HealthResult(false, 20L, "bad sk-abcdefghijk").message()).isEqualTo("bad [redacted]");
|
||||
assertThat(provider.countTokens(new ModelRequest())).isNull();
|
||||
assertThatThrownBy(() -> provider.embed(new EmbeddingRequest("example", List.of("text"))))
|
||||
.isInstanceOfSatisfying(ModelProviderException.class, error -> assertThat(error.getKind()).isEqualTo(ModelProviderException.Kind.INVALID_REQUEST));
|
||||
StringBuilder deltas = new StringBuilder();
|
||||
ModelEventListener listener = deltas::append;
|
||||
listener.onToolUseStart("call", "lookup");
|
||||
assertThat(deltas).isEmpty();
|
||||
listener.onTextDelta("visible answer");
|
||||
assertThat(deltas).hasToString("visible answer");
|
||||
}
|
||||
|
||||
|
||||
|
||||
/*******************************************************************************
|
||||
** Only the original required SPI methods are implemented.
|
||||
*******************************************************************************/
|
||||
private static class ExampleProvider implements AssistantProviderType, AssistantModelProvider
|
||||
{
|
||||
private ProviderSettings settings;
|
||||
|
||||
|
||||
|
||||
/*******************************************************************************
|
||||
** Minimal provider contract.
|
||||
*******************************************************************************/
|
||||
@Override
|
||||
public String getType()
|
||||
{
|
||||
return ("example-provider");
|
||||
}
|
||||
|
||||
|
||||
/*******************************************************************************
|
||||
** Minimal provider contract.
|
||||
*******************************************************************************/
|
||||
@Override
|
||||
public String getLabel()
|
||||
{
|
||||
return ("Example");
|
||||
}
|
||||
|
||||
|
||||
/*******************************************************************************
|
||||
** Minimal provider contract.
|
||||
*******************************************************************************/
|
||||
@Override
|
||||
public List<String> getModels()
|
||||
{
|
||||
return (List.of("example"));
|
||||
}
|
||||
|
||||
|
||||
/*******************************************************************************
|
||||
** Minimal provider contract.
|
||||
*******************************************************************************/
|
||||
@Override
|
||||
public String getDefaultApiKeyEnvName()
|
||||
{
|
||||
return ("EXAMPLE_KEY");
|
||||
}
|
||||
|
||||
|
||||
/*******************************************************************************
|
||||
** Minimal provider contract.
|
||||
*******************************************************************************/
|
||||
@Override
|
||||
public String getDefaultBaseUrl()
|
||||
{
|
||||
return (null);
|
||||
}
|
||||
|
||||
|
||||
/*******************************************************************************
|
||||
** Minimal provider contract.
|
||||
*******************************************************************************/
|
||||
@Override
|
||||
public AssistantModelProvider create(String apiKey, String baseUrl)
|
||||
{
|
||||
settings = new ProviderSettings().withApiKey(apiKey).withBaseUrl(baseUrl);
|
||||
return (this);
|
||||
}
|
||||
|
||||
|
||||
/*******************************************************************************
|
||||
** Minimal provider contract.
|
||||
*******************************************************************************/
|
||||
@Override
|
||||
public String getName()
|
||||
{
|
||||
return ("example");
|
||||
}
|
||||
|
||||
|
||||
/*******************************************************************************
|
||||
** Minimal provider contract.
|
||||
*******************************************************************************/
|
||||
@Override
|
||||
public ModelCapabilities getCapabilities(String modelId)
|
||||
{
|
||||
return (new ModelCapabilities());
|
||||
}
|
||||
|
||||
|
||||
/*******************************************************************************
|
||||
** Minimal provider contract.
|
||||
*******************************************************************************/
|
||||
@Override
|
||||
public StreamHandle stream(ModelRequest request, ModelEventListener listener)
|
||||
{
|
||||
throw (new UnsupportedOperationException());
|
||||
}
|
||||
}
|
||||
}
|
||||
+1
-1
@@ -14,7 +14,7 @@
|
||||
* limitations under the License.
|
||||
*/
|
||||
|
||||
package com.kingsrook.qbits.assistant.provider;
|
||||
package com.kingsrook.qbits.assistant.spi;
|
||||
|
||||
|
||||
import java.security.KeyStore;
|
||||
@@ -41,9 +41,14 @@
|
||||
<artifactId>qbit-assistant-provider-anthropic</artifactId>
|
||||
</dependency>
|
||||
|
||||
<dependency>
|
||||
<groupId>com.kingsrook.qbits</groupId>
|
||||
<artifactId>qbit-assistant-provider-api</artifactId>
|
||||
</dependency>
|
||||
<dependency>
|
||||
<groupId>com.kingsrook.qbits</groupId>
|
||||
<artifactId>qbit-assistant</artifactId>
|
||||
<scope>test</scope>
|
||||
</dependency>
|
||||
<dependency>
|
||||
<groupId>com.kingsrook.qqq</groupId>
|
||||
|
||||
+7
-8
@@ -24,12 +24,11 @@ import com.anthropic.backends.Backend;
|
||||
import com.anthropic.bedrock.backends.BedrockBackend;
|
||||
import com.anthropic.client.okhttp.AnthropicOkHttpClient;
|
||||
import com.anthropic.core.Timeout;
|
||||
import com.kingsrook.qbits.assistant.model.AssistantProvider;
|
||||
import com.kingsrook.qbits.assistant.provider.AssistantModelProvider;
|
||||
import com.kingsrook.qbits.assistant.provider.AssistantProviderType;
|
||||
import com.kingsrook.qbits.assistant.provider.DiscoveredModel;
|
||||
import com.kingsrook.qbits.assistant.provider.ProviderSettings;
|
||||
import com.kingsrook.qbits.assistant.provider.anthropic.AnthropicModelProvider;
|
||||
import com.kingsrook.qbits.assistant.spi.AssistantModelProvider;
|
||||
import com.kingsrook.qbits.assistant.spi.AssistantProviderType;
|
||||
import com.kingsrook.qbits.assistant.spi.DiscoveredModel;
|
||||
import com.kingsrook.qbits.assistant.spi.ProviderSettings;
|
||||
import software.amazon.awssdk.auth.credentials.AwsCredentialsProvider;
|
||||
import software.amazon.awssdk.auth.credentials.DefaultCredentialsProvider;
|
||||
import software.amazon.awssdk.regions.Region;
|
||||
@@ -117,14 +116,14 @@ public class BedrockProviderType implements AssistantProviderType
|
||||
** Validate cloud settings without loading credentials.
|
||||
*******************************************************************************/
|
||||
@Override
|
||||
public List<String> validate(AssistantProvider row)
|
||||
public List<String> validate(ProviderSettings settings)
|
||||
{
|
||||
List<String> errors = new ArrayList<>();
|
||||
if(row.getRegion() == null || row.getRegion().isBlank())
|
||||
if(settings.getRegion() == null || settings.getRegion().isBlank())
|
||||
{
|
||||
errors.add("Region is required for BEDROCK.");
|
||||
}
|
||||
if(row.getApiKeyEnvName() != null && !row.getApiKeyEnvName().isBlank())
|
||||
if(settings.getApiKeyEnvName() != null && !settings.getApiKeyEnvName().isBlank())
|
||||
{
|
||||
errors.add("Leave API key variable empty: AWS Bedrock (Claude) uses the AWS default credential chain (environment, profile or server role).");
|
||||
}
|
||||
|
||||
+6
-6
@@ -27,13 +27,13 @@ import java.util.Set;
|
||||
import com.kingsrook.qbits.assistant.AssistantQBitConfig;
|
||||
import com.kingsrook.qbits.assistant.engine.ProviderService;
|
||||
import com.kingsrook.qbits.assistant.model.AssistantProvider;
|
||||
import com.kingsrook.qbits.assistant.provider.ModelEventListener;
|
||||
import com.kingsrook.qbits.assistant.provider.ModelMessage;
|
||||
import com.kingsrook.qbits.assistant.provider.ModelProviderException;
|
||||
import com.kingsrook.qbits.assistant.provider.ModelRequest;
|
||||
import com.kingsrook.qbits.assistant.provider.ModelToolDefinition;
|
||||
import com.kingsrook.qbits.assistant.provider.ProviderSettings;
|
||||
import com.kingsrook.qbits.assistant.provider.anthropic.AnthropicModelProvider;
|
||||
import com.kingsrook.qbits.assistant.spi.ModelEventListener;
|
||||
import com.kingsrook.qbits.assistant.spi.ModelMessage;
|
||||
import com.kingsrook.qbits.assistant.spi.ModelProviderException;
|
||||
import com.kingsrook.qbits.assistant.spi.ModelRequest;
|
||||
import com.kingsrook.qbits.assistant.spi.ModelToolDefinition;
|
||||
import com.kingsrook.qbits.assistant.spi.ProviderSettings;
|
||||
import com.kingsrook.qbits.assistant.testing.CloudProviderTestServer;
|
||||
import org.junit.jupiter.api.Test;
|
||||
import org.junit.jupiter.params.ParameterizedTest;
|
||||
|
||||
@@ -32,9 +32,14 @@
|
||||
<url>https://github.com/QRun-IO/qbit-assistant</url>
|
||||
|
||||
<dependencies>
|
||||
<dependency>
|
||||
<groupId>com.kingsrook.qbits</groupId>
|
||||
<artifactId>qbit-assistant-provider-api</artifactId>
|
||||
</dependency>
|
||||
<dependency>
|
||||
<groupId>com.kingsrook.qbits</groupId>
|
||||
<artifactId>qbit-assistant</artifactId>
|
||||
<scope>test</scope>
|
||||
</dependency>
|
||||
<dependency>
|
||||
<groupId>com.kingsrook.qqq</groupId>
|
||||
|
||||
+91
-11
@@ -36,17 +36,19 @@ import java.util.concurrent.atomic.AtomicReference;
|
||||
import com.fasterxml.jackson.core.type.TypeReference;
|
||||
import com.fasterxml.jackson.databind.JsonNode;
|
||||
import com.fasterxml.jackson.databind.node.ObjectNode;
|
||||
import com.kingsrook.qbits.assistant.provider.AssistantModelProvider;
|
||||
import com.kingsrook.qbits.assistant.provider.CompletableStreamHandle;
|
||||
import com.kingsrook.qbits.assistant.provider.ModelCapabilities;
|
||||
import com.kingsrook.qbits.assistant.provider.ModelEventListener;
|
||||
import com.kingsrook.qbits.assistant.provider.ModelPart;
|
||||
import com.kingsrook.qbits.assistant.provider.ModelProviderException;
|
||||
import com.kingsrook.qbits.assistant.provider.ModelRequest;
|
||||
import com.kingsrook.qbits.assistant.provider.ModelResponse;
|
||||
import com.kingsrook.qbits.assistant.provider.ModelUsage;
|
||||
import com.kingsrook.qbits.assistant.provider.ProviderSettings;
|
||||
import com.kingsrook.qbits.assistant.provider.StreamHandle;
|
||||
import com.kingsrook.qbits.assistant.spi.AssistantModelProvider;
|
||||
import com.kingsrook.qbits.assistant.spi.CompletableStreamHandle;
|
||||
import com.kingsrook.qbits.assistant.spi.EmbeddingRequest;
|
||||
import com.kingsrook.qbits.assistant.spi.EmbeddingResponse;
|
||||
import com.kingsrook.qbits.assistant.spi.ModelCapabilities;
|
||||
import com.kingsrook.qbits.assistant.spi.ModelEventListener;
|
||||
import com.kingsrook.qbits.assistant.spi.ModelPart;
|
||||
import com.kingsrook.qbits.assistant.spi.ModelProviderException;
|
||||
import com.kingsrook.qbits.assistant.spi.ModelRequest;
|
||||
import com.kingsrook.qbits.assistant.spi.ModelResponse;
|
||||
import com.kingsrook.qbits.assistant.spi.ModelUsage;
|
||||
import com.kingsrook.qbits.assistant.spi.ProviderSettings;
|
||||
import com.kingsrook.qbits.assistant.spi.StreamHandle;
|
||||
|
||||
|
||||
/*******************************************************************************
|
||||
@@ -82,6 +84,84 @@ public class OpenAiCompatibleModelProvider implements AssistantModelProvider
|
||||
|
||||
|
||||
|
||||
/*******************************************************************************
|
||||
** One bounded batch, with the deadline covering headers and the entire body.
|
||||
** Restore input order from the response indexes; reject malformed vectors.
|
||||
*******************************************************************************/
|
||||
@Override
|
||||
public EmbeddingResponse embed(EmbeddingRequest request) throws ModelProviderException
|
||||
{
|
||||
ObjectNode body = OpenAiHttp.JSON.createObjectNode();
|
||||
body.put("model", request.model());
|
||||
body.set("input", OpenAiHttp.JSON.valueToTree(request.input()));
|
||||
var pending = http.client.sendAsync(http.request(request.model(), http.settings.getRequestTimeoutSeconds(), "embeddings")
|
||||
.POST(java.net.http.HttpRequest.BodyPublishers.ofString(body.toString())).build(), HttpResponse.BodyHandlers.ofString());
|
||||
try
|
||||
{
|
||||
HttpResponse<String> response = pending.get(http.settings.getRequestTimeoutSeconds(), TimeUnit.SECONDS);
|
||||
if(response.statusCode() != 200)
|
||||
{
|
||||
throw (http.error(response.statusCode(), response.body(), OpenAiHttp.requestId(response), false));
|
||||
}
|
||||
JsonNode json = OpenAiHttp.JSON.readTree(response.body());
|
||||
if(json.has("error"))
|
||||
{
|
||||
throw (http.error(500, response.body(), OpenAiHttp.requestId(response), false));
|
||||
}
|
||||
float[][] vectors = new float[request.input().size()][];
|
||||
Integer dimensions = null;
|
||||
for(JsonNode item : json.path("data"))
|
||||
{
|
||||
Integer index = item.path("index").asInt(-1);
|
||||
JsonNode values = item.path("embedding");
|
||||
if(index < 0 || index >= vectors.length || vectors[index] != null || !values.isArray() || values.isEmpty()
|
||||
|| (dimensions != null && dimensions != values.size()))
|
||||
{
|
||||
throw (new IOException("Invalid embedding response."));
|
||||
}
|
||||
dimensions = values.size();
|
||||
float[] vector = new float[dimensions];
|
||||
for(Integer i = 0; i < vector.length; i++)
|
||||
{
|
||||
if(!values.get(i).isNumber())
|
||||
{
|
||||
throw (new IOException("Invalid embedding coordinate."));
|
||||
}
|
||||
vector[i] = (float) values.get(i).asDouble();
|
||||
if(!Float.isFinite(vector[i]))
|
||||
{
|
||||
throw (new IOException("Non-finite embedding coordinate."));
|
||||
}
|
||||
}
|
||||
vectors[index] = vector;
|
||||
}
|
||||
if(java.util.Arrays.stream(vectors).anyMatch(java.util.Objects::isNull))
|
||||
{
|
||||
throw (new IOException("Missing embedding."));
|
||||
}
|
||||
return (new EmbeddingResponse(List.of(vectors), new ModelUsage().withInputTokens(json.path("usage").path("prompt_tokens").asLong()), OpenAiHttp.requestId(response)));
|
||||
}
|
||||
catch(java.util.concurrent.TimeoutException e)
|
||||
{
|
||||
throw (new ModelProviderException(ModelProviderException.Kind.TIMEOUT, null, "The provider did not answer in time."));
|
||||
}
|
||||
catch(InterruptedException e)
|
||||
{
|
||||
Thread.currentThread().interrupt();
|
||||
throw (new ModelProviderException(ModelProviderException.Kind.NETWORK, null, "The embedding request was interrupted."));
|
||||
}
|
||||
catch(java.util.concurrent.ExecutionException | IOException e)
|
||||
{
|
||||
throw (OpenAiHttp.transportError(e));
|
||||
}
|
||||
finally
|
||||
{
|
||||
pending.cancel(true);
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
|
||||
/*******************************************************************************
|
||||
** Conservative defaults; registry rows can override model-specific facts.
|
||||
*******************************************************************************/
|
||||
|
||||
+6
-6
@@ -18,12 +18,12 @@ package com.kingsrook.qbits.assistant.provider.openai;
|
||||
|
||||
|
||||
import java.util.List;
|
||||
import com.kingsrook.qbits.assistant.provider.AssistantModelProvider;
|
||||
import com.kingsrook.qbits.assistant.provider.AssistantProviderType;
|
||||
import com.kingsrook.qbits.assistant.provider.DiscoveredModel;
|
||||
import com.kingsrook.qbits.assistant.provider.HealthResult;
|
||||
import com.kingsrook.qbits.assistant.provider.ModelProviderException;
|
||||
import com.kingsrook.qbits.assistant.provider.ProviderSettings;
|
||||
import com.kingsrook.qbits.assistant.spi.AssistantModelProvider;
|
||||
import com.kingsrook.qbits.assistant.spi.AssistantProviderType;
|
||||
import com.kingsrook.qbits.assistant.spi.DiscoveredModel;
|
||||
import com.kingsrook.qbits.assistant.spi.HealthResult;
|
||||
import com.kingsrook.qbits.assistant.spi.ModelProviderException;
|
||||
import com.kingsrook.qbits.assistant.spi.ProviderSettings;
|
||||
|
||||
|
||||
/*******************************************************************************
|
||||
|
||||
+16
-6
@@ -33,12 +33,12 @@ import java.util.concurrent.CompletableFuture;
|
||||
import java.util.concurrent.ExecutionException;
|
||||
import java.util.concurrent.TimeUnit;
|
||||
import java.util.concurrent.TimeoutException;
|
||||
import javax.net.ssl.SSLHandshakeException;
|
||||
import com.fasterxml.jackson.databind.JsonNode;
|
||||
import com.fasterxml.jackson.databind.ObjectMapper;
|
||||
import com.kingsrook.qbits.assistant.provider.DiscoveredModel;
|
||||
import com.kingsrook.qbits.assistant.provider.ModelProviderException;
|
||||
import com.kingsrook.qbits.assistant.provider.ProviderSettings;
|
||||
import com.kingsrook.qbits.assistant.spi.DiscoveredModel;
|
||||
import com.kingsrook.qbits.assistant.spi.ModelProviderException;
|
||||
import com.kingsrook.qbits.assistant.spi.ProviderSettings;
|
||||
import javax.net.ssl.SSLHandshakeException;
|
||||
|
||||
|
||||
/*******************************************************************************
|
||||
@@ -84,13 +84,23 @@ final class OpenAiHttp
|
||||
** Azure uses deployment paths and a version query parameter.
|
||||
*******************************************************************************/
|
||||
HttpRequest.Builder request(String model, Integer seconds) throws ModelProviderException
|
||||
{
|
||||
return (request(model, seconds, "chat/completions"));
|
||||
}
|
||||
|
||||
|
||||
|
||||
/*******************************************************************************
|
||||
** Chat and embeddings share authentication, TLS, deadlines and Azure paths.
|
||||
*******************************************************************************/
|
||||
HttpRequest.Builder request(String model, Integer seconds, String operation) throws ModelProviderException
|
||||
{
|
||||
try
|
||||
{
|
||||
String path = model == null ? "/models" : "/chat/completions";
|
||||
String path = model == null ? "/models" : "/" + operation;
|
||||
if("AZURE_OPENAI".equals(settings.getKind()))
|
||||
{
|
||||
path = model == null ? "/openai/models" : "/openai/deployments/" + encode(model) + "/chat/completions";
|
||||
path = model == null ? "/openai/models" : "/openai/deployments/" + encode(model) + "/" + operation;
|
||||
path += "?api-version=" + encode(settings.getApiVersion() == null || settings.getApiVersion().isBlank() ? "2024-10-21" : settings.getApiVersion());
|
||||
}
|
||||
HttpRequest.Builder builder = HttpRequest.newBuilder(URI.create(base + path)).timeout(Duration.ofSeconds(seconds)).header("Content-Type", "application/json");
|
||||
|
||||
+6
-6
@@ -24,12 +24,12 @@ import com.fasterxml.jackson.core.JsonProcessingException;
|
||||
import com.fasterxml.jackson.databind.JsonNode;
|
||||
import com.fasterxml.jackson.databind.node.ArrayNode;
|
||||
import com.fasterxml.jackson.databind.node.ObjectNode;
|
||||
import com.kingsrook.qbits.assistant.provider.ModelCapabilities;
|
||||
import com.kingsrook.qbits.assistant.provider.ModelMessage;
|
||||
import com.kingsrook.qbits.assistant.provider.ModelPart;
|
||||
import com.kingsrook.qbits.assistant.provider.ModelRequest;
|
||||
import com.kingsrook.qbits.assistant.provider.ModelToolDefinition;
|
||||
import com.kingsrook.qbits.assistant.provider.SystemBlock;
|
||||
import com.kingsrook.qbits.assistant.spi.ModelCapabilities;
|
||||
import com.kingsrook.qbits.assistant.spi.ModelMessage;
|
||||
import com.kingsrook.qbits.assistant.spi.ModelPart;
|
||||
import com.kingsrook.qbits.assistant.spi.ModelRequest;
|
||||
import com.kingsrook.qbits.assistant.spi.ModelToolDefinition;
|
||||
import com.kingsrook.qbits.assistant.spi.SystemBlock;
|
||||
|
||||
|
||||
/*******************************************************************************
|
||||
|
||||
+4
-4
@@ -21,10 +21,10 @@ import java.nio.file.Path;
|
||||
import java.time.Duration;
|
||||
import java.util.List;
|
||||
import com.kingsrook.qbits.assistant.AssistantQBitConfig;
|
||||
import com.kingsrook.qbits.assistant.provider.ModelMessage;
|
||||
import com.kingsrook.qbits.assistant.provider.ModelProviderException;
|
||||
import com.kingsrook.qbits.assistant.provider.ModelRequest;
|
||||
import com.kingsrook.qbits.assistant.provider.ProviderSettings;
|
||||
import com.kingsrook.qbits.assistant.spi.ModelMessage;
|
||||
import com.kingsrook.qbits.assistant.spi.ModelProviderException;
|
||||
import com.kingsrook.qbits.assistant.spi.ModelRequest;
|
||||
import com.kingsrook.qbits.assistant.spi.ProviderSettings;
|
||||
import org.junit.jupiter.api.Assumptions;
|
||||
import org.junit.jupiter.api.Tag;
|
||||
import org.junit.jupiter.api.Test;
|
||||
|
||||
+10
-10
@@ -22,16 +22,16 @@ import java.util.ArrayList;
|
||||
import java.util.List;
|
||||
import java.util.Map;
|
||||
import com.fasterxml.jackson.databind.JsonNode;
|
||||
import com.kingsrook.qbits.assistant.provider.ModelCapabilities;
|
||||
import com.kingsrook.qbits.assistant.provider.ModelEventListener;
|
||||
import com.kingsrook.qbits.assistant.provider.ModelMessage;
|
||||
import com.kingsrook.qbits.assistant.provider.ModelPart;
|
||||
import com.kingsrook.qbits.assistant.provider.ModelProviderException;
|
||||
import com.kingsrook.qbits.assistant.provider.ModelRequest;
|
||||
import com.kingsrook.qbits.assistant.provider.ModelResponse;
|
||||
import com.kingsrook.qbits.assistant.provider.ModelToolDefinition;
|
||||
import com.kingsrook.qbits.assistant.provider.ProviderSettings;
|
||||
import com.kingsrook.qbits.assistant.provider.SystemBlock;
|
||||
import com.kingsrook.qbits.assistant.spi.ModelCapabilities;
|
||||
import com.kingsrook.qbits.assistant.spi.ModelEventListener;
|
||||
import com.kingsrook.qbits.assistant.spi.ModelMessage;
|
||||
import com.kingsrook.qbits.assistant.spi.ModelPart;
|
||||
import com.kingsrook.qbits.assistant.spi.ModelProviderException;
|
||||
import com.kingsrook.qbits.assistant.spi.ModelRequest;
|
||||
import com.kingsrook.qbits.assistant.spi.ModelResponse;
|
||||
import com.kingsrook.qbits.assistant.spi.ModelToolDefinition;
|
||||
import com.kingsrook.qbits.assistant.spi.ProviderSettings;
|
||||
import com.kingsrook.qbits.assistant.spi.SystemBlock;
|
||||
import org.junit.jupiter.api.Test;
|
||||
import org.junit.jupiter.params.ParameterizedTest;
|
||||
import org.junit.jupiter.params.provider.CsvSource;
|
||||
|
||||
+133
@@ -0,0 +1,133 @@
|
||||
/*
|
||||
* Copyright 2026 Kingsrook, LLC
|
||||
*
|
||||
* Licensed under the Apache License, Version 2.0 (the "License");
|
||||
* you may not use this file except in compliance with the License.
|
||||
* You may obtain a copy of the License at
|
||||
*
|
||||
* http://www.apache.org/licenses/LICENSE-2.0
|
||||
*
|
||||
* Unless required by applicable law or agreed to in writing, software
|
||||
* distributed under the License is distributed on an "AS IS" BASIS,
|
||||
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
|
||||
* See the License for the specific language governing permissions and
|
||||
* limitations under the License.
|
||||
*/
|
||||
|
||||
package com.kingsrook.qbits.assistant.provider.openai;
|
||||
|
||||
|
||||
import java.util.List;
|
||||
import com.kingsrook.qbits.assistant.spi.EmbeddingRequest;
|
||||
import com.kingsrook.qbits.assistant.spi.ModelProviderException;
|
||||
import com.kingsrook.qbits.assistant.spi.ProviderSettings;
|
||||
import org.junit.jupiter.api.Test;
|
||||
import static org.assertj.core.api.Assertions.assertThat;
|
||||
import static org.assertj.core.api.Assertions.assertThatThrownBy;
|
||||
|
||||
|
||||
/*******************************************************************************
|
||||
** Embedding wire contracts through the same local HTTP harness as chat.
|
||||
*******************************************************************************/
|
||||
class OpenAiEmbeddingTest
|
||||
{
|
||||
/*******************************************************************************
|
||||
** Input arrays, response indexes, usage and authentication are preserved.
|
||||
*******************************************************************************/
|
||||
@Test
|
||||
void shapeOrderAndAzure() throws Exception
|
||||
{
|
||||
for(String kind : List.of("OPENAI", "AZURE_OPENAI", "OLLAMA"))
|
||||
{
|
||||
try(MockOpenAiServer server = new MockOpenAiServer())
|
||||
{
|
||||
server.enqueue(200, "{\"data\":[{\"index\":1,\"embedding\":[0,1]},{\"index\":0,\"embedding\":[1,0]}],\"usage\":{\"prompt_tokens\":7}}");
|
||||
var provider = new OpenAiCompatibleModelProvider(new ProviderSettings().withKind(kind).withBaseUrl(server.url()).withApiKey("synthetic-key").withApiVersion("2024-10-21"));
|
||||
var response = provider.embed(new EmbeddingRequest("bge-m3", List.of("first", "second")));
|
||||
assertThat(response.vectors()).hasSize(2);
|
||||
assertThat(response.vectors().getFirst()).containsExactly(1, 0);
|
||||
assertThat(response.usage().getInputTokens()).isEqualTo(7L);
|
||||
var captured = server.requests.getFirst();
|
||||
assertThat(captured.path()).isEqualTo(kind.equals("AZURE_OPENAI") ? "/v1/openai/deployments/bge-m3/embeddings?api-version=2024-10-21" : "/v1/embeddings");
|
||||
var body = OpenAiHttp.JSON.readTree(captured.body());
|
||||
assertThat(body.path("model").asText()).isEqualTo("bge-m3");
|
||||
assertThat(body.path("input").size()).isEqualTo(2);
|
||||
assertThat(body.has("messages")).isFalse();
|
||||
assertThat(body.has("stream")).isFalse();
|
||||
assertThat(kind.equals("AZURE_OPENAI") ? captured.apiKey() : captured.authorization()).contains("synthetic-key");
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
|
||||
/*******************************************************************************
|
||||
** Reuse chat's safe error categories, without echoing credentials.
|
||||
*******************************************************************************/
|
||||
@Test
|
||||
void errorsAndMalformedVectors() throws Exception
|
||||
{
|
||||
try(MockOpenAiServer server = new MockOpenAiServer())
|
||||
{
|
||||
var provider = new OpenAiCompatibleModelProvider(new ProviderSettings().withKind("OPENAI").withBaseUrl(server.url()).withApiKey("synthetic-key"));
|
||||
server.enqueue(429, "{\"error\":{\"message\":\"synthetic-key rejected\"}}");
|
||||
assertThatThrownBy(() -> provider.embed(new EmbeddingRequest("embed", List.of("text"))))
|
||||
.isInstanceOfSatisfying(ModelProviderException.class, e ->
|
||||
{
|
||||
assertThat(e.getKind()).isEqualTo(ModelProviderException.Kind.RATE_LIMITED);
|
||||
assertThat(e.getMessage()).doesNotContain("synthetic-key");
|
||||
});
|
||||
for(String body : List.of("{}", "{\"data\":[{\"index\":0,\"embedding\":[\"not numeric\"]}]}",
|
||||
"{\"data\":[{\"index\":2,\"embedding\":[1]}]}", "{\"data\":[{\"index\":0,\"embedding\":[1]},{\"index\":0,\"embedding\":[1]}]}"))
|
||||
{
|
||||
server.enqueue(200, body);
|
||||
assertThatThrownBy(() -> provider.embed(new EmbeddingRequest("embed", List.of("text")))).isInstanceOf(ModelProviderException.class);
|
||||
}
|
||||
assertThatThrownBy(() -> new EmbeddingRequest("embed", java.util.Collections.nCopies(65, "text"))).isInstanceOf(IllegalArgumentException.class);
|
||||
assertThatThrownBy(() -> new EmbeddingRequest("embed", List.of())).isInstanceOf(IllegalArgumentException.class);
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
|
||||
/*******************************************************************************
|
||||
** Deadline covers a stalled response body, not only HTTP headers.
|
||||
*******************************************************************************/
|
||||
@Test
|
||||
void bodyTimeout() throws Exception
|
||||
{
|
||||
try(MockOpenAiServer server = new MockOpenAiServer())
|
||||
{
|
||||
server.stall(true);
|
||||
var provider = new OpenAiCompatibleModelProvider(new ProviderSettings().withKind("OLLAMA").withBaseUrl(server.url()).withRequestTimeoutSeconds(1));
|
||||
assertThatThrownBy(() -> provider.embed(new EmbeddingRequest("embed", List.of("text"))))
|
||||
.isInstanceOfSatisfying(ModelProviderException.class, e -> assertThat(e.getKind()).isEqualTo(ModelProviderException.Kind.TIMEOUT));
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
|
||||
/*******************************************************************************
|
||||
** The transport accepts a complete 64-input batch and rejects overflow
|
||||
** before sending. EmbeddingService owns splitting larger indexing jobs.
|
||||
*******************************************************************************/
|
||||
@Test
|
||||
void maximumBatch() throws Exception
|
||||
{
|
||||
try(MockOpenAiServer server = new MockOpenAiServer())
|
||||
{
|
||||
var body = OpenAiHttp.JSON.createObjectNode();
|
||||
var data = body.putArray("data");
|
||||
for(Integer i = 0; i < 64; i++)
|
||||
{
|
||||
data.addObject().put("index", i).putArray("embedding").add(1).add(0);
|
||||
}
|
||||
server.enqueue(200, body.toString());
|
||||
var provider = new OpenAiCompatibleModelProvider(new ProviderSettings().withKind("OLLAMA").withBaseUrl(server.url()));
|
||||
assertThat(provider.embed(new EmbeddingRequest("embed", java.util.Collections.nCopies(64, "text"))).vectors()).hasSize(64);
|
||||
assertThat(OpenAiHttp.JSON.readTree(server.requests.getFirst().body()).path("input").size()).isEqualTo(64);
|
||||
assertThatThrownBy(() -> provider.embed(new EmbeddingRequest("embed", java.util.Collections.nCopies(65, "text")))).isInstanceOf(IllegalArgumentException.class);
|
||||
assertThat(server.requests).hasSize(1);
|
||||
}
|
||||
}
|
||||
}
|
||||
+4
-4
@@ -24,14 +24,14 @@ import java.nio.file.Path;
|
||||
import java.security.KeyStore;
|
||||
import java.time.Duration;
|
||||
import java.util.Set;
|
||||
import javax.net.ssl.KeyManagerFactory;
|
||||
import javax.net.ssl.SSLContext;
|
||||
import com.kingsrook.qbits.assistant.AssistantQBitConfig;
|
||||
import com.kingsrook.qbits.assistant.model.AssistantProvider;
|
||||
import com.kingsrook.qbits.assistant.provider.ModelProviderException;
|
||||
import com.kingsrook.qbits.assistant.provider.ProviderSettings;
|
||||
import com.kingsrook.qbits.assistant.spi.ModelProviderException;
|
||||
import com.kingsrook.qbits.assistant.spi.ProviderSettings;
|
||||
import com.kingsrook.qbits.assistant.testing.AssistantTestFixture;
|
||||
import com.kingsrook.qqq.backend.core.context.QContext;
|
||||
import javax.net.ssl.KeyManagerFactory;
|
||||
import javax.net.ssl.SSLContext;
|
||||
import org.junit.jupiter.api.Test;
|
||||
import org.junit.jupiter.api.io.TempDir;
|
||||
import static org.assertj.core.api.Assertions.assertThat;
|
||||
|
||||
+96
-12
@@ -21,8 +21,13 @@ import java.io.IOException;
|
||||
import java.math.BigDecimal;
|
||||
import java.net.InetSocketAddress;
|
||||
import java.nio.charset.StandardCharsets;
|
||||
import java.util.ArrayList;
|
||||
import java.util.LinkedHashMap;
|
||||
import java.util.List;
|
||||
import java.util.Map;
|
||||
import java.util.Set;
|
||||
import com.fasterxml.jackson.databind.JsonNode;
|
||||
import com.fasterxml.jackson.databind.ObjectMapper;
|
||||
import com.kingsrook.qbits.assistant.AssistantQBitConfig;
|
||||
import com.kingsrook.qbits.assistant.metadata.AssistantMetaDataBuilder;
|
||||
import com.kingsrook.qbits.assistant.model.AssistantModel;
|
||||
@@ -31,10 +36,13 @@ import com.kingsrook.qbits.assistant.persistence.AssistantStore;
|
||||
import com.kingsrook.qbits.assistant.processes.DiscoverModelsProcess;
|
||||
import com.kingsrook.qbits.assistant.processes.TestConnectionProcess;
|
||||
import com.kingsrook.qbits.assistant.processes.TestModelConnectionProcess;
|
||||
import com.kingsrook.qbits.assistant.provider.AssistantProviderType;
|
||||
import com.kingsrook.qbits.assistant.provider.fake.ScriptedModelProvider;
|
||||
import com.kingsrook.qbits.assistant.provider.openai.OpenAiCompatibleProviderType;
|
||||
import com.kingsrook.qbits.assistant.spi.AssistantProviderType;
|
||||
import com.kingsrook.qbits.assistant.testing.AssistantTestFixture;
|
||||
import com.kingsrook.qbits.assistant.testing.EvalSupport;
|
||||
import com.kingsrook.qbits.assistant.testing.GoldenTasks;
|
||||
import com.kingsrook.qbits.assistant.testing.PresentationGoldenTask;
|
||||
import com.kingsrook.qbits.assistant.testing.TurnRunner;
|
||||
import com.kingsrook.qqq.backend.core.actions.processes.QProcessCallbackFactory;
|
||||
import com.kingsrook.qqq.backend.core.actions.processes.RunProcessAction;
|
||||
@@ -61,6 +69,8 @@ public class OpenAiDemoServer extends AbstractQQQApplication
|
||||
{
|
||||
private static final String ADMIN = "admin-demo";
|
||||
private static final String MODEL = "qwen3:30b-a3b";
|
||||
private static final String IMAGE_QUESTION = "How many images do I have by type?";
|
||||
private static final ObjectMapper JSON = new ObjectMapper();
|
||||
private static QInstance instance;
|
||||
|
||||
|
||||
@@ -160,6 +170,8 @@ public class OpenAiDemoServer extends AbstractQQQApplication
|
||||
{
|
||||
throw (new QException("Demo assistant turn failed: " + outcome.errorCode()));
|
||||
}
|
||||
TurnRunner.Outcome presentation = new TurnRunner(instance, config).run(ADMIN, IMAGE_QUESTION);
|
||||
PresentationGoldenTask.check(presentation);
|
||||
instance.withInstanceDefaultAuthentication(new QAuthenticationMetaData().withName("mock").withType(QAuthenticationType.MOCK)
|
||||
.withCustomizer(new QCodeReference(DemoSessionCustomizer.class)));
|
||||
instance.setHomeAppName(AssistantMetaDataBuilder.APP_NAME);
|
||||
@@ -167,6 +179,7 @@ public class OpenAiDemoServer extends AbstractQQQApplication
|
||||
System.out.println("Assistant home: http://localhost:" + port + "/app/" + AssistantMetaDataBuilder.APP_NAME);
|
||||
System.out.println("Local provider: http://localhost:" + port + "/app/assistant_provider/" + providerId);
|
||||
System.out.println("Local model: http://localhost:" + port + "/app/assistant_model/" + modelId);
|
||||
System.out.println("Image presentation conversation id: " + presentation.conversationId());
|
||||
}
|
||||
|
||||
|
||||
@@ -211,7 +224,7 @@ public class OpenAiDemoServer extends AbstractQQQApplication
|
||||
{
|
||||
try(exchange)
|
||||
{
|
||||
exchange.getRequestBody().readAllBytes();
|
||||
byte[] request = exchange.getRequestBody().readAllBytes();
|
||||
String path = exchange.getRequestURI().getPath();
|
||||
String body;
|
||||
if("GET".equals(exchange.getRequestMethod()) && "/v1/models".equals(path))
|
||||
@@ -227,16 +240,7 @@ public class OpenAiDemoServer extends AbstractQQQApplication
|
||||
else if("POST".equals(exchange.getRequestMethod()) && "/v1/chat/completions".equals(path))
|
||||
{
|
||||
exchange.getResponseHeaders().set("Content-Type", "text/event-stream");
|
||||
body = """
|
||||
data: {"id":"demo-completion","object":"chat.completion.chunk","choices":[{"index":0,"delta":{"role":"assistant","content":"Hello from the local demo provider."}}]}
|
||||
|
||||
data: {"choices":[{"index":0,"delta":{},"finish_reason":"stop"}]}
|
||||
|
||||
data: {"choices":[],"usage":{"prompt_tokens":24,"completion_tokens":8,"total_tokens":32}}
|
||||
|
||||
data: [DONE]
|
||||
|
||||
""";
|
||||
body = completion(JSON.readTree(request));
|
||||
}
|
||||
else
|
||||
{
|
||||
@@ -248,4 +252,84 @@ public class OpenAiDemoServer extends AbstractQQQApplication
|
||||
exchange.getResponseBody().flush();
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
|
||||
/*******************************************************************************
|
||||
** Follow the latest user turn, so connection tests and repeated chats are
|
||||
** independent. Counts are read from the adapter's actual tool messages.
|
||||
*******************************************************************************/
|
||||
private static String completion(JsonNode request) throws IOException
|
||||
{
|
||||
String question = "";
|
||||
Map<String, Integer> counts = new LinkedHashMap<>();
|
||||
boolean presented = false;
|
||||
for(JsonNode message : request.path("messages"))
|
||||
{
|
||||
if("user".equals(message.path("role").asText()))
|
||||
{
|
||||
question = message.path("content").asText();
|
||||
counts.clear();
|
||||
presented = false;
|
||||
}
|
||||
else if("tool".equals(message.path("role").asText()) && IMAGE_QUESTION.equals(question))
|
||||
{
|
||||
String id = message.path("tool_call_id").asText();
|
||||
if(id.startsWith("count-image/"))
|
||||
{
|
||||
counts.put(id.substring("count-".length()), ((Number) EvalSupport.unwrap(message.path("content").asText()).get("count")).intValue());
|
||||
}
|
||||
else if("present-images".equals(id))
|
||||
{
|
||||
presented = true;
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
Map<String, Object> delta = Map.of("role", "assistant", "content", "Hello from the local demo provider.");
|
||||
String finish = "stop";
|
||||
if(IMAGE_QUESTION.equals(question) && !presented)
|
||||
{
|
||||
List<Map<String, Object>> calls = new ArrayList<>();
|
||||
if(counts.isEmpty())
|
||||
{
|
||||
for(String mime : List.of("image/jpeg", "image/png", "image/webp", "image/gif", "image/svg+xml"))
|
||||
{
|
||||
calls.add(toolCall(calls.size(), "count-" + mime, "count_records", Map.of("table", "media", "filter",
|
||||
GoldenTasks.filter("AND", GoldenTasks.criterion("mimeType", "EQUALS", mime)))));
|
||||
}
|
||||
}
|
||||
else
|
||||
{
|
||||
if(counts.size() != 5 || counts.get("image/webp") != 0 || counts.get("image/gif") != 0 || counts.get("image/svg+xml") != 0)
|
||||
{
|
||||
throw (new IOException("Unexpected demo image counts."));
|
||||
}
|
||||
Map<String, Object> input = PresentationGoldenTask.input(counts.get("image/jpeg"), counts.get("image/png"));
|
||||
input.put("actions", List.of(Map.of("label", "Show the PNG files", "prompt", "Show the PNG files")));
|
||||
calls.add(toolCall(0, "present-images", "present_results", input));
|
||||
}
|
||||
delta = Map.of("role", "assistant", "tool_calls", calls);
|
||||
finish = "tool_calls";
|
||||
}
|
||||
else if(presented)
|
||||
{
|
||||
delta = Map.of("role", "assistant", "content", "You can open either image type above.");
|
||||
}
|
||||
return ("data: " + JSON.writeValueAsString(Map.of("id", "demo-completion", "object", "chat.completion.chunk",
|
||||
"choices", List.of(Map.of("index", 0, "delta", delta)))) + "\n\n"
|
||||
+ "data: " + JSON.writeValueAsString(Map.of("choices", List.of(Map.of("index", 0, "delta", Map.of(), "finish_reason", finish)))) + "\n\n"
|
||||
+ "data: {\"choices\":[],\"usage\":{\"prompt_tokens\":24,\"completion_tokens\":8,\"total_tokens\":32}}\n\n"
|
||||
+ "data: [DONE]\n\n");
|
||||
}
|
||||
|
||||
|
||||
|
||||
/*******************************************************************************
|
||||
** Encode tool arguments as a JSON string, as OpenAI streaming requires.
|
||||
*******************************************************************************/
|
||||
private static Map<String, Object> toolCall(Integer index, String id, String name, Map<String, Object> arguments) throws IOException
|
||||
{
|
||||
return (Map.of("index", index, "id", id, "type", "function", "function", Map.of("name", name, "arguments", JSON.writeValueAsString(arguments))));
|
||||
}
|
||||
}
|
||||
+13
-2
@@ -29,6 +29,11 @@ Startup prints these URLs (with the selected port):
|
||||
- Local provider: `http://localhost:8099/app/assistant_provider/1`
|
||||
- Priced and tested model: `http://localhost:8099/app/assistant_model/1`
|
||||
|
||||
Startup also prints `Image presentation conversation id: <id>`. Open that
|
||||
conversation in the assistant panel history as `admin-demo` to capture the
|
||||
answer to "How many images do I have by type?". The id is assigned on each run;
|
||||
the conversation and its presentation are memory-backed and reset on restart.
|
||||
|
||||
Every browser session is `admin-demo`. Startup inserts an enabled, default,
|
||||
keyless Local GPU (Ollama) provider, marked LOCAL and HIPAA eligible for the
|
||||
synthetic demo, and a disabled CLOUD OpenRouter provider whose key is Not set.
|
||||
@@ -40,8 +45,14 @@ mock: `qwen3:30b-a3b`, `gpt-oss:20b`, `qwen3-coder:30b`, and `bge-m3`.
|
||||
A normal update sets qwen3's input/output compute prices to $0.05/$0.10 per
|
||||
million tokens. The provider and model Test connection processes then each
|
||||
make a real HTTP completion call, recording two TEST usage rows and the
|
||||
last-test fields. One assistant turn records a third usage row with purpose
|
||||
TURN. Discovery timestamps/status also come from the actual process.
|
||||
last-test fields. The greeting turn records a third usage row with purpose
|
||||
TURN. An image breakdown turn then makes three more model calls through the
|
||||
real OpenAI adapter and engine: five MIME-filtered `count_records` calls,
|
||||
`present_results` using the returned counts, and a short closing message.
|
||||
The fixture seeds 81 JPEG and 20 PNG rows (no WebP, GIF or SVG). The presentation
|
||||
includes a table with computed shares, filtered row links, a pie chart, JPEG
|
||||
and PNG filter links, and a "Show the PNG files" prompt action.
|
||||
Discovery timestamps/status also come from the actual process.
|
||||
|
||||
Replies and token counts are synthetic mock API responses (24 input / 8 output
|
||||
tokens per completion), not live GPU measurements or billed cloud usage.
|
||||
|
||||
@@ -45,9 +45,14 @@
|
||||
<artifactId>qbit-assistant-provider-openai</artifactId>
|
||||
</dependency>
|
||||
|
||||
<dependency>
|
||||
<groupId>com.kingsrook.qbits</groupId>
|
||||
<artifactId>qbit-assistant-provider-api</artifactId>
|
||||
</dependency>
|
||||
<dependency>
|
||||
<groupId>com.kingsrook.qbits</groupId>
|
||||
<artifactId>qbit-assistant</artifactId>
|
||||
<scope>test</scope>
|
||||
</dependency>
|
||||
<dependency>
|
||||
<groupId>com.kingsrook.qqq</groupId>
|
||||
|
||||
+6
-6
@@ -23,14 +23,14 @@ import com.anthropic.client.okhttp.AnthropicOkHttpClient;
|
||||
import com.anthropic.core.Timeout;
|
||||
import com.anthropic.vertex.backends.VertexBackend;
|
||||
import com.google.auth.oauth2.GoogleCredentials;
|
||||
import com.kingsrook.qbits.assistant.provider.AssistantModelProvider;
|
||||
import com.kingsrook.qbits.assistant.provider.ModelCapabilities;
|
||||
import com.kingsrook.qbits.assistant.provider.ModelEventListener;
|
||||
import com.kingsrook.qbits.assistant.provider.ModelRequest;
|
||||
import com.kingsrook.qbits.assistant.provider.ProviderSettings;
|
||||
import com.kingsrook.qbits.assistant.provider.StreamHandle;
|
||||
import com.kingsrook.qbits.assistant.provider.anthropic.AnthropicModelProvider;
|
||||
import com.kingsrook.qbits.assistant.provider.openai.OpenAiCompatibleModelProvider;
|
||||
import com.kingsrook.qbits.assistant.spi.AssistantModelProvider;
|
||||
import com.kingsrook.qbits.assistant.spi.ModelCapabilities;
|
||||
import com.kingsrook.qbits.assistant.spi.ModelEventListener;
|
||||
import com.kingsrook.qbits.assistant.spi.ModelRequest;
|
||||
import com.kingsrook.qbits.assistant.spi.ProviderSettings;
|
||||
import com.kingsrook.qbits.assistant.spi.StreamHandle;
|
||||
|
||||
|
||||
/*******************************************************************************
|
||||
|
||||
+8
-9
@@ -19,11 +19,10 @@ package com.kingsrook.qbits.assistant.provider.vertex;
|
||||
|
||||
import java.util.ArrayList;
|
||||
import java.util.List;
|
||||
import com.kingsrook.qbits.assistant.model.AssistantProvider;
|
||||
import com.kingsrook.qbits.assistant.provider.AssistantModelProvider;
|
||||
import com.kingsrook.qbits.assistant.provider.AssistantProviderType;
|
||||
import com.kingsrook.qbits.assistant.provider.DiscoveredModel;
|
||||
import com.kingsrook.qbits.assistant.provider.ProviderSettings;
|
||||
import com.kingsrook.qbits.assistant.spi.AssistantModelProvider;
|
||||
import com.kingsrook.qbits.assistant.spi.AssistantProviderType;
|
||||
import com.kingsrook.qbits.assistant.spi.DiscoveredModel;
|
||||
import com.kingsrook.qbits.assistant.spi.ProviderSettings;
|
||||
|
||||
|
||||
/*******************************************************************************
|
||||
@@ -104,18 +103,18 @@ public class VertexProviderType implements AssistantProviderType
|
||||
** Validate cloud settings without loading credentials.
|
||||
*******************************************************************************/
|
||||
@Override
|
||||
public List<String> validate(AssistantProvider row)
|
||||
public List<String> validate(ProviderSettings settings)
|
||||
{
|
||||
List<String> errors = new ArrayList<>();
|
||||
if(row.getRegion() == null || row.getRegion().isBlank())
|
||||
if(settings.getRegion() == null || settings.getRegion().isBlank())
|
||||
{
|
||||
errors.add("Region is required for VERTEX.");
|
||||
}
|
||||
if(row.getApiKeyEnvName() != null && !row.getApiKeyEnvName().isBlank())
|
||||
if(settings.getApiKeyEnvName() != null && !settings.getApiKeyEnvName().isBlank())
|
||||
{
|
||||
errors.add("Leave API key variable empty: Google Vertex AI (Claude, Gemini) uses Google Application Default Credentials (GOOGLE_APPLICATION_CREDENTIALS or workload identity).");
|
||||
}
|
||||
if(row.getCloudProject() == null || row.getCloudProject().isBlank())
|
||||
if(settings.getCloudProject() == null || settings.getCloudProject().isBlank())
|
||||
{
|
||||
errors.add("GCP project id (cloudProject) is required for VERTEX.");
|
||||
}
|
||||
|
||||
+5
-5
@@ -29,11 +29,11 @@ import com.google.auth.oauth2.GoogleCredentials;
|
||||
import com.kingsrook.qbits.assistant.AssistantQBitConfig;
|
||||
import com.kingsrook.qbits.assistant.engine.ProviderService;
|
||||
import com.kingsrook.qbits.assistant.model.AssistantProvider;
|
||||
import com.kingsrook.qbits.assistant.provider.ModelMessage;
|
||||
import com.kingsrook.qbits.assistant.provider.ModelProviderException;
|
||||
import com.kingsrook.qbits.assistant.provider.ModelRequest;
|
||||
import com.kingsrook.qbits.assistant.provider.ModelToolDefinition;
|
||||
import com.kingsrook.qbits.assistant.provider.ProviderSettings;
|
||||
import com.kingsrook.qbits.assistant.spi.ModelMessage;
|
||||
import com.kingsrook.qbits.assistant.spi.ModelProviderException;
|
||||
import com.kingsrook.qbits.assistant.spi.ModelRequest;
|
||||
import com.kingsrook.qbits.assistant.spi.ModelToolDefinition;
|
||||
import com.kingsrook.qbits.assistant.spi.ProviderSettings;
|
||||
import com.kingsrook.qbits.assistant.testing.CloudProviderTestServer;
|
||||
import org.junit.jupiter.api.Test;
|
||||
import org.junit.jupiter.params.ParameterizedTest;
|
||||
|
||||
@@ -0,0 +1,130 @@
|
||||
<?xml version="1.0" encoding="UTF-8"?>
|
||||
<!--
|
||||
~ Copyright 2026 Kingsrook, LLC
|
||||
~
|
||||
~ Licensed under the Apache License, Version 2.0 (the "License");
|
||||
~ you may not use this file except in compliance with the License.
|
||||
~ You may obtain a copy of the License at
|
||||
~
|
||||
~ http://www.apache.org/licenses/LICENSE-2.0
|
||||
~
|
||||
~ Unless required by applicable law or agreed to in writing, software
|
||||
~ distributed under the License is distributed on an "AS IS" BASIS,
|
||||
~ WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
|
||||
~ See the License for the specific language governing permissions and
|
||||
~ limitations under the License.
|
||||
-->
|
||||
|
||||
<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
|
||||
<modelVersion>4.0.0</modelVersion>
|
||||
|
||||
<parent>
|
||||
<groupId>com.kingsrook.qbits</groupId>
|
||||
<artifactId>qbit-assistant-parent</artifactId>
|
||||
<version>${revision}</version>
|
||||
</parent>
|
||||
|
||||
<artifactId>qbit-assistant-rag-pgvector</artifactId>
|
||||
<packaging>jar</packaging>
|
||||
|
||||
<name>QBit Assistant - pgvector</name>
|
||||
<description>Content-free per-instance vector storage through JDBC</description>
|
||||
<url>https://github.com/QRun-IO/qbit-assistant</url>
|
||||
|
||||
<dependencies>
|
||||
<dependency>
|
||||
<groupId>com.kingsrook.qbits</groupId>
|
||||
<artifactId>qbit-assistant</artifactId>
|
||||
</dependency>
|
||||
<dependency>
|
||||
<groupId>com.kingsrook.qqq</groupId>
|
||||
<artifactId>qqq-backend-core</artifactId>
|
||||
</dependency>
|
||||
<dependency>
|
||||
<groupId>org.testcontainers</groupId>
|
||||
<artifactId>junit-jupiter</artifactId>
|
||||
<version>1.21.4</version>
|
||||
<scope>test</scope>
|
||||
</dependency>
|
||||
<dependency>
|
||||
<groupId>org.testcontainers</groupId>
|
||||
<artifactId>postgresql</artifactId>
|
||||
<version>1.21.4</version>
|
||||
<scope>test</scope>
|
||||
</dependency>
|
||||
<dependency>
|
||||
<groupId>org.postgresql</groupId>
|
||||
<artifactId>postgresql</artifactId>
|
||||
<version>42.7.14</version>
|
||||
<scope>test</scope>
|
||||
</dependency>
|
||||
<dependency>
|
||||
<groupId>org.junit.jupiter</groupId>
|
||||
<artifactId>junit-jupiter</artifactId>
|
||||
<scope>test</scope>
|
||||
</dependency>
|
||||
<dependency>
|
||||
<groupId>org.assertj</groupId>
|
||||
<artifactId>assertj-core</artifactId>
|
||||
<scope>test</scope>
|
||||
</dependency>
|
||||
</dependencies>
|
||||
|
||||
<build>
|
||||
<plugins>
|
||||
<plugin>
|
||||
<groupId>org.apache.maven.plugins</groupId>
|
||||
<artifactId>maven-surefire-plugin</artifactId>
|
||||
<configuration>
|
||||
<!-- live evals call the real API: opt-in only -->
|
||||
<excludedGroups>${test.excludedGroups}</excludedGroups>
|
||||
<redirectTestOutputToFile>true</redirectTestOutputToFile>
|
||||
</configuration>
|
||||
</plugin>
|
||||
<plugin>
|
||||
<groupId>org.jacoco</groupId>
|
||||
<artifactId>jacoco-maven-plugin</artifactId>
|
||||
<executions>
|
||||
<execution>
|
||||
<id>prepare-agent</id>
|
||||
<goals>
|
||||
<goal>prepare-agent</goal>
|
||||
</goals>
|
||||
</execution>
|
||||
<execution>
|
||||
<id>report</id>
|
||||
<phase>verify</phase>
|
||||
<goals>
|
||||
<goal>report</goal>
|
||||
</goals>
|
||||
</execution>
|
||||
<execution>
|
||||
<id>check</id>
|
||||
<goals>
|
||||
<goal>check</goal>
|
||||
</goals>
|
||||
<configuration>
|
||||
<rules>
|
||||
<rule>
|
||||
<element>BUNDLE</element>
|
||||
<limits>
|
||||
<limit>
|
||||
<counter>INSTRUCTION</counter>
|
||||
<value>COVEREDRATIO</value>
|
||||
<minimum>0.70</minimum>
|
||||
</limit>
|
||||
<limit>
|
||||
<counter>CLASS</counter>
|
||||
<value>COVEREDRATIO</value>
|
||||
<minimum>0.90</minimum>
|
||||
</limit>
|
||||
</limits>
|
||||
</rule>
|
||||
</rules>
|
||||
</configuration>
|
||||
</execution>
|
||||
</executions>
|
||||
</plugin>
|
||||
</plugins>
|
||||
</build>
|
||||
</project>
|
||||
+452
@@ -0,0 +1,452 @@
|
||||
/*
|
||||
* Copyright 2026 Kingsrook, LLC
|
||||
*
|
||||
* Licensed under the Apache License, Version 2.0 (the "License");
|
||||
* you may not use this file except in compliance with the License.
|
||||
* You may obtain a copy of the License at
|
||||
*
|
||||
* http://www.apache.org/licenses/LICENSE-2.0
|
||||
*
|
||||
* Unless required by applicable law or agreed to in writing, software
|
||||
* distributed under the License is distributed on an "AS IS" BASIS,
|
||||
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
|
||||
* See the License for the specific language governing permissions and
|
||||
* limitations under the License.
|
||||
*/
|
||||
|
||||
package com.kingsrook.qbits.assistant.rag.pgvector;
|
||||
|
||||
|
||||
import java.sql.Connection;
|
||||
import java.sql.PreparedStatement;
|
||||
import java.sql.ResultSet;
|
||||
import java.sql.SQLException;
|
||||
import java.util.ArrayList;
|
||||
import java.util.Collections;
|
||||
import java.util.List;
|
||||
import java.util.Set;
|
||||
import java.util.StringJoiner;
|
||||
import javax.sql.DataSource;
|
||||
import com.kingsrook.qbits.assistant.rag.ChunkVector;
|
||||
import com.kingsrook.qbits.assistant.rag.VectorStore;
|
||||
import com.kingsrook.qqq.backend.core.exceptions.QException;
|
||||
|
||||
|
||||
/*******************************************************************************
|
||||
** Host-supplied JDBC only, without QQQ RDBMS internals. No text is ever stored.
|
||||
*******************************************************************************/
|
||||
public class PgVectorStore implements VectorStore
|
||||
{
|
||||
private final ConnectionSupplier connections;
|
||||
private final Integer dimensions;
|
||||
private String schema = "assistant_rag";
|
||||
|
||||
|
||||
|
||||
/*******************************************************************************
|
||||
** The host owns credentials and connection pooling; each call closes its lease.
|
||||
*******************************************************************************/
|
||||
@FunctionalInterface
|
||||
public interface ConnectionSupplier
|
||||
{
|
||||
/*******************************************************************************
|
||||
** Return a connection owned by this caller until it closes it.
|
||||
*******************************************************************************/
|
||||
Connection open() throws SQLException;
|
||||
}
|
||||
|
||||
|
||||
|
||||
/*******************************************************************************
|
||||
** Use any host DataSource and a fixed vector dimension for this instance.
|
||||
*******************************************************************************/
|
||||
public PgVectorStore(DataSource dataSource, Integer dimensions)
|
||||
{
|
||||
this(dataSource::getConnection, dimensions);
|
||||
}
|
||||
|
||||
|
||||
|
||||
/*******************************************************************************
|
||||
** HNSW vector cosine indexes support up to 2000 dimensions.
|
||||
*******************************************************************************/
|
||||
public PgVectorStore(ConnectionSupplier connections, Integer dimensions)
|
||||
{
|
||||
if(connections == null || dimensions == null || dimensions < 1 || dimensions > 2000)
|
||||
{
|
||||
throw (new IllegalArgumentException("A connection supplier and 1 to 2000 dimensions are required."));
|
||||
}
|
||||
this.connections = connections;
|
||||
this.dimensions = dimensions;
|
||||
}
|
||||
|
||||
|
||||
|
||||
/*******************************************************************************
|
||||
** Configure before use. Identifiers cannot be parameters, so validate strictly.
|
||||
*******************************************************************************/
|
||||
public PgVectorStore withSchema(String schema)
|
||||
{
|
||||
if(schema == null || !schema.matches("[a-z_][a-z0-9_]{0,62}"))
|
||||
{
|
||||
throw (new IllegalArgumentException("The vector schema must be a lower-case SQL identifier of at most 63 characters."));
|
||||
}
|
||||
this.schema = schema;
|
||||
return (this);
|
||||
}
|
||||
|
||||
|
||||
|
||||
/*******************************************************************************
|
||||
** The DBA normally installs vector. An existing extension needs no elevated
|
||||
** privileges; if absent, attempt installation and report an actionable error.
|
||||
*******************************************************************************/
|
||||
public void ensureSchema() throws QException
|
||||
{
|
||||
try(Connection connection = connections.open())
|
||||
{
|
||||
try(PreparedStatement check = connection.prepareStatement("SELECT 1 FROM pg_extension WHERE extname = ?"))
|
||||
{
|
||||
check.setString(1, "vector");
|
||||
try(ResultSet rows = check.executeQuery())
|
||||
{
|
||||
if(!rows.next())
|
||||
{
|
||||
try(PreparedStatement extension = connection.prepareStatement("CREATE EXTENSION IF NOT EXISTS vector"))
|
||||
{
|
||||
extension.execute();
|
||||
}
|
||||
catch(SQLException e)
|
||||
{
|
||||
throw (new QException("Ask the DBA to run CREATE EXTENSION IF NOT EXISTS vector in this database, then retry.", e));
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
for(String sql : List.of("CREATE SCHEMA IF NOT EXISTS " + schema,
|
||||
"CREATE TABLE IF NOT EXISTS " + table() + " (id BIGSERIAL PRIMARY KEY, source_id INT NOT NULL, table_name TEXT NOT NULL, record_pk TEXT NOT NULL, field_name TEXT NOT NULL, chunk_index INT NOT NULL, content_hash CHAR(64) NOT NULL, embedding vector(" + dimensions + ") NOT NULL, indexed_at TIMESTAMPTZ NOT NULL DEFAULT CURRENT_TIMESTAMP, UNIQUE(source_id, table_name, record_pk, field_name, chunk_index))",
|
||||
"CREATE INDEX IF NOT EXISTS assistant_rag_chunk_cosine ON " + table() + " USING hnsw (embedding vector_cosine_ops)"))
|
||||
{
|
||||
try(PreparedStatement statement = connection.prepareStatement(sql))
|
||||
{
|
||||
statement.execute();
|
||||
}
|
||||
}
|
||||
}
|
||||
catch(SQLException e)
|
||||
{
|
||||
throw (failure(e));
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
|
||||
/*******************************************************************************
|
||||
** Validate the entire batch before sending anything to JDBC.
|
||||
*******************************************************************************/
|
||||
@Override
|
||||
public void upsert(List<ChunkVector> chunks) throws QException
|
||||
{
|
||||
chunks.forEach(chunk -> vector(chunk.embedding()));
|
||||
try(Connection connection = connections.open())
|
||||
{
|
||||
upsert(connection, chunks);
|
||||
}
|
||||
catch(SQLException e)
|
||||
{
|
||||
throw (failure(e));
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
|
||||
/*******************************************************************************
|
||||
** Values, including vectors and arbitrary record keys, are bound parameters.
|
||||
*******************************************************************************/
|
||||
private void upsert(Connection connection, List<ChunkVector> chunks) throws SQLException
|
||||
{
|
||||
String sql = "INSERT INTO " + table() + " (source_id, table_name, record_pk, field_name, chunk_index, content_hash, embedding) VALUES (?, ?, ?, ?, ?, ?, ?::vector) ON CONFLICT (source_id, table_name, record_pk, field_name, chunk_index) DO UPDATE SET content_hash = EXCLUDED.content_hash, embedding = EXCLUDED.embedding, indexed_at = CURRENT_TIMESTAMP";
|
||||
try(PreparedStatement statement = connection.prepareStatement(sql))
|
||||
{
|
||||
for(ChunkVector chunk : chunks)
|
||||
{
|
||||
statement.setInt(1, chunk.source());
|
||||
statement.setString(2, chunk.table());
|
||||
statement.setString(3, chunk.pk());
|
||||
statement.setString(4, chunk.field());
|
||||
statement.setInt(5, chunk.chunkIndex());
|
||||
statement.setString(6, chunk.contentHash());
|
||||
statement.setString(7, vector(chunk.embedding()));
|
||||
statement.addBatch();
|
||||
}
|
||||
statement.executeBatch();
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
|
||||
/*******************************************************************************
|
||||
** A record replacement is transactional, including empty replacements.
|
||||
*******************************************************************************/
|
||||
@Override
|
||||
public void replaceRecord(Integer source, String table, String pk, List<ChunkVector> chunks) throws QException
|
||||
{
|
||||
for(ChunkVector chunk : chunks)
|
||||
{
|
||||
vector(chunk.embedding());
|
||||
if(!source.equals(chunk.source()) || !table.equals(chunk.table()) || !pk.equals(chunk.pk()))
|
||||
{
|
||||
throw (new IllegalArgumentException("Replacement chunks must belong to the specified record."));
|
||||
}
|
||||
}
|
||||
try(Connection connection = connections.open())
|
||||
{
|
||||
Boolean autoCommit = connection.getAutoCommit();
|
||||
connection.setAutoCommit(false);
|
||||
try
|
||||
{
|
||||
deleteRecord(connection, source, table, pk);
|
||||
upsert(connection, chunks);
|
||||
connection.commit();
|
||||
}
|
||||
catch(SQLException e)
|
||||
{
|
||||
connection.rollback();
|
||||
throw (e);
|
||||
}
|
||||
finally
|
||||
{
|
||||
connection.setAutoCommit(autoCommit);
|
||||
}
|
||||
}
|
||||
catch(SQLException e)
|
||||
{
|
||||
throw (failure(e));
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
|
||||
/*******************************************************************************
|
||||
** Remove one record, always scoped to its source.
|
||||
*******************************************************************************/
|
||||
@Override
|
||||
public void deleteRecord(Integer source, String table, String pk) throws QException
|
||||
{
|
||||
try(Connection connection = connections.open())
|
||||
{
|
||||
deleteRecord(connection, source, table, pk);
|
||||
}
|
||||
catch(SQLException e)
|
||||
{
|
||||
throw (failure(e));
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
|
||||
/*******************************************************************************
|
||||
** Shared transactional delete statement.
|
||||
*******************************************************************************/
|
||||
private void deleteRecord(Connection connection, Integer source, String table, String pk) throws SQLException
|
||||
{
|
||||
try(PreparedStatement statement = connection.prepareStatement("DELETE FROM " + table() + " WHERE source_id = ? AND table_name = ? AND record_pk = ?"))
|
||||
{
|
||||
statement.setInt(1, source);
|
||||
statement.setString(2, table);
|
||||
statement.setString(3, pk);
|
||||
statement.executeUpdate();
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
|
||||
/*******************************************************************************
|
||||
** Clear a source, preserving every other source in the instance.
|
||||
*******************************************************************************/
|
||||
@Override
|
||||
public void deleteSource(Integer source) throws QException
|
||||
{
|
||||
try(Connection connection = connections.open(); PreparedStatement statement = connection.prepareStatement("DELETE FROM " + table() + " WHERE source_id = ?"))
|
||||
{
|
||||
statement.setInt(1, source);
|
||||
statement.executeUpdate();
|
||||
}
|
||||
catch(SQLException e)
|
||||
{
|
||||
throw (failure(e));
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
|
||||
/*******************************************************************************
|
||||
** HNSW cosine ordering; tables are values, never interpolated SQL identifiers.
|
||||
*******************************************************************************/
|
||||
@Override
|
||||
public List<Hit> search(float[] query, Integer k, Set<String> tables) throws QException
|
||||
{
|
||||
return (search(query, k, tables, Set.of()));
|
||||
}
|
||||
|
||||
|
||||
|
||||
/*******************************************************************************
|
||||
** Apply enabled compatible source restrictions before the nearest-hit limit.
|
||||
*******************************************************************************/
|
||||
@Override
|
||||
public List<Hit> search(float[] query, Integer k, Set<String> tables, Set<Integer> sources) throws QException
|
||||
{
|
||||
if(tables.isEmpty() || k <= 0)
|
||||
{
|
||||
return (List.of());
|
||||
}
|
||||
String vector = vector(query);
|
||||
String sql = "SELECT source_id, table_name, record_pk, field_name, chunk_index, 1 - (embedding <=> ?::vector) AS score FROM " + table()
|
||||
+ " WHERE table_name IN (" + String.join(", ", Collections.nCopies(tables.size(), "?")) + ")"
|
||||
+ (sources.isEmpty() ? "" : " AND source_id IN (" + String.join(", ", Collections.nCopies(sources.size(), "?")) + ")")
|
||||
+ " ORDER BY embedding <=> ?::vector LIMIT ?";
|
||||
try(Connection connection = connections.open(); PreparedStatement statement = connection.prepareStatement(sql))
|
||||
{
|
||||
Integer parameter = 1;
|
||||
statement.setString(parameter++, vector);
|
||||
for(String table : tables)
|
||||
{
|
||||
statement.setString(parameter++, table);
|
||||
}
|
||||
for(Integer source : sources)
|
||||
{
|
||||
statement.setInt(parameter++, source);
|
||||
}
|
||||
statement.setString(parameter++, vector);
|
||||
statement.setInt(parameter, k);
|
||||
List<Hit> hits = new ArrayList<>();
|
||||
try(ResultSet rows = statement.executeQuery())
|
||||
{
|
||||
while(rows.next())
|
||||
{
|
||||
Double score = rows.getDouble("score");
|
||||
if(Double.isFinite(score))
|
||||
{
|
||||
hits.add(new Hit(rows.getInt("source_id"), rows.getString("table_name"), rows.getString("record_pk"), rows.getString("field_name"), rows.getInt("chunk_index"), score));
|
||||
}
|
||||
}
|
||||
}
|
||||
return (hits);
|
||||
}
|
||||
catch(SQLException e)
|
||||
{
|
||||
throw (failure(e));
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
|
||||
/*******************************************************************************
|
||||
** Count chunks for the source's status screen.
|
||||
*******************************************************************************/
|
||||
@Override
|
||||
public Long count(Integer source) throws QException
|
||||
{
|
||||
try(Connection connection = connections.open(); PreparedStatement statement = connection.prepareStatement("SELECT COUNT(*) FROM " + table() + " WHERE source_id = ?"))
|
||||
{
|
||||
statement.setInt(1, source);
|
||||
try(ResultSet rows = statement.executeQuery())
|
||||
{
|
||||
rows.next();
|
||||
return (rows.getLong(1));
|
||||
}
|
||||
}
|
||||
catch(SQLException e)
|
||||
{
|
||||
throw (failure(e));
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
|
||||
/*******************************************************************************
|
||||
** Content-free reconciliation data. Embedding text is pgvector's numeric form.
|
||||
*******************************************************************************/
|
||||
@Override
|
||||
public List<ChunkVector> chunks(Integer source) throws QException
|
||||
{
|
||||
try(Connection connection = connections.open(); PreparedStatement statement = connection.prepareStatement("SELECT table_name, record_pk, field_name, chunk_index, content_hash, embedding::text FROM " + table() + " WHERE source_id = ?"))
|
||||
{
|
||||
statement.setInt(1, source);
|
||||
List<ChunkVector> chunks = new ArrayList<>();
|
||||
try(ResultSet rows = statement.executeQuery())
|
||||
{
|
||||
while(rows.next())
|
||||
{
|
||||
chunks.add(new ChunkVector(source, rows.getString("table_name"), rows.getString("record_pk"), rows.getString("field_name"), rows.getInt("chunk_index"), rows.getString("content_hash"), parse(rows.getString("embedding"))));
|
||||
}
|
||||
}
|
||||
return (chunks);
|
||||
}
|
||||
catch(SQLException e)
|
||||
{
|
||||
throw (failure(e));
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
|
||||
/*******************************************************************************
|
||||
** Qualified name uses only the validated instance schema.
|
||||
*******************************************************************************/
|
||||
private String table()
|
||||
{
|
||||
return (schema + ".assistant_rag_chunk");
|
||||
}
|
||||
|
||||
|
||||
|
||||
/*******************************************************************************
|
||||
** Serialize only finite coordinates with the configured dimension.
|
||||
*******************************************************************************/
|
||||
private String vector(float[] vector)
|
||||
{
|
||||
if(vector == null || vector.length != dimensions)
|
||||
{
|
||||
throw (new IllegalArgumentException("Vector dimensions differ from the configured pgvector schema."));
|
||||
}
|
||||
StringJoiner values = new StringJoiner(",", "[", "]");
|
||||
for(float value : vector)
|
||||
{
|
||||
if(!Float.isFinite(value))
|
||||
{
|
||||
throw (new IllegalArgumentException("Vector coordinates must be finite."));
|
||||
}
|
||||
values.add(Float.toString(value));
|
||||
}
|
||||
return (values.toString());
|
||||
}
|
||||
|
||||
|
||||
|
||||
/*******************************************************************************
|
||||
** Parse the database's numeric representation without any source content.
|
||||
*******************************************************************************/
|
||||
private float[] parse(String text)
|
||||
{
|
||||
String[] parts = text.substring(1, text.length() - 1).split(",");
|
||||
float[] vector = new float[parts.length];
|
||||
for(Integer i = 0; i < parts.length; i++)
|
||||
{
|
||||
vector[i] = Float.parseFloat(parts[i]);
|
||||
}
|
||||
vector(vector);
|
||||
return (vector);
|
||||
}
|
||||
|
||||
|
||||
|
||||
/*******************************************************************************
|
||||
** Do not expose database URLs, SQL values or credentials in tool responses.
|
||||
*******************************************************************************/
|
||||
private static QException failure(SQLException cause)
|
||||
{
|
||||
return (new QException("The knowledge vector store is unavailable. Check its schema, dimensions and database permissions.", cause));
|
||||
}
|
||||
}
|
||||
+76
@@ -0,0 +1,76 @@
|
||||
/*
|
||||
* Copyright 2026 Kingsrook, LLC
|
||||
*
|
||||
* Licensed under the Apache License, Version 2.0 (the "License");
|
||||
* you may not use this file except in compliance with the License.
|
||||
* You may obtain a copy of the License at
|
||||
*
|
||||
* http://www.apache.org/licenses/LICENSE-2.0
|
||||
*
|
||||
* Unless required by applicable law or agreed to in writing, software
|
||||
* distributed under the License is distributed on an "AS IS" BASIS,
|
||||
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
|
||||
* See the License for the specific language governing permissions and
|
||||
* limitations under the License.
|
||||
*/
|
||||
|
||||
package com.kingsrook.qbits.assistant.rag.pgvector;
|
||||
|
||||
|
||||
import java.sql.DriverManager;
|
||||
import java.util.List;
|
||||
import java.util.Set;
|
||||
import com.kingsrook.qbits.assistant.rag.ChunkVector;
|
||||
import com.kingsrook.qbits.assistant.rag.TextChunks;
|
||||
import org.junit.jupiter.api.Test;
|
||||
import org.testcontainers.containers.PostgreSQLContainer;
|
||||
import org.testcontainers.junit.jupiter.Container;
|
||||
import org.testcontainers.junit.jupiter.Testcontainers;
|
||||
import org.testcontainers.utility.DockerImageName;
|
||||
import static org.assertj.core.api.Assertions.assertThat;
|
||||
|
||||
|
||||
/*******************************************************************************
|
||||
** Real pgvector contract; skipped automatically on hosts without Docker.
|
||||
*******************************************************************************/
|
||||
@Testcontainers(disabledWithoutDocker = true)
|
||||
class PgVectorContainerTest
|
||||
{
|
||||
@Container
|
||||
static final PostgreSQLContainer<?> POSTGRES = new PostgreSQLContainer<>(DockerImageName.parse("pgvector/pgvector:pg16").asCompatibleSubstituteFor("postgres"));
|
||||
|
||||
|
||||
|
||||
/*******************************************************************************
|
||||
** DDL idempotence, cosine ranking, upsert, deletes and instance isolation.
|
||||
*******************************************************************************/
|
||||
@Test
|
||||
void realVectorLifecycle() throws Exception
|
||||
{
|
||||
PgVectorStore.ConnectionSupplier connections = () -> DriverManager.getConnection(POSTGRES.getJdbcUrl(), POSTGRES.getUsername(), POSTGRES.getPassword());
|
||||
PgVectorStore store = new PgVectorStore(connections, 3).withSchema("instance_one");
|
||||
PgVectorStore other = new PgVectorStore(connections, 3).withSchema("instance_two");
|
||||
store.ensureSchema();
|
||||
store.ensureSchema();
|
||||
other.ensureSchema();
|
||||
ChunkVector first = new ChunkVector(1, "article", "1", "body", 0, TextChunks.hash("one"), new float[] { 1, 0, 0 });
|
||||
ChunkVector second = new ChunkVector(1, "article", "2", "body", 0, TextChunks.hash("two"), new float[] { 0, 1, 0 });
|
||||
store.upsert(List.of(first, second));
|
||||
store.upsert(List.of(first));
|
||||
assertThat(store.count(1)).isEqualTo(2);
|
||||
assertThat(other.count(1)).isZero();
|
||||
assertThat(store.search(new float[] { 1, 0, 0 }, 1, Set.of("article"))).singleElement().satisfies(hit ->
|
||||
{
|
||||
assertThat(hit.pk()).isEqualTo("1");
|
||||
assertThat(hit.score()).isEqualTo(1.0);
|
||||
});
|
||||
assertThat(store.chunks(1)).hasSize(2);
|
||||
store.replaceRecord(1, "article", "1", List.of());
|
||||
assertThat(store.count(1)).isEqualTo(1);
|
||||
store.deleteRecord(1, "article", "2");
|
||||
assertThat(store.count(1)).isZero();
|
||||
store.upsert(List.of(first));
|
||||
store.deleteSource(1);
|
||||
assertThat(store.count(1)).isZero();
|
||||
}
|
||||
}
|
||||
+228
@@ -0,0 +1,228 @@
|
||||
/*
|
||||
* Copyright 2026 Kingsrook, LLC
|
||||
*
|
||||
* Licensed under the Apache License, Version 2.0 (the "License");
|
||||
* you may not use this file except in compliance with the License.
|
||||
* You may obtain a copy of the License at
|
||||
*
|
||||
* http://www.apache.org/licenses/LICENSE-2.0
|
||||
*
|
||||
* Unless required by applicable law or agreed to in writing, software
|
||||
* distributed under the License is distributed on an "AS IS" BASIS,
|
||||
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
|
||||
* See the License for the specific language governing permissions and
|
||||
* limitations under the License.
|
||||
*/
|
||||
|
||||
package com.kingsrook.qbits.assistant.rag.pgvector;
|
||||
|
||||
|
||||
import java.lang.reflect.Proxy;
|
||||
import java.sql.Connection;
|
||||
import java.sql.PreparedStatement;
|
||||
import java.sql.ResultSet;
|
||||
import java.sql.SQLException;
|
||||
import java.util.ArrayList;
|
||||
import java.util.HashMap;
|
||||
import java.util.List;
|
||||
import java.util.Map;
|
||||
import java.util.Set;
|
||||
import javax.sql.DataSource;
|
||||
import com.kingsrook.qbits.assistant.rag.ChunkVector;
|
||||
import com.kingsrook.qbits.assistant.rag.TextChunks;
|
||||
import org.junit.jupiter.api.Test;
|
||||
import static org.assertj.core.api.Assertions.assertThat;
|
||||
import static org.assertj.core.api.Assertions.assertThatThrownBy;
|
||||
|
||||
|
||||
/*******************************************************************************
|
||||
** Always-on JDBC SQL-shape and transaction tests, with no Docker dependency.
|
||||
*******************************************************************************/
|
||||
class PgVectorStoreTest
|
||||
{
|
||||
private final List<String> sql = new ArrayList<>();
|
||||
private final List<Map<Integer, Object>> parameters = new ArrayList<>();
|
||||
private final List<String> operations = new ArrayList<>();
|
||||
private Boolean extensionExists = true;
|
||||
private Boolean failBatch = false;
|
||||
private Boolean failExtension = false;
|
||||
|
||||
|
||||
|
||||
/*******************************************************************************
|
||||
** JDBC recording connection; values never appear in SQL text.
|
||||
*******************************************************************************/
|
||||
private Connection connection()
|
||||
{
|
||||
return ((Connection) Proxy.newProxyInstance(getClass().getClassLoader(), new Class<?>[] { Connection.class }, (proxy, method, args) ->
|
||||
{
|
||||
operations.add(method.getName());
|
||||
if(method.getName().equals("prepareStatement"))
|
||||
{
|
||||
return (statement((String) args[0]));
|
||||
}
|
||||
return (method.getName().equals("getAutoCommit") ? true : null);
|
||||
}));
|
||||
}
|
||||
|
||||
|
||||
|
||||
/*******************************************************************************
|
||||
** Capture each binding and emulate rows or SQL failures.
|
||||
*******************************************************************************/
|
||||
private PreparedStatement statement(String query)
|
||||
{
|
||||
sql.add(query);
|
||||
Map<Integer, Object> values = new HashMap<>();
|
||||
parameters.add(values);
|
||||
return ((PreparedStatement) Proxy.newProxyInstance(getClass().getClassLoader(), new Class<?>[] { PreparedStatement.class }, (proxy, method, args) ->
|
||||
{
|
||||
if(method.getName().startsWith("set"))
|
||||
{
|
||||
values.put((Integer) args[0], args[1]);
|
||||
}
|
||||
if(method.getName().equals("executeQuery"))
|
||||
{
|
||||
return (rows(query));
|
||||
}
|
||||
if(method.getName().equals("executeBatch"))
|
||||
{
|
||||
if(failBatch)
|
||||
{
|
||||
throw (new SQLException("synthetic batch failure"));
|
||||
}
|
||||
return (new int[] { 1 });
|
||||
}
|
||||
if(method.getName().equals("executeUpdate"))
|
||||
{
|
||||
return (1);
|
||||
}
|
||||
if(method.getName().equals("execute"))
|
||||
{
|
||||
if(failExtension && query.startsWith("CREATE EXTENSION"))
|
||||
{
|
||||
throw (new SQLException("extension privilege required"));
|
||||
}
|
||||
return (true);
|
||||
}
|
||||
return (null);
|
||||
}));
|
||||
}
|
||||
|
||||
|
||||
|
||||
/*******************************************************************************
|
||||
** One content-free result; the extension probe can return no rows.
|
||||
*******************************************************************************/
|
||||
private ResultSet rows(String query)
|
||||
{
|
||||
Boolean[] first = { true };
|
||||
return ((ResultSet) Proxy.newProxyInstance(getClass().getClassLoader(), new Class<?>[] { ResultSet.class }, (proxy, method, args) ->
|
||||
{
|
||||
if(method.getName().equals("next"))
|
||||
{
|
||||
Boolean next = first[0] && (!query.contains("pg_extension") || extensionExists);
|
||||
first[0] = false;
|
||||
return (next);
|
||||
}
|
||||
return (switch(method.getName())
|
||||
{
|
||||
case "getString" -> switch(String.valueOf(args[0]))
|
||||
{
|
||||
case "content_hash" -> TextChunks.hash("synthetic");
|
||||
case "embedding" -> "[1,0,0]";
|
||||
case "record_pk" -> "pk'; --";
|
||||
case "field_name" -> "body";
|
||||
default -> "article";
|
||||
};
|
||||
case "getInt" -> "chunk_index".equals(args[0]) ? 0 : 1;
|
||||
case "getLong" -> 1L;
|
||||
case "getDouble" -> 1.0;
|
||||
default -> null;
|
||||
});
|
||||
}));
|
||||
}
|
||||
|
||||
|
||||
|
||||
/*******************************************************************************
|
||||
** Exercise every statement with values that would be unsafe to interpolate.
|
||||
*******************************************************************************/
|
||||
@Test
|
||||
void statementsAreBoundAndContentFree() throws Exception
|
||||
{
|
||||
PgVectorStore store = new PgVectorStore(this::connection, 3).withSchema("instance_one");
|
||||
store.ensureSchema();
|
||||
assertThat(sql).anyMatch(s -> s.contains("embedding vector(3)"));
|
||||
assertThat(sql).anyMatch(s -> s.contains("USING hnsw (embedding vector_cosine_ops)"));
|
||||
assertThat(sql).noneMatch(s -> s.contains("CREATE EXTENSION"));
|
||||
ChunkVector chunk = new ChunkVector(1, "article", "pk'; --", "body", 0, TextChunks.hash("synthetic"), new float[] { 1, 0, 0 });
|
||||
store.upsert(List.of(chunk));
|
||||
store.replaceRecord(1, "article", "pk'; --", List.of(chunk));
|
||||
assertThat(store.search(new float[] { 1, 0, 0 }, 8, Set.of("article", "injection'; --"))).hasSize(1);
|
||||
assertThat(store.search(new float[] { 1, 0, 0 }, 8, Set.of("article"), Set.of(1))).hasSize(1);
|
||||
assertThat(store.chunks(1)).singleElement().satisfies(v -> assertThat(v.embedding()).containsExactly(1, 0, 0));
|
||||
assertThat(store.count(1)).isEqualTo(1);
|
||||
store.deleteRecord(1, "article", "pk'; --");
|
||||
store.deleteSource(1);
|
||||
assertThat(sql).anyMatch(s -> s.contains("?::vector") && s.contains("ON CONFLICT"));
|
||||
assertThat(sql).anyMatch(s -> s.contains("ORDER BY embedding <=> ?::vector LIMIT ?"));
|
||||
assertThat(sql).noneMatch(s -> s.contains("pk'; --") || s.contains("injection'; --") || s.contains("synthetic"));
|
||||
assertThat(parameters).anyMatch(p -> p.containsValue("pk'; --"));
|
||||
assertThat(parameters).anyMatch(p -> p.containsValue("injection'; --"));
|
||||
assertThat(operations).contains("commit", "close", "setAutoCommit");
|
||||
assertThat(store.search(new float[] { 1, 0, 0 }, 8, Set.of())).isEmpty();
|
||||
assertThat(store.search(new float[] { 1, 0, 0 }, 0, Set.of("article"))).isEmpty();
|
||||
DataSource dataSource = (DataSource) Proxy.newProxyInstance(getClass().getClassLoader(), new Class<?>[] { DataSource.class }, (p, method, args) -> connection());
|
||||
assertThat(new PgVectorStore(dataSource, 3).count(1)).isEqualTo(1);
|
||||
}
|
||||
|
||||
|
||||
|
||||
/*******************************************************************************
|
||||
** DBA failure is actionable; failed replacement rolls back before closing.
|
||||
*******************************************************************************/
|
||||
@Test
|
||||
void extensionAndRollback() throws Exception
|
||||
{
|
||||
extensionExists = false;
|
||||
PgVectorStore store = new PgVectorStore(this::connection, 3);
|
||||
store.ensureSchema();
|
||||
assertThat(sql).contains("CREATE EXTENSION IF NOT EXISTS vector");
|
||||
failExtension = true;
|
||||
assertThatThrownBy(store::ensureSchema).hasMessageContaining("DBA");
|
||||
failBatch = true;
|
||||
assertThatThrownBy(() -> store.replaceRecord(1, "article", "1", List.of())).hasMessageContaining("vector store");
|
||||
assertThat(operations).contains("rollback");
|
||||
PgVectorStore down = new PgVectorStore(() ->
|
||||
{
|
||||
throw (new SQLException("offline"));
|
||||
}, 3);
|
||||
assertThatThrownBy(down::ensureSchema).hasMessageContaining("vector store");
|
||||
assertThatThrownBy(() -> down.count(1)).hasMessageContaining("vector store");
|
||||
assertThatThrownBy(() -> down.chunks(1)).hasMessageContaining("vector store");
|
||||
assertThatThrownBy(() -> down.upsert(List.of())).hasMessageContaining("vector store");
|
||||
assertThatThrownBy(() -> down.deleteRecord(1, "a", "1")).hasMessageContaining("vector store");
|
||||
assertThatThrownBy(() -> down.deleteSource(1)).hasMessageContaining("vector store");
|
||||
assertThatThrownBy(() -> down.search(new float[] { 1, 0, 0 }, 8, Set.of("a"))).hasMessageContaining("vector store");
|
||||
}
|
||||
|
||||
|
||||
|
||||
/*******************************************************************************
|
||||
** Identifier and coordinate validation happens before opening a connection.
|
||||
*******************************************************************************/
|
||||
@Test
|
||||
void invalidInputsNeverReachJdbc()
|
||||
{
|
||||
PgVectorStore store = new PgVectorStore(this::connection, 3);
|
||||
for(String name : List.of("a.b", "bad; DROP SCHEMA public", "UPPER", "a".repeat(64)))
|
||||
{
|
||||
assertThatThrownBy(() -> store.withSchema(name)).isInstanceOf(IllegalArgumentException.class);
|
||||
}
|
||||
assertThatThrownBy(() -> new PgVectorStore(this::connection, 2001)).isInstanceOf(IllegalArgumentException.class);
|
||||
assertThatThrownBy(() -> store.search(new float[] { 1 }, 1, Set.of("a"))).isInstanceOf(IllegalArgumentException.class);
|
||||
assertThatThrownBy(() -> store.search(new float[] { Float.NaN, 0, 0 }, 1, Set.of("a"))).isInstanceOf(IllegalArgumentException.class);
|
||||
assertThat(operations).isEmpty();
|
||||
}
|
||||
}
|
||||
+47
-1
@@ -28,10 +28,14 @@
|
||||
<packaging>jar</packaging>
|
||||
|
||||
<name>QBit Assistant</name>
|
||||
<description>In-app AI assistant QBit for QQQ: conversations, turn engine, SSE routes, budgets, provider SPI</description>
|
||||
<description>In-app AI assistant QBit for QQQ: conversations, turn engine, SSE routes, budgets and provider registry</description>
|
||||
<url>https://github.com/QRun-IO/qbit-assistant</url>
|
||||
|
||||
<dependencies>
|
||||
<dependency>
|
||||
<groupId>com.kingsrook.qbits</groupId>
|
||||
<artifactId>qbit-assistant-provider-api</artifactId>
|
||||
</dependency>
|
||||
<dependency>
|
||||
<groupId>com.kingsrook.qqq</groupId>
|
||||
<artifactId>qqq-backend-core</artifactId>
|
||||
@@ -45,6 +49,15 @@
|
||||
<optional>true</optional>
|
||||
</dependency>
|
||||
|
||||
<!-- Optional email delivery of scheduled-task results. Every reference is in -->
|
||||
<!-- the email package; without the jar nothing changes. -->
|
||||
<dependency>
|
||||
<groupId>com.kingsrook.qbits</groupId>
|
||||
<artifactId>qbit-email</artifactId>
|
||||
<version>${qbit-email.version}</version>
|
||||
<optional>true</optional>
|
||||
</dependency>
|
||||
|
||||
<dependency>
|
||||
<groupId>org.junit.jupiter</groupId>
|
||||
<artifactId>junit-jupiter</artifactId>
|
||||
@@ -60,6 +73,39 @@
|
||||
<artifactId>archunit-junit5</artifactId>
|
||||
<scope>test</scope>
|
||||
</dependency>
|
||||
<!-- AssistantDefaultsChangelogTest runs the shipped seed changelog against H2 (PostgreSQL mode). -->
|
||||
<dependency>
|
||||
<groupId>com.h2database</groupId>
|
||||
<artifactId>h2</artifactId>
|
||||
<version>2.3.232</version>
|
||||
<scope>test</scope>
|
||||
</dependency>
|
||||
<!-- ...through real Liquibase (the version kof22 runs), so preconditions and bookkeeping are exercised. -->
|
||||
<dependency>
|
||||
<groupId>org.liquibase</groupId>
|
||||
<artifactId>liquibase-core</artifactId>
|
||||
<version>4.33.0</version>
|
||||
<scope>test</scope>
|
||||
</dependency>
|
||||
<!-- the reference DDL guardrail (SchemaForeignKeyPostgresTest) -->
|
||||
<dependency>
|
||||
<groupId>org.testcontainers</groupId>
|
||||
<artifactId>junit-jupiter</artifactId>
|
||||
<version>1.21.4</version>
|
||||
<scope>test</scope>
|
||||
</dependency>
|
||||
<dependency>
|
||||
<groupId>org.testcontainers</groupId>
|
||||
<artifactId>postgresql</artifactId>
|
||||
<version>1.21.4</version>
|
||||
<scope>test</scope>
|
||||
</dependency>
|
||||
<dependency>
|
||||
<groupId>org.postgresql</groupId>
|
||||
<artifactId>postgresql</artifactId>
|
||||
<version>42.7.14</version>
|
||||
<scope>test</scope>
|
||||
</dependency>
|
||||
</dependencies>
|
||||
|
||||
<build>
|
||||
|
||||
+471
-6
@@ -32,13 +32,15 @@ import java.util.regex.Pattern;
|
||||
import com.fasterxml.jackson.annotation.JsonIgnore;
|
||||
import com.kingsrook.qbits.assistant.classification.ClassificationSource;
|
||||
import com.kingsrook.qbits.assistant.classification.ConfiguredClassificationSource;
|
||||
import com.kingsrook.qbits.assistant.classification.DataClassification;
|
||||
import com.kingsrook.qbits.assistant.engine.ModelPricing;
|
||||
import com.kingsrook.qbits.assistant.provider.AssistantModelProvider;
|
||||
import com.kingsrook.qbits.assistant.provider.AssistantProviderType;
|
||||
import com.kingsrook.qbits.assistant.provider.TrustedCaBundle;
|
||||
import com.kingsrook.qbits.assistant.jobs.AssistantRunTracker;
|
||||
import com.kingsrook.qbits.assistant.rag.VectorStore;
|
||||
import com.kingsrook.qbits.assistant.spi.AssistantModelProvider;
|
||||
import com.kingsrook.qbits.assistant.spi.AssistantProviderType;
|
||||
import com.kingsrook.qbits.assistant.spi.ModelPricing;
|
||||
import com.kingsrook.qbits.assistant.spi.TrustedCaBundle;
|
||||
import com.kingsrook.qbits.assistant.uiapi.UiApiGateway;
|
||||
import com.kingsrook.qqq.backend.core.actions.ai.AiExposure;
|
||||
import com.kingsrook.qqq.backend.core.actions.ai.DataClassification;
|
||||
import com.kingsrook.qqq.backend.core.model.metadata.QInstance;
|
||||
import com.kingsrook.qqq.backend.core.model.metadata.producers.MetaDataCustomizerInterface;
|
||||
import com.kingsrook.qqq.backend.core.model.metadata.qbits.QBitConfig;
|
||||
@@ -59,6 +61,8 @@ import com.kingsrook.qqq.backend.core.utils.StringUtils;
|
||||
*******************************************************************************/
|
||||
public class AssistantQBitConfig implements QBitConfig
|
||||
{
|
||||
private VectorStore vectorStore;
|
||||
|
||||
public static final String ACCESS_PERMISSION = "assistant.hasAccess";
|
||||
public static final String ADMIN_PERMISSION = "assistant.admin";
|
||||
public static final String DEFAULT_OWNER_KEY_TYPE = "assistant_user_id";
|
||||
@@ -87,6 +91,7 @@ public class AssistantQBitConfig implements QBitConfig
|
||||
private String conversationEncryptionKeyEnvName;
|
||||
|
||||
private Boolean enabled = true;
|
||||
private Boolean recordHistory = false;
|
||||
private String backendName;
|
||||
private String providerName = DEFAULT_PROVIDER_NAME;
|
||||
private AssistantModelRouting models = new AssistantModelRouting();
|
||||
@@ -95,18 +100,29 @@ public class AssistantQBitConfig implements QBitConfig
|
||||
private Integer maxParallelToolCalls = 4;
|
||||
private Integer maxRowsToModel = 50;
|
||||
private Integer maxCellChars = 500;
|
||||
private Integer turnHeartbeatSeconds = 5;
|
||||
private Integer turnLeaseSeconds = 45;
|
||||
private Integer turnForceFinalizeGraceSeconds = 20;
|
||||
private Integer shutdownGraceSeconds = 8;
|
||||
private String defaultConcurrencyMode = "SUPERSEDE";
|
||||
private Boolean registerShutdownHook = true;
|
||||
private AssistantRunTracker runTracker = AssistantRunTracker.NOOP;
|
||||
|
||||
private Integer maxTurnSeconds = 300;
|
||||
private Integer maxUserMessageChars = 8000;
|
||||
private Integer historyMessageLimit = 40;
|
||||
private AssistantBudgets budgets = new AssistantBudgets();
|
||||
private Integer maxTurnsPerUserPerMinute = 10;
|
||||
private Integer maxConcurrentTurnsPerUser = 1;
|
||||
private Integer maxConcurrentTurnsPerUser = 3;
|
||||
private Integer conversationRetentionDays = 90;
|
||||
private Integer toolResultRetentionDays = 30;
|
||||
private Integer approvalRetentionDays = 365;
|
||||
private Integer policyCacheSeconds = 30;
|
||||
private String ownerSecurityKeyType = DEFAULT_OWNER_KEY_TYPE;
|
||||
private String shortcut = DEFAULT_SHORTCUT;
|
||||
private Set<String> allowedScheduledCredentialEnvNames = new LinkedHashSet<>();
|
||||
private String scheduledTasksSchedulerName;
|
||||
|
||||
private String retentionSchedulerName;
|
||||
private Boolean registerRoutes = true;
|
||||
private Map<String, ModelPricing> pricing = ModelPricing.defaults();
|
||||
@@ -130,6 +146,7 @@ public class AssistantQBitConfig implements QBitConfig
|
||||
//////////////////////////////////////////////////////////////////////////
|
||||
private String uiApiBaseUrl;
|
||||
private UiApiGateway uiApiGateway;
|
||||
private com.kingsrook.qbits.assistant.tools.bulkload.BulkLoadRunner bulkLoadRunner;
|
||||
private Integer pendingActionTtlSeconds = 900;
|
||||
private List<String> customRedactionPatterns = new ArrayList<>();
|
||||
private Integer killSwitchPollMillis = 2000;
|
||||
@@ -138,11 +155,13 @@ public class AssistantQBitConfig implements QBitConfig
|
||||
private Integer providerTestTimeoutSeconds = 30;
|
||||
private Integer homeMaxRows = 20000;
|
||||
private String tablePathPrefix = "/app";
|
||||
private Boolean emailExternalApproved = false;
|
||||
|
||||
private transient MetaDataCustomizerInterface<QTableMetaData> tableMetaDataCustomizer;
|
||||
private transient Map<String, AssistantModelProvider> modelProviders = new LinkedHashMap<>();
|
||||
private transient Map<String, AssistantProviderType> providerTypes = new LinkedHashMap<>();
|
||||
private transient Function<String, String> secretResolver = System::getenv;
|
||||
private transient Function<String, String> emailRecipientResolver;
|
||||
private transient AssistantRuntime runtime;
|
||||
|
||||
|
||||
@@ -196,6 +215,23 @@ public class AssistantQBitConfig implements QBitConfig
|
||||
requirePositive(errors, "maxRowsToModel", maxRowsToModel);
|
||||
requirePositive(errors, "maxCellChars", maxCellChars);
|
||||
requirePositive(errors, "maxTurnSeconds", maxTurnSeconds);
|
||||
requirePositive(errors, "turnHeartbeatSeconds", turnHeartbeatSeconds);
|
||||
requirePositive(errors, "turnLeaseSeconds", turnLeaseSeconds);
|
||||
requirePositive(errors, "turnForceFinalizeGraceSeconds", turnForceFinalizeGraceSeconds);
|
||||
requirePositive(errors, "shutdownGraceSeconds", shutdownGraceSeconds);
|
||||
if(turnHeartbeatSeconds != null && turnLeaseSeconds != null && turnLeaseSeconds < 2 * turnHeartbeatSeconds)
|
||||
{
|
||||
errors.add("turnLeaseSeconds must be at least twice turnHeartbeatSeconds.");
|
||||
}
|
||||
if(!"SUPERSEDE".equals(defaultConcurrencyMode) && !"CONCURRENT".equals(defaultConcurrencyMode))
|
||||
{
|
||||
errors.add("defaultConcurrencyMode must be SUPERSEDE or CONCURRENT.");
|
||||
}
|
||||
if(turnHeartbeatSeconds != null && turnLeaseSeconds != null && turnHeartbeatSeconds >= turnLeaseSeconds)
|
||||
{
|
||||
errors.add("turnHeartbeatSeconds must be less than turnLeaseSeconds.");
|
||||
}
|
||||
|
||||
requirePositive(errors, "maxUserMessageChars", maxUserMessageChars);
|
||||
requirePositive(errors, "historyMessageLimit", historyMessageLimit);
|
||||
requirePositive(errors, "maxTurnsPerUserPerMinute", maxTurnsPerUserPerMinute);
|
||||
@@ -210,6 +246,13 @@ public class AssistantQBitConfig implements QBitConfig
|
||||
requirePositive(errors, "killSwitchPollMillis", killSwitchPollMillis);
|
||||
requirePositive(errors, "providerTestTimeoutSeconds", providerTestTimeoutSeconds);
|
||||
requirePositive(errors, "homeMaxRows", homeMaxRows);
|
||||
for(String name : allowedScheduledCredentialEnvNames == null ? Set.<String>of() : allowedScheduledCredentialEnvNames)
|
||||
{
|
||||
if(name == null || !ENV_NAME.matcher(name).matches())
|
||||
{
|
||||
errors.add("allowedScheduledCredentialEnvNames contains an invalid environment variable name.");
|
||||
}
|
||||
}
|
||||
for(String name : allowedApiKeyEnvNames == null ? Set.<String>of() : allowedApiKeyEnvNames)
|
||||
{
|
||||
if(name == null || !ENV_NAME.matcher(name).matches())
|
||||
@@ -1199,6 +1242,38 @@ public class AssistantQBitConfig implements QBitConfig
|
||||
|
||||
|
||||
|
||||
/*******************************************************************************
|
||||
** Getter for bulkLoadRunner (null: the durable jobs launch,
|
||||
** JobsLaunchBulkLoadRunner) - how bulk_load_run starts a load.
|
||||
*******************************************************************************/
|
||||
public com.kingsrook.qbits.assistant.tools.bulkload.BulkLoadRunner getBulkLoadRunner()
|
||||
{
|
||||
return (this.bulkLoadRunner);
|
||||
}
|
||||
|
||||
|
||||
|
||||
/*******************************************************************************
|
||||
** Setter for bulkLoadRunner
|
||||
*******************************************************************************/
|
||||
public void setBulkLoadRunner(com.kingsrook.qbits.assistant.tools.bulkload.BulkLoadRunner bulkLoadRunner)
|
||||
{
|
||||
this.bulkLoadRunner = bulkLoadRunner;
|
||||
}
|
||||
|
||||
|
||||
|
||||
/*******************************************************************************
|
||||
** Fluent setter for bulkLoadRunner
|
||||
*******************************************************************************/
|
||||
public AssistantQBitConfig withBulkLoadRunner(com.kingsrook.qbits.assistant.tools.bulkload.BulkLoadRunner bulkLoadRunner)
|
||||
{
|
||||
this.bulkLoadRunner = bulkLoadRunner;
|
||||
return (this);
|
||||
}
|
||||
|
||||
|
||||
|
||||
/*******************************************************************************
|
||||
** Getter for uiApiGateway (null: the loopback stand-in)
|
||||
*******************************************************************************/
|
||||
@@ -1456,6 +1531,62 @@ public class AssistantQBitConfig implements QBitConfig
|
||||
|
||||
|
||||
|
||||
/*******************************************************************************
|
||||
** Whether the host's EXTERNAL approval rule allows a scheduled task's result
|
||||
** to leave the app by email. There is no approval rule in the qbit yet (the
|
||||
** scheduled runner is P-g), so this explicit flag stands in; default false.
|
||||
*******************************************************************************/
|
||||
public Boolean getEmailExternalApproved()
|
||||
{
|
||||
return (this.emailExternalApproved);
|
||||
}
|
||||
|
||||
|
||||
|
||||
/*******************************************************************************
|
||||
** Setter for emailExternalApproved
|
||||
*******************************************************************************/
|
||||
public void setEmailExternalApproved(Boolean emailExternalApproved)
|
||||
{
|
||||
this.emailExternalApproved = emailExternalApproved;
|
||||
}
|
||||
|
||||
|
||||
|
||||
/*******************************************************************************
|
||||
** Fluent setter for emailExternalApproved
|
||||
*******************************************************************************/
|
||||
public AssistantQBitConfig withEmailExternalApproved(Boolean emailExternalApproved)
|
||||
{
|
||||
this.emailExternalApproved = emailExternalApproved;
|
||||
return (this);
|
||||
}
|
||||
|
||||
|
||||
|
||||
/*******************************************************************************
|
||||
** The hook that turns a task owner's user id into an email address; null
|
||||
** means the default (an owner id that already is an address).
|
||||
*******************************************************************************/
|
||||
@JsonIgnore
|
||||
public Function<String, String> getEmailRecipientResolver()
|
||||
{
|
||||
return (emailRecipientResolver);
|
||||
}
|
||||
|
||||
|
||||
|
||||
/*******************************************************************************
|
||||
** Fluent setter for emailRecipientResolver
|
||||
*******************************************************************************/
|
||||
public AssistantQBitConfig withEmailRecipientResolver(Function<String, String> emailRecipientResolver)
|
||||
{
|
||||
this.emailRecipientResolver = emailRecipientResolver;
|
||||
return (this);
|
||||
}
|
||||
|
||||
|
||||
|
||||
/*******************************************************************************
|
||||
** Getter for allowedApiKeyEnvNames (extra API key environment variable names a provider row may reference)
|
||||
*******************************************************************************/
|
||||
@@ -1654,6 +1785,28 @@ public class AssistantQBitConfig implements QBitConfig
|
||||
|
||||
|
||||
|
||||
/*******************************************************************************
|
||||
** Whether the host opts into record history; false by default.
|
||||
*******************************************************************************/
|
||||
public Boolean getRecordHistory()
|
||||
{
|
||||
return (recordHistory);
|
||||
}
|
||||
|
||||
|
||||
|
||||
/*******************************************************************************
|
||||
** Owner decision — hard wall: record history requires explicit host opt-in.
|
||||
** kof22 does not opt in. The user's own audit permissions still apply.
|
||||
*******************************************************************************/
|
||||
public AssistantQBitConfig withRecordHistory(boolean recordHistory)
|
||||
{
|
||||
this.recordHistory = recordHistory;
|
||||
return (this);
|
||||
}
|
||||
|
||||
|
||||
|
||||
/*******************************************************************************
|
||||
** Getter for hipaaMode
|
||||
*******************************************************************************/
|
||||
@@ -1788,4 +1941,316 @@ public class AssistantQBitConfig implements QBitConfig
|
||||
configuredClassifications.withClassification(tableName, fieldName, classification);
|
||||
return (this);
|
||||
}
|
||||
|
||||
|
||||
|
||||
/*******************************************************************************
|
||||
** Getter for vectorStore
|
||||
*******************************************************************************/
|
||||
public VectorStore getVectorStore()
|
||||
{
|
||||
return (vectorStore);
|
||||
}
|
||||
|
||||
|
||||
|
||||
/*******************************************************************************
|
||||
** Setter for vectorStore
|
||||
*******************************************************************************/
|
||||
public void setVectorStore(VectorStore vectorStore)
|
||||
{
|
||||
this.vectorStore = vectorStore;
|
||||
}
|
||||
|
||||
|
||||
|
||||
/*******************************************************************************
|
||||
** Fluent setter for vectorStore
|
||||
*******************************************************************************/
|
||||
public AssistantQBitConfig withVectorStore(VectorStore vectorStore)
|
||||
{
|
||||
this.vectorStore = vectorStore;
|
||||
return (this);
|
||||
}
|
||||
|
||||
|
||||
|
||||
/*******************************************************************************
|
||||
** Getter for allowedScheduledCredentialEnvNames
|
||||
*******************************************************************************/
|
||||
public Set<String> getAllowedScheduledCredentialEnvNames()
|
||||
{
|
||||
return (allowedScheduledCredentialEnvNames);
|
||||
}
|
||||
|
||||
|
||||
|
||||
/*******************************************************************************
|
||||
** Setter for allowedScheduledCredentialEnvNames
|
||||
*******************************************************************************/
|
||||
public void setAllowedScheduledCredentialEnvNames(Set<String> allowedScheduledCredentialEnvNames)
|
||||
{
|
||||
this.allowedScheduledCredentialEnvNames = allowedScheduledCredentialEnvNames;
|
||||
}
|
||||
|
||||
|
||||
|
||||
/*******************************************************************************
|
||||
** Fluent setter for allowedScheduledCredentialEnvNames
|
||||
*******************************************************************************/
|
||||
public AssistantQBitConfig withAllowedScheduledCredentialEnvNames(Set<String> allowedScheduledCredentialEnvNames)
|
||||
{
|
||||
this.allowedScheduledCredentialEnvNames = allowedScheduledCredentialEnvNames;
|
||||
return (this);
|
||||
}
|
||||
|
||||
|
||||
|
||||
/*******************************************************************************
|
||||
** Getter for scheduledTasksSchedulerName
|
||||
*******************************************************************************/
|
||||
public String getScheduledTasksSchedulerName()
|
||||
{
|
||||
return (scheduledTasksSchedulerName);
|
||||
}
|
||||
|
||||
|
||||
|
||||
/*******************************************************************************
|
||||
** Setter for scheduledTasksSchedulerName
|
||||
*******************************************************************************/
|
||||
public void setScheduledTasksSchedulerName(String scheduledTasksSchedulerName)
|
||||
{
|
||||
this.scheduledTasksSchedulerName = scheduledTasksSchedulerName;
|
||||
}
|
||||
|
||||
|
||||
|
||||
/*******************************************************************************
|
||||
** Fluent setter for scheduledTasksSchedulerName
|
||||
*******************************************************************************/
|
||||
public AssistantQBitConfig withScheduledTasksSchedulerName(String scheduledTasksSchedulerName)
|
||||
{
|
||||
this.scheduledTasksSchedulerName = scheduledTasksSchedulerName;
|
||||
return (this);
|
||||
}
|
||||
|
||||
|
||||
|
||||
/*******************************************************************************
|
||||
** Getter for turnHeartbeatSeconds
|
||||
*******************************************************************************/
|
||||
public Integer getTurnHeartbeatSeconds()
|
||||
{
|
||||
return (this.turnHeartbeatSeconds);
|
||||
}
|
||||
|
||||
|
||||
|
||||
/*******************************************************************************
|
||||
** Setter for turnHeartbeatSeconds
|
||||
*******************************************************************************/
|
||||
public void setTurnHeartbeatSeconds(Integer turnHeartbeatSeconds)
|
||||
{
|
||||
this.turnHeartbeatSeconds = turnHeartbeatSeconds;
|
||||
}
|
||||
|
||||
|
||||
|
||||
/*******************************************************************************
|
||||
** Fluent setter for turnHeartbeatSeconds
|
||||
*******************************************************************************/
|
||||
public AssistantQBitConfig withTurnHeartbeatSeconds(Integer turnHeartbeatSeconds)
|
||||
{
|
||||
this.turnHeartbeatSeconds = turnHeartbeatSeconds;
|
||||
return (this);
|
||||
}
|
||||
|
||||
|
||||
|
||||
/*******************************************************************************
|
||||
** Getter for turnLeaseSeconds
|
||||
*******************************************************************************/
|
||||
public Integer getTurnLeaseSeconds()
|
||||
{
|
||||
return (this.turnLeaseSeconds);
|
||||
}
|
||||
|
||||
|
||||
|
||||
/*******************************************************************************
|
||||
** Setter for turnLeaseSeconds
|
||||
*******************************************************************************/
|
||||
public void setTurnLeaseSeconds(Integer turnLeaseSeconds)
|
||||
{
|
||||
this.turnLeaseSeconds = turnLeaseSeconds;
|
||||
}
|
||||
|
||||
|
||||
|
||||
/*******************************************************************************
|
||||
** Fluent setter for turnLeaseSeconds
|
||||
*******************************************************************************/
|
||||
public AssistantQBitConfig withTurnLeaseSeconds(Integer turnLeaseSeconds)
|
||||
{
|
||||
this.turnLeaseSeconds = turnLeaseSeconds;
|
||||
return (this);
|
||||
}
|
||||
|
||||
|
||||
|
||||
/*******************************************************************************
|
||||
** Getter for turnForceFinalizeGraceSeconds
|
||||
*******************************************************************************/
|
||||
public Integer getTurnForceFinalizeGraceSeconds()
|
||||
{
|
||||
return (this.turnForceFinalizeGraceSeconds);
|
||||
}
|
||||
|
||||
|
||||
|
||||
/*******************************************************************************
|
||||
** Setter for turnForceFinalizeGraceSeconds
|
||||
*******************************************************************************/
|
||||
public void setTurnForceFinalizeGraceSeconds(Integer turnForceFinalizeGraceSeconds)
|
||||
{
|
||||
this.turnForceFinalizeGraceSeconds = turnForceFinalizeGraceSeconds;
|
||||
}
|
||||
|
||||
|
||||
|
||||
/*******************************************************************************
|
||||
** Fluent setter for turnForceFinalizeGraceSeconds
|
||||
*******************************************************************************/
|
||||
public AssistantQBitConfig withTurnForceFinalizeGraceSeconds(Integer turnForceFinalizeGraceSeconds)
|
||||
{
|
||||
this.turnForceFinalizeGraceSeconds = turnForceFinalizeGraceSeconds;
|
||||
return (this);
|
||||
}
|
||||
|
||||
|
||||
|
||||
/*******************************************************************************
|
||||
** Getter for shutdownGraceSeconds
|
||||
*******************************************************************************/
|
||||
public Integer getShutdownGraceSeconds()
|
||||
{
|
||||
return (this.shutdownGraceSeconds);
|
||||
}
|
||||
|
||||
|
||||
|
||||
/*******************************************************************************
|
||||
** Setter for shutdownGraceSeconds
|
||||
*******************************************************************************/
|
||||
public void setShutdownGraceSeconds(Integer shutdownGraceSeconds)
|
||||
{
|
||||
this.shutdownGraceSeconds = shutdownGraceSeconds;
|
||||
}
|
||||
|
||||
|
||||
|
||||
/*******************************************************************************
|
||||
** Fluent setter for shutdownGraceSeconds
|
||||
*******************************************************************************/
|
||||
public AssistantQBitConfig withShutdownGraceSeconds(Integer shutdownGraceSeconds)
|
||||
{
|
||||
this.shutdownGraceSeconds = shutdownGraceSeconds;
|
||||
return (this);
|
||||
}
|
||||
|
||||
|
||||
|
||||
/*******************************************************************************
|
||||
** Getter for defaultConcurrencyMode
|
||||
*******************************************************************************/
|
||||
public String getDefaultConcurrencyMode()
|
||||
{
|
||||
return (this.defaultConcurrencyMode);
|
||||
}
|
||||
|
||||
|
||||
|
||||
/*******************************************************************************
|
||||
** Setter for defaultConcurrencyMode
|
||||
*******************************************************************************/
|
||||
public void setDefaultConcurrencyMode(String defaultConcurrencyMode)
|
||||
{
|
||||
this.defaultConcurrencyMode = defaultConcurrencyMode;
|
||||
}
|
||||
|
||||
|
||||
|
||||
/*******************************************************************************
|
||||
** Fluent setter for defaultConcurrencyMode
|
||||
*******************************************************************************/
|
||||
public AssistantQBitConfig withDefaultConcurrencyMode(String defaultConcurrencyMode)
|
||||
{
|
||||
this.defaultConcurrencyMode = defaultConcurrencyMode;
|
||||
return (this);
|
||||
}
|
||||
|
||||
|
||||
|
||||
/*******************************************************************************
|
||||
** Getter for registerShutdownHook
|
||||
*******************************************************************************/
|
||||
public Boolean getRegisterShutdownHook()
|
||||
{
|
||||
return (this.registerShutdownHook);
|
||||
}
|
||||
|
||||
|
||||
|
||||
/*******************************************************************************
|
||||
** Setter for registerShutdownHook
|
||||
*******************************************************************************/
|
||||
public void setRegisterShutdownHook(Boolean registerShutdownHook)
|
||||
{
|
||||
this.registerShutdownHook = registerShutdownHook;
|
||||
}
|
||||
|
||||
|
||||
|
||||
/*******************************************************************************
|
||||
** Fluent setter for registerShutdownHook
|
||||
*******************************************************************************/
|
||||
public AssistantQBitConfig withRegisterShutdownHook(Boolean registerShutdownHook)
|
||||
{
|
||||
this.registerShutdownHook = registerShutdownHook;
|
||||
return (this);
|
||||
}
|
||||
|
||||
|
||||
|
||||
/*******************************************************************************
|
||||
** Getter for runTracker
|
||||
*******************************************************************************/
|
||||
@JsonIgnore
|
||||
public AssistantRunTracker getRunTracker()
|
||||
{
|
||||
return (this.runTracker == null ? AssistantRunTracker.NOOP : this.runTracker);
|
||||
}
|
||||
|
||||
|
||||
|
||||
/*******************************************************************************
|
||||
** Setter for runTracker
|
||||
*******************************************************************************/
|
||||
public void setRunTracker(AssistantRunTracker runTracker)
|
||||
{
|
||||
this.runTracker = runTracker;
|
||||
}
|
||||
|
||||
|
||||
|
||||
/*******************************************************************************
|
||||
** Fluent setter for runTracker
|
||||
*******************************************************************************/
|
||||
public AssistantQBitConfig withRunTracker(AssistantRunTracker runTracker)
|
||||
{
|
||||
this.runTracker = runTracker;
|
||||
return (this);
|
||||
}
|
||||
|
||||
}
|
||||
+62
-6
@@ -21,21 +21,30 @@ import java.io.InputStream;
|
||||
import java.util.ArrayList;
|
||||
import java.util.List;
|
||||
import java.util.Properties;
|
||||
import com.kingsrook.qbits.assistant.api.AssistantRoutes;
|
||||
import com.kingsrook.qbits.assistant.developer.AssistantDeveloperPanels;
|
||||
import com.kingsrook.qbits.assistant.home.AssistantAccessWidget;
|
||||
import com.kingsrook.qbits.assistant.home.AssistantHome;
|
||||
import com.kingsrook.qbits.assistant.metadata.AssistantChannelWall;
|
||||
import com.kingsrook.qbits.assistant.metadata.AssistantInstanceMetaData;
|
||||
import com.kingsrook.qbits.assistant.metadata.AssistantMetaDataBuilder;
|
||||
import com.kingsrook.qbits.assistant.metadata.AssistantRecordScreens;
|
||||
import com.kingsrook.qbits.assistant.model.AssistantBudget;
|
||||
import com.kingsrook.qbits.assistant.processes.DataAccessDefaultsProcess;
|
||||
import com.kingsrook.qbits.assistant.processes.DiscoverModelsProcess;
|
||||
import com.kingsrook.qbits.assistant.processes.KnowledgeIndexProcess;
|
||||
import com.kingsrook.qbits.assistant.processes.ScheduledTaskProcess;
|
||||
import com.kingsrook.qbits.assistant.processes.TestConnectionProcess;
|
||||
import com.kingsrook.qbits.assistant.processes.TestModelConnectionProcess;
|
||||
import com.kingsrook.qqq.backend.core.alerts.AlertSeverity;
|
||||
import com.kingsrook.qqq.backend.core.alerts.QAlertTypeMetaData;
|
||||
import com.kingsrook.qbits.assistant.model.AssistantBudget;
|
||||
import com.kingsrook.qqq.backend.core.exceptions.QException;
|
||||
import com.kingsrook.qqq.backend.core.logging.QLogger;
|
||||
import com.kingsrook.qqq.backend.core.model.metadata.MetaDataProducerMultiOutput;
|
||||
import com.kingsrook.qqq.backend.core.model.metadata.QInstance;
|
||||
import com.kingsrook.qqq.backend.core.model.metadata.help.bundles.HelpBundles;
|
||||
import com.kingsrook.qqq.backend.core.model.metadata.layout.QAppMetaData;
|
||||
import com.kingsrook.qqq.backend.core.model.metadata.permissions.ClientChannelsMetaData;
|
||||
import com.kingsrook.qqq.backend.core.model.metadata.processes.QProcessMetaData;
|
||||
import com.kingsrook.qqq.backend.core.model.metadata.qbits.QBitMetaData;
|
||||
import com.kingsrook.qqq.backend.core.model.metadata.qbits.QBitMetaDataProducer;
|
||||
@@ -173,24 +182,71 @@ public class AssistantQBitProducer implements QBitMetaDataProducer<AssistantQBit
|
||||
QProcessMetaData testConnection = TestConnectionProcess.process();
|
||||
testConnection.setSourceQBitName(qBitMetaData.getName());
|
||||
qInstance.addProcess(testConnection);
|
||||
for(QProcessMetaData process : java.util.List.of(DiscoverModelsProcess.process(), TestModelConnectionProcess.process()))
|
||||
for(QProcessMetaData process : List.of(DiscoverModelsProcess.process(), TestModelConnectionProcess.process(), DataAccessDefaultsProcess.process()))
|
||||
{
|
||||
process.setSourceQBitName(qBitMetaData.getName());
|
||||
qInstance.addProcess(process);
|
||||
}
|
||||
|
||||
for(QProcessMetaData process : KnowledgeIndexProcess.processes())
|
||||
{
|
||||
process.setSourceQBitName(qBitMetaData.getName());
|
||||
qInstance.addProcess(process);
|
||||
}
|
||||
|
||||
for(QProcessMetaData process : ScheduledTaskProcess.processes(qBitConfig))
|
||||
{
|
||||
process.setSourceQBitName(qBitMetaData.getName());
|
||||
qInstance.addProcess(process);
|
||||
}
|
||||
qInstance.addWidget(AssistantHome.widget());
|
||||
qInstance.addWidget(AssistantAccessWidget.widget());
|
||||
|
||||
QAppMetaData app = builder.buildAdminApp(tables);
|
||||
qInstance.addApp(app);
|
||||
// Registration is metadata-only; core startup sync guards hosts without helpContent.
|
||||
HelpBundles.register(qInstance, "help/qbit-assistant.yaml");
|
||||
|
||||
AssistantChannelWall.register(qInstance);
|
||||
if(Boolean.TRUE.equals(qBitConfig.getRecordHistory()))
|
||||
{
|
||||
enableRecordHistory(ClientChannelsMetaData.ofOrWithNew(qInstance));
|
||||
}
|
||||
else
|
||||
{
|
||||
ClientChannelsMetaData.ofOrWithNew(qInstance).withDeniedPattern("assistant", "audit*");
|
||||
}
|
||||
postProduceActions(new MetaDataProducerMultiOutput(), qInstance);
|
||||
return (new MetaDataProducerMultiOutput());
|
||||
}
|
||||
|
||||
|
||||
|
||||
/*******************************************************************************
|
||||
** STAND-IN(core=QRun-IO/qqq#1193, removeBy=RC.8): call withAssistantAuditReads() directly once the qbit builds on a QQQ RC that has it
|
||||
*******************************************************************************/
|
||||
private void enableRecordHistory(ClientChannelsMetaData channels)
|
||||
{
|
||||
try
|
||||
{
|
||||
channels.getClass().getMethod("withAssistantAuditReads").invoke(channels);
|
||||
}
|
||||
catch(NoSuchMethodException e)
|
||||
{
|
||||
List<String> denied = channels.getDeniedPatterns().get("assistant");
|
||||
if(denied != null)
|
||||
{
|
||||
denied.removeIf("audit*"::equals);
|
||||
}
|
||||
}
|
||||
catch(ReflectiveOperationException e)
|
||||
{
|
||||
throw (new IllegalStateException("Could not enable assistant audit reads.", e));
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
|
||||
/*******************************************************************************
|
||||
** Declare budget alerts as top-level core metadata for admin visibility.
|
||||
*******************************************************************************/
|
||||
@@ -219,19 +275,19 @@ public class AssistantQBitProducer implements QBitMetaDataProducer<AssistantQBit
|
||||
boolean routes = false;
|
||||
if(Boolean.TRUE.equals(qBitConfig.getRegisterRoutes()) && isJavalinAvailable())
|
||||
{
|
||||
com.kingsrook.qbits.assistant.api.AssistantRoutes.register(qInstance);
|
||||
AssistantRoutes.register(qInstance);
|
||||
routes = true;
|
||||
}
|
||||
|
||||
if(qBitConfig.isEffectivelyEnabled())
|
||||
{
|
||||
com.kingsrook.qbits.assistant.metadata.AssistantInstanceMetaData.register(qInstance);
|
||||
AssistantInstanceMetaData.register(qInstance);
|
||||
}
|
||||
|
||||
boolean developerPanel = false;
|
||||
if(com.kingsrook.qbits.assistant.developer.AssistantDeveloperPanels.isContractAvailable())
|
||||
if(AssistantDeveloperPanels.isContractAvailable())
|
||||
{
|
||||
com.kingsrook.qbits.assistant.developer.AssistantDeveloperPanels.register(qInstance);
|
||||
AssistantDeveloperPanels.register(qInstance);
|
||||
developerPanel = true;
|
||||
}
|
||||
|
||||
|
||||
@@ -17,6 +17,15 @@
|
||||
package com.kingsrook.qbits.assistant;
|
||||
|
||||
|
||||
import java.net.InetAddress;
|
||||
import java.time.Clock;
|
||||
import java.time.Duration;
|
||||
import java.util.Map;
|
||||
import java.util.UUID;
|
||||
import java.util.concurrent.ConcurrentHashMap;
|
||||
import java.util.concurrent.ExecutorService;
|
||||
import java.util.concurrent.Executors;
|
||||
import java.util.regex.Pattern;
|
||||
import com.kingsrook.qbits.assistant.access.AccessExplainer;
|
||||
import com.kingsrook.qbits.assistant.access.DataAccessService;
|
||||
import com.kingsrook.qbits.assistant.engine.BudgetService;
|
||||
@@ -26,23 +35,28 @@ import com.kingsrook.qbits.assistant.engine.ProfileService;
|
||||
import com.kingsrook.qbits.assistant.engine.ProviderService;
|
||||
import com.kingsrook.qbits.assistant.engine.RateLimiter;
|
||||
import com.kingsrook.qbits.assistant.engine.RunningTurn;
|
||||
import com.kingsrook.qbits.assistant.metadata.AssistantChannelWall;
|
||||
import com.kingsrook.qbits.assistant.persistence.AssistantStore;
|
||||
import com.kingsrook.qbits.assistant.rag.InMemoryVectorStore;
|
||||
import com.kingsrook.qbits.assistant.rag.RagService;
|
||||
import com.kingsrook.qbits.assistant.rag.VectorStore;
|
||||
import com.kingsrook.qbits.assistant.scheduled.ScheduledTurn;
|
||||
import com.kingsrook.qbits.assistant.tools.KnowledgeTool;
|
||||
import com.kingsrook.qbits.assistant.tools.UiApiToolbox;
|
||||
import com.kingsrook.qbits.assistant.uiapi.LoopbackUiApiGateway;
|
||||
import com.kingsrook.qbits.assistant.tools.bulkload.BulkLoadTools;
|
||||
import com.kingsrook.qbits.assistant.uiapi.CoreUiApiGateway;
|
||||
import com.kingsrook.qbits.assistant.uiapi.UiApiCall;
|
||||
import com.kingsrook.qbits.assistant.uiapi.UiApiGateway;
|
||||
import com.kingsrook.qbits.assistant.uiapi.UiApiResult;
|
||||
import com.kingsrook.qqq.backend.core.actions.ai.AiToolKernel;
|
||||
import com.kingsrook.qqq.backend.core.actions.ai.AiToolKernelSettings;
|
||||
import com.kingsrook.qqq.backend.core.actions.ai.exposure.AiExposurePolicy;
|
||||
import com.kingsrook.qqq.backend.core.actions.ai.output.AiRedactor;
|
||||
import com.kingsrook.qqq.backend.core.exceptions.QException;
|
||||
import com.kingsrook.qqq.backend.core.logging.QLogger;
|
||||
import com.kingsrook.qqq.backend.core.model.metadata.QInstance;
|
||||
import com.kingsrook.qqq.backend.core.model.metadata.qbits.QBitMetaData;
|
||||
import com.kingsrook.qqq.backend.core.utils.StringUtils;
|
||||
import java.time.Clock;
|
||||
import java.util.Map;
|
||||
import java.util.concurrent.ConcurrentHashMap;
|
||||
import java.util.concurrent.ExecutorService;
|
||||
import java.util.concurrent.Executors;
|
||||
import java.util.regex.Pattern;
|
||||
|
||||
|
||||
/*******************************************************************************
|
||||
@@ -52,6 +66,17 @@ import java.util.regex.Pattern;
|
||||
*******************************************************************************/
|
||||
public class AssistantRuntime
|
||||
{
|
||||
private static final QLogger LOG = QLogger.getLogger(AssistantRuntime.class);
|
||||
private final String instanceId = instanceId();
|
||||
private volatile boolean shuttingDown;
|
||||
private Thread shutdownHook;
|
||||
|
||||
private final ScheduledTurn scheduledTurn = new ScheduledTurn();
|
||||
|
||||
private final RagService ragService;
|
||||
private final KnowledgeTool knowledgeTool;
|
||||
private final BulkLoadTools bulkLoadTools;
|
||||
|
||||
private final QInstance qInstance;
|
||||
private final AssistantQBitConfig config;
|
||||
private final Clock clock;
|
||||
@@ -88,10 +113,21 @@ public class AssistantRuntime
|
||||
*******************************************************************************/
|
||||
public AssistantRuntime(QInstance qInstance, AssistantQBitConfig config, Clock clock)
|
||||
{
|
||||
this(qInstance, config, clock, new AssistantStore(config));
|
||||
}
|
||||
|
||||
|
||||
|
||||
/*******************************************************************************
|
||||
** Explicit persistence collaborator for embedded runtimes and fault tests.
|
||||
*******************************************************************************/
|
||||
public AssistantRuntime(QInstance qInstance, AssistantQBitConfig config, Clock clock, AssistantStore store)
|
||||
{
|
||||
AssistantChannelWall.validate(qInstance);
|
||||
this.qInstance = qInstance;
|
||||
this.config = config;
|
||||
this.clock = clock;
|
||||
this.store = new AssistantStore(config);
|
||||
this.store = store;
|
||||
this.policyService = new PolicyService(config, store, clock);
|
||||
this.providerService = new ProviderService(config, store, clock);
|
||||
this.budgetService = new BudgetService(store, providerService, clock);
|
||||
@@ -105,8 +141,56 @@ public class AssistantRuntime
|
||||
this.accessExplainer = new AccessExplainer(qInstance, dataAccessService);
|
||||
this.toolbox = new UiApiToolbox(qInstance, dataAccessService, exposurePolicy, new AiRedactor(settings.getCustomRedactionPatterns()),
|
||||
config.getMaxCellChars() == null ? AiToolKernelSettings.DEFAULT_MAX_CELL_CHARS : config.getMaxCellChars());
|
||||
this.uiApiGateway = config.getUiApiGateway() != null ? config.getUiApiGateway() : new LoopbackUiApiGateway(this::uiApiBaseUrl, qInstance);
|
||||
this.contextBuilder = new ContextBuilder(config, kernel, toolbox);
|
||||
UiApiGateway delegate = config.getUiApiGateway() != null ? config.getUiApiGateway() : new CoreUiApiGateway(this::uiApiBaseUrl, qInstance);
|
||||
this.uiApiGateway = new UiApiGateway()
|
||||
{
|
||||
/*******************************************************************************
|
||||
** Delegate using this instance's configured collaborator.
|
||||
*******************************************************************************/
|
||||
@Override
|
||||
public boolean isInvocable(String method, String pathTemplate)
|
||||
{
|
||||
return (delegate.isInvocable(method, pathTemplate));
|
||||
}
|
||||
|
||||
/*******************************************************************************
|
||||
** Delegate using this instance's configured collaborator.
|
||||
*******************************************************************************/
|
||||
@Override
|
||||
public UiApiResult invoke(UiApiCall call) throws QException
|
||||
{
|
||||
String channel = scheduledTurn.channel(call.getSessionUUID());
|
||||
if(channel != null)
|
||||
{
|
||||
if(!(delegate instanceof CoreUiApiGateway))
|
||||
{
|
||||
throw (new QException("Scheduled tasks require the core UI API gateway for client attribution."));
|
||||
}
|
||||
call.withClientDetail(channel.substring(CoreUiApiGateway.CLIENT_CHANNEL.length() + 1));
|
||||
}
|
||||
return (delegate.invoke(call));
|
||||
}
|
||||
};
|
||||
VectorStore vectors = config.getVectorStore() == null ? new InMemoryVectorStore() : config.getVectorStore();
|
||||
this.ragService = new RagService(this, vectors);
|
||||
this.knowledgeTool = new KnowledgeTool(this, ragService, vectors);
|
||||
this.bulkLoadTools = new BulkLoadTools(qInstance, dataAccessService, config.getBulkLoadRunner());
|
||||
this.contextBuilder = new ContextBuilder(config, kernel, toolbox).withKnowledgeTool(knowledgeTool).withBulkLoadTools(bulkLoadTools);
|
||||
if(Boolean.TRUE.equals(config.getRegisterShutdownHook()))
|
||||
{
|
||||
shutdownHook = new Thread(() ->
|
||||
{
|
||||
try
|
||||
{
|
||||
shutdown(Duration.ofSeconds(config.getShutdownGraceSeconds()));
|
||||
}
|
||||
catch(Throwable ignored)
|
||||
{
|
||||
// Shutdown must never fail the JVM hook.
|
||||
}
|
||||
}, "assistant-shutdown-" + instanceId);
|
||||
Runtime.getRuntime().addShutdownHook(shutdownHook);
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
@@ -262,8 +346,13 @@ public class AssistantRuntime
|
||||
/*******************************************************************************
|
||||
** Track a turn running here.
|
||||
*******************************************************************************/
|
||||
public RunningTurn register(RunningTurn turn)
|
||||
public synchronized RunningTurn register(RunningTurn turn)
|
||||
{
|
||||
if(shuttingDown)
|
||||
{
|
||||
turn.forceFinalize("SHUTDOWN");
|
||||
return (turn);
|
||||
}
|
||||
runningTurns.put(turn.getTurnId(), turn);
|
||||
return (turn);
|
||||
}
|
||||
@@ -295,7 +384,17 @@ public class AssistantRuntime
|
||||
*******************************************************************************/
|
||||
public void cancelAll(String reason)
|
||||
{
|
||||
runningTurns.values().forEach(t -> t.cancel(reason));
|
||||
runningTurns.values().forEach(t ->
|
||||
{
|
||||
try
|
||||
{
|
||||
t.cancel(reason);
|
||||
}
|
||||
catch(Exception e)
|
||||
{
|
||||
LOG.warn("Assistant cancellation failed; finalization will still run");
|
||||
}
|
||||
});
|
||||
}
|
||||
|
||||
|
||||
@@ -305,8 +404,7 @@ public class AssistantRuntime
|
||||
*******************************************************************************/
|
||||
public void close()
|
||||
{
|
||||
runningTurns.values().forEach(t -> t.cancel("SHUTDOWN"));
|
||||
executor.shutdownNow();
|
||||
shutdown(Duration.ZERO);
|
||||
}
|
||||
|
||||
|
||||
@@ -417,4 +515,134 @@ public class AssistantRuntime
|
||||
{
|
||||
return (budgetService);
|
||||
}
|
||||
|
||||
|
||||
/*******************************************************************************
|
||||
** Manual indexing service, always using the current caller's session.
|
||||
*******************************************************************************/
|
||||
public RagService getRagService()
|
||||
{
|
||||
return (ragService);
|
||||
}
|
||||
|
||||
|
||||
|
||||
/*******************************************************************************
|
||||
** Permission-filtered retrieval tool.
|
||||
*******************************************************************************/
|
||||
public KnowledgeTool getKnowledgeTool()
|
||||
{
|
||||
return (knowledgeTool);
|
||||
}
|
||||
|
||||
/*******************************************************************************
|
||||
** Server-owned scheduled execution context.
|
||||
*******************************************************************************/
|
||||
public ScheduledTurn getScheduledTurn()
|
||||
{
|
||||
return (scheduledTurn);
|
||||
}
|
||||
|
||||
|
||||
/*******************************************************************************
|
||||
** The bulk-load tools (saved profiles, attached files, dry runs, loads).
|
||||
*******************************************************************************/
|
||||
public BulkLoadTools getBulkLoadTools()
|
||||
{
|
||||
return (bulkLoadTools);
|
||||
}
|
||||
|
||||
|
||||
|
||||
|
||||
/*******************************************************************************
|
||||
** Stop accepting work, cancel, wait a bounded grace, then force finalization.
|
||||
*******************************************************************************/
|
||||
public void shutdown(Duration grace)
|
||||
{
|
||||
synchronized(this)
|
||||
{
|
||||
shuttingDown = true;
|
||||
}
|
||||
cancelAll("SHUTDOWN");
|
||||
long until = System.nanoTime() + Math.max(0, grace.toNanos());
|
||||
while(!runningTurns.isEmpty() && System.nanoTime() < until)
|
||||
{
|
||||
try
|
||||
{
|
||||
Thread.sleep(10);
|
||||
}
|
||||
catch(InterruptedException e)
|
||||
{
|
||||
Thread.currentThread().interrupt();
|
||||
break;
|
||||
}
|
||||
}
|
||||
runningTurns.values().forEach(t ->
|
||||
{
|
||||
try
|
||||
{
|
||||
t.forceFinalize("SHUTDOWN");
|
||||
}
|
||||
catch(Exception e)
|
||||
{
|
||||
LOG.warn("Assistant shutdown finalization failed");
|
||||
}
|
||||
});
|
||||
executor.shutdownNow();
|
||||
if(shutdownHook != null && Thread.currentThread() != shutdownHook)
|
||||
{
|
||||
try
|
||||
{
|
||||
Runtime.getRuntime().removeShutdownHook(shutdownHook);
|
||||
}
|
||||
catch(IllegalStateException ignored)
|
||||
{
|
||||
// The JVM is already shutting down.
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
|
||||
/*******************************************************************************
|
||||
** Getter for shuttingDown
|
||||
*******************************************************************************/
|
||||
public boolean isShuttingDown()
|
||||
{
|
||||
return (shuttingDown);
|
||||
}
|
||||
|
||||
|
||||
|
||||
/*******************************************************************************
|
||||
** Getter for instanceId
|
||||
*******************************************************************************/
|
||||
public String getInstanceId()
|
||||
{
|
||||
return (instanceId);
|
||||
}
|
||||
|
||||
|
||||
|
||||
/*******************************************************************************
|
||||
** A stable, bounded hostname plus a per-runtime random suffix.
|
||||
*******************************************************************************/
|
||||
private static String instanceId()
|
||||
{
|
||||
String host = System.getenv("HOSTNAME");
|
||||
if(!StringUtils.hasContent(host))
|
||||
{
|
||||
try
|
||||
{
|
||||
host = InetAddress.getLocalHost().getHostName();
|
||||
}
|
||||
catch(Exception ignored)
|
||||
{
|
||||
host = "unknown";
|
||||
}
|
||||
}
|
||||
return (host.substring(0, Math.min(87, host.length())) + ":" + UUID.randomUUID().toString().substring(0, 8));
|
||||
}
|
||||
|
||||
}
|
||||
+22
-1
@@ -31,6 +31,7 @@ import com.kingsrook.qqq.backend.core.exceptions.QException;
|
||||
import com.kingsrook.qqq.backend.core.model.metadata.QInstance;
|
||||
import com.kingsrook.qqq.backend.core.model.metadata.tables.QTableMetaData;
|
||||
import com.kingsrook.qqq.backend.core.utils.StringUtils;
|
||||
import com.kingsrook.qqq.middleware.javalin.specs.invoke.UiApiCredentials;
|
||||
|
||||
|
||||
/*******************************************************************************
|
||||
@@ -92,7 +93,27 @@ public class AccessExplainer
|
||||
*******************************************************************************/
|
||||
public List<TableAccess> explain(UiApiGateway gateway, String sessionUUID, PolicyService.ToolPolicy policy, String tableName, String prompt) throws QException
|
||||
{
|
||||
UiApiResult response = gateway.invoke(new UiApiCall("GET", "/metaData").withSessionUUID(sessionUUID).withInvokedBy("assistant-explain"));
|
||||
return (explain(gateway, sessionUUID, null, policy, tableName, prompt));
|
||||
}
|
||||
|
||||
|
||||
|
||||
/*******************************************************************************
|
||||
** Explain, with the caller's request credentials when they are known.
|
||||
*******************************************************************************/
|
||||
public List<TableAccess> explain(UiApiGateway gateway, String sessionUUID, UiApiCredentials credentials, PolicyService.ToolPolicy policy, String tableName, String prompt) throws QException
|
||||
{
|
||||
return (explain(gateway, sessionUUID, credentials, policy, tableName, prompt, null));
|
||||
}
|
||||
|
||||
|
||||
|
||||
/*******************************************************************************
|
||||
** Preserve a known turn's attribution on the metadata request.
|
||||
*******************************************************************************/
|
||||
public List<TableAccess> explain(UiApiGateway gateway, String sessionUUID, UiApiCredentials credentials, PolicyService.ToolPolicy policy, String tableName, String prompt, String turnId) throws QException
|
||||
{
|
||||
UiApiResult response = gateway.invoke(new UiApiCall("GET", "/metaData").withSessionUUID(sessionUUID).withCredentials(credentials).withInvokedBy("assistant-explain").withClientDetail(turnId));
|
||||
if(!response.isSuccess())
|
||||
{
|
||||
throw (new QException("GET /metaData answered HTTP " + response.status() + (response.errorMessage() == null ? "" : ": " + response.errorMessage())));
|
||||
|
||||
@@ -17,11 +17,14 @@
|
||||
package com.kingsrook.qbits.assistant.api;
|
||||
|
||||
|
||||
import java.time.Duration;
|
||||
import java.time.Instant;
|
||||
import java.util.ArrayList;
|
||||
import java.util.Comparator;
|
||||
import java.util.HashSet;
|
||||
import java.util.LinkedHashMap;
|
||||
import java.util.List;
|
||||
import java.util.Locale;
|
||||
import java.util.Map;
|
||||
import com.fasterxml.jackson.core.type.TypeReference;
|
||||
import com.kingsrook.qbits.assistant.AssistantQBitConfig;
|
||||
@@ -45,15 +48,20 @@ import com.kingsrook.qbits.assistant.model.AssistantToolCall;
|
||||
import com.kingsrook.qbits.assistant.model.AssistantTurn;
|
||||
import com.kingsrook.qbits.assistant.model.AssistantTurnEvent;
|
||||
import com.kingsrook.qbits.assistant.persistence.AssistantStore;
|
||||
import com.kingsrook.qbits.assistant.persistence.TranscriptRedactor;
|
||||
import com.kingsrook.qbits.assistant.tools.UiApiToolbox;
|
||||
import com.kingsrook.qbits.assistant.tools.bulkload.BulkLoadTools;
|
||||
import com.kingsrook.qqq.backend.core.actions.ai.AiToolOutcome;
|
||||
import com.kingsrook.qqq.backend.core.actions.ai.AiToolResult;
|
||||
import com.kingsrook.qqq.backend.core.actions.ai.output.AiRedactor;
|
||||
import com.kingsrook.qqq.backend.core.exceptions.QException;
|
||||
import com.kingsrook.qqq.backend.core.logging.QLogger;
|
||||
import com.kingsrook.qqq.backend.core.model.data.QRecord;
|
||||
import com.kingsrook.qqq.backend.core.model.session.QSession;
|
||||
import com.kingsrook.qqq.backend.core.utils.JsonUtils;
|
||||
import com.kingsrook.qqq.backend.core.utils.StringUtils;
|
||||
import com.kingsrook.qqq.middleware.javalin.specs.invoke.UiApiCredentials;
|
||||
import static com.kingsrook.qqq.backend.core.logging.LogUtils.logPair;
|
||||
|
||||
|
||||
/*******************************************************************************
|
||||
@@ -63,6 +71,8 @@ import com.kingsrook.qqq.backend.core.utils.StringUtils;
|
||||
*******************************************************************************/
|
||||
public class AssistantApi
|
||||
{
|
||||
private static final QLogger LOG = QLogger.getLogger(AssistantApi.class);
|
||||
|
||||
public static final int TITLE_MAX_CHARS = 60;
|
||||
|
||||
private final AssistantRuntime runtime;
|
||||
@@ -70,6 +80,7 @@ public class AssistantApi
|
||||
private final AssistantStore store;
|
||||
private final QSession session;
|
||||
private final String userId;
|
||||
private UiApiCredentials credentials;
|
||||
|
||||
|
||||
|
||||
@@ -92,6 +103,18 @@ public class AssistantApi
|
||||
|
||||
|
||||
|
||||
/*******************************************************************************
|
||||
** The credentials of the request this API serves, exactly as they came in;
|
||||
** the tools forward them to the UI API. Never logged.
|
||||
*******************************************************************************/
|
||||
public AssistantApi withCredentials(UiApiCredentials credentials)
|
||||
{
|
||||
this.credentials = credentials;
|
||||
return (this);
|
||||
}
|
||||
|
||||
|
||||
|
||||
/*******************************************************************************
|
||||
** GET /config - the feature probe. Never throws for a signed-in user.
|
||||
*******************************************************************************/
|
||||
@@ -274,6 +297,19 @@ public class AssistantApi
|
||||
public RunningTurn startTurn(Integer conversationId, Map<String, Object> body) throws QException, AssistantApiException
|
||||
{
|
||||
requireAccess();
|
||||
if(runtime.isShuttingDown())
|
||||
{
|
||||
throw (new AssistantApiException(503, "SHUTTING_DOWN", "The server is restarting. Try again in a moment."));
|
||||
}
|
||||
String concurrency = config.getDefaultConcurrencyMode();
|
||||
if(body.containsKey("concurrency"))
|
||||
{
|
||||
if(!(body.get("concurrency") instanceof String mode) || !("supersede".equalsIgnoreCase(mode) || "concurrent".equalsIgnoreCase(mode)))
|
||||
{
|
||||
throw (new AssistantApiException(400, "concurrency must be supersede or concurrent."));
|
||||
}
|
||||
concurrency = mode.toUpperCase(Locale.ROOT);
|
||||
}
|
||||
AssistantConversation conversation = requireConversation(conversationId);
|
||||
|
||||
if(!(body.get("text") instanceof String text) || !StringUtils.hasContent(text))
|
||||
@@ -309,30 +345,43 @@ public class AssistantApi
|
||||
throw (new AssistantApiException(429, "BUDGET", budget.message()));
|
||||
}
|
||||
|
||||
long running = 0;
|
||||
for(AssistantTurn other : store.listRunningTurns(userId))
|
||||
{
|
||||
if(isRunning(reapIfOrphaned(other)))
|
||||
{
|
||||
running++;
|
||||
}
|
||||
}
|
||||
if(running >= config.getMaxConcurrentTurnsPerUser())
|
||||
{
|
||||
throw (new AssistantApiException(429, "RATE_LIMIT", "You already have an assistant answer in progress. Wait for it to finish or stop it."));
|
||||
}
|
||||
|
||||
String limited = runtime.getRateLimiter().tryAcquire(userId, config.getMaxTurnsPerUserPerMinute(), config.getMaxConcurrentTurnsPerUser());
|
||||
if(limited != null)
|
||||
{
|
||||
throw (new AssistantApiException(429, "RATE_LIMIT", limited));
|
||||
}
|
||||
|
||||
List<AssistantTurn> remaining = new ArrayList<>();
|
||||
for(AssistantTurn other : store.listRunningTurns(userId))
|
||||
{
|
||||
other = reapIfOrphaned(other);
|
||||
if(!isRunning(other) || "SUPERSEDED".equals(other.getCancelReason()))
|
||||
{
|
||||
continue;
|
||||
}
|
||||
if("SUPERSEDE".equals(concurrency) && conversationId.equals(other.getConversationId()))
|
||||
{
|
||||
requestStop(other, "SUPERSEDED");
|
||||
}
|
||||
else
|
||||
{
|
||||
remaining.add(other);
|
||||
}
|
||||
}
|
||||
remaining.sort(Comparator.comparing(AssistantTurn::getStartedAt, Comparator.nullsFirst(Comparator.naturalOrder()))
|
||||
.thenComparing(AssistantTurn::getId));
|
||||
while(remaining.size() >= config.getMaxConcurrentTurnsPerUser())
|
||||
{
|
||||
requestStop(remaining.removeFirst(), "SUPERSEDED");
|
||||
}
|
||||
|
||||
TranscriptRedactor transcript = new TranscriptRedactor(runtime.getQInstance(), config.getClassificationSource());
|
||||
transcript.attach();
|
||||
try
|
||||
{
|
||||
if(!StringUtils.hasContent(conversation.getTitle()))
|
||||
{
|
||||
String title = deriveTitle(text);
|
||||
String title = text;
|
||||
store.updateFields(AssistantConversation.TABLE_NAME, new QRecord().withValue("id", conversationId).withValue("title", title));
|
||||
conversation.setTitle(title);
|
||||
}
|
||||
@@ -346,13 +395,18 @@ public class AssistantApi
|
||||
.withSeq(seq)
|
||||
.withPartsJson(new MessageParts().addText(text).toJson()));
|
||||
|
||||
Instant startedAt = runtime.getClock().instant();
|
||||
AssistantTurn turn = store.insert(new AssistantTurn()
|
||||
.withConversationId(conversationId)
|
||||
.withUserId(userId)
|
||||
.withUserMessageId(userMessage.getId())
|
||||
.withStatus("RUNNING")
|
||||
.withModel(active.model())
|
||||
.withStartedAt(runtime.getClock().instant())
|
||||
.withStartedAt(startedAt)
|
||||
.withHeartbeatAt(startedAt)
|
||||
.withLeaseOwner(runtime.getInstanceId())
|
||||
.withPhase("starting")
|
||||
.withConcurrencyMode(concurrency)
|
||||
.withToolCallCount(0)
|
||||
.withModelCallCount(0));
|
||||
|
||||
@@ -370,17 +424,49 @@ public class AssistantApi
|
||||
store.updateFields(AssistantTurn.TABLE_NAME, new QRecord().withValue("id", turn.getId()).withValue("assistantMessageId", assistantMessage.getId()));
|
||||
turn.setAssistantMessageId(assistantMessage.getId());
|
||||
|
||||
RunningTurn runningTurn = runtime.register(new RunningTurn(turn.getId(), userId));
|
||||
RunningTurn runningTurn = new RunningTurn(turn.getId(), userId);
|
||||
TurnEngine engine = new TurnEngine(runtime, session, userId, conversation, userMessage, assistantMessage, turn, text, pageContext, policy, runningTurn,
|
||||
budget.softExceeded() ? budget.message() : null);
|
||||
runtime.getExecutor().submit(engine);
|
||||
budget.softExceeded() ? budget.message() : null).withCredentials(credentials).withTranscript(transcript);
|
||||
try
|
||||
{
|
||||
if(config.getRunTracker() != null)
|
||||
{
|
||||
///////////////////////////////////////////////////////////////////
|
||||
// never the conversation title: it is derived from the prompt //
|
||||
///////////////////////////////////////////////////////////////////
|
||||
runningTurn.setTrackingId(config.getRunTracker().start(userId, turn.getId(), conversationId, "Assistant answer"));
|
||||
config.getRunTracker().onCancel(runningTurn.getTrackingId(), () -> runningTurn.cancel("USER"));
|
||||
}
|
||||
}
|
||||
catch(Exception e)
|
||||
{
|
||||
LOG.warn("Assistant run tracker start failed", logPair("turnId", turn.getId()));
|
||||
}
|
||||
runtime.register(runningTurn);
|
||||
if(!runningTurn.isFinalized())
|
||||
{
|
||||
try
|
||||
{
|
||||
runtime.getExecutor().submit(engine);
|
||||
}
|
||||
catch(RuntimeException e)
|
||||
{
|
||||
runningTurn.forceFinalize("SHUTDOWN");
|
||||
throw (e);
|
||||
}
|
||||
}
|
||||
return (runningTurn);
|
||||
}
|
||||
catch(QException | RuntimeException e)
|
||||
{
|
||||
transcript.close();
|
||||
runtime.getRateLimiter().release(userId);
|
||||
throw (e);
|
||||
}
|
||||
finally
|
||||
{
|
||||
TranscriptRedactor.detach();
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
@@ -428,22 +514,94 @@ public class AssistantApi
|
||||
{
|
||||
requireAccess();
|
||||
AssistantTurn turn = requireTurn(turnId);
|
||||
if(runtime.getRunningTurn(turnId) == null)
|
||||
if(isRunning(turn))
|
||||
{
|
||||
turn = requestStop(turn, "USER");
|
||||
}
|
||||
return (Map.of("status", turn.getStatus()));
|
||||
}
|
||||
|
||||
|
||||
|
||||
/*******************************************************************************
|
||||
** Durable Stop, shared by the API and superseding another question.
|
||||
*******************************************************************************/
|
||||
private AssistantTurn requestStop(AssistantTurn turn, String reason) throws QException
|
||||
{
|
||||
synchronized(store)
|
||||
{
|
||||
turn = store.getTurn(userId, turn.getId());
|
||||
if(!isRunning(turn))
|
||||
{
|
||||
return (turn);
|
||||
}
|
||||
RunningTurn live = runtime.getRunningTurn(turn.getId());
|
||||
if(live == null && orphaned(turn))
|
||||
{
|
||||
return (reap(turn, reason));
|
||||
}
|
||||
Instant now = runtime.getClock().instant();
|
||||
if(!store.updateRunningTurn(userId, new QRecord().withValue("id", turn.getId())
|
||||
.withValue("status", "CANCELLING").withValue("cancelReason", reason).withValue("cancelRequestedAt", now)))
|
||||
{
|
||||
return (store.getTurn(userId, turn.getId()));
|
||||
}
|
||||
turn.setStatus("CANCELLING");
|
||||
turn.setCancelReason(reason);
|
||||
turn.setCancelRequestedAt(now);
|
||||
if(live != null)
|
||||
{
|
||||
try
|
||||
{
|
||||
live.cancel(reason);
|
||||
}
|
||||
catch(Exception e)
|
||||
{
|
||||
LOG.warn("Assistant stream cancellation failed; watchdog will finalize");
|
||||
}
|
||||
}
|
||||
return (turn);
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
|
||||
/*******************************************************************************
|
||||
** GET /turns/active: the caller's runs, newest first, after orphan recovery.
|
||||
*******************************************************************************/
|
||||
public Map<String, Object> activeTurns() throws QException, AssistantApiException
|
||||
{
|
||||
requireAccess();
|
||||
List<AssistantTurn> turns = new ArrayList<>();
|
||||
for(AssistantTurn turn : store.listRunningTurns(userId))
|
||||
{
|
||||
turn = reapIfOrphaned(turn);
|
||||
if(isRunning(turn))
|
||||
{
|
||||
turns.add(turn);
|
||||
}
|
||||
}
|
||||
if(!isRunning(turn))
|
||||
turns.sort(Comparator.comparing(AssistantTurn::getStartedAt, Comparator.nullsFirst(Comparator.naturalOrder()))
|
||||
.thenComparing(AssistantTurn::getId).reversed());
|
||||
List<Map<String, Object>> rows = new ArrayList<>();
|
||||
for(AssistantTurn turn : turns)
|
||||
{
|
||||
throw (new AssistantApiException(409, "This answer has already finished."));
|
||||
RunningTurn live = runtime.getRunningTurn(turn.getId());
|
||||
Map<String, Object> row = new LinkedHashMap<>();
|
||||
row.put("turnId", turn.getId());
|
||||
row.put("conversationId", turn.getConversationId());
|
||||
row.put("assistantMessageId", turn.getAssistantMessageId());
|
||||
row.put("userMessageId", turn.getUserMessageId());
|
||||
row.put("status", turn.getStatus());
|
||||
row.put("phase", live == null ? turn.getPhase() : live.getPhase());
|
||||
row.put("startedAt", turn.getStartedAt() == null ? null : turn.getStartedAt().toString());
|
||||
row.put("heartbeatAt", turn.getHeartbeatAt() == null ? null : turn.getHeartbeatAt().toString());
|
||||
row.put("elapsedMs", turn.getStartedAt() == null ? 0 : Math.max(0, Duration.between(turn.getStartedAt(), runtime.getClock().instant()).toMillis()));
|
||||
row.put("live", live != null);
|
||||
row.put("concurrencyMode", turn.getConcurrencyMode());
|
||||
rows.add(row);
|
||||
}
|
||||
|
||||
store.updateFields(AssistantTurn.TABLE_NAME, new QRecord().withValue("id", turnId).withValue("status", "CANCELLING"));
|
||||
RunningTurn live = runtime.getRunningTurn(turnId);
|
||||
if(live != null && userId.equals(live.getUserId()))
|
||||
{
|
||||
live.cancel("USER");
|
||||
}
|
||||
return (Map.of("status", "CANCELLING"));
|
||||
return (Map.of("turns", rows));
|
||||
}
|
||||
|
||||
|
||||
@@ -459,60 +617,106 @@ public class AssistantApi
|
||||
|
||||
|
||||
/*******************************************************************************
|
||||
** A turn whose replica died: it still says RUNNING / CANCELLING, no turn
|
||||
** of this runtime owns it, and it started longer ago than maxTurnSeconds
|
||||
** + 60 s (a live engine always ends itself by then). On first sight it is
|
||||
** finished as ERROR: the assistant message gets status ERROR and a
|
||||
** notice, and synthetic error (INTERNAL) + message.end events are
|
||||
** persisted, so replays end. Returns the (possibly updated) turn.
|
||||
** A remote run loses its lease, exceeds the absolute deadline, or has a
|
||||
** cancellation request that its owner did not acknowledge in time.
|
||||
*******************************************************************************/
|
||||
private boolean orphaned(AssistantTurn turn)
|
||||
{
|
||||
Instant now = runtime.getClock().instant();
|
||||
Instant heartbeat = turn.getHeartbeatAt() == null ? turn.getStartedAt() : turn.getHeartbeatAt();
|
||||
return ((heartbeat != null && heartbeat.isBefore(now.minusSeconds(config.getTurnLeaseSeconds())))
|
||||
|| (turn.getStartedAt() != null && turn.getStartedAt().isBefore(now.minusSeconds(maxStreamSeconds())))
|
||||
|| ("CANCELLING".equals(turn.getStatus()) && turn.getCancelRequestedAt() != null
|
||||
&& turn.getCancelRequestedAt().isBefore(now.minusSeconds(config.getTurnLeaseSeconds()))));
|
||||
}
|
||||
|
||||
|
||||
|
||||
/*******************************************************************************
|
||||
** Recover an abandoned run and leave a terminal replay for refreshes.
|
||||
*******************************************************************************/
|
||||
AssistantTurn reapIfOrphaned(AssistantTurn turn) throws QException
|
||||
{
|
||||
if(!isRunning(turn) || runtime.getRunningTurn(turn.getId()) != null || turn.getStartedAt() == null)
|
||||
synchronized(store)
|
||||
{
|
||||
return (turn);
|
||||
}
|
||||
Instant stale = runtime.getClock().instant().minusSeconds(config.getMaxTurnSeconds() + 60L);
|
||||
if(!turn.getStartedAt().isBefore(stale))
|
||||
{
|
||||
return (turn);
|
||||
}
|
||||
|
||||
String text = "This answer was interrupted (the server restarted). Ask again.";
|
||||
if(turn.getAssistantMessageId() != null)
|
||||
{
|
||||
AssistantMessage message = store.getMessage(userId, turn.getAssistantMessageId());
|
||||
if(message != null)
|
||||
if(!isRunning(turn) || runtime.getRunningTurn(turn.getId()) != null || !orphaned(turn))
|
||||
{
|
||||
store.updateFields(AssistantMessage.TABLE_NAME, new QRecord()
|
||||
.withValue("id", message.getId())
|
||||
.withValue("status", "ERROR")
|
||||
.withValue("partsJson", MessageParts.fromJson(message.getPartsJson()).addNotice("error", text).toJson()));
|
||||
return (turn);
|
||||
}
|
||||
String reason = "CANCELLING".equals(turn.getStatus()) && turn.getCancelRequestedAt() != null
|
||||
&& turn.getCancelRequestedAt().isBefore(runtime.getClock().instant().minusSeconds(config.getTurnLeaseSeconds()))
|
||||
? (turn.getCancelReason() == null ? "USER" : turn.getCancelReason()) : null;
|
||||
return (reap(turn, reason));
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
|
||||
/*******************************************************************************
|
||||
** Re-read before recovery; never overwrite an already terminal row or
|
||||
** append another terminal event. Each persistence step is independent.
|
||||
*******************************************************************************/
|
||||
private AssistantTurn reap(AssistantTurn turn, String cancelReason) throws QException
|
||||
{
|
||||
AssistantTurn current = store.getTurn(userId, turn.getId());
|
||||
if(!isRunning(current))
|
||||
{
|
||||
return (current);
|
||||
}
|
||||
if(!orphaned(current))
|
||||
{
|
||||
return (cancelReason == null ? current : requestStop(current, cancelReason));
|
||||
}
|
||||
// Recovery only appends fixed notices to already redacted stored parts (or
|
||||
// crash placeholders). It never reloads model/tool values or raw user text.
|
||||
String status = cancelReason == null ? "ERROR" : "CANCELLED";
|
||||
String text = cancelReason == null ? "This answer was interrupted (the server restarted). Ask again."
|
||||
: ("SUPERSEDED".equals(cancelReason) ? TurnEngine.SUPERSEDED_TEXT : "Stopped by you.");
|
||||
if(current.getAssistantMessageId() != null)
|
||||
{
|
||||
try
|
||||
{
|
||||
AssistantMessage message = store.getMessage(userId, current.getAssistantMessageId());
|
||||
if(message != null)
|
||||
{
|
||||
store.updateFields(AssistantMessage.TABLE_NAME, new QRecord().withValue("id", message.getId()).withValue("status", status)
|
||||
.withValue("partsJson", MessageParts.fromJson(message.getPartsJson()).addNotice(cancelReason == null ? "error" : "info", text).toJson()));
|
||||
}
|
||||
}
|
||||
catch(Exception e)
|
||||
{
|
||||
LOG.warn("Could not persist recovered assistant message");
|
||||
}
|
||||
}
|
||||
|
||||
int seq = store.lastEventSeq(userId, turn.getId());
|
||||
store.insertEvent(turn.getId(), userId, seq + 1, TurnEvent.ERROR, new TurnEvent(seq + 1, TurnEvent.ERROR, Map.of("code", "INTERNAL", "message", text)).toJson());
|
||||
Map<String, Object> end = new java.util.LinkedHashMap<>();
|
||||
if(turn.getAssistantMessageId() != null)
|
||||
try
|
||||
{
|
||||
end.put("messageId", turn.getAssistantMessageId());
|
||||
int seq = store.lastEventSeq(userId, current.getId());
|
||||
List<AssistantTurnEvent> last = store.listEvents(userId, current.getId(), Math.max(0, seq - 1), 1);
|
||||
if(last.isEmpty() || !TurnEvent.MESSAGE_END.equals(last.getFirst().getEventType()))
|
||||
{
|
||||
if(cancelReason == null)
|
||||
{
|
||||
seq++;
|
||||
store.insertEvent(current.getId(), userId, seq, TurnEvent.ERROR,
|
||||
new TurnEvent(seq, TurnEvent.ERROR, Map.of("code", "INTERNAL", "message", text)).toJson());
|
||||
}
|
||||
seq++;
|
||||
Map<String, Object> end = new LinkedHashMap<>();
|
||||
end.put("messageId", current.getAssistantMessageId());
|
||||
end.put("status", status);
|
||||
end.put("stopReason", cancelReason == null ? "interrupted" : "cancelled");
|
||||
store.insertEvent(current.getId(), userId, seq, TurnEvent.MESSAGE_END, new TurnEvent(seq, TurnEvent.MESSAGE_END, end).toJson());
|
||||
}
|
||||
}
|
||||
catch(Exception e)
|
||||
{
|
||||
LOG.warn("Could not persist recovered assistant events");
|
||||
}
|
||||
end.put("status", "ERROR");
|
||||
end.put("stopReason", "interrupted");
|
||||
store.insertEvent(turn.getId(), userId, seq + 2, TurnEvent.MESSAGE_END, new TurnEvent(seq + 2, TurnEvent.MESSAGE_END, end).toJson());
|
||||
|
||||
Instant now = runtime.getClock().instant();
|
||||
store.updateFields(AssistantTurn.TABLE_NAME, new QRecord()
|
||||
.withValue("id", turn.getId())
|
||||
.withValue("status", "ERROR")
|
||||
.withValue("errorCode", "INTERNAL")
|
||||
.withValue("stopReason", "interrupted")
|
||||
.withValue("endedAt", now));
|
||||
turn.setStatus("ERROR");
|
||||
turn.setErrorCode("INTERNAL");
|
||||
turn.setEndedAt(now);
|
||||
return (turn);
|
||||
store.updateRunningTurn(userId, new QRecord().withValue("id", current.getId()).withValue("status", status)
|
||||
.withValue("errorCode", cancelReason == null ? "INTERNAL" : null).withValue("cancelReason", cancelReason)
|
||||
.withValue("stopReason", cancelReason == null ? "interrupted" : "cancelled").withValue("phase", "done").withValue("endedAt", now));
|
||||
return (store.getTurn(userId, current.getId()));
|
||||
}
|
||||
|
||||
|
||||
@@ -576,6 +780,12 @@ public class AssistantApi
|
||||
throw (new AssistantApiException(409, "This action is already " + action.getStatus().toLowerCase() + "."));
|
||||
}
|
||||
|
||||
AssistantTurn proposingTurn = store.getTurn(userId, action.getTurnId());
|
||||
if(proposingTurn != null && isRunning(proposingTurn))
|
||||
{
|
||||
throw (new AssistantApiException(409, "Wait for the assistant to finish before confirming this action."));
|
||||
}
|
||||
|
||||
///////////////////////////////////////////////////////////////////////
|
||||
// claim it first, so a double click cannot run the write twice //
|
||||
///////////////////////////////////////////////////////////////////////
|
||||
@@ -597,8 +807,10 @@ public class AssistantApi
|
||||
throw (new QException("The stored values of action " + id + " are not valid JSON", e));
|
||||
}
|
||||
PolicyService.EffectivePolicy policy = runtime.getPolicyService().current(true);
|
||||
UiApiToolbox.Context context = new UiApiToolbox.Context(session.getUuid(), session.getValue(QSession.VALUE_KEY_USER_TIMEZONE), runtime.getUiApiGateway(), policy.tools(), null);
|
||||
UiApiToolbox.Outcome outcome = runtime.getToolbox().executeConfirmedWrite(context, action.getToolCallId(), action.getToolName(), action.getTableName(), action.getRecordId(), values);
|
||||
UiApiToolbox.Context context = new UiApiToolbox.Context(session.getUuid(), session.getValue(QSession.VALUE_KEY_USER_TIMEZONE), runtime.getUiApiGateway(), policy.tools(), null, credentials, action.getTurnId() == null ? null : String.valueOf(action.getTurnId()));
|
||||
UiApiToolbox.Outcome outcome = BulkLoadTools.WRITE_TOOLS.contains(action.getToolName())
|
||||
? runtime.getBulkLoadTools().executeConfirmed(context, action.getToolCallId(), action.getToolName(), action.getTableName(), values)
|
||||
: runtime.getToolbox().executeConfirmedWrite(context, action.getToolCallId(), action.getToolName(), action.getTableName(), action.getRecordId(), values);
|
||||
AiToolResult result = outcome.getResult();
|
||||
boolean ok = result.getOutcome() == AiToolOutcome.OK;
|
||||
|
||||
@@ -610,6 +822,7 @@ public class AssistantApi
|
||||
|
||||
store.insert(new AssistantToolCall()
|
||||
.withTurnId(action.getTurnId())
|
||||
.withClientChannel("assistant" + (action.getTurnId() == null ? "" : "/" + action.getTurnId()))
|
||||
.withConversationId(action.getConversationId())
|
||||
.withUserId(userId)
|
||||
.withToolCallId(action.getToolCallId())
|
||||
@@ -716,10 +929,24 @@ public class AssistantApi
|
||||
** reason.
|
||||
*******************************************************************************/
|
||||
public Map<String, Object> access(String table, String prompt) throws QException, AssistantApiException
|
||||
{
|
||||
return (access(table, prompt, null));
|
||||
}
|
||||
|
||||
|
||||
|
||||
/*******************************************************************************
|
||||
** A supplied turn must belong to this user before using it for attribution.
|
||||
*******************************************************************************/
|
||||
public Map<String, Object> access(String table, String prompt, Integer turnId) throws QException, AssistantApiException
|
||||
{
|
||||
requireAccess();
|
||||
if(turnId != null)
|
||||
{
|
||||
requireTurn(turnId);
|
||||
}
|
||||
List<Map<String, Object>> tables = new ArrayList<>();
|
||||
for(AccessExplainer.TableAccess access : runtime.getAccessExplainer().explain(runtime.getUiApiGateway(), session.getUuid(), runtime.getPolicyService().current(false).tools(), table, prompt))
|
||||
for(AccessExplainer.TableAccess access : runtime.getAccessExplainer().explain(runtime.getUiApiGateway(), session.getUuid(), credentials, runtime.getPolicyService().current(false).tools(), table, prompt, turnId == null ? null : String.valueOf(turnId)))
|
||||
{
|
||||
if(!access.uiVisible() && access.mode() == DataAccessMode.NONE)
|
||||
{
|
||||
@@ -754,6 +981,16 @@ public class AssistantApi
|
||||
|
||||
|
||||
|
||||
/*******************************************************************************
|
||||
** Hard upper bound for remote stream polling and stale-run recovery.
|
||||
*******************************************************************************/
|
||||
public long maxStreamSeconds()
|
||||
{
|
||||
return (config.getMaxTurnSeconds() + (long) config.getTurnForceFinalizeGraceSeconds() + config.getTurnLeaseSeconds());
|
||||
}
|
||||
|
||||
|
||||
|
||||
/*******************************************************************************
|
||||
** The user may use the panel: enabled, signed in, assistant.hasAccess.
|
||||
*******************************************************************************/
|
||||
|
||||
+6
-464
@@ -17,63 +17,27 @@
|
||||
package com.kingsrook.qbits.assistant.api;
|
||||
|
||||
|
||||
import java.io.IOException;
|
||||
import java.io.OutputStream;
|
||||
import java.nio.charset.StandardCharsets;
|
||||
import java.util.LinkedHashMap;
|
||||
import java.util.List;
|
||||
import java.util.Map;
|
||||
import com.fasterxml.jackson.annotation.JsonInclude;
|
||||
import com.fasterxml.jackson.core.type.TypeReference;
|
||||
import com.fasterxml.jackson.databind.DeserializationFeature;
|
||||
import com.kingsrook.qbits.assistant.AssistantRuntime;
|
||||
import com.kingsrook.qbits.assistant.engine.RunningTurn;
|
||||
import com.kingsrook.qbits.assistant.engine.TurnEvent;
|
||||
import com.kingsrook.qbits.assistant.engine.TurnEventLog;
|
||||
import com.kingsrook.qqq.backend.core.context.QContext;
|
||||
import com.kingsrook.qqq.backend.core.exceptions.QException;
|
||||
import com.kingsrook.qqq.backend.core.logging.QLogger;
|
||||
import com.kingsrook.qqq.backend.core.model.metadata.QInstance;
|
||||
import com.kingsrook.qqq.backend.core.model.session.QSession;
|
||||
import com.kingsrook.qqq.backend.core.utils.JsonUtils;
|
||||
import com.kingsrook.qqq.backend.core.utils.StringUtils;
|
||||
import com.kingsrook.qqq.middleware.javalin.QJavalinRouteProviderInterface;
|
||||
import com.kingsrook.qqq.middleware.javalin.QJavalinUtils;
|
||||
import com.kingsrook.qqq.middleware.javalin.executors.ExecutorSessionUtils;
|
||||
import io.javalin.config.JavalinConfig;
|
||||
import io.javalin.http.ContentType;
|
||||
import io.javalin.http.Context;
|
||||
import static com.kingsrook.qqq.backend.core.logging.LogUtils.logPair;
|
||||
|
||||
|
||||
/*******************************************************************************
|
||||
** Javalin routes under /qqq/v1/assistant (contract section 3).
|
||||
**
|
||||
** Every request gets the user's own session from the instance's
|
||||
** authentication module (ExecutorSessionUtils.setupSession: session cookie,
|
||||
** bearer token or API key) - never a system session. Bodies must be JSON
|
||||
** (a cross-site form cannot send that without a CORS preflight).
|
||||
**
|
||||
** Streams (POST /conversations/{id}/turns, GET /turns/{id}/events) are
|
||||
** Server-Sent Events written to the response as they happen: "id: seq",
|
||||
** "event: type", "data: json", a blank line; a ping every 15 seconds;
|
||||
** Cache-Control no-cache and X-Accel-Buffering no (proxies must not
|
||||
** buffer; give the route a long idle timeout). The turn itself runs on its
|
||||
** own thread, so a client disconnect does not stop it; the client resumes
|
||||
** with /events?after=<last seq>.
|
||||
**
|
||||
** Request and response bodies are never logged.
|
||||
** No routes any more: the assistant's endpoints are spec'd /qqq/v1
|
||||
** operations ({@link com.kingsrook.qbits.assistant.api.specs.AssistantSpecs}).
|
||||
** What is left is a before-handler that learns this server's local port from
|
||||
** the first /qqq/v1 request, so the tools (and Explain access) can call the
|
||||
** UI API on 127.0.0.1 before any assistant operation has run.
|
||||
*******************************************************************************/
|
||||
public class AssistantRouteProvider implements QJavalinRouteProviderInterface
|
||||
{
|
||||
private static final QLogger LOG = QLogger.getLogger(AssistantRouteProvider.class);
|
||||
|
||||
public static final String BASE_PATH = "/qqq/v1/assistant";
|
||||
public static final long PING_MILLIS = 15_000;
|
||||
public static final long REMOTE_POLL_MS = 1_000;
|
||||
public static final String BASE_PATH = "/qqq/v1/assistant";
|
||||
|
||||
private QInstance qInstance;
|
||||
private long pingMillis = PING_MILLIS;
|
||||
|
||||
|
||||
|
||||
@@ -88,28 +52,12 @@ public class AssistantRouteProvider implements QJavalinRouteProviderInterface
|
||||
|
||||
|
||||
|
||||
/*******************************************************************************
|
||||
** Ping interval (tests use a short one).
|
||||
*******************************************************************************/
|
||||
public AssistantRouteProvider withPingMillis(long pingMillis)
|
||||
{
|
||||
this.pingMillis = pingMillis;
|
||||
return (this);
|
||||
}
|
||||
|
||||
|
||||
|
||||
/*******************************************************************************
|
||||
**
|
||||
*******************************************************************************/
|
||||
@Override
|
||||
public void acceptJavalinConfig(JavalinConfig config)
|
||||
{
|
||||
///////////////////////////////////////////////////////////////////////
|
||||
// learn this server's local port from the first UI request (e.g. //
|
||||
// the metaData load), so tools and Explain access can loop back to //
|
||||
// /qqq/v1 before any assistant route has been called //
|
||||
///////////////////////////////////////////////////////////////////////
|
||||
config.routes.before("/qqq/v1/*", ctx ->
|
||||
{
|
||||
AssistantRuntime runtime = AssistantRuntime.of(qInstance);
|
||||
@@ -125,412 +73,6 @@ public class AssistantRouteProvider implements QJavalinRouteProviderInterface
|
||||
}
|
||||
}
|
||||
});
|
||||
config.routes.get(BASE_PATH + "/config", ctx -> json(ctx, false, (api, body) -> api.config()));
|
||||
config.routes.get(BASE_PATH + "/conversations", ctx -> json(ctx, false, (api, body) -> api.listConversations(ctx.queryParam("status"))));
|
||||
config.routes.post(BASE_PATH + "/conversations", ctx -> json(ctx, true, (api, body) ->
|
||||
{
|
||||
ctx.status(201);
|
||||
return (api.createConversation(body));
|
||||
}));
|
||||
config.routes.get(BASE_PATH + "/conversations/{id}", ctx -> json(ctx, false, (api, body) -> api.getConversation(pathInt(ctx, "id"), queryInt(ctx, "before"), queryInt(ctx, "limit"))));
|
||||
config.routes.patch(BASE_PATH + "/conversations/{id}", ctx -> json(ctx, true, (api, body) -> api.patchConversation(pathInt(ctx, "id"), body)));
|
||||
config.routes.delete(BASE_PATH + "/conversations/{id}", ctx -> json(ctx, false, (api, body) ->
|
||||
{
|
||||
api.deleteConversation(pathInt(ctx, "id"));
|
||||
ctx.status(204);
|
||||
return (null);
|
||||
}));
|
||||
config.routes.post(BASE_PATH + "/conversations/{id}/turns", this::startTurn);
|
||||
config.routes.get(BASE_PATH + "/turns/{turnId}/events", this::turnEvents);
|
||||
config.routes.post(BASE_PATH + "/turns/{turnId}/cancel", ctx -> json(ctx, true, (api, body) ->
|
||||
{
|
||||
ctx.status(202);
|
||||
return (api.cancelTurn(pathInt(ctx, "turnId")));
|
||||
}));
|
||||
config.routes.get(BASE_PATH + "/access", ctx -> json(ctx, false, (api, body) -> api.access(ctx.queryParam("table"), ctx.queryParam("prompt"))));
|
||||
config.routes.get(BASE_PATH + "/actions/{id}", ctx -> json(ctx, false, (api, body) -> api.getAction(pathInt(ctx, "id"))));
|
||||
config.routes.post(BASE_PATH + "/actions/{id}/confirm", ctx -> json(ctx, true, (api, body) -> api.confirmAction(pathInt(ctx, "id"))));
|
||||
config.routes.post(BASE_PATH + "/actions/{id}/reject", ctx -> json(ctx, true, (api, body) -> api.rejectAction(pathInt(ctx, "id"))));
|
||||
config.routes.post(BASE_PATH + "/messages/{id}/feedback", ctx -> json(ctx, true, (api, body) ->
|
||||
{
|
||||
api.feedback(pathInt(ctx, "id"), body);
|
||||
ctx.status(204);
|
||||
return (null);
|
||||
}));
|
||||
}
|
||||
|
||||
|
||||
|
||||
/*******************************************************************************
|
||||
** Session, runtime, body, handler, JSON - or the error.
|
||||
*******************************************************************************/
|
||||
private void json(Context context, boolean readsBody, Handler handler)
|
||||
{
|
||||
try
|
||||
{
|
||||
AssistantApi api = api(context);
|
||||
Map<String, Object> body = readsBody ? readJsonBody(context) : Map.of();
|
||||
Object result = handler.handle(api, body);
|
||||
if(result != null)
|
||||
{
|
||||
context.contentType(ContentType.APPLICATION_JSON);
|
||||
context.result(JsonUtils.toJsonCustomized(result, builder -> builder.serializationInclusion(JsonInclude.Include.ALWAYS)));
|
||||
}
|
||||
}
|
||||
catch(Exception e)
|
||||
{
|
||||
handleException(context, e);
|
||||
}
|
||||
finally
|
||||
{
|
||||
QContext.clear();
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
|
||||
/*******************************************************************************
|
||||
** POST /conversations/{id}/turns
|
||||
*******************************************************************************/
|
||||
private void startTurn(Context context)
|
||||
{
|
||||
RunningTurn turn;
|
||||
try
|
||||
{
|
||||
AssistantApi api = api(context);
|
||||
turn = api.startTurn(pathInt(context, "id"), readJsonBody(context));
|
||||
}
|
||||
catch(Exception e)
|
||||
{
|
||||
handleException(context, e);
|
||||
QContext.clear();
|
||||
return;
|
||||
}
|
||||
QContext.clear();
|
||||
streamLive(context, turn.getLog(), 0);
|
||||
}
|
||||
|
||||
|
||||
|
||||
/*******************************************************************************
|
||||
** GET /turns/{turnId}/events?after=
|
||||
*******************************************************************************/
|
||||
private void turnEvents(Context context)
|
||||
{
|
||||
Integer turnId;
|
||||
int after;
|
||||
AssistantApi api;
|
||||
AssistantApi.TurnEvents events;
|
||||
try
|
||||
{
|
||||
api = api(context);
|
||||
turnId = pathInt(context, "turnId");
|
||||
Integer afterParam = queryInt(context, "after");
|
||||
after = afterParam == null ? 0 : Math.max(0, afterParam);
|
||||
events = api.turnEvents(turnId, after);
|
||||
}
|
||||
catch(Exception e)
|
||||
{
|
||||
handleException(context, e);
|
||||
QContext.clear();
|
||||
return;
|
||||
}
|
||||
|
||||
if(events.live() != null)
|
||||
{
|
||||
QContext.clear();
|
||||
streamLive(context, events.live().getLog(), after);
|
||||
return;
|
||||
}
|
||||
|
||||
///////////////////////////////////////////////////////////////////////
|
||||
// persisted events; if the turn still runs on another replica, poll //
|
||||
///////////////////////////////////////////////////////////////////////
|
||||
try
|
||||
{
|
||||
OutputStream out = startStream(context);
|
||||
int last = after;
|
||||
long lastWrite = System.currentTimeMillis();
|
||||
long giveUpAt = System.currentTimeMillis() + (api.maxTurnSeconds() + 60L) * 1000L;
|
||||
AssistantApi.TurnEvents current = events;
|
||||
while(true)
|
||||
{
|
||||
boolean ended = false;
|
||||
for(TurnEvent event : current.persisted())
|
||||
{
|
||||
write(out, event.toSseFrame());
|
||||
last = event.getSeq();
|
||||
lastWrite = System.currentTimeMillis();
|
||||
ended |= event.isTerminal();
|
||||
}
|
||||
if(ended || (current.finished() && !current.more()) || System.currentTimeMillis() > giveUpAt)
|
||||
{
|
||||
return;
|
||||
}
|
||||
if(!current.more())
|
||||
{
|
||||
Thread.sleep(REMOTE_POLL_MS);
|
||||
}
|
||||
if(System.currentTimeMillis() - lastWrite >= pingMillis)
|
||||
{
|
||||
write(out, ping());
|
||||
lastWrite = System.currentTimeMillis();
|
||||
}
|
||||
current = api.turnEvents(turnId, last);
|
||||
if(current.live() != null)
|
||||
{
|
||||
QContext.clear();
|
||||
writeLive(out, current.live().getLog(), last);
|
||||
return;
|
||||
}
|
||||
}
|
||||
}
|
||||
catch(IOException e)
|
||||
{
|
||||
LOG.debug("Assistant event stream closed by the client", logPair("turnId", turnId));
|
||||
}
|
||||
catch(InterruptedException e)
|
||||
{
|
||||
Thread.currentThread().interrupt();
|
||||
}
|
||||
catch(Exception e)
|
||||
{
|
||||
LOG.warn("Assistant event replay failed", e, logPair("turnId", turnId));
|
||||
}
|
||||
finally
|
||||
{
|
||||
QContext.clear();
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
|
||||
/*******************************************************************************
|
||||
** Stream a live log from a sequence number until message.end.
|
||||
*******************************************************************************/
|
||||
private void streamLive(Context context, TurnEventLog log, int after)
|
||||
{
|
||||
try
|
||||
{
|
||||
writeLive(startStream(context), log, after);
|
||||
}
|
||||
catch(IOException e)
|
||||
{
|
||||
LOG.debug("Assistant stream closed by the client (the turn continues)");
|
||||
}
|
||||
catch(InterruptedException e)
|
||||
{
|
||||
Thread.currentThread().interrupt();
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
|
||||
/*******************************************************************************
|
||||
**
|
||||
*******************************************************************************/
|
||||
private void writeLive(OutputStream out, TurnEventLog log, int after) throws IOException, InterruptedException
|
||||
{
|
||||
int last = after;
|
||||
while(true)
|
||||
{
|
||||
List<TurnEvent> events = log.after(last, pingMillis);
|
||||
if(events.isEmpty())
|
||||
{
|
||||
if(log.isClosed())
|
||||
{
|
||||
return;
|
||||
}
|
||||
write(out, ping());
|
||||
continue;
|
||||
}
|
||||
for(TurnEvent event : events)
|
||||
{
|
||||
write(out, event.toSseFrame());
|
||||
last = event.getSeq();
|
||||
if(event.isTerminal())
|
||||
{
|
||||
return;
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
|
||||
/*******************************************************************************
|
||||
** Start an SSE response.
|
||||
*******************************************************************************/
|
||||
private static OutputStream startStream(Context context) throws IOException
|
||||
{
|
||||
context.status(200);
|
||||
context.disableCompression();
|
||||
context.res().setContentType("text/event-stream; charset=utf-8");
|
||||
context.res().setHeader("Cache-Control", "no-cache");
|
||||
context.res().setHeader("X-Accel-Buffering", "no");
|
||||
context.res().setHeader("Connection", "keep-alive");
|
||||
OutputStream out = context.res().getOutputStream();
|
||||
out.flush();
|
||||
return (out);
|
||||
}
|
||||
|
||||
|
||||
|
||||
/*******************************************************************************
|
||||
**
|
||||
*******************************************************************************/
|
||||
private static void write(OutputStream out, String frame) throws IOException
|
||||
{
|
||||
out.write(frame.getBytes(StandardCharsets.UTF_8));
|
||||
out.flush();
|
||||
}
|
||||
|
||||
|
||||
|
||||
/*******************************************************************************
|
||||
**
|
||||
*******************************************************************************/
|
||||
private static String ping()
|
||||
{
|
||||
return ("event: " + TurnEvent.PING + "\ndata: {}\n\n");
|
||||
}
|
||||
|
||||
|
||||
|
||||
/*******************************************************************************
|
||||
** Session + API for a request. 404 when the QBit is not in the instance.
|
||||
*******************************************************************************/
|
||||
private AssistantApi api(Context context) throws Exception
|
||||
{
|
||||
AssistantRuntime runtime = AssistantRuntime.of(qInstance);
|
||||
if(runtime == null)
|
||||
{
|
||||
throw (new AssistantApiException(404, "The assistant is not installed."));
|
||||
}
|
||||
////////////////////////////////////////////////////////////////////
|
||||
// the tools call /qqq/v1 on this server: remember its local port //
|
||||
////////////////////////////////////////////////////////////////////
|
||||
try
|
||||
{
|
||||
runtime.learnLocalPort(context.req().getLocalPort());
|
||||
}
|
||||
catch(RuntimeException e)
|
||||
{
|
||||
LOG.debug("Could not read the local port", e);
|
||||
}
|
||||
QSession session = ExecutorSessionUtils.setupSession(context, qInstance);
|
||||
return (new AssistantApi(runtime, session));
|
||||
}
|
||||
|
||||
|
||||
|
||||
/*******************************************************************************
|
||||
** Map errors: API errors with their status, others through QQQ's handler
|
||||
** (401 / 403 / 404 / 500).
|
||||
*******************************************************************************/
|
||||
private static void handleException(Context context, Exception e)
|
||||
{
|
||||
if(e instanceof AssistantApiException apiException)
|
||||
{
|
||||
Map<String, Object> body = new LinkedHashMap<>();
|
||||
body.put("error", apiException.getMessage());
|
||||
if(apiException.getCode() != null)
|
||||
{
|
||||
body.put("code", apiException.getCode());
|
||||
}
|
||||
context.status(apiException.getStatus());
|
||||
context.contentType(ContentType.APPLICATION_JSON);
|
||||
context.result(JsonUtils.toJson(body));
|
||||
return;
|
||||
}
|
||||
if(!(e instanceof QException))
|
||||
{
|
||||
LOG.warn("Assistant request failed", e);
|
||||
}
|
||||
QJavalinUtils.handleException(null, context, e);
|
||||
}
|
||||
|
||||
|
||||
|
||||
/*******************************************************************************
|
||||
** A JSON object body (empty body = empty object).
|
||||
*******************************************************************************/
|
||||
static Map<String, Object> readJsonBody(Context context) throws AssistantApiException
|
||||
{
|
||||
String body = context.body();
|
||||
if(!StringUtils.hasContent(body))
|
||||
{
|
||||
return (new LinkedHashMap<>());
|
||||
}
|
||||
|
||||
String contentType = context.contentType();
|
||||
if(contentType == null || !contentType.toLowerCase().startsWith("application/json"))
|
||||
{
|
||||
throw (new AssistantApiException(400, "Request bodies must be JSON (Content-Type: application/json)."));
|
||||
}
|
||||
|
||||
try
|
||||
{
|
||||
Map<String, Object> map = JsonUtils.toObject(body, new TypeReference<Map<String, Object>>() {}, mapper -> mapper.enable(DeserializationFeature.USE_BIG_DECIMAL_FOR_FLOATS));
|
||||
return (map == null ? new LinkedHashMap<>() : map);
|
||||
}
|
||||
catch(Exception e)
|
||||
{
|
||||
throw (new AssistantApiException(400, "The request body is not a JSON object."));
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
|
||||
/*******************************************************************************
|
||||
**
|
||||
*******************************************************************************/
|
||||
private static Integer pathInt(Context context, String name) throws AssistantApiException
|
||||
{
|
||||
try
|
||||
{
|
||||
return (Integer.parseInt(context.pathParam(name)));
|
||||
}
|
||||
catch(NumberFormatException e)
|
||||
{
|
||||
throw (new AssistantApiException(400, name + " must be an integer."));
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
|
||||
/*******************************************************************************
|
||||
**
|
||||
*******************************************************************************/
|
||||
private static Integer queryInt(Context context, String name) throws AssistantApiException
|
||||
{
|
||||
String value = context.queryParam(name);
|
||||
if(!StringUtils.hasContent(value))
|
||||
{
|
||||
return (null);
|
||||
}
|
||||
try
|
||||
{
|
||||
return (Integer.parseInt(value.trim()));
|
||||
}
|
||||
catch(NumberFormatException e)
|
||||
{
|
||||
throw (new AssistantApiException(400, name + " must be an integer."));
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
|
||||
/*******************************************************************************
|
||||
** One JSON endpoint's work.
|
||||
*******************************************************************************/
|
||||
@FunctionalInterface
|
||||
private interface Handler
|
||||
{
|
||||
/*******************************************************************************
|
||||
**
|
||||
*******************************************************************************/
|
||||
Object handle(AssistantApi api, Map<String, Object> body) throws Exception;
|
||||
}
|
||||
|
||||
}
|
||||
@@ -17,10 +17,12 @@
|
||||
package com.kingsrook.qbits.assistant.api;
|
||||
|
||||
|
||||
import com.kingsrook.qbits.assistant.api.specs.AssistantSpecs;
|
||||
import com.kingsrook.qqq.backend.core.model.metadata.QInstance;
|
||||
import com.kingsrook.qqq.backend.core.model.metadata.code.QCodeReference;
|
||||
import com.kingsrook.qqq.backend.core.utils.CollectionUtils;
|
||||
import com.kingsrook.qqq.middleware.javalin.QJavalinMetaData;
|
||||
import com.kingsrook.qqq.middleware.javalin.specs.extensions.MiddlewareSpecExtensionsMetaData;
|
||||
|
||||
|
||||
/*******************************************************************************
|
||||
@@ -43,6 +45,16 @@ public class AssistantRoutes
|
||||
{
|
||||
javalinMetaData.withAdditionalRouteProviderReference(new QCodeReference(AssistantRouteProvider.class));
|
||||
}
|
||||
|
||||
////////////////////////////////////////////////////////////////////
|
||||
// the endpoints: the spec'd "assistant" UI API extension //
|
||||
////////////////////////////////////////////////////////////////////
|
||||
MiddlewareSpecExtensionsMetaData extensions = MiddlewareSpecExtensionsMetaData.ofOrWithNew(qInstance);
|
||||
boolean hasExtension = extensions.getExtensions() != null && extensions.getExtensions().containsKey(AssistantSpecs.EXTENSION_NAME);
|
||||
if(!hasExtension)
|
||||
{
|
||||
extensions.withExtension(AssistantSpecs.extension());
|
||||
}
|
||||
}
|
||||
|
||||
}
|
||||
@@ -0,0 +1,234 @@
|
||||
/*
|
||||
* Copyright 2026 Kingsrook, LLC
|
||||
*
|
||||
* Licensed under the Apache License, Version 2.0 (the "License");
|
||||
* you may not use this file except in compliance with the License.
|
||||
* You may obtain a copy of the License at
|
||||
*
|
||||
* http://www.apache.org/licenses/LICENSE-2.0
|
||||
*
|
||||
* Unless required by applicable law or agreed to in writing, software
|
||||
* distributed under the License is distributed on an "AS IS" BASIS,
|
||||
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
|
||||
* See the License for the specific language governing permissions and
|
||||
* limitations under the License.
|
||||
*/
|
||||
|
||||
package com.kingsrook.qbits.assistant.api;
|
||||
|
||||
|
||||
import java.io.IOException;
|
||||
import java.io.OutputStream;
|
||||
import java.nio.charset.StandardCharsets;
|
||||
import java.util.List;
|
||||
import java.util.Map;
|
||||
import com.kingsrook.qbits.assistant.engine.TurnEvent;
|
||||
import com.kingsrook.qbits.assistant.engine.TurnEventLog;
|
||||
import com.kingsrook.qqq.backend.core.logging.QLogger;
|
||||
import io.javalin.http.Context;
|
||||
import static com.kingsrook.qqq.backend.core.logging.LogUtils.logPair;
|
||||
|
||||
|
||||
/*******************************************************************************
|
||||
** Writes a turn's events as server-sent events: the live log of a turn
|
||||
** running here, or the persisted events (polling while the turn runs on
|
||||
** another replica), with a ping every pingMillis while idle.
|
||||
*******************************************************************************/
|
||||
public final class TurnStreams
|
||||
{
|
||||
private static final QLogger LOG = QLogger.getLogger(TurnStreams.class);
|
||||
|
||||
public static final long PING_MILLIS = 15_000;
|
||||
public static final long REMOTE_POLL_MS = 1_000;
|
||||
|
||||
private static volatile long pingMillis = PING_MILLIS;
|
||||
|
||||
|
||||
|
||||
/*******************************************************************************
|
||||
** Utility class.
|
||||
*******************************************************************************/
|
||||
private TurnStreams()
|
||||
{
|
||||
}
|
||||
|
||||
|
||||
|
||||
/*******************************************************************************
|
||||
** The ping interval (tests use a short one).
|
||||
*******************************************************************************/
|
||||
public static void setPingMillis(long millis)
|
||||
{
|
||||
pingMillis = millis;
|
||||
}
|
||||
|
||||
|
||||
|
||||
/*******************************************************************************
|
||||
** Stream a live log from a sequence number until message.end.
|
||||
*******************************************************************************/
|
||||
public static void streamLive(Context context, TurnEventLog log, int after)
|
||||
{
|
||||
try
|
||||
{
|
||||
writeLive(startStream(context), log, after);
|
||||
}
|
||||
catch(IOException e)
|
||||
{
|
||||
LOG.debug("Assistant stream closed by the client (the turn continues)");
|
||||
}
|
||||
catch(InterruptedException e)
|
||||
{
|
||||
Thread.currentThread().interrupt();
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
|
||||
/*******************************************************************************
|
||||
** Stream the events of a turn after a sequence number: live when it runs
|
||||
** here, else the persisted ones (polling while it runs elsewhere). The
|
||||
** caller's QContext (session) must be set: the replay reads the store.
|
||||
*******************************************************************************/
|
||||
public static void streamEvents(Context context, AssistantApi api, Integer turnId, int after, AssistantApi.TurnEvents first)
|
||||
{
|
||||
if(first.live() != null)
|
||||
{
|
||||
streamLive(context, first.live().getLog(), after);
|
||||
return;
|
||||
}
|
||||
try
|
||||
{
|
||||
OutputStream out = startStream(context);
|
||||
int last = after;
|
||||
long lastWrite = System.currentTimeMillis();
|
||||
long giveUpAt = System.currentTimeMillis() + api.maxStreamSeconds() * 1000L;
|
||||
AssistantApi.TurnEvents current = first;
|
||||
while(true)
|
||||
{
|
||||
boolean ended = false;
|
||||
for(TurnEvent event : current.persisted())
|
||||
{
|
||||
write(out, event.toSseFrame());
|
||||
last = event.getSeq();
|
||||
lastWrite = System.currentTimeMillis();
|
||||
ended |= event.isTerminal();
|
||||
}
|
||||
if(ended || (current.finished() && !current.more()))
|
||||
{
|
||||
return;
|
||||
}
|
||||
if(System.currentTimeMillis() > giveUpAt)
|
||||
{
|
||||
write(out, new TurnEvent(last + 1, TurnEvent.ERROR, Map.of("code", "TIMEOUT", "message", "The event stream timed out. Reconnect to check this answer.")).toSseFrame());
|
||||
write(out, new TurnEvent(last + 2, TurnEvent.MESSAGE_END, Map.of("status", "ERROR", "stopReason", "stream_timeout")).toSseFrame());
|
||||
return;
|
||||
}
|
||||
if(!current.more())
|
||||
{
|
||||
Thread.sleep(REMOTE_POLL_MS);
|
||||
}
|
||||
if(System.currentTimeMillis() - lastWrite >= pingMillis)
|
||||
{
|
||||
write(out, ping());
|
||||
lastWrite = System.currentTimeMillis();
|
||||
}
|
||||
current = api.turnEvents(turnId, last);
|
||||
if(current.live() != null)
|
||||
{
|
||||
writeLive(out, current.live().getLog(), last);
|
||||
return;
|
||||
}
|
||||
}
|
||||
}
|
||||
catch(IOException e)
|
||||
{
|
||||
LOG.debug("Assistant event stream closed by the client", logPair("turnId", turnId));
|
||||
}
|
||||
catch(InterruptedException e)
|
||||
{
|
||||
Thread.currentThread().interrupt();
|
||||
}
|
||||
catch(Exception e)
|
||||
{
|
||||
LOG.warn("Assistant event replay failed", e, logPair("turnId", turnId));
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
|
||||
/*******************************************************************************
|
||||
**
|
||||
*******************************************************************************/
|
||||
static void writeLive(OutputStream out, TurnEventLog log, int after) throws IOException, InterruptedException
|
||||
{
|
||||
int last = after;
|
||||
while(true)
|
||||
{
|
||||
List<TurnEvent> events = log.after(last, pingMillis);
|
||||
if(events.isEmpty())
|
||||
{
|
||||
if(log.isClosed())
|
||||
{
|
||||
// The terminal event may have arrived after the empty poll.
|
||||
if(log.size() <= last)
|
||||
{
|
||||
return;
|
||||
}
|
||||
continue;
|
||||
}
|
||||
write(out, ping());
|
||||
continue;
|
||||
}
|
||||
for(TurnEvent event : events)
|
||||
{
|
||||
write(out, event.toSseFrame());
|
||||
last = event.getSeq();
|
||||
if(event.isTerminal())
|
||||
{
|
||||
return;
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
|
||||
/*******************************************************************************
|
||||
** Start an SSE response.
|
||||
*******************************************************************************/
|
||||
private static OutputStream startStream(Context context) throws IOException
|
||||
{
|
||||
context.status(200);
|
||||
context.disableCompression();
|
||||
context.res().setContentType("text/event-stream; charset=utf-8");
|
||||
context.res().setHeader("Cache-Control", "no-cache");
|
||||
context.res().setHeader("X-Accel-Buffering", "no");
|
||||
context.res().setHeader("Connection", "keep-alive");
|
||||
OutputStream out = context.res().getOutputStream();
|
||||
out.flush();
|
||||
return (out);
|
||||
}
|
||||
|
||||
|
||||
|
||||
/*******************************************************************************
|
||||
**
|
||||
*******************************************************************************/
|
||||
private static void write(OutputStream out, String frame) throws IOException
|
||||
{
|
||||
out.write(frame.getBytes(StandardCharsets.UTF_8));
|
||||
out.flush();
|
||||
}
|
||||
|
||||
|
||||
|
||||
/*******************************************************************************
|
||||
**
|
||||
*******************************************************************************/
|
||||
private static String ping()
|
||||
{
|
||||
return ("event: " + TurnEvent.PING + "\ndata: {}\n\n");
|
||||
}
|
||||
|
||||
}
|
||||
+1417
File diff suppressed because it is too large.
Load diff
+4
-3
@@ -22,11 +22,12 @@ package com.kingsrook.qbits.assistant.classification;
|
||||
|
||||
|
||||
import java.util.Collection;
|
||||
import com.kingsrook.qqq.backend.core.actions.ai.DataClassification;
|
||||
import com.kingsrook.qqq.backend.core.context.QContext;
|
||||
|
||||
|
||||
/*******************************************************************************
|
||||
** Host seam for table and field classifications; a core metadata adapter can replace the configured source.
|
||||
** Host seam for table and field classifications; the default reads core metadata merged with configuration.
|
||||
*******************************************************************************/
|
||||
public interface ClassificationSource
|
||||
{
|
||||
@@ -63,7 +64,7 @@ public interface ClassificationSource
|
||||
DataClassification result = DataClassification.PUBLIC;
|
||||
for(String field : fields)
|
||||
{
|
||||
result = DataClassification.max(result, field == null || "*".equals(field) ? highest(table) : ofField(table, field));
|
||||
result = Classifications.max(result, field == null || "*".equals(field) ? highest(table) : ofField(table, field));
|
||||
}
|
||||
return (result);
|
||||
}
|
||||
@@ -80,7 +81,7 @@ public interface ClassificationSource
|
||||
{
|
||||
if(!table.startsWith("assistant_"))
|
||||
{
|
||||
result = DataClassification.max(result, highest(table));
|
||||
result = Classifications.max(result, highest(table));
|
||||
}
|
||||
}
|
||||
return (result);
|
||||
|
||||
+20
-19
@@ -1,15 +1,11 @@
|
||||
/*
|
||||
* QQQ - Low-code Application Framework for Engineers.
|
||||
* Copyright (C) 2026. Kingsrook, LLC
|
||||
* 651 N Broad St Ste 205 # 6917 | Middletown DE 19709 | United States
|
||||
* contact@kingsrook.com
|
||||
* https://github.com/Kingsrook/
|
||||
* Copyright 2026 Kingsrook, LLC
|
||||
*
|
||||
* Licensed under the Apache License, Version 2.0 (the "License");
|
||||
* you may not use this file except in compliance with the License.
|
||||
* You may obtain a copy of the License at
|
||||
*
|
||||
* https://www.apache.org/licenses/LICENSE-2.0
|
||||
* http://www.apache.org/licenses/LICENSE-2.0
|
||||
*
|
||||
* Unless required by applicable law or agreed to in writing, software
|
||||
* distributed under the License is distributed on an "AS IS" BASIS,
|
||||
@@ -21,24 +17,31 @@
|
||||
package com.kingsrook.qbits.assistant.classification;
|
||||
|
||||
|
||||
|
||||
import com.kingsrook.qqq.backend.core.actions.ai.DataClassification;
|
||||
|
||||
|
||||
/*******************************************************************************
|
||||
** Stand-in for core DataClassification (QRun-IO/qqq#1142); replace when the qbit builds on an RC that has it.
|
||||
** The assistant's conventions over core's {@link DataClassification}: an
|
||||
** absent classification is PUBLIC, and a stored level this version does not
|
||||
** know is treated as PHI (fail conservative).
|
||||
*******************************************************************************/
|
||||
public enum DataClassification
|
||||
public final class Classifications
|
||||
{
|
||||
PUBLIC, CONFIDENTIAL, PII, PHI;
|
||||
/*******************************************************************************
|
||||
** Utility class.
|
||||
*******************************************************************************/
|
||||
private Classifications()
|
||||
{
|
||||
}
|
||||
|
||||
|
||||
|
||||
/*******************************************************************************
|
||||
** Whether this classification is at least the supplied level; null means PUBLIC.
|
||||
** The level, or PUBLIC when absent.
|
||||
*******************************************************************************/
|
||||
public boolean isAtLeast(DataClassification other)
|
||||
public static DataClassification orPublic(DataClassification classification)
|
||||
{
|
||||
return (ordinal() >= (other == null ? PUBLIC : other).ordinal());
|
||||
return (classification == null ? DataClassification.PUBLIC : classification);
|
||||
}
|
||||
|
||||
|
||||
@@ -48,9 +51,7 @@ public enum DataClassification
|
||||
*******************************************************************************/
|
||||
public static DataClassification max(DataClassification left, DataClassification right)
|
||||
{
|
||||
DataClassification a = left == null ? PUBLIC : left;
|
||||
DataClassification b = right == null ? PUBLIC : right;
|
||||
return (a.isAtLeast(b) ? a : b);
|
||||
return (DataClassification.max(orPublic(left), orPublic(right)));
|
||||
}
|
||||
|
||||
|
||||
@@ -62,15 +63,15 @@ public enum DataClassification
|
||||
{
|
||||
if(value == null)
|
||||
{
|
||||
return (PUBLIC);
|
||||
return (DataClassification.PUBLIC);
|
||||
}
|
||||
try
|
||||
{
|
||||
return (valueOf(value));
|
||||
return (DataClassification.valueOf(value));
|
||||
}
|
||||
catch(IllegalArgumentException e)
|
||||
{
|
||||
return (PHI);
|
||||
return (DataClassification.PHI);
|
||||
}
|
||||
}
|
||||
}
|
||||
+32
-6
@@ -23,12 +23,21 @@ package com.kingsrook.qbits.assistant.classification;
|
||||
|
||||
import java.util.LinkedHashMap;
|
||||
import java.util.Map;
|
||||
import com.kingsrook.qqq.backend.core.actions.ai.AiDataClassifications;
|
||||
import com.kingsrook.qqq.backend.core.actions.ai.AiFieldMetaData;
|
||||
import com.kingsrook.qqq.backend.core.actions.ai.DataClassification;
|
||||
import com.kingsrook.qqq.backend.core.context.QContext;
|
||||
import com.kingsrook.qqq.backend.core.model.metadata.QInstance;
|
||||
import com.kingsrook.qqq.backend.core.model.metadata.tables.QTableMetaData;
|
||||
|
||||
|
||||
/*******************************************************************************
|
||||
** Default classification source for RCs without core classification metadata.
|
||||
** The default classification source: core's AI classification metadata
|
||||
** (AiTableMetaData / AiFieldMetaData, via AiDataClassifications) merged with
|
||||
** the classifications configured on the qbit. A configured value wins when
|
||||
** both are set; a field falls back to its own core classification, then to
|
||||
** its table's; anything unclassified (and the assistant's own tables) is
|
||||
** PUBLIC.
|
||||
*******************************************************************************/
|
||||
public class ConfiguredClassificationSource implements ClassificationSource
|
||||
{
|
||||
@@ -71,7 +80,7 @@ public class ConfiguredClassificationSource implements ClassificationSource
|
||||
@Override
|
||||
public DataClassification ofTable(String table)
|
||||
{
|
||||
return (table == null || table.startsWith("assistant_") ? DataClassification.PUBLIC : DataClassification.max(null, tables.get(table)));
|
||||
return (table == null || table.startsWith("assistant_") ? DataClassification.PUBLIC : Classifications.max(null, tables.get(table) == null ? AiDataClassifications.ofTable(coreTable(table)) : tables.get(table)));
|
||||
}
|
||||
|
||||
|
||||
@@ -87,11 +96,28 @@ public class ConfiguredClassificationSource implements ClassificationSource
|
||||
return (DataClassification.PUBLIC);
|
||||
}
|
||||
DataClassification value = field == null ? null : fields.getOrDefault(table, Map.of()).get(field);
|
||||
if(value == null)
|
||||
{
|
||||
QTableMetaData metadata = coreTable(table);
|
||||
AiFieldMetaData coreField = metadata == null || metadata.getFields() == null || field == null ? null : AiFieldMetaData.of(metadata.getFields().get(field));
|
||||
value = coreField == null ? null : coreField.getClassification();
|
||||
}
|
||||
return (value == null ? ofTable(table) : value);
|
||||
}
|
||||
|
||||
|
||||
|
||||
/*******************************************************************************
|
||||
** The table's core metadata, or null (no instance in context, or unknown).
|
||||
*******************************************************************************/
|
||||
private static QTableMetaData coreTable(String table)
|
||||
{
|
||||
QInstance qInstance = QContext.getQInstance();
|
||||
return (qInstance == null ? null : qInstance.getTable(table));
|
||||
}
|
||||
|
||||
|
||||
|
||||
/*******************************************************************************
|
||||
** Resolve all field names from the current instance, also retaining configured overrides.
|
||||
*******************************************************************************/
|
||||
@@ -108,12 +134,12 @@ public class ConfiguredClassificationSource implements ClassificationSource
|
||||
{
|
||||
for(String field : metadata.getFields().keySet())
|
||||
{
|
||||
result = DataClassification.max(result, ofField(table, field));
|
||||
result = Classifications.max(result, ofField(table, field));
|
||||
}
|
||||
}
|
||||
for(DataClassification value : fields.getOrDefault(table, Map.of()).values())
|
||||
{
|
||||
result = DataClassification.max(result, value);
|
||||
result = Classifications.max(result, value);
|
||||
}
|
||||
return (result);
|
||||
}
|
||||
@@ -129,11 +155,11 @@ public class ConfiguredClassificationSource implements ClassificationSource
|
||||
DataClassification result = ClassificationSource.super.highestAnywhere();
|
||||
for(String table : tables.keySet())
|
||||
{
|
||||
result = DataClassification.max(result, highest(table));
|
||||
result = Classifications.max(result, highest(table));
|
||||
}
|
||||
for(String table : fields.keySet())
|
||||
{
|
||||
result = DataClassification.max(result, highest(table));
|
||||
result = Classifications.max(result, highest(table));
|
||||
}
|
||||
return (result);
|
||||
}
|
||||
|
||||
@@ -0,0 +1,111 @@
|
||||
/*
|
||||
* QQQ - Low-code Application Framework for Engineers.
|
||||
* Copyright (C) 2026. Kingsrook, LLC
|
||||
* 651 N Broad St Ste 205 # 6917 | Middletown DE 19709 | United States
|
||||
* contact@kingsrook.com
|
||||
* https://github.com/Kingsrook/
|
||||
*
|
||||
* Licensed under the Apache License, Version 2.0 (the "License");
|
||||
* you may not use this file except in compliance with the License.
|
||||
* You may obtain a copy of the License at
|
||||
*
|
||||
* https://www.apache.org/licenses/LICENSE-2.0
|
||||
*
|
||||
* Unless required by applicable law or agreed to in writing, software
|
||||
* distributed under the License is distributed on an "AS IS" BASIS,
|
||||
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
|
||||
* See the License for the specific language governing permissions and
|
||||
* limitations under the License.
|
||||
*/
|
||||
|
||||
package com.kingsrook.qbits.assistant.email;
|
||||
|
||||
|
||||
import com.kingsrook.qbits.assistant.AssistantQBitConfig;
|
||||
import com.kingsrook.qqq.backend.core.exceptions.QException;
|
||||
import com.kingsrook.qqq.backend.core.model.metadata.QInstance;
|
||||
|
||||
|
||||
/*******************************************************************************
|
||||
** Email delivery of a scheduled task's result, when the optional qbit-email
|
||||
** is present. This class names no qbit-email type, so it loads without the
|
||||
** jar; the adapter (AssistantEmailSender) is only loaded after the guard passes.
|
||||
**
|
||||
** Hosts can call sendScheduledResult after a run; the scheduled-task runner
|
||||
** does not yet wire email delivery. The gates below apply to every call:
|
||||
** the task opted in, the host approved EXTERNAL delivery
|
||||
** (AssistantQBitConfig.getEmailExternalApproved, until the approval rule
|
||||
** exists), and there is a recipient address.
|
||||
*******************************************************************************/
|
||||
public final class AssistantEmail
|
||||
{
|
||||
/*******************************************************************************
|
||||
** Utility class.
|
||||
*******************************************************************************/
|
||||
private AssistantEmail()
|
||||
{
|
||||
}
|
||||
|
||||
|
||||
|
||||
/*******************************************************************************
|
||||
** Whether qbit-email is on the classpath and produced in this instance.
|
||||
*******************************************************************************/
|
||||
public static boolean isAvailable(QInstance qInstance)
|
||||
{
|
||||
try
|
||||
{
|
||||
Class.forName("com.kingsrook.qbits.email.api.EmailApi");
|
||||
}
|
||||
catch(ClassNotFoundException | LinkageError e)
|
||||
{
|
||||
return (false);
|
||||
}
|
||||
return (AssistantEmailSender.isInstalled(qInstance));
|
||||
}
|
||||
|
||||
|
||||
|
||||
/*******************************************************************************
|
||||
** Email a finished scheduled run to its owner, if the task opted in and
|
||||
** every gate allows it. A missing email qbit is not an error; the status
|
||||
** says what happened.
|
||||
*******************************************************************************/
|
||||
public static ScheduledEmailStatus sendScheduledResult(QInstance qInstance, AssistantQBitConfig config, ScheduledResultNotice notice) throws QException
|
||||
{
|
||||
if(notice == null || !notice.emailResult())
|
||||
{
|
||||
return (ScheduledEmailStatus.NOT_REQUESTED);
|
||||
}
|
||||
if(!isAvailable(qInstance))
|
||||
{
|
||||
return (ScheduledEmailStatus.NOT_AVAILABLE);
|
||||
}
|
||||
if(!Boolean.TRUE.equals(config.getEmailExternalApproved()))
|
||||
{
|
||||
return (ScheduledEmailStatus.NOT_APPROVED);
|
||||
}
|
||||
String recipient = recipient(config, notice.ownerUserId());
|
||||
if(recipient == null)
|
||||
{
|
||||
return (ScheduledEmailStatus.NO_RECIPIENT);
|
||||
}
|
||||
return (AssistantEmailSender.send(notice, recipient));
|
||||
}
|
||||
|
||||
|
||||
|
||||
/*******************************************************************************
|
||||
** The owner's address: the host's resolver, else the owner id when it is
|
||||
** itself an address. Null when there is none.
|
||||
*******************************************************************************/
|
||||
static String recipient(AssistantQBitConfig config, String ownerUserId)
|
||||
{
|
||||
if(ownerUserId == null || ownerUserId.isBlank())
|
||||
{
|
||||
return (null);
|
||||
}
|
||||
String address = config.getEmailRecipientResolver() != null ? config.getEmailRecipientResolver().apply(ownerUserId) : (ownerUserId.contains("@") ? ownerUserId : null);
|
||||
return (address == null || address.isBlank() ? null : address.trim());
|
||||
}
|
||||
}
|
||||
+156
@@ -0,0 +1,156 @@
|
||||
/*
|
||||
* QQQ - Low-code Application Framework for Engineers.
|
||||
* Copyright (C) 2026. Kingsrook, LLC
|
||||
* 651 N Broad St Ste 205 # 6917 | Middletown DE 19709 | United States
|
||||
* contact@kingsrook.com
|
||||
* https://github.com/Kingsrook/
|
||||
*
|
||||
* Licensed under the Apache License, Version 2.0 (the "License");
|
||||
* you may not use this file except in compliance with the License.
|
||||
* You may obtain a copy of the License at
|
||||
*
|
||||
* https://www.apache.org/licenses/LICENSE-2.0
|
||||
*
|
||||
* Unless required by applicable law or agreed to in writing, software
|
||||
* distributed under the License is distributed on an "AS IS" BASIS,
|
||||
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
|
||||
* See the License for the specific language governing permissions and
|
||||
* limitations under the License.
|
||||
*/
|
||||
|
||||
package com.kingsrook.qbits.assistant.email;
|
||||
|
||||
|
||||
import java.io.Serializable;
|
||||
import java.util.LinkedHashMap;
|
||||
import java.util.Map;
|
||||
import com.kingsrook.qbits.email.api.EmailApi;
|
||||
import com.kingsrook.qbits.email.api.EmailApiCategory;
|
||||
import com.kingsrook.qbits.email.api.EmailApiRequest;
|
||||
import com.kingsrook.qbits.email.api.EmailApiResult;
|
||||
import com.kingsrook.qbits.email.api.EmailApiTemplate;
|
||||
import com.kingsrook.qqq.backend.core.actions.ai.DataClassification;
|
||||
import com.kingsrook.qqq.backend.core.exceptions.QException;
|
||||
import com.kingsrook.qqq.backend.core.model.metadata.QInstance;
|
||||
|
||||
|
||||
/*******************************************************************************
|
||||
** The only class that touches qbit-email. Registers the scheduled-result
|
||||
** template on first use (never overwriting edits) and queues one message per
|
||||
** recipient. Addresses, summaries and bodies are never logged.
|
||||
*******************************************************************************/
|
||||
final class AssistantEmailSender
|
||||
{
|
||||
static final String TEMPLATE_NAME = "assistant_scheduled_result";
|
||||
static final String SECURE_TEMPLATE = "email_secure_message";
|
||||
static final String SENDER_QBIT = "assistant";
|
||||
static final String SENDER_PROCESS = "assistantScheduledTask";
|
||||
|
||||
private static final int MAX_SUMMARY = 280;
|
||||
|
||||
|
||||
|
||||
/*******************************************************************************
|
||||
** Utility class.
|
||||
*******************************************************************************/
|
||||
private AssistantEmailSender()
|
||||
{
|
||||
}
|
||||
|
||||
|
||||
|
||||
/*******************************************************************************
|
||||
** Whether the email qbit is produced in this instance.
|
||||
*******************************************************************************/
|
||||
static boolean isInstalled(QInstance qInstance)
|
||||
{
|
||||
return (EmailApi.isInstalled(qInstance));
|
||||
}
|
||||
|
||||
|
||||
|
||||
/*******************************************************************************
|
||||
** Queue one message to one recipient. A result classified above PUBLIC
|
||||
** sends only the link, with the secure-message pattern.
|
||||
*******************************************************************************/
|
||||
static ScheduledEmailStatus send(ScheduledResultNotice notice, String recipient) throws QException
|
||||
{
|
||||
boolean linkOnly = notice.classification() != null && notice.classification().isAtLeast(DataClassification.CONFIDENTIAL);
|
||||
|
||||
EmailApiRequest request = new EmailApiRequest().withTo(recipient)
|
||||
.withIdempotencyKey("assistant:scheduled:" + notice.runId())
|
||||
.withLinkedRecord(notice.runTable(), notice.runId())
|
||||
.withSender(SENDER_QBIT, SENDER_PROCESS);
|
||||
|
||||
Map<String, Serializable> variables = new LinkedHashMap<>();
|
||||
variables.put("link", notice.link());
|
||||
if(linkOnly)
|
||||
{
|
||||
request.withTemplateName(SECURE_TEMPLATE);
|
||||
}
|
||||
else
|
||||
{
|
||||
ensureTemplate();
|
||||
request.withTemplateName(TEMPLATE_NAME);
|
||||
variables.put("taskName", notice.taskName());
|
||||
variables.put("runTime", notice.runTime() == null ? null : notice.runTime().toString());
|
||||
variables.put("summary", summary(notice.summary()));
|
||||
}
|
||||
request.withVariables(variables);
|
||||
|
||||
return (map(EmailApi.send(request)));
|
||||
}
|
||||
|
||||
|
||||
|
||||
/*******************************************************************************
|
||||
** One line, cut short; the full model output never goes in an email.
|
||||
*******************************************************************************/
|
||||
static String summary(String value)
|
||||
{
|
||||
if(value == null)
|
||||
{
|
||||
return (null);
|
||||
}
|
||||
String oneLine = value.replaceAll("\\s+", " ").trim();
|
||||
return (oneLine.length() <= MAX_SUMMARY ? oneLine : oneLine.substring(0, MAX_SUMMARY - 3) + "...");
|
||||
}
|
||||
|
||||
|
||||
|
||||
/*******************************************************************************
|
||||
** Outbox result to the qbit's own vocabulary.
|
||||
*******************************************************************************/
|
||||
private static ScheduledEmailStatus map(EmailApiResult result)
|
||||
{
|
||||
return (switch(result.status())
|
||||
{
|
||||
case QUEUED -> ScheduledEmailStatus.QUEUED;
|
||||
case DUPLICATE -> ScheduledEmailStatus.DUPLICATE;
|
||||
case SUPPRESSED -> ScheduledEmailStatus.SUPPRESSED;
|
||||
case REFUSED -> ScheduledEmailStatus.REFUSED;
|
||||
});
|
||||
}
|
||||
|
||||
|
||||
|
||||
/*******************************************************************************
|
||||
** Register the NOTIFICATION template once; an existing template is left alone.
|
||||
*******************************************************************************/
|
||||
static void ensureTemplate() throws QException
|
||||
{
|
||||
EmailApi.ensureTemplate(new EmailApiTemplate()
|
||||
.withName(TEMPLATE_NAME)
|
||||
.withLabel("Assistant scheduled task result")
|
||||
.withCategory(EmailApiCategory.NOTIFICATION)
|
||||
.withKind("MARKDOWN")
|
||||
.withOwnerQbit(SENDER_QBIT)
|
||||
.withSubject("Assistant task result: {{taskName}}")
|
||||
.withBody("Your scheduled assistant task **{{taskName}}** finished at {{runTime}}.\n\n{{summary}}\n\n[Open the run]({{link}}){.button}")
|
||||
.withVariable("taskName", "Task name", "STRING", true, "CONFIDENTIAL")
|
||||
.withVariable("runTime", "Run time", "DATE_TIME", true, "PUBLIC")
|
||||
.withVariable("summary", "Short summary", "STRING", false, "CONFIDENTIAL")
|
||||
.withVariable("link", "Link to the run", "URL", true, "PUBLIC")
|
||||
.withSampleVariables("{\"taskName\":\"Weekly review\",\"runTime\":\"2026-10-12T09:00:00Z\",\"summary\":\"Three items need attention.\",\"link\":\"https://app.example.com/app/assistant_run/1\"}"));
|
||||
}
|
||||
}
|
||||
+38
@@ -0,0 +1,38 @@
|
||||
/*
|
||||
* QQQ - Low-code Application Framework for Engineers.
|
||||
* Copyright (C) 2026. Kingsrook, LLC
|
||||
* 651 N Broad St Ste 205 # 6917 | Middletown DE 19709 | United States
|
||||
* contact@kingsrook.com
|
||||
* https://github.com/Kingsrook/
|
||||
*
|
||||
* Licensed under the Apache License, Version 2.0 (the "License");
|
||||
* you may not use this file except in compliance with the License.
|
||||
* You may obtain a copy of the License at
|
||||
*
|
||||
* https://www.apache.org/licenses/LICENSE-2.0
|
||||
*
|
||||
* Unless required by applicable law or agreed to in writing, software
|
||||
* distributed under the License is distributed on an "AS IS" BASIS,
|
||||
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
|
||||
* See the License for the specific language governing permissions and
|
||||
* limitations under the License.
|
||||
*/
|
||||
|
||||
package com.kingsrook.qbits.assistant.email;
|
||||
|
||||
|
||||
/*******************************************************************************
|
||||
** Outcome of trying to email a scheduled task's result. The first four mean
|
||||
** nothing was queued and why; the rest mirror the outbox result.
|
||||
*******************************************************************************/
|
||||
public enum ScheduledEmailStatus
|
||||
{
|
||||
NOT_REQUESTED,
|
||||
NOT_AVAILABLE,
|
||||
NOT_APPROVED,
|
||||
NO_RECIPIENT,
|
||||
QUEUED,
|
||||
DUPLICATE,
|
||||
SUPPRESSED,
|
||||
REFUSED
|
||||
}
|
||||
+46
@@ -0,0 +1,46 @@
|
||||
/*
|
||||
* QQQ - Low-code Application Framework for Engineers.
|
||||
* Copyright (C) 2026. Kingsrook, LLC
|
||||
* 651 N Broad St Ste 205 # 6917 | Middletown DE 19709 | United States
|
||||
* contact@kingsrook.com
|
||||
* https://github.com/Kingsrook/
|
||||
*
|
||||
* Licensed under the Apache License, Version 2.0 (the "License");
|
||||
* you may not use this file except in compliance with the License.
|
||||
* You may obtain a copy of the License at
|
||||
*
|
||||
* https://www.apache.org/licenses/LICENSE-2.0
|
||||
*
|
||||
* Unless required by applicable law or agreed to in writing, software
|
||||
* distributed under the License is distributed on an "AS IS" BASIS,
|
||||
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
|
||||
* See the License for the specific language governing permissions and
|
||||
* limitations under the License.
|
||||
*/
|
||||
|
||||
package com.kingsrook.qbits.assistant.email;
|
||||
|
||||
|
||||
import java.time.Instant;
|
||||
import com.kingsrook.qqq.backend.core.actions.ai.DataClassification;
|
||||
|
||||
|
||||
/*******************************************************************************
|
||||
** What the scheduled-task runner knows about one finished run, for the
|
||||
** result email. The full model output is deliberately not part of it: only a
|
||||
** short summary, and only when the result is classified PUBLIC.
|
||||
**
|
||||
** @param runTable the table holding the run record (the email's linked record)
|
||||
** @param runId the run's id (also the idempotency key)
|
||||
** @param taskName the scheduled task's name
|
||||
** @param runTime when the run finished
|
||||
** @param summary a short summary (cut to 280 characters; never the model output)
|
||||
** @param classification the result's classification; null means PUBLIC
|
||||
** @param ownerUserId the task owner's user id (the way the qbit identifies users)
|
||||
** @param emailResult whether the task opted in to email delivery
|
||||
** @param link absolute link to the run record in the app
|
||||
*******************************************************************************/
|
||||
public record ScheduledResultNotice(String runTable, Object runId, String taskName, Instant runTime, String summary, DataClassification classification,
|
||||
String ownerUserId, boolean emailResult, String link)
|
||||
{
|
||||
}
|
||||
+42
-11
@@ -23,14 +23,17 @@ import java.util.List;
|
||||
import com.kingsrook.qbits.assistant.AssistantRuntime;
|
||||
import com.kingsrook.qbits.assistant.model.AssistantModel;
|
||||
import com.kingsrook.qbits.assistant.model.AssistantProvider;
|
||||
import com.kingsrook.qbits.assistant.provider.AssistantProviderType;
|
||||
import com.kingsrook.qbits.assistant.provider.HealthResult;
|
||||
import com.kingsrook.qbits.assistant.provider.ModelMessage;
|
||||
import com.kingsrook.qbits.assistant.provider.ModelProviderException;
|
||||
import com.kingsrook.qbits.assistant.provider.ModelRequest;
|
||||
import com.kingsrook.qbits.assistant.provider.ModelResponse;
|
||||
import com.kingsrook.qbits.assistant.provider.RegistryModelProvider;
|
||||
import com.kingsrook.qbits.assistant.provider.StreamHandle;
|
||||
import com.kingsrook.qbits.assistant.rag.EmbeddingService;
|
||||
import com.kingsrook.qbits.assistant.spi.AssistantProviderType;
|
||||
import com.kingsrook.qbits.assistant.spi.HealthResult;
|
||||
import com.kingsrook.qbits.assistant.spi.ModelMessage;
|
||||
import com.kingsrook.qbits.assistant.spi.ModelPricing;
|
||||
import com.kingsrook.qbits.assistant.spi.ModelProviderException;
|
||||
import com.kingsrook.qbits.assistant.spi.ModelRequest;
|
||||
import com.kingsrook.qbits.assistant.spi.ModelResponse;
|
||||
import com.kingsrook.qbits.assistant.spi.StreamHandle;
|
||||
import com.kingsrook.qqq.backend.core.actions.ai.DataClassification;
|
||||
import com.kingsrook.qqq.backend.core.exceptions.QException;
|
||||
import com.kingsrook.qqq.backend.core.model.data.QRecord;
|
||||
|
||||
@@ -209,10 +212,17 @@ public final class ConnectionTest
|
||||
{
|
||||
throw (new ProviderService.ProviderSetupException("The model's provider no longer exists."));
|
||||
}
|
||||
AssistantProviderType type = runtime.getConfig().getProviderTypes().get(row.getProviderType());
|
||||
var settings = runtime.getProviderService().settings(row);
|
||||
var provider = new RegistryModelProvider(type.create(settings), model);
|
||||
result = call(runtime, new ProviderService.Active(row, row.getProviderType(), model.getModelId(), provider), userId);
|
||||
if(!model.isChat())
|
||||
{
|
||||
result = testEmbedding(runtime, model);
|
||||
}
|
||||
else
|
||||
{
|
||||
AssistantProviderType type = runtime.getConfig().getProviderTypes().get(row.getProviderType());
|
||||
var settings = runtime.getProviderService().settings(row);
|
||||
var provider = new RegistryModelProvider(type.create(settings), model);
|
||||
result = call(runtime, new ProviderService.Active(row, row.getProviderType(), model.getModelId(), provider), userId);
|
||||
}
|
||||
}
|
||||
catch(ProviderService.ProviderSetupException e)
|
||||
{
|
||||
@@ -226,6 +236,27 @@ public final class ConnectionTest
|
||||
|
||||
|
||||
|
||||
/*******************************************************************************
|
||||
** An embedding model is tested with embeddings, never a chat completion.
|
||||
** The normal embedding budget, eligibility and usage rules still apply.
|
||||
*******************************************************************************/
|
||||
private static Result testEmbedding(AssistantRuntime runtime, AssistantModel model)
|
||||
{
|
||||
Long started = System.nanoTime();
|
||||
try
|
||||
{
|
||||
new EmbeddingService(runtime).embed(model.getId(), List.of("Connection test."),
|
||||
DataClassification.PUBLIC, "", null, null);
|
||||
return (new Result(STATUS_OK, (int) ((System.nanoTime() - started) / 1_000_000), model.getModelId(), null));
|
||||
}
|
||||
catch(QException e)
|
||||
{
|
||||
return (new Result(STATUS_ERROR, null, model.getModelId(), e.getMessage()));
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
|
||||
|
||||
/*******************************************************************************
|
||||
** Map the provider error category.
|
||||
|
||||
+93
-7
@@ -28,16 +28,19 @@ import java.util.Set;
|
||||
import java.util.TreeMap;
|
||||
import com.kingsrook.qbits.assistant.AssistantQBitConfig;
|
||||
import com.kingsrook.qbits.assistant.model.AssistantMessage;
|
||||
import com.kingsrook.qbits.assistant.provider.CacheHint;
|
||||
import com.kingsrook.qbits.assistant.provider.ModelMessage;
|
||||
import com.kingsrook.qbits.assistant.provider.ModelPart;
|
||||
import com.kingsrook.qbits.assistant.provider.ModelRequest;
|
||||
import com.kingsrook.qbits.assistant.provider.ModelToolDefinition;
|
||||
import com.kingsrook.qbits.assistant.provider.SystemBlock;
|
||||
import com.kingsrook.qbits.assistant.spi.CacheHint;
|
||||
import com.kingsrook.qbits.assistant.spi.ModelMessage;
|
||||
import com.kingsrook.qbits.assistant.spi.ModelPart;
|
||||
import com.kingsrook.qbits.assistant.spi.ModelRequest;
|
||||
import com.kingsrook.qbits.assistant.spi.ModelToolDefinition;
|
||||
import com.kingsrook.qbits.assistant.spi.SystemBlock;
|
||||
import com.kingsrook.qbits.assistant.tools.KnowledgeTool;
|
||||
import com.kingsrook.qbits.assistant.tools.PresentResultsTool;
|
||||
import com.kingsrook.qbits.assistant.tools.UiApiToolbox;
|
||||
import com.kingsrook.qbits.assistant.tools.bulkload.BulkLoadTools;
|
||||
import com.kingsrook.qqq.backend.core.actions.ai.AiToolDefinition;
|
||||
import com.kingsrook.qqq.backend.core.actions.ai.AiToolKernel;
|
||||
import com.kingsrook.qqq.backend.core.context.QContext;
|
||||
import com.kingsrook.qqq.backend.core.model.session.QSession;
|
||||
import com.kingsrook.qqq.backend.core.utils.JsonUtils;
|
||||
import com.kingsrook.qqq.backend.core.utils.StringUtils;
|
||||
@@ -64,11 +67,14 @@ public class ContextBuilder
|
||||
|
||||
public static final int MAX_CONTEXT_CHARS = 512;
|
||||
public static final int MAX_SELECTED_IDS = 100;
|
||||
public static final int MAX_ATTACHMENTS = 5;
|
||||
|
||||
private final AssistantQBitConfig config;
|
||||
private final AiToolKernel kernel;
|
||||
private final UiApiToolbox toolbox;
|
||||
private volatile String appDigest;
|
||||
private KnowledgeTool knowledgeTool;
|
||||
private BulkLoadTools bulkLoadTools;
|
||||
|
||||
|
||||
|
||||
@@ -100,6 +106,16 @@ public class ContextBuilder
|
||||
** kernel's navigate and search_help.
|
||||
*******************************************************************************/
|
||||
public List<ModelToolDefinition> tools(PolicyService.ToolPolicy policy)
|
||||
{
|
||||
return (tools(policy, null));
|
||||
}
|
||||
|
||||
|
||||
|
||||
/*******************************************************************************
|
||||
** Attribute tool-discovery requests to the turn that needs them.
|
||||
*******************************************************************************/
|
||||
private List<ModelToolDefinition> tools(PolicyService.ToolPolicy policy, String turnId)
|
||||
{
|
||||
Map<String, ModelToolDefinition> byName = new TreeMap<>();
|
||||
for(ModelToolDefinition definition : toolbox.definitions(policy, toolbox.anyWritableTable()))
|
||||
@@ -117,7 +133,18 @@ public class ContextBuilder
|
||||
.withStrict(isStrict(definition.getName(), !Boolean.FALSE.equals(definition.getStrict()))));
|
||||
}
|
||||
}
|
||||
if(knowledgeTool != null && knowledgeTool.offered(policy, QContext.getQSession(), turnId))
|
||||
{
|
||||
byName.put(KnowledgeTool.NAME, knowledgeTool.definition());
|
||||
}
|
||||
byName.put(PresentResultsTool.NAME, PresentResultsTool.definition(isStrict(PresentResultsTool.NAME, true)));
|
||||
if(bulkLoadTools != null && bulkLoadTools.offered())
|
||||
{
|
||||
for(ModelToolDefinition definition : bulkLoadTools.definitions(policy, toolbox.anyWritableTable()))
|
||||
{
|
||||
byName.put(definition.getName(), definition);
|
||||
}
|
||||
}
|
||||
return (new ArrayList<>(byName.values()));
|
||||
}
|
||||
|
||||
@@ -199,12 +226,23 @@ public class ContextBuilder
|
||||
*******************************************************************************/
|
||||
public ModelRequest build(QSession session, String model, String effort, List<AssistantMessage> history, String userText, Map<String, Object> pageContext, PolicyService.ToolPolicy toolPolicy,
|
||||
String profileInstructions)
|
||||
{
|
||||
return (build(session, model, effort, history, userText, pageContext, toolPolicy, profileInstructions, null));
|
||||
}
|
||||
|
||||
|
||||
|
||||
/*******************************************************************************
|
||||
** Include the turn in any UI API calls needed to discover available tools.
|
||||
*******************************************************************************/
|
||||
public ModelRequest build(QSession session, String model, String effort, List<AssistantMessage> history, String userText, Map<String, Object> pageContext, PolicyService.ToolPolicy toolPolicy,
|
||||
String profileInstructions, String turnId)
|
||||
{
|
||||
ModelRequest request = new ModelRequest()
|
||||
.withModel(model)
|
||||
.withEffort(effort)
|
||||
.withMaxTokens(config.getModels().getMainMaxOutputTokens())
|
||||
.withTools(tools(toolPolicy));
|
||||
.withTools(tools(toolPolicy, turnId));
|
||||
|
||||
request.getSystem().add(new SystemBlock(SystemPrompt.staticBlock(appDigest()), CacheHint.LONG));
|
||||
request.getSystem().add(new SystemBlock(userBlock(session) + (StringUtils.hasContent(profileInstructions) ? "\n" + profileInstructions : ""), CacheHint.SHORT));
|
||||
@@ -345,6 +383,32 @@ public class ContextBuilder
|
||||
}
|
||||
}
|
||||
|
||||
////////////////////////////////////////////////////////////////////
|
||||
// files the user attached in the panel (already uploaded through //
|
||||
// the UI API as the user): only their opaque refs and names //
|
||||
////////////////////////////////////////////////////////////////////
|
||||
if(raw.get("attachments") instanceof List<?> attachments)
|
||||
{
|
||||
List<Map<String, Object>> kept = new ArrayList<>();
|
||||
for(Object attachment : attachments)
|
||||
{
|
||||
if(attachment instanceof Map<?, ?> a && scalar(a.get("uploadRef")) != null && kept.size() < MAX_ATTACHMENTS)
|
||||
{
|
||||
Map<String, Object> one = new LinkedHashMap<>();
|
||||
one.put("uploadRef", scalar(a.get("uploadRef")));
|
||||
if(scalar(a.get("fileName")) != null)
|
||||
{
|
||||
one.put("fileName", scalar(a.get("fileName")));
|
||||
}
|
||||
kept.add(one);
|
||||
}
|
||||
}
|
||||
if(!kept.isEmpty())
|
||||
{
|
||||
clean.put("attachments", kept);
|
||||
}
|
||||
}
|
||||
|
||||
if(JsonUtils.toJson(clean).length() > 4000)
|
||||
{
|
||||
clean.remove("filter");
|
||||
@@ -372,4 +436,26 @@ public class ContextBuilder
|
||||
return (null);
|
||||
}
|
||||
|
||||
|
||||
|
||||
/*******************************************************************************
|
||||
** Additive optional tool hook; UI API toolbox stays independently maintained.
|
||||
*******************************************************************************/
|
||||
public ContextBuilder withKnowledgeTool(KnowledgeTool knowledgeTool)
|
||||
{
|
||||
this.knowledgeTool = knowledgeTool;
|
||||
return (this);
|
||||
}
|
||||
|
||||
|
||||
|
||||
/*******************************************************************************
|
||||
** Fluent setter for the bulk-load tools.
|
||||
*******************************************************************************/
|
||||
public ContextBuilder withBulkLoadTools(BulkLoadTools bulkLoadTools)
|
||||
{
|
||||
this.bulkLoadTools = bulkLoadTools;
|
||||
return (this);
|
||||
}
|
||||
|
||||
}
|
||||
+6
-6
@@ -27,15 +27,15 @@ import java.util.concurrent.atomic.AtomicBoolean;
|
||||
import java.util.function.Consumer;
|
||||
import java.util.function.Supplier;
|
||||
import com.kingsrook.qbits.assistant.AssistantRuntime;
|
||||
import com.kingsrook.qbits.assistant.classification.DataClassification;
|
||||
import com.kingsrook.qbits.assistant.model.AssistantModel;
|
||||
import com.kingsrook.qbits.assistant.model.AssistantProvider;
|
||||
import com.kingsrook.qbits.assistant.model.AssistantTurn;
|
||||
import com.kingsrook.qbits.assistant.provider.ModelEventListener;
|
||||
import com.kingsrook.qbits.assistant.provider.ModelMessage;
|
||||
import com.kingsrook.qbits.assistant.provider.ModelProviderException;
|
||||
import com.kingsrook.qbits.assistant.provider.ModelRequest;
|
||||
import com.kingsrook.qbits.assistant.provider.ModelResponse;
|
||||
import com.kingsrook.qbits.assistant.spi.ModelEventListener;
|
||||
import com.kingsrook.qbits.assistant.spi.ModelMessage;
|
||||
import com.kingsrook.qbits.assistant.spi.ModelProviderException;
|
||||
import com.kingsrook.qbits.assistant.spi.ModelRequest;
|
||||
import com.kingsrook.qbits.assistant.spi.ModelResponse;
|
||||
import com.kingsrook.qqq.backend.core.actions.ai.DataClassification;
|
||||
import com.kingsrook.qqq.backend.core.exceptions.QException;
|
||||
|
||||
|
||||
|
||||
+35
-5
@@ -24,11 +24,11 @@ import java.util.Set;
|
||||
import com.kingsrook.qbits.assistant.AssistantRuntime;
|
||||
import com.kingsrook.qbits.assistant.model.AssistantModel;
|
||||
import com.kingsrook.qbits.assistant.model.AssistantProvider;
|
||||
import com.kingsrook.qbits.assistant.provider.AssistantProviderType;
|
||||
import com.kingsrook.qbits.assistant.provider.DiscoveredModel;
|
||||
import com.kingsrook.qbits.assistant.provider.ModelCapabilities;
|
||||
import com.kingsrook.qbits.assistant.provider.ModelProviderException;
|
||||
import com.kingsrook.qbits.assistant.provider.ProviderSettings;
|
||||
import com.kingsrook.qbits.assistant.spi.AssistantProviderType;
|
||||
import com.kingsrook.qbits.assistant.spi.DiscoveredModel;
|
||||
import com.kingsrook.qbits.assistant.spi.ModelCapabilities;
|
||||
import com.kingsrook.qbits.assistant.spi.ModelProviderException;
|
||||
import com.kingsrook.qbits.assistant.spi.ProviderSettings;
|
||||
import com.kingsrook.qqq.backend.core.exceptions.QException;
|
||||
import com.kingsrook.qqq.backend.core.model.data.QRecord;
|
||||
|
||||
@@ -85,6 +85,7 @@ public final class ModelDiscovery
|
||||
}
|
||||
ModelCapabilities caps = provider.getCapabilities(model.modelId());
|
||||
runtime.getStore().insert(new AssistantModel().withProviderId(row.getId()).withModelId(model.modelId())
|
||||
.withModelKind(embedding(model.modelId()) ? "EMBEDDING" : "CHAT").withEmbeddingDimensions(dimensions(model.modelId()))
|
||||
.withDisplayName(model.displayName()).withEnabled(local || discovered.size() <= 20)
|
||||
.withSource("DISCOVERED").withDiscoveredAt(runtime.getClock().instant())
|
||||
.withSupportsTools(caps.getTools()).withSupportsVision(caps.getVision()).withSupportsStreaming(caps.getStreaming())
|
||||
@@ -115,4 +116,33 @@ public final class ModelDiscovery
|
||||
return (result);
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
/*******************************************************************************
|
||||
** Discovery is a suggestion; an administrator can correct the kind.
|
||||
*******************************************************************************/
|
||||
public static Boolean embedding(String id)
|
||||
{
|
||||
String lower = id.toLowerCase(java.util.Locale.ROOT);
|
||||
return (List.of("embed", "bge", "e5", "gte", "nomic").stream().anyMatch(lower::contains));
|
||||
}
|
||||
|
||||
|
||||
|
||||
/*******************************************************************************
|
||||
** Known local defaults; other models must declare their dimensions.
|
||||
*******************************************************************************/
|
||||
private static Integer dimensions(String id)
|
||||
{
|
||||
if(id.contains("bge-m3"))
|
||||
{
|
||||
return (1024);
|
||||
}
|
||||
if(id.contains("nomic-embed-text"))
|
||||
{
|
||||
return (768);
|
||||
}
|
||||
return (null);
|
||||
}
|
||||
|
||||
}
|
||||
+16
-13
@@ -17,32 +17,33 @@
|
||||
package com.kingsrook.qbits.assistant.engine;
|
||||
|
||||
|
||||
import java.util.stream.Collectors;
|
||||
import java.util.Objects;
|
||||
import com.kingsrook.qbits.assistant.model.AssistantProvider;
|
||||
import java.time.Duration;
|
||||
import java.time.Instant;
|
||||
import java.util.List;
|
||||
import java.util.Locale;
|
||||
import java.util.Map;
|
||||
import java.util.Objects;
|
||||
import java.util.Set;
|
||||
import java.util.concurrent.Semaphore;
|
||||
import java.util.function.Consumer;
|
||||
import java.util.regex.Pattern;
|
||||
import java.util.stream.Collectors;
|
||||
import com.kingsrook.qbits.assistant.AssistantRuntime;
|
||||
import com.kingsrook.qbits.assistant.classification.DataClassification;
|
||||
import com.kingsrook.qbits.assistant.model.AssistantConversation;
|
||||
import com.kingsrook.qbits.assistant.model.AssistantPendingAction;
|
||||
import com.kingsrook.qbits.assistant.model.AssistantProfile;
|
||||
import com.kingsrook.qbits.assistant.model.AssistantProvider;
|
||||
import com.kingsrook.qbits.assistant.model.AssistantTurn;
|
||||
import com.kingsrook.qbits.assistant.provider.CacheHint;
|
||||
import com.kingsrook.qbits.assistant.provider.ModelMessage;
|
||||
import com.kingsrook.qbits.assistant.provider.ModelProviderException;
|
||||
import com.kingsrook.qbits.assistant.provider.ModelRequest;
|
||||
import com.kingsrook.qbits.assistant.provider.ModelResponse;
|
||||
import com.kingsrook.qbits.assistant.provider.ModelUsage;
|
||||
import com.kingsrook.qbits.assistant.provider.StreamHandle;
|
||||
import com.kingsrook.qbits.assistant.provider.SystemBlock;
|
||||
import com.kingsrook.qbits.assistant.scheduled.ScheduledTurn;
|
||||
import com.kingsrook.qbits.assistant.spi.CacheHint;
|
||||
import com.kingsrook.qbits.assistant.spi.ModelMessage;
|
||||
import com.kingsrook.qbits.assistant.spi.ModelProviderException;
|
||||
import com.kingsrook.qbits.assistant.spi.ModelRequest;
|
||||
import com.kingsrook.qbits.assistant.spi.ModelResponse;
|
||||
import com.kingsrook.qbits.assistant.spi.ModelUsage;
|
||||
import com.kingsrook.qbits.assistant.spi.StreamHandle;
|
||||
import com.kingsrook.qbits.assistant.spi.SystemBlock;
|
||||
import com.kingsrook.qqq.backend.core.actions.ai.DataClassification;
|
||||
import com.kingsrook.qqq.backend.core.exceptions.QException;
|
||||
import com.kingsrook.qqq.backend.core.model.actions.tables.query.QCriteriaOperator;
|
||||
import com.kingsrook.qqq.backend.core.model.actions.tables.query.QFilterOrderBy;
|
||||
@@ -116,7 +117,9 @@ public class ModelRouter
|
||||
public Route route(QSession session, AssistantConversation conversation, AssistantTurn turn, String question, Map<String, Object> pageContext,
|
||||
PolicyService.EffectivePolicy policy, TurnClassification classification, RunningTurn running, Instant deadline, Consumer<String> notice) throws QException, InterruptedException
|
||||
{
|
||||
AssistantProfile profile = runtime.getProfileService().pick(session, runtime.appNameFor(pageContext));
|
||||
var scheduled = runtime.getScheduledTurn().task(conversation.getId());
|
||||
ScheduledTurn.checkCost(scheduled, 0L);
|
||||
AssistantProfile profile = runtime.getProfileService().pick(session, runtime.appNameFor(pageContext), scheduled == null ? null : scheduled.getProfileId());
|
||||
String mode = profile == null || profile.getRoutingMode() == null ? "OFF" : profile.getRoutingMode();
|
||||
Boolean escalation = profile == null && Boolean.TRUE.equals(runtime.getConfig().getModels().getEscalationEnabled());
|
||||
String decision = "OFF";
|
||||
|
||||
+1
-1
@@ -22,8 +22,8 @@ package com.kingsrook.qbits.assistant.engine;
|
||||
|
||||
|
||||
import java.util.Optional;
|
||||
import com.kingsrook.qbits.assistant.classification.DataClassification;
|
||||
import com.kingsrook.qbits.assistant.model.AssistantProvider;
|
||||
import com.kingsrook.qqq.backend.core.actions.ai.DataClassification;
|
||||
|
||||
|
||||
/*******************************************************************************
|
||||
|
||||
+27
-1
@@ -107,7 +107,17 @@ public class ProfileService
|
||||
*******************************************************************************/
|
||||
public Persona persona(QSession session, String appName)
|
||||
{
|
||||
AssistantProfile profile = pick(session, appName);
|
||||
return (persona(session, appName, null));
|
||||
}
|
||||
|
||||
|
||||
|
||||
/*******************************************************************************
|
||||
** An administrator-selected scheduled profile still respects role scope.
|
||||
*******************************************************************************/
|
||||
public Persona persona(QSession session, String appName, Integer profileId)
|
||||
{
|
||||
AssistantProfile profile = pick(session, appName, profileId);
|
||||
if(profile == null)
|
||||
{
|
||||
return (new Persona(null, DEFAULT_DISPLAY_NAME, DEFAULT_ICON, null, null, List.of()));
|
||||
@@ -217,6 +227,22 @@ public class ProfileService
|
||||
*******************************************************************************/
|
||||
public AssistantProfile pick(QSession session, String appName)
|
||||
{
|
||||
return (pick(session, appName, null));
|
||||
}
|
||||
|
||||
|
||||
|
||||
/*******************************************************************************
|
||||
** Explicit profiles supply instructions and routing, never permissions.
|
||||
*******************************************************************************/
|
||||
public AssistantProfile pick(QSession session, String appName, Integer profileId)
|
||||
{
|
||||
if(profileId != null)
|
||||
{
|
||||
return (load().profiles().stream().filter(p -> profileId.equals(p.getId()) && !Boolean.FALSE.equals(p.getEnabled())
|
||||
&& (!StringUtils.hasContent(p.getPermissionName()) || session.hasPermission(p.getPermissionName()))).findFirst().orElse(null));
|
||||
}
|
||||
|
||||
List<AssistantProfile> enabled = load().profiles().stream().filter(p -> !Boolean.FALSE.equals(p.getEnabled())).toList();
|
||||
return (enabled.stream()
|
||||
.filter(p -> appliesTo(p, session, appName))
|
||||
|
||||
+3
-3
@@ -23,9 +23,9 @@ import java.util.concurrent.FutureTask;
|
||||
import java.util.concurrent.TimeUnit;
|
||||
import com.kingsrook.qbits.assistant.AssistantRuntime;
|
||||
import com.kingsrook.qbits.assistant.model.AssistantProvider;
|
||||
import com.kingsrook.qbits.assistant.provider.HealthResult;
|
||||
import com.kingsrook.qbits.assistant.provider.ModelProviderException;
|
||||
import com.kingsrook.qbits.assistant.provider.ProviderSettings;
|
||||
import com.kingsrook.qbits.assistant.spi.HealthResult;
|
||||
import com.kingsrook.qbits.assistant.spi.ModelProviderException;
|
||||
import com.kingsrook.qbits.assistant.spi.ProviderSettings;
|
||||
import com.kingsrook.qqq.backend.core.exceptions.QException;
|
||||
import com.kingsrook.qqq.backend.core.model.data.QRecord;
|
||||
|
||||
|
||||
+57
-18
@@ -17,18 +17,6 @@
|
||||
package com.kingsrook.qbits.assistant.engine;
|
||||
|
||||
|
||||
import com.kingsrook.qbits.assistant.AssistantQBitConfig;
|
||||
import com.kingsrook.qbits.assistant.model.AssistantModel;
|
||||
import com.kingsrook.qbits.assistant.model.AssistantModelPrice;
|
||||
import com.kingsrook.qbits.assistant.model.AssistantProvider;
|
||||
import com.kingsrook.qbits.assistant.persistence.AssistantStore;
|
||||
import com.kingsrook.qbits.assistant.provider.AssistantModelProvider;
|
||||
import com.kingsrook.qbits.assistant.provider.AssistantProviderType;
|
||||
import com.kingsrook.qbits.assistant.provider.ProviderSettings;
|
||||
import com.kingsrook.qbits.assistant.provider.RegistryModelProvider;
|
||||
import com.kingsrook.qqq.backend.core.exceptions.QException;
|
||||
import com.kingsrook.qqq.backend.core.logging.QLogger;
|
||||
import com.kingsrook.qqq.backend.core.utils.StringUtils;
|
||||
import java.math.BigDecimal;
|
||||
import java.math.RoundingMode;
|
||||
import java.nio.charset.StandardCharsets;
|
||||
@@ -43,6 +31,19 @@ import java.util.List;
|
||||
import java.util.Map;
|
||||
import java.util.concurrent.ConcurrentHashMap;
|
||||
import java.util.concurrent.Semaphore;
|
||||
import com.kingsrook.qbits.assistant.AssistantQBitConfig;
|
||||
import com.kingsrook.qbits.assistant.model.AssistantModel;
|
||||
import com.kingsrook.qbits.assistant.model.AssistantModelPrice;
|
||||
import com.kingsrook.qbits.assistant.model.AssistantProvider;
|
||||
import com.kingsrook.qbits.assistant.persistence.AssistantStore;
|
||||
import com.kingsrook.qbits.assistant.provider.RegistryModelProvider;
|
||||
import com.kingsrook.qbits.assistant.spi.AssistantModelProvider;
|
||||
import com.kingsrook.qbits.assistant.spi.AssistantProviderType;
|
||||
import com.kingsrook.qbits.assistant.spi.ModelPricing;
|
||||
import com.kingsrook.qbits.assistant.spi.ProviderSettings;
|
||||
import com.kingsrook.qqq.backend.core.exceptions.QException;
|
||||
import com.kingsrook.qqq.backend.core.logging.QLogger;
|
||||
import com.kingsrook.qqq.backend.core.utils.StringUtils;
|
||||
import static com.kingsrook.qqq.backend.core.logging.LogUtils.logPair;
|
||||
|
||||
|
||||
@@ -186,6 +187,16 @@ public class ProviderService
|
||||
** with a message for the admin when the row cannot be used.
|
||||
*******************************************************************************/
|
||||
public Active forRow(AssistantProvider row, String fallbackModel) throws ProviderSetupException
|
||||
{
|
||||
return (forRow(row, fallbackModel, false));
|
||||
}
|
||||
|
||||
|
||||
|
||||
/*******************************************************************************
|
||||
** Resolve only the requested kind; embedding calls never select chat models.
|
||||
*******************************************************************************/
|
||||
private Active forRow(AssistantProvider row, String fallbackModel, Boolean embedding) throws ProviderSetupException
|
||||
{
|
||||
if(Boolean.TRUE.equals(config.getHipaaMode()) && !Boolean.TRUE.equals(row.getHipaaEligible()))
|
||||
{
|
||||
@@ -205,7 +216,7 @@ public class ProviderService
|
||||
String model = StringUtils.hasContent(row.getModel()) ? row.getModel() : null;
|
||||
if(model == null && !models.isEmpty())
|
||||
{
|
||||
model = models.stream().filter(m -> Boolean.TRUE.equals(m.getEnabled())).map(AssistantModel::getModelId).findFirst().orElse(null);
|
||||
model = models.stream().filter(m -> Boolean.TRUE.equals(m.getEnabled()) && !m.isChat().equals(embedding)).map(AssistantModel::getModelId).findFirst().orElse(null);
|
||||
if(model == null)
|
||||
{
|
||||
throw (new ProviderSetupException("All models of this provider are disabled. Enable a model first."));
|
||||
@@ -217,7 +228,7 @@ public class ProviderService
|
||||
}
|
||||
String selected = model;
|
||||
AssistantModel registry = models.stream().filter(m -> java.util.Objects.equals(selected, m.getModelId())).findFirst().orElse(null);
|
||||
if(registry != null && !Boolean.TRUE.equals(registry.getEnabled()))
|
||||
if(registry != null && (!Boolean.TRUE.equals(registry.getEnabled()) || registry.isChat().equals(embedding)))
|
||||
{
|
||||
throw (new ProviderSetupException("The selected model is disabled in this provider's model registry."));
|
||||
}
|
||||
@@ -248,7 +259,11 @@ public class ProviderService
|
||||
return (errors);
|
||||
}
|
||||
|
||||
errors.addAll(type.validate(row));
|
||||
errors.addAll(type.validate(new ProviderSettings().withKind(kind(row))
|
||||
.withApiKeyEnvName(row.getApiKeyEnvName()).withBaseUrl(row.getBaseUrl())
|
||||
.withApiVersion(row.getApiVersion()).withRegion(row.getRegion()).withCloudProject(row.getCloudProject())
|
||||
.withTlsCaBundle(row.getTlsCaBundle()).withConnectTimeoutSeconds(row.getConnectTimeoutSeconds())
|
||||
.withRequestTimeoutSeconds(row.getRequestTimeoutSeconds())));
|
||||
String envName = keyEnvName(row);
|
||||
if(envName != null && !AssistantQBitConfig.ENV_NAME.matcher(envName).matches())
|
||||
{
|
||||
@@ -668,7 +683,7 @@ public class ProviderService
|
||||
{
|
||||
throw (new ProviderSetupException("No API key: the environment variable " + keyEnvName(row) + " is not set on this server."));
|
||||
}
|
||||
return (new ProviderSettings().withKind(kind(row)).withApiKey(key)
|
||||
return (new ProviderSettings().withKind(kind(row)).withApiKeyEnvName(row.getApiKeyEnvName()).withApiKey(key)
|
||||
.withBaseUrl(StringUtils.hasContent(row.getBaseUrl()) ? row.getBaseUrl().trim() : null)
|
||||
.withApiVersion(row.getApiVersion()).withRegion(row.getRegion()).withCloudProject(row.getCloudProject())
|
||||
.withTlsCaBundle(row.getTlsCaBundle()).withSslContext(StringUtils.hasContent(row.getTlsCaBundle()) ? config.getTrustedCaBundles().get(row.getTlsCaBundle()) : null)
|
||||
@@ -728,7 +743,7 @@ public class ProviderService
|
||||
/*******************************************************************************
|
||||
** P-e seam: no automatic alternative is selected in P-c. Never downgrade PHI eligibility.
|
||||
*******************************************************************************/
|
||||
public java.util.Optional<Active> eligibleAlternative(com.kingsrook.qbits.assistant.classification.DataClassification classification, AssistantProvider blockedProvider)
|
||||
public java.util.Optional<Active> eligibleAlternative(com.kingsrook.qqq.backend.core.actions.ai.DataClassification classification, AssistantProvider blockedProvider)
|
||||
{
|
||||
return (java.util.Optional.empty());
|
||||
}
|
||||
@@ -752,7 +767,7 @@ public class ProviderService
|
||||
public Active resolveModel(Integer modelId, Boolean requiresHipaa, Boolean requireTools) throws QException
|
||||
{
|
||||
AssistantModel model = store.listModels().stream().filter(m -> modelId.equals(m.getId()) && Boolean.TRUE.equals(m.getEnabled())).findFirst().orElse(null);
|
||||
if(model == null)
|
||||
if(model == null || !model.isChat())
|
||||
{
|
||||
return (null);
|
||||
}
|
||||
@@ -816,4 +831,28 @@ public class ProviderService
|
||||
{
|
||||
return (left != null && right != null && java.util.Objects.equals(left.providerId(), right.providerId()) && java.util.Objects.equals(left.model(), right.model()));
|
||||
}
|
||||
|
||||
|
||||
/*******************************************************************************
|
||||
** Embedding selection is explicit and checks fresh provider eligibility.
|
||||
*******************************************************************************/
|
||||
public Active resolveEmbedding(Integer modelId, Boolean requiresHipaa) throws QException
|
||||
{
|
||||
AssistantModel model = store.listModels().stream().filter(m -> java.util.Objects.equals(modelId, m.getId())).findFirst().orElse(null);
|
||||
if(model == null || !"EMBEDDING".equals(model.getModelKind()) || !Boolean.TRUE.equals(model.getEnabled()))
|
||||
{
|
||||
throw (new ProviderSetupException("Select an enabled EMBEDDING model for this knowledge source."));
|
||||
}
|
||||
AssistantProvider row = store.getProvider(model.getProviderId());
|
||||
if(row == null || !Boolean.TRUE.equals(row.getEnabled()))
|
||||
{
|
||||
throw (new ProviderSetupException("The embedding provider is disabled or unavailable."));
|
||||
}
|
||||
if((requiresHipaa || Boolean.TRUE.equals(config.getHipaaMode())) && !Boolean.TRUE.equals(row.getHipaaEligible()))
|
||||
{
|
||||
throw (new ProviderSetupException("PHI may only be embedded by a HIPAA-eligible provider. Nothing was sent."));
|
||||
}
|
||||
return (forRow(new AssistantProvider(row.toQRecord()).withModel(model.getModelId()), model.getModelId(), true));
|
||||
}
|
||||
|
||||
}
|
||||
@@ -26,15 +26,12 @@ import java.util.Map;
|
||||
|
||||
|
||||
/*******************************************************************************
|
||||
** Per-user turn rate limits (spec 3.9): turns started per minute and turns
|
||||
** running at once. In memory, per replica - with several replicas the
|
||||
** effective limit is per replica (the concurrent limit is also checked
|
||||
** against the turn table by the API).
|
||||
** Per-user starts per minute, in memory per replica. The API implements
|
||||
** concurrency by superseding turns, never by refusing another question.
|
||||
*******************************************************************************/
|
||||
public class RateLimiter
|
||||
{
|
||||
private final Map<String, Deque<Instant>> starts = new HashMap<>();
|
||||
private final Map<String, Integer> running = new HashMap<>();
|
||||
private final Clock clock;
|
||||
|
||||
|
||||
@@ -61,17 +58,12 @@ public class RateLimiter
|
||||
queue.pollFirst();
|
||||
}
|
||||
|
||||
if(running.getOrDefault(userId, 0) >= concurrent)
|
||||
{
|
||||
return ("You already have an assistant answer in progress. Wait for it to finish or stop it.");
|
||||
}
|
||||
if(queue.size() >= perMinute)
|
||||
{
|
||||
return ("Too many assistant requests in the last minute. Try again shortly.");
|
||||
}
|
||||
|
||||
queue.addLast(now);
|
||||
running.merge(userId, 1, Integer::sum);
|
||||
return (null);
|
||||
}
|
||||
|
||||
@@ -82,7 +74,7 @@ public class RateLimiter
|
||||
*******************************************************************************/
|
||||
public synchronized void release(String userId)
|
||||
{
|
||||
running.computeIfPresent(userId, (k, v) -> v <= 1 ? null : v - 1);
|
||||
// Only starts per minute are counted; completion does not refund a start.
|
||||
}
|
||||
|
||||
}
|
||||
Loaded 100 of 205 files, more files were not shown because too many files have changed in this diff.
Show more
Reference in new issue
Block a user