Skip to main content

Overview

The Chat API powers the interactive weather assistant feature in SkyCast IA. It uses Groq’s LLaMA 3.1 model to provide weather-related advice with a direct, honest, and slightly sarcastic tone.

POST /api/chat

Sends a chat message and receives an AI-generated response based on current weather context.

Endpoint

POST /api/chat

Request Body

messages
array
required
Array of message objects following the OpenAI chat format
context
object
required
Current weather context data
captchaToken
string
Google reCAPTCHA v3 token (required for first message only)

Response

answer
string
AI-generated response text (max 25 words, 2 emojis max)

Example

const response = await fetch('/api/chat', {
  method: 'POST',
  headers: {
    'Content-Type': 'application/json',
  },
  body: JSON.stringify({
    messages: [
      {
        role: 'user',
        content: '¿Qué ropa me recomiendas hoy?'
      }
    ],
    context: {
      city: 'Buenos Aires',
      temp: 28,
      feels_like: 32,
      humidity: 75,
      wind_speed: 12,
      pressure: 1010,
      pop: '40%',
      description: 'parcialmente nublado'
    },
    captchaToken: 'YOUR_RECAPTCHA_TOKEN'
  })
});

const data = await response.json();
console.log(data.answer);

reCAPTCHA Verification

The endpoint implements Google reCAPTCHA v3 verification for security:
  1. When to send: Include captchaToken only for the first message in a conversation
  2. Validation: Token is verified against Google’s API using RECAPTCHA_SECRET_KEY
  3. Failure handling: Returns 403 status with error message if verification fails
  4. Subsequent messages: No token required after first successful verification
import { useGoogleReCaptcha } from 'react-google-recaptcha-v3';

const { executeRecaptcha } = useGoogleReCaptcha();

const sendMessage = async () => {
  const token = await executeRecaptcha('chat_submit');
  
  const response = await fetch('/api/chat', {
    method: 'POST',
    headers: { 'Content-Type': 'application/json' },
    body: JSON.stringify({
      messages: [{ role: 'user', content: userInput }],
      context: weatherContext,
      captchaToken: token
    })
  });
};

AI Personality & Behavior

The chat endpoint configures the AI with specific guidelines: Tone: Direct, honest, and slightly sarcastic
Response Length: Maximum 25 words
Emoji Limit: Maximum 2 per response
Temperature: 0.7 (balanced creativity and consistency)
Max Tokens: 150
Key Rules:
  • Uses technical data (pressure, probability of precipitation) for real advice
  • Doesn’t sugarcoat bad weather conditions
  • Uses feels_like temperature for clothing recommendations
  • Provides practical, actionable suggestions

Status Codes

CodeMeaning
200Success - AI response generated
403Forbidden - reCAPTCHA verification failed
500Server Error - Missing API keys or connection error
503Service Unavailable - Groq API unavailable

getAiWeatherAnalysis

Server action that generates automatic weather analysis for the main weather card.
export async function getAiWeatherAnalysis(weatherData: any)

Parameters

weatherData
object
required
OpenWeatherMap API response object

Returns

string
string
Brief AI-generated analysis (max 20 words, 1 emoji)

Example

"use server";
import { getAiWeatherAnalysis } from '@/lib/api/mistral';
import { getCurrentWeather } from '@/lib/api/weather';

const weatherData = await getCurrentWeather(lat, lon);
const analysis = await getAiWeatherAnalysis(weatherData);

console.log(analysis);
// Output: "Día perfecto para caminar. Llevá agua. ☀️"

Configuration

Model: llama-3.1-8b-instant (Groq)
Temperature: 0.3 (low for consistency)
Max Response: 20 words
Endpoint: https://api.groq.com/openai/v1/chat/completions

System Prompt

Eres una API de clima práctica. Tu objetivo es dar un consejo de 
vestimenta o actividad basado en los datos. Máximo 20 palabras y un 
emoji. Sé directo, breve y no uses comillas ni introducciones.

Error Handling

Returns fallback messages instead of throwing errors:
ScenarioReturn Value
Missing API key"Falta la API Key. 🔑"
API error"Análisis no disponible. ☁️"
Network error"Análisis no disponible. ☁️"
Empty response"¡Disfrutá el día! ☀️"

Environment Variables

Required environment variables:
GROQ_API_KEY=your_groq_api_key
RECAPTCHA_SECRET_KEY=your_recaptcha_secret

API Keys

Security Notes

  • Never expose RECAPTCHA_SECRET_KEY to the client
  • Use NEXT_PUBLIC_ prefix only for reCAPTCHA site key
  • Groq API key must remain server-side only

Build docs developers (and LLMs) love