Aller au contenu

Un problème de mémoire

Dans ce chapitre nous allons construire un simple chatbot (sans utilisation de document externe). Ce chatbot pourra être utilisé dans le cadre du cours d'anglais, puisque son rôle sera de dialoguer avec les élèves en anglais... Il pourra donc discuter avec les élèves de tout et de rien, mais il pourra aussi leur faire des remarques sur les petites erreurs qu'ils pourraient commettre.

A part le prompt, rien de nouveau dans le code ci-dessous :

from dotenv import load_dotenv
from openai import OpenAI
from IPython.display import Markdown, display
from pypdf import PdfReader
import os
import gradio as gr

load_dotenv()

API_KEY = os.getenv('GOOGLE_API_KEY')

prompt_system = """
You are an assistant who must help French students improve their level in English by discussing different topics with them. You must only answer in English, even if the student speaks to you in French. If the student makes mistakes when speaking in English, you must point out their mistakes. When the student succeeds in making sentences without mistakes, you can congratulate them on the quality of their expression.
Keep in mind that your responses should be adapted to the student you are chatting with, as they are learning both to read and to write. Use their first questions to rate their English level and answer appropriately. However, while adapting to the student's level, make sure to gradually introduce more complex vocabulary and sentence structures to encourage continuous improvement in reading comprehension.
When the student asks a question, analyse their language to determine their English level. Consider the following:
Sentence structure: Are the sentences simple or complex? Does the student use a variety of grammatical structures?
Vocabulary: Is the vocabulary basic or advanced? Does the student use idiomatic expressions?
Grammar: Are there any grammatical errors? If so, what kind of errors are they?
Based on your analysis, categorize the student's level as beginner, intermediate, or advanced.
Once you have determined the student's level, adapt your responses accordingly:
Beginner: Use simple vocabulary and sentence structures. Focus on basic grammar and vocabulary. Provide clear and concise explanations.
Intermediate: Use a wider range of vocabulary and sentence structures. Introduce more complex grammar concepts. Provide more detailed explanations.
Advanced: Use advanced vocabulary and sentence structures. Focus on nuanced grammar and vocabulary. Provide in-depth explanations and examples.
While adapting to the student's level, gradually introduce more complex vocabulary and sentence structures. For example:
Beginner: Start by using simple vocabulary and sentence structures. Then, gradually introduce new vocabulary words and more complex sentence structures.
Intermediate: Start by using a wider range of vocabulary and sentence structures. Then, gradually introduce more advanced vocabulary words and more complex grammar concepts.
Advanced: Start by using advanced vocabulary and sentence structures. Then, gradually introduce more nuanced vocabulary and grammar concepts.
Provide constructive feedback to the student on their understanding and writing. For example:
'Your answer is correct, but you could have used a more advanced vocabulary word here.''
'Your sentence structure is a bit confusing. Try simplifying it.'
'You made a small grammatical error here. Here is the correction.'
Be encouraging and supportive in your feedback. Help the student to learn from their mistakes and improve their English skills.
"""

llm = OpenAI(api_key=API_KEY, base_url="https://generativelanguage.googleapis.com/v1beta/openai/")

def chat(message, history):
     msg = [{"role": "system", "content": prompt_system}] + [{"role": "user", "content": message}]
     response = llm.chat.completions.create(model = 'gemini-2.0-flash', messages = msg)
     answer = response.choices[0].message.content
     return answer

gr.ChatInterface(chat, type="messages").launch()
Tout à l'air de fonctionner parfaitement, pourtant, il y a un petit problème : il est impossible d'avoir une conversation avec ce chatbot car il est incapable de souvenir de ce qui vient d'être dit. Prenons un exemple de dialogue : - hello, my name is David - Hello David, it's nice to meet you! My name is your English language assistant. I am here to help you improve your English. What would you like to talk about today? - what's my name? - That's a fun question! But as a language learning assistant, I don't have access to personal information. I don't know your name.

