一个纯同步、钩子驱动的 Python Agent 框架,构建在 LangGraph 之上。
当前为 v0.2 重写版(
master分支)。核心引擎与 LLM 层已就绪,中间件 / 多智能体 / CLI 仍在实现中。
- 钩子即架构:
BaseAgent极薄,只提供 15 个同步钩子与 LangGraph 状态机,不内置任何功能 - 中间件叠加:中间件是类,通过动态类继承(MRO)叠加到基类,顺序即执行顺序
- 状态机驱动:LangGraph
StateGraph即状态机,错误是一等状态,可随时改道 - 纯同步:全框架无 async,LLM 走裸 HTTP(httpx),流式用 SSE
- 类型固定:状态用
Phase枚举,LLM 交换用结构体,不散用 dict - 状态最瘦:
AgentState只有messages,其他一切走钩子
uv sync --extra dev需要 Python 3.12。
from agentframe import Agent, LLMClient
client = LLMClient(
model="deepseek-chat",
base_url="https://api.deepseek.com",
api_key="sk-...",
)
agent = Agent(
llm_client=client,
system_prompt="你是一个乐于助人的助手",
)
print(agent.invoke("你好"))
# 会话持久化内置(checkpointer 默认内存 InMemorySaver):
# 同 session_id 自动沿用之前上下文,无需手动传 config
agent2 = Agent(llm_client=client, session_id="s1")
agent2.invoke("hi")
agent2.invoke("继续") # 带上轮上下文组合中间件(工厂函数返回中间件类,需实例化):
import logging
from agentframe import Agent, LLMClient
from agentframe.middlewares import log, tools
client = LLMClient(model="deepseek-chat", base_url="...", api_key="...")
def get_weather(city: str) -> str:
"""查询城市天气。"""
return f"{city} 晴天"
agent = Agent(
llm_client=client,
middlewares=[
log(logging.getLogger("agent"))(), # 关键事件日志(trace/turn/llm/tool/error)
tools([get_weather])(), # 把工具反射成 schema 暴露给 LLM
],
)继承式自定义行为:
from agentframe import Agent, LLMClient
class MyAgent(Agent):
def on_content_end(self, content: str) -> None:
super().on_content_end(content)
print(content, end="", flush=True)
client = LLMClient(model="deepseek-chat", base_url="...", api_key="...")
agent = MyAgent(llm_client=client)Agent(公共类,可继承 + 可组合)
└─ middlewares=[...] 动态类继承(MRO = 执行顺序)
└─ BaseAgent(引擎 + 钩子协议)
└─ LangGraph StateGraph 状态机:LLM ⇄ TOOLS 循环
└─ LLMClient(裸 httpx,结构体进出)
AgentState = {messages}:跨节点唯一领域数据Phase枚举:LLM/TOOLS/END- 错误处理:
NodeError→handle_error(error, node) -> Command(goto=...),可修复状态 + 改道 - 流式中断:钩子抛
StreamStop,由打断者中间件的handle_error认领
| 类别 | 钩子 | 说明 |
|---|---|---|
| trace | before_trace / after_trace |
整个回合前后。before_trace(messages, session_id) 收到恢复的历史 + 本轮 human,可整体重写会话(压缩/注入记忆),结果由框架写回 checkpointer |
| turn | before_turn / after_turn |
一次 LLM 调用(含其工具输出)前后;after_turn 可改写本 turn 消息并写回 |
| LLM | before_llm / on_llm_reasoning / on_reasoning_end / on_llm_content / on_content_end / after_llm |
请求可改、流式事件、响应转消息历史 |
| 工具 | before_tool_call / after_tool_result |
审批子集、结果转消息历史(含 tool_call_id) |
| 流程 | handle_next / handle_error |
状态机决策与错误改道 |
.venv/bin/python -m pytest tests/ -q- ✅ 核心:
BaseAgent/ 钩子协议 /Phase枚举 /AgentState - ✅ LLM 层:
LLMClient(裸 httpx)/LLMRequest/LLMResponse/LLMStreamEvent - ✅ 中间件:
log/tools/compress - ✅ 测试:68 个用例(状态转换 / 钩子 / 错误处理 / LLMClient 解析 / 中间件)
- 🚧 实现中:middlewares(mcp/memory)、multiagent、CLI、examples
MIT