Skip to main content

Agent

Struct Agent 

Source
pub struct Agent { /* private fields */ }
Expand description

Builds one agent from a name to an answer: model, instructions, tools, evals, limits, storage and laws. Setters never fail; build checks everything, reports the first problem and makes no model call. run and run_with build and run in one call.

Implementations§

Source§

impl Agent

Source

pub fn from_toml(text: impl Into<String>) -> Agent

Starts a builder from persona TOML text, parsed at build. Builder settings shared with the persona (model, instructions, display name, role, goal, evals, turn and token caps) beat the TOML. Tools the TOML names must be added with .tool(..).

Source

pub fn from_toml_file(path: impl AsRef<Path>) -> Agent

Starts a builder from the persona file at path, read at build. The path must have no .., end in .toml and name a regular UTF-8 file of at most MAX_PERSONA_BYTES. An instructions_file is read from the persona’s own directory, no symlinks, no escape. Otherwise as from_toml, where instructions_file is refused.

Source§

impl Agent

Source

pub async fn start( self, input: impl Into<Input>, ) -> Result<(BuiltAgent, RunId), KitError>

Builds the agent and starts a run on input with no model call. Returns the built agent and the run id to store for resume or resume_for. Fails like build, then like BuiltAgent::start.

Source§

impl Agent

Source

pub async fn stream( self, input: impl Into<Input>, ) -> Result<RunStream, KitError>

Builds the agent and starts a streamed run on input. Output: the stream once the run id is known, or the first build or setup error. Keep a BuiltAgent and call its stream instead to run many times.

Source§

impl Agent

Source

pub fn new(name: impl Into<String>) -> Self

Starts a builder for the agent called name. The name must be 1 to 64 of [a-z0-9-]; build checks it. Every other setting starts at its documented default.

Source

pub fn model(self, selector: impl Into<String>) -> Self

Sets the model: vendor/model from the catalog, or an alias that needs .model_client(..). Required. Returns the builder.

Source

pub fn instructions(self, text: impl Into<String>) -> Self

Sets the system instructions. Required; the macro uses the doc comment. The text is kept exactly, never parsed as TOML. Returns the builder.

Source

pub fn display_name(self, text: impl Into<String>) -> Self

Sets the display name shown in the system prompt. Defaults to the agent name. Returns the builder.

Source

pub fn role(self, text: impl Into<String>) -> Self

Sets the role line of the system prompt. Defaults to "An assistant.". Returns the builder.

Source

pub fn goal(self, text: impl Into<String>) -> Self

Sets the goal line of the system prompt. Defaults to "Answer the user's request.". Returns the builder.

Source

pub fn tool(self, tool: impl AsTool) -> Self

Adds a tool: a #[tool] fn or a tool(..) value. A second tool under a taken name fails at build. Returns the builder.

Source

pub fn tool_arc(self, tool: Arc<dyn Tool>) -> Self

Adds a tool already behind an Arc<dyn Tool>. Same checks as tool at build. Returns the builder.

Source

pub fn tools(self, tools: impl IntoIterator<Item = Arc<dyn Tool>>) -> Self

Adds every tool of tools, in order. Same checks as tool at build. Returns the builder.

Source

pub fn toolkit(self, toolkit: Toolkit) -> Self

Adds every tool of toolkit, in order. Same checks as tool at build. Returns the builder.

Source

pub fn eval(self, call: impl Into<String>) -> Self

Adds one persona eval call, such as min_items(items, 2). Parsed and checked against registered evals at build. Returns the builder.

Source

pub fn evals<S: Into<String>>(self, calls: impl IntoIterator<Item = S>) -> Self

Adds every eval call of calls, in order. Same checks as eval at build. Returns the builder.

Source

pub fn eval_fn(self, name: impl Into<String>, f: EvalFn) -> Self

Registers custom eval name running f, next to the built-ins. An invalid, reserved or taken name fails at build. Returns the builder.

Source

pub fn memory(self, memory: AgentMemory) -> Self

Gives the agent long-term memory for one user and session: the five memory tools, bound to them, and a preamble of facts and summary. Needs AgentMemory::sqlite(..) or .knowledge(..) in 0.2.

Source

pub fn knowledge(self, knowledge: impl Into<Knowledge>) -> Self

Lets the agent search a folder: ingested at build (unchanged files skipped) and served by the search_knowledge tool, fenced as untrusted text. Takes Knowledge::dir(..) or a path.

Source

pub fn limits(self, limits: Limits) -> Self

Sets the spend limits checked before every model call. Defaults to Limits::default(), no limit. Returns the builder.

Source

pub fn max_turns(self, turns: u32) -> Self

