Skip to main content

PhiAgent

Struct PhiAgent 

Source
pub struct PhiAgent {
    pub config: PhiAgentConfig,
    /* private fields */
}
Expand description

A built Agent instance.

Wraps AgentRuntime with common operations behind a simpler API.

§Example

ⓘ
let agent = PhiAgent::build(builder, config)?;
let session = agent.create_session().await;
agent.run_turn(session, "Hello!", |event| renderer.render(event)).await?;

Fields§

§config: PhiAgentConfig

The configuration this agent was built with.

Implementations§

Source§

impl PhiAgent

Source

pub fn builder( llm_client: Arc<dyn LlmProvider>, system_prompt: String, ) -> AgentBuilder

Create a pre-configured AgentBuilder.

Equivalent to base_agent_builder(llm_client).system_prompt(system_prompt), after which you register tools, middleware, and approval handlers, then call Self::build.

§Example
ⓘ
use phi_agent::PhiAgent;
use phi_agent::build_system_prompt;
use std::sync::Arc;

// Create your LLM provider (e.g., via llm_unified::create_provider)
let llm_client: Arc<dyn agent_base::llm_trait::LlmProvider> = todo!();

let builder = PhiAgent::builder(llm_client, build_system_prompt());
Source

pub fn build(builder: AgentBuilder, config: PhiAgentConfig) -> AgentResult<Self>

Build from an AgentBuilder.

§Example
ⓘ
use phi_agent::{PhiAgent, PhiAgentConfig, base_agent_builder, build_system_prompt};
use std::sync::Arc;

// Create your LLM provider (e.g., via llm_unified::create_provider)
let llm_client: Arc<dyn agent_base::llm_trait::LlmProvider> = todo!();
let builder = base_agent_builder(llm_client).system_prompt(build_system_prompt());

let config = PhiAgentConfig {
    model: "gpt-4o".into(),
    enable_thinking: true,
    ..Default::default()
};
let agent = PhiAgent::build(builder, config)?;
Source

pub async fn create_session(&self) -> SessionId

Create an agent session.

§Example
ⓘ
let session = agent.create_session().await;
println!("Session id: {}", session.id);
Source

pub async fn run_turn<F>( &self, session_id: SessionId, query: &str, on_event: F, ) -> AgentResult<RunOutcome>
where F: FnMut(RuntimeEvent) -> AgentResult<()> + Send + 'static,

Execute one turn.

§Example
ⓘ
let session = agent.create_session().await;
let renderer = create_stdout_renderer();

let outcome = agent
    .run_turn(session, "What is 2+2?", |event| renderer.render(event))
    .await?;
println!("Turn completed: {:?}", outcome);
Source

pub async fn run_turn_ephemeral_input<F>( &self, session_id: SessionId, query: &str, on_event: F, ) -> AgentResult<RunOutcome>
where F: FnMut(RuntimeEvent) -> AgentResult<()> + Send + 'static,

Like run_turn, but the query is pushed as an ephemeral user message: the LLM sees it for this turn only, then turn-end cleanup removes it from memory and persistence. Used for skill-body injection — history keeps only the original command.

Source

pub async fn system_prompt(&self) -> Option<String>

The pristine build-time system prompt (async — safe inside a runtime). Hosts that bake session state into the prompt (e.g. skill activation) capture this once and append to it, never recompose.

Source

pub async fn set_system_prompt( &self, session_id: &SessionId, prompt: impl Into<String>, ) -> AgentResult<()>

Replace the session’s system prompt (the first non-ephemeral System message). phimint uses this to re-bake the prompt when a session-scope skill is activated — the body joins an “Active Skills” section.

Source

pub fn cancel(&self)

Cancel the currently executing turn.

§Example
ⓘ
let agent_clone = agent.clone();
let session = agent.create_session().await;

// Run the turn in a separate task
let handle = tokio::spawn(async move {
    agent_clone.run_turn(session, "count to 100", |_| Ok(())).await
});

// Cancel after a short delay
tokio::time::sleep(std::time::Duration::from_millis(100)).await;
agent.cancel();
Source

pub fn is_cancelled(&self) -> bool

Check whether the agent has been cancelled.

§Example
ⓘ
assert!(!agent.is_cancelled());
agent.cancel();
assert!(agent.is_cancelled());
Source

pub async fn set_reasoning_effort(&self, effort: ReasoningEffort)

Set the reasoning effort.

§Example
ⓘ
use phi_agent::ReasoningEffort;
// Switch to high reasoning effort mid-conversation
agent.set_reasoning_effort(ReasoningEffort::High).await;
Source

