@restatedev/agents 0.2.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.
Files changed (136) hide show
  1. package/README.md +89 -49
  2. package/dist/calls.d.ts +29 -8
  3. package/dist/calls.d.ts.map +1 -1
  4. package/dist/calls.js +79 -18
  5. package/dist/calls.js.map +1 -1
  6. package/dist/claude/index.d.ts +36 -7
  7. package/dist/claude/index.d.ts.map +1 -1
  8. package/dist/claude/index.js +238 -156
  9. package/dist/claude/index.js.map +1 -1
  10. package/dist/client.d.ts +12 -3
  11. package/dist/client.d.ts.map +1 -1
  12. package/dist/client.js.map +1 -1
  13. package/dist/common.d.ts +161 -71
  14. package/dist/common.d.ts.map +1 -1
  15. package/dist/common.js +277 -226
  16. package/dist/common.js.map +1 -1
  17. package/dist/conversation.d.ts +466 -0
  18. package/dist/conversation.d.ts.map +1 -0
  19. package/dist/conversation.js +1247 -0
  20. package/dist/conversation.js.map +1 -0
  21. package/dist/deepseek/index.d.ts +38 -5
  22. package/dist/deepseek/index.d.ts.map +1 -1
  23. package/dist/deepseek/index.js +323 -107
  24. package/dist/deepseek/index.js.map +1 -1
  25. package/dist/deepseek/persistence.d.ts +9 -3
  26. package/dist/deepseek/persistence.d.ts.map +1 -1
  27. package/dist/deepseek/persistence.js +12 -6
  28. package/dist/deepseek/persistence.js.map +1 -1
  29. package/dist/index.d.ts +2 -2
  30. package/dist/index.d.ts.map +1 -1
  31. package/dist/index.js +2 -3
  32. package/dist/index.js.map +1 -1
  33. package/dist/langgraph/checkpointer.d.ts +16 -2
  34. package/dist/langgraph/checkpointer.d.ts.map +1 -1
  35. package/dist/langgraph/checkpointer.js +133 -26
  36. package/dist/langgraph/checkpointer.js.map +1 -1
  37. package/dist/langgraph/context.d.ts +10 -0
  38. package/dist/langgraph/context.d.ts.map +1 -0
  39. package/dist/langgraph/context.js +21 -0
  40. package/dist/langgraph/context.js.map +1 -0
  41. package/dist/langgraph/errors.d.ts +16 -0
  42. package/dist/langgraph/errors.d.ts.map +1 -0
  43. package/dist/langgraph/errors.js +30 -0
  44. package/dist/langgraph/errors.js.map +1 -0
  45. package/dist/langgraph/graph.d.ts +25 -0
  46. package/dist/langgraph/graph.d.ts.map +1 -0
  47. package/dist/langgraph/graph.js +346 -0
  48. package/dist/langgraph/graph.js.map +1 -0
  49. package/dist/langgraph/index.d.ts +65 -12
  50. package/dist/langgraph/index.d.ts.map +1 -1
  51. package/dist/langgraph/index.js +234 -180
  52. package/dist/langgraph/index.js.map +1 -1
  53. package/dist/langgraph/nodes.d.ts +70 -0
  54. package/dist/langgraph/nodes.d.ts.map +1 -0
  55. package/dist/langgraph/nodes.js +145 -0
  56. package/dist/langgraph/nodes.js.map +1 -0
  57. package/dist/messages.d.ts +18 -0
  58. package/dist/messages.d.ts.map +1 -0
  59. package/dist/messages.js +182 -0
  60. package/dist/messages.js.map +1 -0
  61. package/dist/object.d.ts +65 -23
  62. package/dist/object.d.ts.map +1 -1
  63. package/dist/object.js +123 -40
  64. package/dist/object.js.map +1 -1
  65. package/dist/output.d.ts +15 -7
  66. package/dist/output.d.ts.map +1 -1
  67. package/dist/output.js +44 -26
  68. package/dist/output.js.map +1 -1
  69. package/dist/pi/index.d.ts +39 -11
  70. package/dist/pi/index.d.ts.map +1 -1
  71. package/dist/pi/index.js +281 -77
  72. package/dist/pi/index.js.map +1 -1
  73. package/dist/pi/storage.d.ts +29 -4
  74. package/dist/pi/storage.d.ts.map +1 -1
  75. package/dist/pi/storage.js +18 -6
  76. package/dist/pi/storage.js.map +1 -1
  77. package/dist/signals.d.ts +75 -7
  78. package/dist/signals.d.ts.map +1 -1
  79. package/dist/signals.js +154 -27
  80. package/dist/signals.js.map +1 -1
  81. package/dist/steering.d.ts +31 -0
  82. package/dist/steering.d.ts.map +1 -0
  83. package/dist/steering.js +45 -0
  84. package/dist/steering.js.map +1 -0
  85. package/dist/tools.d.ts +28 -0
  86. package/dist/tools.d.ts.map +1 -1
  87. package/dist/tools.js +34 -5
  88. package/dist/tools.js.map +1 -1
  89. package/package.json +33 -37
  90. package/src/calls.ts +110 -24
  91. package/src/claude/README.md +41 -20
  92. package/src/claude/index.ts +271 -183
  93. package/src/client.ts +14 -3
  94. package/src/common.ts +354 -247
  95. package/src/conversation.ts +1527 -0
  96. package/src/deepseek/README.md +78 -11
  97. package/src/deepseek/index.ts +385 -138
  98. package/src/deepseek/persistence.ts +11 -8
  99. package/src/index.ts +13 -4
  100. package/src/langgraph/README.md +115 -25
  101. package/src/langgraph/checkpointer.ts +168 -28
  102. package/src/langgraph/context.ts +27 -0
  103. package/src/langgraph/errors.ts +26 -0
  104. package/src/langgraph/graph.ts +396 -0
  105. package/src/langgraph/index.ts +337 -193
  106. package/src/langgraph/nodes.ts +243 -0
  107. package/src/messages.ts +244 -0
  108. package/src/object.ts +178 -48
  109. package/src/output.ts +52 -31
  110. package/src/pi/README.md +18 -3
  111. package/src/pi/index.ts +346 -79
  112. package/src/pi/storage.ts +20 -7
  113. package/src/signals.ts +235 -31
  114. package/src/steering.ts +67 -0
  115. package/src/tools.ts +61 -8
  116. package/dist/claude/conversation.d.ts +0 -33
  117. package/dist/claude/conversation.d.ts.map +0 -1
  118. package/dist/claude/conversation.js +0 -95
  119. package/dist/claude/conversation.js.map +0 -1
  120. package/dist/log.d.ts +0 -29
  121. package/dist/log.d.ts.map +0 -1
  122. package/dist/log.js +0 -145
  123. package/dist/log.js.map +0 -1
  124. package/dist/opencode/db.d.ts +0 -40
  125. package/dist/opencode/db.d.ts.map +0 -1
  126. package/dist/opencode/db.js +0 -161
  127. package/dist/opencode/db.js.map +0 -1
  128. package/dist/opencode/index.d.ts +0 -100
  129. package/dist/opencode/index.d.ts.map +0 -1
  130. package/dist/opencode/index.js +0 -436
  131. package/dist/opencode/index.js.map +0 -1
  132. package/src/claude/conversation.ts +0 -114
  133. package/src/log.ts +0 -193
  134. package/src/opencode/README.md +0 -125
  135. package/src/opencode/db.ts +0 -223
  136. package/src/opencode/index.ts +0 -559
