Skip to content
Source
Sign inSign up
TanStack/ai
Open History to see the last commit

turn.ts

284 lines10.2 KB

1import type { AnyTextAdapter, KeyedAdapter, ModelMessage } from '@tanstack/ai'
2import type { LogRecord } from '@tanstack/ai-persistence'
3import type { SessionWithMetadata } from './define'
4import type {
5 HarnessInput,
6 HarnessUser,
7 SettlementOutcome,
8 TurnOverrides,
9 UserInput,
10} from './types'
11​
12/** What recovery does with one input. */
13export type RecoverDecision =
14 | {
15 action: 'run'
16 /**
17 * The overrides of the turn that runs, as in `prompt()`. Not kept in
18 * the log: a later recovery asks the hook again. A steer that joins
19 * the running turn ignores them.
20 */
21 overrides?: TurnOverrides
22 }
23 | ({ action: 'settle' } & Exclude<
24 SettlementOutcome,
25 { outcome: 'interrupted' }
26 >)
27​
28/** What `durability.recover` gets for one input. */
29export interface RecoverContext<TMetadataSchema = any> {
30 session: SessionWithMetadata<TMetadataSchema>
31 input: {
32 inputId: string
33 input: HarnessInput
34 attempt: number
35 timeoutAt?: number
36 abortRequested: boolean
37 operationId?: string
38 /** Model retries since the last finished tool phase, from the log. */
39 retries: number
40 }
41 /** The transcript of the session, from the log. */
42 messages: ReadonlyArray<ModelMessage>
43 /**
44 * The tool calls of this input that recovery closes with an error result,
45 * in call order: `'interrupted'` for a `replay: 'never'` call that a crash
46 * cut (it gets `durability.interruptedToolResult`), and `'truncated'` for a
47 * call of an answer that stopped at the output limit (it gets
48 * `durability.truncatedToolResult`). A finished call and a `replay: 'safe'`
49 * call (it runs again) are not in it. The list is the same when the hook
50 * settles the input, so then it names the calls that a run would close.
51 */
52 interruptedTools: ReadonlyArray<{
53 toolCallId: string
54 toolName: string
55 reason: 'interrupted' | 'truncated'
56 }>
57 /** What the harness does when the hook returns `undefined`. */
58 decision: RecoverDecision
60​
61/** Decide how an input that a crashed host left recovers. */
62export type RecoverHook<TMetadataSchema = any> = (
63 ctx: RecoverContext<TMetadataSchema>,
64) => RecoverDecision | undefined | Promise<RecoverDecision | undefined>
65​
66/** Messages and host records that a turn hook adds, in one append. */
67export interface TurnAdditions {
68 /** Messages after the transcript, for the next model call. */
69 messages?: Array<ModelMessage>
70 /** Host records in the same append. */
71 records?: ReadonlyArray<LogRecord>
72 /**
73 * Messages at the end of the context of the next model call only. No store
74 * keeps them: not the transcript, and not the log.
75 */
76 ephemeral?: ReadonlyArray<ModelMessage>
78​
79/** What `turn.onModelError` gets. */
80export interface ModelErrorContext<TMetadataSchema = any> {
81 session: SessionWithMetadata<TMetadataSchema>
82 operationId: string
83 inputId?: string
84 /**
85 * `retryAfterMs` is how long the provider asks you to wait, from the
86 * `RUN_ERROR` event. Adapters read it from the `retry-after` headers.
87 */
88 error: { message: string; code?: string; retryAfterMs?: number }
89 /**
90 * Retries since the last finished tool phase of this turn. The log keeps
91 * the count, so an attempt that recovery runs goes on from it. The
92 * log has the count with this failed call before the hook runs, so a host
93 * that stops during a backoff loses no retry.
94 */
95 retries: number
96 /**
97 * True when the failed call streamed text, reasoning, or a tool call before
98 * the error.
99 */
100 partial: boolean
101 /** The adapter of the failed call. */
102 adapter: AnyTextAdapter
103 /** The model of the failed call, `provider/model`, as `TurnInfo.model`. */
104 model: string
105 /** Aborted when the turn is cancelled. */
106 signal: AbortSignal
108​
109/**
110 * What `turn.onModelError` returns. `{ retry: true, adapter }` retries as
111 * `'retry'` does, on `adapter`, for the rest of the turn.
112 */
113export type ModelErrorAnswer =
114 | 'retry'
115 | 'continue'
116 | { retry: true; adapter: AnyTextAdapter | KeyedAdapter<AnyTextAdapter> }
117 | undefined
118​
119/** What `turn.beforeFinish` gets. */
120export interface FinishContext<TMetadataSchema = any> {
121 session: SessionWithMetadata<TMetadataSchema>
122 operationId: string
123 inputId?: string
124 /** How many times this hook continued the turn so far. */
125 cycle: number
126 messages: ReadonlyArray<ModelMessage>
127 signal: AbortSignal
129​
130/** An input that waits to join the running turn. */
131export interface JoinCandidate {
132 inputId: string
133 message: UserInput
134 /**
135 * Who sent the input. A joined input runs with the credentials of the
136 * turn's sender, so refuse a join from another person when that matters.
137 */
138 user?: HarnessUser
139 /**
140 * Who sent the running turn. Compare it with `user` to keep one
141 * person's message out of another person's turn.
142 */
143 turnUser?: HarnessUser
145​
146/** What `turn.onJoin` gets. */
147export interface JoinContext<TMetadataSchema = any> {
148 session: SessionWithMetadata<TMetadataSchema>
149 operationId: string
150 /** The inputs that join now, in admission order. */
151 inputs: ReadonlyArray<JoinCandidate>
152 signal: AbortSignal
154​
155/** Hooks that control a chat turn. */
156export interface HarnessTurnOptions<TMetadataSchema = any> {
157 /**
158 * A run of the turn failed (a `RUN_ERROR`, or an error thrown by the run).
159 * Return `'retry'` to run the model again in the same operation, after any
160 * work (a backoff, a compaction record). The text of the failed call is
161 * dropped. Return `'continue'` to keep that text: the model gets it and a
162 * note to continue from where it stopped. When no text streamed,
163 * `'continue'` acts as `'retry'`. See `retryTransientErrors`.
164 *
165 * Return `{ retry: true, adapter }` to retry on another model: the next
166 * calls of this turn use `adapter`, and `TurnInfo.model` and the usage
167 * name its model. A keyed adapter gets the key of the turn's user. A
168 * recovery after a host stop starts again on the turn's own model.
169 *
170 * A chat middleware `onModelError` (for example `withCompaction` on a
171 * `context_overflow`) runs first, inside the `chat()` call, and can retry
172 * there with `ctx.retry()`. This hook sees the error only after such
173 * retries also fail.
174 */
175 onModelError?: (
176 ctx: ModelErrorContext<TMetadataSchema>,
177 ) => ModelErrorAnswer | Promise<ModelErrorAnswer>
178 /**
179 * The model stopped calling tools and the turn would end. Return messages,
180 * records, or ephemeral messages to send the model back to work in the same
181 * turn.
182 */
183 beforeFinish?: (
184 ctx: FinishContext<TMetadataSchema>,
185 ) => TurnAdditions | undefined | Promise<TurnAdditions | undefined>
186 /**
187 * How many times `beforeFinish` can continue one turn. Default 32. At the
188 * limit, a hook that still returns messages or records fails the turn
189 * (records or ephemeral messages alone count too).
190 */
191 maxFinishCycles?: number
192 /**
193 * Whether a waiting input joins the running turn now. A refused input
194 * stops the join: it and the inputs after it wait.
195 */
196 canJoin?: (candidate: JoinCandidate) => boolean | Promise<boolean>
197 /** Runs before the model call that the joined inputs reach. */
198 onJoin?: (
199 ctx: JoinContext<TMetadataSchema>,
200 ) => TurnAdditions | undefined | Promise<TurnAdditions | undefined>
202​
203// ponytail: the patterns of Flue's isRetryableModelError. A qualified finish
204// reason (error_quota, content_filter) stays terminal. The status codes need
205// word boundaries, or the 500 in "250000 tokens" would match.
206const TRANSIENT_ERROR =
207 /overloaded|rate.?limit|too many requests|\b(?:429|500|502|503|504)\b|service.?unavailable|server.?error|network.?error|connection.?(?:reset|refused|lost|error)|socket hang up|fetch failed|timed? out|timeout|terminated|provider finish_reason:\s*error(?![-\w])/i
208​
209/**
210 * True for a model error that can pass when you try again: overloaded, rate
211 * limits, 429 and 5xx, network and connection errors, timeouts, and a
212 * provider `finish_reason: error`.
213 */
214export function isTransientModelError(error: {
215 message: string
216 code?: string
217}): boolean {
218 return (
219 TRANSIENT_ERROR.test(error.message) ||
220 (error.code !== undefined && TRANSIENT_ERROR.test(error.code))
221 )
223​
224/** Resolve after `ms`, or at once when `signal` aborts. */
225export function wait(ms: number, signal: AbortSignal) {
226 return new Promise<void>((resolve) => {
227 if (signal.aborted) return resolve()
228 const done = () => {
229 clearTimeout(timer)
230 signal.removeEventListener('abort', done)
231 resolve()
232 }
233 const timer = setTimeout(done, ms)
234 signal.addEventListener('abort', done, { once: true })
235 })
237​
238/**
239 * A `turn.onModelError` policy: retry a transient model error after a
240 * backoff of `baseDelayMs * 2^retries`, times a jitter from 0.75 to 1.0.
241 * When the error has a `retryAfterMs`, it waits that long instead. Above
242 * `maxRetryAfterMs`, it does not retry. It answers `'continue'` when the
243 * failed call streamed output, so the model continues it, and `'retry'`
244 * otherwise.
245 *
246 * @example
247 * ```ts
248 * defineHarness({ ..., turn: { onModelError: retryTransientErrors() } })
249 * ```
250 */
251export function retryTransientErrors(
252 options: {
253 /** Retries after the last finished tool phase. Default 3. */
254 maxRetries?: number
255 /** The first delay, in milliseconds. Default 2000. */
256 baseDelayMs?: number
257 /** Default {@link isTransientModelError}. */
258 isTransient?: (error: { message: string; code?: string }) => boolean
259 /**
260 * The longest `retryAfterMs` to wait, in milliseconds. A longer one ends
261 * the retries. Default 900000 (15 minutes).
262 */
263 maxRetryAfterMs?: number
264 } = {},
265) {
266 const maxRetries = options.maxRetries ?? 3
267 const baseDelayMs = options.baseDelayMs ?? 2_000
268 const isTransient = options.isTransient ?? isTransientModelError
269 const maxRetryAfterMs = options.maxRetryAfterMs ?? 15 * 60_000
270 return async (ctx: ModelErrorContext) => {
271 if (ctx.retries >= maxRetries || !isTransient(ctx.error)) return undefined
272 const { retryAfterMs } = ctx.error
273 if (retryAfterMs !== undefined && retryAfterMs > maxRetryAfterMs) {
274 return undefined
275 }
276 const jitter = 0.75 + Math.random() * 0.25
277 await wait(
278 retryAfterMs ?? Math.round(baseDelayMs * 2 ** ctx.retries * jitter),
279 ctx.signal,
280 )
281 if (ctx.signal.aborted) return undefined
282 return ctx.partial ? 'continue' : 'retry'
283 }