You are an expert AI engineer and full-stack developer tasked with creating a single-page application (SPA) for building and managing AI agents powered by Google's Gemma models. The application, named 'Gemma Agent Builder', will provide a low-code interface for developers to create, test, and deploy autonomous agents. The target audience includes developers, data scientists, and AI engineers who want to leverage Gemma's capabilities for task automation, function calling, and multimodal reasoning.
**PROJECT OVERVIEW:**
The primary goal of Gemma Agent Builder is to democratize the creation of AI agents based on Google's latest Gemma models. It aims to solve the problem of complex setup and configuration required for building intelligent agents by providing an intuitive, low-code interface. The core value proposition is enabling users to "build autonomous agents that plan, navigate apps, and complete tasks on your behalf" with native support for function calling and multimodal reasoning, efficiently running models on their own hardware or cloud infrastructure. The application will focus on ease of use, flexibility, and efficient deployment, allowing users to fine-tune Gemma models for specific tasks.
**TECH STACK:**
- **Frontend Framework:** React (using Vite for fast development)
- **Styling:** Tailwind CSS for rapid UI development and responsive design.
- **State Management:** Zustand for efficient and scalable global state management.
- **Routing:** React Router DOM for client-side navigation.
- **UI Components:** A headless UI library like Headless UI or Radix UI for accessible and customizable components, or custom components styled with Tailwind.
- **API Communication:** Axios for making HTTP requests to a potential backend (though MVP focuses on client-side logic and mock data).
- **Icons:** Heroicons or similar for clear and consistent iconography.
**CORE FEATURES:**
1. **Agent Creation Interface:**
* **User Flow:** User navigates to the 'Create Agent' page. They see input fields for Agent Name, Description, and a primary Prompt. A section for defining 'Function Calls' is available, allowing users to add functions with names, descriptions, and parameter schemas (JSON schema format). A dropdown allows selection of the Gemma model (e.g., Gemma-2B, Gemma-7B, Gemma-26B, Gemma-31B - initially simulated).
* **Details:** Input fields for name and description, a large textarea for the system prompt. Function definition involves adding rows, each with fields for function name, a description of what the function does, and a JSON editor for defining parameters (e.g., `{"type": "object", "properties": {"location": {"type": "string"}}, "required": ["location"]} `). Model selection uses a dropdown.
2. **Interactive Sandbox/Playground:**
* **User Flow:** After creating an agent, the user can enter the 'Sandbox' environment. They see the agent's prompt and defined functions. There's an input area for user queries/tasks. When the user submits a query, the application simulates the agent's response, including potential function calls. The output displays the agent's response and any triggered function calls with their arguments.
* **Details:** A split-pane layout might be effective: one side for agent configuration/output and the other for user input. Simulated responses should mimic LLM behavior, sometimes returning direct text, sometimes returning a JSON object indicating a function call and its parameters (e.g., `{"tool_code": "get_weather", "args": {"location": "London"}}`). The simulation should also handle basic error scenarios or ambiguous requests.
3. **Agent Management Dashboard:**
* **User Flow:** Users land on the dashboard after login (simulated). They see a list of their created agents, with columns for Name, Model, Status (e.g., Active, Inactive, Testing), Last Run, and Actions (Edit, Test, Delete).
* **Details:** A table or card-based layout displaying agent summaries. Each agent card/row has buttons for quick actions. Clicking an agent name might navigate to its detailed view or sandbox.
4. **Pre-built Agent Templates:**
* **User Flow:** Within the 'Create Agent' flow, users can select from a gallery of pre-built templates (e.g., 'Email Summarizer', 'Content Idea Generator', 'Simple Q&A Bot'). Selecting a template pre-populates the agent's prompt and potentially function definitions.
* **Details:** A modal or dedicated page displaying template cards with titles, descriptions, and a "Use Template" button. Templates cover common use cases leveraging Gemma's capabilities like multilingual support or efficient architecture.
**UI/UX DESIGN:**
- **Layout:** A clean, modern, and responsive single-page application layout. A persistent sidebar navigation for Dashboard, Create Agent, Templates, and Settings. The main content area adapts to the selected section. Minimalistic aesthetic to keep the focus on the AI agent creation process.
- **Color Palette:** A sophisticated and tech-oriented palette. Primary: Dark charcoal (#1a1a1a) or deep blue (#0f172a) for backgrounds. Secondary: White/light gray (#e5e7eb) for text and primary elements. Accent: A vibrant but not overwhelming color like teal (#14b8a6) or electric blue (#3b82f6) for interactive elements, buttons, and highlights. Use subtle gradients for depth.
- **Typography:** A clean, readable sans-serif font family like Inter or Poppins for all text. Clear hierarchy using font weights (bold for titles, semi-bold for subtitles, regular for body text) and sizes. Ensure good line spacing for readability.
- **Responsive Design:** Mobile-first approach. Sidebar collapses into a hamburger menu on smaller screens. Main content adjusts fluidly. Forms and tables should be usable on all screen sizes. Tailwind CSS's responsive prefixes (sm:, md:, lg:, xl:) will be extensively used.
**COMPONENT BREAKDOWN:**
- `App.jsx`: Main application component, sets up routing and overall layout.
- `Layout.jsx`: Contains the persistent sidebar and the main content area wrapper.
- `Sidebar.jsx`: Navigation menu component. Props: `navItems` (array of objects with label, path, icon).
- `AgentDashboardPage.jsx`: Displays the list of agents. Fetches/receives agent data. Uses `AgentList` component.
- `AgentList.jsx`: Renders a table or list of agents. Props: `agents` (array).
- `AgentListItem.jsx` / `AgentCard.jsx`: Represents a single agent in the list. Props: `agent` (object), `onEdit`, `onTest`, `onDelete` (functions).
- `CreateAgentPage.jsx`: Form for creating/editing agents. Contains `AgentForm`.
- `AgentForm.jsx`: The main form component. Manages form state using Zustand or local state. Includes fields for name, description, model selection, prompt input, and `FunctionDefinitionSection`.
- `PromptInput.jsx`: Textarea for agent prompt. Props: `value`, `onChange`.
- `ModelSelector.jsx`: Dropdown for selecting Gemma models. Props: `models` (array), `selectedModel`, `onChange`.
- `FunctionDefinitionSection.jsx`: Manages adding and editing function definitions. Renders multiple `FunctionDefinitionRow` components. Props: `functions`, `onChange`.
- `FunctionDefinitionRow.jsx`: A single row for defining a function (name, description, JSON schema). Props: `func` (object), `index`, `onChange`, `onRemove`.
- `JsonSchemaEditor.jsx`: A textarea or dedicated editor for JSON schema. Props: `value`, `onChange`.
- `SandboxPage.jsx`: The interactive playground. Fetches agent config, displays chat interface. Uses `ChatInterface`.
- `ChatInterface.jsx`: Handles user input and displays conversation history. Props: `agentConfig` (object), `onQuerySubmit`.
- `QueryInput.jsx`: Text input for user queries in the sandbox. Props: `onSubmit`.
- `ResponseDisplay.jsx`: Renders agent responses, including parsed function calls. Props: `response` (object).
- `TemplatesPage.jsx`: Displays available agent templates. Uses `TemplateList`.
- `TemplateList.jsx`: Renders a list/grid of templates. Props: `templates`.
- `TemplateCard.jsx`: Represents a single template. Props: `template`, `onUse`.
**DATA MODEL (Zustand Store):**
```javascript
// store/agentStore.js
import create from 'zustand';
const useAgentStore = create((set) => ({
agents: [], // Array of agent objects
currentAgent: null, // The agent currently being edited or tested
models: [
{ id: 'gemma-2b', name: 'Gemma 2B (Simulated)' },
{ id: 'gemma-7b', name: 'Gemma 7B (Simulated)' },
// Add more simulated models as needed
],
templates: [], // Array of template objects
// Agent Actions
addAgent: (agent) => set((state) => ({ agents: [...state.agents, { ...agent, id: Date.now().toString() }] })),
updateAgent: (updatedAgent) => set((state) => ({ agents: state.agents.map(a => a.id === updatedAgent.id ? updatedAgent : a) })),
deleteAgent: (agentId) => set((state) => ({ agents: state.agents.filter(a => a.id !== agentId) })),
setAgents: (agents) => set({ agents }),
setCurrentAgent: (agent) => set({ currentAgent: agent }),
// Template Actions
setTemplates: (templates) => set({ templates }),
// Mock Simulation Function (for sandbox)
simulateAgentResponse: async (agentConfig, query) => {
// This is a placeholder. In a real app, this would involve API calls or complex logic.
console.log('Simulating response for agent:', agentConfig.name, 'with query:', query);
// Simulate a delay
await new Promise(resolve => setTimeout(resolve, 1000));
// Simple simulation logic:
const random = Math.random();
if (random < 0.3) {
// Simulate function call
const functionToCall = agentConfig.functions?.[0]; // Pick first function
if (functionToCall) {
// Generate dummy args based on schema (very basic)
const args = {};
if (functionToCall.schema?.properties) {
Object.keys(functionToCall.schema.properties).forEach(key => {
args[key] = `dummy_${key}_${Date.now().toString().slice(-4)}`;
});
}
return { type: 'function_call', function: functionToCall.name, arguments: args };
}
}
// Simulate text response
return { type: 'text', content: `Simulated response to '${query}' for agent '${agentConfig.name}'. The model used is ${agentConfig.model}.` };
}
}));
export default useAgentStore;
// Mock Data Structure Examples:
/*
const mockAgent = {
id: '123',
name: 'My First Agent',
description: 'This agent automates task X.',
prompt: 'You are a helpful AI assistant. Respond concisely.',
model: 'gemma-7b',
functions: [
{
name: 'getCurrentTime',
description: 'Gets the current time.',
schema: {
type: 'object',
properties: {},
}
},
{
name: 'searchWeb',
description: 'Searches the web for a given query.',
schema: {
type: 'object',
properties: {
query: { type: 'string', description: 'The search query.' },
},
required: ['query'],
}
}
]
};
const mockTemplate = {
id: 't1',
name: 'Email Summarizer',
description: 'Summarizes provided email text.',
prompt: 'You are an expert summarizer. Condense the following text into 3 bullet points.',
model: 'gemma-7b',
functions: []
};
*/
```
**ANIMATIONS & INTERACTIONS:**
- **Hover Effects:** Subtle background color changes or slight scaling on buttons and interactive cards (e.g., agent cards, template cards) on hover.
- **Transitions:** Smooth transitions for panel expansions/collapses (e.g., function definition rows), modal openings/closings, and route changes (fade-in/out effects).
- **Loading States:** Use skeleton loaders or spinners (e.g., `react-spinners`) for data fetching (agents, templates) and during simulated agent responses in the sandbox. Display clear loading indicators.
- **Micro-interactions:** Input field focus states, button click feedback (slight press effect), successful save/delete confirmations (e.g., subtle toast notifications).
- **Form Validation:** Real-time feedback on input fields (e.g., red border, error message below) when validation fails.
**EDGE CASES:**
- **Empty States:** Display informative messages and clear calls-to-action when lists are empty (e.g., "You haven't created any agents yet. Click 'Create Agent' to start!"). The sandbox should have a placeholder message when no agent is loaded.
- **Error Handling:** Gracefully handle API errors (if backend is added) or simulation errors. Display user-friendly error messages. For invalid JSON schema input, provide clear inline validation errors.
- **Validation Rules:**
* Agent Name: Required, min/max length.
* Prompt: Required, min length.
* Function Name: Required, valid identifier format.
* Function Schema: Must be valid JSON.
- **Accessibility (a11y):** Use semantic HTML elements. Ensure proper ARIA attributes where necessary (e.g., for modals, buttons with dynamic states). Ensure keyboard navigability for all interactive elements. Sufficient color contrast.
- **Long Inputs:** Handle potentially long prompts and descriptions with scrollable text areas.
**SAMPLE DATA:**
```json
// Mock Agents for Dashboard
[
{
"id": "agent-001",
"name": "Web Content Summarizer",
"description": "Summarizes articles fetched from a given URL.",
"prompt": "You are an AI assistant that summarizes web content. Extract the main points from the provided text and present them as a concise summary.",
"model": "gemma-7b",
"functions": [
{
"name": "fetchUrlContent",
"description": "Fetches the content of a given URL.",
"schema": {
"type": "object",
"properties": {
"url": {"type": "string", "description": "The URL to fetch content from."}
},
"required": ["url"]
}
}
]
},
{
"id": "agent-002",
"name": "Multilingual Translator Bot",
"description": "Translates text between English and Spanish using Gemma's multilingual capabilities.",
"prompt": "You are a highly accurate translator. Translate the user's input into the target language. Support English and Spanish.",
"model": "gemma-2b",
"functions": [
{
"name": "translateText",
"description": "Translates text from a source language to a target language.",
"schema": {
"type": "object",
"properties": {
"text": {"type": "string", "description": "The text to translate."},
"source_lang": {"type": "string", "enum": ["en", "es"]},
"target_lang": {"type": "string", "enum": ["en", "es"]}
},
"required": ["text", "source_lang", "target_lang"]
}
}
]
}
]
// Mock Templates for Templates Page
[
{
"id": "tpl-001",
"name": "Meeting Minutes Taker",
"description": "Takes raw meeting notes and structures them into key decisions and action items.",
"prompt": "Analyze the following meeting notes. Identify key decisions made and create a list of action items with assigned owners if mentioned. Format the output clearly.",
"model": "gemma-7b",
"functions": []
},
{
"id": "tpl-002",
"name": "Code Explainer",
"description": "Explains a given code snippet in simple terms.",
"prompt": "You are a developer educator. Explain the following code snippet. Describe what it does, its purpose, and any important logic. Use clear and simple language.",
"model": "gemma-2b",
"functions": []
},
{
"id": "tpl-003",
"name": "Customer Support FAQ Bot",
"description": "Answers common customer questions based on provided knowledge.",
"prompt": "You are a customer support agent. Answer the user's question based on the provided context. If the answer is not found, politely state that you don't have the information.",
"model": "gemma-31b",
"functions": [
{
"name": "getFaqAnswer",
"description": "Retrieves an answer for a given question from a knowledge base.",
"schema": {
"type": "object",
"properties": {
"question": {"type": "string", "description": "The customer's question."}
},
"required": ["question"]
}
}
]
}
]
```
**DEPLOYMENT NOTES:**
- **Build Tool:** Vite is recommended for its speed. Configure `vite.config.js` for production builds (`npm run build`).
- **Environment Variables:** Use `.env` files for environment-specific configurations (e.g., API endpoints if a backend is introduced later). Prefix variables with `VITE_` for Vite.
- **Performance Optimizations:** Code splitting (handled by Vite), lazy loading components, optimizing images, memoization (React.memo, useMemo) where applicable, especially in the sandbox and dashboard lists.
- **Static Site Hosting:** Suitable for hosting on platforms like Netlify, Vercel, or GitHub Pages.