@@ -1,5 +1,7 @@
1
- // LangGraph agents in Restate virtual objects: a tool-calling graph whose
2
- // checkpoints are in the object's database (checkpointer.ts).
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,93 +15,125 @@
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 LangGraph carries on from the last step it
17
- // stored:
18
- // - Each step is stored before the next starts (`durability: 'sync'`), in
19
- // order with everything else the handler does. So the tool calls a model
20
- // made are stored before any tool runs, and a crash during the tools
21
- // resumes them with the same tool call ids, which a tool passes on to stay
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: the graph records each answer
27
- // in its state, and a retried attempt returns it.
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
- import type { ChatAnthropic } from '@langchain/anthropic';
32
- import type { ChatOpenAI } from '@langchain/openai';
33
32
  import type { BaseChatModel } from '@langchain/core/language_models/chat_models';
34
- import { AIMessage, type BaseMessage, HumanMessage, SystemMessage, ToolMessage } from '@langchain/core/messages';
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';
35
43
  import { type StructuredToolInterface, tool, ToolInputParsingException } from '@langchain/core/tools';
36
- import { Annotation, END, isGraphInterrupt, MessagesAnnotation, START, StateGraph } from '@langchain/langgraph';
44
+ import { END, isGraphInterrupt, MessagesAnnotation, START, StateGraph } from '@langchain/langgraph';
37
45
  import { ToolNode, toolsCondition } from '@langchain/langgraph/prebuilt';
