Files
2025-10-16 21:45:52 -07:00

276 lines
6.7 KiB
Plaintext

---
title: Getting Started with Hanzo React
description: Build AI-powered applications with generative UI using @hanzo/react
---
# 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:
```bash
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:
```tsx
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:
```tsx
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:
```tsx
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:
```tsx
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:
```tsx
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:
```tsx
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:
```bash
# .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:
```tsx
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(),
}),
}
```
## Next Steps
- [Explore all available hooks](/docs/hanzo-react/hooks)
- [Learn about Model Context Protocol (MCP)](/docs/hanzo-react/mcp)
- [Build custom components](/docs/hanzo-react/components)
- [See example applications](/docs/hanzo-react/examples)