useAI
A hook that sends a prompt to an AI model and returns its reply. Use it for content that is different every time, such as a daily poem, a fun fact or a summary of data the widget already has. No API key is needed.
Like useFetch, which it is built on, the widget waits for the
reply before it renders, so data is always defined. A failed request is shown in place of the
widget, with nothing to handle in your code.
Import
import { useAI } from "~lib/use-ai";
API
const { data } = useAI({ prompt });
Parameters
| Name | Type | Required | Description |
|---|---|---|---|
prompt | string | Yes | The text to send to the model. |
Return Value
| Name | Type | Description |
|---|---|---|
data.output | string | The model's reply. |
Examples
Basic Usage
import { Paragraph } from "~lib/typography";
import { useAI } from "~lib/use-ai";
export const Widget = () => {
const { data } = useAI({
prompt: "Write a haiku about autumn",
});
// A haiku's lines are separated by line breaks, which pre-line keeps.
return (
<div className="whitespace-pre-line">
<Paragraph>{data.output}</Paragraph>
</div>
);
};
A Prompt Built From Data
The prompt is an ordinary string, so fill it with inputs or with data already fetched. Say how long the reply should be and how it should be laid out, so it fits the widget:
import { Paragraph } from "~lib/typography";
import { useAI } from "~lib/use-ai";
import { useFetch } from "~lib/use-fetch";
export const Widget = () => {
const { data: forecast } = useFetch<{ temperature: number; summary: string }>(
"https://api.example.com/forecast",
);
const { data } = useAI({
prompt: `In one short sentence, suggest what to wear today. It will be ${forecast.temperature}°C and ${forecast.summary}.`,
});
return <Paragraph>{data.output}</Paragraph>;
};
See Also
- useFetch - The hook
useAIis built on