38
46
  import {
39
- AttemptEnded,
40
- CANCELLED,
41
47
  chatHandler,
42
48
  type Configure,
43
49
  configured,
44
50
  fromTool,
45
- messagesHandler,
46
51
  ModelError,
47
52
  modelOf,
48
- nextPromptId,
49
53
  providerOf,
50
- refusal,
54
+ RETURNED_UNRECORDED,
51
55
  stopSignalOf,
52
- storedAnswer,
56
+ type Summarize,
53
57
  toolCallEnded,
54
58
  toolCallStarted,
55
- transcribing,
56
- Transcript,
57
- UNANSWERED,
59
+ NO_ANSWER,
58
60
  } from '../common.ts';
59
- import { type Answer, withOutput } from '../output.ts';
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';
60
64
  import type { z } from 'zod';
61
65
  import { type Definition, sessionObject } from '../object.ts';
66
+ import { takeSteers } from '../steering.ts';
62
67
  import { isTool, jsonSchemaOf, type Tool as AnyTool } from '../tools.ts';
63
68
 
64
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';
65
73
 
66
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
+ };
67
115
 
68
- const State = Annotation.Root({
69
- ...MessagesAnnotation.spec,
70
- /** The id of the prompt being answered. */
71
- prompt: Annotation<string>(),
72
- /** The answer to each prompt, by id. */
73
- answers: Annotation<Record<string, string>>({ reducer: (a, b) => ({ ...a, ...b }), default: () => ({}) }),
74
- });
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())));
75
122
 
76
123
  /**
77
- * The tools node: each tool call of the model's last message run by a
78
- * ToolNode, which answers the model with what is wrong when a call names a
79
- * tool the agent does not have, or arguments that do not fit (the model's to
80
- * fix: failing the attempt, every retry would meet the same call again). Any
81
- * other error of a tool fails the attempt, at once (the ToolNode would hand
82
- * it to the model too). The round is published as it starts and ends, for
83
- * 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.
84
127
  */
85
- function toolsNode(ctx: restate.SessionContext, tools: StructuredToolInterface[]) {
86
- return async (state: typeof MessagesAnnotation.State, config: RunnableConfig) => {
87
- await toolCallStarted(ctx);
88
- // The first error fails the attempt at once, not once the other calls end.
89
- const { promise: failure, reject: failed } = Promise.withResolvers<never>();
90
- failure.catch(() => {});
91
- const node = new ToolNode(
92
- tools.map((t) => failing(t, failed)),
93
- { handleToolErrors: true },
94
- );
95
- const ran: { messages: BaseMessage[] } = await Promise.race([node.invoke(state, config), failure]);
96
- await toolCallEnded(ctx);
97
- return ran;
98
- };
99
- }
128
+ const sendable = (messages: BaseMessage[]) =>
129
+ messages.map((m) => (AIMessage.isInstance(m) && blank(m) ? new AIMessage(NO_ANSWER) : m));
100
130
 
101
131
  /** `t`, its errors given to `failed`, but for its input's (arguments that do not fit) and LangGraph's interrupts. */
