phi-agent 0.1.11

phi-agent — General-purpose AI Agent framework (builder factory, renderer, config, session management)
Documentation
# 快速开始

5 分钟跑起你的第一个 phi-agent。

## 前置条件

- [Rust]https://rustup.rs(stable,edition 2024)
- 一个 LLM API Key(兼容 OpenAI 接口)

## 安装

```bash
cargo install phi-agent
```

## 方式一:REPL 交互(推荐)

```bash
phi init my-agent
cd my-agent
cp .env.example .env
# 编辑 .env,填入你的 LLM_API_KEY=sk-xxx
cargo run
```

## 方式二:库集成

```bash
phi init --lib my-agent
cd my-agent
cp .env.example .env
# 编辑 .env,填入你的 LLM_API_KEY=sk-xxx
cargo run
```

```
phi> 现在几点了?
🔧 get_time
当前时间:2025-07-30 19:30:00

phi> /exit
```

打开 `src/main.rs`,你会看到三部分:

**1. 定义工具** — 实现 `Tool` trait,告诉 Agent 这个工具叫什么、能干什么:

```rust
struct ClockTool;

#[async_trait]
impl Tool for ClockTool {
    fn name(&self) -> &'static str { "get_time" }

    fn definition(&self) -> Value {
        json!({
            "type": "function",
            "function": {
                "name": "get_time",
                "description": "获取当前日期和时间",
                "parameters": { "type": "object", "properties": {} }
            }
        })
    }

    async fn call(&self, _args: &Value, _ctx: &ToolContext) -> AgentResult<ToolOutput> {
        let now = chrono::Local::now().format("%Y-%m-%d %H:%M:%S").to_string();
        Ok(ToolOutput {
            summary: format!("当前时间:{}", now),
            control_flow: ToolControlFlow::Continue,
            raw: None, truncation: None,
        })
    }
}
```

**2. 注册工具** — 把工具挂到 Agent 上:

```rust
let agent = PhiAgent::build(
    base_agent_builder(llm)
        .system_prompt(build_system_prompt())
        .register_tool(ClockTool),      // ← 这里注册
    PhiAgentConfig { ... },
)?;
```

**3. REPL** — 交互对话,Agent 自动决定何时调用工具。

照着 `ClockTool` 写你自己的工具就行。[自定义工具](custom-tool.md) 里有更多示例。

## 方式二:库集成

把 phi-agent 作为库加入已有项目:

```bash
cargo new my-agent && cd my-agent
cargo add phi-agent tokio --features full anyhow dotenvy async-trait serde_json chrono rustyline
echo 'LLM_API_KEY=sk-your-key-here' > .env
```

然后复制以下代码到 `src/main.rs`:

```rust
use phi_agent::{
    base_agent_builder, build_system_prompt,
    PhiAgent, PhiAgentConfig, OpenAiClient,
    SafetyConfig, ReasoningEffort,
    OutputFormat, create_stdout_renderer,
    AgentResult, Tool, ToolContext, ToolControlFlow, ToolOutput,
};
use async_trait::async_trait;
use rustyline::DefaultEditor;
use serde_json::{Value, json};
use std::sync::Arc;

// ── ClockTool ──

struct ClockTool;

#[async_trait]
impl Tool for ClockTool {
    fn name(&self) -> &'static str { "get_time" }

    fn definition(&self) -> Value {
        json!({
            "type": "function",
            "function": {
                "name": "get_time",
                "description": "获取当前日期和时间",
                "parameters": { "type": "object", "properties": {} }
            }
        })
    }

    async fn call(&self, _args: &Value, _ctx: &ToolContext) -> AgentResult<ToolOutput> {
        let now = chrono::Local::now().format("%Y-%m-%d %H:%M:%S").to_string();
        Ok(ToolOutput {
            summary: format!("当前时间:{}", now),
            control_flow: ToolControlFlow::Continue,
            raw: None, truncation: None,
        })
    }
}

// ── REPL ──

#[tokio::main]
async fn main() -> anyhow::Result<()> {
    dotenvy::dotenv().ok();

    let model = std::env::var("LLM_MODEL").unwrap_or_else(|_| "gpt-4o".into());
    let llm = Arc::new(OpenAiClient::new(
        std::env::var("LLM_API_KEY")?,
        model.clone(),
        std::env::var("LLM_BASE_URL").ok(),
    ));

    let agent = PhiAgent::build(
        base_agent_builder(llm)
            .system_prompt(build_system_prompt())
            .register_tool(ClockTool),
        PhiAgentConfig {
            model,
            enable_thinking: true,
            thinking_budget: None,
            thinking_effort: ReasoningEffort::Medium,
            safety: SafetyConfig::default(),
        },
    )?;

    let mut rl = DefaultEditor::new()?;
    let mut renderer = create_stdout_renderer(&OutputFormat::Terminal {
        show_thinking: true, show_tool_args: true, color: true,
    });

    println!("phi-agent REPL — type /exit to quit\n");
    loop {
        let line = rl.readline("phi> ")?;
        let input = line.trim().to_string();
        if input.is_empty() { continue; }
        if input == "/exit" { break; }
        rl.add_history_entry(&input)?;

        let session = agent.create_session().await;
        agent.run_turn(session, &input, |event| renderer.render(event)).await?;
        println!();
    }
}
```

三步:定义 Tool → 注册到 Agent → REPL 交互。

```bash
cargo run
```

```
phi> 现在几点了?
🔧 get_time
当前时间:2025-07-30 19:30:00

phi> /exit
```