Skip to main content

ChatTaskOptions

Options for chat.task().
OptionTypeDefaultDescription
idstringrequiredTask identifier
run(payload: ChatTaskRunPayload) => Promise<unknown>requiredHandler for each turn
clientDataSchemaTaskSchemaSchema for validating and typing clientData
onPreload(event: PreloadEvent) => Promise<void> | voidFires on preloaded runs before the first message
onChatStart(event: ChatStartEvent) => Promise<void> | voidFires on turn 0 before run()
onTurnStart(event: TurnStartEvent) => Promise<void> | voidFires every turn before run()
onTurnComplete(event: TurnCompleteEvent) => Promise<void> | voidFires after each turn completes
maxTurnsnumber100Max conversational turns per run
turnTimeoutstring"1h"How long to wait for next message
warmTimeoutInSecondsnumber30Seconds to stay warm before suspending
chatAccessTokenTTLstring"1h"How long the scoped access token remains valid
preloadWarmTimeoutInSecondsnumberSame as warmTimeoutInSecondsWarm timeout after onPreload fires
preloadTimeoutstringSame as turnTimeoutSuspend timeout for preloaded runs
uiMessageStreamOptionsChatUIMessageStreamOptionsDefault options for toUIMessageStream(). Per-turn override via chat.setUIMessageStreamOptions()
Plus all standard TaskOptionsretry, queue, machine, maxDuration, etc.

ChatTaskRunPayload

The payload passed to the run function.
FieldTypeDescription
messagesModelMessage[]Model-ready messages — pass directly to streamText
chatIdstringUnique chat session ID
trigger"submit-message" | "regenerate-message"What triggered the request
messageIdstring | undefinedMessage ID (for regenerate)
clientDataTyped by clientDataSchemaCustom data from the frontend (typed when schema is provided)
continuationbooleanWhether this run is continuing an existing chat (previous run ended)
signalAbortSignalCombined stop + cancel signal
cancelSignalAbortSignalCancel-only signal
stopSignalAbortSignalStop-only signal (per-turn)

PreloadEvent

Passed to the onPreload callback.
FieldTypeDescription
chatIdstringChat session ID
runIdstringThe Trigger.dev run ID
chatAccessTokenstringScoped access token for this run
clientDataTyped by clientDataSchemaCustom data from the frontend

ChatStartEvent

Passed to the onChatStart callback.
FieldTypeDescription
chatIdstringChat session ID
messagesModelMessage[]Initial model-ready messages
clientDataTyped by clientDataSchemaCustom data from the frontend
runIdstringThe Trigger.dev run ID
chatAccessTokenstringScoped access token for this run
continuationbooleanWhether this run is continuing an existing chat
previousRunIdstring | undefinedPrevious run ID (only when continuation is true)
preloadedbooleanWhether this run was preloaded before the first message

TurnStartEvent

Passed to the onTurnStart callback.
FieldTypeDescription
chatIdstringChat session ID
messagesModelMessage[]Full accumulated conversation (model format)
uiMessagesUIMessage[]Full accumulated conversation (UI format)
turnnumberTurn number (0-indexed)
runIdstringThe Trigger.dev run ID
chatAccessTokenstringScoped access token for this run
clientDataTyped by clientDataSchemaCustom data from the frontend
continuationbooleanWhether this run is continuing an existing chat
previousRunIdstring | undefinedPrevious run ID (only when continuation is true)
preloadedbooleanWhether this run was preloaded

TurnCompleteEvent

Passed to the onTurnComplete callback.
FieldTypeDescription
chatIdstringChat session ID
messagesModelMessage[]Full accumulated conversation (model format)
uiMessagesUIMessage[]Full accumulated conversation (UI format)
newMessagesModelMessage[]Only this turn’s messages (model format)
newUIMessagesUIMessage[]Only this turn’s messages (UI format)
responseMessageUIMessage | undefinedThe assistant’s response for this turn
rawResponseMessageUIMessage | undefinedRaw response before abort cleanup
turnnumberTurn number (0-indexed)
runIdstringThe Trigger.dev run ID
chatAccessTokenstringScoped access token for this run
lastEventIdstring | undefinedStream position for resumption
stoppedbooleanWhether the user stopped generation during this turn
continuationbooleanWhether this run is continuing an existing chat

ChatSessionOptions

Options for chat.createSession().
OptionTypeDefaultDescription
signalAbortSignalrequiredRun-level cancel signal
warmTimeoutInSecondsnumber30Seconds to stay warm between turns
timeoutstring"1h"Duration string for suspend timeout
maxTurnsnumber100Max turns before ending

ChatTurn

Each turn yielded by chat.createSession().
FieldTypeDescription
numbernumberTurn number (0-indexed)
chatIdstringChat session ID
triggerstringWhat triggered this turn
clientDataunknownClient data from the transport
messagesModelMessage[]Full accumulated model messages
uiMessagesUIMessage[]Full accumulated UI messages
signalAbortSignalCombined stop+cancel signal (fresh each turn)
stoppedbooleanWhether the user stopped generation this turn
continuationbooleanWhether this is a continuation run
MethodReturnsDescription
complete(source)Promise<UIMessage | undefined>Pipe, capture, accumulate, cleanup, and signal turn-complete
done()Promise<void>Signal turn-complete (when you’ve piped manually)
addResponse(response)Promise<void>Add response to accumulator manually