102
- const failing = (t: StructuredToolInterface, failed: (error: unknown) => void): StructuredToolInterface =>
132
+ const failing = (
133
+ ctx: restate.SessionContext,
134
+ t: StructuredToolInterface,
135
+ failed: (error: unknown) => void,
136
+ ): StructuredToolInterface =>
103
137
  Object.create(t, {
104
138
  invoke: {
105
139
  value: async (...args: Parameters<StructuredToolInterface['invoke']>) => {
@@ -107,7 +141,7 @@ const failing = (t: StructuredToolInterface, failed: (error: unknown) => void):
107
141
  return await t.invoke(...args);
108
142
  } catch (error) {
109
143
  if (!(error instanceof ToolInputParsingException) && !isGraphInterrupt(error)) {
110
- fromTool(error);
144
+ fromTool(ctx, error);
111
145
  failed(error);
112
146
  }
113
147
  throw error;
@@ -116,6 +150,47 @@ const failing = (t: StructuredToolInterface, failed: (error: unknown) => void):
116
150
  },
117
151
  }) as StructuredToolInterface;
118
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
+
119
194
  /** `provider/model-id` as its provider and model id, for a provider the usual graph takes. */
120
195
  const providerOfModel = (named: string) => {
121
196
  const [provider, id] = providerOf(named);
@@ -128,22 +203,21 @@ const providerOfModel = (named: string) => {
128
203
 
129
204
  /**
130
205
  * The chat model `provider/model-id` names: OpenAI's or Anthropic's, through
131
- * LangChain's integration of the provider, loaded once, when a model of it is
132
- * first used: only that one need be installed.
206
+ * LangChain's integration of the provider, loaded when a model of it is
207
+ * used (Node loads a module once): only that one need be installed.
133
208
  */
134
209
  const chatModel = async (named: string): Promise<BaseChatModel> => {
135
210
  const [provider, id] = providerOfModel(named);
136
211
  if (provider === 'openai') {
137
- openai ??= integration('@langchain/openai', () => import('@langchain/openai'));
138
- return new (await openai).ChatOpenAI({ model: id });
212
+ const { ChatOpenAI } = await integration('@langchain/openai', () => import('@langchain/openai'));
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 });
139
216
  }
140
- anthropic ??= integration('@langchain/anthropic', () => import('@langchain/anthropic'));
141
- return new (await anthropic).ChatAnthropic({ model: id });
217
+ const { ChatAnthropic } = await integration('@langchain/anthropic', () => import('@langchain/anthropic'));
218
+ return new ChatAnthropic({ model: id });
142
219
  };
143
220
 
144
- let openai: Promise<{ ChatOpenAI: typeof ChatOpenAI }> | undefined;
145
- let anthropic: Promise<{ ChatAnthropic: typeof ChatAnthropic }> | undefined;
146
-
147
221
  /** The integration `name`, which its user installs beside @restatedev/agents. */
148
222
  async function integration<T>(name: string, load: () => Promise<T>): Promise<T> {
149
223
  try {
@@ -156,33 +230,111 @@ async function integration<T>(name: string, load: () => Promise<T>): Promise<T>
156
230
  }
157
231
  }
158
232
 
159
- /** The agent's graph: `model`, calling `tools`. */
160
- function graph(ctx: restate.SessionContext, model: BaseChatModel, tools: StructuredToolInterface[], system?: string) {
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
+ ) {
161
248
  if (!model.bindTools) throw new Error(`${model.getName()} does not call tools`);
162
249
  const withTools = model.bindTools(tools);
163
- return new StateGraph(State)
164
- .addNode('model', async ({ messages }) => ({
165
- messages: [await withTools.invoke(system ? [new SystemMessage(system), ...messages] : messages)],
166
- }))
167
- .addNode('tools', toolsNode(ctx, tools))
168
- .addNode('answer', ({ prompt, messages }) => ({ answers: { [prompt]: messages.at(-1)!.text } }))
169
- .addEdge(START, 'model')
170
- .addConditionalEdges('model', toolsCondition, { tools: 'tools', [END]: 'answer' })
171
- .addEdge('tools', 'model')
172
- .addEdge('answer', END);
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');
173
266
  }
174
267
 
175
- /** `t` as a LangChain tool: `t.run` checks the model's arguments itself. */
176
- const native = (t: AnyTool, ctx: restate.SessionContext): StructuredToolInterface =>
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 =>
177
303
  tool(
178
- async (args: unknown, { toolCall }) => {
304
+ async (args: unknown, config) => {
305
+ const { toolCall } = config;
179
306
  if (!toolCall?.id) throw new Error('a tool call without an id');
180
- return t.run(args, { ctx, callId: toolCall.id });
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 });
181
315
  },
182
316
  // What does not fit, for the model to fix: not only that something does not.
183
317
  { name: t.name, description: t.description, schema: jsonSchemaOf(t), verboseParsingErrors: true },
184
318
  );
185
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
+
186
338
  /** An agent's options: `chat` and `prompt` take them. */
