AIChatAgent API reference for Python
agents.AIChatAgent extends Agent, so every hook and
method there also works here. See Build a chat agent for a guide.
Options
Set options = AIChatAgentOptions(...) on the class. It extends
AgentOptions with these fields. A plain
AgentOptions on a chat agent raises TypeError when the agent is created.
| Field | Type | Default | Description |
|---|---|---|---|
message_concurrency |
MessageConcurrency |
"queue" |
What a send does while another turn runs: "queue", "latest", "merge", "drop" or Debounce(seconds). |
max_persisted_messages |
int \| None |
None |
Keep at most this many stored messages, deleting the oldest after each save. |
hydration_byte_budget |
int \| None |
33554432 (32 MiB) |
Bytes of the newest messages self.messages loads on wake. None loads all. |
Debounce(seconds) waits 0.75 seconds by default. A negative or non-finite
seconds raises ValueError. message_concurrency applies only to user
sends. Regenerations and turns from save_messages always queue.
Hooks
on_chat_message
def on_chat_message(
self, options: ChatMessageOptions
) -> AsyncIterator[UIMessageChunk] | AsyncIterator[str]
Produces the reply to self.messages. Write it as an async generator that
yields str or chunks, not both. An async def that returns an async
iterator also works. The default raises NotImplementedError.
ChatMessageOptions fields:
| Field | Type | Description |
|---|---|---|
request_id |
str |
The turn's id. |
client_tools |
Sequence[ClientToolSchema] |
Tools the client declared, with name, description, parameters. |
body |
dict[str, JSONValue] \| None |
Extra fields from the client's request body. None when there are none. |
continuation |
bool |
True when the turn appends to the last assistant message. |
on_chat_response
async def on_chat_response(self, result: ChatResponseResult) -> None
Runs after a turn's message is saved, for every outcome except a skipped
turn. ChatResponseResult has message, request_id, continuation,
status ("completed", "error" or "aborted") and error, the error
message, which is None unless status is "error". It may call
save_messages. A turn started from here doesn't call on_chat_response
again.
sanitize_message_for_persistence
def sanitize_message_for_persistence(self, message: UIMessage) -> UIMessage
Returns the message as it should be stored. Runs on every saved message. The default returns it unchanged.
repair_interrupted_tool_part
def repair_interrupted_tool_part(self, part: AnyToolPart) -> UIMessagePart
Replaces a tool call left without a result before the next turn, so the model
never sees a call with no result. The default returns an output-error part.
Transcript
| Member | Returns | Description |
|---|---|---|
messages |
Sequence[UIMessage] |
The conversation, oldest first. Read-only. |
persist_messages(messages, *, exclude=()) |
None |
Stores messages as the transcript without running a turn. Sends the result to clients except exclude. |
save_messages(messages) |
SaveMessagesResult |
Stores messages, then runs a turn to answer them. Waits for a running turn. |
continue_last_turn(*, body=None) |
SaveMessagesResult |
Runs a turn that appends to the last assistant message. |
delete_messages(message_ids, *, exclude=()) |
None |
Deletes messages by id and ignores unknown ids. |
save_messages also accepts an async function that receives the current
messages and returns the new list. persist_messages doesn't delete stored
messages that the list leaves out.
SaveMessagesResult has request_id, status ("completed", "error",
"skipped" or "aborted") and error. "skipped" means the chat was cleared
before the turn ran, or continue_last_turn found no assistant message.
Cancelling the code awaiting save_messages stops the turn and raises
CancelledError.
Turn control
| Method | Description |
|---|---|
abort_request(request_id) |
Stops one running turn. It ends as "aborted" and its partial reply is saved. |
abort_all_requests() |
Stops every running turn. Queued turns still run. |
reset_turn_state() |
Stops the running turn and drops queued ones. |
Storage attributes
| Attribute | Type | Description |
|---|---|---|
sessions |
Sessions |
Where the transcript is stored. |
streams |
Streams |
Where each turn's output is stored, so reconnecting clients can resume. |
Messages and parts
UIMessage is a dataclass matching the AI SDK's UIMessage. Its fields are
keyword-only:
@dataclass(slots=True, kw_only=True)
class UIMessage:
id: str
role: Literal["system", "user", "assistant"]
parts: list[UIMessagePart] = field(default_factory=list)
metadata: JSONValue = None
UIMessagePart is one of: TextPart, ReasoningPart, FilePart,
SourceUrlPart, SourceDocumentPart, StepStartPart, DataPart, a tool part
(ToolInputStreamingPart, ToolInputAvailablePart,
ToolOutputAvailablePart, ToolOutputErrorPart, ToolOutputDeniedPart,
ToolApprovalRequestedPart, ToolApprovalRespondedPart) or UnknownPart.
Use isinstance to tell them apart.
Chunks
on_chat_message yields classes from agents.chat.chunks. Fields are
snake_case versions of the
AI SDK v6 chunk fields.
| Group | Classes |
|---|---|
| Text | TextStart(id), TextDelta(id, delta), TextEnd(id) |
| Reasoning | ReasoningStart(id), ReasoningDelta(id, delta), ReasoningEnd(id) |
| Tools | ToolInputStart, ToolInputDelta, ToolInputAvailable, ToolInputError, ToolOutputAvailable, ToolOutputError, ToolOutputDenied, ToolApprovalRequest |
| Sources | SourceUrl, SourceDocument, File |
| Data | Data, MessageMetadata |
| Steps | StartStep, FinishStep |
| Control | Start, Finish, Error(error_text), Abort |
Rules the SDK enforces:
- The SDK sends
StartandFinishif the stream doesn't. - A delta or end chunk must follow a start chunk with the same id
(
TextStart,ReasoningStartorToolInputStart). Otherwise the turn fails withTypeError. - A
strafter chunks, or a chunk after astr, fails the turn withTypeError. Errorends the turn as failed, andon_errorreceives aChatStreamErrorwhoseerror_textis what the client was sent.