@bitte-ai/chat
Version:
Bitte AI chat component
509 lines (396 loc) • 16.1 kB
Markdown
# Bitte AI Chat
<p align="center">
<img src="https://img.shields.io/github/v/release/BitteProtocol/chat" />
<img src="https://img.shields.io/github/release-date/BitteProtocol/chat" />
<img src="https://img.shields.io/github/commit-activity/m/BitteProtocol/chat" />
<img src='https://img.shields.io/npm/dw/@bitte-ai/chat' />
<a href="https://stackblitz.com/~/github.com/BitteProtocol/chat-boilerplate" target="_blank"> <img src='https://img.shields.io/badge/StackBlitz-Edit-blue?style=flat-square&logo=data:image/png;base64,iVBORw0KGgoAAAANSUhEUgAAAC4AAABECAYAAAD+1gcLAAAACXBIWXMAAC4jAAAuIwF4pT92AAAAB3RJTUUH5AINBw4X0bTGRQAABSxJREFUaN7VmVtsFFUYx//fmQW79bbd2QKpaIIaDcGoifFBEgMGqTTRRA01SgxE5Rbi7QG6S3lgo9J2twpeotxEQlCigLdoQwJ4ARN9QB9MRCNRDBdRzE7LJbTSmTl/H4BYStmd2Z3tDOdt5lzml/9833fO9x0gYi2xgom6Tt5aapyKEnRDlrVGPzfGT+G3SwZ87HLGT8f5uYD7jmSl99IAX80RfTY3A5wMqDVepoQPnqVKHtMbAN4PyJeFtPwafXBSknG9UoDHAIDQq7xODRU8mdc5Aeaeffy7O2F8GnnwZM5dKsCic88CrMU8sSMNbubdZwTIDnjlOoZa52eNYQc3c84sEK+d/1a6ji2UA5EFN3POw4C8fcYy/m+a3p1y2MGTOXsqIJsAxAZ1Hei53tgeSfBkBycK1McALrswJGIVHhE3cuD1ed4uorsAXD5Ed7/hqvXlrFtV8LpO3qKpdwJIDLn/AB/+s0SORgp8VJ43KK23AzAvNsagWlXu+lKV6LGc14itvyEwrsiwX6wWNQEijITiY9pYD1vvKAENAG+VC40hQlNlNt3Bq22lt4EYX2Jor6PVe5V8KzDFG7KsFXE/A3GHB/vcdHyx9IQPnuXI/ji3CuRuT+N1+U4ZHPhmGqk43yXY5C0ccE9hsfwQLjgp5n69hmCz9ylY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izikfkwKiQAAAAASUVORK5CYII=)]' /> </a>
</p>
## Introduction
The **Bitte AI Chat** component is a React component that enables AI-powered chat interactions in your application. It supports both **NEAR Protocol** and **EVM blockchain** interactions through wallet integrations, allowing users to interact with smart contracts and perform transactions directly through the chat interface.
> 🔑 Before you begin, make sure you have:
>
> - A **Bitte API Key** - [Get yours here](placeholder-link-for-api-key)
---
## Quick Start
1. [Configure Wallet Integration](#wallet-integration)
2. [Setup the API Route](#api-route-setup)
3. [Add the Chat Component](#basic-chat-usage) or [use as Widget](#widget-chat-usage)
## Compatibility
Our stable version (latest) currently supports React 18 Applications.
We have a beta version that supports React 19 and Next.js 15 Applications.
We are working on support more frameworks like Vite React 19 in the mean time.
You can check an working Next.js example on our [chat-boilerplate](https://github.com/BitteProtocol/chat-boilerplate) repo
Run on [Stackblitz](https://stackblitz.com/~/github.com/BitteProtocol/chat-boilerplate)
## Wallet Integration
We recommend installing the package using pnpm or yarn:
```
pnpm install @bitte-ai/chat
```
or
```
yarn add @bitte-ai/chat
```
if you are using npm and find issues, you can use the current command:
```
npm install @bitte-ai/chat --legacy-peer-deps
```
### NEAR Integration
You can integrate with NEAR using either the NEAR Wallet Selector or a direct account connection. If you want to be able to send near transacitons through the chat you will need to define at least one of these
### Using Next.js
Check our [Next.js boilerplate](https://github.com/BitteProtocol/chat-boilerplate) repo.
Currently turbopack builds arent working due to tailwind build issue.
#### Using Wallet Selector
1. You need to wrap your application with [BitteWalletContextProvider](https://github.com/BitteProtocol/react?tab=readme-ov-file#bittewalletcontextprovider)
2. If you using Next.js you need to add `"use client"` on top of file
```typescript
import { useEffect, useState } from "react"
import { useBitteWallet, Wallet } from "@bitte-ai/react";
import { BitteAiChat } from "@bitte-ai/chat";
import "@bitte-ai/chat/styles.css";
export default function Chat() {
const { selector } = useBitteWallet();
const [wallet, setWallet] = useState<Wallet>();
useEffect(() => {
const fetchWallet = async () => {
const walletInstance = await selector.wallet();
setWallet(walletInstance);
};
if (selector) fetchWallet();
}, [selector]);
return (
<BitteAiChat
agentId="your-agent-id"
apiUrl="/api/chat"
wallet={{ near: { wallet } }}
/>
);
}
```
#### Using Direct Account
```typescript
import { Account } from "near-api-js";
// get near account instance from near-api-js by instantiating a keypair
<BitteAiChat
agentId="your-agent-id"
apiUrl="/api/chat"
wallet={{ near: { account: nearAccount } }}
/>
```
### EVM Integration
EVM integration uses WalletConnect with wagmi hooks:
```typescript
import { useSendTransaction, useAccount } from 'wagmi';
export default function Chat() {
const { address } = useAccount();
const { sendTransaction } = useSendTransaction();
return (
<BitteAiChat
agentId="your-agent-id"
apiUrl="/api/chat"
wallet={{
evm: {
sendTransaction,
address
}
}}
/>
);
}
```
## API Route Setup
Create an API route in your Next.js application to proxy requests to the Bitte API to not expose your key:
```typescript
import type { NextRequest } from "next/server";
const { BITTE_API_KEY, BITTE_API_URL = "https://ai-runtime-446257178793.europe-west1.run.app/chat" } =
process.env;
export const dynamic = "force-dynamic";
export const maxDuration = 60;
export const POST = async (req: NextRequest): Promise<Response> => {
const requestInit: RequestInit & { duplex: "half" } = {
method: "POST",
body: req.body,
headers: {
Authorization: `Bearer ${BITTE_API_KEY}`,
},
duplex: "half",
};
const upstreamResponse = await fetch(BITTE_API_URL, requestInit);
const headers = new Headers(upstreamResponse.headers);
headers.delete("Content-Encoding");
return new Response(upstreamResponse.body, {
status: upstreamResponse.status,
headers,
});
};
```
## History API Route Setup
Create an API route in your Next.js application that will allow your app if you want to save chat context when signing a transaction after getting redirected to the wallet.
```typescript
import { type NextRequest, NextResponse } from 'next/server';
const { BITTE_API_KEY, BITTE_API_URL = 'https://ai-runtime-446257178793.europe-west1.run.app' } =
process.env;
export const dynamic = 'force-dynamic';
export const maxDuration = 60;
export const GET = async (req: NextRequest): Promise<NextResponse> => {
const { searchParams } = new URL(req.url);
const id = searchParams.get('id');
const url = `${BITTE_API_URL}/history?id=${id}`;
const response = await fetch(url, {
headers: {
Authorization: `Bearer ${BITTE_API_KEY}`,
},
});
const result = await response.json();
return NextResponse.json(result);
};
```
## Chat Components Overview
Bitte AI Chat provides two main components for different use cases:
- **`BitteAiChat`** - Full-featured chat interface for embedding directly in your app pages
- **`BitteWidgetChat`** - Floating chat widget that overlays your existing content
## Basic Chat Usage
The `BitteAiChat` component provides a full-featured chat interface that can be embedded directly into your application pages.
### Standard Chat Setup
```typescript
import { BitteAiChat } from "@bitte-ai/chat";
import { useAccount, useSendTransaction } from 'wagmi';
import "@bitte-ai/chat/styles.css";
export default function ChatPage() {
const { address } = useAccount();
const { sendTransaction } = useSendTransaction();
return (
<div className="container mx-auto p-4">
<h1>AI Assistant</h1>
{/* Full-page chat interface */}
<div style={{ height: '600px' }}>
<BitteAiChat
agentId="your-agent-id"
apiUrl="/api/chat"
historyApiUrl="/api/history"
wallet={{
evm: {
sendTransaction,
address
}
}}
options={{
agentName: "My AI Assistant",
agentImage: "/agent-avatar.png",
colors: {
generalBackground: "#ffffff",
messageBackground: "#f8fafc",
textColor: "#1f2937",
buttonColor: "#3b82f6",
borderColor: "#e5e7eb"
},
customComponents: {
welcomeMessageComponent: (
<div>
<h2>Welcome to our AI Assistant!</h2>
<p>How can I help you today?</p>
</div>
)
}
}}
/>
</div>
</div>
);
}
```
### NEAR Wallet Integration
```typescript
import { useEffect, useState } from "react";
import { useBitteWallet, Wallet } from "@bitte-ai/react";
import { BitteAiChat } from "@bitte-ai/chat";
import "@bitte-ai/chat/styles.css";
export default function Chat() {
const { selector } = useBitteWallet();
const [wallet, setWallet] = useState<Wallet>();
useEffect(() => {
const fetchWallet = async () => {
const walletInstance = await selector.wallet();
setWallet(walletInstance);
};
if (selector) fetchWallet();
}, [selector]);
return (
<BitteAiChat
agentId="your-agent-id"
apiUrl="/api/chat"
wallet={{ near: { wallet } }}
options={{
agentName: "NEAR Assistant",
colors: {
generalBackground: "#000000",
textColor: "#ffffff"
}
}}
/>
);
}
```
## Widget Chat Usage
The `BitteWidgetChat` component provides a floating chat widget that can be embedded anywhere on your website. It includes a trigger button and a popup chat interface.
### Basic Widget Setup
```typescript
import { BitteWidgetChat } from "@bitte-ai/chat";
import { useAccount, useSendTransaction } from 'wagmi';
import "@bitte-ai/chat/styles.css";
export default function App() {
const { address } = useAccount();
const { sendTransaction } = useSendTransaction();
return (
<div>
{/* Your existing app content */}
<main>
<h1>My App</h1>
{/* Other content */}
</main>
{/* Widget Chat - floating at bottom right */}
<BitteWidgetChat
agentId="your-agent-id"
apiUrl="/api/chat"
historyApiUrl="/api/history"
wallet={{
evm: {
sendTransaction,
address
}
}}
widget={{
widgetWelcomePrompts: {
title: "Hey there! 👋",
description: "I'm your AI assistant. What would you like to do?",
questions: [
"What's my portfolio balance?",
"Show me trending tokens",
"How do I swap tokens?"
],
actions: [
"Check my wallet balance",
"View recent transactions",
"Help me with DeFi"
]
},
triggerButtonStyles: {
backgroundColor: "#6366F1",
logoColor: "#FFFFFF"
}
}}
options={{
agentName: "DeFi Assistant",
agentImage: "/assistant-avatar.png"
}}
/>
</div>
);
}
```
### Custom Trigger Button
You can replace the default trigger button with your own component:
```typescript
<BitteWidgetChat
agentId="your-agent-id"
apiUrl="/api/chat"
wallet={{ /* wallet config */ }}
widget={{
customTriggerButton: (
<div className="custom-chat-button">
<ChatIcon />
<span>Chat with us!</span>
</div>
)
}}
/>
```
### Trigger Button Styling
Customize the appearance of the trigger button:
```typescript
widget={{
triggerButtonStyles: {
backgroundColor: "#1F2937", // Dark background
logoColor: "#F3F4F6" // Light logo color
}
}}
```
**Note:** The widget position is fixed at bottom-right of the viewport and cannot be customized through props.
## Component Props
### BitteAiChat Props
```typescript
interface BitteAiChatProps {
agentId: string; // ID of the AI agent to use
apiUrl: string; // Your API route path (e.g., "/api/chat")
historyApiUrl?: string; // Your history API route to keep context when signing transactions
wallet?: WalletOptions; // Wallet configuration
apiKey?: string; // Optional API key for server-side requests
messages?: Message[]; // Initial messages to display
customToolComponents?: CustomToolComponent[]; // Custom tool components
onChatLoaded?: () => void; // Callback when chat is loaded
onMessageReceived?: (message: Message) => void; // Callback when message is received
widget?: WidgetChatProps; // Widget-specific configuration
isWidgetChat?: boolean; // Whether to render as widget
options?: {
agentName?: string; // Custom agent name
agentImage?: string; // Custom agent image URL
chatId?: string; // Custom chat ID
prompt?: string; // Custom Initial prompt
placeholderText?: string; // Custom placeholder text
hideToolCall?: boolean; // Hide tool call UI (default: true for widget)
localAgent?: {
pluginId: string;
accountId: string;
spec: BitteOpenAPISpec;
};
colors?: ChatComponentColors;
customComponents?: {
welcomeMessageComponent?: React.JSX.Element;
mobileInputExtraButton?: React.JSX.Element;
messageContainer?: React.ComponentType<MessageGroupComponentProps>;
chatContainer?: React.ComponentType<ChatContainerComponentProps>;
inputContainer?: React.ComponentType<InputContainerProps>;
sendButtonComponent?: React.ComponentType<SendButtonComponentProps>;
loadingIndicator?: React.ComponentType<LoadingIndicatorComponentProps>;
};
};
}
```
### BitteWidgetChat Props
The `BitteWidgetChat` component accepts all the same props as `BitteAiChat` plus widget-specific styling and behavior.
```typescript
interface WidgetChatProps {
// Welcome prompts configuration for widget
widgetWelcomePrompts?: {
title?: string; // Welcome title (default: "Hello")
description?: string; // Welcome description
questions?: string[]; // Array of suggested questions
actions?: string[]; // Array of suggested actions
};
// Custom trigger button (replaces default Bitte logo)
customTriggerButton?: React.ReactElement;
// Trigger button styling
triggerButtonStyles?: {
backgroundColor?: string; // Background color (default: "#000000")
logoColor?: string; // Logo color (default: "#ffffff")
};
}
```
## Available Agents
[Agent registry](https://www.bitte.ai/registry)
## Creating Custom Agents
[Make Agent](https://docs.bitte.ai/agents/introduction)
## Styling
The component can be customized using the `colors` prop:
```typescript
type ChatComponentColors = {
generalBackground?: string; // Chat container background
messageBackground?: string; // Message bubble background
textColor?: string; // Text color
buttonColor?: string; // Button color
borderColor?: string; // Border color
};
```
## Example Projects
- [Bitte AI Chat Boilerplate](https://github.com/BitteProtocol/chat-boilerplate)
- [Bitte AI Chat Boilerplate Next.js Pages Router](https://github.com/BitteProtocol/chat-boilerplate-next-pages)