Skip to content

Commit

Permalink
Reverted to edit b8ad2189-62aa-4fdc-b6cf-21b17e637120: "Update token …
Browse files Browse the repository at this point in the history
…usage policy

Clarified that the application will define a limited monthly token usage for all users.
[skip gpt_engineer]"
  • Loading branch information
lovable-dev[bot] committed Dec 21, 2024
1 parent 457c0c0 commit 439b724
Show file tree
Hide file tree
Showing 6 changed files with 18 additions and 153 deletions.
14 changes: 0 additions & 14 deletions src/components/chat/ToastActionButton.tsx

This file was deleted.

74 changes: 0 additions & 74 deletions src/hooks/chat/useConversations.ts

This file was deleted.

29 changes: 0 additions & 29 deletions src/hooks/chat/useTitleGeneration.ts

This file was deleted.

38 changes: 12 additions & 26 deletions src/hooks/useChat.tsx → src/hooks/useChat.ts
Original file line number Diff line number Diff line change
Expand Up @@ -2,16 +2,12 @@ import { useState, useEffect } from "react"
import { supabase } from "@/integrations/supabase/client"
import { ChatMessage } from "@/types/chat"
import { v4 as uuidv4 } from 'uuid'
import { useToast } from "@/hooks/use-toast"
import { useNavigate } from "react-router-dom"

