roboto.ai.core#

Core AI abstractions usable by any other submodule within module roboto.ai.

Submodules#

Package Contents#

roboto.ai.core.AGENT_CONTENT_MODEL_BY_TYPE: dict[AgentContentType, type[AgentContent]]#

The model class for each JSON-serialized content type, keyed by discriminator.

Excludes AgentContentType.TEXT, whose payload is persisted as raw text rather than a serialized model. Every other member of AgentContent carries a content_type discriminator and round-trips through model_dump_json / model_validate_json; driving both serialization directions off this one map keeps them symmetric, so a member added to the union without a home here fails loudly instead of being silently dropped on write or reconstructed without its payload on read.

class roboto.ai.core.AgentClientContextEntry(/, **data)#

Bases: pydantic.BaseModel

The caller’s attached viewing context, carried on their own message.

Replaces a <ctx>{json}</ctx> marker persisted as a separate ROBOTO-role message. That shape made every consumer regex a JSON blob back out of prose it had serialized itself – four parsers across two languages – and relied on the ROBOTO role to keep the marker out of the chat view. It also put the context on a non-USER message, which the compression deletion pass collapses wholesale inside a resolved task’s interior, so the context silently disappeared from compressed history.

As a block on the user’s own message it is a typed field, invisible to text renderers (no text field), and safe from that collapse – USER turns are never dropped.

Parameters:

data (Any)

content_type: Literal[AgentContentType]#
context: roboto.ai.core.context.ClientViewingContext#

attached datasets, files, and visualizer state.

Type:

What the caller had open

class roboto.ai.core.AgentCompressionFillerContent(/, **data)#

Bases: pydantic.BaseModel

Filler standing in for a message the compression deletion pass emptied.

Carries no payload. A message reduced to nothing but tombstones keeps this single block instead of an empty content list, so it stays in the Bedrock payload at its original role and turn alternation survives without relocating content. The Bedrock boundary renders it as <Deleted in compression>. Produced only by the compression deletion pass and stored only at the DELETED tier; the verbatim original thread (what the SDK and UI render) never contains one.

Parameters:

data (Any)

content_type: Literal[AgentContentType]#
type roboto.ai.core.AgentContent = AgentTextContent | AgentToolUseContent | AgentToolResultContent | AgentErrorContent | AgentDeletedContent | AgentCompressionFillerContent | AgentClientContextEntry#

Type alias for all possible content types within agent messages.

class roboto.ai.core.AgentContentType#

Bases: roboto.compat.StrEnum

Enumeration of different types of content within agent messages.

Defines the various content types that can be included in agent messages.

CLIENT_CONTEXT = 'client_context'#

What the caller was looking at when they composed the message this block sits on.

Superseded shape: the same payload used to be persisted as a whole ROBOTO-role message whose text was a <ctx>...</ctx> marker (ENG-2185). Readers still accept that form for threads written before this type existed; nothing emits it any more.

COMPRESSION_FILLER = 'compression_filler'#

Stand-in block kept in a message the deletion pass emptied entirely.

A message reduced to nothing but tombstones would break user/assistant alternation if it dropped from the payload. Replacing its content with this single filler keeps the message — and its role — in place. The model sees it as <Deleted in compression>. Only the cross-message deletion pass produces it, so it appears only inside a DELETED-tier compressed variant, never in the verbatim original thread the SDK and UI read.

DELETED = 'deleted'#

Tombstone marking a content block elided by compression.

Appears only inside a DELETED-tier compressed variant. Both producers — message-tier compression dropping a pure-filler text run, and the cross-message deletion pass dropping a whole tool exchange — store their output at the DELETED tier, so a message carrying one is always a DELETED-tier variant. Never in the verbatim original thread the SDK and UI read.

ERROR = 'error'#

Error information when message generation fails.

TEXT = 'text'#

Plain text content from users or AI responses.

TOOL_RESULT = 'tool_result'#

Results returned from tool executions.

TOOL_USE = 'tool_use'#

