@restatedev/agents 0.3.0 → 0.4.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/README.md +89 -49
- package/dist/calls.d.ts +29 -5
- package/dist/calls.d.ts.map +1 -1
- package/dist/calls.js +77 -10
- package/dist/calls.js.map +1 -1
- package/dist/claude/index.d.ts +36 -7
- package/dist/claude/index.d.ts.map +1 -1
- package/dist/claude/index.js +232 -151
- package/dist/claude/index.js.map +1 -1
- package/dist/client.d.ts +12 -3
- package/dist/client.d.ts.map +1 -1
- package/dist/client.js.map +1 -1
- package/dist/common.d.ts +151 -70
- package/dist/common.d.ts.map +1 -1
- package/dist/common.js +246 -204
- package/dist/common.js.map +1 -1
- package/dist/conversation.d.ts +466 -0
- package/dist/conversation.d.ts.map +1 -0
- package/dist/conversation.js +1247 -0
- package/dist/conversation.js.map +1 -0
- package/dist/deepseek/index.d.ts +38 -5
- package/dist/deepseek/index.d.ts.map +1 -1
- package/dist/deepseek/index.js +322 -106
- package/dist/deepseek/index.js.map +1 -1
- package/dist/deepseek/persistence.d.ts +9 -3
- package/dist/deepseek/persistence.d.ts.map +1 -1
- package/dist/deepseek/persistence.js +12 -6
- package/dist/deepseek/persistence.js.map +1 -1
- package/dist/index.d.ts +2 -2
- package/dist/index.d.ts.map +1 -1
- package/dist/index.js +2 -3
- package/dist/index.js.map +1 -1
- package/dist/langgraph/checkpointer.d.ts +16 -2
- package/dist/langgraph/checkpointer.d.ts.map +1 -1
- package/dist/langgraph/checkpointer.js +133 -26
- package/dist/langgraph/checkpointer.js.map +1 -1
- package/dist/langgraph/context.d.ts +10 -0
- package/dist/langgraph/context.d.ts.map +1 -0
- package/dist/langgraph/context.js +21 -0
- package/dist/langgraph/context.js.map +1 -0
- package/dist/langgraph/errors.d.ts +16 -0
- package/dist/langgraph/errors.d.ts.map +1 -0
- package/dist/langgraph/errors.js +30 -0
- package/dist/langgraph/errors.js.map +1 -0
- package/dist/langgraph/graph.d.ts +25 -0
- package/dist/langgraph/graph.d.ts.map +1 -0
- package/dist/langgraph/graph.js +346 -0
- package/dist/langgraph/graph.js.map +1 -0
- package/dist/langgraph/index.d.ts +65 -12
- package/dist/langgraph/index.d.ts.map +1 -1
- package/dist/langgraph/index.js +227 -171
- package/dist/langgraph/index.js.map +1 -1
- package/dist/langgraph/nodes.d.ts +70 -0
- package/dist/langgraph/nodes.d.ts.map +1 -0
- package/dist/langgraph/nodes.js +145 -0
- package/dist/langgraph/nodes.js.map +1 -0
- package/dist/messages.d.ts +18 -0
- package/dist/messages.d.ts.map +1 -0
- package/dist/messages.js +182 -0
- package/dist/messages.js.map +1 -0
- package/dist/object.d.ts +65 -23
- package/dist/object.d.ts.map +1 -1
- package/dist/object.js +121 -35
- package/dist/object.js.map +1 -1
- package/dist/output.d.ts +15 -7
- package/dist/output.d.ts.map +1 -1
- package/dist/output.js +44 -26
- package/dist/output.js.map +1 -1
- package/dist/pi/index.d.ts +39 -11
- package/dist/pi/index.d.ts.map +1 -1
- package/dist/pi/index.js +281 -77
- package/dist/pi/index.js.map +1 -1
- package/dist/pi/storage.d.ts +29 -4
- package/dist/pi/storage.d.ts.map +1 -1
- package/dist/pi/storage.js +18 -6
- package/dist/pi/storage.js.map +1 -1
- package/dist/signals.d.ts +74 -4
- package/dist/signals.d.ts.map +1 -1
- package/dist/signals.js +144 -15
- package/dist/signals.js.map +1 -1
- package/dist/steering.d.ts +31 -0
- package/dist/steering.d.ts.map +1 -0
- package/dist/steering.js +45 -0
- package/dist/steering.js.map +1 -0
- package/dist/tools.d.ts +28 -0
- package/dist/tools.d.ts.map +1 -1
- package/dist/tools.js +34 -5
- package/dist/tools.js.map +1 -1
- package/package.json +33 -37
- package/src/calls.ts +107 -15
- package/src/claude/README.md +41 -20
- package/src/claude/index.ts +266 -178
- package/src/client.ts +14 -3
- package/src/common.ts +317 -232
- package/src/conversation.ts +1527 -0
- package/src/deepseek/README.md +78 -11
- package/src/deepseek/index.ts +384 -137
- package/src/deepseek/persistence.ts +11 -8
- package/src/index.ts +13 -4
- package/src/langgraph/README.md +115 -25
- package/src/langgraph/checkpointer.ts +168 -28
- package/src/langgraph/context.ts +27 -0
- package/src/langgraph/errors.ts +26 -0
- package/src/langgraph/graph.ts +396 -0
- package/src/langgraph/index.ts +326 -181
- package/src/langgraph/nodes.ts +243 -0
- package/src/messages.ts +244 -0
- package/src/object.ts +167 -38
- package/src/output.ts +52 -31
- package/src/pi/README.md +18 -3
- package/src/pi/index.ts +346 -78
- package/src/pi/storage.ts +20 -7
- package/src/signals.ts +225 -19
- package/src/steering.ts +67 -0
- package/src/tools.ts +61 -8
- package/dist/claude/conversation.d.ts +0 -33
- package/dist/claude/conversation.d.ts.map +0 -1
- package/dist/claude/conversation.js +0 -95
- package/dist/claude/conversation.js.map +0 -1
- package/dist/log.d.ts +0 -29
- package/dist/log.d.ts.map +0 -1
- package/dist/log.js +0 -146
- package/dist/log.js.map +0 -1
- package/dist/opencode/db.d.ts +0 -40
- package/dist/opencode/db.d.ts.map +0 -1
- package/dist/opencode/db.js +0 -161
- package/dist/opencode/db.js.map +0 -1
- package/dist/opencode/index.d.ts +0 -100
- package/dist/opencode/index.d.ts.map +0 -1
- package/dist/opencode/index.js +0 -436
- package/dist/opencode/index.js.map +0 -1
- package/src/claude/conversation.ts +0 -114
- package/src/log.ts +0 -194
- package/src/opencode/README.md +0 -125
- package/src/opencode/db.ts +0 -223
- package/src/opencode/index.ts +0 -559
package/src/langgraph/index.ts
CHANGED
|
@@ -1,5 +1,7 @@
|
|
|
1
|
-
// LangGraph agents in Restate virtual objects: a tool-calling graph
|
|
2
|
-
//
|
|
1
|
+
// LangGraph agents in Restate virtual objects: a tool-calling graph on the
|
|
2
|
+
// object's conversation of turns (../conversation.ts), whose items are
|
|
3
|
+
// LangChain's messages. `SqlCheckpointSaver` (checkpointer.ts) is for graphs
|
|
4
|
+
// of your own, which keep their checkpoints in the object's database.
|
|
3
5
|
//
|
|
4
6
|
// const assistant = langgraph.agent({ name: 'assistant', tools: [search] });
|
|
5
7
|
//
|
|
@@ -13,88 +15,118 @@
|
|
|
13
15
|
// openai/gpt-6-sol, with OPENAI_API_KEY.
|
|
14
16
|
//
|
|
15
17
|
// The handler is not replayed: a retried attempt (a crash, a lost connection)
|
|
16
|
-
// runs again from the start, and
|
|
17
|
-
//
|
|
18
|
-
//
|
|
19
|
-
//
|
|
20
|
-
//
|
|
21
|
-
//
|
|
22
|
-
// idempotent
|
|
18
|
+
// runs again from the start, and the graph starts from what the model sees
|
|
19
|
+
// of the conversation (`history()`: the earlier turns as their prompts and
|
|
20
|
+
// answers, the latest whole):
|
|
21
|
+
// - The model node stores its reply before it returns, and the tools node
|
|
22
|
+
// each tool's result as it lands. So a crash during the tools resumes
|
|
23
|
+
// those without a result, with the same tool call ids, which a tool passes
|
|
24
|
+
// on to stay idempotent; and a stored final reply is the answer, without
|
|
25
|
+
// asking the model again.
|
|
23
26
|
// - A tool's error fails the attempt, which Restate retries (the ToolNode
|
|
24
27
|
// would hand it to the model as the tool's result); a call of a tool the
|
|
25
28
|
// agent lacks, or with arguments that do not fit, is the model's to fix.
|
|
26
|
-
// - A message is answered once per invocation
|
|
27
|
-
|
|
28
|
-
import * as restate from '@restatedev/sessions';
|
|
29
|
-
import type { Database } from '@restatedev/sessions';
|
|
29
|
+
// - A message is answered once per invocation (`answerOnce`).
|
|
30
|
+
import type * as restate from '@restatedev/sessions';
|
|
30
31
|
import type { RunnableConfig } from '@langchain/core/runnables';
|
|
31
32
|
import type { BaseChatModel } from '@langchain/core/language_models/chat_models';
|
|
32
|
-
import {
|
|
33
|
+
import {
|
|
34
|
+
AIMessage,
|
|
35
|
+
type BaseMessage,
|
|
36
|
+
HumanMessage,
|
|
37
|
+
mapStoredMessagesToChatMessages,
|
|
38
|
+
type StoredMessage,
|
|
39
|
+
SystemMessage,
|
|
40
|
+
type ToolCall,
|
|
41
|
+
ToolMessage,
|
|
42
|
+
} from '@langchain/core/messages';
|
|
33
43
|
import { type StructuredToolInterface, tool, ToolInputParsingException } from '@langchain/core/tools';
|
|
34
|
-
import {
|
|
44
|
+
import { END, isGraphInterrupt, MessagesAnnotation, START, StateGraph } from '@langchain/langgraph';
|
|
35
45
|
import { ToolNode, toolsCondition } from '@langchain/langgraph/prebuilt';
|
|
36
46
|
import {
|
|
37
|
-
AttemptEnded,
|
|
38
|
-
CANCELLED,
|
|
39
47
|
chatHandler,
|
|
40
48
|
type Configure,
|
|
41
49
|
configured,
|
|
42
50
|
fromTool,
|
|
43
|
-
messagesHandler,
|
|
44
51
|
ModelError,
|
|
45
52
|
modelOf,
|
|
46
|
-
nextPromptId,
|
|
47
53
|
providerOf,
|
|
48
|
-
|
|
54
|
+
RETURNED_UNRECORDED,
|
|
49
55
|
stopSignalOf,
|
|
50
|
-
|
|
56
|
+
type Summarize,
|
|
51
57
|
toolCallEnded,
|
|
52
58
|
toolCallStarted,
|
|
53
|
-
|
|
54
|
-
Transcript,
|
|
55
|
-
UNANSWERED,
|
|
59
|
+
NO_ANSWER,
|
|
56
60
|
} from '../common.ts';
|
|
57
|
-
import { type
|
|
61
|
+
import { answerOnce, type Conversation, type Items, type Run, type Turn } from '../conversation.ts';
|
|
62
|
+
import { conversationView } from '../messages.ts';
|
|
63
|
+
import { type Answer, withChecked } from '../output.ts';
|
|
58
64
|
import type { z } from 'zod';
|
|
59
65
|
import { type Definition, sessionObject } from '../object.ts';
|
|
66
|
+
import { takeSteers } from '../steering.ts';
|
|
60
67
|
import { isTool, jsonSchemaOf, type Tool as AnyTool } from '../tools.ts';
|
|
61
68
|
|
|
62
69
|
import { SqlCheckpointSaver } from './checkpointer.ts';
|
|
70
|
+
import { handlerContext } from './context.ts';
|
|
71
|
+
import { terminalOf } from './errors.ts';
|
|
72
|
+
import { type AnyGraph, check as checkGraph, graphRun } from './graph.ts';
|
|
63
73
|
|
|
64
74
|
export { SqlCheckpointSaver };
|
|
75
|
+
export { type AnyGraph, INTERRUPT } from './graph.ts';
|
|
76
|
+
export * as nodes from './nodes.ts';
|
|
77
|
+
|
|
78
|
+
/**
|
|
79
|
+
* LangGraph's items: LangChain's messages, stored as their `toDict()`. A
|
|
80
|
+
* human message is said by the user; an AI message by the assistant, with
|
|
81
|
+
* its `tool_calls` as calls; a tool message is a result (an error if its
|
|
82
|
+
* status says so).
|
|
83
|
+
*/
|
|
84
|
+
export const items: Items<BaseMessage> = {
|
|
85
|
+
dump: (message) => JSON.stringify(message.toDict()),
|
|
86
|
+
load: (stored) => mapStoredMessagesToChatMessages([JSON.parse(stored) as StoredMessage])[0]!,
|
|
87
|
+
prompt: (text) => new HumanMessage(text),
|
|
88
|
+
// A steered message, told apart from a prompt in the run's state by its id, which is stored with it.
|
|
89
|
+
steered: (text, steerId) => new HumanMessage({ content: text, id: `steer:${steerId}` }),
|
|
90
|
+
// A provider may refuse an empty message: an empty answer, as the model sees it later, says so.
|
|
91
|
+
reply: (text) => new AIMessage(text.trim() ? text : NO_ANSWER),
|
|
92
|
+
results: (results) =>
|
|
93
|
+
results.map(
|
|
94
|
+
([call, output]) =>
|
|
95
|
+
new ToolMessage({
|
|
96
|
+
tool_call_id: call.id,
|
|
97
|
+
name: call.name,
|
|
98
|
+
content: output,
|
|
99
|
+
...(output === RETURNED_UNRECORDED ? {} : { status: 'error' as const }),
|
|
100
|
+
}),
|
|
101
|
+
),
|
|
102
|
+
read: (message) => {
|
|
103
|
+
if (HumanMessage.isInstance(message)) return { said: ['user', message.text] };
|
|
104
|
+
if (AIMessage.isInstance(message)) {
|
|
105
|
+
const calls = (message.tool_calls ?? []).map((c) => ({ id: c.id ?? '', name: c.name, input: c.args }));
|
|
106
|
+
// Each reply is a message of its own, its tool calls' too.
|
|
107
|
+
return { said: ['assistant', message.text], calls };
|
|
108
|
+
}
|
|
109
|
+
if (ToolMessage.isInstance(message)) {
|
|
110
|
+
return { results: [{ id: message.tool_call_id, output: message.text, error: message.status === 'error' }] };
|
|
111
|
+
}
|
|
112
|
+
return {};
|
|
113
|
+
},
|
|
114
|
+
};
|
|
65
115
|
|
|
66
|
-
|
|
67
|
-
|
|
68
|
-
|
|
69
|
-
|
|
70
|
-
|
|
71
|
-
|
|
72
|
-
});
|
|
116
|
+
/** Whether `message` is a reply of the model with nothing in it: no text, no tool call, no other content. */
|
|
117
|
+
const blank = (message: AIMessage) =>
|
|
118
|
+
(message.tool_calls ?? []).length === 0 &&
|
|
119
|
+
(typeof message.content === 'string'
|
|
120
|
+
? !message.content.trim()
|
|
121
|
+
: message.content.every((b) => b.type === 'text' && !(typeof b.text === 'string' && b.text.trim())));
|
|
73
122
|
|
|
74
123
|
/**
|
|
75
|
-
*
|
|
76
|
-
*
|
|
77
|
-
*
|
|
78
|
-
* fix: failing the attempt, every retry would meet the same call again). Any
|
|
79
|
-
* other error of a tool fails the attempt, at once (the ToolNode would hand
|
|
80
|
-
* it to the model too). The round is published as it starts and ends, for
|
|
81
|
-
* the clients that follow the conversation.
|
|
124
|
+
* `messages` as a provider takes them: a reply of the model with nothing in
|
|
125
|
+
* it (stored as it came) says so, as an empty answer does. Anthropic's API
|
|
126
|
+
* refuses an empty message but the last.
|
|
82
127
|
*/
|
|
83
|
-
|
|
84
|
-
|
|
85
|
-
await toolCallStarted(ctx);
|
|
86
|
-
// The first error fails the attempt at once, not once the other calls end.
|
|
87
|
-
const { promise: failure, reject: failed } = Promise.withResolvers<never>();
|
|
88
|
-
failure.catch(() => {});
|
|
89
|
-
const node = new ToolNode(
|
|
90
|
-
tools.map((t) => failing(ctx, t, failed)),
|
|
91
|
-
{ handleToolErrors: true },
|
|
92
|
-
);
|
|
93
|
-
const ran: { messages: BaseMessage[] } = await Promise.race([node.invoke(state, config), failure]);
|
|
94
|
-
await toolCallEnded(ctx);
|
|
95
|
-
return ran;
|
|
96
|
-
};
|
|
97
|
-
}
|
|
128
|
+
const sendable = (messages: BaseMessage[]) =>
|
|
129
|
+
messages.map((m) => (AIMessage.isInstance(m) && blank(m) ? new AIMessage(NO_ANSWER) : m));
|
|
98
130
|
|
|
99
131
|
/** `t`, its errors given to `failed`, but for its input's (arguments that do not fit) and LangGraph's interrupts. */
|
|
100
132
|
const failing = (
|
|
@@ -118,6 +150,47 @@ const failing = (
|
|
|
118
150
|
},
|
|
119
151
|
}) as StructuredToolInterface;
|
|
120
152
|
|
|
153
|
+
/**
|
|
154
|
+
* The tools node: each tool call of the turn without a result run by a
|
|
155
|
+
* ToolNode, which answers the model with what is wrong when a call names a
|
|
156
|
+
* tool the agent does not have, or arguments that do not fit (the model's to
|
|
157
|
+
* fix: failing the attempt, every retry would meet the same call again). Each
|
|
158
|
+
* result is stored as it lands. Any other error of a tool fails the attempt,
|
|
159
|
+
* at once (the ToolNode would hand it to the model too). The round is
|
|
160
|
+
* published as it starts and ends, for the clients that follow the
|
|
161
|
+
* conversation.
|
|
162
|
+
*/
|
|
163
|
+
function toolsNode(ctx: restate.SessionContext, turn: Turn<BaseMessage>, tools: StructuredToolInterface[]) {
|
|
164
|
+
return async (_state: typeof MessagesAnnotation.State, config: RunnableConfig) => {
|
|
165
|
+
await toolCallStarted(ctx);
|
|
166
|
+
// The first error fails the attempt at once, not once the other calls end.
|
|
167
|
+
const { promise: failure, reject } = Promise.withResolvers<never>();
|
|
168
|
+
failure.catch(() => {});
|
|
169
|
+
let broken = false;
|
|
170
|
+
const failed = (error: unknown) => {
|
|
171
|
+
broken = true;
|
|
172
|
+
reject(error);
|
|
173
|
+
};
|
|
174
|
+
const node = new ToolNode(
|
|
175
|
+
tools.map((t) => failing(ctx, t, failed)),
|
|
176
|
+
{ handleToolErrors: true },
|
|
177
|
+
);
|
|
178
|
+
const one = async (call: ToolCall) => {
|
|
179
|
+
const ran = (await node.invoke({ messages: [new AIMessage({ content: '', tool_calls: [call] })] }, config)) as {
|
|
180
|
+
messages: BaseMessage[];
|
|
181
|
+
};
|
|
182
|
+
// A tool's error fails the attempt: the ToolNode's answer to the model of it is not the call's result.
|
|
183
|
+
if (broken) return [];
|
|
184
|
+
await turn.append(...ran.messages);
|
|
185
|
+
return ran.messages;
|
|
186
|
+
};
|
|
187
|
+
const calls = turn.openCalls().map((c) => ({ id: c.id, name: c.name, args: c.input as Record<string, unknown> }));
|
|
188
|
+
const ran = await Promise.race([Promise.all(calls.map(one)), failure]);
|
|
189
|
+
await toolCallEnded(ctx);
|
|
190
|
+
return { messages: ran.flat() };
|
|
191
|
+
};
|
|
192
|
+
}
|
|
193
|
+
|
|
121
194
|
/** `provider/model-id` as its provider and model id, for a provider the usual graph takes. */
|
|
122
195
|
const providerOfModel = (named: string) => {
|
|
123
196
|
const [provider, id] = providerOf(named);
|
|
@@ -137,7 +210,9 @@ const chatModel = async (named: string): Promise<BaseChatModel> => {
|
|
|
137
210
|
const [provider, id] = providerOfModel(named);
|
|
138
211
|
if (provider === 'openai') {
|
|
139
212
|
const { ChatOpenAI } = await integration('@langchain/openai', () => import('@langchain/openai'));
|
|
140
|
-
|
|
213
|
+
// OpenAI's reasoning models take function tools only on the Responses API
|
|
214
|
+
// (on Chat Completions they refuse them, unless reasoning is off).
|
|
215
|
+
return new ChatOpenAI({ model: id, useResponsesApi: true });
|
|
141
216
|
}
|
|
142
217
|
const { ChatAnthropic } = await integration('@langchain/anthropic', () => import('@langchain/anthropic'));
|
|
143
218
|
return new ChatAnthropic({ model: id });
|
|
@@ -155,33 +230,111 @@ async function integration<T>(name: string, load: () => Promise<T>): Promise<T>
|
|
|
155
230
|
}
|
|
156
231
|
}
|
|
157
232
|
|
|
158
|
-
/**
|
|
159
|
-
|
|
233
|
+
/**
|
|
234
|
+
* The agent's graph, for the latest turn of `conversation`: `model`, calling
|
|
235
|
+
* `tools`, from the tools if the turn has calls without results (a crash cut
|
|
236
|
+
* them off). The model node takes the messages steered to the turn first
|
|
237
|
+
* (`takeSteers`: it runs after the prompt or the tools' results), which go
|
|
238
|
+
* into its request and stay in the run's state, and stores each reply before
|
|
239
|
+
* it returns.
|
|
240
|
+
*/
|
|
241
|
+
function toolLoop(
|
|
242
|
+
ctx: restate.SessionContext,
|
|
243
|
+
conversation: Conversation<BaseMessage>,
|
|
244
|
+
model: BaseChatModel,
|
|
245
|
+
tools: StructuredToolInterface[],
|
|
246
|
+
system?: string,
|
|
247
|
+
) {
|
|
160
248
|
if (!model.bindTools) throw new Error(`${model.getName()} does not call tools`);
|
|
161
249
|
const withTools = model.bindTools(tools);
|
|
162
|
-
|
|
163
|
-
|
|
164
|
-
|
|
165
|
-
|
|
166
|
-
|
|
167
|
-
|
|
168
|
-
|
|
169
|
-
|
|
170
|
-
|
|
171
|
-
.
|
|
250
|
+
const turn = conversation.turn;
|
|
251
|
+
return new StateGraph(MessagesAnnotation)
|
|
252
|
+
.addNode('model', async ({ messages }) => {
|
|
253
|
+
const steered = await takeSteers(ctx, conversation);
|
|
254
|
+
const asked = [...messages, ...steered];
|
|
255
|
+
const reply = await withTools.invoke(system ? [new SystemMessage(system), ...asked] : asked);
|
|
256
|
+
await turn.appendReply([reply]);
|
|
257
|
+
return { messages: [...steered, reply] };
|
|
258
|
+
})
|
|
259
|
+
.addNode('tools', toolsNode(ctx, turn, tools))
|
|
260
|
+
.addConditionalEdges(START, () => (turn.openCalls().length > 0 ? 'tools' : 'model'), {
|
|
261
|
+
tools: 'tools',
|
|
262
|
+
model: 'model',
|
|
263
|
+
})
|
|
264
|
+
.addConditionalEdges('model', toolsCondition, { tools: 'tools', [END]: END })
|
|
265
|
+
.addEdge('tools', 'model');
|
|
172
266
|
}
|
|
173
267
|
|
|
174
|
-
/**
|
|
175
|
-
const
|
|
268
|
+
/** How many steps a turn takes at most, by default: tool rounds enough for any turn, and the end of a run that loops. */
|
|
269
|
+
const RECURSION_LIMIT = 10_000;
|
|
270
|
+
|
|
271
|
+
/** The run of the agent: the graph from what the model sees, to the final reply's text. */
|
|
272
|
+
const runOf =
|
|
273
|
+
(
|
|
274
|
+
ctx: restate.SessionContext,
|
|
275
|
+
model: BaseChatModel,
|
|
276
|
+
tools: StructuredToolInterface[],
|
|
277
|
+
system?: string,
|
|
278
|
+
recursionLimit = RECURSION_LIMIT,
|
|
279
|
+
): Run<BaseMessage> =>
|
|
280
|
+
async (conversation) => {
|
|
281
|
+
const turn = conversation.turn;
|
|
282
|
+
// A stored final reply is the answer: the model is not asked for it again.
|
|
283
|
+
const final = turn.finalReply();
|
|
284
|
+
if (final !== undefined) return final;
|
|
285
|
+
const app = toolLoop(ctx, conversation, model, tools, system).compile();
|
|
286
|
+
try {
|
|
287
|
+
const { messages } = await app.invoke(
|
|
288
|
+
{ messages: sendable(conversation.history()) },
|
|
289
|
+
{ signal: stopSignalOf(ctx), recursionLimit },
|
|
290
|
+
);
|
|
291
|
+
return messages.at(-1)!.text;
|
|
292
|
+
} catch (error) {
|
|
293
|
+
// LangGraph's own errors (a run that loops, an invalid update) would be met again: they end the turn.
|
|
294
|
+
throw terminalOf(error) ?? error;
|
|
295
|
+
}
|
|
296
|
+
};
|
|
297
|
+
|
|
298
|
+
/**
|
|
299
|
+
* `t` as a LangChain tool: `t.run` checks the model's arguments itself. Its
|
|
300
|
+
* context is `ctx`, or else the graph's run's (context.ts).
|
|
301
|
+
*/
|
|
302
|
+
const native = (t: AnyTool, ctx?: restate.SessionContext): StructuredToolInterface =>
|
|
176
303
|
tool(
|
|
177
|
-
async (args: unknown,
|
|
304
|
+
async (args: unknown, config) => {
|
|
305
|
+
const { toolCall } = config;
|
|
178
306
|
if (!toolCall?.id) throw new Error('a tool call without an id');
|
|
179
|
-
|
|
307
|
+
const at = ctx ?? handlerContext((config as { context?: unknown }).context);
|
|
308
|
+
if (!at) {
|
|
309
|
+
throw new TypeError(
|
|
310
|
+
`the tool ${t.name} runs in a graph that langgraph.agent({ graph }) runs, or that is invoked with the ` +
|
|
311
|
+
"handler's context: invoke(input, { context: ctx })",
|
|
312
|
+
);
|
|
313
|
+
}
|
|
314
|
+
return t.run(args, { ctx: at, callId: toolCall.id });
|
|
180
315
|
},
|
|
181
316
|
// What does not fit, for the model to fix: not only that something does not.
|
|
182
317
|
{ name: t.name, description: t.description, schema: jsonSchemaOf(t), verboseParsingErrors: true },
|
|
183
318
|
);
|
|
184
319
|
|
|
320
|
+
/**
|
|
321
|
+
* `given` as LangChain tools, for a graph of your own or LangChain's
|
|
322
|
+
* `createAgent`:
|
|
323
|
+
*
|
|
324
|
+
* const graph = createAgent({ model, tools: langgraph.tools([call(orders, 'status', { description: '…' })]) });
|
|
325
|
+
* const desk = langgraph.agent({ name: 'desk', graph });
|
|
326
|
+
*
|
|
327
|
+
* Restate's tools (`call`, `send`, `workflow`, `subagent`, `signal`) make
|
|
328
|
+
* their Restate calls once per tool call, even if a crash runs the tool call
|
|
329
|
+
* again: the model's reply, with the tool call's id, is checkpointed before
|
|
330
|
+
* the tools run. A `tool()` of your own runs your function, again after a
|
|
331
|
+
* crash, as do LangChain's tools, which are passed through. They take the
|
|
332
|
+
* handler's context from the graph's run (`langgraph.agent({ graph })` gives
|
|
333
|
+
* it; a handler of your own passes `context: ctx`).
|
|
334
|
+
*/
|
|
335
|
+
export const tools = (given: (AnyTool | StructuredToolInterface)[]): StructuredToolInterface[] =>
|
|
336
|
+
given.map((t) => (isTool(t) ? native(t) : t));
|
|
337
|
+
|
|
185
338
|
/** An agent's options: `chat` and `prompt` take them. */
|
|
186
339
|
export interface Options<O extends z.ZodObject | undefined = z.ZodObject | undefined> {
|
|
187
340
|
/** The model: `openai/model-id` or `anthropic/model-id` (MODEL, or else openai/gpt-6-sol), or a chat model that calls tools. */
|
|
@@ -190,145 +343,130 @@ export interface Options<O extends z.ZodObject | undefined = z.ZodObject | undef
|
|
|
190
343
|
system?: string;
|
|
191
344
|
/** The agent's tools: `tool()`s, Restate's (`call`, `signal`...), or LangChain's. */
|
|
192
345
|
tools?: (AnyTool | StructuredToolInterface)[];
|
|
346
|
+
/** How many steps of the graph a turn takes at most (default 10 000): past it, the turn fails for good. */
|
|
347
|
+
recursionLimit?: number;
|
|
193
348
|
/**
|
|
194
349
|
* The answer as data: a zod object, whose JSON the agent replies with
|
|
195
|
-
* (checked), and `chat` and `prompt` answer with (see output.ts).
|
|
350
|
+
* (checked), and `chat` and `prompt` answer with (see output.ts). With
|
|
351
|
+
* `graph`, the graph's own prompts must ask for it.
|
|
196
352
|
*/
|
|
197
353
|
output?: O;
|
|
354
|
+
/**
|
|
355
|
+
* A graph of your own to run, instead of the built-in tool-calling loop
|
|
356
|
+
* (graph.ts): a `StateGraph` whose state has `messages`, or a compiled one
|
|
357
|
+
* (such as LangChain's `createAgent` makes). It has its own model and
|
|
358
|
+
* tools, so it takes no `model`, `system`, `tools` or `recursionLimit`.
|
|
359
|
+
*/
|
|
360
|
+
graph?: AnyGraph;
|
|
361
|
+
/**
|
|
362
|
+
* The run context of `graph` (LangGraph's `context`), for a graph with a
|
|
363
|
+
* context schema of its own. By default the handler's context. The
|
|
364
|
+
* prebuilt `nodes` and the tools of `tools()` get the handler's context
|
|
365
|
+
* either way.
|
|
366
|
+
*/
|
|
367
|
+
context?: unknown;
|
|
198
368
|
}
|
|
199
369
|
|
|
200
|
-
/**
|
|
201
|
-
|
|
202
|
-
|
|
203
|
-
|
|
204
|
-
|
|
205
|
-
() => answerOnce(ctx, text, options),
|
|
206
|
-
);
|
|
207
|
-
|
|
208
|
-
const answerOnce = async (
|
|
209
|
-
ctx: restate.SessionContext,
|
|
210
|
-
text: string,
|
|
211
|
-
{ model, system, tools = [] }: Options,
|
|
212
|
-
): Promise<string> => {
|
|
213
|
-
const llm = typeof model === 'object' ? model : await chatModel(modelOf(model));
|
|
214
|
-
// The latest checkpoint is all an agent resumes from: earlier ones would
|
|
215
|
-
// store the conversation again at each step.
|
|
216
|
-
const checkpointer = new SqlCheckpointSaver(ctx.db, { history: 'latest' });
|
|
217
|
-
const app = graph(
|
|
218
|
-
ctx,
|
|
219
|
-
llm,
|
|
220
|
-
tools.map((t) => (isTool(t) ? native(t, ctx) : t)),
|
|
221
|
-
system,
|
|
222
|
-
).compile({ checkpointer });
|
|
223
|
-
const config = { configurable: { thread_id: ctx.key }, durability: 'sync' as const };
|
|
224
|
-
const id = nextPromptId(ctx);
|
|
225
|
-
for (;;) {
|
|
226
|
-
const state = await app.getState(config);
|
|
227
|
-
const answer = state.values.answers?.[id];
|
|
228
|
-
if (answer !== undefined) return storedAnswer(answer);
|
|
229
|
-
// Finish an interrupted run first (this prompt's, after a crash), then
|
|
230
|
-
// start this prompt's. A run is unfinished while its prompt has no
|
|
231
|
-
// answer: `next` does not say, as it leaves out the steps whose writes
|
|
232
|
-
// are stored.
|
|
233
|
-
const { prompt: last, answers = {} } = state.values;
|
|
234
|
-
const interrupted = last !== undefined && answers[last] === undefined;
|
|
235
|
-
const turn = stopSignalOf(ctx);
|
|
236
|
-
try {
|
|
237
|
-
await app.invoke(interrupted ? null : { messages: [new HumanMessage(text)], prompt: id }, {
|
|
238
|
-
...config,
|
|
239
|
-
signal: turn,
|
|
240
|
-
});
|
|
241
|
-
} catch (error) {
|
|
242
|
-
// The attempt ended: it stops, and the next attempt goes on with the run.
|
|
243
|
-
if (turn?.reason instanceof AttemptEnded) throw turn.reason;
|
|
244
|
-
// Cancelled: the run ends, and the next prompt starts afresh.
|
|
245
|
-
if (turn?.aborted || error instanceof restate.CancelledError) {
|
|
246
|
-
await close(app, config, CANCELLED);
|
|
247
|
-
throw turn?.aborted ? turn.reason : error;
|
|
248
|
-
}
|
|
249
|
-
// Refused for good (a wrong API key): the run ends unanswered, and
|
|
250
|
-
// fails as terminal. An earlier prompt's, this one goes on.
|
|
251
|
-
const refused = refusalOf(ctx, error);
|
|
252
|
-
if (!refused) throw error;
|
|
253
|
-
await close(app, config, UNANSWERED);
|
|
254
|
-
if (!interrupted || last === id) throw refused;
|
|
255
|
-
}
|
|
370
|
+
/** Throw a `TypeError` if `options` gives a graph of your own with what only the built-in loop takes, or the other way around. */
|
|
371
|
+
function checkOptions({ graph, model, system, tools: given, recursionLimit, context }: Options) {
|
|
372
|
+
if (graph === undefined) {
|
|
373
|
+
if (context !== undefined) throw new TypeError('context is the run context of a graph of your own: pass graph');
|
|
374
|
+
return;
|
|
256
375
|
}
|
|
257
|
-
}
|
|
258
|
-
|
|
259
|
-
/**
|
|
260
|
-
* End the run of `app` that was cancelled or refused, as its `answer` node: a
|
|
261
|
-
* result of `text` for each tool call of the last reply that has none, then
|
|
262
|
-
* `text` as the reply and the prompt's answer. A run that stored no input
|
|
263
|
-
* yet (cancelled at once) has nothing to end: the prompt the state has is
|
|
264
|
-
* an earlier one, which has its answer.
|
|
265
|
-
*/
|
|
266
|
-
async function close(app: ReturnType<ReturnType<typeof graph>['compile']>, config: RunnableConfig, text: string) {
|
|
267
|
-
const { values } = await app.getState(config);
|
|
268
|
-
if (values.prompt === undefined || values.answers?.[values.prompt] !== undefined) return;
|
|
269
|
-
const messages = (values.messages ?? []) as BaseMessage[];
|
|
270
|
-
const answered = new Set(messages.filter((m) => ToolMessage.isInstance(m)).map((m) => m.tool_call_id));
|
|
271
|
-
const last = messages.findLast((m) => AIMessage.isInstance(m));
|
|
272
|
-
const calls = (last && AIMessage.isInstance(last) ? (last.tool_calls ?? []) : []).filter(
|
|
273
|
-
(call) => call.id !== undefined && !answered.has(call.id),
|
|
274
|
-
);
|
|
275
|
-
await app.updateState(
|
|
276
|
-
config,
|
|
277
|
-
{
|
|
278
|
-
messages: [
|
|
279
|
-
...calls.map((call) => new ToolMessage({ tool_call_id: call.id!, content: text, status: 'error' })),
|
|
280
|
-
new AIMessage(text),
|
|
281
|
-
],
|
|
282
|
-
answers: { [values.prompt]: text },
|
|
283
|
-
},
|
|
284
|
-
'answer',
|
|
376
|
+
const extra = Object.entries({ model, system, tools: given, recursionLimit }).flatMap(([name, value]) =>
|
|
377
|
+
value === undefined ? [] : [name],
|
|
285
378
|
);
|
|
379
|
+
if (extra.length > 0) {
|
|
380
|
+
throw new TypeError(`a graph of your own has its own model and tools: it takes no ${extra.join(', ')}`);
|
|
381
|
+
}
|
|
382
|
+
checkGraph(graph);
|
|
286
383
|
}
|
|
287
384
|
|
|
385
|
+
/** The chat model of `model`. */
|
|
386
|
+
const modelOfOptions = async (model: Options['model']) =>
|
|
387
|
+
typeof model === 'object' ? model : chatModel(modelOf(model));
|
|
388
|
+
|
|
288
389
|
/**
|
|
289
390
|
* Answer `text`, once: a retried attempt resumes the same prompt. Each prompt
|
|
290
|
-
* of an invocation is a prompt of its own.
|
|
391
|
+
* of an invocation is a prompt of its own.
|
|
291
392
|
* With `output`, it answers with the value the agent replies with (see
|
|
292
|
-
* output.ts), not its text
|
|
393
|
+
* output.ts), not its text: a reply that is not one is asked again within
|
|
394
|
+
* its turn, once.
|
|
293
395
|
*/
|
|
294
396
|
export const prompt = <O extends z.ZodObject | undefined = undefined>(
|
|
295
397
|
ctx: restate.SessionContext,
|
|
296
398
|
text: string,
|
|
297
399
|
options: Options<O> = {},
|
|
298
|
-
): Promise<Answer<O>> =>
|
|
400
|
+
): Promise<Answer<O>> => {
|
|
401
|
+
checkOptions(options);
|
|
402
|
+
const { graph, context } = options;
|
|
403
|
+
if (graph !== undefined) {
|
|
404
|
+
// The graph keeps its own history: the conversation loads the previous turn whole, for what closed it.
|
|
405
|
+
return withChecked(text, options, (t, _options, check) =>
|
|
406
|
+
answerOnce(ctx, t, items, graphRun(ctx, graph, context), { check, window: 1, budget: 0 }),
|
|
407
|
+
) as Promise<Answer<O>>;
|
|
408
|
+
}
|
|
409
|
+
return withChecked(text, options, async (t, { model, system, tools: given = [], recursionLimit }, check, reminder) =>
|
|
410
|
+
answerOnce(
|
|
411
|
+
ctx,
|
|
412
|
+
t,
|
|
413
|
+
items,
|
|
414
|
+
runOf(
|
|
415
|
+
ctx,
|
|
416
|
+
await modelOfOptions(model),
|
|
417
|
+
given.map((x) => (isTool(x) ? native(x, ctx) : x)),
|
|
418
|
+
system,
|
|
419
|
+
recursionLimit,
|
|
420
|
+
),
|
|
421
|
+
{ check, reminder },
|
|
422
|
+
),
|
|
423
|
+
) as Promise<Answer<O>>;
|
|
424
|
+
};
|
|
299
425
|
|
|
300
426
|
/**
|
|
301
|
-
* A chat handler: each message an invocation, the
|
|
302
|
-
*
|
|
427
|
+
* A chat handler: each message an invocation, the conversation in the
|
|
428
|
+
* object's database, with `options`, or the options a function of the
|
|
303
429
|
* invocation's context gives. It takes the message as plain text
|
|
304
430
|
* (`curl -d 'Hi'`) or as a JSON string (`curl --json '"Hi"'`).
|
|
305
431
|
*/
|
|
306
432
|
export const chat = <O extends z.ZodObject | undefined = undefined>(options: Configure<Options<O>> = {}) => {
|
|
307
|
-
if (typeof options === 'object'
|
|
308
|
-
|
|
433
|
+
if (typeof options === 'object') {
|
|
434
|
+
checkOptions(options);
|
|
435
|
+
if (options.graph === undefined && typeof options.model !== 'object') providerOfModel(modelOf(options.model));
|
|
436
|
+
}
|
|
437
|
+
// The built-in loop takes steered messages at its steps; a graph of your own takes none (each is a turn of its
|
|
438
|
+
// own). Options a function gives are its message's: given once per attempt, to the turn's start and its prompt.
|
|
439
|
+
if (typeof options !== 'function') {
|
|
440
|
+
const steers = options.graph === undefined;
|
|
441
|
+
return chatHandler(async (ctx, message) => prompt(ctx, message, options), { steers });
|
|
442
|
+
}
|
|
443
|
+
const given = new WeakMap<restate.SessionContext, Promise<Options<O>>>();
|
|
444
|
+
const optionsOf = (ctx: restate.SessionContext) => {
|
|
445
|
+
let of = given.get(ctx);
|
|
446
|
+
if (!of) given.set(ctx, (of = configured(options, ctx)));
|
|
447
|
+
return of;
|
|
448
|
+
};
|
|
449
|
+
return chatHandler(async (ctx, message) => prompt(ctx, message, await optionsOf(ctx)), {
|
|
450
|
+
steers: async (ctx) => (await optionsOf(ctx)).graph === undefined,
|
|
451
|
+
});
|
|
309
452
|
};
|
|
310
453
|
|
|
311
454
|
/**
|
|
312
|
-
* A
|
|
313
|
-
*
|
|
314
|
-
*
|
|
455
|
+
* A view of the conversation as clients read it: a page at a time, or what
|
|
456
|
+
* is new or changed since a cursor; `view: 'summary'` for each turn's
|
|
457
|
+
* message and answer. It answers while a message is answered.
|
|
315
458
|
*/
|
|
316
|
-
export const messages = () =>
|
|
459
|
+
export const messages = () => conversationView(items);
|
|
317
460
|
|
|
318
|
-
/**
|
|
319
|
-
|
|
320
|
-
|
|
321
|
-
|
|
322
|
-
|
|
323
|
-
|
|
324
|
-
|
|
325
|
-
|
|
326
|
-
|
|
327
|
-
}
|
|
328
|
-
if (ToolMessage.isInstance(m)) transcript.result(m.tool_call_id, m.text, m.status === 'error');
|
|
329
|
-
}
|
|
330
|
-
return transcript;
|
|
331
|
-
};
|
|
461
|
+
/**
|
|
462
|
+
* How an agent of `model` summarizes the earliest turns, past its budget:
|
|
463
|
+
* with its own model (`agent()` gives it; for an object of your own,
|
|
464
|
+
* `sessionObject`'s `summarize`).
|
|
465
|
+
*/
|
|
466
|
+
export const summarizer =
|
|
467
|
+
(model?: Options['model']): Summarize =>
|
|
468
|
+
async (_ctx, request) =>
|
|
469
|
+
(await (await modelOfOptions(model)).invoke([new HumanMessage(request)])).text;
|
|
332
470
|
|
|
333
471
|
/** An agent: a virtual object `name`, one per key, whose `chat` handler is {@link chat}, and `messages` {@link messages}. */
|
|
334
472
|
export const agent = <P extends string, O extends z.ZodObject | undefined = undefined>({
|
|
@@ -336,6 +474,9 @@ export const agent = <P extends string, O extends z.ZodObject | undefined = unde
|
|
|
336
474
|
description,
|
|
337
475
|
schema,
|
|
338
476
|
background,
|
|
477
|
+
window,
|
|
478
|
+
budget,
|
|
479
|
+
summarize,
|
|
339
480
|
...options
|
|
340
481
|
}: Options<O> & Definition<P>) =>
|
|
341
482
|
sessionObject({
|
|
@@ -343,6 +484,10 @@ export const agent = <P extends string, O extends z.ZodObject | undefined = unde
|
|
|
343
484
|
description,
|
|
344
485
|
schema,
|
|
345
486
|
background,
|
|
487
|
+
window,
|
|
488
|
+
budget,
|
|
489
|
+
// A graph of your own keeps its own history, which the conversation's summaries do not reach.
|
|
490
|
+
summarize: summarize ?? (options.graph === undefined ? summarizer(options.model) : undefined),
|
|
346
491
|
handlers: { chat: chat(options) },
|
|
347
492
|
views: { messages: messages() },
|
|
348
493
|
});
|