Caps model turns per run; 2 to 50, checked at build. Defaults to DEFAULT_MAX_TURNS. Returns the builder.

Source

pub fn max_tokens(self, tokens: u32) -> Self

Caps output tokens per model call; 1 to 200000, checked at build. Defaults to DEFAULT_MAX_TOKENS. Returns the builder.

Source

pub fn checkpoints(self, storage: Storage) -> Self

Sets where run checkpoints live. Defaults to Storage::memory(), fresh per run. Returns the builder.

Source

pub fn catalog(self, catalog: Catalog) -> Self

Replaces the built-in provider catalog. Model selectors and prices resolve against it at build. Returns the builder.

Source

pub fn api_key(self, key: Secret) -> Self

Sets the API key, beating any environment variable. The key never appears in Debug or an error. Returns the builder.

Source

pub fn api_key_env(self, name: impl Into<String>) -> Self

Reads the API key from environment variable name at build. Defaults to <VENDOR>_API_KEY. Returns the builder.

Source

pub fn transport(self, transport: Arc<dyn Transport>) -> Self

Sets the HTTP transport for catalog models. Defaults to a new reqwest transport (feature reqwest). Returns the builder.

Source

pub fn model_client(self, model: Arc<dyn Model>) -> Self

Serves model for the selector instead of connecting one. For tests, aliases and custom hosts; needs no key or network. Returns the builder.

Source

pub fn price(self, price: Price) -> Self

Sets the price replies are charged at. Defaults to the catalog price, else free with a model client. Returns the builder.

Source

pub fn events(self, sink: Arc<dyn EventSink>) -> Self

Sends every run event to sink. Defaults to a sink that drops events, so memory stays bounded. Returns the builder.

Source

pub fn ledger(self, ledger: Arc<dyn UsageLedger>) -> Self

Records usage in ledger for period limits and a route’s daily cloud spend. Default: limits count in memory per built agent; route spend goes to the Storage::sqlite file, else in memory per built agent.

Source

pub fn retries(self, retries: u32) -> Self

Sets how often a transient provider failure is retried per run. At most 32, checked at build; defaults to 3. Returns the builder.

Source

pub fn laws(self, path: impl AsRef<Path>) -> Self

Adds a .bend law file, checked at build. 0.2 stores laws; no run proves them yet. Returns the builder.

Source

pub fn law(self, law: impl Into<String>) -> Self

Adds one inline law, checked at build. 0.2 stores laws; no run proves them yet. Returns the builder.

Source

pub fn auto_laws(self, on: bool) -> Self

Asks for laws derived from the code as well. Defaults to true. 0.2 records the choice only. Returns the builder.

Source

pub async fn build(self) -> Result<BuiltAgent, KitError>

Checks every setting and returns a ready, shareable agent. Fails with the first problem: settings, tools, persona, laws, evals, model, key or storage. Makes no model call.

Source

pub async fn run(self, input: impl Into<Input>) -> Result<String, KitError>

Builds the agent and runs it once on input. Returns the final answer as text. Fails like build, then like BuiltAgent::run.

Source

pub async fn run_with( self, input: impl Into<Input>, ) -> Result<RunOutcome, KitError>

Builds the agent and runs it once on input. Returns the full outcome: text, output, usage, calls, messages. Fails like build, then like BuiltAgent::run_with.

Source§

impl Agent

Source

pub fn route(self, policy: RoutePolicy) -> Self

Routes each model call by policy: target cloud is the .model(..) selector, target local the .local(..) model; any other target id fails build. Replaces route_file.

Source

pub fn route_file(self, path: impl AsRef<Path>) -> Self

Routes by the policy in TOML file path, read and checked at build (at most 64 KiB). Same targets as route. Replaces route.

Source

pub fn private(self, on: bool) -> Self

Keeps the agent’s model requests on the device, even on fallback. Default false. build refuses a private agent with no on-device model, a cloud knowledge embedder, a judge eval naming a cloud model, or a tool whose uses_network is true (web_fetch, web_search, HTTP and hosted tools). A custom tool is trusted unless it overrides it.

Source

pub fn tier(self, name: impl Into<String>) -> Self

Sends requests only to route targets that list task tier name. Needs .route(..); a tier no target serves fails build. Default: no tier.

Source

pub fn network(self, state: NetworkState) -> Self

Reads the network state for routing from state, which the app keeps a clone of and sets. Without it a passive probe infers the state from network errors.

Source

pub fn device(self, state: DeviceState) -> Self

Reads battery and thermal state for routing from state, which the app keeps a clone of and sets. Without it both are unknown and the policy’s device rules are skipped.

Source§

impl Agent

Source

pub fn tracing(self, on: bool) -> Self