chat namespace

All methods available on the chat object from @trigger.dev/sdk/ai.
MethodDescription
chat.task(options)Create a chat task
chat.createSession(payload, options)Create an async iterator for chat turns
chat.pipe(source, options?)Pipe a stream to the frontend (from anywhere inside a task)
chat.pipeAndCapture(source, options?)Pipe and capture the response UIMessage
chat.writeTurnComplete(options?)Signal the frontend that the current turn is complete
chat.createStopSignal()Create a managed stop signal wired to the stop input stream
chat.messagesInput stream for incoming messages — use .waitWithWarmup()
chat.local<T>({ id })Create a per-run typed local (see Per-run data)
chat.createAccessToken(taskId)Create a public access token for a chat task
chat.setTurnTimeout(duration)Override turn timeout at runtime (e.g. "2h")
chat.setTurnTimeoutInSeconds(seconds)Override turn timeout at runtime (in seconds)
chat.setWarmTimeoutInSeconds(seconds)Override warm timeout at runtime
chat.setUIMessageStreamOptions(options)Override toUIMessageStream() options for the current turn
chat.defer(promise)Run background work in parallel with streaming, awaited before onTurnComplete
chat.isStopped()Check if the current turn was stopped by the user
chat.cleanupAbortedParts(message)Remove incomplete parts from a stopped response message
chat.streamTyped chat output stream — use .writer(), .pipe(), .append(), .read()
chat.MessageAccumulatorClass that accumulates conversation messages across turns

ChatUIMessageStreamOptions

Options for customizing toUIMessageStream(). Set as static defaults via uiMessageStreamOptions on chat.task(), or override per-turn via chat.setUIMessageStreamOptions(). See Stream options for usage examples. Derived from the AI SDK’s UIMessageStreamOptions with onFinish, originalMessages, and generateMessageId omitted (managed internally).
OptionTypeDefaultDescription
onError(error: unknown) => stringRaw error messageCalled on LLM errors and tool execution errors. Return a sanitized string — sent as { type: "error", errorText } to the frontend.
sendReasoningbooleantrueSend reasoning parts to the client
sendSourcesbooleanfalseSend source parts to the client
sendFinishbooleantrueSend the finish event. Set to false when chaining multiple streamText calls.
sendStartbooleantrueSend the message start event. Set to false when chaining.
messageMetadata(options: { part }) => metadataExtract message metadata to send to the client. Called on start and finish events.

TriggerChatTransport options

Options for the frontend transport constructor and useTriggerChatTransport hook.
OptionTypeDefaultDescription
taskstringrequiredTask ID to trigger
accessTokenstring | () => string | Promise<string>requiredAuth token or function that returns one
baseURLstring"https://api.trigger.dev"API base URL (for self-hosted)
streamKeystring"chat"Stream key (only change if using custom key)
headersRecord<string, string>Extra headers for API requests
streamTimeoutSecondsnumber120How long to wait for stream data
clientDataTyped by clientDataSchemaDefault client data for every request
sessionsRecord<string, {...}>Restore sessions from storage
onSessionChange(chatId, session | null) => voidFires when session state changes
triggerOptions{...}Options for the initial task trigger (see below)

triggerOptions

Options forwarded to the Trigger.dev API when starting a new run. Only applies to the first message — subsequent messages reuse the same run. A chat:{chatId} tag is automatically added to every run.
OptionTypeDescription
tagsstring[]Additional tags for the run (merged with auto-tags, max 5 total)
queuestringQueue name for the run
maxAttemptsnumberMaximum retry attempts
machine"micro" | "small-1x" | ...Machine preset for the run
prioritynumberPriority (lower = higher priority)
const transport = useTriggerChatTransport({
  task: "my-chat",
  accessToken: getChatToken,
  triggerOptions: {
    tags: ["user:123"],
    queue: "chat-queue",
  },
});

transport.preload()

Eagerly trigger a run before the first message.
transport.preload(chatId, { warmTimeoutInSeconds?: number }): Promise<void>
No-op if a session already exists for this chatId. See Preload for full details.

useTriggerChatTransport

React hook that creates and memoizes a TriggerChatTransport instance. Import from @trigger.dev/sdk/chat/react.
import { useTriggerChatTransport } from "@trigger.dev/sdk/chat/react";
import type { myChat } from "@/trigger/chat";

const transport = useTriggerChatTransport<typeof myChat>({
  task: "my-chat",
  accessToken: () => getChatToken(),
  sessions: savedSessions,
  onSessionChange: handleSessionChange,
});
The transport is created once on first render and reused across re-renders. Pass a type parameter for compile-time validation of the task ID.