# API
Source: https://docs.illa.io/build/api
Send financial intents, receive simulation results and ready-to-sign transaction data.
Send financial intents, receive simulation results and ready-to-sign transaction data. Same core pipeline (Intelligence, Safety, Engine) for products that manage their own UI and conversation.
**Best for:** Direct integration with ILLA, granular control over the lifecycle, automated workflows, custom agent architectures.
The API is currently in private beta. [Get in touch](mailto:partners@illalabs.io) to request access.
# MCP Server
Source: https://docs.illa.io/build/mcp-server
ILLA as a tool server for AI agent platforms.
ILLA as a tool server for AI agent platforms. Financial capabilities exposed as MCP resources that any compatible agent can call natively. Configure scope, limits, and policies per deployment.
**Best for:** Developers building AI agents that need financial capabilities. Custom agent deployments, enterprise agent platforms, multi-agent systems.
The MCP Server is currently in private beta. [Get in touch](mailto:partners@illalabs.io) to request access.
# Overview
Source: https://docs.illa.io/build/overview
One integration gives your product the full ILLA execution stack.
One integration gives your product the full ILLA execution stack: intent resolution, planning, safety, simulation, and multi-protocol execution. You own the surface and the wallet infrastructure. ILLA handles everything between intent and ready-to-sign transaction data.
Configuration applies across all integration paths: capability scoping, protocol and chain restrictions, and autonomy policies. All enforced at runtime.
Full-stack conversational finance for your product.
Direct integration with granular lifecycle control.
Financial capabilities for AI agent platforms.
# SDK
Source: https://docs.illa.io/build/sdk
Full-stack conversational finance. Intent resolution, conversation management, simulation, execution, and optional wallet provisioning.
The SDK packages ILLA's conversational finance stack for products where chat is part of the user experience. It covers intent resolution, conversation state, simulation, execution, and optional wallet provisioning in a white-label integration.
**Best for:** DeFi protocol frontends, financial assistants, savings products, embedded wallet experiences.
The SDK is currently in private beta. [Get in touch](mailto:partners@illalabs.io) to request access.
# Connect ILLA to Claude
Source: https://docs.illa.io/connect/claude
Install ILLA's MCP connector and Claude becomes financially capable immediately.
Install ILLA's MCP connector and Claude becomes financially capable immediately. ILLA provisions an embedded wallet, and Claude gains access to the full capability stack: transfers, trading, lending, portfolio queries, and more.
The user authenticates once. From that point, financial intents expressed in natural conversation flow through ILLA's planning and safety stack. Claude says "send \$20 to Maria" or "rebalance my portfolio" and ILLA handles intent resolution, simulation, and execution. The user reviews the plan and approves.
No code, no wallet setup, no configuration required.
The Claude connector is currently in private beta. [Get in touch](mailto:hello@illalabs.io) to request access.
# ILLA Apps
Source: https://docs.illa.io/connect/illa-apps
ILLA's own surfaces. The full capability stack, directly — no agent platform, no integration required.
ILLA's own surfaces. The full capability stack, directly — no agent platform, no integration required.
## ILLA Chat
Conversational interface for financial execution. Built on the same core stack that powers all ILLA integrations. Available in early access.
## ILLA Live
Voice-first financial interaction. Express financial intent naturally — ILLA handles the rest. Currently in private beta.
Your wallet and context persist across both surfaces. Switch between Chat and Live without losing state.
Both apps are in early access. [Get in touch](mailto:hello@illalabs.io) to request access.
# Overview
Source: https://docs.illa.io/connect/overview
Connect ILLA to the AI agents and surfaces you already use.
ILLA connects to the AI agents and surfaces you already use. No code required.
Install ILLA's MCP connector and Claude becomes financially capable immediately.
Direct access to ILLA through Chat and Live.
# Capabilities
Source: https://docs.illa.io/illa/capabilities
ILLA aggregates financial operations into a unified execution surface across chains, protocols, and asset types.
ILLA aggregates financial operations into a unified execution surface.
Instead of integrating with individual protocols directly, AI systems connect to ILLA and gain access to a growing set of financial capabilities across chains, protocols, and asset types.
Every capability flows through the same core pipeline:
* **[Intelligence](/illa/intelligence)** resolves the intent.
* **[Safety](/illa/safety-and-security)** simulates, verifies, and enforces policies.
* **[Engine](/illa/engine)** executes.
This means every new integration automatically inherits ILLA's full safety stack.
## Intent to execution
The power of ILLA's capability surface is composition. The intelligence layer takes a single intent and decomposes it into a coordinated, multi-step, multi-chain plan across multiple capabilities.
**Treasury operations.**
```
Pull enough from our earning balance to cover today's invoices,
consolidate to USDC, and pay each one on the required network.
```
Queries portfolio balances and DeFi positions, calculates the required withdrawal amount
Withdraws from lending protocol
Swaps withdrawn assets to USDC
Bridges to each recipient's network
Executes individual transfers
**Take profit and redeploy.**
```
Sell half my ETH, put $800 into yield, and use the rest to bet
on the Fed holding rates.
```
Queries balances, calculates 50% of ETH holdings
Executes swap to USDC
Calculates split, supplies the majority to lending protocol for yield
Bridges remainder to prediction market network
Resolves target market by natural language, places position
**Portfolio rebalance.**
```
Rebalance to 60% stablecoins in yield and 40% ETH, using the
best rates across chains.
```
Queries full portfolio and existing positions
Calculates target allocations against current holdings
Withdraws from existing lending positions, executes swaps to reach target ratios
Queries yield rates across chains and protocols
Supplies stablecoins to highest-yield protocol on optimal network
Each example is a single intent, multiple capability groups, multiple chains, one coordinated plan. The user sees the full plan, approves it once, and signs each transaction.
## Capability reference
What ILLA can execute today, and what's coming next.
### Transfers and payments
Move value between addresses, across chains, and between networks.
| Capability | Description |
| ------------------ | --------------------------------------------------- |
| Token Transfer | Send any supported asset to any address |
| Cross-Chain Bridge | Move assets between networks via aggregated routing |
Cross-chain bridging selects the optimal bridge path based on cost, speed, and liquidity.
### Trading
Exchange assets at the best available rate across aggregated liquidity.
| Capability | Description |
| ---------- | ----------------------------------------------------------------------------------------------------------------- |
| Token Swap | Exchange any token for another. Same-chain or cross-chain. Supports batched multi-swap execution in a single plan |
Swaps route through aggregated DEX liquidity by default. Integrators can restrict routing to specific providers or pools.
### DeFi lending and yield
Supply assets to earn yield and manage positions across lending protocols.
| Capability | Description |
| ---------- | --------------------------------------------------- |
| Supply | Deposit assets into lending protocols to earn yield |
| Withdraw | Retrieve supplied assets and accrued yield |
When protocol is not specified, ILLA routes to the optimal provider based on yield, risk, and integrator preference.
### Prediction markets
Take positions on real-world events through decentralised prediction markets.
| Capability | Description |
| --------------- | ----------------------------------------------------- |
| Market Search | Find markets and odds by topic using natural language |
| Buy Outcome | Purchase outcome shares in an active market |
| Sell Position | Exit an existing position |
| Redeem Winnings | Claim returns from resolved markets |
Users describe the position they want to enter, and ILLA resolves the intent to the correct market and outcome.
### Perpetual futures
Open and manage leveraged long and short positions on perpetual markets.
| Capability | Description |
| --------------------- | -------------------------------------------------- |
| Open Position | Open a leveraged long or short |
| Close Position | Exit an open position, fully or partially |
| Set Leverage | Set or adjust leverage on a position |
| Stop and Limit Orders | Set stop-loss, take-profit, and limit entry orders |
Users describe the position they want, and ILLA resolves the intent to the correct market, side, and size.
### Portfolio and positions
Query balances, positions, and portfolio state across chains and protocols.
| Capability | Description |
| ---------------------- | ------------------------------------------------- |
| Portfolio Balances | View asset balances across all supported networks |
| DeFi Positions | Query active lending and yield positions |
| Supported Tokens | Retrieve available tokens per network |
| Supported Capabilities | Discover what ILLA can execute |
Read-only capabilities execute automatically without user approval. They feed context into the planning layer, enabling intents like "withdraw enough from my earning balance to cover today's invoices" where the system needs to know current balances to construct the plan.
### Market intelligence
Access real-time pricing, yield data, and market information.
| Capability | Description |
| ----------------- | --------------------------------------------------- |
| Token Prices | Current and historical asset pricing |
| DeFi Market Rates | Yield rates and lending conditions across protocols |
| Market Details | Odds, volume, and status for prediction markets |
Market intelligence capabilities are read-only and auto-executable. They inform both user queries and the planning layer's decision-making.
### Expansion
ILLA's capability set is expanding continuously. The integration pattern is repeatable: define capability mappings, implement protocol adapters, vet for security and reliability, and activate.
Capabilities in development include: fiat gateway (on-ramp and off-ramp between fiat and digital assets, fiat-to-fiat transfers via traditional rails) and tokenised equities (tokenised exposure to traditional equity markets).
As new asset types and financial products come online, ILLA integrates them.
### Supported networks
ILLA operates across multiple EVM-compatible networks. Capabilities are not chain-specific. A user can express intent without specifying a chain, and ILLA resolves the optimal execution path.
| Network | Type |
| --------- | ---- |
| Ethereum | L1 |
| Polygon | L1 |
| Optimism | L2 |
| Base | L2 |
| Arbitrum | L2 |
| Avalanche | L1 |
| BSC | L1 |
| 0G | L1 |
Cross-chain operations are handled as coordinated multi-step plans. The user sees the full sequence and approves it as a single intent. The Engine handles cross-chain coordination underneath.
### Adding capabilities
Every new integration follows the same process. The protocol is evaluated for reliability and security. Capability mappings are defined. Protocol adapters are implemented and tested against ILLA's evaluation pipeline. The integration is activated and immediately inherits the full safety stack: simulation, verification, policy enforcement, and approval flows.
Integrators can scope their ILLA instance to specific capabilities, protocols, chains, or asset types. By default, ILLA routes through the full set of integrated protocols for optimal execution. These preferences are defined at the integration level and enforced by the Engine.
# Engine
Source: https://docs.illa.io/illa/engine
ILLA's protocol-aware orchestration and execution runtime.
The Engine is ILLA's protocol-aware orchestration and execution runtime. It takes an approved execution plan and turns it into a coordinated transaction sequence across protocols, chains, and asset types.
## From plan to execution
The intelligence layer decides what to do. Safety validates that it is safe. The Engine runs it.
An approved plan arrives as structured data: an ordered list of steps, each with its target protocol, parameters, dependencies, and expected outputs. The Engine's job is to execute that plan faithfully, handling the coordination complexity that arises when a single user intent spans multiple protocols and networks.
Engine does not reinterpret intent or make autonomous decisions. It follows the contract established during planning, with the verification and signing gates enforced at every write step.
## Dependency ordering
Financial operations often have inherent dependencies. You cannot deposit into a yield pool until the required bridge transaction completes. You cannot swap unless the withdrawal has settled.
The Engine resolves these dependencies from the execution schema. Steps are ordered so that each step's preconditions are satisfied by the outputs of previous steps. The dependency graph is computed at plan time and enforced at execution time. Where steps are independent (two swaps on different protocols, a balance check alongside a price query), the architecture supports concurrent execution.
## Step execution
Each write step follows a strict sequence:
1. Simulate the transaction against current network state.
2. Verify the simulation result against the original plan intent.
3. Present a human-readable preview to the user.
4. Handoff for approval and execution.
5. Confirm the result.
Read-only steps execute without user interaction. They resolve automatically and feed their outputs into subsequent steps that depend on them.
## Failure handling
Financial execution cannot silently fail.
The Engine implements controlled recovery paths. If a step fails, ILLA does not retry indefinitely or improvise a workaround. The response depends on the failure type: input errors halt immediately, execution errors are retried up to three times. If the failure persists, execution halts and the failure is surfaced to the user with a clear explanation of what happened and what options are available.
Partial completion is handled explicitly. If a three-step plan completes steps one and two but fails on step three, the user sees exactly where things stand. Already-executed steps are recorded, and the user can choose to resume, modify, or abandon the remaining steps. Nothing is left in an ambiguous state.
## Stateless execution
Statelessness is a security property. In a system handling financial execution, stale state is a liability. The Engine treats each execution as self-contained: the approved plan is the complete source of truth for what should happen.
Statelessness also enables horizontal scaling. Any instance can handle any request without session affinity.
## Multi-chain coordination
ILLA operates natively across multiple networks. A single plan can span several, with the Engine coordinating the sequence and managing handoffs between them.
Cross-chain operations introduce additional complexity: bridge latency, finality differences between chains, and the possibility that conditions on the destination chain change between plan approval and execution arrival. The Engine coordinates cross-network handoffs, with verification applied at each execution boundary. When funds arrive on the destination chain, conditions are re-verified before the next step proceeds.
## Protocol routing
The Engine routes transactions through integrated protocols based on the execution plan, respecting partner-specific routing preferences while optimising for execution quality. Protocol and operation selection are determined during planning. Execution-time routing (for example, optimal swap paths) may be resolved at execution for best available pricing.
As ILLA's capability set grows, the Engine's protocol routing will expand to cover additional financial domains. The execution pattern remains the same: structured plan in, coordinated transactions out.
Integrators can scope protocol access to their specific needs. By default, ILLA routes through the full set of integrated protocols for optimal execution. An integrator can restrict to specific protocols, chains, or asset types to match their product's domain. These preferences are defined at the integration level and enforced at the Engine level.
# Intelligence
Source: https://docs.illa.io/illa/intelligence
ILLA's intelligence layer resolves ambiguous natural language into precise, structured execution plans.
ILLA's intelligence layer is continuously evaluated against financial context, transaction patterns, and failure modes. It resolves ambiguous natural language into precise, structured execution plans.
## Intent classification and routing
When a message arrives, it passes through an intent classifier that evaluates complexity and operation type. The system distinguishes between read-only queries, simple single-step actions, and complex multi-step operations, and handles each differently.
Low-confidence or ambiguous requests are not forced into execution. They fall through to conversational handling, where the system disambiguates rather than assumes.
The classifier also evaluates complexity. A balance check and a multi-protocol rebalancing strategy are fundamentally different operations. The intelligence layer recognises this and routes accordingly.
## Multi-step execution planning
For requests that qualify for planning, the intelligence layer produces a complete execution schema: every step, every dependency, every parameter, generated upfront before anything is acted on.
The output is a deterministic contract: every step, every operation, every dependency is locked before execution begins. Once the plan is approved, no further probabilistic decision-making occurs anywhere in the execution path. Where a step depends on the output of a previous step (for example, bridged amounts feeding into a subsequent swap), the plan uses relative values. The operation is fixed, the exact amount resolves at execution time from the actual output.
An intent like "Pull enough from our earning balance to cover today's invoices, consolidate to USDC, and pay each one on the required network" produces a multi-step plan with dependency ordering, where each step's inputs are derived from the outputs of the previous step. The user sees the full plan, understands what will happen, and approves it as a whole before any step begins execution.
## Fast paths
Not every request needs full planning. The intelligence layer is designed to match effort to complexity.
Simple single-step operations take a fast path. A straightforward transfer or a single swap resolves directly into a one-step plan without a full generation pass. The safety layers (simulation, verification, signing) still apply, but the planning overhead is eliminated.
Read-only requests resolve without requiring approval. The system recognises the difference between observing and acting, and treats them accordingly.
## Disambiguation over assumption
Financial intent is often ambiguous. "Sell \$500 of our NVDA position and move into something safe" could mean a savings protocol, a stablecoin conversion, or a low-risk investment product.
The intelligence layer is evaluated specifically on its ability to identify ambiguity and ask clarifying questions rather than make assumptions. This is one of the core metrics in ILLA's evaluation pipeline: correct refusals and correct disambiguation are measured alongside correct execution.
## Domain-specific evaluation
General-purpose AI evaluation does not apply to financial systems. "Close enough" is not a standard that works when real money is at stake.
ILLA maintains a continuous evaluation pipeline focused on financial correctness. Does the system produce the right plan for the stated intent? Does it correctly refuse when it should? Does it disambiguate rather than assume? Does simulation match execution? The pipeline catches regressions and edge-case failures before they reach production.
The evaluation pipeline runs continuously as the system evolves. New capabilities, protocol integrations, and model updates are tested against it before they reach production.
# Overview
Source: https://docs.illa.io/illa/overview
ILLA provides the specialised planning, safety, and orchestration stack that AI systems need to safely act on financial intent.
## Architecture
ILLA's architecture is organised around a deliberate separation: an opinionated core and agnostic edges.
### Core
The core is where every financial intent is processed. It is opinionated about how AI systems should handle real money: how ambiguity is resolved, how risk is evaluated, how transactions are constructed and verified. Every request, without exception, flows through three layers:
Resolves natural language into precise, structured execution plans.
Architectural separation between probabilistic reasoning and deterministic execution.
Turns approved plans into coordinated transaction sequences.
### Edges
The edges are where ILLA connects to the outside world. They are intentionally agnostic, designed to extend as the landscape evolves.
Aggregate financial operations across an expanding set of protocols and networks.
SDK, API, and MCP Server — how to build with ILLA.
Identity, wallet provisioning, and unified configuration across all ILLA surfaces.
## Why this separation
The agnostic edges make ILLA durable. As new agentic interfaces and wallets emerge, ILLA plugs in. As new financial protocols and rails come online, ILLA integrates.
The opinionated core means the safety properties, planning, and orchestration capabilities are consistent regardless of what connects at the edges. They cannot be replicated by wiring together generic tools.
Each layer is non-trivial alone. Together, they form a system that cannot be replicated by wiring generic tools together.
# Safety & Security
Source: https://docs.illa.io/illa/safety-and-security
How ILLA reconciles irreversible financial actions with probabilistic AI systems.
Financial actions are high-value but dangerous to get wrong. Every design decision starts from one premise: financial actions are irreversible, and AI systems are probabilistic. ILLA's architecture is built to reconcile that tension.
## Plan, then execute
ILLA maintains an architectural separation between planning and execution.
The intelligence layer is used to produce a plan. Once that plan is approved, no further probabilistic decision-making occurs anywhere in the execution path.
The plan is a deterministic contract between what the user approved and what the system will execute. This separation is the foundation that other safety mechanisms build on.
## Simulation and verification
Once a plan is approved, each write step follows the same sequence: simulate, verify, present for execution. ILLA encourages human oversight because trust in agentic finance is earned, not assumed. As trust is established, the approval surface is configurable.
The approval surface is defined by the integration. ILLA provides structured simulation data and approval checkpoints; the integrator determines which actions require explicit confirmation and which resolve automatically.
Transactions are simulated before the user is asked to sign. The simulation produces structured outcome data — which assets move, how much, to where, at what cost — presented by the integration layer as a clear, human readable preview.
After simulation the result is presented alongside the original intent, allowing verification that the outcome matches the request. If the planned outcome and the simulated result diverge, the user is presented with a clear decision: continue, modify, or stop.
## Approval and signing
ILLA never holds private keys or custodies assets. Transaction signing is always controlled by the user's wallet. ILLA produces ready-to-sign transaction data and hands off to the wallet for approval and execution. ILLA's architecture supports session-scoped signing delegation through smart wallets — bounded, revocable authority for flows where step-by-step confirmation creates friction.
## Stateless core
Each request stands on its own, evaluated against current conditions. No session bleed nor cross-request contamination. The stateless core reduces attack surface, with no shared session state to compromise. User context, identity, and preferences persist across sessions through Hub. The safety evaluation path does not.
## Policies and controls
Safety configuration is per-integration. Every ILLA instance operates under a set of policies that define the boundaries of what the system can do.
**Contract and address scoping.** Execution is bounded to ILLA's integrated protocol set, as scoped by the integrator. Transactions route only through vetted, approved protocol contracts. The AI layer cannot reach outside this boundary.
**Spending limits.** Per-transaction limits enforced before simulation. Per-period and per-integration configurability in active development.
**Autonomy policies.** Read-only queries resolve automatically. All write transactions surface for approval by default. Granular policies (auto-approve thresholds, per-capability rules, per-integration configuration) are in active development.
These execution boundaries are enforced at the infrastructure level. Wallet level policies can add a second layer of security.
## Evaluation pipeline
ILLA maintains a domain-specific evaluation pipeline focused on financial correctness: does the system produce the right plan for the stated intent? Does it correctly refuse when it should? Does it disambiguate rather than assume? Does simulation match execution?
"Close enough" is not a standard that applies when real money is at stake.
The evaluation pipeline runs continuously, catching regressions and edge-case failures before they reach production. It runs continuously and evolves alongside the product.
# Wallets & Hub
Source: https://docs.illa.io/illa/wallets-and-hub
ILLA's wallet models and user-facing workspace.
## Wallets
ILLA supports two wallet models depending on the integration.
**Bring your own wallet.** For developers and agents, ILLA plugs into existing wallet infrastructure. The integrator manages its own wallets and key management. ILLA provides aggregated capabilities, intent resolution, planning and safety. Transaction data flows to the integrator's wallet for signing. ILLA never touches the keys.
**ILLA-provisioned wallets.** For end users connecting through MCP connectors or ILLA-owned apps, ILLA provisions an embedded wallet automatically. No wallet setup required. The user authenticates (Google sign-in, passkey, or similar), and a wallet is provisioned and ready.
ILLA-provisioned wallets are self-custodial. ILLA never holds private keys. The wallet infrastructure is provided by specialist partners who handle key management with hardware-backed security. ILLA produces ready-to-sign transaction data and hands off to the wallet. The wallet signs.
These wallets are portable. The same wallet is available across every surface the user authenticates with: Claude and ILLA Apps today, Slack and WhatsApp and more to follow. The user authenticates once, and their wallet and execution capability travel with them.
This separation means ILLA can serve consumer-facing products (where wallet setup is a barrier) and developer-facing products (where the integrator already has wallet infrastructure and wants to keep it) without architectural changes.
## Hub
Hub is ILLA's user-facing workspace. A user's wallet, context, and preferences — unified across every ILLA surface.
A user logs in and sees their wallet(s), transaction history, settings, and preferences. They can upload or link financial context: contacts, invoices, documents, connected accounts. This context becomes persistent financial memory, available across every surface the user interacts with ILLA through.
ILLA Hub is currently in development.
# Welcome to ILLA
Source: https://docs.illa.io/introduction
Financial connectivity, safety and execution infrastructure for AI agents
ILLA is a purpose-built execution system for agentic finance, enabling AI agents to safely execute real money operations. ILLA bridges the gap between probabilistic AI systems and deterministic financial rails, a challenge that requires deeply specialized infrastructure.
ILLA provides a connectivity, planning, safety, and execution stack that sits between an AI system's understanding of financial intent and the actual movement of money.
See how ILLA powers agentic financial products and AI agent execution.
Explore ILLA's architecture: Intelligence, Safety, Engine, and Capabilities.
Integrate via SDK, API, or MCP Server.
Connect ILLA to Claude or use ILLA Apps directly.
# AsyncToolChecker
Source: https://docs.illa.io/sdk/api/async-tool-checker
Track long-running actions triggered by tool execution
`AsyncToolChecker` wraps action-status polling logic.
## Constructor
```ts theme={null}
new AsyncToolChecker({ coreApiProvider })
```
## Methods
### `check`
```ts theme={null}
check({ toolName, protocol, descriptor }): Promise
```
Performs one status check.
```ts theme={null}
const result = await checker.check({
toolName: 'swap',
protocol: 'lifi',
descriptor: { txHash: '0x...' },
})
if (result.isError) {
console.error(result.error)
} else {
console.log(result.response.pollStatus)
}
```
### `subscribe`
```ts theme={null}
subscribe(
params,
{
onStatusChange,
onError,
},
{
interval,
retryThreshold,
maxRetries,
maxDuration,
},
): { unsubscribe(): void }
```
Config units are seconds.
```ts theme={null}
const sub = checker.subscribe(
{
toolName: 'bridge',
protocol: 'lifi',
descriptor: { txHash: '0x...' },
},
{
onStatusChange: ({ current }) => console.log(current.pollStatus),
onError: (error) => console.error(error),
},
{
interval: 5,
retryThreshold: 30,
maxRetries: 5,
maxDuration: 600,
},
)
sub.unsubscribe()
```
# InMemoryCache
Source: https://docs.illa.io/sdk/api/caching/in-memory-cache
Default in‑process cache for development and small apps
A simple `ICache` implementation backed by a JavaScript `Map`. Suitable for development and single‑process deployments.
## Constructor
```ts theme={null}
new InMemoryCache()
```
## Methods
* `get(key): Promise`
* `set(key, value, options?: { ttl?: number /* ms */ }): Promise`
* `del(key): Promise`
Notes:
* TTL is expressed in milliseconds and enforced on `get()`.
* Expired entries are evicted lazily upon access.
# Chat
Source: https://docs.illa.io/sdk/api/chat
Low-level conversational object for session-scoped control
`Chat` represents one conversation and gives direct control over prompts, context, and streaming.
Use `IllaSDK#createChat` unless you need custom dependency wiring.
## Construction
```ts theme={null}
new Chat({
coreApiProvider,
contextManager,
userContext,
id,
asyncToolChecker,
defaultRole,
personalityContext,
modelContext,
})
```
## Properties
### `getId(): string`
Returns the chat identifier.
### `messages: Promise`
Returns current message history from the context manager.
## Core methods
### `sendMessage(prompt, options?)`
```ts theme={null}
sendMessage(
prompt: Prompt | Prompt[],
options?: SendMessageOptions,
): Promise
```
Rules:
* Single `Prompt` must be text-kind.
* `Prompt[]` is for tool-result prompts only.
### `sendMessageStreaming(prompt, options?)`
```ts theme={null}
sendMessageStreaming(
prompt: Prompt,
options?: SendMessageStreamingOptions,
): Promise
```
Streams telemetry and final result via callbacks.
### `getContext()` / `setContext(snapshot)`
```ts theme={null}
getContext(): Promise
setContext(snapshot: ChatContextSnapshot): Promise
```
Read/replace persisted chat context.
### `awaitAction(descriptor)`
```ts theme={null}
awaitAction(descriptor: AwaitableActionDescriptor): Promise
```
Requires `asyncToolChecker` at construction. Descriptor fields are `toolName`, `protocol`, and `args`.
## Example
```ts theme={null}
import {
AsyncToolChecker,
Chat,
ContextManager,
CoreApiProvider,
InMemoryCache,
Prompt,
} from '@illalabs/sdk'
const provider = new CoreApiProvider({
headers: { 'x-api-key': process.env.ILLA_API_KEY! },
})
const contextManager = new ContextManager(new InMemoryCache())
const checker = new AsyncToolChecker({ coreApiProvider: provider })
const chat = new Chat({
coreApiProvider: provider,
contextManager,
asyncToolChecker: checker,
userContext: { address: '0x1234...' },
})
const result = await chat.sendMessage(new Prompt({ text: 'What is my wallet balance?' }))
if (!result.response.isError) {
console.log(result.response.data.text)
}
```
## See also
* [ILLA SDK](/sdk/api/illa-sdk)
* [Streaming events](/sdk/api/streaming-events)
# ContextManager
Source: https://docs.illa.io/sdk/api/context-manager
Persist and manage per‑chat message history and tool config
Stores and retrieves a chat's message history and tools configuration.
## Constructor
```ts theme={null}
new ContextManager(cache: ICache, options?: ContextManagerOptions)
```
| Option | Type | Description |
| -------------------- | ----------------------- | ----------------------------------------------------------- |
| `cacheKeyPrefix` | `string` | Key prefix for cache entries (default: `"illa:sdk:ctx"`) |
| `cacheEntryOptions` | `CacheEntryOptions` | Default TTL settings forwarded to the cache |
| `defaultToolsConfig` | `ToolAutorouterRequest` | Default tool routing config returned when no data is stored |
## Methods
* `getContext(chatId): Promise<{ messages, toolsConfig }>`
* `clearContext(chatId): Promise`
* `setMessages(chatId, messages): Promise`
* `appendMessages(chatId, messages): Promise`
* `setToolsConfig(chatId, toolsConfig): Promise`
* `deleteContext(chatId): Promise`
Notes:
* `clearContext` resets message history and tools config to defaults for a chat but keeps the chat ID registered. Use `deleteContext` to remove everything including the cache entry.
* The manager deep‑clones stored data to avoid accidental mutation by callers.
## Example
```ts theme={null}
const snapshot = await chat.getContext()
await chat.setContext(snapshot)
```
# Errors
Source: https://docs.illa.io/sdk/api/errors
How SDK methods signal failures and which errors are surfaced
SDK integrations handle errors in two channels:
* Returned API errors (`response.isError === true`)
* Thrown exceptions (configuration/runtime issues)
## Returned API errors
These methods return `SendMessageResult`, where API failures are represented as:
```ts theme={null}
{ response: { isError: true, error: CoreApiChatErrorResponse } }
```
Methods:
* `IllaSDK.sendMessage`
* `IllaSDK.sendToolResult`
* `IllaSDK.sendToolResults`
* `Chat.sendMessage`
## Common thrown errors
* `ChatNotFound`
* `UserContextMissing`
* `TelemetryStreamFailed`
* `SSEParse`
* `StreamingHttpError`
* `StreamingResponseBodyNull`
* `StreamingServerError`
Additional thrown errors to account for in advanced flows:
* `CoreApiAuthenticationMissing` (when constructing `CoreApiProvider` without `x-api-key`)
* `ChatAsyncToolCheckerUnavailable` (calling `Chat.awaitAction` without checker)
* `SdkEmptyToolsResultsError` (calling `sendToolResults` with empty array)
## Practical handling pattern
```ts theme={null}
try {
const result = await sdk.sendMessage('What can I do?', {
userContext: { address: '0x1234...' },
})
if (result.response.isError) {
console.error(result.response.error.name, result.response.error.message)
return
}
console.log(result.response.data.text)
} catch (error) {
console.error('SDK/runtime failure:', error)
}
```
## Streaming handling pattern
For `sendMessageStreaming`, handle failures via `onError` callback and transport exceptions.
# Hyperliquid submission
Source: https://docs.illa.io/sdk/api/hyperliquid-submit
Relay pre-signed Hyperliquid exchange payloads with submitHyperliquidAction
`sdk.submitHyperliquidAction` is a thin relay for **pre-signed** Hyperliquid exchange payloads. It
POSTs to `/api/v1/hyperliquid/exchange`, which forwards the already-signed action to Hyperliquid and
returns the mapped result. The SDK never signs — the caller signs the EIP-712 typed data from the
preceding `hyperliquid*` tool result.
```ts theme={null}
submitHyperliquidAction(
request: HyperliquidExchangeSubmitRequest,
options?: { signal?: AbortSignal },
): Promise
```
The request carries the unsigned `action` verbatim, the `nonce` the signature commits to, the
`{ r, s, v }` signature split, the `network` (`'mainnet' | 'testnet'`), and an optional integrity
`hmac`. The response is `{ success, status, oid?, avgPx?, totalSz?, error? }` where `status` is
`'filled' | 'resting' | 'error' | 'rebuilt'`.
```ts theme={null}
import { IllaSDK } from '@illalabs/sdk'
const sdk = new IllaSDK({ apiKey: process.env.ILLA_API_KEY! })
// `actionMetadata` and `signatureRequests` come from a preceding hyperliquid* tool result.
const sigHex = await wallet.signTypedData(signatureRequests[0].typedData)
const res = await sdk.submitHyperliquidAction({
action: actionMetadata.unsignedAction, // unsigned action, verbatim from the tool
nonce: actionMetadata.nonce, // ms nonce the signature commits to
signature: { // Hyperliquid expects the { r, s, v } split
r: `0x${sigHex.slice(2, 66)}`,
s: `0x${sigHex.slice(66, 130)}`,
v: parseInt(sigHex.slice(130, 132), 16),
},
network: actionMetadata.network, // 'mainnet' | 'testnet'
hmac: signatureRequests[0].hmac, // integrity HMAC, if the request carried one
})
if (!res.success) {
console.error('Hyperliquid submission failed:', res.error)
} else {
console.log(res.status, res.oid, res.avgPx, res.totalSz)
}
```
## Related pages
* [ILLA SDK](/sdk/api/illa-sdk)
* [Handling Tool Execution](/sdk/guides/handling-tool-execution)
* [PolymarketService](/sdk/api/polymarket-service)
* [Error handling](/sdk/concepts/error-handling)
# IllaSDK
Source: https://docs.illa.io/sdk/api/illa-sdk
High-level SDK facade for chat sessions, tool loops, and polling
`IllaSDK` is the main SDK client. Use it when you want one object to manage chat sessions, tool-result loops, and async action polling.
## Typical usage
```ts theme={null}
import { IllaSDK } from '@illalabs/sdk'
const sdk = new IllaSDK({
apiKey: process.env.ILLA_API_KEY!,
})
const result = await sdk.sendMessage(
'Swap 1 ETH to USDC on Base',
{ userContext: { address: '0x1234...' } },
)
```
## When to use `IllaSDK`
Use `IllaSDK` if your integration needs:
* a high-level chat client
* chat ID management
* helper methods for returning tool results
* polling utilities for long-running actions
If you need lower-level control over transport or context storage, use [`Chat`](/sdk/api/chat), [`CoreApiProvider`](/sdk/api/providers/core-api-provider), and [`ContextManager`](/sdk/api/context-manager) directly.
## Constructor
```ts theme={null}
new IllaSDK(config, options?)
```
The constructor accepts API transport settings in `config` and context/cache customization in `options`.
### `config`
API key used as `x-api-key` for Core API requests.
Optional Core API base URL override.
HTTP timeout in milliseconds.
Extra headers merged into requests.
Optional Axios client factory.
Optional route overrides (`chat`, `actionStatus`).
### `options`
Provide either:
* `cache` + optional `contextManagerOptions`, or
* `contextManager` (custom implementation)
## Property
### `chatIds: string[]`
List of active chat IDs managed by the instance.
## Core workflow
Most integrations use `IllaSDK` in this order:
1. `sendMessage(...)` to start or continue a chat
2. inspect `response.data.pendingTools`
3. execute the returned tools in your app
4. `sendToolResults(...)` to continue the loop
5. use polling helpers if the action completes asynchronously
## Core methods
### `sendMessage`
```ts theme={null}
sendMessage(
msg: string | Prompt,
context: { chatId: string } | { userContext: UserContext },
chatOptions?: Omit,
options?: { signal?: AbortSignal; onRequestId?: (requestId: string) => void },
): Promise
```
Starts or continues a chat turn.
When creating a new chat via `{ userContext }`, you can include `signerWallet`
for smart-account flows where a separate EOA signs transactions/messages.
This is the main entry point for non-streaming chat requests.
### `sendMessageStreaming`
```ts theme={null}
sendMessageStreaming(
msg: string | Prompt,
context: { chatId: string } | { userContext: UserContext },
options?: SendMessageStreamingOptions,
chatOptions?: Omit,
): Promise
```
Streams telemetry and final result via a single SSE request.
Use this when you want streaming events and the final assistant response from a single request.
### `sendToolResult`
```ts theme={null}
sendToolResult(chatId: string, toolResult: IllaToolOutcomeJSON): Promise
```
Sends one tool outcome.
### `sendToolResults`
```ts theme={null}
sendToolResults(chatId: string, toolResults: IllaToolOutcomeJSON[]): Promise
```
Sends multiple tool outcomes in one request.
Throws `SdkEmptyToolsResultsError` if `toolResults` is empty.
The returned `SendMessageResult` can include:
* Final assistant text (`response.data.text`)
* Additional `pendingTools` (for multi-step tool loops)
Use `sendToolResults` for the common case. It reduces request overhead and keeps the tool loop explicit.
### Chat and context methods
```ts theme={null}
getMessages(chatId: string): Promise
appendMessages(chatId: string, messages: MessageHistoryType): Promise
clearContext(chatId: string): Promise
deleteChat(chatId: string): Promise
createChat(options: ChatOptions, contextManager?: ContextManager): Chat
getChat(chatId: string): Chat
getChatIds(): string[]
```
Use these methods when you need direct access to stored conversation state or want to manage chat instances manually.
### Polling methods
```ts theme={null}
subscribeToToolStatus(
params: { toolName: string; protocol: string; descriptor: BaseLongPollingArgs },
callbacks: AsyncCheckerEvents,
config?: Partial,
): EventSubscription
```
```ts theme={null}
awaitAction(
chatId: string,
descriptor: { toolName: string; protocol: string; args: BaseLongPollingArgs },
): Promise
```
Polling config units are seconds.
Use polling after you have already submitted a transaction or other long-running tool action and want status updates.
### Utilities
```ts theme={null}
getResponseMetadata(result: SendMessageResult): ResponseMetadata
static createNewContextManager(cache: ICache, options: ContextManagerOptions): ContextManager
```
## Tool loop example
```ts theme={null}
import { IllaSDK } from '@illalabs/sdk'
import { IllaToolError, IllaToolOutcome } from '@illalabs/interfaces'
const sdk = new IllaSDK({ apiKey: process.env.ILLA_API_KEY! })
const first = await sdk.sendMessage(
'Swap 1 ETH to USDC on Base',
{
userContext: {
address: '0x1234...',
// Optional signer EOA for smart-account flows
// signerWallet: '0x5678...'
},
},
)
if (first.response.isError) {
throw new Error(first.response.error.message)
}
let pendingTools = [...(first.response.data.pendingTools ?? [])]
while (pendingTools.length > 0) {
const outcomes = await Promise.all(
pendingTools.map(async (tool) => {
try {
const executionResult = await executeTool(tool)
return IllaToolOutcome.success(tool.toolCallId, tool.toolName, executionResult).toJSON()
} catch (error) {
return IllaToolOutcome.error(
tool.toolCallId,
tool.toolName,
IllaToolError.execution(
tool.toolCallId,
tool.toolName,
error instanceof Error ? error.message : 'Execution failed',
),
).toJSON()
}
}),
)
const followUp = await sdk.sendToolResults(first.chatId, outcomes)
if (followUp.response.isError) {
throw new Error(followUp.response.error.message)
}
pendingTools = [...(followUp.response.data.pendingTools ?? [])]
}
```
## Related pages
* [Chat](/sdk/api/chat)
* [AsyncToolChecker](/sdk/api/async-tool-checker)
* [Handling Tool Execution](/sdk/guides/handling-tool-execution)
# PlanStream
Source: https://docs.illa.io/sdk/api/plan-stream
Execute and steer approved execution plans with executePlan, sendStepDecision, and PlanStream
`PlanStream` is the client-side wrapper for consuming planning lifecycle events while an
approved execution plan runs. Use it together with the `IllaSDK` facade methods
`executePlan` (start streaming a plan) and `sendStepDecision` (steer a step that needs a decision).
Planning is an early-access capability. The planning backend is gated on the server side and
may not be enabled for your API key or environment — when it is not, a chat turn behaves like a
normal (non-planning) response and no `plan` is returned. The planning types and event surface
may still change; for example, step decisions currently reuse the `/api/v1/chat/` route pending a
dedicated endpoint.
## How planning fits together
1. A planning-enabled chat turn returns an `ExecutionPlan` on the response (`response.data.plan`),
along with `requiresApproval` and `availableActions`.
2. After the user approves, call `executePlan(plan)` to stream the plan's execution.
3. Attach handlers to the returned `PlanStream` to observe lifecycle events.
4. If a step fails or needs guidance, call `sendStepDecision(...)` to retry, stop, or edit the request.
## `executePlan`
```ts theme={null}
executePlan(
plan: ExecutionPlan,
options?: { signal?: AbortSignal },
): Promise
```
Submits an approved `ExecutionPlan` and returns a `PlanStream` that emits real-time planning
events. Internally this opens an SSE request (`Accept: text/event-stream`) and hands the response
body to a new `PlanStream`.
## `sendStepDecision`
```ts theme={null}
sendStepDecision(
decision: StepDecision,
options?: { signal?: AbortSignal },
): Promise
```
Sends a step-level decision. `StepDecision` has:
ID of the plan the step belongs to.
Version of the plan (positive integer).
1-based step number the decision applies to.
What to do with the step.
New intent text. Required when `action` is `'edit_request'`.
The returned `CoreApiChatResponse` is the same union a chat turn returns. Narrow success with
`"status" in response && response.status === 200`.
## `PlanStream`
`PlanStream` parses SSE frames from a `ReadableStream`, validates each frame against
the shared telemetry-event schema, and dispatches planning events to typed handlers. Unknown event
types are silently ignored for forward compatibility, and stream consumption is deferred to the
next microtask so you can register handlers synchronously right after construction.
```ts theme={null}
new PlanStream(stream: ReadableStream, options?: PlanStreamOptions)
```
`PlanStreamOptions`:
Called when the stream closes normally.
Called on a connection- or parsing-level error.
### Methods
```ts theme={null}
on(eventType: T, handler: (event) => void): void // register a handler (multiple allowed per type)
off(eventType: T, handler): void // remove a handler
close(): void // abort the stream and release resources
isClosed(): boolean // whether the stream has closed
```
The stream returned by `executePlan` is constructed without `PlanStreamOptions`, so it reports
server-sent problems through the `error` event and closes automatically when the stream ends. To
observe connection- or parsing-level failures (network drop, malformed SSE) or to run a close hook,
construct `PlanStream` directly with `onError` / `onClose`.
## Plan event vocabulary
`on()` accepts every planning event plus the stream-control types `connected`, `stream_end`,
and `error`.
**Lifecycle events**
* `plan_generating` — plan generation started (`messageCount`)
* `plan_generated` — plan ready (`planId`, `version`, `stepCount`, `complexity`, `isExecutable`, `autoExecutable`, `hasConflicts`)
* `plan_step_started` — a step began (`planId`, `stepNumber`, `description`, `operationType`)
* `plan_step_retrying` — a step attempt failed and a retry is scheduled (`stepNumber`, `attempt`, `maxRetries`, `phase`)
* `plan_step_completed` — a step finished (`stepNumber`, `status`: `completed` | `failed` | `skipped`)
* `plan_invalidated` — the plan can no longer continue (`reason`, `failedStepNumber`)
* `replan_started` — re-planning started (`previousPlanId`, `reason`, `preservedStepCount`)
* `replan_complete` — re-planning produced a new plan (`previousPlanId`, `newPlanId`, `newVersion`)
* `plan_execution_complete` — execution finished (`status`: `complete` | `partial` | `failed`, `completedSteps`, `totalSteps`)
* `plan_expired` — the plan or planning session expired before the next resume step (`subject`, `blockedAction`, `expiredAt`)
**Runtime (simulation) events**
* `plan_step_simulated` — a write step was simulated (`simulationSuccess`, `simulationSummary`)
* `plan_step_verification_passed` — the verifier accepted the simulation (`confidence`, `reason`)
* `plan_step_verification_failed` — the verifier rejected the simulation (`confidence`, `reason`, `conflicts`, `recommendedAction`)
* `plan_execution_failed` — execution failed fatally (`error`, `phase`)
## `PlanStreamHandlerFailure`
If one of your registered handlers throws while processing an event, `PlanStream` wraps the thrown
error in a `PlanStreamHandlerFailure` and forwards it to `onError`. The failure exposes the
`eventType` whose handler threw and preserves the original error as its `cause`, so a handler
throwing never breaks the stream or other handlers.
## Full example
```ts theme={null}
import { IllaSDK } from '@illalabs/sdk'
import type { ExecutionPlan } from '@illalabs/sdk'
const sdk = new IllaSDK({ apiKey: process.env.ILLA_API_KEY! })
// 1. A planning-enabled chat turn returns a plan to approve.
const turn = await sdk.sendMessage(
'Swap 1 ETH to USDC, then supply the USDC to Aave on Base',
{ userContext: { address: '0x1234...' } },
)
if (turn.response.isError) {
throw new Error(turn.response.error.message)
}
const plan: ExecutionPlan | undefined = turn.response.data.plan
if (!plan) {
// Planning was not enabled for this key/environment — treat as a normal chat turn.
console.log(turn.response.data.text)
} else {
// 2. After the user approves, stream the plan's execution.
const stream = await sdk.executePlan(plan)
stream.on('plan_generated', (event) => {
console.log(`Plan ${event.data.planId}: ${event.data.stepCount} step(s)`)
})
stream.on('plan_step_started', (event) => {
console.log(`Step ${event.data.stepNumber}: ${event.data.description}`)
})
stream.on('plan_step_completed', (event) => {
console.log(`Step ${event.data.stepNumber} → ${event.data.status}`)
// 3. If a step fails, decide how to proceed.
if (event.data.status === 'failed') {
void sdk.sendStepDecision({
planId: event.data.planId,
planVersion: plan.version,
stepNumber: event.data.stepNumber,
action: 'retry',
})
}
})
stream.on('plan_execution_complete', (event) => {
console.log(
`Execution ${event.data.status}: ${event.data.completedSteps}/${event.data.totalSteps}`,
)
stream.close()
})
stream.on('error', (event) => {
console.error('Plan error:', event.data.message)
stream.close()
})
}
```
## Related pages
* [ILLA SDK](/sdk/api/illa-sdk)
* [Streaming Events](/sdk/api/streaming-events)
* [TelemetryClient](/sdk/api/telemetry-client)
# PolymarketService
Source: https://docs.illa.io/sdk/api/polymarket-service
Direct Polymarket CLOB calls outside the chat loop
`PolymarketService` is a direct HTTP client for the Polymarket CLOB endpoints exposed by the ILLA
gateway. Reach it through the `sdk.polymarket` getter when you want to place, cancel, read, redeem,
or withdraw imperatively — without going through the agent and the chat/tool loop.
The instance is created lazily on first access and reused for the lifetime of the SDK instance.
```ts theme={null}
import { IllaSDK } from '@illalabs/sdk'
const sdk = new IllaSDK({ apiKey: process.env.ILLA_API_KEY! })
const polymarket = sdk.polymarket // PolymarketService (lazy, cached)
```
You can pass a `polymarket` block to the `IllaSDK` constructor config to override the base URL,
timeout, headers, or route paths for this service.
## Authentication model
At the ILLA edge these routes pass the same gateway authentication as every other endpoint — an
OAuth session bearer **or** an `x-api-key` (the SDK supplies the `apiKey` you configured). Inside
the API there is no additional user-session binding for these routes; Polymarket-level
authentication happens at the protocol level via a signed `authData` object passed in the request
body — obtain it (and the order signature) beforehand by signing with
`POST /api/v1/signatures/sign`.
`authData` is `{ signature, timestamp, nonce, address }` (all strings); `getOrders` in particular
requires auth data signed immediately before the call.
## Methods
```ts theme={null}
// Each method POSTs to a Polymarket route on the ILLA gateway and resolves to a PolymarketResult.
postOrder(body: PolymarketPostOrderBody, options?):
Promise> // /api/v1/polymarket/post-order
postRedeem(body: PolymarketPostRedeemBody, options?):
Promise> // /api/v1/polymarket/post-redeem
postWithdraw(body: PolymarketPostWithdrawBody, options?):
Promise> // /api/v1/polymarket/post-withdraw
getOrders(body: PolymarketGetOrdersBody, options?):
Promise> // /api/v1/polymarket/get-orders
cancelOrder(body: PolymarketCancelOrderBody, options?):
Promise> // /api/v1/polymarket/cancel-order
getRoutes(): PolymarketRoutes
```
`options` is `{ signal?: AbortSignal }`. `postRedeem` and `postWithdraw` submit signed Safe or
deposit-wallet operations to the Polymarket relayer; both resolve to a `PolymarketSafeExecuteSuccessResponse`.
## `PolymarketResult` envelope
Every method resolves to a discriminated result rather than throwing on request failure:
```ts theme={null}
type PolymarketResult =
| { isError: false; data: T }
| { isError: true; error: PolymarketErrorResponse }
```
`PolymarketErrorResponse` is a union of a validation error
(`{ name: 'PolymarketInvalidParams', statusCode: 400, details.validationErrors[] }`) and an action
error (`{ success: false, error: string }`).
```ts theme={null}
const result = await sdk.polymarket.postOrder({
order: signedOrder,
signature: orderSignature,
authData: { signature, timestamp, nonce, address },
// optional: additionalSignatures, orderType ('GTC' | 'GTD' | 'FOK')
})
if (result.isError) {
console.error(result.error) // PolymarketErrorResponse
} else {
console.log('Order placed:', result.data.orderId, result.data.status)
}
```
## Routing by action
`routePolymarketAction` dispatches a single tagged request to the matching `PolymarketService`
method. `sdk.postPolymarketAction(request, options)` is the built-in facade shortcut that routes
against `sdk.polymarket`.
```ts theme={null}
routePolymarketAction(
service: PolymarketService,
request: PolymarketActionRequest,
options?: PolymarketRequestOptions,
): Promise>
```
`PolymarketActionRequest` is a discriminated union on `action`:
| `action` | Method |
| --------------------------- | -------------- |
| `polymarketPostOrder` | `postOrder` |
| `polymarketPostRedeem` | `postRedeem` |
| `polymarketPostWithdraw` | `postWithdraw` |
| `polymarketPostGetOrders` | `getOrders` |
| `polymarketPostCancelOrder` | `cancelOrder` |
The `polymarketAuth` action is intentionally excluded — it is handled client-side and has no
server endpoint.
```ts theme={null}
import { IllaSDK, routePolymarketAction } from '@illalabs/sdk'
import type { PolymarketActionRequest } from '@illalabs/sdk'
const sdk = new IllaSDK({ apiKey: process.env.ILLA_API_KEY! })
const request: PolymarketActionRequest = {
action: 'polymarketPostCancelOrder',
body: { authData, orderId: '0xorder...' },
}
// Facade shortcut:
const result = await sdk.postPolymarketAction(request)
// ...or route against any PolymarketService instance directly:
// const result = await routePolymarketAction(sdk.polymarket, request)
if (result.isError) {
console.error(result.error)
} else {
console.log('Success:', result.data) // PolymarketActionSuccessResponse
}
```
## `PolymarketService` vs the tool-execution path
Every Polymarket order reaches the CLOB the same way — a `POST` to the Polymarket routes this
service wraps. What differs between the two paths is who *builds* the order, not how it is
submitted:
* **Agent-assisted build.** You send a natural-language message; the model emits a
`predictionMarketsBet` tool call that arrives in `pendingTools` with the signature requests for
the order. Your executor signs and reports back with `sendToolResults` — but the LLM is not in
the loop for submission: your app still posts the signed order to
`/api/v1/polymarket/post-order` (i.e. `sdk.polymarket.postOrder(...)`) itself. See
[Handling Tool Execution](/sdk/guides/handling-tool-execution).
* **Fully imperative.** Your app builds and signs the order and `authData` without involving the
agent, then calls `sdk.polymarket.postOrder(...)` (or routes by action) directly.
Either way `PolymarketService` is the submission surface; the agent path just derives a built,
ready-to-sign order from natural language first.
## Related pages
* [ILLA SDK](/sdk/api/illa-sdk)
* [Submitting Hyperliquid actions](/sdk/api/hyperliquid-submit)
* [Handling Tool Execution](/sdk/guides/handling-tool-execution)
* [Error handling](/sdk/concepts/error-handling)
# Prompt
Source: https://docs.illa.io/sdk/api/prompt
Create and normalize user and tool messages for chat calls
`Prompt` is a validated wrapper for user input and tool-result payloads.
## Constructor
```ts theme={null}
new Prompt(options)
```
Accepted options (discriminated):
* `{ text: string }`
* `{ toolResult: ToolOutcomesType }`
`PromptConfigurationConflict` is thrown if both or neither are set.
## Methods
### getSnapshot
```ts theme={null}
getSnapshot(): PromptSnapshot
```
### getNormalizedSnapshot
```ts theme={null}
getNormalizedSnapshot(): NormalizedPromptSnapshot
```
### toString
```ts theme={null}
toString(): string
```
## Example
```ts theme={null}
const message = new Prompt({ text: 'Show my Base balance' })
```
# CoreApiProvider
Source: https://docs.illa.io/sdk/api/providers/core-api-provider
HTTP transport for ILLA's Core API
`CoreApiProvider` is the low-level HTTP client used by `Chat` and `IllaSDK`.
## Constructor
```ts theme={null}
new CoreApiProvider({
headers: { 'x-api-key': string },
baseURL?: string,
timeout?: number,
routes?: { chat?: string; actionStatus?: string },
httpClientFactory?: (config) => AxiosInstance,
})
```
Throws `CoreApiAuthenticationMissing` when `x-api-key` is missing.
## Methods
### `sendMessage`
```ts theme={null}
sendMessage(
body: CoreApiChatRequest['body'],
options?: {
signal?: AbortSignal
onRequestId?: (requestId: string) => void
},
): Promise
```
Sends a non-streaming chat request.
### `sendMessageStreaming`
```ts theme={null}
sendMessageStreaming(
body: CoreApiChatRequest['body'],
options?: {
signal?: AbortSignal
onRequestId?: (requestId: string) => void
onEvent?: (event: TelemetryEvent) => void
onTextDelta?: (delta: string) => void
onComplete?: (result: ValidatedResultEventData) => void
onError?: (error: Error) => void
},
): Promise
```
Sends a streaming SSE request and emits telemetry/final callbacks.
The canonical streaming path is `POST /api/v1/chat` with `Accept: text/event-stream`.
### `awaitTransaction`
```ts theme={null}
awaitTransaction(
params: LongPollingActionRequest['params'],
options?: { signal?: AbortSignal },
): Promise
```
Checks action status via `/api/v1/actions/check`.
### `getRoutes`
```ts theme={null}
getRoutes(): { chat: string; actionStatus: string }
```
Returns resolved route paths.
## Defaults
* `baseURL`: `https://api.illa.io`
* `routes.chat`: `/api/v1/chat/`
* `routes.actionStatus`: `/api/v1/actions/check`
## Example
```ts theme={null}
const provider = new CoreApiProvider({
headers: { 'x-api-key': process.env.ILLA_API_KEY! },
})
const response = await provider.sendMessage(
{
userContext: { address: '0x1234...' },
prompt: {
role: 'user',
content: [{ type: 'text', text: 'What is my balance?' }],
},
messages: [],
toolResults: [],
toolsConfig: {},
personalityContext: { channel: 'text' },
// languageModel: configured by ILLA Core
},
)
```
# Streaming Events
Source: https://docs.illa.io/sdk/api/streaming-events
SSE event payloads and streaming parser utilities
The SDK exposes utilities and types for parsing SSE output from `/api/v1/chat`
when `Accept: text/event-stream` is set.
## Parser
```ts theme={null}
parseSSEStream(
stream: ReadableStream,
signal?: AbortSignal,
): AsyncGenerator
```
`parseSSEStream` yields typed events as they arrive.
## Event union
`SSEStreamEvent` includes:
* `telemetry`
* `result`
* `error`
* `stream_end`
The SDK also exports:
* `TelemetryStreamEvent`
* `ResultStreamEvent`
* `ErrorStreamEvent`
* `SSEStreamEndEvent`
## Example
```ts theme={null}
const response = await fetch('https://api.illa.io/api/v1/chat', {
method: 'POST',
headers: {
'content-type': 'application/json',
accept: 'text/event-stream',
'x-api-key': process.env.ILLA_API_KEY!,
},
body: JSON.stringify(body),
})
if (!response.body) throw new Error('No stream body')
for await (const event of parseSSEStream(response.body)) {
if (event.type === 'telemetry' && event.data.type === 'text_delta') {
process.stdout.write(event.data.data.delta)
}
if (event.type === 'result') {
console.log('\nfinal text:', event.data.text)
}
}
```
## Streaming errors
* `SSEParse`
* `StreamingHttpError`
* `StreamingResponseBodyNull`
* `StreamingServerError`
## Typical lifecycle
1. `telemetry` events (including `connected` and optional `text_delta`)
2. `result`
3. `stream_end`
4. `error` appears when the stream fails
`/api/v1/chat/stream` may still be available in compatibility deployments, but `/api/v1/chat` is the canonical SDK target.
## See also
* [ILLA SDK](/sdk/api/illa-sdk)
* [Chat](/sdk/api/chat)
# TelemetryClient
Source: https://docs.illa.io/sdk/api/telemetry-client
Browser SSE telemetry client for request-level orchestration tracking
`TelemetryClient` connects to a telemetry SSE endpoint and emits typed telemetry events.
Use it only when your deployment exposes a dedicated `${baseUrl}/telemetry/{requestId}` stream.
The primary public API flow documented in this docs set uses single-request SSE via `sendMessageStreaming`.
`TelemetryClient` is for deployments that separately expose request-scoped telemetry streams.
## Constructor
```ts theme={null}
new TelemetryClient({
baseUrl: string,
onEvent?: (event: TelemetryEvent) => void,
onComplete?: () => void,
onError?: (error: Error) => void,
})
```
## Methods
### `connect(requestId: string): void`
Connects to `${baseUrl}/telemetry/{requestId}`.
### `disconnect(): void`
Closes the active `EventSource` connection.
## State helpers
* `isConnected`
* `isComplete`
* `TelemetryClient.getPhaseFromEvent(event)`
* `TelemetryClient.getPhaseLabel(phase)`
* `TelemetryClient.isTerminalEvent(type)`
## Example
```ts theme={null}
import { TelemetryClient } from '@illalabs/sdk'
const telemetry = new TelemetryClient({
baseUrl: 'https://api.illa.io/api/v1/chat',
onEvent: (event) => console.log(event.type),
onComplete: () => console.log('done'),
onError: (error) => console.error(error),
})
telemetry.connect('request-id')
telemetry.disconnect()
```
## Environment note
`TelemetryClient` depends on `EventSource`. In Node.js, provide an `EventSource` polyfill before use.
# Types and utilities
Source: https://docs.illa.io/sdk/api/types-and-utilities
Key public contracts used when integrating with the SDK
This page documents high-value types used across the ILLA SDK, `Chat`, and polling APIs.
## Core request/response types
### `ChatOptions`
```ts theme={null}
type ChatOptions = {
id?: string
coreApiProvider: ICoreApiProvider
contextManager: IContextManager
defaultRole?: PromptRole
modelContext?: ModelContext
userContext: UserContext
asyncToolChecker?: AsyncToolChecker
personalityContext?: PersonalityContext
}
```
### `SendMessageOptions`
```ts theme={null}
type SendMessageOptions = {
signal?: AbortSignal
onRequestId?: (requestId: string) => void
}
```
### `SendMessageStreamingOptions`
```ts theme={null}
type SendMessageStreamingOptions = {
signal?: AbortSignal
onEvent?: (event: TelemetryEvent) => void
onTextDelta?: (delta: string) => void
onComplete?: (result: ValidatedResultEventData) => void
onError?: (error: Error) => void
}
```
### `SendMessageResult`
```ts theme={null}
type SendMessageResult = {
chatId: string
requestId?: string
prompt: CoreApiChatBodyRequest['prompt']
promptSnapshot: PromptSnapshot | PromptSnapshot[]
messages: MessageHistoryType
toolsConfig: ToolAutorouterRequest
response:
| { isError: false; data: CoreApiChatSuccessResponse }
| { isError: true; error: CoreApiChatErrorResponse }
}
```
## Context and persistence
### `IContextManager`
Key methods:
* `getContext(chatId)`
* `setMessages(chatId, messages)`
* `appendMessages(chatId, messages)`
* `setToolsConfig(chatId, toolsConfig)`
* `clearContext(chatId)`
* `deleteContext(chatId)`
### `ChatContextSnapshot`
```ts theme={null}
type ChatContextSnapshot = {
messages: MessageHistoryType
toolsConfig: ToolAutorouterRequest
}
```
## Polling and async action types
### `AsyncToolCheckerCheckParams`
```ts theme={null}
type AsyncToolCheckerCheckParams = {
toolName: string
protocol: string
descriptor: BaseLongPollingArgs
}
```
### `AwaitableActionDescriptor`
Alias used by `awaitAction`:
```ts theme={null}
type AwaitableActionDescriptor = {
toolName: string
protocol: string
args: BaseLongPollingArgs
}
```
### `PollingConfig`
```ts theme={null}
type PollingConfig = {
interval: number
maxDuration: number
retryThreshold: number
maxRetries: number
}
```
All polling values are seconds.
### `EventSubscription`
```ts theme={null}
type EventSubscription = { unsubscribe(): void }
```
## Pending tool payload
`PendingToolCallType` includes optional simulation metadata and multiple executable input shapes:
```ts theme={null}
type PendingToolCallType = {
type: 'tool-call'
toolCallId: string
toolName: string
input:
| { type: 'SingleTransaction'; value: TransactionWithMetadata }
| { type: 'BatchTransactions'; value: TransactionWithMetadata[] }
| { type: 'SignatureRequests'; value: { signatureRequests: SignatureRequest[] } }
| { type: 'ActionSequence'; value: ActionStep[] }
simulated?: boolean
simulation?: SimulationResult
}
```
### `ActionSequence`
An ordered array of steps that must be executed sequentially. Each step can be a `SingleTransaction`, `BatchTransactions`, or `SignatureRequests`.
```ts theme={null}
{
type: 'ActionSequence',
value: [
{ type: 'BatchTransactions', value: [{ transaction: usdcTransfer }] },
{ type: 'SignatureRequests', value: { signatureRequests: [orderSignature] } },
],
}
```
### `SignatureRequest`
Discriminated union based on `signMethod`:
```ts theme={null}
type SignatureRequest =
| {
signMethod: 'typedData'
id: string
signerAddress: string
description?: string
metadata?: Record
typedData: EIP712TypedData
}
| {
signMethod: 'message'
id: string
signerAddress: string
description?: string
metadata?: Record
rawHash: string
}
```
## Simulation types
When simulation is enabled server-side, pending tools may include a `SimulationResult` describing the expected transaction outcome.
### `SimulationResult`
```ts theme={null}
type SimulationResult = {
willSucceed: boolean
assetChanges: AssetChange[]
gasEstimate: GasEstimate
errorMessage?: string
errorExplanation?: string
simulationId?: string
simulatedAt: number
actionType?: SimulationActionType
sourceChainId?: number
destChainId?: number
actionMetadata?: ActionMetadata
contractInteractions?: ContractInteraction[]
nativeTokenSymbol?: string
}
```
### `AssetChange`
```ts theme={null}
type AssetChange = {
tokenAddress: string
tokenSymbol: string
tokenName: string
decimals: number
rawAmount: string
formattedAmount: string
usdValue: string
direction: 'in' | 'out'
logoUrl?: string
}
```
### `GasEstimate`
```ts theme={null}
type GasEstimate = {
gasLimit: string
gasPrice: string
gasCostNative: string
gasCostUsd: string
}
```
### `SimulationActionType`
```ts theme={null}
type SimulationActionType =
| 'transfer'
| 'swap'
| 'bridge'
| 'supply'
| 'withdraw'
| 'contract'
```
### `ActionMetadata`
```ts theme={null}
type ActionMetadata = {
inputToken?: string
inputAmount?: string
inputUsdValue?: string
outputToken?: string
outputAmount?: string
outputUsdValue?: string
chainName?: string
destChainName?: string
protocol?: string
recipient?: string
}
```
### `ContractInteraction`
```ts theme={null}
type ContractInteraction = {
address: string
name?: string | null
method?: string | null
chainId: number
}
```
## Narrowing result safely
```ts theme={null}
const result = await sdk.sendMessage('Hello', { userContext: { address: '0x1234...' } })
if (result.response.isError) {
console.error(result.response.error.name, result.response.error.message)
} else {
console.log(result.response.data.text)
console.log(result.response.data.pendingTools)
}
```
## See also
* [Errors](/sdk/api/errors)
* [Streaming events](/sdk/api/streaming-events)
# Authentication
Source: https://docs.illa.io/sdk/authentication
Authenticate requests to the Core API with an API key
All requests to ILLA's Core API require an API key.
## Using the ILLA SDK (recommended)
```ts theme={null}
import { IllaSDK } from '@illalabs/sdk'
const sdk = new IllaSDK({
apiKey: process.env.ILLA_API_KEY!,
})
```
## Using CoreApiProvider directly
```ts theme={null}
import { CoreApiProvider } from '@illalabs/sdk'
const provider = new CoreApiProvider({
headers: {
'x-api-key': process.env.ILLA_API_KEY!,
},
})
```
## Best practices
* Store API keys in environment variables.
* Never commit keys to source control.
* Follow your platform/team key lifecycle process.
# Configuration
Source: https://docs.illa.io/sdk/concepts/configuration
Configure the ILLA SDK, CoreApiProvider, ContextManager, and caching
This page summarizes the main configuration surfaces.
## ILLA SDK configuration
The `IllaSDK` class accepts configuration for API connectivity and internal state components.
### Basic configuration
```ts theme={null}
import { IllaSDK } from '@illalabs/sdk'
const sdk = new IllaSDK({
apiKey: process.env.ILLA_API_KEY!,
})
```
### With custom cache
```ts theme={null}
import { IllaSDK, InMemoryCache } from '@illalabs/sdk'
const sdk = new IllaSDK(
{ apiKey: process.env.ILLA_API_KEY! },
{ cache: new InMemoryCache() },
)
```
### With context manager options
```ts theme={null}
import { IllaSDK } from '@illalabs/sdk'
const sdk = new IllaSDK(
{ apiKey: process.env.ILLA_API_KEY! },
{
contextManagerOptions: {
cacheKeyPrefix: 'illa:sdk:ctx',
defaultToolsConfig: {
autoRouter: { swapOrBridge: 'lifi' },
},
},
},
)
```
### With custom context manager
```ts theme={null}
import { IllaSDK, InMemoryCache } from '@illalabs/sdk'
const cache = new InMemoryCache()
const contextManager = IllaSDK.createNewContextManager(cache, {
cacheKeyPrefix: 'my-app:ctx',
defaultToolsConfig: {},
})
const sdk = new IllaSDK(
{ apiKey: process.env.ILLA_API_KEY! },
{ contextManager },
)
```
## CoreApiProvider config
```ts theme={null}
import { CoreApiProvider } from '@illalabs/sdk'
const provider = new CoreApiProvider({
headers: { 'x-api-key': process.env.ILLA_API_KEY! },
timeout: 30_000,
routes: {
chat: '/api/v1/chat/',
actionStatus: '/api/v1/actions/check',
},
})
```
Notes:
* `x-api-key` is required.
* `timeout` is in milliseconds.
* Route overrides are useful for proxies and gateway path rewrites.
## ContextManager options
```ts theme={null}
const contextManager = new ContextManager(new InMemoryCache(), {
cacheKeyPrefix: 'illa:sdk:ctx',
defaultToolsConfig: {
autoRouter: { swapOrBridge: 'lifi' },
},
})
```
## Cache entry TTL
```ts theme={null}
await cache.set('key', value, { ttl: 5 * 60_000 })
```
TTL values are milliseconds.
# Error Handling
Source: https://docs.illa.io/sdk/concepts/error-handling
Understand runtime errors and SDK responses
The SDK uses both thrown errors and structured results depending on the API.
## Handling ILLA SDK errors
When using the `IllaSDK` class, errors are returned as structured results.
### sendMessage Error Handling
```ts theme={null}
import { IllaSDK } from '@illalabs/sdk'
const sdk = new IllaSDK({
apiKey: process.env.ILLA_API_KEY!
})
const result = await sdk.sendMessage(
'Swap 1 ETH for USDC',
{ userContext: { address: '0x1234...' } }
)
if (!result.response.isError) {
// Success: access the response data
console.log('Text:', result.response.data.text)
console.log('Messages:', result.messages)
// Check for pending tools
if (result.response.data.pendingTools) {
console.log('Tools to execute:', result.response.data.pendingTools)
}
} else {
// Error: inspect the error object
console.error('Error occurred:', result.response.error)
}
```
### sendToolResult Error Handling
```ts theme={null}
try {
const result = await sdk.sendToolResult(chatId, toolResult)
if (!result.response.isError) {
console.log('Success:', result.response.data.text)
} else {
console.error('Error:', result.response.error)
}
} catch (error) {
// Thrown when chatId doesn't exist
if (error instanceof ChatNotFound) {
console.error('Chat not found:', error.chatId)
}
}
```
### getMessages Error Handling
```ts theme={null}
import { ChatNotFound } from '@illalabs/sdk'
try {
const messages = await sdk.getMessages(chatId)
console.log('Messages:', messages)
} catch (error) {
if (error instanceof ChatNotFound) {
console.error('Chat not found:', error.chatId)
}
}
```
## Advanced: Lower-Level Component Errors
### Thrown errors (public)
* `PromptConfigurationConflict`: Creating `Prompt` with both or neither `text`/`toolResult`
* `CoreApiAuthenticationMissing`: Constructing `CoreApiProvider` without `x-api-key`
* `CoreApiMethodNotImplemented`: Server returned HTTP 501 to a provider call
```ts theme={null}
import { CoreApiProvider, Prompt } from '@illalabs/sdk'
try {
new Prompt({
text: 'hi',
})
} catch (e) {
// handle misconfiguration
}
try {
new CoreApiProvider({ headers: {} as any })
} catch (e) {
// missing auth
}
```
### Structured results
* `chat.sendMessage(prompt)` returns an object with `status` and either `response` or `error`
* `AsyncToolChecker.check(...)` returns a discriminated union `{ isError: boolean, response?: ..., error?: ... }`
Always inspect the shape before using the payload.
```ts theme={null}
const res = await chat.sendMessage(prompt)
if (!res.response.isError) {
// success: access response text and messages
console.log('Text:', res.response.data.text)
console.log('Messages:', res.messages)
// Check for pending tools
if (res.response.data.pendingTools) {
console.log('Pending tools:', res.response.data.pendingTools)
}
} else {
// error: inspect error fields
console.error('Error:', res.response.error)
}
```
### Long-running actions
* `Chat.awaitAction(...)` throws `ChatAsyncToolCheckerUnavailable` if no `AsyncToolChecker` is configured (note: this error class is not exported)
* `AsyncToolChecker.subscribe(...)` delivers issues via `onError` callback (e.g., timeouts, max retries) rather than throwing
```ts theme={null}
const sub = asyncToolChecker.subscribe(
{
/* ... */
},
{
onStatusChange: (ev) => console.log(ev),
onError: (err) => console.error('Polling failed', err),
}
)
// later
sub.unsubscribe()
```
## Error Handling Best Practices
* Wrap SDK calls in try/catch when constructing objects or when a method documents it may throw
* Prefer discriminated unions and status codes for flow control over exceptions from network errors
* Log unexpected error shapes for observability
# TypeScript Support
Source: https://docs.illa.io/sdk/concepts/typescript-support
Types you can import and how to use them effectively
## TypeScript support
The SDK is written in TypeScript and ships full type definitions. Most apps only need classes, but you can also import types for stronger guarantees.
## Publicly exported classes
```ts theme={null}
import {
IllaSDK,
Chat,
Prompt,
ContextManager,
CoreApiProvider,
InMemoryCache,
AsyncToolChecker,
ChatNotFound,
UserContextMissing,
} from '@illalabs/sdk'
```
## Publicly exported types
```ts theme={null}
import type {
// SDK configuration
illaSDKConfig,
SendMessageContext,
// Context management
ChatContextSnapshot,
ContextManagerOptions,
IContextManager,
// Caching
CacheEntryOptions,
ICache,
} from '@illalabs/sdk'
```
Note: Additional types are available from `@illalabs/interfaces` package for tool execution, message history, and user context.
## Usage Examples
### Using the ILLA SDK with types
```ts theme={null}
import { IllaSDK } from '@illalabs/sdk'
import type { illaSDKConfig, SendMessageContext } from '@illalabs/sdk'
const config: illaSDKConfig = {
apiKey: process.env.ILLA_API_KEY!,
}
const sdk = new IllaSDK(config)
// Type-safe message context
const context: SendMessageContext = {
userContext: { address: '0x1234...' }
}
const result = await sdk.sendMessage('Hello', context)
```
### Customize context manager
```ts theme={null}
import type { ContextManagerOptions } from '@illalabs/sdk'
const options: ContextManagerOptions = {
cacheKeyPrefix: 'illa:sdk:ctx',
defaultToolsConfig: {
autoRouter: { swapOrBridge: 'lifi' }
}
}
const ctx = new ContextManager(new InMemoryCache(), options)
```
### TTL with CacheEntryOptions
```ts theme={null}
import type { CacheEntryOptions } from '@illalabs/sdk'
const options: CacheEntryOptions = { ttl: 60_000 }
await cache.set('key', value, options)
```
### Using interfaces from @illalabs/interfaces
```ts theme={null}
import type {
MessageHistoryType,
PendingToolCallType,
IllaToolOutcomeJSON,
UserContext,
} from '@illalabs/interfaces'
const userContext: UserContext = { address: '0x1234...' }
const messages: MessageHistoryType = await sdk.getMessages(chatId)
```
### Simulation and signing types
```ts theme={null}
import type {
SimulationResult,
AssetChange,
GasEstimate,
ActionMetadata,
ContractInteraction,
SimulationActionType,
SignatureRequest,
EIP712TypedData,
} from '@illalabs/interfaces'
```
### Supported constants and values
```ts theme={null}
import {
SUPPORTED_ACTIONS,
SUPPORTED_CHAINS,
SUPPORTED_CHAIN_IDS,
SUPPORTED_OPENAI_MODELS,
SUPPORTED_OPENROUTER_MODELS,
type SupportedAction,
type SupportedChain,
type SupportedChainId,
type SupportedOpenAIModel,
type SupportedOpenRouterModel,
} from '@illalabs/interfaces'
```
# Awaiting actions & polling
Source: https://docs.illa.io/sdk/guides/awaiting-actions-and-polling
Track long-running blockchain actions triggered by tool execution
Use these APIs when a tool execution continues asynchronously after submission.
## Option 1: Await one action result
Use `sdk.awaitAction` when you want a single promise-based result tied to a chat.
```ts theme={null}
const result = await sdk.awaitAction(chatId, {
toolName: 'swap',
protocol: 'lifi',
args: { txHash: '0xabc...' },
})
if (result.isError) {
console.error('Polling failed:', result.error)
} else {
console.log('Status:', result.response.pollStatus)
}
```
## Option 2: Subscribe to status transitions
Use `sdk.subscribeToToolStatus` for UI progress updates.
```ts theme={null}
const subscription = sdk.subscribeToToolStatus(
{
toolName: 'bridge',
protocol: 'lifi',
descriptor: { txHash: '0xabc...' },
},
{
onStatusChange: ({ previous, current }) => {
console.log('prev:', previous?.pollStatus, 'curr:', current.pollStatus)
},
onError: (error) => {
console.error('Polling error:', error)
},
},
{
interval: 5,
retryThreshold: 30,
maxRetries: 5,
maxDuration: 600,
},
)
// Later
subscription.unsubscribe()
```
## Option 3: Use AsyncToolChecker directly
For lower-level control, use `AsyncToolChecker`.
```ts theme={null}
import { AsyncToolChecker } from '@illalabs/sdk'
const checker = new AsyncToolChecker({ coreApiProvider: provider })
const once = await checker.check({
toolName: 'defiWithdraw',
protocol: 'aave',
descriptor: { txHash: '0xabc...' },
})
```
## Descriptor fields
* `toolName`: action key (`swap`, `bridge`, `defiSupply`, `defiWithdraw`)
* `protocol`: provider key (`lifi`, `aave`, ...)
* For `awaitAction`: `args`
* For `subscribeToToolStatus` / `AsyncToolChecker.check`: `descriptor`
## Polling config units
`interval`, `retryThreshold`, and `maxDuration` are **seconds**.
# Building a chat flow
Source: https://docs.illa.io/sdk/guides/building-a-chat-flow
Step-by-step guide to integrate ILLA SDK in your app
This guide walks you through creating a complete chat flow with the ILLA SDK.
## Using the ILLA SDK (recommended)
The simplest way to build a chat flow is with the `IllaSDK` class.
### 1) Initialize the SDK
```ts theme={null}
import { IllaSDK } from '@illalabs/sdk'
const sdk = new IllaSDK({
apiKey: process.env.ILLA_API_KEY!
})
```
### 2) Start a conversation
```ts theme={null}
const result = await sdk.sendMessage(
'What can I do on Base?',
{ userContext: { address: '0xYourAddress' } }
)
// Save the chatId to continue the conversation
const chatId = result.chatId
if (!result.response.isError) {
console.log('Assistant:', result.response.data.text)
}
```
### 3) Continue the conversation
```ts theme={null}
const followUp = await sdk.sendMessage(
'Swap 0.1 ETH to USDC',
{ chatId }
)
if (!followUp.response.isError && followUp.response.data.pendingTools) {
// Handle tool execution - see Handling Tool Execution guide
console.log('Tools to execute:', followUp.response.data.pendingTools)
}
```
### 4) Retrieve message history
```ts theme={null}
const messages = await sdk.getMessages(chatId)
console.log('Conversation history:', messages)
```
### 5) Multiple chats
```ts theme={null}
// Track multiple conversations
const chatIds = sdk.chatIds
console.log('Active chats:', chatIds)
// Send messages to different chats
await sdk.sendMessage('Hello', { chatId: chatIds[0] })
await sdk.sendMessage('Hi there', { chatId: chatIds[1] })
```
## Advanced: Using Chat class
For more control, you can use the lower-level `Chat` class directly.
### 1) Initialize the components
```ts theme={null}
import {
Chat,
ContextManager,
CoreApiProvider,
InMemoryCache,
} from '@illalabs/sdk'
const provider = new CoreApiProvider({
headers: { 'x-api-key': process.env.ILLA_API_KEY! },
})
const context = new ContextManager(new InMemoryCache())
const chat = new Chat({
coreApiProvider: provider,
contextManager: context,
userContext: { address: '0xYourAddress' },
// optional:
// id: 'my-chat-id',
// defaultRole: 'user',
})
```
### 2) Send messages
```ts theme={null}
import { Prompt } from '@illalabs/sdk'
const first = await chat.sendMessage(
new Prompt({ text: 'What can I do on Base?' })
)
// Inspect returned shape
if (!first.response.isError) {
console.log('Assistant:', first.response.data.text)
}
// Follow-up
const second = await chat.sendMessage(
new Prompt({ text: 'Swap 0.1 ETH to USDC' })
)
// Handle potential tool execution
if (!second.response.isError && second.response.data.pendingTools) {
console.log('Tools to execute:', second.response.data.pendingTools)
}
```
### 3) Persisted context
The chat automatically persists message history using the `ContextManager`. You can snapshot or restore it as needed.
```ts theme={null}
const snapshot = await chat.getContext()
// ... store snapshot ...
await chat.setContext(snapshot)
```
### 4) Long‑running actions (optional)
If your prompts can trigger on-chain actions, add an `AsyncToolChecker` and use `chat.awaitAction` or subscribe for progress.
See: [Awaiting actions & polling](/sdk/guides/awaiting-actions-and-polling)
# Custom cache
Source: https://docs.illa.io/sdk/guides/custom-cache
Implement the ICache interface to plug in Redis or your store
`ContextManager` accepts any `ICache` implementation. This allows swapping the default in-memory cache with Redis, a KV store, or your own logic.
## ICache interface
```ts theme={null}
import type { CacheEntryOptions, ICache } from '@illalabs/sdk'
class MyCache implements ICache {
private store = new Map()
async get(key: string): Promise {
const rec = this.store.get(key)
if (!rec) return undefined
if (rec.expiresAt && Date.now() > rec.expiresAt) {
this.store.delete(key)
return undefined
}
return rec.value as T
}
async set(
key: string,
value: unknown,
options?: CacheEntryOptions
): Promise {
const expiresAt = options?.ttl ? Date.now() + options.ttl : undefined
this.store.set(key, { value, expiresAt })
}
async del(key: string): Promise {
this.store.delete(key)
}
}
```
## Use it with ContextManager
```ts theme={null}
const context = new ContextManager(new MyCache(), {
cacheKeyPrefix: 'illa:sdk:ctx'
})
```
# Custom provider & routes
Source: https://docs.illa.io/sdk/guides/custom-provider-and-routes
Override base URL, routes, and inject a custom Axios instance
Customize `CoreApiProvider` for observability, auth, or environment routing.
Advanced/optional: skip this unless you have a concrete infrastructure requirement
(for example proxy routing, custom gateway paths, or Axios interceptors).
## Override base URL and routes
```ts theme={null}
import { CoreApiProvider } from '@illalabs/sdk'
const provider = new CoreApiProvider({
headers: { 'x-api-key': process.env.ILLA_API_KEY! },
baseURL: 'https://api.illa.io',
routes: {
chat: '/api/v1/chat/',
actionStatus: '/api/v1/actions/check',
},
})
```
## Inject a custom Axios client
```ts theme={null}
import { CoreApiProvider } from '@illalabs/sdk'
import axios from 'axios'
const provider = new CoreApiProvider({
headers: { 'x-api-key': process.env.ILLA_API_KEY! },
httpClientFactory: (config) => {
const client = axios.create(config)
client.interceptors.request.use((req) => {
console.debug('[core-api] =>', req.method, req.url)
return req
})
client.interceptors.response.use((res) => {
console.debug('[core-api] <=', res.status, res.config.url)
return res
})
return client
},
})
```
# Handling Tool Execution
Source: https://docs.illa.io/sdk/guides/handling-tool-execution
Execute pending tools and return outcomes to complete the chat loop
When ILLA needs your application to execute an on-chain action, the response includes `pendingTools`. Your app becomes the executor: run those tools, collect the result, and send the outcome back with `sendToolResults`.
## What this guide covers
* how to read `pendingTools`
* how to run the standard execution loop
* how to handle `ActionSequence` and signature requests
* how to use simulation previews safely
* when to use polling helpers
## Read `pendingTools`
Each item in `pendingTools` includes:
* `toolCallId`
* `toolName`
* `input`
* `simulated` (optional)
* `simulation` (optional simulation preview payload)
`input.type` can be:
* `SingleTransaction`
* `BatchTransactions`
* `SignatureRequests`
* `ActionSequence`
`tool.input` is always the execution source of truth. Optional simulation fields are for display and review.
## Run the standard execution loop
Use batched outcome submission (`sendToolResults`) and continue until no more tools are returned.
```ts theme={null}
import { IllaSDK } from '@illalabs/sdk'
import {
IllaToolError,
IllaToolOutcome,
type IllaToolOutcomeJSON,
type PendingToolCallType,
} from '@illalabs/interfaces'
const sdk = new IllaSDK({ apiKey: process.env.ILLA_API_KEY! })
async function executePendingTool(tool: PendingToolCallType): Promise {
try {
// Your executor should handle:
// SingleTransaction / BatchTransactions / SignatureRequests / ActionSequence
const executionResult = await walletExecutor.execute(tool.input)
return IllaToolOutcome
.success(tool.toolCallId, tool.toolName, executionResult)
.toJSON()
} catch (error) {
return IllaToolOutcome
.error(
tool.toolCallId,
tool.toolName,
IllaToolError.execution(
tool.toolCallId,
tool.toolName,
error instanceof Error ? error.message : 'Unknown execution error',
),
)
.toJSON()
}
}
async function runToolLoop(
chatId: string,
initialTools: ReadonlyArray,
): Promise {
let pendingTools = [...initialTools]
while (pendingTools.length > 0) {
const outcomes = await Promise.all(pendingTools.map(executePendingTool))
const followUp = await sdk.sendToolResults(chatId, outcomes)
if (followUp.response.isError) {
throw new Error(followUp.response.error.message)
}
pendingTools = [...(followUp.response.data.pendingTools ?? [])]
}
}
```
This is the default pattern for SDK integrations.
## Handle `ActionSequence`
When `input.type` is `ActionSequence`, the value is an ordered array of steps. Execute steps sequentially and preserve the server-defined order.
```ts theme={null}
async function executeActionSequence(steps: ActionStep[]): Promise {
const results = []
for (const step of steps) {
switch (step.type) {
case 'SingleTransaction':
results.push(await sendTransaction(step.value.transaction))
break
case 'BatchTransactions':
results.push(await sendBatchTransactions(step.value))
break
case 'SignatureRequests':
results.push(await collectSignatures(step.value.signatureRequests))
break
}
}
return results
}
```
A common pattern is a prediction-market flow that transfers funds first and collects a signature second.
## Handle signature requests
Some tools return `SignatureRequests` directly, or as a step inside `ActionSequence`. Signature requests use either EIP-712 typed data (`signMethod: 'typedData'`) or raw hash signing (`signMethod: 'message'`).
Your executor should collect signatures and return them in the tool result payload, then continue the loop normally.
Common flows include:
* `predictionMarketsBet`
* `predictionMarketsRedeem`
* `polymarketPostOrder`
* `polymarketPostRedeem`
## Use simulation previews for review UI
When simulation is enabled server-side, pending tools may include a `simulation` object that you can use to build a confirmation UI before execution.
```ts theme={null}
for (const tool of pendingTools) {
if (!tool.simulation) continue
const sim = tool.simulation
if (!sim.willSucceed) {
console.warn('Simulation predicts failure:', sim.errorExplanation)
}
for (const change of sim.assetChanges) {
const sign = change.direction === 'out' ? '-' : '+'
console.log(`${sign}${change.formattedAmount} ${change.tokenSymbol} ($${change.usdValue})`)
}
console.log(
`Gas: ${sim.gasEstimate.gasCostNative} ${sim.nativeTokenSymbol ?? 'ETH'} ($${sim.gasEstimate.gasCostUsd})`,
)
}
```
Key fields worth surfacing:
* `willSucceed`
* `assetChanges`
* `gasEstimate`
* `actionType`
* `contractInteractions`
* `actionMetadata`
Treat simulation as display-only metadata. `tool.input` remains the execution source of truth.
## End-to-end example
```ts theme={null}
const first = await sdk.sendMessage(
'Swap 1 ETH to USDC on Base',
{ userContext: { address: '0x1234...' } },
)
if (first.response.isError) {
throw new Error(first.response.error.message)
}
await runToolLoop(first.chatId, first.response.data.pendingTools ?? [])
const finalMessages = await sdk.getMessages(first.chatId)
console.log(finalMessages)
```
## Track long-running tools
For tools that may take longer after submission (for example bridge completion), use polling helpers with the transaction hash:
```ts theme={null}
const subscription = sdk.subscribeToToolStatus(
{
toolName: 'bridge',
protocol: 'lifi',
descriptor: { txHash: '0x...' },
},
{
onStatusChange: ({ current }) => console.log(current.pollStatus),
onError: (error) => console.error(error),
},
{
interval: 5,
retryThreshold: 30,
maxRetries: 5,
maxDuration: 600,
},
)
subscription.unsubscribe()
```
## Common mistakes
1. Ignoring failed tools instead of returning an error outcome.
2. Executing `ActionSequence` steps out of order.
3. Using simulation output as the execution payload.
4. Sending many single tool results when one batched call would work.
## Related pages
* [ILLA SDK API](/sdk/api/illa-sdk)
* [Simulation previews](/sdk/guides/simulation-previews)
* [Types and utilities](/sdk/api/types-and-utilities)
* [Awaiting actions & polling](/sdk/guides/awaiting-actions-and-polling)
* [Error handling](/sdk/concepts/error-handling)
# Request cancellation
Source: https://docs.illa.io/sdk/guides/request-cancellation
Abort in-flight chat calls and stop polling safely
Cancellation is supported at both request and polling levels.
## Cancel `sendMessage`
`IllaSDK.sendMessage` accepts an abort signal via the fourth argument.
```ts theme={null}
const controller = new AbortController()
const pending = sdk.sendMessage(
'Check my balance',
{ chatId },
undefined,
{ signal: controller.signal },
)
setTimeout(() => controller.abort(), 1_000)
const result = await pending
if (result.response.isError) {
console.error('Request failed or was aborted:', result.response.error)
}
```
## Cancel `sendMessageStreaming`
`sendMessageStreaming` accepts `signal` in its streaming options.
```ts theme={null}
const controller = new AbortController()
const pending = sdk.sendMessageStreaming(
'Swap 0.1 ETH to USDC',
{ chatId },
{
signal: controller.signal,
onEvent: (event) => console.log(event.type),
onError: (error) => console.error(error),
},
)
setTimeout(() => controller.abort(), 1_000)
try {
await pending
} catch (error) {
console.error('Streaming request stopped:', error)
}
```
## Cancel provider-level requests
`CoreApiProvider.sendMessage` and `CoreApiProvider.awaitTransaction` also accept `signal`.
```ts theme={null}
const ac = new AbortController()
const pending = provider.sendMessage(body, { signal: ac.signal })
ac.abort()
await pending
```
Apply the same pattern to `provider.awaitTransaction(params, { signal: ac.signal })`.
## Stop polling subscriptions
`subscribeToToolStatus` and `AsyncToolChecker.subscribe` return a subscription with `unsubscribe()`.
```ts theme={null}
const sub = sdk.subscribeToToolStatus(
{
toolName: 'swap',
protocol: 'lifi',
descriptor: { txHash: '0x...' },
},
{
onStatusChange: ({ current }) => console.log(current.pollStatus),
onError: (error) => console.error(error),
},
)
sub.unsubscribe()
```
## Notes
* `sendToolResult` and `sendToolResults` do not currently accept an abort signal.
* Always wire cancellation to route changes and component unmounts.
# Tools configuration
Source: https://docs.illa.io/sdk/guides/tools-configuration
Control which tools the assistant can use and preferred providers
Tool routing configuration is modeled by `ToolAutorouterRequest` from `@illalabs/interfaces`.
Start with SDK defaults unless you need deterministic routing behavior.
Most integrations should not define the full autorouter config initially.
## Using the ILLA SDK
Set default routing via `contextManagerOptions.defaultToolsConfig`.
```ts theme={null}
import { IllaSDK } from '@illalabs/sdk'
const sdk = new IllaSDK(
{ apiKey: process.env.ILLA_API_KEY! },
{
contextManagerOptions: {
defaultToolsConfig: {
autoRouter: {
swapOrBridge: 'lifi',
defi: { lending: 'aave' },
},
},
},
},
)
```
## Per-chat configuration with a custom ContextManager
```ts theme={null}
import { IllaSDK, InMemoryCache } from '@illalabs/sdk'
const cache = new InMemoryCache()
const contextManager = IllaSDK.createNewContextManager(cache, {
defaultToolsConfig: {
autoRouter: {
swapOrBridge: 'lifi',
},
},
})
const sdk = new IllaSDK(
{ apiKey: process.env.ILLA_API_KEY! },
{ contextManager },
)
const chat = sdk.createChat({
userContext: { address: '0x1234...' },
})
```
## Read current configuration
```ts theme={null}
const snapshot = await sdk.getChat(chatId).getContext()
console.log(snapshot.toolsConfig)
```
## Update configuration on an existing chat
```ts theme={null}
const chat = sdk.getChat(chatId)
const snapshot = await chat.getContext()
await chat.setContext({
...snapshot,
toolsConfig: {
autoRouter: {
swapOrBridge: 'lifi',
defi: { lending: 'aave' },
},
},
})
```
## Notes
* Configuration is persisted in the chat context.
* `ContextManager` deep-clones stored config to avoid accidental mutation.
# SDK Overview
Source: https://docs.illa.io/sdk/introduction
Introduction to the ILLA SDK and its core building blocks
The ILLA SDK is the fastest way to add ILLA to your product. It wraps the Core API with chat session management, tool-result loops, context persistence, and polling helpers so you can focus on your product logic instead of request orchestration.
Use `IllaSDK` when you want one client that can:
* start and continue chats
* return `pendingTools` for your app to execute
* send tool outcomes back to ILLA
* poll long-running actions
* manage chat context for you
Use the lower-level SDK components only if you need custom transport, custom context storage, or tighter control over how requests are assembled.
## Install
```bash theme={null}
npm install @illalabs/sdk
```
## First request
Start with `IllaSDK`. It is the primary integration surface for most applications.
```ts theme={null}
import { IllaSDK } from '@illalabs/sdk'
const sdk = new IllaSDK({
apiKey: process.env.ILLA_API_KEY!
})
const result = await sdk.sendMessage(
'Swap 0.5 ETH to USDC',
{ userContext: { address: '0xYourAddress' } }
)
if (!result.response.isError) {
console.log(result.response.data.text)
}
```
## What the SDK gives you
* `IllaSDK` for the full chat and tool loop
* `Chat` for lower-level request handling
* `CoreApiProvider` for HTTP transport and route overrides
* `ContextManager` for persisted chat state
* `Prompt` for structured user and tool messages
* `AsyncToolChecker` for long-running action polling
## Use lower-level components when needed
If you need custom transport, storage, or request construction, you can compose the building blocks directly:
```ts theme={null}
import {
Chat,
ContextManager,
CoreApiProvider,
InMemoryCache,
Prompt,
} from '@illalabs/sdk'
const provider = new CoreApiProvider({
headers: { 'x-api-key': process.env.ILLA_API_KEY! },
})
const context = new ContextManager(new InMemoryCache())
const chat = new Chat({
coreApiProvider: provider,
contextManager: context,
userContext: { address: '0xYourAddress' },
})
const prompt = new Prompt({ text: 'Swap 0.5 ETH to USDC' })
const result = await chat.sendMessage(prompt)
if (!result.response.isError) {
console.log(result.response.data.text)
}
```
## Next steps
* Read the [Authentication](/sdk/authentication) guide
* Follow the [SDK Quickstart](/sdk/quickstart)
* Learn the tool loop in [Handling tool execution](/sdk/guides/handling-tool-execution)
# Quickstart
Source: https://docs.illa.io/sdk/quickstart
Build your first chat flow with the ILLA SDK
This guide shows the shortest path to a working ILLA integration with `IllaSDK`.
By the end, you will be able to:
* initialize the SDK
* send a user message
* inspect `pendingTools`
* continue the same chat
## Before you start
* Node.js 20+
* An ILLA API key
* A wallet address for `userContext.address`
## 1. Install
```bash theme={null}
npm install @illalabs/sdk
```
## 2. Create the client
```ts theme={null}
import { IllaSDK } from '@illalabs/sdk'
const sdk = new IllaSDK({
apiKey: process.env.ILLA_API_KEY!
})
```
`IllaSDK` is stateful. It creates chats, remembers active chat IDs, and exposes helpers for tool execution and polling.
## 3. Send the first message
```ts theme={null}
const result = await sdk.sendMessage(
'What can I do on Base today?',
{
userContext: {
address: '0xYourAddress',
// Optional: EOA signer for smart-account flows
// signerWallet: '0xYourSignerAddress'
}
}
)
if (!result.response.isError) {
console.log('Assistant:', result.response.data.text)
console.log('Chat ID:', result.chatId) // Save this to continue the conversation
// Check if there are pending tools to execute
if (result.response.data.pendingTools) {
console.log('Pending tools:', result.response.data.pendingTools)
}
} else {
console.error('Error:', result.response.error)
}
```
If the assistant returns `pendingTools`, your app is expected to execute those actions and send the outcomes back with `sendToolResults`.
## 4. Continue the same chat
```ts theme={null}
// Use the chatId from the previous message to continue
const followUp = await sdk.sendMessage(
'Swap 1 ETH for USDC',
{ chatId: result.chatId }
)
if (!followUp.response.isError) {
console.log('Assistant:', followUp.response.data.text)
}
```
## What to do next
* Handle tool execution: [Handling tool execution](/sdk/guides/handling-tool-execution)
* Build a complete flow: [Building a chat flow](/sdk/guides/building-a-chat-flow)
* Handle errors properly: [Error handling](/sdk/concepts/error-handling)
## Use lower-level components if needed
If you need custom transport or custom context persistence, you can use the lower-level components directly:
```ts theme={null}
import {
Chat,
ContextManager,
CoreApiProvider,
InMemoryCache,
Prompt,
} from '@illalabs/sdk'
const provider = new CoreApiProvider({
headers: { 'x-api-key': process.env.ILLA_API_KEY! },
})
const context = new ContextManager(new InMemoryCache())
const chat = new Chat({
coreApiProvider: provider,
contextManager: context,
userContext: {
address: '0xYourAddress',
// Optional signer EOA for smart-account + signature flows
// signerWallet: '0xYourSignerAddress'
},
})
const prompt = new Prompt({ text: 'What can I do on Base today?' })
const res = await chat.sendMessage(prompt)
if (!res.response.isError) {
console.log('Assistant:', res.response.data.text)
}
```
See the [Chat API reference](/sdk/api/chat) for the lower-level surface.
# Tools & Providers Reference
Source: https://docs.illa.io/sdk/reference/tools-and-providers
Reference for tool names, provider keys, and routing defaults
Use this page when you need the exact names that appear in SDK configuration, request payloads, or runtime responses.
The name lists on this page are generated from the `@illalabs/interfaces` constants (`scripts/generate-reference.mjs`), so they match the shipped SDK version.
Valid `autoRouter` values today: `swapOrBridge: 'lifi' | 'aerodrome'`, `defi.lending: 'aave' | 'morpho'`, and a `perpetuals` provider config (`'hyperliquid'`). The example below shows the common defaults.
## Start with the common defaults
```ts theme={null}
import { IllaSDK } from '@illalabs/sdk'
const sdk = new IllaSDK(
{ apiKey: process.env.ILLA_API_KEY! },
{
contextManagerOptions: {
defaultToolsConfig: {
autoRouter: {
swapOrBridge: 'lifi',
defi: { lending: 'aave' },
},
},
},
},
)
```
Use this as the baseline if you want explicit tool-routing defaults without overriding the rest of the SDK behavior.
## Tool names
* `tokenTransfer`
* `exchangeRate`
* `getWalletBalance`
* `getConsolidatedWalletBalances`
* `defiFetchListings`
* `defiPositions`
* `defiSupply`
* `defiWithdraw`
* `swap`
* `bridge`
* `predictionMarketsFetch`
* `predictionMarketsGet`
* `predictionMarketsBet`
* `predictionMarketsPositions`
* `predictionMarketsRedeem`
* `predictionMarketsWithdraw`
* `polymarketPostOrder`
* `polymarketPostRedeem`
* `polymarketPostWithdraw`
* `polymarketAuth`
* `polymarketPostGetOrders`
* `polymarketPostCancelOrder`
* `resolveName`
* `perpetualsGetAccountSummary`
* `perpetualsGetPositions`
* `perpetualsPlaceOrder`
* `perpetualsClosePosition`
* `perpetualsUpdateLeverage`
* `hyperliquidDeposit`
* `hyperliquidWithdraw`
* `getPortfolioChart`
* `getTokenPriceChart`
* `getWalletTransactions`
These are the names you should expect in `pendingTools`, tool configs, and provider-specific docs.
## Provider keys
* **Swap:** `lifi`, `aerodrome` (Base-only swaps)
* **Bridge:** `lifi`
* **DeFi lending (supply/withdraw/listings/positions):** `aave`, `morpho`
* **Exchange rates:** `coinMarketCap`, `coingecko`, `zerion`
* **Wallet balances:** `moralis`, `polymarket`, `zerion`
* **Prediction markets:** `polymarket`
* **Perpetuals:** `hyperliquid`
* **Portfolio / price charts:** `zerion`
* **Transaction history:** `zerion`
* **Name resolution:** `ens`
## Prediction-market redeem flow
Redeem support is a two-step tool sequence:
1. `predictionMarketsRedeem` returns a signature request payload for Safe execution.
2. `polymarketPostRedeem` submits the signed payload to the relayer.
If your integration executes `pendingTools` directly, ensure your executor supports signature request handling in addition to transaction handling.
## Supported chains
These chains are currently enumerated in the shared interfaces:
| Chain | Chain ID |
| --------- | -------- |
| Ethereum | 1 |
| Polygon | 137 |
| Optimism | 10 |
| Base | 8453 |
| Arbitrum | 42161 |
| Avalanche | 43114 |
| BSC | 56 |
| 0G | 16661 |
## Model selection
The SDK exposes model selection through `modelContext`, and the raw API exposes it through the `languageModel` request field.
SDK example:
```ts theme={null}
const result = await sdk.sendMessage(
'What is my balance?',
{ userContext: { address: '0x1234...' } },
{
modelContext: {
provider: 'openrouter',
model: 'anthropic/claude-sonnet-4.5',
},
},
)
```
Raw API example:
```bash theme={null}
curl -X POST https://api.illa.io/api/v1/chat \
-H "x-api-key: $ILLA_API_KEY" \
-H "content-type: application/json" \
-d '{
"messages": [],
"userContext": { "address": "0x1234..." },
"prompt": { "role": "user", "content": [{ "type": "text", "text": "What is my balance?" }] },
"languageModel": "openrouter:anthropic/claude-sonnet-4.5"
}'
```
Use the SDK form when you are calling `sdk.sendMessage(...)`. Use the raw API form only if you are integrating directly with the HTTP API.
## Async execution
For operations that continue after submission, use:
* `IllaSDK.awaitAction(...)`
* `IllaSDK.subscribeToToolStatus(...)`
* `GET /api/v1/actions/check`
# Build Agentic Financial Apps
Source: https://docs.illa.io/use-cases/agentic-financial-apps
Embed an agent in your financial product that executes real operations. Your brand and your UX, with ILLA's connectivity, safety, and execution underneath.
## Intent is becoming the interface
Fintechs at the frontier are already building toward one idea: you say what you want, and your money does it. For years, using a financial product meant learning its interface, the screens, the menus, the order you click them in. That is inverting, and it's fast becoming what users expect.
A bolted-on chat widget that talks about your product but can't operate it is the kind users have learned to ignore. What makes an agent useful is the execution underneath: turning a loose instruction into the right sequence of transactions, simulating them, enforcing limits, recovering when a step fails, and doing all of it safely across products and venues. That is a long tail of specialised work that doesn't end.
ILLA is that execution layer. You integrate once, and your product can act across every venue ILLA reaches. The brand, the surface, and the experience stay yours. Underneath, ILLA handles planning, simulation, safety, and execution. It separates the probabilistic reasoning that reads intent from the deterministic execution that moves money, so once a plan is approved, nothing probabilistic touches it.
## From a sentence to a signed transaction
You embed an agent that understands your product and lets users act in plain language. A user says "invest \$50 in TSLA." Another says "pull \$100 from my savings and split it evenly between ETH and BTC." A third says "move my fixed deposit to the higher-yield option." ILLA resolves the intent, plans the route, simulates the outcome, and presents a clear confirmation to approve. No screen navigation, no parameter selection, no multi-step flows.
Your most powerful features become reachable through conversation instead of buried in the interface, with nothing dumbed down to get there. ILLA never holds funds and never executes on its own. It returns ready-to-authorise transaction data, scoped to your accounts, your terminology, and your workflows, and hands off to your infrastructure.
## You stay in control
You define what the agent can do, and ILLA enforces that boundary at runtime. The agent cannot reach outside it. Because ILLA never holds funds and every action runs through that boundary, you get a single, auditable execution path for everything the agent does. That is the accountability regulated products require. You also get hands-on engineering support from us to set the boundary and scope the integration to your product.
## Building with ILLA
ILLA integrates via SDK, API, or MCP. You scope capabilities to your product, set autonomy policies, and bring your own wallet infrastructure. ILLA handles everything from intent to execution, so you can focus on your product.
Explore integration paths: SDK, API, and MCP Server.
# Financial Execution for AI Agents
Source: https://docs.illa.io/use-cases/financial-execution-agents
Give any AI agent the ability to safely execute financial actions. From Claude to your company's internal agents.
## Agents that advise on financial intent, but cannot act
AI agents understand financial intent. They can describe a trade, recommend a savings strategy, explain how to rebalance a portfolio. They cannot reliably execute any of it.
The gap isn't intelligence, nor is it giving your agent access to a wallet that can hold funds. What's missing is a complete, packaged service. Plug in, and financial execution just works. Safe, auditable, end to end.
## One connection to every venue
Every financial venue ships its own agent tooling. But our money is spread across many of them, and each one is a separate integration.
A single instruction can touch several at once. Funds sit in one venue, the action happens in another, and moving between them is a third integration in its own right. One intent, three integrations, and the failure surface grows with every hop.
ILLA collapses this into one connection. You integrate ILLA once and your agent gets coordinated access to every venue ILLA reaches, with orchestration and safety handled inside the core. As ILLA aggregates more venues, more capability becomes available to every agent built on it, without touching your integration. What your agent can do stays scoped to the policies you set.
## More than tools
ILLA connects to AI agents via [MCP](https://modelcontextprotocol.io/docs/getting-started/intro), the open protocol that lets agents call external systems natively. It is an opinionated execution layer, not a set of raw financial tools bolted onto your agent. Every request for financial execution, without compromise, flows through ILLA's full core stack for planning, safety and orchestration.
ILLA returns a complete execution plan to your agent — structured transaction data, simulation results, ready for approval and signing.
Bring your own wallet infrastructure, or connect directly and ILLA provisions one.
## For users
ILLA is live on Claude and available for any agent via MCP. Install the connector, sign in, and you're set — ILLA provisions an embedded wallet and your agent becomes financially capable immediately. No code, no wallet setup, no configuration required.
## For agent builders
If you're building agents that already have wallet infrastructure — agent wallets, your own key management — ILLA plugs in as the intelligence, safety, and planning layer. Your agent routes financial intents through ILLA for disambiguation, simulation, and policy enforcement. ILLA returns structured, ready-to-sign transaction data. Your wallet signs.
Available as a configurable MCP server with full control over capabilities, protocols, limits, and autonomy policies.
Configure ILLA as an MCP server for your agents.