pub fn runtime(&self) -> &AgentRuntime

Access the underlying runtime (for advanced use like hook registration).

§Example
ⓘ
let runtime = agent.runtime();
let event_rx = runtime.subscribe_runtime_events();
println!("Subscribed to events, receiver lag: {}", event_rx.len());
Source

pub async fn list_tools(&self) -> Vec<ToolMetadata>

List all registered tools with their metadata, sorted by name.

§Example
ⓘ
let tools = agent.list_tools().await;
for tool in &tools {
    println!("{} - {} ({})", tool.name, tool.description, tool.origin);
}
println!("{} tools registered", tools.len());
Source

pub async fn resume_session( &self, messages: Vec<ChatMessage>, ) -> AgentResult<SessionId>

Create a new session and inject historical messages for resume.

Creates a fresh session (which receives a fresh System prompt), then replaces the chat messages with [fresh_system] + messages. The caller must ensure messages contains no System messages — use crate::session::load_session_messages which filters them out automatically.

§Errors

Returns an error if messages is empty / System-only, or if the combined sequence fails validate_message_sequence (e.g. dangling tool calls). Again, crate::session::load_session_messages sanitizes all of this.

Source

pub async fn switch_to_session( &self, picked_session_dir: &Path, base_dir: &Path, ) -> AgentResult<(SessionId, Vec<ChatMessage>, SessionContext)>

One-step session switch: resolve → load messages → resume.

Given a session directory (from the picker), resolves the session context, loads historical messages, and creates a new agent session with those messages. Returns the new session ID, the loaded messages (for transcript replay), and the resolved context.

Source§

impl PhiAgent

Source

pub async fn attach_mcp(&self, config: McpServerConfig) -> AgentResult<()>

Dynamically attach an MCP server at runtime.

Adds the server config, connects, discovers tools, and registers them into the agent’s ToolRegistry. Tools are registered with the mcp.<server_name>.<tool_name> naming convention.

Returns an error if the server cannot be connected or tools cannot be discovered. On failure, the server config is rolled back (removed from the hub) so a partial entry is never left behind.

§Example
ⓘ
// Attach a filesystem MCP server at runtime
agent
    .attach_mcp(McpServerConfig {
        name: "filesystem".into(),
        transport: phi_agent::McpTransport::Stdio {
            command: "npx".into(),
            args: vec!["-y".into(), "@modelcontextprotocol/server-filesystem".into(), "/tmp".into()],
            env: Default::default(),
        },
    })
    .await?;
§Performance note

Currently calls hub.register_all() which re-registers all servers’ tools (O(total-servers)). For the common case this is fine because re-registration is a no-op HashMap insert. A future optimization would register only the newly attached server’s tools.

Source

pub async fn detach_mcp(&self, name: &str)

Dynamically detach an MCP server at runtime.

Unregisters all tools belonging to this server from the agent’s ToolRegistry, disconnects the server, and removes its config from the hub.

This is a no-op if the server is not attached.

§Example
ⓘ
// Detach the server — tools are unregistered, connection is closed
agent.detach_mcp("filesystem").await;
§Concurrency note

There is a TOCTOU window between collecting tool names (read lock) and removing them (write lock). If another thread re-attaches a server with the same name during this window, its tools may be prematurely removed. In practice this race is harmless: the new attach will re-register tools on the next turn, and tool calls in flight will fail with a clear error since hub.remove_server disconnects clients.

Source

pub fn into_mcp_server(&self, config: McpServeConfig) -> McpServer

Convert this agent into an MCP server that external orchestrators can call.

§Example
ⓘ
// Expose the agent as an MCP server via stdio
let mcp_server = agent.into_mcp_server(McpServeConfig {
    transport: McpServerTransport::Stdio,
    name: "phi-agent".into(),
    version: "1.0.0".into(),
});
// External orchestrators (LangGraph, CrewAI, etc.) can now call
// the agent's tools through the MCP protocol

Trait Implementations§

Source§

impl Clone for PhiAgent

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

Auto Trait Implementations§

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<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> Pointable for T

Source§

const ALIGN: usize

The alignment of pointer.
Source§

type Init = T

The type for initializers.
Source§

unsafe fn init(init: <T as Pointable>::Init) -> usize

Initializes a with the given initializer. Read more
Source§

unsafe fn deref<'a>(ptr: usize) -> &'a T

Dereferences the given pointer. Read more
Source§

unsafe fn deref_mut<'a>(ptr: usize) -> &'a mut T

Mutably dereferences the given pointer. Read more
Source§

unsafe fn drop(ptr: usize)

Drops the object pointed to by the given pointer. Read more
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> 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