toolsplice 0.0.1 → 0.0.2
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 +62 -330
- package/dist/abortable.d.ts +6 -0
- package/dist/abortable.js +50 -0
- package/dist/adaptive-read.d.ts +50 -0
- package/dist/adaptive-read.js +780 -0
- package/dist/answer-wait.d.ts +7 -0
- package/dist/answer-wait.js +45 -0
- package/dist/cache-reads.d.ts +18 -0
- package/dist/cache-reads.js +89 -0
- package/dist/calibration-ledger.d.ts +37 -0
- package/dist/calibration-ledger.js +148 -0
- package/dist/calibration-marker.d.ts +4 -0
- package/dist/calibration-marker.js +77 -0
- package/dist/catalog-setup.d.ts +33 -0
- package/dist/catalog-setup.js +89 -0
- package/dist/catalog.d.ts +10 -0
- package/dist/catalog.js +42 -0
- package/dist/checkpoint-files.d.ts +15 -0
- package/dist/checkpoint-files.js +99 -0
- package/dist/cli.js +545 -14
- package/dist/coalesce-reads.d.ts +6 -0
- package/dist/coalesce-reads.js +33 -0
- package/dist/contract-caller.d.ts +2 -1
- package/dist/contract-caller.js +35 -16
- package/dist/contract-schema.d.ts +3 -1
- package/dist/contract-schema.js +34 -4
- package/dist/contracts.d.ts +1 -0
- package/dist/contracts.js +5 -1
- package/dist/core.d.ts +31 -1
- package/dist/core.js +27 -0
- package/dist/db-final-answer.d.ts +9 -0
- package/dist/db-final-answer.js +62 -0
- package/dist/define.d.ts +78 -0
- package/dist/define.js +14 -0
- package/dist/final-answer-stores.d.ts +71 -0
- package/dist/final-answer-stores.js +72 -0
- package/dist/final-answer.d.ts +32 -0
- package/dist/final-answer.js +104 -0
- package/dist/impact.d.ts +48 -0
- package/dist/impact.js +71 -0
- package/dist/index.d.ts +32 -1
- package/dist/index.js +28 -0
- package/dist/local-tool.d.ts +18 -0
- package/dist/local-tool.js +32 -0
- package/dist/mcp-apps.d.ts +53 -0
- package/dist/mcp-apps.js +32 -0
- package/dist/mcp-event-delivery.d.ts +98 -0
- package/dist/mcp-event-delivery.js +211 -0
- package/dist/mcp-extensions.d.ts +46 -0
- package/dist/mcp-extensions.js +200 -0
- package/dist/mcp-peer.d.ts +45 -0
- package/dist/mcp-peer.js +207 -0
- package/dist/mcp-server-card.d.ts +21 -0
- package/dist/mcp-server-card.js +54 -0
- package/dist/page-checkpoint.d.ts +71 -0
- package/dist/page-checkpoint.js +286 -0
- package/dist/page-read-gate.d.ts +15 -0
- package/dist/page-read-gate.js +48 -0
- package/dist/pattern.d.ts +1 -0
- package/dist/pattern.js +27 -5
- package/dist/probe.js +6 -19
- package/dist/read-pages.d.ts +25 -0
- package/dist/read-pages.js +85 -0
- package/dist/read-policy.d.ts +6 -0
- package/dist/read-policy.js +16 -0
- package/dist/read-steps.d.ts +12 -0
- package/dist/read-steps.js +36 -0
- package/dist/result-session.d.ts +109 -0
- package/dist/result-session.js +620 -0
- package/dist/route-checkpoint.d.ts +3 -0
- package/dist/route-checkpoint.js +80 -0
- package/dist/route-driver-cli.d.ts +3 -0
- package/dist/route-driver-cli.js +43 -0
- package/dist/route-evaluation.d.ts +141 -0
- package/dist/route-evaluation.js +329 -0
- package/dist/row-groups.d.ts +17 -0
- package/dist/row-groups.js +79 -0
- package/dist/row-query.d.ts +62 -0
- package/dist/row-query.js +172 -0
- package/dist/rules.d.ts +30 -0
- package/dist/rules.js +72 -0
- package/dist/run-diagnostics.d.ts +75 -0
- package/dist/run-diagnostics.js +212 -0
- package/dist/search-fetch.d.ts +50 -0
- package/dist/search-fetch.js +264 -0
- package/dist/skill-files.d.ts +9 -0
- package/dist/skill-files.js +49 -0
- package/dist/splice-diagnostics.d.ts +4 -0
- package/dist/splice-diagnostics.js +24 -16
- package/dist/splice-measure.d.ts +33 -0
- package/dist/splice-measure.js +55 -0
- package/dist/splice-project.d.ts +12 -6
- package/dist/splice-project.js +72 -20
- package/dist/splice-recording.d.ts +29 -2
- package/dist/splice-recording.js +22 -5
- package/dist/splice.d.ts +98 -1
- package/dist/splice.js +225 -27
- package/dist/sqlite-checkpoint-store.d.ts +5 -0
- package/dist/sqlite-checkpoint-store.js +91 -0
- package/dist/sqlite-checkpoint-worker.d.ts +1 -0
- package/dist/sqlite-checkpoint-worker.js +115 -0
- package/dist/test-difference.d.ts +13 -0
- package/dist/test-difference.js +42 -0
- package/dist/testing.d.ts +122 -0
- package/dist/testing.js +261 -0
- package/dist/text-pages.d.ts +24 -0
- package/dist/text-pages.js +36 -0
- package/dist/tool-discovery.d.ts +59 -0
- package/dist/tool-discovery.js +136 -0
- package/dist/unevaluated.d.ts +7 -0
- package/dist/unevaluated.js +156 -0
- package/dist/v2.js +25 -8
- package/dist/version.d.ts +1 -1
- package/dist/version.js +1 -1
- package/dist/workflow-json.js +1 -1
- package/docs/AGENT-FRAMEWORKS.md +431 -0
- package/docs/BENCHMARKS.md +43 -0
- package/docs/INTEGRATION-QUICKSTART.md +859 -0
- package/docs/LEARNING-AND-STORAGE.md +393 -0
- package/docs/MCP.md +204 -0
- package/docs/PROJECTS-AND-UPGRADES.md +67 -9
- package/docs/PYTHON-REFERENCE.md +348 -0
- package/docs/PYTHON.md +120 -0
- package/docs/RECORDING-AND-CORRECTIONS.md +30 -1
- package/docs/TESTING.md +259 -0
- package/examples/mcp-app/build.mjs +11 -0
- package/examples/mcp-app/view.mjs +22 -0
- package/examples/quickstart.mjs +43 -0
- package/examples/route-driver.mjs +67 -0
- package/integrations/ai.d.mts +36 -0
- package/integrations/ai.mjs +178 -0
- package/integrations/call-options.mjs +9 -0
- package/integrations/langchain.d.mts +31 -0
- package/integrations/langchain.mjs +114 -0
- package/integrations/managed.mjs +154 -0
- package/integrations/types.d.mts +13 -0
- package/package.json +47 -3
|
@@ -0,0 +1,859 @@
|
|
|
1
|
+
# Wrap the tools your agent already uses
|
|
2
|
+
|
|
3
|
+
Pass the framework tools you already give the agent and the user's question. Each call gets a private result store. Small reads can pass through. When a run fills its adaptive retention budget, an additional valid result can pass through in full and earlier references remain usable. For a large read, the agent can receive a selected view and use `inspect_result` to read the original during the same run. Toolsplice needs no database, model key or hosted service. Your application keeps its existing model, MCP connections and authorization.
|
|
4
|
+
|
|
5
|
+
## Install the integration you use
|
|
6
|
+
|
|
7
|
+
Choose the command for your framework. Run it in the environment where your agent runs.
|
|
8
|
+
|
|
9
|
+
| Framework | Install |
|
|
10
|
+
| --- | --- |
|
|
11
|
+
| Agno | `python -m pip install 'toolsplice[agno]==0.0.2'` |
|
|
12
|
+
| LangChain Python | `python -m pip install 'toolsplice[langchain]==0.0.2' 'langchain>=1,<2'` |
|
|
13
|
+
| Vercel AI SDK | `npm install toolsplice@0.0.2 'ai@>=6 <8'` |
|
|
14
|
+
| LangChain JS | `npm install toolsplice@0.0.2 langchain@^1 @langchain/core@^1` |
|
|
15
|
+
|
|
16
|
+
Keep your existing model provider and the MCP connections your app has authorized.
|
|
17
|
+
|
|
18
|
+
Jump to [Agno](#agno), [LangChain Python](#langchain-python), [Vercel AI SDK](#vercel-ai-sdk), [LangChain JS](#langchain-js) or [direct MCP calls](#call-tools-directly).
|
|
19
|
+
|
|
20
|
+
## Choose a route with your own tasks
|
|
21
|
+
|
|
22
|
+
Start in an application that has Toolsplice installed. The Python CLI creates a runnable driver and saves a portable policy with these commands.
|
|
23
|
+
|
|
24
|
+
```sh
|
|
25
|
+
toolsplice evaluate --init routes.py
|
|
26
|
+
toolsplice evaluate --driver routes.py --plan
|
|
27
|
+
toolsplice evaluate --driver routes.py --save-trials trials.json --out policy.json
|
|
28
|
+
```
|
|
29
|
+
|
|
30
|
+
With npm, use the JavaScript driver.
|
|
31
|
+
|
|
32
|
+
```sh
|
|
33
|
+
npx toolsplice evaluate --init routes.mjs
|
|
34
|
+
npx toolsplice evaluate --driver routes.mjs --plan
|
|
35
|
+
npx toolsplice evaluate --driver routes.mjs --save-trials trials.json --out policy.json
|
|
36
|
+
```
|
|
37
|
+
|
|
38
|
+
The plan loads your trusted driver and reports how many agent runs it will schedule, including whether each workload has enough distinct fit and holdout cases. `sharedInputsAcrossSplits` counts distinct JSON inputs appearing in both splits, even if case IDs or object key order differ. Check those cases for leakage before you run a paid evaluation. The plan leaves the runner and grader uncalled. The CLI writes driver and framework logs to stderr and reserves stdout for its report. The starter runs two local reads. Its model-call count and cost are zero. Replace its `run` callback with your actual integration. Return `answer`, `modelCalls`, and measured `costUsd` for each attempt. If a failed call incurred charges, return its measured usage with `failed: true`. If usage is unknown, stop the evaluation. Supply a boolean `grade` callback. The SDK gives each arm a fresh copy of the task input. Only the grader receives the expected answer.
|
|
39
|
+
|
|
40
|
+
Group tasks by stable application workload, such as `page-count`. Give fit and holdout questions different IDs and different inputs. The default requires at least five paired trials and two distinct questions in **each** split. It requires all candidate answers to be correct, preserves each correct native answer, and checks p95 time and average cost against native. A faster or cheaper candidate needs at least a 1% improvement in one of those measurements if accuracy is tied. Set `limits` on the suite to change `minPairs`, `minCases`, `minAccuracy`, `maxP95Ms`, `maxMeanCostUsd`, or `minGain`. An absolute budget tightens the comparison. A route that loses its holdout falls back to native. The fallback itself may miss your budget.
|
|
41
|
+
|
|
42
|
+
The `context` is your compatibility label for the model, prompts, tool schemas, and configuration. Change it when any of those changes, or calculate it from a configuration object using `routeContext({model, promptVersion, tools})` in JS or `route_context({"model": model, "promptVersion": prompt_version, "tools": tools})` in Python. Pass the current catalog’s JSON definitions. Both languages produce the same SHA-256 stamp. Either SDK can consume either CLI’s policy. Reviewing a saved receipt is offline.
|
|
43
|
+
|
|
44
|
+
```sh
|
|
45
|
+
toolsplice evaluate trials.json --json
|
|
46
|
+
```
|
|
47
|
+
|
|
48
|
+
Compile the policy once at startup. Dispatch by workload when the request arrives. Each callback below runs your existing agent with the corresponding tool configuration. Only the selected callback executes.
|
|
49
|
+
|
|
50
|
+
```python
|
|
51
|
+
import json
|
|
52
|
+
from pathlib import Path
|
|
53
|
+
from toolsplice import RunDiagnostics, prepare_route_policy, run_routed
|
|
54
|
+
|
|
55
|
+
choose = prepare_route_policy(json.loads(Path("policy.json").read_text()), "local-pages/v1")
|
|
56
|
+
|
|
57
|
+
async def answer(workload, question):
|
|
58
|
+
trace = RunDiagnostics()
|
|
59
|
+
reply = await run_routed(
|
|
60
|
+
choose, workload,
|
|
61
|
+
native=lambda: answer_with_native_tools(question),
|
|
62
|
+
adaptive=lambda: answer_with_wrapped_tools(question),
|
|
63
|
+
configured=lambda: answer_with_handoff(question),
|
|
64
|
+
diagnostics=trace,
|
|
65
|
+
)
|
|
66
|
+
return reply, trace.snapshot()
|
|
67
|
+
```
|
|
68
|
+
|
|
69
|
+
```js
|
|
70
|
+
import { readFile } from "node:fs/promises";
|
|
71
|
+
import { prepareRoutePolicy, runRouted, RunDiagnostics } from "toolsplice";
|
|
72
|
+
|
|
73
|
+
const policy = JSON.parse(await readFile("policy.json", "utf8"));
|
|
74
|
+
const choose = prepareRoutePolicy(policy, "local-pages/v1");
|
|
75
|
+
|
|
76
|
+
async function answer(workload, question) {
|
|
77
|
+
const trace = new RunDiagnostics();
|
|
78
|
+
const reply = await runRouted(choose, workload, {
|
|
79
|
+
native: () => answerWithNativeTools(question),
|
|
80
|
+
adaptive: () => answerWithWrappedTools(question),
|
|
81
|
+
configured: () => answerWithHandoff(question),
|
|
82
|
+
}, trace);
|
|
83
|
+
return { reply, diagnostics: trace.snapshot() };
|
|
84
|
+
}
|
|
85
|
+
```
|
|
86
|
+
|
|
87
|
+
An unknown workload, a different context, or an unavailable callback uses native. An exception from a chosen callback propagates to the host. The SDK executes a single route per request.
|
|
88
|
+
|
|
89
|
+
### Read a run’s diagnostics
|
|
90
|
+
|
|
91
|
+
For a one-line wrapper, pass `diagnostics=trace` to `agno_tools` or `langchain_tools`, or pass `{ diagnostics: trace }` to the Vercel or JavaScript LangChain wrappers. For generic code use `with trace.run("configured"):` in Python or `await trace.run("configured", fn)` in JS. Create an observer per agent run.
|
|
92
|
+
|
|
93
|
+
The snapshot includes the route, status, elapsed time, handoff search and fetch attempts, retries, local deadlines, cancellations, and inspection calls. `upstreamBytes` counts decoded handoff responses. `inputBytes` and `visibleBytes` count adaptive presentations before framework message formatting. Native SDK traffic outside Toolsplice is visible to the host. To include provider usage, call `trace.model_call(input_tokens=…, output_tokens=…, cost_usd=…)` or `trace.modelCall({inputTokens, outputTokens, costUsd})` inside the run. A missing price increments `unpricedCalls`. An optional `on_event` or `onEvent` callback receives structured operation names, counts, and timings. These events omit prompts, tool arguments, URLs, result bodies, and credentials.
|
|
94
|
+
|
|
95
|
+
### Resume an interrupted calibration
|
|
96
|
+
|
|
97
|
+
Give a paid evaluation a dedicated local checkpoint directory on the first run. Use the same command and directory after restarting.
|
|
98
|
+
|
|
99
|
+
```sh
|
|
100
|
+
toolsplice evaluate --driver routes.py --checkpoint .calibration --save-trials trials.json --out policy.json
|
|
101
|
+
```
|
|
102
|
+
|
|
103
|
+
For JS, pass `routes.mjs`. The library equivalents are `collectRouteTrials(suite, { checkpoint: ".calibration" })` and `await collect_route_trials(suite, checkpoint=".calibration")`. Either SDK can resume the other’s checkpoint when both use the same suite definition and context. Change the context when the model, tools, runner or grading logic changes.
|
|
104
|
+
|
|
105
|
+
Toolsplice saves each graded trial’s result, timing and usage before starting the next one. On restart it reuses saved trials, including billed failures. Checkpoints contain case identifiers, grades, timing, usage and fingerprints. Inputs, expected values and provider responses stay with the driver.
|
|
106
|
+
|
|
107
|
+
Inspect all attempts with `toolsplice evaluate --ledger .calibration`. This local read works even when a calibration cannot resume. A saved grade is sufficient for either SDK to finish a trial after a crash. If the grade is missing, ordinary resume stops. After reconciling the interrupted attempt, use `--retry-incomplete` to deliberately rerun it. One worker can claim the retry.
|
|
108
|
+
|
|
109
|
+
To retain usage before a trial finishes, instrument each outbound model request in your calibration driver or transport. Call the start hook immediately before sending, then pass the provider’s measured cost as soon as usage arrives. Include each automatic transport retry as a separate call.
|
|
110
|
+
|
|
111
|
+
```js
|
|
112
|
+
import { startCalibrationCall } from "toolsplice";
|
|
113
|
+
|
|
114
|
+
const finish = startCalibrationCall();
|
|
115
|
+
const response = await callModel();
|
|
116
|
+
finish({ costUsd: price(response.usage), inputTokens: response.usage.input_tokens });
|
|
117
|
+
```
|
|
118
|
+
|
|
119
|
+
```python
|
|
120
|
+
from toolsplice import start_calibration_call
|
|
121
|
+
|
|
122
|
+
finish = start_calibration_call()
|
|
123
|
+
response = await call_model()
|
|
124
|
+
finish({"costUsd": price(response.usage), "inputTokens": response.usage.input_tokens})
|
|
125
|
+
```
|
|
126
|
+
|
|
127
|
+
The model call and pricing functions come from your application. Both SDKs accept optional `inputTokens` and `outputTokens`. Each receipt stores the local call ID, time and measured usage. Requests, model answers and credentials stay in the application. A call intent with no receipt has unknown usage even if the provider completed it. `totals.knownCostUsd` includes recorded spend across retries and completed trials from older drivers. `pendingCalls` counts unresolved call intents. `unmeteredIncompleteAttempts` flags unfinished attempts that had no request hooks. For a programmatic snapshot use `readCalibrationLedger(directory)` or `read_calibration_ledger(directory)`.
|
|
128
|
+
|
|
129
|
+
On macOS the JS writer stores each request as a private directory and its usage as a single empty entry. The entry names carry the measurements, so copying or backing up a checkpoint must preserve empty files and directories. Upgrade both SDKs when sharing these checkpoints. The current readers support both these markers and earlier JSON records. Python continues writing JSON records.
|
|
130
|
+
|
|
131
|
+
Keep the complete directory on a local filesystem that supports atomic hard links. Run concurrent workers in the same host and PID namespace. The final receipt and policy use separate, unused output paths outside the checkpoint directory. If a complete receipt already exists, `toolsplice evaluate trials.json --out new-policy.json` rebuilds the policy offline.
|
|
132
|
+
|
|
133
|
+
## Agno
|
|
134
|
+
|
|
135
|
+
```python
|
|
136
|
+
from agno.agent import Agent
|
|
137
|
+
from toolsplice.integrations.agno import agno_tools
|
|
138
|
+
|
|
139
|
+
with agno_tools(existing_tools, question) as tools:
|
|
140
|
+
reply = await Agent(model=model, tools=tools).arun(question)
|
|
141
|
+
print(reply.content)
|
|
142
|
+
```
|
|
143
|
+
|
|
144
|
+
`existing_tools` can hold Python functions, Agno `Function` objects, an already-connected `MCPTools` toolkit, or Toolsplice executable tools. Continue using your app's usual MCP connection lifecycle. The wrapper closes its result store as the block exits, including on exceptions and cancellation.
|
|
145
|
+
|
|
146
|
+
### Isolate upstream HTTP failures across concurrent users
|
|
147
|
+
|
|
148
|
+
A managed result scope isolates references. The MCP client supplied by the application controls the lifetime of network requests. In the Python MCP clients tested, a dropped shared HTTP connection could interrupt other users' healthy reads. To isolate failures, open the connected toolkit inside each request. Keep the model client shared if your application already does so.
|
|
149
|
+
|
|
150
|
+
```python
|
|
151
|
+
from agno.agent import Agent
|
|
152
|
+
from agno.tools.mcp import MCPTools
|
|
153
|
+
from toolsplice.integrations.agno import agno_tools
|
|
154
|
+
|
|
155
|
+
async def answer(question, model):
|
|
156
|
+
async with MCPTools(url="https://learn.microsoft.com/api/mcp",
|
|
157
|
+
transport="streamable-http") as mcp:
|
|
158
|
+
with agno_tools([mcp], question) as tools:
|
|
159
|
+
return (await Agent(model=model, tools=tools).arun(question)).content
|
|
160
|
+
```
|
|
161
|
+
|
|
162
|
+
This pays MCP setup and catalog discovery per run. A connection pool can reuse a healthy client for successive runs if it enforces the appropriate authorization scope and gives each active run an exclusive lease. Discard a failed connection before accepting more work on it.
|
|
163
|
+
|
|
164
|
+
## LangChain Python
|
|
165
|
+
|
|
166
|
+
```python
|
|
167
|
+
from langchain.agents import create_agent
|
|
168
|
+
from toolsplice.integrations.langchain import langchain_tools
|
|
169
|
+
|
|
170
|
+
with langchain_tools(existing_tools, question) as tools:
|
|
171
|
+
agent = create_agent(model=model, tools=tools)
|
|
172
|
+
state = await agent.ainvoke({"messages": [{"role": "user", "content": question}]})
|
|
173
|
+
print(state["messages"][-1].content)
|
|
174
|
+
```
|
|
175
|
+
|
|
176
|
+
You can pass the list from a LangChain MCP adapter directly. Native structured tools retain their argument schemas and callbacks. With a `content_and_artifact` tool, selection applies to the model-visible content. The application still receives the original artifact.
|
|
177
|
+
|
|
178
|
+
## Vercel AI SDK
|
|
179
|
+
|
|
180
|
+
```js
|
|
181
|
+
import { generateText, stepCountIs } from "ai";
|
|
182
|
+
import { withAiTools } from "toolsplice/ai";
|
|
183
|
+
|
|
184
|
+
const result = await withAiTools(existingTools, question, (tools, activeTools) =>
|
|
185
|
+
generateText({ model, tools, prompt: question, prepareStep: () => ({ activeTools: activeTools() }), stopWhen: stepCountIs(6) })
|
|
186
|
+
);
|
|
187
|
+
console.log(result.text);
|
|
188
|
+
```
|
|
189
|
+
|
|
190
|
+
`existingTools` can be the object returned by `await mcpClient.tools()`. A native tool's `execute` still returns its original application value. Toolsplice runs its selection on what `toModelOutput` makes visible to the model. Existing approvals, error outputs and media blocks keep their framework behavior.
|
|
191
|
+
|
|
192
|
+
### Reuse the connection for a batch of questions
|
|
193
|
+
|
|
194
|
+
When a worker has several jobs for the same endpoint and authorization scope, open its MCP client once and list the tools once. Run the jobs sequentially and give each question its own `withAiTools` call. Each tool execution still reads from the server.
|
|
195
|
+
|
|
196
|
+
```js
|
|
197
|
+
import { generateText, stepCountIs } from "ai";
|
|
198
|
+
import { createMCPClient } from "@ai-sdk/mcp";
|
|
199
|
+
import { withAiTools } from "toolsplice/ai";
|
|
200
|
+
|
|
201
|
+
const toolFailed = ({ steps }) => steps.at(-1).content.some(part =>
|
|
202
|
+
part.type === "tool-error" ||
|
|
203
|
+
(part.type === "tool-result" && part.output?.isError === true)
|
|
204
|
+
);
|
|
205
|
+
|
|
206
|
+
async function answerBatch(jobs, { model, transport, save }) {
|
|
207
|
+
const client = await createMCPClient({ transport, maxRetries: 0 });
|
|
208
|
+
try {
|
|
209
|
+
const catalog = await client.tools();
|
|
210
|
+
for (const { id, question } of jobs) {
|
|
211
|
+
const result = await withAiTools(catalog, question, (tools, activeTools) =>
|
|
212
|
+
generateText({
|
|
213
|
+
model, tools, prompt: question, maxRetries: 0,
|
|
214
|
+
prepareStep: () => ({ activeTools: activeTools() }),
|
|
215
|
+
stopWhen: [stepCountIs(6), toolFailed],
|
|
216
|
+
})
|
|
217
|
+
);
|
|
218
|
+
if (toolFailed(result)) throw new Error("MCP tool failed");
|
|
219
|
+
await save(id, result);
|
|
220
|
+
}
|
|
221
|
+
} finally {
|
|
222
|
+
await client.close();
|
|
223
|
+
}
|
|
224
|
+
}
|
|
225
|
+
```
|
|
226
|
+
|
|
227
|
+
Pass a bounded batch, a transport configured for that principal, and a `save` function that records each completed job by ID. Start a new batch when permissions or tool definitions change. Use a separate client for another concurrent batch. After a failed read, the next batch opens a fresh client and discovers the catalog again. A lost response can follow a completed upstream action, so reconcile the failed job before retrying it.
|
|
228
|
+
|
|
229
|
+
## LangChain JS
|
|
230
|
+
|
|
231
|
+
```js
|
|
232
|
+
import { createAgent } from "langchain";
|
|
233
|
+
import { withLangChainTools } from "toolsplice/langchain";
|
|
234
|
+
|
|
235
|
+
const state = await withLangChainTools(existingTools, question, tools =>
|
|
236
|
+
createAgent({ model, tools }).invoke({ messages: [{ role: "user", content: question }] })
|
|
237
|
+
);
|
|
238
|
+
console.log(state.messages.at(-1).content);
|
|
239
|
+
```
|
|
240
|
+
|
|
241
|
+
Pass the array from your LangChain MCP adapter or a mix of native tools and Toolsplice executables. The wrapper adapts dynamic structured and string tools. Custom tool subclasses and direct-return tools pass through.
|
|
242
|
+
|
|
243
|
+
## Follow-up reads
|
|
244
|
+
|
|
245
|
+
The managed adapters give the model one additional tool, `inspect_result(ref, query)`. An empty query reads the root, and a JSON Pointer such as `/metadata/language` reads one field. A JSON selector string such as `{"countMatches":"timeout"}` counts exact non-overlapping occurrences, including zero. Invalid queries return an `error` field the agent can use to correct its next call. The direct `ResultSession` API accepts the selector fields as a dictionary or object.
|
|
246
|
+
|
|
247
|
+
## Advertise follow-up reads when they become available
|
|
248
|
+
|
|
249
|
+
The Vercel example above asks for the active tool names before each model request. The first request then carries the native catalog. Once a large result has a reference, the next request can offer `inspect_result`. A scalar-only run keeps the original catalog throughout.
|
|
250
|
+
|
|
251
|
+
In LangChain Python, a tool list also exposes `for_model()`. If you already use model middleware, intersect its allowed tools with that list. In LangChain JS the second callback argument returns the currently active tool objects. A plain framework integration can always use the full list shown in the one-line examples.
|
|
252
|
+
|
|
253
|
+
```python
|
|
254
|
+
from langchain.agents.middleware import wrap_model_call
|
|
255
|
+
|
|
256
|
+
with langchain_tools(existing_tools, question) as tools:
|
|
257
|
+
@wrap_model_call
|
|
258
|
+
async def available(request, handler):
|
|
259
|
+
active = tools.for_model()
|
|
260
|
+
return await handler(request.override(tools=[t for t in request.tools if t in active]))
|
|
261
|
+
|
|
262
|
+
agent = create_agent(model=model, tools=tools, middleware=[available])
|
|
263
|
+
state = await agent.ainvoke({"messages": [{"role": "user", "content": question}]})
|
|
264
|
+
```
|
|
265
|
+
|
|
266
|
+
## Use native tools for an unproven workload
|
|
267
|
+
|
|
268
|
+
For an application that requires adaptive reads to earn their place, keep a set of workload IDs that passed your evaluations with the production model. Pass the decision into the same wrapper. When disabled, native framework tools keep their original definitions and execution, with no result store or inspector. Existing Toolsplice workflow objects still register as ordinary tools.
|
|
269
|
+
|
|
270
|
+
```python
|
|
271
|
+
with agno_tools(existing_tools, question, enabled=workload_id in approved) as tools:
|
|
272
|
+
reply = await Agent(model=model, tools=tools).arun(question)
|
|
273
|
+
```
|
|
274
|
+
|
|
275
|
+
```js
|
|
276
|
+
await withAiTools(existingTools, question, tools =>
|
|
277
|
+
generateText({ model, tools, prompt: question, stopWhen: stepCountIs(6) }),
|
|
278
|
+
{ enabled: approved.has(workloadId) }
|
|
279
|
+
);
|
|
280
|
+
```
|
|
281
|
+
|
|
282
|
+
LangChain and the JS stream helpers accept the same option. The default is adaptive. Key the allowlist by an application-owned workflow and keep it with the model, tool catalog and version you evaluated. Unknown workloads take the native path in this example.
|
|
283
|
+
|
|
284
|
+
## Return a verified count directly
|
|
285
|
+
|
|
286
|
+
For an endpoint with a fixed answer shape, the application can calculate the answer in the tool and accept its successful result. This saves the model request that would transcribe the numbers. Both SDKs support `lt`, `lte`, `gt` and `gte` in row queries, including paginated queries. Missing fields and nonnumeric cells produce an error.
|
|
287
|
+
|
|
288
|
+
```python
|
|
289
|
+
from toolsplice import project_tool, query_rows
|
|
290
|
+
from toolsplice.integrations.agno import as_agno_tool
|
|
291
|
+
|
|
292
|
+
def hemisphere_counts(page, args):
|
|
293
|
+
rows = page["events"]
|
|
294
|
+
south = query_rows(rows, {"where": {"field": "latitude", "lt": 0}})["count"]
|
|
295
|
+
return {"south": south, "north": len(rows) - south}
|
|
296
|
+
|
|
297
|
+
counts = project_tool(authorized_read, hemisphere_counts, description="Count north and south events in the returned sample.")
|
|
298
|
+
agent_tool = as_agno_tool(counts, return_direct=True)
|
|
299
|
+
```
|
|
300
|
+
|
|
301
|
+
```js
|
|
302
|
+
import { projectTool, queryRows } from "toolsplice";
|
|
303
|
+
import { asLangChainTool } from "toolsplice/langchain";
|
|
304
|
+
|
|
305
|
+
const counts = projectTool(authorizedRead, ({ events }) => {
|
|
306
|
+
const south = queryRows(events, { where: { field: "latitude", lt: 0 } }).count;
|
|
307
|
+
return { south, north: events.length - south };
|
|
308
|
+
}, { description: "Count north and south events in the returned sample." });
|
|
309
|
+
const agentTool = asLangChainTool(counts, { returnDirect: true });
|
|
310
|
+
```
|
|
311
|
+
|
|
312
|
+
Here `authorized_read` / `authorizedRead` is a registered Toolsplice executable. Return a successful terminal tool result only after checking it matches the application's complete answer contract. Use `query_row_pages` / `queryRowPages` if the job requires more than the returned sample. [Handling terminal results in all three frameworks](AGENT-FRAMEWORKS.md)
|
|
313
|
+
|
|
314
|
+
## Recover a completed answer after a restart
|
|
315
|
+
|
|
316
|
+
Choose a terminal tool when its successful result answers the whole request. For example, a report endpoint can promise the exact source URL, first heading and match count. The developer defines those **fields** once. The tool reads their **values** at runtime. If a registered tool's MCP `outputSchema` already describes the entire answer, reuse it. For a raw page or a broader object, first project the required fields and declare that projection's schema. A schema checks shape and types. Your tool must still check that it fetched the authorized source and completed the requested calculation.
|
|
317
|
+
|
|
318
|
+
Choose a persistent directory for file checkpoints or an application database for workers on separate machines. Use a stable, globally unique queue job ID or a tenant-namespaced idempotency key. Bind the tenant, inputs and workflow version in `context`. Authorize the caller **before** opening the checkpoint, including on replay. Use a new job ID when the user asks for a fresh read. The examples assume an existing terminal tool called `report` whose output schema describes the finished report.
|
|
319
|
+
|
|
320
|
+
```python
|
|
321
|
+
from toolsplice import FinalAnswerCheckpoint, project_tool
|
|
322
|
+
from toolsplice.integrations.agno import as_agno_tool
|
|
323
|
+
from agno.agent import Agent
|
|
324
|
+
|
|
325
|
+
checkpoint = FinalAnswerCheckpoint(
|
|
326
|
+
settings.checkpoint_dir,
|
|
327
|
+
job_id=job.id,
|
|
328
|
+
context={"tenant": tenant_id, "question": question, "workflow": "report/v1"},
|
|
329
|
+
schema=report.definition["outputSchema"],
|
|
330
|
+
)
|
|
331
|
+
|
|
332
|
+
async def work(save):
|
|
333
|
+
terminal = project_tool(report, lambda result, args: save(result))
|
|
334
|
+
agent = Agent(model=make_model(), tools=[as_agno_tool(terminal, return_direct=True)])
|
|
335
|
+
await agent.arun(question)
|
|
336
|
+
|
|
337
|
+
answer = await checkpoint.run(work)
|
|
338
|
+
```
|
|
339
|
+
|
|
340
|
+
```js
|
|
341
|
+
import { finalAnswerCheckpoint, projectTool } from "toolsplice";
|
|
342
|
+
import { aiTools } from "toolsplice/ai";
|
|
343
|
+
import { generateText, stepCountIs } from "ai";
|
|
344
|
+
|
|
345
|
+
const checkpoint = finalAnswerCheckpoint({
|
|
346
|
+
directory: settings.checkpointDir,
|
|
347
|
+
jobId: job.id,
|
|
348
|
+
context: { tenant: tenantId, question, workflow: "report/v1" },
|
|
349
|
+
schema: report.definition.outputSchema,
|
|
350
|
+
});
|
|
351
|
+
|
|
352
|
+
const answer = await checkpoint.run(async save => {
|
|
353
|
+
const terminal = projectTool(report, result => save(result));
|
|
354
|
+
await generateText({
|
|
355
|
+
model: makeModel(), prompt: question, tools: aiTools(terminal),
|
|
356
|
+
stopWhen: [stepCountIs(4), () => checkpoint.inspect().state === "saved"],
|
|
357
|
+
});
|
|
358
|
+
});
|
|
359
|
+
```
|
|
360
|
+
|
|
361
|
+
Inside a LangChain agent, register the same projected tool with `as_langchain_tool(terminal, return_direct=True)` or `asLangChainTool(terminal, { returnDirect: true })`. Open live MCP connections inside the work callback, or use a lazily connected source, so replay also skips initialization.
|
|
362
|
+
|
|
363
|
+
Call `checkpoint.inspect()` to get the job state, or simply call `run` again to receive the saved answer. Both SDKs use the same file format. For a cross-language job use identical directory, job ID string, context and schema in both processes.
|
|
364
|
+
|
|
365
|
+
| State | What the application knows |
|
|
366
|
+
| --- | --- |
|
|
367
|
+
| `missing` | The job has no claim yet. `run` can claim it and start work. |
|
|
368
|
+
| `saved` | The validated JSON answer is available in `answer`. `run` returns it before invoking your callback. |
|
|
369
|
+
| `incomplete` | A worker claimed the job and has yet to save an answer. It can still be running. Check worker status and provider receipts before explicitly starting another attempt. |
|
|
370
|
+
|
|
371
|
+
The directory holds a private claim file and a result file containing the answer (up to 64 KiB). Mount it on a volume that survives process or container replacement and supports atomic hard links and directory sync. Treat the answer as application data and apply the same access and retention policies. A process kill before the save can leave a billed request with an unknown outcome.
|
|
372
|
+
|
|
373
|
+
### Resume from PostgreSQL or MongoDB
|
|
374
|
+
|
|
375
|
+
Workers can share a database without mounting a checkpoint directory. Give them the same database, job ID, context and answer schema. In Python, install `toolsplice[postgres]` or `toolsplice[mongo]`. In JavaScript, install the chosen driver (`pg` or `mongodb`). Your application owns the pooled client and closes it on shutdown.
|
|
376
|
+
|
|
377
|
+
| Backend | JavaScript store | Python store | Setup |
|
|
378
|
+
| --- | --- | --- | --- |
|
|
379
|
+
| PostgreSQL | `postgresFinalAnswerStore(pool)` with a `pg.Pool` | `PostgresFinalAnswerStore(pool)` with an open `psycopg_pool.AsyncConnectionPool` | Call `await store.initialize()` once in a migration to create `toolsplice_final_answers`. Give workers SELECT, INSERT and UPDATE, and point them at the same primary and schema. |
|
|
380
|
+
| MongoDB | `mongoFinalAnswerStore(client.db("jobs"))` | `MongoFinalAnswerStore(client["jobs"])` with a PyMongo `AsyncMongoClient` | Use an application database. Both adapters use the `toolsplice_final_answers` collection and its unique `_id` index. |
|
|
381
|
+
|
|
382
|
+
```js
|
|
383
|
+
import { finalAnswerCheckpoint, postgresFinalAnswerStore } from "toolsplice";
|
|
384
|
+
|
|
385
|
+
const store = postgresFinalAnswerStore(pool);
|
|
386
|
+
const cp = finalAnswerCheckpoint({
|
|
387
|
+
store, jobId: job.id, context: { tenant, question, workflow: "report/v1" },
|
|
388
|
+
schema: report.definition.outputSchema,
|
|
389
|
+
});
|
|
390
|
+
const answer = await cp.run(async save => {
|
|
391
|
+
const result = await report.execute(job.args);
|
|
392
|
+
return await save(result);
|
|
393
|
+
});
|
|
394
|
+
```
|
|
395
|
+
|
|
396
|
+
```python
|
|
397
|
+
from toolsplice import FinalAnswerCheckpoint, MongoFinalAnswerStore
|
|
398
|
+
|
|
399
|
+
store = MongoFinalAnswerStore(mongo_client["jobs"])
|
|
400
|
+
cp = FinalAnswerCheckpoint.from_store(
|
|
401
|
+
store, job_id=job.id, context={"tenant": tenant, "question": question, "workflow": "report/v1"},
|
|
402
|
+
schema=report.definition["outputSchema"],
|
|
403
|
+
)
|
|
404
|
+
|
|
405
|
+
async def work(save):
|
|
406
|
+
result = await report.execute(job.args)
|
|
407
|
+
return await save(result)
|
|
408
|
+
|
|
409
|
+
answer = await cp.run(work)
|
|
410
|
+
```
|
|
411
|
+
|
|
412
|
+
Database I/O is asynchronous in both SDKs. Use `await cp.inspect()` for status. Await `save(answer)` inside the terminal tool, or return its promise/coroutine to a wrapper that awaits it. `projectTool` and `project_tool` both await their projectors. A Vercel stop condition that checks database state can use `async () => (await cp.inspect()).state === "saved"`.
|
|
413
|
+
|
|
414
|
+
One worker claims a new job using its unique key. Saving updates only that worker's matching, incomplete record. PostgreSQL waits for the transaction commit with `synchronous_commit=on`. MongoDB requests journaled majority acknowledgement and reads from the primary. A later `run` for a saved job checks the context, schema and answer digest before returning. A competing worker that sees an incomplete claim fails before entering the work callback. An uncertain write or a crash before save requires reconciliation. Keep completed rows for as long as callers can retry the same job.
|
|
415
|
+
|
|
416
|
+
### Join a running job
|
|
417
|
+
|
|
418
|
+
For a queue that delivers the same job to multiple workers, opt in to waiting on the existing owner. In JS use `await cp.run(work, { waitMs: 5000 })`. In Python use `await cp.run(work, wait_timeout=5)`. The claim winner executes the callback. The wait timeout applies to a losing worker once its claim attempt returns. By default duplicate callers still receive an incomplete-job error.
|
|
419
|
+
|
|
420
|
+
An observer can call `await cp.waitForResult(5000, signal)` or `await cp.wait_for_result(5)` directly, even before the owner appears. These methods never claim a job. They poll with bounded backoff. At the deadline `FinalAnswerWaitTimeout.state` gives the last observed state (`missing`, `incomplete`, or `unknown` if the first database read has yet to finish). JavaScript also accepts an abort signal for an observer; Python observers support normal task cancellation. Re-authorize the caller before opening a checkpoint.
|
|
421
|
+
|
|
422
|
+
### Resume a sequence of named reads
|
|
423
|
+
|
|
424
|
+
```js
|
|
425
|
+
import { readSteps } from "toolsplice";
|
|
426
|
+
|
|
427
|
+
const steps = readSteps({ store, jobId: job.id, context: { tenant, workflow: "docs/v1" } });
|
|
428
|
+
const url = await steps.read("search", { query }, { type: "string" }, searchForFirstUrl);
|
|
429
|
+
const facts = await steps.read("fetch", url, factsSchema, fetchFacts);
|
|
430
|
+
```
|
|
431
|
+
|
|
432
|
+
```python
|
|
433
|
+
from toolsplice import ReadSteps
|
|
434
|
+
|
|
435
|
+
steps = ReadSteps(store=store, job_id=job.id, context={"tenant": tenant, "workflow": "docs/v1"})
|
|
436
|
+
url = await steps.read("search", {"query": query}, {"type": "string"}, search_for_first_url)
|
|
437
|
+
facts = await steps.read("fetch", url, facts_schema, fetch_facts)
|
|
438
|
+
```
|
|
439
|
+
|
|
440
|
+
On restart, re-enter this sequence from the beginning with the same job identity. Completed named steps replay, and the first unstarted step executes. Each step uses the existing checkpoint store, checks its input, schema and workflow identity, and saves up to 64 KiB of validated JSON. Project a compact result when reading a large page. A crash during a read can leave that step incomplete and requires reconciliation. An outer final-answer job with an unresolved claim has the same recovery requirement. A fresh job ID requests new data.
|
|
441
|
+
|
|
442
|
+
### Count groups across pages
|
|
443
|
+
|
|
444
|
+
```js
|
|
445
|
+
const query = { groupBy: { field: "time", bucket: "utcDay", top: 2, ties: "include" } };
|
|
446
|
+
const { count, groups } = await queryRowPages(readEventPage, query);
|
|
447
|
+
```
|
|
448
|
+
|
|
449
|
+
```python
|
|
450
|
+
result = await query_row_pages(read_event_page, {
|
|
451
|
+
"groupBy": {"field": "time", "bucket": "utcDay", "top": 2, "ties": "include"}
|
|
452
|
+
})
|
|
453
|
+
```
|
|
454
|
+
|
|
455
|
+
Use the same query with `queryRows` / `query_rows` for one array. The result counts matching rows and returns groups as `{key, count}` records. All pages contribute before ranking. Groups sort by count descending and key ascending; mixed keys order null, booleans, numbers, then strings in UTF-16 order. The default includes all groups tied with the Kth. Set `ties: "truncate"` for exactly K when there are enough groups. UTC bucketing accepts integer epoch milliseconds or an explicitly offset-qualified ISO timestamp. Missing group keys and malformed timestamps raise an error. Filtering with `where` happens before grouping. Bind this calculation in a local tool or expose its options to the agent.
|
|
456
|
+
|
|
457
|
+
### Return the grouped answer in one model call
|
|
458
|
+
|
|
459
|
+
For a report that asks for the top two UTC dates in a 24-event sample, give the model a terminal tool. The model selects the tool, the SDK ranks the rows across pages, and the tool saves the finished JSON. Configure the framework's direct-return or stop condition as in the checkpoint example above. On a retry, wrap the model dispatch inside the same checkpoint so it can return before opening an MCP connection.
|
|
460
|
+
|
|
461
|
+
These are the terminal handlers inside the checkpoint's work callback. The application binds the date-field query shown above to this report, and its authorized page reader verifies distinct event IDs across the sample. If the model can choose a field, bucket, or cutoff, validate that choice against the report before fetching the rows.
|
|
462
|
+
|
|
463
|
+
```js
|
|
464
|
+
async function topDates(save) {
|
|
465
|
+
const { count, groups } = await queryRowPages(readEventPage, query);
|
|
466
|
+
if (count !== 24) throw new Error("Expected the full 24-event sample");
|
|
467
|
+
return await save({ groups });
|
|
468
|
+
}
|
|
469
|
+
```
|
|
470
|
+
|
|
471
|
+
```python
|
|
472
|
+
async def top_dates(save):
|
|
473
|
+
result = await query_row_pages(read_event_page, {
|
|
474
|
+
"groupBy": {"field": "time", "bucket": "utcDay", "top": 2, "ties": "include"}
|
|
475
|
+
})
|
|
476
|
+
if result["count"] != 24:
|
|
477
|
+
raise ValueError("Expected the full 24-event sample")
|
|
478
|
+
return save({"groups": result["groups"]}) # File checkpoint
|
|
479
|
+
```
|
|
480
|
+
|
|
481
|
+
With an asynchronous Python database checkpoint, use `return await save(...)`. A request that also needs a narrative explanation may still need another model turn. For runnable examples with a model-selected query and scope-checked replay, see `bench/frameworks/grouped-early/README.md` in the source checkout.
|
|
482
|
+
|
|
483
|
+
### Retry a failed MCP page without another model call
|
|
484
|
+
|
|
485
|
+
Keep the model-selected query outside the page callback. Opt in to retries on `queryRowPages` / `query_row_pages`, or the corresponding text-page reader. Mark transient failures of an idempotent read with `RetryablePageError`. Only the failed cursor repeats. Successfully accepted pages stay in the running aggregation.
|
|
486
|
+
|
|
487
|
+
For a service that throttles several jobs at once, share one `PageReadGate` per upstream quota scope. Its queue permits one in-flight read, spaces starts and shares any retry delay supplied by the adapter. Set the minimum interval to zero for immediate healthy reads and a shared cooldown after throttling. Here the application's MCP adapter translates its transport status into an error with a numeric status and an optional retry interval in milliseconds.
|
|
488
|
+
|
|
489
|
+
```js
|
|
490
|
+
import { PageReadGate, RetryablePageError, queryRowPages } from "toolsplice";
|
|
491
|
+
|
|
492
|
+
const gate = new PageReadGate({ minIntervalMs: 2000 }); // shared by jobs
|
|
493
|
+
async function readPage(cursor, signal) {
|
|
494
|
+
return gate.read(async () => {
|
|
495
|
+
try {
|
|
496
|
+
return await readEarthquakePage(cursor, signal);
|
|
497
|
+
} catch (err) {
|
|
498
|
+
if (err.status === 429) {
|
|
499
|
+
throw new RetryablePageError("Earthquake service throttled", err.retryAfterMs ?? 30000);
|
|
500
|
+
}
|
|
501
|
+
throw err;
|
|
502
|
+
}
|
|
503
|
+
}, signal);
|
|
504
|
+
}
|
|
505
|
+
const result = await queryRowPages(readPage, selectedQuery, {
|
|
506
|
+
maxReadAttempts: 3, maxRetryWaitMs: 60000,
|
|
507
|
+
});
|
|
508
|
+
```
|
|
509
|
+
|
|
510
|
+
```python
|
|
511
|
+
from toolsplice import PageReadGate, RetryablePageError, query_row_pages
|
|
512
|
+
|
|
513
|
+
gate = PageReadGate(min_interval_ms=2000) # shared on this event loop
|
|
514
|
+
|
|
515
|
+
async def read_page(cursor):
|
|
516
|
+
async def fetch():
|
|
517
|
+
try:
|
|
518
|
+
return await read_earthquake_page(cursor)
|
|
519
|
+
except EarthquakeReadError as err:
|
|
520
|
+
if err.status == 429:
|
|
521
|
+
delay = 30000 if err.retry_after_ms is None else err.retry_after_ms
|
|
522
|
+
raise RetryablePageError("Earthquake service throttled", delay) from err
|
|
523
|
+
raise
|
|
524
|
+
return await gate.read(fetch)
|
|
525
|
+
|
|
526
|
+
result = await query_row_pages(
|
|
527
|
+
read_page, selected_query, max_read_attempts=3, max_retry_wait_ms=60000,
|
|
528
|
+
)
|
|
529
|
+
```
|
|
530
|
+
|
|
531
|
+
The default is one attempt. You can configure up to five attempts per cursor. The traversal shares a cumulative retry-sleep budget (default five seconds). A server delay longer than the remaining budget propagates the error. Cancellation, invalid data and ordinary errors stop the read. Set transport timeouts separately. Gate queueing and upstream request time are additional to the retry-sleep budget. Separate processes can share an application-level transport queue when they use the same upstream quota.
|
|
532
|
+
|
|
533
|
+
For a deferred retry after process exit, save the validated model selection **before the first read**. Give the decision its own stable checkpoint identity. The callback below asks the model for a selection and checks that its field, bucket and rank cover the request.
|
|
534
|
+
|
|
535
|
+
```js
|
|
536
|
+
const decision = finalAnswerCheckpoint({
|
|
537
|
+
directory, jobId: job.id + "/selection", context, schema: selectionSchema,
|
|
538
|
+
});
|
|
539
|
+
const selectedQuery = await decision.run(async save =>
|
|
540
|
+
save(await chooseAndValidateQuery(job))
|
|
541
|
+
);
|
|
542
|
+
```
|
|
543
|
+
|
|
544
|
+
```python
|
|
545
|
+
decision = FinalAnswerCheckpoint(
|
|
546
|
+
directory, job_id=job.id + "/selection", context=context, schema=selection_schema,
|
|
547
|
+
)
|
|
548
|
+
|
|
549
|
+
async def choose(save):
|
|
550
|
+
return save(await choose_and_validate_query(job))
|
|
551
|
+
|
|
552
|
+
selected_query = await decision.run(choose)
|
|
553
|
+
```
|
|
554
|
+
|
|
555
|
+
The new worker opens the same decision checkpoint with the same tenant, source, query and workflow version in its context. A saved decision skips the model callback. If a previous final-answer attempt has an incomplete claim, reconcile that attempt before starting another read-only attempt. A saved final answer skips both selection and reading. The checkout example `bench/frameworks/grouped-retry/restart.py` exercises both directions between JS and Python.
|
|
556
|
+
|
|
557
|
+
### Resume paginated reads after a worker exits
|
|
558
|
+
|
|
559
|
+
Pass a checkpoint to `queryRowPages` or `query_row_pages`. Use the same options on every worker. The job ID identifies this run. Include the authenticated tenant, source snapshot or version, and all request arguments in the context. Toolsplice binds the saved progress to that context, the query and the traversal limits. Use an upstream snapshot or stable ordering when the result must describe one point in time.
|
|
560
|
+
|
|
561
|
+
```ts
|
|
562
|
+
const progress = await queryRowPages(readPage, selectedQuery, {
|
|
563
|
+
checkpoint: { directory: checkpointDir, jobId: job.id, context },
|
|
564
|
+
});
|
|
565
|
+
|
|
566
|
+
switch (progress.state) {
|
|
567
|
+
case "complete": return progress.result;
|
|
568
|
+
case "deferred": return queue.schedule(job, new Date(progress.retryAt));
|
|
569
|
+
case "busy": return queue.observe(job);
|
|
570
|
+
case "expired": return reportExpiredSnapshot(job);
|
|
571
|
+
}
|
|
572
|
+
```
|
|
573
|
+
|
|
574
|
+
```python
|
|
575
|
+
from datetime import datetime, timezone
|
|
576
|
+
from toolsplice import query_row_pages
|
|
577
|
+
|
|
578
|
+
progress = await query_row_pages(
|
|
579
|
+
read_page, selected_query,
|
|
580
|
+
checkpoint={"directory": checkpoint_dir, "job_id": job.id, "context": context},
|
|
581
|
+
)
|
|
582
|
+
match progress["state"]:
|
|
583
|
+
case "complete":
|
|
584
|
+
return progress["result"]
|
|
585
|
+
case "deferred":
|
|
586
|
+
when = datetime.fromtimestamp(progress["retryAt"] / 1000, timezone.utc)
|
|
587
|
+
return await queue.schedule(job, when)
|
|
588
|
+
case "busy":
|
|
589
|
+
return await queue.observe(job)
|
|
590
|
+
case "expired":
|
|
591
|
+
return await report_expired_snapshot(job)
|
|
592
|
+
```
|
|
593
|
+
|
|
594
|
+
`queue` and `reportExpiredSnapshot` are application hooks. `retryAt` is an absolute Unix timestamp in milliseconds in both SDKs. A queue can release the worker until then. An early delivery returns the saved deadline without contacting the source. Mark retryable, idempotent reads with `RetryablePageError`. If the source reports an expired snapshot or cursor, raise `ExpiredPageCursorError`; the caller receives the affected one-based page number. The checkpointed defaults allow three attempts per cursor and 60 seconds of cumulative retry delay across the job. Explicit retry limits still apply after a restart.
|
|
595
|
+
|
|
596
|
+
The same option works on `collectTextPages` and `collect_text_pages`. For workers on different machines, substitute the existing PostgreSQL or MongoDB `store` for `directory`. Each page stores its cursor and the query's contribution, including requested values, group keys and counts, or the full chunk for text collection. Protect the store using the application's normal data access and retention policy. Each encoded checkpoint entry supports up to 12 MiB. Existing traversal byte and page limits also apply. Replay reconstructs the answer from local or database entries.
|
|
597
|
+
|
|
598
|
+
A competing worker receives `busy` while a read is outstanding. Use `rowPageJob` or `row_page_job` when an operator or scheduler needs to inspect progress and confirm a source response. For text pages use `textPageJob` or `text_page_job`. These handles can open jobs created by the existing paginated readers.
|
|
599
|
+
|
|
600
|
+
#### Inspect and recover one page
|
|
601
|
+
|
|
602
|
+
```js
|
|
603
|
+
import { rowPageJob } from "toolsplice";
|
|
604
|
+
|
|
605
|
+
const pages = rowPageJob({ values: "id" }, { checkpoint });
|
|
606
|
+
const outcome = await pages.run(({ cursor, key }) =>
|
|
607
|
+
source.readPage({ cursor, requestId: key })
|
|
608
|
+
);
|
|
609
|
+
|
|
610
|
+
// In a replacement worker, using the same checkpoint, query and limits
|
|
611
|
+
const status = await pages.inspect();
|
|
612
|
+
if (status.state === "outcome_unknown") {
|
|
613
|
+
const response = await source.lookupResponse(status.key);
|
|
614
|
+
if (response !== null) await pages.confirm(status.key, response);
|
|
615
|
+
}
|
|
616
|
+
```
|
|
617
|
+
|
|
618
|
+
```python
|
|
619
|
+
from toolsplice import row_page_job
|
|
620
|
+
|
|
621
|
+
pages = row_page_job({"values": "id"}, checkpoint=checkpoint)
|
|
622
|
+
outcome = await pages.run(lambda attempt: source.read_page(
|
|
623
|
+
cursor=attempt["cursor"], request_id=attempt["key"]
|
|
624
|
+
))
|
|
625
|
+
|
|
626
|
+
status = await pages.inspect()
|
|
627
|
+
if status["state"] == "outcome_unknown":
|
|
628
|
+
response = await source.lookup_response(status["key"])
|
|
629
|
+
if response is not None:
|
|
630
|
+
await pages.confirm(status["key"], response)
|
|
631
|
+
```
|
|
632
|
+
|
|
633
|
+
The `source` methods in these snippets belong to your application. Pass the attempt key to a source that supports lookup by request ID, or have a broker save its actual response under that key. `inspect` reads checkpoint storage only. `acceptedPages` counts completed pages. An outstanding attempt includes its one-based page and attempt numbers, key and opaque cursor. `deferred` includes the absolute `retryAt` deadline. `complete` includes the final page count.
|
|
634
|
+
|
|
635
|
+
`confirm` validates and saves the contribution for that exact attempt. Two workers can confirm the same contribution. A conflicting confirmation raises an error. Call `run` again to continue with the next unsaved page or retrieve the completed answer. If the source cannot confirm what happened, keep the job pending for reconciliation. This also applies when another worker may still be running. Persist a model-selected query separately so replacement workers can enter the page job directly. With a database store, a worker that has just saved a page claims the next key directly. If another worker already claimed it, the reader checks that record. Replaying a completed job only reads the stored entries.
|
|
636
|
+
|
|
637
|
+
If a transport loses the response after dispatch and the source might have finished, raise `UncertainPageReadError` from the read callback. Both SDKs propagate that exception and retain the outstanding claim. A replacement can inspect the attempt and confirm a response. Use `RetryablePageError` when the source explicitly permits repeating the read. An ordinary callback error remains a terminal failure for the job.
|
|
638
|
+
|
|
639
|
+
#### Recover a page from an MCP task
|
|
640
|
+
|
|
641
|
+
For a server that supports the MCP Tasks extension, bind a peer to the original endpoint and authenticated principal. In the page callback, bind `onTaskCreated` or `on_task_created` to that page’s attempt key. Persist the returned task ID before the first status poll. A new worker can ask that server for the result of the original task. [MCP peer setup](MCP.md#resume-interactive-calls-and-tasks) · [MCP Tasks specification](https://tasks.extensions.modelcontextprotocol.io/specification/2026-07-28/tasks)
|
|
642
|
+
|
|
643
|
+
```js
|
|
644
|
+
const status = await pages.inspect();
|
|
645
|
+
if (status.state === "outcome_unknown") {
|
|
646
|
+
const saved = await taskHandle(status.key).inspect();
|
|
647
|
+
if (saved.state === "saved") {
|
|
648
|
+
const result = await peer.resumeTask(saved.answer);
|
|
649
|
+
if (result.isError) throw new Error("The source task failed.");
|
|
650
|
+
await pages.confirm(status.key, result.structuredContent);
|
|
651
|
+
}
|
|
652
|
+
}
|
|
653
|
+
```
|
|
654
|
+
|
|
655
|
+
```python
|
|
656
|
+
status = await pages.inspect()
|
|
657
|
+
if status["state"] == "outcome_unknown":
|
|
658
|
+
saved = await task_handle(status["key"]).inspect()
|
|
659
|
+
if saved["state"] == "saved":
|
|
660
|
+
result = await peer.resume_task(saved["answer"])
|
|
661
|
+
if result.get("isError"):
|
|
662
|
+
raise ValueError("The source task failed.")
|
|
663
|
+
await pages.confirm(status["key"], result["structuredContent"])
|
|
664
|
+
```
|
|
665
|
+
|
|
666
|
+
Here `taskHandle(key)` is a database-backed final-answer checkpoint with a string schema, a job ID derived from the attempt key and the same source and principal in its context. The task-created callback can persist the ID with `await handle.run(save => save(taskId))` in JS or `await handle.run(lambda save: save(task_id))` in Python. These examples assume the tool returns `rows` and `nextCursor` in its structured content. Adapt the tool result to your page shape before confirming. A status lookup sends `tasks/get`. A missing handle or an expired source task leaves the attempt pending. See `bench/frameworks/durable-pages/task_fixture.py` in the source checkout for both worker implementations and the four crash cases.
|
|
667
|
+
|
|
668
|
+
#### Share one SQLite store on a host
|
|
669
|
+
|
|
670
|
+
```js
|
|
671
|
+
import { openSqliteCheckpointStore, rowPageJob } from "toolsplice";
|
|
672
|
+
|
|
673
|
+
const store = await openSqliteCheckpointStore("/var/lib/myapp/jobs.sqlite");
|
|
674
|
+
try {
|
|
675
|
+
const pages = rowPageJob(query, { checkpoint: { store, jobId, context } });
|
|
676
|
+
const status = await pages.inspect();
|
|
677
|
+
} finally {
|
|
678
|
+
await store.close();
|
|
679
|
+
}
|
|
680
|
+
```
|
|
681
|
+
|
|
682
|
+
```python
|
|
683
|
+
from toolsplice import open_sqlite_checkpoint_store, row_page_job
|
|
684
|
+
|
|
685
|
+
store = await open_sqlite_checkpoint_store("/var/lib/myapp/jobs.sqlite")
|
|
686
|
+
try:
|
|
687
|
+
pages = row_page_job(query, checkpoint={"store": store, "job_id": job_id, "context": context})
|
|
688
|
+
status = await pages.inspect()
|
|
689
|
+
finally:
|
|
690
|
+
await store.close()
|
|
691
|
+
```
|
|
692
|
+
|
|
693
|
+
Open the store once per application worker, share it across jobs and close it at shutdown. Supply an existing parent directory on local disk. Both SDKs use the same SQLite table and group queued writes on the same connection. Acknowledgement follows the transaction commit. The adapter uses WAL, synchronous FULL and macOS fullfsync where supported. It requires a runtime with the SQLite WAL-reset fix, available in 3.51.3 or later and the 3.50.7 and 3.44.6 backports. JS uses the built-in `node:sqlite` module. Python uses the standard-library `sqlite3` module. For workers on multiple hosts, use a PostgreSQL or MongoDB store. [SQLite WAL requirements and fixed versions](https://sqlite.org/wal.html)
|
|
694
|
+
|
|
695
|
+
### Cache selected reads across jobs
|
|
696
|
+
|
|
697
|
+
```js
|
|
698
|
+
import { cacheReads } from "toolsplice";
|
|
699
|
+
const read = cacheReads(caller, {
|
|
700
|
+
tools: ["lookup_document"], scope: () => currentAuthCacheKey(), ttlMs: 30_000,
|
|
701
|
+
});
|
|
702
|
+
```
|
|
703
|
+
|
|
704
|
+
```python
|
|
705
|
+
from toolsplice import cache_reads
|
|
706
|
+
read = cache_reads(caller, tools=["lookup_document"], scope=current_auth_cache_key, ttl_ms=30_000)
|
|
707
|
+
```
|
|
708
|
+
|
|
709
|
+
Authorize every request before reaching the cache. Include tenant, identity or grant set, and catalog version in the scope key if they can affect the answer. Retain this wrapper across jobs within a process; in Python use it within one event loop. It stores complete successful responses for the shorter of the configured TTL and any upstream TTL. A zero TTL, error, pending task, oversize result or call-specific options bypass reuse. Entries use LRU eviction, defaulting to 128 entries and 1 MiB. `read.stats()` gives hits, misses, entries and bytes. `read.clear()` invalidates existing entries and prevents outstanding reads from refilling them after invalidation.
|
|
710
|
+
|
|
711
|
+
## Start with a read your application has already authorized
|
|
712
|
+
|
|
713
|
+
When your handler already knows the tool and its arguments, it can perform that read before the first model request. LangChain accepts the actual tool result in the message history. Keep the read inside the same Toolsplice scope so the agent can inspect a retained result. Apply the application's normal authorization and approval before initiating the read.
|
|
714
|
+
|
|
715
|
+
```python
|
|
716
|
+
from uuid import uuid4
|
|
717
|
+
from langchain_core.messages import AIMessage
|
|
718
|
+
|
|
719
|
+
with langchain_tools(existing_tools, question) as tools:
|
|
720
|
+
read = next(t for t in tools if t.name == "read_page")
|
|
721
|
+
call = {"type": "tool_call", "name": read.name, "args": {"url": url}, "id": uuid4().hex}
|
|
722
|
+
result = await read.ainvoke(call)
|
|
723
|
+
messages = [
|
|
724
|
+
{"role": "user", "content": question},
|
|
725
|
+
AIMessage(content="", tool_calls=[call]),
|
|
726
|
+
result,
|
|
727
|
+
]
|
|
728
|
+
state = await create_agent(model=model, tools=tools).ainvoke({"messages": messages})
|
|
729
|
+
```
|
|
730
|
+
|
|
731
|
+
Replace `read_page` with your registered read tool. The model can answer on its first request. The same scheduling technique also works with ordinary native tools. When the agent needs to discover the tool or construct its arguments, pass it the original question and tools as in the first examples.
|
|
732
|
+
|
|
733
|
+
## Streaming
|
|
734
|
+
|
|
735
|
+
In Python, iterate the framework's stream inside the same `with` block. For JS, the streaming helper owns the scope until the iterator finishes, throws, or the consumer breaks out of the loop.
|
|
736
|
+
|
|
737
|
+
```js
|
|
738
|
+
import { streamText, stepCountIs } from "ai";
|
|
739
|
+
import { streamAiTools } from "toolsplice/ai";
|
|
740
|
+
|
|
741
|
+
for await (const chunk of streamAiTools(existingTools, question, tools =>
|
|
742
|
+
streamText({ model, tools, prompt: question, stopWhen: stepCountIs(6) }).textStream
|
|
743
|
+
)) {
|
|
744
|
+
process.stdout.write(chunk);
|
|
745
|
+
}
|
|
746
|
+
```
|
|
747
|
+
|
|
748
|
+
For LangChain JS, use `streamLangChainTools(existingTools, question, tools => agentWith(tools).stream(input))`, where `agentWith` constructs your agent. In both languages, create a scope for each new agent run. A result reference is valid only inside its originating scope. Supply tools whose returned content the current user may inspect. If you redact content in middleware after a tool returns, apply that redaction before wrapping the tool.
|
|
749
|
+
|
|
750
|
+
|
|
751
|
+
|
|
752
|
+
## Search and fetch in one model tool call
|
|
753
|
+
|
|
754
|
+
Register a search executable and a fetch executable from the caller’s authorized catalog. By default the handoff follows the first result at `/results`, reads its `/contentUrl` and passes that exact string to the fetch tool’s `url` argument. The two upstream reads happen inside the handoff. An absent rank returns `no_match` and skips the fetch.
|
|
755
|
+
|
|
756
|
+
```python
|
|
757
|
+
from toolsplice import search_then_fetch
|
|
758
|
+
from toolsplice.integrations.agno import agno_tools
|
|
759
|
+
|
|
760
|
+
read = search_then_fetch(search, fetch, origins=["https://learn.microsoft.com"],
|
|
761
|
+
rank="input", page_view="markdown")
|
|
762
|
+
with agno_tools([read], question) as tools:
|
|
763
|
+
reply = await Agent(model=model, tools=tools).arun(question)
|
|
764
|
+
```
|
|
765
|
+
|
|
766
|
+
```js
|
|
767
|
+
import { searchThenFetch } from "toolsplice";
|
|
768
|
+
import { withAiTools } from "toolsplice/ai";
|
|
769
|
+
|
|
770
|
+
const read = searchThenFetch(search, fetchPage, {
|
|
771
|
+
origins: ["https://learn.microsoft.com"], rank: "input", pageView: "markdown",
|
|
772
|
+
});
|
|
773
|
+
const result = await withAiTools([read], question, (tools, activeTools) =>
|
|
774
|
+
generateText({ model, prompt: question, tools, stopWhen: stepCountIs(6),
|
|
775
|
+
prepareStep: () => ({ activeTools: activeTools() }) }));
|
|
776
|
+
```
|
|
777
|
+
|
|
778
|
+
The same `read` registers with `langchain_tools([read], question)` in Python and `withLangChainTools([read], question, use)` in JS. For direct calls on tools with a `query` input, use `await read.execute({query, rank: 2, countLiteral: "host.json"})` in JS or `await read.execute({"query": query, "rank": 2, "countLiteral": "host.json"})` in Python. The Markdown view returns `requestedUrl`, the first H1 title, and the exact case-sensitive count if a literal was supplied. It scans Markdown or text pages up to 256 KiB. Set `headingLevel: 2` in JS or `heading_level=2` in Python for a first-H2 task. A missing heading at the chosen level yields null. The default page view returns the source page and URL for open-ended questions. An adaptive wrapper may take additional model turns to inspect that page.
|
|
779
|
+
|
|
780
|
+
The application selects allowed HTTP(S) origins. The handoff checks the selected URL before dispatch and passes the original spelling, query and fragment through to the connected fetcher. That fetcher owns redirect handling. Set a fixed numeric `rank` to bind result selection at registration. Use `resultsPath`, `urlPath` and `urlArgument` in JS or their snake_case equivalents in Python to match other catalogs. If a search input collides with a handoff field or has complex root constraints, the generated tool schema nests the source arguments under `search`.
|
|
781
|
+
|
|
782
|
+
## Bound a read and retry a transient fetch
|
|
783
|
+
|
|
784
|
+
If your fetcher reports a temporary failure and the operation is safe to repeat, register a predicate for that error. The handoff searches once and can make one extra fetch of the exact selected URL, including its query and fragment. A single call deadline covers the search, both fetch attempts and the retry decision. The default allows one fetch attempt.
|
|
785
|
+
|
|
786
|
+
```python
|
|
787
|
+
from toolsplice import search_then_fetch
|
|
788
|
+
|
|
789
|
+
read = search_then_fetch(search, fetch_page, origins=["https://learn.microsoft.com"],
|
|
790
|
+
retry_fetch_if=lambda exc: isinstance(exc, ConnectionResetError))
|
|
791
|
+
page = await read.execute({"query": question}, timeout=5) # seconds
|
|
792
|
+
```
|
|
793
|
+
|
|
794
|
+
```js
|
|
795
|
+
import { searchThenFetch } from "toolsplice";
|
|
796
|
+
|
|
797
|
+
const read = searchThenFetch(search, fetchPage, {
|
|
798
|
+
origins: ["https://learn.microsoft.com"],
|
|
799
|
+
retryFetchIf: error => error?.code === "ECONNRESET",
|
|
800
|
+
});
|
|
801
|
+
const page = await read.execute({ query: question }, { timeoutMs: 5000 });
|
|
802
|
+
```
|
|
803
|
+
|
|
804
|
+
Match the error type your own fetcher exposes. A caller can cancel the Python task or pass a JS `AbortSignal` alongside `timeoutMs`. The SDK stops waiting and discards late output. The transport and server determine whether remote work stops. For multi-user hosts, create a new managed scope or `ResultSession` per user run. Explicit first reads reserve retention capacity before dispatch. A failed, cancelled or oversized read releases its reservation. Retained result references live until the scope closes or its process exits. The optional file and PostgreSQL stores retain learned tool shapes across runs.
|
|
805
|
+
|
|
806
|
+
## Expose large catalogs on demand
|
|
807
|
+
|
|
808
|
+
```python
|
|
809
|
+
from toolsplice import discover_tools
|
|
810
|
+
with langchain_tools(discover_tools(authorized_tools, question=question), question) as tools:
|
|
811
|
+
agent = create_agent(model=model, tools=tools)
|
|
812
|
+
```
|
|
813
|
+
|
|
814
|
+
```js
|
|
815
|
+
import { discoverTools } from "toolsplice";
|
|
816
|
+
const tools = discoverTools(authorizedTools, { question });
|
|
817
|
+
await withLangChainTools(tools, question, runAgent);
|
|
818
|
+
```
|
|
819
|
+
|
|
820
|
+
Catalogs below 16 tools keep their direct names and schemas. For larger catalogs, passing the question exposes up to two ranked tools immediately, plus discovery and dispatch. Omit the question to start with just those two helper tools. Set `threshold` and `limit` at registration. Discovery returns full input schemas for matches. Dispatch validates the named tool’s arguments before calling it. Ranking is local and adds no model or database dependency. Pass the authorized Toolsplice executables for this run. For a connected MCP client, use the catalog adaptation shown below.
|
|
821
|
+
|
|
822
|
+
## Return a full ordered column on the first read
|
|
823
|
+
|
|
824
|
+
Adaptive reads recognize requests such as “Return every event ID in source order.” When a large result contains that scalar field in every returned row and the column fits the view budget, the response includes the field name, ordered values, row count and `complete: true`. Duplicates and nulls are preserved. An oversized projection returns `complete: false` and the retained rows can be paged by reference. Completeness covers this response's rows. Any upstream pagination still applies. Small native results already contain all their values.
|
|
825
|
+
|
|
826
|
+
## Call tools directly
|
|
827
|
+
|
|
828
|
+
Direct calls do not invoke a model. With an initialized MCP v1 connection and the catalog the current user is authorized to use:
|
|
829
|
+
|
|
830
|
+
```python
|
|
831
|
+
from toolsplice import ResultSession, create_tool_caller, result_tools_from_mcp
|
|
832
|
+
|
|
833
|
+
catalog = (await mcp.list_tools()).model_dump(mode="json", by_alias=True, exclude_none=True)
|
|
834
|
+
remote = result_tools_from_mcp(catalog, create_tool_caller(mcp))
|
|
835
|
+
run = ResultSession()
|
|
836
|
+
try:
|
|
837
|
+
tools = {t.definition["name"]: t for t in run.tools(remote, adaptive_read=question)}
|
|
838
|
+
page = await tools["read_page"].execute({"url": url})
|
|
839
|
+
if isinstance(page, dict) and "ref" in page:
|
|
840
|
+
excerpt = await tools["inspect_result"].execute({"ref": page["ref"]})
|
|
841
|
+
finally:
|
|
842
|
+
run.close()
|
|
843
|
+
```
|
|
844
|
+
|
|
845
|
+
```js
|
|
846
|
+
import { ResultSession, createToolCaller, resultToolsFromMcp } from "toolsplice";
|
|
847
|
+
|
|
848
|
+
const remote = resultToolsFromMcp(await client.listTools(), createToolCaller(client));
|
|
849
|
+
const run = new ResultSession();
|
|
850
|
+
try {
|
|
851
|
+
const tools = run.tools(remote, { adaptiveRead: question });
|
|
852
|
+
const page = await tools.find(t => t.definition.name === "read_page").execute({ url });
|
|
853
|
+
console.log(page);
|
|
854
|
+
} finally {
|
|
855
|
+
run.close();
|
|
856
|
+
}
|
|
857
|
+
```
|
|
858
|
+
|
|
859
|
+
Replace `read_page` with a tool from your server. Supply all authorized pages of a paginated catalog. For a Markdown or text page read with a submitted HTTP(S) URL, the adaptive result can carry the exact string as `requestedUrl`. For a known multi-tool workflow, a prepared tool can validate intermediate mappings and deliver a final result directly. [Prepared workflows and framework options](AGENT-FRAMEWORKS.md)
|