@termix-it/vue-tool
v1.0.1
Published
A configurable AI chat interface component library for Vue
Maintainers
Readme
TermiX Frontend SDK (Vue) - Easy to Use
TermiX offers a library of out-of-the-box Vue 3 components that enable your dApp to support intelligent AI conversations and Web3 workflows in minutes. These components are highly customizable and can even be fully white-labeled. This means you have access to out-of-the-box natural language interaction, smart contract calls, MCP tool integration, and more.
Features
- 🤖 AI Chat Interface: Ready-to-use chat component with real-time streaming responses
- 🔧 Highly Configurable: Extensive props for customization and theming
- 🛠️ Function Calls: Automatic AI function calling with REST API and smart contract execution
- 📚 Knowledge Base: Built-in knowledge base search and reference display
- 🎨 Tailwind CSS: Beautiful, responsive UI with customizable styling
- ⚡ ReAct Pattern: Support for reasoning and acting patterns in AI responses
- 🔗 Smart Contracts: Direct blockchain interaction through MetaMask and web3
- 📱 Responsive: Works seamlessly on desktop and mobile devices
- 🚀 TypeScript: Full TypeScript support with comprehensive type definitions
- 🌊 Real-time Streaming: Server-Sent Events (SSE) support for live chat responses
- 🪝 Request Hooks:
beforeCallApiFunchook for intercepting and modifying API requests - 🔐 HMAC Utilities: Built-in HMAC signing and verification functions for secure API authentication
- 💳 AP2 Payment: Built-in AP2 payment flow support with mandate signing
Installation
npm install @termix-it/vue-tool
# or
yarn add @termix-it/vue-tool
# or
pnpm add @termix-it/vue-toolAfter installation, you'll have access to:
- ✅ ChatInterface component with AI chat capabilities
- ✅ ChatWidget component for floating chat button
- ✅ PaymentApprovalModal component for AP2 payments
- ✅ Built-in styles (import separately)
- ✅ TypeScript support with full type definitions
- ✅ Automatic knowledge base integration
- ✅ Function calling (REST APIs & smart contracts)
- ✅ Real-time streaming support
- ✅ AP2 Payment composable
Peer Dependencies
This library requires the following peer dependencies to be installed in your project:
npm install vue ethers
# or
yarn add vue ethers
# or
pnpm add vue ethersRequired peer dependencies:
{
"vue": "^3.3.0",
"ethers": "^5.7.0 || ^6.15.0"
}Ethers.js Version Compatibility
This library supports both ethers v5 and ethers v6 through an internal compatibility layer. You can use either version in your project:
- ethers v5:
npm install ethers@^5.7.0 - ethers v6:
npm install ethers@^6.15.0
The library will automatically detect which version you have installed and adapt accordingly. All Web3-related functionality (smart contract calls, wallet connections, etc.) works seamlessly with both versions.
Quick Start
Minimal Setup
The absolute minimum code needed to get started:
<script setup lang="ts">
import { ChatInterface } from '@termix-it/vue-tool';
import '@termix-it/vue-tool/style.css';
</script>
<template>
<ChatInterface
project-id="your-project-id"
ai-config-id="your-ai-config-id"
/>
</template>Basic Usage with Common Options
<script setup lang="ts">
import { ChatInterface } from '@termix-it/vue-tool';
import '@termix-it/vue-tool/style.css';
const handleMessageSent = (message) => console.log('Sent:', message);
const handleResponseReceived = (message) => console.log('Received:', message);
const handleError = (error) => console.error('Error:', error);
</script>
<template>
<div style="height: 100vh">
<ChatInterface
project-id="your-project-id"
ai-config-id="your-ai-config-id"
authorization="Bearer your-jwt-token"
:enable-streaming-mode="true"
:show-header="false"
placeholder="Type your message..."
@message-sent="handleMessageSent"
@response-received="handleResponseReceived"
@error="handleError"
/>
</div>
</template>Note:
- You need to import styles separately:
import '@termix-it/vue-tool/style.css' - All styles are scoped with
.termix-prefix to prevent conflicts - The API base URL is built into the SDK and defaults to
https://dashboard.termix.ai
Chat Widget Component
The ChatWidget component provides a floating chat button with a popup dialog, perfect for customer service or help functionality. The widget includes its own header, so you typically don't need to enable showHeader on the ChatInterface inside it.
Basic Widget Usage
<script setup lang="ts">
import { ChatWidget, ChatInterface } from '@termix-it/vue-tool';
import '@termix-it/vue-tool/style.css';
const handleWidgetOpenChange = (open: boolean) => {
console.log('Widget open:', open);
};
</script>
<template>
<div style="position: relative; height: 100vh">
<!-- Your main content -->
<div>Your application content</div>
<!-- Fixed positioned chat widget -->
<div style="position: fixed; bottom: 24px; right: 24px">
<ChatWidget
title="AI Assistant"
:default-open="false"
@open-change="handleWidgetOpenChange"
>
<ChatInterface
project-id="your-project-id"
ai-config-id="your-ai-config-id"
authorization="your-token"
:enable-streaming-mode="true"
:show-header="false"
/>
</ChatWidget>
</div>
</div>
</template>ChatWidget Props
| Prop | Type | Default | Description |
|------|------|---------|-------------|
| buttonIcon | string | undefined | Custom button icon URL |
| title | string | "AI Assistant" | Dialog header title |
| class | string | "" | CSS classes for the widget container |
| style | Record<string, string> | undefined | Inline styles for the widget container |
| buttonClassName | string | "" | CSS classes for the chat button |
| buttonStyle | Record<string, string> | undefined | Inline styles for the chat button |
| dialogClassName | string | "" | CSS classes for the dialog |
| dialogStyle | Record<string, string> | undefined | Inline styles for the dialog |
| defaultOpen | boolean | false | Whether dialog is open by default |
ChatWidget Events
| Event | Payload | Description |
|-------|---------|-------------|
| openChange | boolean | Emitted when dialog open state changes |
Configuration
Chat Header
The ChatInterface component includes an optional header that displays the AI model name and personality. Control it with the showHeader prop:
<ChatInterface
:show-header="true"
personality-name="AI Assistant"
:show-usage-info="true"
...
/>The header features:
- Blue gradient background with white text
- Model and personality name display
- Optional usage cost display (when
showUsageInfois true) - Automatically hidden by default for cleaner integration
Required Props
| Prop | Type | Description |
|------|------|-------------|
| projectId | string | Your Termix project identifier |
| aiConfigId | string | AI configuration identifier |
Authentication & API
| Prop | Type | Default | Description |
|------|------|---------|-------------|
| authorization | string | undefined | Authorization header value (e.g., 'Bearer token') |
| apiHeaders | Record<string, string> | {} | Additional headers for API requests |
| restExecuteHeader | Record<string, string> | undefined | Custom headers object for REST execution (deprecated) |
| restExecuteHeaders | DomainHeaderConfig[] | undefined | Domain-specific headers for REST execute requests |
| proxyMode | boolean | false | Enable proxy mode to route third-party REST API requests through backend proxy |
UI Configuration
| Prop | Type | Default | Description |
|------|------|---------|-------------|
| placeholder | string | "Type your message..." | Input placeholder text |
| personalityName | string | undefined | Optional override for personality name (overrides API config value) |
Feature Toggles
| Prop | Type | Default | Description |
|------|------|---------|-------------|
| enableStreamingMode | boolean | false | Enable real-time streaming responses via SSE |
| showHeader | boolean | false | Show/hide the chat header with title and model info |
| showUsageInfo | boolean | false | Show token usage and cost information |
| showTimestamp | boolean | false | Show message timestamps |
| maxKnowledgeResults | number | 3 | Maximum knowledge base results to show |
Note: The following features are now always enabled and cannot be disabled:
- Knowledge base integration
- Function calls (REST API and smart contracts)
- ReAct pattern (reasoning and acting)
- Knowledge references display
Styling Props
| Prop | Type | Description |
|------|------|-------------|
| className | string | Additional CSS classes for the main container |
| style | CSSProperties | Inline styles for the main container |
| messagesClassName | string | CSS classes for the messages area |
| messagesStyle | CSSProperties | Inline styles for the messages area |
| inputClassName | string | CSS classes for the input field |
| inputStyle | CSSProperties | Inline styles for the input field |
Events
| Event | Payload | Description |
|-------|---------|-------------|
| messageSent | Message | Emitted when user sends a message |
| responseReceived | Message | Emitted when AI responds |
| functionExecuted | FunctionCall, ExecutionResult | Emitted when a function is executed |
| error | any | Emitted when an error occurs |
| messagesChange | Message[] | Emitted when messages array changes (for controlled mode) |
Hooks
| Prop | Type | Description |
|------|------|-------------|
| beforeCallApiFunc | (request: ApiRequest) => Promise<ApiRequest> | Optional async hook called before API executor makes a request. Allows modification of the request object. |
Controlled Messages Mode
You can use v-model:messages to control the messages state externally:
<script setup lang="ts">
import { ref } from 'vue';
import { ChatInterface } from '@termix-it/vue-tool';
import type { Message } from '@termix-it/vue-tool';
const messages = ref<Message[]>([]);
</script>
<template>
<ChatInterface
project-id="your-project-id"
ai-config-id="your-ai-config-id"
v-model:messages="messages"
/>
</template>Streaming Mode
The ChatInterface supports real-time streaming responses using Server-Sent Events (SSE). When enabled, messages appear character by character as they are received from the server.
Basic Streaming Setup
<ChatInterface
project-id="your-project-id"
ai-config-id="your-ai-config-id"
authorization="your-token"
:enable-streaming-mode="true"
/>Streaming vs Regular Mode
| Feature | Regular Mode | Streaming Mode |
|---------|-------------|----------------|
| Endpoint | /chat | /chat/stream |
| Response | Complete message | Character-by-character |
| Usage Info | Available | Limited (cost not tracked) |
| Visual Feedback | Loading spinner | Real-time typing |
| Network | Single request | SSE connection |
Advanced Usage
Custom Headers for REST API Calls
<script setup lang="ts">
const customHeaders = { "X-API-Key": "your-key", "X-Custom": "value" };
</script>
<template>
<ChatInterface
project-id="your-project-id"
ai-config-id="your-ai-config-id"
authorization="your-token"
:rest-execute-header="customHeaders"
/>
</template>Domain-Specific Headers
For more granular control, use restExecuteHeaders to specify different headers for different domains:
<script setup lang="ts">
const domainHeaders = [
{ domain: 'api.example.com', headers: { 'X-API-Key': 'key1' } },
{ domain: 'other-api.com', headers: { 'Authorization': 'Bearer token2' } },
{ domain: '*', headers: { 'X-Default': 'value' } } // fallback for all other domains
];
</script>
<template>
<ChatInterface
project-id="your-project-id"
ai-config-id="your-ai-config-id"
:rest-execute-headers="domainHeaders"
/>
</template>beforeCallApiFunc Hook
The beforeCallApiFunc hook allows you to intercept and modify API requests before they are sent:
<script setup lang="ts">
import { ChatInterface, hmacSign } from '@termix-it/vue-tool';
import type { ApiRequest } from '@termix-it/vue-tool';
const handleBeforeApiCall = async (request: ApiRequest): Promise<ApiRequest> => {
const timestamp = Date.now().toString();
const message = `${request.method}:${request.url}:${timestamp}`;
const signature = await hmacSign('your-secret-key', message);
return {
...request,
headers: {
...request.headers,
'X-Timestamp': timestamp,
'X-Signature': signature,
},
};
};
</script>
<template>
<ChatInterface
project-id="your-project-id"
ai-config-id="your-ai-config-id"
:before-call-api-func="handleBeforeApiCall"
/>
</template>Function Call Handling
<script setup lang="ts">
import type { FunctionCall, ExecutionResult } from '@termix-it/vue-tool';
const handleFunctionExecuted = (functionCall: FunctionCall, result: ExecutionResult) => {
console.log('Function executed:', functionCall.name);
if (functionCall.metadata?.type === 'contract' && result.success) {
if (result.data?.transactionHash) {
console.log('Transaction hash:', result.data.transactionHash);
}
}
if (functionCall.metadata?.type === 'api') {
console.log('API call result:', result.data);
}
};
</script>
<template>
<ChatInterface
project-id="your-project-id"
ai-config-id="your-ai-config-id"
@function-executed="handleFunctionExecuted"
/>
</template>AP2 Payment Integration
The library includes built-in support for AP2 payments with the useAP2Payment composable and PaymentApprovalModal component.
Using the Payment Composable
<script setup lang="ts">
import { useAP2Payment, PaymentApprovalModal } from '@termix-it/vue-tool';
const {
pendingPayment,
isPaymentModalOpen,
approvePayment,
rejectPayment,
clearPayment,
} = useAP2Payment({
projectId: 'your-project-id',
authorization: 'your-token',
});
</script>
<template>
<PaymentApprovalModal
v-if="isPaymentModalOpen && pendingPayment"
:mandate="pendingPayment"
@approve="approvePayment"
@reject="rejectPayment"
@close="clearPayment"
/>
</template>TypeScript Support
Full TypeScript support with exported types:
import type {
Message,
ToolCall,
KnowledgeContext,
FunctionCall,
ExecutionResult,
ChatInterfaceProps,
APIConfig,
ApiRequest,
BeforeCallApiFunc,
HmacAlgorithm,
WalletState,
UseAP2PaymentReturn,
UseAP2PaymentOptions,
PaymentMandate
} from '@termix-it/vue-tool';Type Definitions
interface Message {
id: string;
role: 'user' | 'assistant' | 'system';
content: string;
timestamp: Date;
usage?: {
promptTokens?: number;
completionTokens?: number;
totalTokens?: number;
cost: number;
};
knowledgeContext?: KnowledgeContext[];
toolCalls?: ToolCall[];
}
interface FunctionCall {
name: string;
parameters: Record<string, any>;
metadata?: {
type?: 'api' | 'contract' | 'fiat' | 'ap2' | 'unknown';
description?: string;
method?: string;
path?: string;
baseUrl?: string;
contractName?: string;
contractAddress?: string;
chainName?: string;
};
}
interface ExecutionResult {
success: boolean;
type: 'api' | 'contract' | 'fiat' | 'ap2' | 'payment' | 'wallet' | 'error';
data?: any;
error?: string;
metadata?: Record<string, any>;
}Exported Components and Utilities
// Main components
export { ChatInterface } from './components/ChatInterface.vue';
export { ChatWidget } from './components/ChatWidget.vue';
export { PaymentApprovalModal } from './components/PaymentApprovalModal.vue';
// Composables
export { useAP2Payment } from './composables/useAP2Payment';
// Utilities
export { hmacSign, hmacVerify, hmacSignBase64 } from './lib/utils';HMAC Utilities
The SDK provides built-in HMAC utilities for secure API request signing:
import { hmacSign, hmacVerify, hmacSignBase64 } from '@termix-it/vue-tool';
// Generate hex signature
const signature = await hmacSign('your-secret-key', 'message to sign');
// Returns: "a1b2c3d4e5..." (hex string)
// Generate base64 signature
const base64Sig = await hmacSignBase64('your-secret-key', 'message to sign');
// Returns: "oWLDMtRT..." (base64 string)
// Verify signature
const isValid = await hmacVerify('your-secret-key', 'message', 'a1b2c3...');
// Returns: true or false
// With custom algorithm (SHA-256, SHA-384, SHA-512)
const sha512Sig = await hmacSign('secret', 'message', 'SHA-512');Styling
Importing Styles
You must import styles separately:
import '@termix-it/vue-tool/style.css';Using Inline Styles
Both ChatInterface and ChatWidget support inline styles:
<ChatInterface
project-id="your-project-id"
ai-config-id="your-ai-config-id"
:style="{
height: '600px',
borderRadius: '12px',
boxShadow: '0 4px 6px rgba(0,0,0,0.1)'
}"
:messages-style="{ backgroundColor: '#f9f9f9' }"
:input-style="{ fontSize: '16px', padding: '12px 16px' }"
/>Development
Running the Test App
A test application with interactive control panel is included for development and testing:
# From the vue-tool directory
npm run example
# or
pnpm exampleThis will start a Vite dev server with hot reload.
Features:
- Control Panel - Real-time property adjustment for all component props
- Live Preview - Test both ChatInterface and ChatWidget components
- Hot Reload - Changes to source code are reflected immediately
- No Code Editing - Configure everything through the UI
Building the Library
# Build for production
npm run build
# Build for development (with dev API URL)
npm run build:dev
# Watch mode - rebuild on changes
npm run dev
npm run dev:localType Checking
npm run type-checkLicense
MIT
Support
For issues and questions, please use the GitHub issue tracker.
Publishing
# Publish the package
npm publish --access public
# Update version
npm version patch # 1.0.0 -> 1.0.1
npm version minor # 1.0.0 -> 1.1.0
npm version major # 1.0.0 -> 2.0.0