OsmosisAgentToolkit Class Architecture: A Deep Dive into the Osmosis Agent Toolkit
The OsmosisAgentToolkit class serves as a central façade that bundles account management, SQS query services, and six specialized tools into a unified interface for LLM agents interacting with the Osmosis blockchain.
The OsmosisAgentToolkit class architecture provides a modular, cache-aware foundation for building language-model agents that can query balances, fetch swap quotes, and execute transactions on the Osmosis network. Located in packages/core/src/toolkit.ts, this class orchestrates three distinct layers—core façade, service, and tool layers—to deliver a type-safe, stateful toolkit for blockchain automation.
Three-Layer Architecture of OsmosisAgentToolkit
The architecture separates concerns into three distinct layers, each with specific responsibilities and source file locations.
Core Façade Layer
The core façade provides a single public entry point through the OsmosisAgentToolkit constructor. This layer exposes ready-to-use tools and utilities while hiding the complexity of blockchain interactions. The primary implementation resides in packages/core/src/toolkit.ts (lines 16-86).
Service Layer
The service layer handles low-level blockchain queries, price feeds, and transaction building. The OsmosisSqsQueryClient class in packages/core/src/queries/sqs/client.ts implements the Sidecar Quote Service (SQS) API, providing spot prices and swap quotes to the tool layer.
Tool Layer
The tool layer consists of stateless, reusable Tool objects that implement concrete operations. Each tool implements the generic Tool<Input, Output> interface defined in packages/core/src/tools/tool.ts. These tools remain side-effect-free except for the two transaction-sending tools that broadcast to the blockchain.
Core Façade: The OsmosisAgentToolkit Class
The OsmosisAgentToolkit class in packages/core/src/toolkit.ts maintains several protected stateful members that persist throughout the agent's lifecycle.
Stateful Members
The class initializes five core dependencies in its constructor:
protected readonly _account: Account
protected readonly _sqsClient = new OsmosisSqsQueryClient()
protected readonly _accountTool: AccountTool
protected readonly _swapQuoteInGivenOutTool: SwapQuoteInGivenOutTool
protected readonly _swapQuoteOutGivenInTool: SwapQuoteOutGivenInTool
protected readonly _sendSwapInGivenOutQuoteTxTool: SendSwapInGivenOutQuoteTxTool
protected readonly _sendSwapOutGivenInQuoteTxTool: SendSwapOutGivenInQuoteTxTool
The Account object (from packages/core/src/account.ts) owns the mnemonic and handles address derivation and message signing. The OsmosisSqsQueryClient provides HTTP connectivity to the Sidecar Quote Service for price data and swap routing.
LRU Cache Implementation
To prevent redundant HTTP calls and memory leaks in long-running agents, the toolkit implements two LRUCache instances:
protected readonly _quoteAmountOutMemory = new LRUCache<string, SidecarInGivenOutQuoteResponse>({ max: 100 })
protected readonly _quoteAmountInMemory = new LRUCache<string, SidecarOutGivenInQuoteResponse>({ max: 100 })
These caches store recent swap quote responses with a maximum capacity of 100 entries each, located at lines 25-33 of packages/core/src/toolkit.ts.
Constructor Wiring and Public Getters
The constructor wires every tool with the shared Account, OsmosisSqsQueryClient, and appropriate cache. This ensures all tools operate on a single consistent context. Public getters expose the individual tools so an LLM agent can invoke them directly:
get accountTool() { return this._accountTool }
get swapQuoteInGivenOutTool() { return this._swapQuoteInGivenOutTool }
// ... additional getters for remaining tools
Service Layer: OsmosisSqsQueryClient
The OsmosisSqsQueryClient class in packages/core/src/queries/sqs/client.ts implements the Sidecar Quote Service API through REST endpoints. This stateless service client provides:
- Current token prices via
getPrices(denoms)– used byAccountToolto calculate USD-denominated balances - Swap quotes via
quoteInGivenOut()andquoteOutGivenIn()– used by the swap tools to determine exchange rates and price impact
The client is stateless; every tool receives the same instance, guaranteeing that all queries share the same HTTP configuration and rate-limit handling. Type definitions for SQS responses reside in packages/core/src/queries/sqs/router.ts.
Tool Layer: Stateless Tool Implementations
All tools implement the generic Tool<Input, Output> interface defined in packages/core/src/tools/tool.ts. They are deliberately side-effect-free except for the two "Send-Tx" tools, which broadcast a transaction to the blockchain.
Available Tools and Dependencies
| Tool | Purpose | Dependencies | Source |
|---|---|---|---|
AccountTool |
Returns the account address plus USD-valued balances. | Account (for address), OsmosisSqsQueryClient (price feed), chain-registry assets list. |
packages/core/src/tools/account.ts |
SwapQuoteInGivenOutTool |
Given a desired output amount, returns the required input amount and price impact. | OsmosisSqsQueryClient, _quoteAmountOutMemory cache. |
packages/core/src/tools/swap.ts |
SwapQuoteOutGivenInTool |
Given an input amount, returns the expected output amount. | OsmosisSqsQueryClient, _quoteAmountInMemory cache. |
packages/core/src/tools/swap.ts |
SendSwapInGivenOutQuoteTxTool |
Builds & broadcasts a transaction that satisfies an in-given-out quote. | Account (signing), _quoteAmountOutMemory for the cached quote. |
packages/core/src/tools/swap.ts |
SendSwapOutGivenInQuoteTxTool |
Builds & broadcasts a transaction for an out-given-in quote. | Account, _quoteAmountInMemory. |
packages/core/src/tools/swap.ts |
Cache-Aware Tool Implementation
Tools leverage the LRU caches maintained by the toolkit to avoid redundant network requests. Here is a simplified example from the swap quote tools:
// Inside SwapQuoteInGivenOutTool (simplified)
async call(params) {
const cacheKey = `${params.poolId}-${params.amountOut}`
const cached = this.quoteCache.get(cacheKey)
if (cached) return cached
const quote = await this.sqsClient.quoteInGivenOut(params)
this.quoteCache.set(cacheKey, quote)
return quote
}
This pattern ensures that repeated quote requests for the same pool and amount return instantly from memory rather than triggering additional HTTP calls to the Sidecar Quote Service.
Interaction Flow: From Agent to Blockchain
The architecture enables a clear interaction pattern for LLM agents. Here is the typical flow from initialization to transaction execution:
1. Initialize the Façade
const toolkit = new OsmosisAgentToolkit(mnemonic)
This creates the Account, OsmosisSqsQueryClient, and all tool instances, wiring them together with shared caches.
2. Query Account Information
const accountInfo = await toolkit.accountTool.call()
// → Returns address + balances (USD totals)
The AccountTool uses the shared Account for the address and OsmosisSqsQueryClient to fetch current token prices for USD valuation.
3. Request a Swap Quote
For a swap from OSMO to USDC:
const quote = await toolkit.swapQuoteOutGivenInTool.call({
poolId: 1,
amountIn: "1000000", // 1 OSMO (6 decimals)
})
// → Returns expected amountOut and price impact
The tool checks _quoteAmountInMemory first, then falls back to OsmosisSqsQueryClient.quoteOutGivenIn().
4. Execute the Transaction
const txResult = await toolkit.sendSwapOutGivenInQuoteTxTool.call({
poolId: 1,
amountIn: "1000000",
})
console.log('Tx hash:', txResult.transactionHash)
The SendSwapOutGivenInQuoteTxTool retrieves the cached quote from _quoteAmountInMemory, builds the transaction using the Account for signing, and broadcasts it to the Osmosis network.
All steps share the same underlying Account, OsmosisSqsQueryClient, and LRU caches, guaranteeing consistent state and efficient network usage.
Key Files and Responsibilities
| File | Role |
|---|---|
packages/core/src/toolkit.ts |
The façade that wires all tools together and manages shared state. |
packages/core/src/account.ts |
Mnemonic-based signing and address generation. |
packages/core/src/queries/sqs/client.ts |
HTTP client for the Sidecar Quote Service (SQS). |
packages/core/src/tools/account.ts |
Retrieves balances and calculates USD valuation. |
packages/core/src/tools/swap.ts |
Implements quote and transaction-sending tools with LRU cache integration. |
packages/core/src/tools/tool.ts |
Generic Tool<Input, Output> interface. |
packages/core/src/queries/sqs/router.ts |
Type definitions for SQS response payloads. |
These files together form the complete architecture of the Osmosis Agent Toolkit – a modular, cache-aware, and testable set of tools that enable language-model agents to read on-chain data, obtain price quotes, and execute swaps on the Osmosis network.
Summary
- The OsmosisAgentToolkit acts as a central façade in
packages/core/src/toolkit.ts, providing a single entry point for LLM agents to interact with the Osmosis blockchain. - The architecture follows a three-layer pattern: Core Façade (state management), Service Layer (
OsmosisSqsQueryClientfor HTTP queries), and Tool Layer (stateless operation implementations). - Six specialized tools handle specific tasks:
AccountToolfor balances,SwapQuoteInGivenOutToolandSwapQuoteOutGivenInToolfor pricing, andSendSwapInGivenOutQuoteTxTool/SendSwapOutGivenInQuoteTxToolfor execution. - LRU caching prevents redundant network calls, with
_quoteAmountOutMemoryand_quoteAmountInMemorycaches shared across quote tools and transaction senders. - All tools implement the generic
Tool<Input, Output>interface frompackages/core/src/tools/tool.ts, ensuring consistent signatures and testability.
Frequently Asked Questions
What is the purpose of the OsmosisAgentToolkit class?
The OsmosisAgentToolkit class serves as the central orchestration point for LLM agents interacting with the Osmosis blockchain. It encapsulates account management, price querying via the Sidecar Quote Service, and transaction execution into a single, stateful façade that maintains LRU caches and shared service clients across all operations.
How does the toolkit handle caching for swap quotes?
The toolkit implements two LRUCache instances—_quoteAmountOutMemory and _quoteAmountInMemory—within the OsmosisAgentToolkit class (lines 25-33 of packages/core/src/toolkit.ts). These caches store up to 100 recent quote responses each, allowing SwapQuoteInGivenOutTool and SwapQuoteOutGivenInTool to return cached results instantly, while the corresponding transaction tools (SendSwapInGivenOutQuoteTxTool and SendSwapOutGivenInQuoteTxTool) retrieve these cached quotes to build and broadcast transactions without re-querying the SQS service.
What are the dependencies between the AccountTool and the swap tools?
All tools depend on shared infrastructure provided by the OsmosisAgentToolkit façade. Specifically, AccountTool relies on the Account class (for address derivation and signing) and OsmosisSqsQueryClient (for fetching token prices to calculate USD-denominated balances). The swap tools (SwapQuoteInGivenOutTool, SwapQuoteOutGivenInTool, and the transaction variants) share the same OsmosisSqsQueryClient instance for quote fetching and access the toolkit's LRU caches for performance optimization.
Where is the Tool interface defined, and why is it important?
The generic Tool<Input, Output> interface is defined in packages/core/src/tools/tool.ts. This interface standardizes the contract for all toolkit operations, ensuring that every tool implements a consistent call(params: Input): Promise<Output> method signature. This abstraction enables the OsmosisAgentToolkit to treat diverse operations—ranging from balance queries to complex swap transactions—as interchangeable, testable units that LLM agents can invoke through a unified API.
Have a question about this repo?
These articles cover the highlights, but your codebase questions are specific. Give your agent direct access to the source. Share this with your agent to get started:
curl -s "https://instagit.com/install.md" Maintain an open-source project? Get it listed too →