briyah 2.0.5 → 2.0.7
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/README.md +105 -0
- package/data/common/prompts/moderate.json +34 -0
- package/data/common/prompts/moderate.prompt +136 -0
- package/data/packs/dnd5e/pack.json +7 -1
- package/dist-sdk/server/src/ai/LLM/base-ai.service.d.ts +16 -0
- package/dist-sdk/server/src/ai/LLM/base-ai.service.js +23 -0
- package/dist-sdk/server/src/ai/agent.d.ts +33 -0
- package/dist-sdk/server/src/ai/agent.js +64 -13
- package/dist-sdk/server/src/app/user-service-factory.js +3 -0
- package/dist-sdk/server/src/app.controller.d.ts +7 -1
- package/dist-sdk/server/src/app.controller.js +55 -0
- package/dist-sdk/server/src/app.service.d.ts +114 -2
- package/dist-sdk/server/src/app.service.js +181 -4
- package/dist-sdk/server/src/data/data-guide.builder.d.ts +2 -0
- package/dist-sdk/server/src/data/data-guide.builder.js +90 -0
- package/dist-sdk/server/src/data/data-registry.d.ts +32 -0
- package/dist-sdk/server/src/data/data-registry.js +61 -0
- package/dist-sdk/server/src/data/data.types.d.ts +158 -0
- package/dist-sdk/server/src/data/data.types.js +24 -0
- package/dist-sdk/server/src/data/query-validation.d.ts +45 -0
- package/dist-sdk/server/src/data/query-validation.js +245 -0
- package/dist-sdk/server/src/documents/document-conversion.d.ts +70 -0
- package/dist-sdk/server/src/documents/document-conversion.js +341 -0
- package/dist-sdk/server/src/documents/library/chunking.d.ts +65 -0
- package/dist-sdk/server/src/documents/library/chunking.js +263 -0
- package/dist-sdk/server/src/documents/library/document-guide.builder.d.ts +2 -0
- package/dist-sdk/server/src/documents/library/document-guide.builder.js +58 -0
- package/dist-sdk/server/src/documents/library/document-registry.d.ts +22 -0
- package/dist-sdk/server/src/documents/library/document-registry.js +44 -0
- package/dist-sdk/server/src/documents/library/document.types.d.ts +108 -0
- package/dist-sdk/server/src/documents/library/document.types.js +20 -0
- package/dist-sdk/server/src/documents/library/embedding.d.ts +57 -0
- package/dist-sdk/server/src/documents/library/embedding.js +151 -0
- package/dist-sdk/server/src/packs/pack-manifest.d.ts +46 -0
- package/dist-sdk/server/src/packs/pack-manifest.js +46 -1
- package/dist-sdk/server/src/room/artifact-store.service.js +44 -11
- package/dist-sdk/server/src/room/artifact.d.ts +8 -0
- package/dist-sdk/server/src/room/room.d.ts +7 -5
- package/dist-sdk/server/src/room/room.js +44 -7
- package/dist-sdk/server/src/rpg/rpg-roster.d.ts +70 -29
- package/dist-sdk/server/src/rpg/rpg-roster.js +152 -41
- package/dist-sdk/server/src/rpg/rpg.service.d.ts +66 -29
- package/dist-sdk/server/src/rpg/rpg.service.js +140 -65
- package/dist-sdk/server/src/sdk/index.d.ts +16 -2
- package/dist-sdk/server/src/sdk/index.js +37 -1
- package/dist-sdk/server/src/tools/core/data.tools.d.ts +17 -0
- package/dist-sdk/server/src/tools/core/data.tools.js +165 -0
- package/dist-sdk/server/src/tools/core/document.tools.d.ts +39 -0
- package/dist-sdk/server/src/tools/core/document.tools.js +391 -0
- package/dist-sdk/server/src/tools/core/index.js +3 -1
- package/dist-sdk/server/src/tools/native-tool.types.d.ts +37 -0
- package/dist-sdk/server/src/tools/tool-execution.service.d.ts +23 -2
- package/dist-sdk/server/src/tools/tool-execution.service.js +30 -6
- package/dist-sdk/shared/types/app.types.d.ts +39 -5
- package/package.json +172 -167
|
@@ -0,0 +1,58 @@
|
|
|
1
|
+
"use strict";
|
|
2
|
+
Object.defineProperty(exports, "__esModule", { value: true });
|
|
3
|
+
exports.buildDocumentGuideMarkdown = buildDocumentGuideMarkdown;
|
|
4
|
+
/**
|
|
5
|
+
* Renders how to use the document library, as a document to attach to an agent.
|
|
6
|
+
*
|
|
7
|
+
* Unlike the data guide, this does not list what is in the library. A library
|
|
8
|
+
* changes while an agent works — the person uploads a contract mid-conversation —
|
|
9
|
+
* and an attached document is frozen into the agent's cached prefix when it is
|
|
10
|
+
* attached, so a listing would be wrong exactly when it mattered. What does not
|
|
11
|
+
* change is how the tools are best used, and that is what this carries.
|
|
12
|
+
* `list_documents` is the live answer to what is there.
|
|
13
|
+
*/
|
|
14
|
+
const document_registry_1 = require("./document-registry");
|
|
15
|
+
/** @returns The guide, or an empty string when no source is registered */
|
|
16
|
+
function buildDocumentGuideMarkdown() {
|
|
17
|
+
const sources = (0, document_registry_1.listDocumentSources)();
|
|
18
|
+
if (sources.length === 0) {
|
|
19
|
+
return '';
|
|
20
|
+
}
|
|
21
|
+
const lines = [
|
|
22
|
+
'# Working With Documents',
|
|
23
|
+
'',
|
|
24
|
+
...sources.map((source) => `- **${source.name}**: ${source.description}`),
|
|
25
|
+
'',
|
|
26
|
+
'## Look things up; hold only what you must',
|
|
27
|
+
'',
|
|
28
|
+
'There are two ways to use a document, and they cost very different amounts.',
|
|
29
|
+
'',
|
|
30
|
+
'1. **Look it up.** `find_in_documents` finds passages about something; `read_document`',
|
|
31
|
+
' reads the pages around them. Only what you read goes into your history. Use this',
|
|
32
|
+
' for any question about *part* of a document: what the contract says about',
|
|
33
|
+
' termination, the limit on a policy, which claims were over $100,000.',
|
|
34
|
+
'2. **Hold it.** `load_document` puts the entire document into your context, where',
|
|
35
|
+
' it is sent with every request you make until you `unload_document` it. Use this',
|
|
36
|
+
' only when the work needs all of it at once: reviewing a whole contract,',
|
|
37
|
+
' summarising everything in it, or comparing two documents side by side.',
|
|
38
|
+
'',
|
|
39
|
+
'When you do hold a document, tell the person you are reading the whole thing. When',
|
|
40
|
+
'the work that needed it is done, unload it.',
|
|
41
|
+
'',
|
|
42
|
+
'## Every time',
|
|
43
|
+
'',
|
|
44
|
+
'- **Start with `list_documents`** unless you listed them in this same piece of work.',
|
|
45
|
+
' Documents are added while you work.',
|
|
46
|
+
'- **Search in the document\'s own words.** A contract says "hold harmless" and',
|
|
47
|
+
' "indemnify"; a loss run says "incurred" and "reserve". Try a second phrasing before',
|
|
48
|
+
' concluding something is not there.',
|
|
49
|
+
'- **Cite the document and page** for every fact you take from one: *(Acme Master',
|
|
50
|
+
' Services Agreement, p. 12)*. A person acting on a clause needs to find it.',
|
|
51
|
+
'- **Quote exact wording when it matters** — a limit, an exclusion, a deadline — rather',
|
|
52
|
+
' than paraphrasing it. A paraphrase of a legal clause can change what it means.',
|
|
53
|
+
'- **Say so when a document does not answer the question.** Never fill a gap with what',
|
|
54
|
+
' a document of that kind usually says.',
|
|
55
|
+
'',
|
|
56
|
+
];
|
|
57
|
+
return lines.join('\n');
|
|
58
|
+
}
|
|
@@ -0,0 +1,22 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* The process-global registry of host document sources.
|
|
3
|
+
*
|
|
4
|
+
* Module state, for the reason the data registry is: a source is registered once
|
|
5
|
+
* at boot and is the same for every room, and a tool handler runs with no Nest
|
|
6
|
+
* scope to inject into. Scope — whose documents a call may see — rides the tool
|
|
7
|
+
* context and never lives here.
|
|
8
|
+
*/
|
|
9
|
+
import { DocumentSource } from './document.types';
|
|
10
|
+
/**
|
|
11
|
+
* Registers (or replaces) a document source.
|
|
12
|
+
* @param source The host's document source
|
|
13
|
+
*/
|
|
14
|
+
export declare function registerDocumentSource(source: DocumentSource): void;
|
|
15
|
+
/** Removes a document source. @returns True if one was removed */
|
|
16
|
+
export declare function unregisterDocumentSource(name: string): boolean;
|
|
17
|
+
/** @returns Every registered source, in registration order */
|
|
18
|
+
export declare function listDocumentSources(): DocumentSource[];
|
|
19
|
+
/** @returns Whether any source is registered — the tools say so rather than failing oddly */
|
|
20
|
+
export declare function hasDocumentSources(): boolean;
|
|
21
|
+
/** Test seam. */
|
|
22
|
+
export declare function resetDocumentSources(): void;
|
|
@@ -0,0 +1,44 @@
|
|
|
1
|
+
"use strict";
|
|
2
|
+
Object.defineProperty(exports, "__esModule", { value: true });
|
|
3
|
+
exports.registerDocumentSource = registerDocumentSource;
|
|
4
|
+
exports.unregisterDocumentSource = unregisterDocumentSource;
|
|
5
|
+
exports.listDocumentSources = listDocumentSources;
|
|
6
|
+
exports.hasDocumentSources = hasDocumentSources;
|
|
7
|
+
exports.resetDocumentSources = resetDocumentSources;
|
|
8
|
+
const logger_1 = require("../../common/logger");
|
|
9
|
+
const sources = new Map();
|
|
10
|
+
const REQUIRED = ['list', 'search', 'read', 'fullText'];
|
|
11
|
+
/**
|
|
12
|
+
* Registers (or replaces) a document source.
|
|
13
|
+
* @param source The host's document source
|
|
14
|
+
*/
|
|
15
|
+
function registerDocumentSource(source) {
|
|
16
|
+
if (!source?.name) {
|
|
17
|
+
throw new Error('A document source needs a name');
|
|
18
|
+
}
|
|
19
|
+
for (const method of REQUIRED) {
|
|
20
|
+
if (typeof source[method] !== 'function') {
|
|
21
|
+
throw new Error(`Document source "${source.name}" must have a ${String(method)} function`);
|
|
22
|
+
}
|
|
23
|
+
}
|
|
24
|
+
if (sources.has(source.name)) {
|
|
25
|
+
logger_1.logger.warn(`Document source "${source.name}" is already registered; overwriting`);
|
|
26
|
+
}
|
|
27
|
+
sources.set(source.name, source);
|
|
28
|
+
}
|
|
29
|
+
/** Removes a document source. @returns True if one was removed */
|
|
30
|
+
function unregisterDocumentSource(name) {
|
|
31
|
+
return sources.delete(name);
|
|
32
|
+
}
|
|
33
|
+
/** @returns Every registered source, in registration order */
|
|
34
|
+
function listDocumentSources() {
|
|
35
|
+
return [...sources.values()];
|
|
36
|
+
}
|
|
37
|
+
/** @returns Whether any source is registered — the tools say so rather than failing oddly */
|
|
38
|
+
function hasDocumentSources() {
|
|
39
|
+
return sources.size > 0;
|
|
40
|
+
}
|
|
41
|
+
/** Test seam. */
|
|
42
|
+
function resetDocumentSources() {
|
|
43
|
+
sources.clear();
|
|
44
|
+
}
|
|
@@ -0,0 +1,108 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* A host's library of documents, made searchable and readable by an agent.
|
|
3
|
+
*
|
|
4
|
+
* The host keeps the documents — its database, its tenancy, its idea of who may
|
|
5
|
+
* see what — and answers four questions about them. Briyah supplies everything
|
|
6
|
+
* between those answers and a model: the tools, argument checking, refusals that
|
|
7
|
+
* name the valid choices, result budgets, pagination, and holding a document in
|
|
8
|
+
* an agent's context when the work needs all of it at once.
|
|
9
|
+
*
|
|
10
|
+
* Every method receives the opaque tool context the host passed when it started
|
|
11
|
+
* the interaction. That is the only place scope comes from. A document id an
|
|
12
|
+
* agent supplies is checked against what `list` returns for that scope before
|
|
13
|
+
* any other method sees it, so a host never has to trust one.
|
|
14
|
+
*
|
|
15
|
+
* `chunkPages` and `embedTexts` are exported alongside for a host building the
|
|
16
|
+
* index this searches, but nothing here requires them: `search` is the host's,
|
|
17
|
+
* and full-text, vector or both are all fine behind it.
|
|
18
|
+
*/
|
|
19
|
+
/** One document as an agent sees it listed. */
|
|
20
|
+
export interface DocumentSummary {
|
|
21
|
+
/** Unique within the source. What every tool takes. */
|
|
22
|
+
documentId: string;
|
|
23
|
+
/** What a person calls it — a title, or the file name. */
|
|
24
|
+
name: string;
|
|
25
|
+
/** The host's word for what it is, e.g. `contract` or `loss run`. */
|
|
26
|
+
kind?: string;
|
|
27
|
+
/** Pages as a reader counts them. A Word document is one. */
|
|
28
|
+
pages: number;
|
|
29
|
+
/** Size of its text, so an agent can judge what holding it would cost. */
|
|
30
|
+
chars: number;
|
|
31
|
+
/** ISO date it was added. */
|
|
32
|
+
addedAt?: string;
|
|
33
|
+
/** A paragraph describing it, when the host has one. */
|
|
34
|
+
summary?: string;
|
|
35
|
+
/**
|
|
36
|
+
* Whether it can be searched yet. A document still being indexed can be read
|
|
37
|
+
* but not found; one that failed can be read if its text exists at all.
|
|
38
|
+
* Defaults to `ready`.
|
|
39
|
+
*/
|
|
40
|
+
state?: 'ready' | 'indexing' | 'failed';
|
|
41
|
+
}
|
|
42
|
+
export interface DocumentSearchRequest {
|
|
43
|
+
/** What to look for, in the agent's words. Never empty. */
|
|
44
|
+
query: string;
|
|
45
|
+
/** Restricts the search to these documents. Absent means every document in scope. */
|
|
46
|
+
documentIds?: string[];
|
|
47
|
+
/** How many passages to return. Briyah clamps it; hosts need not. */
|
|
48
|
+
limit: number;
|
|
49
|
+
}
|
|
50
|
+
/** One passage a search found. */
|
|
51
|
+
export interface DocumentHit {
|
|
52
|
+
documentId: string;
|
|
53
|
+
/** The document's name, so a hit can be cited without another call. */
|
|
54
|
+
name: string;
|
|
55
|
+
pageNum: number;
|
|
56
|
+
/** The headings above the passage, when the host knows them. */
|
|
57
|
+
heading?: string;
|
|
58
|
+
/** The passage. Briyah trims it to fit the result; send it whole. */
|
|
59
|
+
excerpt: string;
|
|
60
|
+
/**
|
|
61
|
+
* Higher is better. Hits from different sources are merged by it, so a host
|
|
62
|
+
* with more than one source should keep scores on a common scale.
|
|
63
|
+
*/
|
|
64
|
+
score: number;
|
|
65
|
+
}
|
|
66
|
+
/** A span of pages, inclusive, 1-based. */
|
|
67
|
+
export interface PageRange {
|
|
68
|
+
from: number;
|
|
69
|
+
to: number;
|
|
70
|
+
}
|
|
71
|
+
export interface DocumentPage {
|
|
72
|
+
pageNum: number;
|
|
73
|
+
markdown: string;
|
|
74
|
+
/** A name for the page, when it has one — a workbook's sheet. */
|
|
75
|
+
label?: string;
|
|
76
|
+
}
|
|
77
|
+
export interface DocumentPages {
|
|
78
|
+
documentId: string;
|
|
79
|
+
name: string;
|
|
80
|
+
/** The document's page count, whatever range was asked for. */
|
|
81
|
+
pageCount: number;
|
|
82
|
+
pages: DocumentPage[];
|
|
83
|
+
}
|
|
84
|
+
export interface DocumentText {
|
|
85
|
+
documentId: string;
|
|
86
|
+
name: string;
|
|
87
|
+
markdown: string;
|
|
88
|
+
}
|
|
89
|
+
/** A host's documents. */
|
|
90
|
+
export interface DocumentSource {
|
|
91
|
+
name: string;
|
|
92
|
+
/** One sentence for the agent: what these documents are. */
|
|
93
|
+
description: string;
|
|
94
|
+
/** Every document the context may see. Called often; keep it cheap. */
|
|
95
|
+
list(context: unknown): Promise<DocumentSummary[]>;
|
|
96
|
+
/**
|
|
97
|
+
* Passages matching a query, best first. Only ever called with document ids
|
|
98
|
+
* that `list` returned for the same context.
|
|
99
|
+
*/
|
|
100
|
+
search(context: unknown, request: DocumentSearchRequest): Promise<DocumentHit[]>;
|
|
101
|
+
/**
|
|
102
|
+
* The pages in a range. Briyah clamps the range to the document. Returning
|
|
103
|
+
* null means the document is not there after all.
|
|
104
|
+
*/
|
|
105
|
+
read(context: unknown, documentId: string, range: PageRange): Promise<DocumentPages | null>;
|
|
106
|
+
/** The whole document, for holding in an agent's context. Null as for `read`. */
|
|
107
|
+
fullText(context: unknown, documentId: string): Promise<DocumentText | null>;
|
|
108
|
+
}
|
|
@@ -0,0 +1,20 @@
|
|
|
1
|
+
"use strict";
|
|
2
|
+
/**
|
|
3
|
+
* A host's library of documents, made searchable and readable by an agent.
|
|
4
|
+
*
|
|
5
|
+
* The host keeps the documents — its database, its tenancy, its idea of who may
|
|
6
|
+
* see what — and answers four questions about them. Briyah supplies everything
|
|
7
|
+
* between those answers and a model: the tools, argument checking, refusals that
|
|
8
|
+
* name the valid choices, result budgets, pagination, and holding a document in
|
|
9
|
+
* an agent's context when the work needs all of it at once.
|
|
10
|
+
*
|
|
11
|
+
* Every method receives the opaque tool context the host passed when it started
|
|
12
|
+
* the interaction. That is the only place scope comes from. A document id an
|
|
13
|
+
* agent supplies is checked against what `list` returns for that scope before
|
|
14
|
+
* any other method sees it, so a host never has to trust one.
|
|
15
|
+
*
|
|
16
|
+
* `chunkPages` and `embedTexts` are exported alongside for a host building the
|
|
17
|
+
* index this searches, but nothing here requires them: `search` is the host's,
|
|
18
|
+
* and full-text, vector or both are all fine behind it.
|
|
19
|
+
*/
|
|
20
|
+
Object.defineProperty(exports, "__esModule", { value: true });
|
|
@@ -0,0 +1,57 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* Turning text into vectors for semantic search.
|
|
3
|
+
*
|
|
4
|
+
* Anthropic publishes no embeddings endpoint, so this defaults to OpenAI's
|
|
5
|
+
* `text-embedding-3-small`. The provider sits behind {@link EmbeddingProvider} so
|
|
6
|
+
* a host can supply another, and so tests never reach a network.
|
|
7
|
+
*
|
|
8
|
+
* The dimension is the one number a host has to agree with: it is baked into the
|
|
9
|
+
* vector column of whatever database stores the result, and a model that returns
|
|
10
|
+
* a different length would fail every insert — or worse, succeed against a column
|
|
11
|
+
* declared without one. So {@link EMBEDDING_DIMENSIONS} is exported for the host's
|
|
12
|
+
* migration to use, and every response is checked against what was asked for.
|
|
13
|
+
*/
|
|
14
|
+
/** The default model. Override with `EMBEDDING_MODEL` or per call. */
|
|
15
|
+
export declare const DEFAULT_EMBEDDING_MODEL = "text-embedding-3-small";
|
|
16
|
+
/**
|
|
17
|
+
* The vector length a host's schema should declare. `text-embedding-3-small`
|
|
18
|
+
* produces 1536 natively. Override with `EMBEDDING_DIMENSIONS` only together with
|
|
19
|
+
* a migration — the column and the model have to change as one.
|
|
20
|
+
*/
|
|
21
|
+
export declare const EMBEDDING_DIMENSIONS = 1536;
|
|
22
|
+
/** A source of embeddings. */
|
|
23
|
+
export interface EmbeddingProvider {
|
|
24
|
+
/**
|
|
25
|
+
* Embeds a batch. Returns one vector per input, in input order, and the tokens
|
|
26
|
+
* the provider billed for the batch.
|
|
27
|
+
*/
|
|
28
|
+
embed(texts: string[], model: string, dimensions: number): Promise<{
|
|
29
|
+
vectors: number[][];
|
|
30
|
+
tokens: number;
|
|
31
|
+
}>;
|
|
32
|
+
}
|
|
33
|
+
export interface EmbeddingOptions {
|
|
34
|
+
/** Defaults to `EMBEDDING_MODEL`, then {@link DEFAULT_EMBEDDING_MODEL}. */
|
|
35
|
+
model?: string;
|
|
36
|
+
/** Defaults to `EMBEDDING_DIMENSIONS`, then {@link EMBEDDING_DIMENSIONS}. */
|
|
37
|
+
dimensions?: number;
|
|
38
|
+
/** Defaults to OpenAI with `OPENAI_API_KEY`. */
|
|
39
|
+
provider?: EmbeddingProvider;
|
|
40
|
+
/** Called as batches complete, for a caller with somewhere to show it. */
|
|
41
|
+
onProgress?: (message: string) => void;
|
|
42
|
+
}
|
|
43
|
+
export interface EmbeddingResult {
|
|
44
|
+
/** One per input, in input order. */
|
|
45
|
+
vectors: number[][];
|
|
46
|
+
model: string;
|
|
47
|
+
dimensions: number;
|
|
48
|
+
tokens: number;
|
|
49
|
+
/** In dollars, priced from `model_prices.json`. Zero for a model with no price entry. */
|
|
50
|
+
cost: number;
|
|
51
|
+
}
|
|
52
|
+
/**
|
|
53
|
+
* Embeds texts in as few requests as the provider's limits allow.
|
|
54
|
+
*
|
|
55
|
+
* @throws If the provider is unavailable, or returns vectors of the wrong length
|
|
56
|
+
*/
|
|
57
|
+
export declare function embedTexts(texts: readonly string[], options?: EmbeddingOptions): Promise<EmbeddingResult>;
|
|
@@ -0,0 +1,151 @@
|
|
|
1
|
+
"use strict";
|
|
2
|
+
/**
|
|
3
|
+
* Turning text into vectors for semantic search.
|
|
4
|
+
*
|
|
5
|
+
* Anthropic publishes no embeddings endpoint, so this defaults to OpenAI's
|
|
6
|
+
* `text-embedding-3-small`. The provider sits behind {@link EmbeddingProvider} so
|
|
7
|
+
* a host can supply another, and so tests never reach a network.
|
|
8
|
+
*
|
|
9
|
+
* The dimension is the one number a host has to agree with: it is baked into the
|
|
10
|
+
* vector column of whatever database stores the result, and a model that returns
|
|
11
|
+
* a different length would fail every insert — or worse, succeed against a column
|
|
12
|
+
* declared without one. So {@link EMBEDDING_DIMENSIONS} is exported for the host's
|
|
13
|
+
* migration to use, and every response is checked against what was asked for.
|
|
14
|
+
*/
|
|
15
|
+
var __importDefault = (this && this.__importDefault) || function (mod) {
|
|
16
|
+
return (mod && mod.__esModule) ? mod : { "default": mod };
|
|
17
|
+
};
|
|
18
|
+
Object.defineProperty(exports, "__esModule", { value: true });
|
|
19
|
+
exports.EMBEDDING_DIMENSIONS = exports.DEFAULT_EMBEDDING_MODEL = void 0;
|
|
20
|
+
exports.embedTexts = embedTexts;
|
|
21
|
+
const openai_1 = __importDefault(require("openai"));
|
|
22
|
+
const model_prices_1 = require("../../ai/model_prices");
|
|
23
|
+
const logger_1 = require("../../common/logger");
|
|
24
|
+
/** The default model. Override with `EMBEDDING_MODEL` or per call. */
|
|
25
|
+
exports.DEFAULT_EMBEDDING_MODEL = 'text-embedding-3-small';
|
|
26
|
+
/**
|
|
27
|
+
* The vector length a host's schema should declare. `text-embedding-3-small`
|
|
28
|
+
* produces 1536 natively. Override with `EMBEDDING_DIMENSIONS` only together with
|
|
29
|
+
* a migration — the column and the model have to change as one.
|
|
30
|
+
*/
|
|
31
|
+
exports.EMBEDDING_DIMENSIONS = 1536;
|
|
32
|
+
/**
|
|
33
|
+
* OpenAI allows 2,048 inputs and 300,000 tokens per request. The token bound is
|
|
34
|
+
* the one that bites: 2,048 chunks of 1,800 characters is roughly a million
|
|
35
|
+
* tokens. Batches are sized by an estimate that errs high.
|
|
36
|
+
*/
|
|
37
|
+
const MAX_INPUTS_PER_REQUEST = 2_048;
|
|
38
|
+
const MAX_ESTIMATED_TOKENS_PER_REQUEST = 200_000;
|
|
39
|
+
/**
|
|
40
|
+
* One input's hard ceiling is 8,191 tokens. Text past this is cut rather than
|
|
41
|
+
* failing the batch — a passage that long is not a passage, and the first part of
|
|
42
|
+
* it is still a good vector for what it is about.
|
|
43
|
+
*/
|
|
44
|
+
const MAX_CHARS_PER_INPUT = 24_000;
|
|
45
|
+
/** Characters per token, pessimistically: dense tables and numbers tokenize poorly. */
|
|
46
|
+
const CHARS_PER_TOKEN_ESTIMATE = 3;
|
|
47
|
+
/**
|
|
48
|
+
* Embeds texts in as few requests as the provider's limits allow.
|
|
49
|
+
*
|
|
50
|
+
* @throws If the provider is unavailable, or returns vectors of the wrong length
|
|
51
|
+
*/
|
|
52
|
+
async function embedTexts(texts, options = {}) {
|
|
53
|
+
const model = options.model || process.env.EMBEDDING_MODEL || exports.DEFAULT_EMBEDDING_MODEL;
|
|
54
|
+
const dimensions = options.dimensions || Number(process.env.EMBEDDING_DIMENSIONS) || exports.EMBEDDING_DIMENSIONS;
|
|
55
|
+
const provider = options.provider ?? openAiProvider();
|
|
56
|
+
const progress = options.onProgress ?? (() => undefined);
|
|
57
|
+
const inputs = texts.map((text) => (text || ' ').slice(0, MAX_CHARS_PER_INPUT));
|
|
58
|
+
const batches = batch(inputs);
|
|
59
|
+
const vectors = [];
|
|
60
|
+
let tokens = 0;
|
|
61
|
+
for (let i = 0; i < batches.length; i++) {
|
|
62
|
+
const result = await provider.embed(batches[i], model, dimensions);
|
|
63
|
+
if (result.vectors.length !== batches[i].length) {
|
|
64
|
+
throw new Error(`The embedding provider returned ${result.vectors.length} vectors for ${batches[i].length} inputs.`);
|
|
65
|
+
}
|
|
66
|
+
const wrong = result.vectors.find((vector) => vector.length !== dimensions);
|
|
67
|
+
if (wrong) {
|
|
68
|
+
throw new Error(`The embedding model "${model}" returned vectors of length ${wrong.length}, not ${dimensions}. ` +
|
|
69
|
+
'The model and the database column have to agree; change them together.');
|
|
70
|
+
}
|
|
71
|
+
vectors.push(...result.vectors);
|
|
72
|
+
tokens += result.tokens;
|
|
73
|
+
if (batches.length > 1) {
|
|
74
|
+
progress(`Embedded batch ${i + 1} of ${batches.length}.`);
|
|
75
|
+
}
|
|
76
|
+
}
|
|
77
|
+
return { vectors, model, dimensions, tokens, cost: tokens * pricePerToken(model) };
|
|
78
|
+
}
|
|
79
|
+
/**
|
|
80
|
+
* The model's price per input token, or zero when it cannot be found. Accounting
|
|
81
|
+
* failing is logged, never fatal: the vectors are already paid for, and throwing
|
|
82
|
+
* them away over a missing price file would only mean paying for them twice.
|
|
83
|
+
*/
|
|
84
|
+
function pricePerToken(model) {
|
|
85
|
+
try {
|
|
86
|
+
return (0, model_prices_1.resolveModelInfo)(model)?.input_cost_per_token ?? 0;
|
|
87
|
+
}
|
|
88
|
+
catch (error) {
|
|
89
|
+
logger_1.logger.warn(`No price for embedding model "${model}"; recording its cost as zero. ${error.message}`);
|
|
90
|
+
return 0;
|
|
91
|
+
}
|
|
92
|
+
}
|
|
93
|
+
/** Groups inputs so no request passes either of the provider's limits. */
|
|
94
|
+
function batch(inputs) {
|
|
95
|
+
const batches = [];
|
|
96
|
+
let current = [];
|
|
97
|
+
let estimate = 0;
|
|
98
|
+
for (const input of inputs) {
|
|
99
|
+
const tokens = Math.ceil(input.length / CHARS_PER_TOKEN_ESTIMATE);
|
|
100
|
+
if (current.length && (current.length >= MAX_INPUTS_PER_REQUEST || estimate + tokens > MAX_ESTIMATED_TOKENS_PER_REQUEST)) {
|
|
101
|
+
batches.push(current);
|
|
102
|
+
current = [];
|
|
103
|
+
estimate = 0;
|
|
104
|
+
}
|
|
105
|
+
current.push(input);
|
|
106
|
+
estimate += tokens;
|
|
107
|
+
}
|
|
108
|
+
if (current.length) {
|
|
109
|
+
batches.push(current);
|
|
110
|
+
}
|
|
111
|
+
return batches;
|
|
112
|
+
}
|
|
113
|
+
let defaultProvider = null;
|
|
114
|
+
/** OpenAI, constructed on first use so a host that never embeds needs no key. */
|
|
115
|
+
function openAiProvider() {
|
|
116
|
+
if (defaultProvider) {
|
|
117
|
+
return defaultProvider;
|
|
118
|
+
}
|
|
119
|
+
const apiKey = process.env.OPENAI_API_KEY;
|
|
120
|
+
if (!apiKey) {
|
|
121
|
+
throw new Error('Embedding needs OPENAI_API_KEY, or an EmbeddingProvider passed in the options.');
|
|
122
|
+
}
|
|
123
|
+
const client = new openai_1.default({
|
|
124
|
+
apiKey,
|
|
125
|
+
maxRetries: 4,
|
|
126
|
+
timeout: 120_000,
|
|
127
|
+
...(process.env.OPENAI_ORGANIZATION_ID && { organization: process.env.OPENAI_ORGANIZATION_ID }),
|
|
128
|
+
});
|
|
129
|
+
defaultProvider = {
|
|
130
|
+
async embed(texts, model, dimensions) {
|
|
131
|
+
// Sent only to shorten a model's native vectors: a model that cannot
|
|
132
|
+
// shorten them rejects the parameter even when it matches.
|
|
133
|
+
let native;
|
|
134
|
+
try {
|
|
135
|
+
native = (0, model_prices_1.resolveModelInfo)(model)?.output_vector_size;
|
|
136
|
+
}
|
|
137
|
+
catch {
|
|
138
|
+
native = undefined; // no price table: send nothing, take the model's own size
|
|
139
|
+
}
|
|
140
|
+
const response = await client.embeddings.create({
|
|
141
|
+
model,
|
|
142
|
+
input: texts,
|
|
143
|
+
...(native && native !== dimensions ? { dimensions } : {}),
|
|
144
|
+
});
|
|
145
|
+
// The API documents `index`; order by it rather than trusting array order.
|
|
146
|
+
const ordered = [...response.data].sort((a, b) => a.index - b.index);
|
|
147
|
+
return { vectors: ordered.map((item) => item.embedding), tokens: response.usage?.total_tokens ?? 0 };
|
|
148
|
+
},
|
|
149
|
+
};
|
|
150
|
+
return defaultProvider;
|
|
151
|
+
}
|
|
@@ -19,6 +19,10 @@
|
|
|
19
19
|
* copy of a directory listing drifts from it — which is the mistake
|
|
20
20
|
* `prompt-folders.spec.ts` exists to catch in the D&D prompts.
|
|
21
21
|
*
|
|
22
|
+
* {@link PackTable} is the exception, and it is one because it declares a *choice*
|
|
23
|
+
* rather than a listing: a pack ships several room templates and nothing on disk
|
|
24
|
+
* says which of them the RPG page should build.
|
|
25
|
+
*
|
|
22
26
|
* `pack.json` is optional. A directory holding only `artifacts/manifest.json` is
|
|
23
27
|
* still a pack, titled after itself.
|
|
24
28
|
*/
|
|
@@ -51,7 +55,47 @@ export interface PackManifest {
|
|
|
51
55
|
* never an auto-enable, never a block.
|
|
52
56
|
*/
|
|
53
57
|
requiresPacks?: string[];
|
|
58
|
+
/** What the RPG page builds from this pack. Absent means it is not a game pack. */
|
|
59
|
+
table?: PackTable;
|
|
60
|
+
}
|
|
61
|
+
/**
|
|
62
|
+
* How a pack is played from the RPG page.
|
|
63
|
+
*
|
|
64
|
+
* The RPG page exists to reduce a table to two decisions — who is playing and how
|
|
65
|
+
* good the models are — so it needs one room template to build and one agent
|
|
66
|
+
* template to seat a party from. A pack ships several of each and nothing on disk
|
|
67
|
+
* distinguishes them: `rooms/table.json` and `rooms/campaign.json` are both real
|
|
68
|
+
* D&D tables, and only one of them is the one to build when the party is chosen
|
|
69
|
+
* separately. So this is declared, and everything a declaration would duplicate —
|
|
70
|
+
* the prompt folder a seat comes from, which crew agents are expensive, what the
|
|
71
|
+
* seats are called — is derived from the templates it names.
|
|
72
|
+
*
|
|
73
|
+
* A pack without one is not offered, which is every pack but a game.
|
|
74
|
+
*/
|
|
75
|
+
export interface PackTable {
|
|
76
|
+
/**
|
|
77
|
+
* The room template to build: the crew, and **no player seats**.
|
|
78
|
+
*
|
|
79
|
+
* Player-less because the RPG page seats the party itself, one agent at a time,
|
|
80
|
+
* so each AI player can have its own model and its own personality. A template
|
|
81
|
+
* that seats a player would have the party arrive twice.
|
|
82
|
+
*/
|
|
83
|
+
room: string;
|
|
84
|
+
/** The agent template one seat is created from, and the roster discriminator. */
|
|
85
|
+
playerAgent: string;
|
|
86
|
+
/** What one player is called: `Player`, `Student`. Defaults to `Player`. */
|
|
87
|
+
playerNoun: string;
|
|
88
|
+
/** How many the table seats. Defaults to {@link MAX_TABLE_SEATS}. */
|
|
89
|
+
maxPlayers: number;
|
|
54
90
|
}
|
|
91
|
+
/**
|
|
92
|
+
* The most seats a pack may ask for.
|
|
93
|
+
*
|
|
94
|
+
* Not a technical limit — the room does not care. But every player is another agent
|
|
95
|
+
* perceiving every message, and a pack asking for forty has made a mistake rather
|
|
96
|
+
* than a choice.
|
|
97
|
+
*/
|
|
98
|
+
export declare const MAX_TABLE_SEATS = 12;
|
|
55
99
|
/**
|
|
56
100
|
* One agent a pack ships, as a reference to a prompt folder plus overrides.
|
|
57
101
|
*
|
|
@@ -146,6 +190,8 @@ export interface LoadedPack {
|
|
|
146
190
|
/** Tool names the pack's grants and manifest between them ask for. */
|
|
147
191
|
requiresTools: string[];
|
|
148
192
|
requiresPacks: string[];
|
|
193
|
+
/** How the RPG page plays it, when the pack says. Absent for a pack that is not a game. */
|
|
194
|
+
table?: PackTable;
|
|
149
195
|
}
|
|
150
196
|
export type PackOrigin = 'host' | 'user';
|
|
151
197
|
/**
|
|
@@ -20,6 +20,10 @@
|
|
|
20
20
|
* copy of a directory listing drifts from it — which is the mistake
|
|
21
21
|
* `prompt-folders.spec.ts` exists to catch in the D&D prompts.
|
|
22
22
|
*
|
|
23
|
+
* {@link PackTable} is the exception, and it is one because it declares a *choice*
|
|
24
|
+
* rather than a listing: a pack ships several room templates and nothing on disk
|
|
25
|
+
* says which of them the RPG page should build.
|
|
26
|
+
*
|
|
23
27
|
* `pack.json` is optional. A directory holding only `artifacts/manifest.json` is
|
|
24
28
|
* still a pack, titled after itself.
|
|
25
29
|
*/
|
|
@@ -57,7 +61,7 @@ var __importStar = (this && this.__importStar) || (function () {
|
|
|
57
61
|
};
|
|
58
62
|
})();
|
|
59
63
|
Object.defineProperty(exports, "__esModule", { value: true });
|
|
60
|
-
exports.PACK_SUBDIR = void 0;
|
|
64
|
+
exports.MAX_TABLE_SEATS = exports.PACK_SUBDIR = void 0;
|
|
61
65
|
exports.readPack = readPack;
|
|
62
66
|
exports.roomAgentKey = roomAgentKey;
|
|
63
67
|
const fs = __importStar(require("fs"));
|
|
@@ -71,6 +75,14 @@ exports.PACK_SUBDIR = {
|
|
|
71
75
|
agents: 'agents',
|
|
72
76
|
rooms: 'rooms',
|
|
73
77
|
};
|
|
78
|
+
/**
|
|
79
|
+
* The most seats a pack may ask for.
|
|
80
|
+
*
|
|
81
|
+
* Not a technical limit — the room does not care. But every player is another agent
|
|
82
|
+
* perceiving every message, and a pack asking for forty has made a mistake rather
|
|
83
|
+
* than a choice.
|
|
84
|
+
*/
|
|
85
|
+
exports.MAX_TABLE_SEATS = 12;
|
|
74
86
|
/**
|
|
75
87
|
* Reads a pack directory.
|
|
76
88
|
*
|
|
@@ -93,6 +105,7 @@ function readPack(dir, name, origin) {
|
|
|
93
105
|
return null;
|
|
94
106
|
}
|
|
95
107
|
const manifest = readManifest(dir, name);
|
|
108
|
+
const table = manifest?.table ? validateTable(manifest.table, dir) : null;
|
|
96
109
|
const agents = readTemplates(dir, exports.PACK_SUBDIR.agents, validateAgentTemplate);
|
|
97
110
|
const rooms = readTemplates(dir, exports.PACK_SUBDIR.rooms, validateRoomTemplate);
|
|
98
111
|
const promptFolders = subdirectoriesOf(path.join(dir, exports.PACK_SUBDIR.prompts));
|
|
@@ -108,6 +121,7 @@ function readPack(dir, name, origin) {
|
|
|
108
121
|
rooms,
|
|
109
122
|
requiresTools: deriveRequiredTools(dir, promptFolders, agents, manifest),
|
|
110
123
|
requiresPacks: (manifest?.requiresPacks ?? []).filter(prompt_resolver_1.isValidPackName),
|
|
124
|
+
...(table && { table }),
|
|
111
125
|
};
|
|
112
126
|
}
|
|
113
127
|
/**
|
|
@@ -233,6 +247,37 @@ function sanitizeOverrides(overrides, file) {
|
|
|
233
247
|
}
|
|
234
248
|
return clean;
|
|
235
249
|
}
|
|
250
|
+
/**
|
|
251
|
+
* Reads the `table` block, or drops it with a warning.
|
|
252
|
+
*
|
|
253
|
+
* Dropped rather than thrown, as a malformed template is: a `table` a host mistyped
|
|
254
|
+
* costs them the pack's row in the RPG page's game picker, not the whole pack. The
|
|
255
|
+
* keys it names are resolved where they are used, so a `room` that does not exist
|
|
256
|
+
* is caught with the rest of the roster rather than twice.
|
|
257
|
+
*/
|
|
258
|
+
function validateTable(value, dir) {
|
|
259
|
+
const where = `${dir}/pack.json`;
|
|
260
|
+
if (!value || typeof value !== 'object') {
|
|
261
|
+
logger_1.logger.warn(`Ignoring "table" in ${where}: expected a JSON object`);
|
|
262
|
+
return null;
|
|
263
|
+
}
|
|
264
|
+
if (!isValidKey(value.room) || !isValidKey(value.playerAgent)) {
|
|
265
|
+
logger_1.logger.warn(`Ignoring "table" in ${where}: "room" and "playerAgent" must both name a template`);
|
|
266
|
+
return null;
|
|
267
|
+
}
|
|
268
|
+
const noun = typeof value.playerNoun === 'string' ? value.playerNoun.trim() : '';
|
|
269
|
+
const seats = Number(value.maxPlayers);
|
|
270
|
+
const seatable = Number.isInteger(seats) && seats >= 1 && seats <= exports.MAX_TABLE_SEATS;
|
|
271
|
+
if (value.maxPlayers !== undefined && !seatable) {
|
|
272
|
+
logger_1.logger.warn(`Seating ${exports.MAX_TABLE_SEATS} at ${where}'s table: "maxPlayers" must be 1 to ${exports.MAX_TABLE_SEATS}`);
|
|
273
|
+
}
|
|
274
|
+
return {
|
|
275
|
+
room: value.room,
|
|
276
|
+
playerAgent: value.playerAgent,
|
|
277
|
+
playerNoun: noun || 'Player',
|
|
278
|
+
maxPlayers: seatable ? seats : exports.MAX_TABLE_SEATS,
|
|
279
|
+
};
|
|
280
|
+
}
|
|
236
281
|
function validateRoomTemplate(value, file) {
|
|
237
282
|
if (!value || typeof value !== 'object') {
|
|
238
283
|
logger_1.logger.warn(`Ignoring ${file}: expected a JSON object`);
|