Turns tracing on with every category, or off. Default off. Covers build and every run; spans go to trace_to, trace_file or ./traces/<name>-<trace id>.jsonl ($TROUPEKIT_TRACE_DIR).

Source

pub fn trace(self, categories: impl IntoIterator<Item = Trace>) -> Self

Turns tracing on for the listed categories only. An empty list turns tracing off. Returns the builder.

Source

pub fn trace_content(self, on: bool) -> Self

Keeps prompt, reply, tool argument, query and document text in spans. Default off: spans then hold only byte counts. Secrets are scrubbed either way.

Source

pub fn trace_to(self, sink: Arc<dyn TraceSink>) -> Self

Sends trace records to sink instead of a file. Takes effect only with tracing on; replaces trace_file. Returns the builder.

Source

pub fn trace_file(self, path: impl AsRef<Path>) -> Self

Writes trace records to the new file path; an existing file is refused at build. Takes effect only with tracing on; replaces trace_to.

Source§

impl Agent

Source

pub fn local(self, choice: impl Into<LocalChoice>) -> Self

Sets the on-device model: a local catalog id, a GGUF file path or a loaded Arc<dyn LocalModel>. Without .model(..) the agent is local only. Default: none. Needs feature llama to load a file.

Source

pub fn download(self, on: bool) -> Self

Lets build download a catalog model that is not in the model cache yet. Default false: a missing model fails build instead. Has no effect on a file or a loaded model.

Source

pub fn local_settings(self, settings: LocalChatSettings) -> Self

Sets how the on-device chat model samples and calls tools: tool mode, the temperature used when a request has none, the seed, the end-of-text ban and the confidence floor. Default: LocalChatSettings::default(). Applies to the .local(..) model.

Trait Implementations§

Source§

impl Clone for Agent

Source§

fn clone(&self) -> Self

Returns a duplicate of the value. Read more
1.0.0 (const: unstable) · Source§

fn clone_from(&mut self, source: &Self)

Performs copy-assignment from source. Read more
Source§

impl Debug for Agent

Source§