187
339
  export interface Options<O extends z.ZodObject | undefined = z.ZodObject | undefined> {
188
340
  /** The model: `openai/model-id` or `anthropic/model-id` (MODEL, or else openai/gpt-6-sol), or a chat model that calls tools. */
@@ -191,145 +343,130 @@ export interface Options<O extends z.ZodObject | undefined = z.ZodObject | undef
191
343
  system?: string;
192
344
  /** The agent's tools: `tool()`s, Restate's (`call`, `signal`...), or LangChain's. */
193
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;
194
348
  /**
195
349
  * The answer as data: a zod object, whose JSON the agent replies with
196
- * (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.
197
352
  */
198
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;
199
368
  }
200
369
 
201
- /** {@link prompt}, answering with the agent's text. */
202
- const promptText = (ctx: restate.SessionContext, text: string, options: Options): Promise<string> =>
203
- transcribing(
204
- ctx,
205
- () => transcribe(ctx.db, ctx.key),
206
- () => answerOnce(ctx, text, options),
207
- );
208
-
209
- const answerOnce = async (
210
- ctx: restate.SessionContext,
211
- text: string,
212
- { model, system, tools = [] }: Options,
213
- ): Promise<string> => {
214
- const llm = typeof model === 'object' ? model : await chatModel(modelOf(model));
215
- // The latest checkpoint is all an agent resumes from: earlier ones would
216
- // store the conversation again at each step.
217
- const checkpointer = new SqlCheckpointSaver(ctx.db, { history: 'latest' });
218
- const app = graph(
219
- ctx,
220
- llm,
221
- tools.map((t) => (isTool(t) ? native(t, ctx) : t)),
222
- system,
223
- ).compile({ checkpointer });
224
- const config = { configurable: { thread_id: ctx.key }, durability: 'sync' as const };
225
- const id = nextPromptId(ctx);
226
- for (;;) {
227
- const state = await app.getState(config);
228
- const answer = state.values.answers?.[id];
229
- if (answer !== undefined) return storedAnswer(answer);
230
- // Finish an interrupted run first (this prompt's, after a crash), then
231
- // start this prompt's. A run is unfinished while its prompt has no
232
- // answer: `next` does not say, as it leaves out the steps whose writes
233
- // are stored.
234
- const { prompt: last, answers = {} } = state.values;
235
- const interrupted = last !== undefined && answers[last] === undefined;
236
- const turn = stopSignalOf(ctx);
237
- try {
238
- await app.invoke(interrupted ? null : { messages: [new HumanMessage(text)], prompt: id }, {
239
- ...config,
240
- signal: turn,
241
- });
242
- } catch (error) {
243
- // The attempt ended: it stops, and the next attempt goes on with the run.
244
- if (turn?.reason instanceof AttemptEnded) throw turn.reason;
245
- // Cancelled: the run ends, and the next prompt starts afresh.
246
- if (turn?.aborted || error instanceof restate.CancelledError) {
247
- await close(app, config, CANCELLED);
248
- throw turn?.aborted ? turn.reason : error;
249
- }
250
- // Refused for good (a wrong API key): the run ends unanswered, and
251
- // fails as terminal. An earlier prompt's, this one goes on.
252
- const refused = refusal(error);
253
- if (!refused) throw error;
254
- await close(app, config, UNANSWERED);
255
- if (!interrupted || last === id) throw refused;
256
- }
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;
257
375
  }
258
- };
259
-
260
- /**
261
- * End the run of `app` that was cancelled or refused, as its `answer` node: a
262
- * result of `text` for each tool call of the last reply that has none, then
263
- * `text` as the reply and the prompt's answer. A run that stored no input
264
- * yet (cancelled at once) has nothing to end: the prompt the state has is
265
- * an earlier one, which has its answer.
266
- */
267
- async function close(app: ReturnType<ReturnType<typeof graph>['compile']>, config: RunnableConfig, text: string) {
268
- const { values } = await app.getState(config);
269
- if (values.prompt === undefined || values.answers?.[values.prompt] !== undefined) return;
270
- const messages = (values.messages ?? []) as BaseMessage[];
271
- const answered = new Set(messages.filter((m) => ToolMessage.isInstance(m)).map((m) => m.tool_call_id));
272
- const last = messages.findLast((m) => AIMessage.isInstance(m));
273
- const calls = (last && AIMessage.isInstance(last) ? (last.tool_calls ?? []) : []).filter(
274
- (call) => call.id !== undefined && !answered.has(call.id),
275
- );
276
- await app.updateState(
277
- config,
278
- {
279
- messages: [
280
- ...calls.map((call) => new ToolMessage({ tool_call_id: call.id!, content: text, status: 'error' })),
281
- new AIMessage(text),
282
- ],
283
- answers: { [values.prompt]: text },
284
- },
285
- 'answer',
376
+ const extra = Object.entries({ model, system, tools: given, recursionLimit }).flatMap(([name, value]) =>
377
+ value === undefined ? [] : [name],
286
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);
287
383
  }
288
384
 
385
+ /** The chat model of `model`. */
386
+ const modelOfOptions = async (model: Options['model']) =>
387
+ typeof model === 'object' ? model : chatModel(modelOf(model));
388
+
289
389
  /**
290
390
  * Answer `text`, once: a retried attempt resumes the same prompt. Each prompt
291
- * of an invocation is a prompt of its own. The thread is the object's key.
391
+ * of an invocation is a prompt of its own.
292
392
  * With `output`, it answers with the value the agent replies with (see
293
- * 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.
294
395
  */
295
396
  export const prompt = <O extends z.ZodObject | undefined = undefined>(
296
397
  ctx: restate.SessionContext,
297
398
  text: string,
298
399
  options: Options<O> = {},
299
- ): Promise<Answer<O>> => withOutput(text, options, (t, o) => promptText(ctx, t, o)) as 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
+ };
300
425
 
