Agent
The Agent and what it is built from: its model settings, subagents, permissions, skills, secrets and redaction.
Guides: What an agent is, Configuring the agent, Secrets, Guardrails, Skills and Subagents.
| Name | What it is |
|---|---|
Agent | An agent: a model and its instructions, with the tools, sandbox, connectors, MCP servers, skills, hooks and subagents it can use. |
Builtins | Built-in features of the agent. |
ProgrammaticToolCallingConfig | Options of programmatic tool calling. |
SessionAgentCustomization | Per-session overrides of an agent's settings: the agent= of Agent.start_session. |
Subagent | A child agent that its parent starts with the agents.spawn tool. |
SubagentPolicy | Limits on the subagents of one session tree: the root session and every subagent below it. |
PermissionMode | Which tool calls need an approval: "auto" runs every call that the agent's permission_policy allows (every call without one), "ask" opens an approval for each call, and "deny" refuses them. |
PermissionPolicy | Ordered permission rules and the fallback for calls that match no rule. |
PermissionRule | Whether calls of the tools that match tools run, ask for an approval or are refused. |
RegistrySkill | One skill from your workspace's AI Registry, by ID and optional version. |
AllRegistrySkills | Every skill of your workspace's AI Registry, as of the root session's start. |
agents.all_registry_skills | Give the agent every skill of your workspace's AI Registry. |
SandboxWorkspaceSkills | Serve the skills already in the sandbox, such as those of a repository a sandbox hook cloned. |
LocalSkillBundle | A skill that the agent carries with it: the files of a skill folder on your machine. |
LocalSkillFile | One file of a LocalSkillBundle. |
MistralSecret | A secret of the Mistral Secret Manager. |
redaction.Redaction | What Agent(redaction=...) takes: one RedactionPolicy or a list of them, applied in order. |
redaction.RedactionPolicy | One way the agent's traces mask secrets and personal data: a redaction policy or a (key, value) function. |
redaction.RegexRedactionPolicy | Replaces the matches of patterns, such as API keys, email addresses and card numbers, with [REDACTED] in the agent's traces. |
redaction.AttributeRedactionPolicy | Redacts the values of sensitive trace fields whole, such as messages and tool arguments, and replaces tokens in the values it keeps. |
redaction.CallbackRedactionPolicy | Redacts with your function: it gets each field's key and value and returns the value to keep, or None to drop the field. |
redaction.AttributeMaskCallback | A redaction function: it gets a field's key and value and returns the value to keep, or None to drop the field. |
AgentAgent
class Agent(
*,
model: str,
instructions: str | None = None,
provider: str = 'mistral',
name: str = 'default_agent',
max_iterations: int | None = None,
first_output_timeout_seconds: float | None = None,
builtins: Builtins | None = None,
permission_mode: PermissionMode = 'auto',
permission_policy: PermissionPolicy | None = None,
auto_compact_threshold: int | None = None,
description: str | None = None,
reasoning_effort: Literal['off', 'none', 'minimal', 'low', 'medium', 'high', 'xhigh', 'max'] | None = None,
temperature: float | None = None,
output_type: type[BaseModel] | None = None,
subagents: Sequence[Subagent] = (),
subagent_policy: SubagentPolicy | None = None,
tool_errors: Literal['hide', 'show', 'raise'] = 'hide',
tools: Sequence[PythonTool[..., Any] | ClientTool[..., Any] | Callable[..., Any]] | None = None,
environment: Sandbox | None = None,
connectors: Sequence[Connector | AllConnectors] | None = None,
mcps: dict[str, RemoteMCP] | None = None,
skills: Sequence[LocalSkillBundle | RegistrySkill | SandboxWorkspaceSkills | AllRegistrySkills] | None = None,
hooks: Sequence[Hook] | None = None,
guardrails: Sequence[Hook] | None = None,
secrets: Mapping[str, MistralSecret] | None = None,
redaction: redaction.Redaction | None = None,
)An agent: a model and its instructions, with the tools, sandbox, connectors, MCP servers, skills, hooks and subagents it can use.
Agent.run() runs one turn in a new session, Agent.start_session() starts a session for many
turns, and Agent.session(session_id) binds a handle to a session that exists. Agent.load_from()
reaches an agent you deployed.
| Parameter | Type | Default | Description |
|---|---|---|---|
model | str | required | The model, such as "mistral-large-4". |
instructions | str | None | None | Your instructions to the model, added to the agent loop's default system prompt. |
provider | str | 'mistral' | The built-in completion provider: "mistral", the default, "openai" or "anthropic". It tries a model call up to 5 times when the call fails with a rate limit, a server error such as a 503, or a network error, and waits as long as a Retry-After header asks. |
name | str | 'default_agent' | The agent's name. agents serve and agents deploy register the agent under it, and your app loads it by it. A name with a dot is reserved for Mistral's own agents. |
max_iterations | int | None | None | The most steps of the agent loop in one turn. None sets no limit. |
first_output_timeout_seconds | float | None | None | How long one model call waits for its first output. Defaults to 720 seconds. A call stopped this way, or after 300 seconds without output once it started, is retried once. |
builtins | Builtins | None | None | The built-in features to turn off, such as subagents or background processes. |
permission_mode | PermissionMode | 'auto' | Which tool calls need an approval: "auto" runs every call that permission_policy allows (every call without one), "ask" opens an approval for each call, and "deny" refuses them. |
permission_policy | PermissionPolicy | None | None | Rules that decide per tool, and per argument, whether a call runs, asks or is refused. It needs permission_mode="auto". |
auto_compact_threshold | int | None | None | The number of tokens at which the loop summarizes older turns. Defaults to a value set from the model's context window. |
description | str | None | None | What the agent does, in a sentence. A deployed agent shows it, and its traces record it. |
reasoning_effort | Literal['off', 'none', 'minimal', 'low', 'medium', 'high', 'xhigh', 'max'] | None | None | How much the model reasons, from "off" to "max". Defaults to the model's own. |
temperature | float | None | None | The sampling temperature, from 0 to 2. Defaults to the model's own. |
output_type | type[BaseModel] | None | None | A Pydantic model that the final answer of every turn must match. |
subagents | Sequence[Subagent] | () | The child agents that the agent can start, each an agents.Subagent. |
subagent_policy | SubagentPolicy | None | None | Limits on the subagents of a session tree: how many turns run at once and how deep the tree goes. |
tool_errors | Literal['hide', 'show', 'raise'] | 'hide' | What the model reads when a tool raises an unexpected error: "hide", the default, a generic message, "show" the exception's type and message, and "raise" fails the turn; for a client tool, with "raise", the exception raises in your program instead, and the call stays open. |
tools | Sequence[PythonTool[..., Any] | ClientTool[..., Any] | Callable[..., Any]] | None | None | Your functions, each a plain or @agents.tool function, and client tools. |
environment | Sandbox | None | None | The sandbox where the agent runs shell commands and edits files. Defaults to NoSandbox(): no shell and no files. |
connectors | Sequence[Connector | AllConnectors] | None | None | The connectors your workspace set up in Studio, each with agents.connector(name). |
mcps | dict[str, RemoteMCP] | None | None | MCP servers that are not Studio connectors, by name. |
skills | Sequence[LocalSkillBundle | RegistrySkill | SandboxWorkspaceSkills | AllRegistrySkills] | None | None | Instructions that the agent loads only when it needs them. |
hooks | Sequence[Hook] | None | None | Code that runs before a turn, around model and tool calls, or after the answer. |
guardrails | Sequence[Hook] | None | None | Hooks for safety checks, which run before hooks at every hook point. |
secrets | Mapping[str, MistralSecret] | None | None | The credentials that the agent reads, by name, each with where its value comes from. |
redaction | redaction.Redaction | None | None | How the agent's traces mask secrets and personal data: a redaction policy, a (key, value) function, or a list of them, applied in order. [] turns redaction off. |
Agent.runAgent.run
async def run(
content: str | Sequence[TextContentBlock | ImageContentBlock | Mapping[str, Any]],
*,
output_type: type[BaseModel] | None = None,
on_approval: ApprovalHandler | None = None,
on_sign_in: Callable[[OpenSignIn], SignInAnswer | Awaitable[SignInAnswer]] | None = None,
on_client_tool: Callable[[ClientToolCall], Any] | ClientToolAnswers | None = None,
on_event: Callable[[Event], Awaitable[None] | None] | None = None,
idempotency_key: str | None = None,
timeout: float | None = None,
) -> TurnState[Any] | BusyStart a session, run one turn in it, and return the turn's record.
The record is a value, never raised: Completed, Blocked, Interrupted, Failed,
Running, or UnknownOutcome for an outcome added after your SDK version. With output_type=T, it is
a TurnState[T]. Its session_id and turn_id reach the session and the turn again, as in
agent.session(state.session_id).
On a deployed agent, output_type only parses the answer, and the model gets the deployed
agent's format. output is InvalidOutput when the answer does not validate, and None
when the turn ended early.
A callback with no handler for it, or one whose handler returns KeepCallbackOpen(), makes
the run return Blocked. Answer it with
agent.session(state.session_id).turn(state.turn_id).answer(cb.id, ...). An approval or
sign-in handler that raises makes the run raise its error. An approval handler that returns
anything else, None included, raises SdkError. A sign-in handler that returns None,
KeepCallbackOpen(), or an answer that leaves a source out raises SdkError. A client
tool answer that cannot be sent raises ClientToolAnswerError. In each case the callback
stays open and the turn keeps running. A client tool answer or on_client_tool handler
that raises follows the agent's tool_errors: by default the model reads that the call
failed and the run goes on. With "raise", the run raises the error and the call stays
open: the turn stays blocked on it, and the session takes no new turn, until the callback
times out (one hour by default).
| Parameter | Type | Default | Description |
|---|---|---|---|
content | str | Sequence[TextContentBlock | ImageContentBlock | Mapping[str, Any]] | required | The user's message: a string, or a list of content blocks. |
output_type | type[BaseModel] | None | None | A Pydantic model that this run's answer must match, instead of the agent's own output_type; Completed.output is validated against it. |
on_approval | ApprovalHandler | None | None | A plain or async function that answers each approval of the session and its subagents with AllowApproval or DenyApproval. |
on_sign_in | Callable[[OpenSignIn], SignInAnswer | Awaitable[SignInAnswer]] | None | None | A function that answers each connector sign-in of the session and its subagents with a SignInAnswer. |
on_client_tool | Callable[[ClientToolCall], Any] | ClientToolAnswers | None | None | A function that answers each client tool call of the session and its subagents, or an agents.ClientToolAnswers. |
on_event | Callable[[Event], Awaitable[None] | None] | None | None | A function that gets each event of the turn as it comes. When the turn has ended, the last event is TurnEnded. |
idempotency_key | str | None | None | A key of 1 to 256 characters that makes the run safe to retry: a second run with the same key returns the same turn's record, even once the turn has ended. The same key with another message or other agent settings raises SessionIdempotencyConflictError. Generate it once per request, for example as a UUID. A run with a key can return Busy while another turn runs. |
timeout | float | None | None | How long the run waits for the turn, in seconds. An on_approval or on_sign_in handler's time counts; your client-tool code does not. Then the run returns Running or Blocked, and the turn keeps running. None waits until the turn ends or waits on you. |
Agent.overrideAgent.override
def override(*, model: testing.ScriptedModel) -> SelfReturn a copy of this agent that sends its model calls to model. This agent is unchanged.
Call it on a local agent: on a deployed agent, it raises SdkError.
Agent.start_sessionAgent.start_session
async def start_session(
*,
history: Sequence[HistoryImportEntry] | None = None,
session_inputs: Mapping[str, SessionInput] | None = None,
agent: SessionAgentCustomization | Mapping[str, object] | None = None,
idempotency_key: str | None = None,
on_approval: ApprovalHandler | None = None,
on_sign_in: Callable[[OpenSignIn], SignInAnswer | Awaitable[SignInAnswer]] | None = None,
on_client_tool: Callable[[ClientToolCall], Any] | ClientToolAnswers | None = None,
) -> SessionStart a session and return its handle.
A local session runs in this process until its event loop shuts down, and its handle binds again only inside that event loop. A session of a deployed agent is kept by Mistral, and its handle binds again from any process.
A second call with the same idempotency_key and the same options returns the same
session, even once it is running a turn or has ended. The same key with other
session_inputs or agent, or from an agent with other settings such as
permission_mode, raises agents.SessionIdempotencyConflictError; another history is
not checked, and returns the first session. Generate the key once per request, for example
as a UUID, and reuse it only on that request's retries.
The handlers stay in this process: they are not part of the start, so the same
idempotency_key takes other ones. An answer to a stub that is not a tool of this agent, of
its guardrails and hooks, or of its subagents raises SdkError before the start.
The handle keeps this agent's output_type: session.run(), turn.get() and
turn.result() parse a Completed output with it when given none.
| Parameter | Type | Default | Description |
|---|---|---|---|
history | Sequence[HistoryImportEntry] | None | None | Existing entries that seed the conversation. Only a local session takes it. |
session_inputs | Mapping[str, SessionInput] | None | None | The session inputs, keyed by each value's input_id. They are fixed for the session's lifetime and delivered only to the tools, hooks and sandbox hooks that declare them with agents.Depends(). |
agent | SessionAgentCustomization | Mapping[str, object] | None | None | Changes to this agent for this session only, as an agents.SessionAgentCustomization or the same keys as a dict: additional_instructions append to its instructions, and model and reasoning_effort override its completion defaults. A deployment keeps its saved agent unchanged. Permissions are not customized per session: set permission_mode= or permission_policy= on the agent. |
idempotency_key | str | None | None | A key of 1 to 256 characters that makes the start safe to retry. |
on_approval | ApprovalHandler | None | None | Answers approvals while a call waits on the handle (see Session). |
on_sign_in | Callable[[OpenSignIn], SignInAnswer | Awaitable[SignInAnswer]] | None | None | Answers sign-ins while a call waits on the handle, as on run. |
on_client_tool | Callable[[ClientToolCall], Any] | ClientToolAnswers | None | None | Answers client tool calls while a call waits on the handle, as on run. |
Agent.sessionAgent.session
def session(
session_id: str,
*,
on_approval: ApprovalHandler | None = None,
on_sign_in: Callable[[OpenSignIn], SignInAnswer | Awaitable[SignInAnswer]] | None = None,
on_client_tool: Callable[[ClientToolCall], Any] | ClientToolAnswers | None = None,
) -> SessionReturn the handle of one of this agent's sessions by its ID. Sends no request.
For a deployed agent, an ID that is not a UUID raises SdkError at once. An unknown ID
binds too: the first request through the handle raises SessionNotFoundError. The handle
keeps this agent's output_type, as start_session()'s does. An answer to a stub that
is not a tool of this agent, of its guardrails and hooks, or of its subagents raises
SdkError here.
In an async with agents.local_runtime(journal_factory=...) block, a local session that
an earlier process saved there reopens on the handle's first request, and keeps running in
this process until the block exits. It must be a session of this agent: one with other
tools, hooks, MCP servers, connectors or sandbox raises SessionConfigMismatchError,
and one that another process holds open raises SessionInUseError.
| Parameter | Type | Default | Description |
|---|---|---|---|
session_id | str | required | The ID of the session. |
on_approval | ApprovalHandler | None | None | Answers approvals while a call waits on the handle (see Session). |
on_sign_in | Callable[[OpenSignIn], SignInAnswer | Awaitable[SignInAnswer]] | None | None | Answers sign-ins while a call waits on the handle, as on run. |
on_client_tool | Callable[[ClientToolCall], Any] | ClientToolAnswers | None | None | Answers client tool calls while a call waits on the handle, as on run. |
Agent.load_fromAgent.load_from
@classmethod
def load_from(
*,
agent_name: str | None = None,
agent_id: str | None = None,
server_url: str | None = None,
api_key: str | None = None,
client: Client | None = None,
) -> AgentBuild a lazy handle to a deployed agent, by its name or its ID.
Pass exactly one of agent_name or agent_id, of an agent deployed with Studio,
self-hosted or Mistral-managed. To continue a session, bind a handle to it with .session(session_id).
Without client, server_url and api_key build one with no shared connection pool:
each session then opens its own, which closes with the session and serves the event loop
that opened it. Pass either client or them, not both.
| Parameter | Type | Default | Description |
|---|---|---|---|
agent_name | str | None | None | The name the agent was deployed under. |
agent_id | str | None | None | The ID of the deployed agent, a UUID. |
server_url | str | None | None | The Mistral API root, as agents.Client takes it. |
api_key | str | None | None | The API key, as agents.Client takes it. |
client | Client | None | None | The client that the agent and its sessions send their requests through. |
BuiltinsBuiltins
class Builtins(
*,
skills: bool = True,
subagents: bool = True,
programmatic_tool_calling: bool | ProgrammaticToolCallingConfig = True,
background_processes: bool | None = None,
)Built-in features of the agent. Everything is on by default; set a field to False to opt out.
File and shell tools are not here: they come from the sandbox access level.
Builtins.noneBuiltins.none
@classmethod
def none() -> SelfNo built-in features. With the default NoSandbox, the model sees only your tools.
A sandbox still gives the file and shell tools its access level allows.
ProgrammaticToolCallingConfigProgrammaticToolCallingConfig
class ProgrammaticToolCallingConfig(*, sleep: bool = True)Options of programmatic tool calling. Passing them turns the feature on.
Per-session customization
SessionAgentCustomizationSessionAgentCustomization
class SessionAgentCustomization(
*,
additional_instructions: str = '',
model: str | None = None,
reasoning_effort: Literal['off', 'none', 'minimal', 'low', 'medium', 'high', 'xhigh', 'max'] | None = None,
)Per-session overrides of an agent's settings: the agent= of Agent.start_session.
additional_instructions append to the agent's instructions; model and reasoning_effort
override its completion defaults. A field left out keeps the agent's value; None for model or
reasoning_effort and unknown keys raise a validation error. agent= also takes the same keys as a
dict.
Subagents
SubagentSubagent
class Subagent(
*,
name: str,
description: str,
instructions: str,
model: str | None = None,
provider: str | None = None,
reasoning_effort: Literal['off', 'none', 'minimal', 'low', 'medium', 'high', 'xhigh', 'max'] | None = None,
temperature: float | None = None,
max_iterations: int | None = None,
first_output_timeout_seconds: float | None = None,
auto_compact_threshold: int | None = None,
tools: Sequence[PythonTool[..., Any] | ClientTool[..., Any] | Callable[..., Any]] | None = None,
hooks: Sequence[Hook] | None = None,
mcps: Mapping[str, RemoteMCP] | None = None,
connectors: Sequence[Connector | AllConnectors] | None = None,
skills: Sequence[LocalSkillBundle | RegistrySkill] | None = None,
subagents: Sequence[Subagent] | None = None,
builtins: Builtins | None = None,
sandbox_access: Literal['none', 'files', 'full'] | None = None,
)A child agent that its parent starts with the agents.spawn tool.
A subagent runs in its own session, below its parent's, as the user who started the root
session. It uses the parent's value for every field you leave as None. A field you set
replaces the parent's value, and an empty list gives the subagent none: nothing is merged.
model, reasoning_effort and temperature follow the same rules as on
agents.Agent. provider needs model too. The parent's output_type never reaches
a subagent: its result is its final answer.
A subagent always runs under the root agent's permission policy and mode. To make it stricter, give it fewer tools.
A subagent can have tools and hooks that its parent does not have. Their functions run where the parent's run. Tool names are shared by the whole tree, so two different functions cannot have the same name anywhere in it.
Connectors: connectors=[] gives the subagent none. A list takes the same items as
Agent(connectors=...): agents.connector(...) gives it exactly those connectors, and
agents.all_connectors(...) gives it every connector the user can use.
builtins is the one field that merges: each field you set in agents.Builtins(...)
replaces the parent's value, and each field you leave out keeps it. For example,
agents.Builtins(skills=False) turns off only skills. Turning off programmatic_tool_calling
also needs subagents=False. A subagent that sets its own skills or subagents needs that
built-in on. sandbox_access sets the subagent's access to the sandbox the whole tree shares;
a tree with no sandbox takes only "none".
skills takes local bundles and registry skills. On a sandbox that holds files, a subagent's
own skills are written into it when the subagent starts. agents.all_registry_skills() is for the
root agent only: a subagent that leaves skills unset uses the root's skills.
To add a tool to the parent's, pass the parent's list and the child's extended list:
BASE = [lookup, search]
agent = agents.Agent(
model="mistral-large-4",
tools=BASE,
subagents=[
agents.Subagent(
name="deployer",
description="Deploys a reviewed build.",
instructions="Deploy only what you are asked to deploy.",
tools=[*BASE, deploy],
)
],
)SubagentPolicySubagentPolicy
class SubagentPolicy(
*,
concurrent_child_turn_limit: int = 10,
max_depth: int = 2,
idle_message_starts: Literal['direct_children', 'none'] = 'direct_children',
)Limits on the subagents of one session tree: the root session and every subagent below it.
Pass it as Agent(subagent_policy=...). The root agent's policy applies to every subagent
below it, and a subagent cannot raise it. An agent that has subagents and no policy gets the
defaults below.
Permissions
PermissionModePermissionMode
PermissionMode = Literal['auto', 'ask', 'deny']Which tool calls need an approval: "auto" runs every call that the agent's permission_policy
allows (every call without one), "ask" opens an approval for each call, and "deny" refuses them.
PermissionPolicyPermissionPolicy
class PermissionPolicy(
*,
default: Literal['allow', 'deny', 'ask'],
rules: tuple[PermissionRule, ...] = (),
)Ordered permission rules and the fallback for calls that match no rule.
PermissionRulePermissionRule
class PermissionRule(
*,
tools: tuple[str, ...],
decision: Literal['allow', 'deny', 'ask'],
allowlist: tuple[str, ...] = (),
denylist: tuple[str, ...] = (),
sensitive: tuple[str, ...] = (),
)Whether calls of the tools that match tools run, ask for an approval or are refused.
A policy applies the first rule whose tools match the call's stable tool ID, such as
client.deploy_service, not the name the model sees; a call that matches no rule gets the
policy's default. In the rule that applies:
- A
denylistpattern matches: deny. - A
sensitivepattern matches: ask. allowlistis not empty: allow if a pattern matches, otherwise ask.- Otherwise: the rule's
decision.
Patterns are case-sensitive globs that match the whole text. Argument patterns match the call's
arguments as JSON with sorted keys, with or without a space after : and ,, such as
'*"environment": "production"*'. A tools pattern with no namespace and no wildcard, such
as deploy_service, matches no tool, so it raises ValueError.
Skills
RegistrySkillRegistrySkill
class RegistrySkill(*, id: UUID, version: int | None = None)One skill from your workspace's AI Registry, by ID and optional version.
AllRegistrySkillsAllRegistrySkills
class AllRegistrySkills()Every skill of your workspace's AI Registry, as of the root session's start.
agents.all_registry_skills() returns it.
agents.all_registry_skillsagents.all_registry_skills
def agents.all_registry_skills() -> AllRegistrySkillsGive the agent every skill of your workspace's AI Registry.
A deployed agent gets the skills that the user who starts the session can use. A local
session uses your Mistral API key. The versions are fixed when the session starts, and each
skill downloads the first time the agent uses it. A RegistrySkill in the same list keeps
its own version.
SandboxWorkspaceSkillsSandboxWorkspaceSkills
class SandboxWorkspaceSkills(
*,
root: str | None = None,
dirs: tuple[str, ...] = ('.agents/skills', '.vibe/skills'),
)Serve the skills already in the sandbox, such as those of a repository a sandbox hook cloned.
The SDK looks for them once, after the sandbox hooks ran and before the first turn. A skill is
a folder with a SKILL.md under one of dirs, in root or in a repository directly
below it.
LocalSkillBundleLocalSkillBundle
class LocalSkillBundle(*, files: list[LocalSkillFile] = [])A skill that the agent carries with it: the files of a skill folder on your machine.
Build one with LocalSkillBundle.from_directory(path).
LocalSkillBundle.from_directoryLocalSkillBundle.from_directory
@classmethod
def from_directory(path: str | Path) -> SelfBundle a skill directory: its SKILL.md and every asset beside it.
LocalSkillFileLocalSkillFile
class LocalSkillFile(*, path: str, content_base64: str, executable: bool = False)One file of a LocalSkillBundle.
Secrets
MistralSecretMistralSecret
class MistralSecret(*, ref: str | None = None, worker_env: bool = False)A secret of the Mistral Secret Manager.
Build it with MistralSecret.workspace(NAME), or leave the reference out with
MistralSecret() and bind it at deploy time with
agents deploy --secret-binding NAME=secret:workspace:..., which also overrides a reference.
worker_env=True also sets the secret as an environment variable where your Python tools
run, so they can read it; without it, the secret reaches only the destinations that name it.
| Attribute | Type | Description |
|---|---|---|
kind | Literal['mistral'] | Always "mistral": the Mistral Secret Manager. |
MistralSecret.workspaceMistralSecret.workspace
@classmethod
def workspace(name: str, *, worker_env: bool = False) -> SelfThe workspace secret name of the Secret Manager.
Redaction
redaction.Redactionredaction.Redaction
type Redaction = (
redaction.RedactionPolicy
| list[redaction.RedactionPolicy]
| tuple[redaction.RedactionPolicy, ...]
)What Agent(redaction=...) takes: one RedactionPolicy or a list of them, applied in order.
[] turns redaction off.
redaction.RedactionPolicyredaction.RedactionPolicy
type RedactionPolicy = (
OperationDataTransformer
| Callable[[str, OperationDataValue], OperationDataValue | None]
)One way the agent's traces mask secrets and personal data: a redaction policy or a
(key, value) function.
OperationDataTransformer is what a redaction policy is, such as RegexRedactionPolicy: an
object whose transform method returns the value to record, or None to drop it.
OperationDataValue is a trace field's value: a string, a number, a boolean, bytes, None,
or a list or a mapping of these.
redaction.RegexRedactionPolicyredaction.RegexRedactionPolicy
class RegexRedactionPolicy(
patterns: Sequence[Pattern[str]] = redaction.DEFAULT_PII_SECRET_PATTERNS,
*,
safe_keys: frozenset[str] = redaction.DEFAULT_SAFE_ATTRIBUTE_KEYS,
safe_key_patterns: Sequence[Pattern[str]] = redaction.DEFAULT_TOKEN_PATTERNS,
redacted_value: str = '[REDACTED]',
)Replaces the matches of patterns, such as API keys, email addresses and card numbers, with [REDACTED] in the agent's traces. The values of safe keys are scanned with safe_key_patterns only.
redaction.AttributeRedactionPolicyredaction.AttributeRedactionPolicy
class AttributeRedactionPolicy(
*,
sensitive_keys: frozenset[str] = redaction.DEFAULT_SENSITIVE_ATTRIBUTE_KEYS,
safe_keys: frozenset[str] = redaction.DEFAULT_SAFE_ATTRIBUTE_KEYS,
sensitive_fragments: frozenset[str] = redaction.DEFAULT_SENSITIVE_ATTRIBUTE_FRAGMENTS,
token_patterns: Sequence[Pattern[str]] = redaction.DEFAULT_TOKEN_PATTERNS,
redact_non_primitive: bool = True,
redacted_value: str = '[REDACTED]',
)Redacts the values of sensitive trace fields whole, such as messages and tool arguments, and replaces tokens in the values it keeps.
redaction.CallbackRedactionPolicyredaction.CallbackRedactionPolicy
class CallbackRedactionPolicy(
mask_function: redaction.AttributeMaskCallback,
*,
recursive: bool = False,
)Redacts with your function: it gets each field's key and value and returns the value to keep, or None to drop the field.
With recursive=True, the function gets each leaf of a structured value, such as the text of every message, with the field's name as key. Returning None then drops that leaf only.
redaction.AttributeMaskCallbackredaction.AttributeMaskCallback
type AttributeMaskCallback = Callable[[str, OperationDataValue], OperationDataValue | None]A redaction function: it gets a field's key and value and returns the value to keep, or None to drop the field.
Redaction defaults
| Name | What it is |
|---|---|
redaction.CARD_NUMBER_PATTERN | A pattern for card numbers: 13 to 16 digits, with optional spaces or dashes. |
redaction.DEFAULT_PII_SECRET_PATTERNS | DEFAULT_TOKEN_PATTERNS, plus EMAIL_PATTERN, CARD_NUMBER_PATTERN and IPV4_PATTERN. |
redaction.DEFAULT_REDACTED_VALUE | The text that replaces a redacted value: '[REDACTED]'. |
redaction.DEFAULT_SAFE_ATTRIBUTE_KEYS | Trace keys whose values are IDs, names and settings, such as gen_ai.request.model and gen_ai.tool.name: they are only scanned for tokens. |
redaction.DEFAULT_SENSITIVE_ATTRIBUTE_FRAGMENTS | Parts of a key that make its value redacted whole: api_key, argument, arguments, authorization, body, completion, content, cookie, input, message, messages, output, password, payload, prompt, secret, set_cookie and token. |
redaction.DEFAULT_SENSITIVE_ATTRIBUTE_KEYS | Trace keys whose values are redacted whole: messages, tool definitions, arguments and results, request and response bodies and headers, URLs, addresses, queries and exception messages. |
redaction.DEFAULT_TOKEN_PATTERNS | Patterns for secrets: bearer tokens, private keys, JSON Web Tokens, webhook URLs, and the API keys of Mistral, GitHub, GitLab, Slack, AWS, Google, Hugging Face, Stripe and other services. |
redaction.EMAIL_PATTERN | A pattern for email addresses. |
redaction.IPV4_PATTERN | A pattern for IPv4 addresses. |