### Run UI2 Quick Start Example
Source: https://github.com/evanzhoudev/ui2/blob/main/examples/quick-start/README.md
Command to execute the UI2 Quick Start example using Node.js. This command assumes Node.js is installed and the 'index.js' file is present in the current directory.
```bash
node index.js
```
--------------------------------
### Configure UI2 API Key
Source: https://github.com/evanzhoudev/ui2/blob/main/examples/quick-start/README.md
Instructions to replace the placeholder API key in the UI2 example's configuration. This step is essential for authenticating with Cerebras API or other Vercel AI SDK compatible providers.
```JavaScript
apiKey: "API_KEY"
```
--------------------------------
### Install UI2 SDK
Source: https://github.com/evanzhoudev/ui2/blob/main/docs/content/docs/quick-start/setup-ui2.mdx
Instructions for installing the UI2 SDK using various package managers like NPM, PNPM, Bun, and Yarn.
```bash
npm i ui2-sdk
```
```bash
pnpm add ui2-sdk
```
```bash
bun add ui2-sdk
```
```bash
yarn add ui2-sdk
```
--------------------------------
### Complete UI2 Setup and Intent Identification Example
Source: https://github.com/evanzhoudev/ui2/blob/main/docs/content/docs/quick-start/identifying-intents.mdx
This comprehensive example illustrates the full setup of the `ui2-sdk`. It initializes `createUI2` with a model, defines two intents ('sum' and 'square') using Zod for parameter validation and `onIntent` callbacks for execution, and then demonstrates calling `identifyIntent` with a sample query.
```ts
import { createUI2 } from "ui2-sdk";
import { z } from "zod";
import { createCerebras } from "@ai-sdk/cerebras";
const cerebras = createCerebras({
apiKey: "API_KEY"
});
let { identifyIntent } = createUI2({
model: cerebras("llama-3.3-70b")
})
.addIntent("sum", {
parameters: z.object({
a: z.number(),
b: z.number()
}),
description: "Add two numbers together",
onIntent: (intentCall) => {
console.log(
`${intentCall.parameters.a} + ${intentCall.parameters.b} = ${
intentCall.parameters.a + intentCall.parameters.b
}`
);
}
})
.addIntent("square", {
parameters: z.object({
a: z.number()
}),
description: "Squares a number",
onIntent: (intentCall) => {
console.log(
`${intentCall.parameters.a}^2 = ${
intentCall.parameters.a * intentCall.parameters.a
}`
);
}
});
identifyIntent("what is 2+2");
```
--------------------------------
### Install UI2 SDK
Source: https://github.com/evanzhoudev/ui2/blob/main/docs/content/docs/react-quick-start/making-ui2-app.mdx
Install the core UI2 SDK package into your project using npm or your preferred package manager. This provides the necessary components and hooks for building UI2 applications.
```sh
npm i ui2-sdk
```
--------------------------------
### Basic Intent Setup with useUI2 Hook
Source: https://github.com/evanzhoudev/ui2/blob/main/docs/content/docs/react-quick-start/adding-intents.mdx
Demonstrates the initial setup of the `useUI2` hook and the `addIntent` call for the 'addTodo' functionality, showing where intent configuration will be placed.
```jsx
let { inputValue, handleInputChange, handleSubmit } = useUI2({
model: cerebras("llama-3.3-70b"),
systemPrompt: "This is a todo app.",
context: todos.filter((x) => !x.preview),
}).addIntent("addTodo", {
// config here...
});
```
--------------------------------
### Install UI2 SDK with JavaScript Package Managers
Source: https://github.com/evanzhoudev/ui2/blob/main/docs/content/docs/installation.mdx
Instructions for installing the UI2 SDK using common JavaScript package managers like npm, pnpm, Bun, and Yarn. The UI2 SDK is currently only available as a JS/TS package.
```bash
npm i ui2-sdk
```
```bash
pnpm add ui2-sdk
```
```bash
bun add ui2-sdk
```
```bash
yarn add ui2-sdk
```
--------------------------------
### Run React Development Server
Source: https://github.com/evanzhoudev/ui2/blob/main/examples/react-quick-start/README.md
This command starts the local development server for the React application. Before running, ensure you have replaced 'API_KEY' with your actual Cerebras API key in 'app/page.tsx' for proper functionality.
```bash
npm run dev
```
--------------------------------
### Install AI SDK Dependencies
Source: https://github.com/evanzhoudev/ui2/blob/main/docs/content/docs/quick-start/setup-ui2.mdx
Install required dependencies for UI2, including `@ai-sdk/cerebras` and `zod`, which are used for model integration and schema validation.
```bash
npm i @ai-sdk/cerebras zod
```
--------------------------------
### Run Your UI2 Application
Source: https://github.com/evanzhoudev/ui2/blob/main/docs/content/docs/react-quick-start/making-ui2-app.mdx
Start the development server for your Next.js application. Keep the server running to observe changes in real-time as you continue developing your UI2 app.
```sh
npm run dev
```
--------------------------------
### Complete UI2 Integration in Next.js Todo App
Source: https://github.com/evanzhoudev/ui2/blob/main/docs/content/docs/react-quick-start/setup-ui2.mdx
This comprehensive snippet presents the complete `page.tsx` file, integrating all previously discussed UI2 setup steps. It includes state management for todos, `useUI2` hook initialization with Cerebras model, system prompt, and filtered context, along with the connected UI elements, providing a fully functional UI2-powered todo application.
```jsx
"use client";
import { useUI2 } from "ui2-sdk/react";
import { createCerebras } from "@ai-sdk/cerebras";
import { useState } from "react";
export default function Page() {
const [todos, setTodos] = useState<
{
id: string;
name: string;
completed: boolean;
status: boolean;
}[]
>([]);
let cerebras = createCerebras({
apiKey: "API_KEY",
});
let { inputValue, handleInputChange, handleSubmit } = useUI2({
model: cerebras("llama-3.3-70b"),
systemPrompt: "This is a todo app.",
context: todos.filter((x) => !x.preview),
});
return (
{todos.length
? todos.map((x) => (
{x.name} - {x.completed ? "Completed" : "Todo"}
))
: "No todos"}
handleInputChange(e.target.value)}
/>
);
}
```
--------------------------------
### UI2 Example Intent: completeTodo
Source: https://github.com/evanzhoudev/ui2/blob/main/docs/content/docs/react-quick-start/thinking-in-ui2.mdx
Illustrates the `completeTodo` intent with its specific parameters and actions for each lifecycle event (`onIntent`, `onCleanup`, `onSubmit`), demonstrating how to preview, clean up, and confirm marking a todo item as complete.
```APIDOC
Intent: completeTodo
Parameters: Which todo to mark as complete (string/ID)
onIntent: Show a preview of the todo to be marked as complete
onCleanup: Remove the preview
onSubmit: Actually mark the todo as complete
```
--------------------------------
### Install UI2 SDK with NPM
Source: https://github.com/evanzhoudev/ui2/blob/main/README.md
This command installs the UI2 SDK package using npm, a popular Node.js package manager. It allows developers to integrate UI2 functionalities into their projects.
```bash
npm i ui2-sdk
```
--------------------------------
### Add System Prompt to useUI2 Configuration
Source: https://github.com/evanzhoudev/ui2/blob/main/docs/content/docs/react-quick-start/setup-ui2.mdx
This snippet extends the `useUI2` hook configuration by adding a `systemPrompt`. The system prompt provides context to the underlying AI model, guiding its behavior and informing it about the application's purpose, such as 'This is a todo app.'
```jsx
let { inputValue, handleInputChange, handleSubmit } = useUI2({
model: cerebras("llama-3.3-70b"),
systemPrompt: "This is a todo app.",
});
```
--------------------------------
### Install Other Dependencies
Source: https://github.com/evanzhoudev/ui2/blob/main/docs/content/docs/react-quick-start/making-ui2-app.mdx
Install additional required dependencies for the UI2 application. This includes 'zod' for schema validation and '@ai-sdk/cerebras' for AI model integration, using npm or your preferred package manager.
```sh
npm i zod @ai-sdk/cerebras
```
--------------------------------
### Run Next.js Development Server
Source: https://github.com/evanzhoudev/ui2/blob/main/docs/README.md
This snippet provides commands to start the local development server for the Next.js application. Users can choose their preferred package manager (npm, pnpm, or yarn) to run the 'dev' script, which will make the application accessible via http://localhost:3000 in a web browser.
```bash
npm run dev
# or
pnpm dev
# or
yarn dev
```
--------------------------------
### Run UI2 Spreadsheet Development Server
Source: https://github.com/evanzhoudev/ui2/blob/main/examples/spreadsheet/README.md
This command starts the local development server for the UI2 Spreadsheet application. It allows you to view and interact with the application in your browser during development.
```bash
npm run dev
```
--------------------------------
### UI2 Example Intent: addTodo
Source: https://github.com/evanzhoudev/ui2/blob/main/docs/content/docs/react-quick-start/thinking-in-ui2.mdx
Illustrates the `addTodo` intent with its specific parameters and actions for each lifecycle event (`onIntent`, `onCleanup`, `onSubmit`), demonstrating how to preview, clean up, and confirm a new todo item.
```APIDOC
Intent: addTodo
Parameters: Name of the todo (string)
onIntent: Show a preview of the new todo, to be added
onCleanup: Remove the preview
onSubmit: Actually add the new todo to the list
```
--------------------------------
### Run UI2 Todo App Development Server
Source: https://github.com/evanzhoudev/ui2/blob/main/examples/todo-list/README.md
This command starts the local development server for the UI2 Todo App. Before running, ensure you've replaced `apiKey: "API_KEY"` with your Cerebras API key in `app/components/TodoApp.tsx`.
```bash
npm run dev
```
--------------------------------
### Zod Parameters Schema Example
Source: https://github.com/evanzhoudev/ui2/blob/main/docs/content/docs/api-reference/addIntent.mdx
An example demonstrating how to define a Zod object schema for intent parameters, specifying two number fields `a` and `b`.
```typescript
parameters: z.object({
a: z.number(),
b: z.number()
});
```
--------------------------------
### Run UI2 Photo Editor Development Server
Source: https://github.com/evanzhoudev/ui2/blob/main/examples/photo-editor/README.md
This command starts the local development server for the UI2 Photo Editor. Ensure you have configured your API key in `app/components/PhotoEditor.tsx` before running.
```bash
npm run dev
```
--------------------------------
### React Hook Example: Building a Todo App with useUI2
Source: https://github.com/evanzhoudev/ui2/blob/main/docs/content/docs/react-hook-reference.mdx
This example demonstrates how to use the `useUI2` React hook to manage input state and handle user intents in a todo application. It showcases `inputValue`, `handleInputChange`, `handleSubmit`, and the `addIntent` method with `onIntent`, `onCleanup`, and `onSubmit` callbacks for managing asynchronous updates and UI previews.
```tsx
"use client";
import { useUI2 } from "ui2-sdk/react";
import { createCerebras } from "@ai-sdk/cerebras";
import { useState } from "react";
import { z } from "zod";
export default function Page() {
const [todos, setTodos] = useState<
{
id: string;
name: string;
completed: boolean;
preview: boolean;
}[]
>([]);
let cerebras = createCerebras({
apiKey: "API_KEY",
});
let { inputValue, handleInputChange, handleSubmit } = useUI2({
model: cerebras("llama-3.3-70b"),
systemPrompt: "This is a todo app.",
context: todos.filter(x => !x.preview),
})
.addIntent("addTodo", {
description: "Add a todo",
parameters: z.object({
name: z.string(),
}),
onIntent: ({ parameters, id }) => {
setTodos((prev) => [
...prev,
{
id,
name: parameters.name,
completed: false,
preview: true,
},
]);
},
onCleanup: ({parameters, id}) => {
setTodos((prev) => prev.filter((x) => x.id !== id))
},
onSubmit: ({ id }) =>
setTodos((prev) =>
prev.map((x) => (x.id === id ? { ...x, preview: false } : x))
),
})
.addIntent("completeTodo", {
description: "complete a todo",
parameters: z.object({
id: z.string(),
}),
onIntent: ({ parameters }) => {
setTodos((prev) =>
prev.map((x) =>
x.id === parameters.id
? { ...x, preview: true, completed: true }
: x
)
);
},
onCleanup: ({ parameters }) => {
setTodos((prev) =>
prev.map((x) =>
x.id === parameters.id
? { ...x, preview: false, completed: false }
: x
)
);
},
onSubmit: ({ parameters }) =>
setTodos((prev) =>
prev.map((x) =>
x.id === parameters.id
? { ...x, preview: false, completed: true }
: x
)
),
});
return (
{todos.length
? todos.map((x) => (
{x.name} - {x.completed ? "Completed" : "Todo"}
))
: "No todos"}
handleInputChange(e.target.value)}
/>
);
}
```
--------------------------------
### Configuring UI2 SDK with Catch-all 'other' Intent
Source: https://github.com/evanzhoudev/ui2/blob/main/docs/content/docs/examples/other-intent.mdx
This TypeScript example demonstrates how to initialize the `ui2-sdk` and configure a catch-all 'other' intent. It shows the use of `createUI2` and `addOther` methods, alongside a standard `addIntent` for 'sum', to handle both specific and unhandled user queries.
```ts
import { createUI2 } from "ui2-sdk";
import { cerebras } from "@ai-sdk/cerebras";
import { z } from "zod";
let { identifyIntent } = createUI2({
model: cerebras("llama-3.3-70b")
})
.addIntent("sum", {
parameters: z.object({
a: z.number(),
b: z.number()
}),
description: "Add two numbers together",
onIntent: (intentCall) => {
console.log(
`${intentCall.parameters.a} + ${intentCall.parameters.b} = ${
intentCall.parameters.a + intentCall.parameters.b
}`
);
}
})
.addOther({
description: "Use this for any other mathematical operation",
onIntent: (intentCall) => console.log("That operation has no intent!")
});
identifyIntent("what is log base 2 of 4?");
```
--------------------------------
### addIntent with onIntent Callback Example
Source: https://github.com/evanzhoudev/ui2/blob/main/docs/content/docs/api-reference/addIntent.mdx
Illustrates how to use the `addIntent` function with a `parameters` schema and an `onIntent` callback that logs the sum of two numbers from the identified intent's parameters.
```typescript
.addIntent("sum", {
parameters: z.object({
a: z.number(),
b: z.number()
}),
description: "Add two numbers together",
onIntent: (intentCall) => {
console.log(
`${intentCall.parameters.a} + ${intentCall.parameters.b} = ${intentCall.parameters.a + intentCall.parameters.b}`
);
}
});
```
--------------------------------
### Chain Multiple Intents in UI2 SDK
Source: https://github.com/evanzhoudev/ui2/blob/main/docs/content/docs/quick-start/adding-intents.mdx
This TypeScript example illustrates how to add multiple intents to a UI2 application by chaining `.addIntent` calls. It extends the previous example by adding a 'square' intent, which takes a single number parameter (`a`) and logs its square. This demonstrates the scalability and ease of defining multiple behaviors within the UI2 framework by simply chaining intent definitions.
```ts
import { createUI2 } from "ui2-sdk";
import { z } from "zod";
import { createCerebras } from "@ai-sdk/cerebras";
const cerebras = createCerebras({
apiKey: "API_KEY",
});
let { identifyIntent } = createUI2({
model: cerebras("llama-3.3-70b"),
})
.addIntent("sum", {
parameters: z.object({
a: z.number(),
b: z.number(),
}),
description: "Add two numbers together",
onIntent: (intentCall) => {
console.log(
`${intentCall.parameters.a} + ${intentCall.parameters.b} = ${
intentCall.parameters.a + intentCall.parameters.b
}`
);
},
})
.addIntent("square", {
parameters: z.object({
a: z.number(),
}),
description: "Squares a number",
onIntent: (intentCall) => {
console.log(
`${intentCall.parameters.a}^2 = ${
intentCall.parameters.a * intentCall.parameters.a
}`
);
},
});
```
--------------------------------
### Example UI2 Intents for Sum and Square App
Source: https://github.com/evanzhoudev/ui2/blob/main/docs/content/docs/quick-start/thinking-in-ui2.mdx
Illustrates the definition of two specific intents, `sum` and `square`, for a 'Sum and Square' application. Each intent specifies its parameters and the action performed by its `onIntent` function.
```APIDOC
Intent: sum
parameters:
- number1: number
- number2: number
onIntent:
- Logs the sum of number1 and number2.
Intent: square
parameters:
- todo_item: string (Which todo to mark as complete)
onIntent:
- Shows a preview of the todo to be marked as complete.
```
--------------------------------
### Implement a UI2 React Todo Application
Source: https://github.com/evanzhoudev/ui2/blob/main/docs/content/docs/react-quick-start/overview.mdx
This TypeScript React code demonstrates a complete Todo application integrated with UI2. It utilizes the `useUI2` hook to define 'addTodo' and 'completeTodo' intents, managing todo items' state with React's `useState`. The application showcases real-time intent identification and submission based on user input, including preview states for pending actions and cleanup logic for uncommitted intents. It depends on `ui2-sdk/react`, `@ai-sdk/cerebras`, and `zod` for schema validation.
```tsx
"use client";
import { useUI2 } from "ui2-sdk/react";
import { createCerebras } from "@ai-sdk/cerebras";
import { useState } from "react";
import { z } from "zod";
export default function Page() {
const [todos, setTodos] = useState<
{
id: string;
name: string;
completed: boolean;
preview: boolean;
}[]
>([]);
let cerebras = createCerebras({
apiKey: "API_KEY",
});
let { inputValue, handleInputChange, handleSubmit } = useUI2({
model: cerebras("llama-3.3-70b"),
systemPrompt: "This is a todo app.",
context: todos.filter((x) => !x.preview),
})
.addIntent("addTodo", {
description: "Add a todo",
parameters: z.object({
name: z.string(),
}),
onIntent: ({ parameters, id }) => {
setTodos((prev) => [
...prev,
{
id,
name: parameters.name,
completed: false,
preview: true,
},
]);
},
onCleanup: ({ parameters, id }) => {
setTodos((prev) => prev.filter((x) => x.id !== id));
},
onSubmit: ({ id }) =>
setTodos((prev) =>
prev.map((x) => (x.id === id ? { ...x, preview: false } : x))
),
})
.addIntent("completeTodo", {
description: "complete a todo",
parameters: z.object({
id: z.string(),
}),
onIntent: ({ parameters }) => {
setTodos((prev) =>
prev.map((x) =>
x.id === parameters.id
? { ...x, preview: true, completed: true }
: x
)
);
},
onCleanup: ({ parameters }) => {
setTodos((prev) =>
prev.map((x) =>
x.id === parameters.id
? { ...x, preview: false, completed: false }
: x
)
);
},
onSubmit: ({ parameters }) =>
setTodos((prev) =>
prev.map((x) =>
x.id === parameters.id
? { ...x, preview: false, completed: true }
: x
)
),
});
return (
{todos.length
? todos.map((x) => (
{x.name} - {x.completed ? "Completed" : "Todo"}
))
: "No todos"}
handleInputChange(e.target.value)}
/>
);
}
```
--------------------------------
### Initialize UI2 SDK and Destructure identifyIntent
Source: https://github.com/evanzhoudev/ui2/blob/main/docs/content/docs/api-reference/createUI2.mdx
This TypeScript example demonstrates how to initialize the `ui2-sdk` using `createUI2`, configuring it with a Cerebras model and a system prompt. It also shows how to destructure the `identifyIntent` method from the returned `IntentCreator` instance for direct use, along with `onLoadStart` and `onLoadEnd` callbacks.
```TypeScript
import { createUI2 } from "ui2-sdk";
import { cerebras } from "@ai-sdk/cerebras";
import { z } from "zod";
let { identifyIntent } = createUI2({
model: cerebras("llama-3.3-70b"),
systemPrompt: "You are identifying intents on a todo app.",
onLoadStart: () => console.log("Loading started!"),
onLoadEnd: () => console.log("Loading finished")
});
```
--------------------------------
### Initialize UI2 and Define Intents for Sum and Square Operations (TypeScript)
Source: https://github.com/evanzhoudev/ui2/blob/main/docs/content/docs/quick-start/overview.mdx
This TypeScript code initializes the UI2 SDK with a Cerebras model, then defines two distinct intents: 'sum' for adding two numbers and 'square' for squaring a single number. Each intent specifies its required parameters using Zod for validation and includes an `onIntent` callback to perform and log the respective calculation when the intent is identified. Finally, it demonstrates identifying an intent from a sample text.
```TypeScript
import { createUI2 } from "ui2-sdk";
import { z } from "zod";
import { createCerebras } from "@ai-sdk/cerebras";
const cerebras = createCerebras({
apiKey: "API_KEY",
});
let { identifyIntent } = createUI2({
model: cerebras("llama-3.3-70b"),
})
.addIntent("sum", {
parameters: z.object({
a: z.number(),
b: z.number(),
}),
description: "Add two numbers together",
onIntent: (intentCall) => {
console.log(
`${intentCall.parameters.a} + ${intentCall.parameters.b} = ${
intentCall.parameters.a + intentCall.parameters.b
}`
);
},
})
.addIntent("square", {
parameters: z.object({
a: z.number(),
}),
description: "Squares a number",
onIntent: (intentCall) => {
console.log(
`${intentCall.parameters.a}^2 = ${
intentCall.parameters.a * intentCall.parameters.a
}`
);
},
});
identifyIntent("what is 2+2");
```
--------------------------------
### Identify Intent Method
Source: https://github.com/evanzhoudev/ui2/blob/main/docs/content/docs/api-reference/intentCreator.mdx
This method identifies intents from a given text input. It takes the text to identify and an optional configuration object. The configuration object can include `currentIntents` to guide the identification process, determining which intents to trigger, ignore, or clean up. This is primarily an internal API.
```APIDOC
async identifyIntent(text: string, config?: IdentifyIntentConfig): IntentCall[]
text: string - The current text to identify.
config?: IdentifyIntentConfig - Optional configuration object.
currentIntents: IntentCalls[] - An array of IntentCalls[] used to determine which intents to trigger, do nothing, or cleanup.
```
```TypeScript
async identifyIntent(text: string, config?: IdentifyIntentConfig): IntentCall[]
```
--------------------------------
### Dynamically Add and Remove UI2 Intents in TypeScript
Source: https://github.com/evanzhoudev/ui2/blob/main/docs/content/docs/examples/dynamic-intents.mdx
This TypeScript example demonstrates how to dynamically manage intents using the `ui2-sdk`. It initializes UI2 with a 'sum' intent, then removes it and adds a new 'square' intent, showcasing the flexibility of `addIntent` and `removeIntent` functions. It also highlights the use of `zod` for defining intent parameters and `cerebras` for the model.
```TypeScript
import { createUI2 } from "ui2-sdk";
import { cerebras } from "@ai-sdk/cerebras";
import { z } from "zod";
let { identifyIntent, removeIntent, addIntent } = createUI2({
model: cerebras("llama-3.3-70b"),
}).addIntent("sum", {
parameters: z.object({
a: z.number(),
b: z.number()
}),
description: "Add two numbers together",
onIntent: (intentCall) => {
console.log(
`${intentCall.parameters.a} + ${intentCall.parameters.b} = ${
intentCall.parameters.a + intentCall.parameters.b
}`
);
}
});
removeIntent("sum");
addIntent("square", {
parameters: z.object({
a: z.number()
}),
description: "Squares a number",
onIntent: (intentCall) => {
console.log(
`${intentCall.parameters.a}^2 = ${
intentCall.parameters.a * intentCall.parameters.a
}`
);
}
});
```
--------------------------------
### Initialize Todo State and Basic UI in Next.js
Source: https://github.com/evanzhoudev/ui2/blob/main/docs/content/docs/react-quick-start/setup-ui2.mdx
This snippet sets up the initial React component for a todo application. It defines a state variable `todos` to manage a list of todo items, each with an ID, name, completion status, and a preview flag. It also renders a simple UI to display todos and includes placeholder input and submit elements.
```jsx
"use client";
import { useUI2 } from "ui2-sdk/react";
import { useState } from "react";
export default function Page() {
const [todos, setTodos] = useState<
{
id: string;
name: string;
completed: boolean;
preview: string;
}[]
>([]);
return (
{todos.length
? todos.map((x) => (
{x.name} - {x.completed ? "Completed" : "Todo"}
))
: "No todos"}
);
}
```
--------------------------------
### Prepare the Main Application File (page.tsx)
Source: https://github.com/evanzhoudev/ui2/blob/main/docs/content/docs/react-quick-start/making-ui2-app.mdx
Set up the main page component for your UI2 application. This snippet demonstrates a basic 'Hello UI2!' page, importing the 'useUI2' hook from 'ui2-sdk/react' to enable UI2 functionalities.
```jsx
"use client";
import { useUI2 } from "ui2-sdk/react";
export default function Page() {
return (
Hello UI2!
);
}
```
--------------------------------
### Run UI2 Application
Source: https://github.com/evanzhoudev/ui2/blob/main/docs/content/docs/quick-start/setup-ui2.mdx
Instructions for running the UI2 application using Node.js, applicable for both compiled TypeScript or direct JavaScript execution.
```bash
node yourCode.js
```
--------------------------------
### Basic Integration of useUI2 Hook
Source: https://github.com/evanzhoudev/ui2/blob/main/docs/content/docs/react-quick-start/setup-ui2.mdx
This snippet demonstrates the basic destructuring of the `useUI2` hook from `ui2-sdk/react`. It shows how to obtain `inputValue`, `handleInputChange`, and `handleSubmit` variables and functions, which are essential for managing UI2's input and submission logic.
```jsx
let { inputValue, handleInputChange, handleSubmit } = useUI2({
// config here...
});
```
--------------------------------
### Initialize UI2 and Identify Intent
Source: https://github.com/evanzhoudev/ui2/blob/main/docs/content/docs/quick-start/setup-ui2.mdx
Import `createUI2` from `ui2-sdk` and initialize it. This sets up the core UI2 application and provides access to functions like `identifyIntent` for text processing.
```ts
import { createUI2 } from "ui2-sdk";
let { identifyIntent } = createUI2({});
```
--------------------------------
### Create a Next.js App
Source: https://github.com/evanzhoudev/ui2/blob/main/docs/content/docs/react-quick-start/making-ui2-app.mdx
Initialize a new Next.js project using the latest version of create-next-app. Follow the prompts to configure your application, ideally selecting TypeScript and Tailwind CSS for compatibility with UI2.
```sh
npx create-next-app@latest
```
--------------------------------
### Configure UI2 with Cerebras Model
Source: https://github.com/evanzhoudev/ui2/blob/main/docs/content/docs/quick-start/setup-ui2.mdx
Set up UI2 to use a specific model, such as `llama-3.3-70b` from Cerebras, by importing `createCerebras` and passing the initialized model to `createUI2`. This enables structured output capabilities.
```ts
import { createUI2 } from "ui2-sdk";
import { createCerebras } from "@ai-sdk/cerebras";
const cerebras = createCerebras({
apiKey: "API_KEY"
});
let { identifyIntent } = createUI2({
model: cerebras("llama-3.3-70b")
});
```
--------------------------------
### createUI2 Function Parameters
Source: https://github.com/evanzhoudev/ui2/blob/main/docs/content/docs/api-reference/createUI2.mdx
Detailed documentation for the `createUI2` wrapper function, outlining its parameters, their types, descriptions, and specific usage notes, including model configuration and various lifecycle callbacks for intent processing.
```APIDOC
createUI2(parameters: object): IntentCreator instance
Parameters:
model: LanguageModel | Model Configuration
Description: Configure the model to use with UI2.
Options:
- Vercel AI SDK compatible LanguageModel (e.g., from @ai-sdk/providers)
- Object schema:
baseURL: string
apiKey: string
modelId: string
Note: UI2 requires models supporting Structured Output.
systemPrompt: string
Description: Additional instructions for the AI to guide intent identification. Should be general, specific instructions can be per intent.
context: object
Description: Supplies context to the AI. Must have a stable reference; updates to reference update context. Can have any schema.
onLoadStart: () => void
Description: Callback called when AI loading starts.
onLoadEnd: () => void
Description: Callback called when AI loading ends.
onPartialIntent: (partialIntents: IntentCall[]) => void
Description: Low-level callback called on each stream part for the intent. The IntentCall objects may be incomplete. Useful for live streaming incomplete tool calls.
onIntent: (intentCall: IntentCall, input?: string) => void
Description: Callback called when any full intent is detected. Provides the IntentCall object and current input. Useful for global intent processing.
onCleanup: (intentCall: IntentCall, input?: string) => void
Description: Callback called when any full Intent is cleaned up (no longer identified). Provides the IntentCall object and current input. Useful for global intent processing.
```
--------------------------------
### Implement completeTodo Intent with Lifecycle Callbacks
Source: https://github.com/evanzhoudev/ui2/blob/main/docs/content/docs/react-quick-start/adding-intents.mdx
This code demonstrates the initial implementation of the `completeTodo` intent, including `onIntent`, `onCleanup`, and `onSubmit` callbacks. It shows how to update a todo item's `preview` and `completed` status based on the intent's lifecycle, using `parameters.id` to identify the target todo.
```tsx
.addIntent("completeTodo", {
description: "complete a todo",
parameters: z.object({
id: z.string(),
}),
onIntent: ({ parameters }) => {
setTodos((prev) =>
prev.map((x) =>
x.id === parameters.id
? { ...x, preview: true, completed: true }
: x
)
);
},
onCleanup: ({ parameters, id }) =>
setTodos((prev) =>
prev.map((x) =>
x.id === parameters.id
? { ...x, preview: false, completed: false }
: x
)
),
onSubmit: ({ parameters, id }) =>
setTodos((prev) =>
prev.map((x) =>
x.id === parameters.id
? { ...x, preview: false, completed: true }
: x
)
),
});
```
--------------------------------
### Provide Application Context to useUI2 Hook
Source: https://github.com/evanzhoudev/ui2/blob/main/docs/content/docs/react-quick-start/setup-ui2.mdx
This snippet demonstrates how to pass relevant application state as `context` to the `useUI2` hook. By providing filtered `todos` data, the AI model can use this information to better understand user intents and generate appropriate responses or actions, enhancing the app's intelligence.
```jsx
let { inputValue, handleInputChange, handleSubmit } = useUI2({
model: cerebras("llama-3.3-70b"),
systemPrompt: "This is a todo app.",
context: todos.filter((x) => !x.preview),
});
```
--------------------------------
### addIntent Parameters Reference
Source: https://github.com/evanzhoudev/ui2/blob/main/docs/content/docs/api-reference/addIntent.mdx
Detailed documentation for the parameters accepted by the `addIntent` function, including their types and descriptions.
```APIDOC
Value Name | Type | Description
:------------ | :---------------------------------------------------- | :--------------------------------------------------
`parameters` | `z.ZodType` (default: `z.ZodObject`) | Zod schema defining the parameters for this intent.
`description` | `string` | Description of what the intent does.
`onIntent` | `(intentCall: IntentCall, input?: string) => void` | Called when this intent is identified.
`onCleanup` | `(intentCall: IntentCall, input?: string) => void` | Called when this intent is no longer detected.
```
--------------------------------
### Implement onIntent Callback for Todo Preview
Source: https://github.com/evanzhoudev/ui2/blob/main/docs/content/docs/react-quick-start/adding-intents.mdx
Shows the implementation of the `onIntent` callback for the 'addTodo' intent. It creates a new todo item with a `preview: true` status, allowing the UI to display a temporary preview before final submission.
```jsx
let { inputValue, handleInputChange, handleSubmit } = useUI2({
model: cerebras("llama-3.3-70b"),
systemPrompt: "This is a todo app.",
context: todos.filter((x) => !x.preview),
}).addIntent("addTodo", {
description: "Add a todo",
parameters: z.object({
name: z.string(),
}),
onIntent: ({ parameters, id }) => {
setTodos((prev) => [
...prev,
{
id,
name: parameters.name,
completed: false,
preview: true,
},
]);
},
});
```
--------------------------------
### Define Intent Description and Zod Parameters
Source: https://github.com/evanzhoudev/ui2/blob/main/docs/content/docs/react-quick-start/adding-intents.mdx
Illustrates how to define the `description` for the 'addTodo' intent and specify its `parameters` using Zod for type validation, ensuring structured output from the AI.
```jsx
let { inputValue, handleInputChange, handleSubmit } = useUI2({
model: cerebras("llama-3.3-70b"),
systemPrompt: "This is a todo app.",
context: todos.filter((x) => !x.preview),
}).addIntent("addTodo", {
description: "Add a todo",
parameters: z.object({
name: z.string(),
}),
});
```
--------------------------------
### IntentCreator Class Constructor and Configuration
Source: https://github.com/evanzhoudev/ui2/blob/main/docs/content/docs/api-reference/intentCreator.mdx
Documents the `IntentCreator` class constructor, detailing its configuration object parameters. This includes options for specifying the AI model, providing system prompts and context, and defining various lifecycle callbacks for intent processing.
```APIDOC
IntentCreator:
__init__(config: object)
config:
model: LanguageModel | object
description: Configure the model to use with UI2. Supports Vercel AI SDK LanguageModel or a custom configuration object.
systemPrompt: string
description: Additional instructions for the AI to guide its intent identification.
context: object
description: An object supplying context to the AI, which is JSON.stringify()'d before being provided. Should have a stable reference.
onLoadStart: () => void
description: Callback invoked when the AI starts loading.
onLoadEnd: () => void
description: Callback invoked when the AI finishes loading.
onPartialIntent: (partialIntents: IntentCall[]) => void
description: Low-level callback invoked on each stream part for the intent. The returned IntentCall properties may be incomplete.
onIntent: (intentCall: IntentCall, input?: string) => void
description: Callback invoked when any full intent is detected, providing the IntentCall object and the current input.
onCleanup: (intentCall: IntentCall, input?: string) => void
description: Callback invoked when any full Intent is cleaned up (no longer identified), providing the IntentCall object and the current input.
```
```js
{
baseURL: string,
apiKey: string,
modelId: string
}
```
--------------------------------
### StatefulIntentCreator onSubmitStart and onSubmitEnd Event Listeners
Source: https://github.com/evanzhoudev/ui2/blob/main/docs/content/docs/statefulIntentCreator.mdx
Details the `onSubmitStart` and `onSubmitEnd` event listeners, which manage the submission process in `StatefulIntentCreator`. It clarifies their respective triggers and the reason for the delay between them.
```APIDOC
Event Listener: onSubmitStart
Type: (input?: string) => void
Description: Called immediately when the submission process begins. By default, this clears the input box, but this behavior can be modified. Input box content is preserved internally.
Event Listener: onSubmitEnd
Type: (input?: string) => void
Description: Called when all processing related to the submission has been finished.
Note: Submission is not instantaneous due to potential ongoing intent detection or new intent detection starts, necessitating two distinct event listeners.
```
--------------------------------
### StatefulIntentCreator Constructor Definition
Source: https://github.com/evanzhoudev/ui2/blob/main/docs/content/docs/statefulIntentCreator.mdx
Documents the constructor for `StatefulIntentCreator`, detailing its configuration object parameters and additional state management properties. It highlights the differences from the standard IntentCreator constructor.
```APIDOC
StatefulIntentCreator Constructor:
__init__(configuration: object, inputValue: string, setInputValue: Function, isLoading: boolean, setIsLoading: Function)
Configuration Object Properties:
debounceDelay:
Type: number
Description: In milliseconds, the debounce delay for intent identification.
onSubmitStart:
Type: (input?: string) => void
Description: Called when the submission process starts.
onSubmitEnd:
Type: (input?: string) => void
Description: Called when the submission process completes.
Additional Constructor Parameters (after configuration):
inputValue:
Type: string
Description: Getter for the state of the UI2 input.
setInputValue:
Type: Function
Description: Setter for the state of the UI2 input.
isLoading:
Type: boolean
Description: Getter for the state of the loading indicator.
setIsLoading:
Type: Function
Description: Setter for the state of the loading indicator.
```
--------------------------------
### Direct Usage of IntentCreator Class
Source: https://github.com/evanzhoudev/ui2/blob/main/docs/content/docs/api-reference-overview.mdx
Demonstrates how to directly instantiate and use the `IntentCreator` class to add multiple intents and then identify an intent based on a given string. This approach requires maintaining a reference to the `IntentCreator` instance.
```ts
let ic = new IntentCreator();
ic.addIntent("intent1", {
// config...
});
ic.addIntent("intent2", {
// config...
});
ic.addIntent("intent3", {
// config...
});
ic.identifyIntent("some intent");
```
--------------------------------
### General UI2 Intent Lifecycle Flow
Source: https://github.com/evanzhoudev/ui2/blob/main/docs/content/docs/react-quick-start/thinking-in-ui2.mdx
Provides a general overview of the expected behavior for each UI2 intent lifecycle event: `onIntent` for showing previews, `onCleanup` for removing previews, and `onSubmit` for confirming actions.
```APIDOC
Intent Lifecycle General Flow:
onIntent:
- Typically the first event listener called, when the intent is detected.
- Responsible for showing a preview of the user's Intent, translated to Action.
onCleanup:
- Possibly called after `onIntent`, after the intent is no longer detected.
- Responsible for removing that preview of the user's Intent to "clean up" any side-effects.
onSubmit:
- Called when the user "submits" the intent by confirming. Cleanup is _not_ called when submitted.
- Responsible for "confirming" the preview.
```
--------------------------------
### React Hook Configuration for UI2
Source: https://github.com/evanzhoudev/ui2/blob/main/docs/content/docs/react-hook-reference.mdx
Describes the configuration options available when initializing the React Hook for UI2, which are identical to `createUI2`. These parameters control the language model, system prompts, context, and various lifecycle callbacks for AI processing.
```APIDOC
Configuration Parameters:
- model: LanguageModel or Model Configuration
Description: Configure the model to use with UI2.
- systemPrompt: string
Description: Additional instructions for the AI.
- context: object
Description: Context for intent identification
- onLoadStart: () => void
Description: Called when AI loading starts.
- onLoadEnd: () => void
Description: Called when AI loading ends.
- onPartialIntent: (partialIntents: IntentCall[]) => void;
Description: Called on each stream part for the intent.
- onIntent: (intentCall: IntentCall, input?: string) => void
Description: Called when any full intent is detected.
- onCleanup: (intentCall: IntentCall, input?: string) => void
Description: Called when any full Intent is cleaned up.
```
--------------------------------
### UI2 SDK addOther Method Configuration
Source: https://github.com/evanzhoudev/ui2/blob/main/docs/content/docs/examples/other-intent.mdx
This API documentation outlines the specific parameters available for configuration when using the `addOther` method in the UI2 SDK. It highlights that `addOther` functions similarly to `addIntent` but with a restricted set of customizable options, specifically excluding the ability to pass a name or define parameters.
```APIDOC
addOther method configurable parameters:
description: string - A description for the 'other' intent.
onIntent: function - Callback executed when the intent transitions to 'other' from a non-'other' state.
onCleanup: function - Callback for cleanup operations.
onSubmit: function - Callback for submission (typically with React hook).
Note: The 'other' intent cannot have a custom name or parameters defined.
```
--------------------------------
### addOther Method Parameters
Source: https://github.com/evanzhoudev/ui2/blob/main/docs/content/docs/api-reference/addOther.mdx
Details the configurable parameters for the `addOther` method, which manages the catch-all 'other' intent. It highlights the differences from `addIntent` by listing parameters that can be customized for the 'other' intent.
```APIDOC
addOther Parameters:
description:
type: string
description: Customize when the `other` intent can be called.
onIntent:
type: (intentCall: IntentCall, input?: string) => void
description: Called when this intent is identified.
onCleanup:
type: (intentCall: IntentCall, input?: string) => void
description: Called when this intent is no longer detected.
```
--------------------------------
### Using the UI2 Function Builder Syntax
Source: https://github.com/evanzhoudev/ui2/blob/main/docs/content/docs/api-reference-overview.mdx
Illustrates the more concise function builder syntax provided by `createUI2`. This pattern allows for chaining `addIntent` calls and directly destructuring methods like `identifyIntent` without needing to explicitly manage an `IntentCreator` instance.
```ts
let { identifyIntent } = createUI2()
.addIntent("intent1", {
// config...
})
.addIntent("intent2", {
// config...
})
.addIntent("intent3", {
// config...
});
identifyIntent("some intent");
```
--------------------------------
### Configure useUI2 with Cerebras AI Model
Source: https://github.com/evanzhoudev/ui2/blob/main/docs/content/docs/react-quick-start/setup-ui2.mdx
This snippet shows how to configure the `useUI2` hook to use a specific AI model, in this case, a Cerebras model. It demonstrates importing `createCerebras` from `@ai-sdk/cerebras`, initializing the model with an API key, and passing the configured model instance to the `useUI2` hook's `model` property.
```jsx
import { createCerebras } from "@ai-sdk/cerebras";
let cerebras = createCerebras({
apiKey: "API_KEY",
});
let { inputValue, handleInputChange, handleSubmit } = useUI2({
model: cerebras("llama-3.3-70b"),
});
```
--------------------------------
### UI2 Intent Structure and Lifecycle
Source: https://github.com/evanzhoudev/ui2/blob/main/docs/content/docs/react-quick-start/thinking-in-ui2.mdx
Describes the core components of a UI2 intent, including its name, optional description, parameters, and the three main lifecycle events: `onIntent`, `onCleanup`, and `onSubmit`.
```APIDOC
Intent:
name: string
description: string (optional)
parameters: list of Parameter
lifecycle_events:
onIntent: function (called when intent is identified)
onCleanup: function (called when intent is no longer relevant)
onSubmit: function (called when user submits textbox with intent)
```
--------------------------------
### Connect UI Elements to useUI2 Hook
Source: https://github.com/evanzhoudev/ui2/blob/main/docs/content/docs/react-quick-start/setup-ui2.mdx
This snippet updates the previously defined input field and submit button to integrate with the `useUI2` hook. The input's `value` is bound to `inputValue` and its `onChange` event calls `handleInputChange`. The button's `onClick` event is linked to `handleSubmit`, enabling UI2's core functionality.
```jsx
handleInputChange(e.target.value)}
/>
```
--------------------------------
### UI2 Code Naming Conventions
Source: https://github.com/evanzhoudev/ui2/blob/main/docs/content/docs/branding.mdx
Guidelines for correctly naming functions and packages related to UI2 within codebases. It specifies capitalization rules to ensure brand consistency while acknowledging standard programming conventions like reserving capitalized first letters for classes and lowercase for package names.
```General
✅ Do:
- A function written as `createUI2()`
- A function written as `ui2()`
- A package name written as `ui2-sdk`
❌ Don't Do:
- `createUi2()` or `createui2()`
- `UI2()` (as capitalized first letter is reserved for class)
- `UI2-sdk`, if your package manager prefers lowercase first letter
```