Getting Started with @hanzo/react
Hanzo React is a comprehensive React package for building AI-powered applications with generative UI, where users interact through natural language. Use Hanzo to build AI chats, copilots, or completely custom AI interactions.
Installation
Install the Hanzo React package in your project:
npm install @hanzo/react
# or
pnpm add @hanzo/react
# or
yarn add @hanzo/react
Quick Start
1. Wrap Your App with HanzoProvider
The HanzoProvider
component provides the necessary context for all Hanzo features:
import { HanzoProvider } from "@hanzo/react"
export function App() {
return (
<HanzoProvider
apiKey={process.env.HANZO_API_KEY}
components={
[
/* your components */
]
}
tools={
[
/* your tools */
]
}
>
<YourAIApp />
</HanzoProvider>
)
}
2. Send Messages
Use the useMessage
hook to send messages to the AI:
import { useMessage } from "@hanzo/react"
function ChatInterface() {
const { sendMessage, isLoading, lastMessage } = useMessage()
const handleSubmit = async (content: string) => {
const response = await sendMessage(content)
console.log("AI Response:", response)
}
return (
<div>
<input
onKeyDown={(e) => {
if (e.key === "Enter") {
handleSubmit(e.currentTarget.value)
}
}}
/>
{isLoading && <p>Thinking...</p>}
{lastMessage && <p>{lastMessage.content}</p>}
</div>
)
}
3. Stream Responses
For real-time streaming of AI responses:
import { useStreaming } from "@hanzo/react"
function StreamingChat() {
const { streamMessage, currentMessage, isStreaming } = useStreaming()
const handleStream = async (content: string) => {
await streamMessage(content)
}
return (
<div>
<button onClick={() => handleStream("Tell me a story")}>
Stream Response
</button>
{isStreaming && <p>Streaming...</p>}
<div>{currentMessage}</div>
</div>
)
}
Core Concepts
Generative UI Components
Register components that the AI can dynamically render in responses:
import { HanzoProvider } from "@hanzo/react"
// Define a custom component
function WeatherCard({ city, temperature, conditions }) {
return (
<div className="weather-card">
<h3>{city}</h3>
<p>{temperature}°F</p>
<p>{conditions}</p>
</div>
)
}
// Register it with Hanzo
const components = [
{
name: "weather-card",
component: WeatherCard,
description: "Displays weather information for a city",
parameters: z.object({
city: z.string(),
temperature: z.number(),
conditions: z.string(),
}),
},
]
function App() {
return (
<HanzoProvider components={components} apiKey="...">
<YourApp />
</HanzoProvider>
)
}
Message Threads
Manage conversation history with threads:
import { useThread } from "@hanzo/react"
function ThreadManager() {
const { threads, activeThread, createThread, switchThread, deleteThread } =
useThread()
const handleNewConversation = () => {
const thread = createThread({ name: "New Chat" })
switchThread(thread.id)
}
return (
<div>
<button onClick={handleNewConversation}>New Chat</button>
<ul>
{Array.from(threads.values()).map((thread) => (
<li key={thread.id}>
<button onClick={() => switchThread(thread.id)}>
{thread.metadata?.name || thread.id}
</button>
</li>
))}
</ul>
</div>
)
}
Tool Calling
Add tools that the AI can execute during conversations:
import { z } from 'zod'
const tools = [
{
name: 'calculate',
description: 'Perform mathematical calculations',
parameters: z.object({
expression: z.string()
}),
execute: async ({ expression }) => {
// Safely evaluate the expression
const result = eval(expression) // Use a safe math library in production
return { result }
}
},
{
name: 'fetchData',
description: 'Fetch data from an API',
parameters: z.object({
endpoint: z.string(),
method: z.enum(['GET', 'POST'])
}),
execute: async ({ endpoint, method }) => {
const response = await fetch(endpoint, { method })
return response.json()
}
}
]
<HanzoProvider tools={tools} apiKey="...">
<App />
</HanzoProvider>
Configuration
HanzoProvider Props
Prop | Type | Description | Default |
---|---|---|---|
apiKey | string | Your Hanzo API key | Required |
apiUrl | string | API endpoint URL | https://api.hanzo.ai/v1 |
model | string | LLM model to use | gpt-4-turbo-preview |
components | HanzoComponent[] | Generative UI components | [] |
tools | HanzoTool[] | Tools for the AI to use | [] |
initialMessages | Message[] | Initial conversation | [] |
enableStreaming | boolean | Enable response streaming | true |
enableMCP | boolean | Enable Model Context Protocol | false |
onMessage | (message: Message) => void | Message callback | - |
onError | (error: Error) => void | Error callback | - |
Environment Variables
Set up your environment variables:
# .env.local
HANZO_API_KEY=your-api-key
NEXT_PUBLIC_HANZO_API_URL=https://api.hanzo.ai/v1
TypeScript Support
Hanzo React is built with TypeScript and provides complete type definitions:
import type { HanzoComponent, HanzoTool, Message, Thread } from "@hanzo/react"
// Fully typed components
const typedComponent: HanzoComponent = {
name: "my-component",
component: MyComponent,
description: "A typed component",
parameters: z.object({
title: z.string(),
count: z.number(),
}),
}