aixplain.v2.session
from aixplain import ExecutionConfig, ExecutionConfigDict, Session, SessionMessage, SessionMessageAttachment
Session module for aiXplain v2 SDK.
resolve_attachments
def resolve_attachments(context: Any,
attachments: Optional[List[Union[str, Path, Dict[str,
Any],
File]]],
files: Optional[List[Union[str, Path]]],
*,
error_label: str = "") -> List[Dict[str, Any]]
Normalize the unified attachments (plus deprecated files) for the API.
Each entry becomes a {url, name, type, mimeType} dict. URL entries (http(s)://
/ s3:// strings, or dicts carrying a url) pass through unchanged; local paths
(plain strings, or dicts carrying a path) are uploaded to aiXplain storage and the
resulting download link is attached. A saved File is attached by a short-lived
signed url fetched on demand (File.get_signed_url) — file-asset responses
never carry a stable url; an unsaved File or a folder raises, rather than
silently re-uploading or guessing. The FileUploader is created lazily, only when
an upload is actually needed. Shared by Session.add_message and Agent runs.
Arguments:
context- An object exposingbackend_urlandapi_key(the SDK context).attachments- The unified attachments list.files- Deprecated local-path list (merged in, with a warning).error_label- Optional context for upload-error messages (e.g."session 's1'").
SessionMessageAttachment Objects
@dataclass_json
@dataclass
class SessionMessageAttachment()
Attachment on a session message.
SessionMessage Objects
@dataclass_json
@dataclass
class SessionMessage()
A message within a session (not a resource — all ops go through Session).
ExecutionConfigDict Objects
class ExecutionConfigDict(TypedDict)
The dict form of ExecutionConfig, on the same field names.
Every key is optional, so a partial update leaves the rest of the session's
configuration alone. Declared as a TypedDict so a plain dict still gets
autocomplete and a type error on a misspelled key, with nothing to import.
ExecutionConfig Objects
@dataclass_json
@dataclass
class ExecutionConfig()
Per-session execution configuration.
Mirrors the run-time agent parameters historically passed to
agent.run so that messages posted to a session execute the agent
with the same configuration. The backend reads executionConfig
on session create/update and applies it when subsequent user
messages trigger agent runs.
Attributes:
execution_params- Backend execution params (output format, max tokens, etc.). Both snake_case and camelCase keys are accepted; snake_case is normalized to camelCase on send.criteria- Free-form evaluation criteria sent to the agent.evolve- Evolution config as a JSON string (kept as a string to match the backend contract).identifier- Free-form identifier the backend can echo back on messages (e.g. for client-side correlation).run_response_generation- Whether the agent should run its final response-generation step.budget- Per-session run budget (cost / duration / iterations). Accepts aBudgetinstance or a snake_case/camelCase dict. Serialized intoexecutionParams.budgetso messages posted to the session run the agent with this budget — the session-scoped equivalent of the agent's ownagent.budget.
__setattr__
def __setattr__(name: str, value: Any) -> None
Coerce a dict budget into a Budget, rejecting unknown keys.
Here rather than in __post_init__ so that config.budget = {...}
behaves the same as passing it to the constructor: reading it back gives
an object with attributes, and a misspelled key raises instead of
silently meaning "no cap". The generated __init__ assigns through
this too, so ExecutionConfig(budget={...}) is covered by the same
check. Mirrors how Agent.__setattr__ coerces budget.
Strict everywhere except inside _decoding_wire_payload, which the
two from_dict entry points set. budget is typed Any, so
dataclasses_json hands over the raw wire dict instead of decoding it
the way it does for every other input struct -- and a field the backend
adds to the budget object is not a caller's typo, so it must not break
every Session.get().
to_api_dict
def to_api_dict() -> Dict[str, Any]
Build the camelCase API payload, normalizing nested params.
Only fields the caller set are included so the backend keeps
existing values on partial updates. The deprecated
execution_params['max_iterations'] is folded into
executionParams.budget.maxIterations (Budget wins on conflict) and a
standalone executionParams.maxIterations is never emitted — mirroring
the agent run path so sessions and direct runs behave identically.
coerce
@classmethod
def coerce(cls, value: Any) -> Optional["ExecutionConfig"]
Accept an ExecutionConfig, dict, or None and return a config or None.
An unknown key raises rather than being dropped: from_dict ignores
what it does not recognise, so a misspelled critera used to produce a
session configured with no criteria at all and no indication why.
Raises:
ValidationError- If value is a dict carrying an unrecognised key.TypeError- If value is neitherNone, a config, nor a dict.
Session Objects
@dataclass_json
@dataclass(repr=False)
class Session(BaseResource, GetResourceMixin[BaseGetParams, "Session"],
DeleteResourceMixin[BaseDeleteParams, "Session"],
SearchResourceMixin[BaseSearchParams, "Session"])
Session resource for managing agent conversation sessions.
Sessions are the single entry point for conversation threads: create with
aix.Session(agent=…) + save(), find with aix.Session.search(agent=…),
and drive with agent.run(query, session=…). Each session is bound to one
agent (agent_id).
__setattr__
def __setattr__(name: str, value: Any) -> None
Coerce a dict execution_config into an ExecutionConfig.
On every assignment rather than in __post_init__ alone: a dict
assigned afterwards stayed a dict, so build_save_payload died with
AttributeError: 'dict' object has no attribute 'to_api_dict' and an
unknown key went unvalidated. Mirrors how Trigger coerces
configuration.
__post_init__
def __post_init__(agent: Optional[Any] = None) -> None
Resolve the agent convenience arg.
execution_config is coerced by __setattr__, which the generated
__init__ routes through, so there is nothing left to do here.
build_save_payload
def build_save_payload(**kwargs: Any) -> dict
Build payload with only mutable fields.
search
@classmethod
def search(cls,
agent: Optional[Any] = None,
status: Optional[str] = None,
user_id: Optional[str] = None,
created_after: Optional[Union[str, datetime]] = None,
created_before: Optional[Union[str, datetime]] = None,
memory_enabled: Optional[bool] = None,
page_number: int = 0,
page_size: int = 20,
**kwargs: Any) -> Page["Session"]
Search sessions with optional filters, returning a paginated Page.
The single, standard way to list sessions (there is no agent.list_sessions()
and no bespoke Session.list()). Mirrors the search on every other
asset, but hits the session list endpoint (a plain GET /v1/sessions
with query-param filters) and wraps the result in a Page.
Arguments:
agent- Filter by agent — anAgentinstance or an agent id string.status- Filter by session status (e.g."active").user_id- Filter by owning user id.created_after- Lower bound on the session's creation time (datetimeor ISO string).created_before- Upper bound on the session's creation time.memory_enabled- WhenTruereturn memory-on threads (sessions with persisted traces); whenFalsereturn memory-off runs.None(default) applies no memory filter. (Backend filter delivery is a follow-up; the SDK forwards the parameter today.)page_number- Zero-indexed page number (default 0).page_size- Page size (default 20).**kwargs- Accepted for forward compatibility with the standard search signature; ignored by the session list endpoint.
Returns:
Page[Session]- A page of Session instances.
Raises:
ResourceError- If the API response cannot be parsed or deserialization fails.APIError- If the API request fails.
messages
def messages() -> List[SessionMessage]
Get all messages in this session.
Returns:
List of SessionMessage instances.
Raises:
ResourceError- If the API response is not a list or deserialization fails.APIError- If the API request fails.
add_message
def add_message(
role: str,
content: str,
request_id: Optional[str] = None,
attachments: Optional[List[Union[str, Path, Dict[str, Any],
File]]] = None,
files: Optional[List[Union[str, Path]]] = None,
tools: Optional[List[Dict[str, Any]]] = None) -> SessionMessage
Add a message to this session.
Arguments:
-
role- Message role ("user" or "assistant"). -
content- Message content. May be empty whenattachmentscarry the turn's input (e.g. an audio clip that is itself the prompt). -
request_id- Optional request ID to associate with the message. -
attachments- The message's attachments. Each entry may be:- a hosted-URL dict
{"url", "type"?, "name"?, "mimeType"?}— used as-is; - a local-path dict
{"path": "/...", "type"?, ...}— uploaded; - a string URL (
http(s):///s3://) — attached as-is; - a string local path — uploaded to aiXplain storage.
- a hosted-URL dict
-
files- Deprecated. Local file paths to upload and attach — pass these throughattachmentsinstead. -
tools- Per-message per-tool parameter overrides in the platform[{id, parameters: [{name, value}]}]shape, applied to the run this message triggers. Normally populated automatically from the agent's tool objects byagent.run(query, session=…).
Returns:
The created SessionMessage.
Raises:
ResourceError- If the operation fails.APIError- If the API request fails.FileUploadError- If a file upload fails.
get_message
def get_message(message_id: str) -> SessionMessage
Get a specific message by ID.
Arguments:
message_id- The message ID.
Returns:
The SessionMessage.
Raises:
ResourceError- If deserialization fails.APIError- If the API request fails (e.g., message not found).
delete_message
def delete_message(message_id: str) -> None
Delete a message from this session.
Arguments:
message_id- The message ID to delete.
Raises:
APIError- If the API request fails (e.g., message not found).ResourceError- If the session is in an invalid state.
react
def react(message_id: str, reaction: Optional[str]) -> SessionMessage
React to a message or clear a reaction.
Only assistant messages can be reacted to.
Arguments:
message_id- The message ID to react to.reaction- "LIKE", "DISLIKE", or None to clear.
Returns:
The updated SessionMessage.
Raises:
APIError- If the API request fails (e.g., reacting to a non-assistant message).ResourceError- If deserialization fails.