Tool invocation requests from the AI assistant.

class roboto.ai.core.AgentDeletedContent(/, **data)#

Bases: pydantic.BaseModel

Tombstone for a content block removed by compression.

Carries no payload — its presence records that a block once occupied this slot, and it converts to None at the Bedrock boundary so the block drops from the LLM payload. Produced when compression drops a block — a pure-filler text run at message compression, or a whole redundant tool exchange in the cross-message deletion pass — and stored only at the DELETED tier, so a message carrying one is always a DELETED-tier variant. A message reduced to nothing but tombstones does not drop: it is replaced with a single AgentCompressionFillerContent so it keeps its role and turn. The verbatim original thread (what the SDK and UI render) never contains one.

Parameters:

data (Any)

content_type: Literal[AgentContentType]#
class roboto.ai.core.AgentErrorContent(/, **data)#

Bases: pydantic.BaseModel

Error content within an agent message.

Used when message generation fails due to an error or is cancelled by the user.

Parameters:

data (Any)

content_type: Literal[AgentContentType]#
error_code: str | None = None#

Optional error code for programmatic handling.

error_message: str#

User-friendly error message describing what went wrong.

class roboto.ai.core.AgentErrorEvent(/, **data)#

Bases: pydantic.BaseModel

Signals that message generation failed or was cancelled.

Parameters:

data (Any)

error_code: str | None = None#

Optional error code for programmatic handling.

error_message: str#

User-friendly error message describing what went wrong.

type roboto.ai.core.AgentEvent = Union[AgentStartTextEvent, AgentTextDeltaEvent, AgentTextEndEvent, AgentToolUseEvent, AgentToolResultEvent, AgentErrorEvent]#
class roboto.ai.core.AgentMessage(/, **data)#

Bases: pydantic.BaseModel

A single message within an agent thread.

Represents one message in the conversation, containing the sender role, content blocks, and generation status. Messages can contain multiple content blocks of different types (text, tool use, tool results).

Parameters:

data (Any)

content: list[roboto.ai.core.content.AgentContent]#

List of content blocks that make up this message.

created: datetime.datetime = None#

Timestamp when this message was created.

is_complete()#

Check if message generation is complete.

Returns:

True if the message status is COMPLETED, False otherwise.

Return type:

bool

is_unsuccessful()#

Check if message generation failed or was cancelled.

Returns:

True if the message status is FAILED or CANCELLED, False otherwise.

Return type:

bool

role: AgentRole#

The role of the message sender (user, assistant, or roboto).

status: AgentMessageStatus#

Current generation status of this message.

classmethod text(text, role=AgentRole.USER)#

Create a simple text message.

Convenience method for creating a message containing only text content.

Parameters:
  • text (str) – The text content for the message.

  • role (AgentRole) – The role of the message sender. Defaults to USER.

Returns:

AgentMessage instance containing the text content.

Return type:

AgentMessage

class roboto.ai.core.AgentMessageStatus#

Bases: roboto.compat.StrEnum

Enumeration of possible message generation states.

Tracks the lifecycle of message generation from initiation to completion.

CANCELLED = 'cancelled'#

Message generation was cancelled by the user.

COMPLETED = 'completed'#

Message generation has finished and content is complete.

FAILED = 'failed'#

Message generation failed due to an error.

GENERATING = 'generating'#

Message content is currently being generated.

NOT_STARTED = 'not_started'#

Message has been queued but generation has not begun.

is_terminal()#

Check if the message generation is in a terminal state.

Returns:

True if the message is in a terminal state, False otherwise.

Return type:

bool

class roboto.ai.core.AgentRole#

Bases: roboto.compat.StrEnum

Enumeration of possible roles in an agent thread.

Defines the different participants that can send messages in a thread.

ASSISTANT = 'assistant'#

AI agent responding to user queries and requests.

ROBOTO = 'roboto'#

Roboto system providing tool results and system information.

USER = 'user'#

Human user sending messages to the agent.

class roboto.ai.core.AgentStartTextEvent(/, **data)#

