This content originally appeared on DEV Community and was authored by AlixWang
This technical document outlines how to build an AI-powered cron expression builder using Cloudflare Pages, Next.js, and Cloudflare's AI capabilities. The result site is cronbuilder.online
Table of Contents
- Project Overview
- Technical Stack
- Setup and Configuration
- Key Components
- AI Integration
- Deployment
1. Project Overview
The AI Cron Builder is a web application that helps users create cron expressions through:
- Natural language input processing using AI
- Visual cron expression builder
- Real-time validation
2. Technical Stack
- Frontend Framework: Next.js 14
- Hosting: Cloudflare Pages
- AI Model: Cloudflare Workers AI (Llama 3)
- UI Components: Ant Design
- Styling: Tailwind CSS
3. Setup and Configuration
3.1 Project Structure
app/
├── api/
│ └── cron/ # AI endpoint
├── components/ # React components
├── layout.tsx # Root layout
└── page.tsx # Main page
3.2 Edge Runtime Configuration
Enable edge runtime in your API routes by adding:
export const runtime = 'edge'
3.3 Cloudflare Configuration
- Create a Cloudflare Pages project
- Enable Cloudflare AI in your project settings
- Configure environment variables for AI access
4. Key Components
4.1 Main Page Layout
The main page layout (referenced from app/page.tsx) includes:
export default function Home() {
return (
<main className="flex min-h-screen flex-col items-center px-12 bg-[#FAFDFF]">
<header className="w-full h-16">
<nav className="w-full h-full">
<ul className="flex list-none h-full items-center justify-between">
<li className="flex self-center items-center">
<Image alt="logo" className="w-10 h-10 mr-2" width={100} height={100} src={"/logo.png"} />
<h1 className="text-lg font-bold text-[#44779C]">Cron Builder</h1>
</li>
<li>
<a role="button" tabIndex={0} href="mailto:service@cronbuilder.online" className="px-2.5 py-1 bg-blue-400 font-bold text-base text-white rounded-md">
Contact
</a>
</li>
</ul>
</nav>
</header>
<h1 className="text-clip bg-clip-text text-transparent bg-[length:200%_100%] bg-ai animate-ai-animate-btn font-bold text-5xl text-center mt-10 ">
Build Your Perfect
<br/>
Cron Expression Effortlessly
</h1>
<section className="w-full mt-8 flex justify-center">
{/* <h2>Generate your cron expression</h2> */}
<CronComp />
</section>
<section>
</section>
</main>
);
}
4.2 Cron Component
The core cron builder component (referenced from app/components/cron/index.tsx) provides:
- Visual cron expression builder
- Expression validation
- AI integration
const CronComp = () => {
const [value, setValue] = useState('* * * * *');
const [error, setError] = useState<boolean>(false);
const handleCatchError = (error: CronError) => {
if(error) {
setError(true)
} else {
setError(false)
}
}
return <ConfigProvider
theme={
{
token: {
borderRadius: 0
}
}
}
>
<div className='flex flex-col min-w-full'>
<div>
<AiGen onGenerate={(string) => {
if(string) {
setValue(string)
}
}} />
</div>
<div>
<Cron onError={handleCatchError} locale={NO_PREFIX_SUFFIX_LOCALE} value={value} setValue={setValue} />
</div>
<div>
<Input status={error ? 'error' : ''} onChange={(e) => setValue(e.target.value)} value={value} />
</div>
</div>
</ConfigProvider>
}
4.3 AI Generation Component
The AI generation component (referenced from app/components/AiGen/index.tsx) handles:
- User prompt input
- AI request handling
- Response processing
const AiGen:FC<AiGenProps> = ({onGenerate}) => {
const [prompt, setPrompt] = useState<string>();
const [loading, setLoading] = useState<boolean>(false);
const btnClick = () => {
if(loading) {
return
}
setLoading(true);
fetch('/api/cron', {
method: 'POST',
headers: {
'Content-Type': 'application/json',
},
body: JSON.stringify({ prompt}),
}).then(res => res.json()).then((res: any) => {
onGenerate(res.response);
}).finally(() => {
setLoading(false);
})
}
return <div className="flex flex-col">
<Input.TextArea style={{resize: 'none'}} className='resize-none' placeholder="please input your prompt to generate the cron expression" onChange={(e) => setPrompt(e.target.value)} value={prompt} rows={4} />
<button className={`${loading ? "cursor-wait" : ""} bg-[length:200%_100%] hover:animate-ai-animate-btn px-4 py-1 flex justify-center items-center mt-4 mb-4 self-end bg-ai text-white rounded-md` }onClick={btnClick}>
<span className='mr-2'>Run</span>
<Image alt='image' width={10} height={10} src={"/magic.svg"} />
</button>
</div>
}
5. AI Integration
5.1 API Route Setup
The cron API route (referenced from app/api/cron/route.ts) handles:
export async function POST(request: NextRequest) {
// let responseText = 'Hello World'
const { prompt } = await request.json<any>();
const input = { prompt: `
role: you are a cron expression master;
capability: you can give valid cron expression by user nature language input;
examples:
Q: every minute invoke cron expression
A: * * * * *
Q: every hour at 30 minutes cron expression
A: 30 * * * *
Q: once a day cron expression
A: 0 0 * * *
Q: once a month
A: 0 0 1 * *
limit:
1. no "?" or "#" non-standard character.
2. all cron expression only have 5 part(eg * * * * *).
rule:
1. don't give me expression detail just give me result.
2. the result must be a valid cron expression.
3. no extra useless string, just a cron expression (very important).
now please generate cron by user input "${prompt}", if you can't give valid cron expression just told me "please try again"
`};
//@ts-ignore
const answer = await getRequestContext().env.AI.run(
"@cf/meta/llama-3-8b-instruct",
input,
);
return new Response(JSON.stringify(answer))
}
5.2 AI Prompt Template
The AI system uses a structured prompt template that includes:
- Role definition
- Capabilities
- Examples
- Rules and limitations
Example prompt structure:
const input = {
prompt: `
role: you are a cron expression master;
capability: you can give valid cron expression by user nature language input;
examples: [...]
limit: [...]
rule: [...]
`
}
5.3 Error Handling
Implement error handling for:
- Invalid AI responses
- Network failures
- Invalid cron expressions
6. Deployment
6.1 Deployment Steps
- Push code to GitHub repository
- Connect repository to Cloudflare Pages
- Configure build settings:
Build command: npm run build
Build output directory: .next
6.2 Environment Variables
Required environment variables:
-
AI
: Cloudflare AI binding -
NODE_VERSION
: 18.x or higher
Best Practices
- Use edge runtime for optimal performance
- Implement proper error handling
- Add input validation
- Use TypeScript for type safety
- Follow responsive design principles
- Implement proper loading states
Limitations
- AI response time may vary
- Limited to standard cron expressions (5 parts)
- No support for special characters (?, #)
- Edge runtime restrictions
Conclusion
This project demonstrates how to build a modern AI-powered web application using Cloudflare's ecosystem and Next.js. The combination provides a scalable, performant solution for generating cron expressions through both visual interface and AI assistance.
For more information, refer to:
This content originally appeared on DEV Community and was authored by AlixWang
AlixWang | Sciencx (2024-11-06T16:23:09+00:00) Building an AI Cron Builder with Cloudflare Pages and Next.js. Retrieved from https://www.scien.cx/2024/11/06/building-an-ai-cron-builder-with-cloudflare-pages-and-next-js/
Please log in to upload a file.
There are no updates yet.
Click the Upload button above to add an update.