Getting Started with Zoo React

Build AI-powered applications with generative UI using @zooai/react

Getting Started with @zooai/react

Zoo React is a comprehensive React package for building AI-powered applications with generative UI, where users interact through natural language. Use Zoo to build AI chats, copilots, or completely custom AI interactions.

Installation

Install the Zoo React package in your project:

npm install @zooai/react
# or
pnpm add @zooai/react
# or
yarn add @zooai/react

Quick Start

1. Wrap Your App with ZooProvider

The ZooProvider component provides the necessary context for all Zoo features:

import { ZooProvider } from "@zooai/react"

export function App() {
  return (
    <ZooProvider
      apiKey={process.env.ZOO_API_KEY}
      components={
        [
          /* your components */
        ]
      }
      tools={
        [
          /* your tools */
        ]
      }
    >
      <YourAIApp />
    </ZooProvider>
  )
}

2. Send Messages

Use the useMessage hook to send messages to the AI:

import { useMessage } from "@zooai/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 "@zooai/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 { ZooProvider } from "@zooai/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 Zoo
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 (
    <ZooProvider components={components} apiKey="...">
      <YourApp />
    </ZooProvider>
  )
}

Message Threads

Manage conversation history with threads:

import { useThread } from "@zooai/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()
    }
  }
]

<ZooProvider tools={tools} apiKey="...">
  <App />
</ZooProvider>

Configuration

ZooProvider Props

PropTypeDescriptionDefault
apiKeystringYour Zoo API keyRequired
apiUrlstringAPI endpoint URLhttps://api.zoo.ngo/v1
modelstringLLM model to usegpt-4-turbo-preview
componentsZooComponent[]Generative UI components[]
toolsZooTool[]Tools for the AI to use[]
initialMessagesMessage[]Initial conversation[]
enableStreamingbooleanEnable response streamingtrue
enableMCPbooleanEnable Model Context Protocolfalse
onMessage(message: Message) => voidMessage callback-
onError(error: Error) => voidError callback-

Environment Variables

Set up your environment variables:

# .env.local
ZOO_API_KEY=your-api-key
NEXT_PUBLIC_ZOO_API_URL=https://api.zoo.ngo/v1

TypeScript Support

Zoo React is built with TypeScript and provides complete type definitions:

import type { ZooComponent, ZooTool, Message, Thread } from "@zooai/react"

// Fully typed components
const typedComponent: ZooComponent = {
  name: "my-component",
  component: MyComponent,
  description: "A typed component",
  parameters: z.object({
    title: z.string(),
    count: z.number(),
  }),
}

Next Steps