Bases: pydantic.BaseModel

Signals the beginning of text generation in a chat response.

Parameters:

data (Any)

class roboto.ai.core.AgentTextContent(/, **data)#

Bases: pydantic.BaseModel

Text content within an agent message.

Parameters:

data (Any)

text: str#

The actual text content of the message.

class roboto.ai.core.AgentTextDeltaEvent(/, **data)#

Bases: pydantic.BaseModel

Contains incremental text content as the AI generates its response.

Parameters:

data (Any)

text: str#

Text fragment from the streaming response.

class roboto.ai.core.AgentTextEndEvent(/, **data)#

Bases: pydantic.BaseModel

Signals the completion of text generation in a chat response.

Parameters:

data (Any)

class roboto.ai.core.AgentThreadDelta(/, **data)#

Bases: pydantic.BaseModel

Incremental update to an agent thread.

Contains only the changes since the last synchronization, used for efficient real-time updates without transferring the entire thread history.

Parameters:

data (Any)

continuation_token: str#

Updated token for the next incremental synchronization.

goals: list[AgentThreadGoalRecord] | None = None#

Latest snapshot of every goal declared in the thread, ordered by allocation. None means there has been no change since the previous delta — clients should retain the snapshot they already hold. An empty list means the thread has no declared goals. A non-empty list is the authoritative current snapshot and replaces any prior value.

messages_by_idx: dict[int, AgentMessage]#

New or updated messages indexed by their position in the conversation.

reset_from_message_sequence_num: int | None = None#

Discard held messages from this index onward before applying this delta.

A delta’s messages normally extend what a client already holds, because the server sends only content the client has not seen. That breaks when a turn is abandoned partway and regenerated: the replacement message reuses the same index, so what the client holds at that index is text from an attempt that no longer exists, and appending to it would splice the real reply onto a discarded draft.

When this field is set, the client must truncate its held messages to indices strictly below it, then apply messages_by_idx and adopt continuation_token as usual — the server has rewound the stream to that point and will resend it. None (the common case) means append as normal.

status: AgentThreadStatus | None = None#

Updated status of the agent thread.

tasks: list[roboto.ai.core.task.AgentTask] | None = None#

Latest snapshot of the thread’s task list, ordered by position. None means no change since the previous delta — clients should retain the snapshot they already hold. An empty list means the thread has no tasks. A non-empty list is the authoritative current snapshot and replaces any prior value.

title: str | None = None#

Updated title of the agent thread.

class roboto.ai.core.AgentThreadRecord(/, **data)#

Bases: pydantic.BaseModel

Complete record of an agent thread.

Contains all the persistent data for a thread including metadata, message history, and synchronization state.

Parameters:

data (Any)

continuation_token: str#

Token used for incremental updates and synchronization.

created: datetime.datetime#

Timestamp when this agent thread was created.

created_by: str#

User ID of the person who created this agent thread.

created_by_principal: str | None = None#

Serialized RobotoPrincipal ("ptype:id") that started this thread, e.g. "user:jo@example.com" or "invocation:iv_123". Unlike created_by, this preserves whether the thread was driven by a person, a device, or an action invocation. None on threads created before this field existed.

created_from_agent_id: str | None = None#

If this thread was started via the agent launch flow, the id of the agent that produced it. None for threads started directly through POST /v1/ai/threads. Forks do not inherit this field — a fork is its own thread.

created_from_trigger_id: str | None = None#

If a trigger’s start_agent target launched this thread, the id of that trigger. None for every other thread, including one launched from the same agent by a person. Set alongside created_from_agent_id, which names the agent; this names what decided to run it. Forks do not inherit this field — a fork is its own thread.

forked_from_message_sequence_num: int | None = None#

Message sequence number in the source thread that this fork was taken from.

Populated in tandem with forked_from_thread_id; both are None for threads that were not created as a fork.

forked_from_thread_id: str | None = None#

If this thread was forked, the id of the source thread. None otherwise.

