Skip to main content

Crate phi_agent

Crate phi_agent 

Source
Expand description

phi-agent: Rust AI Agent runtime framework — orchestration, sessions, streaming all built-in. You only define tools, prompts, and domain knowledge.

Built on agent-base and agent-works, providing builder factory, renderer, config resolution, session management, and other infrastructure. Ships with zero application tools. Kernel tools (file I/O, shell, multi-agent) are available via phi-kernel-tools behind feature flags — all off by default. Application tools are injected by consumers.

Re-exports§

pub use agent::PhiAgent;
pub use agent::PhiAgentConfig;
pub use agent::base_agent_builder;
pub use agent::base_agent_builder_with_excludes;
pub use agent::base_agent_builder_with_options;
pub use agent::clear_compression_cache;
pub use agent::run_compact_session;
pub use cli::ApprovalMode;
pub use cli::AutoApprovalHandler;
pub use config::LlmConfig;
pub use config::resolve_llm_config;
pub use event_log::event_to_jsonl;
pub use event_log::event_to_value;
pub use event_log::save_turn_log;
pub use prompt::build_system_prompt;
pub use prompt::build_system_prompt_cn;
pub use prompt::build_system_prompt_with_fragments;
pub use render::EventRenderer;
pub use render::JsonStreamRenderer;
pub use render::NullRenderer;
pub use render::OutputFormat;
pub use render::create_renderer;
pub use render::create_stdout_renderer;
pub use session::SessionContext;
pub use session::SnapshotInfo;
pub use session::cleanup_expired_sessions;
pub use session::create_snapshot;
pub use session::delete_snapshot;
pub use session::list_snapshots;
pub use session::resolve_session;
pub use session::restore_snapshot;
pub use session::validate_session_id;
pub use session::validate_snapshot_name;

Modules§

agent
Agent construction and lifecycle management.
bridge
Bridge protocol — adapts phi-agent for SDK consumption.
cli
CLI helpers — approval strategies and utilities shared across consumers.
config
Configuration resolution helpers.
event_log
Event log: serialize turn events to JSONL files.
prompt
System prompt generation (EN/CN). System prompt construction using composable fragments.
render
Event renderers — transform RuntimeEvent streams into display output.
session
Session management — ID resolution, locking, snapshots, cleanup.

Structs§

AgentBuilder
AgentRuntime
ApprovalRequest
CompressionMiddleware
Middleware that compresses conversation history before each LLM call.
ConsecutiveFailureRecovery
Recovery strategy that tracks consecutive failures per tool and stops after a limit.
DynamicToolsFragment
Dynamically generate tool descriptions from registered tools.
EnvironmentFragment
Injects runtime environment information: OS, working directory, git branch.
Focus
A focused LLM call.
FocusContext
Structured context for multi-field input scenarios.
FocusOutput
Output wrapper for a Focus call.
FragmentContext
Context passed to each fragment during rendering.
McpServeConfig
Configuration for running as an MCP server.
McpServer
An MCP Server that wraps an AgentRuntime and exposes it as an MCP tool.
McpServerConfig
PlanItem
A single step in a lightweight plan checklist.
PostLlmCtx
PreLlmCtx
ReasoningConfig
Reasoning/thinking configuration, unifying reasoning/thinking parameters across vendors.
SafetyConfig
Safety configuration for agent runtime guardrails.
SessionId
Unique identifier for an agent session.
SessionMetrics
Accumulated session metrics. Written incrementally to session_metrics.json at the end of each turn.
SessionSummary
Lightweight summary returned by list_all().
ToolContext
ToolMetadata
Machine-readable metadata for a registered tool — origin, version, and runtime requirements in a stable shape consumers can inspect without parsing the LLM-facing definition JSON.
TurnFactMiddleware
Turn fact summary middleware — injects structured facts from the previous turn’s tool results into the next user message.
TurnMetrics
Per-turn metrics — one per LLM interaction.
TurnToolLimitMiddleware
Middleware that enforces a hard limit on tool calls per turn.
UpdatePlanTool
A lightweight tool that records and displays a plan checklist to the user.
UserMessageCtx

Enums§

AgentError
ApprovalDecision
Content
Structured content returned by a tool, aligned with the MCP content array shape (no envelope, no orchestration/failure/truncation semantics).
FinishReason
Semantic finish reason, replacing scattered Option<String> matching.
FocusError
Error type for Focus calls.
McpServerTransport
Transport mode for the MCP server.
McpTransport
PlanStepStatus
Lightweight plan step status — display-only, no execution semantics.
ReasoningEffort
Reasoning intensity/depth enumeration.
RiskLevel
RunOutcome
The outcome of an Agent turn or run.
RuntimeEvent
Unified runtime event — the single event type for both internal and external consumers (frontends, CLIs, tests).
SessionOutcome
Outcome of a session (the entire conversation).
TurnOutcome
Outcome of a single turn (one LLM interaction).

Traits§

ApprovalHandler
Trait for handling tool approval requests.
FocusInput
Input for a Focus call — either a simple string or a structured context.
Middleware
PromptFragment
Composable prompt fragment — each fragment owns one concern.
Tool
ToolPolicy
Policy-based control over tool execution.

Functions§

compose_fragments
Sort fragments by priority (ascending) and concatenate with double newlines.
format_number
Format a number with K/M suffixes for display.
list_all_metrics
List all session summaries by scanning the sessions directory. Reads each session_metrics.json and extracts summary fields.
load_metrics
Load session metrics from session_metrics.json in a session directory.
save_metrics
Incrementally write session metrics to session_metrics.json. Overwrites the file on each call — safe for per-turn writes.
try_load_metrics
Try to load session metrics, returning None if the file doesn’t exist.

Type Aliases§

AgentResult