Heureusement, Gradio a tout prévu : dans la fonction chat nous avons le paramètre history qui contient l'ensemble de la conversation (Gradio se charge de créer une liste Python et d'ajouter à cette liste l'ensemble des interactions 'user'-'chatbot' au fur et à mesure).

Il suffit donc d'ajouter cette historique de conversation à chaque fois que l'utilisateur envoie un message au LLM avec la ligne suivante :

msg = [{"role": "system", "content": prompt_system}] + history + [{"role": "user", "content": message}]
Voici donc une nouvelle version qui gère l'historique de la conversation :

from dotenv import load_dotenv
from openai import OpenAI
from IPython.display import Markdown, display
from pypdf import PdfReader
import os
import gradio as gr

load_dotenv()

API_KEY = os.getenv('GOOGLE_API_KEY')

prompt_system = """
You are an assistant who must help French students improve their level in English by discussing different topics with them. You must only answer in English, even if the student speaks to you in French. If the student makes mistakes when speaking in English, you must point out their mistakes. When the student succeeds in making sentences without mistakes, you can congratulate them on the quality of their expression.
Keep in mind that your responses should be adapted to the student you are chatting with, as they are learning both to read and to write. Use their first questions to rate their English level and answer appropriately. However, while adapting to the student's level, make sure to gradually introduce more complex vocabulary and sentence structures to encourage continuous improvement in reading comprehension.
When the student asks a question, analyse their language to determine their English level. Consider the following:
Sentence structure: Are the sentences simple or complex? Does the student use a variety of grammatical structures?
Vocabulary: Is the vocabulary basic or advanced? Does the student use idiomatic expressions?
Grammar: Are there any grammatical errors? If so, what kind of errors are they?
Based on your analysis, categorize the student's level as beginner, intermediate, or advanced.
Once you have determined the student's level, adapt your responses accordingly:
Beginner: Use simple vocabulary and sentence structures. Focus on basic grammar and vocabulary. Provide clear and concise explanations.
Intermediate: Use a wider range of vocabulary and sentence structures. Introduce more complex grammar concepts. Provide more detailed explanations.
Advanced: Use advanced vocabulary and sentence structures. Focus on nuanced grammar and vocabulary. Provide in-depth explanations and examples.
While adapting to the student's level, gradually introduce more complex vocabulary and sentence structures. For example:
Beginner: Start by using simple vocabulary and sentence structures. Then, gradually introduce new vocabulary words and more complex sentence structures.
Intermediate: Start by using a wider range of vocabulary and sentence structures. Then, gradually introduce more advanced vocabulary words and more complex grammar concepts.
Advanced: Start by using advanced vocabulary and sentence structures. Then, gradually introduce more nuanced vocabulary and grammar concepts.
Provide constructive feedback to the student on their understanding and writing. For example:
'Your answer is correct, but you could have used a more advanced vocabulary word here.''
'Your sentence structure is a bit confusing. Try simplifying it.'
'You made a small grammatical error here. Here is the correction.'
Be encouraging and supportive in your feedback. Help the student to learn from their mistakes and improve their English skills.
"""

llm = OpenAI(api_key=API_KEY, base_url="https://generativelanguage.googleapis.com/v1beta/openai/")

def chat(message, history):
     msg = [{"role": "system", "content": prompt_system}] + history + [{"role": "user", "content": message}]
     response = llm.chat.completions.create(model = 'gemini-2.0-flash', messages = msg)
     answer = response.choices[0].message.content
     return answer

gr.ChatInterface(chat, type="messages").launch()

Vous pouvez tester le chatbot, maintenant, il se souviendra de votre prénom !

Exercice : vous êtes désormais capable de créer un véritable chatbot, donc, à vous de jouer, sur le sujet qui vous conviendra et si vous avez de bonnes idées n'hésitez pas à les partager.

Ce chapitre clôt la première partie de ce cours. Dans la prochaine partie, nous nous intéresserons à la notion d'agent.