Deserialization also accepts the legacy forked_from_session_id spelling for backward compatibility.

goals: list[AgentThreadGoalRecord] | None = None#

Goals declared across this thread’s turns, ordered by the turn that declared them. None means goals were not loaded for this record; an empty list means they were loaded but the thread never declared any.

messages: list[AgentMessage] = None#

Complete list of messages in the conversation.

model_config#

Configuration for the model, should be a dictionary conforming to [ConfigDict][pydantic.config.ConfigDict].

model_profile: str | None = None#

Model profile used for this agent thread (e.g., ‘standard’, ‘advanced’).

org_id: str#

Organization ID that owns this agent thread.

origin: ThreadOrigin | None = None#

The surface that owns this thread.

Set by Roboto when the thread is created; it cannot be supplied by a caller. A thread owned by a surface outside Roboto refuses new messages over the API, raising RobotoThreadReadOnlyException; reading, cancelling, and rating it stay open, and a fork does not inherit the origin, so the copy is writable.

None on threads created before this field existed, and equivalent to ThreadOrigin.API — every surface that predates the field was Roboto’s own. It stays nullable until those rows are backfilled.

pinned_at: datetime.datetime | None = None#

When the calling user pinned this thread, or None if they have not.

A pin is a personal bookmark, so two users reading the same thread see different values here. Pin and unpin through roboto.ai.agent_thread.AgentThread.set_pinned(). Only GET /v1/ai/threads and POST /v1/ai/threads/search report it; reads of a single thread leave it None whatever the pin state.

status: AgentThreadStatus#

Current status of this agent thread.

tasks: list[roboto.ai.core.task.AgentTask] | None = None#

The thread’s task list, ordered by AgentTask.position. None means tasks were not loaded for this record; an empty list means they were loaded but the thread has none.

thread_id: str = None#

Unique identifier for this agent thread.

Deserialization also accepts the legacy session_id and chat_id spellings for backward compatibility; the canonical attribute name is thread_id.

title: str | None = None#

Title of this agent thread.

visibility: ThreadVisibility#

Who can read this thread. PRIVATE (the default) restricts reads to the created_by user and Roboto admins; ORG opens the thread to every member of org_id.

class roboto.ai.core.AgentThreadStatus#

Bases: roboto.compat.StrEnum

Enumeration of possible agent thread states.

Tracks the overall status of an agent thread from creation to termination.

CLIENT_TOOL_TURN = 'client_tool_turn'#

Client must execute pending tool uses and submit results.

GOALS_FAILED = 'goals_failed'#

The agent runner exhausted its corrective re-prompt budget without achieving every declared goal for the most-recent turn. Signals to clients that the thread needs human intervention before it can continue.

NOT_STARTED = 'not_started'#

Thread has been created but no messages have been sent.

ROBOTO_TURN = 'roboto_turn'#

Roboto is generating a message.

USER_TURN = 'user_turn'#

User has the turn to send a message.

class roboto.ai.core.AgentToolResultContent(/, **data)#

Bases: pydantic.BaseModel

Tool execution result content within an agent message.

Parameters:

data (Any)

content_type: Literal[AgentContentType]#
payload: str | dict[str, Any] | list[Any] | None = None#

free-form text, or a JSON object or array of structured data.

Independent of any model provider’s wire format (provider-agnostic, like AgentToolUseContent.input). None on results written before this field existed; use resolve_payload() to read old and new results uniformly.

Type:

What the tool returned

raw_response: dict[str, Any] | None = None#

Legacy provider-formatted response envelope (Bedrock toolResult shape).

Kept so results written before payload existed remain readable; deprecated for new readers, who should call resolve_payload() instead of parsing this field.

Populated only where the server-side envelope is in scope: threads read over the API arrive with this field stripped (and, for legacy rows, with payload synthesized from it server-side before the strip), so API/SDK readers should not expect it.

resolve_payload()#

Return what the tool returned, whichever field carries it.

Prefers payload. Results written before that field existed carry only the legacy envelope, from which the equivalent value is reconstructed via synthesize_tool_result_payload().

