@sperax/widget
v0.2.2
Published
Embeddable AI agent widget for SperaxOS — drop DeFi AI into any dApp in 3 lines of code
Maintainers
Readme
@sperax/widget
Install
npm install @sperax/widgetDrop a DeFi-native AI agent into any dApp. Ships as a Web Component, so it works
in plain HTML, React, Vue, Svelte, or anything that can render a <div>.
<script type="module" src="https://unpkg.com/@sperax/widget"></script>
<sperax-agent api-key="sk_live_…" agent-id="portfolio-advisor"></sperax-agent>That is the whole integration. The agent can read live prices, on-chain balances, yields, and contract risk through SperaxOS's tool fleet, and it answers questions about whatever your dApp is currently showing.
Install
npm install @sperax/widgetOr skip the install and load it from a CDN — the module registers the
<sperax-agent> element and a global SperaxWidget on import.
Using React? Reach for @sperax/react-widget instead; it wraps
this package in a component with props and a ref.
Two ways to mount it
Declaratively, in HTML
<sperax-agent
api-key="sk_live_…"
agent-id="yield-optimizer"
position="bottom-right"
theme="auto"
primary-color="#6366f1"
></sperax-agent>Attributes are kebab-case versions of the config fields below. Anything that
isn't a string — event handlers, the context object, tools — has to be set
imperatively.
Imperatively, from JavaScript
import { SperaxWidget } from '@sperax/widget';
const el = SperaxWidget.init({
agentId: 'portfolio-advisor',
apiKey: 'sk_live_…',
context: { connectedWallet: '0xabc…', currentChain: 42_161 },
onMessage: ({ content, role }) => console.log(role, content),
});
SperaxWidget.open(el); // open the panel
SperaxWidget.close(el); // close itinit() appends the element to <body> unless you pass a target:
SperaxWidget.init(config, document.querySelector('#agent-slot'));Keeping the agent in sync with your app
context is the difference between a generic chatbot and an assistant that knows
what the user is looking at. Push it again whenever your app state changes:
const el = SperaxWidget.init({ agentId: 'trading-assistant', apiKey });
// user switches network or selects a token
SperaxWidget.configure(el, {
agentId: 'trading-assistant',
apiKey,
context: {
connectedWallet: address,
currentChain: chainId,
currentProtocol: 'uniswap-v3',
currentToken: 'ARB',
},
});Every key in context is forwarded to the agent, so you can add your own:
context: { …, cartValue: 1200, tier: 'pro' }.
Presets
Pass a preset id as agentId to get a pre-tuned agent with the right tools and
system prompt already selected. No agent needs to be created first.
| Preset id | What it is for |
| --- | --- |
| yield-optimizer | Yield aggregator assistant — best APYs, vault comparison, risk analysis |
| portfolio-advisor | Portfolio tracker assistant — holdings analysis, performance, rebalancing |
| trading-assistant | DEX trading assistant — market data, swap quotes, funding rates, sentiment |
| security-auditor | Wallet security assistant — token approvals, MEV risk, contract audits |
| lending-advisor | Lending protocol UI assistant — rates, health factors, liquidation risk |
| nft-advisor | NFT marketplace assistant — floor prices, rarity, wallet analysis |
Read the full definitions at runtime:
import { WIDGET_PRESETS, resolvePreset } from '@sperax/widget';
console.log(Object.keys(WIDGET_PRESETS));
console.log(resolvePreset('yield-optimizer')?.description);Pass a SperaxOS agent UUID instead of a preset id to load one of your own agents.
Configuration
WidgetConfig, passed to init() / configure():
| Field | Type | Default | Description |
| --- | --- | --- | --- |
| apiKey | string | — | Required. Your SperaxOS key (sk_live_… / sk_test_…). |
| agentId | string | preset default | A preset id or a SperaxOS agent UUID. |
| tools | string[] | agent's tools | Allowlist. Only these tools are offered to the agent. |
| context | WidgetContext | {} | Live state from your dApp (see above). |
| position | 'bottom-right' \| 'bottom-left' \| 'inline' | 'bottom-right' | Placement. 'inline' renders in flow instead of floating. |
| theme | 'dark' \| 'light' \| 'auto' | 'auto' | 'auto' follows the OS preference. |
| primaryColor | string | '#6366f1' | Brand accent, any CSS color. |
| greeting | string | — | Shown before the first message. |
| suggestedPrompts | string[] | — | Quick-action chips under the greeting. |
| onMessage | (e: WidgetMessageEvent) => void | — | Fires for every user and assistant message. |
| onToolCall | (e: WidgetToolCallEvent) => void | — | Fires each time the agent runs a tool. |
| baseUrl | string | 'https://api.sperax.io' | Point at your own deployment. |
Event payloads:
interface WidgetMessageEvent { content: string; role: 'assistant' | 'user'; timestamp: number }
interface WidgetToolCallEvent { params: Record<string, unknown>; result: unknown; tool: string }Instrumenting the agent
onToolCall is the hook for analytics — it tells you which capabilities users
actually reach for:
SperaxWidget.init({
agentId: 'security-auditor',
apiKey,
onToolCall: ({ tool, params }) => analytics.track('agent_tool_used', { params, tool }),
});Exports
import {
SperaxWidget, // imperative API: init, configure, open, close
SperaxAgentElement, // the custom element class
registerWebComponent, // manual registration (called automatically in browsers)
WIDGET_PRESETS,
resolvePreset,
} from '@sperax/widget';
import type {
ChatMessage, PresetConfig, WidgetConfig, WidgetContext,
WidgetMessageEvent, WidgetPosition, WidgetPresetId,
WidgetTheme, WidgetToolCallEvent,
} from '@sperax/widget';The element auto-registers on import in any environment with a window. Under
SSR nothing is touched, so importing the package in a server bundle is safe;
call registerWebComponent() yourself if you defer registration.
Related
@sperax/react-widget— React wrapper with props and a ref@sperax/sdk— call the same agents from Node or the browser@sperax/plugin-sdk— give the agents new tools
Apache-2.0
License
widget is released under the Apache-2.0 license.
