Comment on page
useAI
Hook which asks the AI to answer a prompt and returns the AsyncState corresponding to the execution of the query.
function useAI(
prompt: string,
options?: {
creativity?: AI.Creativity;
model?: AI.Model;
stream?: boolean;
execute?: boolean;
onError?: (error: Error) => void;
onData?: (data: T) => void;
onWillExecute?: (args: string[]) -> void;
}
): AsyncState<String> & {
revalidate: () => void;
};
prompt
is the prompt to ask the AI.
With a few options:
options.creativity
is a number between 0 and 2 to control the creativity of the answer. Concrete tasks, such as fixing grammar, require less creativity while open-ended questions, such as generating ideas, require more.options.model
is a string determining which AI model will be used to answer.options.stream
is a boolean controlling whether to stream the answer or only update the data when the entire answer has been received. By default, thedata
will be streamed.
options.execute
is a boolean to indicate whether to actually execute the function or not. This is useful for cases where one of the function's arguments depends on something that might not be available right away (for example, depends on some user inputs). Because React requires every hook to be defined on the render, this flag enables you to define the hook right away but wait until you have all the arguments ready to execute the function.options.onError
is a function called when an execution fails. By default, it will log the error and show a generic failure toast with an action to retry.options.onData
is a function called when an execution succeeds.options.onWillExecute
is a function called when an execution will start.
Returns an object with the AsyncState corresponding to the execution of the function as well as a couple of methods to manipulate it.
revalidate
is a method to manually call the function with the same arguments again.
import { Detail } from "@raycast/api";
import { useAI } from "@raycast/utils";
export default function Command() {
const { data, isLoading } = useAI("Suggest 5 jazz songs");
return <Detail isLoading={isLoading} markdown={data} />;
}
An object corresponding to the execution state of the function.
// Initial State
{
isLoading: true, // or `false` if `options.execute` is `false`
data: undefined,
error: undefined
}
// Success State
{
isLoading: false,
data: string,
error: undefined
}
// Error State
{
isLoading: false,
data: undefined,
error: Error
}
// Reloading State
{
isLoading: true,
data: string | undefined,
error: Error | undefined
}
Last modified 6mo ago