Returns:

The tool’s text or JSON output, or None when neither field carries a recognizable value.

Return type:

Optional[Union[str, dict[str, Any], list[Any]]]

runtime_ms: int#

Wall-clock execution time of the tool in milliseconds.

status: str#

Outcome of the tool execution (e.g. ‘success’, ‘error’).

tool_name: str#

Name of the tool that was executed.

tool_use_id: str#

Identifier of the tool invocation this result corresponds to.

class roboto.ai.core.AgentToolResultEvent(/, **data)#

Bases: pydantic.BaseModel

Contains the result of a tool invocation.

Parameters:

data (Any)

name: str#

Name of the tool that was invoked.

output: dict[str, Any] | None = None#

Raw tool output payload (from the underlying tool_result’s raw_response). May be None for errored invocations or for tools that return no data.

runtime_ms: int | None = None#

Wall-clock execution time of the tool in milliseconds, as reported by the tool-result content. None only if the underlying content omits it.

success: bool#

Whether the tool invocation succeeded.

tool_use_id: str#

Unique identifier for this tool invocation.

class roboto.ai.core.AgentToolUseContent(/, **data)#

Bases: pydantic.BaseModel

Tool usage request content within an agent message.

Parameters:

data (Any)

content_type: Literal[AgentContentType]#
input: dict[str, Any] | None = None#

Parsed tool input parameters chosen by the LLM (provider-agnostic).

raw_request: dict[str, Any] | None = None#

Raw, unparsed request payload for this tool invocation.

tool_name: str#

Name of the tool the LLM is requesting to invoke.

tool_use_id: str#

Unique identifier for this tool invocation, used to correlate with its result.

class roboto.ai.core.AgentToolUseEvent(/, **data)#

Bases: pydantic.BaseModel

Signals that the AI is invoking a tool to gather information.

Parameters:

data (Any)

input: dict[str, Any] | None = None#

Parsed tool input parameters chosen by the LLM.

name: str#

Name of the tool being invoked.

tool_use_id: str#

Unique identifier for this tool invocation.

class roboto.ai.core.AnalysisScope(/, **data)#

Bases: pydantic.BaseModel

The slice of data an agent is expected to analyze.

An AnalysisScope is delivered to every AgentTool invocation on the server side. Individual tools opt in to honoring the scope as they are adopted; this SDK type carries the configuration, it does not itself enforce anything. Fields set to None are unconstrained on that dimension; an AnalysisScope with every field None is equivalent to no scope at all.

Parameters:

data (Any)

end_time: int | None = None#

Upper bound (inclusive) of the analysis window, expressed as nanoseconds since the Unix epoch.

merge(override)#

Zipper-merge override onto this scope, dimension by dimension.

For each field, the override value wins when it is set (not None); otherwise this scope’s value carries through. Used to reconcile an invoke-time scope (override) against an authored template scope (self): a launch can override individual dimensions while inheriting the rest.

Parameters:

override (AnalysisScope)

Return type:

AnalysisScope

start_time: int | None = None#

Lower bound (inclusive) of the analysis window, expressed as nanoseconds since the Unix epoch.

class roboto.ai.core.ClientToolSpec(/, **data)#

Bases: pydantic.BaseModel

Declarative specification for a client-side tool.

Unlike AgentTool (which is an ABC with a __call__ method for server-side execution), ClientToolSpec is a plain data model. The backend includes it in the LLM’s tool list but never executes it — the client is responsible for execution and submitting the result.

Parameters:

data (Any)

description: str#
input_schema: dict[str, Any]#
name: str#
class roboto.ai.core.ClientViewingContext(/, **data)#

Bases: pydantic.BaseModel

What the Roboto client (e.g. the Web UI) is currently viewing when the user composed a message.

Passed to the agent as implicit context for resolving deictic references — “this dataset”, “those files”, “the visualizer state I’m looking at” — that the user would otherwise have to spell out. This type is purely informational; it is not enforced and never gates tool authorization.

