@restatedev/agents 0.0.0-stage → 0.1.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/LICENSE +21 -0
- package/README.md +689 -2
- package/dist/calls.d.ts +29 -0
- package/dist/calls.d.ts.map +1 -0
- package/dist/calls.js +91 -0
- package/dist/calls.js.map +1 -0
- package/dist/claude/conversation.d.ts +33 -0
- package/dist/claude/conversation.d.ts.map +1 -0
- package/dist/claude/conversation.js +95 -0
- package/dist/claude/conversation.js.map +1 -0
- package/dist/claude/index.d.ts +78 -0
- package/dist/claude/index.d.ts.map +1 -0
- package/dist/claude/index.js +269 -0
- package/dist/claude/index.js.map +1 -0
- package/dist/client.d.ts +83 -0
- package/dist/client.d.ts.map +1 -0
- package/dist/client.js +88 -0
- package/dist/client.js.map +1 -0
- package/dist/common.d.ts +284 -0
- package/dist/common.d.ts.map +1 -0
- package/dist/common.js +475 -0
- package/dist/common.js.map +1 -0
- package/dist/deepseek/index.d.ts +69 -0
- package/dist/deepseek/index.d.ts.map +1 -0
- package/dist/deepseek/index.js +381 -0
- package/dist/deepseek/index.js.map +1 -0
- package/dist/deepseek/persistence.d.ts +61 -0
- package/dist/deepseek/persistence.d.ts.map +1 -0
- package/dist/deepseek/persistence.js +224 -0
- package/dist/deepseek/persistence.js.map +1 -0
- package/dist/index.d.ts +15 -0
- package/dist/index.d.ts.map +1 -0
- package/dist/index.js +37 -0
- package/dist/index.js.map +1 -0
- package/dist/langgraph/checkpointer.d.ts +29 -0
- package/dist/langgraph/checkpointer.d.ts.map +1 -0
- package/dist/langgraph/checkpointer.js +275 -0
- package/dist/langgraph/checkpointer.js.map +1 -0
- package/dist/langgraph/index.d.ts +67 -0
- package/dist/langgraph/index.d.ts.map +1 -0
- package/dist/langgraph/index.js +265 -0
- package/dist/langgraph/index.js.map +1 -0
- package/dist/log.d.ts +29 -0
- package/dist/log.d.ts.map +1 -0
- package/dist/log.js +145 -0
- package/dist/log.js.map +1 -0
- package/dist/object.d.ts +181 -0
- package/dist/object.d.ts.map +1 -0
- package/dist/object.js +232 -0
- package/dist/object.js.map +1 -0
- package/dist/opencode/db.d.ts +40 -0
- package/dist/opencode/db.d.ts.map +1 -0
- package/dist/opencode/db.js +161 -0
- package/dist/opencode/db.js.map +1 -0
- package/dist/opencode/index.d.ts +101 -0
- package/dist/opencode/index.d.ts.map +1 -0
- package/dist/opencode/index.js +464 -0
- package/dist/opencode/index.js.map +1 -0
- package/dist/output.d.ts +17 -0
- package/dist/output.d.ts.map +1 -0
- package/dist/output.js +81 -0
- package/dist/output.js.map +1 -0
- package/dist/pi/index.d.ts +90 -0
- package/dist/pi/index.d.ts.map +1 -0
- package/dist/pi/index.js +313 -0
- package/dist/pi/index.js.map +1 -0
- package/dist/pi/storage.d.ts +5 -0
- package/dist/pi/storage.d.ts.map +1 -0
- package/dist/pi/storage.js +41 -0
- package/dist/pi/storage.js.map +1 -0
- package/dist/signals.d.ts +195 -0
- package/dist/signals.d.ts.map +1 -0
- package/dist/signals.js +258 -0
- package/dist/signals.js.map +1 -0
- package/dist/tools.d.ts +158 -0
- package/dist/tools.d.ts.map +1 -0
- package/dist/tools.js +211 -0
- package/dist/tools.js.map +1 -0
- package/dist/webhook.d.ts +73 -0
- package/dist/webhook.d.ts.map +1 -0
- package/dist/webhook.js +104 -0
- package/dist/webhook.js.map +1 -0
- package/package.json +224 -3
- package/src/calls.ts +138 -0
- package/src/claude/README.md +84 -0
- package/src/claude/conversation.ts +114 -0
- package/src/claude/index.ts +364 -0
- package/src/client.ts +179 -0
- package/src/common.ts +593 -0
- package/src/deepseek/README.md +110 -0
- package/src/deepseek/index.ts +487 -0
- package/src/deepseek/persistence.ts +293 -0
- package/src/index.ts +60 -0
- package/src/langgraph/README.md +87 -0
- package/src/langgraph/checkpointer.ts +364 -0
- package/src/langgraph/index.ts +349 -0
- package/src/log.ts +193 -0
- package/src/object.ts +343 -0
- package/src/opencode/README.md +125 -0
- package/src/opencode/db.ts +223 -0
- package/src/opencode/index.ts +595 -0
- package/src/output.ts +95 -0
- package/src/pi/README.md +105 -0
- package/src/pi/index.ts +402 -0
- package/src/pi/storage.ts +65 -0
- package/src/signals.ts +426 -0
- package/src/tools.ts +343 -0
- package/src/webhook.ts +163 -0
|
@@ -0,0 +1,293 @@
|
|
|
1
|
+
// The DeepSeek Harness's session persistence (`ctx.sessionPersistence`) over
|
|
2
|
+
// a Restate virtual object's SQL database: each session's header, and its
|
|
3
|
+
// event log, one row per event, in order.
|
|
4
|
+
//
|
|
5
|
+
// The harness writes a session through a handle: `append` accepts a batch,
|
|
6
|
+
// and `flush` is the durability barrier. Here an append is kept in memory and
|
|
7
|
+
// a flush stores everything appended before it in one SQL transaction; a new
|
|
8
|
+
// session's header is stored with its first flush, so a session that crashed
|
|
9
|
+
// before then never existed. The session checkpoint policy
|
|
10
|
+
// (dsh-session-checkpoint-policy) flushes before each model request, before
|
|
11
|
+
// each tool body, and before each step; so the events a tool's call follows
|
|
12
|
+
// from are stored before the tool runs, and a crash loses only events that
|
|
13
|
+
// nothing has acted on.
|
|
14
|
+
import type { Context } from '@deepseek-ai/cordis';
|
|
15
|
+
import { SessionLogOffset, type SessionEvent, type SessionHeader, type SessionId } from '@deepseek-ai/dsh-session';
|
|
16
|
+
import {
|
|
17
|
+
SessionAlreadyExistsError,
|
|
18
|
+
SessionAlreadyOwnedError,
|
|
19
|
+
SessionHandleClosedError,
|
|
20
|
+
SessionPersistence,
|
|
21
|
+
SessionPersistenceNotFoundError,
|
|
22
|
+
SessionPersistenceRevision,
|
|
23
|
+
SessionReadOnlyError,
|
|
24
|
+
assertContiguous,
|
|
25
|
+
materializeAppendBatch,
|
|
26
|
+
materializeCreateHeader,
|
|
27
|
+
validateStoredEvents,
|
|
28
|
+
type SessionAccess,
|
|
29
|
+
type SessionHandle,
|
|
30
|
+
type SessionHandleReadResult,
|
|
31
|
+
type SessionPersistenceCreateOptions,
|
|
32
|
+
type SessionPersistenceSnapshot,
|
|
33
|
+
} from '@deepseek-ai/dsh-session-persistence';
|
|
34
|
+
import type { Database } from '@restatedev/sessions';
|
|
35
|
+
import { Schema } from '@restatedev/sessions/internal';
|
|
36
|
+
|
|
37
|
+
const SCHEMA = new Schema('restate-agents.deepseek', [
|
|
38
|
+
'CREATE TABLE restate_deepseek_sessions (id TEXT PRIMARY KEY, header TEXT NOT NULL, inherited INTEGER NOT NULL)',
|
|
39
|
+
'CREATE TABLE restate_deepseek_events (session TEXT NOT NULL, seq INTEGER NOT NULL, event TEXT NOT NULL, PRIMARY KEY (session, seq))',
|
|
40
|
+
]);
|
|
41
|
+
|
|
42
|
+
/** The stored events of session `id`, in order: for reading the log without a harness. */
|
|
43
|
+
export async function storedEvents(db: Database, id: SessionId): Promise<SessionEvent[]> {
|
|
44
|
+
await SCHEMA.ensure(db);
|
|
45
|
+
const rows = await db.values('SELECT event FROM restate_deepseek_events WHERE session = ? ORDER BY seq', [id]);
|
|
46
|
+
return rows.map(([event]) => JSON.parse(String(event)) as SessionEvent);
|
|
47
|
+
}
|
|
48
|
+
|
|
49
|
+
/** A session as stored: its header, inherited prefix length and event count. */
|
|
50
|
+
interface Stored {
|
|
51
|
+
header: SessionHeader;
|
|
52
|
+
inherited: number;
|
|
53
|
+
count: number;
|
|
54
|
+
}
|
|
55
|
+
|
|
56
|
+
/** The harness's session persistence (a cordis plugin, `{ db }`): see the top of this file. */
|
|
57
|
+
export class SqlSessionPersistence extends SessionPersistence {
|
|
58
|
+
// Plain fields, not private ones: cordis hands out the service through a proxy.
|
|
59
|
+
db: Database;
|
|
60
|
+
schema: Promise<void> | undefined;
|
|
61
|
+
queue: Promise<unknown> = Promise.resolve();
|
|
62
|
+
/** The open write handle of each session, by id. */
|
|
63
|
+
writers = new Map<SessionId, SqlSessionHandle>();
|
|
64
|
+
/** Sessions created and not stored yet: their headers and inherited counts, by id. */
|
|
65
|
+
created = new Map<SessionId, Omit<Stored, 'count'>>();
|
|
66
|
+
handles = new Set<SqlSessionHandle>();
|
|
67
|
+
abandoned = false;
|
|
68
|
+
|
|
69
|
+
/** `config.db`: the object's database (`ctx.db`). */
|
|
70
|
+
constructor(ctx: Context, config: { db: Database }) {
|
|
71
|
+
super(ctx);
|
|
72
|
+
this.db = config.db;
|
|
73
|
+
// The live session's events go to its write handle; its flushes and its
|
|
74
|
+
// disposal reach the handle too.
|
|
75
|
+
ctx.on('session/event', (session, event) => this.writers.get(session.id)?.enqueue(event));
|
|
76
|
+
ctx.on('session/flush', (session) => this.writers.get(session.id)?.flush());
|
|
77
|
+
ctx.on('session/disposed', (session) => void this.writers.get(session.id)?.close());
|
|
78
|
+
ctx.effect(
|
|
79
|
+
() => async () => {
|
|
80
|
+
await Promise.all([...this.handles].map((handle) => handle.close()));
|
|
81
|
+
},
|
|
82
|
+
'sql session handles',
|
|
83
|
+
);
|
|
84
|
+
}
|
|
85
|
+
|
|
86
|
+
/**
|
|
87
|
+
* Store nothing more: what is not stored yet is lost, as in a crash. For an
|
|
88
|
+
* attempt that fails, so that its retry resumes from the last checkpoint.
|
|
89
|
+
*/
|
|
90
|
+
abandon() {
|
|
91
|
+
this.abandoned = true;
|
|
92
|
+
}
|
|
93
|
+
|
|
94
|
+
/** Run `operation` on the database after the ones before it: it serves one statement at a time. */
|
|
95
|
+
serial<T>(operation: (db: Database) => Promise<T>): Promise<T> {
|
|
96
|
+
if (this.abandoned) return Promise.reject(new Error('sql session persistence: abandoned'));
|
|
97
|
+
this.schema ??= SCHEMA.ensure(this.db);
|
|
98
|
+
const result = this.queue.then(() => this.schema).then(() => operation(this.db));
|
|
99
|
+
this.queue = result.catch(() => {});
|
|
100
|
+
return result;
|
|
101
|
+
}
|
|
102
|
+
|
|
103
|
+
async stored(id: SessionId): Promise<Stored | undefined> {
|
|
104
|
+
const created = this.created.get(id);
|
|
105
|
+
if (created) return { ...created, count: 0 };
|
|
106
|
+
const [row] = await this.serial((db) =>
|
|
107
|
+
db.values(
|
|
108
|
+
'SELECT header, inherited, (SELECT count(*) FROM restate_deepseek_events WHERE session = id) FROM restate_deepseek_sessions WHERE id = ?',
|
|
109
|
+
[id],
|
|
110
|
+
),
|
|
111
|
+
);
|
|
112
|
+
return row && { header: JSON.parse(String(row[0])), inherited: Number(row[1]), count: Number(row[2]) };
|
|
113
|
+
}
|
|
114
|
+
|
|
115
|
+
async create(header: SessionHeader, options: SessionPersistenceCreateOptions = {}): Promise<SessionHandle> {
|
|
116
|
+
const meta = materializeCreateHeader(header);
|
|
117
|
+
if (await this.stored(meta.id)) throw new SessionAlreadyExistsError(meta.id);
|
|
118
|
+
const inherited = options.inheritedEventCount ?? 0;
|
|
119
|
+
this.created.set(meta.id, { header: meta, inherited });
|
|
120
|
+
return this.openHandle(meta, inherited, 0, 'write');
|
|
121
|
+
}
|
|
122
|
+
|
|
123
|
+
async open(id: SessionId, access: SessionAccess): Promise<SessionHandle> {
|
|
124
|
+
const stored = await this.stored(id);
|
|
125
|
+
if (!stored) throw new SessionPersistenceNotFoundError(id);
|
|
126
|
+
if (access === 'write' && this.writers.has(id)) throw new SessionAlreadyOwnedError(id);
|
|
127
|
+
return this.openHandle(stored.header, stored.inherited, stored.count, access);
|
|
128
|
+
}
|
|
129
|
+
|
|
130
|
+
openHandle(header: SessionHeader, inherited: number, count: number, access: SessionAccess): SqlSessionHandle {
|
|
131
|
+
const handle: SqlSessionHandle = new SqlSessionHandle(this, header, inherited, count, access, () => {
|
|
132
|
+
this.handles.delete(handle);
|
|
133
|
+
if (this.writers.get(handle.id) === handle) this.writers.delete(handle.id);
|
|
134
|
+
});
|
|
135
|
+
this.handles.add(handle);
|
|
136
|
+
if (access === 'write') this.writers.set(handle.id, handle);
|
|
137
|
+
return handle;
|
|
138
|
+
}
|
|
139
|
+
|
|
140
|
+
async flush(): Promise<void> {
|
|
141
|
+
const results = await Promise.allSettled([...this.writers.values()].map((writer) => writer.flush()));
|
|
142
|
+
const errors = results.flatMap((r) => (r.status === 'rejected' ? [r.reason] : []));
|
|
143
|
+
if (errors.length > 0) throw new AggregateError(errors, 'sql session persistence: flush failed');
|
|
144
|
+
}
|
|
145
|
+
|
|
146
|
+
async stat(id: SessionId): Promise<SessionPersistenceSnapshot | undefined> {
|
|
147
|
+
const stored = await this.stored(id);
|
|
148
|
+
return stored && snapshot(stored);
|
|
149
|
+
}
|
|
150
|
+
|
|
151
|
+
async list(): Promise<readonly SessionPersistenceSnapshot[]> {
|
|
152
|
+
const rows = await this.serial((db) =>
|
|
153
|
+
db.values(
|
|
154
|
+
'SELECT header, inherited, (SELECT count(*) FROM restate_deepseek_events WHERE session = id) FROM restate_deepseek_sessions',
|
|
155
|
+
),
|
|
156
|
+
);
|
|
157
|
+
return [
|
|
158
|
+
...[...this.created.values()].map((created) => snapshot({ ...created, count: 0 })),
|
|
159
|
+
...rows.map(([header, inherited, count]) =>
|
|
160
|
+
snapshot({ header: JSON.parse(String(header)), inherited: Number(inherited), count: Number(count) }),
|
|
161
|
+
),
|
|
162
|
+
];
|
|
163
|
+
}
|
|
164
|
+
}
|
|
165
|
+
|
|
166
|
+
// The log is append-only, so its length identifies its revision.
|
|
167
|
+
const snapshot = ({ header, count }: Stored): SessionPersistenceSnapshot => ({
|
|
168
|
+
header,
|
|
169
|
+
revision: SessionPersistenceRevision(`${header.id}:${count}`),
|
|
170
|
+
eventCount: count,
|
|
171
|
+
});
|
|
172
|
+
|
|
173
|
+
/** One open session: its stored events, and for a write handle the ones appended and not yet stored. */
|
|
174
|
+
class SqlSessionHandle implements SessionHandle {
|
|
175
|
+
readonly id: SessionId;
|
|
176
|
+
readonly header: SessionHeader;
|
|
177
|
+
readonly inheritedEventCount: SessionLogOffset;
|
|
178
|
+
readonly access: SessionAccess;
|
|
179
|
+
#store: SqlSessionPersistence;
|
|
180
|
+
#release: () => void;
|
|
181
|
+
#stored: number; // events stored
|
|
182
|
+
#pending: SessionEvent[] = []; // appended, not stored yet
|
|
183
|
+
#flushing: Promise<void> = Promise.resolve();
|
|
184
|
+
#closed = false;
|
|
185
|
+
|
|
186
|
+
constructor(
|
|
187
|
+
store: SqlSessionPersistence,
|
|
188
|
+
header: SessionHeader,
|
|
189
|
+
inherited: number,
|
|
190
|
+
stored: number,
|
|
191
|
+
access: SessionAccess,
|
|
192
|
+
release: () => void,
|
|
193
|
+
) {
|
|
194
|
+
this.#store = store;
|
|
195
|
+
this.header = header;
|
|
196
|
+
this.id = header.id;
|
|
197
|
+
this.inheritedEventCount = SessionLogOffset(inherited);
|
|
198
|
+
this.access = access;
|
|
199
|
+
this.#stored = stored;
|
|
200
|
+
this.#release = release;
|
|
201
|
+
}
|
|
202
|
+
|
|
203
|
+
#check(operation: string) {
|
|
204
|
+
if (this.#closed) throw new SessionHandleClosedError(this.id, operation);
|
|
205
|
+
}
|
|
206
|
+
|
|
207
|
+
/** The next seq: after every stored and appended event. */
|
|
208
|
+
get #end() {
|
|
209
|
+
return this.#stored + this.#pending.length;
|
|
210
|
+
}
|
|
211
|
+
|
|
212
|
+
async read(offset = 0, length = Infinity): Promise<SessionHandleReadResult> {
|
|
213
|
+
this.#check('read');
|
|
214
|
+
const rows = await this.#store.serial((db) =>
|
|
215
|
+
db.values('SELECT event FROM restate_deepseek_events WHERE session = ? AND seq >= ? ORDER BY seq', [
|
|
216
|
+
this.id,
|
|
217
|
+
offset,
|
|
218
|
+
]),
|
|
219
|
+
);
|
|
220
|
+
let events: SessionEvent[] = [
|
|
221
|
+
...rows.map(([event]) => JSON.parse(String(event)) as SessionEvent),
|
|
222
|
+
...this.#pending.filter((e) => e.seq >= offset),
|
|
223
|
+
];
|
|
224
|
+
if (offset === 0) events = validateStoredEvents(this.header, events);
|
|
225
|
+
return { eventState: 'detached', events: events.slice(0, length) };
|
|
226
|
+
}
|
|
227
|
+
|
|
228
|
+
async append(events: readonly SessionEvent[]): Promise<void> {
|
|
229
|
+
this.#check('append');
|
|
230
|
+
if (this.access !== 'write') throw new SessionReadOnlyError(this.id, 'append');
|
|
231
|
+
const batch = materializeAppendBatch(events);
|
|
232
|
+
assertContiguous(this.id, batch, this.#end);
|
|
233
|
+
this.#pending.push(...batch);
|
|
234
|
+
}
|
|
235
|
+
|
|
236
|
+
/** A live session's event, routed here by the persistence service. */
|
|
237
|
+
enqueue(event: SessionEvent) {
|
|
238
|
+
if (this.#closed || event.seq < this.#end) return;
|
|
239
|
+
this.#pending.push(...materializeAppendBatch([event]));
|
|
240
|
+
}
|
|
241
|
+
|
|
242
|
+
/** Store every event appended so far, in one transaction. */
|
|
243
|
+
flush(): Promise<void> {
|
|
244
|
+
this.#check('flush');
|
|
245
|
+
if (this.access !== 'write') throw new SessionReadOnlyError(this.id, 'flush');
|
|
246
|
+
this.#flushing = this.#flushing.then(() => this.#write());
|
|
247
|
+
return this.#flushing;
|
|
248
|
+
}
|
|
249
|
+
|
|
250
|
+
/** Store the events appended so far, and the session's header the first time, in one transaction. */
|
|
251
|
+
async #write(): Promise<void> {
|
|
252
|
+
const batch = this.#pending.slice();
|
|
253
|
+
const created = this.#store.created.get(this.id);
|
|
254
|
+
if (batch.length === 0 && !created) return;
|
|
255
|
+
await this.#store.serial((db) =>
|
|
256
|
+
db.transaction(async (tx) => {
|
|
257
|
+
if (created) {
|
|
258
|
+
await tx.execute('INSERT INTO restate_deepseek_sessions (id, header, inherited) VALUES (?, ?, ?)', [
|
|
259
|
+
this.id,
|
|
260
|
+
JSON.stringify(created.header),
|
|
261
|
+
created.inherited,
|
|
262
|
+
]);
|
|
263
|
+
}
|
|
264
|
+
for (const event of batch) {
|
|
265
|
+
await tx.execute('INSERT INTO restate_deepseek_events (session, seq, event) VALUES (?, ?, ?)', [
|
|
266
|
+
this.id,
|
|
267
|
+
event.seq,
|
|
268
|
+
JSON.stringify(event),
|
|
269
|
+
]);
|
|
270
|
+
}
|
|
271
|
+
}),
|
|
272
|
+
);
|
|
273
|
+
if (created) this.#store.created.delete(this.id);
|
|
274
|
+
this.#pending.splice(0, batch.length);
|
|
275
|
+
this.#stored += batch.length;
|
|
276
|
+
}
|
|
277
|
+
|
|
278
|
+
async close(): Promise<void> {
|
|
279
|
+
if (this.#closed) return;
|
|
280
|
+
try {
|
|
281
|
+
if (this.access === 'write') await this.flush().catch(() => {});
|
|
282
|
+
} finally {
|
|
283
|
+
this.#closed = true;
|
|
284
|
+
// A session never stored is gone with its writer.
|
|
285
|
+
if (this.access === 'write') this.#store.created.delete(this.id);
|
|
286
|
+
this.#release();
|
|
287
|
+
}
|
|
288
|
+
}
|
|
289
|
+
|
|
290
|
+
[Symbol.asyncDispose]() {
|
|
291
|
+
return this.close();
|
|
292
|
+
}
|
|
293
|
+
}
|
package/src/index.ts
ADDED
|
@@ -0,0 +1,60 @@
|
|
|
1
|
+
// @restatedev/agents: agent frameworks in Restate session objects. Each framework
|
|
2
|
+
// is a subpath (@restatedev/agents/pi, /opencode, /langgraph, /claude,
|
|
3
|
+
// /deepseek); this is what they share: session objects, tools for
|
|
4
|
+
// any of them, and the tools that are Restate itself.
|
|
5
|
+
import { sdk as restate } from '@restatedev/sessions/internal';
|
|
6
|
+
import { signals } from './signals.ts';
|
|
7
|
+
|
|
8
|
+
export {
|
|
9
|
+
CANCELLED,
|
|
10
|
+
chatHandler,
|
|
11
|
+
type ChatMessage,
|
|
12
|
+
type Messages,
|
|
13
|
+
type MessagesRequest,
|
|
14
|
+
type Part,
|
|
15
|
+
REFUSED,
|
|
16
|
+
type Turn,
|
|
17
|
+
UNANSWERED,
|
|
18
|
+
type Configure,
|
|
19
|
+
} from './common.ts';
|
|
20
|
+
export { sessionObject, type Status, type Stopped } from './object.ts';
|
|
21
|
+
export {
|
|
22
|
+
companionOf,
|
|
23
|
+
deliver,
|
|
24
|
+
signals,
|
|
25
|
+
type Companion,
|
|
26
|
+
type Resolved,
|
|
27
|
+
type Signal,
|
|
28
|
+
type Steer,
|
|
29
|
+
type Steered,
|
|
30
|
+
type Waiting,
|
|
31
|
+
} from './signals.ts';
|
|
32
|
+
export { call, send, signal, subagent, tool, workflow, type Tool, type ToolCall, type ToolContext } from './tools.ts';
|
|
33
|
+
export { webhook, webhookMessage, type WebhookAuth, type WebhookEvent, type WebhookOptions } from './webhook.ts';
|
|
34
|
+
|
|
35
|
+
/**
|
|
36
|
+
* Serve `services` on PORT (default 9080), with what the agents need beside
|
|
37
|
+
* them (the `signals` object). RESTATE_SERVE_ONLY, names separated by commas
|
|
38
|
+
* (`triage,planner,signals`), serves only those of them: one image, deployed
|
|
39
|
+
* in parts. The agents reach `signals` through Restate, so one part serves it
|
|
40
|
+
* for them all.
|
|
41
|
+
*/
|
|
42
|
+
export const serve = (...services: restate.ServeOptions['services']) =>
|
|
43
|
+
restate.serve({
|
|
44
|
+
services: only([...services.filter((s) => s !== signals), signals], process.env.RESTATE_SERVE_ONLY),
|
|
45
|
+
port: Number(process.env.PORT ?? 9080),
|
|
46
|
+
});
|
|
47
|
+
|
|
48
|
+
/** The `services` that `names` (comma separated) names, or all of them without names; a name of none is an error. */
|
|
49
|
+
function only(services: restate.ServeOptions['services'], names: string | undefined) {
|
|
50
|
+
const wanted = (names ?? '')
|
|
51
|
+
.split(',')
|
|
52
|
+
.map((name) => name.trim())
|
|
53
|
+
.filter(Boolean);
|
|
54
|
+
if (wanted.length === 0) return services;
|
|
55
|
+
const known = services.map((s) => s.name);
|
|
56
|
+
const unknown = wanted.filter((name) => !known.includes(name));
|
|
57
|
+
if (unknown.length > 0)
|
|
58
|
+
throw new Error(`RESTATE_SERVE_ONLY names ${unknown.join(', ')}: the services are ${known.join(', ')}`);
|
|
59
|
+
return services.filter((s) => wanted.includes(s.name));
|
|
60
|
+
}
|
|
@@ -0,0 +1,87 @@
|
|
|
1
|
+
# LangGraph
|
|
2
|
+
|
|
3
|
+
[LangGraph](https://langchain-ai.github.io/langgraphjs/) runs an agent as a
|
|
4
|
+
graph of steps and stores a checkpoint after each one, so a run can resume
|
|
5
|
+
where it stopped. Here the checkpoints are in the agent's SQL database
|
|
6
|
+
([SQL in Restate virtual objects](../../../sessions/README.md)), and the thread is
|
|
7
|
+
the object's key.
|
|
8
|
+
|
|
9
|
+
## Use
|
|
10
|
+
|
|
11
|
+
```ts
|
|
12
|
+
import { serve } from '@restatedev/agents';
|
|
13
|
+
import * as langgraph from '@restatedev/agents/langgraph';
|
|
14
|
+
import { weather } from './weather.ts';
|
|
15
|
+
|
|
16
|
+
const assistant = langgraph.agent({ name: 'assistant', system: 'Answer briefly.', tools: [weather] });
|
|
17
|
+
await serve(assistant);
|
|
18
|
+
```
|
|
19
|
+
|
|
20
|
+
| Option | What |
|
|
21
|
+
| -------- | ---------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- |
|
|
22
|
+
| `model` | `openai/model-id` (`ChatOpenAI`) or `anthropic/model-id` (`ChatAnthropic`); or else `MODEL`, or else `openai/gpt-6-sol` (`OPENAI_API_KEY`); or any LangChain chat model that calls tools |
|
|
23
|
+
| `system` | The system prompt |
|
|
24
|
+
| `tools` | `tool()`s and Restate's tools of `@restatedev/agents`, or LangChain's tools |
|
|
25
|
+
| `output` | A zod object: the answer as data, which the agent replies with as JSON, and `chat` answers with (see [Structured answers](../../README.md#structured-answers)) |
|
|
26
|
+
|
|
27
|
+
For a session object of your own, `langgraph.chat(options)` is the handler and
|
|
28
|
+
`langgraph.messages()` the view; `options` may be a function of the
|
|
29
|
+
invocation's context (each user's system prompt, say). `langgraph.prompt(ctx,
|
|
30
|
+
text, options)` answers a prompt in a handler of your own, once, however
|
|
31
|
+
often the handler runs; each prompt of an invocation is a prompt of its own. The graph is the usual tool-calling
|
|
32
|
+
loop: a model node, a tools node, and back to the model until it answers.
|
|
33
|
+
|
|
34
|
+
## Through crashes
|
|
35
|
+
|
|
36
|
+
The checkpointer ([`checkpointer.ts`](checkpointer.ts), `SqlCheckpointSaver`)
|
|
37
|
+
keeps checkpoints, channel values and pending writes in three tables; a step
|
|
38
|
+
stores only the channels it changed. An agent's thread keeps its latest
|
|
39
|
+
checkpoint only (`history: 'latest'`), as each step changes the message
|
|
40
|
+
list: kept at every step, it would grow with the square of the
|
|
41
|
+
conversation. `new SqlCheckpointSaver(db)` of your own graph keeps them all,
|
|
42
|
+
for LangGraph's history. The handler is not replayed: a retried
|
|
43
|
+
attempt runs it again from the start, and LangGraph carries on from the last
|
|
44
|
+
step it stored.
|
|
45
|
+
|
|
46
|
+
- **Each step is stored before the next starts** (`durability: 'sync'`). So
|
|
47
|
+
the tool calls a model made are stored before any tool runs, and a crash
|
|
48
|
+
during the tools resumes them with the same tool call ids, without asking
|
|
49
|
+
the model again.
|
|
50
|
+
- **A tool is idempotent by its tool call id** (`callId` of `tool()`'s
|
|
51
|
+
`run`), which it passes on, such as in an idempotency key.
|
|
52
|
+
- **A tool's error fails the attempt**, and Restate retries it (the ToolNode
|
|
53
|
+
would hand it to the model); a `restate.TerminalError` of a
|
|
54
|
+
`@restatedev/agents` tool is its answer to the model, and so are arguments
|
|
55
|
+
that do not fit a tool, and a call of a tool the agent does not have.
|
|
56
|
+
- **A message is answered once per invocation**: the graph records each
|
|
57
|
+
answer in its state, by invocation id, and a retried attempt returns it. A
|
|
58
|
+
run that a crash interrupted (its prompt without an answer) is finished
|
|
59
|
+
before the next message starts.
|
|
60
|
+
|
|
61
|
+
## Run
|
|
62
|
+
|
|
63
|
+
```sh
|
|
64
|
+
cd packages/examples && OPENAI_API_KEY=… node basic/langgraph.ts
|
|
65
|
+
```
|
|
66
|
+
|
|
67
|
+
With a Restate server, and the agent registered with it: see
|
|
68
|
+
[Run an example](../../../examples/README.md#run-an-example).
|
|
69
|
+
|
|
70
|
+
## Tests
|
|
71
|
+
|
|
72
|
+
The tests run on a scripted model, [`test/fakes/langgraph.ts`](../../test/fakes/langgraph.ts)
|
|
73
|
+
(`pnpm --filter @restatedev/agents test langgraph`, from the repository root):
|
|
74
|
+
|
|
75
|
+
- [`test/storage/langgraph.test.ts`](../../test/storage/langgraph.test.ts):
|
|
76
|
+
LangGraph's checkpointer conformance suite
|
|
77
|
+
(`@langchain/langgraph-checkpoint-validation`, 718 tests); and
|
|
78
|
+
[`langgraph-fork.test.ts`](../../test/storage/langgraph-fork.test.ts),
|
|
79
|
+
a forked thread.
|
|
80
|
+
- [`test/langgraph.test.ts`](../../test/langgraph.test.ts):
|
|
81
|
+
each point above, with crashes that stop an attempt in a tool call, or
|
|
82
|
+
at any of its state requests; the
|
|
83
|
+
system prompt; arguments that do not fit a tool; and `messages`. With
|
|
84
|
+
`durability: 'async'`, it fails.
|
|
85
|
+
- [`test/langgraph.ts`](../../test/langgraph.ts): the
|
|
86
|
+
bank agent, through crashes in [the crash test](../../../e2e/crash.ts)
|
|
87
|
+
(`pnpm --filter e2e crash`): every message moves money exactly once.
|