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