How Agent Frameworks Collaborate: From Protocol Design to Engineering Implementation
This article explores the engineering challenges and solutions for combining different AI agent frameworks. It covers establishing clear responsibility boundaries between planning and execution, optimizing structured data communication, and designing a robust five-layer communication architecture. It further provides guidelines on reliability mechanisms, gradual integration strategies with existing services, and evaluation metrics to ensure that framework combinations result in stable, maintainable, and production-ready systems.
1. Can Two Agent Systems Be Combined Directly?
When one system excels at planning, reasoning, and context management, while another excels at tool execution, task scheduling, and external service integration, combining them is a natural engineering choice. The former is responsible for understanding goals and decomposing tasks, while the latter translates plans into verifiable actions.
However, “being able to invoke each other” does not equate to “being able to collaborate stably.”
The simplest implementation involves one system passing tasks to another via an API and returning the results to the model. This approach works for proof of concepts, but in real-world business environments, issues typically emerge in the following areas:
- Whether both sides share a consistent understanding of tasks, tool parameters, and return results;
- Whether user authorization can be securely passed to downstream execution components;
- Whether the system can determine if an operation has completed after a network timeout;
- Whether large-scale results consume too much model context;
- In multi-turn invocations, who saves and restores the state;
- When errors occur, whether the system can pinpoint the specific stage: planning, authorization, execution, or result interpretation.
Therefore, a more reasonable starting point is not simply concatenating two frameworks, but rather establishing clear responsibility boundaries and communication contracts. The value of the protocol layer should be derived from these collaboration costs, rather than aiming to “replace all existing interfaces.”
2. Define Division of Labor Before Deciding How to Connect
An easily implementable combination approach is to divide the system into a planning end and an execution end.
The planning end receives user goals, formulates task plans, selects tools, and adjusts subsequent actions based on execution feedback. The execution end handles parameter validation, permission checks, resource access, task execution, and result logging.
The link between the two can follow this flow:
User Request → Planning End → Protocol Adapter Layer → Execution End → External Services
Execution results are returned in the opposite direction.
The protocol adapter layer does not necessarily have to be deployed independently. It can initially exist as an in-process module and later evolve into a standalone service as collaboration scales up, execution nodes increase, or isolation requirements rise.
When dividing labor, two principles should be maintained:
First, the plan proposed by the model should not automatically receive execution permissions. The planning end outputs operation intent; the execution end must independently judge whether execution is allowed based on user identity, resource scope, and risk level.
Second, tasks at the same level should not be re-planned by both systems simultaneously. Otherwise, this may lead to redundant decomposition, repetitive handoffs, and circular invocations. A more robust approach is for one system to own the master task state, while the other receives well-defined sub-tasks.
3. Repeated Field Overhead: Worth Optimizing, but Must Be Measured
In structured data such as product catalogs, account details, or equipment lists, the same set of fields appears repeatedly with each record. For traditional services, this is typically an acceptable data representation. For model invocations, if the raw response directly enters the context, the repeated fields will also participate in tokenization and consume the input budget.
For example, here is a sample response:
[{"id": 101, "name": "Item A", "price": 28},{"id": 102, "name": "Item B", "price": 35}]
As the number of records increases, the overhead caused by repeating field names grows accordingly. You can consider separating the structure declaration from the record values:
{"schema": {"fields": ["id", "name", "price"]},"rows": [[101, "Item A", 28],[102, "Item B", 35]]}
The above is merely an illustration of a custom data contract and does not represent the standard interface of any existing protocol.
While this structure reduces repetitive text, it introduces new responsibilities: the sender and receiver must maintain consistency regarding field order, data types, missing values, and versions. If positions shift, errors may be harder to detect than with repeated field names.
More importantly, you must distinguish between three types of gains:
- Reduced transmission bytes: Affects bandwidth and partial transmission latency;
- Reduced model input tokens: Affects context capacity and inference costs;
- Reduced total system cost: Must also account for the extra costs of encoding, validation, caching, and adaptation.
Transmission compression does not necessarily reduce model tokens. If the data is restored to full text before being fed into the model, the online savings will not automatically translate into context savings.
Therefore, the optimization target should be the complete data path, not an isolated network packet.
4. What a Five-Layer Communication Architecture Should Solve
For ease of analysis, agent communication capabilities can be broken down into five logical layers. The following is an engineering division recommendation, not a description of the implemented capabilities of any specific project.
1. Transport and Message Boundary Layer
This layer is responsible for reliably sending and receiving messages, including connection management, message framing, timeouts, size limits, and streaming.
Existing transport protocols are typically mature enough that there is no need to redesign underlying network mechanisms just because the business entity has become an agent.
What truly needs to be clarified is: when a logical message starts and ends, what content can be resent after a connection interruption, and how large results are delivered in segments.
For long-running tasks, a distinction should also be made between “the connection is still alive” and “the task is still executing.” A disconnected connection cannot be directly equated to task failure.
2. Data Contract and Structure Negotiation Layer
This layer defines fields, types, constraints, structure versions, and the encoding methods supported by both parties.
If structural reuse is adopted, the full structure can be exchanged first, then referenced via a structure identifier. However, the following must be considered:
- How to recover when the receiving end has no cache;
- How to identify compatibility when fields are added or removed;
- Whether structure information is shared across multiple nodes;
- How to validate structure content to prevent errors or malicious overrides;
- Whether structure caches for different tenants need isolation.
For fields where business semantics have changed, you should not just modify the description while keeping the version unchanged. For example, if the currency unit changes from “dollars” to “cents,” even if the field remains an integer, the original contract is already broken.
When the structure is unknown or incompatible, the system should pause consumption, re-fetch the structure, or fall back to a self-describing format, rather than relying on model guesses.
3. Identity and Authorization Layer
When agents invoke external services, they need to express both “who is calling” and “on behalf of whom.”
Existing network authentication mechanisms can carry credentials, but credentials alone do not mean business authorization is complete. Authorization design should also cover:
- Identity of the user or service principal;
- Identity of the currently executing agent;
- Granted scope of operations;
- Validity period and target of use for credentials;
- Whether further delegation is allowed;
- Handling of permission expiration or revocation.
The key is not to put more fields into the request, but to have a trusted execution environment verify this information and enforce restrictions during resource access.
For example, if an agent is granted permission to read order status, it should not automatically gain permission to modify orders or export all customer data just because the task plan requires it.
High-risk operations should also have independent approval conditions. A user approving a specific action does not equate to approving all subsequent similar actions.
4. Semantic and Tool Capability Layer
Correct structure does not mean clear meaning. An integer might represent a quantity, an amount, or a status enum; a time string might be missing a timezone.
This layer should describe field semantics, units of measurement, time conventions, enum meanings, and tool side effects, enabling the execution end and planning end to share the same basis for interpretation.
For example, you can agree that:
- Amounts are represented as integers in the smallest currency unit;
- Time includes explicit timezone information;
- Status values have stable, versioned meanings;
- Missing fields have different meanings than explicit null values;
- Tool declarations specify read-only, write, or irreversible operation attributes.
These metadata cannot replace model reasoning, but they can reduce the burden of relying on ad-hoc prompts to explain fields and support deterministic validation.
At the same time, note that text returned by tools is data and should not be treated as a higher-priority instruction. Even if the response includes a semantic description, it cannot be used to alter authorization policies or trigger new high-risk operations.
5. Task Lifecycle and Collaboration Layer
Agent collaboration is different from a single query. Tasks may run for a long time, involve multiple steps, and be paused, canceled, or wait for user confirmation midway.
Therefore, explicit task state management is required, such as accepted, executing, waiting for confirmation, success, failure, and canceled. The set of states can be tailored to the business, but the transition rules must be clear.
It is especially important to distinguish between:
- The request did not reach the execution end;
- The request was accepted, but the result has not yet returned;
- The operation has been completed, but the receipt was lost;
- The operation was partially completed, requiring compensation or manual processing.
These situations cannot be uniformly handled as “invoke again.” For operations that produce side effects, blind retries may lead to duplicate submissions, duplicate writes, or duplicate notifications.
5. Reliability Cannot Depend on the Model’s On-the-Fly Judgment
In actual integration, at least four mechanisms need to be implemented.
Idempotency and Duplicate Request Identification
Establish an idempotency identifier for a specific business operation, and the execution end should save it alongside the result or status. When a duplicate request arrives, the existing status should be returned, or the conflicting request should be rejected.
When parameters corresponding to the same idempotency identifier change, they cannot be silently overwritten, as this would destroy the traceability of the operation.
Idempotency is not an indefinite promise. The retention period, tenant scope, and concurrency handling methods should all be defined in the contract.
Timeout, Retry, and Status Query
A timeout only indicates that the caller did not receive a result within the deadline; it does not prove that the operation was not executed.
Read requests are generally safer to retry; write requests should combine idempotency records or status queries to confirm whether they can be submitted again.
Multi-layer systems should also propagate the remaining execution time to prevent each layer from restarting a full timeout window, causing the overall duration to lose constraints.
Cancellation and Compensation
A cancel request can stop steps that have not yet started, but it may not necessarily undo operations that have already been completed.
For tasks involving multiple resources, a distinction should be made between rollback-able operations, compensable operations, and irreversible operations. Irreversible operations should ideally have a clear confirmation point before execution, rather than leaving all risks to the post-failure recovery process.
Backpressure and Resource Limits
When the task receiving speed is higher than the execution speed, the system must limit concurrency, control queue length, and feed back a busy status to upstream.
Model context is also a finite resource. Large results can be filtered, aggregated, or paginated at the execution end, returning only the information needed for decision-making to the planning end. Complete results needed for auditing or further calculations should be stored in controlled storage.
6. Integrating with Existing Services is More Realistic Than Full Replacement
Most teams already have stable business interfaces. A more feasible path is to first use an adapter layer to unify data contracts, authorization checks, and task status, rather than requiring all services to migrate simultaneously.
This can be advanced in three steps:
Step 1: Connect Read-Only Tasks.
Prioritize query, retrieval, and statistical scenarios to verify whether task division, result interpretation, and error propagation are correct.
Step 2: Optimize High-Frequency Structured Data.
Only attempt structural reuse for interfaces with many repeated fields, large response sizes, and relatively stable structures. Low-frequency, small-response interfaces may not be worth the added negotiation complexity.
Step 3: Gradually Open Write Capabilities.
After idempotency, approval, auditing, and recovery processes are mature, connect modifications, creations, and batch operations.
When new and old formats coexist, a clear negotiation and degradation strategy must be defined. Efficiency optimizations can be degraded, but identity verification, permission checks, and critical semantic constraints cannot be skipped due to compatibility mode.
7. How to Prove the Combined Approach is Actually Better
You cannot just show that the message payload became shorter, nor can you use a few internal samples to draw universal savings conclusions.
The evaluation should cover at least three sets of metrics:
- Efficiency Metrics: Transmission bytes, model input tokens, end-to-end latency, and additional computing costs;
- Correctness Metrics: Task success rate, field interpretation error rate, result completeness, and number of repeated executions;
- Operability Metrics: Exception recovery time, structure cache miss impact, number of manual interventions, and fault localization costs.
Test data should cover different numbers of fields, records, structure change frequencies, and task complexities. When comparing, it is necessary to fix the model version, prompt content, tool selection, and result truncation rules to avoid attributing other optimizations to protocol gains.
Cold start and hot cache states should be tested separately, and exceptions such as connection interruptions, structure version inconsistencies, permission revocations, and duplicate requests should be injected.
If structural reuse reduces tokens but significantly increases the interpretation error rate, it may not be a better solution. Communication efficiency must be evaluated alongside business correctness.
8. Final Questions to Answer Before Landing
Before deciding to combine two agent systems, it is recommended to check the following first:
- Who owns the master task state, and who is responsible for sub-task execution?
- Do both parties share explicit data and semantic contracts?
- Can the execution end independently perform permission checks?
- Can you determine whether an operation has already occurred after a timeout?
- Is there a safe recovery path when the structure cache fails?
- Can you trace the various stages a task goes through?
- Do logs avoid recording unnecessary credentials and sensitive data?
- When the new protocol is unavailable, can the system continue to run without lowering security requirements?
Once these questions have reliable answers, the framework combination is more than just “being connected.”
The core of agent collaboration is not making two systems send more messages to each other, but ensuring that every message exchange has a clear identity, structure, semantics, and state. Establishing responsibility boundaries first, perfecting communication contracts second, and finally using reproducible testing to judge optimization value is typically more robust than directly pursuing a brand-new protocol, and makes it easier to move toward maintainable production systems.
