diff --git a/kits/agentic/system-design-analyzer/.env.example b/kits/agentic/system-design-analyzer/.env.example new file mode 100644 index 00000000..9b7e07ad --- /dev/null +++ b/kits/agentic/system-design-analyzer/.env.example @@ -0,0 +1,9 @@ +# Required Lamatic API Credentials +# Get these from your Lamatic project dashboard +LAMATIC_PROJECT_ENDPOINT=https://your-organization.lamatic.dev/graphql +LAMATIC_FLOW_ID=your-flow-id-here +LAMATIC_PROJECT_ID=your-project-id-here +LAMATIC_PROJECT_API_KEY=lt-your-api-key-here + +# Application Branding (public) +NEXT_PUBLIC_APP_NAME="System Design Analyzer" diff --git a/kits/agentic/system-design-analyzer/.gitignore b/kits/agentic/system-design-analyzer/.gitignore new file mode 100644 index 00000000..428a20cb --- /dev/null +++ b/kits/agentic/system-design-analyzer/.gitignore @@ -0,0 +1,39 @@ +# dependencies +/node_modules +/.pnp +.pnp.js + +# testing +/coverage + +# next.js +/.next/ +/out/ +next-env.d.ts + +# production +/build + +# misc +.DS_Store +*.pem + +# debug +npm-debug.log* +yarn-debug.log* +yarn-error.log* + +# local env files +.env +.env.local +.env.*.local + +# IDE +.vscode/ +.idea/ +*.swp +*.swo + +# OS +.DS_Store +Thumbs.db diff --git a/kits/agentic/system-design-analyzer/README.md b/kits/agentic/system-design-analyzer/README.md new file mode 100644 index 00000000..61fc1f62 --- /dev/null +++ b/kits/agentic/system-design-analyzer/README.md @@ -0,0 +1,226 @@ +# System Design Analyzer + +A modern, AI-powered web application that analyzes system design specifications and provides comprehensive insights using Lamatic flows. + +## Features + +- šŸ¤– **AI-Powered Analysis** - Get intelligent insights on your system architecture +- ⚔ **Real-time Processing** - Get instant feedback on your design specifications +- šŸŽØ **Modern UI** - Clean, responsive interface built with Next.js and Tailwind CSS +- šŸ“‹ **Example Designs** - Quick-start examples to explore the tool +- šŸ“‹ **Copy Results** - Easily copy analysis results to clipboard + +## Tech Stack + +- **Frontend**: Next.js 15, React 18, TypeScript +- **Styling**: Tailwind CSS v4, custom components +- **API**: Lamatic SDK (`lamatic` npm package) +- **Form Handling**: React Hook Form + Zod validation +- **Icons**: Lucide React + +## Prerequisites + +- Node.js 18+ and npm +- A Lamatic API Key +- Lamatic Project ID and API URL + +## Installation + +### 1. Clone or Navigate to the Kit + +```bash +cd kits/agentic/system-design-analyzer +``` + +### 2. Install Dependencies + +```bash +npm install +``` + +### 3. Set Up Environment Variables + +Copy the example environment file and fill in your Lamatic credentials: + +```bash +cp .env.example .env.local +``` + +Edit `.env.local` with your Lamatic credentials: + +```env +LAMATIC_PROJECT_ENDPOINT="https://your-organization.lamatic.dev/graphql" +LAMATIC_FLOW_ID="your-flow-id-here" +LAMATIC_PROJECT_ID="your-project-id-here" +LAMATIC_PROJECT_API_KEY="lt-your-api-key-here" +NEXT_PUBLIC_APP_NAME="System Design Analyzer" +``` + +### 4. Run Development Server + +```bash +npm run dev +``` + +Open [http://localhost:3000](http://localhost:3000) in your browser to see the application. + +## Configuration + +### Environment Variables + +| Variable | Description | Required | +|----------|-------------|----------| +| `LAMATIC_PROJECT_ENDPOINT` | Lamatic GraphQL endpoint | āœ… | +| `LAMATIC_FLOW_ID` | Flow ID for system design analysis | āœ… | +| `LAMATIC_PROJECT_ID` | Your Lamatic Project ID | āœ… | +| `LAMATIC_PROJECT_API_KEY` | Your Lamatic API Key | āœ… | +| `NEXT_PUBLIC_APP_NAME` | Application name | āœ… | + +## Flows + +### System Design Analyzer Flow + +- **Flow ID**: `2392ad97-51e9-4954-8d38-bc668e644818` +- **Type**: Synchronous +- **Input**: `system_design` (string) - The system design specification +- **Output**: `status` (string), `result` (string) - Analysis status and results + +## Usage + +1. **Enter Design Specification**: Paste or type your system design requirements in the text area +2. **Click Analyze**: Submit your design for AI analysis +3. **View Results**: Get comprehensive insights and recommendations +4. **Copy Results**: Use the copy button to save results to clipboard + +### Example Designs + +The app comes with example designs that you can quickly load: + +- Design a scalable distributed cache system like Redis +- Build a real-time notification system for a mobile app +- Create a URL shortener service like bit.ly +- Design a video streaming platform like YouTube + +## Building for Production + +```bash +npm run build +npm run start +``` + +## API Integration + +The application uses the **Lamatic SDK** (`lamatic` npm package) to execute flows. The integration is handled through server actions in `actions/orchestrate.ts`. + +### Server Action + +The `analyzeSystemDesign()` server action in `actions/orchestrate.ts` handles the API communication: + +```typescript +import { lamaticClient } from '@/lib/lamatic-client'; + +const { LAMATIC_FLOW_ID } = process.env; + +export async function analyzeSystemDesign( + systemDesign: string +): Promise> { + const response = await lamaticClient.executeFlow(LAMATIC_FLOW_ID, { + system_design: systemDesign, + }); + + return response; +} +``` + +## Project Structure + +``` +system-design-analyzer/ +ā”œā”€ā”€ app/ +│ ā”œā”€ā”€ layout.tsx # Root layout +│ ā”œā”€ā”€ page.tsx # Main page +│ └── globals.css # Global styles +ā”œā”€ā”€ actions/ +│ └── orchestrate.ts # Server action for API calls +ā”œā”€ā”€ components/ +│ └── ui/ # Reusable UI components +│ ā”œā”€ā”€ button.tsx +│ ā”œā”€ā”€ card.tsx +│ ā”œā”€ā”€ input.tsx +│ └── textarea.tsx +ā”œā”€ā”€ flows/ +│ └── system-design-analyzer/ # Flow configuration +│ ā”œā”€ā”€ config.json +│ ā”œā”€ā”€ inputs.json +│ ā”œā”€ā”€ meta.json +│ └── README.md +ā”œā”€ā”€ public/ # Static assets +ā”œā”€ā”€ styles/ # Additional styles +ā”œā”€ā”€ .env.example # Example environment variables +ā”œā”€ā”€ .env.local # Local environment variables +ā”œā”€ā”€ package.json +ā”œā”€ā”€ tsconfig.json +ā”œā”€ā”€ tailwind.config.ts +ā”œā”€ā”€ next.config.mjs +└── README.md +``` + +## Design Theme + +The application follows Lamatic's modern design system: + +- **Colors**: White (#ffffff) background, Black (#000000) text, Red (#dc2626) accent +- **Typography**: Inter font family with variable weights +- **Components**: Clean, minimalist design with focus on usability +- **Responsiveness**: Fully responsive mobile and tablet support + +## Error Handling + +The application handles various error scenarios: + +- Input validation errors (minimum 10 characters) +- Network errors during API calls +- Server errors from Lamatic flows +- Missing API credentials in environment variables + +All errors are displayed to the user with clear, actionable messages in the error section of the form. + +## License + +This project is part of the Lamatic AgentKit and follows the same license. + +## Deployment + +### Vercel (Recommended) + +1. Push your code to GitHub +2. Import the repository in Vercel +3. Set the root directory to `kits/agentic/system-design-analyzer` +4. Add environment variables in Vercel Dashboard: + - `LAMATIC_PROJECT_ENDPOINT` + - `LAMATIC_FLOW_ID` + - `LAMATIC_PROJECT_ID` + - `LAMATIC_PROJECT_API_KEY` +5. Deploy + +## Troubleshooting + +**Issue**: "LAMATIC_FLOW_ID is not set" +- **Solution**: Check `.env.local` has all required variables + +**Issue**: Flow returns object instead of string +- **Solution**: Ensure the flow response is properly serialized in `actions/orchestrate.ts` + +**Issue**: Port 3000 already in use +- **Solution**: Use `PORT=3001 npm run dev` to run on a different port + +## Support + +For issues or questions: +1. Check the [Lamatic documentation](https://lamatic.ai/docs) +2. Review the [AgentKit README](https://github.com/Lamatic/AgentKit) +3. Open an issue in the [GitHub repository](https://github.com/Lamatic/AgentKit/issues) + +## Contributing + +Contributions are welcome! Please follow the [AgentKit contribution guidelines](https://github.com/Lamatic/AgentKit/blob/main/CONTRIBUTING.md). diff --git a/kits/agentic/system-design-analyzer/actions/orchestrate.ts b/kits/agentic/system-design-analyzer/actions/orchestrate.ts new file mode 100644 index 00000000..bdea48cf --- /dev/null +++ b/kits/agentic/system-design-analyzer/actions/orchestrate.ts @@ -0,0 +1,87 @@ +'use server'; + +import { lamaticClient } from '@/lib/lamatic-client'; +import type { ServerActionResponse, SystemDesignAnalysis } from '@/lib/types'; + +const { LAMATIC_FLOW_ID } = process.env; + +export async function analyzeSystemDesign( + systemDesign: string +): Promise> { + if (!LAMATIC_FLOW_ID) { + throw new Error('[Server] LAMATIC_FLOW_ID is not set in environment variables'); + } + + if (!systemDesign || systemDesign.trim().length === 0) { + throw new Error('[Server] System design input cannot be empty'); + } + + try { + console.log('[v0] Executing flow:', { + flowId: LAMATIC_FLOW_ID, + inputLength: systemDesign.length, + timestamp: new Date().toISOString(), + }); + + const response = await lamaticClient.executeFlow(LAMATIC_FLOW_ID, { + system_design: systemDesign, + }); + + console.log('[v0] Flow response received:', { status: response?.status }); + + if (!response) { + throw new Error('[Flow] No response received from flow execution'); + } + + // Check if the flow returned an error status + if (response.status === 'error' || response.status === 'failed') { + const errorDetails = response.error || response.message || 'Unknown error from flow'; + console.error('[v0] Flow error:', errorDetails); + throw new Error(`[Flow] Execution failed: ${errorDetails}`); + } + + // Validate and parse result + let analysisResult: SystemDesignAnalysis = {}; + + if (typeof response.result === 'string') { + try { + analysisResult = JSON.parse(response.result); + } catch { + // If not JSON, treat as summary text + analysisResult = { summary: { nextSteps: [response.result] } }; + } + } else if (typeof response.result === 'object' && response.result !== null) { + analysisResult = response.result as SystemDesignAnalysis; + } + + console.log('[v0] Analysis completed successfully'); + + return { + success: true, + status: response.status || 'completed', + result: analysisResult, + }; + } catch (error) { + const errorMessage = error instanceof Error ? error.message : 'Unknown error'; + console.error('[v0] Analysis failed:', errorMessage); + + // Handle specific flow configuration issues + let userFriendlyError = errorMessage; + + if (errorMessage.includes('tool call validation failed') || + errorMessage.includes('attempted to call tool') || + errorMessage.includes('Instructor Agent')) { + userFriendlyError = + 'The flow is configured with Instructor Agents that require specific tools to be available. ' + + 'Please update the flow in Lamatic Studio: Change node types from InstructorLLMNode to LLMNode, ' + + 'or disable structured output mode to allow direct text generation.'; + console.error('[v0] Flow configuration issue detected: Tool-calling nodes without available tools'); + } + + return { + success: false, + status: 'error', + error: userFriendlyError, + }; + } +} diff --git a/kits/agentic/system-design-analyzer/app/globals.css b/kits/agentic/system-design-analyzer/app/globals.css new file mode 100644 index 00000000..85c21586 --- /dev/null +++ b/kits/agentic/system-design-analyzer/app/globals.css @@ -0,0 +1,7 @@ +@import "tailwindcss"; + +@theme { + --color-primary: #ff5630; + --color-primary-dark: #e63d1a; + --color-secondary: #1a1a2e; +} diff --git a/kits/agentic/system-design-analyzer/app/layout.tsx b/kits/agentic/system-design-analyzer/app/layout.tsx new file mode 100644 index 00000000..bc06d69f --- /dev/null +++ b/kits/agentic/system-design-analyzer/app/layout.tsx @@ -0,0 +1,83 @@ +import type { Metadata, Viewport } from 'next'; +import { Inter } from 'next/font/google'; +import './globals.css'; + +const inter = Inter({ + subsets: ['latin'], + weight: ['400', '500', '600', '700', '800', '900'], + variable: '--font-inter', +}); + +export const metadata: Metadata = { + metadataBase: new URL('https://lamatic.ai'), + title: 'System Design Analyzer | AI-Powered Architecture Analysis | Lamatic', + description: 'Analyze your system designs with AI-powered insights on architecture, performance, reliability, and security. Get instant feedback from a multi-agent system powered by Lamatic.', + keywords: ['system design', 'system architecture', 'AI analysis', 'lamatic', 'system design interview', 'architecture review', 'scalability analysis', 'reliability assessment'], + authors: [{ name: 'Lamatic', url: 'https://lamatic.ai' }], + creator: 'Lamatic', + publisher: 'Lamatic', + formatDetection: { + email: false, + telephone: false, + address: false, + }, + icons: { + icon: '/lamatic logo.png', + shortcut: '/lamatic logo.png', + apple: '/lamatic logo.png', + }, + openGraph: { + title: 'System Design Analyzer | AI-Powered Architecture Analysis', + description: 'Analyze your system designs with AI-powered insights on architecture, performance, reliability, and security. Powered by Lamatic.', + url: 'https://lamatic.ai', + siteName: 'Lamatic - System Design Analyzer', + type: 'website', + images: [ + { + url: '/lamatic logo.png', + width: 128, + height: 128, + alt: 'Lamatic Logo', + }, + ], + }, + twitter: { + card: 'summary', + title: 'System Design Analyzer | Lamatic', + description: 'AI-powered system design analysis with instant feedback on your architecture', + images: ['/lamatic logo.png'], + }, + robots: { + index: true, + follow: true, + }, +}; + +export const viewport: Viewport = { + width: 'device-width', + initialScale: 1, + maximumScale: 5, + userScalable: true, + themeColor: [ + { media: '(prefers-color-scheme: light)', color: 'white' }, + { media: '(prefers-color-scheme: dark)', color: '#000' }, + ], +}; + +export default function RootLayout({ + children, +}: { + children: React.ReactNode; +}) { + return ( + + + + + + + {children} + + + ); +} diff --git a/kits/agentic/system-design-analyzer/app/page.tsx b/kits/agentic/system-design-analyzer/app/page.tsx new file mode 100644 index 00000000..fa2b98be --- /dev/null +++ b/kits/agentic/system-design-analyzer/app/page.tsx @@ -0,0 +1,369 @@ +'use client'; + +import { useForm } from 'react-hook-form'; +import { zodResolver } from '@hookform/resolvers/zod'; +import { z } from 'zod'; +import { useState } from 'react'; +import { analyzeSystemDesign } from '@/actions/orchestrate'; +import { Button } from '@/components/ui/button'; +import { Textarea } from '@/components/ui/textarea'; +import { Loader2, ChevronRight, Copy, Check, Github, Zap, Shield, TrendingUp, Database, Network, AlertCircle, Coffee } from 'lucide-react'; + +const formSchema = z.object({ + systemDesign: z.string().min(10, { + message: 'Please enter a system design specification (at least 10 characters).', + }), +}); + +type FormValues = z.infer; + +// Helper function to render analysis results +function renderAnalysisResults(result: string | object) { + try { + let data: any = result; + if (typeof result === 'string') { + data = JSON.parse(result); + } + + const issues = Array.isArray(data.issues) ? data.issues : []; + const recommendations = Array.isArray(data.recommendations) ? data.recommendations : []; + const summary = typeof data.summary === 'string' ? data.summary : data.summary?.summary || ''; + + return ( +
+ {/* Summary Section */} + {summary && ( +
+
+
+
+
+ šŸ“‹ +
+
+

Analysis Summary

+

{summary}

+
+
+
+
+ )} + + {/* Issues Section */} + {issues.length > 0 && ( +
+
+
+

Critical Issues

+ + {issues.length} found + +
+
+ {issues.map((issue: any, idx: number) => { + const issueText = typeof issue === 'string' ? issue : issue.description || issue; + return ( +
+
+
+ ! +
+
+

{issueText}

+
+
+
+ ); + })} +
+
+ )} + + {/* Recommendations Section */} + {recommendations.length > 0 && ( +
+
+
+

Recommendations

+ + {recommendations.length} actions + +
+
+ {recommendations.map((rec: any, idx: number) => { + const recText = typeof rec === 'string' ? rec : rec.suggestion || rec; + return ( +
+
+
+ āœ“ +
+
+

{recText}

+
+
+
+ ); + })} +
+
+ )} + + {/* Fallback if no structured data */} + {!summary && issues.length === 0 && recommendations.length === 0 && ( +
+

Response:

+
+              {typeof result === 'string' ? result : JSON.stringify(result, null, 2)}
+            
+
+ )} +
+ ); + } catch (error) { + return ( +
+

Response:

+
+          {typeof result === 'string' ? result : JSON.stringify(result, null, 2)}
+        
+
+ ); + } +} + +export default function Home() { + const [isLoading, setIsLoading] = useState(false); + const [result, setResult] = useState(null); + const [copied, setCopied] = useState(false); + const [error, setError] = useState(null); + const [show429, setShow429] = useState(false); + + const form = useForm({ + resolver: zodResolver(formSchema), + defaultValues: { + systemDesign: '', + }, + }); + + const onSubmit = async (values: FormValues) => { + setIsLoading(true); + setError(null); + setResult(null); + + try { + const response = await analyzeSystemDesign(values.systemDesign); + + // Check if response has an error + if (!response.success && response.error) { + const errorMessage = response.error; + + // Check if it's a 429 error + if (errorMessage.includes('429') || errorMessage.includes('rate limit') || errorMessage.includes('Too Many Requests')) { + setShow429(true); + } else { + setError(errorMessage); + } + return; + } + + // Ensure result is a string + const resultData = typeof response.result === 'string' + ? response.result + : JSON.stringify(response.result, null, 2); + + setResult(resultData); + } catch (err) { + const errorMessage = err instanceof Error ? err.message : 'Failed to analyze system design'; + + // Check if it's a 429 error + if (errorMessage.includes('429') || errorMessage.includes('rate limit') || errorMessage.includes('Too Many Requests')) { + setShow429(true); + } else { + setError(errorMessage); + } + console.error('Error:', err); + } finally { + setIsLoading(false); + } + }; + + const copyToClipboard = () => { + if (result) { + navigator.clipboard.writeText(result); + setCopied(true); + setTimeout(() => setCopied(false), 2000); + } + }; + + return ( +
+ {/* 429 Error Modal */} + {show429 && ( +
+
+
+
+ + +
+
+

Whoa there, speed racer!

+

+ You're analyzing systems faster than we can handle! The AI needs a coffee break. Please wait a moment and try again. +

+

Error: Too many requests (429)

+ +
+
+ )} + {/* Premium Header */} +
+
+ {/* Logo */} + + Lamatic + + + {/* Right side - GitHub Link */} + + + +
+
+ + {/* Main Content */} +
+
+ + {/* Hero Section */} + {!result && ( +
+

+ Analyze Your System Design +

+

+ AI-powered insights on architecture, performance & reliability +

+
+ )} + + {/* Form Card */} + {!result && ( +
+
+
+
+