一个轻量级、模块化的 Python Agent 框架,支持流式处理、工具编排及可选 Rust 加速绑定。
项目概述#
TinyAgent 是一个轻量级、模块化的 Python Agent 框架,专注于简化 LLM 应用的构建。项目受 smolagents 启发,采用最小化抽象和零样板代码的设计理念,允许开发者通过简单的 @tool 装饰器将 Python 函数转化为 AI 可调用的工具。
核心特性#
Streaming-first 架构#
- 所有 LLM 交互原生支持流式响应
- 支持订阅代理事件以获取实时 UI 更新
- 完整的事件生命周期管理(Agent/Turn/Message/ToolExecution)
工具系统#
@tool装饰器实现零样板代码,函数即工具- 自动多步推理和工具编排
- v1.2.5+ 支持并行工具调用(asyncio.gather())
- 支持结构化输出
双提供者路径#
- 纯 Python 路径: 默认实现,通过
stream_openrouter等函数 - Rust 绑定路径: 通过 PyO3 提供可选的高性能实现,用于 SSE 解析和 JSON 反序列化
Provider 兼容性#
- 兼容任何 OpenAI-compatible
/chat/completions端点 - 默认支持 OpenRouter
- 支持 OpenAI、Anthropic (via OpenRouter)、MiniMax、Chutes (本地模型)
成本优化#
- 支持 Anthropic-style Prompt 缓存(cache breakpoints)
- 减少重复上下文的 token 成本和延迟
架构设计#
tinyagent/
├── agent.py # Agent 类
├── agent_loop.py # 核心代理执行循环
├── agent_tool_execution.py # 工具执行助手
├── agent_types.py # 类型定义
├── caching.py # Prompt 缓存工具
├── openrouter_provider.py # OpenRouter 集成
├── alchemy_provider.py # 基于 Rust 的提供者
└── proxy.py # 代理服务器集成
Rust 绑定架构#
Python (async) Rust (Tokio)
───────────────── ─────────────────────────
stream_alchemy_*() ──> alchemy_llm::stream()
│
AlchemyStreamResponse ├─ SSE parse + deserialize
.__anext__() <── ├─ event_to_py_value()
(asyncio.to_thread) └─ mpsc channel -> Python
安装与使用#
安装#
# 推荐(更快)
uv pip install tiny_agent_os
# 或使用 pip
pip install tiny_agent_os
环境配置#
export OPENAI_API_KEY=your_openrouter_key_here
export OPENAI_BASE_URL=https://openrouter.ai/api/v1
快速开始#
from tinyagent import ReactAgent, tool
@tool
def add_numbers(a: int, b: int) -> int:
"""Add two numbers together."""
return a + b
agent = ReactAgent(tools=[add_numbers])
result = agent.run("What is 5 plus 3?")
print(result) # 输出: 8
多步推理示例#
from tinyagent import tool, ReactAgent
@tool
def multiply(a: float, b: float) -> float:
"""Multiply two numbers together."""
return a * b
@tool
def divide(a: float, b: float) -> float:
"""Divide the first number by the second."""
return a / b
agent = ReactAgent(tools=[multiply, divide])
result = agent.run("What is 12 times 5, then divided by 3?")
# → 20 (自动调用 multiply(12, 5) 得到 60,然后 divide(60, 3) 得到 20)
事件订阅#
def on_event(event):
print(f"Event: {event.type}")
unsubscribe = agent.subscribe(on_event)
核心类与配置#
- Agent: 基础代理类
- ReactAgent: 实现 ReAct (Reasoning + Acting) 模式的代理
- AgentOptions: 代理配置选项
- AgentTool: 自定义工具类
关键配置项#
enable_prompt_caching: 启用 Prompt 缓存model: 指定模型(如anthropic/claude-3.5-sonnet)verbose=True: 开启调试日志session_id: 会话标识
当前状态#
- 版本: v1.2.5
- 阶段: Beta(API 可能在次要版本间变化)
- 主要语言: Python (85.1%), Rust (14.9%)
- 开源协议: MIT License
注意事项#
- 项目目前处于 Beta 阶段,不建议直接用于关键生产环境
- Rust 绑定目前仅支持
openai-completions和minimax-completions - 图像块支持尚不完整(文本和思考块可用)
- 官网声称的 Business Source License 与 GitHub 仓库的 MIT License 存在不一致,以 GitHub 为准