export const useChat = (userId: string | null) => {
const [messages, setMessages] = useState<Array<ChatMessage>>([])
const [isLoading, setIsLoading] = useState(false)
const [conversations, setConversations] = useState<Array<{id: string, title: string}>>([])
const [currentConversationId, setCurrentConversationId] = useState<string | null>(null)
const { toast } = useToast()
const navigate = useNavigate()

useEffect(() => {
if (userId) {
Expand All @@ -35,6 +31,7 @@ export const useChat = (userId: string | null) => {
return
}

// Group by conversation_id and get unique conversations with their titles
const uniqueConversations = data.reduce((acc: Array<{id: string, title: string}>, curr) => {
if (curr.conversation_id && curr.conversation_title &&
!acc.some(conv => conv.id === curr.conversation_id)) {
Expand Down Expand Up @@ -70,6 +67,7 @@ export const useChat = (userId: string | null) => {
}

const generateTitle = async (message: string) => {
// Detect if the message is in English using a simple heuristic
const commonEnglishWords = /\b(the|is|are|was|were|have|has|had|been|will|would|could|should|may|might|must|can|a|an|and|or|but|in|on|at|to|for|of|with)\b/i;
const isEnglish = commonEnglishWords.test(message.toLowerCase());

Expand Down Expand Up @@ -101,18 +99,22 @@ export const useChat = (userId: string | null) => {
const conversationId = currentConversationId || uuidv4()

try {
// If this is the first message in a new conversation, generate a title
if (!currentConversationId) {
const title = await generateTitle(userMessage)
setCurrentConversationId(conversationId)

// Add the new conversation to the list
setConversations(prev => [{
id: conversationId,
title
}, ...prev])
}

// Add user message to UI
setMessages(prev => [...prev, { role: 'user', content: userMessage }])

// Save user message to database
await supabase
.from('chats')
.insert([{
Expand All @@ -123,31 +125,16 @@ export const useChat = (userId: string | null) => {
conversation_title: !currentConversationId ? await generateTitle(userMessage) : undefined
}])

// Get AI response
const { data, error } = await supabase.functions.invoke('chat-with-openai', {
body: { message: userMessage }
})

if (error) throw error

if (data.error && data.type === "UPGRADE_REQUIRED") {
toast({
title: "Limite d'utilisation atteinte",
description: "Vous avez atteint votre limite mensuelle de messages. Passez à un forfait supérieur pour continuer à utiliser notre service sans interruption.",
variant: "destructive",
action: (
<button
onClick={() => navigate('/pricing')}
className="bg-white text-red-600 px-3 py-2 rounded-md text-sm font-medium hover:bg-red-50 transition-colors"
>
Voir les forfaits
</button>
),
})
return
}

const aiResponse = data.response

// Save AI response to database
await supabase
.from('chats')
.insert([{
Expand All @@ -157,14 +144,10 @@ export const useChat = (userId: string | null) => {
conversation_id: conversationId
}])

// Add AI response to UI
setMessages(prev => [...prev, { role: 'assistant', content: aiResponse }])
} catch (error) {
console.error("Error:", error)
toast({
title: "Erreur",
description: "Une erreur est survenue lors de l'envoi de votre message. Veuillez réessayer.",
variant: "destructive",
})
} finally {
setIsLoading(false)
}
Expand All @@ -174,6 +157,7 @@ export const useChat = (userId: string | null) => {
if (!userId) return

try {
// Soft delete all messages from this conversation
const { error } = await supabase
.from('chats')
.update({ deleted_at: new Date().toISOString() })
Expand All @@ -182,8 +166,10 @@ export const useChat = (userId: string | null) => {

if (error) throw error

// Update the conversations list
setConversations(prev => prev.filter(conv => conv.id !== conversationId))

// If the deleted conversation was the current one, clear messages
if (currentConversationId === conversationId) {
setMessages([])
setCurrentConversationId(null)
Expand Down
6 changes: 1 addition & 5 deletions src/pages/Pricing.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -14,15 +14,12 @@ const PricingPage = () => {
}

return (
<div className="min-h-screen bg-gradient-to-b from-background to-secondary/20">
<div className="min-h-screen bg-background">
<main className="container mx-auto px-4 py-16">
<div className="max-w-3xl mx-auto text-center mb-12">
<h1 className="text-4xl font-bold tracking-tight mb-4">
Découvrez la puissance de l'intelligence artificielle dans votre métier grâce à PedagoIA
</h1>
<p className="text-xl text-muted-foreground mb-6">
Des outils d'IA adaptés à vos besoins, avec un accès illimité à notre assistant intelligent
</p>
<Badge variant="secondary" className="mb-4 bg-secondary text-primary">
<MessageSquareText className="w-4 h-4 mr-1" />
Essai gratuit de 7 jours
Expand All @@ -33,7 +30,6 @@ const PricingPage = () => {
<PricingCard
title="Plan Mensuel"
price="7,99€"
period="/mois"
badge="Plan Flexible"
badgeIcon={<MessageSquareText className="w-4 h-4 mr-1" />}
features={[
Expand Down
10 changes: 5 additions & 5 deletions supabase/functions/chat-with-openai/index.ts
Original file line number Diff line number Diff line change
Expand Up @@ -2,7 +2,7 @@ import { serve } from "https://deno.land/[email protected]/http/server.ts"
import "https://deno.land/x/[email protected]/mod.ts"

const openAIApiKey = Deno.env.get('OPENAI_API_KEY')
const MONTHLY_TOKEN_LIMIT = 50000 // Nouvelle limite de 50k tokens par mois
const MONTHLY_TOKEN_LIMIT = 100000 // Limite de 100k tokens par mois

const corsHeaders = {
'Access-Control-Allow-Origin': '*',
Expand All @@ -22,6 +22,7 @@ serve(async (req) => {
throw new Error('OpenAI API key not configured')
}

// Si c'est une génération de titre, on utilise un prompt système spécifique
const systemPrompt = type === 'title-generation'
? "Tu es un assistant qui génère des titres courts et concis (maximum 5 mots) pour des conversations. Réponds uniquement avec le titre, sans ponctuation ni guillemets."
: "Tu es un assistant pédagogique français qui aide les utilisateurs à apprendre et à comprendre des concepts. Tu es amical et encourageant."
Expand All @@ -35,9 +36,8 @@ serve(async (req) => {
if (estimatedTokens > MONTHLY_TOKEN_LIMIT) {
return new Response(
JSON.stringify({
error: "Limite mensuelle de tokens atteinte",
details: "Vous avez atteint votre limite mensuelle de 50 000 tokens. Pour continuer à utiliser notre service sans interruption, nous vous invitons à passer à un forfait supérieur.",
type: "UPGRADE_REQUIRED"
error: "Limite mensuelle de tokens dépassée",
details: "Vous avez atteint votre limite mensuelle de tokens. Réessayez le mois prochain ou passez à un forfait supérieur."
}), {
status: 429,
headers: { ...corsHeaders, 'Content-Type': 'application/json' },
Expand Down Expand Up @@ -81,7 +81,7 @@ serve(async (req) => {
return new Response(
JSON.stringify({
error: error.message,
details: 'Une erreur est survenue lors du traitement de votre demande'
details: 'An error occurred while processing your request'
}), {
status: 500,
headers: { ...corsHeaders, 'Content-Type': 'application/json' },
Expand Down

0 comments on commit 439b724

Please sign in to comment.