@cslug/ai 0.5.0 → 0.6.0
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/docs/README.md +56 -2
- package/docs/api.md +8 -0
- package/package.json +12 -7
- package/src/agent.ts +64 -11
- package/src/ai-provider.ts +52 -3
- package/src/ai.ts +16 -4
- package/src/conversations.ts +44 -8
- package/src/embedders.ts +133 -0
- package/src/fake.ts +9 -0
- package/src/index.ts +21 -1
- package/src/search-tools.ts +163 -0
package/docs/README.md
CHANGED
|
@@ -6,13 +6,13 @@ List `AiProvider` in `bootstrap/providers.ts` (`cslug add ai` does it and writes
|
|
|
6
6
|
## Agents
|
|
7
7
|
|
|
8
8
|
An agent is an `@inject()` class with a `model` (a model ID, or a role from `ai.models`) and, optionally,
|
|
9
|
-
`instructions` (a string
|
|
9
|
+
`instructions` (a string, `prompt('name')`, or a function of the context), `output` (a `v` schema), `tools`, `maxSteps` (8), `provider`,
|
|
10
10
|
`effort` and `maxTokens`. These settings are not declared on `Agent`, as for jobs, so apps compiled with
|
|
11
11
|
`noImplicitOverride` don't write `override`.
|
|
12
12
|
|
|
13
13
|
`run({ input, context })`:
|
|
14
14
|
|
|
15
|
-
1. renders the instructions
|
|
15
|
+
1. renders the instructions: a function is called with `context` (and awaited); a prompt file is filled from it,
|
|
16
16
|
2. calls the provider with the tools and, with `output`, the schema as structured output (the JSON Schema without
|
|
17
17
|
the constraints the API rejects: numeric and length limits, patterns, array sizes),
|
|
18
18
|
3. while the model calls tools: validates each input with the tool's schema, runs the calls of the turn together and
|
|
@@ -62,6 +62,21 @@ turns it on for plain runs. Timestamps come from `Clock`.
|
|
|
62
62
|
`ai.runs: false` turns it off, and a failure to record is logged (`ai.run_not_recorded`), never thrown. Without
|
|
63
63
|
@cslug/database nothing is recorded, and `Conversations` throws `ai.no_database`.
|
|
64
64
|
|
|
65
|
+
## Prompts
|
|
66
|
+
|
|
67
|
+
`prompt('trips/brief')` reads `resources/prompts/trips/brief.md` on every run and fills it with `fillPrompt`:
|
|
68
|
+
|
|
69
|
+
| In the file | Gives |
|
|
70
|
+
|---|---|
|
|
71
|
+
| `{{ name }}` | `context.name`: a string as is, a number or boolean as text, a `Date` as ISO, an object or a list as indented JSON (bigint as text) |
|
|
72
|
+
| `{{ trip.circuit.name }}` | A nested value (each step must be an object) |
|
|
73
|
+
| `{{ language \| English }}` | The value, or `English` when it is missing or null (`{{ note \| }}`: empty) |
|
|
74
|
+
|
|
75
|
+
A missing value without a default throws `ai.prompt_variables` listing every one; a present `null` without a
|
|
76
|
+
default renders empty. `cslug ai:prompts` lists each file and its variables, with `?` after those that have a
|
|
77
|
+
default. `PROMPT_VARIABLE` is the pattern (path, default); `renderInstructions(instructions, context)` gives the
|
|
78
|
+
system prompt for any `Instructions`.
|
|
79
|
+
|
|
65
80
|
## Providers
|
|
66
81
|
|
|
67
82
|
| Driver | Config | |
|
|
@@ -75,6 +90,45 @@ Without `config/ai.ts`, the default provider is `anthropic`. `ai.extend(name, pr
|
|
|
75
90
|
`ai.result(agent, { input, context })` is `run()` in detail: `{ value, raw, model, steps, usage, costUsd }` (`raw` is
|
|
76
91
|
the answer before validation: the parsed JSON, or the text).
|
|
77
92
|
|
|
93
|
+
## Search tools (with @cslug/search)
|
|
94
|
+
|
|
95
|
+
`tools` accepts tool objects besides classes and MCP tools.
|
|
96
|
+
|
|
97
|
+
- `searchTool(index, { name = 'search_<index>', description, perPage = 5, filter, words = 40 })`: input
|
|
98
|
+
`{ query, page? }`; result `{ results: [{ key, title, snippet, metadata }], total, page, lastPage }`, snippets as
|
|
99
|
+
plain text (marks removed, entities decoded). `index` is any `searchIndex()` (typed structurally as
|
|
100
|
+
`SearchableIndex`).
|
|
101
|
+
- `ai.recall: true` (or `{ index }`): each stored turn's text messages (user and assistant, not tool rounds) are
|
|
102
|
+
upserted into a search index, `ai-conversations` by default, semantic when an `Embedder` is bound, keyed
|
|
103
|
+
`<conversation>:<position>` with `{ ownerType, ownerId, conversationId, role }` metadata. Unowned conversations
|
|
104
|
+
are not kept. A failure to index is logged (`ai.recall_failed`), never thrown into the turn. `chat.delete()`
|
|
105
|
+
removes its entries.
|
|
106
|
+
- `recallTool({ perPage = 5 })`: `{ query }` → `{ results: [{ conversationId, role, text }] }`, searched within the
|
|
107
|
+
current conversation's owner (from the ambient context `Conversation.send` / `stream` set: `currentConversation()`),
|
|
108
|
+
the current conversation left out. Outside a stored conversation it answers that there is nothing to search.
|
|
109
|
+
|
|
110
|
+
## Embeddings (for @cslug/search)
|
|
111
|
+
|
|
112
|
+
```ts
|
|
113
|
+
embeddings: { driver: 'voyage', model: 'voyage-3.5' }, // VOYAGE_API_KEY
|
|
114
|
+
embeddings: { driver: 'openai-compatible', baseUrl: 'https://api.openai.com/v1', apiKey: env.OPENAI_API_KEY,
|
|
115
|
+
model: 'text-embedding-3-small', dimensions: 512 },
|
|
116
|
+
embeddings: { driver: 'openai-compatible', baseUrl: 'http://localhost:11434/v1', model: 'nomic-embed-text' }, // Ollama
|
|
117
|
+
```
|
|
118
|
+
|
|
119
|
+
With `ai.embeddings` and `@cslug/search` installed, `AiProvider` binds search's `Embedder` (semantic indexes use it).
|
|
120
|
+
Anthropic has no embeddings API; Voyage is the provider it recommends.
|
|
121
|
+
|
|
122
|
+
- `voyage`: `POST {baseUrl}/embeddings` with `input_type` (`document` for indexed texts, `query` for searches) and
|
|
123
|
+
`output_dimension` from `dimensions`.
|
|
124
|
+
- `openai-compatible`: `POST {baseUrl}/embeddings` `{ model, input, dimensions? }`.
|
|
125
|
+
- The vectors' `model` includes the dimensions (`voyage-3.5@512`), so changing either re-embeds documents.
|
|
126
|
+
- Calls are checked against and charged to the daily budget, as input tokens of `model`. There are no built-in
|
|
127
|
+
prices for embedding models: add yours to `ai.prices` (`{ 'voyage-3.5': { input: <USD per million>, output: 0 } }`),
|
|
128
|
+
otherwise the calls are logged once as unpriced and cost nothing in the budget.
|
|
129
|
+
- `testApp({ fakes: ['ai'] })` also swaps the bound `Embedder` for a `FakeEmbedder`, so a test never calls the
|
|
130
|
+
provider.
|
|
131
|
+
|
|
78
132
|
## Daily budget
|
|
79
133
|
|
|
80
134
|
```ts
|
package/docs/api.md
CHANGED
|
@@ -7,6 +7,8 @@
|
|
|
7
7
|
| `AiStream` | Async iterable of text; `result: Promise<AiResult>`, settled once the text is read |
|
|
8
8
|
| `Tool` | Abstract `name`, `description`, `input` (a `v` schema), `handle(input)` |
|
|
9
9
|
| `prompt(name)` / `Prompt` | `resources/prompts/<name>.md`; `render(vars)`, `ai.prompt_variables` when one is missing |
|
|
10
|
+
| `fillPrompt(template, vars, name?)` | `{{ path }}` (nested, objects as JSON), `{{ path \| default }}`; `PROMPT_VARIABLE` |
|
|
11
|
+
| `Instructions`, `renderInstructions(instructions, context)` | `string \| Prompt \| (context) => string \| Prompt` (or a promise of one); the system prompt for a run |
|
|
10
12
|
| `Ai` | Injectable runtime: `run(agent, options)`, `result(agent, options, meta?)` → `AiResult`, `stream(agent, options, meta?)`, `provider(name?)`, `extend(name, provider)`, `budget`, `recorder` |
|
|
11
13
|
| `AiResult` | `{ runId, value, raw, model, steps, usage, costUsd, messages }` |
|
|
12
14
|
| `Conversations` | `start(Agent, options)`, `find(Agent, id, options)`, `list(options)`; `store` (set with @cslug/database) |
|
|
@@ -33,4 +35,10 @@
|
|
|
33
35
|
| `handleMcp(message, tools, caller)` | One MCP message → its reply, over the `@mcp()` tools `caller` may use (core's `handleMcpMessage`); `asMcpTools(tools, caller)`, `MCP_VERSIONS`, `discoverTools(app)`, `mcpTools()` |
|
|
34
36
|
| `McpServeCommand` | `cslug mcp:serve` (stdio) |
|
|
35
37
|
| `AiFake`, `installAiFake(app)` | `fakes: ['ai']`: `respond`, `fixture(Agent, name)`, `assertRan`, `assertNotRan`, `ran`, `runs` |
|
|
38
|
+
| `searchTool(index, options?)`, `SearchToolOptions`, `SearchableIndex` | A tool object searching a `@cslug/search` index |
|
|
39
|
+
| `recallTool(options?)` | Search the current conversation owner's earlier conversations (`ai.recall`) |
|
|
40
|
+
| `currentConversation()`, `CONVERSATION_KEY`, `ConversationScope` | The conversation a run belongs to (`{ id, owner }`), in the ambient context |
|
|
41
|
+
| `EmbeddingsConfig`, `embedderFor(config, budget?)` | `config/ai.ts` → `embeddings`: `{ driver: 'voyage' \| 'openai-compatible', model, dimensions?, apiKey?, baseUrl? }`; the embedder for it |
|
|
42
|
+
| `VoyageEmbedder`, `OpenAiCompatibleEmbedder`, `TextEmbedder` | The drivers (`model`, `embed(texts, purpose)`), charged to the budget |
|
|
43
|
+
| `setFakeEmbedder(token, create)` | Set by `AiProvider`: what `installAiFake` swaps the bound `Embedder` for |
|
|
36
44
|
| `AiFixture`, `FIXTURES_DIR` | A fixture file's shape (`history` when the run continued one); `tests/fixtures/ai` |
|
package/package.json
CHANGED
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "@cslug/ai",
|
|
3
|
-
"version": "0.
|
|
3
|
+
"version": "0.6.0",
|
|
4
4
|
"description": "Agents and tools, structured output, prompts, streaming; Anthropic and OpenAI-compatible providers.",
|
|
5
5
|
"license": "MIT",
|
|
6
6
|
"type": "module",
|
|
@@ -29,11 +29,12 @@
|
|
|
29
29
|
"bun": ">=1.3.14"
|
|
30
30
|
},
|
|
31
31
|
"peerDependencies": {
|
|
32
|
-
"@cslug/core": "0.
|
|
33
|
-
"@cslug/validation": "0.
|
|
34
|
-
"@cslug/queue": "0.
|
|
35
|
-
"@cslug/http": "0.
|
|
36
|
-
"@cslug/database": "0.
|
|
32
|
+
"@cslug/core": "0.6.0",
|
|
33
|
+
"@cslug/validation": "0.6.0",
|
|
34
|
+
"@cslug/queue": "0.6.0",
|
|
35
|
+
"@cslug/http": "0.6.0",
|
|
36
|
+
"@cslug/database": "0.6.0",
|
|
37
|
+
"@cslug/search": "0.6.0"
|
|
37
38
|
},
|
|
38
39
|
"peerDependenciesMeta": {
|
|
39
40
|
"@cslug/queue": {
|
|
@@ -44,11 +45,15 @@
|
|
|
44
45
|
},
|
|
45
46
|
"@cslug/database": {
|
|
46
47
|
"optional": true
|
|
48
|
+
},
|
|
49
|
+
"@cslug/search": {
|
|
50
|
+
"optional": true
|
|
47
51
|
}
|
|
48
52
|
},
|
|
49
53
|
"devDependencies": {
|
|
50
54
|
"@cslug/testing": "workspace:*",
|
|
51
55
|
"@cslug/http": "workspace:*",
|
|
52
|
-
"@cslug/database": "workspace:*"
|
|
56
|
+
"@cslug/database": "workspace:*",
|
|
57
|
+
"@cslug/search": "workspace:*"
|
|
53
58
|
}
|
|
54
59
|
}
|
package/src/agent.ts
CHANGED
|
@@ -8,6 +8,44 @@ import type { AiStream } from './ai-stream'
|
|
|
8
8
|
import type { McpTools } from './mcp-client'
|
|
9
9
|
import type { Effort, Message } from './model'
|
|
10
10
|
|
|
11
|
+
/** `{{ path }}` or `{{ path | default }}`: a dotted path into the context, and an optional fallback text. */
|
|
12
|
+
export const PROMPT_VARIABLE = /\{\{\s*([\w]+(?:\.[\w]+)*)\s*(?:\|\s*([^}]*?)\s*)?\}\}/g
|
|
13
|
+
|
|
14
|
+
const lookup = (vars: Record<string, unknown>, path: string): { found: boolean; value: unknown } => {
|
|
15
|
+
let value: unknown = vars
|
|
16
|
+
for (const key of path.split('.')) {
|
|
17
|
+
if (value === null || typeof value !== 'object' || !(key in value)) return { found: false, value: undefined }
|
|
18
|
+
value = (value as Record<string, unknown>)[key]
|
|
19
|
+
}
|
|
20
|
+
return { found: true, value }
|
|
21
|
+
}
|
|
22
|
+
|
|
23
|
+
const asText = (value: unknown): string =>
|
|
24
|
+
typeof value === 'string'
|
|
25
|
+
? value
|
|
26
|
+
: value !== null && typeof value === 'object' && !(value instanceof Date)
|
|
27
|
+
? JSON.stringify(value, (_k, x) => (typeof x === 'bigint' ? x.toString() : x), 2)
|
|
28
|
+
: String(value instanceof Date ? value.toISOString() : value)
|
|
29
|
+
|
|
30
|
+
/**
|
|
31
|
+
* Fill a prompt template: `{{ trip.circuit }}` reads a nested value, an object or a list is written as JSON,
|
|
32
|
+
* `{{ language | English }}` falls back when the value is missing or null. A missing value without a default is
|
|
33
|
+
* an `ai.prompt_variables` error naming every one.
|
|
34
|
+
*/
|
|
35
|
+
export function fillPrompt(template: string, vars: Record<string, unknown>, name = 'prompt'): string {
|
|
36
|
+
const missing = new Set<string>()
|
|
37
|
+
const text = template.replace(PROMPT_VARIABLE, (_m, path: string, fallback: string | undefined) => {
|
|
38
|
+
const { found, value } = lookup(vars, path)
|
|
39
|
+
if (found && value !== null && value !== undefined) return asText(value)
|
|
40
|
+
if (fallback !== undefined) return fallback
|
|
41
|
+
if (!found) missing.add(path)
|
|
42
|
+
return ''
|
|
43
|
+
})
|
|
44
|
+
if (missing.size)
|
|
45
|
+
throw new CslugError('ai.prompt_variables', `Prompt ${name} needs ${[...missing].join(', ')} in context`)
|
|
46
|
+
return text
|
|
47
|
+
}
|
|
48
|
+
|
|
11
49
|
/** A prompt file, `resources/prompts/<name>.md`, with `{{ variables }}` filled from the run's `context`. */
|
|
12
50
|
export class Prompt {
|
|
13
51
|
constructor(readonly name: string) {}
|
|
@@ -18,17 +56,25 @@ export class Prompt {
|
|
|
18
56
|
|
|
19
57
|
render(vars: Record<string, unknown> = {}): string {
|
|
20
58
|
if (!existsSync(this.path)) throw new CslugError('ai.no_prompt', `No prompt file resources/prompts/${this.name}.md`)
|
|
21
|
-
|
|
22
|
-
const text = readFileSync(this.path, 'utf8').replace(/\{\{\s*([\w.]+)\s*\}\}/g, (_m, key: string) => {
|
|
23
|
-
if (!(key in vars)) missing.add(key)
|
|
24
|
-
return String(vars[key] ?? '')
|
|
25
|
-
})
|
|
26
|
-
if (missing.size)
|
|
27
|
-
throw new CslugError('ai.prompt_variables', `Prompt ${this.name} needs ${[...missing].join(', ')} in context`)
|
|
28
|
-
return text
|
|
59
|
+
return fillPrompt(readFileSync(this.path, 'utf8'), vars, this.name)
|
|
29
60
|
}
|
|
30
61
|
}
|
|
31
62
|
|
|
63
|
+
/** What an agent's `instructions` may be. */
|
|
64
|
+
export type Instructions =
|
|
65
|
+
| string
|
|
66
|
+
| Prompt
|
|
67
|
+
| ((context: Record<string, unknown>) => string | Prompt | Promise<string | Prompt>)
|
|
68
|
+
|
|
69
|
+
/** The system prompt for a run: a function is called with the context, a `Prompt` is filled from it. */
|
|
70
|
+
export async function renderInstructions(
|
|
71
|
+
instructions: Instructions | undefined,
|
|
72
|
+
context: Record<string, unknown>,
|
|
73
|
+
): Promise<string> {
|
|
74
|
+
const value = typeof instructions === 'function' ? await instructions(context) : (instructions ?? '')
|
|
75
|
+
return typeof value === 'string' ? value : value.render(context)
|
|
76
|
+
}
|
|
77
|
+
|
|
32
78
|
/** `instructions = prompt('proposals/extract-offer')` → `resources/prompts/proposals/extract-offer.md`. */
|
|
33
79
|
export const prompt = (name: string) => new Prompt(name)
|
|
34
80
|
|
|
@@ -70,11 +116,18 @@ export type RunOptions = {
|
|
|
70
116
|
export type AgentSettings = {
|
|
71
117
|
/** A model ID (`claude-opus-5-5`), or a role from config `ai.models` (`fast`, `smart`). */
|
|
72
118
|
model: string
|
|
73
|
-
|
|
119
|
+
/**
|
|
120
|
+
* A string, `prompt('name')` (a file with `{{ variables }}`), or a function of the run's `context` returning
|
|
121
|
+
* either (it may be async), for instructions built in code.
|
|
122
|
+
*/
|
|
123
|
+
instructions?: Instructions
|
|
74
124
|
/** Structured output: the answer is parsed and validated (`AiOutputError` otherwise). */
|
|
75
125
|
output?: Schema<unknown>
|
|
76
|
-
/**
|
|
77
|
-
|
|
126
|
+
/**
|
|
127
|
+
* Tool classes, MCP servers' tools and tool objects: `tools = [FindOperatorsTool,
|
|
128
|
+
* ...mcp('maps').tools(['route_duration']), searchTool(helpIndex), recallTool()]`.
|
|
129
|
+
*/
|
|
130
|
+
tools?: (ToolClass | McpTools | RunnableTool)[]
|
|
78
131
|
/** Model calls before giving up (each tool round is one); default 8. */
|
|
79
132
|
maxSteps?: number
|
|
80
133
|
/** A provider from config `ai.providers` (default: `ai.default`). */
|
package/src/ai-provider.ts
CHANGED
|
@@ -1,12 +1,23 @@
|
|
|
1
1
|
import { existsSync, readdirSync, readFileSync } from 'node:fs'
|
|
2
2
|
import { join } from 'node:path'
|
|
3
|
-
import { arg, Command, flag, Logger, resolve, ServiceProvider, serveMcpStdio } from '@cslug/core'
|
|
3
|
+
import { arg, Command, flag, Logger, resolve, ServiceProvider, serveMcpStdio, type Token } from '@cslug/core'
|
|
4
4
|
import type { HttpContext } from '@cslug/http'
|
|
5
|
+
import { PROMPT_VARIABLE } from './agent'
|
|
5
6
|
import { Ai, type AiConfig } from './ai'
|
|
6
7
|
import { AiEvalCommand } from './ai-eval-command'
|
|
7
8
|
import { databaseStore } from './conversation-store'
|
|
8
9
|
import { Conversations } from './conversations'
|
|
10
|
+
import { embedderFor, type TextEmbedder } from './embedders'
|
|
11
|
+
import { setFakeEmbedder } from './fake'
|
|
9
12
|
import { asMcpTools, discoverTools, handleMcp, type McpCaller, type McpReply, mcpTools } from './mcp'
|
|
13
|
+
import type { SearchableIndex } from './search-tools'
|
|
14
|
+
|
|
15
|
+
/** What this package uses of @cslug/search (an optional peer, imported only when installed). */
|
|
16
|
+
type SearchModule = {
|
|
17
|
+
Embedder: Token<TextEmbedder>
|
|
18
|
+
FakeEmbedder: new () => TextEmbedder
|
|
19
|
+
SearchIndex: new (name: string, options: { semantic?: boolean }) => SearchableIndex
|
|
20
|
+
}
|
|
10
21
|
|
|
11
22
|
/**
|
|
12
23
|
* `cslug mcp:serve`: the `@mcp()` tools over stdio, for a local client (every exposed tool: the caller is whoever
|
|
@@ -40,7 +51,11 @@ export class AiPromptsCommand extends Command {
|
|
|
40
51
|
.map((f) => ({
|
|
41
52
|
prompt: f.replace(/\.md$/, ''),
|
|
42
53
|
variables: [
|
|
43
|
-
...new Set(
|
|
54
|
+
...new Set(
|
|
55
|
+
[...readFileSync(join(dir, f), 'utf8').matchAll(PROMPT_VARIABLE)].map((m) =>
|
|
56
|
+
m[2] === undefined ? m[1] : `${m[1]}?`,
|
|
57
|
+
),
|
|
58
|
+
),
|
|
44
59
|
].join(', '),
|
|
45
60
|
}))
|
|
46
61
|
: []
|
|
@@ -75,7 +90,8 @@ export class AiRecordCommand extends Command {
|
|
|
75
90
|
}
|
|
76
91
|
|
|
77
92
|
/**
|
|
78
|
-
* Binds `Ai` from `config/ai.ts` (`default`, `providers`, `models`, `mcp`, `budget`, `prices`, `runs
|
|
93
|
+
* Binds `Ai` from `config/ai.ts` (`default`, `providers`, `models`, `mcp`, `budget`, `prices`, `runs`,
|
|
94
|
+
* `embeddings`: @cslug/search's `Embedder` when it is installed) and
|
|
79
95
|
* `Conversations`; contributes `ai:prompts`, `ai:record`, `ai:eval` and `mcp:serve`. With @cslug/database: the
|
|
80
96
|
* `cslug_ai_*` tables, stored conversations and a record per run.
|
|
81
97
|
* With `@mcp()` tools in `app/tools/` and @cslug/http installed: `POST /mcp` (streamable HTTP, in the api group's
|
|
@@ -92,6 +108,8 @@ export class AiProvider extends ServiceProvider {
|
|
|
92
108
|
}
|
|
93
109
|
|
|
94
110
|
async boot() {
|
|
111
|
+
await this.bindEmbedder()
|
|
112
|
+
await this.recallIndex()
|
|
95
113
|
const store = await databaseStore(this.app)
|
|
96
114
|
if (store) {
|
|
97
115
|
this.app.resolve(Conversations).store = store
|
|
@@ -111,6 +129,37 @@ export class AiProvider extends ServiceProvider {
|
|
|
111
129
|
)
|
|
112
130
|
}
|
|
113
131
|
|
|
132
|
+
/** With `ai.embeddings` and @cslug/search installed: its `Embedder`, from the configured driver. */
|
|
133
|
+
private async bindEmbedder() {
|
|
134
|
+
const config = this.app.config<AiConfig | undefined>('ai')?.embeddings
|
|
135
|
+
if (!config) return
|
|
136
|
+
// a variable specifier: apps without @cslug/search still type-check (TypeScript does not resolve it)
|
|
137
|
+
const specifier = '@cslug/search'
|
|
138
|
+
const search = (await import(specifier).catch(() => undefined)) as SearchModule | undefined
|
|
139
|
+
if (!search) {
|
|
140
|
+
this.app.resolve(Logger).warn('ai.embeddings_unused', { reason: '@cslug/search is not installed' })
|
|
141
|
+
return
|
|
142
|
+
}
|
|
143
|
+
const embedder = embedderFor(config, () => this.app.resolve(Ai).budget)
|
|
144
|
+
this.app.instance(search.Embedder, embedder)
|
|
145
|
+
// tests (`fakes: ['ai']`) swap it for a FakeEmbedder: no paid call from a test
|
|
146
|
+
setFakeEmbedder(search.Embedder, () => new search.FakeEmbedder())
|
|
147
|
+
}
|
|
148
|
+
|
|
149
|
+
/** With `ai.recall`: the index conversations' turns are kept in (semantic when an embedder is bound). */
|
|
150
|
+
private async recallIndex() {
|
|
151
|
+
const recall = this.app.config<AiConfig | undefined>('ai')?.recall
|
|
152
|
+
if (!recall) return
|
|
153
|
+
const specifier = '@cslug/search'
|
|
154
|
+
const search = (await import(specifier).catch(() => undefined)) as SearchModule | undefined
|
|
155
|
+
if (!search) {
|
|
156
|
+
this.app.resolve(Logger).warn('ai.recall_unused', { reason: '@cslug/search is not installed' })
|
|
157
|
+
return
|
|
158
|
+
}
|
|
159
|
+
const name = (typeof recall === 'object' && recall.index) || 'ai-conversations'
|
|
160
|
+
this.app.resolve(Ai).recallIndex = new search.SearchIndex(name, { semantic: this.app.has(search.Embedder) })
|
|
161
|
+
}
|
|
162
|
+
|
|
114
163
|
/** One MCP message over HTTP: Origin checked (DNS rebinding), notifications 202, JSON responses. */
|
|
115
164
|
private async mcpHttp(ctx: HttpContext, info: { name: string; version: string }): Promise<Response> {
|
|
116
165
|
const origin = ctx.request.header('origin')
|
package/src/ai.ts
CHANGED
|
@@ -1,5 +1,5 @@
|
|
|
1
1
|
import { type Application, Cache, Clock, CslugError, currentContext, type Logger, resolve } from '@cslug/core'
|
|
2
|
-
import type
|
|
2
|
+
import { type AgentSettings, type RunnableTool, type RunOptions, renderInstructions } from './agent'
|
|
3
3
|
import { AiStream } from './ai-stream'
|
|
4
4
|
import { Budget, type BudgetConfig, costOf, type ModelPrice } from './budget'
|
|
5
5
|
import {
|
|
@@ -8,6 +8,7 @@ import {
|
|
|
8
8
|
type OpenAiCompatibleConfig,
|
|
9
9
|
OpenAiCompatibleProvider,
|
|
10
10
|
} from './drivers'
|
|
11
|
+
import type { EmbeddingsConfig } from './embedders'
|
|
11
12
|
import { McpConnection, type McpServerConfig, McpTools } from './mcp-client'
|
|
12
13
|
import {
|
|
13
14
|
type Block,
|
|
@@ -18,6 +19,7 @@ import {
|
|
|
18
19
|
type Provider,
|
|
19
20
|
type Usage,
|
|
20
21
|
} from './model'
|
|
22
|
+
import type { SearchableIndex } from './search-tools'
|
|
21
23
|
|
|
22
24
|
/** `config/ai.ts`. */
|
|
23
25
|
export type AiConfig = {
|
|
@@ -33,6 +35,13 @@ export type AiConfig = {
|
|
|
33
35
|
prices?: Record<string, ModelPrice>
|
|
34
36
|
/** With @cslug/database, a row per run in `cslug_ai_runs` (default true). */
|
|
35
37
|
runs?: boolean
|
|
38
|
+
/** The embedding model `@cslug/search` uses for semantic indexes (bound as its `Embedder`). */
|
|
39
|
+
embeddings?: EmbeddingsConfig
|
|
40
|
+
/**
|
|
41
|
+
* Keep stored conversations' text in a search index (`ai-conversations` by default; semantic when an embedder is
|
|
42
|
+
* bound), so `recallTool()` can search an owner's earlier conversations. Needs @cslug/search and @cslug/database.
|
|
43
|
+
*/
|
|
44
|
+
recall?: boolean | { index?: string }
|
|
36
45
|
}
|
|
37
46
|
|
|
38
47
|
/** A finished or failed run, as `cslug_ai_runs` stores it. */
|
|
@@ -95,6 +104,8 @@ export class Ai {
|
|
|
95
104
|
private budgetTracker?: Budget
|
|
96
105
|
/** Stores each run (set by `AiProvider` with @cslug/database). */
|
|
97
106
|
recorder?: (record: RunRecord) => Promise<void>
|
|
107
|
+
/** Where stored conversations' turns are kept for `recallTool()` (set by `AiProvider` with `ai.recall`). */
|
|
108
|
+
recallIndex?: SearchableIndex
|
|
98
109
|
|
|
99
110
|
constructor(
|
|
100
111
|
protected readonly app: Application,
|
|
@@ -222,12 +233,13 @@ export class Ai {
|
|
|
222
233
|
meta: RunMeta,
|
|
223
234
|
runId: string,
|
|
224
235
|
) {
|
|
225
|
-
const {
|
|
236
|
+
const { maxSteps = 8 } = agent
|
|
226
237
|
const tools: RunnableTool[] = []
|
|
227
|
-
for (const t of agent.tools ?? [])
|
|
238
|
+
for (const t of agent.tools ?? [])
|
|
239
|
+
tools.push(...(t instanceof McpTools ? await this.remote(t) : typeof t === 'function' ? [resolve(t)] : [t]))
|
|
228
240
|
const request: ModelRequest = {
|
|
229
241
|
model: this.config.models?.[agent.model] ?? agent.model,
|
|
230
|
-
system:
|
|
242
|
+
system: await renderInstructions(agent.instructions, context),
|
|
231
243
|
messages: [...history, { role: 'user', content: [{ type: 'text', text: input }] }],
|
|
232
244
|
tools: tools.map((t) => ({
|
|
233
245
|
name: t.name,
|
package/src/conversations.ts
CHANGED
|
@@ -1,8 +1,19 @@
|
|
|
1
|
-
import {
|
|
1
|
+
import {
|
|
2
|
+
type Application,
|
|
3
|
+
Clock,
|
|
4
|
+
ConflictError,
|
|
5
|
+
CslugError,
|
|
6
|
+
currentContext,
|
|
7
|
+
type Logger,
|
|
8
|
+
Logger as LoggerToken,
|
|
9
|
+
NotFoundError,
|
|
10
|
+
runInContext,
|
|
11
|
+
} from '@cslug/core'
|
|
2
12
|
import type { Agent, AgentOutput } from './agent'
|
|
3
13
|
import { Ai, type AiResult, type RunRecord } from './ai'
|
|
4
14
|
import { AiStream } from './ai-stream'
|
|
5
15
|
import type { Message } from './model'
|
|
16
|
+
import { CONVERSATION_KEY, remember } from './search-tools'
|
|
6
17
|
|
|
7
18
|
type AgentClass<A extends Agent> = abstract new (...args: never[]) => A
|
|
8
19
|
|
|
@@ -89,19 +100,32 @@ export class Conversation<A extends Agent = Agent> {
|
|
|
89
100
|
/** Continue the conversation; the new messages are stored with the run's id. */
|
|
90
101
|
async send(input: string, options: { context?: Record<string, unknown> } = {}): Promise<AiResult<AgentOutput<A>>> {
|
|
91
102
|
const history = await this.messages()
|
|
92
|
-
const result = await this.ai.result(this.agent, { input, history, ...options }, this.meta())
|
|
103
|
+
const result = await this.scoped(() => this.ai.result(this.agent, { input, history, ...options }, this.meta()))
|
|
93
104
|
await this.storeTurn(history.length, result)
|
|
94
105
|
return result as AiResult<AgentOutput<A>>
|
|
95
106
|
}
|
|
96
107
|
|
|
108
|
+
/** Run `fn` with this conversation in the ambient context (`recallTool()` reads its owner from there). */
|
|
109
|
+
private scoped<T>(fn: () => T): T {
|
|
110
|
+
const context = currentContext()
|
|
111
|
+
if (!context) return fn()
|
|
112
|
+
return runInContext({ ...context, [CONVERSATION_KEY]: { id: this.id, owner: this.owner } }, fn)
|
|
113
|
+
}
|
|
114
|
+
|
|
97
115
|
/** `send` as a stream: the text as it arrives; the messages are stored once it has been read. */
|
|
98
116
|
stream(input: string, options: { context?: Record<string, unknown> } = {}): AiStream<AgentOutput<A>> {
|
|
99
117
|
const self = this
|
|
100
118
|
return new AiStream(
|
|
101
119
|
(async function* () {
|
|
102
120
|
const history = await self.messages()
|
|
103
|
-
const inner = self.ai.stream(self.agent, { input, history, ...options }, self.meta())
|
|
104
|
-
|
|
121
|
+
const inner = self.scoped(() => self.ai.stream(self.agent, { input, history, ...options }, self.meta()))
|
|
122
|
+
const iterator = inner[Symbol.asyncIterator]()
|
|
123
|
+
for (
|
|
124
|
+
let next = await self.scoped(() => iterator.next());
|
|
125
|
+
!next.done;
|
|
126
|
+
next = await self.scoped(() => iterator.next())
|
|
127
|
+
)
|
|
128
|
+
yield { type: 'text' as const, text: next.value }
|
|
105
129
|
const result = await inner.result
|
|
106
130
|
await self.storeTurn(history.length, result)
|
|
107
131
|
yield { type: 'result' as const, result }
|
|
@@ -115,9 +139,10 @@ export class Conversation<A extends Agent = Agent> {
|
|
|
115
139
|
this.row = { ...this.row, ...changes } as ConversationRow
|
|
116
140
|
}
|
|
117
141
|
|
|
118
|
-
/** Delete the conversation and its messages (its run records stay, without the link). */
|
|
119
|
-
delete(): Promise<void> {
|
|
120
|
-
|
|
142
|
+
/** Delete the conversation and its messages (its run records stay, without the link; recall forgets it). */
|
|
143
|
+
async delete(): Promise<void> {
|
|
144
|
+
await this.store.delete(this.id)
|
|
145
|
+
await this.ai.recallIndex?.removeWhere({ conversationId: this.id })
|
|
121
146
|
}
|
|
122
147
|
|
|
123
148
|
private meta() {
|
|
@@ -133,7 +158,16 @@ export class Conversation<A extends Agent = Agent> {
|
|
|
133
158
|
'Another message was added to this conversation during the run; reload it and send again',
|
|
134
159
|
)
|
|
135
160
|
this.row = { ...this.row, messageCount: result.messages.length }
|
|
161
|
+
const recall = this.ai.recallIndex
|
|
162
|
+
if (recall)
|
|
163
|
+
// best effort: a turn is stored even if recall (an embedding call) fails
|
|
164
|
+
await remember(recall, { id: this.id, owner: this.owner }, after, result.messages.slice(after)).catch((error) =>
|
|
165
|
+
this.log?.warn('ai.recall_failed', { conversation: this.id, error }),
|
|
166
|
+
)
|
|
136
167
|
}
|
|
168
|
+
|
|
169
|
+
/** Set by `Conversations` (recall failures are logged). */
|
|
170
|
+
log?: Logger
|
|
137
171
|
}
|
|
138
172
|
|
|
139
173
|
const ownerKey = (owner: OwnerRef | null | undefined, type = 'user') =>
|
|
@@ -164,7 +198,9 @@ export class Conversations {
|
|
|
164
198
|
}
|
|
165
199
|
|
|
166
200
|
private open<A extends Agent>(row: ConversationRow, agent: AgentClass<A>): Conversation<A> {
|
|
167
|
-
|
|
201
|
+
const conversation = new Conversation(row, this.app.resolve(agent as never) as A, this.db, this.app.resolve(Ai))
|
|
202
|
+
conversation.log = this.app.resolve(LoggerToken)
|
|
203
|
+
return conversation
|
|
168
204
|
}
|
|
169
205
|
|
|
170
206
|
/** A new conversation with `agent`, owned by the signed-in user unless `owner` says otherwise. */
|
package/src/embedders.ts
ADDED
|
@@ -0,0 +1,133 @@
|
|
|
1
|
+
import { CslugError } from '@cslug/core'
|
|
2
|
+
import type { Budget } from './budget'
|
|
3
|
+
import { postJson } from './model'
|
|
4
|
+
|
|
5
|
+
/** `config/ai.ts` → `embeddings`: the model `@cslug/search` embeds documents and queries with. */
|
|
6
|
+
export type EmbeddingsConfig =
|
|
7
|
+
| {
|
|
8
|
+
driver: 'openai-compatible'
|
|
9
|
+
/** The API root (`https://api.openai.com/v1`, `http://localhost:11434/v1` for Ollama). */
|
|
10
|
+
baseUrl: string
|
|
11
|
+
apiKey?: string
|
|
12
|
+
model: string
|
|
13
|
+
/** Shorter vectors, for models that support it. */
|
|
14
|
+
dimensions?: number
|
|
15
|
+
}
|
|
16
|
+
| {
|
|
17
|
+
driver: 'voyage'
|
|
18
|
+
/** Default: `VOYAGE_API_KEY`. */
|
|
19
|
+
apiKey?: string
|
|
20
|
+
/** `voyage-3.5`, `voyage-3.5-lite`, `voyage-multilingual-2`… */
|
|
21
|
+
model: string
|
|
22
|
+
dimensions?: number
|
|
23
|
+
baseUrl?: string
|
|
24
|
+
}
|
|
25
|
+
|
|
26
|
+
type Json = Record<string, unknown>
|
|
27
|
+
|
|
28
|
+
/** What `@cslug/search`'s `Embedder` asks for (structural: this package does not import search). */
|
|
29
|
+
export interface TextEmbedder {
|
|
30
|
+
readonly model: string
|
|
31
|
+
embed(texts: string[], purpose: 'document' | 'query'): Promise<number[][]>
|
|
32
|
+
}
|
|
33
|
+
|
|
34
|
+
/** The vectors of a `/embeddings` response, in input order. */
|
|
35
|
+
function vectorsOf(json: Json, count: number): number[][] {
|
|
36
|
+
const data = ((json.data ?? []) as { embedding: number[]; index: number }[]).slice().sort((a, b) => a.index - b.index)
|
|
37
|
+
if (data.length !== count)
|
|
38
|
+
throw new CslugError('ai.embeddings', `The embeddings API returned ${data.length} vectors for ${count} texts`)
|
|
39
|
+
return data.map((d) => d.embedding)
|
|
40
|
+
}
|
|
41
|
+
|
|
42
|
+
/** Embeddings over `fetch`, charged to the daily budget (`ai.budget`) as input tokens of `model`. */
|
|
43
|
+
abstract class HttpEmbedder implements TextEmbedder {
|
|
44
|
+
/** Identifies the vectors: the model, and the dimensions when set (`voyage-3.5@512`). */
|
|
45
|
+
abstract readonly model: string
|
|
46
|
+
/** The model's name as priced in the budget (`ai.prices`). */
|
|
47
|
+
protected abstract readonly priced: string
|
|
48
|
+
constructor(protected readonly budget?: () => Budget | undefined) {}
|
|
49
|
+
|
|
50
|
+
protected abstract request(texts: string[], purpose: 'document' | 'query'): [string, Record<string, string>, Json]
|
|
51
|
+
protected abstract tokens(json: Json): number
|
|
52
|
+
|
|
53
|
+
async embed(texts: string[], purpose: 'document' | 'query'): Promise<number[][]> {
|
|
54
|
+
if (!texts.length) return []
|
|
55
|
+
const budget = this.budget?.()
|
|
56
|
+
await budget?.check()
|
|
57
|
+
const json = (await (await postJson(...this.request(texts, purpose))).json()) as Json
|
|
58
|
+
await budget?.charge(this.priced, { inputTokens: this.tokens(json), outputTokens: 0 })
|
|
59
|
+
return vectorsOf(json, texts.length)
|
|
60
|
+
}
|
|
61
|
+
}
|
|
62
|
+
|
|
63
|
+
/** Any OpenAI-compatible `/embeddings` endpoint (OpenAI, Ollama, vLLM, LM Studio…). */
|
|
64
|
+
export class OpenAiCompatibleEmbedder extends HttpEmbedder {
|
|
65
|
+
readonly model: string
|
|
66
|
+
protected readonly priced: string
|
|
67
|
+
constructor(
|
|
68
|
+
private readonly config: Extract<EmbeddingsConfig, { driver: 'openai-compatible' }>,
|
|
69
|
+
budget?: () => Budget | undefined,
|
|
70
|
+
) {
|
|
71
|
+
super(budget)
|
|
72
|
+
this.model = config.dimensions ? `${config.model}@${config.dimensions}` : config.model
|
|
73
|
+
this.priced = config.model
|
|
74
|
+
}
|
|
75
|
+
|
|
76
|
+
protected request(texts: string[]): [string, Record<string, string>, Json] {
|
|
77
|
+
const headers: Record<string, string> = this.config.apiKey ? { authorization: `Bearer ${this.config.apiKey}` } : {}
|
|
78
|
+
return [
|
|
79
|
+
`${this.config.baseUrl.replace(/\/$/, '')}/embeddings`,
|
|
80
|
+
headers,
|
|
81
|
+
{
|
|
82
|
+
model: this.config.model,
|
|
83
|
+
input: texts,
|
|
84
|
+
...(this.config.dimensions ? { dimensions: this.config.dimensions } : {}),
|
|
85
|
+
},
|
|
86
|
+
]
|
|
87
|
+
}
|
|
88
|
+
|
|
89
|
+
protected tokens(json: Json): number {
|
|
90
|
+
const usage = (json.usage ?? {}) as Json
|
|
91
|
+
return Number(usage.prompt_tokens ?? usage.total_tokens ?? 0)
|
|
92
|
+
}
|
|
93
|
+
}
|
|
94
|
+
|
|
95
|
+
/** Voyage AI embeddings (the provider Anthropic recommends): queries and documents are embedded differently. */
|
|
96
|
+
export class VoyageEmbedder extends HttpEmbedder {
|
|
97
|
+
readonly model: string
|
|
98
|
+
protected readonly priced: string
|
|
99
|
+
constructor(
|
|
100
|
+
private readonly config: Extract<EmbeddingsConfig, { driver: 'voyage' }>,
|
|
101
|
+
budget?: () => Budget | undefined,
|
|
102
|
+
) {
|
|
103
|
+
super(budget)
|
|
104
|
+
this.model = config.dimensions ? `${config.model}@${config.dimensions}` : config.model
|
|
105
|
+
this.priced = config.model
|
|
106
|
+
}
|
|
107
|
+
|
|
108
|
+
protected request(texts: string[], purpose: 'document' | 'query'): [string, Record<string, string>, Json] {
|
|
109
|
+
const key = this.config.apiKey ?? process.env.VOYAGE_API_KEY
|
|
110
|
+
if (!key) throw new CslugError('ai.no_key', 'Set VOYAGE_API_KEY (or embeddings.apiKey in config/ai.ts)')
|
|
111
|
+
return [
|
|
112
|
+
`${(this.config.baseUrl ?? 'https://api.voyageai.com/v1').replace(/\/$/, '')}/embeddings`,
|
|
113
|
+
{ authorization: `Bearer ${key}` },
|
|
114
|
+
{
|
|
115
|
+
model: this.config.model,
|
|
116
|
+
input: texts,
|
|
117
|
+
input_type: purpose,
|
|
118
|
+
...(this.config.dimensions ? { output_dimension: this.config.dimensions } : {}),
|
|
119
|
+
},
|
|
120
|
+
]
|
|
121
|
+
}
|
|
122
|
+
|
|
123
|
+
protected tokens(json: Json): number {
|
|
124
|
+
return Number(((json.usage ?? {}) as Json).total_tokens ?? 0)
|
|
125
|
+
}
|
|
126
|
+
}
|
|
127
|
+
|
|
128
|
+
/** The embedder for `config/ai.ts` → `embeddings`. */
|
|
129
|
+
export function embedderFor(config: EmbeddingsConfig, budget?: () => Budget | undefined): TextEmbedder {
|
|
130
|
+
if (config.driver === 'voyage') return new VoyageEmbedder(config, budget)
|
|
131
|
+
if (config.driver === 'openai-compatible') return new OpenAiCompatibleEmbedder(config, budget)
|
|
132
|
+
throw new CslugError('ai.unknown_driver', `Unknown embeddings driver "${(config as { driver: string }).driver}"`)
|
|
133
|
+
}
|
package/src/fake.ts
CHANGED
|
@@ -149,8 +149,17 @@ export class AiFake extends Ai {
|
|
|
149
149
|
}
|
|
150
150
|
}
|
|
151
151
|
|
|
152
|
+
let embedderFake: { token: unknown; create: () => unknown } | undefined
|
|
153
|
+
|
|
154
|
+
/** Set by `AiProvider` when it binds @cslug/search's `Embedder`: what the AI fake swaps it for. */
|
|
155
|
+
export function setFakeEmbedder(token: unknown, create: () => unknown): void {
|
|
156
|
+
embedderFake = { token, create }
|
|
157
|
+
}
|
|
158
|
+
|
|
159
|
+
/** `fakes: ['ai']`: `Ai` is an `AiFake`, and a configured `Embedder` a `FakeEmbedder` (no provider is called). */
|
|
152
160
|
export function installAiFake(app: Application): AiFake {
|
|
153
161
|
const fake = new AiFake(app)
|
|
154
162
|
app.swap(Ai, fake)
|
|
163
|
+
if (embedderFake && app.has(embedderFake.token as never)) app.swap(embedderFake.token as never, embedderFake.create())
|
|
155
164
|
return fake
|
|
156
165
|
}
|
package/src/index.ts
CHANGED
|
@@ -6,10 +6,14 @@ export {
|
|
|
6
6
|
Agent,
|
|
7
7
|
type AgentOutput,
|
|
8
8
|
type AgentSettings,
|
|
9
|
+
fillPrompt,
|
|
10
|
+
type Instructions,
|
|
11
|
+
PROMPT_VARIABLE,
|
|
9
12
|
Prompt,
|
|
10
13
|
prompt,
|
|
11
14
|
type RunnableTool,
|
|
12
15
|
type RunOptions,
|
|
16
|
+
renderInstructions,
|
|
13
17
|
Tool,
|
|
14
18
|
type ToolClass,
|
|
15
19
|
} from './agent'
|
|
@@ -42,7 +46,14 @@ export {
|
|
|
42
46
|
type OpenAiCompatibleConfig,
|
|
43
47
|
OpenAiCompatibleProvider,
|
|
44
48
|
} from './drivers'
|
|
45
|
-
export {
|
|
49
|
+
export {
|
|
50
|
+
type EmbeddingsConfig,
|
|
51
|
+
embedderFor,
|
|
52
|
+
OpenAiCompatibleEmbedder,
|
|
53
|
+
type TextEmbedder,
|
|
54
|
+
VoyageEmbedder,
|
|
55
|
+
} from './embedders'
|
|
56
|
+
export { AiFake, type AiFixture, type AiRun, FIXTURES_DIR, installAiFake, setFakeEmbedder } from './fake'
|
|
46
57
|
export {
|
|
47
58
|
asMcpTools,
|
|
48
59
|
discoverTools,
|
|
@@ -67,4 +78,13 @@ export {
|
|
|
67
78
|
type ToolSpec,
|
|
68
79
|
type Usage,
|
|
69
80
|
} from './model'
|
|
81
|
+
export {
|
|
82
|
+
CONVERSATION_KEY,
|
|
83
|
+
type ConversationScope,
|
|
84
|
+
currentConversation,
|
|
85
|
+
recallTool,
|
|
86
|
+
type SearchableIndex,
|
|
87
|
+
type SearchToolOptions,
|
|
88
|
+
searchTool,
|
|
89
|
+
} from './search-tools'
|
|
70
90
|
export { sse } from './sse'
|
|
@@ -0,0 +1,163 @@
|
|
|
1
|
+
import { currentContext, resolve } from '@cslug/core'
|
|
2
|
+
import { v } from '@cslug/validation'
|
|
3
|
+
import type { RunnableTool } from './agent'
|
|
4
|
+
import { Ai } from './ai'
|
|
5
|
+
import type { Message } from './model'
|
|
6
|
+
|
|
7
|
+
/** What the tools use of a `@cslug/search` index (structural: this package does not import search). */
|
|
8
|
+
export type SearchableIndex = {
|
|
9
|
+
readonly name: string
|
|
10
|
+
search(
|
|
11
|
+
term: string,
|
|
12
|
+
options: {
|
|
13
|
+
page?: number
|
|
14
|
+
perPage?: number
|
|
15
|
+
filter?: Record<string, unknown>
|
|
16
|
+
highlight?: { words?: number; fragments?: number }
|
|
17
|
+
},
|
|
18
|
+
): Promise<{
|
|
19
|
+
data: {
|
|
20
|
+
key: string
|
|
21
|
+
title: string
|
|
22
|
+
metadata: Record<string, unknown>
|
|
23
|
+
rank: number
|
|
24
|
+
highlight?: { body: string }
|
|
25
|
+
}[]
|
|
26
|
+
meta: { page: number; total: number; lastPage: number }
|
|
27
|
+
}>
|
|
28
|
+
upsertMany(
|
|
29
|
+
documents: { key: string; title?: string; body?: string; metadata?: Record<string, unknown> }[],
|
|
30
|
+
): Promise<void>
|
|
31
|
+
removeWhere(filter: Record<string, unknown>): Promise<number>
|
|
32
|
+
}
|
|
33
|
+
|
|
34
|
+
const ENTITIES: Record<string, string> = { '&': '&', '<': '<', '>': '>', '"': '"' }
|
|
35
|
+
/** A highlight as plain text for a model: marks dropped, entities decoded. */
|
|
36
|
+
const plain = (html = '') => html.replace(/<\/?mark>/g, '').replace(/&(amp|lt|gt|quot);/g, (e) => ENTITIES[e] ?? e)
|
|
37
|
+
|
|
38
|
+
const searchInput = v.object({
|
|
39
|
+
query: v.string().min(1).max(300).describe('What to look for, in the words of the question'),
|
|
40
|
+
page: v.int().min(1).optional().describe('Result page, from 1'),
|
|
41
|
+
})
|
|
42
|
+
|
|
43
|
+
export type SearchToolOptions = {
|
|
44
|
+
/** The tool's name for the model (default `search_<index>`). */
|
|
45
|
+
name?: string
|
|
46
|
+
/** What the index holds, for the model to know when to search it. */
|
|
47
|
+
description?: string
|
|
48
|
+
/** Results per call (default 5). */
|
|
49
|
+
perPage?: number
|
|
50
|
+
/** Always applied: `{ published: true }`, a tenant… */
|
|
51
|
+
filter?: Record<string, unknown>
|
|
52
|
+
/** Snippet length in words (default 40). */
|
|
53
|
+
words?: number
|
|
54
|
+
}
|
|
55
|
+
|
|
56
|
+
/**
|
|
57
|
+
* A tool an agent searches an index with: `tools = [searchTool(helpIndex, { description: 'The help center' })]`.
|
|
58
|
+
* The model sends `{ query, page? }` and reads `{ results: [{ key, title, snippet, metadata }], total, page,
|
|
59
|
+
* lastPage }`, snippets in plain text.
|
|
60
|
+
*/
|
|
61
|
+
export function searchTool(index: SearchableIndex, options: SearchToolOptions = {}): RunnableTool {
|
|
62
|
+
const name = options.name ?? `search_${index.name.replace(/[^a-zA-Z0-9_]/g, '_')}`
|
|
63
|
+
return {
|
|
64
|
+
name,
|
|
65
|
+
description: `${options.description ?? `Search the "${index.name}" index`}. Returns the best matches with a snippet each.`,
|
|
66
|
+
input: searchInput,
|
|
67
|
+
async handle(input: never) {
|
|
68
|
+
const { query, page } = input as v.infer<typeof searchInput>
|
|
69
|
+
const found = await index.search(query, {
|
|
70
|
+
page: page ?? 1,
|
|
71
|
+
perPage: options.perPage ?? 5,
|
|
72
|
+
highlight: { words: options.words ?? 40, fragments: 2 },
|
|
73
|
+
...(options.filter ? { filter: options.filter } : {}),
|
|
74
|
+
})
|
|
75
|
+
return {
|
|
76
|
+
results: found.data.map((d) => ({
|
|
77
|
+
key: d.key,
|
|
78
|
+
title: d.title,
|
|
79
|
+
snippet: plain(d.highlight?.body),
|
|
80
|
+
metadata: d.metadata,
|
|
81
|
+
})),
|
|
82
|
+
total: found.meta.total,
|
|
83
|
+
page: found.meta.page,
|
|
84
|
+
lastPage: found.meta.lastPage,
|
|
85
|
+
}
|
|
86
|
+
},
|
|
87
|
+
}
|
|
88
|
+
}
|
|
89
|
+
|
|
90
|
+
/** The conversation a run belongs to (set by `Conversation.send` / `stream` in the ambient context). */
|
|
91
|
+
export type ConversationScope = { id: string; owner: { type: string; id: string } | null }
|
|
92
|
+
export const CONVERSATION_KEY = 'aiConversation'
|
|
93
|
+
export const currentConversation = (): ConversationScope | undefined =>
|
|
94
|
+
currentContext()?.[CONVERSATION_KEY] as ConversationScope | undefined
|
|
95
|
+
|
|
96
|
+
/** The text of a message (its text blocks), or '' for tool rounds and provider blocks. */
|
|
97
|
+
export const messageText = (m: Message) =>
|
|
98
|
+
m.content
|
|
99
|
+
.flatMap((b) => (b.type === 'text' ? [b.text] : []))
|
|
100
|
+
.join('\n')
|
|
101
|
+
.trim()
|
|
102
|
+
|
|
103
|
+
/**
|
|
104
|
+
* Store a turn's text messages in the recall index (`ai.recall`), keyed `<conversation>:<position>`, with the
|
|
105
|
+
* owner in the metadata so recall stays within one owner's conversations.
|
|
106
|
+
*/
|
|
107
|
+
export async function remember(index: SearchableIndex, scope: ConversationScope, after: number, messages: Message[]) {
|
|
108
|
+
if (!scope.owner) return // an unowned conversation is nobody's to recall
|
|
109
|
+
const owner = scope.owner
|
|
110
|
+
const documents = messages.flatMap((m, i) => {
|
|
111
|
+
const body = messageText(m)
|
|
112
|
+
return body
|
|
113
|
+
? [
|
|
114
|
+
{
|
|
115
|
+
key: `${scope.id}:${after + i}`,
|
|
116
|
+
body,
|
|
117
|
+
metadata: { ownerType: owner.type, ownerId: owner.id, conversationId: scope.id, role: m.role },
|
|
118
|
+
},
|
|
119
|
+
]
|
|
120
|
+
: []
|
|
121
|
+
})
|
|
122
|
+
if (documents.length) await index.upsertMany(documents)
|
|
123
|
+
}
|
|
124
|
+
|
|
125
|
+
const recallInput = v.object({
|
|
126
|
+
query: v.string().min(1).max(300).describe('What the user said or was told before, in their words'),
|
|
127
|
+
})
|
|
128
|
+
|
|
129
|
+
/**
|
|
130
|
+
* A tool for a stored conversation's agent to look up what the same owner said in their earlier conversations
|
|
131
|
+
* (needs `ai.recall`). It only ever searches the current conversation's owner, never the model's choice.
|
|
132
|
+
*/
|
|
133
|
+
export function recallTool(options: { perPage?: number } = {}): RunnableTool {
|
|
134
|
+
return {
|
|
135
|
+
name: 'recall_conversations',
|
|
136
|
+
description:
|
|
137
|
+
"Search this user's earlier conversations (not the current one) for something they said or were told. " +
|
|
138
|
+
'Returns matching messages with their role and conversation.',
|
|
139
|
+
input: recallInput,
|
|
140
|
+
async handle(input: never) {
|
|
141
|
+
const { query } = input as v.infer<typeof recallInput>
|
|
142
|
+
const scope = currentConversation()
|
|
143
|
+
const recall = resolve(Ai).recallIndex
|
|
144
|
+
if (!recall) return 'Recall is not enabled (ai.recall).'
|
|
145
|
+
if (!scope?.owner) return 'There is no earlier conversation to search: this conversation has no owner.'
|
|
146
|
+
const perPage = options.perPage ?? 5
|
|
147
|
+
const found = await recall.search(query, {
|
|
148
|
+
perPage: perPage * 2,
|
|
149
|
+
filter: { ownerType: scope.owner.type, ownerId: scope.owner.id },
|
|
150
|
+
highlight: { words: 60, fragments: 0 }, // the message from its start: messages are short
|
|
151
|
+
})
|
|
152
|
+
const results = found.data
|
|
153
|
+
.filter((d) => d.metadata.conversationId !== scope.id)
|
|
154
|
+
.slice(0, perPage)
|
|
155
|
+
.map((d) => ({
|
|
156
|
+
conversationId: d.metadata.conversationId,
|
|
157
|
+
role: d.metadata.role,
|
|
158
|
+
text: plain(d.highlight?.body),
|
|
159
|
+
}))
|
|
160
|
+
return { results }
|
|
161
|
+
},
|
|
162
|
+
}
|
|
163
|
+
}
|