Distinct from:

  • AnalysisScope, which is a hard analysis window honored by individual tools on the server side.

  • AgentGoal, which declares typed outcomes the agent runner must drive the turn to satisfy.

The corresponding wire-format field is client_context (with a one-release context alias for migration).

Parameters:

data (Any)

collection_ids: list[str] = None#

IDs of collections the user is currently viewing or has selected.

dataset_ids: list[str] = None#

IDs of datasets the user is currently viewing or has selected.

device_ids: list[str] = None#

IDs of devices the user is currently viewing or has selected.

Device IDs are user-chosen rather than minted by Roboto, so unlike the other fields here a value may look like anything at all.

display_time_anchor_label: str | None = None#

What the client shows the user as the name of that t=0 — “Start of workspace”, or a picked timestamp rendered as local time.

Informational, like every field here: it lets the agent name the instant an offset is counted from, rather than leaving the reader to guess. None whenever display_time_anchor_ns is None.

display_time_anchor_ns: int | None = None#

Epoch nanoseconds the client renders as t=0, set only while the user is reading timestamps as an elapsed count from that instant, and None otherwise.

Informational, like every field here: it lets the agent resolve a bare relative time the user types (“around 65 s”) to an absolute instant, and the agent still reports absolute nanoseconds back.

file_ids: list[str] = None#

IDs of files the user is currently viewing or has selected.

misc_context: dict[str, Any] | None = None#

Miscellaneous client-supplied context that doesn’t fit the typed fields above. Use sparingly; prefer adding a typed field when a recurring shape emerges.

table_state: dict[str, Any] | None = None#

The resource table on screen, when the user composed the message from one: its target (datasets, files, …) and its live definition – the same shape a View stores: RoboQL text or filter controls, plus visible columns, sort, and page size.

Sent whether or not a View is loaded, so the agent can describe ad-hoc filters and so “save what I’m looking at as a View” names something concrete. Informational, like every field here.

view_ids: list[str] = None#

IDs of Views – saved, shareable searches over one resource type – applied to a resource table the user is looking at.

Informational, like every field here: it lets the agent resolve “this View” without the user naming it, and the agent still reads the View through its own tools.

visualizer_state: dict[str, Any] | None = None#

State of the visualizer, when the user composed the message from the visualizer view. A relatively opaque JSON blob.

class roboto.ai.core.ModelProfileResponse(/, **data)#

Bases: pydantic.BaseModel

Metadata about an available model profile, returned by the API.

Parameters:

data (Any)

description: str#

Short description of the profile’s characteristics.

id: str#

Profile identifier, e.g. ‘standard’ or ‘advanced’.

is_default: bool = False#

Whether this profile is selected by default for new threads.

label: str#

Human-readable display label.

roboto.ai.core.synthesize_tool_result_payload(raw_response)#

Reconstruct a tool result’s text or JSON output from its legacy response envelope.

Reads both shapes tool results were persisted with before AgentToolResultContent.payload existed:

  • The provider envelope: a toolResult object whose content list carries the output as a text or json block, followed at most by image attachments.

  • A bare output dict with no toolResult key at all — the shape client-submitted results and fabricated skill-invocation results persisted, where the dict is the tool’s output and is returned as the payload verbatim.

A json value of the exact single-key form {"items": [...]} — the wrapper applied because the model provider rejected a top-level array — is unwrapped back to the bare array. This unwrap is heuristic: a tool that genuinely returned a single-key {"items": [...]} dict is indistinguishable from the wrapper here and synthesizes as the bare array. Writers that still hold the tool’s true return value should persist AgentToolResultContent.payload directly rather than round- tripping through this function.

Parameters:

raw_response (Optional[dict[str, Any]]) – The legacy value, as carried by AgentToolResultContent.raw_response. None is accepted.

Returns:

The tool’s text or JSON output, or None when the value is absent, is a malformed envelope, or is an envelope carrying no text or JSON block.

Return type:

Optional[Union[str, dict[str, Any], list[Any]]]