How to Choose an Open-Source AI Agent Framework: Architecture Patterns and Performance Design
This article breaks down how to evaluate open-source AI agent frameworks beyond feature lists. It compares four architecture patterns, then walks through the runtime engineering decisions that determine long-session stability and cost: main loop and event granularity, context compression thresholds and token counting, session persistence and crash recovery, tool visibility and approval gating, and prefix cache hit optimization. Use it as a practical scoring order for framework selection.
1. Why “Too Many Frameworks” Becomes an Engineering Problem
The number of open-source AI agent implementations has grown quickly. On the surface this looks like a choice problem; in practice it is a missing evaluation coordinate system. Different projects make completely different trade-offs on five things: how the main loop is driven, how context is compressed, how tools are scheduled, how failures are recovered, and how cache hits are achieved. If you compare feature checklists before defining dimensions, you will easily reach the wrong conclusion that “more features means better.”
A practical approach is to split evaluation into two layers. The first is the architecture pattern, which determines how code is organized and how coupled it becomes. The second is runtime engineering capability, which determines stability and cost in long sessions. The first affects the difficulty of secondary development; the second directly affects your bill and user experience.
2. Four Architecture Patterns and Why They Diverge
Public implementations roughly fall into four organizational styles:
- Protocol-agnostic core plus adapter layer: the core loop is unaware of any specific model protocol, and differences are pushed down into adapters. The advantage is low switching cost between model providers; the drawback is that the adapter layer tends to swell into a “second set of business logic.”
- Data-structure-driven: a “stable prefix” is made a first-class data structure, for example an append-only context structure and cache identity inheritance on fork. The advantage is predictability; the drawback is heavy constraints on upper-layer callers.
- Session-affinity-based: the protocol is left unchanged, and requests from the same session are pinned to the same cache slot via a session identifier. The implementation is light, but it depends on whether the underlying layer truly offers session-level affinity.
- Read-only pass-through: cache is not actively managed; the implementation only reads cache hit counters from responses and records them in a ledger. This is the simplest option, and also the one with the least optimization headroom.
The root of this divergence is usually not aesthetics but constraints of the target scenario. Implementations aimed at interactive terminals care more about startup latency and interrupt recovery; implementations aimed at server-side orchestration care more about concurrency and multi-tenant isolation.
3. Main Loop and Event Mechanism
The main loop sets the ceiling on capability. The common shape is a closed loop of “model output → parse actions → execute tools → backfill results,” and the differences come down to three points:
- Event granularity: coarse-grained “turns,” or fine-grained streaming incremental events. Fine granularity is better for front-end rendering and interruption, but state machine complexity rises sharply.
- Interrupt semantics: when a user interrupts midway, are all side effects of the current turn discarded, or are tool calls that already happened allowed to land? This must be designed together with the side-effect safety policy.
- Loop termination conditions: besides “the model no longer requests tools,” do you add a step cap, a budget cap, and repeated-action detection to avoid spinning and burning money?
A sketch of the loop skeleton:
while not done and steps < MAX_STEPS and cost < BUDGET:resp = model.stream(messages, tools=visible_tools)for ev in resp:yield ev # emit fine-grained eventsif resp.tool_calls:results = scheduler.run(resp.tool_calls, gate=approval)messages.extend(backfill(results))else:done = True
4. Context Management: Compression Thresholds and Counting Rules
The core tension in long sessions is that the window is finite while history grows without limit. Engineering needs four things settled:
- Trigger threshold: trigger by token share (for example, approaching 70% of the window) rather than by message count, which becomes badly distorted when tool results balloon.
- Summarization style: rolling summaries (append one compressed record per turn) and layered summaries (verbatim text nearby, summaries far away) each have trade-offs; the former is simpler to implement but loses information faster.
- Counting rules: implementations count tokens differently (local estimation, server-returned values, character-based conversion), and inconsistent rules make thresholds meaningless. The recommendation is to treat server-returned values as authoritative and local estimation as an early warning only.
- Cross-session memory: store long-term memory separately from the current context and retrieve it on demand for injection, so memory does not pollute the main context.
5. Session Management and Crash Recovery
Persistence usually comes in three layers: in-memory state, local session files, and external storage. The value of the three layers is recovery granularity: after a process crash you can recover to the most recent tool boundary rather than the most recent user input. Capabilities that need deliberate design include concurrency control (serialize access to the same session to avoid interleaved writes), forking (inherit cache identity after a fork to reuse the prefix), and idempotency checks on recovery (deciding whether a given tool call already produced a side effect).
6. Tool Calls: Visibility, Parallelism, and Gating
The tool layer is the easiest place to lose control, and four semantics should be made explicit:
- Registration and visibility: dynamically trim the tool set by session phase to reduce mis-calls and prompt bloat.
- Parallel scheduling: read-only tools can run in parallel; write tools must be serialized or locked. The backfill order of parallel results must be stable, otherwise prefix stability breaks.
- Approval gating: the default posture should be “high-risk actions require confirmation,” graded by action reversibility rather than hard-coded by tool name.
- Error handling: backfill structured failure results to the model with repairable hints, so the model does not repeat the same failing call.
7. Performance Design: Make Every Turn Hit the Prefix Cache
This is the most direct way to save money in long sessions. Cache read pricing is typically far below standard input pricing, and the gap is amplified in long sessions. Engineering can proceed in three tiers:
- Active breakpoint management: place cache breakpoints uniformly in the protocol-agnostic layer, guaranteeing that the system prompt, tool definitions, and history prefix stay byte-for-byte identical.
- Stable prefix data structures: append-only context plus fork inheritance naturally raises the hit rate.
- Session affinity and read-only accounting: a lightweight option that first achieves “do not break what you do not change,” and records hit volume in the cost ledger.
One frequently overlooked principle: never concatenate dynamic content into the prefix. Timestamps, random identifiers, and rotating prompt fragments will invalidate the cache entirely.
[stable prefix] system instructions + tool definitions + fixed examples[growing area] history messages (append-only)[volatile area] time, environment info, retrieval results
8. Fault Tolerance, Security, and Extensibility
Reconnection and fault tolerance need the concept of a “budget”: cap retry counts and total duration, distinguish retryable from non-retryable errors, and on stream interruption keep content already produced and support resumption. The degradation chain should follow the order “switch model → shrink context → hand off to a human.” On the security side, the recommendation is two-layer sandbox semantics (process-level isolation plus a file system allowlist), redacting sensitive information before it enters the context, and full audit logs. For extensibility, three general levers are tool protocol integration, multi-provider model adaptation, and exposing a stable external interface.
9. Practical Recommendations
When selecting a framework, first fix the scenario constraints (interactive or server-side, single-tenant or multi-tenant), then score in the order “architecture coupling → context and session capability → tool governance → cache and cost → security and audit.” If the team needs long-term evolution, prefer implementations that separate the core from the adapter layer and keep the context structure controllable; if the goal is fast validation, a lightweight pass-through option is enough. If you already use general-purpose cloud capabilities, you can hand session persistence to object storage and audit and metrics to logging and monitoring services, keeping your effort focused on the agent’s own policy design.