301
426
  /**
302
- * A chat handler: each message an invocation, the thread (the object's key)
303
- * in the object's database, with `options`, or the options a function of the
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
304
429
  * invocation's context gives. It takes the message as plain text
305
430
  * (`curl -d 'Hi'`) or as a JSON string (`curl --json '"Hi"'`).
306
431
  */
307
432
  export const chat = <O extends z.ZodObject | undefined = undefined>(options: Configure<Options<O>> = {}) => {
308
- if (typeof options === 'object' && typeof options.model !== 'object') providerOfModel(modelOf(options.model));
309
- return chatHandler(async (ctx, message) => prompt(ctx, message, await configured(options, ctx)));
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
+ });
310
452
  };
311
453
 
312
454
  /**
313
- * A handler of the conversation as clients read it: a page at a time, or
314
- * what is new or changed since a cursor, from the log each change writes
315
- * (log.ts). It answers while a message is answered.
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.
316
458
  */
317
- export const messages = () => messagesHandler();
459
+ export const messages = () => conversationView(items);
318
460
 
319
- /** The thread `key` in `db`, from its last checkpoint, as `messages` gives it. */
320
- const transcribe = async (db: Database, key: string) => {
321
- const transcript = new Transcript();
322
- const saved = await new SqlCheckpointSaver(db).getTuple({ configurable: { thread_id: key } });
323
- for (const m of (saved?.checkpoint.channel_values.messages ?? []) as BaseMessage[]) {
324
- if (HumanMessage.isInstance(m)) transcript.say('user', m.text);
325
- if (AIMessage.isInstance(m)) {
326
- transcript.say('assistant', m.text);
327
- for (const call of m.tool_calls ?? []) transcript.call(call.id ?? '', call.name, call.args);
328
- }
329
- if (ToolMessage.isInstance(m)) transcript.result(m.tool_call_id, m.text, m.status === 'error');
330
- }
331
- return transcript;
332
- };
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;
333
470
 
334
471
  /** An agent: a virtual object `name`, one per key, whose `chat` handler is {@link chat}, and `messages` {@link messages}. */
335
472
  export const agent = <P extends string, O extends z.ZodObject | undefined = undefined>({
@@ -337,6 +474,9 @@ export const agent = <P extends string, O extends z.ZodObject | undefined = unde
337
474
  description,
338
475
  schema,
339
476
  background,
477
+ window,
478
+ budget,
479
+ summarize,
340
480
  ...options
341
481
  }: Options<O> & Definition<P>) =>
342
482
  sessionObject({
@@ -344,6 +484,10 @@ export const agent = <P extends string, O extends z.ZodObject | undefined = unde
344
484
  description,
345
485
  schema,
346
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),
347
491
  handlers: { chat: chat(options) },
348
492
  views: { messages: messages() },
349
493
  });