///
/**
* Test pattern to validate generateObject error handling snippet for LLM.md
*
* This pattern tests the correct way to handle pending/error/result states
* with generateObject. The corrected doc example should look like this:
*
* {ifElse(idea.pending,
* Generating...,
* ifElse(idea.error,
* Error: {idea.error},
*
*
{idea.result?.name}
*
{idea.result?.description}
*
${idea.result?.price}
*
* )
* )}
*
* Note: Use optional chaining (?.) because TypeScript doesn't narrow through ifElse.
* At runtime, if we reach the inner else branch, result IS defined (pending=false, error=false).
*/
import {
Default,
derive,
generateObject,
ifElse,
NAME,
pattern,
UI,
} from "commontools";
interface ProductIdea {
name: string;
description: string;
price: number;
}
interface Input {
userInput: Default;
}
export default pattern(({ userInput }) => {
const idea = generateObject({
prompt: userInput,
system:
"Generate a creative product idea based on the user's input. Be concise.",
model: "anthropic:claude-sonnet-4-5",
});
// Derive error message as string for display
const errorMessage = derive(
idea.error,
(err) =>
err
? (typeof err === "string" ? err : JSON.stringify(err, null, 2))
: null,
);
return {
[NAME]: "GenerateObject Error Handling Test",
[UI]: (
generateObject Error Handling Test
This pattern validates the correct error handling snippet for LLM.md
Result (with proper error handling):
{/* This is the CORRECT pattern - nested ifElse for error handling */}
{/* Note: Use optional chaining (?.property) since TypeScript doesn't narrow through ifElse */}
{ifElse(
idea.pending,
Generating...
,
ifElse(
idea.error,
Error: {errorMessage},