taugraph 0.2.0 → 0.3.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/CHANGELOG.md +62 -0
- package/README.md +232 -18
- package/README.zh-CN.md +232 -18
- package/dist/agent/index.d.ts +66 -0
- package/dist/agent/index.d.ts.map +1 -0
- package/dist/agent/index.js +228 -0
- package/dist/agent/index.js.map +1 -0
- package/dist/agent/state.d.ts +30 -0
- package/dist/agent/state.d.ts.map +1 -0
- package/dist/agent/state.js +135 -0
- package/dist/agent/state.js.map +1 -0
- package/dist/agent/util.d.ts +9 -0
- package/dist/agent/util.d.ts.map +1 -0
- package/dist/agent/util.js +28 -0
- package/dist/agent/util.js.map +1 -0
- package/dist/nodes/content.d.ts +18 -0
- package/dist/nodes/content.d.ts.map +1 -0
- package/dist/nodes/content.js +88 -0
- package/dist/nodes/content.js.map +1 -0
- package/dist/nodes/index.d.ts +2 -1
- package/dist/nodes/index.d.ts.map +1 -1
- package/dist/nodes/index.js +1 -0
- package/dist/nodes/index.js.map +1 -1
- package/dist/nodes/llm.d.ts +98 -4
- package/dist/nodes/llm.d.ts.map +1 -1
- package/dist/nodes/llm.js.map +1 -1
- package/dist/openai/index.d.ts +39 -0
- package/dist/openai/index.d.ts.map +1 -0
- package/dist/openai/index.js +178 -0
- package/dist/openai/index.js.map +1 -0
- package/package.json +15 -3
- package/src/agent/index.ts +315 -0
- package/src/agent/state.ts +147 -0
- package/src/agent/util.ts +35 -0
- package/src/nodes/content.ts +100 -0
- package/src/nodes/index.ts +10 -0
- package/src/nodes/llm.ts +102 -6
- package/src/openai/index.ts +246 -0
package/CHANGELOG.md
ADDED
|
@@ -0,0 +1,62 @@
|
|
|
1
|
+
# Changelog
|
|
2
|
+
|
|
3
|
+
All notable changes to this project are documented here. The format follows [Keep a Changelog](https://keepachangelog.com/en/1.1.0/) and the project uses [Semantic Versioning](https://semver.org/).
|
|
4
|
+
|
|
5
|
+
## [Unreleased]
|
|
6
|
+
|
|
7
|
+
## [0.3.0] - 2026-11-25
|
|
8
|
+
|
|
9
|
+
Tool calling, images and reasoning models in the model contract, plus two plugin entry points: `taugraph/agent` (the model ↔ tools loop as a graph) and `taugraph/openai` (an adapter for any OpenAI-compatible endpoint).
|
|
10
|
+
|
|
11
|
+
### Changed
|
|
12
|
+
|
|
13
|
+
- **Breaking:** the `content` of `user` and `tool` messages is `string | ContentPart[]`, so they can carry images. Code that builds messages is unaffected; code that reads `content` as a string no longer compiles. An adapter that sends text only replaces `m.content` with `textOf(m.content)`, which throws on images unless given `{ imagePlaceholder }`. Template strings, `+` and `String()` still compile but turn parts into `[object Object]`, and JavaScript adapters get no compile error, so search for reads of `content` too.
|
|
14
|
+
- Types: `ChatMessage` is now a union by `role` and includes `role: "tool"`. Code that only reads `role` and `content` is unaffected, and nothing changes at run time for code that sends no tool messages. An adapter that maps `role` into a provider SDK's message type, or switches over `role` exhaustively, needs a `tool` branch; TypeScript points to the line.
|
|
15
|
+
|
|
16
|
+
### Added
|
|
17
|
+
|
|
18
|
+
- Tool calling in the model contract: optional `tools` and `toolChoice` on `LLMRequest`, `toolCalls` on `LLMResponse`, `tool` messages and assistant `toolCalls` in `ChatMessage`. Tool definitions follow MCP (`name`, `description`, `inputSchema`); arguments are parsed JSON.
|
|
19
|
+
- `taugraph/agent`: `createAgent` runs the model ↔ tools loop as a graph with one step per model call and one per tool call, so tracing, replay, write protection, crash recovery and approvals (`approve` → `ctx.interrupt`) apply to each call. `tool()` takes a Standard Schema for arguments and derives the JSON Schema through Standard JSON Schema. Bounded by `maxRounds` (default 8) and 32 calls per reply; calls beyond 32 get error answers after the results of the calls that ran. For adapter authors: assistant messages written by the agent always carry `model`, may carry `reasoning`, and tool calls may carry `signature`; strict endpoints such as OpenAI's refuse these fields, so build the provider's message from `role` and `content` (and tool fields) instead of forwarding messages as they are.
|
|
20
|
+
- `taugraph/openai`: the OpenAI-compatible adapter, formerly an example, as a plugin entry point. `openAICompatible({ baseURL, model, apiKey?, resolveImage?, reasoningParams?, sendReasoning?, fetch? })` adds no dependencies and uses the global `fetch` unless given one. It translates tools, tool calls and tool results (`pnpm example:agent`); missing call ids become `call_<round>_<index>`, and error results that do not already start with `Error` get an `Error: ` prefix because OpenAI's tool messages have no error flag. It sends images, reads image references with `resolveImage`, and moves images from tool results into a user message after the tool messages. It sends `reasoning_effort` or your `reasoningParams`, reads `reasoning_content` and `reasoning`, and sends the model's own reasoning back unless `sendReasoning: false`. `fetch` replaces the global one, e.g. for a proxy, retries or tests.
|
|
21
|
+
- Images in messages: `TextPart`, `ImagePart` (base64 `data` + `mimeType`, or a `url` that may be a reference of your own) and `ContentPart` in `taugraph/nodes`. `resolveImages(messages, resolve)` reads references when a request is sent, so traces can keep a few bytes per image; `textOf(content)` gives the text for text-only adapters.
|
|
22
|
+
- Agent tools can return text and images (`{ content: ContentPart[] }`); the state schema checks parts and points at the bad one.
|
|
23
|
+
- Reasoning models: `reasoning` on `LLMRequest` (seven levels, `"off"` to `"max"`), what the model thought in `LLMResponse.reasoning` and `usage.reasoningTokens`, `ToolCall.signature`, and `reasoning` and `model` on assistant messages, so a tool loop can send a model's own thinking back as DeepSeek V4, Claude and Gemini 3 require. `createAgent({ reasoning })` sets the level for every call and records which model wrote each message.
|
|
24
|
+
|
|
25
|
+
## [0.2.0] - 2026-11-19
|
|
26
|
+
|
|
27
|
+
First release on npm.
|
|
28
|
+
|
|
29
|
+
### Added
|
|
30
|
+
|
|
31
|
+
- Pause and resume: `ctx.interrupt(request)` pauses a run; `graph.resume(trace, value)` / `resumeSync` continues it under the same runId, appending to the same trace. Runs now return `status: "completed" | "paused"`, and paused runs carry `pending: { nodeId, step, request }`.
|
|
32
|
+
- Crash recovery: `resume(trace)` continues a trace that ended without `run_end`. An unfinished `write` step fails with `UNKNOWN_OUTCOME` unless `allowWrites: true`; restarted steps see `ctx.meta.recovered`.
|
|
33
|
+
- Effects: nodes can declare `effect: "read" | "write"` (`defineNode`, `CodeNode`). Replay blocks live `write` nodes with `WRITE_BLOCKED` unless overridden or `allowWrites: true`, including when a paused replay is resumed.
|
|
34
|
+
- Replay feeds values delivered by `resume` back to `ctx.interrupt` when a step sees its recorded state, in both modes.
|
|
35
|
+
- `HumanNode` plugin: pause for an answer, validate it with a schema, ask again with the error.
|
|
36
|
+
- Kernel events `pause` and `resume`; `run_end.meta.status` can be `paused`. Error codes `WRITE_BLOCKED`, `UNKNOWN_OUTCOME`, `NOT_RESUMABLE`, `SINK_FAILED`.
|
|
37
|
+
- Example `examples/checkout.ts`: the model only picks one of a fixed set of commands, and code does the rest.
|
|
38
|
+
|
|
39
|
+
### Changed
|
|
40
|
+
|
|
41
|
+
- `onEvent` failures stop the run with `SINK_FAILED` instead of being rethrown asynchronously while the run continued.
|
|
42
|
+
- `RunResult` is now a union of `CompletedRun` and `PausedRun`; check `status` before reading `pending`.
|
|
43
|
+
- Removed the conventional `human_pause` plugin event type; pausing is now the kernel's `pause` event.
|
|
44
|
+
|
|
45
|
+
## [0.1.0] - 2026-11-19
|
|
46
|
+
|
|
47
|
+
GitHub only, not published to npm.
|
|
48
|
+
|
|
49
|
+
### Added
|
|
50
|
+
|
|
51
|
+
- Kernel: `createGraph` with static validation, sequential and conditional edges, end nodes, `maxSteps`.
|
|
52
|
+
- Runtime: `run` (async) and `runSync` sharing one generator-based loop; per-node retry policy; cancellation via `AbortSignal`.
|
|
53
|
+
- State: Standard Schema validation of input and every node output; JSON-only, deeply frozen state.
|
|
54
|
+
- Trace: append-only event log (format version 1), `onEvent` streaming, `toJSONL` / `fromJSONL`, `diffTraces`.
|
|
55
|
+
- Replay: `graph.replay` with node overrides and `recorded` / `live` modes.
|
|
56
|
+
- Plugin nodes (`taugraph/nodes`): `CodeNode`, `LLMNode` with a provider-agnostic `LLMModel` contract and structured output.
|
|
57
|
+
- Examples: quick start, retrieval with retry loop, OpenAI-compatible adapter.
|
|
58
|
+
|
|
59
|
+
[Unreleased]: https://github.com/wangcao-hub/taugraph/compare/v0.3.0...HEAD
|
|
60
|
+
[0.3.0]: https://github.com/wangcao-hub/taugraph/compare/v0.2.0...v0.3.0
|
|
61
|
+
[0.2.0]: https://github.com/wangcao-hub/taugraph/compare/v0.1.0...v0.2.0
|
|
62
|
+
[0.1.0]: https://github.com/wangcao-hub/taugraph/releases/tag/v0.1.0
|
package/README.md
CHANGED
|
@@ -22,16 +22,79 @@ In reinforcement learning, τ is the standard symbol for a trajectory: the seque
|
|
|
22
22
|
|
|
23
23
|
If a model decides every step and gets each one right 95% of the time, a 3-step flow succeeds about 86% of the time and a 5-step flow about 77%. Better prompts move 95% to 97%, never to 100%. taugraph takes everything that can be written down in advance (what runs next, when to stop and ask, which calls change the world) out of the model and into a typed graph. The model is left with what only it can do, such as understanding a reply and picking one of a few allowed commands.
|
|
24
24
|
|
|
25
|
+
## How it works
|
|
26
|
+
|
|
27
|
+
A model is one kind of node among others. It writes a value into state; code reads that value and decides what happens next.
|
|
28
|
+
|
|
29
|
+
```mermaid
|
|
30
|
+
flowchart LR
|
|
31
|
+
reply(["user reply<br/>resume(trace, value)"]) --> ask
|
|
32
|
+
ask["confirm<br/>HumanNode · ctx.interrupt"] --> classify
|
|
33
|
+
classify["classify<br/>LLMNode<br/>output: one of 4 commands"] --> route{"conditional edge<br/>pure code"}
|
|
34
|
+
route -->|confirm| place["place order<br/>effect: write"]
|
|
35
|
+
route -->|modify| quote["quote<br/>code"]
|
|
36
|
+
route -->|explore| explain["explain<br/>code"]
|
|
37
|
+
route -->|cancel| cancelled["cancelled<br/>code"]
|
|
38
|
+
quote -.-> ask
|
|
39
|
+
explain -.-> ask
|
|
40
|
+
classDef human fill:#fef3c7,stroke:#d97706,color:#111
|
|
41
|
+
classDef model fill:#ede9fe,stroke:#7c3aed,color:#111
|
|
42
|
+
classDef code fill:#e0f2fe,stroke:#0284c7,color:#111
|
|
43
|
+
classDef write fill:#fee2e2,stroke:#dc2626,color:#111
|
|
44
|
+
class reply,ask human
|
|
45
|
+
class classify model
|
|
46
|
+
class route,quote,explain,cancelled code
|
|
47
|
+
class place write
|
|
48
|
+
```
|
|
49
|
+
|
|
50
|
+
<sub>The graph of [`examples/checkout.ts`](./examples/checkout.ts). Yellow waits for a person. Purple is the only place a model runs, and its output must parse as one of four commands. Blue is code you can unit-test. Red changes the outside world, so replays block it unless you allow it.</sub>
|
|
51
|
+
|
|
52
|
+
Everything taugraph does after a run is computed from one append-only log. There is no second store to keep in sync.
|
|
53
|
+
|
|
54
|
+
```mermaid
|
|
55
|
+
flowchart LR
|
|
56
|
+
exec["run · resume"] -- "append, write-ahead" --> trace[("trace · JSONL<br/>state at every step<br/>LLM and tool calls<br/>human answers")]
|
|
57
|
+
trace -- "resume(trace, value)" --> pause["pause and resume<br/>no checkpointer"]
|
|
58
|
+
trace -- "resume(trace)" --> recover["crash recovery<br/>unfinished write: UNKNOWN_OUTCOME"]
|
|
59
|
+
trace -- "replay(trace, overrides)" --> cf["counterfactual replay<br/>writes blocked"]
|
|
60
|
+
trace -- "diffTraces · export" --> evals["regression evals"]
|
|
61
|
+
classDef log fill:#f1f5f9,stroke:#475569,color:#111
|
|
62
|
+
class trace log
|
|
63
|
+
```
|
|
64
|
+
|
|
65
|
+
## What's new in the design
|
|
66
|
+
|
|
67
|
+
1. **The trace is the checkpoint.** Pause, resume and crash recovery are all derived from the append-only log, so the kernel has no checkpointer, thread store or storage interface. Store the JSONL wherever you like. (LangGraph's `interrupt()` needs a checkpointer and a thread id.)
|
|
68
|
+
2. **Counterfactual replay.** A replayed step reuses its recorded output only when it receives exactly the recorded input state; any step that sees a different state runs live. "What if step 2 had used another model?" is one call, and the steps before the first change cost nothing. (LangGraph's replay re-executes every node after the checkpoint, LLM and API calls included. Durable-execution engines such as Temporal treat a divergence from history as a non-determinism error.)
|
|
69
|
+
|
|
70
|
+
```mermaid
|
|
71
|
+
flowchart LR
|
|
72
|
+
s0["step 0 · quote<br/>recorded"] --> s1["step 1 · confirm<br/>recorded answer: make it 2"] --> s2["step 2 · classify<br/>new model says: confirm"] --> s3["step 3 · place order<br/>WRITE_BLOCKED"]
|
|
73
|
+
classDef rec fill:#f1f5f9,stroke:#94a3b8,color:#111
|
|
74
|
+
classDef new fill:#ede9fe,stroke:#7c3aed,color:#111
|
|
75
|
+
classDef stop fill:#fee2e2,stroke:#dc2626,color:#111
|
|
76
|
+
class s0,s1 rec
|
|
77
|
+
class s2 new
|
|
78
|
+
class s3 stop
|
|
79
|
+
```
|
|
80
|
+
|
|
81
|
+
<sub>The checkout conversation replayed with an over-eager classifier. Steps 0 and 1 come from the trace, including the person's answer. The new model reads "make it 2" as a confirmation, so the run would now place an order; the replay stops there instead.</sub>
|
|
82
|
+
|
|
83
|
+
3. **Replays don't repeat side effects unless you say so.** `effect: "write"` is part of the node, not a convention. Replays, and resumed replays, refuse to run a write node live unless you override it or pass `allowWrites: true`. A write that was running when the process died becomes `UNKNOWN_OUTCOME`, never a silent retry.
|
|
84
|
+
4. **Conversations become test cases.** Human answers are stored in the trace as inputs. Replaying a human-in-the-loop run needs no human: each `ctx.interrupt` gets its recorded answer as long as the step sees the recorded state. (LangGraph fires interrupts again on replay.)
|
|
85
|
+
5. **Models choose, code routes.** Routers are synchronous functions of the state; an async router is rejected at run time. A model can only write a schema-checked value into state, such as one of four commands, and the edge reads it. A router cannot await a model call, so model decisions happen in nodes, where the trace records them.
|
|
86
|
+
|
|
25
87
|
## Where it sits
|
|
26
88
|
|
|
27
|
-
|
|
|
28
|
-
|
|
|
29
|
-
| Kernel
|
|
30
|
-
| Orchestration
|
|
31
|
-
| State
|
|
32
|
-
|
|
|
33
|
-
|
|
|
34
|
-
|
|
|
89
|
+
| | Pi | LangGraph | taugraph |
|
|
90
|
+
| --------------- | ------------------------------- | ----------------------------------------- | --------------------------------------------- |
|
|
91
|
+
| Kernel | single-agent loop (LLM ↔ tools) | stateful graph with channels and reducers | graph scheduler + typed state |
|
|
92
|
+
| Orchestration | extension | core | core |
|
|
93
|
+
| State | message transcript | channels, checkpoint per step | one schema-checked, frozen JSON object |
|
|
94
|
+
| Pause for input | the conversation itself | `interrupt()` + a checkpointer | `ctx.interrupt()`, resumed from the trace |
|
|
95
|
+
| Log | append-only session | checkpoints in a persistence backend | append-only event stream with state snapshots |
|
|
96
|
+
| LLM / tools | built in | bring your own, often LangChain | plugin nodes, none in the kernel |
|
|
97
|
+
| Runtime deps | provider SDKs | LangChain core and friends | **none** |
|
|
35
98
|
|
|
36
99
|
## Rules of the kernel
|
|
37
100
|
|
|
@@ -41,7 +104,7 @@ If a model decides every step and gets each one right 95% of the time, a 3-step
|
|
|
41
104
|
4. A run is a serializable trace. Replay it at any time, with any node or model swapped.
|
|
42
105
|
5. No hidden magic. Side effects are recorded as explicit events, and nodes that change the world declare `effect: "write"` so a replay never repeats them.
|
|
43
106
|
6. Sync first, async optional. `runSync` never touches a Promise; no async runtime is assumed.
|
|
44
|
-
7. Zero runtime dependencies. Works in Node ≥ 22, Bun, Deno and browsers.
|
|
107
|
+
7. Zero runtime dependencies. Works in Node ≥ 22, Bun, Deno and browsers (CI runs Node 22 and 24; Bun was checked by hand for 0.3.0, Deno and Chrome for 0.2.0).
|
|
45
108
|
|
|
46
109
|
These are enforced by tests (`test/architecture.test.ts`), not only by convention.
|
|
47
110
|
|
|
@@ -49,7 +112,7 @@ These are enforced by tests (`test/architecture.test.ts`), not only by conventio
|
|
|
49
112
|
|
|
50
113
|
```ts
|
|
51
114
|
import { createGraph, diffTraces, toJSONL } from "taugraph";
|
|
52
|
-
import { CodeNode, LLMNode, type LLMModel } from "taugraph/nodes";
|
|
115
|
+
import { CodeNode, LLMNode, type LLMModel, textOf } from "taugraph/nodes";
|
|
53
116
|
import { z } from "zod";
|
|
54
117
|
|
|
55
118
|
const State = z.object({
|
|
@@ -58,8 +121,11 @@ const State = z.object({
|
|
|
58
121
|
final: z.string().nullable().default(null),
|
|
59
122
|
});
|
|
60
123
|
|
|
61
|
-
// Any provider fits this contract
|
|
62
|
-
const model: LLMModel = {
|
|
124
|
+
// Any provider fits this contract; taugraph/openai covers OpenAI-compatible endpoints.
|
|
125
|
+
const model: LLMModel = {
|
|
126
|
+
id: "mock:echo",
|
|
127
|
+
complete: (req) => ({ content: `echo: ${textOf(req.messages.at(-1)?.content ?? "")}` }),
|
|
128
|
+
};
|
|
63
129
|
|
|
64
130
|
const graph = createGraph(State, {
|
|
65
131
|
start: "fetch",
|
|
@@ -87,6 +153,8 @@ console.log(diffTraces(trace, replay.trace)); // { equal: false, firstDivergence
|
|
|
87
153
|
|
|
88
154
|
State, input and node ids are all inferred from the schema and `nodes`. A typo in an edge, or a node that returns the wrong shape, is a compile error.
|
|
89
155
|
|
|
156
|
+
With TypeScript older than 5.9, a node that returns a literal value (for example `outcome: "ordered"` for a union field) is not inferred; write `CodeNode<State>(...)` there. TypeScript 5.9 and 7 need no annotation.
|
|
157
|
+
|
|
90
158
|
## Concepts
|
|
91
159
|
|
|
92
160
|
### State
|
|
@@ -175,13 +243,13 @@ Every failure is a `TaugraphError` with a `code` (`INVALID_GRAPH`, `INVALID_STAT
|
|
|
175
243
|
|
|
176
244
|
## Plugin nodes (`taugraph/nodes`)
|
|
177
245
|
|
|
178
|
-
| Node | What it does
|
|
179
|
-
| ----------- |
|
|
180
|
-
| `CodeNode` | Deterministic state transformation.
|
|
181
|
-
| `LLMNode` | Calls an `LLMModel
|
|
182
|
-
| `HumanNode` | Pauses for an answer via `ctx.interrupt`, validates it with a schema, asks again if invalid.
|
|
246
|
+
| Node | What it does |
|
|
247
|
+
| ----------- | --------------------------------------------------------------------------------------------------------------- |
|
|
248
|
+
| `CodeNode` | Deterministic state transformation. |
|
|
249
|
+
| `LLMNode` | Calls an `LLMModel` (tools included), records an `llm_call` event, optionally parses JSON output with a schema. |
|
|
250
|
+
| `HumanNode` | Pauses for an answer via `ctx.interrupt`, validates it with a schema, asks again if invalid. |
|
|
183
251
|
|
|
184
|
-
`LLMNode` only defines the call contract (`{ id, complete(request, { signal }) }`); bring
|
|
252
|
+
`LLMNode` only defines the call contract (`{ id, complete(request, { signal }) }`); bring any other provider through a small adapter. [`taugraph/openai`](#openai-compatible-models-taugraphopenai) covers OpenAI-compatible endpoints. Messages can carry images; see [Images](#images).
|
|
185
253
|
|
|
186
254
|
Writing your own node type takes one call to `defineNode`:
|
|
187
255
|
|
|
@@ -204,6 +272,152 @@ export const ToolNode = <S>(tool: Tool, apply: (s: S, out: unknown) => S) =>
|
|
|
204
272
|
);
|
|
205
273
|
```
|
|
206
274
|
|
|
275
|
+
## Agent (`taugraph/agent`)
|
|
276
|
+
|
|
277
|
+
`createAgent` turns the model ↔ tools loop into an ordinary taugraph graph. Each model call and each tool call is a step of its own, so everything above applies to every single call: it is in the trace, replay reuses it, a replay never repeats a write, a crash mid-write stops with `UNKNOWN_OUTCOME`, and a call can wait for a human.
|
|
278
|
+
|
|
279
|
+
```ts
|
|
280
|
+
import { createAgent, tool } from "taugraph/agent";
|
|
281
|
+
import { z } from "zod";
|
|
282
|
+
|
|
283
|
+
const weather = tool({
|
|
284
|
+
name: "weather",
|
|
285
|
+
description: "Today's weather for a city",
|
|
286
|
+
input: z.object({ city: z.string() }), // validates arguments and becomes the JSON Schema the model sees
|
|
287
|
+
run: ({ city }) => `${city}: cloudy, -2~5°C`,
|
|
288
|
+
});
|
|
289
|
+
|
|
290
|
+
const addTodo = tool({
|
|
291
|
+
name: "add_todo",
|
|
292
|
+
effect: "write", // runs in a write step
|
|
293
|
+
input: z.object({ text: z.string() }),
|
|
294
|
+
run: ({ text }) => `added "${text}"`,
|
|
295
|
+
});
|
|
296
|
+
|
|
297
|
+
const agent = createAgent({
|
|
298
|
+
model, // any LLMModel whose adapter supports tools
|
|
299
|
+
tools: [weather, addTodo],
|
|
300
|
+
system: "You help with the day.",
|
|
301
|
+
approve: (call, t) => (t.effect === "write" ? "ask" : "run"),
|
|
302
|
+
});
|
|
303
|
+
|
|
304
|
+
const result = await agent.run({ messages: [{ role: "user", content: "What should I wear today?" }] });
|
|
305
|
+
// paused on add_todo: result.pending.request is { type: "tool_approval", call, effect: "write" }
|
|
306
|
+
const done = await agent.resume(result.trace, true); // or false, or { approved: false, reason }
|
|
307
|
+
console.log(done.state.final);
|
|
308
|
+
```
|
|
309
|
+
|
|
310
|
+
```
|
|
311
|
+
think ──a read call──▶ act ───────┐
|
|
312
|
+
▲ ──a write call─▶ act_write ─┤ more calls: act / act_write
|
|
313
|
+
└───────────────────────────────┘ none left: think
|
|
314
|
+
think ──no calls, or maxRounds──▶ finish
|
|
315
|
+
```
|
|
316
|
+
|
|
317
|
+
- The state is `{ messages, pending, rounds, final, stop }`, validated by a built-in Standard Schema (no validator needed).
|
|
318
|
+
- Tool definitions follow MCP (`name`, `description`, `inputSchema` as JSON Schema). A tool's JSON Schema comes from `inputSchema` if given, else from `input` through [Standard JSON Schema](https://standardschema.dev/json-schema) (Zod 4, Valibot, ArkType).
|
|
319
|
+
- Invalid arguments, unknown tools, unreadable arguments and thrown errors go back to the model as error results; the loop continues.
|
|
320
|
+
- `maxRounds` (default 8) bounds model calls; at most 32 calls run per reply. Each tool run is a `tool_call` event.
|
|
321
|
+
- Models: the call contract gained optional `tools`, `toolChoice` and `toolCalls`, and `tool` messages. An adapter that maps `role` itself needs a `tool` branch. The [OpenAI-compatible adapter](#openai-compatible-models-taugraphopenai) translates them. `pnpm example:agent` runs the whole thing. Tool results may carry images (see [Images](#images)).
|
|
322
|
+
|
|
323
|
+
## OpenAI-compatible models (`taugraph/openai`)
|
|
324
|
+
|
|
325
|
+
`openAICompatible` turns any OpenAI-compatible `/chat/completions` endpoint into an `LLMModel`: OpenAI, DeepSeek, Qwen, Kimi, Ollama, vLLM, LM Studio and others. It translates tool calls, images and reasoning, uses the global `fetch`, and adds no dependencies. The kernel and `taugraph/nodes` contain no provider code; this entry is an optional plugin, like `taugraph/agent`.
|
|
326
|
+
|
|
327
|
+
```ts
|
|
328
|
+
import { openAICompatible } from "taugraph/openai";
|
|
329
|
+
|
|
330
|
+
const model = openAICompatible({
|
|
331
|
+
baseURL: "https://api.deepseek.com",
|
|
332
|
+
model: "deepseek-flash",
|
|
333
|
+
apiKey: process.env.DEEPSEEK_API_KEY,
|
|
334
|
+
});
|
|
335
|
+
```
|
|
336
|
+
|
|
337
|
+
| Option | What it does |
|
|
338
|
+
| ----------------- | ---------------------------------------------------------------------------------------------------- |
|
|
339
|
+
| `baseURL` | The part before `/chat/completions`, e.g. `https://api.openai.com/v1` or `http://localhost:11434/v1` |
|
|
340
|
+
| `model` | The model name the endpoint expects |
|
|
341
|
+
| `apiKey` | Optional; sent as a Bearer token |
|
|
342
|
+
| `resolveImage` | Reads image references such as `media:abc` when a request is sent; see [Images](#images) |
|
|
343
|
+
| `reasoningParams` | Maps a reasoning level to request parameters; see [Reasoning models](#reasoning-models) |
|
|
344
|
+
| `sendReasoning` | `false` stops sending the model's own reasoning back, for endpoints that refuse the field |
|
|
345
|
+
| `fetch` | Used instead of the global `fetch`, e.g. for a proxy, retries or tests |
|
|
346
|
+
|
|
347
|
+
The model's `id` is `openai-compatible:<model>`. It is recorded in every `llm_call` event, and assistant messages with that `model` count as this model's own when reasoning is sent back.
|
|
348
|
+
|
|
349
|
+
Any other provider fits the same contract through a small adapter of your own: an `LLMModel` is `{ id, complete(request, { signal }) }`.
|
|
350
|
+
|
|
351
|
+
## Images
|
|
352
|
+
|
|
353
|
+
User messages and tool results can carry images. Their `content` is then an array of parts, in order; `system` and `assistant` messages stay text.
|
|
354
|
+
|
|
355
|
+
```ts
|
|
356
|
+
const question: ChatMessage = {
|
|
357
|
+
role: "user",
|
|
358
|
+
content: [
|
|
359
|
+
{ type: "text", text: "Which of these is the receipt?" },
|
|
360
|
+
{ type: "image", data: base64, mimeType: "image/png" }, // the bytes, in base64
|
|
361
|
+
{ type: "image", url: "media:9f2c" }, // or a reference the adapter reads when it calls the model
|
|
362
|
+
],
|
|
363
|
+
};
|
|
364
|
+
```
|
|
365
|
+
|
|
366
|
+
- A URL may be `https:`, `data:` or a reference of your own. The trace stores the state at every step and every request, so a base64 image is stored again and again, while a reference costs a few bytes. In `recorded` replay, a step that sees its recorded state reuses its recorded result, so a reference only has to resolve for steps that run again.
|
|
367
|
+
- Tools return images the same way: `run: () => ({ content: [{ type: "text", text: "the page" }, { type: "image", url: "media:shot1" }] })`.
|
|
368
|
+
- An MCP tool result can be returned as it is when it holds text and image blocks; other blocks, such as audio or resources, fail the run, so convert them first.
|
|
369
|
+
- For adapters, `resolveImages(messages, resolve)` turns `data:` URLs into base64 and every other URL into what `resolve` returns. An adapter that sends text only uses `textOf(m.content)`, which throws on images unless given `{ imagePlaceholder }`, so a model never answers about a picture it did not get.
|
|
370
|
+
- The [OpenAI-compatible adapter](#openai-compatible-models-taugraphopenai) sends http(s) and `data:` URLs as they are and reads the rest with `resolveImage`. OpenAI's tool messages take text only, so it moves tool images into a user message right after them.
|
|
371
|
+
|
|
372
|
+
```ts
|
|
373
|
+
const model = openAICompatible({
|
|
374
|
+
baseURL: "https://api.openai.com/v1",
|
|
375
|
+
model: "gpt-4o-mini",
|
|
376
|
+
resolveImage: async (url) => {
|
|
377
|
+
const id = /^media:([\w-]+)$/.exec(url)?.[1];
|
|
378
|
+
if (!id) throw new Error(`Unknown image reference: ${url}`);
|
|
379
|
+
return { type: "image", mimeType: "image/png", data: (await readFile(`media/${id}.png`)).toString("base64") };
|
|
380
|
+
},
|
|
381
|
+
});
|
|
382
|
+
```
|
|
383
|
+
|
|
384
|
+
## Reasoning models
|
|
385
|
+
|
|
386
|
+
`reasoning` on a request says how much the model should think first: `"off"`, `"minimal"`, `"low"`, `"medium"`, `"high"`, `"xhigh"` or `"max"`. Leave it out and the adapter sends nothing, so the model uses its default. Adapters map the level to the provider's setting; one that knows the model's levels rounds to the nearest, and one for a provider that takes a token budget turns levels into budgets.
|
|
387
|
+
|
|
388
|
+
```ts
|
|
389
|
+
const agent = createAgent({ model, tools, reasoning: "high" }); // every model call in the run
|
|
390
|
+
```
|
|
391
|
+
|
|
392
|
+
- Replies carry what the model thought in `response.reasoning` (`{ text, signature?, redacted? }[]`) and its token count in `usage.reasoningTokens`, which is part of `outputTokens`. Both are in the `llm_call` event.
|
|
393
|
+
- Some providers refuse the next request of a tool loop unless the model's earlier thinking comes back unchanged: DeepSeek V4 (`reasoning_content`), Claude (signed thinking blocks) and Gemini 3 (a `thoughtSignature` on the first tool call of a step, kept in `ToolCall.signature`). The agent stores reasoning and signatures in the assistant messages it writes, so the next round sends them.
|
|
394
|
+
- A signature is only valid for the model that wrote it, so every assistant message the agent writes records `model`, the `LLMModel.id`. Adapters send reasoning and signatures back only when `m.model` is their own `id`, so a replay that swaps the model never sends one model's signatures to another.
|
|
395
|
+
- Assistant messages record `model`, so a replay that swaps the model diverges at the first model call that runs again, even if the new model answers the same; later steps run live and write steps stop with `WRITE_BLOCKED`.
|
|
396
|
+
- The [OpenAI-compatible adapter](#openai-compatible-models-taugraphopenai) sends the level as `reasoning_effort` as it is (`"off"` as `"none"`), reads `reasoning_content` or `reasoning` from replies, and sends its own `reasoning_content` back; set `sendReasoning: false` for endpoints that refuse that field, such as Groq and Cerebras. When a provider has its own switch, or refuses a level, map levels in `reasoningParams`:
|
|
397
|
+
|
|
398
|
+
```ts
|
|
399
|
+
// DeepSeek V4: a thinking switch; it maps the levels itself
|
|
400
|
+
const deepseek = (level: ReasoningLevel) =>
|
|
401
|
+
level === "off" ? { thinking: { type: "disabled" } } : { thinking: { type: "enabled" }, reasoning_effort: level };
|
|
402
|
+
// Qwen on vLLM or SGLang
|
|
403
|
+
const qwen = (level: ReasoningLevel) => ({ chat_template_kwargs: { enable_thinking: level !== "off" } });
|
|
404
|
+
|
|
405
|
+
const model = openAICompatible({
|
|
406
|
+
baseURL: "https://api.deepseek.com",
|
|
407
|
+
model: "deepseek-flash",
|
|
408
|
+
reasoningParams: deepseek,
|
|
409
|
+
});
|
|
410
|
+
```
|
|
411
|
+
|
|
412
|
+
## Integrations
|
|
413
|
+
|
|
414
|
+
| Package | Use it to |
|
|
415
|
+
| ----------------------------------------------------------- | --------------------------------------------------------------------------------------------------------------------------- |
|
|
416
|
+
| [taugraph-mcp](https://github.com/wangcao-hub/taugraph-mcp) | Serve flows as MCP tools to any MCP client: Claude, Cursor, Kiro, AgentScope Java and others. `npx -y taugraph-mcp ./flows` |
|
|
417
|
+
| [taugraph-pi](https://github.com/wangcao-hub/taugraph-pi) | Run flows as tools inside the [Pi](https://pi.dev) coding agent. `pi install npm:taugraph-pi` |
|
|
418
|
+
|
|
419
|
+
Both keep the trace format, so runs recorded through them can be replayed and diffed with this package.
|
|
420
|
+
|
|
207
421
|
## Not in the kernel, on purpose
|
|
208
422
|
|
|
209
423
|
Persistence backends, distributed workers, parallel nodes, nested subgraphs, built-in tools, memory, vector stores, visual editors, event routing, triggers and schedulers. Parallel calls inside one step are fine: use `Promise.all` in a node. Some will arrive as separate plugin packages; none will enter the kernel.
|