### Genkit Environment Variables for Google AI API
Source: https://context7.com/prathmesh2028/agrivision-ai-pccoe/llms.txt
Setup instructions for environment variables required by Genkit to access Google AI API services. This includes specifying the API key, with a link provided to obtain the key from Google AI Studio.
```bash
# .env.local
GOOGLE_GENAI_API_KEY=your_api_key_here
# Get API key from: https://aistudio.google.com/app/apikey
```
--------------------------------
### Next.js Development and Build Commands
Source: https://context7.com/prathmesh2028/agrivision-ai-pccoe/llms.txt
Commands for managing the Next.js application locally and for production builds. This includes installing dependencies, starting the development server with Turbopack for fast refresh, launching Genkit developer tools for AI flow testing, performing type checking, building the application for production, and starting the production server.
```bash
# Install dependencies
npm install
# Start Next.js development server on port 9002
npm run dev
# Start Genkit developer UI for testing AI flows
npm run genkit:dev
# Start Genkit with auto-reload on file changes
npm run genkit:watch
# Run TypeScript type checking
npm run typecheck
# Build for production
npm run build
# Start production server
npm start
```
--------------------------------
### Project Package Configuration for Development and Genkit
Source: https://context7.com/prathmesh2028/agrivision-ai-pccoe/llms.txt
Defines the project's dependencies and scripts for development, building, and running Genkit AI flows. It specifies versions for Next.js, React, Genkit, and other essential libraries, along with commands for starting development servers and Genkit processes.
```json
{
"name": "agrivision-ai",
"version": "0.1.0",
"scripts": {
"dev": "next dev --turbopack -p 9002",
"genkit:dev": "genkit start -- tsx src/ai/dev.ts",
"genkit:watch": "genkit start -- tsx --watch src/ai/dev.ts",
"build": "next build",
"start": "next start"
},
"dependencies": {
"@genkit-ai/googleai": "^1.14.1",
"@genkit-ai/next": "^1.14.1",
"next": "15.3.3",
"react": "^18.3.1",
"react-hook-form": "^7.54.2",
"zod": "^3.24.2",
"firebase": "^11.9.1",
"genkit": "^1.14.1",
"tailwindcss": "^3.4.1"
}
}
```
--------------------------------
### Firebase App Hosting Configuration and Deployment
Source: https://context7.com/prathmesh2028/agrivision-ai-pccoe/llms.txt
Configuration for Firebase App Hosting, specifying maximum instances, and the command to deploy the application to Firebase Hosting. This ensures the application is correctly set up for hosting services.
```yaml
# apphosting.yaml
runConfig:
maxInstances: 1
# Deploy to Firebase
# firebase deploy --only hosting
```
--------------------------------
### Next.js Configuration for TypeScript, ESLint, and Images
Source: https://context7.com/prathmesh2028/agrivision-ai-pccoe/llms.txt
Configuration file for Next.js, enabling TypeScript support with ignored build errors, ESLint integration with ignored build checks, and image optimization settings. The image configuration specifies allowed remote image hosts for optimization.
```typescript
// next.config.ts
import type { NextConfig } from 'next';
const nextConfig: NextConfig = {
typescript: {
ignoreBuildErrors: true,
},
eslint: {
ignoreDuringBuilds: true,
},
images: {
remotePatterns: [
{
protocol: 'https',
hostname: 'placehold.co',
},
{
protocol: 'https',
hostname: 'picsum.photos',
},
],
},
};
export default nextConfig;
```
--------------------------------
### Configure Next.js Root Layout for Language and UI
Source: https://context7.com/prathmesh2028/agrivision-ai-pccoe/llms.txt
Sets up the main application layout in Next.js, including global styles, language support context, sidebar navigation, header, and toast notifications. It ensures a consistent and accessible user interface across the application.
```typescript
import type { Metadata } from 'next';
import './globals.css';
import { cn } from '@/lib/utils';
import { Toaster } from '@/components/ui/toaster';
import { AppSidebar } from '@/components/app-sidebar';
import { AppHeader } from '@/components/app-header';
import { SidebarProvider } from '@/components/ui/sidebar';
import { LanguageProvider } from '@/contexts/language-context';
export const metadata: Metadata = {
title: 'AgriVision AI',
description: 'AI-powered tools for modern agriculture',
};
export default function RootLayout({ children }: { children: React.ReactNode }) {
return (
{children}
);
}
```
--------------------------------
### Initialize Genkit AI with Google AI Plugin
Source: https://context7.com/prathmesh2028/agrivision-ai-pccoe/llms.txt
Configures the Genkit framework to use Google AI plugins, specifically targeting the Gemini 2.5 Flash model for AI processing. This is essential for enabling AI functionalities within the application.
```typescript
import { genkit } from 'genkit';
import { googleAI } from '@genkit-ai/googleai';
export const ai = genkit({
plugins: [googleAI()],
model: 'googleai/gemini-2.5-flash',
});
```
--------------------------------
### TypeScript Flow for Emission Reduction Suggestions | Agrivision AI
Source: https://context7.com/prathmesh2028/agrivision-ai-pccoe/llms.txt
Defines a server action flow using Genkit to suggest emission reductions in agriculture. It includes input and output schemas for farming practices and sustainability recommendations. The flow leverages an AI prompt to generate actionable advice based on provided details.
```typescript
// src/ai/flows/suggest-emission-reductions.ts
'use server';
import { ai } from '@/ai/genkit';
import { z } from 'genkit';
const SuggestEmissionReductionsInputSchema = z.object({
fertilizerType: z.string().describe('Type of fertilizer being used'),
waterUsage: z.string().describe('Information about water usage for irrigation'),
machineryType: z.string().describe('Type of machinery being used'),
region: z.string().describe('Geographic region where farming is happening'),
cropType: z.string().describe('Type of crop being cultivated'),
language: z.string().describe('Response language (e.g., "en", "hi", "mr")'),
});
const SuggestEmissionReductionsOutputSchema = z.object({
fertilizerReductionSuggestions: z.string().describe('Suggestions for reducing emissions from fertilizer use'),
waterReductionSuggestions: z.string().describe('Suggestions for reducing emissions from water usage'),
machineryReductionSuggestions: z.string().describe('Suggestions for reducing emissions from machinery use'),
overallSustainabilityScore: z.number().describe('Overall sustainability score based on current practices and potential improvements'),
});
export type SuggestEmissionReductionsInput = z.infer;
export type SuggestEmissionReductionsOutput = z.infer;
const prompt = ai.definePrompt({
name: 'suggestEmissionReductionsPrompt',
input: { schema: SuggestEmissionReductionsInputSchema },
output: { schema: SuggestEmissionReductionsOutputSchema },
prompt: `You are an expert in sustainable farming practices.
Based on the information provided about the farmer's current practices, provide specific and actionable suggestions for reducing emissions from fertilizer, water, and machinery use.
Also give an overall sustainability score, which reflects the overall sustainability of current farming practices and potential improvements that were suggested.
Please provide the response in the following language: {{{language}}}
Fertilizer Type: {{{fertilizerType}}}
Water Usage: {{{waterUsage}}}
Machinery Type: {{{machineryType}}}
Region: {{{region}}}
Crop Type: {{{cropType}}}
Respond in a well-structured manner.`,
});
const suggestEmissionReductionsFlow = ai.defineFlow(
{
name: 'suggestEmissionReductionsFlow',
inputSchema: SuggestEmissionReductionsInputSchema,
outputSchema: SuggestEmissionReductionsOutputSchema,
},
async input => {
const { output } = await prompt(input);
return output!;
}
);
export async function suggestEmissionReductions(input: SuggestEmissionReductionsInput): Promise {
return suggestEmissionReductionsFlow(input);
}
// Usage Example:
const emissions = await suggestEmissionReductions({
fertilizerType: "Chemical NPK",
waterUsage: "Flood irrigation, 200mm per cycle",
machineryType: "Diesel tractors",
region: "Punjab, India",
cropType: "Wheat",
language: "en"
});
// Returns: {
// fertilizerReductionSuggestions: "Switch to organic compost or reduce NPK application by 20%...",
// waterReductionSuggestions: "Adopt drip irrigation to reduce water usage by 40-50%...",
// machineryReductionSuggestions: "Consider electric tractors or optimize field operations...",
// overallSustainabilityScore: 62
// }
```
--------------------------------
### Suggest Crops for Soil pH with AI Flow (TypeScript)
Source: https://context7.com/prathmesh2028/agrivision-ai-pccoe/llms.txt
This TypeScript code defines an AI flow to suggest suitable crop varieties based on soil pH levels. It accepts soil pH and desired language as input, returning a comma-separated list of compatible crops. Genkit is used for prompt and flow definition.
```typescript
// src/ai/flows/suggest-crops-for-ph.ts
'use server';
import { ai } from '@/ai/genkit';
import { z } from 'genkit';
const SuggestCropsForPhInputSchema = z.object({
ph: z.number().describe('Soil pH value between 0 and 14'),
language: z.string().describe('Response language (e.g., "en", "hi", "mr")'),
});
const SuggestCropsForPhOutputSchema = z.object({
crops: z.string().describe('Comma-separated list of crops suitable for the given soil pH'),
});
export type SuggestCropsForPhInput = z.infer;
export type SuggestCropsForPhOutput = z.infer;
const prompt = ai.definePrompt({
name: 'suggestCropsForPhPrompt',
input: { schema: SuggestCropsForPhInputSchema },
output: { schema: SuggestCropsForPhOutputSchema },
prompt: `You are an expert agricultural advisor. Based on the provided soil pH, suggest a list of suitable crops.
Please provide the response in the following language: {{{language}}}.
Soil pH: {{{ph}}}
Respond with a comma-separated list of suitable crops.`,
});
const suggestCropsForPhFlow = ai.defineFlow(
{
name: 'suggestCropsForPhFlow',
inputSchema: SuggestCropsForPhInputSchema,
outputSchema: SuggestCropsForPhOutputSchema,
},
async input => {
const { output } = await prompt(input);
return output!;
}
);
export async function suggestCropsForPh(input: SuggestCropsForPhInput): Promise {
return suggestCropsForPhFlow(input);
}
// Usage Example:
const cropSuggestions = await suggestCropsForPh({
ph: 6.5,
language: "en"
});
// Returns: { crops: "Corn, Wheat, Soybeans, Potatoes, Carrots, Lettuce, Tomatoes" }
```
--------------------------------
### TypeScript AI Flow for Fertilizer Safety Info
Source: https://context7.com/prathmesh2028/agrivision-ai-pccoe/llms.txt
This TypeScript code defines a server-side AI flow using Genkit to provide safety information for fertilizers and pesticides. It includes input and output schemas, a detailed prompt for the AI model, and an exported function to trigger the flow. Dependencies include 'genkit' and 'zod'.
```typescript
// src/ai/flows/get-fertilizer-info.ts
'use server';
import { ai } from '@/ai/genkit';
import { z } from 'genkit';
const GetFertilizerInfoInputSchema = z.object({
fertilizerName: z.string().describe('Name of the fertilizer or pesticide'),
language: z.string().describe('Response language (e.g., "en", "hi", "mr")'),
});
const GetFertilizerInfoOutputSchema = z.object({
usage: z.string().describe('Instructions on proper use of the fertilizer/pesticide'),
dangers: z.string().describe('Summary of potential dangers and risks'),
safetyPrecautions: z.string().describe('List of safety precautions when handling'),
});
export type GetFertilizerInfoInput = z.infer;
export type GetFertilizerInfoOutput = z.infer;
const prompt = ai.definePrompt({
name: 'getFertilizerInfoPrompt',
input: { schema: GetFertilizerInfoInputSchema },
output: { schema: GetFertilizerInfoOutputSchema },
prompt: `You are an agricultural safety expert. A farmer has asked for information about a specific fertilizer or pesticide.
Fertilizer/Pesticide Name: {{{fertilizerName}}}
Provide the following information in a clear, concise, and easy-to-understand format for a farmer.
Please provide the response in the following language: {{{language}}}.
1. **Usage:** How to properly use it (application methods, timing, dosage).
2. **Dangers:** The potential dangers and risks to humans, animals, and the environment.
3. **Safety Precautions:** Specific safety measures to take when handling and applying it (e.g., personal protective equipment).`,
});
const getFertilizerInfoFlow = ai.defineFlow(
{
name: 'getFertilizerInfoFlow',
inputSchema: GetFertilizerInfoInputSchema,
outputSchema: GetFertilizerInfoOutputSchema,
},
async input => {
const { output } = await prompt(input);
return output!;
}
);
export async function getFertilizerInfo(input: GetFertilizerInfoInput): Promise {
return getFertilizerInfoFlow(input);
}
// Usage Example:
const fertilizerInfo = await getFertilizerInfo({
fertilizerName: "Urea",
language: "en"
});
// Returns: {
// usage: "Apply 50-100 kg per acre during vegetative growth stage. Split application recommended...",
// dangers: "Can cause skin irritation, harmful if ingested, high nitrogen runoff pollutes water...",
// safetyPrecautions: "Wear gloves and mask during application. Store in cool, dry place. Avoid contact with eyes..."
// }
```
--------------------------------
### TypeScript: Retrieve Climate Insights for Farming Locations
Source: https://context7.com/prathmesh2028/agrivision-ai-pccoe/llms.txt
This TypeScript server action retrieves real-time climate insights, including humidity, temperature, forecast, and air quality, for a given farming location. It uses Genkit and Zod for defining input/output schemas and prompt templating. The function `getClimateInsights` takes location and language as input and returns structured climate data. Dependencies include 'genkit' and 'zod'.
```typescript
'use server';
import { ai } from '@/ai/genkit';
import { z } from 'genkit';
const ClimateInsightsInputSchema = z.object({
locationDescription: z.string().describe("Location description like 'near Sacramento, California' or 'Kenya'"),
language: z.string().describe('Response language (e.g., "en", "hi", "mr")'),
});
const ClimateInsightsOutputSchema = z.object({
humidity: z.string().describe('Current humidity at the location'),
temperature: z.string().describe('Current temperature at the location'),
forecast: z.string().describe('Short weather forecast including expected temperature or rainy days'),
airQuality: z.string().describe('Current air quality at the location'),
});
export type ClimateInsightsInput = z.infer;
export type ClimateInsightsOutput = z.infer;
const prompt = ai.definePrompt({
name: 'climateInsightsPrompt',
input: { schema: ClimateInsightsInputSchema },
output: { schema: ClimateInsightsOutputSchema },
prompt: `You are an AI assistant that provides climate insights for farmers. Based on the provided location, return the current humidity, temperature, a short weather forecast, and the air quality.
Please provide the response in the following language: {{{language}}}.
Location: {{{locationDescription}}}
Your response must be in a JSON format.`,
});
const getClimateInsightsFlow = ai.defineFlow(
{
name: 'getClimateInsightsFlow',
inputSchema: ClimateInsightsInputSchema,
outputSchema: ClimateInsightsOutputSchema,
},
async input => {
const { output } = await prompt(input);
return output!;
}
);
export async function getClimateInsights(input: ClimateInsightsInput): Promise {
return getClimateInsightsFlow(input);
}
// Usage Example:
const insights = await getClimateInsights({
locationDescription: "near Mumbai, Maharashtra",
language: "en"
});
// Returns: { humidity: "75%", temperature: "32°C", forecast: "Partly cloudy with chance of rain", airQuality: "Moderate" }
```
--------------------------------
### TypeScript Crop Health Forecasting Flow with Genkit
Source: https://context7.com/prathmesh2028/agrivision-ai-pccoe/llms.txt
Implements a crop health forecasting flow using TypeScript and Genkit. It defines input and output schemas for disease and pest risk prediction, taking crop type, location, weather, and historical data as input. The flow leverages a defined prompt to generate risk assessments and recommended actions, supporting multi-language responses.
```typescript
// src/ai/flows/forecast-crop-health.ts
'use server';
import { ai } from '@/ai/genkit';
import { z } from 'genkit';
const ForecastCropHealthInputSchema = z.object({
cropType: z.string().describe('The type of crop for health forecast'),
location: z.string().describe('Geographic location of the farm'),
plantingDate: z.string().describe('Date when crop was planted (YYYY-MM-DD)'),
weatherConditions: z.string().describe('Current and expected weather conditions'),
pastDiseaseHistory: z.string().describe('Description of past disease and pest issues'),
language: z.string().describe('Response language (e.g., "en", "hi", "mr")'),
});
const ForecastCropHealthOutputSchema = z.object({
diseaseRisk: z.string().describe('Predicted risk of specific diseases'),
pestRisk: z.string().describe('Predicted risk of specific pests'),
recommendedActions: z.string().describe('Actions to mitigate disease and pest risks'),
});
export type ForecastCropHealthInput = z.infer;
export type ForecastCropHealthOutput = z.infer;
const prompt = ai.definePrompt({
name: 'forecastCropHealthPrompt',
input: { schema: ForecastCropHealthInputSchema },
output: { schema: ForecastCropHealthOutputSchema },
prompt: `You are an expert in crop health and pest management. Based on the following information, provide a forecast of potential disease and pest outbreaks, and recommend actions to mitigate these risks.
Please provide the response in the following language: {{{language}}}.
Crop Type: {{{cropType}}}
Location: {{{location}}}
Planting Date: {{{plantingDate}}}
Weather Conditions: {{{weatherConditions}}}
Past Disease History: {{{pastDiseaseHistory}}}
Provide a detailed disease risk assessment, pest risk assessment, and recommended actions for the farmer.`,
});
const forecastCropHealthFlow = ai.defineFlow(
{
name: 'forecastCropHealthFlow',
inputSchema: ForecastCropHealthInputSchema,
outputSchema: ForecastCropHealthOutputSchema,
},
async input => {
const { output } = await prompt(input);
return output!;
}
);
export async function forecastCropHealth(input: ForecastCropHealthInput): Promise {
return forecastCropHealthFlow(input);
}
// Usage Example:
const healthForecast = await forecastCropHealth({
cropType: "Tomato",
location: "Punjab, India",
plantingDate: "2025-03-15",
weatherConditions: "High humidity, temperatures 25-35°C, monsoon expected",
pastDiseaseHistory: "Late blight observed in previous season",
language: "en"
});
// Returns: {
// diseaseRisk: "High risk of late blight due to humid conditions",
// pestRisk: "Moderate risk of whitefly and aphid infestation",
// recommendedActions: "Apply copper-based fungicide preventively, monitor for early signs..."
// }
```
--------------------------------
### React Context for Language Management (TypeScript)
Source: https://context7.com/prathmesh2028/agrivision-ai-pccoe/llms.txt
Implements a React context to manage the application's language state. It provides a hook to access the current language and a translation function. Dependencies include React. Inputs are language preference and translation objects. Outputs are the current language and a translated string. It ensures language is managed globally.
```typescript
// src/contexts/language-context.tsx
'use client';
import React, { createContext, useState, useContext, ReactNode } from 'react';
type Language = 'en' | 'hi' | 'mr';
interface LanguageContextType {
language: Language;
setLanguage: (language: Language) => void;
t: (translations: Record) => string;
}
const LanguageContext = createContext(undefined);
export const LanguageProvider = ({ children }: { children: ReactNode }) => {
const [language, setLanguage] = useState('en');
const t = (translations: Record): string => {
return translations[language] || translations['en'];
};
return (
{children}
);
};
export const useLanguage = () => {
const context = useContext(LanguageContext);
if (context === undefined) {
throw new Error('useLanguage must be used within a LanguageProvider');
}
return context;
};
// Usage in components:
const MyComponent = () => {
const { language, setLanguage, t } = useLanguage();
return (
);
};
```
--------------------------------
### Predict Irrigation Schedules with AI Flow (TypeScript)
Source: https://context7.com/prathmesh2028/agrivision-ai-pccoe/llms.txt
This TypeScript code defines an AI flow to predict optimal irrigation schedules and water amounts. It takes crop name and cultivation date as input and outputs the next irrigation date, water amount, and reasoning. It utilizes Genkit for defining prompts and flows.
```typescript
// src/ai/flows/predict-irrigation.ts
'use server';
import { ai } from '@/ai/genkit';
import { z } from 'genkit';
const PredictIrrigationInputSchema = z.object({
cropName: z.string().describe('The name of the crop'),
cultivationDate: z.string().describe('Date of cultivation (YYYY-MM-DD)'),
language: z.string().describe('Response language (e.g., "en", "hi", "mr")'),
});
const PredictIrrigationOutputSchema = z.object({
nextIrrigationDate: z.string().describe('Recommended date for next irrigation (e.g., "In 3-5 days", "2024-08-15")'),
waterAmount: z.string().describe('Recommended water amount (e.g., "2-3 inches", "25-30 mm")'),
reasoning: z.string().describe('Brief explanation for recommendation, considering crop stage and water needs'),
});
export type PredictIrrigationInput = z.infer;
export type PredictIrrigationOutput = z.infer;
const prompt = ai.definePrompt({
name: 'predictIrrigationPrompt',
input: { schema: PredictIrrigationInputSchema },
output: { schema: PredictIrrigationOutputSchema },
prompt: `You are an agricultural expert specializing in irrigation management. Based on the crop and its cultivation date, predict the next irrigation schedule.
Please provide the response in the following language: {{{language}}}.
Crop Name: {{{cropName}}}
Cultivation Date: {{{cultivationDate}}}
Provide the next recommended irrigation date, the amount of water to use, and a brief reasoning for your prediction. Assume typical weather conditions for this stage of growth.`,
});
const predictIrrigationFlow = ai.defineFlow(
{
name: 'predictIrrigationFlow',
inputSchema: PredictIrrigationInputSchema,
outputSchema: PredictIrrigationOutputSchema,
},
async input => {
const { output } = await prompt(input);
return output!;
}
);
export async function predictIrrigation(input: PredictIrrigationInput): Promise {
return predictIrrigationFlow(input);
}
// Usage Example:
const irrigation = await predictIrrigation({
cropName: "Rice",
cultivationDate: "2025-06-01",
language: "en"
});
// Returns: {
// nextIrrigationDate: "In 5-7 days",
// waterAmount: "50-75 mm (2-3 inches)",
// reasoning: "Rice is in the tillering stage and requires consistent moisture. Water when soil is moist but not saturated."
// }
```
--------------------------------
### React Form Pattern with Zod Validation and AI Integration
Source: https://context7.com/prathmesh2028/agrivision-ai-pccoe/llms.txt
A generic and reusable form pattern utilizing React Hook Form for state management and Zod for schema validation. This pattern is designed to integrate with AI flows, handling form submission, asynchronous operations, loading states, and error display with a toast notification. It includes input fields, a submit button, and dynamic loading indicators.
```typescript
// Generic form pattern used across all features
import { useForm } from "react-hook-form";
import { zodResolver } from "@hookform/resolvers/zod";
import { z } from "zod";
// 1. Define validation schema
const schema = z.object({
fieldName: z.string().min(1, "Field is required"),
numericField: z.number().min(0).max(14),
});
// 2. Create form component
export function MyFeatureForm() {
const [result, setResult] = useState(null);
const [isLoading, setIsLoading] = useState(false);
const { toast } = useToast();
const { language } = useLanguage();
// 3. Initialize form with Zod resolver
const form = useForm({
resolver: zodResolver(schema),
defaultValues: { fieldName: "", numericField: 7 },
});
// 4. Handle form submission with AI flow
async function onSubmit(values) {
setIsLoading(true);
try {
const output = await myAIFlow({ ...values, language });
setResult(output);
} catch (error) {
toast({
variant: "destructive",
title: "Error",
description: "Operation failed. Please try again.",
});
} finally {
setIsLoading(false);
}
}
// 5. Render form with FormField components
return (
);
}
```
--------------------------------
### Climate Insights Form Component with React and TypeScript
Source: https://context7.com/prathmesh2028/agrivision-ai-pccoe/llms.txt
A client-side React component for fetching climate insights based on a location description. It uses `react-hook-form` for form state management and validation with Zod. The component integrates with an AI flow (`getClimateInsights`) and displays results, loading states, and error messages using toasts. Dependencies include `react`, `react-dom`, `next`, `zod`, `lucide-react`, and custom UI components.
```typescript
"use client";
import { useState } from "react";
import { useForm } from "react-hook-form";
import { zodResolver } from "@hookform/resolvers/zod";
import { z } from "zod";
import { getClimateInsights, type ClimateInsightsOutput } from "@/ai/flows/get-climate-insights";
import { Button } from "@/components/ui/button";
import { Form, FormControl, FormField, FormItem, FormLabel, FormMessage } from "@/components/ui/form";
import { Input } from "@/components/ui/input";
import { useToast } from "@/hooks/use-toast";
import { Loader2, Droplets, Thermometer, Wind, Sun } from "lucide-react";
import { Card, CardContent, CardHeader, CardTitle } from "@/components/ui/card";
import { Skeleton } from "@/components/ui/skeleton";
import { useLanguage } from "@/contexts/language-context";
const formSchema = z.object({
locationDescription: z.string().min(3, "Location must be at least 3 characters."),
});
export function ClimateInsightsForm() {
const [result, setResult] = useState(null);
const [isLoading, setIsLoading] = useState(false);
const { toast } = useToast();
const { language } = useLanguage();
const form = useForm>({
resolver: zodResolver(formSchema),
defaultValues: { locationDescription: "" },
});
async function onSubmit(values: z.infer) {
setIsLoading(true);
setResult(null);
try {
const insights = await getClimateInsights({ ...values, language });
setResult(insights);
} catch (error) {
console.error(error);
toast({
variant: "destructive",
title: "Error",
description: "Failed to get climate insights. Please try again.",
});
} finally {
setIsLoading(false);
}
}
const InsightCard = ({ icon: Icon, title, value }: { icon: React.ElementType, title: string, value: string }) => (
{title}
{value}
);
return (
{isLoading && (
)}
{result && (
)}
);
}
// Example output when form is submitted with "near Delhi, India":
// Temperature: 28°C
// Humidity: 65%
// Air Quality: Moderate
// Forecast: Partly cloudy with highs of 32°C
```
=== COMPLETE CONTENT === This response contains all available snippets from this library. No additional content exists. Do not make further requests.