fn fmt(&self, f: &mut Formatter<'_>) -> Result

Formats the value using the given formatter. Read more

Auto Trait Implementations§

§

impl !RefUnwindSafe for Agent

§

impl !UnwindSafe for Agent

§

impl Forget for Agent

§

impl Freeze for Agent
where *const u8 is !null: Freeze, PhantomData<u8>: Freeze, PhantomData<Arc<dyn Tool>>: Freeze, PhantomData<String>: Freeze, PhantomData<(String, Arc<dyn Fn(&Value, &[Value]) -> Result<(), String> + Sync + Send>)>: Freeze, *const ArcInner<dyn CheckpointStore> is !null: Freeze, PhantomData<ArcInner<dyn CheckpointStore>>: Freeze, *const ArcInner<dyn Embedder> is !null: Freeze, PhantomData<ArcInner<dyn Embedder>>: Freeze, *const ArcInner<dyn LocalModel> is !null: Freeze, PhantomData<ArcInner<dyn LocalModel>>: Freeze, PhantomData<VendorSpec>: Freeze, PhantomData<EmbeddingSpec>: Freeze, *const ArcInner<dyn Transport> is !null: Freeze, PhantomData<ArcInner<dyn Transport>>: Freeze, *const ArcInner<dyn Model> is !null: Freeze, PhantomData<ArcInner<dyn Model>>: Freeze, *const ArcInner<dyn EventSink> is !null: Freeze, PhantomData<ArcInner<dyn EventSink>>: Freeze, *const ArcInner<dyn UsageLedger> is !null: Freeze, PhantomData<ArcInner<dyn UsageLedger>>: Freeze, PhantomData<PathBuf>: Freeze, *const ArcInner<dyn TraceSink> is !null: Freeze, PhantomData<ArcInner<dyn TraceSink>>: Freeze, PhantomData<RouteTarget>: Freeze, *const ArcInner<NetworkState> is !null: Freeze, PhantomData<ArcInner<NetworkState>>: Freeze, *const ArcInner<DeviceState> is !null: Freeze, PhantomData<ArcInner<DeviceState>>: Freeze,

§

impl Move for Agent

§

impl Send for Agent
where RawVecInner: Send, Arc<dyn Tool>: Send, Arc<dyn Fn(&Value, &[Value]) -> Result<(), String> + Sync + Send>: Send, Arc<dyn CheckpointStore>: Send, Arc<dyn Embedder>: Send, Arc<dyn LocalModel>: Send, Arc<dyn Transport>: Send, Arc<dyn Model>: Send, Arc<dyn EventSink>: Send, Arc<dyn UsageLedger>: Send, Arc<dyn TraceSink>: Send, Arc<NetworkState>: Send, Arc<DeviceState>: Send,

§

impl Sync for Agent
where RawVecInner: Sync, Arc<dyn Tool>: Sync, Arc<dyn Fn(&Value, &[Value]) -> Result<(), String> + Sync + Send>: Sync, Arc<dyn CheckpointStore>: Sync, Arc<dyn Embedder>: Sync, Arc<dyn LocalModel>: Sync, Arc<dyn Transport>: Sync, Arc<dyn Model>: Sync, Arc<dyn EventSink>: Sync, Arc<dyn UsageLedger>: Sync, Arc<dyn TraceSink>: Sync, Arc<NetworkState>: Sync, Arc<DeviceState>: Sync,

§

impl Unpin for Agent

§

impl UnsafeUnpin for Agent

Blanket Implementations§

Source§

impl<T> Any for T
where T: 'static + ?Sized,

Source§

fn type_id(&self) -> TypeId

Gets the TypeId of self. Read more
Source§

impl<T> Borrow<T> for T
where T: ?Sized,

Source§

fn borrow(&self) -> &T

Immutably borrows from an owned value. Read more
Source§

impl<T> BorrowMut<T> for T
where T: ?Sized,

Source§

fn borrow_mut(&mut self) -> &mut T

Mutably borrows from an owned value. Read more
Source§

impl<ST, DT> CastableFrom<ST, Initialized, Initialized> for DT
where ST: ?Sized, DT: ?Sized,

Source§

impl<ST, DT> CastableFrom<ST, Uninit, Uninit> for DT
where ST: ?Sized, DT: ?Sized,

Source§

impl<T> CloneToUninit for T
where T: Clone,

Source§

unsafe fn clone_to_uninit(&self, dest: *mut u8)

🔬This is a nightly-only experimental API. (clone_to_uninit)
Performs copy-assignment from self to dest. Read more
Source§

impl<T> DynClone for T
where T: Clone,

Source§

fn __clone_box(&self, _: Private) -> *mut ()

Source§

impl<T> From<T> for T

Source§

fn from(t: T) -> T

Returns the argument unchanged.

Source§

impl<T> Instrument for T

Source§

fn instrument(self, span: Span) -> Instrumented<Self> ⓘ

Instruments this type with the provided Span, returning an Instrumented wrapper. Read more
Source§

fn in_current_span(self) -> Instrumented<Self> ⓘ

Instruments this type with the current Span, returning an Instrumented wrapper. Read more
Source§

impl<T, U> Into<U> for T
where U: From<T>,

Source§

fn into(self) -> U

Calls U::from(self).

That is, this conversion is whatever the implementation of From<T> for U chooses to do.

Source§

impl<T> PolicyExt for T
where T: ?Sized,

Source§

fn and<P, B, E>(self, other: P) -> And<T, P>
where T: Sized + Policy<B, E>, P: Policy<B, E>,

Create a new Policy that returns Action::Follow only if self and other return Action::Follow. Read more
Source§

fn or<P, B, E>(self, other: P) -> Or<T, P>
where T: Sized + Policy<B, E>, P: Policy<B, E>,

Create a new Policy that returns Action::Follow if either self or other returns Action::Follow. Read more
Source§

impl<T> Read<Exclusive, BecauseExclusive> for T
where T: ?Sized,

Source§

impl<T> ToOwned for T
where T: Clone,

Source§

type Owned = T

The resulting type after obtaining ownership.
Source§

fn to_owned(&self) -> T

Creates owned data from borrowed data, usually by cloning. Read more
Source§

fn clone_into(&self, target: &mut T)

Uses borrowed data to replace owned data, usually by cloning. Read more
Source§

impl<T, U> TryFrom<U> for T
where U: Into<T>,

Source§

type Error = !

The type returned in the event of a conversion error.
Source§

fn try_from(value: U) -> Result<T, !>

Performs the conversion.
Source§

impl<T, U> TryInto<U> for T
where U: TryFrom<T>,

Source§

type Error = <U as TryFrom<T>>::Error

The type returned in the event of a conversion error.
Source§

fn try_into(self) -> Result<U, <U as TryFrom<T>>::Error>

Performs the conversion.
Source§

impl<T> WithSubscriber for T

Source§

fn with_subscriber<S>(self, subscriber: S) -> WithDispatch<Self> ⓘ
where S: Into<Dispatch>,

Attaches the provided Subscriber to this type, returning a WithDispatch wrapper. Read more
Source§

fn with_current_subscriber(self) -> WithDispatch<Self> ⓘ

Attaches the current default Subscriber to this type, returning a WithDispatch wrapper. Read more